diff --git a/.github/actions/setup-ci-deps/action.yml b/.github/actions/setup-ci-deps/action.yml index e27a8c90fdff8..cc6dc80511aca 100644 --- a/.github/actions/setup-ci-deps/action.yml +++ b/.github/actions/setup-ci-deps/action.yml @@ -35,7 +35,7 @@ runs: - name: Cache Vite+ id: vp_cache if: steps.vp.outputs.version != '' - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ~/.vite-plus key: vite-plus-home-v2-${{ runner.os }}-${{ runner.arch }}-${{ steps.vp.outputs.version }}-node${{ steps.vp.outputs.node }}-${{ steps.vp.outputs.pnpm }} @@ -56,7 +56,7 @@ runs: # partial bytes, so a shorter limit costs a slow download only a retry. - name: Setup Vite+ if: steps.vp_cache.outputs.cache-hit != 'true' - uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1 + uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1.15.0 env: VP_DOWNLOAD_TIMEOUT: "120" with: @@ -92,7 +92,7 @@ runs: - name: Restore pnpm store id: pnpm_cache if: inputs.install == 'true' - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ steps.pnpm_store.outputs.path }} key: pnpm-${{ steps.pnpm_store.outputs.namespace }}-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml', 'pnpm-workspace.yaml', 'package.json') }} @@ -106,7 +106,7 @@ runs: - name: Restore lockfile verification id: pnpm_verified if: inputs.install == 'true' - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ steps.pnpm_store.outputs.verified }} key: pnpm-verified-v1-${{ hashFiles('pnpm-lock.yaml', 'pnpm-workspace.yaml', 'package.json') }} @@ -121,7 +121,7 @@ runs: - name: Save lockfile verification if: inputs.install == 'true' && steps.pnpm_verified.outputs.cache-hit != 'true' - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ steps.pnpm_store.outputs.verified }} key: ${{ steps.pnpm_verified.outputs.cache-primary-key }} @@ -138,7 +138,7 @@ runs: steps.pnpm_cache.outputs.cache-hit != 'true' && (steps.pnpm_store.outputs.namespace == 'full' || steps.pnpm_cache.outputs.cache-matched-key != format('pnpm-full-v1-{0}-{1}-{2}', runner.os, runner.arch, hashFiles('pnpm-lock.yaml', 'pnpm-workspace.yaml', 'package.json'))) - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ steps.pnpm_store.outputs.path }} key: ${{ steps.pnpm_cache.outputs.cache-primary-key }} diff --git a/.github/workflows/agent-context-budget.yml b/.github/workflows/agent-context-budget.yml index 41efb7b69a5a2..3a9a148194ad2 100644 --- a/.github/workflows/agent-context-budget.yml +++ b/.github/workflows/agent-context-budget.yml @@ -24,7 +24,7 @@ jobs: ALLOW_INCREASE: ${{ contains(github.event.pull_request.labels.*.name, 'agent-context-increase') }} steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: sparse-checkout: apps/server/src/provider/agentContextBudget.json sparse-checkout-cone-mode: false diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d27b2c6a85729..1f7ffa6ac4d3c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,7 +39,7 @@ jobs: # Only the package manifests the script reads to build the dependency graph. # Depth 2 brings the base commit the change is diffed against. - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 2 sparse-checkout: | @@ -68,7 +68,7 @@ jobs: timeout-minutes: 10 steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: sparse-checkout: | /* @@ -92,7 +92,7 @@ jobs: # electron's install.js (run by ensure:electron) reads this cache before it # downloads from GitHub. The key changes only with the Electron version. - name: Cache Electron download - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ~/.cache/electron key: electron-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('node_modules/.pnpm/electron@*/node_modules/electron/package.json') }} @@ -124,7 +124,7 @@ jobs: timeout-minutes: 10 steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: sparse-checkout: | /* @@ -161,7 +161,7 @@ jobs: # electron's install.js (run by ensure:electron) reads this cache before it # downloads from GitHub. The key changes only with the Electron version. - name: Cache Electron download - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ~/.cache/electron key: electron-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('node_modules/.pnpm/electron@*/node_modules/electron/package.json') }} @@ -213,7 +213,7 @@ jobs: - name: Upload desktop launch check if: ${{ failure() && steps.desktop_launch.outcome == 'failure' }} - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: desktop-launch-check path: ${{ runner.temp }}/desktop-launch-check @@ -231,7 +231,7 @@ jobs: - name: Cache Chromium id: chromium_cache if: ${{ !cancelled() && steps.build.outcome == 'success' && needs.changes.outputs.test_web != 'false' }} - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ~/.cache/ms-playwright key: playwright-chromium-shell-${{ runner.os }}-${{ runner.arch }}-${{ steps.playwright_version.outputs.version }} @@ -279,7 +279,7 @@ jobs: timeout-minutes: 10 steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: sparse-checkout: | /* @@ -314,7 +314,7 @@ jobs: # electron's install.js (run by ensure:electron) reads this cache before it # downloads from GitHub. The key changes only with the Electron version. - name: Cache Electron download - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ~/.cache/electron key: electron-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('node_modules/.pnpm/electron@*/node_modules/electron/package.json') }} @@ -373,7 +373,7 @@ jobs: shard: [1, 2] steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: sparse-checkout: | /* @@ -394,7 +394,7 @@ jobs: - name: Cache Chromium id: chromium_cache - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ~/.cache/ms-playwright key: playwright-chromium-shell-${{ runner.os }}-${{ runner.arch }}-${{ steps.playwright_version.outputs.version }} @@ -438,7 +438,7 @@ jobs: steps: # Depth 2 brings the base commit the change is diffed against. - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 2 sparse-checkout: | @@ -469,7 +469,7 @@ jobs: - name: Cache Chromium id: chromium_cache if: steps.changes.outputs.test_server != 'false' - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ~/.cache/ms-playwright key: playwright-chromium-shell-${{ runner.os }}-${{ runner.arch }}-${{ steps.playwright_version.outputs.version }} @@ -492,7 +492,7 @@ jobs: # Only pushes to main save it, so pull requests never evict each other's entries. - name: Restore Vitest module cache if: steps.changes.outputs.test_server != 'false' - uses: actions/cache/restore@v6 + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: node_modules/.vitest-cache key: vitest-modules-server-${{ matrix.shard }}-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }}-${{ github.sha }} @@ -511,7 +511,7 @@ jobs: - name: Save Vitest module cache if: github.event_name == 'push' && steps.changes.outputs.test_server != 'false' - uses: actions/cache/save@v6 + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: node_modules/.vitest-cache key: vitest-modules-server-${{ matrix.shard }}-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }}-${{ github.sha }} @@ -541,7 +541,7 @@ jobs: - name: Upload thread transfer result if: always() && steps.transfer_budget.outputs.present == 'true' - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: thread-transfer-results path: | @@ -560,7 +560,7 @@ jobs: timeout-minutes: 10 steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: sparse-checkout: | /* @@ -569,8 +569,9 @@ jobs: sparse-checkout-cone-mode: false - name: Setup Rust - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master with: + toolchain: stable components: rustfmt - name: Check Rust formatting @@ -593,7 +594,7 @@ jobs: timeout-minutes: 10 steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: sparse-checkout: | /* @@ -601,7 +602,7 @@ jobs: sparse-checkout-cone-mode: false - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1.15.0 with: node-version-file: package.json cache: true @@ -626,7 +627,7 @@ jobs: timeout-minutes: 15 steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: sparse-checkout: | /* @@ -684,7 +685,7 @@ jobs: # server tests ran must have produced it. - name: Require transfer measurements if: needs.test_server.result == 'success' && needs.changes.outputs.test_server != 'false' - uses: actions/download-artifact@v8 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: thread-transfer-results path: ${{ runner.temp }}/thread-transfer diff --git a/.github/workflows/deploy-relay.yml b/.github/workflows/deploy-relay.yml index 5db7a86eb98c9..da779c2783d4c 100644 --- a/.github/workflows/deploy-relay.yml +++ b/.github/workflows/deploy-relay.yml @@ -51,7 +51,7 @@ jobs: ALCHEMY_TELEMETRY_DISABLED: "1" steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: sparse-checkout: | /* @@ -59,7 +59,7 @@ jobs: sparse-checkout-cone-mode: false - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1.15.0 with: node-version-file: package.json cache: true @@ -83,7 +83,7 @@ jobs: T3CHAT_LINK_SECRET: ${{ secrets.T3CHAT_LINK_SECRET }} - name: Publish relay deploy commit status - uses: actions/github-script@v8 + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 with: script: | await github.rest.repos.createCommitStatus({ diff --git a/.github/workflows/desktop-macos-preview-publish.yml b/.github/workflows/desktop-macos-preview-publish.yml index 6e8805b7f790b..a9615439929fe 100644 --- a/.github/workflows/desktop-macos-preview-publish.yml +++ b/.github/workflows/desktop-macos-preview-publish.yml @@ -55,7 +55,7 @@ jobs: steps: - id: pr name: Resolve the pull request behind the build - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8 + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 with: script: | const run = context.payload.workflow_run; @@ -134,7 +134,7 @@ jobs: - id: vouch name: Check PR author trust if: steps.pr.outputs.eligible == 'true' - uses: mitchellh/vouch/action/check-user@d66fa29a64600490892131ad87597c30c91fcac4 # v1 + uses: mitchellh/vouch/action/check-user@d66fa29a64600490892131ad87597c30c91fcac4 # v1.5.0 with: user: ${{ steps.pr.outputs.author }} allow-fail: true @@ -149,7 +149,7 @@ jobs: - id: consume name: Consume the preview label if: steps.pr.outputs.eligible == 'true' - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8 + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 env: PR_NUMBER: ${{ steps.pr.outputs.pr_number }} with: @@ -271,7 +271,7 @@ jobs: # Only validated bundle files cross into the signing job's artifact. - name: Stage JS bundle for packaging if: steps.gate.outputs.eligible == 'true' - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: js-bundle path: ${{ runner.temp }}/js-bundle @@ -338,7 +338,7 @@ jobs: pull-requests: write steps: - name: Download macOS artifacts - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: desktop-mac-arm64 path: release @@ -431,7 +431,7 @@ jobs: - name: Comment download link if: steps.upload.outputs.download_url != '' - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8 + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 env: PR_NUMBER: ${{ needs.resolve.outputs.pr_number }} DOWNLOAD_URL: ${{ steps.upload.outputs.download_url }} @@ -552,7 +552,7 @@ jobs: - name: Mark the preview comment as removed if: steps.delete.outputs.removed == 'true' - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8 + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 with: script: | const marker = ""; diff --git a/.github/workflows/desktop-macos-preview.yml b/.github/workflows/desktop-macos-preview.yml index 0213f3fce6a99..2c54052ea66d5 100644 --- a/.github/workflows/desktop-macos-preview.yml +++ b/.github/workflows/desktop-macos-preview.yml @@ -50,7 +50,7 @@ jobs: git checkout --detach FETCH_HEAD - name: Setup Vite+ - uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1 + uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1.15.0 with: node-version-file: package.json cache: true @@ -98,7 +98,7 @@ jobs: # Same layout as release.yml's js-bundle so release-desktop.yml can # package it unchanged. - name: Upload JS bundle - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: js-bundle path: | diff --git a/.github/workflows/issue-labels.yml b/.github/workflows/issue-labels.yml index d6571d65d4530..fd9ba6b60302b 100644 --- a/.github/workflows/issue-labels.yml +++ b/.github/workflows/issue-labels.yml @@ -18,7 +18,7 @@ jobs: runs-on: ubuntu-24.04 steps: - name: Ensure managed issue labels exist - uses: actions/github-script@v7 + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 with: script: | const managedLabels = [ diff --git a/.github/workflows/mobile-android-apk.yml b/.github/workflows/mobile-android-apk.yml index 18d977c50f4a0..8650b5a6d527d 100644 --- a/.github/workflows/mobile-android-apk.yml +++ b/.github/workflows/mobile-android-apk.yml @@ -37,7 +37,7 @@ jobs: - name: Checkout if: steps.credentials.outputs.present == 'true' - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: sparse-checkout: .github/scripts diff --git a/.github/workflows/mobile-dev-client.yml b/.github/workflows/mobile-dev-client.yml index 5f8cb86befb59..e204b16f01626 100644 --- a/.github/workflows/mobile-dev-client.yml +++ b/.github/workflows/mobile-dev-client.yml @@ -83,7 +83,7 @@ jobs: T3_NATIVE_CLIENT_VERBOSE: "1" steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ inputs.ref || github.sha }} @@ -144,7 +144,7 @@ jobs: # the runs holding the cache login restore. - name: Mount build cache if: github.event_name != 'pull_request' - uses: useblacksmith/stickydisk@v1 + uses: useblacksmith/stickydisk@3f6be1451e3cad893b778bc93495c80452a5da26 # v1.7.2 with: key: ${{ github.repository }}-android-dev-client-${{ matrix.abi }} path: ~/.cache/t3-android-dev-client @@ -165,7 +165,7 @@ jobs: install-args: --filter=@t3tools/mobile... --filter=@t3tools/scripts... - name: Setup Java - uses: actions/setup-java@v5 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: temurin java-version: 17 @@ -232,7 +232,7 @@ jobs: T3_NATIVE_CLIENT_VERBOSE: "1" steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ inputs.ref || github.sha }} diff --git a/.github/workflows/mobile-eas-preview-fork.yml b/.github/workflows/mobile-eas-preview-fork.yml index a8bf5725af70c..13ca814defd7e 100644 --- a/.github/workflows/mobile-eas-preview-fork.yml +++ b/.github/workflows/mobile-eas-preview-fork.yml @@ -40,7 +40,7 @@ jobs: # If a maintainer removed the label first, that removal wins. - id: consume name: Consume the deployment label - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8 + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 with: script: | try { @@ -75,7 +75,7 @@ jobs: # the PR's scripts to read. - name: Checkout reviewed commit if: steps.expo-token.outputs.present == 'true' - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ github.event.pull_request.head.sha }} fetch-depth: 0 @@ -84,7 +84,7 @@ jobs: # The comment script comes from main, not from the PR. - name: Checkout trusted scripts if: steps.expo-token.outputs.present == 'true' - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: path: .trusted sparse-checkout: .github/scripts @@ -120,7 +120,7 @@ jobs: # trusted workflows with other secrets would restore what PR code wrote. - name: Setup Vite+ if: steps.expo-token.outputs.present == 'true' - uses: voidzero-dev/setup-vp@v1 + uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1.15.0 with: node-version-file: package.json cache: false @@ -138,7 +138,7 @@ jobs: - name: Setup EAS if: steps.expo-token.outputs.present == 'true' - uses: expo/expo-github-action@v8 + uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 with: # Pinned and installed with npm for the same reasons as mobile-eas-preview.yml. eas-version: 21.8.0 @@ -166,7 +166,7 @@ jobs: - name: Deploy with fingerprint check if: steps.expo-token.outputs.present == 'true' - uses: expo/expo-github-action/continuous-deploy-fingerprint@main + uses: expo/expo-github-action/continuous-deploy-fingerprint@5273c2136bd09c2a341fe3340d3e767ce5a13015 # v9.0.2 env: EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} RUNNER_DEBUG: "1" @@ -249,14 +249,14 @@ jobs: ORG_GRADLE_PROJECT_reactNativeArchitectures: armeabi-v7a,arm64-v8a steps: - name: Checkout reviewed commit - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ github.event.pull_request.head.sha }} fetch-depth: 0 # The comment script comes from main, not from the PR. - name: Checkout trusted scripts - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: path: .trusted sparse-checkout: .github/scripts @@ -288,7 +288,7 @@ jobs: fi - name: Setup Node - uses: actions/setup-node@v6 + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 with: node-version-file: package.json @@ -302,13 +302,13 @@ jobs: run: pnpm install --frozen-lockfile --filter=@t3tools/mobile... - name: Setup Java - uses: actions/setup-java@v5 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: temurin java-version: 17 - name: Setup EAS - uses: expo/expo-github-action@v8 + uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 with: eas-version: latest eas-cache: false diff --git a/.github/workflows/mobile-eas-preview.yml b/.github/workflows/mobile-eas-preview.yml index 5989d7a0c0cc8..b46e090434f58 100644 --- a/.github/workflows/mobile-eas-preview.yml +++ b/.github/workflows/mobile-eas-preview.yml @@ -38,7 +38,7 @@ jobs: - name: Checkout if: steps.expo-token.outputs.present == 'true' - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 0 # No sparse-checkout here: it makes actions/checkout fetch with @@ -48,7 +48,7 @@ jobs: - name: Setup Vite+ if: steps.expo-token.outputs.present == 'true' - uses: voidzero-dev/setup-vp@v1 + uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1.15.0 with: node-version-file: package.json cache: true @@ -66,7 +66,7 @@ jobs: - name: Setup EAS if: steps.expo-token.outputs.present == 'true' - uses: expo/expo-github-action@v8 + uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 with: # eas-cli 22 renamed `project` to `app` in build JSON, and # continuous-deploy-fingerprint still reads `build.project.ownerAccount`. @@ -99,7 +99,7 @@ jobs: - name: Deploy with fingerprint check if: steps.expo-token.outputs.present == 'true' - uses: expo/expo-github-action/continuous-deploy-fingerprint@main + uses: expo/expo-github-action/continuous-deploy-fingerprint@5273c2136bd09c2a341fe3340d3e767ce5a13015 # v9.0.2 env: EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} # The Expo action otherwise suppresses the EAS command's failure output. @@ -154,7 +154,7 @@ jobs: - name: Checkout if: steps.expo-token.outputs.present == 'true' - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 0 @@ -187,7 +187,7 @@ jobs: - name: Setup Vite+ if: steps.expo-token.outputs.present == 'true' - uses: voidzero-dev/setup-vp@v1 + uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1.15.0 with: node-version-file: package.json cache: true @@ -205,7 +205,7 @@ jobs: - name: Setup EAS if: steps.expo-token.outputs.present == 'true' - uses: expo/expo-github-action@v8 + uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 with: eas-version: latest token: ${{ secrets.EXPO_PREVIEW_TOKEN }} @@ -290,7 +290,7 @@ jobs: ORG_GRADLE_PROJECT_reactNativeArchitectures: armeabi-v7a,arm64-v8a steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 0 @@ -349,7 +349,7 @@ jobs: - name: Mount build cache if: steps.record.outputs.built != 'true' - uses: useblacksmith/stickydisk@v1 + uses: useblacksmith/stickydisk@3f6be1451e3cad893b778bc93495c80452a5da26 # v1.7.2 with: key: ${{ github.repository }}-android-preview-build path: ~/.cache/t3-android-preview @@ -367,7 +367,7 @@ jobs: - name: Setup Node if: steps.record.outputs.built != 'true' - uses: actions/setup-node@v6 + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 with: node-version-file: package.json @@ -384,14 +384,14 @@ jobs: - name: Setup Java if: steps.record.outputs.built != 'true' - uses: actions/setup-java@v5 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: temurin java-version: 17 - name: Setup EAS if: steps.record.outputs.built != 'true' - uses: expo/expo-github-action@v8 + uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 with: eas-version: latest token: ${{ secrets.EXPO_PREVIEW_TOKEN }} diff --git a/.github/workflows/mobile-eas-production.yml b/.github/workflows/mobile-eas-production.yml index 1bf16d8a8f65e..39f9d01f61348 100644 --- a/.github/workflows/mobile-eas-production.yml +++ b/.github/workflows/mobile-eas-production.yml @@ -124,7 +124,7 @@ jobs: - id: version_app_token name: Mint release app token for version override if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' && inputs.version != '' && inputs.profile != 'testflight' - uses: actions/create-github-app-token@v2 + uses: actions/create-github-app-token@fee1f7d63c2ff003460e3d139729b119787bc349 # v2.2.2 with: app-id: ${{ secrets.RELEASE_APP_ID }} private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }} @@ -132,7 +132,7 @@ jobs: - name: Checkout if: steps.expo-token.outputs.present == 'true' - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 0 token: ${{ steps.version_app_token.outputs.token || github.token }} @@ -143,7 +143,7 @@ jobs: - name: Setup Vite+ if: steps.expo-token.outputs.present == 'true' - uses: voidzero-dev/setup-vp@v1 + uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1.15.0 with: node-version-file: package.json cache: true @@ -161,7 +161,7 @@ jobs: - name: Setup EAS if: steps.expo-token.outputs.present == 'true' - uses: expo/expo-github-action@v8 + uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 with: eas-version: latest token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} @@ -498,7 +498,7 @@ jobs: BUILD_TAG: mobile-android-build/${{ needs.production.outputs.android_version }}/${{ needs.production.outputs.android_fingerprint }} steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ needs.production.outputs.android_sha }} fetch-depth: 0 @@ -551,7 +551,7 @@ jobs: - name: Mount build cache if: steps.record.outputs.built != 'true' - uses: useblacksmith/stickydisk@v1 + uses: useblacksmith/stickydisk@3f6be1451e3cad893b778bc93495c80452a5da26 # v1.7.2 with: key: ${{ github.repository }}-android-store-build path: ~/.cache/t3-android-store @@ -569,7 +569,7 @@ jobs: - name: Setup Node if: steps.record.outputs.built != 'true' - uses: actions/setup-node@v6 + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 with: node-version-file: package.json @@ -588,14 +588,14 @@ jobs: - name: Setup Java if: steps.record.outputs.built != 'true' - uses: actions/setup-java@v5 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: temurin java-version: 17 - name: Setup EAS if: steps.record.outputs.built != 'true' - uses: expo/expo-github-action@v8 + uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 with: eas-version: latest token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} @@ -642,7 +642,7 @@ jobs: # A --path submission doesn't keep its archive on EAS; this is the only downloadable copy. - name: Keep the AAB if: steps.record.outputs.built != 'true' - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: android-store-aab-${{ github.run_id }}-${{ github.run_attempt }} path: ${{ runner.temp }}/t3code.aab @@ -704,7 +704,7 @@ jobs: ALLOW_XCODE_RC: ${{ vars.MOBILE_IOS_ALLOW_XCODE_RC == 'true' }} steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ needs.production.outputs.ios_sha }} fetch-depth: 0 @@ -761,7 +761,7 @@ jobs: - name: Setup Node if: steps.record.outputs.built != 'true' - uses: actions/setup-node@v6 + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 with: node-version-file: package.json @@ -780,7 +780,7 @@ jobs: - name: Setup EAS if: steps.record.outputs.built != 'true' - uses: expo/expo-github-action@v8 + uses: expo/expo-github-action@c7b66a9c327a43a8fa7c0158e7f30d6040d2481e # v8.2.1 with: eas-version: latest token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} diff --git a/.github/workflows/mobile-fingerprint-check.yml b/.github/workflows/mobile-fingerprint-check.yml index 9fabb3a5f2ad2..437f16c4684be 100644 --- a/.github/workflows/mobile-fingerprint-check.yml +++ b/.github/workflows/mobile-fingerprint-check.yml @@ -33,7 +33,7 @@ jobs: NODE_OPTIONS: --max-old-space-size=8192 steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: # The merge ref can advance after the event is queued. Pin its commit # and compare against its first parent, rather than the event's base. @@ -58,7 +58,7 @@ jobs: - name: Setup Vite+ if: steps.changes.outputs.relevant == 'true' - uses: voidzero-dev/setup-vp@v1 + uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1.15.0 with: node-version-file: package.json cache: true @@ -136,7 +136,7 @@ jobs: printf '%s\n' "$CHANGED_PLATFORMS" > "$RUNNER_TEMP/fingerprint-result/changed-platforms" - name: Upload changed platforms - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: fingerprint-result path: ${{ runner.temp }}/fingerprint-result diff --git a/.github/workflows/mobile-fingerprint-label.yml b/.github/workflows/mobile-fingerprint-label.yml index 45e4c9f2ad42d..a48462eec8c53 100644 --- a/.github/workflows/mobile-fingerprint-label.yml +++ b/.github/workflows/mobile-fingerprint-label.yml @@ -33,7 +33,7 @@ jobs: steps: - id: pr name: Resolve the pull request behind the check - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8 + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 with: script: | const run = context.payload.workflow_run; @@ -100,7 +100,7 @@ jobs: - name: Sync native change label if: steps.pr.outputs.pr_number != '' - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8 + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 env: PR_NUMBER: ${{ steps.pr.outputs.pr_number }} CHANGED_PLATFORMS: ${{ steps.result.outputs.changed_platforms }} diff --git a/.github/workflows/mobile-showcase-screenshots.yml b/.github/workflows/mobile-showcase-screenshots.yml index 53b0a74a1f5aa..3210ae37d7671 100644 --- a/.github/workflows/mobile-showcase-screenshots.yml +++ b/.github/workflows/mobile-showcase-screenshots.yml @@ -51,7 +51,7 @@ jobs: timeout-minutes: ${{ inputs.theme == 'all' && 300 || 60 }} steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: sparse-checkout: | /* @@ -59,7 +59,7 @@ jobs: sparse-checkout-cone-mode: false - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1.15.0 with: node-version-file: package.json cache: true @@ -98,7 +98,7 @@ jobs: - name: Upload iOS screenshots if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: app-store-connect-screenshots path: artifacts/app-store/screenshots/apple/ @@ -116,7 +116,7 @@ jobs: T3_SHOWCASE_ANDROID_ABI: x86_64 steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: sparse-checkout: | /* @@ -124,7 +124,7 @@ jobs: sparse-checkout-cone-mode: false - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1.15.0 with: node-version-file: package.json cache: true @@ -142,13 +142,13 @@ jobs: "$vp_pnpm_bin/pnpm" --version - name: Setup Java - uses: actions/setup-java@v5 + uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 with: distribution: temurin java-version: 17 - name: Setup Gradle cache - uses: gradle/actions/setup-gradle@v5 + uses: gradle/actions/setup-gradle@0723195856401067f7a2779048b490ace7a47d7c # v5.0.2 - name: Enable KVM run: | @@ -158,7 +158,7 @@ jobs: sudo udevadm trigger --name-match=kvm - name: Capture Android showcase - uses: reactivecircus/android-emulator-runner@v2 + uses: reactivecircus/android-emulator-runner@a421e43855164a8197daf9d8d40fe71c6996bb0d # v2.38.0 with: api-level: 36 target: google_apis @@ -175,7 +175,7 @@ jobs: - name: Upload Android screenshots if: always() - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: google-play-screenshots path: artifacts/app-store/screenshots/google-play/ diff --git a/.github/workflows/pr-limits.yml b/.github/workflows/pr-limits.yml index 75943062735cd..d6a2864f94a9b 100644 --- a/.github/workflows/pr-limits.yml +++ b/.github/workflows/pr-limits.yml @@ -34,13 +34,13 @@ jobs: # branch and never run PR code. Cone mode also checks out the files beside # .github/scripts, which is where TRIAGE_EXEMPTIONS.td and VOUCHED.td live. - name: Checkout trusted scripts - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ github.event.repository.default_branch }} sparse-checkout: .github/scripts - name: Close PRs over the limit - uses: actions/github-script@v8 + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 env: DRY_RUN: ${{ vars.PR_LIMITS_ENFORCE != 'true' }} with: @@ -57,13 +57,13 @@ jobs: cancel-in-progress: false steps: - name: Checkout trusted scripts - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ github.event.repository.default_branch }} sparse-checkout: .github/scripts - name: Request rebases and close what went unanswered - uses: actions/github-script@v8 + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 env: DRY_RUN: ${{ vars.PR_LIMITS_ENFORCE != 'true' || (github.event_name == 'workflow_dispatch' && inputs.dry_run) }} with: diff --git a/.github/workflows/pr-size.yml b/.github/workflows/pr-size.yml index cb0c9637fcef7..45f5c9b9f7760 100644 --- a/.github/workflows/pr-size.yml +++ b/.github/workflows/pr-size.yml @@ -16,7 +16,7 @@ jobs: steps: - id: config name: Build PR size label config - uses: actions/github-script@v8 + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 with: result-encoding: string script: | @@ -64,7 +64,7 @@ jobs: issues: write steps: - name: Ensure PR size labels exist - uses: actions/github-script@v8 + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 env: PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }} with: @@ -128,11 +128,11 @@ jobs: # git data. Do not add dependency installs, build/test scripts, or cache # actions here; use pull_request plus workflow_run for that pattern instead. - name: Checkout base repository - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: fetch-depth: 0 - name: Sync PR size label - uses: actions/github-script@v8 + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 env: PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }} with: @@ -295,7 +295,7 @@ jobs: ); # Reads the script from the base checkout above; the PR's own commits are only diffed. - name: Report test suite growth - uses: actions/github-script@v8 + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 with: script: | const { execFileSync } = require("node:child_process"); diff --git a/.github/workflows/pr-vouch.yml b/.github/workflows/pr-vouch.yml index 75e2ee8a56548..39d368f9a20d6 100644 --- a/.github/workflows/pr-vouch.yml +++ b/.github/workflows/pr-vouch.yml @@ -29,7 +29,7 @@ jobs: targets: ${{ steps.collect.outputs.targets }} steps: - id: collect - uses: actions/github-script@v8 + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 with: script: | if (context.eventName === "pull_request_target") { @@ -81,7 +81,7 @@ jobs: steps: - id: vouch name: Check PR author trust - uses: mitchellh/vouch/action/check-user@v1 + uses: mitchellh/vouch/action/check-user@d66fa29a64600490892131ad87597c30c91fcac4 # v1.5.0 with: user: ${{ matrix.target.user }} allow-fail: true @@ -89,7 +89,7 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Sync PR labels - uses: actions/github-script@v8 + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 env: PR_NUMBER: ${{ matrix.target.number }} VOUCH_STATUS: ${{ steps.vouch.outputs.status }} diff --git a/.github/workflows/publish-aur.yml b/.github/workflows/publish-aur.yml index 4ab6db89ab703..dc88f0150945b 100644 --- a/.github/workflows/publish-aur.yml +++ b/.github/workflows/publish-aur.yml @@ -48,7 +48,7 @@ jobs: run: pacman -Syu --noconfirm --needed git github-cli jq namcap openssh sudo - name: Checkout packaging sources - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 - name: Create unprivileged build user run: | diff --git a/.github/workflows/relay-preview-cleanup.yml b/.github/workflows/relay-preview-cleanup.yml index eed067adfd773..483e3e0b01b7e 100644 --- a/.github/workflows/relay-preview-cleanup.yml +++ b/.github/workflows/relay-preview-cleanup.yml @@ -58,7 +58,7 @@ jobs: ALCHEMY_TELEMETRY_DISABLED: "1" steps: - name: Checkout default branch - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ github.event.repository.default_branch }} sparse-checkout: | @@ -67,7 +67,7 @@ jobs: sparse-checkout-cone-mode: false - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1.15.0 with: node-version-file: package.json cache: true @@ -170,7 +170,7 @@ jobs: - name: Checkout default branch if: steps.eligible.outputs.eligible == 'yes' - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ github.event.repository.default_branch }} sparse-checkout: | @@ -180,7 +180,7 @@ jobs: - name: Setup Vite+ if: steps.eligible.outputs.eligible == 'yes' - uses: voidzero-dev/setup-vp@v1 + uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1.15.0 with: node-version-file: package.json cache: true diff --git a/.github/workflows/relay-preview.yml b/.github/workflows/relay-preview.yml index fdce22c68a59e..daec319087759 100644 --- a/.github/workflows/relay-preview.yml +++ b/.github/workflows/relay-preview.yml @@ -53,7 +53,7 @@ jobs: fi - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ github.event.pull_request.head.sha }} sparse-checkout: | @@ -62,7 +62,7 @@ jobs: sparse-checkout-cone-mode: false - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1.15.0 with: node-version-file: package.json cache: true diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml index b227a2b8b12fe..48f410f0c920a 100644 --- a/.github/workflows/release-desktop.yml +++ b/.github/workflows/release-desktop.yml @@ -157,7 +157,7 @@ jobs: # artifact leaves the cache empty, so installation runs the checks again. - name: Download dependency verification continue-on-error: true - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: release-dependency-verification path: ${{ runner.temp }}/pnpm-metadata @@ -183,7 +183,7 @@ jobs: - name: Restore staged install cache id: stage_pnpm_cache - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ steps.stage_pnpm.outputs.dir }} key: ${{ steps.stage_pnpm.outputs.prefix }}${{ github.run_id }}-${{ github.run_attempt }} @@ -195,7 +195,7 @@ jobs: - name: Cache resource monitor id: resource_monitor_cache - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: native/resource-monitor/target/${{ inputs.rust_target }}/release/t3-resource-monitor${{ inputs.platform == 'win' && '.exe' || '' }} key: resource-monitor-${{ inputs.rust_target }}-${{ hashFiles('native/resource-monitor/Cargo.lock', 'native/resource-monitor/Cargo.toml', 'native/resource-monitor/src/**') }} @@ -203,7 +203,7 @@ jobs: - name: Cache Linux capture helpers if: inputs.platform == 'linux' id: capture_helper_cache - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: | native/kde-snap-shot/target/${{ inputs.rust_target }}/release/t3-kde-snap-shot @@ -216,7 +216,7 @@ jobs: # files and downloads again on a mismatch, so only raw archives are cached. - name: Cache Linux packaging tool archives if: inputs.platform == 'linux' - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: | ~/.cache/electron-builder/appimage@*/appimage-tools-runtime-*.tar.gz @@ -234,14 +234,14 @@ jobs: - name: Setup Rust if: steps.resource_monitor_cache.outputs.cache-hit != 'true' || (inputs.platform == 'linux' && steps.capture_helper_cache.outputs.cache-hit != 'true') - uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable + uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master with: toolchain: stable targets: ${{ inputs.rust_target }} - name: Download relay client tracing config if: inputs.relay_client_tracing - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: relay-client-tracing-config path: ${{ runner.temp }}/relay-client-tracing @@ -262,14 +262,14 @@ jobs: # ancestor of its paths), so extracting into `apps` restores # apps/server/dist and apps/desktop/dist-electron at their build paths. - name: Download JS bundle - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: js-bundle path: apps - name: Install cargo-xwin if: inputs.platform == 'win' && steps.resource_monitor_cache.outputs.cache-hit != 'true' - uses: taiki-e/install-action@8cca0918f8471c33515202b73f56ab27f2bed283 # v2 + uses: taiki-e/install-action@cfdb7ed4ccc7c7dce37759eae89dc5674b469b39 # v2.90.3 with: tool: cargo-xwin@0.23.1 @@ -317,7 +317,7 @@ jobs: - name: Restore target Node.js for the CLI executable id: target_node_cache if: inputs.cli_archive && inputs.platform == 'win' - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ runner.temp }}/node-download key: node-download-v${{ steps.target_node.outputs.version }}-win-${{ inputs.arch }} @@ -344,7 +344,7 @@ jobs: # Saved right away so a later failure in this job still keeps the download. - name: Save target Node.js for the CLI executable if: inputs.cli_archive && inputs.platform == 'win' && steps.target_node_cache.outputs.cache-hit != 'true' - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ runner.temp }}/node-download key: ${{ steps.target_node_cache.outputs.cache-primary-key }} @@ -479,7 +479,7 @@ jobs: # macOS uploads its archive after "Await CLI notarization" instead. - name: Upload CLI archive if: inputs.cli_archive && inputs.platform != 'mac' - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: cli-${{ inputs.platform }}-${{ inputs.arch }} path: release-cli/* @@ -559,7 +559,7 @@ jobs: - name: Download Linux CLI archive for WSL if: inputs.platform == 'win' - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: cli-linux-${{ inputs.arch }} path: wsl-runtime @@ -680,7 +680,7 @@ jobs: - name: Upload notarized CLI archive if: inputs.cli_archive && inputs.platform == 'mac' - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: cli-${{ inputs.platform }}-${{ inputs.arch }} path: release-cli/* @@ -700,7 +700,7 @@ jobs: - name: Save staged install cache if: steps.stage_pnpm_changed.outputs.changed == 'true' - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ steps.stage_pnpm.outputs.dir }} key: ${{ steps.stage_pnpm_cache.outputs.cache-primary-key }} @@ -731,7 +731,7 @@ jobs: - name: Upload launch check output if: failure() && inputs.launch_check - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: desktop-launch-check-${{ inputs.platform }}-${{ inputs.arch }} path: ${{ runner.temp }}/desktop-launch-check @@ -759,7 +759,7 @@ jobs: - name: Upload verification inputs if: inputs.verify_runner != '' - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: verify-${{ inputs.platform }}-${{ inputs.arch }} path: verify/* @@ -826,7 +826,7 @@ jobs: cp "$source_path" "$target_dir/$binary_name" - name: Upload build artifacts - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: desktop-${{ inputs.platform }}-${{ inputs.arch }} path: release-publish/* @@ -835,7 +835,7 @@ jobs: compression-level: 0 - name: Upload resource monitor - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: resource-monitor-${{ inputs.resource_key }} path: resource-monitor-publish/${{ inputs.resource_key }}/* @@ -849,14 +849,14 @@ jobs: timeout-minutes: 15 steps: - name: Download verification inputs - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: verify-${{ inputs.platform }}-${{ inputs.arch }} path: verify - name: Download CLI archive if: inputs.cli_archive - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: cli-${{ inputs.platform }}-${{ inputs.arch }} path: release-cli diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ec5ec6b15a6ba..415082f21f209 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -61,13 +61,13 @@ jobs: has_changes: ${{ steps.resolve.outputs.has_changes }} steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: sparse-checkout: .github/scripts - id: resolve name: Resolve release commit - uses: actions/github-script@v8 + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 env: DISPATCH_CHANNEL: ${{ inputs.channel }} with: @@ -124,7 +124,7 @@ jobs: ref: ${{ needs.resolve_commit.outputs.ref }} steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ needs.resolve_commit.outputs.ref }} fetch-depth: 0 @@ -228,7 +228,7 @@ jobs: # Share only the verification results, not the large registry metadata cache. - name: Upload dependency verification continue-on-error: true - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: release-dependency-verification path: ${{ runner.temp }}/pnpm-metadata/lockfile-verified.jsonl @@ -241,7 +241,7 @@ jobs: timeout-minutes: 10 steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ needs.preflight.outputs.ref }} sparse-checkout: | @@ -273,7 +273,7 @@ jobs: timeout-minutes: 10 steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ needs.preflight.outputs.ref }} sparse-checkout: | @@ -313,7 +313,7 @@ jobs: shard: [1, 2] steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ needs.preflight.outputs.ref }} sparse-checkout: | @@ -332,7 +332,7 @@ jobs: - name: Cache Chromium id: chromium_cache - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ~/.cache/ms-playwright key: playwright-chromium-shell-${{ runner.os }}-${{ runner.arch }}-${{ steps.playwright_version.outputs.version }} @@ -372,7 +372,7 @@ jobs: shard: [1, 2, 3, 4, 5, 6, 7, 8] steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ needs.preflight.outputs.ref }} sparse-checkout: | @@ -425,7 +425,7 @@ jobs: CLERK_CLI_OAUTH_CLIENT_ID: ${{ vars.CLERK_CLI_OAUTH_CLIENT_ID }} steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ needs.resolve_commit.outputs.ref }} sparse-checkout: | @@ -465,7 +465,7 @@ jobs: } > "$RUNNER_TEMP/relay-client-tracing.env" - name: Upload relay client tracing config - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: relay-client-tracing-config path: ${{ runner.temp }}/relay-client-tracing.env @@ -535,7 +535,7 @@ jobs: T3CODE_RELAY_URL: ${{ needs.relay_public_config.outputs.relay_url }} steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ needs.preflight.outputs.ref }} sparse-checkout: | @@ -547,7 +547,7 @@ jobs: # artifact leaves the cache empty, so installation runs the checks again. - name: Download dependency verification continue-on-error: true - uses: actions/download-artifact@v8 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: release-dependency-verification path: ${{ runner.temp }}/pnpm-metadata @@ -560,7 +560,7 @@ jobs: pnpm_config_cache_dir: ${{ runner.temp }}/pnpm-metadata - name: Download relay client tracing config - uses: actions/download-artifact@v8 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: relay-client-tracing-config path: ${{ runner.temp }}/relay-client-tracing @@ -606,7 +606,7 @@ jobs: # Two paths under apps/ so the artifact root is apps/; consumers download # into `apps` to restore both at their original locations. - name: Upload JS bundle - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: js-bundle path: | @@ -624,7 +624,7 @@ jobs: # this upload by its ID, which a publish_cli-only rerun keeps. - name: Upload the npm launcher id: npm_launcher - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: npm-launcher path: npm-packages/t3.tgz @@ -819,7 +819,7 @@ jobs: pull-requests: read steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ needs.preflight.outputs.ref }} # Release notes need history back to the previous tag, not file contents. @@ -854,14 +854,14 @@ jobs: fi - name: Download all desktop artifacts - uses: actions/download-artifact@v8 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: pattern: desktop-* merge-multiple: true path: release-assets - name: Download all CLI archives - uses: actions/download-artifact@v8 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: pattern: cli-* merge-multiple: true @@ -1004,7 +1004,7 @@ jobs: - name: Publish release if: needs.preflight.outputs.previous_tag != '' - uses: softprops/action-gh-release@v3 + uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4 with: tag_name: ${{ needs.preflight.outputs.tag }} target_commitish: ${{ needs.preflight.outputs.ref }} @@ -1021,7 +1021,7 @@ jobs: - name: Publish first release if: needs.preflight.outputs.previous_tag == '' - uses: softprops/action-gh-release@v3 + uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4 with: tag_name: ${{ needs.preflight.outputs.tag }} target_commitish: ${{ needs.preflight.outputs.ref }} @@ -1062,7 +1062,7 @@ jobs: steps: # Only what setup-ci-deps reads to install the project's Node and npm. - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ needs.preflight.outputs.ref }} sparse-checkout: | @@ -1089,7 +1089,7 @@ jobs: fi - name: Download the npm launcher - uses: actions/download-artifact@v8 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: artifact-ids: ${{ needs.build_bundle.outputs.npm_launcher_artifact_id }} path: npm-packages @@ -1151,7 +1151,7 @@ jobs: VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }} steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ needs.preflight.outputs.ref }} sparse-checkout: | @@ -1165,7 +1165,7 @@ jobs: install-args: --filter=@t3tools/scripts... --filter=@t3tools/web... - name: Download relay client tracing config - uses: actions/download-artifact@v8 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: relay-client-tracing-config path: ${{ runner.temp }}/relay-client-tracing @@ -1251,7 +1251,7 @@ jobs: # Only what setup-ci-deps reads to install vp and Node. The alias call # names its deployment and scope, so it reads nothing else from the repo. - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ needs.preflight.outputs.ref }} sparse-checkout: | @@ -1322,7 +1322,7 @@ jobs: VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }} steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ needs.preflight.outputs.ref }} sparse-checkout: | @@ -1388,7 +1388,7 @@ jobs: VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }} steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ needs.preflight.outputs.ref }} sparse-checkout: | @@ -1426,14 +1426,14 @@ jobs: steps: - id: app_token name: Mint release app token - uses: actions/create-github-app-token@v2 + uses: actions/create-github-app-token@fee1f7d63c2ff003460e3d139729b119787bc349 # v2.2.2 with: app-id: ${{ secrets.RELEASE_APP_ID }} private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }} owner: ${{ github.repository_owner }} - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: main fetch-depth: 0 @@ -1517,7 +1517,7 @@ jobs: timeout-minutes: 10 steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ needs.preflight.outputs.ref }} sparse-checkout: | diff --git a/.github/workflows/stale-needs-more-info.yml b/.github/workflows/stale-needs-more-info.yml index b7b475a6117dc..9d994115705f4 100644 --- a/.github/workflows/stale-needs-more-info.yml +++ b/.github/workflows/stale-needs-more-info.yml @@ -13,7 +13,7 @@ jobs: stale: runs-on: ubuntu-latest steps: - - uses: actions/stale@v9 + - uses: actions/stale@5bef64f19d7facfb25b37b414482c7164d639639 # v9.1.0 with: only-issue-labels: "needs more info" # The label is applied by the triage flow, so never auto-mark; close 7 days after it was added. diff --git a/.github/workflows/thread-transfer-report.yml b/.github/workflows/thread-transfer-report.yml index 23eec72923bd8..94987b447745b 100644 --- a/.github/workflows/thread-transfer-report.yml +++ b/.github/workflows/thread-transfer-report.yml @@ -22,7 +22,7 @@ jobs: # workflow_run has a write-capable token even for fork PRs. Only load the # publisher from the trusted default branch and never execute PR code. - name: Checkout trusted publisher - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ github.event.repository.default_branch }} sparse-checkout: .github/scripts @@ -32,7 +32,7 @@ jobs: - id: resolve name: Resolve PR and baseline artifacts - uses: actions/github-script@v8 + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 with: script: | const reporter = require("./.github/scripts/thread-transfer-report.cjs"); @@ -40,7 +40,7 @@ jobs: - name: Download PR result if: steps.resolve.outputs.publish == 'true' && steps.resolve.outputs.pr_artifact == 'true' - uses: actions/download-artifact@v8 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: thread-transfer-results path: ${{ runner.temp }}/thread-transfer/pr @@ -49,7 +49,7 @@ jobs: - name: Download main baseline if: steps.resolve.outputs.publish == 'true' && steps.resolve.outputs.baseline_artifact == 'true' - uses: actions/download-artifact@v8 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: thread-transfer-results path: ${{ runner.temp }}/thread-transfer/main @@ -58,7 +58,7 @@ jobs: - name: Update thread transfer comment if: steps.resolve.outputs.publish == 'true' - uses: actions/github-script@v8 + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 env: PR_NUMBER: ${{ steps.resolve.outputs.pull_number }} PR_SHA: ${{ steps.resolve.outputs.pr_sha }} diff --git a/.github/workflows/web-preview.yml b/.github/workflows/web-preview.yml index 4b3f8952d503d..69db6b6025e8f 100644 --- a/.github/workflows/web-preview.yml +++ b/.github/workflows/web-preview.yml @@ -46,7 +46,7 @@ jobs: VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }} steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ github.event.pull_request.head.sha }} sparse-checkout: | @@ -55,7 +55,7 @@ jobs: sparse-checkout-cone-mode: false - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1.15.0 with: node-version-file: package.json cache: true @@ -97,7 +97,7 @@ jobs: echo "deployment_url=$deployment_url" >> "$GITHUB_OUTPUT" - name: Comment deployment URL - uses: actions/github-script@v8 + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 env: DEPLOYMENT_URL: ${{ steps.deploy.outputs.deployment_url }} HEAD_SHA: ${{ github.event.pull_request.head.sha }} diff --git a/.github/workflows/windows-tests.yml b/.github/workflows/windows-tests.yml index 3a70ad5a26a05..9a8e69d69cc29 100644 --- a/.github/workflows/windows-tests.yml +++ b/.github/workflows/windows-tests.yml @@ -30,7 +30,7 @@ jobs: timeout-minutes: 45 steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: sparse-checkout: | /* @@ -40,7 +40,7 @@ jobs: # setup-vp's own cache restores a Linux-shaped store on Windows, which is # slower than no cache (see #7975). Cache pnpm's Windows store directly. - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1.15.0 with: node-version-file: package.json cache: false @@ -52,7 +52,7 @@ jobs: run: '"path=$(vp pm cache dir)" >> $env:GITHUB_OUTPUT' - name: Cache packages - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ steps.package_cache_path.outputs.path }} key: windows-tests-packages-v1-${{ hashFiles('pnpm-lock.yaml') }} diff --git a/apps/desktop/src/app/DesktopObservability.test.ts b/apps/desktop/src/app/DesktopObservability.test.ts index ab8ea0b8e9d6e..ceb29b149e3d6 100644 --- a/apps/desktop/src/app/DesktopObservability.test.ts +++ b/apps/desktop/src/app/DesktopObservability.test.ts @@ -281,6 +281,27 @@ describe("DesktopObservability", () => { ), ); + it.effect("startup prunes only canonical rotation suffixes", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const directory = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-desktop-rotating-prune-test-", + }); + const filePath = `${directory}/server-child.log`; + const retained = ["1", "3", "04", "4.0", "4e0", "0x4", "+4", "notes"]; + for (const suffix of [...retained, "4", "50"]) { + yield* fileSystem.writeFileString(`${filePath}.${suffix}`, suffix); + } + + yield* DesktopObservability.makeRotatingLogFileWriter({ filePath, maxFiles: 3 }); + + assert.deepEqual( + (yield* fileSystem.readDirectory(directory)).sort(), + retained.map((suffix) => `server-child.log.${suffix}`).sort(), + ); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + it.effect("stops every export when the OpenTelemetry SDK is disabled", () => { const requests: Array = []; return Effect.gen(function* () { diff --git a/apps/desktop/src/app/DesktopObservability.ts b/apps/desktop/src/app/DesktopObservability.ts index e9b0ab9379dfe..16192fff46de8 100644 --- a/apps/desktop/src/app/DesktopObservability.ts +++ b/apps/desktop/src/app/DesktopObservability.ts @@ -263,8 +263,10 @@ export const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")( const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => [])); for (const entry of entries) { if (!entry.startsWith(`${baseName}.`)) continue; - const suffix = Number(entry.slice(baseName.length + 1)); - if (!Number.isInteger(suffix) || suffix <= maxFiles) continue; + const suffixText = entry.slice(baseName.length + 1); + const suffix = Number(suffixText); + if (!Number.isInteger(suffix) || String(suffix) !== suffixText || suffix <= maxFiles) + continue; yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore); } }); diff --git a/apps/desktop/src/backend/tailscaleEndpointProvider.test.ts b/apps/desktop/src/backend/tailscaleEndpointProvider.test.ts index 054655917cecc..397a757704835 100644 --- a/apps/desktop/src/backend/tailscaleEndpointProvider.test.ts +++ b/apps/desktop/src/backend/tailscaleEndpointProvider.test.ts @@ -1,7 +1,7 @@ import { assert, describe, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import { HttpClient } from "effect/http"; +import { HttpClient, HttpClientResponse } from "effect/http"; import { ChildProcessSpawner } from "effect/process"; import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts"; @@ -79,4 +79,41 @@ describe("tailscale endpoint provider", () => { ); }).pipe(Effect.provide(layerUnusedTailscaleExternalServices)), ); + + it.effect("offers Tailscale HTTPS only when Serve reaches this desktop's backend", () => + Effect.gen(function* () { + const magicDnsStatus = (servedEnvironmentId: string) => + resolveTailscaleAdvertisedEndpoints({ + port: 3773, + serveEnabled: true, + networkInterfaces: {}, + statusJson: `{"Self":{"DNSName":"desktop.example.ts.net.","TailscaleIPs":[]}}`, + }).pipe( + Effect.map((endpoints) => endpoints.map((endpoint) => endpoint.status)), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + Response.json({ + environmentId: + new URL(request.url).hostname === "127.0.0.1" + ? "desktop-backend" + : servedEnvironmentId, + label: "T3 server", + platform: { os: "linux", arch: "x64" }, + serverVersion: "0.1.9", + capabilities: { repositoryIdentity: true }, + }), + ), + ), + ), + ), + ); + + assert.deepEqual(yield* magicDnsStatus("desktop-backend"), ["available"]); + assert.deepEqual(yield* magicDnsStatus("another-server"), ["unavailable"]); + }).pipe(Effect.provide(layerUnusedTailscaleExternalServices)), + ); }); diff --git a/apps/desktop/src/backend/tailscaleEndpointProvider.ts b/apps/desktop/src/backend/tailscaleEndpointProvider.ts index 4b75afccdb5bc..1b8d9dff4ed4d 100644 --- a/apps/desktop/src/backend/tailscaleEndpointProvider.ts +++ b/apps/desktop/src/backend/tailscaleEndpointProvider.ts @@ -1,5 +1,9 @@ import { createAdvertisedEndpoint } from "@t3tools/shared/advertisedEndpoint"; -import type { AdvertisedEndpoint, AdvertisedEndpointProvider } from "@t3tools/contracts"; +import { + ExecutionEnvironmentDescriptor, + type AdvertisedEndpoint, + type AdvertisedEndpointProvider, +} from "@t3tools/contracts"; import { buildTailscaleHttpsBaseUrl, isTailscaleIpv4Address, @@ -11,6 +15,7 @@ import { import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientResponse from "effect/http/HttpClientResponse"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import type { NetworkInterfaces } from "./DesktopNetworkInterfaces.ts"; @@ -71,10 +76,20 @@ function resolveTailscaleIpAdvertisedEndpoints(input: { return endpoints; } +// The backend may run elsewhere (WSL), so ask it for its id instead of reading the state dir. +const probeServesThisBackend = (localHttpUrl: string) => (baseUrl: string) => + HttpClient.get(new URL("/.well-known/t3/environment", localHttpUrl)).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)), + Effect.flatMap(({ environmentId }) => probeTailscaleHttpsEndpoint({ baseUrl, environmentId })), + Effect.orElseSucceed(() => false), + ); + const resolveTailscaleMagicDnsAdvertisedEndpoint = Effect.fn( "resolveTailscaleMagicDnsAdvertisedEndpoint", )(function* (input: { readonly dnsName: string | null; + readonly localHttpUrl: string; readonly serveEnabled: boolean; readonly servePort?: number; readonly probe?: (baseUrl: string) => Effect.Effect; @@ -87,11 +102,7 @@ const resolveTailscaleMagicDnsAdvertisedEndpoint = Effect.fn( magicDnsName: input.dnsName, ...(input.servePort === undefined ? {} : { servePort: input.servePort }), }); - const probe = - input.probe?.(httpBaseUrl) ?? - probeTailscaleHttpsEndpoint({ - baseUrl: httpBaseUrl, - }); + const probe = (input.probe ?? probeServesThisBackend(input.localHttpUrl))(httpBaseUrl); const isReachable = input.serveEnabled ? yield* probe : false; return Option.some( @@ -140,6 +151,7 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd const ipEndpoints = resolveTailscaleIpAdvertisedEndpoints({ ...input, status }); const magicDnsEndpoint = yield* resolveTailscaleMagicDnsAdvertisedEndpoint({ dnsName: status?.magicDnsName ?? null, + localHttpUrl: `http://127.0.0.1:${input.port}`, serveEnabled: input.serveEnabled === true, ...(input.servePort === undefined ? {} : { servePort: input.servePort }), ...(input.probe === undefined ? {} : { probe: input.probe }), diff --git a/apps/desktop/src/electron/ElectronShell.test.ts b/apps/desktop/src/electron/ElectronShell.test.ts index 9864c19b0d0ab..e8618b4f5cc4d 100644 --- a/apps/desktop/src/electron/ElectronShell.test.ts +++ b/apps/desktop/src/electron/ElectronShell.test.ts @@ -54,18 +54,30 @@ describe("ElectronShell", () => { }).pipe(Effect.provide(ElectronShell.layer)), ); - it.effect("opens only the bare Grok Bot launch link", () => + it.effect("opens only the Grok Bot prompt link", () => Effect.gen(function* () { openExternalMock.mockResolvedValue(undefined); + const prompt = "grokbot://app/v1/prompt?text=Add%20the%20MCP%20server"; const electronShell = yield* ElectronShell.ElectronShell; const results = yield* Effect.forEach( - ["grokbot://app", "grokbot://app/v1/prompt?id=bot&text=hi", "grokbot://"], + [ + prompt, + "grokbot://app", + "grokbot://app/v1/prompt?id=bot&text=hi", + "grokbot://app/v1/prompt?text=a&text=b", + "grokbot://app/v1/other?text=hi", + "grokbot://app/v1/prompt?text=hi#x", + "grokbot://:secret@app/v1/prompt?text=hi", + "grokbot://user@app/v1/prompt?text=hi", + "grokbot://other/v1/prompt?text=hi", + "other://app/v1/prompt?text=hi", + ], (url) => electronShell.openExternal(url), ); - assert.deepEqual(results, [true, false, false]); - assert.deepEqual(openExternalMock.mock.calls, [["grokbot://app"]]); + assert.deepEqual(results, [true, ...Array(9).fill(false)]); + assert.deepEqual(openExternalMock.mock.calls, [[prompt]]); }).pipe(Effect.provide(ElectronShell.layer)), ); diff --git a/apps/desktop/src/electron/ElectronShell.ts b/apps/desktop/src/electron/ElectronShell.ts index e342361750f41..d27c51d57c6eb 100644 --- a/apps/desktop/src/electron/ElectronShell.ts +++ b/apps/desktop/src/electron/ElectronShell.ts @@ -21,9 +21,16 @@ const REMOTE_EDITOR_PROTOCOLS = new Set( }), ); -// "Use T3 Code in another app" opens these apps (apps/web/src/components/mcp/mcpApps.ts). List +// "Use T3 Code in another app" opens these apps (apps/web/src/components/mcp/mcpApps.ts). Match // each exact link shape the wizard sends, never a whole scheme. -const APP_LAUNCH_URLS = new Set(["grokbot://app"]); +const isAppLaunchUrl = (url: URL) => + url.protocol === "grokbot:" && + url.host === "app" && + url.pathname === "/v1/prompt" && + url.username.length === 0 && + url.password.length === 0 && + url.hash.length === 0 && + [...url.searchParams.keys()].join() === "text"; // Zed embeds [user@]host in the path; reject passwords and ports there. const ZED_SSH_PATHNAME = /^\/(?:[^/@:]+@)?[^/@:]+\/.*$/; @@ -50,7 +57,7 @@ export function parseSafeExternalUrl(rawUrl: unknown): Option.Option { try { const url = new URL(rawUrl); return SAFE_WEB_PROTOCOLS.has(url.protocol) || - APP_LAUNCH_URLS.has(url.href) || + isAppLaunchUrl(url) || isRemoteEditorUrl(url) || isLocalEditorFileUrl(url) ? Option.some(url.href) diff --git a/apps/desktop/src/preview/PickPreload.test.ts b/apps/desktop/src/preview/PickPreload.test.ts index 8a080183b3830..34beb7f4c8011 100644 --- a/apps/desktop/src/preview/PickPreload.test.ts +++ b/apps/desktop/src/preview/PickPreload.test.ts @@ -62,3 +62,25 @@ it("keeps the tool while typing a tool key in the comment", () => { expect(document.documentElement.getAttribute("data-t3code-annotation-tool")).toBe("select"); }); + +it("keeps comment keystrokes away from the page's capture-phase shortcuts", () => { + const pageShortcut = vi.fn((event: KeyboardEvent) => event.preventDefault()); + window.addEventListener("keydown", pageShortcut, { capture: true }); + const shadowRoot = startAnnotation(); + const comment = shadowRoot.querySelector("textarea"); + if (!comment) throw new Error("comment textarea not found"); + + comment.focus(); + const space = new KeyboardEvent("keydown", { + key: " ", + code: "Space", + bubbles: true, + cancelable: true, + composed: true, + }); + comment.dispatchEvent(space); + window.removeEventListener("keydown", pageShortcut, { capture: true }); + + expect(pageShortcut).not.toHaveBeenCalled(); + expect(space.defaultPrevented).toBe(false); +}); diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts index a9f479d32b81a..0784b21a5308b 100644 --- a/apps/desktop/src/preview/PickPreload.ts +++ b/apps/desktop/src/preview/PickPreload.ts @@ -149,6 +149,7 @@ interface AnnotationSession { teardown: (notifyMain: boolean) => void; applyTheme: (theme: DesktopPreviewAnnotationTheme) => void; setSendEnabled: (enabled: boolean) => void; + handleOverlayKey: (event: KeyboardEvent) => void; } let activeSession: AnnotationSession | null = null; @@ -225,6 +226,18 @@ const reportUnhandledShortcut = (event: KeyboardEvent): void => { window.addEventListener("keydown", reportUnhandledShortcut, true); +// Registered before page scripts so their capture listeners never see keys typed into the +// overlay; the closed shadow root retargets those to the host, hiding that they edit text. +const isolateOverlayKey = (event: KeyboardEvent): void => { + if (!activeSession || !(event.target instanceof Element) || !isAnnotationNode(event.target)) + return; + activeSession.handleOverlayKey(event); + event.stopImmediatePropagation(); +}; + +for (const type of ["keydown", "keypress", "keyup"] as const) + window.addEventListener(type, isolateOverlayKey, true); + const MOUSE_BUTTON_BACK = 3; const MOUSE_BUTTON_FORWARD = 4; @@ -1762,15 +1775,17 @@ function startAnnotation( }); }; submit.addEventListener("click", () => submitAnnotation("attach")); - root.addEventListener("keydown", (event) => { + const handleOverlayKey = (event: KeyboardEvent): void => { + if (event.type === "keyup") onVoiceKeyUp(event); + if (event.type !== "keydown") return; + onKeyDown(event); + if (event.cancelBubble) return; const submission = - event.target === comment ? resolveAnnotationSubmission(event, sendEnabled) : null; - // Bubble phase lets editor inputs handle events before hiding them from the page. - event.stopImmediatePropagation(); + shadowRoot.activeElement === comment ? resolveAnnotationSubmission(event, sendEnabled) : null; if (!submission) return; event.preventDefault(); submitAnnotation(submission); - }); + }; window.addEventListener("pointermove", onPointerMove, { capture: true, passive: false }); window.addEventListener("pointerdown", onPointerDown, { capture: true, passive: false }); @@ -1806,6 +1821,7 @@ function startAnnotation( sendEnabled = enabled; updateSendHint(); }, + handleOverlayKey, }; } diff --git a/apps/desktop/src/updates/releaseNotes.test.ts b/apps/desktop/src/updates/releaseNotes.test.ts index 6f05b1e9e94ab..a8fcc70ea355c 100644 --- a/apps/desktop/src/updates/releaseNotes.test.ts +++ b/apps/desktop/src/updates/releaseNotes.test.ts @@ -241,14 +241,20 @@ describe("normalizeDesktopUpdateReleaseNotes", () => { }); }); - it("does not throw on out-of-range numeric entities and keeps the literal", () => { + it("keeps unsupported entities literal, including out-of-range and Object.prototype names", () => { const result = normalizeDesktopUpdateReleaseNotes( - "- Broken entity �", + "- Broken entity �\n- Mentions &constructor; and &toString;", "1.0.0", "latest", ); expect(result).toEqual({ - releaseNotes: [{ version: "1.0.0", items: ["Broken entity �"], totalItems: 1 }], + releaseNotes: [ + { + version: "1.0.0", + items: ["Mentions &constructor; and &toString;", "Broken entity �"], + totalItems: 2, + }, + ], omittedReleaseCount: 0, }); }); diff --git a/apps/desktop/src/updates/releaseNotes.ts b/apps/desktop/src/updates/releaseNotes.ts index 715c1767e6a04..30bfb9ace64b8 100644 --- a/apps/desktop/src/updates/releaseNotes.ts +++ b/apps/desktop/src/updates/releaseNotes.ts @@ -20,14 +20,14 @@ const MAX_RELEASE_NOTE_GROUPS = 6; const MAX_RELEASE_NOTE_ITEMS_PER_GROUP = 8; const MAX_RELEASE_NOTE_ITEM_LENGTH = 220; -const HTML_ENTITY_REPLACEMENTS: Readonly> = { - amp: "&", - apos: "'", - gt: ">", - lt: "<", - nbsp: " ", - quot: '"', -}; +const HTML_ENTITY_REPLACEMENTS: ReadonlyMap = new Map([ + ["amp", "&"], + ["apos", "'"], + ["gt", ">"], + ["lt", "<"], + ["nbsp", " "], + ["quot", '"'], +]); function decodeCodePoint(codePoint: number, entity: string): string { if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) { @@ -37,7 +37,7 @@ function decodeCodePoint(codePoint: number, entity: string): string { } function decodeHtmlEntity(entity: string): string { - const named = HTML_ENTITY_REPLACEMENTS[entity]; + const named = HTML_ENTITY_REPLACEMENTS.get(entity); if (named) return named; if (entity.startsWith("#x")) { return decodeCodePoint(Number.parseInt(entity.slice(2), 16), entity); diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index d93bf076a78e0..b2ad65cf05374 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -493,11 +493,11 @@ const RootStackConfig = createWorkspaceStackNavigator({ Home: createNativeStackScreen({ screen: WorkspaceRootScreen, linking: "", - listeners: { + listeners: ({ navigation }) => ({ transitionStart: ({ data }) => recordHomeTransitionStart(data.closing), - transitionEnd: ({ data }) => recordHomeTransitionEnd(data.closing), + transitionEnd: ({ data }) => recordHomeTransitionEnd(data.closing, navigation.isFocused()), focus: recordHomeFocus, - }, + }), options: { ...pageRoute({ duoMinimize: "never", root: true }), contentStyle: { backgroundColor: "transparent" }, diff --git a/apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx b/apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx index d83852f260466..b312eeb645346 100644 --- a/apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx +++ b/apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx @@ -35,16 +35,33 @@ type BrowserPreviewRouteScreenProps = StaticScreenProps<{ export function BrowserPreviewRouteScreen({ route }: BrowserPreviewRouteScreenProps) { const navigation = useNavigation(); const onClose = () => navigation.goBack(); + const { environmentId, threadId } = route.params; + if (!environmentId?.trim() || !threadId?.trim()) { + return ; + } return ( ); } +function BrowserUnavailableScreen({ onClose }: { readonly onClose: () => void }) { + const insets = useSafeAreaInsets(); + const contentTopInset = useContentTopInset(); + return ( + + + + ); +} + function BrowserPreviewScreen({ environmentId, threadId, diff --git a/apps/mobile/src/features/files/filePath.test.ts b/apps/mobile/src/features/files/filePath.test.ts index 46b26d7e3bf3d..c58316af3698b 100644 --- a/apps/mobile/src/features/files/filePath.test.ts +++ b/apps/mobile/src/features/files/filePath.test.ts @@ -2,6 +2,8 @@ import { describe, expect, it } from "vite-plus/test"; import { fileRoutePathSegments, + isAudioPreviewFile, + isMarkdownPreviewFile, needsWorkspaceFileContents, resolveFileLinkPath, resolveWorkspaceRelativeFilePath, @@ -58,3 +60,14 @@ describe("needsWorkspaceFileContents", () => { expect(needsWorkspaceFileContents({ ...input, metadataKind: "directory" })).toBe(false); }); }); + +describe("workspace preview classifiers", () => { + it("treat # and ? as literal filename characters", () => { + for (const path of ["notes/clip#1.wav", "notes/clip?1.wav", "notes#old/clip.wav"]) { + expect(isAudioPreviewFile(path)).toBe(true); + } + for (const path of ["docs/draft#1.md", "docs/draft?1.md", "docs#old/draft.md"]) { + expect(isMarkdownPreviewFile(path)).toBe(true); + } + }); +}); diff --git a/apps/mobile/src/features/files/filePath.ts b/apps/mobile/src/features/files/filePath.ts index e38ff86fa6656..330ff5784da6d 100644 --- a/apps/mobile/src/features/files/filePath.ts +++ b/apps/mobile/src/features/files/filePath.ts @@ -100,15 +100,15 @@ export function isVideoPreviewFile(path: string): boolean { } export function isAudioPreviewFile(path: string): boolean { - return isWorkspaceAudioPreviewPath(path.split(/[?#]/, 1)[0] ?? ""); + return isWorkspaceAudioPreviewPath(path); } export function isSvgImagePreviewFile(path: string): boolean { - return /\.svg$/i.test(path.split(/[?#]/, 1)[0] ?? ""); + return /\.svg$/i.test(path); } export function isMarkdownPreviewFile(path: string): boolean { - return /\.(?:md|mdx)$/i.test(path.split(/[?#]/, 1)[0] ?? ""); + return /\.(?:md|mdx)$/i.test(path); } export function needsWorkspaceFileContents(input: { diff --git a/apps/mobile/src/features/home/home-route-visibility.test.tsx b/apps/mobile/src/features/home/home-route-visibility.test.tsx index b720bbae033ac..dae399420944a 100644 --- a/apps/mobile/src/features/home/home-route-visibility.test.tsx +++ b/apps/mobile/src/features/home/home-route-visibility.test.tsx @@ -4,7 +4,10 @@ import { act, useLayoutEffect } from "react"; import { createRoot } from "react-dom/client"; import { expect, it, vi } from "vite-plus/test"; -import { NativePrimaryColumnContext } from "../../native/v5-workspace-context"; +import { + NativePrimaryColumnContext, + NativeWorkspaceTabActivityContext, +} from "../../native/v5-workspace-context"; // The Thread in the detail column is the focused route on iPad split view. vi.mock("@react-navigation/native", () => ({ @@ -12,6 +15,7 @@ vi.mock("@react-navigation/native", () => ({ })); import { + recordHomeFocus, recordHomeTransitionEnd, recordHomeTransitionStart, useAtomValueWhileVisible, @@ -54,6 +58,18 @@ function setup() { ), ); }, + /** A phone has no primary column: Home is the root page of its tab's slot. */ + showHomeInTabSlot(active: boolean) { + act(() => + root.render( + + active }}> + + + , + ), + ); + }, [Symbol.dispose]() { act(() => root.unmount()); registry.dispose(); @@ -71,11 +87,51 @@ it("keeps the sidebar thread list live after switching tabs beside a focused Thr // Chats → PRs → Chats: Chats' column will-appear, then the PRs column's did-disappear. act(() => { - recordHomeTransitionEnd(true); + recordHomeTransitionEnd(true, false); recordHomeTransitionStart(false); - recordHomeTransitionEnd(true); + recordHomeTransitionEnd(true, false); }); act(() => home.registry.set(shellsAtom, 2)); expect(home.latest, "new thread shells reach the sidebar list").toBe(2); }); + +// Each phone tab slot shows its own copy of the Home route. PRs keeps Home focused; Settings +// is a route of its own. +it.each([ + { tab: "PRs", homeFocusedUnderTab: true }, + { tab: "Settings", homeFocusedUnderTab: false }, +])( + "keeps the phone thread list live after a round trip through $tab", + ({ homeFocusedUnderTab }) => { + using home = setup(); + recordHomeFocus(); + home.showHomeInTabSlot(true); + act(() => home.registry.set(shellsAtom, 1)); + expect(home.latest).toBe(1); + + // To the other tab: its slot will-appear, then the Chats slot's did-disappear. + act(() => { + recordHomeTransitionStart(false); + recordHomeTransitionEnd(true, homeFocusedUnderTab); + }); + home.showHomeInTabSlot(false); + act(() => home.registry.set(shellsAtom, 2)); + expect(home.latest, "the list under another tab holds its rows").toBe(1); + + // Back to Chats: its slot will-appear, then the other slot's did-disappear comes last. + act(() => { + recordHomeFocus(); + recordHomeTransitionStart(false); + recordHomeTransitionEnd(true, true); + }); + home.showHomeInTabSlot(true); + act(() => home.registry.set(shellsAtom, 3)); + expect(home.latest, "a server rename reaches the list").toBe(3); + + // A pushed Thread takes the focus and still stops the list. + act(() => recordHomeTransitionEnd(true, false)); + act(() => home.registry.set(shellsAtom, 4)); + expect(home.latest, "the list under a Thread holds its rows").toBe(3); + }, +); diff --git a/apps/mobile/src/features/home/home-route-visibility.ts b/apps/mobile/src/features/home/home-route-visibility.ts index 532053f8f8d07..7a8837b582a11 100644 --- a/apps/mobile/src/features/home/home-route-visibility.ts +++ b/apps/mobile/src/features/home/home-route-visibility.ts @@ -3,7 +3,10 @@ import { useNavigation } from "@react-navigation/native"; import { useContext, useRef, useSyncExternalStore } from "react"; import type { Atom } from "effect/reactivity"; -import { NativePrimaryColumnContext } from "../../native/v5-workspace-context"; +import { + NativePrimaryColumnContext, + NativeWorkspaceTabActivityContext, +} from "../../native/v5-workspace-context"; /** * Home stays mounted under a pushed Thread, and native-stack never freezes the @@ -34,8 +37,12 @@ export function recordHomeTransitionStart(closing: boolean): void { if (!closing) setHomeVisible(true); } -export function recordHomeTransitionEnd(closing: boolean): void { - if (closing) setHomeVisible(false); +/** + * Each iOS tab slot shows its own copy of the Home route, and the slot a tab switch leaves + * disappears last. So a disappear hides Home only when another route has the focus. + */ +export function recordHomeTransitionEnd(closing: boolean, homeFocused: boolean): void { + if (closing && !homeFocused) setHomeVisible(false); } /** Popping a sheet or a deep-linked route above Home has no appear event. */ @@ -46,10 +53,13 @@ export function recordHomeFocus(): void { export function useHomeRouteVisible(): boolean { const navigation = useNavigation(); const primaryColumn = useContext(NativePrimaryColumnContext); + const tabActive = useContext(NativeWorkspaceTabActivityContext)?.active ?? true; const visible = useSyncExternalStore(subscribeHomeVisibility, () => homeVisible); // Every tab slot's primary column reports to the one Home route, so a tab // switch can end on the leaving slot's disappear. Trust this column instead. if (primaryColumn) return primaryColumn.presented; + // The store is true for the Home route of every tab; this list shows in one of them. + if (!tabActive) return false; // Before Home's first navigation event: a cold deep link mounts Home under // its Thread without ever showing it. return visible ?? navigation.isFocused(); diff --git a/apps/mobile/src/features/home/useThreadListActions.test.ts b/apps/mobile/src/features/home/useThreadListActions.test.ts index b0f0ce78d0a89..0bea39e419e21 100644 --- a/apps/mobile/src/features/home/useThreadListActions.test.ts +++ b/apps/mobile/src/features/home/useThreadListActions.test.ts @@ -7,6 +7,7 @@ import { ProviderInstanceId, RunId, ThreadId, + type ThreadTitleRegenerationOutcome, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import { AsyncResult } from "effect/reactivity"; @@ -18,6 +19,7 @@ const state = vi.hoisted(() => ({ dropBusy: false, holdingRows: false, failedAction: null as string | null, + titleOutcome: null as ThreadTitleRegenerationOutcome | null, archivedRefreshes: [] as string[], scopes: new Map>(), shells: [] as EnvironmentThreadShell[], @@ -141,6 +143,7 @@ vi.mock("../../state/threads", () => ({ "reorderPin", "reorderActive", "updateMetadata", + "regenerateTitle", ].map((action) => [ action, async (request: { @@ -155,7 +158,7 @@ vi.mock("../../state/threads", () => ({ if (action === state.failedAction) return AsyncResult.failure(Cause.fail(new Error("Server rejected action"))); state.afterRequest?.(); - return AsyncResult.success(undefined); + return AsyncResult.success(action === "regenerateTitle" ? state.titleOutcome : undefined); }, ]), ), @@ -186,12 +189,13 @@ const mutationCases = [ ["unsnoozeThread", "unsnooze"], ["pinThread", "pin"], ["unpinThread", "unpin"], - ["regenerateThreadTitle", "updateMetadata"], + ["regenerateThreadTitle", "regenerateTitle"], ] as const; beforeEach(() => { state.connectedEnvironmentIds = [primaryEnvironmentId, otherEnvironmentId]; state.failedAction = null; + state.titleOutcome = null; state.archivedRefreshes = []; state.pendingOrder = null; state.dropBusy = false; @@ -214,6 +218,16 @@ afterEach(() => { vi.unstubAllEnvs(); }); +it("reports a failed title generation as unsuccessful and allows another request", async () => { + const actions = useThreadListActions(); + const thread = makeThread(); + state.titleOutcome = { status: "failed", message: "Model unavailable" }; + expect(await actions.regenerateThreadTitle(thread)).toBe(false); + + state.titleOutcome = { status: "renamed" }; + expect(await actions.regenerateThreadTitle(thread)).toBe(true); +}); + describe("thread list operation permissions", () => { it.each(mutationCases)( "%s rejects a retained callback after its environment loses permission", diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts index aaba12dd8f419..3cd180db6273f 100644 --- a/apps/mobile/src/features/home/useThreadListActions.ts +++ b/apps/mobile/src/features/home/useThreadListActions.ts @@ -240,6 +240,9 @@ export function useThreadListActions(): { const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, { reportFailure: false, }); + const regenerateTitle = useAtomCommand(threadEnvironment.regenerateTitle, { + reportFailure: false, + }); const snoozeInFlightThreadKeys = useRef(new Set()); const titleRegenerationInFlightThreadKeys = useRef(new Set()); @@ -529,9 +532,9 @@ export function useThreadListActions(): { titleRegenerationInFlightThreadKeys.current.add(key); selectionHaptic(); const succeeded = await (async () => { - const result = await updateThreadMetadata({ + const result = await regenerateTitle({ environmentId: thread.environmentId, - input: { threadId: thread.id, regenerateTitle: true }, + input: { threadId: thread.id }, }); if (result._tag === "Failure") { const error = Cause.squash(result.cause); @@ -543,6 +546,13 @@ export function useThreadListActions(): { ); return false; } + if (result.value?.status === "failed") { + Dialog.alert( + "Could not regenerate title", + result.value.message ?? "The thread title could not be regenerated.", + ); + return false; + } return true; })(); titleRegenerationInFlightThreadKeys.current.delete(key); diff --git a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx index f4604ca4a2f6d..3f552c1f0c46c 100644 --- a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx @@ -87,9 +87,7 @@ import { useScheduledTaskDestinationLabel, useScheduledTaskEditor } from "./sche import { discardScheduledTaskEditor, markScheduledTaskEditorSaved, - scheduledTaskEditorSessionAtom, } from "./scheduled-task-editor-state"; -import { appAtomRegistry } from "../../state/atom-registry"; import { formatNextScheduledTaskRun, formatScheduledTaskInterval, @@ -519,8 +517,6 @@ function SettingsScheduledTaskEditorScreen({ title }: { readonly title: string } const voiceInput = useVoiceInputController({ ownerKey, label: editor?.draft.title.trim() || title, - subscribeToDraftChanges: (onChange) => - appAtomRegistry.subscribe(scheduledTaskEditorSessionAtom, onChange), selection, readDraftMessage: () => { const current = readEditor(); diff --git a/apps/mobile/src/features/threads/McpAppFullscreenScreen.tsx b/apps/mobile/src/features/threads/McpAppFullscreenScreen.tsx index de3041c06b57e..747b9a9fc1867 100644 --- a/apps/mobile/src/features/threads/McpAppFullscreenScreen.tsx +++ b/apps/mobile/src/features/threads/McpAppFullscreenScreen.tsx @@ -56,6 +56,41 @@ function descendsFrom( /** Resolve apps from stored tool calls so links cannot supply apps the call never produced. */ export function McpAppFullscreenScreen({ route }: McpAppFullscreenScreenProps) { + const navigation = useNavigation(); + const { environmentId, threadId, itemId } = route.params; + if (!environmentId?.trim() || !threadId?.trim() || !itemId?.trim()) { + return ( + + navigation.goBack()} + closeAccessibilityLabel="Exit full screen" + /> + This app cannot be shown. + + ); + } + return ( + + ); +} + +function McpAppFullscreen({ + params, + environmentId, + threadId, + itemId, +}: { + readonly params: McpAppFullscreenScreenProps["route"]["params"]; + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly itemId: TurnItemId; +}) { const navigation = useNavigation(); const insets = useSafeAreaInsets(); // Wait for focus before goBack; an exit under another screen must not pop that screen. @@ -74,10 +109,6 @@ export function McpAppFullscreenScreen({ route }: McpAppFullscreenScreenProps) { }); }; const [size, setSize] = useState({ width: 0, height: 0 }); - const params = route.params; - const environmentId = EnvironmentId.make(params.environmentId); - const threadId = ThreadId.make(params.threadId); - const itemId = TurnItemId.make(params.itemId); const conversationThreadId = useConversationThreadId( environmentId, threadId, diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 9c2eb6d4c38df..3b1b927ef8a9b 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -57,13 +57,11 @@ import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/re import { scopedThreadKey } from "../../lib/scopedEntities"; import { getComposerDraftSnapshot, - composerDraftsAtom, setComposerDraftText, composerContextImportsAtom, countComposerDraftAttachmentsAfterSelection, useComposerDraft, } from "../../state/use-composer-drafts"; -import { appAtomRegistry } from "../../state/atom-registry"; import type { ComposerDocumentAttachment } from "../../lib/composerContext"; import { useProject, useVisibleThreadShells } from "../../state/entities"; import { useMentionableEnvironments } from "../../state/environments"; @@ -579,7 +577,6 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps ownerKey: composerDraftKey, label: props.selectedThread.title || "Untitled thread", readDraftMessage: () => getComposerDraftSnapshot(composerDraftKey).text, - subscribeToDraftChanges: (onChange) => appAtomRegistry.subscribe(composerDraftsAtom, onChange), selection: composerMenu.selection, onChangeDraftMessage: (text) => setComposerDraftText(composerDraftKey, text), onChangeSelection: composerMenu.onSelectionChange, diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index dbbcaa1fd9cff..39cc885e4d2e3 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -3326,7 +3326,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const jumpRunId = jumpReady && !presentedFeed.some((entry) => entry.type === "message" && entry.id === jumpToMessageId) - ? messageFoldRunId(props.feed, jumpToMessageId) + ? messageFoldRunId(props.feed, jumpToMessageId, presentedFeed) : null; if (jumpRunId && !expandedTurnIds.has(jumpRunId)) { setInteractionState((current) => ({ diff --git a/apps/mobile/src/features/threads/ThreadQueueControl.tsx b/apps/mobile/src/features/threads/ThreadQueueControl.tsx index 58129ebc0cece..d3b3ba6006291 100644 --- a/apps/mobile/src/features/threads/ThreadQueueControl.tsx +++ b/apps/mobile/src/features/threads/ThreadQueueControl.tsx @@ -5,6 +5,10 @@ import { queuedRunEditBlockedReason, } from "@t3tools/client-runtime/queued-run-edit"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message"; import type { ChatAttachment, EnvironmentId, RunId, ThreadId } from "@t3tools/contracts"; import { Atom } from "effect/reactivity"; @@ -20,6 +24,7 @@ import { useUniwindTheme } from "../../lib/useUniwindTheme"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { Button } from "../../components/ui/Button"; +import * as Dialog from "../../components/ui/Dialog"; import { SheetHeader } from "../../components/ui/SheetHeader"; import { AppText as Text } from "../../components/ui/AppText"; import { SymbolView } from "../../components/ui/AppSymbol"; @@ -132,6 +137,10 @@ export function ThreadQueueSheet({ route }: StaticScreenProps) { const promote = useAtomCommand(threadEnvironment.promoteQueuedRun, "promote queued message"); const cancel = useAtomCommand(threadEnvironment.cancelQueuedRun, "remove queued message"); const resume = useAtomCommand(threadEnvironment.resumeThreadQueue, "resume queue"); + const resumeHeldQueue = useAtomCommand(threadEnvironment.resumeThreadQueue, { + label: "resume queue", + reportFailure: false, + }); const [resuming, setResuming] = useState(false); const [busyRunId, setBusyRunId] = useState(null); const busyRef = useRef(false); @@ -217,9 +226,20 @@ export function ThreadQueueSheet({ route }: StaticScreenProps) { if (busyRef.current) return; busyRef.current = true; setResuming(true); - await resume({ ...target, input: { threadId: target.threadId } }); + const result = await resumeHeldQueue({ + ...target, + input: { threadId: target.threadId }, + }); busyRef.current = false; setResuming(false); + // A usage limit holds the queue until the composer's Resume thread continues the run. + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + Dialog.alert( + "Could not resume queue", + error instanceof Error ? error.message : "Try again.", + ); + } }} /> diff --git a/apps/mobile/src/features/voice-input/lazyVoiceRecorder.test.ts b/apps/mobile/src/features/voice-input/lazyVoiceRecorder.test.ts index c16519c0ec798..da4ecdb402d1d 100644 --- a/apps/mobile/src/features/voice-input/lazyVoiceRecorder.test.ts +++ b/apps/mobile/src/features/voice-input/lazyVoiceRecorder.test.ts @@ -143,7 +143,6 @@ describe("createLazyVoiceRecorder", () => { ownerKey: "thread", text: "", selection: { start: 0, end: 0 }, - revision: 0, }), commitDraft: () => undefined, onStateChange: () => undefined, diff --git a/apps/mobile/src/features/voice-input/useVoiceInputController.ts b/apps/mobile/src/features/voice-input/useVoiceInputController.ts index e26672b5b4809..e3152f3627fd3 100644 --- a/apps/mobile/src/features/voice-input/useVoiceInputController.ts +++ b/apps/mobile/src/features/voice-input/useVoiceInputController.ts @@ -15,7 +15,6 @@ export function useVoiceInputController(input: { readonly ownerKey: string | null; readonly label: string; readonly readDraftMessage: () => string | null; - readonly subscribeToDraftChanges: (onChange: () => void) => () => void; readonly selection: ComposerEditorSelection; readonly disabled?: boolean; readonly onChangeDraftMessage: (value: string) => void; @@ -58,7 +57,6 @@ export function useVoiceInputController(input: { } }, captured.selection, - captured.subscribeToDraftChanges, ), label: captured.label, }); diff --git a/apps/mobile/src/features/voice-input/voiceInputSession.test.ts b/apps/mobile/src/features/voice-input/voiceInputSession.test.ts index 9d30e376b54e2..a935422c89df8 100644 --- a/apps/mobile/src/features/voice-input/voiceInputSession.test.ts +++ b/apps/mobile/src/features/voice-input/voiceInputSession.test.ts @@ -1,6 +1,5 @@ import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; import type { PreparedVoiceTranscription } from "@t3tools/client-runtime/voice-input"; -import { Atom, AtomRegistry } from "effect/reactivity"; import { resetVoiceInputGlobalsForTests } from "../../../../../packages/client-runtime/src/voice-input/controller"; import { acquireAudioSession, @@ -23,19 +22,9 @@ import { createVoiceInputTarget, VoiceInputSession, type VoiceInputSessionDependencies, - type VoiceInputTarget, type VoiceRecordingSample, } from "./voiceInputSession"; -function createTarget( - ownerKey: string, - readText: () => string | null, - commit: VoiceInputTarget["commitDraft"], - selection: { start: number; end: number }, -) { - return createVoiceInputTarget(ownerKey, readText, commit, selection, () => () => {}); -} - function createSession( overrides?: Partial< Pick< @@ -116,7 +105,7 @@ describe("global voice input", () => { if (outcome === "activation failure") { audio.setActive.mockRejectedValueOnce(new Error("Audio activation failed")); } - await session.start(createTarget("first", () => "", vi.fn(), { start: 0, end: 0 })); + await session.start(createVoiceInputTarget("first", () => "", vi.fn(), { start: 0, end: 0 })); expect(pause).toHaveBeenCalledOnce(); expect(isAudioSessionOwner(playback)).toBe(false); if (outcome === "complete") { @@ -154,9 +143,9 @@ describe("global voice input", () => { async ({ selection, expected, cursor }) => { const { session } = createSession(); const commit = vi.fn(); - await session.start(createTarget("first", () => "hello world", commit, selection)); + await session.start(createVoiceInputTarget("first", () => "hello world", commit, selection)); await session.start( - createTarget("second", () => "other prompt", vi.fn(), { start: 12, end: 12 }), + createVoiceInputTarget("second", () => "other prompt", vi.fn(), { start: 12, end: 12 }), ); await session.controller.stop(); expect(commit).toHaveBeenCalledWith(expected, { @@ -175,7 +164,7 @@ describe("global voice input", () => { let visibleDraft = "first"; const targetKey = visibleDraft; await session.start( - createTarget( + createVoiceInputTarget( targetKey, () => drafts.get(targetKey) ?? null, (text) => drafts.set(targetKey, text), @@ -207,7 +196,7 @@ describe("global voice input", () => { const firstCommit = vi.fn(); const secondCommit = vi.fn(); const starting = session.start( - createTarget("first", () => "first", firstCommit, { start: 5, end: 5 }), + createVoiceInputTarget("first", () => "first", firstCommit, { start: 5, end: 5 }), ); await preparationEntered.promise; let stopping: Promise | null = null; @@ -226,7 +215,7 @@ describe("global voice input", () => { await transcriptionEntered.promise; } await session.start( - createTarget("second", () => "second", secondCommit, { start: 6, end: 6 }), + createVoiceInputTarget("second", () => "second", secondCommit, { start: 6, end: 6 }), ); expect(session.ownerKey).toBe("first"); expect(session.controller.currentState.phase).toBe(phase); @@ -247,7 +236,9 @@ describe("global voice input", () => { const { session } = createSession(); let text: string | null = "first"; const commit = vi.fn(); - await session.start(createTarget("first", () => text, commit, { start: 5, end: 5 })); + await session.start( + createVoiceInputTarget("first", () => text, commit, { start: 5, end: 5 }), + ); text = change === "removed" ? null : "edited prompt"; await session.controller.stop(); expect(commit).not.toHaveBeenCalled(); @@ -255,10 +246,26 @@ describe("global voice input", () => { }, ); + it("retries a failed start against the draft as edited since", async () => { + const { session, prepare } = createSession(); + prepare.mockRejectedValueOnce(new Error("model unavailable")); + let text = "first"; + const commit = vi.fn(); + await session.start(createVoiceInputTarget("first", () => text, commit, { start: 5, end: 5 })); + expect(session.controller.currentState.phase).toBe("error"); + text = "first draft"; + await session.retry(); + await session.controller.stop(); + expect(prepare).toHaveBeenCalledTimes(2); + expect(commit).toHaveBeenCalledWith("first spoken text draft", { start: 17, end: 17 }); + }); + it("finishes the original draft at the recording limit while it is off screen", async () => { const { session, recorder } = createSession(); const commit = vi.fn(); - await session.start(createTarget("first", () => "first", commit, { start: 5, end: 5 })); + await session.start( + createVoiceInputTarget("first", () => "first", commit, { start: 5, end: 5 }), + ); await session.controller.handleRecorderStatus({ isFinished: true, hasError: false, @@ -269,41 +276,14 @@ describe("global voice input", () => { expect(session.controller.currentState.phase).toBe("idle"); }); - it("rejects a transcript when its off-screen draft changes and returns to the original text", async () => { - const registry = AtomRegistry.make(); - const draft = Atom.make("hello world"); - const unsubscribe = vi.fn(); - const { session } = createSession(); - const commit = vi.fn(); - const target = createVoiceInputTarget( - "first", - () => registry.get(draft), - commit, - { start: 6, end: 6 }, - (onChange) => { - const stop = registry.subscribe(draft, onChange); - return () => { - stop(); - unsubscribe(); - }; - }, - ); - await session.start(target); - registry.set(draft, "changed"); - registry.set(draft, "hello world"); - await session.controller.stop(); - expect(commit).not.toHaveBeenCalled(); - expect(session.controller.currentState.error).toContain("draft changed"); - expect(unsubscribe).toHaveBeenCalledTimes(1); - registry.dispose(); - }); - it("stops recording when its queued edit is discarded", async () => { const { session, recorder } = createSession(); const commit = vi.fn(); let draft: string | null = "queued prompt"; const ownerKey = "thread~queued-edit~run"; - await session.start(createTarget(ownerKey, () => draft, commit, { start: 13, end: 13 })); + await session.start( + createVoiceInputTarget(ownerKey, () => draft, commit, { start: 13, end: 13 }), + ); session.cancel(ownerKey); draft = null; await session.controller.stop(); @@ -319,7 +299,9 @@ describe("global voice input", () => { it("keeps another prompt's recording when a queued edit is discarded", async () => { const { session, recorder } = createSession(); const commit = vi.fn(); - await session.start(createTarget("other prompt", () => "hello", commit, { start: 5, end: 5 })); + await session.start( + createVoiceInputTarget("other prompt", () => "hello", commit, { start: 5, end: 5 }), + ); session.cancel("thread~queued-edit~run"); expect(recorder.stop).not.toHaveBeenCalled(); expect(session.controller.currentState.phase).toBe("recording"); @@ -338,12 +320,12 @@ describe("global voice input", () => { const oldCommit = vi.fn(); const nextCommit = vi.fn(); const firstStart = session.start( - createTarget("first", () => "first", oldCommit, { start: 5, end: 5 }), + createVoiceInputTarget("first", () => "first", oldCommit, { start: 5, end: 5 }), ); await preparationEntered.promise; session.cancel("first"); const nextStart = session.start( - createTarget("second", () => "second", nextCommit, { start: 6, end: 6 }), + createVoiceInputTarget("second", () => "second", nextCommit, { start: 6, end: 6 }), ); expect(prepare).toHaveBeenCalledTimes(1); expect(recorder.record).not.toHaveBeenCalled(); @@ -366,7 +348,9 @@ describe("global voice input", () => { const snapshots: number[] = []; session.subscribe(() => snapshots.push(session.getSnapshot().elapsedSeconds)); - await session.start(createTarget("first", () => "first", vi.fn(), { start: 5, end: 5 })); + await session.start( + createVoiceInputTarget("first", () => "first", vi.fn(), { start: 5, end: 5 }), + ); expect(session.getSnapshot().state.phase).toBe("recording"); expect(keepAwake).toHaveBeenCalledTimes(1); // Silence on a silent history publishes nothing. @@ -388,7 +372,9 @@ describe("global voice input", () => { expect(session.getSnapshot().elapsedSeconds).toBe(2); sample = { durationMillis: 0, metering: -100 }; - await session.start(createTarget("first", () => "first", vi.fn(), { start: 5, end: 5 })); + await session.start( + createVoiceInputTarget("first", () => "first", vi.fn(), { start: 5, end: 5 }), + ); expect(session.getSnapshot().elapsedSeconds).toBe(0); expect(publishAudioLevels).toHaveBeenLastCalledWith(expect.not.arrayContaining([1])); expect(keepAwake).toHaveBeenCalledTimes(2); diff --git a/apps/mobile/src/features/voice-input/voiceInputSession.ts b/apps/mobile/src/features/voice-input/voiceInputSession.ts index 5bf9395daf59c..6a5ecd5bde22a 100644 --- a/apps/mobile/src/features/voice-input/voiceInputSession.ts +++ b/apps/mobile/src/features/voice-input/voiceInputSession.ts @@ -19,7 +19,6 @@ export type VoiceInputTarget = { readonly label?: string; readonly readDraft: () => VoiceDraftSnapshot | null; readonly commitDraft: VoiceInputControllerDependencies["commitDraft"]; - readonly subscribe: () => () => void; }; export type VoiceInputSnapshot = { @@ -52,27 +51,14 @@ export function createVoiceInputTarget( readText: () => string | null, commitDraft: VoiceInputTarget["commitDraft"], selection: VoiceDraftSnapshot["selection"], - subscribeToChanges: (onChange: () => void) => () => void, ): VoiceInputTarget { - let revision = 0; return { ownerKey, readDraft: () => { const text = readText(); - if (text === null) return null; - return { ownerKey, text, selection, revision }; + return text === null ? null : { ownerKey, text, selection }; }, commitDraft, - subscribe: () => { - let previousText = readText(); - return subscribeToChanges(() => { - const text = readText(); - if (text !== previousText) { - previousText = text; - revision += 1; - } - }); - }, }; } @@ -84,7 +70,7 @@ export class VoiceInputSession { readonly controller: VoiceInputController; private readonly dependencies: VoiceInputSessionDependencies; private target: VoiceInputTarget | null = null; - private unsubscribe: (() => void) | null = null; + private startText: string | null = null; private snapshot: VoiceInputSnapshot = { state: IDLE_STATE, ownerKey: null, @@ -102,7 +88,11 @@ export class VoiceInputSession { this.controller = new VoiceInputController({ ...dependencies, onStateChange: (state) => this.handleStateChange(state), - readDraft: () => this.target?.readDraft() ?? null, + // The target's selection is fixed at start, so a draft changed since refuses the transcript. + readDraft: () => { + const draft = this.target?.readDraft() ?? null; + return draft?.text === this.startText ? draft : null; + }, commitDraft: (text, selection) => this.target?.commitDraft(text, selection), }); } @@ -141,23 +131,17 @@ export class VoiceInputSession { start(target: VoiceInputTarget): Promise { if (voiceInputBlocksSubmission(this.controller.currentState)) return Promise.resolve(); this.target = target; - this.unsubscribe = target.subscribe(); + this.startText = target.readDraft()?.text ?? null; return this.controller.start(); } dispose(): void { this.controller.dispose(); this.stopRecordingActivity(); - this.unsubscribe?.(); - this.unsubscribe = null; this.listeners.clear(); } private handleStateChange(state: VoiceInputState): void { - if (!voiceInputBlocksSubmission(state)) { - this.unsubscribe?.(); - this.unsubscribe = null; - } const previousPhase = this.snapshot.state.phase; let elapsedSeconds = this.snapshot.elapsedSeconds; if (state.phase !== previousPhase) { diff --git a/apps/mobile/src/lib/enrichedLinkPresentation.ts b/apps/mobile/src/lib/enrichedLinkPresentation.ts index 859c015c0533d..5d2e9431339d1 100644 --- a/apps/mobile/src/lib/enrichedLinkPresentation.ts +++ b/apps/mobile/src/lib/enrichedLinkPresentation.ts @@ -92,7 +92,7 @@ export function enrichedLinkVariantPattern(url: string) { } export const ENRICHED_INLINE_FILE_LINK_REGEX = - /^(?!\S*:\/\/)(?:(?:\.{1,2}[\\/]|~[\\/]|\/(?:Users|home|tmp|var|etc|opt|mnt|Volumes|private|root|usr|bin|sbin|lib|lib64|srv|dev|proc|sys|run|boot|media|workspace|workspaces)\/|[A-Za-z]:[\\/])[^\s`]+|(?:[A-Za-z0-9._-]+[\\/])+[A-Za-z0-9._-]+\.[A-Za-z0-9_-]+(?::\d+(?::\d+|-\d+)?)?|[A-Za-z0-9._-]+\.[A-Za-z0-9_-]+:\d+(?::\d+|-\d+)?)$/; + /^(?!\S*:\/\/)(?:(?:\.{1,2}[\\/]|~[\\/]|\/(?:Users|home|tmp|var|etc|opt|mnt|Volumes|private|root|usr|bin|sbin|lib|lib64|srv|dev|proc|sys|run|boot|media|workspace|workspaces)\/|[A-Za-z]:[\\/])[^\s`]+|(?:[\p{L}\p{M}\p{N}._-]+[\\/])+[\p{L}\p{M}\p{N}._-]+\.[A-Za-z0-9_-]+(?::\d+(?::\d+|-\d+)?)?|[\p{L}\p{M}\p{N}._-]+\.[A-Za-z0-9_-]+:\d+(?::\d+|-\d+)?)$/u; export function enrichedSkillLinkRegex(skills?: ReadonlyArray) { const names = [...new Set(skills?.map((skill) => skill.name) ?? [])].filter(Boolean); diff --git a/apps/mobile/src/lib/markdownDocument.ts b/apps/mobile/src/lib/markdownDocument.ts index dc8d741559aba..dceebd418b1b5 100644 --- a/apps/mobile/src/lib/markdownDocument.ts +++ b/apps/mobile/src/lib/markdownDocument.ts @@ -226,12 +226,13 @@ function htmlTagMarkdown( const alt = (attribute(tag, "alt") ?? "").replace(/[\\[\]&]/g, "\\$&"); return `![${alt}](${markdownDestination(src)})`; } + // A raw newline would end the table row; both parsers decode this reference to one inside the cell. + const cellBreak = " "; // A blank line inside an open link label would end the paragraph before its "]". - const blockBreak = anchors.open === 0 ? "\n\n" : " "; + const blockBreak = anchors.open > 0 ? " " : options.inTableCell ? cellBreak : "\n\n"; if (/^/i.test(tag)) return `**${blockBreak}`; - // A raw newline would end the table row; both parsers decode this reference to one inside the cell. - if (/^ { ]); }); + it.each([ + "one

two

", + "one
two
", + "onetwo", + "

one

two

", + ])("keeps a table row intact when a cell contains block HTML: %s", async (cell) => { + const native = await parseMarkdown( + markdownForNativeRendering( + `| A | B |\n| - | - |\n| ${cell} | x |`, + ENRICHED_INLINE_FILE_LINK_REGEX, + ), + ); + const text = (node: { content?: string; children?: unknown[] }): string => + (node.content ?? "") + + (node.children ?? []).map((child) => text(child as typeof node)).join(""); + expect(native.children).toHaveLength(1); + expect(native.children?.[0]?.children?.[1]?.children?.[0]?.children?.map(text)).toEqual([ + expect.stringMatching(/one\s*two/), + "x", + ]); + }); + it("keeps a table row intact when an anchor href contains a pipe", () => { const document = parseMarkdownDocument( "| Preview | Logs |\n| - | - |\n| Open | done |", diff --git a/apps/mobile/src/lib/markdownInlineFileLinks.test.ts b/apps/mobile/src/lib/markdownInlineFileLinks.test.ts index 5cce10e3c3e33..e2d81cf869561 100644 --- a/apps/mobile/src/lib/markdownInlineFileLinks.test.ts +++ b/apps/mobile/src/lib/markdownInlineFileLinks.test.ts @@ -93,6 +93,9 @@ describe("inline code that names a file", () => { expect(rewrite("See `src/math.ts:2` and `./README.md`.")).toBe( "See [src/math.ts:2]() and [./README.md](<./README.md>).", ); + for (const path of ["src/數學.ts:2", "數學/math.ts:2", "數學.ts:2", "src/數學.ts:2-4"]) { + expect(rewrite(`See \`${path}\`.`), path).toBe(`See [${path}](<${path}>).`); + } }); it("keeps commands, identifiers and URLs as code", () => { diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index d810563f72660..86e7f3f7182ac 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -896,16 +896,20 @@ describe("buildThreadFeed", () => { projected(runless ? { ...item, runId: null } : item, position), ), ); - const foldRunId = messageFoldRunId(feed, "message-middle"); - expect(foldRunId, String(runless)).toBe(runless ? "runless:message-user" : runId); const ids = (expanded: ReadonlySet) => deriveThreadFeedPresentation(feed, null, expanded).map((entry) => entry.id); + const foldRunId = messageFoldRunId( + feed, + "message-middle", + deriveThreadFeedPresentation(feed, null, new Set()), + ); + expect(foldRunId, String(runless)).toBe(runless ? "runless:message-user" : runId); expect(ids(new Set())).not.toContain("message-middle"); expect(ids(new Set([foldRunId!]))).toContain("message-middle"); } - expect(messageFoldRunId(buildThreadFeed([projected(userMessage(), 0)]), "message-user")).toBe( - null, - ); + expect( + messageFoldRunId(buildThreadFeed([projected(userMessage(), 0)]), "message-user", []), + ).toBe(null); }); it("folds progress messages while keeping the final assistant answer visible", () => { @@ -1010,6 +1014,66 @@ describe("buildThreadFeed", () => { ]); }); + it("splits a settled turn's work fold at a steer", () => { + const steer = { + ...userMessage("2026-06-20T00:00:04.000Z"), + id: TurnItemId.make("item-steer"), + messageId: MessageId.make("message-steer"), + inputIntent: "steer" as const, + }; + const after = { ...command("2026-06-20T00:00:06.000Z"), id: TurnItemId.make("item-after") }; + const progress = { + ...assistantMessage("2026-06-20T00:00:07.000Z"), + id: TurnItemId.make("item-progress"), + messageId: MessageId.make("message-progress"), + }; + const feed = buildThreadFeed( + [ + userMessage(), + command(), + steer, + after, + progress, + assistantMessage("2026-06-20T00:00:09.000Z"), + ].map((item, position) => projected(item, position)), + ); + + expect( + deriveThreadFeedPresentation(feed, null, new Set()).map((entry) => + entry.type === "message" ? entry.id : entry.type, + ), + ).toEqual(["message-user", "run-fold", "message-steer", "run-fold", "message-assistant"]); + const foldRunId = messageFoldRunId( + feed, + "message-progress", + deriveThreadFeedPresentation(feed, null, new Set()), + ); + expect( + deriveThreadFeedPresentation(feed, null, new Set([foldRunId!])).map((entry) => + entry.type === "message" ? entry.id : entry.type, + ), + ).toEqual([ + "message-user", + "run-fold", + "message-steer", + "run-fold", + "activity-group", + "message-progress", + "message-assistant", + ]); + + // Hiding tools leaves no output before the steer, so nothing splits there. + const hideAll = (expanded: ReadonlySet) => + deriveThreadFeedPresentation(feed, null, expanded, new Set(), null, false, undefined, { + toolCallVisibility: "hideAll", + revealedMessageId: null, + }); + const hiddenToolsFoldRunId = messageFoldRunId(feed, "message-progress", hideAll(new Set())); + expect(hideAll(new Set([hiddenToolsFoldRunId!])).map((entry) => entry.id)).toContain( + "message-progress", + ); + }); + it("folds subagents while keeping created-thread and fork cards visible", () => { const { providerThreadId: _providerThreadId, ...forkBase } = base( "item-fork", diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 16f16b200c8d1..7591b0060985b 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -1058,25 +1058,51 @@ export function failedFeedRunIds( /** * The key a run fold uses for the message `entryId`: its run, or for an * imported message with no run, the runless key of the user message before - * it. Null for user messages, which never fold. + * it, or the segment after its run's last steer when `presented` shows that + * fold. Null for user messages, which never fold. */ export function messageFoldRunId( feed: ReadonlyArray, entryId: string, + presented: ReadonlyArray<{ readonly type: string; readonly runId?: RunId | null }>, ): RunId | null { let runlessKey: RunId | null = null; + const lastSteerIdByRunId = new Map(); for (const entry of feed) { if (entry.type !== "message") continue; if (entry.message.role === "user") { if (entry.id === entryId) return null; + if (isSteerMessage(entry.message) && entry.message.runId != null) { + lastSteerIdByRunId.set(entry.message.runId, entry.id); + } runlessKey = entry.message.runId == null ? RunId.make(`runless:${entry.id}`) : null; } else if (entry.id === entryId) { - return entry.message.runId ?? runlessKey; + const runId = entry.message.runId ?? runlessKey; + const steerId = runId === null ? undefined : lastSteerIdByRunId.get(runId); + if (runId === null || steerId === undefined) return runId; + // Tool visibility can drop all output before the steer, leaving no split. + const steerKey = steerFoldRunId(runId, steerId); + return presented.some((row) => row.type === "run-fold" && row.runId === steerKey) + ? steerKey + : runId; } } return null; } +function steerFoldRunId(runId: RunId, steerEntryId: string): RunId { + return RunId.make(`${runId}:steer:${steerEntryId}`); +} + +function feedEntryFoldRunId(entry: ThreadFeedEntry, runlessKey: RunId | null): RunId | null { + if (entry.type === "message") { + return entry.message.role === "assistant" ? (entry.message.runId ?? runlessKey) : null; + } + return entry.type === "activity-group" || entry.type === "html-render" || entry.type === "mcp-app" + ? (entry.runId ?? runlessKey) + : null; +} + function answersBeforeSteers(feed: ReadonlyArray): ReadonlySet { const ids = new Set(); let previous: ThreadFeedEntry | undefined; @@ -1121,26 +1147,35 @@ function deriveThreadFeedRunFolds( } const groupsByRunId = new Map< RunId, - { entries: ThreadFeedEntry[]; startBoundary: string | null } + { + entries: ThreadFeedEntry[]; + startBoundary: string | null; + /** Each steer after the run has output starts a segment at this index into `entries`. */ + steerSegments: Array<{ startIndex: number; steer: ThreadFeedEntry }>; + } >(); let runlessKey: RunId | null = null; let responseKey: RunId | null = null; let pendingUserBoundary: string | null = null; for (const [index, entry] of feed.entries()) { if (entry.type === "message" && entry.message.role === "user") { + const steerGroup = + isSteerMessage(entry.message) && entry.message.runId != null + ? groupsByRunId.get(entry.message.runId) + : undefined; + if (steerGroup && steerGroup.entries.length > 0) { + // Back-to-back steers split once, after the last of them. + if (steerGroup.steerSegments.at(-1)?.startIndex === steerGroup.entries.length) { + steerGroup.steerSegments.pop(); + } + steerGroup.steerSegments.push({ startIndex: steerGroup.entries.length, steer: entry }); + } pendingUserBoundary = entry.message.createdAt; runlessKey = entry.message.runId == null ? RunId.make(`runless:${entry.id}`) : null; responseKey = entry.message.runId ?? runlessKey; continue; } - const ownRunId = - entry.type === "message" && entry.message.role === "assistant" - ? (entry.message.runId ?? runlessKey) - : entry.type === "activity-group" || - entry.type === "html-render" || - entry.type === "mcp-app" - ? (entry.runId ?? runlessKey) - : null; + const ownRunId = feedEntryFoldRunId(entry, runlessKey); if (!ownRunId) continue; // Resumed subagents keep their original turn position and fold, leaving later run folds under their own prompts. const runId = @@ -1149,7 +1184,7 @@ function deriveThreadFeedRunFolds( : ownRunId; let group = groupsByRunId.get(runId); if (!group) { - group = { entries: [], startBoundary: pendingUserBoundary }; + group = { entries: [], startBoundary: pendingUserBoundary, steerSegments: [] }; pendingUserBoundary = null; groupsByRunId.set(runId, group); } @@ -1215,15 +1250,15 @@ function deriveThreadFeedRunFolds( .map((entry) => entry.id), ); const firstEntry = group.entries[0]; - const firstHiddenEntry = group.entries.find((entry) => hiddenEntryIds.has(entry.id)); const lastEntry = group.entries.at(-1); - if (!firstHiddenEntry || !firstEntry || !lastEntry) continue; - const hidesNonCompactionWork = group.entries.some( - (entry) => - hiddenEntryIds.has(entry.id) && - !(entry.type === "activity-group" && isContextCompactionActivityGroup(entry)), - ); - if (!hidesNonCompactionWork) continue; + if (!firstEntry || !lastEntry) continue; + const hidesNonCompactionWork = (entries: ReadonlyArray) => + entries.some( + (entry) => + hiddenEntryIds.has(entry.id) && + !(entry.type === "activity-group" && isContextCompactionActivityGroup(entry)), + ); + if (!hidesNonCompactionWork(group.entries)) continue; const terminalEntry = terminalAssistantId ? group.entries.find((entry) => entry.id === terminalAssistantId) : null; @@ -1243,28 +1278,58 @@ function deriveThreadFeedRunFolds( const duration = elapsedMs === null ? null : formatDuration(elapsedMs); const interrupted = latestRunMatches && (latestRun.status === "interrupted" || latestRun.status === "cancelled"); - const deferredWorkItemIds = group.entries.flatMap((entry) => - entry.type === "activity-group" - ? entry.activities.flatMap((activity) => - activity.projectedItem.item.deferredWork - ? [String(activity.projectedItem.sourceItemId)] - : [], - ) - : [], - ); - foldsByAnchorId.set(firstHiddenEntry.id, { - ...(deferredWorkItemIds.length > 0 ? { deferredWorkItemIds } : {}), - runId, - createdAt: firstHiddenEntry.createdAt, - hiddenEntryIds, - label: interrupted - ? duration - ? `You stopped after ${duration}` - : "You stopped this response" - : duration - ? `Worked for ${duration}` - : "Worked", - }); + const label = interrupted + ? duration + ? `You stopped after ${duration}` + : "You stopped this response" + : duration + ? `Worked for ${duration}` + : "Worked"; + // The top row keeps the whole turn's time. Work after a steer folds under + // its own row below that steer, keyed apart so each segment opens alone. + const segments = [ + { + runId, + entries: group.entries.slice(0, group.steerSegments[0]?.startIndex), + label, + }, + ...group.steerSegments.map(({ startIndex, steer }, index) => { + const entries = group.entries.slice(startIndex, group.steerSegments[index + 1]?.startIndex); + const segmentMs = computeElapsedMs( + steer.createdAt, + entries + .map((entry) => (entry.type === "message" ? entry.message.updatedAt : entry.createdAt)) + .reduce(maxIsoTimestamp, null) ?? steer.createdAt, + ); + return { + runId: steerFoldRunId(runId, steer.id), + entries, + label: segmentMs !== null ? `Continued for ${formatDuration(segmentMs)}` : "Continued", + }; + }), + ]; + for (const segment of segments) { + const firstHiddenEntry = segment.entries.find((entry) => hiddenEntryIds.has(entry.id)); + if (!firstHiddenEntry || !hidesNonCompactionWork(segment.entries)) continue; + const deferredWorkItemIds = segment.entries.flatMap((entry) => + entry.type === "activity-group" + ? entry.activities.flatMap((activity) => + activity.projectedItem.item.deferredWork + ? [String(activity.projectedItem.sourceItemId)] + : [], + ) + : [], + ); + foldsByAnchorId.set(firstHiddenEntry.id, { + ...(deferredWorkItemIds.length > 0 ? { deferredWorkItemIds } : {}), + runId: segment.runId, + createdAt: firstHiddenEntry.createdAt, + hiddenEntryIds: new Set( + segment.entries.flatMap((entry) => (hiddenEntryIds.has(entry.id) ? [entry.id] : [])), + ), + label: segment.label, + }); + } } const covered = new Set( [...foldsByAnchorId.values()].flatMap((fold) => [...fold.hiddenEntryIds]), diff --git a/apps/server/scripts/migrate-dev-db.test.ts b/apps/server/scripts/migrate-dev-db.test.ts index 6898eff9ccbf0..91045459d281e 100644 --- a/apps/server/scripts/migrate-dev-db.test.ts +++ b/apps/server/scripts/migrate-dev-db.test.ts @@ -34,10 +34,21 @@ const createFixtureSource = Effect.fn("createMigrateDevDbFixtureSource")(functio const sql = yield* SqlClient.SqlClient; yield* runMigrations({ toMigrationInclusive }); + const scripts = JSON.stringify([ + { id: "lint", name: "Lint", command: "vp lint", icon: "lint", runOnWorktreeCreate: false }, + { + id: "teardown", + name: "Teardown", + command: "./teardown", + icon: "configure", + runOnWorktreeCreate: false, + runOnSettle: true, + }, + ]); yield* sql`INSERT INTO projection_projects (project_id, title, workspace_root, scripts_json, created_at, updated_at, deleted_at) VALUES - ('project-kept', 'Kept', '/tmp/kept', '[]', '2026-08-01', '2026-08-01', NULL), + ('project-kept', 'Kept', '/tmp/kept', ${scripts}, '2026-08-01', '2026-08-01', NULL), ('project-deleted', 'Deleted', '/tmp/deleted', '[]', '2026-08-01', '2026-08-02', '2026-08-02')`; const forkPayload = @@ -162,6 +173,8 @@ it.layer(NodeServices.layer)("migrate-dev-db", (it) => { json_extract(payload_json, '$.pullRequests[0].url') AS url, json_extract(payload_json, '$.pullRequests[0].watch') AS watch FROM orchestration_v2_projection_threads WHERE thread_id = 'stopped-thread'`; + const [project] = yield* sql<{ scripts_json: string }>` + SELECT scripts_json FROM projection_projects WHERE project_id = 'project-kept'`; const [leftovers] = yield* sql<{ auth: number; tasks: number; @@ -176,7 +189,7 @@ it.layer(NodeServices.layer)("migrate-dev-db", (it) => { (SELECT COUNT(*) FROM scheduled_task_webhook_pending) AS webhooks, (SELECT COUNT(*) FROM orchestration_v2_projection_context_transfers) AS transfers, (SELECT COUNT(*) FROM peer_environment_links) AS links`; - return { threads, events, sessions, pullRequest, leftovers }; + return { threads, events, sessions, pullRequest, project, leftovers }; }), ); assert.deepStrictEqual( @@ -196,6 +209,26 @@ it.layer(NodeServices.layer)("migrate-dev-db", (it) => { { url: "https://github.com/owner/repo/pull/7", watch: null }, "copied pull request links keep their history but stop being watched", ); + assert.deepStrictEqual( + JSON.parse(kept.project?.scripts_json ?? "[]"), + [ + { + id: "lint", + name: "Lint", + command: "vp lint", + icon: "lint", + runOnWorktreeCreate: false, + }, + { + id: "teardown", + name: "Teardown", + command: "./teardown", + icon: "configure", + runOnWorktreeCreate: false, + }, + ], + "copied project scripts stay listed but never run on settle in the original checkout", + ); assert.deepStrictEqual(kept.leftovers, { auth: 0, tasks: 0, diff --git a/apps/server/scripts/migrate-dev-db.ts b/apps/server/scripts/migrate-dev-db.ts index afec0c9458b81..211895c9b44fa 100644 --- a/apps/server/scripts/migrate-dev-db.ts +++ b/apps/server/scripts/migrate-dev-db.ts @@ -382,12 +382,20 @@ const pruneSnapshot = Effect.fn("pruneDevDbSnapshot")(function* (input: RunMigra OR (aggregate_kind = 'project' AND stream_id NOT IN (SELECT project_id FROM kept_projects))`; yield* sql`UPDATE orchestration_v2_projection_threads - SET payload_json = json_set(payload_json, '$.pullRequests', ( + SET payload_json = json_set(payload_json, '$.pullRequests', json(( SELECT json_group_array(json_remove(link.value, '$.watch') ORDER BY link.key) - FROM json_each(payload_json, '$.pullRequests') AS link)) + FROM json_each(payload_json, '$.pullRequests') AS link))) WHERE EXISTS ( SELECT 1 FROM json_each(payload_json, '$.pullRequests') AS link WHERE json_extract(link.value, '$.watch') IS NOT NULL)`; + // Copied threads keep their real worktree paths, where a settle script would run. + yield* sql`UPDATE projection_projects + SET scripts_json = ( + SELECT json_group_array(json_remove(script.value, '$.runOnSettle') ORDER BY script.key) + FROM json_each(scripts_json) AS script) + WHERE EXISTS ( + SELECT 1 FROM json_each(scripts_json) AS script + WHERE json_extract(script.value, '$.runOnSettle') IS NOT NULL)`; for (const table of CLEARED_TABLES) { yield* sql`DELETE FROM ${sql(table)}`; } diff --git a/apps/server/src/cli/invocation.test.ts b/apps/server/src/cli/invocation.test.ts index ba3bc840e7448..08e4024d5bfe0 100644 --- a/apps/server/src/cli/invocation.test.ts +++ b/apps/server/src/cli/invocation.test.ts @@ -291,6 +291,43 @@ it.layer(NodeServices.layer)("manual server installation ownership", (it) => { }), ); + it.effect("names the launcher symlink that started a downloaded runtime", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.realPath(yield* fs.makeTempDirectoryScoped()); + // The install script's launcher names ~/.t3, which here links to a home elsewhere. + const executable = path.join(root, "data/t3/runtime/versions/1.0.0/t3"); + const launcher = path.join(root, "bin/t3"); + const copy = path.join(root, "bin/t3-copy"); + yield* fs.makeDirectory(path.dirname(executable), { recursive: true }); + yield* fs.makeDirectory(path.dirname(launcher), { recursive: true }); + yield* fs.writeFileString(executable, "", { mode: 0o755 }); + yield* fs.writeFileString(copy, "", { mode: 0o755 }); + yield* fs.symlink(path.join(root, "data/t3"), path.join(root, ".t3")); + yield* fs.symlink(path.join(root, ".t3/runtime/versions/1.0.0/t3"), launcher); + // Earlier PATH entries hold a directory and a non-executable file named t3. + yield* fs.makeDirectory(path.join(root, "shadow-dir/t3"), { recursive: true }); + yield* fs.makeDirectory(path.join(root, "shadow-file")); + yield* fs.writeFileString(path.join(root, "shadow-file/t3"), ""); + const resolve = (invokedAs: string) => + resolveServerInstallation.pipe( + Effect.provideService(HostProcess.ExecutablePath, executable), + Effect.provideService(HostProcess.IsExecutable, true), + Effect.provideService(HostProcess.InvokedAs, invokedAs), + Effect.provideService(HostProcess.WorkingDirectory, root), + Effect.provideService(HostProcess.Environment, { PATH: "shadow-dir:shadow-file:bin" }), + Effect.provideService(HostProcess.Platform, "linux"), + ); + const baseDir = path.join(root, ".t3"); + + expect(yield* resolve("t3")).toEqual({ kind: "t3-launcher", launcher, baseDir }); + expect(yield* resolve(launcher)).toEqual({ kind: "t3-launcher", launcher, baseDir }); + expect(yield* resolve(executable)).toBeNull(); + expect(yield* resolve(copy)).toBeNull(); + }), + ); + it.effect("leaves local, standalone, missing and unreadable installs unknown", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/cli/invocation.ts b/apps/server/src/cli/invocation.ts index 2a1991fd3070b..459fe6dcfe94d 100644 --- a/apps/server/src/cli/invocation.ts +++ b/apps/server/src/cli/invocation.ts @@ -9,6 +9,9 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import { resolveCommandPath } from "@t3tools/shared/shell"; import packageJson from "../../package.json" with { type: "json" }; +import { resolveLauncherPath } from "../cloud/pinnedRuntime.ts"; + +const PINNED_RUNTIME_ENTRY = /^(.*)\/runtime\/versions\/[^/]+\/t3$/; export type CliRunner = "npx" | "pnpm dlx" | "bunx"; @@ -67,6 +70,21 @@ export const resolveServerInstallation = Effect.gen(function* () { const path = yield* Path.Path; const platform = yield* HostProcess.Platform; const entry = yield* fs.realPath(yield* resolveEntryPath); + const runtime = PINNED_RUNTIME_ENTRY.exec(entry); + if (runtime) { + const launcher = yield* resolveLauncherPath; + if (launcher === undefined) return null; + // Fails for a runtime started directly, as SSH launches do, or through a copy. + const link = yield* fs.readLink(launcher); + // Keep the home as the link spells it; `t3 update` only repoints links into that spelling. + const linked = PINNED_RUNTIME_ENTRY.exec(path.resolve(path.dirname(launcher), link)); + if (!linked || (yield* fs.realPath(linked[1] || "/")) !== (runtime[1] || "/")) return null; + return { + kind: "t3-launcher", + launcher, + baseDir: linked[1] || "/", + } satisfies ServerInstallation; + } const match = /^(.*)\/lib\/node_modules\/t3\/(?:dist\/bin\.mjs|bin\/t3\.mjs)$/.exec(entry); if (!match) { const runner = detectCliRunner(entry); diff --git a/apps/server/src/cli/pair.test.ts b/apps/server/src/cli/pair.test.ts index e626461914a06..01177bd6743cd 100644 --- a/apps/server/src/cli/pair.test.ts +++ b/apps/server/src/cli/pair.test.ts @@ -35,7 +35,12 @@ import { type PersistedServerRuntimeState, } from "../serverRuntimeState.ts"; import { resolveHostCliCommand } from "./invocation.ts"; -import { DevServerNotProxiableError, resolveTailscaleLocalTarget } from "./pair.ts"; +import { + DevServerNotProxiableError, + resolveTailscaleLocalTarget, + ServePortOccupiedError, + TailscaleServeTargetRefusedError, +} from "./pair.ts"; import packageJson from "../../package.json" with { type: "json" }; import { buildPairingAppLink } from "@t3tools/shared/remote"; @@ -136,7 +141,7 @@ describe("t3 pair", () => { Effect.gen(function* () { if (!ChildProcess.isStandardCommand(command)) return yield* Effect.die("Unexpected pipeline"); - if (command.args[0] === "serve") { + if (command.args[0] === "serve" && command.args[1] === "--bg") { const target = String(command.args.at(-1)); const descriptor = yield* Effect.promise(async () => (await fetch(new URL("/.well-known/t3/environment", target))).json(), @@ -194,6 +199,87 @@ describe("t3 pair", () => { ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); + // The MagicDNS probe fails whenever the host cannot reach its own *.ts.net name, + // so it cannot be what decides that the port is free. + it.effect( + "leaves another app's Serve route alone when the host cannot reach its MagicDNS URL", + () => + withDescriptorServer((origin) => + // Another live app on loopback; a dead port's route may be taken back. + withDescriptorServer((otherAppOrigin) => + Effect.gen(function* () { + const fetch = yield* FetchHttpClient.Fetch; + const tailscaleCalls: Array> = []; + const spawner = ChildProcessSpawner.make((command) => { + const { args } = command as unknown as { readonly args: ReadonlyArray }; + tailscaleCalls.push(args); + const stdout = + args[0] === "status" + ? '{"BackendState":"Running","Self":{"DNSName":"host-a.tail.ts.net.","TailscaleIPs":["100.64.0.1"],"CapMap":{"https":null}}}' + : args[0] === "serve" && args[1] === "status" + ? JSON.stringify({ + TCP: { "443": { HTTPS: true } }, + Web: { + "host-a.tail.ts.net:443": { + Handlers: { "/": { Proxy: otherAppOrigin } }, + }, + }, + }) + : ""; + return Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + // A recorded takeover fails fast instead of waiting out the HTTPS retries. + exitCode: Effect.succeed( + ChildProcessSpawner.ExitCode( + args[0] === "serve" && args[1] !== "status" ? 1 : 0, + ), + ), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.make(new TextEncoder().encode(stdout)), + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }), + ); + }); + + const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-ts-held-")); + yield* persistServerRuntimeState({ + path: NodePath.join(baseDir, "userdata", "server-runtime.json"), + state: yield* makePersistedServerRuntimeState({ + config: { host: "127.0.0.1", devUrl: undefined }, + port: Number(new URL(origin).port), + }), + }); + + const exit = yield* runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provideService(HostProcess.Platform, "linux"), + Effect.provideService(FetchHttpClient.Fetch, async (input, init) => { + if (String(input).startsWith(origin)) return fetch(input, init); + throw new TypeError("getaddrinfo ENOTFOUND host-a.tail.ts.net"); + }), + Effect.exit, + ); + + assert.deepEqual( + tailscaleCalls.filter((args) => args[0] === "serve" && args[1] !== "status"), + [], + ); + assert.isTrue(Exit.isFailure(exit)); + if (Exit.isFailure(exit)) { + assert.instanceOf(Cause.squash(exit.cause), ServePortOccupiedError); + } + }), + ), + ).pipe(Effect.provide(layerCliRuntime)), + ); + it.effect("mints a token and prints a QR pairing URL for a live server", () => withDescriptorServer((origin) => Effect.gen(function* () { @@ -468,6 +554,72 @@ describe("t3 pair", () => { }), ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); + + // regression: #35517 - the macOS Tailscale apps refuse Serve targets other than + // localhost, 127.0.0.1 and ::1, so a specific bind needs an explanation. + it.effect("names the bind address when Tailscale refuses it as a Serve target", () => + Effect.gen(function* () { + const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-pair-remote-")); + yield* persistServerRuntimeState({ + path: NodePath.join(baseDir, "userdata", "server-runtime.json"), + state: yield* makePersistedServerRuntimeState({ + config: { host: "127.0.0.2", devUrl: undefined }, + port: 3773, + }), + }); + const spawner = ChildProcessSpawner.make((command) => { + const { args } = command as unknown as { readonly args: ReadonlyArray }; + const serve = args[0] === "serve" && args[1] !== "status"; + return Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(serve ? 1 : 0)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.make( + new TextEncoder().encode( + serve + ? "" + : args[0] === "status" + ? '{"Self":{"DNSName":"pair-test.tail.ts.net."}}' + : "{}", + ), + ), + stderr: Stream.make( + new TextEncoder().encode( + serve + ? "Warning: the MacOS extension doesn't support connecting to remote destinations from non-default route\n" + : "", + ), + ), + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }), + ); + }); + + const error = yield* provideCliTestLayers( + runCli(["pair", "--base-dir", baseDir, "--tailscale"]).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(FetchHttpClient.Fetch, async (input) => { + if (String(input) === "http://127.0.0.2:3773/.well-known/t3/environment") { + return Response.json(testDescriptor); + } + assert.equal(String(input), "https://pair-test.tail.ts.net/.well-known/t3/environment"); + return new Response(null, { status: 503 }); + }), + Effect.flip, + ), + ); + + assert.instanceOf(error, TailscaleServeTargetRefusedError); + assert.include(String(error), "127.0.0.2"); + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); }); describe("auth scope options", () => { diff --git a/apps/server/src/cli/pair.ts b/apps/server/src/cli/pair.ts index e1af3be829ab9..71f380eb718bf 100644 --- a/apps/server/src/cli/pair.ts +++ b/apps/server/src/cli/pair.ts @@ -15,6 +15,7 @@ import { buildTailscaleHttpsBaseUrl, DEFAULT_TAILSCALE_SERVE_PORT, ensureTailscaleServe, + readTailscaleServeRootHolder, readTailscaleStatus, } from "@t3tools/tailscale"; import * as Config from "effect/Config"; @@ -138,6 +139,15 @@ export class TailscaleServeFailedError extends Schema.TaggedError()( + "TailscaleServeTargetRefusedError", + { localHost: Schema.String }, +) { + override get message(): string { + return `This Tailscale install can only proxy to localhost, and the server listens on ${this.localHost}. Restart it with \`--host 127.0.0.1\` or \`--host 0.0.0.0\`, then run this command again.`; + } +} + export class ServePortOccupiedError extends Schema.TaggedError()( "ServePortOccupiedError", { servePort: Schema.Number }, @@ -405,13 +415,26 @@ const resolveTailscalePairingBase = Effect.fn("pair.resolveTailscalePairingBase" if (isDevServerNotProxiableError(localTarget)) { return yield* localTarget; } + // The probe above fails whenever this host cannot reach its own MagicDNS name, so the Serve + // config, not the probe, decides whether the port is free. + const holder = yield* readTailscaleServeRootHolder(input.servePort, { + host: (localTarget.localHost ?? "127.0.0.1").replace(/^\[|\]$/gu, ""), + port: localTarget.localPort, + }).pipe(Effect.mapError((cause) => new TailscaleUnavailableError({ cause }))); + if (holder === "other") { + return yield* new ServePortOccupiedError({ servePort: input.servePort }); + } yield* ensureTailscaleServe({ localPort: localTarget.localPort, servePort: input.servePort, ...(localTarget.localHost !== undefined ? { localHost: localTarget.localHost } : {}), }).pipe( - Effect.mapError( - (cause) => new TailscaleServeFailedError({ servePort: input.servePort, cause }), + Effect.mapError((cause) => + cause._tag === "TailscaleCommandExitError" && + cause.stderrDiagnostic === "unsupported-target" && + localTarget.localHost !== undefined + ? new TailscaleServeTargetRefusedError({ localHost: localTarget.localHost }) + : new TailscaleServeFailedError({ servePort: input.servePort, cause }), ), ); notes.push( diff --git a/apps/server/src/cli/uninstall.ts b/apps/server/src/cli/uninstall.ts index 5cf6f0c5e64cc..5d0361118e10a 100644 --- a/apps/server/src/cli/uninstall.ts +++ b/apps/server/src/cli/uninstall.ts @@ -16,10 +16,11 @@ import { generatedWindowsShimTarget, isVersionExecutable, pinnedRuntimeVersionsDir, + resolveLauncherPath, } from "../cloud/pinnedRuntime.ts"; import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; import * as CliService from "./service.ts"; -import { findWindowsShim, resolveLauncherPath } from "./update.ts"; +import { findWindowsShim } from "./update.ts"; export class CliUninstallError extends Schema.TaggedError()( "CliUninstallError", diff --git a/apps/server/src/cli/update.test.ts b/apps/server/src/cli/update.test.ts index 98ec13d32808e..557dddef554a9 100644 --- a/apps/server/src/cli/update.test.ts +++ b/apps/server/src/cli/update.test.ts @@ -17,12 +17,15 @@ import { afterEach, vi } from "vite-plus/test"; import packageJson from "../../package.json" with { type: "json" }; import * as BootService from "../cloud/bootService.ts"; -import { pinnedRuntimePaths, prunePinnedRuntimes } from "../cloud/pinnedRuntime.ts"; +import { + pinnedRuntimePaths, + prunePinnedRuntimes, + resolveLauncherPath, +} from "../cloud/pinnedRuntime.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; import * as ProcessRunner from "../processRunner.ts"; import { repointLauncher, - resolveLauncherPath, resolveMirrorVersion, resolveNewestVersion, runUpdate, @@ -411,7 +414,7 @@ it.layer(NodeServices.layer)("t3 update launcher", (it) => { const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" }); const launcher = path.join(root, "bin/t3"); yield* fs.makeDirectory(path.dirname(launcher), { recursive: true }); - yield* fs.writeFileString(launcher, ""); + yield* fs.writeFileString(launcher, "", { mode: 0o755 }); const bare = yield* resolveLauncherPath.pipe( Effect.provideService(HostProcess.InvokedAs, "t3"), diff --git a/apps/server/src/cli/update.ts b/apps/server/src/cli/update.ts index 53ff536e6d112..9a4fbc67b4ef0 100644 --- a/apps/server/src/cli/update.ts +++ b/apps/server/src/cli/update.ts @@ -32,6 +32,7 @@ import { pinnedRuntimeVersionsDir, prunePinnedRuntimes, recordPinnedRuntimeLauncher, + resolveLauncherPath, windowsShimTarget, } from "../cloud/pinnedRuntime.ts"; import { compareExactServiceVersions, isExactServiceVersion } from "../cloud/serviceProtocol.ts"; @@ -194,28 +195,6 @@ export const repointLauncher = Effect.fn("cli.update.repoint_launcher")(function return Option.some(input.launchedAs); }); -/** Node preserves argv0's spelling; resolve bare names on PATH to find the launcher symlink. */ -export const resolveLauncherPath = Effect.gen(function* () { - const path = yield* Path.Path; - const fs = yield* FileSystem.FileSystem; - const invokedAs = yield* HostProcess.InvokedAs; - const cwd = yield* HostProcess.WorkingDirectory; - const environment = yield* HostProcess.Environment; - const platform = yield* HostProcess.Platform; - if (invokedAs.includes("/") || invokedAs.includes("\\")) { - return path.resolve(cwd, invokedAs); - } - const delimiter = platform === "win32" ? ";" : ":"; - for (const directory of (environment["PATH"] ?? "").split(delimiter)) { - if (directory.length === 0) continue; - const candidate = path.join(directory, invokedAs); - if (yield* fs.exists(candidate).pipe(Effect.orElseSucceed(() => false))) { - return candidate; - } - } - return undefined; -}); - /** Windows executables see their own path, so find the installer shim by matching t3.cmd targets on PATH. */ export const findWindowsShim = Effect.fn("cli.update.find_windows_shim")(function* ( executablePath: string, diff --git a/apps/server/src/cloud/pinnedRuntime.test.ts b/apps/server/src/cloud/pinnedRuntime.test.ts index 68870bd969436..0c016a504c9b4 100644 --- a/apps/server/src/cloud/pinnedRuntime.test.ts +++ b/apps/server/src/cloud/pinnedRuntime.test.ts @@ -7,9 +7,10 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Fiber from "effect/Fiber"; import * as Path from "effect/Path"; +import * as Stream from "effect/Stream"; import * as NodePath from "node:path"; import * as TestClock from "effect/testing/TestClock"; -import { HttpClient, HttpClientResponse } from "effect/http"; +import { HttpClient, HttpClientError, HttpClientResponse } from "effect/http"; import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; @@ -189,7 +190,127 @@ it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => { validate: () => Effect.die("must not validate a missing archive"), }).pipe(Effect.flip); assert.isTrue(isUnpublishedRelease(yield* failsWith(404))); - assert.isFalse(isUnpublishedRelease(yield* failsWith(500))); + assert.isFalse(isUnpublishedRelease(yield* failsWith(403))); + }), + ); + + it.effect("retries a release download that GitHub answers with a gateway timeout", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-retry-" }); + const checksums = yield* validChecksums; + const requests: string[] = []; + const gatewayTimeoutServed = yield* Deferred.make(); + const install = yield* ensurePinnedRuntimeInstalled({ + baseDir, + version, + fs, + path, + platform: "linux", + arch: "x64", + httpClient: HttpClient.make((request) => { + requests.push(request.url); + const isChecksums = request.url.endsWith("/SHA256SUMS"); + if (requests.length === 1) { + Deferred.doneUnsafe(gatewayTimeoutServed, Effect.void); + return Effect.succeed( + HttpClientResponse.fromWeb(request, new Response("", { status: 504 })), + ); + } + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response(isChecksums ? checksums : archiveBytes), + ), + ); + }), + runner: extractingRunner(fs, path), + validate: () => Effect.void, + }).pipe(Effect.forkScoped); + yield* Deferred.await(gatewayTimeoutServed); + yield* TestClock.adjust(Duration.seconds(2)); + const paths = yield* Fiber.join(install); + assert.equal(yield* fs.readFileString(paths.sentinelPath), `${version}\n`); + assert.equal(requests.filter((url) => url.endsWith("/SHA256SUMS")).length, 2); + }), + ); + + it.effect("retries a release archive whose body fails after the host answered", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-retry-body-" }); + const checksums = yield* validChecksums; + let archiveRequests = 0; + const archiveRequested = yield* Deferred.make(); + const install = yield* ensurePinnedRuntimeInstalled({ + baseDir, + version, + fs, + path, + platform: "linux", + arch: "x64", + httpClient: HttpClient.make((request) => { + const isChecksums = request.url.endsWith("/SHA256SUMS"); + const response = HttpClientResponse.fromWeb( + request, + new Response(isChecksums ? checksums : archiveBytes), + ); + if (isChecksums || ++archiveRequests > 1) return Effect.succeed(response); + const failingBody = Stream.concat( + Stream.make(archiveBytes.slice(0, 4)), + Stream.fail( + new HttpClientError.HttpClientError({ + reason: new HttpClientError.DecodeError({ request, response }), + }), + ), + ); + Deferred.doneUnsafe(archiveRequested, Effect.void); + // TestClock follows the work a woken sleep starts, so one adjust reaches the retry wait. + return Effect.sleep("1 second").pipe( + Effect.as( + Object.create(response, { stream: { value: failingBody } }), + ), + ); + }), + runner: extractingRunner(fs, path), + validate: () => Effect.void, + }).pipe(Effect.forkScoped); + yield* Deferred.await(archiveRequested); + yield* TestClock.adjust(Duration.seconds(3)); + const paths = yield* Fiber.join(install); + assert.equal(yield* fs.readFileString(paths.sentinelPath), `${version}\n`); + assert.equal(archiveRequests, 2); + }), + ); + + it.effect("fails at once when the release host cannot be reached", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-offline-" }); + let requests = 0; + const error = yield* ensurePinnedRuntimeInstalled({ + baseDir, + version, + fs, + path, + platform: "linux", + arch: "x64", + httpClient: HttpClient.make((request) => { + requests += 1; + return Effect.fail( + new HttpClientError.HttpClientError({ + reason: new HttpClientError.TransportError({ request }), + }), + ); + }), + runner: extractingRunner(fs, path), + validate: () => Effect.die("must not validate without a download"), + }).pipe(Effect.flip); + assert.instanceOf(error, PinnedRuntimeInstallError); + assert.equal(requests, 1); }), ); diff --git a/apps/server/src/cloud/pinnedRuntime.ts b/apps/server/src/cloud/pinnedRuntime.ts index 77bcb39f09dcf..b698be2727752 100644 --- a/apps/server/src/cloud/pinnedRuntime.ts +++ b/apps/server/src/cloud/pinnedRuntime.ts @@ -7,6 +7,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as Option from "effect/Option"; +import * as Schedule from "effect/Schedule"; import * as Stream from "effect/Stream"; import * as Semaphore from "effect/Semaphore"; import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http"; @@ -119,6 +120,20 @@ interface PinnedRuntimeInstallInput { readonly onProgress?: (progress: PinnedRuntimeProgress) => void; } +// GitHub release downloads intermittently answer 5xx during incidents; a retry usually lands. +const DOWNLOAD_RETRY = { times: 3, schedule: Schedule.exponential("2 seconds") } as const; + +const isTransientDownloadFailure = ( + error: HttpClientError.HttpClientError | Cause.TimeoutError, +): boolean => { + // No answer or a stall means the host cannot reach the release source; retrying only delays that. + if (error._tag === "TimeoutError") return false; + // Body bytes are read raw, so a DecodeError is a body that failed after the host answered. + if (error.reason._tag === "DecodeError") return true; + const status = error.response?.status; + return status !== undefined && (status >= 500 || status === 429 || status === 408); +}; + const fetchReleaseAsset = Effect.fn("cloud.pinned_runtime.fetch_release_asset")(function* ( httpClient: HttpClient.HttpClient, url: string, @@ -161,6 +176,7 @@ const fetchReleaseAsset = Effect.fn("cloud.pinned_runtime.fetch_release_asset")( return bytes; }), ), + Effect.retry({ ...DOWNLOAD_RETRY, while: isTransientDownloadFailure }), Effect.mapError( (cause) => new PinnedRuntimeInstallError({ @@ -431,6 +447,34 @@ export function launcherOwnsVersionsDir( return relative.length > 0 && !relative.startsWith("..") && !path.isAbsolute(relative); } +/** Node preserves argv0's spelling; resolve bare names on PATH to find the launcher symlink. */ +export const resolveLauncherPath = Effect.gen(function* () { + const path = yield* Path.Path; + const fs = yield* FileSystem.FileSystem; + const invokedAs = yield* HostProcess.InvokedAs; + const cwd = yield* HostProcess.WorkingDirectory; + const environment = yield* HostProcess.Environment; + const platform = yield* HostProcess.Platform; + if (invokedAs.includes("/") || invokedAs.includes("\\")) { + return path.resolve(cwd, invokedAs); + } + const delimiter = platform === "win32" ? ";" : ":"; + for (const directory of (environment["PATH"] ?? "").split(delimiter)) { + if (directory.length === 0) continue; + const candidate = path.resolve(cwd, directory, invokedAs); + const info = yield* fs.stat(candidate).pipe(Effect.option); + // Like the shell, pass over directories and non-executable files named the same. + if ( + Option.isSome(info) && + info.value.type === "File" && + (platform === "win32" || (info.value.mode & 0o111) !== 0) + ) { + return candidate; + } + } + return undefined; +}); + /** * `t3 update` repoints the launcher it was started through, which may be on neither PATH nor the * default bin dir. Unrecorded, the next prune would remove the runtime it now points at. diff --git a/apps/server/src/cloud/selfUpdate.test.ts b/apps/server/src/cloud/selfUpdate.test.ts index 184bd1deb485c..4cae117b2bcc6 100644 --- a/apps/server/src/cloud/selfUpdate.test.ts +++ b/apps/server/src/cloud/selfUpdate.test.ts @@ -184,21 +184,29 @@ it.layer(NodeServices.layer)("server self update", (it) => { ])("reports an HTTP $status downloading $asset and allows retry", ({ asset, status }) => Effect.gen(function* () { let failDownload = true; + const downloadFailed = yield* Deferred.make(); const { selfUpdate, order, baseDir } = yield* makeHarness({ httpClient: releaseHttpClient([], []).pipe( - HttpClient.transform((response, request) => - failDownload && request.url.endsWith("/SHA256SUMS") === (asset === "checksums") - ? Effect.succeed( - HttpClientResponse.fromWeb( - HttpClientRequest.get("https://user:password@cdn.example/private?token=secret"), - new Response("private response body", { status }), - ), - ) - : response, - ), + HttpClient.transform((response, request) => { + if (!failDownload || request.url.endsWith("/SHA256SUMS") !== (asset === "checksums")) + return response; + Deferred.doneUnsafe(downloadFailed, Effect.void); + return Effect.succeed( + HttpClientResponse.fromWeb( + HttpClientRequest.get("https://user:password@cdn.example/private?token=secret"), + new Response("private response body", { status }), + ), + ); + }), ), }); - const error = yield* selfUpdate.update({ targetVersion: "1.1.0" }).pipe(Effect.flip); + const failing = yield* selfUpdate + .update({ targetVersion: "1.1.0" }) + .pipe(Effect.flip, Effect.forkScoped); + yield* Deferred.await(downloadFailed); + // A 5xx is retried after 2, 4, then 8 seconds before the update gives up. + yield* TestClock.adjust("14 seconds"); + const error = yield* Fiber.join(failing); expect(error.reason).toBe( `Could not prepare t3@1.1.0 while downloading the t3 release ${asset} (HTTP ${status} from cdn.example).`, ); diff --git a/apps/server/src/environment/DirectEndpoints.test.ts b/apps/server/src/environment/DirectEndpoints.test.ts index 2b022cd069d27..2580aa7f67809 100644 --- a/apps/server/src/environment/DirectEndpoints.test.ts +++ b/apps/server/src/environment/DirectEndpoints.test.ts @@ -1,4 +1,5 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; +import { EnvironmentId } from "@t3tools/contracts"; import { it as effectIt } from "@effect/vitest"; import type * as NodeOS from "node:os"; import * as Effect from "effect/Effect"; @@ -16,6 +17,7 @@ import { describe, expect, it } from "vite-plus/test"; import * as ServerConfig from "../config.ts"; import * as DirectEndpoints from "./DirectEndpoints.ts"; +import * as ServerEnvironment from "./ServerEnvironment.ts"; import { resolveBoundEndpoints } from "./DirectEndpoints.ts"; const INTERFACES: ReturnType = { @@ -284,6 +286,12 @@ const layerServeConfig = (host = "127.0.0.1") => ).pipe( Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-direct-" })), Layer.provide(NodeServices.layer), + Layer.merge( + Layer.succeed(ServerEnvironment.ServerEnvironment, { + getEnvironmentId: Effect.succeed(EnvironmentId.make("serve-test")), + getDescriptor: Effect.die("unused"), + }), + ), ); const resolveWithServe = (probeStatus: number) => diff --git a/apps/server/src/environment/DirectEndpoints.ts b/apps/server/src/environment/DirectEndpoints.ts index 5b9ecc98299c7..1f7d9f705620c 100644 --- a/apps/server/src/environment/DirectEndpoints.ts +++ b/apps/server/src/environment/DirectEndpoints.ts @@ -23,6 +23,7 @@ import { } from "@t3tools/shared/hostClassification"; import * as ServerConfig from "../config.ts"; +import * as ServerEnvironment from "./ServerEnvironment.ts"; import { isLoopbackHost, isPrivateNetworkAddress, VIRTUAL_INTERFACE } from "../startupAccess.ts"; type NetworkInterfacesMap = ReturnType; @@ -120,6 +121,7 @@ export const make = Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const httpClient = yield* HttpClient.HttpClient; const platform = yield* HostProcess.Platform; + const environmentId = yield* (yield* ServerEnvironment.ServerEnvironment).getEnvironmentId; // Only the service default listens on every interface without being asked, // so only it checks once whether it runs in a cloud. The check starts now so // the first client does not wait for its timeout. @@ -155,7 +157,7 @@ export const make = Effect.gen(function* () { magicDnsName, servePort: config.tailscaleServePort, }); - return probeTailscaleHttpsEndpoint({ baseUrl: httpBaseUrl }).pipe( + return probeTailscaleHttpsEndpoint({ baseUrl: httpBaseUrl, environmentId }).pipe( Effect.map((reachable) => (reachable ? httpBaseUrl : null)), ); }), diff --git a/apps/server/src/environment/RemoteOpenTargets.test.ts b/apps/server/src/environment/RemoteOpenTargets.test.ts index 562321055f862..0d0da302efa5c 100644 --- a/apps/server/src/environment/RemoteOpenTargets.test.ts +++ b/apps/server/src/environment/RemoteOpenTargets.test.ts @@ -162,6 +162,32 @@ describe("RemoteOpenTargets", () => { }), ); + it.effect("drops the tailnet name after `tailscale down` while sshd listens", () => + Effect.gen(function* () { + const targets = yield* resolveTargets({ + sshd: { ipv4: true, ipv6: false }, + tailscale: { + // After `tailscale down`, status still exits 0 and keeps Self from the last netmap. + status: { + exitCode: 0, + stdout: JSON.stringify({ + BackendState: "Stopped", + Self: { + DNSName: "bb-1.tail1234.ts.net.", + TailscaleIPs: ["100.64.1.2"], + Online: false, + }, + }), + }, + prefs: prefsJson({ RunSSH: false, WantRunning: false }), + }, + hostname: "bb-1", + username: "t3-user", + }); + expect(targets).toEqual([{ kind: "mdns", host: "bb-1.local", username: "t3-user" }]); + }), + ); + it.effect("accepts an sshd bound to IPv6 loopback only", () => Effect.gen(function* () { const targets = yield* resolveTargets({ diff --git a/apps/server/src/environment/RemoteOpenTargets.ts b/apps/server/src/environment/RemoteOpenTargets.ts index d6837560790fd..beb216339f06a 100644 --- a/apps/server/src/environment/RemoteOpenTargets.ts +++ b/apps/server/src/environment/RemoteOpenTargets.ts @@ -37,7 +37,8 @@ export const make = Effect.gen(function* () { Effect.orElseSucceed(() => null), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), ); - const magicDnsName = tailscaleStatus?.magicDnsName ?? null; + const magicDnsName = + tailscaleStatus?.running === false ? null : (tailscaleStatus?.magicDnsName ?? null); const targets: Array = []; diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 1f56d49c88b04..06c9b0cb90551 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -237,6 +237,7 @@ export const make = Effect.gen(function* () { storageCleanupRun: true, databaseStorage: true, otlpEndpointCheck: true, + secretSourceCheck: true, projectWorktreeCleanup: true, settledWorktreeCleanup: true, worktreesDirectory: true, diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index d1904945dadc2..73b7173fa0018 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -94,8 +94,9 @@ interface FakeProviderScenario { /** Check out the pull request head from its pull ref: fast-forward only unless forced. */ syncCheckoutWithPullHead?: boolean; /** - * The host's `headBranchProbe`. By default the fake probes only bare branch names, a hundred - * at a time, so tests see GitManager defer to the hook; null leaves the probe to GitManager. + * The host's `headBranchProbe`. By default the fake probes bare branch names, a hundred at a + * time, or only the owner-qualified default branch, as GitHub does, so tests see GitManager + * defer to the hook; null leaves the probe to GitManager. */ headBranchProbe?: SourceControlProvider["Service"]["headBranchProbe"] | null; } @@ -438,8 +439,10 @@ function createFakeSourceControlProvider(scenario: FakeProviderScenario = {}): { : { headBranchProbe: scenario.headBranchProbe ?? - (({ headSelectors }: { readonly headSelectors: ReadonlyArray }) => ({ - headSelectors: headSelectors.filter((selector) => !selector.includes(":")), + (({ headSelectors, defaultBranchHeadSelector }) => ({ + headSelectors: defaultBranchHeadSelector + ? [defaultBranchHeadSelector] + : headSelectors.filter((selector) => !selector.includes(":")), limit: 100, })), }; @@ -2388,7 +2391,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { const { manager, providerCalls } = yield* makeManager({ providerScenario: { prListByHeadSelector: { - main: [ + "contributor:main": [ { number: 777, title: "Fork PR from main", @@ -2419,7 +2422,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }); expect(providerCalls).toContainEqual({ operation: "listChangeRequests", - headSelector: "main", + headSelector: "contributor:main", state: "all", limit: 100, }); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index d10b09b1be961..05da4404dc85e 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -575,9 +575,10 @@ function headBranchProbe( provider: SourceControlProvider.SourceControlProvider["Service"], headSelectors: ReadonlyArray, state: "open" | "all", + defaultBranchHeadSelector?: string, ) { return ( - provider.headBranchProbe?.({ headSelectors, state }) ?? { + provider.headBranchProbe?.({ headSelectors, state, defaultBranchHeadSelector }) ?? { headSelectors, limit: state === "open" ? 1 : 20, } @@ -1266,7 +1267,7 @@ export const make = Effect.gen(function* () { ) { return { latest: null, headContext }; } - const latest = yield* findLatestPrForHeadContext(cwd, headContext); + const latest = yield* findLatestPrForHeadContext(cwd, headContext, details.defaultBranch); if (latest !== null) yield* noteLookupState(latest); return { latest, headContext }; }); @@ -1926,11 +1927,19 @@ export const make = Effect.gen(function* () { const findLatestPrForHeadContext = Effect.fn("findLatestPrForHeadContext")(function* ( cwd: string, headContext: BranchHeadContext, + defaultBranch: string | null, ) { const parsedByNumber = new Map(); const provider = yield* sourceControlProvider(cwd); - const probe = headBranchProbe(provider, headContext.headSelectors, "all"); + const probe = headBranchProbe( + provider, + headContext.headSelectors, + "all", + headContext.headBranch === defaultBranch && headContext.headRepositoryOwnerLogin + ? `${headContext.headRepositoryOwnerLogin}:${defaultBranch}` + : undefined, + ); for (const headSelector of probe.headSelectors) { const pullRequests = yield* provider.listChangeRequests({ cwd, diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index 8f0966f46834b..db7798d994fcd 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -994,6 +994,123 @@ it.effect("terminates HTTP MCP sessions with DELETE", () => ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); +it.effect("answers 2026-07-28 discovery and keeps 2025-06-18 as the initialize fallback", () => + Effect.scoped( + Effect.gen(function* () { + const token = "providerTokenWithoutDots"; + const scope: McpInvocationContext.McpInvocationScope = { + environmentId, + requestNamespace: "provider-session", + thread: { + threadId: ThreadId.make("thread-provider"), + providerSessionId: "provider-session", + providerInstanceId: ProviderInstanceId.make("codex"), + }, + client: undefined, + capabilities: new Set(["orchestration"]), + issuedAt: 1, + }; + const ProbeToolkit = Toolkit.make( + Tool.make("probe", { + description: "Reports success.", + success: Schema.Struct({ ok: Schema.Boolean }), + }), + ); + const layerServer = McpHttpServer.layerMcpTransport( + McpHttpServer.toolkitRegistration( + ProbeToolkit, + McpToolAccess.toLayer(ProbeToolkit, { + probe: McpToolAccess.reads(() => Effect.succeed({ ok: true })), + }), + ), + ).pipe( + Layer.provide(ServerSettings.layerTest()), + Layer.provide( + Layer.mock(McpSessionRegistry.McpSessionRegistry)({ + resolve: (presented) => + Effect.succeed( + presented === token + ? (scope as McpInvocationContext.McpThreadInvocationScope) + : undefined, + ), + }), + ), + ); + yield* HttpRouter.serve(layerServer, { + disableListenLog: true, + disableLogger: true, + }).pipe(Layer.build); + const httpClient = (yield* HttpClient.HttpClient).pipe( + HttpClient.mapRequest(HttpClientRequest.bearerToken(token)), + ); + + const discoverResponse = yield* httpClient.post("/mcp", { + headers: { + accept: "application/json, text/event-stream", + "mcp-method": "server/discover", + "mcp-protocol-version": "2026-07-28", + }, + body: HttpBody.text( + `{"jsonrpc":"2.0","id":1,"method":"server/discover","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{},"io.modelcontextprotocol/clientInfo":{"name":"mcp-test","version":"1.0.0"}}}}`, + "application/json", + ), + }); + expect(discoverResponse.status).toBe(200); + const discovered = (yield* discoverResponse.json) as { + result: { supportedVersions: ReadonlyArray }; + }; + expect(discovered.result.supportedVersions).toEqual( + expect.arrayContaining(["2026-07-28", "2025-06-18"]), + ); + + const toolsResponse = yield* httpClient.post("/mcp", { + headers: { + accept: "application/json, text/event-stream", + "mcp-method": "tools/list", + "mcp-protocol-version": "2026-07-28", + }, + body: HttpBody.text( + JSON.stringify({ + jsonrpc: "2.0", + id: 3, + method: "tools/list", + params: { + _meta: { + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientCapabilities": {}, + "io.modelcontextprotocol/clientInfo": { name: "mcp-test", version: "1.0.0" }, + }, + }, + }), + "application/json", + ), + }); + expect(toolsResponse.status).toBe(200); + const tools = (yield* toolsResponse.json) as { + error?: unknown; + result: { tools: ReadonlyArray<{ name: string }> }; + }; + expect(tools.error).toBeUndefined(); + expect(tools.result.tools).toEqual( + expect.arrayContaining([expect.objectContaining({ name: "probe" })]), + ); + + const initializeResponse = yield* httpClient.post("/mcp", { + headers: { accept: "application/json, text/event-stream" }, + body: HttpBody.text( + `{"jsonrpc":"2.0","id":2,"method":"initialize","params":{"protocolVersion":"2099-01-01","capabilities":{},"clientInfo":{"name":"mcp-test","version":"1.0.0"}}}`, + "application/json", + ), + }); + expect(initializeResponse.status).toBe(200); + const initialized = (yield* initializeResponse.json) as { + result: { protocolVersion: string }; + }; + expect(initialized.result.protocolVersion).toBe("2025-06-18"); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + it.effect("admits provider and OAuth client credentials and points only clients at OAuth", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index a9f21d8eef29f..5ef316ca04d22 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -1307,7 +1307,8 @@ export const layerMcpTransport = (registrations: Layer.Layer @@ -225,6 +237,10 @@ it("readThread preserves caller access errors and prefers activity-run status ov expect(result.thread.status).toBe("running"); expect(result.thread.latestRunId).toBe(cancelledRunId); expect(result.thread.activeRunId).toBe(activeRunId); + expect(result.thread.blockedOnThreadWait).toBe(true); + expect(result.thread.pendingBackgroundTasks).toEqual([ + { taskId: "task-subagent", kind: "subagent", childThreadId }, + ]); // Every page read must not repeat each linked PR, and an open PR shows whether it is watched. const listed = result.thread.pullRequests ?? []; expect(listed.map((link) => link.number)).not.toContain(1); diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 7bf7d2efe2c82..8f349f77b71aa 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -3948,16 +3948,30 @@ describe("OrchestratorMcpService thread list", () => { capabilities: new Set(["orchestration"]), issuedAt: 1, }; - const shell = (id: string, projectId: string, snoozed: boolean) => ({ + const shell = (id: string, projectId: string, snoozed: boolean, waiting = false) => ({ ...liveThreadShell(ThreadId.make(id)), projectId: ProjectId.make(projectId), status: "completed" as const, snoozedUntil: snoozed ? DateTime.makeUnsafe("2099-01-01T00:00:00Z") : null, + blockedOnThreadWait: waiting, + pendingBackgroundTasks: waiting + ? [ + { + taskId: "task-subagent", + kind: "subagent" as const, + description: "Review the diff", + parentTaskId: "task-parent", + providerInstanceId: ProviderInstanceId.make("codex"), + childThreadId: ThreadId.make("thread:b-child"), + }, + { taskId: "task-tests", kind: "command" as const, awaited: true as const }, + ] + : [], }); const shells = [ shell("thread:a-snoozed", "project:a", true), shell("thread:a-awake", "project:a", false), - shell("thread:b-snoozed", "project:b", true), + shell("thread:b-snoozed", "project:b", true, true), { ...shell("thread:a-awaiting-command", "project:a", false), activityRunStatus: null, @@ -4022,6 +4036,24 @@ describe("OrchestratorMcpService thread list", () => { ["thread:b-snoozed", "project:b"], ], ); + assert.deepStrictEqual( + listed.threads.map((thread) => [thread.blockedOnThreadWait, thread.pendingBackgroundTasks]), + [ + [false, []], + [ + true, + [ + { + taskId: "task-subagent", + kind: "subagent", + description: "Review the diff", + childThreadId: ThreadId.make("thread:b-child"), + }, + { taskId: "task-tests", kind: "command", awaited: true }, + ], + ], + ], + ); }).pipe(Effect.provide(service)), ); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index b74619e7b28f4..3a43e2a1751e9 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -803,6 +803,24 @@ function threadSnooze( }; } +// Provider-internal links (parentTaskId, providerInstanceId) stay out of agent results. +function threadBackgroundWork( + thread: Pick, +): Required> { + return { + blockedOnThreadWait: thread.blockedOnThreadWait === true, + pendingBackgroundTasks: (thread.pendingBackgroundTasks ?? []).map((task) => ({ + taskId: task.taskId, + kind: task.kind, + ...(task.description === undefined ? {} : { description: task.description }), + ...(task.awaited === undefined ? {} : { awaited: task.awaited }), + ...(task.kind === "subagent" && task.childThreadId !== undefined + ? { childThreadId: task.childThreadId } + : {}), + })), + }; +} + function threadPullRequests( links: OrchestrationV2ThreadShell["pullRequests"], includeLinks = true, @@ -856,6 +874,7 @@ function listItemFromShell( ...threadPullRequests(shell.pullRequests), ...threadSettlement(shell), ...threadSnooze(shell, nowMs), + ...threadBackgroundWork(shell), parentThreadId: shell.lineage.parentThreadId, relationshipToParent: shell.lineage.relationshipToParent, itemCount: shell.visibleItemCount, @@ -898,6 +917,13 @@ function threadDetail( requestId: projection.thread.titleRegeneration.requestId, startedAt: DateTime.formatIso(projection.thread.titleRegeneration.startedAt), }, + lastTitleRegeneration: + projection.thread.lastTitleRegeneration == null + ? null + : { + ...projection.thread.lastTitleRegeneration, + completedAt: DateTime.formatIso(projection.thread.lastTitleRegeneration.completedAt), + }, branch: projection.thread.branch, worktreePath: projection.thread.worktreePath, parentThreadId: projection.thread.lineage.parentThreadId, @@ -910,6 +936,7 @@ function threadDetail( archived: projection.thread.archivedAt !== null, ...threadSettlement(projection.thread), ...threadSnooze(shell, nowMs), + ...threadBackgroundWork(shell), createdAt: DateTime.formatIso(projection.thread.createdAt), updatedAt: DateTime.formatIso(projection.thread.updatedAt), }; diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index 99937d68b80d3..9682a45f5e592 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -10,6 +10,7 @@ import { EnvironmentId, NodeId, OrchestratorMcpThreadReadResult, + ProjectId, ProviderDriverKind, ProviderInstanceId, RunId, @@ -59,6 +60,7 @@ import * as AnalyticsService from "../../telemetry/AnalyticsService.ts"; import { dispatchFailure } from "../threadAccess.ts"; import * as EnvironmentHandlers from "./environment/handlers.ts"; import * as AttachmentHandlers from "./attachment/handlers.ts"; +import { ThreadToolkit } from "./thread/tools.ts"; import * as PeerForwarding from "../../peer/PeerForwarding.ts"; import * as PeerLinkRequests from "../../peer/PeerLinkRequests.ts"; import * as PeerLinks from "../../peer/PeerLinks.ts"; @@ -76,6 +78,9 @@ import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput"; const decodeMcpAttachmentInput = Schema.decodeUnknownEffect(McpAttachmentInput); const decodeThreadReadResult = Schema.decodeUnknownEffect(OrchestratorMcpThreadReadResult); +const decodeThreadSearchResult = Schema.decodeUnknownEffect( + ThreadToolkit.tools.t3_thread_search.successSchema, +); const layerThreadToolkit = McpHttpServer.layerThreadToolkit.pipe( Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})), @@ -589,6 +594,59 @@ it.effect("a client caller targets any thread within its ceiling and cannot act ), ); +it.effect("search names the calling thread, so an agent can tell its own match apart", () => + Effect.gen(function* () { + const server = yield* McpServer.McpServer; + const search = (invocation: McpInvocationContext.McpInvocationScope) => + server + .callTool({ name: "t3_thread_search", arguments: { query: "release notes" } }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, invocation), + Effect.provideService(McpSchema.McpServerClient, client), + ); + + const fromThread = yield* search(scope); + expect(fromThread.structuredContent).toMatchObject({ + currentThreadId: threadId, + matches: [{ threadId }, { threadId: "earlier-thread" }], + }); + + const fromClient = yield* search(clientScope("auto")); + expect(fromClient.structuredContent).toMatchObject({ currentThreadId: null }); + + // A linked environment on an older version answers without the field. + const fromOlderPeer = yield* decodeThreadSearchResult({ matches: [] }); + expect(fromOlderPeer).toEqual({ matches: [] }); + }).pipe( + Effect.provide( + McpHttpServer.layerThreadToolkit.pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provide(NodeCrypto.layer), + Layer.provide(McpToolAccessTestkit.liveThreadsLayer), + Layer.provide( + Layer.mock(ThreadSearch.ThreadSearch)({ + searchThreads: () => + Effect.succeed({ + matches: [threadId, ThreadId.make("earlier-thread")].map((id) => ({ + threadId: id, + projectId: ProjectId.make("project:mcp-test"), + title: "Release notes", + source: "title" as const, + snippet: "", + messageCreatedAt: null, + })), + }), + }), + ), + Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})), + Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})), + Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})), + Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})), + ), + ), + ), +); + it.effect("a read-only client reads threads and is refused every write before it runs", () => Effect.gen(function* () { const server = yield* McpServer.McpServer; diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index 32e45b5d0a1c0..62023dd986b55 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -132,6 +132,7 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { .searchThreads({ ...input, projectId: input.projectId ?? caller?.projectId }) .pipe(Effect.mapError(unavailable)); return { + currentThreadId: scope.thread?.threadId ?? null, matches: matches.map((match) => ({ ...match, link: McpInvocationContext.threadLinkFor(scope, match.threadId, match.title), diff --git a/apps/server/src/mcp/toolkits/thread/tools.ts b/apps/server/src/mcp/toolkits/thread/tools.ts index c6670c4e953d3..750bf15afc019 100644 --- a/apps/server/src/mcp/toolkits/thread/tools.ts +++ b/apps/server/src/mcp/toolkits/thread/tools.ts @@ -199,6 +199,7 @@ const ThreadSearchTool = Tool.make("t3_thread_search", { projectId: Schema.optional(ProjectId), }), success: Schema.Struct({ + currentThreadId: Schema.optional(Schema.NullOr(ThreadId)), matches: Schema.Array( Schema.Struct({ threadId: OrchestrationThreadSearchMatch.fields.threadId, diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index f9a861cca23fb..a8620e9e7ae7d 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -81,6 +81,7 @@ const RPC_AGGREGATES = { [WS_METHODS.serverDisableAcpRegistryProvider]: "server", [WS_METHODS.serverLogoutAcpRegistry]: "server", [WS_METHODS.serverDiscoverSourceControl]: "server", + [WS_METHODS.serverCheckSecretSource]: "server", [WS_METHODS.serverGetTraceDiagnostics]: "server", [WS_METHODS.serverGetProcessDiagnostics]: "server", [WS_METHODS.serverGetHostResources]: "server", diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index fb51465629018..9083cbba80d92 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -521,6 +521,10 @@ const isProviderAdapterProtocolError = Schema.is(ProviderAdapter.ProviderAdapter const makePromptInactivityHarness = Effect.fnUntraced(function* (input: { readonly environment: (runtimeOrdinal: number) => Readonly>; readonly runtimeMode?: "full-access" | "approval-required"; + readonly wrapPrompt?: ( + prompt: AcpSessionRuntime.AcpSessionRuntime["Service"]["prompt"], + ) => AcpSessionRuntime.AcpSessionRuntime["Service"]["prompt"]; + readonly cancelled?: Deferred.Deferred; }) { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const path = yield* Path.Path; @@ -540,7 +544,14 @@ const makePromptInactivityHarness = Effect.fnUntraced(function* (input: { environment: input.environment, wrapRuntime: (runtime) => { natives.push(runtime); - return runtime; + return { + ...runtime, + prompt: input.wrapPrompt?.(runtime.prompt) ?? runtime.prompt, + cancel: + input.cancelled === undefined + ? runtime.cancel + : Deferred.succeed(input.cancelled, undefined).pipe(Effect.andThen(runtime.cancel)), + }; }, }), }, @@ -571,6 +582,7 @@ const makePromptInactivityHarness = Effect.fnUntraced(function* (input: { return { runtime, natives, + providerThread, startTurn, /** A turn still running makes the next start fail, without waiting on time. */ nextTurnRejected: (ordinal: number) => @@ -4097,6 +4109,90 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest), Effect.scoped), ); + it.effect("delivers a follow-up the agent rejects while it is still processing", () => + Effect.gen(function* () { + let promptCalls = 0; + const rejected = yield* Deferred.make(); + const harness = yield* makePromptInactivityHarness({ + environment: () => ({}), + // pi-agent-core based agents (oh-my-pi) end a turn but keep background work running. + wrapPrompt: (prompt) => (payload, options) => { + promptCalls += 1; + return promptCalls === 2 + ? Deferred.succeed(rejected, undefined).pipe( + Effect.andThen( + Effect.fail( + EffectAcpErrors.AcpRequestError.internalError( + "Agent is already processing. Use steer() or followUp() to queue messages, or wait for completion.", + ), + ), + ), + ) + : prompt(payload, options); + }, + }); + yield* harness.startTurn(1); + const [first] = yield* harness.terminals(1); + assert.equal(first?.status, "completed"); + + const followUp = yield* harness.terminals(1).pipe(Effect.forkScoped); + yield* harness.startTurn(2); + yield* Deferred.await(rejected); + yield* TestClock.adjust("1 minute"); + const [delivered] = yield* Fiber.join(followUp); + assert.equal(delivered?.status, "completed"); + assert.equal(promptCalls, 3); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + + it.effect("sends no more prompts once a follow-up waiting on a busy agent is stopped", () => + Effect.gen(function* () { + let promptCalls = 0; + const rejected = yield* Deferred.make(); + const cancelled = yield* Deferred.make(); + const harness = yield* makePromptInactivityHarness({ + environment: () => ({}), + cancelled, + wrapPrompt: (prompt) => (payload, options) => { + promptCalls += 1; + return promptCalls === 1 + ? prompt(payload, options) + : Deferred.succeed(rejected, undefined).pipe( + Effect.andThen( + Effect.fail( + EffectAcpErrors.AcpRequestError.internalError( + "Agent is already processing. Use steer() or followUp() to queue messages, or wait for completion.", + ), + ), + ), + ); + }, + }); + yield* harness.startTurn(1); + yield* harness.terminals(1); + + const stopped = yield* harness.terminals(1).pipe(Effect.forkScoped); + yield* harness.startTurn(2); + yield* Deferred.await(rejected); + const providerTurnId = (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId( + ProviderInstanceId.make("acp-prompt-inactivity"), + "mock-session-1:turn:2", + ), + }); + const interrupt = yield* harness.runtime + .interruptTurn({ providerThread: harness.providerThread, providerTurnId }) + .pipe(Effect.forkScoped); + yield* Deferred.await(cancelled); + yield* TestClock.adjust("1 second"); + const [terminal] = yield* Fiber.join(stopped); + yield* Fiber.join(interrupt); + assert.equal(terminal?.status, "interrupted"); + assert.equal(promptCalls, 2); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + it.effect("holds the inactivity timeout while the agent waits on an approval", () => Effect.gen(function* () { const harness = yield* makePromptInactivityHarness({ diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 0945a282cee2c..7d8223842505c 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -20,8 +20,10 @@ import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; +import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; import { ChildProcessSpawner } from "effect/process"; import type * as EffectAcpSchema from "effect-acp/compat"; @@ -146,44 +148,73 @@ const layerSession = Layer.mergeAll( ); describe("AntigravityAdapterV2 compaction", () => { - it.effect("does not expose unsupported manual compaction on the provider session", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const path = yield* Path.Path; - const crypto = yield* SecureRandom.SecureRandom; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const instanceId = ProviderInstanceId.make("antigravity-compaction-test"); - const adapter = yield* makeAntigravityAdapterV2({ - instanceId, - selfInvocation: yield* resolveSelfInvocation(), - makeRuntime: (input) => - makeAntigravityAcpRuntime({ - ...input, - childProcessSpawner, - spawn: { - command: process.execPath, - args: [mockAgentPath], - cwd: input.cwd, - env: { T3_ACP_ANTIGRAVITY: "1" }, - }, - }).pipe(Effect.provideService(SecureRandom.SecureRandom, crypto)), - withProcess: (_stop, task) => task, - defaultModel: Effect.undefined, - }); - const session = yield* adapter.openSession({ - threadId: ThreadId.make("thread-antigravity-compaction"), - providerSessionId: ProviderSessionId.make("provider-session-antigravity-compaction"), - modelSelection: { instanceId, model: "gemini-test-low" }, - runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }), - }); - assert.isUndefined(session.compactThread); - }).pipe(Effect.provide(layerSession), Effect.scoped), + it.live.each([false, true])( + "negotiates native goals (%s) without enabling manual compaction", + (nativeGoals) => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const instanceId = ProviderInstanceId.make("antigravity-compaction-test"); + const goalSupport = yield* Ref.make(false); + const startupMilestone = yield* Deferred.make(); + const consumeStartupCommands = yield* Deferred.make(); + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + makeRuntime: (input) => + makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.cwd, + env: { T3_ACP_ANTIGRAVITY: "1" }, + }, + }).pipe( + Effect.provideService(SecureRandom.SecureRandom, crypto), + Effect.map((runtime) => ({ + ...runtime, + drainEvents: Deferred.succeed(startupMilestone, undefined).pipe( + Effect.andThen(runtime.drainEvents), + ), + })), + ), + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + supportsNativeGoals: Ref.get(goalSupport).pipe( + Effect.tap(() => Deferred.succeed(startupMilestone, undefined)), + ), + onSessionEvent: (event) => + event._tag === "AvailableCommandsUpdated" + ? Deferred.await(consumeStartupCommands).pipe( + Effect.andThen(Ref.set(goalSupport, nativeGoals)), + ) + : Effect.void, + }); + const opening = yield* adapter + .openSession({ + threadId: ThreadId.make("thread-antigravity-compaction"), + providerSessionId: ProviderSessionId.make("provider-session-antigravity-compaction"), + modelSelection: { instanceId, model: "gemini-test-low" }, + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }), + }) + .pipe(Effect.forkScoped); + yield* Deferred.await(startupMilestone); + yield* Deferred.succeed(consumeStartupCommands, undefined); + const session = yield* Fiber.join(opening); + assert.isUndefined(session.compactThread); + assert.equal(session.providerSession.capabilities.turns.supportsNativeGoals, nativeGoals); + assert.equal((yield* adapter.getCapabilities()).turns.supportsNativeGoals, nativeGoals); + }).pipe(Effect.provide(layerSession), Effect.scoped), ); }); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 1490140c1e6e2..f74dcf29b1b32 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -82,6 +82,7 @@ export interface AntigravityAdapterV2Options { >; readonly withProcess: AntigravityAuth["withProcess"]; readonly defaultModel: Effect.Effect; + readonly supportsNativeGoals?: Effect.Effect; readonly onSessionStarted?: ( started: AcpSessionRuntime.AcpSessionRuntimeStartResult, cwd: string, @@ -208,6 +209,7 @@ export function makeAntigravityAcpAdapterFlavor( driver: ANTIGRAVITY_PROVIDER, runtimeHarness: "Antigravity", capabilities: AntigravityProviderCapabilitiesV2, + supportsNativeGoals: options.supportsNativeGoals ?? Effect.succeed(false), // Agents that advertise HTTP MCP skip the stdio bridge process; others keep stdio. mcpOverHttp: true, sessionCarriesPullRequestLinking: antigravityAppendsSystemPrompt, diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 6e5fd3516e0b1..bba467deec417 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -31,6 +31,7 @@ import { RunId, ThreadId, TurnItemId, + type ServerProviderModel, } from "@t3tools/contracts"; import { assert, describe, it } from "@effect/vitest"; import * as CodexClient from "effect-codex-app-server/client"; @@ -230,6 +231,34 @@ describe("CodexAdapterV2 runtime policy", () => { }), ); + it.effect("sends the chosen cyber access program, else the model's default", () => + Effect.gen(function* () { + const build = (value?: string, cyberAccess?: { defaultProgram: string | undefined }) => + CodexAdapterV2.buildCodexTurnStartParams({ + nativeThreadId: "native-cyber", + codexInput: [{ type: "text", text: "test" }], + runtimePolicy: { runtimeMode: "full-access", interactionMode: "default", cwd: null }, + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5.4", + ...(value === undefined ? {} : { options: [{ id: "cyberAccessProgram", value }] }), + }, + cyberAccess, + }); + + // Custom models offer no Cyber Access, so even an explicit choice is dropped. + assert.notProperty(yield* build(), "cyberAccessProgram"); + assert.notProperty(yield* build("daybreakBlue"), "cyberAccessProgram"); + const daybreak = { defaultProgram: "daybreakBlue" }; + assert.equal((yield* build(undefined, daybreak)).cyberAccessProgram, "daybreakBlue"); + assert.equal((yield* build("standard", daybreak)).cyberAccessProgram, "standard"); + // An unread config leaves no default, but an explicit Standard still goes. + const unknown = { defaultProgram: undefined }; + assert.notProperty(yield* build(undefined, unknown), "cyberAccessProgram"); + assert.equal((yield* build("standard", unknown)).cyberAccessProgram, "standard"); + }), + ); + it.effect("sends MCP app model context as untrusted Codex context", () => Effect.gen(function* () { const policy = { runtimeMode: "full-access", interactionMode: "default", cwd: null } as const; @@ -1302,6 +1331,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { onUsageLimits?: CodexAdapterV2.CodexAdapterV2Options["onUsageLimits"], promptSuggestions: Effect.Effect = Effect.succeed(false), onNotification: (method: string) => Effect.Effect = () => Effect.void, + models?: CodexAdapterV2.CodexAdapterV2Options["models"], ) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -1364,6 +1394,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { environment: {}, clientFactory, ...(onUsageLimits ? { onUsageLimits } : {}), + ...(models ? { models } : {}), digest: yield* Digest.Digest, fileSystem, idAllocator, @@ -2705,12 +2736,18 @@ describe("CodexAdapterV2 post-settle continuation", () => { Effect.gen(function* () { const nativeThreadId = "context-thread"; const nativeTurnId = "context-turn"; + // An explicit Standard must reach Codex, or Codex falls back to Daybreak. + const modelSelection = { + ...CODEX_TEST_MODEL_SELECTION, + options: [{ id: "cyberAccessProgram", value: "standard" }], + }; const params = yield* CodexAdapterV2.buildCodexTurnStartParams({ nativeThreadId, codexInput: [{ type: "text", text: "work" }], runtimePolicy: CODEX_TEST_RUNTIME_POLICY, - modelSelection: CODEX_TEST_MODEL_SELECTION, + modelSelection, hasT3Mcp: true, + cyberAccess: { defaultProgram: "daybreakBlue" }, }); assert.include( params.additionalContext?.t3_code_orchestration_01?.value ?? "", @@ -2790,6 +2827,27 @@ describe("CodexAdapterV2 post-settle continuation", () => { if (method === "item/completed" || method === "turn/completed") wireOrder.push(method); }), + Effect.succeed>([ + { + slug: modelSelection.model, + name: modelSelection.model, + isCustom: false, + capabilities: { + optionDescriptors: [ + { + id: "cyberAccessProgram", + label: "Cyber Access", + type: "select", + options: [ + { id: "standard", label: "Standard" }, + { id: "daybreakBlue", label: "Daybreak Blue", isDefault: true }, + ], + currentValue: "daybreakBlue", + }, + ], + }, + }, + ]), ); yield* (yield* McpProviderSessions.McpProviderSessions).set({ environmentId: EnvironmentId.make("test"), @@ -2800,15 +2858,16 @@ describe("CodexAdapterV2 post-settle continuation", () => { authorizationHeader: "Bearer test", browserToolsAvailable: true, }); - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ + yield* harness.runtime.startTurn({ + ...makeCodexTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now: yield* DateTime.now, attemptId: RunAttemptId.make("context-attempt"), text: "work", }), - ); + modelSelection, + }); yield* harness.firstTerminal; yield* Deferred.await(restoreRequested); assert.equal(harness.terminalEvents()[0]?.status, "completed"); diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 4e8fd1ac5f30b..e9b41ac8a5b05 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -38,6 +38,7 @@ import { ProviderDriverKind, ProviderSetupError, type ServerProviderCompatibilityAdvisory, + type ServerProviderModel, isDelegatedAppThread, } from "@t3tools/contracts"; import { SKILL_MENTION_PATTERN } from "@t3tools/shared/composerInlineTokens"; @@ -712,19 +713,8 @@ const decodeTurnReasoningEffort = Schema.decodeUnknownEffect( Schema.Union([CodexSchema.V2TurnStartParams__ReasoningEffort, Schema.Null]), ); -const CodexTurnStartParamsWithCollaborationMode = CodexSchema.V2TurnStartParams.pipe( - Schema.fieldsAssign({ - collaborationMode: Schema.optionalKey(CodexSchema.ClientRequest__CollaborationMode), - additionalContext: Schema.optionalKey( - Schema.Record(Schema.String, CodexSchema.V2TurnStartParams__AdditionalContextEntry), - ), - }), -); -type CodexTurnStartParamsWithCollaborationMode = - typeof CodexTurnStartParamsWithCollaborationMode.Type; -const decodeCodexTurnStartParamsWithCollaborationMode = Schema.decodeUnknownEffect( - CodexTurnStartParamsWithCollaborationMode, -); +type CodexTurnStartParams = typeof CodexClient.V2TurnStartParams.Type; +const decodeCodexTurnStartParams = Schema.decodeUnknownEffect(CodexClient.V2TurnStartParams); const isProviderAdapterRuntimeRequestResponseError = Schema.is( ProviderAdapter.ProviderAdapterRuntimeRequestResponseError, ); @@ -770,6 +760,18 @@ function codexRuntimeModeTurnDefaults(runtimeMode: RuntimeMode): { } } +const isCodexCyberAccessProgram = Schema.is(CodexSchema.V2TurnStartParams__CyberAccessProgram); + +function codexCyberAccess( + models: ReadonlyArray, + model: string, +): { readonly defaultProgram: string | undefined } | undefined { + const descriptor = models + .find((candidate) => candidate.slug === model) + ?.capabilities?.optionDescriptors?.find((candidate) => candidate.id === "cyberAccessProgram"); + return descriptor?.type === "select" ? { defaultProgram: descriptor.currentValue } : undefined; +} + export const buildCodexTurnStartParams = Effect.fn("CodexAdapterV2.buildCodexTurnStartParams")( function* (input: { readonly nativeThreadId: string; @@ -782,6 +784,8 @@ export const buildCodexTurnStartParams = Effect.fn("CodexAdapterV2.buildCodexTur /** ChatGPT token sharing does not accept service tiers. */ readonly omitServiceTier?: boolean; readonly appContext?: ProviderAdapter.ProviderAdapterV2TurnInput["appContext"]; + /** Set only for a model that offers Cyber Access; custom models never do. */ + readonly cyberAccess?: { readonly defaultProgram: string | undefined } | undefined; /** The user's `model_reasoning_summary` from the Codex config, when set. */ readonly configuredReasoningSummary?: CodexSchema.V2TurnStartParams__ReasoningSummary; }) { @@ -803,6 +807,14 @@ export const buildCodexTurnStartParams = Effect.fn("CodexAdapterV2.buildCodexTur input.omitServiceTier === true ? undefined : getCodexServiceTierOptionValue(input.modelSelection); + // A chosen program goes as is, even one the model lacks, so Codex rejects it visibly. + const cyberAccessProgram = + input.cyberAccess === undefined + ? undefined + : [ + getModelSelectionStringOptionValue(input.modelSelection, "cyberAccessProgram"), + input.cyberAccess.defaultProgram, + ].find(isCodexCyberAccessProgram); // MCP-written app context must be quoted user input, not developer instructions. const appContext = Object.fromEntries( (input.appContext ?? []).map((entry) => [ @@ -824,7 +836,7 @@ export const buildCodexTurnStartParams = Effect.fn("CodexAdapterV2.buildCodexTur t3Context === undefined && Object.keys(appContext).length === 0 ? undefined : { ...t3Context, ...appContext }; - return yield* decodeCodexTurnStartParamsWithCollaborationMode({ + return yield* decodeCodexTurnStartParams({ threadId: input.nativeThreadId, input: input.codexInput, ...(additionalContext ? { additionalContext } : {}), @@ -839,6 +851,8 @@ export const buildCodexTurnStartParams = Effect.fn("CodexAdapterV2.buildCodexTur ...(sandboxPolicy === undefined ? {} : { sandboxPolicy }), ...(effort === undefined ? {} : { effort }), ...(serviceTier === undefined ? {} : { serviceTier }), + // Codex keeps no per-thread choice for this, so every turn must carry it. + ...(cyberAccessProgram === undefined ? {} : { cyberAccessProgram }), // Codex supplies its own mode instructions; send both modes to clear Plan on exit. collaborationMode: { mode: input.runtimePolicy.interactionMode, @@ -1683,7 +1697,10 @@ export type CodexAdapterV2DriverEnv = export const createCodexAdapterV2 = Effect.fn("CodexAdapterV2.createCodexAdapterV2")(function* ( { instanceId, environment, enabled, config }: ProviderAdapterDriverCreateInput, - hooks: Pick = {}, + hooks: Pick< + CodexAdapterV2Options, + "onUsageLimits" | "resolveRuntime" | "compatibility" | "models" + > = {}, ) { const clientFactory = yield* CodexAppServerClientFactory; const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests; @@ -1733,6 +1750,8 @@ export interface CodexAdapterV2Options { readonly environment: NodeJS.ProcessEnv; readonly clientFactory: CodexAppServerClientFactoryShape; readonly onUsageLimits?: ManagedServerProvider["applyUsageLimits"]; + /** The provider's published models, read per turn for catalog defaults. */ + readonly models?: Effect.Effect>; readonly resolveRuntime?: Effect.Effect; readonly compatibility?: ( version: string, @@ -1792,10 +1811,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( environment: resolvedRuntime?.environment ?? adapterOptions.environment, }); const additionalContextByThread = yield* Ref.make( - new Map< - string, - NonNullable - >(), + new Map>(), ); const threadsAwaitingContextRestore = yield* Ref.make(new Set()); // Codex drops client developer messages during compaction but only resends additionalContext @@ -7240,6 +7256,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ) { const threadId = yield* getNativeThreadId(turnInput.providerThread); const mcpSession = yield* mcpSessions.read(turnInput.threadId); + const models = adapterOptions.models === undefined ? [] : yield* adapterOptions.models; const configuredReasoningSummary = yield* client .request("config/read", { cwd: turnInput.runtimePolicy.cwd, includeLayers: false }) .pipe( @@ -7249,6 +7266,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ), ); const turnStartParams = yield* buildCodexTurnStartParams({ + cyberAccess: codexCyberAccess(models, turnInput.modelSelection.model), nativeThreadId: threadId, codexInput, runtimePolicy: turnInput.runtimePolicy, diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 1efbbfad09d81..acfbdad41ea8e 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -496,6 +496,21 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }).pipe(Effect.scoped), ); + it.effect("never sends a saved variant the catalog model does not list", () => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed([ + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.execution.succeeded", { sessionID: SESSION }), + ]); + const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped); + yield* runtime.startTurn( + turnInput(thread, { ...bigPickle, options: [{ id: "variant", value: "medium" }] }), + ); + assert.equal((yield* Fiber.join(terminal))?.status, "completed"); + }).pipe(Effect.scoped), + ); + it.effect("renames the session before the first turn after the thread was renamed", () => Effect.gen(function* () { const { runtime, thread } = yield* resumed([ diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index c186c40f9e73a..c7cd7a9ff288e 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -1400,14 +1400,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) { const adapter = yield* providerAdapters.get(providerInstanceId).pipe(mapDispatchError(command)); const { driver } = adapter; - if (driver === "opencode") { + if (driver === "opencode" || driver === "antigravity") { const capabilities = yield* adapter.getCapabilities().pipe(mapDispatchError(command)); return capabilities.turns.supportsNativeGoals === true ? driver : undefined; } return driver === "codex" || driver === "claudeAgent" ? driver : undefined; }); - /** Claude Code reads `/goal pause` and `/goal resume` as new goals named "pause" and "resume". */ + /** Unsupported goal controls can become new objectives in native providers. */ const ensureGoalCommandSupported = Effect.fn("Orchestrator.ensureGoalCommandSupported")( function* ( command: OrchestrationV2ServerCommand, @@ -1415,8 +1415,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio providerInstanceId: ProviderInstanceId, ) { const goalCommand = parseGoalCommand(message); - if (goalCommand?.type !== "pause" && goalCommand?.type !== "resume") return; - if ((yield* goalDriverFor(command, providerInstanceId)) !== "claudeAgent") return; + if (goalCommand === null || goalCommand.type === "set") return; + const driver = yield* goalDriverFor(command, providerInstanceId); + if (driver === "antigravity") { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: + "Antigravity accepts /goal followed by an objective. Interrupt the running turn, then ask Antigravity to stop the current goal.", + }); + } + if (goalCommand.type !== "pause" && goalCommand.type !== "resume") return; + if (driver !== "claudeAgent") return; return yield* new OrchestratorDispatchError({ commandId: command.commandId, commandType: command.type, @@ -4768,6 +4778,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? { ...thread, ...(command.title === undefined ? {} : { title: command.title }), + ...(command.outcome === undefined + ? {} + : { + lastTitleRegeneration: { + ...command.outcome, + requestId: command.requestId, + completedAt: now, + }, + }), titleRegeneration: null, updatedAt: now, } diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 3f48cbf247fc7..511c252689cc8 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -54,6 +54,7 @@ import { encodeThreadHistoryCursor, selectHistoryPageFromCursor, THREAD_HISTORY_PAGE_POLICY, + THREAD_HISTORY_SNAPSHOT_ROW_LIMIT, THREAD_HISTORY_TURN_SNAPSHOT_ROW_LIMIT, } from "./threadHistoryPaging.ts"; import { buildBoundedThreadStreamSnapshot } from "./ThreadStream.ts"; @@ -3651,14 +3652,16 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { const threadId = ThreadId.make("thread:bounded-sql-history"); // The raw SQL edits below stand in for committed writes, which always append a thread event. let revision = 0; - const historyPage = (...args: Parameters) => + const committed = (read: Effect.Effect) => sql`INSERT INTO orchestration_events ( event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at, actor_kind, payload_json, metadata_json, application_event_version ) VALUES ( ${`event:bounded-sql-history:revision:${++revision}`}, 'thread', ${threadId}, ${revision}, 'turn-item.updated', ${nowIso}, 'user', '{}', '{}', 2 - )`.pipe(Effect.andThen(projectionStore.getThreadHistoryPage(...args))); + )`.pipe(Effect.andThen(read)); + const historyPage = (...args: Parameters) => + committed(projectionStore.getThreadHistoryPage(...args)); yield* projectionStore.apply({ id: EventId.make("event:bounded-sql-history:thread"), type: "thread.created", @@ -4050,6 +4053,134 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { WHERE thread_id = ${threadId} AND ordinal IN (500, 580) `; + // Older pages and timeline pages read the rows near the page, not the whole history. A + // full index that another read left cached gives the same page. + const pageStatements: Array]> = []; + const recordPageStatements = (read: Effect.Effect) => + committed( + read.pipe( + Effect.provideService(Statement.CurrentTransformer, (statement) => { + pageStatements.push(statement.compile()); + return Effect.succeed(statement); + }), + ), + ); + const olderCursor = encodeThreadHistoryCursor({ + snapshotSequence: 0, + sourceThreadId: threadId, + sourceItemId: TurnItemId.make("turn-item:bounded-sql-history:990"), + position: 989, + }); + const ordinalsFrom = (first: number, length: number) => + Array.from({ length }, (_, index) => first + index); + for (const workMode of [undefined, "deferred"] as const) { + const read = (throughEntryId?: string) => + projectionStore.getThreadHistoryPage( + threadId, + olderCursor, + throughEntryId, + false, + workMode, + ); + const page = yield* recordPageStatements(read()); + assert.deepEqual( + page.items.map((row) => row.item.ordinal), + ordinalsFrom(915, 75), + ); + assert.strictEqual(decodeThreadHistoryCursor(page.nextCursor!).p, 914); + // A jump to an entry reads the full index and leaves it cached. With work, it scans + // payloads for inline output only in its page's runs, not in a run after its cursor. + const scannedRuns: Array = []; + yield* read("turn-item:bounded-sql-history:950").pipe( + Effect.provideService(Statement.CurrentTransformer, (statement) => { + const [query, params] = statement.compile(); + if (query.includes("LIKE '%htmlRender%'")) scannedRuns.push(String(params[0])); + return Effect.succeed(statement); + }), + ); + assert.deepEqual( + [ + scannedRuns.length, + scannedRuns.some((runs) => runs.includes('"run:bounded-sql-history:950"')), + scannedRuns.some((runs) => runs.includes('"run:bounded-sql-history:995"')), + ], + workMode === undefined ? [0, false, false] : [1, true, false], + ); + assert.deepEqual(yield* read(), page); + } + for (const [view, ordinals] of [ + ["activity", ordinalsFrom(902, 20)], + ["messages", [1000]], + ] as const) { + const read = projectionStore.getTimelinePage(threadId, { + afterPosition: 900, + limit: 20, + view, + }); + const page = yield* recordPageStatements(read); + assert.deepEqual( + page.items.map((row) => [row.item.ordinal, row.position]), + ordinals.map((ordinal) => [ordinal, ordinal - 1]), + ); + assert.strictEqual(page.totalItems, 1000); + // An attachment lookup reads the full index and leaves it cached. + yield* projectionStore.getTimelinePage(threadId, { attachmentId: "absent", limit: 1 }); + assert.deepEqual(yield* read, page); + } + { + const pagePath = "file:/history-page-steps?vfs=memdb"; + using copy = new NodeSqlite.DatabaseSync(pagePath); + yield* sql`VACUUM INTO ${pagePath}`; + // Only statements that count positions may grow with the history, and those read an + // index alone. Every other statement costs the same when the rows below the page are gone. + const countsPositions = ([query]: readonly [string, ReadonlyArray]) => + /COUNT\(\*\)|OFFSET/.test(query); + for (const [query, params] of pageStatements.filter(countsPositions)) { + const plan = copy + .prepare(`EXPLAIN QUERY PLAN ${query}`) + .all(...(params as ReadonlyArray)) + .map((row) => String(row.detail)) + .filter((detail) => detail.includes("orchestration_v2_projection_turn_items")); + assert.isTrue( + plan.every((detail) => detail.includes("COVERING INDEX")), + `${query}\n${plan.join("\n")}`, + ); + } + const rowReads = pageStatements.filter((statement) => !countsPositions(statement)); + const rowReadSteps = () => + rowReads.reduce((steps, [query, params]) => { + const statement = copy.prepare(query); + statement.all(...(params as ReadonlyArray)); + return steps + statement.stat("vmStep"); + }, 0); + const fullSteps = rowReadSteps(); + assert.isAbove(fullSteps, 0); + copy.exec( + "DELETE FROM orchestration_v2_projection_turn_items WHERE ordinal BETWEEN 2 AND 400", + ); + assert.isAtMost(fullSteps, rowReadSteps() * 1.1); + } + // Rows that a rolled-back run hides below the page still shift every position above them. + const setOldRunStatus = (status: "rolled_back" | "completed") => sql` + UPDATE orchestration_v2_projection_runs + SET status = ${status}, payload_json = json_set(payload_json, '$.status', ${status}) + WHERE thread_id = ${threadId} AND ordinal BETWEEN 100 AND 109`; + yield* setOldRunStatus("rolled_back"); + const shiftedPage = yield* historyPage(threadId, olderCursor); + assert.strictEqual(decodeThreadHistoryCursor(shiftedPage.nextCursor!).p, 904); + const shiftedTimeline = yield* committed( + projectionStore.getTimelinePage(threadId, { + afterPosition: 900, + limit: 1, + view: "activity", + }), + ); + assert.deepEqual( + [shiftedTimeline.totalItems, shiftedTimeline.items[0]?.item.ordinal], + [990, 912], + ); + yield* setOldRunStatus("completed"); + const retainedRequestPlan = yield* sql<{ readonly detail: string }>` EXPLAIN QUERY PLAN WITH selected AS ( @@ -4205,21 +4336,24 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { window.projection.visibleTurnItems.find((row) => row.item.deferredWork)?.item.ordinal, 3, ); + const newestCursor = encodeThreadHistoryCursor({ + snapshotSequence: 0, + sourceThreadId: threadId, + sourceItemId: "turn-item:bounded-sql-history:1000", + position: 1000, + }); + const page = yield* historyPage(threadId, newestCursor, undefined, false, "deferred"); + assert.isUndefined(page.items.find((row) => row.item.ordinal === 2)?.item.deferredWork); + // Tool payloads hold megabytes, so a page that reads the full index, as a jump to an + // entry does, looks for inline output only in its own runs. const pageRead = traceSqlStatements(); - const page = yield* historyPage( + yield* historyPage( threadId, - encodeThreadHistoryCursor({ - snapshotSequence: 0, - sourceThreadId: threadId, - sourceItemId: "turn-item:bounded-sql-history:1000", - position: 1000, - }), - undefined, + newestCursor, + "turn-item:bounded-sql-history:2", false, "deferred", ).pipe(Effect.withTracer(pageRead.tracer)); - assert.isUndefined(page.items.find((row) => row.item.ordinal === 2)?.item.deferredWork); - // Tool payloads hold megabytes, so a page looks for inline output only in its own runs. const payloadScans = pageRead.statements.filter((statement) => statement.includes("LIKE '%htmlRender%'"), ); @@ -5555,6 +5689,412 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { ) `; assert.strictEqual((yield* forkPage()).totalItems, forkTotal + 2); + + // An agent started this thread, so the snapshot folds no work. Its cursor then names a + // command that an older page folds into the run's one work group. + yield* sql` + UPDATE orchestration_v2_projection_turn_items + SET type = CASE WHEN ordinal = 0 THEN type ELSE 'assistant_message' END, + payload_json = CASE + WHEN ordinal = 0 THEN json_set(payload_json, '$.createdBy', 'agent') + ELSE json_set(payload_json, '$.type', 'assistant_message', + '$.messageId', turn_item_id, '$.streaming', json('false')) + END + WHERE thread_id = ${threadId} AND type = 'user_message' + `; + yield* sql` + INSERT INTO orchestration_events ( + event_id, aggregate_kind, stream_id, stream_version, event_type, + occurred_at, actor_kind, payload_json, metadata_json, application_event_version + ) VALUES ( + 'event:paged-scrollback:agent-started', 'thread', ${threadId}, 2, + 'turn-item.updated', ${nowIso}, 'user', '{}', '{}', 2 + ) + `; + const window = yield* projectionStore.getThreadSnapshotWindow(threadId, { + rowLimit: THREAD_HISTORY_SNAPSHOT_ROW_LIMIT, + userTurnLimit: THREAD_HISTORY_PAGE_POLICY.maxUserTurns, + deferWork: true, + }); + const bounded = buildBoundedThreadProjection({ + projection: window.projection, + snapshotSequence: window.snapshotSequence, + }); + const loaded = [bounded.projection.visibleTurnItems]; + let earlier = bounded.hasMoreHistory ? bounded.historyCursor : null; + while (earlier !== null) { + assert.isBelow(loaded.length, 20); + const page: OrchestrationV2ThreadHistoryPage = yield* projectionStore.getThreadHistoryPage( + threadId, + earlier, + undefined, + false, + "deferred", + ); + loaded.unshift(page.items); + earlier = page.hasMoreHistory ? page.nextCursor : null; + } + const held = loaded.flat(); + const heldOrdinals = held.map((row) => row.item.ordinal); + assert.deepEqual( + heldOrdinals, + [...new Set(heldOrdinals)].toSorted((left, right) => left - right), + ); + const folded = held.find((row) => row.item.deferredWork !== undefined)?.item; + assert.isAbove(folded?.deferredWork?.itemCount ?? 0, 150); + const everyRow = yield* projectionStore.getTimelinePage(threadId, { + view: "activity", + limit: itemCount + 2, + }); + // Every row is on the client, or is work that the folded row stands for. + assert.deepEqual( + everyRow.items + .filter( + ({ item }) => + !heldOrdinals.includes(item.ordinal) && + !( + item.type === "command_execution" && + folded?.deferredWork !== undefined && + item.ordinal > folded.ordinal && + item.ordinal <= folded.deferredWork.lastOrdinal + ), + ) + .map(({ item }) => item.ordinal), + [], + ); + }), + ); + + it.effect("a page read from a window equals the page read from the full index", () => + Effect.gen(function* () { + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const sql = yield* SqlClient.SqlClient; + const now = yield* DateTime.now; + const nowIso = DateTime.formatIso(now); + // Seeded, so every run builds the same threads. + let seed = 0x5eed; + const random = () => { + seed = (Math.imul(seed, 1_664_525) + 1_013_904_223) >>> 0; + return seed / 2 ** 32; + }; + const chance = (probability: number) => random() < probability; + const spans: Array = []; + const tracer = Tracer.make({ + span(options) { + spans.push(options.name); + return new Tracer.NativeSpan(options); + }, + }); + let windowReads = 0; + let foldedGroups = 0; + + for (let round = 0; round < 4; round += 1) { + const threadId = ThreadId.make(`thread:window-equivalence:${round}`); + const created = { + id: EventId.make(`event:window-equivalence:${round}`), + type: "thread.created", + threadId, + occurredAt: now, + payload: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project:window-equivalence"), + title: "Window equivalence", + providerInstanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + } satisfies Parameters[0]; + yield* projectionStore.apply(created); + // One run of each kind in a random order, then an active run. Every other thread has + // one user turn and then only wake turns. + // The last thread is a long run that a late notification wakes, then enough one-row + // runs that a page stops at the raw turn limit only if it counts that wake as a turn. + const kinds = + round === 3 + ? ["late wake", ...Array.from({ length: 148 }, () => "one row")] + : [ + "rolled back", + "cancelled queued turn", + "replaced attempt", + "stopped", + "stopped", + "folds work", + "folds work", + "short", + "short", + "short", + ] + .map((kind) => ({ kind, order: random() })) + .toSorted((left, right) => left.order - right.order) + .map(({ kind }) => kind); + const agentDriven = round === 1; + const runs: Array = []; + const attempts: Array = []; + const items: Array = []; + const tiedWithHidden: Array = []; + const repliesInStoppedRuns: Array = []; + let ordinal = 0; + for (const [index, kind] of [...kinds, "active"].entries()) { + const run = index + 1; + const runId = `run:window-equivalence:${round}:${run}`; + const nodeId = `node:window-equivalence:${round}:${run}`; + const status = + kind === "active" + ? "running" + : kind === "rolled back" + ? "rolled_back" + : kind === "cancelled queued turn" + ? "cancelled" + : kind === "short" && chance(0.5) + ? "interrupted" + : "completed"; + runs.push({ + id: runId, + threadId, + ordinal: run, + providerInstanceId, + modelSelection, + providerThreadId: null, + userMessageId: `message:window-equivalence:${round}:${run}`, + rootNodeId: nodeId, + activeAttemptId: null, + status, + requestedAt: nowIso, + startedAt: nowIso, + completedAt: nowIso, + checkpointId: null, + contextHandoffId: null, + }); + attempts.push({ + id: `attempt:window-equivalence:${round}:${run}`, + runId, + attemptOrdinal: 1, + rootNodeId: nodeId, + providerInstanceId, + providerThreadId: "provider-thread:window-equivalence", + providerTurnId: null, + reason: "initial", + status: kind === "replaced attempt" || chance(0.2) ? "superseded" : "completed", + startedAt: nowIso, + completedAt: nowIso, + }); + // The first row after a rolled-back run shares the ordinal of that run's last row. + let tie = kinds[index - 1] === "rolled back"; + if (tie) + tiedWithHidden.push( + TurnItemId.make(`turn-item:window-equivalence:${round}:${items.length}`), + ); + const add = (type: string, fields: Record = {}) => { + if (ordinal === 0 || !(tie || chance(0.04))) ordinal += 1; + tie = false; + items.push({ + id: `turn-item:window-equivalence:${round}:${items.length}`, + threadId, + runId, + nodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal, + status: "completed", + title: null, + startedAt: nowIso, + completedAt: nowIso, + updatedAt: nowIso, + type, + ...fields, + }); + }; + const userMessage = (inputIntent: string) => + add("user_message", { + createdBy: "user", + creationSource: "web", + messageId: `message:window-equivalence:${round}:${items.length}`, + inputIntent, + text: "Turn", + attachments: [], + }); + const notification = () => + add("notification", { + source: { kind: "system" }, + outcome: "completed", + summary: "Wake", + }); + const wakes = + kind === "one row" + ? run % 10 !== 0 + : kind !== "late wake" && (agentDriven ? run > 1 : chance(0.2)); + if (wakes) notification(); + else userMessage(kind === "cancelled queued turn" ? "queued_turn" : "turn_start"); + // A stopped run never folds, so it is long enough for page ends to fall inside it. + const work = + kind === "late wake" + ? 420 + Math.floor(random() * 40) + : kind === "stopped" + ? 320 + Math.floor(random() * 60) + : kind === "folds work" + ? 155 + Math.floor(random() * 60) + : kind === "one row" + ? 0 + : Math.floor(random() * 30); + for (let row = 0; row < work; row += 1) { + if (chance(0.5)) add("command_execution", { input: "echo", output: "ok", exitCode: 0 }); + else add("reasoning", { text: "", streaming: false }); + // A reply deep in a stopped run: a page that ends on it has enough work below it + // to fold, and only the stop request above it says that it does not. + const reply = kind === "stopped" && row === 200; + if (reply) + repliesInStoppedRuns.push(`turn-item:window-equivalence:${round}:${items.length}`); + if (reply || chance(0.02)) + add("assistant_message", { + messageId: `message:window-equivalence:${round}:${items.length}`, + text: "Reply", + streaming: false, + }); + if (chance(0.01)) notification(); + if (chance(0.004) && !agentDriven) userMessage("steer"); + } + if (kind === "late wake") notification(); + if (kind === "stopped") add("run_interrupt_request", { message: "Stop" }); + if (kind === "replaced attempt" || (kind === "stopped" && chance(0.5))) + add("run_interrupt_result", { message: "Stopped" }); + if (kind === "short" && chance(0.3)) + add("error", { + status: "failed", + failure: { class: "unknown", message: "Failed", code: null, retryable: false }, + }); + } + yield* sql` + INSERT INTO orchestration_v2_projection_runs ( + run_id, thread_id, ordinal, provider, provider_thread_id, status, + requested_at, completed_at, payload_json + ) + SELECT json_extract(value, '$.id'), ${threadId}, json_extract(value, '$.ordinal'), 'codex', + NULL, json_extract(value, '$.status'), ${nowIso}, ${nowIso}, value + FROM json_each(${encodeUnknownJsonString(runs)})`; + yield* sql` + INSERT INTO orchestration_v2_projection_run_attempts ( + attempt_id, thread_id, run_id, attempt_ordinal, root_node_id, provider, + provider_instance_id, provider_thread_id, provider_turn_id, status, payload_json + ) + SELECT json_extract(value, '$.id'), ${threadId}, json_extract(value, '$.runId'), 1, + json_extract(value, '$.rootNodeId'), ${providerInstanceId}, ${providerInstanceId}, + json_extract(value, '$.providerThreadId'), NULL, json_extract(value, '$.status'), value + FROM json_each(${encodeUnknownJsonString(attempts)})`; + yield* sql` + INSERT INTO orchestration_v2_projection_turn_items ( + turn_item_id, thread_id, run_id, node_id, provider_thread_id, provider_turn_id, + parent_item_id, ordinal, type, status, updated_at, payload_json + ) + SELECT json_extract(value, '$.id'), ${threadId}, json_extract(value, '$.runId'), + json_extract(value, '$.nodeId'), NULL, NULL, NULL, json_extract(value, '$.ordinal'), + json_extract(value, '$.type'), json_extract(value, '$.status'), ${nowIso}, value + FROM json_each(${encodeUnknownJsonString(items)})`; + + // Applying an event drops the thread's cached index, as each event of a run does, so + // each of these reads a window. + const requests: Array<{ + readonly read: Effect.Effect; + readonly page: unknown; + }> = []; + const windowed = (read: Effect.Effect) => + Effect.gen(function* () { + yield* projectionStore.apply(created); + spans.length = 0; + const page = yield* read.pipe(Effect.withTracer(tracer)); + if (spans.includes("ProjectionStore.readTimelineWindow")) windowReads += 1; + requests.push({ read, page }); + return page; + }); + const history = ( + cursor: string, + throughEntryId?: string, + conversationOnly?: boolean, + workMode?: "deferred" | "work", + ) => + projectionStore.getThreadHistoryPage( + threadId, + cursor, + throughEntryId, + conversationOnly, + workMode, + ); + const timeline = (options: ProjectionStore.ProjectionTimelinePageOptions) => + projectionStore.getTimelinePage(threadId, options); + + const { totalItems } = yield* windowed(timeline({ limit: 0 })); + const newest = (yield* windowed( + timeline({ view: "activity", afterPosition: totalItems - 2, limit: 1 }), + )).items[0]!; + const firstCursor = encodeThreadHistoryCursor({ + snapshotSequence: 0, + sourceThreadId: threadId, + sourceItemId: newest.sourceItemId, + position: newest.position, + }); + const groups = new Map(); + for (const [conversationOnly, workMode] of [ + [false, "deferred"], + [false, undefined], + [true, undefined], + ] as const) { + for (let cursor: string | null = firstCursor; cursor !== null;) { + const page: OrchestrationV2ThreadHistoryPage = yield* windowed( + history(cursor, undefined, conversationOnly, workMode), + ); + for (const { item } of page.items) + if (item.deferredWork !== undefined) groups.set(item.id, item.deferredWork.cursor); + cursor = page.nextCursor; + } + } + for (const sourceItemId of repliesInStoppedRuns) { + const cursor = encodeThreadHistoryCursor({ + snapshotSequence: 0, + sourceThreadId: threadId, + sourceItemId, + position: 0, + }); + yield* windowed(history(cursor, undefined, false, "deferred")); + } + foldedGroups += groups.size; + for (const [anchorId, groupCursor] of groups) { + for (let cursor: string | null = groupCursor; cursor !== null;) + cursor = (yield* windowed(history(cursor, anchorId, false, "work"))).nextCursor; + } + for (const view of ["messages", "activity"] as const) { + for (const afterPosition of [-1, Math.floor(totalItems / 3), totalItems - 5]) + yield* windowed(timeline({ view, afterPosition, limit: 20 })); + } + for (const itemId of [newest.sourceItemId, ...tiedWithHidden]) + yield* windowed(timeline({ itemId, limit: 1 })); + + // An attachment lookup and a jump to an entry read the full index and leave it cached, + // so the same requests now come from it. + yield* timeline({ attachmentId: "absent", limit: 1 }); + yield* history(firstCursor, "absent", false, "deferred"); + spans.length = 0; + for (const { read, page } of requests) + assert.deepEqual(yield* read.pipe(Effect.withTracer(tracer)), page); + assert.notInclude(spans, "ProjectionStore.readTimelineWindow"); + } + assert.isAtLeast(foldedGroups, 2); + assert.isAbove(windowReads, 60); }), ); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 4ccb6bbf85ad8..d3c55b6d85715 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -90,6 +90,7 @@ import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; import type * as Statement from "effect/sql/Statement"; @@ -98,6 +99,7 @@ import { MCP_APP_OUTPUT_KEY } from "@t3tools/shared/mcpApp"; import { threadHtmlRenderAttachmentIds } from "../attachmentStore.ts"; import { readableSearchText } from "./messageSearchIndex.ts"; import { + isFoldableWorkItem, isThreadHistoryUserTurn, isConversationHistoryItem, THREAD_HISTORY_MAX_RAW_TURNS, @@ -114,6 +116,8 @@ import { THREAD_HISTORY_PAGE_POLICY, THREAD_HISTORY_INLINE_WORK_ITEM_LIMIT, THREAD_HISTORY_TURN_SNAPSHOT_ROW_LIMIT, + type SelectTimelinePageResult, + type ThreadHistoryPrefix, } from "./threadHistoryPaging.ts"; export class ProjectionStoreApplyEventError extends Schema.TaggedError()( @@ -1791,6 +1795,7 @@ export function threadShellFromProjection( lastVisitedAt: projection.thread.lastVisitedAt, opens: projection.thread.opens ?? null, titleRegeneration: projection.thread.titleRegeneration ?? null, + lastTitleRegeneration: projection.thread.lastTitleRegeneration ?? null, limitRecovery: projection.thread.limitRecovery ?? null, deletedAt: projection.thread.deletedAt, }; @@ -2087,6 +2092,7 @@ function shellFromState(input: { lastVisitedAt: input.state.thread.lastVisitedAt, opens: input.state.thread.opens ?? null, titleRegeneration: input.state.thread.titleRegeneration ?? null, + lastTitleRegeneration: input.state.thread.lastTitleRegeneration ?? null, limitRecovery: input.state.thread.limitRecovery ?? null, deletedAt: input.state.thread.deletedAt, }; @@ -6451,6 +6457,459 @@ export const layer: Layer.Layer = readTimelineIndex(threadId, new Set()).pipe(Effect.map((index) => index.visible)), ); + /** + * Index columns of the thread's own turn items that `where` selects, in timeline order. The + * same columns as `readTimelineIndex`, which reads every row and stays as it is. + */ + const readTimelineWindow = Effect.fn("ProjectionStore.readTimelineWindow")(function* ( + threadId: ThreadId, + runs: ProjectionRecords<"runs">["runs"], + includePersistentOutput: boolean, + where: Statement.Fragment, + limit: Statement.Fragment = sql``, + ) { + const rows = yield* sql<{ + turn_item_id: string; + run_id: string | null; + node_id: string | null; + parent_item_id: string | null; + type: OrchestrationV2TurnItem["type"]; + input_intent: NonNullable | null; + created_by: "user" | "agent" | "system" | null; + message_id: string | null; + status: OrchestrationV2TurnItem["status"]; + ordinal: number; + persistent_output: number; + attempt_id: string | null; + attempt_status: string | null; + }>`SELECT item.turn_item_id, item.run_id, item.node_id, item.parent_item_id, item.type, item.status, item.ordinal, + ${includePersistentOutput ? sql`attempt.attempt_id` : sql`NULL`} AS attempt_id, + ${includePersistentOutput ? sql`attempt.status` : sql`NULL`} AS attempt_status, + ${ + includePersistentOutput ? sql`CASE WHEN ${inlineWorkOutput} THEN 1 ELSE 0 END` : sql`0` + } AS persistent_output, + CASE WHEN item.type = 'user_message' THEN json_extract(item.payload_json, '$.inputIntent') END AS input_intent, + CASE WHEN item.type = 'user_message' THEN json_extract(item.payload_json, '$.createdBy') END AS created_by, + CASE WHEN item.type IN ('user_message', 'assistant_message') THEN json_extract(item.payload_json, '$.messageId') END AS message_id + FROM orchestration_v2_projection_turn_items AS item + ${ + includePersistentOutput + ? sql`LEFT JOIN orchestration_v2_projection_nodes AS node ON node.node_id = item.node_id + LEFT JOIN orchestration_v2_projection_run_attempts AS attempt ON attempt.attempt_id = ( + SELECT attempt_id FROM orchestration_v2_projection_run_attempts + WHERE run_id = item.run_id AND root_node_id = COALESCE(node.root_node_id, item.node_id) + ORDER BY attempt_ordinal DESC LIMIT 1 + )` + : sql`` + } + WHERE item.thread_id = ${threadId} ${where} + ORDER BY item.ordinal ASC, item.turn_item_id ASC ${limit}`; + const runStatuses = new Map(runs.map((run) => [String(run.id), run.status])); + return rows.map((row): TimelineIndexItem => ({ + id: TurnItemId.make(row.turn_item_id), + threadId, + runId: row.run_id === null ? null : RunId.make(row.run_id), + nodeId: row.node_id === null ? null : NodeId.make(row.node_id), + parentItemId: row.parent_item_id === null ? null : TurnItemId.make(row.parent_item_id), + type: row.type, + status: row.status, + ordinal: row.ordinal, + runStatus: row.run_id === null ? undefined : runStatuses.get(row.run_id), + attemptId: row.attempt_id, + attemptStatus: row.attempt_status, + persistentOutput: row.persistent_output === 1, + ...(row.input_intent === null ? {} : { inputIntent: row.input_intent }), + ...(row.created_by === null ? {} : { createdBy: row.created_by }), + ...(row.message_id === null ? {} : { messageId: MessageId.make(row.message_id) }), + })); + }); + const localTimelineRow = (item: TimelineIndexItem): TimelineIndexRow => ({ + sourceThreadId: item.threadId, + sourceItemId: item.id, + visibility: "local", + item, + }); + + /** + * Reads parts of a thread's own timeline without indexing all of it. Null when callers read + * the full index instead: the thread shows fork ancestry, so its rows come from other threads, + * or a full index of this snapshot is cached already. + */ + const openLocalTimeline = Effect.fn("ProjectionStore.openLocalTimeline")(function* ( + threadId: ThreadId, + includePersistentOutput = false, + ) { + // A read that only the full index can answer left it cached, and it answers faster than + // a window. The key is the one `readSnapshotTimelineIndex` uses. + const cached = timelineIndexes.get( + `${includePersistentOutput ? "work" : "plain"}:${threadId}`, + ); + if ( + cached !== undefined && + (yield* latestThreadEventSequence(threadId, cached.index.threadIds)) === cached.sequence + ) + return null; + // Checked in SQL, so a fork loads no runs and no thread here before the full index does. + const ownRowsOnly = yield* sql` + SELECT 1 FROM orchestration_v2_projection_threads + WHERE thread_id = ${threadId} + AND NOT (json_extract(payload_json, '$.forkedFrom.type') IS 'run' + AND json_extract(payload_json, '$.lineage.sideChat') IS NOT 1)`; + if (ownRowsOnly.length === 0) return null; + const records = yield* getThreadRecords(threadId, ["runs", "attempts"]); + if (inheritedRunFork(records.thread) !== null) return null; + const superseded = records.attempts.filter((attempt) => attempt.status === "superseded"); + const stopRequests = + superseded.length === 0 + ? [] + : yield* sql<{ run_id: string | null }>` + SELECT DISTINCT run_id FROM orchestration_v2_projection_turn_items + WHERE thread_id = ${threadId} AND type = 'run_interrupt_request'`; + const isVisible = createOrchestrationV2TurnItemVisibility({ + runs: records.runs, + attempts: records.attempts, + items: stopRequests.map((row) => ({ + type: "run_interrupt_request" as const, + runId: row.run_id === null ? null : RunId.make(row.run_id), + nodeId: null, + })), + }); + // Only these runs can hide rows: every row of a rolled-back run, the queued turn of a + // cancelled run, and the stop result of a replaced attempt. So the hidden rows are found + // without reading the thread. + const stoppedRuns = new Set(stopRequests.map((row) => row.run_id)); + const runsWithStatus = (status: "rolled_back" | "cancelled") => + records.runs.flatMap((run) => (run.status === status ? [String(run.id)] : [])); + const rolledBack = runsWithStatus("rolled_back"); + const cancelled = runsWithStatus("cancelled"); + const steered = [...new Set(superseded.map((attempt) => String(attempt.runId)))].filter( + (runId) => !stoppedRuns.has(runId) && !rolledBack.includes(runId), + ); + type HiddenCandidate = { + turn_item_id: string; + run_id: string; + node_id: string | null; + type: OrchestrationV2TurnItem["type"]; + ordinal: number; + input_intent: NonNullable | null; + }; + const candidateColumns = sql`item.turn_item_id, item.run_id, item.node_id, item.type, + item.ordinal, CASE WHEN item.type = 'user_message' + THEN json_extract(item.payload_json, '$.inputIntent') END AS input_intent`; + const [rolledBackRows, conversationRows] = yield* Effect.all([ + rolledBack.length === 0 + ? Effect.succeed([]) + : sql` + SELECT ${candidateColumns} + FROM json_each(${encodeIdList(rolledBack)}) AS wanted + CROSS JOIN orchestration_v2_projection_turn_items AS item + INDEXED BY orchestration_v2_projection_turn_items_thread_run_idx + ON item.thread_id = ${threadId} AND item.run_id = wanted.value`, + // The conversation index holds the type and run of these rows, so only the matches are + // fetched. Through the run index, every row of each cancelled run would be. + cancelled.length + steered.length === 0 + ? Effect.succeed([]) + : sql` + SELECT ${candidateColumns} + FROM orchestration_v2_projection_turn_items AS item + INDEXED BY orchestration_v2_projection_turn_items_conversation_idx + WHERE item.thread_id = ${threadId} + AND item.type NOT IN ${CONVERSATION_INDEX_EXCLUDED_TYPES} + AND ((item.type = 'user_message' + AND item.run_id IN (SELECT value FROM json_each(${encodeIdList(cancelled)}))) + OR (item.type = 'run_interrupt_result' + AND item.run_id IN (SELECT value FROM json_each(${encodeIdList(steered)}))))`, + ]); + const hidden = [...rolledBackRows, ...conversationRows].filter( + (row) => + !isVisible({ + type: row.type, + runId: RunId.make(row.run_id), + nodeId: row.node_id === null ? null : NodeId.make(row.node_id), + ...(row.input_intent === null ? {} : { inputIntent: row.input_intent }), + }), + ); + /** Counts the visible rows that sort before the given ordinal and item id. */ + const visibleBefore = Effect.fn("ProjectionStore.countVisibleTimelineRows")(function* ( + ordinal: number, + itemId = "", + ) { + const rows = yield* sql<{ count: number }>` + SELECT COUNT(*) AS count FROM orchestration_v2_projection_turn_items + WHERE thread_id = ${threadId} AND (ordinal, turn_item_id) < (${ordinal}, ${itemId})`; + const hiddenBefore = hidden.filter( + (row) => + row.ordinal < ordinal || + (row.ordinal === ordinal && + Buffer.compare(Buffer.from(row.turn_item_id), Buffer.from(itemId)) < 0), + ); + return (rows[0]?.count ?? 0) - hiddenBefore.length; + }); + return { + records, + isVisible, + hidden, + visibleBefore, + read: (where: Statement.Fragment, limit?: Statement.Fragment) => + readTimelineWindow(threadId, records.runs, includePersistentOutput, where, limit), + }; + }); + type LocalTimeline = NonNullable>>; + type IndexedTimelineRow = TimelineIndexRow & { + readonly position: number; + readonly canonicalPosition: number; + }; + + /** True when a visible user turn starts before the ordinal. Reads the nearest user messages. */ + const olderUserTurn = (local: LocalTimeline, ordinal: number) => + sql<{ + run_id: string | null; + node_id: string | null; + input_intent: NonNullable; + }>` + SELECT item.run_id, item.node_id, + json_extract(item.payload_json, '$.inputIntent') AS input_intent + FROM orchestration_v2_projection_turn_items AS item + INDEXED BY orchestration_v2_projection_turn_items_user_message_idx + WHERE item.thread_id = ${local.records.thread.id} AND item.type = 'user_message' + AND item.ordinal < ${ordinal} + AND json_extract(item.payload_json, '$.inputIntent') IN ('turn_start', 'queued_turn') + AND json_extract(item.payload_json, '$.createdBy') = 'user' + ORDER BY item.ordinal DESC, item.turn_item_id DESC + LIMIT ${local.hidden.length + 1}`.pipe( + Effect.map((rows) => + rows.some((row) => + local.isVisible({ + type: "user_message", + runId: row.run_id === null ? null : RunId.make(row.run_id), + nodeId: row.node_id === null ? null : NodeId.make(row.node_id), + inputIntent: row.input_intent, + }), + ), + ), + ); + + /** + * A notification starts a turn only as its run's first input. For each run whose first input + * in `rows` is a notification, this finds whether an input row sits before the ordinal. + */ + const runsStartedBefore = Effect.fn("ProjectionStore.runsStartedBefore")(function* ( + local: LocalTimeline, + ordinal: number, + rows: ReadonlyArray, + ) { + const seen = new Set(); + const unknown = new Set(); + for (const { item } of rows) { + if (item.runId === null) continue; + if (item.type !== "user_message" && item.type !== "notification") continue; + if (item.type === "notification" && !seen.has(item.runId)) unknown.add(item.runId); + seen.add(item.runId); + } + if (unknown.size === 0) return new Set(); + const counts = yield* sql<{ run_id: string; inputs: number }>` + SELECT wanted.value AS run_id, ( + SELECT COUNT(*) FROM orchestration_v2_projection_turn_items AS input + INDEXED BY orchestration_v2_projection_turn_items_conversation_idx + WHERE input.thread_id = ${local.records.thread.id} + AND input.ordinal >= ( + SELECT MIN(ordinal) FROM orchestration_v2_projection_turn_items + WHERE run_id = wanted.value + ) + AND input.ordinal < ${ordinal} + AND input.type NOT IN ${CONVERSATION_INDEX_EXCLUDED_TYPES} + AND input.type IN ('user_message', 'notification') + AND input.run_id = wanted.value + ) AS inputs + FROM json_each(${encodeIdList([...unknown])}) AS wanted`; + const isHiddenInput = (row: LocalTimeline["hidden"][number], runId: string) => + row.run_id === runId && + row.ordinal < ordinal && + (row.type === "user_message" || row.type === "notification"); + return new Set( + counts.flatMap((row) => + row.inputs > local.hidden.filter((hidden) => isHiddenInput(hidden, row.run_id)).length + ? [row.run_id] + : [], + ), + ); + }); + + /** + * Selects an older history page from the rows near its cursor. The window grows until the + * page ends inside rows whose inputs are all known, so `select` gives the page it gives on + * the full index. Null when the cursor names no visible row, which needs the full index. + */ + const selectHistoryPageInWindow = Effect.fn("ProjectionStore.selectHistoryPageInWindow")( + function* < + Selection extends { + readonly page: SelectTimelinePageResult; + readonly historyItems: ReadonlyArray; + }, + >( + local: LocalTimeline, + input: { + readonly cursor: string; + readonly throughEntryId: string | undefined; + readonly workMode: "deferred" | "work" | undefined; + }, + select: ( + indexed: ReadonlyArray, + prefix?: ThreadHistoryPrefix, + ) => Effect.Effect, + ) { + const threadId = local.records.thread.id; + const decoded = Result.try(() => decodeThreadHistoryCursor(input.cursor)); + if (Result.isFailure(decoded) || decoded.success.st !== threadId) return null; + const cursor = decoded.success; + // Looked up by key alone: with the thread in the query, SQLite scans the thread's index. + const ends = (yield* sql<{ turn_item_id: string; thread_id: string; ordinal: number }>` + SELECT turn_item_id, thread_id, ordinal FROM orchestration_v2_projection_turn_items + WHERE turn_item_id IN (${cursor.si}, ${input.throughEntryId ?? cursor.si})`).filter( + (row) => row.thread_id === threadId, + ); + const upper = ends.find((row) => row.turn_item_id === cursor.si)?.ordinal; + if (upper === undefined) return null; + /* Runs for each window this operation tries; the operation owns the span. */ + const indexFrom = Effect.fnUntraced(function* ( + items: ReadonlyArray, + from: number | null, + ) { + const base = from === null ? 0 : yield* local.visibleBefore(from); + return items.filter(local.isVisible).map((item, offset): IndexedTimelineRow => ({ + ...localTimelineRow(item), + position: base + offset, + canonicalPosition: base + offset, + })); + }); + const isCursorRow = (row: TimelineIndexRow) => row.sourceItemId === cursor.si; + // The ordinals come from the stop request index, so this does not walk the thread. + const interruptRequests = local + .read( + sql`AND item.type = 'run_interrupt_request' AND item.ordinal IN ( + SELECT ordinal FROM orchestration_v2_projection_turn_items + INDEXED BY orchestration_v2_projection_turn_items_stop_request_idx + WHERE thread_id = ${threadId} AND type = 'run_interrupt_request')`, + ) + .pipe(Effect.flatMap((items) => indexFrom(items, null))); + + if (input.workMode === "work") { + // A work group lies between its first row and the cursor, so that range is the read. + const lower = ends.find((row) => row.turn_item_id === input.throughEntryId)?.ordinal; + if (lower === undefined) return null; + const indexed = yield* indexFrom( + yield* local.read(sql`AND item.ordinal >= ${lower} AND item.ordinal <= ${upper}`), + lower, + ); + if (!indexed.some(isCursorRow)) return null; + if (!indexed.some((row) => row.sourceItemId === input.throughEntryId)) return null; + return { + indexed, + selection: yield* select(indexed), + olderUserTurn: olderUserTurn(local, lower), + interruptRequests, + }; + } + + const rowsBelow = (ordinal: number, count: number) => + sql<{ ordinal: number }>` + SELECT ordinal FROM orchestration_v2_projection_turn_items + WHERE thread_id = ${threadId} AND ordinal < ${ordinal} + ORDER BY ordinal DESC LIMIT 1 OFFSET ${count - 1}`.pipe( + Effect.map((rows) => rows[0]?.ordinal ?? null), + ); + // `trusted` is the lowest ordinal the page may reach. `lower` can sit below it, because + // a run that folds work is read whole. + let step = THREAD_HISTORY_TURN_SNAPSHOT_ROW_LIMIT; + let trusted = yield* rowsBelow(upper, step); + let lower = trusted; + let higher = upper; + let items = yield* local.read( + lower === null + ? sql`AND item.ordinal <= ${upper}` + : sql`AND item.ordinal >= ${lower} AND item.ordinal <= ${upper}`, + ); + const wholeRuns = new Set(); + while (true) { + if (input.workMode === "deferred") { + // Folding needs every row of a run: its stop and error rows, and its group sizes. + const folding = new Set(); + for (const item of items) { + if (item.runId === null || wholeRuns.has(item.runId)) continue; + if (item.ordinal > upper || (trusted !== null && item.ordinal < trusted)) continue; + if (isFoldableWorkItem(item) && local.isVisible(item)) folding.add(item.runId); + } + if (folding.size > 0) { + const runs = encodeIdList([...folding]); + const [extent] = yield* sql<{ lower: number; higher: number }>` + SELECT MIN(run.lower) AS lower, MAX(run.higher) AS higher FROM ( + SELECT + (SELECT MIN(ordinal) FROM orchestration_v2_projection_turn_items + WHERE run_id = wanted.value) AS lower, + (SELECT MAX(ordinal) FROM orchestration_v2_projection_turn_items + WHERE run_id = wanted.value) AS higher + FROM json_each(${runs}) AS wanted + ) AS run`; + if (extent !== undefined && lower !== null && extent.lower < lower) { + const below = yield* local.read( + sql`AND item.ordinal >= ${extent.lower} AND item.ordinal < ${lower}`, + ); + items = below.concat(items); + lower = extent.lower; + } + if (extent !== undefined && extent.higher > higher) { + const newer = yield* local.read( + sql`AND item.ordinal > ${higher} AND item.ordinal <= ${extent.higher}`, + ); + items = items.concat(newer); + higher = extent.higher; + } + for (const runId of folding) wholeRuns.add(runId); + } + } + const indexed = yield* indexFrom(items, lower); + const end = indexed.findIndex(isCursorRow); + if (end < 0) return null; + const older = lower === null ? Effect.succeed(false) : olderUserTurn(local, lower); + const prefix: ThreadHistoryPrefix | undefined = + lower === null + ? undefined + : { + hasUserTurn: indexed + .slice(0, end) + .some((row) => isThreadHistoryUserTurn(row.item)) + ? false + : yield* older, + startedRuns: yield* runsStartedBefore(local, lower, indexed), + }; + const selection = yield* select(indexed, prefix); + // Without its row the cursor falls back to a position, which only the full index has. + if (!selection.historyItems.some(isCursorRow)) return null; + const oldest = selection.page.oldestScanned; + if ( + lower === null || + (trusted !== null && + oldest !== undefined && + oldest !== selection.historyItems[0] && + oldest.item.ordinal >= trusted) + ) { + return { indexed, selection, olderUserTurn: older, interruptRequests }; + } + step *= 2; + trusted = trusted === null ? null : yield* rowsBelow(trusted, step); + if (trusted === null || trusted < lower) { + const below = yield* local.read( + trusted === null + ? sql`AND item.ordinal < ${lower}` + : sql`AND item.ordinal >= ${trusted} AND item.ordinal < ${lower}`, + ); + items = below.concat(items); + lower = trusted; + } + } + }, + ); + const getThreadHistoryPage: ProjectionStoreV2Shape["getThreadHistoryPage"] = ( threadId, cursor, @@ -6461,8 +6920,15 @@ export const layer: Layer.Layer = sql .withTransaction( Effect.gen(function* () { - const index = yield* readSnapshotTimelineIndex(threadId, workMode !== undefined); - if (index.records.thread.deletedAt !== null) + const withWork = workMode !== undefined; + // A jump to a target entry selects from the whole index. + const local = + (workMode === "work") === (throughEntryId !== undefined) + ? yield* openLocalTimeline(threadId, withWork) + : null; + const full = + local === null ? yield* readSnapshotTimelineIndex(threadId, withWork) : null; + if ((local ?? full)?.records.thread.deletedAt !== null) return yield* new ProjectionStoreThreadNotFoundError({ threadId }); const revisions = yield* sql<{ sequence: number; @@ -6470,100 +6936,143 @@ export const layer: Layer.Layer = FROM orchestration_events WHERE application_event_version = 2 AND aggregate_kind = 'thread' AND stream_id = ${threadId}`; const snapshotSequence = revisions[0]?.sequence ?? 0; - const indexed = index.visible.map((row, position) => ({ - ...row, - position, - canonicalPosition: position, - })); - const { olderPolicy, cursorPosition } = yield* Effect.try({ - try: () => ({ - olderPolicy: olderHistoryPagePolicy({ items: indexed, cursor, throughEntryId }), - // The cursor's own row, or the row its stale position falls back to. - cursorPosition: Math.min( - findCursorEndIndex(indexed, decodeThreadHistoryCursor(cursor)), - indexed.length - 1, - ), - }), - catch: (cause) => new ProjectionStoreReadError({ threadId, cause }), - }); - const selectPage = (rows: typeof indexed) => + const select = ( + indexed: ReadonlyArray, + prefix?: ThreadHistoryPrefix, + ) => Effect.try({ - try: () => - workMode === "work" - ? selectDeferredWorkPage({ - items: rows, - cursor, - throughEntryId, - snapshotSequence, - rowEncodedBytes: () => 0, - }) - : selectHistoryPageFromCursor({ - items: workMode === "deferred" ? deferWorkHistoryRows(rows) : rows, - cursor, - snapshotSequence, - rowEncodedBytes: () => 0, - policy: olderPolicy, - }), + try: () => { + const historyItems = + workMode === "deferred" ? deferWorkHistoryRows(indexed) : indexed; + const policy = olderHistoryPagePolicy({ items: indexed, cursor, throughEntryId }); + // Folding can hide the cursor's row: a snapshot folds no work in a thread with no + // user turn. The page then ends at the first row kept from the cursor on. + const cursorRow = + indexed[findCursorEndIndex(indexed, decodeThreadHistoryCursor(cursor))]; + const end = + cursorRow === undefined + ? -1 + : historyItems.findIndex( + (row) => row.canonicalPosition >= cursorRow.canonicalPosition, + ); + const page = + workMode === "work" + ? selectDeferredWorkPage({ + items: indexed, + cursor, + throughEntryId, + snapshotSequence, + rowEncodedBytes: () => 0, + }) + : selectHistoryPageFromCursor({ + items: historyItems, + cursor, + exclusiveEndIndex: end === -1 ? historyItems.length : end, + snapshotSequence, + rowEncodedBytes: () => 0, + policy, + prefix, + }); + return { policy, page, historyItems }; + }, catch: (cause) => new ProjectionStoreReadError({ threadId, cause }), }); - let page = yield* selectPage(indexed); - // Inline output is found by scanning payloads, which costs a whole long thread several - // seconds. Scan only the runs the page spans, then select again with what they hold. - const scannedRuns = new Set(); - const persistentOutputs = new Set(); - while (workMode !== undefined) { - // Rows hidden in a work group move the page, so the scan always reaches the cursor. - const span = [...page.items.slice(0, 1), ...page.items.slice(-1)].map( - (row) => row.canonicalPosition, - ); - if (cursorPosition >= 0) span.push(cursorPosition); - if (span.length === 0) break; - const runs = new Map( - // A work page holds rows of one run, which can be the rows that have no run. - (workMode === "work" - ? page.items.slice(0, 1) - : indexed.slice(Math.min(...span), Math.max(...span) + 1) - ).flatMap(({ sourceThreadId, item }) => - (workMode === "work" || - (item.runId !== null && - (item.runStatus === "completed" || item.attemptStatus === "superseded"))) && - !scannedRuns.has(`${sourceThreadId}:${item.runId}`) - ? [ - [ - `${sourceThreadId}:${item.runId}`, - { threadId: sourceThreadId, id: item.runId }, - ] as const, - ] - : [], - ), - ); - if (runs.size === 0) break; - for (const run of runs.keys()) scannedRuns.add(run); - const found = yield* sql<{ thread_id: string; turn_item_id: string }>` + const window = + local === null + ? null + : yield* selectHistoryPageInWindow( + local, + { cursor, throughEntryId, workMode }, + select, + ); + const whole = Effect.gen(function* () { + const index = full ?? (yield* readSnapshotTimelineIndex(threadId, withWork)); + const indexed = index.visible.map((row, position): IndexedTimelineRow => ({ + ...row, + position, + canonicalPosition: position, + })); + let selection = yield* select(indexed); + // The full index does not say which rows hold inline output: finding it scans + // payloads, which costs a whole long thread several seconds. Scan only the runs + // the page spans, then select again with what they hold. + const scannedRuns = new Set(); + const persistentOutputs = new Set(); + // Rows hidden in a work group move the page, so the scan always reaches the + // cursor's own row, or the row its stale position falls back to. + const cursorPosition = + workMode === undefined + ? -1 + : Math.min( + findCursorEndIndex(indexed, decodeThreadHistoryCursor(cursor)), + indexed.length - 1, + ); + while (workMode !== undefined) { + const { page } = selection; + const span = [...page.items.slice(0, 1), ...page.items.slice(-1)].map( + (row) => row.canonicalPosition, + ); + if (cursorPosition >= 0) span.push(cursorPosition); + if (span.length === 0) break; + const runs = new Map( + // A work page holds rows of one run, which can be the rows that have no run. + (workMode === "work" + ? page.items.slice(0, 1) + : indexed.slice(Math.min(...span), Math.max(...span) + 1) + ).flatMap(({ sourceThreadId, item }) => + (workMode === "work" || + (item.runId !== null && + (item.runStatus === "completed" || item.attemptStatus === "superseded"))) && + !scannedRuns.has(`${sourceThreadId}:${item.runId}`) + ? [ + [ + `${sourceThreadId}:${item.runId}`, + { threadId: sourceThreadId, id: item.runId }, + ] as const, + ] + : [], + ), + ); + if (runs.size === 0) break; + for (const run of runs.keys()) scannedRuns.add(run); + const found = yield* sql<{ thread_id: string; turn_item_id: string }>` SELECT item.thread_id, item.turn_item_id FROM json_each(${yield* encodeTimelineSources([...runs.values()])}) AS wanted CROSS JOIN orchestration_v2_projection_turn_items AS item ON item.thread_id = json_extract(wanted.value, '$.threadId') AND item.run_id IS json_extract(wanted.value, '$.id') WHERE item.status = 'completed' AND ${inlineWorkOutput}`; - if (found.length === 0) break; - for (const row of found) - persistentOutputs.add(`${row.thread_id}:${row.turn_item_id}`); - page = yield* selectPage( - indexed.map((row) => - persistentOutputs.has(`${row.sourceThreadId}:${row.sourceItemId}`) - ? { ...row, item: { ...row.item, persistentOutput: true } } - : row, - ), - ); - } - const policy = workMode === "work" ? THREAD_HISTORY_PAGE_POLICY : olderPolicy; + if (found.length === 0) break; + for (const row of found) + persistentOutputs.add(`${row.thread_id}:${row.turn_item_id}`); + selection = yield* select( + indexed.map((row) => + persistentOutputs.has(`${row.sourceThreadId}:${row.sourceItemId}`) + ? { ...row, item: { ...row.item, persistentOutput: true } } + : row, + ), + ); + } + return { + indexed, + selection, + olderUserTurn: Effect.succeed(false), + interruptRequests: Effect.succeed(indexed), + }; + }); + const { indexed, selection, olderUserTurn, interruptRequests } = + window ?? (yield* whole); + const { page } = selection; + const policy = workMode === "work" ? THREAD_HISTORY_PAGE_POLICY : selection.policy; const end = (page.items.at(-1)?.canonicalPosition ?? -1) + 1; - const hasUserTurns = index.visible - .slice(0, end) - .some((row) => isThreadHistoryUserTurn(row.item)); + const hasUserTurns = + conversationOnly === true && + (indexed.some( + (row) => row.canonicalPosition < end && isThreadHistoryUserTurn(row.item), + ) || + (yield* olderUserTurn)); const materialize = Effect.fn("ProjectionStore.materializeHistoryRows")(function* ( - rows: ReadonlyArray<(typeof indexed)[number]>, + rows: ReadonlyArray, ) { if (rows.length === 0) return []; const sources = yield* encodeTimelineSources( @@ -6606,7 +7115,7 @@ export const layer: Layer.Layer = ); }); const items = yield* materialize( - conversationOnly && hasUserTurns + hasUserTurns ? page.items.filter((row) => isConversationHistoryItem(row.item)) : page.items, ); @@ -6614,7 +7123,14 @@ export const layer: Layer.Layer = const requests = workMode === "work" ? [] - : yield* materialize(missingInterruptRequests(indexed, bounded.items)); + : yield* materialize( + missingInterruptRequests( + bounded.items.some((row) => row.item.type === "run_interrupt_result") + ? yield* interruptRequests + : [], + bounded.items, + ), + ); const pageItems = [...requests, ...bounded.items].map((row, position) => ({ ...row, position, @@ -6631,39 +7147,118 @@ export const layer: Layer.Layer = ) .pipe(Effect.mapError(controlReadError(threadId))); + /** + * The rows `getTimelinePage` matches, cut after the first `limit + 1`, with their positions + * in the full visible index. Reads only the rows from the start position to the page end. + */ + const matchLocalTimelineRows = Effect.fn("ProjectionStore.matchLocalTimelineRows")(function* ( + local: LocalTimeline, + options: ProjectionTimelinePageOptions, + ) { + const threadId = local.records.thread.id; + const totals = yield* sql<{ count: number }>` + SELECT COUNT(*) AS count FROM orchestration_v2_projection_turn_items + WHERE thread_id = ${threadId}`; + const totalItems = (totals[0]?.count ?? 0) - local.hidden.length; + if (options.itemId !== undefined) { + const found = (yield* local.read(sql`AND item.turn_item_id = ${options.itemId}`)).filter( + local.isVisible, + ); + const matching = yield* Effect.forEach(found, (item) => + local + .visibleBefore(item.ordinal, item.id) + .pipe(Effect.map((position) => ({ ...localTimelineRow(item), position }))), + ); + return { matching, totalItems }; + } + const afterPosition = options.afterPosition ?? -1; + const firstPosition = Math.max(afterPosition + 1, 0); + // The row at this raw offset sorts at or before the first wanted row: hidden rows only + // push visible rows to later offsets. + const starts = yield* sql<{ ordinal: number }>` + SELECT ordinal FROM orchestration_v2_projection_turn_items + WHERE thread_id = ${threadId} + ORDER BY ordinal ASC, turn_item_id ASC LIMIT 1 OFFSET ${firstPosition}`; + const start = starts[0]?.ordinal; + if (start === undefined) return { matching: [], totalItems }; + const base = yield* local.visibleBefore(start); + const hiddenAfter = local.hidden.filter((row) => row.ordinal >= start).length; + const messagesOnly = options.view !== "activity"; + const candidates = (yield* local.read( + messagesOnly + ? sql`AND item.ordinal >= ${start} + AND item.type IN ('user_message', 'assistant_message', 'proposed_plan')` + : sql`AND item.ordinal >= ${start}`, + sql`LIMIT ${firstPosition - base + Math.min(options.limit, totalItems) + 1 + hiddenAfter}`, + )).filter(local.isVisible); + const positions = new Map(); + const last = candidates.at(-1); + if (messagesOnly && last !== undefined) { + const hiddenIds = new Set(local.hidden.map((row) => row.turn_item_id)); + const span = yield* sql<{ turn_item_id: string }>` + SELECT turn_item_id FROM orchestration_v2_projection_turn_items + WHERE thread_id = ${threadId} AND ordinal >= ${start} AND ordinal <= ${last.ordinal} + ORDER BY ordinal ASC, turn_item_id ASC`; + for (const row of span) { + if (!hiddenIds.has(row.turn_item_id)) + positions.set(row.turn_item_id, base + positions.size); + } + } + const matching = candidates + .map((item, offset) => ({ + ...localTimelineRow(item), + position: messagesOnly ? (positions.get(item.id) ?? -1) : base + offset, + })) + .filter((row) => row.position > afterPosition); + return { matching, totalItems }; + }); + const getTimelinePage: ProjectionStoreV2Shape["getTimelinePage"] = (threadId, options) => sql .withTransaction( Effect.gen(function* () { - const index = yield* readSnapshotTimelineIndex(threadId, false); - const attachmentOwners = - options.attachmentId === undefined - ? undefined - : new Set( - (yield* sql<{ thread_id: string; turn_item_id: string }>` + const local = + options.attachmentId === undefined && + Number.isSafeInteger(options.limit) && + options.limit >= 0 && + Number.isSafeInteger(options.afterPosition ?? -1) + ? yield* openLocalTimeline(threadId) + : null; + const whole = Effect.gen(function* () { + const index = yield* readSnapshotTimelineIndex(threadId, false); + const attachmentOwners = + options.attachmentId === undefined + ? undefined + : new Set( + (yield* sql<{ thread_id: string; turn_item_id: string }>` SELECT item.thread_id, item.turn_item_id FROM orchestration_v2_projection_turn_items AS item, json_each(item.payload_json, '$.attachments') AS attachment WHERE item.thread_id IN ${sql.in([...new Set(index.visible.map((row) => row.sourceThreadId))])} AND item.type = 'user_message' AND json_extract(attachment.value, '$.id') = ${options.attachmentId}`).map( - (row) => `${row.thread_id}:${row.turn_item_id}`, - ), - ); - const matching = index.visible - .map((row, position) => ({ ...row, position })) - .filter((row) => - options.itemId === undefined - ? row.position > (options.afterPosition ?? -1) && - (options.view === "activity" || - ["user_message", "assistant_message", "proposed_plan"].includes( - row.item.type, - )) - : row.sourceItemId === options.itemId, - ) - .filter( - (row) => attachmentOwners?.has(`${row.sourceThreadId}:${row.sourceItemId}`) ?? true, - ); + (row) => `${row.thread_id}:${row.turn_item_id}`, + ), + ); + const matching = index.visible + .map((row, position) => ({ ...row, position })) + .filter((row) => + options.itemId === undefined + ? row.position > (options.afterPosition ?? -1) && + (options.view === "activity" || + ["user_message", "assistant_message", "proposed_plan"].includes( + row.item.type, + )) + : row.sourceItemId === options.itemId, + ) + .filter( + (row) => + attachmentOwners?.has(`${row.sourceThreadId}:${row.sourceItemId}`) ?? true, + ); + return { matching, totalItems: index.visible.length }; + }); + const { matching, totalItems } = + local === null ? yield* whole : yield* matchLocalTimelineRows(local, options); const page = matching.slice(0, options.limit); const sources = yield* encodeTimelineSources( page @@ -6713,11 +7308,7 @@ export const layer: Layer.Layer = }; }), ); - return { - items, - totalItems: index.visible.length, - hasMore: matching.length > page.length, - }; + return { items, totalItems, hasMore: matching.length > page.length }; }), ) .pipe( diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index ac2692907cbbc..17d40cf05162e 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -272,6 +272,7 @@ it.each([ function makeLocalCommandHarness(input: { readonly text: string; readonly nativeGoals?: boolean; + readonly goalDriver?: "opencode" | "antigravity"; readonly worktreePath?: string; readonly worktreesDir?: string; readonly workspaceRoot?: string; @@ -341,7 +342,9 @@ function makeLocalCommandHarness(input: { }; const providerThread: OrchestrationV2ThreadProjection["providerThreads"][number] = { id: providerThreadId, - driver: ProviderDriverKind.make(input.nativeGoals === undefined ? "codex" : "opencode"), + driver: ProviderDriverKind.make( + input.nativeGoals === undefined ? "codex" : (input.goalDriver ?? "opencode"), + ), providerInstanceId: newInstanceId, providerSessionId, appThreadId: threadId, @@ -1366,12 +1369,18 @@ effectIt.effect.each([ }), ); -effectIt.effect.each([false, true])( - "OpenCode goal prompts defer switched-provider history only with native support: %s", - (nativeGoals) => +effectIt.effect.each([ + { goalDriver: "opencode", nativeGoals: false }, + { goalDriver: "opencode", nativeGoals: true }, + { goalDriver: "antigravity", nativeGoals: false }, + { goalDriver: "antigravity", nativeGoals: true }, +] as const)( + "$goalDriver goal prompts defer switched-provider history only with native support: $nativeGoals", + ({ goalDriver, nativeGoals }) => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "/goal all tests pass", + goalDriver, nativeGoals, sideChat: { contextRun: "failed", switchedProvider: true }, }); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 2de9fcbc70d9d..648e12e5a2aa8 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -873,8 +873,7 @@ export const layer: Layer.Layer< const goalDriver = session.driver === "codex" || session.driver === "claudeAgent" || - (session.driver === "opencode" && - session.providerSession.capabilities.turns.supportsNativeGoals === true); + session.providerSession.capabilities.turns.supportsNativeGoals === true; const goalCommand = goalDriver && parseGoalCommand(message) !== null; // The provider turn marks cancellation work delivered; restart continuations use their own text or resume natively. const noteContinuation = isRestartNoteContinuation( diff --git a/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts b/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts index 06b1e3d9f9f69..02a8e43c1d0e2 100644 --- a/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts +++ b/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts @@ -171,6 +171,7 @@ const missingSummary = Effect.fail( interface HarnessOptions { readonly invalidate?: PullRequestService.PullRequestService["Service"]["invalidate"]; + readonly batchesReads?: (input: PullRequestRef) => boolean; readonly snapshot: TestShellSnapshot; readonly summary?: ( input: PullRequestRef, @@ -228,6 +229,7 @@ const makeHarness = Effect.fn("makePullRequestSyncHarness")(function* (options: const layerDependencies = Layer.mergeAll( Layer.mock(PullRequestService.PullRequestService)({ withSharedProjectReads: (effect) => effect, + batchesReads: (input) => Effect.succeed(options.batchesReads?.(input) ?? true), summary, stack, invalidate: options.invalidate ?? (() => Effect.void), @@ -1224,6 +1226,110 @@ describe("PullRequestSyncReactor", () => { ), ); + it.effect("reads hosts that batch all at once and other hosts at the old sweep width", () => + Effect.scoped( + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const numbers = Array.from({ length: 60 }, (_, index) => index + 1); + const hostOf = (number: number) => (number <= 30 ? "github.com" : "gitlab.example.com"); + const batches = (input: PullRequestRef) => input.host === "github.com"; + const batched = yield* Ref.make(0); + const unbatched = yield* Ref.make(0); + const started = yield* Queue.unbounded(); + const release = yield* Deferred.make(); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot( + numbers.map((number) => + makeThread(`thread-${number}`, { + pullRequests: [makeLink(number, null, { host: hostOf(number) })], + }), + ), + ), + batchesReads: batches, + summary: (input) => { + const inFlight = batches(input) ? batched : unbatched; + return Ref.update(inFlight, (count) => count + 1).pipe( + Effect.andThen(Queue.offer(started, undefined)), + Effect.andThen(Deferred.await(release)), + Effect.andThen(Ref.update(inFlight, (count) => count - 1)), + Effect.as(makeSummary(input)), + ); + }, + }); + yield* Effect.gen(function* () { + const reactor = yield* PullRequestSyncReactor.PullRequestSyncReactor; + yield* reactor.start(); + yield* Deferred.succeed(fixture.activation, undefined); + yield* Queue.takeN(started, 55); + assert.strictEqual(yield* Ref.get(batched), 30); + assert.strictEqual(yield* Ref.get(unbatched), 25); + yield* Deferred.succeed(release, undefined); + yield* reactor.drain; + assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, numbers.length); + }).pipe(Effect.provide(fixture.layer)); + }), + ), + ); + + it.effect("reads a member a sibling flags while the sweep is full", () => + Effect.scoped( + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const stackOf = (layers: ReadonlyArray) => ({ + id: "9", + number: 9, + url: "https://github.com/owner/repository/stack/9", + base: "main", + layers: layers.map(stackLayer), + }); + // #50 is merged and not due until #1's stack read shows it a different layer list. + const merged = makeLink( + 50, + { state: "merged", mergedAt: NOW }, + { stack: { kind: "native", ...stackOf([50]) } }, + ); + const started = yield* Ref.make(0); + const full = yield* Deferred.make(); + const synced1 = yield* Deferred.make(); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([ + // Another host takes 24 of the 25 shared slots and #1 the last one. + ...Array.from({ length: 24 }, (_, index) => + makeThread(`thread-${index + 2}`, { + pullRequests: [makeLink(index + 2, null, { host: "gitlab.example.com" })], + }), + ), + makeThread("thread-1", { pullRequests: [makeLink(1)] }), + makeThread("thread-50", { pullRequests: [merged] }), + ]), + batchesReads: () => false, + // #1 reads once all 25 slots are taken; the other 24 hold theirs until #1 has synced. + summary: (input) => + Ref.updateAndGet(started, (count) => count + 1).pipe( + // Forked, so #1 resumes only after the sweep has handed out its next slot. + Effect.tap((count) => + count === 25 ? Effect.forkChild(Deferred.succeed(full, undefined)) : Effect.void, + ), + Effect.andThen( + input.number === 50 + ? Effect.void + : Deferred.await(input.number === 1 ? full : synced1), + ), + Effect.as(makeSummary(input)), + ), + stack: (input) => Effect.succeed(input.number === 1 ? stackOf([1, 50]) : null), + onSync: (command) => + command.number === 1 ? Deferred.succeed(synced1, undefined) : Effect.void, + }); + yield* Effect.gen(function* () { + yield* startAndSweep(fixture); + const read = (yield* Ref.get(fixture.summaryCalls)).map((ref) => ref.number); + assert.include(read, 50); + }).pipe(Effect.provide(fixture.layer)); + }), + ), + ); + it.effect("skips the stack read for a pull request the summary places in no stack", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts b/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts index 5590a20ce0198..7573a95bb4362 100644 --- a/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts @@ -183,6 +183,19 @@ interface LinkEntry { readonly link: ThreadPullRequestLink; } +const referenceOf = ({ thread, link }: LinkEntry) => ({ + projectId: thread.projectId, + host: normalizeThreadPullRequestKey(link).host, + repository: link.repository, + number: link.number, +}); + +/** Pauses and batching both belong to a project's host. */ +const pauseKeyOf = (entry: LinkEntry) => { + const { projectId, host } = referenceOf(entry); + return `${projectId}\0${host}`; +}; + /** Another layer of the stack `url` belongs to, in its host's canonical shape. */ function siblingChangeRequestUrl(url: string, number: number): string | null { if (!Number.isSafeInteger(number) || number < 1) return null; @@ -478,12 +491,7 @@ export const make = Effect.gen(function* () { const syncGroup = Effect.fnUntraced(function* (key: string, entries: ReadonlyArray) { const first = entries[0]!; - const ref = { - projectId: first.thread.projectId, - host: normalizeThreadPullRequestKey(first.link).host, - repository: first.link.repository, - number: first.link.number, - }; + const ref = referenceOf(first); const refreshRequested = requested.has(key); // A held merged summary is served without asking the host, so a snapshot still missing its // merge time has to drop it or the slow-cadence re-read would hand back the same gap. @@ -612,25 +620,63 @@ export const make = Effect.gen(function* () { return Effect.void; }), ); + const pools = { + // Wider than one summary batch, so reads that finish their cache checks at different + // times still share batches. + batched: { width: 100, reads: yield* Semaphore.make(100) }, + // One read per pull request, often a CLI process, so these keep the narrower width. + unbatched: { width: 25, reads: yield* Semaphore.make(25) }, + }; + const isPaused = (pauseKey: string, atMs: number) => (pausedUntil.get(pauseKey) ?? 0) > atMs; + // Judged once a slot is free, so a stack retry a sibling flags meanwhile still counts, and + // pauses set during the sweep apply at once. + const readIfDue = ( + key: string, + entries: ReadonlyArray, + pauseKey: string, + reads: Semaphore.Semaphore, + ) => + reads.withPermits(1)( + Effect.suspend(() => + isDue(key, entries, nowMs) + ? Clock.currentTimeMillis.pipe( + Effect.flatMap((startedAtMs) => + isPaused(pauseKey, startedAtMs) ? Effect.void : readGroup(key, entries, pauseKey), + ), + ) + : Effect.void, + ), + ); + const groupsByHost = Map.groupBy( + Array.from(groups).filter(([key]) => scope === "all" || requested.has(key)), + ([, entries]) => pauseKeyOf(entries[0]!), + ); yield* Effect.forEach( - groups, - ([key, entries]) => { - if (!((scope === "all" || requested.has(key)) && isDue(key, entries, nowMs))) { + groupsByHost, + ([pauseKey, hostGroups]) => { + // A host paused or with nothing due skips the lookup. Stack retries only flag groups on + // the flagging group's own host, so nothing on it becomes due this sweep. + if ( + isPaused(pauseKey, nowMs) || + !hostGroups.some(([key, entries]) => isDue(key, entries, nowMs)) + ) { return Effect.void; } - const first = entries[0]!; - const pauseKey = `${first.thread.projectId}\0${normalizeThreadPullRequestKey(first.link).host}`; - // Check pauses at each read so changes during the sweep apply immediately. - return Clock.currentTimeMillis.pipe( - Effect.flatMap((startedAtMs) => - (pausedUntil.get(pauseKey) ?? 0) > startedAtMs - ? Effect.void - : readGroup(key, entries, pauseKey), - ), + return pullRequests.batchesReads(referenceOf(hostGroups[0]![1][0]!)).pipe( + Effect.flatMap((batches) => { + const { width, reads } = batches ? pools.batched : pools.unbatched; + return Effect.forEach( + hostGroups, + ([key, entries]) => readIfDue(key, entries, pauseKey, reads), + { + concurrency: width, + discard: true, + }, + ); + }), ); }, - // Match summary batch width so GitHub reads coalesce into one request. - { concurrency: 25, discard: true }, + { concurrency: "unbounded", discard: true }, ); for (const [reason, { count, key }] of skips) { yield* Effect.logWarning("pull request sync skipped", { count, key, reason }); diff --git a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts index c54e6e1f4815d..4ccdcc6e38a57 100644 --- a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts @@ -11,6 +11,7 @@ import { ProviderInstanceId, ProviderThreadId, RunId, + TextGenerationError, ThreadId, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; @@ -432,6 +433,10 @@ describe("ThreadTitleRegenerationService", () => { const projection = yield* threads.getThreadProjection(threadId); assert.equal(projection.thread.title, "Fresh title"); assert.isNotOk(projection.thread.titleRegeneration); + assert.deepInclude(projection.thread.lastTitleRegeneration, { + requestId, + status: "renamed", + }); } }).pipe(Effect.provide(harness.layer)); }).pipe(Effect.provide(NodeServices.layer)), @@ -518,7 +523,14 @@ describe("ThreadTitleRegenerationService", () => { it.effect("clears the marker and keeps the title when generation fails", () => Effect.gen(function* () { const harness = makeHarness({ - generateTitle: () => Effect.die(new Error("model unavailable")), + generateTitle: () => + Effect.fail( + new TextGenerationError({ + operation: "generateThreadTitle", + detail: + "Codex CLI command failed: OpenAI Codex\nuser\nConversation text\nmodel unavailable\n", + }), + ), }); yield* Effect.gen(function* () { const threads = yield* ThreadManagement.ThreadManagementService; @@ -540,6 +552,44 @@ describe("ThreadTitleRegenerationService", () => { const projection = yield* threads.getThreadProjection(threadId); assert.equal(projection.thread.title, "Seed title"); assert.isNotOk(projection.thread.titleRegeneration); + assert.deepInclude(projection.thread.lastTitleRegeneration, { + requestId, + status: "failed", + message: "model unavailable", + }); + }).pipe(Effect.provide(harness.layer)); + }), + ); + + it.effect("records an unchanged outcome when the model keeps the current title", () => + Effect.gen(function* () { + const harness = makeHarness({ + generateTitle: () => Effect.succeed({ title: "Seed title" }), + }); + yield* Effect.gen(function* () { + const threads = yield* ThreadManagement.ThreadManagementService; + const titleRegeneration = yield* ThreadTitleRegeneration.ThreadTitleRegenerationService; + const threadId = yield* createThread({ + command: "command:title:unchanged:create", + thread: "thread:title:unchanged", + }); + yield* dispatchUserMessage({ + command: "command:title:unchanged:message", + threadId, + text: "Some conversation", + }); + const requestId = yield* armRegeneration({ + command: "command:title:unchanged:1", + threadId, + }); + + yield* titleRegeneration.execute({ threadId, requestId, kind: { type: "regenerate" } }); + + const projection = yield* threads.getThreadProjection(threadId); + assert.deepInclude(projection.thread.lastTitleRegeneration, { + requestId, + status: "unchanged", + }); }).pipe(Effect.provide(harness.layer)); }), ); diff --git a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.ts b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.ts index 686d182927171..d3216b1cbd938 100644 --- a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.ts +++ b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.ts @@ -8,6 +8,7 @@ import { type OrchestrationV2ConversationMessage, type RunId, type ServerSettingsError, + TextGenerationError, type ThreadId, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; @@ -17,6 +18,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; import * as ServerSettings from "../serverSettings.ts"; import * as TextGeneration from "../textGeneration/TextGeneration.ts"; @@ -46,6 +48,29 @@ export class ThreadTitleRegenerationService extends Context.Service< } >()("t3/orchestration-v2/ThreadTitleRegenerationService") {} +type Outcome = + | { readonly status: "renamed"; readonly title: string } + | { readonly status: "unchanged" } + | { readonly status: "failed"; readonly message: string }; + +const MAX_FAILURE_MESSAGE_LENGTH = 300; +const isTextGenerationError = Schema.is(TextGenerationError); + +function failureMessage(cause: Cause.Cause): string { + const error = Cause.squash(cause); + const lines = isTextGenerationError(error) + ? error.detail + .split("\n") + .map((line) => line.trim()) + .filter((line) => line.length > 0) + : []; + const detail = lines.at(-1); + if (detail === undefined) return "Title generation failed."; + return detail.length > MAX_FAILURE_MESSAGE_LENGTH + ? `${detail.slice(0, MAX_FAILURE_MESSAGE_LENGTH - 1)}…` + : detail; +} + const make = Effect.gen(function* () { const threads = yield* ThreadManagementService.ThreadManagementService; const projects = yield* ProjectStore.ProjectStoreV2; @@ -56,7 +81,8 @@ const make = Effect.gen(function* () { const complete = (input: { readonly threadId: ThreadId; readonly requestId: CommandId; - readonly title?: string; + readonly kind: { readonly type: "initial" | "regenerate" }; + readonly outcome: Outcome; }) => threads .dispatch({ @@ -64,7 +90,15 @@ const make = Effect.gen(function* () { commandId: CommandId.make(`${input.requestId}:title-complete`), threadId: input.threadId, requestId: input.requestId, - ...(input.title === undefined ? {} : { title: input.title }), + ...(input.outcome.status === "renamed" ? { title: input.outcome.title } : {}), + ...(input.kind.type === "regenerate" + ? { + outcome: { + status: input.outcome.status, + ...(input.outcome.status === "failed" ? { message: input.outcome.message } : {}), + }, + } + : {}), }) .pipe(Effect.asVoid); @@ -110,9 +144,7 @@ const make = Effect.gen(function* () { const execute: ThreadTitleRegenerationService["Service"]["execute"] = Effect.fn( "ThreadTitleRegenerationService.execute", )(function* (input) { - const outcome: - | { readonly type: "stale" } - | { readonly type: "complete"; readonly title?: string } = yield* Effect.gen(function* () { + const outcome: Outcome | { readonly status: "stale" } = yield* Effect.gen(function* () { const projection = yield* threads.getThreadRecords( input.threadId, ["messages"], @@ -121,12 +153,12 @@ const make = Effect.gen(function* () { : { messageRoles: ["user", "assistant"] }, ); if (projection.thread.titleRegeneration?.requestId !== input.requestId) { - return { type: "stale" as const }; + return { status: "stale" as const }; } const project = yield* projects.get(projection.thread.projectId); if (Option.isNone(project)) { - return { type: "complete" as const }; + return { status: "failed" as const, message: "This thread's project no longer exists." }; } let context: { @@ -151,7 +183,10 @@ const make = Effect.gen(function* () { ); } if (context.message.length === 0 && context.attachments.length === 0) { - return { type: "complete" as const }; + return { + status: "failed" as const, + message: "This thread has no messages to title yet.", + }; } // A deleted source should not cost the fork its title. @@ -181,8 +216,8 @@ const make = Effect.gen(function* () { const generatedTitle = result.title.trim(); return generatedTitle === "New thread" || (input.kind.type === "regenerate" && generatedTitle === projection.thread.title.trim()) - ? { type: "complete" as const } - : { type: "complete" as const, title: result.title }; + ? { status: "unchanged" as const } + : { status: "renamed" as const, title: result.title }; }).pipe( Effect.retry({ times: input.kind.type === "initial" ? 2 : 0, @@ -195,17 +230,14 @@ const make = Effect.gen(function* () { threadId: input.threadId, requestId: input.requestId, cause, - }).pipe(Effect.as({ type: "complete" as const })), + }).pipe(Effect.as({ status: "failed" as const, message: failureMessage(cause) })), ), ); - if (outcome.type === "stale") { + if (outcome.status === "stale") { return; } - yield* complete({ - ...input, - ...(outcome.title === undefined ? {} : { title: outcome.title }), - }); + yield* complete({ ...input, outcome }); }); return ThreadTitleRegenerationService.of({ execute }); diff --git a/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts b/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts index 985815bd73eb4..3992d46e6bf9a 100644 --- a/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts +++ b/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts @@ -12,7 +12,7 @@ import * as ProjectionStore from "./ProjectionStore.ts"; import * as Orchestrator from "./Orchestrator.ts"; import * as ThreadManagement from "./ThreadManagementService.ts"; -const MAX_OVERDUE_ARM_MS = 24 * 60 * 60 * 1000; +export const MAX_OVERDUE_ARM_MS = 24 * 60 * 60 * 1000; export function limitRecoveryCommand( thread: ProjectionStore.ProjectionLimitRecoveryCandidate, diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 1557e411af93f..efb826d859052 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -182,19 +182,43 @@ const claudeProviderInstance = { }, } satisfies ProviderInstance; +const antigravityInstanceId = ProviderInstanceId.make("antigravity_test"); +const antigravityDriver = ProviderDriverKind.make("antigravity"); +const antigravityProviderInstance = { + ...providerInstance, + instanceId: antigravityInstanceId, + driverKind: antigravityDriver, + continuationIdentity: { driverKind: antigravityDriver, continuationKey: "antigravity:test" }, + displayName: "Antigravity test", + orchestrationAdapter: { + ...orchestrationAdapter, + instanceId: antigravityInstanceId, + driver: antigravityDriver, + getCapabilities: () => + Effect.succeed({ + ...CodexProviderCapabilitiesV2, + turns: { ...CodexProviderCapabilitiesV2.turns, supportsNativeGoals: true }, + }), + }, +} satisfies ProviderInstance; + const layerTestProviderInstanceRegistry = Layer.succeed( ProviderInstanceRegistry.ProviderInstanceRegistry, { getInstance: (instanceId) => Effect.succeed( - [providerInstance, alternateProviderInstance, claudeProviderInstance].find( - (instance) => instanceId === instance.instanceId, - ), + [ + providerInstance, + alternateProviderInstance, + claudeProviderInstance, + antigravityProviderInstance, + ].find((instance) => instanceId === instance.instanceId), ), listInstances: Effect.succeed([ providerInstance, alternateProviderInstance, claudeProviderInstance, + antigravityProviderInstance, ]), listUnavailable: Effect.succeed([]), streamChanges: Stream.empty, @@ -7963,6 +7987,49 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect.each(["", "pause", "resume", "clear", "edit"])( + "refuses unsupported Antigravity goal controls: %s", + (control) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = ThreadId.make(`antigravity-goal-control-${control}`); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`${threadId}:create`), + threadId, + projectId: ProjectId.make(`${threadId}:project`), + createdBy: "user", + creationSource: "web", + title: "Native goal", + modelSelection: { ...modelSelection, instanceId: antigravityInstanceId }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + }); + const sequence = yield* orchestrator.getThreadEventSequence(threadId); + const refused = yield* Effect.flip( + orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:goal`), + threadId, + messageId: MessageId.make(`${threadId}:goal`), + text: `/goal ${control}`, + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }), + ); + assert.instanceOf(refused, Orchestrator.OrchestratorDispatchError); + assert.equal( + refused.cause, + "Antigravity accepts /goal followed by an objective. Interrupt the running turn, then ask Antigravity to stop the current goal.", + ); + assert.equal(yield* orchestrator.getThreadEventSequence(threadId), sequence); + }), + ); + it.effect("checks a queued goal pause against the model picked ahead of it", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts b/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts index 111cf0541358a..8d81cbfadda7b 100644 --- a/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts +++ b/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts @@ -396,6 +396,38 @@ describe("threadHistoryPaging", () => { expect([...older.items, ...first.items].map((row) => row.sourceItemId)).toEqual( items.map((row) => row.sourceItemId), ); + + // A caller that holds only the newest rows gets the same page when it says what it left + // out: a user turn, and run 3, whose late notification is then not a new turn. + const late = items.with(402, inRun(402, 3, notification("Late"))); + const cursor = encodeThreadHistoryCursor({ + snapshotSequence: 1, + sourceThreadId: THREAD, + sourceItemId: late.at(-1)!.sourceItemId, + position: late.length - 1, + }); + const prefix = { hasUserTurn: true, startedRuns: new Set(["run-3"]) }; + const whole = selectHistoryPageFromCursor({ items: late, cursor, snapshotSequence: 1, policy }); + expect(whole.items[0]?.sourceItemId).toBe(`item-${11 * 4 + 1}`); + expect( + selectHistoryPageFromCursor({ + items: late.slice(22), + cursor, + snapshotSequence: 1, + policy, + prefix, + }), + ).toEqual({ ...whole, oldestScanned: late[45] }); + // A part that ends above the page reports its first row, so the caller reads further back. + expect( + selectHistoryPageFromCursor({ + items: late.slice(60), + cursor, + snapshotSequence: 1, + policy, + prefix, + }).oldestScanned, + ).toBe(late[60]); }); it("pages agent-only child transcripts instead of dropping their earlier activity", () => { diff --git a/apps/server/src/orchestration-v2/threadHistoryPaging.ts b/apps/server/src/orchestration-v2/threadHistoryPaging.ts index b79038a77a803..cf9a101bba44c 100644 --- a/apps/server/src/orchestration-v2/threadHistoryPaging.ts +++ b/apps/server/src/orchestration-v2/threadHistoryPaging.ts @@ -72,10 +72,22 @@ type HistoryRow = Pick< readonly deferredWork?: OrchestrationV2TurnItem["deferredWork"]; }; }; +/** What a caller that passes only the newest part of a history knows about the rows it left out. */ +export type ThreadHistoryPrefix = { + readonly hasUserTurn: boolean; + /** Runs that have a user message or notification among the rows left out. */ + readonly startedRuns: ReadonlySet; +}; + export type SelectTimelinePageResult = { readonly items: ReadonlyArray; readonly nextCursor: string | null; readonly hasMoreHistory: boolean; + /** + * Set with `prefix`: the oldest row the selection read, which can be older than `items[0]`. + * The page is the same as on the full history only when a row lies before this one. + */ + readonly oldestScanned?: Row | undefined; }; export type BoundedProjectionResult = { @@ -200,6 +212,15 @@ function isDeferrableWorkItem(item: HistoryRow["item"]): boolean { ); } +/** A row that folds when its run is not blocked and its group is large enough. */ +export function isFoldableWorkItem(item: HistoryRow["item"]): boolean { + return ( + item.runId != null && + (item.runStatus === "completed" || item.attemptStatus === "superseded") && + isDeferrableWorkItem(item) + ); +} + export function deferWorkHistoryRows(items: ReadonlyArray): Row[] { const blocked = new Set( items.flatMap(({ item }) => @@ -217,12 +238,7 @@ export function deferWorkHistoryRows(items: ReadonlyArra const item = row.item; if (item.runId == null) continue; if (item.type === "user_message") segments.set(item.runId, (segments.get(item.runId) ?? 0) + 1); - if ( - (item.runStatus !== "completed" && item.attemptStatus !== "superseded") || - blocked.has(item.runId) || - !isDeferrableWorkItem(item) - ) - continue; + if (blocked.has(item.runId) || !isFoldableWorkItem(item)) continue; const key = `${row.sourceThreadId}:${item.runId}:${segments.get(item.runId) ?? 0}:${item.attemptId ?? ""}`; const group = groups.get(key) ?? []; group.push(row); @@ -287,8 +303,11 @@ export function selectDeferredWorkPage(input: { } /** Notifications can start wake turns when they are the run's first input; match ProjectionStore run_starts. */ -function threadHistoryTurnStarts(items: ReadonlyArray): ReadonlyArray { - const startedRuns = new Set(); +function threadHistoryTurnStarts( + items: ReadonlyArray, + earlierRuns?: ReadonlySet, +): ReadonlyArray { + const startedRuns = new Set(earlierRuns); return items.map((item) => { if (item.type !== "user_message" && item.type !== "notification") return false; const firstInput = item.runId != null && !startedRuns.has(item.runId); @@ -312,6 +331,7 @@ function selectOlderTimelinePage(input: { readonly snapshotSequence: number; readonly policy?: ThreadHistoryPagePolicy | undefined; readonly rowEncodedBytes?: ((row: Row) => number) | undefined; + readonly prefix?: ThreadHistoryPrefix | undefined; }): SelectTimelinePageResult { const policy = input.policy ?? THREAD_HISTORY_PAGE_POLICY; const rowCost = input.rowEncodedBytes ?? projectedRowEncodedBytes; @@ -325,10 +345,15 @@ function selectOlderTimelinePage(input: { let userTurns = 0; let rawTurns = 0; const candidates = input.items.slice(0, end); - const turnStarts = threadHistoryTurnStarts(candidates.map((row) => row.item)); - const turnLimit = candidates.some((row) => isThreadHistoryUserTurn(row.item)) - ? policy.maxUserTurns - : undefined; + const turnStarts = threadHistoryTurnStarts( + candidates.map((row) => row.item), + input.prefix?.startedRuns, + ); + const turnLimit = + input.prefix?.hasUserTurn === true || + candidates.some((row) => isThreadHistoryUserTurn(row.item)) + ? policy.maxUserTurns + : undefined; const maxItems = turnLimit === undefined ? policy.maxItems : (policy.maxTurnItems ?? policy.maxItems); for (let index = end - 1; index >= 0; index -= 1) { @@ -351,6 +376,7 @@ function selectOlderTimelinePage(input: { // Inside a turn longer than the window, no selected row starts a user turn. // Later pages and the snapshot query see only such rows and use `maxItems`, // so this page uses it too. + const oldestScanned = selected.at(-1); if (userTurns === 0) selected.splice(policy.maxItems); selected.reverse(); @@ -376,6 +402,7 @@ function selectOlderTimelinePage(input: { items: renumberPositions(selected), nextCursor, hasMoreHistory, + ...(input.prefix === undefined ? {} : { oldestScanned }), }; } @@ -458,14 +485,19 @@ export function selectHistoryPageFromCursor(input: { readonly policy?: ThreadHistoryPagePolicy | undefined; readonly rowEncodedBytes?: ((row: Row) => number) | undefined; readonly throughEntryId?: string | undefined; + /** Where the page ends in `items`. Set when `items` can lack the cursor's row. */ + readonly exclusiveEndIndex?: number | undefined; + /** Set when `items` holds only the newest part of the history. */ + readonly prefix?: ThreadHistoryPrefix | undefined; }): SelectTimelinePageResult { const decoded = decodeThreadHistoryCursor(input.cursor); return selectOlderTimelinePage({ items: input.items, - exclusiveEndIndex: findCursorEndIndex(input.items, decoded), + exclusiveEndIndex: input.exclusiveEndIndex ?? findCursorEndIndex(input.items, decoded), snapshotSequence: input.snapshotSequence, ...(input.rowEncodedBytes === undefined ? {} : { rowEncodedBytes: input.rowEncodedBytes }), policy: olderHistoryPagePolicy(input), + prefix: input.prefix, }); } diff --git a/apps/server/src/peer/RemoteDelegation.test.ts b/apps/server/src/peer/RemoteDelegation.test.ts index 8cad52282978b..4ce583944357c 100644 --- a/apps/server/src/peer/RemoteDelegation.test.ts +++ b/apps/server/src/peer/RemoteDelegation.test.ts @@ -6,6 +6,7 @@ import { CommandId, EventId, MessageId, + type ModelSelection, NodeId, type OrchestrationV2Run, ProjectId, @@ -744,7 +745,10 @@ const parentScope: McpInvocationContext.McpInvocationScope = { }; /** The laptop's parent thread, mid-turn when its agent delegates. */ -const seedParent = (laptopEnv: Effect.Success>) => +const seedParent = ( + laptopEnv: Effect.Success>, + parentModelSelection: ModelSelection = modelSelection, +) => Effect.gen(function* () { const now = yield* DateTime.now; const providerThreadId = ProviderThreadId.make("provider-thread:laptop-parent"); @@ -756,7 +760,7 @@ const seedParent = (laptopEnv: Effect.Success>) => threadId: parentThreadId, projectId: ProjectId.make("project:laptop"), title: "Laptop parent", - modelSelection, + modelSelection: parentModelSelection, runtimeMode: "full-access", interactionMode: "default", branch: null, @@ -830,7 +834,7 @@ const seedParent = (laptopEnv: Effect.Success>) => threadId: parentThreadId, ordinal: 1, providerInstanceId: instanceId, - modelSelection, + modelSelection: parentModelSelection, providerThreadId, userMessageId: MessageId.make("message:seed-user:laptop-parent"), rootNodeId: parentRootNode, @@ -1191,16 +1195,24 @@ it.effect("a task named only by environment inherits the parent's model, within const a = yield* makeLaptop(database, offers); // The parent runs with full access; the link allows less. yield* linkTo(a.links, b, "auto-accept-edits"); - yield* seedParent(a); + // An explicit Standard must survive, or a Daybreak default there would replace it. + const parentModelSelection = { + ...modelSelection, + options: [ + { id: "reasoningEffort", value: "high" }, + { id: "cyberAccessProgram", value: "standard" }, + ], + }; + yield* seedParent(a, parentModelSelection); const result = yield* a.call("delegate_task", { task: "Run the suite on the box.", target: { environmentId: box.environmentId }, }); expect(result.isError, JSON.stringify(result.content)).toBe(false); - // The parent's model, and the link's modes rather than the parent's. + // The parent's model and options, and the link's modes rather than the parent's. expect(yield* Ref.get(thread.launchedWith)).toEqual({ - modelSelection, + modelSelection: parentModelSelection, runtimeMode: "auto-accept-edits", interactionMode: "default", }); diff --git a/apps/server/src/persistence/Migrations.test.ts b/apps/server/src/persistence/Migrations.test.ts index 4ab9c86aa10bc..64705e4bbb8f5 100644 --- a/apps/server/src/persistence/Migrations.test.ts +++ b/apps/server/src/persistence/Migrations.test.ts @@ -151,6 +151,22 @@ describe("runMigrations", () => { }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); + it.effect("keeps the migrations that finished before a later one failed", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 81 }); + yield* sql`CREATE TABLE orchestration_v2_projection_turn_item_counts (thread_id TEXT)`; + + const exit = yield* Effect.exit(runMigrations()); + + assert.isTrue(Exit.isFailure(exit)); + assert.deepStrictEqual( + yield* history, + migrationManifest.filter(([id]) => id <= 84), + ); + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), + ); + it.effect("reapplies peer link migrations whose ledger rows are missing", () => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 37b74d5c6db01..8b33ba60f8e9a 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -268,16 +268,40 @@ export const runMigrations = Effect.fn("runMigrations")(function* ({ if (includesV2) { yield* assertV2MigrationsCanRun(toMigrationInclusive); } - const executedMigrations = [ - ...previewMigrations, - ...(yield* run({ loader: makeMigrationLoader(toMigrationInclusive) })), - ]; + const sql = yield* SqlClient.SqlClient; + const ledger = yield* sql` + SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'effect_sql_migrations' + `; + const [latest] = + ledger.length === 0 + ? [] + : yield* sql<{ + readonly id: number | null; + }>`SELECT MAX(migration_id) AS id FROM effect_sql_migrations`; + const latestRecordedId = latest?.id ?? 0; + const pending = migrationEntries.filter( + ([id]) => + id > latestRecordedId && (toMigrationInclusive === undefined || id <= toMigrationInclusive), + ); + // One transaction per migration: an index build on a large database can take minutes, and a + // restart then resumes after the last finished migration instead of rolling all of them back. + const executedMigrations: Array = [...previewMigrations]; + for (const [index, [id, name]] of pending.entries()) { + if (latestRecordedId > 0) { + yield* Effect.log("Upgrading database").pipe( + Effect.annotateLogs({ + migration: `${id}_${name}`, + progress: `${index + 1} of ${pending.length}`, + }), + ); + } + executedMigrations.push(...(yield* run({ loader: makeMigrationLoader(id) }))); + } const migrations = executedMigrations.map(([id, name]) => `${id}_${name}`); yield* migrations.length === 0 ? Effect.logDebug("Database schema is current") : Effect.log("Migrations ran successfully").pipe(Effect.annotateLogs({ migrations })); - const sql = yield* SqlClient.SqlClient; const recorded = yield* sql<{ readonly migration_id: number; readonly name: string; diff --git a/apps/server/src/persistence/Sqlite.test.ts b/apps/server/src/persistence/Sqlite.test.ts index c042ea9afa7ac..8609649c2c1ad 100644 --- a/apps/server/src/persistence/Sqlite.test.ts +++ b/apps/server/src/persistence/Sqlite.test.ts @@ -24,6 +24,7 @@ import { migrationManifest, runMigrations } from "./Migrations.ts"; import * as SqlitePersistence from "./Sqlite.ts"; const workers = vi.hoisted((): Array => []); +const workerData = vi.hoisted((): Array => []); vi.mock("node:worker_threads", async (importOriginal) => { const actual = await importOriginal(); @@ -31,6 +32,7 @@ vi.mock("node:worker_threads", async (importOriginal) => { constructor(...args: ConstructorParameters) { super(...args); workers.push(this); + workerData.push(args[1]?.workerData); } } return { ...actual, Worker: RecordedWorker }; @@ -192,6 +194,43 @@ it.effect("drops planner statistics a database already has", () => { ); }); +it.effect("upgrades an existing database on a read-write worker connection", () => { + const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sqlite-upgrade-")); + const dbPath = NodePath.join(tempDir, "state.sqlite"); + + return Effect.gen(function* () { + yield* Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`PRAGMA journal_mode = WAL;`; + yield* runMigrations({ toMigrationInclusive: 81 }); + }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath }))); + const startedBefore = workerData.length; + + yield* Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const rows = yield* sql<{ readonly migration_id: number; readonly name: string }>` + SELECT migration_id, name FROM effect_sql_migrations ORDER BY migration_id + `; + assert.deepStrictEqual( + rows.map((row) => [row.migration_id, row.name] as const), + migrationManifest, + ); + }).pipe( + Effect.provide( + SqlitePersistence.layerFromPath(dbPath).pipe(Layer.provide(NodeServices.layer)), + ), + ); + assert.deepInclude(workerData.slice(startedBefore), { + filename: dbPath, + readOnly: false, + allowExtension: false, + prepareCacheSize: 200, + }); + }).pipe( + Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))), + ); +}); + it.effect("names a database file that is not SQLite", () => { const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sqlite-notadb-")); const dbPath = NodePath.join(tempDir, "state.sqlite"); diff --git a/apps/server/src/persistence/Sqlite.ts b/apps/server/src/persistence/Sqlite.ts index e8471f3f59891..273c2b3c6dc5c 100644 --- a/apps/server/src/persistence/Sqlite.ts +++ b/apps/server/src/persistence/Sqlite.ts @@ -64,6 +64,26 @@ const runMigrationsAsOwner = Effect.fn("SqlitePersistence.runMigrationsAsOwner") yield* runMigrations(); }, Effect.scoped); +// Index builds over large tables take minutes; on the main connection they block the event loop, +// so requests hang instead of getting the listener's 503. A fresh database stays on the main +// connection, which must create the first table for its auto_vacuum setting to apply. +const runMigrationsOffMainThread = Effect.fn("SqlitePersistence.runMigrationsOffMainThread")( + function* (dbPath: string) { + const sql = yield* SqlClient.SqlClient; + const tables = yield* sql<{ + readonly count: number; + }>`SELECT COUNT(*) AS count FROM sqlite_schema WHERE type = 'table'`; + if (!tables[0]?.count || !(yield* hasPendingMigrations())) return yield* runMigrations(); + return yield* Effect.gen(function* () { + const worker = yield* SqlClient.SqlClient; + yield* worker`PRAGMA foreign_keys = ON;`; + yield* worker`PRAGMA synchronous = NORMAL;`; + yield* worker`PRAGMA temp_store = MEMORY;`; + return yield* runMigrations(); + }).pipe(Effect.provide(NodeSqliteClient.layerWorker(dbPath))); + }, +); + const makeLayerSetup = (migrate: Effect.Effect) => Layer.effectDiscard( Effect.gen(function* () { @@ -100,14 +120,14 @@ const makeLayerSetup = (migrate: Effect.Effect) => const layerSetup = makeLayerSetup(runMigrations()); -const makeLayerFromPath = (setup: Layer.Layer) => +const makeLayerFromPath = (makeSetup: (dbPath: string) => Layer.Layer) => Effect.fn("makeSqlitePersistenceLive")(function* (dbPath: string) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true }); return Layer.provideMerge( - setup, + makeSetup(dbPath), NodeSqliteClient.layer({ filename: dbPath, readerWorker: true, @@ -132,7 +152,9 @@ const makeLayerFromPath = (setup: Layer.Layer) => ); }, Layer.unwrap); -export const layerFromPath = makeLayerFromPath(layerSetup); +export const layerFromPath = makeLayerFromPath((dbPath) => + makeLayerSetup(runMigrationsOffMainThread(dbPath)), +); export const layerMemory = Layer.provideMerge( layerSetup, @@ -154,5 +176,5 @@ export const layerConfig = makeLayerConfig(layerFromPath); /** For CLI commands: pending migrations run only while no server owns the T3 home. */ export const layerCliConfig = makeLayerConfig( - makeLayerFromPath(makeLayerSetup(runMigrationsAsOwner())), + makeLayerFromPath(() => makeLayerSetup(runMigrationsAsOwner())), ); diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts index a86dcc415c109..e408519e9ac1c 100644 --- a/apps/server/src/preview/ServerBrowser.test.ts +++ b/apps/server/src/preview/ServerBrowser.test.ts @@ -63,7 +63,7 @@ vi.mock("./ServerBrowserContexts.ts", () => ({ return context as unknown as BrowserContext; } async scratchPage() { - return makeEncoderPage() as unknown as Page; + return encoderPageOverride ?? (makeEncoderPage() as unknown as Page); } async connectDesktopPage(endpoint: string) { const context = makeContext(undefined, desktopPageUrl); @@ -377,6 +377,7 @@ function makeEncoderPage() { } const contexts: ReturnType[] = []; +let encoderPageOverride: Page | undefined; const encoderStreams: Array<{ frameRate: number | undefined; bitsPerSecond: number }> = []; const contextRequests: Array<{ profileId: string; isolated: boolean }> = []; let contextGate: PromiseWithResolvers | null = null; @@ -560,6 +561,7 @@ const openDesktopViewer = Effect.gen(function* () { beforeEach(() => { contexts.length = 0; + encoderPageOverride = undefined; encoderStreams.length = 0; contextRequests.length = 0; contextGate = null; @@ -742,6 +744,26 @@ it.effect("a tab the desktop does not draw is marked headless, so the desktop st ).pipe(Effect.provide(layer)), ); +it.effect("a server started without the desktop browser channel marks its tabs headless", () => + Effect.scoped( + Effect.gen(function* () { + const { tabId } = yield* ready; + const manager = yield* Manager.PreviewManager; + const { sessions } = yield* manager.list({ threadId: scope.thread.threadId }); + + expect(sessions.find((session) => session.tabId === tabId)?.headless).toBe(true); + }), + ).pipe( + // A WSL-only desktop starts its backend without the browser fds. + Effect.provide( + ServerBrowser.layer.pipe( + Layer.provide(DesktopChannel.layer), + Layer.provideMerge(dependencies), + ), + ), + ), +); + it.effect("an agent's tab the reloaded desktop dropped goes back to the desktop", () => Effect.scoped( Effect.gen(function* () { @@ -916,6 +938,64 @@ it.live.each([ ).pipe(Effect.provide(layer)), ); +it.live.each([{ truncated: false }, { truncated: true }])( + "saves a large recording as a binary download and removes its staged file (truncated: $truncated)", + ({ truncated }) => + Effect.scoped( + Effect.gen(function* () { + const { broker, tabId } = yield* ready; + const fs = yield* FileSystem.FileSystem; + const bytes = 8 * 1024 * 1024; + const payload = Buffer.alloc(bytes, 0x5a); + let stagedPath: string | undefined; + const download = Promise.withResolvers<{ saveAs: (path: string) => Promise }>(); + const sandbox = NodeVM.createContext({ + __t3Recorder: { + frame: async () => true, + stop: async () => ({ mimeType: "video/webm", count: 1, bytes }), + chunk: async () => { + throw new Error("Large recording used Base64 export"); + }, + download: () => + download.resolve({ + saveAs: async (path) => { + stagedPath = path; + await NodeFSP.writeFile(path, truncated ? payload.subarray(1) : payload); + }, + }), + }, + }); + encoderPageOverride = { + ...makeContext().page, + evaluate: async (script: string | ((arg: unknown) => unknown), arg?: unknown) => + typeof script === "function" + ? NodeVM.runInContext(`(${script.toString()})`, sandbox)(arg) + : undefined, + waitForEvent: () => download.promise, + } as unknown as Page; + + yield* broker.invoke({ scope, tabId, operation: "recordingStart", input: {} }); + const stop = broker.invoke<{ path: string; sizeBytes: number }>({ + scope, + tabId, + operation: "recordingStop", + input: {}, + }); + if (truncated) { + expect(yield* stop.pipe(Effect.flip)).toMatchObject({ + _tag: "PreviewAutomationExecutionError", + }); + } else { + const artifact = yield* stop; + expect(artifact.sizeBytes).toBe(bytes); + expect(Buffer.from(yield* fs.readFile(artifact.path)).equals(payload)).toBe(true); + } + expect(stagedPath).toBeDefined(); + expect(yield* fs.exists(stagedPath!)).toBe(false); + }), + ).pipe(Effect.provide(layer)), +); + it.live.each([ { refreshFails: false, expected: "final frame" }, { refreshFails: true, expected: "frame" }, diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts index ecb3184b09979..68c489e9cb15c 100644 --- a/apps/server/src/preview/ServerBrowser.ts +++ b/apps/server/src/preview/ServerBrowser.ts @@ -101,6 +101,8 @@ const HOST_RECONNECT_DELAY = "1 second"; const DESKTOP_ATTACH_TIMEOUT = "10 seconds"; const VIEWER_OUTPUT_LIMIT = 64; const RECORDING_SCREENCAST = { format: "jpeg", quality: 90, everyNthFrame: 1 } as const; +const RECORDING_BINARY_EXPORT_MIN_BYTES = 8 * 1024 * 1024; +const RECORDING_DOWNLOAD_TIMEOUT_MS = 5_000; const decodeViewportSetting = Schema.decodeUnknownSync(PreviewViewportSettingSchema); const AGENT_CURSOR_MOVE_MS = 160; const AGENT_CURSOR_CLICK_LEAD_MS = 40; @@ -294,6 +296,7 @@ interface EncoderWindow { frame(data: string, width: number): Promise; stop(): Promise<{ mimeType: string | null; count: number; bytes: number }>; chunk(index: number): Promise; + download(): void; }; } @@ -887,8 +890,8 @@ const make = Effect.gen(function* () { if (desktop) opened.push(desktop.close); // Attaching over CDP emulates a light scheme; a tab on System follows the desktop's. if (desktop) await desktop.page.emulateMedia({ colorScheme: null }); - // Otherwise a desktop that attaches late shows its own page, and the agent drives another. - if (!desktop && desktopChannel.available) { + // Otherwise a desktop that attaches late, or has no channel to draw it, shows its own page. + if (!desktop) { await runPromise( manager .markHeadless({ threadId: ThreadId.make(snapshot.threadId), tabId: snapshot.tabId }) @@ -1920,8 +1923,6 @@ const make = Effect.gen(function* () { message: "No recording is active for this tab.", }); } - let mimeType: string | null; - const chunks: Array = []; try { await recording.session.send("Page.stopScreencast").catch(constVoid); await Promise.all(recording.framesInFlight); @@ -1945,50 +1946,72 @@ const make = Effect.gen(function* () { .catch(constVoid); } } - const stopped = await recording.encoder.evaluate(() => + const { mimeType, count, bytes } = await recording.encoder.evaluate(() => (globalThis as unknown as EncoderWindow).__t3Recorder.stop(), ); - mimeType = stopped.mimeType; // Checked before the transfer so an oversized video never lands in this process. - if (stopped.bytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) { + if (bytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) { throw new ServerBrowserPage.ServerBrowserOperationError({ tag: "PreviewAutomationRecordingTooLargeError", message: "The recording is larger than the attachment limit.", }); } - for (let index = 0; index < stopped.count; index += 1) { - const chunk = await recording.encoder.evaluate( - (chunkIndex) => (globalThis as unknown as EncoderWindow).__t3Recorder.chunk(chunkIndex), - index, - ); - chunks.push(Buffer.from(chunk, "base64")); + if (!mimeType || bytes === 0) { + throw new ServerBrowserPage.ServerBrowserOperationError({ + tag: "PreviewAutomationExecutionError", + message: "The recording captured no frames.", + }); + } + const extension = mimeType.startsWith("video/mp4") ? "mp4" : "webm"; + const pendingId = `${PENDING_ATTACHMENT_THREAD_SEGMENT}-${NodeCrypto.randomUUID()}-${extension}`; + const path = NodePath.join(config.attachmentsDir, `${pendingId}.${extension}`); + await NodeFSP.mkdir(config.attachmentsDir, { recursive: true }); + if (bytes >= RECORDING_BINARY_EXPORT_MIN_BYTES) { + const stagedPath = `${path}.partial`; + try { + const [download] = await Promise.all([ + recording.encoder.waitForEvent("download", { + timeout: RECORDING_DOWNLOAD_TIMEOUT_MS, + }), + recording.encoder.evaluate(() => + (globalThis as unknown as EncoderWindow).__t3Recorder.download(), + ), + ]); + await download.saveAs(stagedPath); + if ((await NodeFSP.stat(stagedPath)).size !== bytes) { + throw new Error("The recording download is incomplete."); + } + await NodeFSP.rename(stagedPath, path); + } finally { + await NodeFSP.rm(stagedPath, { force: true }).catch(constVoid); + } + } else { + const chunks: Array = []; + for (let index = 0; index < count; index += 1) { + const chunk = await recording.encoder.evaluate( + (chunkIndex) => + (globalThis as unknown as EncoderWindow).__t3Recorder.chunk(chunkIndex), + index, + ); + chunks.push(Buffer.from(chunk, "base64")); + } + const data = Buffer.concat(chunks); + if (data.byteLength !== bytes) throw new Error("The recording transfer is incomplete."); + await NodeFSP.writeFile(path, data); } + return { + id: pendingId, + tabId: tab.tabId, + path, + mimeType: mimeType.split(";")[0]!, + sizeBytes: bytes, + createdAt: new Date().toISOString(), + uploadedAttachmentId: pendingId, + }; } finally { await recording.encoder.close().catch(constVoid); tab.recording = null; } - const data = Buffer.concat(chunks); - if (!mimeType || data.byteLength === 0) { - throw new ServerBrowserPage.ServerBrowserOperationError({ - tag: "PreviewAutomationExecutionError", - message: "The recording captured no frames.", - }); - } - - const extension = mimeType.startsWith("video/mp4") ? "mp4" : "webm"; - const pendingId = `${PENDING_ATTACHMENT_THREAD_SEGMENT}-${NodeCrypto.randomUUID()}-${extension}`; - const path = NodePath.join(config.attachmentsDir, `${pendingId}.${extension}`); - await NodeFSP.mkdir(config.attachmentsDir, { recursive: true }); - await NodeFSP.writeFile(path, data); - return { - id: pendingId, - tabId: tab.tabId, - path, - mimeType: mimeType.split(";")[0]!, - sizeBytes: data.byteLength, - createdAt: new Date().toISOString(), - uploadedAttachmentId: pendingId, - }; }); let pointerSequence = 0; diff --git a/apps/server/src/preview/ServerBrowserPage.ts b/apps/server/src/preview/ServerBrowserPage.ts index 29ba05c21b7ea..9df6c539014c5 100644 --- a/apps/server/src/preview/ServerBrowserPage.ts +++ b/apps/server/src/preview/ServerBrowserPage.ts @@ -1165,11 +1165,18 @@ export const recordingEncoderScript = (frameRate: BrowserRecordingFrameRate) => }, async chunk(index) { const bytes = new Uint8Array(await chunks[index].arrayBuffer()); + if (typeof bytes.toBase64 === "function") return bytes.toBase64(); let binary = ""; for (let offset = 0; offset < bytes.length; offset += 0x8000) { binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000)); } return btoa(binary); }, + download() { + const link = document.createElement("a"); + link.href = URL.createObjectURL(new Blob(chunks, { type: recorder.mimeType })); + link.download = "recording"; + link.click(); + }, }; })()`; diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index df8ef8aaf4270..82890ca9c8353 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -869,7 +869,7 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); - it.effect("skips linked git worktrees and reports the origin of real checkouts", () => + it.effect("folds linked git worktrees into their checkout and reports real origins", () => Effect.gen(function* () { const path = yield* Path.Path; const fileSystem = yield* FileSystem.FileSystem; @@ -905,8 +905,56 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { path.join(submodule, ".git"), `gitdir: ${submoduleGitDir}\n`, ); + // A repository whose sessions all ran in a linked worktree is still offered. + const worktreeOnly = yield* makeTempDir("t3code-workspace-worktree-only-"); + const worktreeOnlyCheckout = yield* makeTempDir("t3code-workspace-worktree-only-wt-"); + const worktreeOnlyGitDir = path.join(worktreeOnly, ".git", "worktrees", "wt"); + yield* fileSystem.makeDirectory(worktreeOnlyGitDir, { recursive: true }); + yield* fileSystem.writeFileString( + path.join(worktreeOnly, ".git", "config"), + '[remote "origin"]\n\turl = git@github.com:pingdotgg/other.git\n', + ); + yield* fileSystem.writeFileString(path.join(worktreeOnlyGitDir, "commondir"), "../..\n"); + yield* fileSystem.writeFileString( + path.join(worktreeOnlyCheckout, ".git"), + `gitdir: ${worktreeOnlyGitDir}\n`, + ); + + // Not offered: the config is unreadable, so the repository could be bare; and + // the main checkout is reached through a symlink into T3's own state. + const configBaseDir = yield* fileSystem.realPath( + yield* makeTempDir("t3code-scanner-base-"), + ); + const links = yield* makeTempDir("t3code-workspace-links-"); + const unknown = yield* makeTempDir("t3code-workspace-unknown-"); + yield* fileSystem.makeDirectory(path.join(configBaseDir, "state-repo")); + yield* fileSystem.symlink(path.join(configBaseDir, "state-repo"), path.join(links, "repo")); + const hiddenCheckouts: Array = []; + for (const [main, config] of [ + [unknown, null], + [path.join(links, "repo"), "[core]\n"], + ] as const) { + const gitDir = path.join(main, ".git", "worktrees", "wt"); + yield* fileSystem.makeDirectory(gitDir, { recursive: true }); + if (config !== null) { + yield* fileSystem.writeFileString(path.join(main, ".git", "config"), config); + } + yield* fileSystem.writeFileString(path.join(gitDir, "commondir"), "../..\n"); + const checkout = yield* makeTempDir("t3code-workspace-hidden-wt-"); + yield* fileSystem.writeFileString(path.join(checkout, ".git"), `gitdir: ${gitDir}\n`); + hiddenCheckouts.push(checkout); + } - for (const [index, cwd] of [repo, worktree, plain, noRemote, submodule].entries()) { + const sessionDirectories = [ + repo, + worktree, + plain, + noRemote, + submodule, + worktreeOnlyCheckout, + ...hiddenCheckouts, + ]; + for (const [index, cwd] of sessionDirectories.entries()) { yield* writeTranscript({ filePath: path.join(claudeHomePath, "projects", `-slug-${index}`, "a.jsonl"), contents: claudeSessionLine(cwd), @@ -914,23 +962,34 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }); } - const result = yield* runScan({ claudeHomePath, codexHomePath }); + const result = yield* runScan({ claudeHomePath, codexHomePath, configBaseDir }); expect( - result.candidates.map((candidate) => ({ path: candidate.path, git: candidate.git })), + result.candidates.map((candidate) => ({ + path: candidate.path, + git: candidate.git, + threadCount: candidate.threadCount, + })), ).toEqual([ + { + path: worktreeOnly, + git: { remoteKey: "github.com/pingdotgg/other", repository: "pingdotgg/other" }, + threadCount: 1, + }, { path: submodule, git: { remoteKey: "gitlab.com/pingdotgg/libs/vendor", repository: "pingdotgg/libs/vendor", }, + threadCount: 1, }, - { path: noRemote, git: { remoteKey: null, repository: null } }, - { path: plain, git: null }, + { path: noRemote, git: { remoteKey: null, repository: null }, threadCount: 1 }, + { path: plain, git: null, threadCount: 1 }, { path: repo, git: { remoteKey: "github.com/pingdotgg/t3code", repository: "pingdotgg/t3code" }, + threadCount: 2, }, ]); }), diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index ee3f2d2b3ab3c..d9ca41b8f26b1 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -876,6 +876,20 @@ export const make = Effect.gen(function* () { return `path:${normalizeProjectPathForComparison(realPath)}`; }); + /** Stats a directory that may be offered as a project, or none when it is missing or excluded. */ + const projectDirectoryStats = Effect.fn("AgentSessionScanner.projectDirectoryStats")(function* ( + directory: string, + ) { + if (isExcludedProjectPath(directory)) return Option.none(); + const stats = yield* statOption(directory); + if (Option.isNone(stats) || stats.value.type !== "Directory") return Option.none(); + const realPath = yield* fileSystem + .realPath(directory) + .pipe(Effect.orElseSucceed(() => directory)); + // Symlinks can disguise excluded worktree paths; re-check their targets. + return isExcludedProjectPath(realPath) ? Option.none() : stats; + }); + // Paths whose own read outlived the deadline, mapped to when they may be read // again. Without this every later scan would wait out the deadline again for // each phase that touches them. @@ -929,7 +943,11 @@ export const make = Effect.gen(function* () { ) { type GitIdentity = | { readonly _tag: "Repository"; readonly git: AgentSessionProjectGit | null } - | { readonly _tag: "Worktree" } + | { + readonly _tag: "Worktree"; + readonly mainCheckout: string | null; + readonly git: AgentSessionProjectGit | null; + } | { readonly _tag: "NotGit" }; const identities = new Map(); const repositories: Array<{ directory: string; gitDir: string; linkedWorktree: boolean }> = []; @@ -962,8 +980,9 @@ export const make = Effect.gen(function* () { ); for (const { directory, gitDir } of linkedWorktrees) { const commonDir = (commonDirTexts.get(path.join(gitDir, "commondir")) ?? "").trim(); - if (commonDir.length === 0) identities.set(directory, { _tag: "Worktree" }); - else + if (commonDir.length === 0) { + identities.set(directory, { _tag: "Worktree", mainCheckout: null, git: null }); + } else repositories.push({ directory, gitDir: path.resolve(gitDir, commonDir), @@ -976,20 +995,25 @@ export const make = Effect.gen(function* () { ); for (const { directory, gitDir, linkedWorktree } of repositories) { const configText = configTexts.get(path.join(gitDir, "config")) ?? ""; + const originUrl = parseOriginUrlFromGitConfig(configText); + const git: AgentSessionProjectGit = { + remoteKey: + originUrl === null ? null : sourceControlDefinitions.repositoryKeyFromRemote(originUrl), + repository: repositoryPathFromRemoteUrl(originUrl), + }; // Bare repositories have no main checkout, so offer their linked worktrees independently. if (linkedWorktree && !isBareGitConfig(configText)) { - identities.set(directory, { _tag: "Worktree" }); + identities.set(directory, { + _tag: "Worktree", + // Only a common dir named .git sits inside its main checkout, and an + // unreadable config can't rule out a bare repository. + mainCheckout: + configText.length > 0 && path.basename(gitDir) === ".git" ? path.dirname(gitDir) : null, + git, + }); continue; } - const originUrl = parseOriginUrlFromGitConfig(configText); - identities.set(directory, { - _tag: "Repository", - git: { - remoteKey: - originUrl === null ? null : sourceControlDefinitions.repositoryKeyFromRemote(originUrl), - repository: repositoryPathFromRemoteUrl(originUrl), - }, - }); + identities.set(directory, { _tag: "Repository", git }); } return identities; }); @@ -1701,17 +1725,8 @@ export const make = Effect.gen(function* () { const expanded = expandHomePath(candidate.cwd.trim(), homeDir); if (!path.isAbsolute(expanded)) continue; const resolved = path.resolve(expanded); - if (directories.has(resolved) || isExcludedProjectPath(resolved)) continue; - const stats = yield* statOption(resolved); - if (Option.isNone(stats) || stats.value.type !== "Directory") { - directories.set(resolved, Option.none()); - continue; - } - const realPath = yield* fileSystem - .realPath(resolved) - .pipe(Effect.orElseSucceed(() => resolved)); - // Symlinks can disguise excluded worktree paths; re-check their targets. - directories.set(resolved, isExcludedProjectPath(realPath) ? Option.none() : stats); + if (directories.has(resolved)) continue; + directories.set(resolved, yield* projectDirectoryStats(resolved)); } const directoryGitIdentities = yield* readGitIdentities( Array.from(directories).flatMap(([directory, stats]) => @@ -1719,8 +1734,14 @@ export const make = Effect.gen(function* () { ), ); - const directoryKeys = new Map(); - const gitIdentities = new Map(); + const directoryProjects = new Map< + string, + { + readonly key: string; + readonly path: string; + readonly git: AgentSessionProjectGit | null; + } | null + >(); for (const candidate of raw) { const expanded = expandHomePath(candidate.cwd.trim(), homeDir); @@ -1728,27 +1749,43 @@ export const make = Effect.gen(function* () { const resolved = path.resolve(expanded); const stats = directories.get(resolved); if (stats === undefined || Option.isNone(stats)) continue; - let key = directoryKeys.get(resolved); - if (key === undefined) { + let project = directoryProjects.get(resolved); + if (project === undefined) { const gitIdentity = directoryGitIdentities.get(resolved); - if (gitIdentity === undefined || gitIdentity._tag === "Worktree") { - key = ""; + if (gitIdentity === undefined) { + project = null; + } else if (gitIdentity._tag === "Worktree") { + // A linked worktree's sessions count toward its main checkout's project. + const { mainCheckout } = gitIdentity; + const mainStats = + mainCheckout === null ? Option.none() : yield* projectDirectoryStats(mainCheckout); + project = + mainCheckout !== null && Option.isSome(mainStats) + ? { + key: yield* directoryIdentity(mainCheckout, mainStats.value), + path: mainCheckout, + git: gitIdentity.git, + } + : null; } else { - key = yield* directoryIdentity(resolved, stats.value); - gitIdentities.set(key, gitIdentity._tag === "Repository" ? gitIdentity.git : null); + project = { + key: yield* directoryIdentity(resolved, stats.value), + path: resolved, + git: gitIdentity._tag === "Repository" ? gitIdentity.git : null, + }; } - directoryKeys.set(resolved, key); + directoryProjects.set(resolved, project); } - if (key === "") continue; + if (project === null) continue; - const existing = merged.get(key); + const existing = merged.get(project.key); if (!existing) { - merged.set(key, { - path: resolved, + merged.set(project.key, { + path: project.path, sources: [candidate.source], threadCount: candidate.threadCount, lastActiveAtMs: candidate.lastActiveAtMs, - git: gitIdentities.get(key) ?? null, + git: project.git, }); continue; } diff --git a/apps/server/src/provider/AcpRegistryProbe.test.ts b/apps/server/src/provider/AcpRegistryProbe.test.ts index 77f2a1ae31d44..3b7b2b42f2b74 100644 --- a/apps/server/src/provider/AcpRegistryProbe.test.ts +++ b/apps/server/src/provider/AcpRegistryProbe.test.ts @@ -66,6 +66,22 @@ describe("ACP Registry probe", () => { { value: "gpt-5.4", name: "Duplicate" }, ], }, + { + id: "effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: "high", + options: [{ value: "high", name: "High" }], + }, + { + id: "mode", + name: "Mode", + category: "mode", + type: "select", + currentValue: "ask", + options: [{ value: "ask", name: "Ask" }], + }, ], }, modelConfigId: "model", @@ -88,7 +104,24 @@ describe("ACP Registry probe", () => { ], models: [{ id: "gpt-5.4", name: "GPT-5.4", description: null }], currentModelId: "gpt-5.4", - configOptions: [], + configOptions: [ + { + id: "effort", + label: "Effort", + type: "select", + options: [{ id: "high", label: "High" }], + currentValue: "high", + role: "reasoning", + }, + { + id: "mode", + label: "Mode", + type: "select", + options: [{ id: "ask", label: "Ask" }], + currentValue: "ask", + }, + ], + modelOptionIds: ["effort"], sessionManagement: { canList: true, canLoad: true, diff --git a/apps/server/src/provider/AntigravityInstallation.test.ts b/apps/server/src/provider/AntigravityInstallation.test.ts index f8e6636f80673..dcd3e40030093 100644 --- a/apps/server/src/provider/AntigravityInstallation.test.ts +++ b/apps/server/src/provider/AntigravityInstallation.test.ts @@ -22,6 +22,7 @@ import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as AntigravityInstallation from "./AntigravityInstallation.ts"; +import * as ModelManifest from "./ModelManifest.ts"; import { type AntigravityReleaseAsset } from "./antigravityRelease.ts"; const serverContents = "antigravity runtime\n"; @@ -127,6 +128,12 @@ interface HarnessOptions { readonly validate?: AntigravityInstallation.AntigravityInstallationOptions["validate"]; readonly useDefaultValidation?: boolean; readonly connectTimeout?: boolean; + readonly manifest?: Effect.Effect; + readonly native?: boolean; + readonly nativeVersion?: string; + readonly nativeManifest?: (manifest: { version: string; url: string; sha512: string }) => unknown; + readonly beforeManifest?: Effect.Effect; + readonly updateChecksEnabled?: Effect.Effect; } const makeHarness = Effect.fn("test.makeAntigravityInstallation")(function* ( @@ -134,6 +141,7 @@ const makeHarness = Effect.fn("test.makeAntigravityInstallation")(function* ( ) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; + const digest = yield* Digest.Digest; const baseDir = options.baseDir ?? (yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-test-" })); const platform = options.platform ?? hostPlatform; @@ -169,7 +177,10 @@ const makeHarness = Effect.fn("test.makeAntigravityInstallation")(function* ( }); const installation = yield* AntigravityInstallation.makeAntigravityInstallation({ baseDir, - releaseAsset: asset, + ...(options.native ? {} : { releaseAsset: asset }), + ...(options.updateChecksEnabled === undefined + ? {} + : { updateChecksEnabled: options.updateChecksEnabled }), ...(options.useDefaultValidation ? {} : { @@ -186,11 +197,34 @@ const makeHarness = Effect.fn("test.makeAntigravityInstallation")(function* ( Effect.provideService(HostProcess.Platform, platform), Effect.provideService(HostProcess.Architecture, arch), Effect.provideService(HostProcess.Environment, { PATH: options.path ?? "" }), + Effect.provideService(ModelManifest.ModelManifest, { + current: options.manifest ?? Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST), + refresh: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST), + forceRefresh: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST), + refreshOnDemand: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST), + refreshInBackground: Effect.void, + }), Effect.provideService( HttpClient.HttpClient, HttpClient.make((request) => Effect.suspend(() => { requests.push(request.url); + if (request.url.includes("/manifests/")) { + return Effect.gen(function* () { + yield* options.beforeManifest ?? Effect.void; + const version = options.nativeVersion ?? "1.5.7"; + const folder = platform === "win32" ? "windows-x64" : "linux-x64"; + const manifest = { + version, + url: `https://storage.googleapis.com/antigravity-public/antigravity-cli/${version}-123/${folder}/cli_${platform === "win32" ? "windows_x64.exe" : "linux_x64.tar.gz"}`, + sha512: Hex.encode(yield* digest.digest(Digest.sha512, archive).pipe(Effect.orDie)), + }; + return HttpClientResponse.fromWeb( + request, + new Response(JSON.stringify(options.nativeManifest?.(manifest) ?? manifest)), + ); + }); + } if (options.connectTimeout) { return Effect.fail( new HttpClientError.HttpClientError({ @@ -255,6 +289,256 @@ const expectPreviousRelease = Effect.fn("test.expectPreviousAntigravityRelease") }); it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity installation", (it) => { + it.effect.each([...new Set(["win32", hostPlatform])] as NodeJS.Platform[])( + "migrates the legacy managed runtime to the native CLI on %s and retains the old release", + (platform) => + Effect.gen(function* () { + const archive = + platform === "win32" + ? Buffer.from(serverContents) + : Buffer.from( + "H4sIAAAAAAACE+3RMQ7CQAwEQNe8Ik8wgYj3XIFQCiiOCxK/56CJRA9CYqZZrxsXLpc2n2q5ze0en5LdYZpe2b1n5rhf5+d+m+MuY8j4guXaSu3n4z+V9f9DXXo5HzcBAAAAAAAAAADAz3sA56lbdQAoAAA=", + "base64", + ); + const { installation, validations, requests, fs, baseDir, stagingReleased } = + yield* makeHarness({ native: true, archive, platform, previous: true }); + yield* installation.start; + expect(yield* terminalState(installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "1.5.7", + }); + yield* Deferred.await(stagingReleased); + const resolved = yield* installation.resolve(); + expect(resolved).toMatchObject({ source: "managed", version: "1.5.7", harnessPath: null }); + expect(validations[0]?.executable.harnessPath).toBeNull(); + expect(yield* fs.readFileString(resolved.executablePath)).toBe(serverContents); + expect(requests.some((url) => url.includes("/manifests/"))).toBe(true); + const restarted = yield* makeHarness({ + baseDir, + native: true, + archive, + platform, + nativeVersion: "1.5.6", + }); + expect(yield* restarted.installation.start).toMatchObject({ + phase: "verifying", + message: "Checking the installed runtime.", + }); + expect(yield* terminalState(restarted.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "1.5.7", + }); + expect(restarted.requests.filter((url) => url.includes("storage.googleapis.com"))).toEqual( + [], + ); + expect((yield* restarted.installation.resolve()).executablePath).toBe( + resolved.executablePath, + ); + }), + ); + + // These tar fixtures exercise the POSIX extraction path; Windows downloads one executable. + it.effect.skipIf(hostPlatform === "win32")( + "rejects unsafe native tar members before activation", + () => + Effect.gen(function* () { + for (const archive of [ + "H4sIAAAAAAACE+3OMQqDQBAFUI/iCYxZJPdZMIRtFHQN5PYOKbW2EN5j4P9iYCZPtXyW/C3111ylD69h+Gc45rk/U4r1NnXdI2be6lrG90XPbWvNS5xvAAAAAAAAAAAA4D523kNDtgAoAAA=", + "H4sIAAAAAAACE+3RMQ7CMBAEQNe8Ii8IBhzxHhcIpYDCcSLxewwNiJ4IiZlmb6+54vp+m691PJe8jPUWviI2x2F4ZvOZMe7Ta37sdzGlQ+hiWME81Vza+fCf3p7flbmVy2kTAAAAAAAAAAAA+Hl3jhn2/wAoAAA=", + "H4sIAAAAAAACE+3TPQrCQBAG0K09RY4wRoPn2UJCClOsG8Hbu6YJ2CtI3mvmp5li+PJcp7Hkx1Sf6VuiuQzDWpvPGtGft/69P0Z/itRF+oHlXnNp59M+5e3/XVnacLseEnv8v/zLv/wDAAAAAAAAAPyZF/c+VksAKAAA", + ]) { + const { installation, validations } = yield* makeHarness({ + native: true, + archive: Buffer.from(archive, "base64"), + platform: "linux", + previous: true, + }); + yield* installation.start; + expect((yield* terminalState(installation)).phase).toBe("failed"); + expect(validations).toEqual([]); + yield* expectPreviousRelease(installation); + } + }), + ); + + it.effect.each([true, false])( + "respects background update checks (%s) while allowing explicit installation", + (enabled) => + Effect.gen(function* () { + const { installation, requests } = yield* makeHarness({ + native: true, + archive: Buffer.from(serverContents), + platform: "win32", + updateChecksEnabled: Effect.succeed(enabled), + }); + yield* installation.checkForUpdate; + if (enabled) { + yield* installation.changes.pipe( + Stream.filter((value) => value.version === "1.5.7"), + Stream.runHead, + ); + yield* installation.state; + expect(requests).toHaveLength(1); + } else { + yield* installation.changes.pipe(Stream.runHead); + expect(requests).toEqual([]); + } + yield* installation.start; + expect((yield* terminalState(installation)).phase).toBe("succeeded"); + }), + ); + + it.effect("keeps withdrawn native releases from activating or launching", () => + Effect.gen(function* () { + let withdrawn = false; + const manifest = Effect.sync(() => + withdrawn + ? ({ + ...ModelManifest.BUNDLED_MODEL_MANIFEST, + compatibility: [ + { + driver: "antigravity", + t3CodeRange: ">=0.0.42", + ranges: [{ range: ">=1.5.7", status: "broken" }], + }, + ], + } satisfies ModelManifest.ModelManifestData) + : ModelManifest.BUNDLED_MODEL_MANIFEST, + ); + const first = yield* makeHarness({ + native: true, + archive: Buffer.from(serverContents), + platform: "win32", + previous: true, + manifest, + validate: () => + Effect.sync(() => { + withdrawn = true; + }), + }); + yield* first.installation.start; + expect((yield* terminalState(first.installation)).phase).toBe("failed"); + yield* expectPreviousRelease(first.installation); + withdrawn = false; + const retry = yield* makeHarness({ + baseDir: first.baseDir, + native: true, + archive: Buffer.from(serverContents), + platform: "win32", + manifest, + }); + yield* retry.installation.start; + expect((yield* terminalState(retry.installation)).phase).toBe("succeeded"); + withdrawn = true; + expect(yield* retry.installation.resolve().pipe(Effect.flip)).toMatchObject({ + operation: "resolve", + }); + expect(yield* retry.installation.start.pipe(Effect.flip)).toMatchObject({ + operation: "start", + }); + const recovery = yield* makeHarness({ + baseDir: first.baseDir, + native: true, + nativeVersion: "1.5.6", + archive: Buffer.from("recovery runtime"), + platform: "win32", + manifest, + }); + yield* recovery.installation.checkForUpdate; + expect(yield* recovery.installation.state).toMatchObject({ + installedVersion: "1.5.7", + version: "1.5.6", + }); + yield* recovery.installation.start; + expect(yield* terminalState(recovery.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "1.5.6", + }); + }), + ); + + it.effect("discovers subsequent native releases from Google's CLI channel", () => + Effect.gen(function* () { + const first = yield* makeHarness({ + native: true, + archive: Buffer.from(serverContents), + platform: "win32", + }); + yield* first.installation.start; + expect((yield* terminalState(first.installation)).phase).toBe("succeeded"); + const initialPath = (yield* first.installation.resolve()).executablePath; + const next = yield* makeHarness({ + baseDir: first.baseDir, + native: true, + nativeVersion: "1.5.8", + archive: Buffer.from("next runtime"), + platform: "win32", + }); + yield* next.installation.start; + expect(yield* terminalState(next.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "1.5.8", + }); + const nextPath = (yield* next.installation.resolve()).executablePath; + expect(nextPath).not.toBe(initialPath); + const republished = yield* makeHarness({ + baseDir: first.baseDir, + native: true, + nativeVersion: "1.5.8", + archive: Buffer.from("republished runtime"), + platform: "win32", + }); + yield* republished.installation.start; + expect((yield* terminalState(republished.installation)).phase).toBe("succeeded"); + expect((yield* republished.installation.resolve()).executablePath).not.toBe(nextPath); + const offline = yield* makeHarness({ + baseDir: first.baseDir, + native: true, + nativeManifest: () => ({}), + archive: Buffer.from("unused"), + platform: "win32", + }); + yield* offline.installation.start; + expect(yield* terminalState(offline.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "1.5.8", + }); + expect(offline.requests.filter((url) => url.includes("storage.googleapis.com"))).toEqual([]); + }), + ); + + it.effect.each([ + { + name: "invalid checksum", + change: (manifest: { version: string; url: string; sha512: string }) => ({ + ...manifest, + sha512: "0".repeat(128), + }), + }, + { + name: "foreign download", + change: (manifest: { version: string; url: string; sha512: string }) => ({ + ...manifest, + url: "https://example.com/agy.exe", + }), + }, + ])("rejects a native $name and preserves the legacy release", ({ change }) => + Effect.gen(function* () { + const { installation, validations } = yield* makeHarness({ + native: true, + nativeManifest: change, + archive: Buffer.from(serverContents), + platform: "win32", + previous: true, + }); + const result = yield* Effect.result(installation.start); + if (result._tag === "Success") + expect((yield* terminalState(installation)).phase).toBe("failed"); + expect(validations).toEqual([]); + yield* expectPreviousRelease(installation); + }), + ); + it.effect("reports missing Node before downloading the standalone provider runtime", () => Effect.gen(function* () { const { installation, requests, validations } = yield* makeHarness(); @@ -768,10 +1052,11 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity inst const windowsDirectory = path.join(baseDir, `windows-${name}`); yield* fs.makeDirectory(windowsDirectory); yield* fs.writeFileString(path.join(windowsDirectory, name), "cli"); - expect(yield* windows.resolve("agy", { PATH: windowsDirectory })).toMatchObject({ - executablePath: path.join(windowsDirectory, name), - harnessPath: null, - }); + const selected = yield* windows.resolve("agy", { PATH: windowsDirectory }); + expect(selected.harnessPath).toBeNull(); + expect((yield* fs.realPath(selected.executablePath)).toLowerCase()).toBe( + (yield* fs.realPath(path.join(windowsDirectory, name))).toLowerCase(), + ); } }), ); @@ -864,14 +1149,29 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity inst it.effect("keeps leased releases available while new sessions resolve the new release", () => Effect.gen(function* () { - const { installation, fs, stagingReleased } = yield* makeHarness({ previous: true }); + const manifestEntered = yield* Deferred.make(); + const releaseManifest = yield* Deferred.make(); + const { installation, fs, stagingReleased } = yield* makeHarness({ + native: true, + platform: "win32", + archive: Buffer.from(serverContents), + previous: true, + beforeManifest: Deferred.succeed(manifestEntered, undefined).pipe( + Effect.andThen(Deferred.await(releaseManifest)), + ), + }); const processScope = yield* Scope.make(); const oldExecutable = yield* installation.acquire().pipe(Scope.provide(processScope)); - yield* installation.start; + const starting = yield* installation.start.pipe(Effect.forkScoped); + yield* Deferred.await(manifestEntered); + const concurrent = yield* installation.acquire().pipe(Scope.provide(processScope)); + expect(concurrent.executablePath).toBe(oldExecutable.executablePath); + yield* Deferred.succeed(releaseManifest, undefined); + yield* Fiber.join(starting); expect((yield* terminalState(installation)).phase).toBe("succeeded"); yield* Deferred.await(stagingReleased); const current = yield* installation.resolve(); - expect(current.version).toBe("fixture-new"); + expect(current.version).toBe("1.5.7"); expect(current.executablePath).not.toBe(oldExecutable.executablePath); expect(yield* fs.readFileString(oldExecutable.executablePath)).toBe(serverContents); expect(yield* installation.remove().pipe(Effect.flip)).toMatchObject({ operation: "remove" }); diff --git a/apps/server/src/provider/AntigravityInstallation.ts b/apps/server/src/provider/AntigravityInstallation.ts index 6f78dc15e842c..feb412867f2e4 100644 --- a/apps/server/src/provider/AntigravityInstallation.ts +++ b/apps/server/src/provider/AntigravityInstallation.ts @@ -1,7 +1,11 @@ // @effect-diagnostics nodeBuiltinImport:off - Effect has no incremental digest or free-space query. +import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; +import * as ModelManifest from "./ModelManifest.ts"; +import { resolveProviderCompatibility } from "./providerCompatibility.ts"; +import { cliArchiveTarCommand } from "@t3tools/shared/cliRelease"; +import { compareSemverVersions } from "@t3tools/shared/semver"; import * as EffectNodeStream from "@effect/platform-node/NodeStream"; import { ProviderDriverKind, type ProviderInstallState } from "@t3tools/contracts"; -import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { resolveNodeExecutable, nodeRuntimeUnavailableMessage } from "@t3tools/shared/nodeRuntime"; import { resolveCommandPath } from "@t3tools/shared/shell"; @@ -30,20 +34,27 @@ import * as NodeFSP from "node:fs/promises"; import * as EffectAcpErrors from "effect-acp/errors"; import * as ServerConfig from "../config.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import { + ANTIGRAVITY_CLI_MANIFEST_BASE, + antigravityCliTarget, + parseAntigravityCliRelease, + type AntigravityCliReleaseAsset, +} from "./antigravityCliRelease.ts"; import { openZipArchive } from "../zipArchive.ts"; import { makeAntigravityAcpRuntime } from "./acp/AntigravityAcpSupport.ts"; import { buildAntigravityAcpSpawnInput, prepareAntigravityProfile, } from "./antigravityAuthSupport.ts"; -import { - resolveAntigravityReleaseAsset, - type AntigravityReleaseAsset, -} from "./antigravityRelease.ts"; +import { type AntigravityReleaseAsset } from "./antigravityRelease.ts"; const DRIVER = ProviderDriverKind.make("antigravity"); const DOWNLOAD_TIMEOUT = "45 minutes"; const VALIDATION_TIMEOUT = "90 seconds"; +const MAX_DOWNLOAD_BYTES = 512 * 1024 * 1024; +const MAX_EXECUTABLE_BYTES = 512 * 1024 * 1024; +const UPDATE_CHECK_INTERVAL = 60 * 60 * 1000; const FREE_SPACE_MARGIN = 256 * 1024 * 1024; const RECORD_MAX_BYTES = 8 * 1024; const RELEASE_RECORD = ".install-complete.json"; @@ -56,7 +67,7 @@ const InstalledRelease = Schema.Struct({ releaseId: ReleaseId, version: Schema.String, executable: Schema.Struct({ name: Schema.String, bytes: Schema.Number }), - harness: Schema.Struct({ name: Schema.String, bytes: Schema.Number }), + harness: Schema.NullOr(Schema.Struct({ name: Schema.String, bytes: Schema.Number })), }); type InstalledRelease = typeof InstalledRelease.Type; const encodeActiveRelease = Schema.encodeEffect(Schema.fromJsonString(ActiveRelease)); @@ -103,6 +114,7 @@ interface AntigravityInstallationService { ) => Effect.Effect; readonly state: Effect.Effect; readonly changes: Stream.Stream; + readonly checkForUpdate: Effect.Effect; readonly remove: ( protectedBinaryPaths?: ReadonlyArray, ) => Effect.Effect; @@ -116,14 +128,22 @@ export class AntigravityInstallation extends Context.Service< AntigravityInstallation, Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; - return yield* makeAntigravityInstallation({ baseDir: config.baseDir }); + const settings = yield* ServerSettings.ServerSettingsService; + return yield* makeAntigravityInstallation({ + baseDir: config.baseDir, + updateChecksEnabled: settings.getSettings.pipe( + Effect.map((value) => value.enableProviderUpdateChecks), + Effect.orElseSucceed(() => false), + ), + }); }), ); } export interface AntigravityInstallationOptions { readonly baseDir: string; - readonly releaseAsset?: AntigravityReleaseAsset | null; + readonly releaseAsset?: AntigravityReleaseAsset | AntigravityCliReleaseAsset | null; + readonly updateChecksEnabled?: Effect.Effect; readonly validate?: ( executable: AntigravityExecutable, expectedVersion: string, @@ -162,6 +182,7 @@ function isRunning(state: ProviderInstallState) { export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.make")(function* ( options: AntigravityInstallationOptions, ) { + const manifestService = yield* ModelManifest.ModelManifest; const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const random = yield* SecureRandom.SecureRandom; @@ -171,10 +192,11 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma const platform = yield* HostProcess.Platform; const arch = yield* HostProcess.Architecture; const environment = yield* HostProcess.Environment; - const releaseAsset = + let releaseAsset = options.releaseAsset ?? null; + const supported = options.releaseAsset === undefined - ? resolveAntigravityReleaseAsset(platform, arch) - : options.releaseAsset; + ? antigravityCliTarget(platform, arch) !== null + : options.releaseAsset !== null; const names = executableNames(platform); const managedDirectory = path.join( options.baseDir, @@ -192,13 +214,36 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma operationId: null, phase: "idle", downloadedBytes: 0, - totalBytes: releaseAsset?.archiveBytes ?? null, + totalBytes: + releaseAsset !== null && "archiveBytes" in releaseAsset ? releaseAsset.archiveBytes : null, version: releaseAsset?.version ?? null, installedVersion: null, canRemove: false, message: null, }); + const isWithdrawn = Effect.fn("AntigravityInstallation.isWithdrawn")(function* (version: string) { + const manifest = yield* manifestService.current; + const status = ( + resolveProviderCompatibility(manifest.compatibility, DRIVER, version) ?? + resolveProviderCompatibility( + ModelManifest.BUNDLED_MODEL_MANIFEST.compatibility, + DRIVER, + version, + ) + )?.status; + return status === "broken" || status === "unsupported"; + }); + const ensureEligible = Effect.fn("AntigravityInstallation.ensureEligible")(function* ( + version: string, + ) { + if (yield* isWithdrawn(version)) + return yield* installationError( + "verify", + "This Antigravity release was withdrawn. Check for updates and try again.", + ); + }); + const readRecord = Effect.fn("AntigravityInstallation.readRecord")(function* ( filePath: string, schema: Schema.Codec, @@ -234,15 +279,20 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma const record = yield* readRecord(path.join(directory, RELEASE_RECORD), InstalledRelease); if ( record.releaseId !== releaseId || - record.executable.name !== names.executable || - record.harness.name !== names.harness || + (record.harness === null + ? record.executable.name !== (platform === "win32" ? "agy.exe" : "antigravity") + : record.executable.name !== names.executable || record.harness.name !== names.harness) || !Number.isSafeInteger(record.executable.bytes) || record.executable.bytes <= 0 || - !Number.isSafeInteger(record.harness.bytes) || - record.harness.bytes <= 0 || + (record.harness !== null && + (!Number.isSafeInteger(record.harness.bytes) || record.harness.bytes <= 0)) || !record.version.trim() || - !(yield* executableFile(path.join(directory, names.executable), record.executable.bytes)) || - !(yield* executableFile(path.join(directory, names.harness), record.harness.bytes)) + !(yield* executableFile( + path.join(directory, record.executable.name), + record.executable.bytes, + )) || + (record.harness !== null && + !(yield* executableFile(path.join(directory, record.harness.name), record.harness.bytes))) ) { return yield* installationError( "resolve", @@ -250,8 +300,8 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma ); } return { - executablePath: path.join(directory, names.executable), - harnessPath: path.join(directory, names.harness), + executablePath: path.join(directory, record.executable.name), + harnessPath: record.harness === null ? null : path.join(directory, record.harness.name), source: "managed", version: record.version, managedVersionDirectory: directory, @@ -264,6 +314,16 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma ) { if (!(yield* executableFile(candidate))) return null; const executablePath = yield* fs.realPath(candidate); + const realVersions = yield* fs.realPath(versionsDirectory).pipe(Effect.option); + const directory = path.dirname(executablePath); + if ( + Option.isSome(realVersions) && + path.dirname(directory) === realVersions.value && + /^[a-f0-9]{64}$/u.test(path.basename(directory)) + ) { + const installed = yield* completedRelease(path.basename(directory)); + return { ...installed, source }; + } // Keep launcher symlinks intact: version-manager shims dispatch by their invoked name. if (isAntigravityCli(candidate, executablePath)) { return { @@ -274,18 +334,8 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma managedVersionDirectory: null, } satisfies AntigravityExecutable; } - const directory = path.dirname(executablePath); const harnessPath = path.join(directory, names.harness); if (!(yield* executableFile(harnessPath))) return null; - const realVersions = yield* fs.realPath(versionsDirectory).pipe(Effect.option); - if ( - Option.isSome(realVersions) && - path.dirname(directory) === realVersions.value && - /^[a-f0-9]{64}$/u.test(path.basename(directory)) - ) { - const installed = yield* completedRelease(path.basename(directory)); - return { ...installed, executablePath, harnessPath, source } satisfies AntigravityExecutable; - } return { executablePath, harnessPath, @@ -343,7 +393,13 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma } if (yield* fs.exists(activePath)) { const active = yield* readRecord(activePath, ActiveRelease); - return yield* completedRelease(active.releaseId); + const installed = yield* completedRelease(active.releaseId); + if (yield* isWithdrawn(installed.version)) + return yield* installationError( + "resolve", + `Antigravity ${installed.version} no longer works with this T3 Code release. Update it in Antigravity setup.`, + ); + return installed; } for (const candidate of yield* commandCandidates(names.executable, processEnvironment)) { const selected = yield* fromExternal(candidate, "path"); @@ -351,7 +407,7 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma } return yield* installationError( "resolve", - releaseAsset + supported ? "Antigravity ACP runtime is not installed. Install it in this environment's provider settings or set a custom ACP executable path. The Antigravity app, IDE, and CLI are separate installations." : `Google does not publish an Antigravity runtime for ${platform}-${arch}. Use a supported environment or a custom executable.`, ); @@ -440,8 +496,10 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma }); const initialized = yield* runtime.initialize(); if ( - initialized.agentInfo?.name !== "antigravity-acp" || - initialized.agentInfo.version !== expectedVersion || + (executable.harnessPath === null + ? initialized.agentInfo?.name !== "Antigravity ACP Server" + : initialized.agentInfo?.name !== "antigravity-acp") || + initialized.agentInfo?.version !== expectedVersion || // Antigravity 1.1.1 may report protocol 2 with legacy ACP; choose wire format from the response shape. (initialized.protocolVersion !== 1 && initialized.protocolVersion !== 2) || initialized.agentCapabilities?.loadSession !== true || @@ -472,7 +530,12 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma ); const install = Effect.fn("AntigravityInstallation.install")( - function* (asset: AntigravityReleaseAsset) { + function* (asset: AntigravityReleaseAsset | AntigravityCliReleaseAsset) { + yield* ensureEligible(asset.version); + const cli = "sha512" in asset; + // Existing installation records use 64-character IDs, including native SHA-512 prefixes. + const releaseId = cli ? asset.sha512.slice(0, 64) : asset.sha256; + const archiveBytes = cli ? null : asset.archiveBytes; yield* resolveNodeExecutable("Antigravity", environment).pipe( Effect.provideService(FileSystem.FileSystem, fs), Effect.provideService(Path.Path, path), @@ -481,7 +544,7 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma installationError("verify", nodeRuntimeUnavailableMessage("Antigravity"), cause), ), ); - if (platform === "linux" && arch === "arm64") { + if (!cli && platform === "linux" && arch === "arm64") { const pageSize = yield* spawner .string(ChildProcess.make("getconf", ["PAGESIZE"], { stdin: "ignore", stderr: "ignore" })) .pipe( @@ -497,19 +560,19 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma SubscriptionRef.update(state, (current) => ({ ...current, phase, message })); yield* fs.makeDirectory(versionsDirectory, { recursive: true }); yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove: true })); - const destination = path.join(versionsDirectory, asset.sha256); + const destination = path.join(versionsDirectory, releaseId); const activate = Effect.fn("AntigravityInstallation.activate")( function* () { + yield* ensureEligible(asset.version); const pointerDirectory = yield* fs.makeTempDirectoryScoped({ directory: managedDirectory, prefix: "active.json.", }); const pointerPath = path.join(pointerDirectory, "contents.tmp"); - yield* fs.writeFileString( - pointerPath, - yield* encodeActiveRelease({ releaseId: asset.sha256 }), - { flag: "wx", mode: 0o600 }, - ); + yield* fs.writeFileString(pointerPath, yield* encodeActiveRelease({ releaseId }), { + flag: "wx", + mode: 0o600, + }); yield* fs.rename(pointerPath, activePath); yield* SubscriptionRef.update( state, @@ -533,7 +596,7 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma ); if (yield* fs.exists(destination)) { - const existing = yield* completedRelease(asset.sha256); + const existing = yield* completedRelease(releaseId); if (existing.version !== asset.version) { return yield* installationError( "verify", @@ -553,8 +616,9 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma try: () => NodeFSP.statfs(versionsDirectory, { bigint: true }), catch: (cause) => installationError("download", "Could not check free disk space.", cause), }).pipe(Effect.option); - const required = - asset.archiveBytes + asset.executable.bytes + asset.harness.bytes + FREE_SPACE_MARGIN; + const required = cli + ? MAX_DOWNLOAD_BYTES + MAX_EXECUTABLE_BYTES + FREE_SPACE_MARGIN + : asset.archiveBytes + asset.executable.bytes + asset.harness.bytes + FREE_SPACE_MARGIN; if ( Option.isSome(available) && available.value.bavail * available.value.bsize < BigInt(required) @@ -571,7 +635,7 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma const archivePath = path.join(staging, "download.zip"); const pairDirectory = path.join(staging, "runtime"); yield* fs.makeDirectory(pairDirectory); - const hash = NodeCrypto.createHash("sha256"); + const hash = NodeCrypto.createHash(cli ? "sha512" : "sha256"); let downloadedBytes = 0; let lastProgressAt = yield* Clock.currentTimeMillis; yield* Effect.gen(function* () { @@ -585,7 +649,8 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma if ( identityBody && contentLength !== undefined && - Number(contentLength) !== asset.archiveBytes + archiveBytes !== null && + Number(contentLength) !== archiveBytes ) { return yield* installationError( "download", @@ -596,15 +661,15 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma Stream.tap((chunk) => Effect.gen(function* () { downloadedBytes += chunk.byteLength; - if (downloadedBytes > asset.archiveBytes) { + if (downloadedBytes > (archiveBytes ?? MAX_DOWNLOAD_BYTES)) { return yield* installationError( "download", - "The Antigravity download exceeded the pinned release size.", + "The Antigravity download exceeded its allowed size.", ); } hash.update(chunk); const now = yield* Clock.currentTimeMillis; - if (now - lastProgressAt >= 250 || downloadedBytes === asset.archiveBytes) { + if (now - lastProgressAt >= 250 || downloadedBytes === archiveBytes) { lastProgressAt = now; yield* SubscriptionRef.update(state, (current) => ({ ...current, @@ -627,98 +692,154 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma : cause, ), ); - if (downloadedBytes !== asset.archiveBytes || hash.digest("hex") !== asset.sha256) { + if ( + (archiveBytes !== null && downloadedBytes !== archiveBytes) || + hash.digest("hex") !== (cli ? asset.sha512 : asset.sha256) + ) { return yield* installationError( "download", - "The Antigravity download failed its size or SHA-256 check. Nothing was installed.", + "The Antigravity download failed its size or checksum check. Nothing was installed.", ); } yield* report("extracting", "Extracting the verified runtime."); - yield* Effect.gen(function* () { - const archive = yield* openZipArchive(archivePath, (detail, cause) => - installationError("extract", detail, cause), - ); - if (archive.entryCount !== 2) { - return yield* installationError( - "extract", - "The archive must contain exactly the Antigravity executable and its harness.", - ); - } - const seen = new Set(); - for (;;) { - const entry = yield* archive.next; - if (!entry) break; - const expected = [asset.executable, asset.harness].find( - (file) => file.name === entry.fileName, - ); - const unixType = (entry.externalFileAttributes >>> 16) & 0o170000; + if (cli) { + const executablePath = path.join(pairDirectory, asset.executable.name); + if (asset.format === "executable") { + yield* fs.copyFile(archivePath, executablePath); + } else { + const tar = cliArchiveTarCommand(platform, environment); + const list = yield* spawner.string(ChildProcess.make(tar, ["-tzf", archivePath])); + const types = yield* spawner.string(ChildProcess.make(tar, ["-tvzf", archivePath])); if ( - !expected || - seen.has(entry.fileName) || - entry.fileName.includes("/") || - entry.fileName.includes("\\") || - (unixType !== 0 && unixType !== 0o100000) || - (entry.externalFileAttributes & 0x10) !== 0 || - (entry.generalPurposeBitFlag & 1) !== 0 || - ![0, 8].includes(entry.compressionMethod) || - entry.uncompressedSize !== expected.bytes + list.trim() !== asset.executable.name || + types.trim().split(/\r?\n/u).length !== 1 || + !types.startsWith("-") ) { return yield* installationError( "extract", - "The archive contains an unexpected, unsafe, or incorrectly sized member.", + "The Antigravity archive must contain one regular executable.", ); } - seen.add(entry.fileName); yield* Effect.gen(function* () { - const readable = yield* archive.streamEntry(entry); + const child = yield* spawner.spawn( + ChildProcess.make(tar, ["-xOzf", archivePath, asset.executable.name], { + stdout: "pipe", + stderr: "pipe", + }), + ); let extractedBytes = 0; - yield* EffectNodeStream.fromReadable({ - evaluate: () => readable, - onError: wrapFailure("extract", "Could not extract the Antigravity runtime."), - }).pipe( + yield* child.stdout.pipe( Stream.tap((chunk) => Effect.gen(function* () { extractedBytes += chunk.byteLength; - if (extractedBytes > expected.bytes) { + if (extractedBytes > MAX_EXECUTABLE_BYTES) return yield* installationError( "extract", - "An archive member exceeded its pinned size.", + "The Antigravity executable exceeded its size limit.", ); - } }), ), - Stream.run( - fs.sink(path.join(pairDirectory, entry.fileName), { flag: "wx", mode: 0o700 }), - ), + Stream.run(fs.sink(executablePath, { flag: "wx", mode: 0o700 })), ); - if (extractedBytes !== expected.bytes) { - return yield* installationError("extract", "An archive member was truncated."); - } + if ((yield* child.exitCode) !== 0 || extractedBytes === 0) + return yield* installationError( + "extract", + "Could not extract the Antigravity executable.", + ); }).pipe(Effect.scoped); } - if (!seen.has(asset.executable.name) || !seen.has(asset.harness.name)) { - return yield* installationError( - "extract", - "The archive is missing the Antigravity executable or its harness.", + } else + yield* Effect.gen(function* () { + const archive = yield* openZipArchive(archivePath, (detail, cause) => + installationError("extract", detail, cause), ); - } - }).pipe(Effect.scoped); + if (archive.entryCount !== 2) { + return yield* installationError( + "extract", + "The archive must contain exactly the Antigravity executable and its harness.", + ); + } + const seen = new Set(); + for (;;) { + const entry = yield* archive.next; + if (!entry) break; + const expected = [asset.executable, asset.harness].find( + (file) => file.name === entry.fileName, + ); + const unixType = (entry.externalFileAttributes >>> 16) & 0o170000; + if ( + !expected || + seen.has(entry.fileName) || + entry.fileName.includes("/") || + entry.fileName.includes("\\") || + (unixType !== 0 && unixType !== 0o100000) || + (entry.externalFileAttributes & 0x10) !== 0 || + (entry.generalPurposeBitFlag & 1) !== 0 || + ![0, 8].includes(entry.compressionMethod) || + entry.uncompressedSize !== expected.bytes + ) { + return yield* installationError( + "extract", + "The archive contains an unexpected, unsafe, or incorrectly sized member.", + ); + } + seen.add(entry.fileName); + yield* Effect.gen(function* () { + const readable = yield* archive.streamEntry(entry); + let extractedBytes = 0; + yield* EffectNodeStream.fromReadable({ + evaluate: () => readable, + onError: wrapFailure("extract", "Could not extract the Antigravity runtime."), + }).pipe( + Stream.tap((chunk) => + Effect.gen(function* () { + extractedBytes += chunk.byteLength; + if (extractedBytes > expected.bytes) { + return yield* installationError( + "extract", + "An archive member exceeded its pinned size.", + ); + } + }), + ), + Stream.run( + fs.sink(path.join(pairDirectory, entry.fileName), { flag: "wx", mode: 0o700 }), + ), + ); + if (extractedBytes !== expected.bytes) { + return yield* installationError("extract", "An archive member was truncated."); + } + }).pipe(Effect.scoped); + } + if (!seen.has(asset.executable.name) || !seen.has(asset.harness.name)) { + return yield* installationError( + "extract", + "The archive is missing the Antigravity executable or its harness.", + ); + } + }).pipe(Effect.scoped); yield* fs.remove(archivePath); const executablePath = path.join(pairDirectory, asset.executable.name); - const harnessPath = path.join(pairDirectory, asset.harness.name); + const harnessPath = cli ? null : path.join(pairDirectory, asset.harness.name); if (platform !== "win32") { yield* fs.chmod(executablePath, 0o755); - yield* fs.chmod(harnessPath, 0o755); + if (harnessPath !== null) yield* fs.chmod(harnessPath, 0o755); } - if (platform === "darwin" && arch === "x64") { + if (!cli && platform === "darwin" && arch === "x64") { // Google signs the Intel build with the hardened runtime but no JIT entitlement, so // libffi's writable+executable trampolines spin forever. Re-sign ad hoc after the hash check. const exitCode = yield* spawner .spawn( ChildProcess.make( "/usr/bin/codesign", - ["--force", "--sign", "-", executablePath, harnessPath], + [ + "--force", + "--sign", + "-", + executablePath, + ...(harnessPath === null ? [] : [harnessPath]), + ], { stdout: "ignore", stderr: "ignore" }, ), ) @@ -745,13 +866,16 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma asset.version, ).pipe(Effect.scoped, Effect.timeout(VALIDATION_TIMEOUT)); const record: InstalledRelease = { - releaseId: asset.sha256, + releaseId, version: asset.version, executable: { name: asset.executable.name, bytes: Number((yield* fs.stat(executablePath)).size), }, - harness: { name: asset.harness.name, bytes: Number((yield* fs.stat(harnessPath)).size) }, + harness: + cli || harnessPath === null + ? null + : { name: asset.harness.name, bytes: Number((yield* fs.stat(harnessPath)).size) }, }; yield* fs.writeFileString( path.join(pairDirectory, RELEASE_RECORD), @@ -760,7 +884,7 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma ); yield* fs.rename(pairDirectory, destination).pipe( Effect.catch((cause) => - completedRelease(asset.sha256).pipe( + completedRelease(releaseId).pipe( Effect.flatMap((existing) => existing.version === asset.version ? validate(existing, asset.version).pipe( @@ -795,31 +919,119 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma ), ); - const start = gate - .withPermit( + let lastUpdateCheck: number | undefined; + const refreshRelease = Effect.fn("AntigravityInstallation.refreshRelease")(function* ( + explicit = false, + ) { + if (options.releaseAsset !== undefined || !supported) return; + if (!explicit && !(yield* options.updateChecksEnabled ?? Effect.succeed(true))) return; + const now = yield* Clock.currentTimeMillis; + if (!explicit && lastUpdateCheck !== undefined && now - lastUpdateCheck < UPDATE_CHECK_INTERVAL) + return; + lastUpdateCheck = now; + const musl = + platform === "linux" && + (yield* fs.exists( + arch === "arm64" ? "/lib/libc.musl-aarch64.so.1" : "/lib/libc.musl-x86_64.so.1", + )); + const target = antigravityCliTarget(platform, arch, musl); + const latest = yield* http.get(`${ANTIGRAVITY_CLI_MANIFEST_BASE}/${target}.json`).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap((response) => response.json), + Effect.map((json) => parseAntigravityCliRelease(json, platform, arch, musl)), + Effect.timeout("10 seconds"), + Effect.orElseSucceed(() => null), + ); + if (latest === null) return; + if (yield* isWithdrawn(latest.version)) { + releaseAsset = null; + return; + } + releaseAsset = latest; + yield* SubscriptionRef.updateEffect(state, (value) => + isRunning(value) + ? Effect.succeed(value) + : Effect.gen(function* () { + const keepInstalled = + value.installedVersion !== null && + compareSemverVersions(value.installedVersion, latest.version) > 0 && + !(yield* isWithdrawn(value.installedVersion)); + return { + ...value, + version: keepInstalled ? value.installedVersion : latest.version, + totalBytes: null, + }; + }), + ); + }); + + const start = Effect.gen(function* () { + const current = yield* SubscriptionRef.get(state); + if (isRunning(current)) return current; + yield* refreshRelease(true); + return yield* gate.withPermit( Effect.gen(function* () { const current = yield* SubscriptionRef.get(state); if (isRunning(current)) return current; - if (!releaseAsset) { + if (!supported) { return yield* installationError( "start", `Google does not publish an Antigravity runtime for ${platform}-${arch}. Use a supported remote environment or a custom executable.`, ); } + const asset = + releaseAsset !== null && !(yield* isWithdrawn(releaseAsset.version)) + ? releaseAsset + : null; + const installed = yield* resolve().pipe(Effect.option); + const reuse = + Option.isSome(installed) && + installed.value.source === "managed" && + installed.value.harnessPath === null && + (asset === null || compareSemverVersions(installed.value.version!, asset.version) > 0) + ? installed.value + : undefined; + if (asset === null && reuse === undefined) + return yield* installationError( + "start", + "Could not find a native Antigravity CLI release. Check the network connection and try again.", + ); const operationId = yield* random.uuidV4(); const next: ProviderInstallState = { driver: DRIVER, operationId, - phase: "downloading", + phase: reuse === undefined ? "downloading" : "verifying", downloadedBytes: 0, - totalBytes: releaseAsset.archiveBytes, - version: releaseAsset.version, + totalBytes: asset !== null && "archiveBytes" in asset ? asset.archiveBytes : null, + version: reuse?.version ?? asset?.version ?? null, installedVersion: current.installedVersion, canRemove: current.canRemove, - message: "Downloading Google's official Antigravity runtime.", + message: + reuse === undefined + ? "Downloading Google's official Antigravity runtime." + : "Checking the installed runtime.", }; yield* SubscriptionRef.set(state, next); - const work = install(releaseAsset).pipe( + const work = ( + reuse === undefined + ? install(asset!) + : validate(reuse, reuse.version!).pipe( + Effect.scoped, + Effect.timeout(VALIDATION_TIMEOUT), + Effect.andThen(ensureEligible(reuse.version!)), + Effect.andThen( + SubscriptionRef.update(state, (value) => ({ + ...value, + phase: "succeeded" as const, + installedVersion: reuse.version, + message: null, + })), + ), + ) + ).pipe( + Effect.mapError( + wrapFailure("verify", "Could not verify the installed Antigravity runtime."), + ), Effect.onExit((exit) => Exit.isFailure(exit) ? SubscriptionRef.update(state, (value) => { @@ -850,8 +1062,8 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma running = { operationId, fiber }; return next; }).pipe(Effect.uninterruptible), - ) - .pipe(Effect.mapError(wrapFailure("start", "Could not start the Antigravity installation."))); + ); + }).pipe(Effect.mapError(wrapFailure("start", "Could not start the Antigravity installation."))); const cancel = Effect.fn("AntigravityInstallation.cancel")(function* (operationId: string) { return yield* gate.withPermit( @@ -959,6 +1171,7 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma cancel, state: SubscriptionRef.get(state), changes: SubscriptionRef.changes(state), + checkForUpdate: refreshRelease().pipe(Effect.ignore), remove, }); }); diff --git a/apps/server/src/provider/CodexInstallation.test.ts b/apps/server/src/provider/CodexInstallation.test.ts index 98861629c79f5..5536fe7a1704d 100644 --- a/apps/server/src/provider/CodexInstallation.test.ts +++ b/apps/server/src/provider/CodexInstallation.test.ts @@ -41,6 +41,8 @@ const makeHarness = Effect.fn("test.makeCodexInstallation")(function* ( platform?: NodeJS.Platform; spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"]; runtimeRenameFailures?: number; + /** Served by URL instead of the pinned package. */ + responses?: Readonly Response>>; } = {}, ) { const fs = yield* FileSystem.FileSystem; @@ -110,6 +112,8 @@ const makeHarness = Effect.fn("test.makeCodexInstallation")(function* ( HttpClient.make((request) => Effect.sync(() => { downloads++; + const respond = input.responses?.[request.url]; + if (respond) return HttpClientResponse.fromWeb(request, respond()); return Object.defineProperty( HttpClientResponse.fromWeb( request, @@ -529,4 +533,214 @@ it.effect("keeps an activated runtime when a later update fails verification", ( }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); -// Stands in for Windows' bsdtar: CRLF listings, and extraction writes the Windows layout. +const upstreamVersion = "0.163.0"; +const upstreamArchive = Buffer.from( + "H4sIAAAAAAACA+3WzY7CIBQF4D5Kw1oqtNQmPoh7rKStP9BQdMaYefcBE43T9RQ1nm8B7Q1Jk94cYN3peW026juZDvOqsrzO3nj2yofnUK9KwZKUJREcByet/2TymabuPby29S3/NIz0EIbWDC5u/sXf/PO8EAL5j+G/ew1vuP/TXrp2bpunnf/5KP+syCvkP4bJmg5vlf96JxuVbQej4+efi2qUf17g/h/Hhezl2RzdStmhM5osUz5Lyen+RljGF0XGiK/6H9UoF4pS2rpdCCr7fq/oRtqvTocVSjt77k2nr6vud0vyg6ABAAAAAAAAAAAAAABE8gvVbjvaACgAAA==", + "base64", +); +const upstreamReleaseUrl = `https://github.com/openai/codex/releases/download/rust-v${upstreamVersion}`; +const upstreamResponses = (checksum: string) => ({ + "https://registry.npmjs.org/@openai/codex/latest": () => + Response.json({ version: upstreamVersion }), + [`${upstreamReleaseUrl}/codex-package_SHA256SUMS`]: () => + new Response( + `${"0".repeat(64)} codex-package-x86_64-apple-darwin.tar.gz\n${checksum} codex-package-aarch64-apple-darwin.tar.gz\n`, + ), + [`${upstreamReleaseUrl}/codex-package-aarch64-apple-darwin.tar.gz`]: () => + new Response(upstreamArchive), +}); + +it.effect("updates a managed install to OpenAI's newest release and never downgrades it", () => + Effect.gen(function* () { + const digest = yield* Digest.Digest; + const checksum = Hex.encode( + yield* digest.digest(Digest.sha256, upstreamArchive).pipe(Effect.orDie), + ); + const h = yield* makeHarness({ responses: upstreamResponses(checksum) }); + yield* h.installation.checkForUpdate; + // A fresh install still gets the pinned release. + expect((yield* h.installation.state).version).toBe("0.156.1"); + yield* h.installation.start; + expect(yield* terminalState(h.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "0.156.1", + version: upstreamVersion, + }); + + yield* h.installation.start; + expect(yield* terminalState(h.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: upstreamVersion, + version: upstreamVersion, + }); + expect((yield* h.installation.resolve()).version).toBe(upstreamVersion); + + // Without upstream information the older pin is not offered as a reinstall. + const restarted = yield* makeHarness({ baseDir: h.baseDir }); + expect(yield* restarted.installation.state).toMatchObject({ + installedVersion: upstreamVersion, + version: upstreamVersion, + }); + yield* restarted.installation.start; + expect(yield* terminalState(restarted.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: upstreamVersion, + }); + expect(restarted.downloads()).toBe(0); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); + +it.effect("keeps the managed install when an update fails its published checksum", () => + Effect.gen(function* () { + const h = yield* makeHarness({ responses: upstreamResponses("f".repeat(64)) }); + yield* h.installation.start; + yield* terminalState(h.installation); + yield* h.installation.checkForUpdate; + yield* h.installation.start; + expect(yield* terminalState(h.installation)).toMatchObject({ + phase: "failed", + installedVersion: "0.156.1", + message: expect.stringContaining("SHA-256"), + }); + expect((yield* h.installation.resolve()).version).toBe("0.156.1"); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); + +it.effect("does not install a cached update the manifest has since withdrawn", () => + Effect.gen(function* () { + const digest = yield* Digest.Digest; + const checksum = Hex.encode( + yield* digest.digest(Digest.sha256, upstreamArchive).pipe(Effect.orDie), + ); + let manifest = ModelManifest.BUNDLED_MODEL_MANIFEST; + const h = yield* makeHarness({ + responses: upstreamResponses(checksum), + manifestCurrent: Effect.sync(() => manifest), + }); + yield* h.installation.start; + yield* terminalState(h.installation); + yield* h.installation.checkForUpdate; + expect((yield* h.installation.state).version).toBe(upstreamVersion); + manifest = { + ...manifest, + compatibility: [ + { + driver: "codex", + t3CodeRange: ">=0.0.42", + ranges: [ + { range: ">=0.160.0", status: "unsupported" }, + { range: ">=0.156.0 <0.160.0", status: "supported" }, + ], + }, + ], + }; + const downloads = h.downloads(); + yield* h.installation.start; + expect(yield* terminalState(h.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "0.156.1", + version: "0.156.1", + }); + expect(h.downloads()).toBe(downloads); + expect((yield* h.installation.resolve()).version).toBe("0.156.1"); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); + +it.effect("returns a managed install the manifest withdraws to the pinned release", () => + Effect.gen(function* () { + const digest = yield* Digest.Digest; + const checksum = Hex.encode( + yield* digest.digest(Digest.sha256, upstreamArchive).pipe(Effect.orDie), + ); + let manifest = ModelManifest.BUNDLED_MODEL_MANIFEST; + const h = yield* makeHarness({ + responses: upstreamResponses(checksum), + manifestCurrent: Effect.sync(() => manifest), + }); + yield* h.installation.checkForUpdate; + yield* h.installation.start; + yield* terminalState(h.installation); + yield* h.installation.start; + expect(yield* terminalState(h.installation)).toMatchObject({ + installedVersion: upstreamVersion, + }); + + manifest = { + ...manifest, + compatibility: [ + { + driver: "codex", + t3CodeRange: ">=0.0.42", + ranges: [ + { range: ">=0.160.0", status: "unsupported" }, + { range: ">=0.156.0 <0.160.0", status: "supported" }, + ], + }, + ], + }; + yield* h.installation.checkForUpdate; + expect(yield* h.installation.state).toMatchObject({ + installedVersion: upstreamVersion, + version: "0.156.1", + }); + yield* h.installation.start; + expect(yield* terminalState(h.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "0.156.1", + version: "0.156.1", + }); + expect((yield* h.installation.resolve()).version).toBe("0.156.1"); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); + +it.effect.each(["update", "reinstall"] as const)( + "rejects withdrawal during $0 validation", + (operation) => + Effect.gen(function* () { + const digest = yield* Digest.Digest; + const checksum = Hex.encode( + yield* digest.digest(Digest.sha256, upstreamArchive).pipe(Effect.orDie), + ); + let manifest = ModelManifest.BUNDLED_MODEL_MANIFEST; + let withdraw = operation === "update"; + const h = yield* makeHarness({ + responses: upstreamResponses(checksum), + manifestCurrent: Effect.sync(() => manifest), + options: { + validate: (_executable, version) => + Effect.sync(() => { + if (withdraw && version === upstreamVersion) + manifest = { + ...ModelManifest.BUNDLED_MODEL_MANIFEST, + compatibility: [ + { + driver: "codex", + t3CodeRange: ">=0.0.42", + ranges: [ + { range: ">=0.160.0", status: "unsupported" }, + { range: ">=0.156.0 <0.160.0", status: "supported" }, + ], + }, + ], + }; + }), + }, + }); + yield* h.installation.start; + yield* terminalState(h.installation); + yield* h.installation.checkForUpdate; + if (operation === "reinstall") { + yield* h.installation.start; + expect((yield* terminalState(h.installation)).phase).toBe("succeeded"); + withdraw = true; + } + yield* h.installation.start; + expect((yield* terminalState(h.installation)).phase).toBe("failed"); + if (operation === "update") { + expect((yield* h.installation.resolve()).version).toBe("0.156.1"); + } else { + expect((yield* h.installation.state).version).toBe("0.156.1"); + yield* Effect.flip(h.installation.resolve()); + } + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); diff --git a/apps/server/src/provider/CodexInstallation.ts b/apps/server/src/provider/CodexInstallation.ts index 8fdcfbebb328e..c1e489ec0e1eb 100644 --- a/apps/server/src/provider/CodexInstallation.ts +++ b/apps/server/src/provider/CodexInstallation.ts @@ -4,7 +4,7 @@ import { type ProviderInstallState, type ServerProviderCompatibilityAdvisory, } from "@t3tools/contracts"; -import { cliArchiveTarCommand } from "@t3tools/shared/cliRelease"; +import { cliArchiveTarCommand, parseChecksums } from "@t3tools/shared/cliRelease"; import { compareSemverVersions } from "@t3tools/shared/semver"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { resolveCommandPath, resolveSpawnCommand } from "@t3tools/shared/shell"; @@ -29,11 +29,18 @@ import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import * as NodeCrypto from "node:crypto"; import * as ServerConfig from "../config.ts"; +import { selectManagedRelease } from "./managedRelease.ts"; import * as ModelManifest from "./ModelManifest.ts"; import { resolveProviderCompatibility } from "./providerCompatibility.ts"; const DRIVER = ProviderDriverKind.make("codex"); const STAGING_STALE_AFTER_MS = 24 * 60 * 60_000; +const UPDATE_CHECK_INTERVAL_MS = 60 * 60_000; +const UPDATE_CHECK_TIMEOUT = "20 seconds"; +const UPSTREAM_LATEST_URL = "https://registry.npmjs.org/@openai/codex/latest"; +const UPSTREAM_RELEASES_URL = "https://github.com/openai/codex/releases/download"; +// An upstream release has no recorded size; current packages are about 160 MB. +const UPSTREAM_MAX_ARCHIVE_BYTES = 1024 * 1024 * 1024; const Version = Schema.String.check(Schema.isPattern(/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/u)); const ActiveRelease = Schema.Struct({ version: Version }); const InstalledRelease = Schema.Struct({ @@ -48,6 +55,7 @@ const PackageManifest = Schema.Struct({ entrypoint: Schema.String, }); const decodeVersion = Schema.decodeUnknownEffect(Version); +const decodeNpmLatest = Schema.decodeUnknownEffect(Schema.Struct({ version: Version })); const encodeRecord = Schema.encodeEffect(Schema.fromJsonString(InstalledRelease)); const encodeActive = Schema.encodeEffect(Schema.fromJsonString(ActiveRelease)); export interface CodexReleaseAsset { @@ -55,7 +63,8 @@ export interface CodexReleaseAsset { readonly target: string; readonly url: string; readonly sha256: string; - readonly archiveBytes: number; + /** Null for an upstream release, whose package checksum is published without a size. */ + readonly archiveBytes: number | null; } const RELEASES: Readonly> = { "darwin-arm64": { @@ -139,6 +148,11 @@ interface CodexInstallationService { ) => Effect.Effect; readonly state: Effect.Effect; readonly changes: Stream.Stream; + /** + * Looks up OpenAI's newest Codex release, at most hourly, and offers it + * through `state.version` when it is newer than the managed install. + */ + readonly checkForUpdate: Effect.Effect; readonly remove: ( protectedBinaryPaths?: ReadonlyArray, ) => Effect.Effect; @@ -186,15 +200,31 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function const activePath = path.join(managedDirectory, "active.json"); const executableName = platform === "win32" ? "codex.exe" : "codex"; const gate = yield* Semaphore.make(1); + const updateCheckGate = yield* Semaphore.make(1); let leases = 0; let running: { readonly operationId: string; readonly fiber: Fiber.Fiber } | undefined; + let upstream: CodexReleaseAsset | null = null; + let upstreamCheckedAt: number | null = null; + + // A local Codex is used as is, so only a managed install is ever updated. + const managedVersion = (current: ProviderInstallState) => + current.source === "managed" ? current.installedVersion : null; + // What `start` installs next. Clients compare `version` with + // `installedVersion` to offer an update. + const offer = (installedVersion: string | null) => { + const release = selectManagedRelease(installedVersion, asset, upstream); + return { + version: release?.version ?? installedVersion, + totalBytes: release?.archiveBytes ?? null, + }; + }; + const state = yield* SubscriptionRef.make({ driver: DRIVER, operationId: null, phase: "idle", downloadedBytes: 0, - totalBytes: asset?.archiveBytes ?? null, - version: asset?.version ?? null, + ...offer(null), installedVersion: null, executablePath: null, canRemove: false, @@ -279,6 +309,70 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function ) ); }); + const isSupported = (version: string) => + compatibility(version).pipe(Effect.map((advisory) => advisory?.status === "supported")); + // Forgets what the manifest withdrew after it was seen. Managed resolution + // refuses a withdrawn install, so the pin replaces it rather than a re-check. + const keptInstall = Effect.fn("CodexInstallation.keptInstall")(function* ( + installedVersion: string | null, + ) { + if (upstream && !(yield* isSupported(upstream.version))) upstream = null; + return installedVersion !== null && (yield* isSupported(installedVersion)) + ? installedVersion + : null; + }); + // npm names the latest stable release; its GitHub release lists the package + // checksums, so an upstream update stays SHA-256 verified. + const lookupUpstream = Effect.gen(function* () { + if (!asset) return null; + const latest = yield* http + .execute(HttpClientRequest.get(UPSTREAM_LATEST_URL)) + .pipe(Effect.flatMap(HttpClientResponse.filterStatusOk)); + const { version } = yield* latest.json.pipe(Effect.flatMap(decodeNpmLatest)); + // Managed resolution refuses anything else, so offering it would break sessions. + if (!(yield* isSupported(version))) return null; + const releaseUrl = `${UPSTREAM_RELEASES_URL}/rust-v${version}`; + const checksums = yield* http + .execute(HttpClientRequest.get(`${releaseUrl}/codex-package_SHA256SUMS`)) + .pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap((response) => response.text), + ); + const fileName = `codex-package-${asset.target}.tar.gz`; + const sha256 = parseChecksums(checksums).get(fileName); + if (!sha256) return null; + return { + version, + target: asset.target, + url: `${releaseUrl}/${fileName}`, + sha256, + archiveBytes: null, + } satisfies CodexReleaseAsset; + }); + // A check already in flight covers concurrent subscribers, including when it fails. + const checkForUpdate = updateCheckGate + .withPermitsIfAvailable(1)( + Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis; + if (upstreamCheckedAt === null || now - upstreamCheckedAt >= UPDATE_CHECK_INTERVAL_MS) { + // A failed lookup counts too, and keeps whatever release was offered before. + upstreamCheckedAt = now; + upstream = yield* lookupUpstream.pipe( + Effect.timeout(UPDATE_CHECK_TIMEOUT), + Effect.orElseSucceed(() => upstream), + ); + } + // A running install already published the release it is installing. + yield* SubscriptionRef.updateEffect(state, (current) => + isRunning(current) + ? Effect.succeed(current) + : keptInstall(managedVersion(current)).pipe( + Effect.map((kept) => ({ ...current, ...offer(kept) })), + ), + ); + }), + ) + .pipe(Effect.ignore); const resolveManaged = Effect.fn("CodexInstallation.resolveManaged")( function* () { const active = yield* readRecord(activePath, ActiveRelease); @@ -464,6 +558,14 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function ); const install = Effect.fn("CodexInstallation.install")( function* (release: CodexReleaseAsset) { + const ensureEligible = Effect.fn("CodexInstallation.ensureEligible")(function* () { + if (release.version !== asset?.version && !(yield* isSupported(release.version))) { + return yield* installationError( + "verify", + "This Codex release was withdrawn. Check for updates and try again.", + ); + } + }); yield* decodeVersion(release.version); yield* fs.makeDirectory(managedDirectory, { recursive: true }); yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove: true })); @@ -480,12 +582,14 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function mode: 0o600, flag: "wx", }); + yield* ensureEligible(); yield* fs.rename(pointer, activePath); yield* SubscriptionRef.update( state, (current) => ({ ...current, + ...offer(release.version), phase: "succeeded", source: "managed", installedVersion: release.version, @@ -508,6 +612,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function "verify", "The existing managed Codex release differs from the official package. Remove it and reinstall.", ); + yield* ensureEligible(); yield* validate(existing, release.version).pipe( Effect.scoped, Effect.timeout("90 seconds"), @@ -523,6 +628,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function const runtime = path.join(staging, "runtime"); yield* fs.makeDirectory(runtime); const hash = NodeCrypto.createHash("sha256"); + const maxArchiveBytes = release.archiveBytes ?? UPSTREAM_MAX_ARCHIVE_BYTES; let downloadedBytes = 0; let lastProgressAt = yield* Clock.currentTimeMillis; const response = yield* http @@ -532,7 +638,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function Stream.tap((chunk) => Effect.gen(function* () { downloadedBytes += chunk.byteLength; - if (downloadedBytes > release.archiveBytes) + if (downloadedBytes > maxArchiveBytes) return yield* installationError( "download", "The Codex download exceeded the expected release size.", @@ -556,7 +662,10 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function ), }), ); - if (downloadedBytes !== release.archiveBytes || hash.digest("hex") !== release.sha256) + if ( + (release.archiveBytes !== null && downloadedBytes !== release.archiveBytes) || + hash.digest("hex") !== release.sha256 + ) return yield* installationError( "download", "The Codex download failed its size or SHA-256 check. Nothing was installed.", @@ -600,6 +709,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function }) satisfies ProviderInstallState, ); const executable = yield* fromDirectory(runtime, release.version, release.target); + yield* ensureEligible(); yield* validate(executable, release.version).pipe( Effect.scoped, Effect.timeout("90 seconds"), @@ -642,13 +752,54 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function ), ), ); + // Nothing newer is known, so "reinstall" re-checks the active runtime rather + // than replacing it with an older pinned release. + const reverify = Effect.fn("CodexInstallation.reverify")( + function* () { + const active = yield* readRecord(activePath, ActiveRelease); + const executable = yield* completedRelease(active.version); + yield* validate(executable, executable.version).pipe( + Effect.scoped, + Effect.timeout("90 seconds"), + ); + const kept = yield* keptInstall(executable.version); + if (kept === null) { + yield* SubscriptionRef.update(state, (current) => ({ ...current, ...offer(kept) })); + return yield* installationError( + "verify", + "This Codex release was withdrawn. Check for updates and try again.", + ); + } + yield* SubscriptionRef.update( + state, + (current) => + ({ + ...current, + ...offer(kept), + phase: "succeeded", + source: "managed", + installedVersion: executable.version, + executablePath: executable.executablePath, + message: null, + }) satisfies ProviderInstallState, + ); + }, + Effect.mapError( + wrapFailure( + "verify", + "The installed Codex runtime could not start. Remove it and reinstall.", + ), + ), + ); const start = gate .withPermit( Effect.gen(function* () { const current = yield* SubscriptionRef.get(state); if (isRunning(current)) return current; if (yield* reuseLocal()) return yield* SubscriptionRef.get(state); - if (!asset) { + const installedVersion = yield* keptInstall(managedVersion(current)); + const release = selectManagedRelease(installedVersion, asset, upstream); + if (!release && installedVersion === null) { return yield* installationError( "start", `OpenAI does not publish a Codex runtime for ${platform}-${arch}. Use a supported remote environment or a custom executable.`, @@ -658,14 +809,13 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function const next: ProviderInstallState = { ...current, operationId, - phase: "downloading", + phase: release ? "downloading" : "verifying", downloadedBytes: 0, - totalBytes: asset.archiveBytes, - version: asset.version, - message: "Downloading Codex.", + ...offer(installedVersion), + message: release ? "Downloading Codex." : "Checking Codex.", }; yield* SubscriptionRef.set(state, next); - const work = install(asset).pipe( + const work = (release ? install(release) : reverify()).pipe( Effect.onExit((exit) => Exit.isFailure(exit) ? SubscriptionRef.update(state, (value) => { @@ -745,6 +895,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function (current) => ({ ...current, + ...offer(null), operationId: null, phase: "idle", downloadedBytes: 0, @@ -796,11 +947,13 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function if (!(yield* fs.exists(activePath))) return; const active = yield* readRecord(activePath, ActiveRelease); const installed = yield* completedRelease(active.version); + const kept = yield* keptInstall(installed.version); yield* SubscriptionRef.update( state, (current) => ({ ...current, + ...offer(kept), installedVersion: installed.version, executablePath: installed.executablePath, source: "managed", @@ -832,6 +985,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function cancel, state: SubscriptionRef.get(state), changes: SubscriptionRef.changes(state), + checkForUpdate, remove, }); }); diff --git a/apps/server/src/provider/CodexProvider.test.ts b/apps/server/src/provider/CodexProvider.test.ts index c9a992bcf5160..7eadf550eab28 100644 --- a/apps/server/src/provider/CodexProvider.test.ts +++ b/apps/server/src/provider/CodexProvider.test.ts @@ -16,6 +16,7 @@ it("maps current Codex model capability fields", () => { id: "gpt-test", isDefault: true, model: "gpt-test", + availableAccessPrograms: { cyber: ["standard", "daybreakBlue"] }, defaultServiceTier: "flex", serviceTiers: [ { @@ -65,6 +66,16 @@ it("maps current Codex model capability fields", () => { ], currentValue: "flex", }, + { + id: "cyberAccessProgram", + label: "Cyber Access", + type: "select", + options: [ + { id: "standard", label: "Standard", isDefault: true }, + { id: "daybreakBlue", label: "Daybreak Blue" }, + ], + currentValue: "standard", + }, ]); }); diff --git a/apps/server/src/provider/CodexProvider.ts b/apps/server/src/provider/CodexProvider.ts index 3fde32add2198..197eed97ff820 100644 --- a/apps/server/src/provider/CodexProvider.ts +++ b/apps/server/src/provider/CodexProvider.ts @@ -82,6 +82,18 @@ const CodexRoutingConfig = Schema.Struct({ }); const decodeCodexRoutingConfig = Schema.decodeUnknownOption(CodexRoutingConfig); +const CodexCyberAccessConfig = Schema.Struct({ + daybreak: Schema.optionalKey(Schema.NullOr(Schema.Boolean)), + features: Schema.optionalKey( + Schema.NullOr( + Schema.Struct({ + api_key_cyber_access_programs: Schema.optionalKey(Schema.NullOr(Schema.Boolean)), + }), + ), + ), +}); +const decodeCodexCyberAccessConfig = Schema.decodeUnknownOption(CodexCyberAccessConfig); + function routesToNativeOpenai(config: unknown): boolean { const decoded = decodeCodexRoutingConfig(config); if (Option.isNone(decoded)) return false; @@ -133,6 +145,9 @@ export interface CodexAppServerProviderSnapshot { readonly version: string | undefined; readonly models: ReadonlyArray | undefined; readonly serviceTier?: string | undefined; + /** Undefined when `config/read` failed, so T3 cannot know Codex's default program. */ + readonly daybreakEnabled?: boolean | undefined; + readonly cyberAccessProgramsUnavailable?: boolean | undefined; readonly skills: ReadonlyArray; } @@ -153,6 +168,12 @@ const SERVICE_TIER_DESCRIPTIONS: Readonly> = { ultrafast: "Even faster, more expensive", }; +const CYBER_ACCESS_PROGRAM_LABELS: Readonly> = { + standard: "Standard", + daybreakBlue: "Daybreak Blue", + daybreakRed: "Daybreak Red", +}; + function reasoningEffortLabel(reasoningEffort: string): string { return REASONING_EFFORT_LABELS[reasoningEffort] ?? reasoningEffort; } @@ -281,6 +302,25 @@ export function mapCodexModelCapabilities( currentValue: defaultServiceTier, }); } + const cyberAccessPrograms = model.availableAccessPrograms?.cyber ?? []; + if (cyberAccessPrograms.length > 0) { + const hasStandard = cyberAccessPrograms.includes("standard"); + const defaultProgram = hasStandard ? "standard" : cyberAccessPrograms[0]; + optionDescriptors.push({ + id: "cyberAccessProgram", + label: "Cyber Access", + type: "select", + // Standard stays selectable as an opt-out; Codex rejects it visibly when the login cannot use it. + options: (hasStandard ? cyberAccessPrograms : ["standard", ...cyberAccessPrograms]).map( + (program) => ({ + id: program, + label: CYBER_ACCESS_PROGRAM_LABELS[program] ?? program, + ...(program === defaultProgram ? { isDefault: true } : {}), + }), + ), + ...(defaultProgram === undefined ? {} : { currentValue: defaultProgram }), + }); + } return createModelCapabilities({ optionDescriptors, @@ -320,37 +360,95 @@ export function applyPreferredCodexDefaultModel( }); } -function applyConfiguredCodexServiceTier( +function mapCodexOptionDescriptors( models: ReadonlyArray, - serviceTier: string | undefined, + update: ( + descriptors: ReadonlyArray, + model: ServerProviderModel, + ) => ReadonlyArray, ): ReadonlyArray { - if (!serviceTier) return models; return models.map((model) => { if (!model.capabilities?.optionDescriptors) return model; return { ...model, capabilities: { ...model.capabilities, - optionDescriptors: model.capabilities.optionDescriptors.map((descriptor) => { - if (descriptor.id !== "serviceTier" || descriptor.type !== "select") return descriptor; - const value = descriptor.options.find( - (option) => - option.id === serviceTier || (serviceTier === "fast" && option.id === "priority"), - )?.id; - if (!value) return descriptor; - return { - ...descriptor, - currentValue: value, - options: descriptor.options.map(({ isDefault: _isDefault, ...option }) => - option.id === value ? { ...option, isDefault: true } : option, - ), - }; - }), + optionDescriptors: update(model.capabilities.optionDescriptors, model), }, }; }); } +function withConfiguredSelectDefault( + models: ReadonlyArray, + descriptorId: string, + pick: (options: ReadonlyArray<{ readonly id: string }>) => string | undefined, +): ReadonlyArray { + return mapCodexOptionDescriptors(models, (descriptors) => + descriptors.map((descriptor) => { + if (descriptor.id !== descriptorId || descriptor.type !== "select") return descriptor; + const value = pick(descriptor.options); + if (!value) return descriptor; + return { + ...descriptor, + currentValue: value, + options: descriptor.options.map(({ isDefault: _isDefault, ...option }) => + option.id === value ? { ...option, isDefault: true } : option, + ), + }; + }), + ); +} + +function applyConfiguredCodexServiceTier( + models: ReadonlyArray, + serviceTier: string | undefined, +): ReadonlyArray { + if (!serviceTier) return models; + return withConfiguredSelectDefault( + models, + "serviceTier", + (options) => + options.find( + (option) => + option.id === serviceTier || (serviceTier === "fast" && option.id === "priority"), + )?.id, + ); +} + +/** Mirrors Codex: `daybreak = true` prefers a Daybreak program, Blue before Red. */ +function applyConfiguredCodexCyberAccess( + models: ReadonlyArray, + snapshot: Pick< + CodexAppServerProviderSnapshot, + "daybreakEnabled" | "cyberAccessProgramsUnavailable" + >, +): ReadonlyArray { + // Without a descriptor no turn sends a program; without a default only an explicit choice goes. + const offered = mapCodexOptionDescriptors(models, (descriptors, model) => + descriptors.flatMap((descriptor): ReadonlyArray => { + if (descriptor.id !== "cyberAccessProgram" || descriptor.type !== "select") { + return [descriptor]; + } + if (model.isCustom || snapshot.cyberAccessProgramsUnavailable === true) return []; + if (snapshot.daybreakEnabled !== undefined) return [descriptor]; + const { currentValue: _currentValue, ...withoutDefault } = descriptor; + return [ + { + ...withoutDefault, + options: descriptor.options.map(({ isDefault: _isDefault, ...option }) => option), + }, + ]; + }), + ); + if (snapshot.daybreakEnabled !== true) return offered; + return withConfiguredSelectDefault(offered, "cyberAccessProgram", (options) => + ["daybreakBlue", "daybreakRed"].find((program) => + options.some((option) => option.id === program), + ), + ); +} + /** * Codex has no static default capability set, so a bare custom slug borrows * the first built-in's descriptors; an entry with its own capabilities keeps @@ -619,7 +717,7 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun // Optional discovery must finish before the outer timeout can discard the account result. const deadlineMs = spawnedAtMs + CODEX_AUTH_PROBE_TIMEOUT_MS - CODEX_DISCOVERY_MARGIN_MS; - const [skillsResponse, models, { serviceTier, nativeUsage, rateLimits }] = yield* Effect.all( + const [skillsResponse, models, { config, nativeUsage, rateLimits }] = yield* Effect.all( [ withCodexDiscoveryDeadline(client.request("skills/list", { cwds: [input.cwd] }), deadlineMs), accountResponse.account?.type === "chatgpt" @@ -648,7 +746,7 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun : Effect.undefined; return readUsage.pipe( Effect.map((rateLimits) => ({ - serviceTier: config?.config.service_tier ?? undefined, + config: config?.config, nativeUsage, rateLimits, })), @@ -659,13 +757,19 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun { concurrency: "unbounded" }, ); + const cyberAccess = Option.getOrUndefined(decodeCodexCyberAccessConfig(config)); return { account: accountResponse, nativeUsage, ...(rateLimits ? { rateLimits } : {}), version, models, - serviceTier, + serviceTier: config?.service_tier ?? undefined, + daybreakEnabled: config === undefined ? undefined : cyberAccess?.daybreak === true, + // An unread config cannot rule out an API key with the programs turned off. + cyberAccessProgramsUnavailable: + accountResponse.account?.type === "apiKey" && + (config === undefined || cyberAccess?.features?.api_key_cyber_access_programs === false), skills: skillsResponse ? parseCodexSkillsListResponse(skillsResponse, input.cwd) : [], } satisfies CodexAppServerProviderSnapshot; }); @@ -942,6 +1046,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu appendCustomCodexModels(snapshot.models ?? [], codexSettings.customModels), applyPreferredCodexDefaultModel, (models) => applyConfiguredCodexServiceTier(models, snapshot.serviceTier), + (models) => applyConfiguredCodexCyberAccess(models, snapshot), ), skills: snapshot.skills, slashCommands: [ diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts index 3747ff032d292..b43f30a419472 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts @@ -426,7 +426,13 @@ it.layer(layerTest)("AntigravityDriver", (it) => { modelSelection, runtimePolicy: cliPolicy, }); - expect(h.launches.at(-1)?.args).toEqual(["acp"]); + expect(h.launches.at(-1)?.args).toEqual([ + "acp", + "--gemini-dir", + h.profileDirectory, + "--app-data-dir", + "antigravity-acp", + ]); expect( (yield* h.readRequests) .slice(requestsBefore) diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index 7bb1f25b67ce7..154020e0b64bd 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -462,6 +462,11 @@ export const AntigravityDriver: ProviderDriver< makeRuntime, withProcess: authFlow.withProcess, defaultModel, + supportsNativeGoals: provider.snapshot.getSnapshot.pipe( + Effect.map( + (snapshot) => snapshot.slashCommands?.some((command) => command.name === "goal") === true, + ), + ), profileDirectory, onSessionStarted: provider.onSessionStarted, onSessionEvent: (event) => { diff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.ts index c9cbb937c2eb4..50fbbc7024b99 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.ts @@ -248,6 +248,9 @@ export const CodexDriver: ProviderDriver< }, { onUsageLimits: (update) => snapshot.applyUsageLimits(update), + models: Effect.suspend(() => snapshot.getSnapshot).pipe( + Effect.map((value) => value.models), + ), compatibility: installation.compatibility, }, ).pipe( diff --git a/apps/server/src/provider/Drivers/CodexManagedProvider.ts b/apps/server/src/provider/Drivers/CodexManagedProvider.ts index ab5e7add556a9..f182245f8840d 100644 --- a/apps/server/src/provider/Drivers/CodexManagedProvider.ts +++ b/apps/server/src/provider/Drivers/CodexManagedProvider.ts @@ -242,8 +242,10 @@ export const makeManagedCodexProvider = Effect.fn("makeManagedCodexProvider")(fu const resolveRuntime = runtime.auth.controller.withAccess!(runtime.resolve); // Launch settings bind the refresh command to the signed-in profile. The registry // already wraps openSession in withAccess, so resolve without re-entering it. + const models = snapshot.getSnapshot.pipe(Effect.map((value) => value.models)); const orchestrationAdapter = yield* createCodexAdapterV2(input, { onUsageLimits: (update) => snapshot.applyUsageLimits(update), + models, resolveRuntime: runtime.resolve, }).pipe( Effect.mapError( @@ -259,7 +261,7 @@ export const makeManagedCodexProvider = Effect.fn("makeManagedCodexProvider")(fu const nativeGeneration = yield* makeCodexTextGeneration( config, undefined, - snapshot.getSnapshot.pipe(Effect.map((value) => value.models)), + models, resolveRuntime, ); const protect = (operation: string, effect: Effect.Effect) => diff --git a/apps/server/src/provider/Drivers/claudeUsage.test.ts b/apps/server/src/provider/Drivers/claudeUsage.test.ts index 6f457f4f4cf2f..bc10ba5b7b29a 100644 --- a/apps/server/src/provider/Drivers/claudeUsage.test.ts +++ b/apps/server/src/provider/Drivers/claudeUsage.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "@effect/vitest"; +import { parseRateTable, priceUsage } from "../../usage/usagePricing.ts"; import { claudeUsageFormat, parseClaudeLine } from "./claudeUsage.ts"; function claudeLine(overrides: { @@ -115,7 +116,8 @@ describe("Claude advisor iterations", () => { model: "claude-fable-5-1", input_tokens: 54204, cache_read_input_tokens: 0, - cache_creation_input_tokens: 0, + cache_creation_input_tokens: 500, + cache_creation: { ephemeral_5m_input_tokens: 200, ephemeral_1h_input_tokens: 300 }, output_tokens: 4229, }, { @@ -160,10 +162,11 @@ describe("Claude advisor iterations", () => { totals: { uncachedInputTokens: 54204, cachedInputTokens: 0, - cacheCreationTokens: 0, + cacheCreationTokens: 500, outputTokens: 4229, reasoningTokens: 0, }, + cacheCreation1hTokens: 300, dedupeKey: expect.any(String), }, ]; @@ -216,3 +219,44 @@ describe("Claude advisor iterations", () => { expect(parse(unusable).map((record) => record.model)).toEqual(["claude-opus-5-5"]); }); }); + +describe("Claude cache write pricing", () => { + it("prices one-hour cache writes at the one-hour rate and the rest at the five-minute rate", () => { + const model = "claude-opus-4-5-20251101"; + const rates = parseRateTable({ + [model]: { + litellm_provider: "anthropic", + input_cost_per_token: 5e-6, + output_cost_per_token: 25e-6, + cache_read_input_token_cost: 5e-7, + cache_creation_input_token_cost: 6.25e-6, + cache_creation_input_token_cost_above_1hr: 1e-5, + }, + }); + const [record] = parseClaudeLine( + JSON.stringify({ + type: "assistant", + timestamp: "2026-08-07T04:05:13.944Z", + sessionId: "s", + message: { + id: "msg_ttl", + model, + usage: { + input_tokens: 0, + cache_read_input_tokens: 0, + cache_creation_input_tokens: 1_000_000, + cache_creation: { + ephemeral_5m_input_tokens: 400_000, + ephemeral_1h_input_tokens: 600_000, + }, + output_tokens: 0, + }, + }, + }), + ); + + if (record === undefined) throw new Error("expected a usage record"); + // 0.4M x $6.25/M + 0.6M x $10/M + expect(priceUsage(rates, record).costUsd).toBeCloseTo(8.5, 9); + }); +}); diff --git a/apps/server/src/provider/Drivers/claudeUsage.ts b/apps/server/src/provider/Drivers/claudeUsage.ts index acb697d2941de..713b35884292b 100644 --- a/apps/server/src/provider/Drivers/claudeUsage.ts +++ b/apps/server/src/provider/Drivers/claudeUsage.ts @@ -30,6 +30,13 @@ export function parseClaudeLine(line: string): readonly UsageRecord[] { return parseClaudeRecord(parsed); } +function cacheCreation1h(usage: Record): { cacheCreation1hTokens?: number } { + const split = usage["cache_creation"]; + if (typeof split !== "object" || split === null) return {}; + const tokens = tokenCount((split as Record)["ephemeral_1h_input_tokens"]); + return tokens > 0 ? { cacheCreation1hTokens: tokens } : {}; +} + function parseClaudeRecord(parsed: unknown): readonly UsageRecord[] { if (typeof parsed !== "object" || parsed === null) return []; @@ -70,6 +77,7 @@ function parseClaudeRecord(parsed: unknown): readonly UsageRecord[] { // Anthropic folds thinking tokens into output and does not break them out. reasoningTokens: 0, }, + ...cacheCreation1h(usageRecord), reportedCostUsd: typeof cost === "number" && Number.isFinite(cost) ? cost : null, speed: usageRecord["speed"] === "fast" ? "fast" : "standard", dedupeKey, @@ -101,6 +109,7 @@ function parseClaudeRecord(parsed: unknown): readonly UsageRecord[] { outputTokens: tokenCount(advisor["output_tokens"]), reasoningTokens: 0, }, + ...cacheCreation1h(advisor), reportedCostUsd: null, speed: executor.speed, dedupeKey: dedupeKey === null ? null : `${dedupeKey}:advisor:${index}`, diff --git a/apps/server/src/provider/Drivers/codexUsage.test.ts b/apps/server/src/provider/Drivers/codexUsage.test.ts index 74812bafb5099..a3abb2ccb4fb1 100644 --- a/apps/server/src/provider/Drivers/codexUsage.test.ts +++ b/apps/server/src/provider/Drivers/codexUsage.test.ts @@ -450,6 +450,61 @@ describe("parseCodexLine", () => { expect(state.malformedRecords).toBe(0); }); + it("bills request-ledger usage through resumed context counters and compaction", () => { + const state = initialCodexScanState(); + const request = (response_id: string, usage: unknown) => + JSON.stringify({ + type: "token_usage_record", + timestamp: "2026-08-01T05:17:45.000Z", + payload: { response_id, usage }, + }); + parseCodexLine(sessionMeta, state); + parseCodexLine(turnContext, state); + parseCodexLine(counted(counters(100, 20), counters(1000, 200)), state); + // Resume restores older context counters, while the request ledger continues. + expect( + parseCodexLine(request("response-1", counters(80, 10)), state)?.totals.outputTokens, + ).toBe(10); + expect(parseCodexLine(counted(counters(80, 10), counters(580, 110)), state)).toBeNull(); + // Rate-limit refreshes repeat the snapshot without another request. + expect(parseCodexLine(counted(counters(80, 10), counters(580, 110)), state)).toBeNull(); + expect( + parseCodexLine(request("compaction", counters(90, 15)), state)?.totals.outputTokens, + ).toBe(15); + parseCodexLine(turnContext, state); + expect( + parseCodexLine(counted({ ...counters(0, 0), total_tokens: 40 }, counters(580, 110)), state), + ).toBeNull(); + expect(parseCodexLine(request("response-2", counters(30, 5)), state)?.totals.outputTokens).toBe( + 5, + ); + expect(parseCodexLine(counted(counters(30, 5), counters(610, 115)), state)).toBeNull(); + expect(state.malformedRecords).toBe(0); + // A later turn from an older CLI can still report usage through snapshots alone. + parseCodexLine(turnContext, state); + expect( + parseCodexLine(counted(counters(20, 2), counters(630, 117)), state)?.totals.outputTokens, + ).toBe(2); + expect( + parseCodexLine(request("interrupted", counters(40, 4)), state)?.totals.outputTokens, + ).toBe(4); + parseCodexLine(turnContext, state); + expect( + parseCodexLine(counted(counters(10, 1), counters(680, 122)), state)?.totals.outputTokens, + ).toBe(1); + expect(parseCodexLine(request("", counters(15, 3)), state)).toBeNull(); + parseCodexLine(turnContext, state); + const transition = parseCodexRecords(request("upgraded", counters(25, 5)), state); + expect(transition.map((record) => record.totals.outputTokens)).toEqual([3, 5]); + expect(parseCodexLine(counted(counters(25, 5), counters(720, 130)), state)).toBeNull(); + expect(parseCodexLine(request("", counters(10, 1)), state)).toBeNull(); + expect( + parseCodexLine(counted(counters(10, 1), counters(730, 131)), state)?.totals.outputTokens, + ).toBe(1); + expect(parseCodexLine(counted(counters(10, 1), counters(730, 131)), state)).toBeNull(); + expect(state.malformedRecords).toBe(0); + }); + it("does not bill a context-window estimate or lose the following real request", () => { const state = initialCodexScanState(); parseCodexLine(turnContext, state); diff --git a/apps/server/src/provider/Drivers/codexUsage.ts b/apps/server/src/provider/Drivers/codexUsage.ts index 90f7c78b849f8..540e06fd2b8dd 100644 --- a/apps/server/src/provider/Drivers/codexUsage.ts +++ b/apps/server/src/provider/Drivers/codexUsage.ts @@ -127,6 +127,7 @@ export const CodexScanState = Schema.Struct({ unreportedRequests: Schema.mutableKey( Schema.optionalKey(Schema.mutable(Schema.Array(CodexUnreportedRequest))), ), + requestLedgerActive: Schema.mutableKey(Schema.optionalKey(Schema.Boolean)), malformedRecords: Schema.mutableKey(TokenCount), sawSessionMeta: Schema.mutableKey(Schema.Boolean), modelProvider: Schema.mutableKey(Schema.String), @@ -181,8 +182,8 @@ function isForkCopy(state: CodexScanState, timestampMs: number): boolean { } /** - * Cumulative counters validate request deltas. Older events without cumulative counters use - * normalized consecutive-request deduplication. + * Identified request-ledger entries report spending independently of context snapshots. + * Legacy snapshots validate request deltas against cumulative counters. */ export function parseCodexLine(line: string, state: CodexScanState): readonly UsageRecord[] { let parsed: unknown; @@ -221,6 +222,7 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag } if (record["type"] === "turn_context") { + state.requestLedgerActive = false; if (typeof payloadRecord["model"] === "string") state.model = payloadRecord["model"]; // Model carry is useful for usage, but history recovery needs this context's own identity. state.turnId = @@ -232,13 +234,31 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag return []; } - // Several of these may sit between two snapshots, so they only explain a gap in the counters. + // Request ledgers include spending that context snapshots can omit. if (record["type"] === "token_usage_record") { const timestampMs = parseTimestampMs(record["timestamp"]); const usage = readCodexTokenUsage(payloadRecord["usage"]); if (timestampMs === null || usage === null || state.model.length === 0) return []; // Copied history is already billed in the parent. if (isForkCopy(state, timestampMs)) return []; + const responseId = payloadRecord["response_id"]; + if (typeof responseId === "string" && responseId.length > 0) { + const pending = state.unreportedRequests ?? []; + state.requestLedgerActive = true; + for (const request of pending) { + state.lastCumulativeUsage = advanceCodexUsage(state.lastCumulativeUsage, request.usage); + } + state.lastCumulativeUsage = advanceCodexUsage(state.lastCumulativeUsage, usage); + delete state.unreportedRequests; + return [ + ...pending.map((request) => codexRequestRecord(state, request.usage, request)), + { + ...codexRequestRecord(state, usage, codexAttribution(state, timestampMs)), + dedupeKey: JSON.stringify(["codex", state.sessionId, responseId]), + }, + ]; + } + state.requestLedgerActive = false; (state.unreportedRequests ??= []).push({ ...codexAttribution(state, timestampMs), usage }); return []; } @@ -278,6 +298,12 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag return []; } + // Context snapshots can rewind on resume and omit compaction spending; identified requests are authoritative. + if (state.requestLedgerActive) { + if (cumulative !== null) rebaseCodexUsage(state, cumulative); + return []; + } + const previous = state.lastCumulativeUsage; const pending = state.unreportedRequests; // A valid snapshot remains the next baseline even when its paired request is malformed. @@ -418,6 +444,7 @@ export const codexUsageFormat: TranscriptUsageFormat = { session_id: true, model_provider: true, turn_id: true, + response_id: true, model: true, thread_settings: { service_tier: true }, forked_from_id: true, diff --git a/apps/server/src/provider/ProviderInstanceRegistry.ts b/apps/server/src/provider/ProviderInstanceRegistry.ts index 3f4df0eb35d18..ae51e8009645c 100644 --- a/apps/server/src/provider/ProviderInstanceRegistry.ts +++ b/apps/server/src/provider/ProviderInstanceRegistry.ts @@ -92,9 +92,20 @@ const withoutSecretReferences = ( typeof variable.value === "string" ? [{ ...variable, value: variable.value }] : [], ); +interface CheckedSecret { + readonly reference: SecretReference; + readonly value: string; +} + +const sameReference = (a: SecretReference, b: SecretReference) => + a.provider === b.provider && a.reference === b.reference; + +// `checked` supplies its reference's value instead of the resolver, which a concurrent refresh +// may have re-read since the check. const readInstanceSecrets = Effect.fn("ProviderInstanceRegistry.readInstanceSecrets")(function* ( driver: AnyProviderDriver | undefined, entry: ProviderInstanceConfig, + checked?: CheckedSecret, ) { const variables = entry.environment ?? []; const configFields = configSecretReferences(driver, entry); @@ -102,8 +113,15 @@ const readInstanceSecrets = Effect.fn("ProviderInstanceRegistry.readInstanceSecr ...secretReferencesIn(variables), ...configFields.map(({ reference }) => reference), ]; - const values = - references.length === 0 ? [] : yield* (yield* SecretResolver.SecretResolver).read(references); + const isChecked = (reference: SecretReference) => + checked !== undefined && sameReference(reference, checked.reference); + const toRead = references.filter((reference) => !isChecked(reference)); + const read = + toRead.length === 0 ? [] : yield* (yield* SecretResolver.SecretResolver).read(toRead); + let readIndex = 0; + const values = references.map((reference) => + isChecked(reference) ? checked?.value : read[readIndex++], + ); const unreadable: Array = []; let index = 0; // An empty secret reads as unreadable, so a driver cannot fall back to an inherited credential. @@ -130,6 +148,36 @@ const readInstanceSecrets = Effect.fn("ProviderInstanceRegistry.readInstanceSecr return { secrets, unreadable }; }); +// Replaces only the checked reference's value in the secrets a live instance already holds, so +// another reference whose read failed earlier is not read again and does not park the instance. +const carryCheckedSecret = ( + driver: AnyProviderDriver | undefined, + entry: ProviderInstanceConfig, + current: InstanceSecrets, + { reference: checked, value }: CheckedSecret, +): InstanceSecrets => { + const matches = (reference: SecretReference) => sameReference(reference, checked); + // A live instance resolved every variable in order, so slots line up with the entry's variables + // by position; names may repeat. + const variables = entry.environment ?? []; + const replacedSlots = configSecretReferences(driver, entry).filter(({ reference }) => + matches(reference), + ); + return { + environment: current.environment.map((variable, index) => { + const source = variables[index]?.value; + return source !== undefined && typeof source !== "string" && matches(source) + ? { ...variable, value } + : variable; + }), + config: current.config.map((slot) => + replacedSlots.some(({ field, key }) => field === slot.field && key === slot.key) + ? { ...slot, value } + : slot, + ), + }; +}; + /** Conflicting saved flags must preserve any explicit disable. */ const resolveEntryEnabled = (entry: ProviderInstanceConfig, typedConfig: unknown): boolean => { const rawConfigEnabled = providerInstanceConfigEnabledFlag(entry.config); @@ -161,6 +209,7 @@ const buildEntry = Effect.fn("ProviderInstanceRegistry.buildEntry")(function* { - const { driversById, parentScope, instanceId, rawInstanceId, entry, deferSecrets } = input; + const { + driversById, + parentScope, + instanceId, + rawInstanceId, + entry, + deferSecrets, + carriedSecrets, + } = input; const blocked = input.blockedReason(entry.driver); if (blocked !== undefined) { return { @@ -235,12 +292,14 @@ const buildEntry = Effect.fn("ProviderInstanceRegistry.buildEntry")(function* 0) { @@ -311,9 +370,10 @@ const makeReconcile = (input: { configMap: ProviderInstanceConfigMap, rebuild?: ReadonlySet, deferSecrets?: boolean, + carried?: ReadonlyMap, ) => Effect.Effect) => { const { state, driversById, blockedReason, parentScope } = input; - return (configMap, rebuild = new Set(), deferSecrets = false) => + return (configMap, rebuild = new Set(), deferSecrets = false, carried = new Map()) => Effect.gen(function* () { const previousEntries = yield* Ref.get(state.entries); const previousUnavailable = yield* Ref.get(state.unavailable); @@ -365,6 +425,7 @@ const makeReconcile = (input: { const instanceId = ProviderInstanceId.make(rawInstanceId); const kept = previousEntries.has(instanceId) && !replacedIds.has(instanceId); return kept || + carried.has(instanceId) || parkedSnapshot(instanceId, entry) !== undefined || !(yield* isEntryEnabled(driversById, entry)) ? [] @@ -406,6 +467,7 @@ const makeReconcile = (input: { rawInstanceId, entry, deferSecrets, + carriedSecrets: carried.get(instanceId), }); if (result.kind === "live") { builtEntries.set(instanceId, result.live); @@ -503,44 +565,87 @@ export const makeProviderInstanceRegistry = Effect.fn( ); // Rebuilds an instance only when it was unavailable or its secrets changed, so a refresh does - // not restart providers whose credentials are the same. - const reloadSecrets: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape["reloadSecrets"] = - Effect.fn("ProviderInstanceRegistry.reloadSecrets")( - function* (instanceId) { - const configMap = yield* Ref.get(configMapRef); - const targets = yield* Effect.filter(Object.entries(configMap), ([rawInstanceId, entry]) => - (instanceId === undefined || rawInstanceId === instanceId) && - secretReferencesOf(driversById, entry).length > 0 - ? isEntryEnabled(driversById, entry) - : Effect.succeed(false), - ); - if (targets.length === 0) return; + // not restart providers whose credentials are the same. Without `checked` the cached values are + // dropped first; with it, only that reference takes the checked value and the rest carry over. + const reloadWhere = Effect.fn("ProviderInstanceRegistry.reloadWhere")( + function* ( + select: (rawInstanceId: string, entry: ProviderInstanceConfig) => boolean, + checked?: CheckedSecret, + ) { + const configMap = yield* Ref.get(configMapRef); + const targets = yield* Effect.filter(Object.entries(configMap), ([rawInstanceId, entry]) => + select(rawInstanceId, entry) && secretReferencesOf(driversById, entry).length > 0 + ? isEntryEnabled(driversById, entry) + : Effect.succeed(false), + ); + if (targets.length === 0) return []; + if (checked === undefined) { const resolver = yield* SecretResolver.SecretResolver; const references = targets.flatMap(([, entry]) => secretReferencesOf(driversById, entry)); yield* resolver.invalidate(references); yield* resolver.read(references); - const live = yield* Ref.get(entries); - const rebuild = new Set(); - for (const [rawInstanceId, entry] of targets) { - const current = live.get(ProviderInstanceId.make(rawInstanceId)); - if (current === undefined) { - rebuild.add(ProviderInstanceId.make(rawInstanceId)); - continue; + } + const live = yield* Ref.get(entries); + const rebuild = new Set(); + const carried = new Map(); + for (const [rawInstanceId, entry] of targets) { + const instanceId = ProviderInstanceId.make(rawInstanceId); + const current = live.get(instanceId); + if (current === undefined) { + rebuild.add(instanceId); + if (checked !== undefined) { + const { secrets, unreadable } = yield* readInstanceSecrets( + driversById.get(entry.driver), + entry, + checked, + ); + if (unreadable.length === 0) carried.set(instanceId, secrets); } - const { secrets, unreadable } = yield* readInstanceSecrets( + continue; + } + if (checked !== undefined) { + const secrets = carryCheckedSecret( driversById.get(entry.driver), - entry, + current.entry, + current.secrets, + checked, ); - // A failed re-read keeps the working instance and the value it already holds. - if (unreadable.length === 0 && !Equal.equals(secrets, current.secrets)) { + if (!Equal.equals(secrets, current.secrets)) { rebuild.add(current.instance.instanceId); + carried.set(current.instance.instanceId, secrets); } + continue; } - yield* reconcileWithR(configMap, rebuild); - }, - (effect) => semaphore.withPermits(1)(effect), - Effect.provideContext(driverContext), - ); + const { secrets, unreadable } = yield* readInstanceSecrets( + driversById.get(entry.driver), + entry, + ); + // A failed re-read keeps the working instance and the value it already holds. + if (unreadable.length === 0 && !Equal.equals(secrets, current.secrets)) { + rebuild.add(current.instance.instanceId); + } + } + yield* reconcileWithR(configMap, rebuild, false, carried); + return targets.map(([rawInstanceId]) => ProviderInstanceId.make(rawInstanceId)); + }, + (effect) => semaphore.withPermits(1)(effect), + Effect.provideContext(driverContext), + ); + const reloadSecrets: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape["reloadSecrets"] = + (instanceId) => + reloadWhere( + (rawInstanceId) => instanceId === undefined || rawInstanceId === instanceId, + undefined, + ).pipe(Effect.asVoid); + const applySecret: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape["applySecret"] = + (reference, value) => + reloadWhere( + (_, entry) => + secretReferencesOf(driversById, entry).some((candidate) => + sameReference(candidate, reference), + ), + { reference, value }, + ); // Reading secrets can wait on a vault unlock, so the server does not wait for it to start. yield* semaphore.withPermits(1)( @@ -592,6 +697,7 @@ export const makeProviderInstanceRegistry = Effect.fn( const mutator: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape = { reconcile, reloadSecrets, + applySecret, }; return { registry, mutator }; diff --git a/apps/server/src/provider/ProviderInstanceRegistryHydration.test.ts b/apps/server/src/provider/ProviderInstanceRegistryHydration.test.ts index dc44f0324a6b0..02bc92f4b4504 100644 --- a/apps/server/src/provider/ProviderInstanceRegistryHydration.test.ts +++ b/apps/server/src/provider/ProviderInstanceRegistryHydration.test.ts @@ -165,6 +165,7 @@ describe("layerSettingsWatcher", () => { const mutator = Layer.succeed(ProviderInstanceRegistryMutator, { reconcile: () => Queue.offer(reconciled, undefined), reloadSecrets: () => Effect.sync(() => void reloads++), + applySecret: () => Effect.succeed([]), }); yield* Layer.build( layerSettingsWatcher(Stream.fromQueue(changes), initial).pipe(Layer.provide(mutator)), diff --git a/apps/server/src/provider/ProviderInstanceRegistryMutator.ts b/apps/server/src/provider/ProviderInstanceRegistryMutator.ts index 35eb52d3f2906..911a055d79625 100644 --- a/apps/server/src/provider/ProviderInstanceRegistryMutator.ts +++ b/apps/server/src/provider/ProviderInstanceRegistryMutator.ts @@ -1,5 +1,9 @@ /** Reconcile closes removed/replaced scopes before creating replacements: at most one live instance per id. */ -import type { ProviderInstanceConfigMap, ProviderInstanceId } from "@t3tools/contracts"; +import type { + ProviderInstanceConfigMap, + ProviderInstanceId, + SecretReference, +} from "@t3tools/contracts"; import * as Context from "effect/Context"; import type * as Effect from "effect/Effect"; @@ -7,6 +11,14 @@ export interface ProviderInstanceRegistryMutatorShape { readonly reconcile: (configMap: ProviderInstanceConfigMap) => Effect.Effect; /** Re-reads the secrets of every instance, or one, and rebuilds those whose secrets changed. */ readonly reloadSecrets: (instanceId?: ProviderInstanceId) => Effect.Effect; + /** + * Rebuilds the instances that read `reference` with `value`, keeping the other secrets a live + * instance holds, and returns them. A parked instance reads its other secrets from the resolver. + */ + readonly applySecret: ( + reference: SecretReference, + value: string, + ) => Effect.Effect>; } export class ProviderInstanceRegistryMutator extends Context.Service< diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts index b5501943ca04f..0f6540d439d4b 100644 --- a/apps/server/src/provider/ProviderRegistry.test.ts +++ b/apps/server/src/provider/ProviderRegistry.test.ts @@ -44,7 +44,11 @@ import { deepMerge } from "@t3tools/shared/Struct"; import { createModelCapabilities } from "@t3tools/shared/model"; import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; -import { checkCodexProviderStatus, type CodexAppServerProviderSnapshot } from "./CodexProvider.ts"; +import { + checkCodexProviderStatus, + mapCodexModelCapabilities, + type CodexAppServerProviderSnapshot, +} from "./CodexProvider.ts"; import { BUNDLED_CLAUDE_MODEL_CATALOG } from "./ClaudeModelCatalog.ts"; import { checkClaudeProviderStatus } from "./ClaudeProvider.ts"; import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; @@ -503,6 +507,84 @@ it.layer( }), ); + it.effect("offers cyber access only on catalog models that advertise it", () => + Effect.gen(function* () { + const catalogModel = (slug: string, cyber?: Array<"standard" | "daybreakBlue">) => ({ + slug, + name: slug, + isCustom: false, + capabilities: mapCodexModelCapabilities({ + additionalSpeedTiers: [], + ...(cyber ? { availableAccessPrograms: { cyber } } : {}), + defaultReasoningEffort: "medium", + description: slug, + displayName: slug, + hidden: false, + id: slug, + isDefault: false, + model: slug, + supportedReasoningEfforts: [], + }), + }); + const defaultPrograms = (snapshot: Partial) => + checkCodexProviderStatus(decodeCodexSettings({ customModels: ["my-model"] }), () => + Effect.succeed( + makeCodexProbeSnapshot({ + models: [ + catalogModel("both", ["standard", "daybreakBlue"]), + catalogModel("daybreak-only", ["daybreakBlue"]), + catalogModel("plain"), + ], + ...snapshot, + }), + ), + ).pipe( + Effect.map((status) => + Object.fromEntries( + status.models.map((model) => { + const descriptor = model.capabilities?.optionDescriptors?.find( + (option) => option.id === "cyberAccessProgram", + ); + return [ + model.slug, + descriptor?.type === "select" + ? (descriptor.currentValue ?? "no default") + : null, + ]; + }), + ), + ), + ); + + assert.deepStrictEqual(yield* defaultPrograms({ daybreakEnabled: false }), { + both: "standard", + "daybreak-only": "daybreakBlue", + plain: null, + "my-model": null, + }); + assert.deepStrictEqual(yield* defaultPrograms({ daybreakEnabled: true }), { + both: "daybreakBlue", + "daybreak-only": "daybreakBlue", + plain: null, + "my-model": null, + }); + // An unread config keeps the choice but cannot know Codex's default. + assert.deepStrictEqual(yield* defaultPrograms({}), { + both: "no default", + "daybreak-only": "no default", + plain: null, + "my-model": null, + }); + assert.deepStrictEqual( + yield* defaultPrograms({ + account: { account: { type: "apiKey" }, requiresOpenaiAuth: false }, + cyberAccessProgramsUnavailable: true, + }), + { both: null, "daybreak-only": null, plain: null, "my-model": null }, + ); + }), + ); + it.effect("reads the version of a Codex CLI too old to run app-server (#20351)", () => Effect.gen(function* () { if ((yield* HostProcess.Platform) === "win32") return; diff --git a/apps/server/src/provider/ProviderRegistry.ts b/apps/server/src/provider/ProviderRegistry.ts index 18456b2397e7e..b2d9ba8af27a2 100644 --- a/apps/server/src/provider/ProviderRegistry.ts +++ b/apps/server/src/provider/ProviderRegistry.ts @@ -4,6 +4,7 @@ import { isProviderWorkspaceSnapshotPending, ProviderDriverKind, type ProviderInstanceId, + type SecretReference, type ServerProvider, type ServerProviderUpdateState, } from "@t3tools/contracts"; @@ -70,6 +71,12 @@ export class ProviderRegistry extends Context.Service< instanceId?: ProviderInstanceId, ) => Effect.Effect>; + /** Rebuilds and refreshes only the instances that read a secret, with the value the caller just read. */ + readonly applySecretAndRefresh: ( + reference: SecretReference, + value: string, + ) => Effect.Effect>; + /** Only refreshed instances can verify an update; the published list still includes every row. */ readonly refreshAfterUpdate: ( provider: ProviderDriverKind, @@ -739,6 +746,15 @@ export const layer = Layer.effect( return yield* instanceId === undefined ? refresh() : refreshInstance(instanceId); }); + const applySecretAndRefresh = Effect.fn("applySecretAndRefresh")(function* ( + reference: SecretReference, + value: string, + ) { + const instanceIds = yield* instanceRegistryMutator.applySecret(reference, value); + yield* Effect.forEach(instanceIds, refreshInstance, { discard: true }); + return yield* Ref.get(providersRef); + }); + const refreshAfterUpdate = Effect.fn("refreshAfterUpdate")(function* ( provider: ProviderDriverKind, selectedInstanceId: ProviderInstanceId, @@ -1176,6 +1192,8 @@ export const layer = Layer.effect( refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)), reloadSecretsAndRefresh: (instanceId?: ProviderInstanceId) => reloadSecretsAndRefresh(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)), + applySecretAndRefresh: (reference: SecretReference, value: string) => + applySecretAndRefresh(reference, value).pipe(Effect.catchCause(recoverRefreshFailure)), refreshWorkspaceSnapshot: (input) => refreshWorkspaceSnapshot(input).pipe(Effect.catchCause(recoverRefreshFailure)), refreshAfterUpdate, diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts index 4996b63772729..dc755d1e7a5a4 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts @@ -60,21 +60,25 @@ function makeModelRuntime( describe("Antigravity release gates", () => { it.each([ - { version: "1.4.1", filter: false, native: false, ownName: false }, - { version: "1.4.2", filter: true, native: false, ownName: false }, - { version: "1.4.4", filter: true, native: false, ownName: false }, - { version: "1.4.5", filter: true, native: true, ownName: false }, - { version: "1.4.6", filter: false, native: false, ownName: false }, - { version: "1.5.0", filter: false, native: false, ownName: false }, - { version: "1.5.1", filter: false, native: false, ownName: true }, - { version: "1.3.0", filter: false, native: false, ownName: false }, - { version: undefined, filter: false, native: false, ownName: false }, - { version: "unknown", filter: false, native: false, ownName: false }, + { version: "1.4.1", filter: false, native: false, ownName: false, advertisedAppend: false }, + { version: "1.4.2", filter: true, native: false, ownName: false, advertisedAppend: false }, + { version: "1.4.4", filter: true, native: false, ownName: false, advertisedAppend: false }, + { version: "1.4.5", filter: true, native: true, ownName: false, advertisedAppend: false }, + { version: "1.4.6", filter: false, native: false, ownName: false, advertisedAppend: false }, + { version: "1.5.0", filter: false, native: false, ownName: false, advertisedAppend: false }, + { version: "1.5.1", filter: false, native: false, ownName: true, advertisedAppend: false }, + { version: "1.5.7", filter: false, native: false, ownName: true, advertisedAppend: true }, + { version: "1.3.0", filter: false, native: false, ownName: false, advertisedAppend: false }, + { version: undefined, filter: false, native: false, ownName: false, advertisedAppend: false }, + { version: "unknown", filter: false, native: false, ownName: false, advertisedAppend: false }, ])( - "$version: workflow filter $filter, native reads and system prompt $native, own client name $ownName", - ({ version, filter, native, ownName }) => { + "$version: workflow filter $filter, qualified reads $native, advertised system append $advertisedAppend, own client name $ownName", + ({ version, filter, native, ownName, advertisedAppend }) => { const initialize = { protocolVersion: 1, + ...(advertisedAppend + ? { agentCapabilities: { _meta: { antigravity: { systemPrompt: { append: true } } } } } + : {}), ...(version === undefined ? {} : { agentInfo: { name: "antigravity-acp", version } }), }; // Helpers send no append, so only the workflow filter can apply. @@ -83,10 +87,12 @@ describe("Antigravity release gates", () => { ); const antigravity = { ...(filter ? { disabledTools: ["run_workflow"] } : {}), - ...(native ? { systemPrompt: { append: "" } } : {}), + ...(native || advertisedAppend + ? { systemPrompt: { append: "" } } + : {}), }; expect(antigravitySessionMeta(initialize, "")).toEqual( - filter || native ? { antigravity } : undefined, + filter || native || advertisedAppend ? { antigravity } : undefined, ); expect(isQualifiedAntigravityRelease(version)).toBe(native); expect(antigravityClientInfo(version).name).toBe(ownName ? "t3-code" : "zed"); diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 66eab95c9fb39..7fd64e2534fa7 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -12,6 +12,7 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; +import * as Predicate from "effect/Predicate"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; @@ -94,7 +95,15 @@ const OPEN_MODEL_ACCESS_RELEASE = [1, 5, 1] as const; */ export const antigravityAppendsSystemPrompt = ( initializeResult: EffectAcpSchema.InitializeResponse, -) => isQualifiedAntigravityRelease(initializeResult.agentInfo?.version); +) => { + if (isQualifiedAntigravityRelease(initializeResult.agentInfo?.version)) return true; + const extension = initializeResult.agentCapabilities?._meta?.antigravity; + return ( + Predicate.isObject(extension) && + Predicate.isObject(extension.systemPrompt) && + extension.systemPrompt.append === true + ); +}; export function antigravitySessionMeta( initializeResult: EffectAcpSchema.InitializeResponse, diff --git a/apps/server/src/provider/antigravityAuthSupport.test.ts b/apps/server/src/provider/antigravityAuthSupport.test.ts index 0220f9fd153c7..832f2961d836a 100644 --- a/apps/server/src/provider/antigravityAuthSupport.test.ts +++ b/apps/server/src/provider/antigravityAuthSupport.test.ts @@ -118,7 +118,13 @@ describe("Antigravity process environment", () => { }); expect(spawn.command).toBe("/usr/bin/agy"); - expect(spawn.args).toEqual(["acp"]); + expect(spawn.args).toEqual([ + "acp", + "--gemini-dir", + profile.geminiHome, + "--app-data-dir", + "antigravity-acp", + ]); expect(spawn.env).not.toHaveProperty("ANTIGRAVITY_HARNESS_PATH"); expect(spawn.env).toMatchObject({ GEMINI_HOME: profile.geminiHome, PATH: "/usr/bin" }); }); diff --git a/apps/server/src/provider/antigravityAuthSupport.ts b/apps/server/src/provider/antigravityAuthSupport.ts index 6a926b12f7c90..8d78a504f9fb5 100644 --- a/apps/server/src/provider/antigravityAuthSupport.ts +++ b/apps/server/src/provider/antigravityAuthSupport.ts @@ -467,7 +467,14 @@ export function buildAntigravityAcpSpawnInput(input: { // The agy CLI has no harness sibling and serves ACP through its `acp` subcommand. args: input.installation.harnessPath === null - ? ["acp"] + ? [ + "acp", + "--gemini-dir", + input.profile.geminiHome, + "--app-data-dir", + // The CLI joins this beneath gemini-dir, including when the value is absolute. + "antigravity-acp", + ] : input.profile.platform === "linux" ? ["--uid="] : [], diff --git a/apps/server/src/provider/antigravityCliRelease.test.ts b/apps/server/src/provider/antigravityCliRelease.test.ts new file mode 100644 index 0000000000000..2e1e0010c22c5 --- /dev/null +++ b/apps/server/src/provider/antigravityCliRelease.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from "@effect/vitest"; +import { antigravityCliTarget, parseAntigravityCliRelease } from "./antigravityCliRelease.ts"; + +const manifest = { + version: "1.5.7", + url: "https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.7-123/darwin-arm/cli_mac_arm64.tar.gz", + sha512: "a".repeat(128), +}; + +describe("Antigravity CLI release manifests", () => { + it.each([ + ["darwin", "arm64", false, "darwin_arm64", "darwin-arm/cli_mac_arm64.tar.gz"], + ["darwin", "x64", false, "darwin_amd64", "darwin-x64/cli_mac_x64.tar.gz"], + ["linux", "arm64", false, "linux_arm64", "linux-arm/cli_linux_arm64.tar.gz"], + ["linux", "x64", false, "linux_amd64", "linux-x64/cli_linux_x64.tar.gz"], + ["linux", "arm64", true, "linux_arm64_musl", "linux-arm-musl/cli_linux_arm64_musl.tar.gz"], + ["linux", "x64", true, "linux_amd64_musl", "linux-x64-musl/cli_linux_x64_musl.tar.gz"], + ["win32", "arm64", false, "windows_arm64", "windows-arm/cli_windows_arm64.exe"], + ["win32", "x64", false, "windows_amd64", "windows-x64/cli_windows_x64.exe"], + ] as const)("selects Google's %s-%s release (musl %s)", (platform, arch, musl, target, file) => { + expect(antigravityCliTarget(platform, arch, musl)).toBe(target); + expect( + parseAntigravityCliRelease( + { + ...manifest, + url: `https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.7-123/${file}`, + }, + platform, + arch, + musl, + ), + ).toMatchObject({ + version: "1.5.7", + format: platform === "win32" ? "executable" : "tar.gz", + executable: { name: platform === "win32" ? "agy.exe" : "antigravity" }, + }); + }); + + it.each([ + { sha512: "invalid" }, + { version: "1.4.5" }, + { url: manifest.url.replace("https:", "http:") }, + { url: manifest.url.replace("storage.googleapis.com", "storage.googleapis.com.evil.test") }, + { url: manifest.url.replace("antigravity-public", "another-bucket") }, + { url: manifest.url.replace("darwin-arm", "linux-arm") }, + { url: `${manifest.url}?redirect=elsewhere` }, + { url: manifest.url.replace("1.5.7-123", "1.5.6-123") }, + ])("rejects invalid or mismatched release metadata: %j", (change) => { + expect(parseAntigravityCliRelease({ ...manifest, ...change }, "darwin", "arm64")).toBeNull(); + }); +}); diff --git a/apps/server/src/provider/antigravityCliRelease.ts b/apps/server/src/provider/antigravityCliRelease.ts new file mode 100644 index 0000000000000..3e033beb37ace --- /dev/null +++ b/apps/server/src/provider/antigravityCliRelease.ts @@ -0,0 +1,60 @@ +import * as Schema from "effect/Schema"; +import { compareSemverVersions } from "@t3tools/shared/semver"; + +export const ANTIGRAVITY_CLI_MANIFEST_BASE = + "https://antigravity-cli-auto-updater-974169037036.us-central1.run.app/manifests"; + +const Manifest = Schema.Struct({ + version: Schema.String.check(Schema.isPattern(/^\d+\.\d+\.\d+$/u)), + url: Schema.String, + sha512: Schema.String.check(Schema.isPattern(/^[a-fA-F0-9]{128}$/u)), +}); +const decodeManifest = Schema.decodeUnknownOption(Manifest); + +export interface AntigravityCliReleaseAsset { + readonly version: string; + readonly url: string; + readonly sha512: string; + readonly executable: { readonly name: string }; + readonly format: "tar.gz" | "executable"; +} + +export function antigravityCliTarget(platform: NodeJS.Platform, arch: string, musl = false) { + if (!["darwin", "linux", "win32"].includes(platform) || !["x64", "arm64"].includes(arch)) { + return null; + } + const os = platform === "win32" ? "windows" : platform; + return `${os}_${arch === "x64" ? "amd64" : arch}${platform === "linux" && musl ? "_musl" : ""}`; +} + +export function parseAntigravityCliRelease( + value: unknown, + platform: NodeJS.Platform, + arch: string, + musl = false, +): AntigravityCliReleaseAsset | null { + const decoded = decodeManifest(value); + if (decoded._tag === "None" || antigravityCliTarget(platform, arch, musl) === null) return null; + const manifest = decoded.value; + if (compareSemverVersions(manifest.version, "1.5.0") < 0) return null; + const os = platform === "darwin" ? "mac" : platform === "win32" ? "windows" : "linux"; + const cpu = arch === "x64" ? "x64" : "arm64"; + const suffix = platform === "linux" && musl ? "_musl" : ""; + const extension = platform === "win32" ? "exe" : "tar.gz"; + const folder = `${platform === "win32" ? "windows" : platform}-${arch === "arm64" ? "arm" : "x64"}${suffix ? "-musl" : ""}`; + const prefix = `https://storage.googleapis.com/antigravity-public/antigravity-cli/${manifest.version}-`; + const rest = manifest.url.startsWith(prefix) ? manifest.url.slice(prefix.length) : ""; + if ( + !/^\d+\//u.test(rest) || + rest.replace(/^\d+\//u, "") !== `${folder}/cli_${os}_${cpu}${suffix}.${extension}` + ) { + return null; + } + return { + version: manifest.version, + url: manifest.url, + sha512: manifest.sha512.toLowerCase(), + executable: { name: platform === "win32" ? "agy.exe" : "antigravity" }, + format: platform === "win32" ? "executable" : "tar.gz", + }; +} diff --git a/apps/server/src/provider/antigravityRelease.ts b/apps/server/src/provider/antigravityRelease.ts index 255a92761994a..54702d69935fb 100644 --- a/apps/server/src/provider/antigravityRelease.ts +++ b/apps/server/src/provider/antigravityRelease.ts @@ -1,7 +1,3 @@ -// Hashes and sizes match the official ACP registry release. Like 1.4.2 through 1.4.4, it writes a -// run-workflow skill into the workspace unless T3 disables the tool (antigravitySessionMeta). -const ANTIGRAVITY_RELEASE_VERSION = "1.4.5"; - export interface AntigravityReleaseAsset { readonly version: string; readonly url: string; @@ -16,79 +12,3 @@ export interface AntigravityReleaseAsset { readonly bytes: number; }; } - -const releaseAssets = new Map([ - [ - "darwin-arm64", - { - version: ANTIGRAVITY_RELEASE_VERSION, - url: "https://dl.google.com/agy-extensions/releases/macos/agy-acp-server-1.4.5-darwin-arm64.zip", - sha256: "886fff7767d08994ca39eb02c3d01a7532c7325a94aa33aaf52d52068733284f", - archiveBytes: 97_923_855, - executable: { name: "agy_acp_server.par", bytes: 178_915_920 }, - harness: { name: "localharness_external", bytes: 122_957_936 }, - }, - ], - [ - "darwin-x64", - { - version: ANTIGRAVITY_RELEASE_VERSION, - url: "https://dl.google.com/agy-extensions/releases/macos/agy-acp-server-1.4.5-darwin-x86_64.zip", - sha256: "b39f3573c03b9acb9df028853f647527f1f3133f32bd77e78b796e48a205114a", - archiveBytes: 103_577_295, - executable: { name: "agy_acp_server.par", bytes: 183_127_600 }, - harness: { name: "localharness_external", bytes: 127_612_208 }, - }, - ], - [ - "linux-x64", - { - version: ANTIGRAVITY_RELEASE_VERSION, - url: "https://dl.google.com/agy-extensions/releases/linux/agy-acp-server-1.4.5-linux-x86_64.zip", - sha256: "923923a0d7dc8073f66cc6f78647a3107e3a7ee2b7e1a24df8b3927b5188013b", - archiveBytes: 321_783_181, - executable: { name: "agy_acp_server.par", bytes: 826_226_766 }, - harness: { name: "localharness_external", bytes: 133_926_136 }, - }, - ], - [ - "linux-arm64", - { - version: ANTIGRAVITY_RELEASE_VERSION, - url: "https://dl.google.com/agy-extensions/releases/linux/agy-acp-server-1.4.5-linux-arm64.zip", - sha256: "7d64246633ae094f67e3bbcd2d679e89048f91346d5339313336e7483f40f056", - archiveBytes: 307_829_008, - executable: { name: "agy_acp_server.par", bytes: 831_194_025 }, - harness: { name: "localharness_external", bytes: 127_512_832 }, - }, - ], - [ - "win32-x64", - { - version: ANTIGRAVITY_RELEASE_VERSION, - url: "https://dl.google.com/agy-extensions/releases/windows/agy-acp-server-1.4.5-windows-x86_64.zip", - sha256: "d24f4c73c9f96d4f44384e281c855a56c72d8eaa9c5b0fad7ccb1635c6b63f50", - archiveBytes: 100_423_655, - executable: { name: "agy_acp_server.exe", bytes: 55_839_864 }, - harness: { name: "localharness_external.exe", bytes: 147_843_736 }, - }, - ], - [ - "win32-arm64", - { - version: ANTIGRAVITY_RELEASE_VERSION, - url: "https://dl.google.com/agy-extensions/releases/windows/agy-acp-server-1.4.5-windows-arm64.zip", - sha256: "ab0a9aac8349e08ef289be6d16da8f89e3abe60eba5158032ef78c4a1220261c", - archiveBytes: 102_703_121, - executable: { name: "agy_acp_server.exe", bytes: 62_293_488 }, - harness: { name: "localharness_external.exe", bytes: 139_322_008 }, - }, - ], -]); - -export function resolveAntigravityReleaseAsset( - platform: NodeJS.Platform, - arch: string, -): AntigravityReleaseAsset | null { - return releaseAssets.get(`${platform}-${arch}`) ?? null; -} diff --git a/apps/server/src/provider/managedRelease.ts b/apps/server/src/provider/managedRelease.ts new file mode 100644 index 0000000000000..ca7c55e43b595 --- /dev/null +++ b/apps/server/src/provider/managedRelease.ts @@ -0,0 +1,29 @@ +import { compareSemverVersions, parseSemver } from "@t3tools/shared/semver"; + +// Older pins recorded non-semver versions such as `agy_acp_server_1.1.1`; any +// other release is an update from those. +const isNewer = (candidate: string, current: string) => + parseSemver(candidate) && parseSemver(current) + ? compareSemverVersions(candidate, current) > 0 + : candidate !== current; + +/** + * Picks the release a managed installation's `start` downloads. A fresh install + * gets T3 Code's pinned release; an existing one moves to the newest known + * release above it. Null means nothing newer is known, so `start` re-checks the + * installed runtime instead of downgrading it. + */ +export function selectManagedRelease( + installedVersion: string | null, + pinned: Release | null, + upstream: Release | null, +): Release | null { + if (installedVersion === null) return pinned; + let selected: Release | null = null; + for (const candidate of [pinned, upstream]) { + if (candidate && isNewer(candidate.version, selected?.version ?? installedVersion)) { + selected = candidate; + } + } + return selected; +} diff --git a/apps/server/src/provider/model-manifest.json b/apps/server/src/provider/model-manifest.json index 678ad71161c3f..4906358bab70b 100644 --- a/apps/server/src/provider/model-manifest.json +++ b/apps/server/src/provider/model-manifest.json @@ -1,6 +1,6 @@ { "version": 1, - "updatedAt": "2026-11-10T17:25:47Z", + "updatedAt": "2026-11-12T18:25:36Z", "compatibility": [ { "driver": "codex", @@ -75,8 +75,9 @@ { "driver": "antigravity", "t3CodeRange": ">=0.0.42", - "recommendedRange": "=1.4.5 || =1.4.1", + "recommendedRange": ">=1.5.1 <2", "ranges": [ + { "range": ">=1.5.1 <2", "status": "supported" }, { "range": "=1.4.5", "status": "supported" }, { "range": "=1.4.1", "status": "supported" }, { "range": "=1.3.0", "status": "supported" }, diff --git a/apps/server/src/provider/providerCompatibility.test.ts b/apps/server/src/provider/providerCompatibility.test.ts index 780c2d789731c..1c599113a2091 100644 --- a/apps/server/src/provider/providerCompatibility.test.ts +++ b/apps/server/src/provider/providerCompatibility.test.ts @@ -22,7 +22,6 @@ import { ProviderCompatibilityPolicy, resolveProviderCompatibility, } from "./providerCompatibility.ts"; -import { resolveAntigravityReleaseAsset } from "./antigravityRelease.ts"; import bundledManifest from "./model-manifest.json" with { type: "json" }; const decodeCompatibilityPolicies = Schema.decodeUnknownSync( @@ -133,19 +132,15 @@ describe("provider compatibility", () => { } }); - it.each([ - ["darwin", "arm64"], - ["win32", "x64"], - ] as const)( - "supports the managed Antigravity runtime for %s-%s in the bundled manifest", - (platform, arch) => { + it.each(["1.4.5", "1.5.7"])( + "supports the legacy and native Antigravity runtime %s in the bundled manifest", + (version) => { const policies = decodeCompatibilityPolicies(bundledManifest.compatibility); - const release = resolveAntigravityReleaseAsset(platform, arch); assert.strictEqual( resolveProviderCompatibility( policies, ProviderDriverKind.make("antigravity"), - `agy_acp_server_${release?.version}`, + `agy_acp_server_${version}`, )?.status, "supported", ); diff --git a/apps/server/src/provider/providerInstallation.test.ts b/apps/server/src/provider/providerInstallation.test.ts index 8a3d3316ac320..d4c7467c62d0d 100644 --- a/apps/server/src/provider/providerInstallation.test.ts +++ b/apps/server/src/provider/providerInstallation.test.ts @@ -95,6 +95,7 @@ const makeHarness = Effect.fn("providerInstallation.test.makeHarness")(function* }), state: Effect.succeed({ ...state, driver: ProviderDriverKind.make("codex") }), changes: Stream.succeed({ ...state, driver: ProviderDriverKind.make("codex") }), + checkForUpdate: Effect.void, remove: (paths) => Effect.sync(() => { protectedPaths = paths ?? []; @@ -103,6 +104,7 @@ const makeHarness = Effect.fn("providerInstallation.test.makeHarness")(function* }), Layer.mock(AntigravityInstallation.AntigravityInstallation)({ managedDirectory: "/unused-managed-runtime", + checkForUpdate: Effect.void, start: Effect.sync(() => { calls.push("start"); return { ...state, operationId: "install-1", phase: "downloading" as const }; diff --git a/apps/server/src/provider/providerInstallation.ts b/apps/server/src/provider/providerInstallation.ts index 7a628dfa5b318..e5e864517ba68 100644 --- a/apps/server/src/provider/providerInstallation.ts +++ b/apps/server/src/provider/providerInstallation.ts @@ -186,9 +186,21 @@ const make = Effect.fn("makeProviderInstallation")(function* () { .pipe(Effect.mapError(failure(input.instanceId))); }); + // Watching an installation is when its owner can act on an update, so the + // lookup runs then, in the background, unless update checks are off. const subscribe = (input: ProviderSetupInput) => Stream.unwrap( requireInstance(input.instanceId, "observe-install").pipe( + Effect.tap(({ installation }) => + settings.getSettings.pipe( + Effect.flatMap((current) => + current.enableProviderUpdateChecks + ? Effect.forkDetach(installation.checkForUpdate) + : Effect.void, + ), + Effect.ignore, + ), + ), Effect.map(({ installation }) => installation.changes), ), ); diff --git a/apps/server/src/provider/providerMaintenanceRunner.test.ts b/apps/server/src/provider/providerMaintenanceRunner.test.ts index 32bf49d5861af..985347a66e96b 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.test.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.test.ts @@ -207,6 +207,7 @@ function makeRegistry( refresh: () => Ref.get(providersRef), refreshInstance: () => Ref.get(providersRef), reloadSecretsAndRefresh: () => Ref.get(providersRef), + applySecretAndRefresh: () => Ref.get(providersRef), refreshAfterUpdate: () => { const version = options?.installedVersionAfterUpdate; if (version === undefined) { diff --git a/apps/server/src/provider/testUtils/providerRegistryMock.ts b/apps/server/src/provider/testUtils/providerRegistryMock.ts index 3ae8079414a9c..ccf4979937b35 100644 --- a/apps/server/src/provider/testUtils/providerRegistryMock.ts +++ b/apps/server/src/provider/testUtils/providerRegistryMock.ts @@ -12,6 +12,7 @@ const makeProviderRegistryMock = ( refresh: () => Effect.succeed(providers), refreshInstance: () => Effect.succeed(providers), reloadSecretsAndRefresh: () => Effect.succeed(providers), + applySecretAndRefresh: () => Effect.succeed(providers), refreshAfterUpdate: () => Effect.succeed(providers), refreshWorkspaceSnapshot: () => Effect.succeed(providers), invalidateModelCaches: () => Effect.void, diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index 91ee91b9ab083..b1aaa7e63e87d 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -200,6 +200,8 @@ export class PullRequestService extends Context.Service< input: PullRequestRef, options?: { readonly recoverTransientFailure?: boolean }, ) => Effect.Effect; + /** Whether the reference's host batches summary reads; false when it cannot be resolved. */ + readonly batchesReads: (input: PullRequestRef) => Effect.Effect; readonly stack: ( input: PullRequestRef, options?: { readonly includeDetails?: boolean }, @@ -536,6 +538,7 @@ function withRateLimitBackoff( ...(api.readsPublicHostWithoutCheckout === undefined ? {} : { readsPublicHostWithoutCheckout: api.readsPublicHostWithoutCheckout }), + ...(api.batchesReads === undefined ? {} : { batchesReads: api.batchesReads }), getViewer: options?.viewerAllowsPause === true ? interactive("getViewer", api.getViewer) @@ -3074,6 +3077,16 @@ export const make = Effect.gen(function* () { ); }; + const batchesReads: PullRequestService["Service"]["batchesReads"] = Effect.fn( + "PullRequestService.batchesReads", + )( + function* (input) { + const project = yield* requireProject(input); + return project.api.batchesReads === true; + }, + Effect.orElseSucceed(() => false), + ); + const stack: PullRequestService["Service"]["stack"] = (input, options) => persistedRead( input, @@ -3850,6 +3863,7 @@ export const make = Effect.gen(function* () { return yield* listStats({ ...input, refs: refs.flatMap(Option.toArray) }); }), summary: credentialCached(summary), + batchesReads, stack: credentialCached(stack), subscribeMerges: PubSub.subscribe(mergedPullRequests).pipe( Effect.map((subscription) => Stream.fromSubscription(subscription)), diff --git a/apps/server/src/secrets/SecretCheck.test.ts b/apps/server/src/secrets/SecretCheck.test.ts new file mode 100644 index 0000000000000..9c0bad4cd3111 --- /dev/null +++ b/apps/server/src/secrets/SecretCheck.test.ts @@ -0,0 +1,363 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { + ProviderDriverKind, + ProviderInstanceId, + SecretProviderId, + SecretProviderKind, + type SecretReference, + SettingsSecretValue, + type ServerProvider, +} from "@t3tools/contracts"; +import type { AnyProviderDriver, ProviderInstance } from "@t3tools/provider-core/server/driver"; +import { makeManualOnlyProviderMaintenanceCapabilities } from "@t3tools/provider-core/server/maintenanceResolver"; +import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions"; +import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; +import { defineSecretProviderDriver } from "@t3tools/secret-provider-core/server/driver"; +import { defineSecretProvider } from "@t3tools/secret-provider-core/shared/definition"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import { HttpClient, HttpClientResponse } from "effect/http"; +import * as Layer from "effect/Layer"; +import * as PubSub from "effect/PubSub"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; + +import * as ServerConfig from "../config.ts"; +import * as ModelManifest from "../provider/ModelManifest.ts"; +import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts"; +import * as ProviderInstanceRegistryMutator from "../provider/ProviderInstanceRegistryMutator.ts"; +import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; +import * as SecretCheck from "./SecretCheck.ts"; + +const FAKE_KIND = SecretProviderKind.make("fake"); +const secretProvider = SecretProviderId.make("personal"); +const wanted: SecretReference = { provider: secretProvider, reference: "fake://wanted" }; +const other: SecretReference = { provider: secretProvider, reference: "fake://other" }; +const locked: SecretReference = { provider: secretProvider, reference: "fake://locked" }; +const driverKind = ProviderDriverKind.make("fake-provider"); +const dependent = ProviderInstanceId.make("dependent"); +const unrelated = ProviderInstanceId.make("unrelated"); + +const providerSnapshot = (instanceId: ProviderInstanceId): ServerProvider => ({ + instanceId, + driver: driverKind, + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "2026-10-03T00:00:00.000Z", + version: "1.0.0", + models: [], + slashCommands: [], + skills: [], +}); + +/** + * A server whose `dependent` instance reads `dependentReads` and `unrelated` reads `other`, all + * through the real resolver, instance registry and provider registry. `vault` answers each read of + * a reference with the next queued value, repeating the last one, after `beforeRead`. + */ +const setup = Effect.fn("SecretCheckTest.setup")(function* ( + vault: Map>, + dependentReads: ReadonlyArray = [wanted], + options: { + readonly dependentConfig?: unknown; + readonly beforeRead?: (reference: string) => Effect.Effect; + } = {}, +) { + const reads: Array = []; + const created: Array<{ instanceId: ProviderInstanceId; secrets: ReadonlyArray }> = []; + const createdConfigs: Array = []; + const refreshed: Array = []; + + const secretDriver = defineSecretProviderDriver({ + kind: FAKE_KIND, + definition: defineSecretProvider({ + kind: FAKE_KIND, + label: "Fake", + configSchema: Schema.Struct({}), + isReference: (value) => value.startsWith("fake://"), + referencePlaceholder: "fake://item", + invalidReferenceMessage: "Use fake://item.", + }), + read: (_config, references) => + Effect.forEach(references, (reference) => + (options.beforeRead?.(reference) ?? Effect.void).pipe( + Effect.andThen( + Effect.sync(() => { + reads.push(reference); + const answers = vault.get(reference) ?? []; + return answers.length > 1 ? answers.shift() : answers[0]; + }), + ), + ), + ), + }); + + const driver: AnyProviderDriver = { + driverKind, + metadata: { displayName: "Fake" }, + configSchema: Schema.Struct({ + keys: Schema.Record(Schema.String, SettingsSecretValue).pipe( + Schema.withDecodingDefault(Effect.succeed({})), + ), + }), + defaultConfig: () => ({}), + create: (input) => + Effect.sync(() => { + created.push({ + instanceId: input.instanceId, + secrets: input.environment.map((variable) => variable.value), + }); + createdConfigs.push(input.config); + const snapshot = providerSnapshot(input.instanceId); + return { + instanceId: input.instanceId, + driverKind, + continuationIdentity: { driverKind, continuationKey: `fake:${input.instanceId}` }, + displayName: undefined, + enabled: input.enabled, + snapshot: { + resolveMaintenance: () => + Effect.succeed( + makeManualOnlyProviderMaintenanceCapabilities({ + provider: driverKind, + packageName: null, + }), + ), + getSnapshot: Effect.succeed(snapshot), + refresh: Effect.sync(() => { + refreshed.push(input.instanceId); + return snapshot; + }), + streamChanges: Stream.empty, + applyUsageLimits: () => Effect.void, + }, + orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], + textGeneration: {} as ProviderInstance["textGeneration"], + } satisfies ProviderInstance; + }), + }; + const instanceConfig = (secrets: ReadonlyArray, config: unknown = {}) => ({ + driver: driverKind, + config, + environment: secrets.map((secret, index) => ({ + name: `API_KEY_${index}`, + value: secret, + sensitive: true, + })), + }); + + const resolverContext = yield* Layer.build( + SecretResolver.layer({ + drivers: [secretDriver], + secretProviders: Effect.succeed({ + [secretProvider]: { kind: FAKE_KIND, label: "Personal", config: {} }, + }), + }), + ); + const { registry, mutator } = yield* ProviderInstanceRegistry.makeProviderInstanceRegistry({ + drivers: [driver], + configMap: { + [dependent]: instanceConfig(dependentReads, options.dependentConfig), + [unrelated]: instanceConfig([other]), + }, + }).pipe(Effect.provide(resolverContext)); + // Secrets are read after startup, so wait for the change that applies them. + const changes = yield* registry.subscribeChanges; + yield* PubSub.take(changes); + + const services = yield* Layer.build( + SecretCheck.layer.pipe( + Layer.provideMerge(ProviderRegistry.layer), + Layer.provide( + Layer.mergeAll( + Layer.succeedContext(resolverContext), + Layer.succeed(ProviderInstanceRegistry.ProviderInstanceRegistry, registry), + Layer.succeed(ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator, mutator), + ), + ), + ), + ); + const secretCheck = yield* SecretCheck.SecretCheck.pipe(Effect.provide(services)); + const resolver = yield* SecretResolver.SecretResolver.pipe(Effect.provide(resolverContext)); + return { secretCheck, registry, mutator, resolver, reads, created, createdConfigs, refreshed }; +}); + +const layerTest = Layer.mergeAll( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-secret-check-" }), + ModelManifest.layerTest, + ProviderLatestVersions.layer, + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ version: "0.0.0" }))), + ), + ), +).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))); + +it.layer(layerTest)("SecretCheck", (it) => { + it.effect( + "a readable secret rebuilds and refreshes only the instances that read it, from that one read", + () => + Effect.gen(function* () { + const vault = new Map>([ + [wanted.reference, [undefined]], + [other.reference, ["other-key"]], + ]); + const server = yield* setup(vault); + assert.deepStrictEqual( + (yield* server.registry.listUnavailable).map((entry) => entry.instanceId), + [dependent], + ); + const createdBefore = server.created.length; + const readsBefore = server.reads.length; + + // Unlocked for the check's own read only: any second read would fail again. + vault.set(wanted.reference, ["wanted-key", undefined]); + const result = yield* server.secretCheck.check(wanted); + + assert.deepStrictEqual(result, { _tag: "Resolved" }); + assert.notInclude(JSON.stringify(result), "wanted-key"); + assert.deepStrictEqual(server.reads.slice(readsBefore), [wanted.reference]); + assert.deepStrictEqual(server.created.slice(createdBefore), [ + { instanceId: dependent, secrets: ["wanted-key"] }, + ]); + assert.deepStrictEqual(server.refreshed, [dependent]); + assert.deepStrictEqual(yield* server.registry.listUnavailable, []); + }).pipe(Effect.scoped), + ); + + it.effect("an unreadable secret fails naming its provider and leaves instances alone", () => + Effect.gen(function* () { + const vault = new Map>([ + [wanted.reference, [undefined]], + [other.reference, ["other-key"]], + ]); + const server = yield* setup(vault); + const createdBefore = server.created.length; + + const result = yield* server.secretCheck.check(wanted); + + assert.strictEqual(result._tag, "Failed"); + if (result._tag === "Failed") assert.include(result.detail, "Personal"); + assert.deepStrictEqual(server.created.slice(createdBefore), []); + assert.deepStrictEqual(server.refreshed, []); + assert.deepStrictEqual( + (yield* server.registry.listUnavailable).map((entry) => entry.instanceId), + [dependent], + ); + }).pipe(Effect.scoped), + ); + + it.effect("a failed check keeps the value the server already holds", () => + Effect.gen(function* () { + const vault = new Map>([ + [wanted.reference, ["wanted-key"]], + [locked.reference, ["locked-key", undefined]], + [other.reference, ["other-key"]], + ]); + const server = yield* setup(vault, [wanted, locked]); + const readsBefore = server.reads.length; + + assert.strictEqual((yield* server.secretCheck.check(locked))._tag, "Failed"); + + assert.deepStrictEqual(yield* server.resolver.read([locked]), ["locked-key"]); + assert.deepStrictEqual(server.reads.slice(readsBefore), [locked.reference]); + }).pipe(Effect.scoped), + ); + + it.effect("a check applies to an instance whose other secret failed a later refresh", () => + Effect.gen(function* () { + const vault = new Map>([ + [wanted.reference, ["wanted-old"]], + [locked.reference, ["locked-key", undefined]], + [other.reference, ["other-key"]], + ]); + const server = yield* setup(vault, [wanted, locked]); + // A Settings refresh while the vault is locked keeps the live instance and caches the failure. + yield* server.mutator.reloadSecrets(dependent); + vault.set(wanted.reference, ["wanted-new"]); + + assert.deepStrictEqual(yield* server.secretCheck.check(wanted), { _tag: "Resolved" }); + + assert.deepStrictEqual(server.created.at(-1), { + instanceId: dependent, + secrets: ["wanted-new", "locked-key"], + }); + assert.deepStrictEqual(yield* server.registry.listUnavailable, []); + }).pipe(Effect.scoped), + ); + + it.effect("a check applies the value it read when a refresh re-reads that secret first", () => + Effect.forEach( + // A live instance holding the old value, and one parked on a locked vault. + ["wanted-old", undefined], + (initial) => + Effect.gen(function* () { + const vault = new Map>([ + [wanted.reference, [initial]], + [other.reference, ["other-key"]], + ]); + const readStarted = yield* Deferred.make(); + const release = yield* Deferred.make(); + let gate: Effect.Effect = Effect.void; + const server = yield* setup(vault, [wanted], { + beforeRead: () => { + const current = gate; + gate = Effect.void; + return current; + }, + }); + // The check reads the rotated value; the refresh's read after it finds the vault locked. + vault.set(wanted.reference, ["wanted-new", undefined]); + gate = Deferred.succeed(readStarted, undefined).pipe( + Effect.andThen(Deferred.await(release)), + ); + + const check = yield* server.secretCheck + .check(wanted) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(readStarted); + // The refresh takes the registry lock, then waits on the resolver for the check's read. + const refresh = yield* server.mutator + .reloadSecrets(dependent) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.succeed(release, undefined); + + assert.deepStrictEqual(yield* Fiber.join(check), { _tag: "Resolved" }); + yield* Fiber.join(refresh); + assert.deepStrictEqual(server.created.at(-1), { + instanceId: dependent, + secrets: ["wanted-new"], + }); + assert.deepStrictEqual(yield* server.registry.listUnavailable, []); + }).pipe(Effect.scoped), + { discard: true }, + ), + ); + + it.effect("a check replaces only its own key of a record-valued config secret", () => + Effect.gen(function* () { + const vault = new Map>([ + [wanted.reference, ["wanted-old"]], + [locked.reference, ["locked-key"]], + [other.reference, ["other-key"]], + ]); + const server = yield* setup(vault, [], { + dependentConfig: { keys: { a: wanted, b: locked } }, + }); + vault.set(wanted.reference, ["wanted-new"]); + + assert.deepStrictEqual(yield* server.secretCheck.check(wanted), { _tag: "Resolved" }); + + assert.deepStrictEqual(server.created.at(-1), { instanceId: dependent, secrets: [] }); + assert.deepStrictEqual(server.createdConfigs.at(-1), { + keys: { a: "wanted-new", b: "locked-key" }, + }); + }).pipe(Effect.scoped), + ); +}); diff --git a/apps/server/src/secrets/SecretCheck.ts b/apps/server/src/secrets/SecretCheck.ts new file mode 100644 index 0000000000000..f2a6241eeb7a0 --- /dev/null +++ b/apps/server/src/secrets/SecretCheck.ts @@ -0,0 +1,39 @@ +import type { SecretReference, SecretSourceCheckResult } from "@t3tools/contracts"; +import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; + +export class SecretCheck extends Context.Service< + SecretCheck, + { + /** + * Reads one secret fresh for the Settings "check" button and never returns the value. A + * readable secret also rebuilds the provider instances that read it, from that same read. + */ + readonly check: (reference: SecretReference) => Effect.Effect; + } +>()("t3/secrets/SecretCheck") {} + +const make = Effect.gen(function* () { + const resolver = yield* SecretResolver.SecretResolver; + const providerRegistry = yield* ProviderRegistry.ProviderRegistry; + + const check = Effect.fn("SecretCheck.check")(function* (reference: SecretReference) { + const [value] = yield* resolver.read([reference], { fresh: true }); + if (value === undefined || value.trim() === "") { + return { + _tag: "Failed", + detail: `Could not read this secret from "${yield* resolver.label(reference.provider)}". Check the provider's settings and that its store is unlocked.`, + } as const; + } + yield* providerRegistry.applySecretAndRefresh(reference, value); + return { _tag: "Resolved" } as const; + }); + + return SecretCheck.of({ check }); +}); + +export const layer = Layer.effect(SecretCheck, make); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index a49a2d5c2dc1d..7ec8a73d0c922 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -18,6 +18,7 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as SpawnHost from "./process/SpawnHost.ts"; import { EnvironmentHttpApi, type RepositoryIdentity } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Cause from "effect/Cause"; import * as Duration from "effect/Duration"; import * as Deferred from "effect/Deferred"; @@ -39,6 +40,7 @@ import { keepIdleConnections, rejectRequestsUntilServing, } from "./httpResponseErrorGuard.ts"; +import { resolveLauncherPath } from "./cloud/pinnedRuntime.ts"; import { fixPath } from "./os-jank.ts"; import * as Ws from "./ws.ts"; import * as AgentScopeLive from "./process/agentScope.ts"; @@ -77,6 +79,7 @@ import * as SourceControlBuiltInDrivers from "./sourceControl/builtInDrivers.ts" import * as SourceControlSignIn from "./sourceControl/SourceControlSignIn.ts"; import { BUILT_IN_SOURCE_CONTROL_DRIVER_LIST } from "./sourceControl/sourceControlDefinitions.ts"; import * as TextGeneration from "./textGeneration/TextGeneration.ts"; +import * as SecretCheck from "./secrets/SecretCheck.ts"; import * as SecretResolver from "./secrets/SecretResolver.ts"; import * as ProviderInstanceRegistryHydration from "./provider/ProviderInstanceRegistryHydration.ts"; import * as ProjectSettingsOverrideSweep from "./provider/ProjectSettingsOverrideSweep.ts"; @@ -221,7 +224,7 @@ import * as RelayClient from "@t3tools/shared/relayClient"; import { disableTailscaleServe, ensureTailscaleServe, - readTailscaleServeRootHolders, + readTailscaleServeRootHolder, readTailscaleServeRoutesTo, readTailscaleStatus, } from "@t3tools/tailscale"; @@ -506,7 +509,9 @@ const layerCheckpointStore = CheckpointStore.layer.pipe(Layer.provide(layerVcsDr const layerPortScanner = PortScanner.layer.pipe(Layer.provide(ProcessRunner.layer)); -const layerTerminal = TerminalManager.layer.pipe( +const layerTerminal = TerminalManager.layer( + ProviderInstanceRegistryHydration.deriveProviderInstanceConfigMap, +).pipe( Layer.provide(layerPtyAdapter), Layer.provide(layerPortScanner), Layer.provide(layerNativeTelemetry), @@ -705,6 +710,7 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( Layer.provideMerge(layerOrchestrationApplication), Layer.provideMerge(RuntimeLayer.layerEventInfrastructure), Layer.provideMerge(Layer.merge(ProjectStore.layer, ThreadSearch.layer)), + Layer.provideMerge(SecretCheck.layer), Layer.provideMerge(SecretResolver.layer), Layer.provideMerge(layerServerSettings), Layer.provideMerge(layerSourceControlProviderRegistry), @@ -727,7 +733,9 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( Layer.provideMerge(layerPortScanner), Layer.provideMerge( Layer.mergeAll( - AntigravityInstallation.AntigravityInstallation.layer, + AntigravityInstallation.AntigravityInstallation.layer.pipe( + Layer.provide(layerServerSettings), + ), CodexInstallation.CodexInstallation.layer, ), ), @@ -787,7 +795,7 @@ const layerRuntimeDependencies = layerRuntimeCoreDependencies.pipe( Layer.provideMerge(AnalyticsService.layer.pipe(Layer.provide(ManagedPolicy.layer))), Layer.provideMerge(ExternalLauncher.layer), Layer.provideMerge(RemoteOpenTargets.layer), - Layer.provideMerge(DirectEndpoints.layer), + Layer.provideMerge(DirectEndpoints.layer.pipe(Layer.provide(layerServerEnvironment))), Layer.provideMerge(ServerLifecycleEvents.layer), Layer.provide(NetService.layer), ); @@ -885,6 +893,8 @@ const layerMakeServer = Layer.unwrap( const routesReady = yield* Deferred.make(); const layerLauncher = ServiceLauncherClient.layer; + // fixPath rewrites PATH, so pin the launcher the shell chose before it does. + const invokedAs = (yield* resolveLauncherPath) ?? (yield* HostProcess.InvokedAs); yield* fixPath({ shellEnvironmentPrepared: config.shellEnvironmentPrepared }); const layerHttpListening = Layer.effectDiscard( @@ -920,22 +930,8 @@ const layerMakeServer = Layer.unwrap( ); }), ); - // Who holds the Serve port's root: nobody, this server, only dead loopback ports (an unclean - // exit leaves one), or another live server or app, whose route is left alone. - const tailscaleServeRootHolder = Effect.fn("server.tailscaleServeRootHolder")( - function* (target: { readonly host: string; readonly port: number }) { - const net = yield* NetService.NetService; - const holders = yield* readTailscaleServeRootHolders(config.tailscaleServePort, target); - if (holders.length === 0) return "none" as const; - if (holders.some((holder) => holder.ours)) return "ours" as const; - const live = yield* Effect.forEach(holders, (holder) => - holder.ours || holder.loopback === undefined - ? Effect.succeed(true) - : net.hasListenerOnHost(holder.loopback.port, holder.loopback.host), - ); - return live.includes(true) ? ("other" as const) : ("dead" as const); - }, - ); + const tailscaleServeRootHolder = (target: { readonly host: string; readonly port: number }) => + readTailscaleServeRootHolder(config.tailscaleServePort, target); const layerTailscaleServe = config.tailscaleServeEnabled ? Layer.effectDiscard( Effect.acquireRelease( @@ -982,11 +978,13 @@ const layerMakeServer = Layer.unwrap( }), ), Effect.catch((cause) => - Effect.logWarning("Failed to configure Tailscale Serve", { - cause, - localPort, - servePort: config.tailscaleServePort, - }).pipe(Effect.as(null)), + Effect.logWarning( + cause._tag === "TailscaleCommandExitError" && + cause.stderrDiagnostic === "unsupported-target" + ? `Tailscale Serve left off; this Tailscale install can only proxy to localhost, not ${localHost}. Bind --host 127.0.0.1 or 0.0.0.0 instead` + : "Failed to configure Tailscale Serve", + { cause, localPort, servePort: config.tailscaleServePort }, + ).pipe(Effect.as(null)), ), ); }), @@ -1309,6 +1307,7 @@ const layerMakeServer = Layer.unwrap( Layer.provideMerge(FetchHttpClient.layer), Layer.provide(VcsProcess.layer), Layer.provideMerge(AgentScopeLive.layer), + Layer.provide(Layer.succeed(HostProcess.InvokedAs, invokedAs)), ); }), ).pipe(Layer.provide(ProcessRunner.layer), Layer.provide(layerPlatformServices)); diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index 347b43dd6f44c..3ca2d29da7c81 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -1,3 +1,4 @@ +import { deriveProviderInstanceConfigMap } from "./provider/ProviderInstanceRegistryHydration.ts"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { @@ -539,6 +540,17 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" (yield* serverSettings.getSettings).providerInstances[instanceId]?.displayName ?? "", ), ); + + // An inherited Object.prototype member is not an instance that already exists. + for (const name of ["constructor", "toString", "valueOf"]) { + const prototypeNamedId = ProviderInstanceId.make(name); + const created = yield* serverSettings.updateProviderInstance({ + operation: "create", + instanceId: prototypeNamedId, + instance: { driver: ProviderDriverKind.make("codex") }, + }); + assert.isTrue(Object.hasOwn(created.providerInstances, prototypeNamedId)); + } }).pipe(Effect.provide(layerServerSettings())), ); @@ -2063,6 +2075,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" }); const environment = yield* resolveProviderInstanceTerminalEnvironment({ + deriveProviderInstanceConfigMap, serverSettings, path, rawProviderInstanceId: instanceId, diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index 251becba12f6c..4dc30d29a6cff 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -237,7 +237,7 @@ function ensureProviderInstanceMutationAllowed( ): Effect.Effect { if ( mutation.operation === "create" && - settings.providerInstances[mutation.instanceId] !== undefined + Object.hasOwn(settings.providerInstances, mutation.instanceId) ) { return Effect.fail( new ServerSettingsError({ diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts index b933895c4de1a..cf4fd495d988d 100644 --- a/apps/server/src/storageCleanup.test.ts +++ b/apps/server/src/storageCleanup.test.ts @@ -205,6 +205,13 @@ describe("V2 storage cleanup eligibility", () => { resetIn: -1_000, idle: false, }, + { + name: "never armed because its reset is days overdue", + armed: false, + autoResumeSetting: true, + resetIn: -5 * DAY_MS, + idle: true, + }, { name: "not armed with recovery settings off", armed: false, @@ -1755,6 +1762,57 @@ describe("orphan worktree reports", () => { ), ); + it.live.each([ + { home: "an installed", worktreeHome: false, customFolderOutcome: "removed" }, + { home: "a git worktree's dev", worktreeHome: true, customFolderOutcome: "kept" }, + ] as const)( + "on $home home, a custom worktrees folder ends $customFolderOutcome", + ({ worktreeHome, customFolderOutcome }) => + runCleanupTest( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const config = yield* ServerConfig.ServerConfig; + const checkout = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-dev-checkout-" }); + yield* fs.writeFileString(`${checkout}/.git`, "gitdir: /repo/.git/worktrees/dev\n"); + const baseDir = worktreeHome ? `${checkout}/.t3` : config.baseDir; + const fixture = yield* cleanupFixture().pipe( + Effect.provideService(ServerConfig.ServerConfig, { + ...config, + baseDir, + worktreesDir: `${baseDir}/worktrees`, + }), + ); + const customFolder = yield* fs.realPath( + yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-real-worktrees-" }), + ); + const realWorktree = `${customFolder}/seeded`; + yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "seeded", realWorktree]); + fixture.setSettings({ worktreesDirectory: customFolder }); + fixture.setThreads([ + shell({ branch: "feature", worktreePath: fixture.worktree }), + shell({ + id: ThreadId.make("seeded"), + lineage: { + rootThreadId: ThreadId.make("seeded"), + parentThreadId: null, + relationshipToParent: null, + }, + branch: "seeded", + worktreePath: realWorktree, + }), + ]); + + const { entries } = yield* fixture.service.runNow; + + expect(entries.find((entry) => entry.path === realWorktree)?.outcome).toBe( + customFolderOutcome, + ); + expect(yield* fs.exists(realWorktree)).toBe(customFolderOutcome === "kept"); + expect(yield* fs.exists(fixture.worktree)).toBe(false); + }), + ), + ); + it.live("skips symbolic links at both directory levels and disabled cleanup", () => runCleanupTest( Effect.gen(function* () { diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts index d044c2f7bdc40..4721b0c1b1bf8 100644 --- a/apps/server/src/storageCleanup.ts +++ b/apps/server/src/storageCleanup.ts @@ -17,6 +17,7 @@ import type { ThreadId, } from "@t3tools/contracts"; import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings"; +import { resolveWorktreeT3Home } from "@t3tools/shared/devHome"; import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker"; import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; @@ -42,6 +43,7 @@ import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts"; import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts"; import { threadHasQueuedTurnStart } from "./orchestration-v2/ThreadSettlementService.ts"; +import { MAX_OVERDUE_ARM_MS } from "./orchestration-v2/UsageLimitRecoveryWorker.ts"; import { forkParked } from "./serverActivation.ts"; import * as Settings from "./serverSettings.ts"; import * as TerminalManager from "./terminal/Manager.ts"; @@ -182,10 +184,12 @@ function heldForLimitRecovery( // An auto-resume holds until its continuation replaces the failed run. return recovery.autoResume || (recovery.snooze === true && resetMs > now); // The recovery worker arms this failure on a later tick; hold it until then. - // Like the worker, skip a reset that had already passed when the run ended. + // Like the worker, skip a reset that had already passed when the run ended + // or that is too overdue to arm. if ( !Number.isFinite(resetMs) || - resetMs <= DateTime.toEpochMillis(thread.latestRunCompletedAt ?? thread.updatedAt) + resetMs <= DateTime.toEpochMillis(thread.latestRunCompletedAt ?? thread.updatedAt) || + now - resetMs > MAX_OVERDUE_ARM_MS ) return false; return settings.autoResumeLimitedThreads || (settings.snoozeLimitedThreads && resetMs > now); @@ -922,12 +926,18 @@ const make = Effect.gen(function* () { let waiting = false; const kept: string[] = []; const roots: Array = []; - for (const directory of managedWorktreesDirectories( - serverSettings, - config.worktreesDir, - path, - yield* HostProcess.HomeDirectory, - )) { + // A git worktree's dev home is seeded from real data, so its threads and any + // copied settings can point at the developer's real worktrees. + const isWorktreeDevHome = + (yield* resolveWorktreeT3Home(config.baseDir)) === path.resolve(config.baseDir); + for (const directory of isWorktreeDevHome + ? [config.worktreesDir] + : managedWorktreesDirectories( + serverSettings, + config.worktreesDir, + path, + yield* HostProcess.HomeDirectory, + )) { const root = yield* fs.exists(directory).pipe( Effect.flatMap((exists) => (exists ? fs.realPath(directory) : Effect.succeed(null))), Effect.orElseSucceed(() => null), diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index 5c65b9d973baa..60b1dd131d3cc 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -1,3 +1,4 @@ +import { deriveProviderInstanceConfigMap } from "../provider/ProviderInstanceRegistryHydration.ts"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; @@ -9,6 +10,7 @@ import { ProviderDriverKind, ProviderInstanceId, ProjectId, + retainedTerminalHistory, TerminalProviderInstanceNotFoundError, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -1157,6 +1159,7 @@ it.layer( process.emitData("prompt "); process.emitData("\u001b[?2026$p\u001b[?2026;2$y\u001b[>q\u001b[?u\u001b[?31u"); + process.emitData("\u001b[=c\u001b[=0c"); process.emitData("\u001bP$q m\u001b\\\u001bP1$r0m\u001b\\"); process.emitData("\u001bP+q544e\u001b\\\u001bP1+r544e=1b\u001b\\"); process.emitData('\u001b[!p\u001b["p\u001b[4 q\u001b[u'); @@ -2053,6 +2056,7 @@ it.layer( const path = yield* Path.Path; const serverSettings = yield* ServerSettings.ServerSettingsService; const environment = yield* TerminalManager.resolveProviderInstanceTerminalEnvironment({ + deriveProviderInstanceConfigMap, serverSettings, path, rawProviderInstanceId: "configured_home", @@ -2322,6 +2326,57 @@ it.layer( }).pipe(Effect.scoped), ); + it.effect("sends bounded attach streams only the history the client retains", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + const maxHistoryBytes = 9; + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]!; + const published = yield* Deferred.make(); + const unsubscribe = yield* manager.subscribe((event) => + event.type === "output" && event.data === "yz\n" + ? Deferred.succeed(published, undefined).pipe(Effect.asVoid) + : Effect.void, + ); + process.emitData("aaaa\nx名😀"); + process.emitData("yz\n"); + yield* Deferred.await(published); + unsubscribe(); + + const full = yield* Stream.toPull(manager.attachOutputStream(openInput(), "full")); + const bounded = yield* Stream.toPull( + manager.attachOutputStream({ ...openInput(), maxHistoryBytes }, "bounded"), + ); + const expectRetained = Effect.fnUntraced(function* () { + const [fullEvents, boundedEvents] = [yield* full, yield* bounded]; + const fullSnapshot = fullEvents.at(-1); + if (fullSnapshot?.type !== "snapshot") throw new Error("Expected a full snapshot"); + expect(boundedEvents.at(-1)).toEqual({ + ...fullSnapshot, + snapshot: { + ...fullSnapshot.snapshot, + history: retainedTerminalHistory(fullSnapshot.snapshot.history, maxHistoryBytes), + }, + }); + return fullSnapshot.snapshot.history; + }); + + expect(yield* expectRetained()).toBe("aaaa\nx名😀yz\n"); + // The cap starts inside 名, so the tail begins at the next code point. + expect(retainedTerminalHistory("aaaa\nx名😀yz\n", maxHistoryBytes)).toBe("😀yz\n"); + process.emitData("after\n"); + expect(yield* full).toEqual(yield* bounded); + + yield* publishPastOutputBudget(manager, process); + expect(yield* expectRetained()).toMatch(/last\n$/); + + process.emitExit({ exitCode: 0, signal: 0 }); + expect(yield* full).toEqual(yield* bounded); + yield* manager.attachStream({ ...openInput(), restartIfNotRunning: true }, () => Effect.void); + yield* expectRetained(); + }).pipe(Effect.scoped), + ); + it.effect("does not replay in-flight output already included in an observer snapshot", () => Effect.gen(function* () { const { manager, ptyAdapter } = yield* createManager(); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 625b678446e17..d5f6b2edee914 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -5,6 +5,7 @@ import { withWorkspaceLease } from "../workspace/workspaceLease.ts"; import { DEFAULT_TERMINAL_ID, DEFAULT_MAX_TERMINAL_BUFFER_BYTES, + retainedTerminalHistory, TerminalCwdError, TerminalCwdNotDirectoryError, TerminalCwdNotFoundError, @@ -67,7 +68,7 @@ import * as ServerConfig from "../config.ts"; import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts"; import { makeClaudeEnvironment } from "../provider/Drivers/ClaudeHome.ts"; -import { deriveProviderInstanceConfigMap } from "../provider/ProviderInstanceRegistryHydration.ts"; +import type { deriveProviderInstanceConfigMap } from "../provider/ProviderInstanceRegistryHydration.ts"; import * as ServerSettings from "../serverSettings.ts"; import { increment, terminalSessionsTotal } from "../observability/Metrics.ts"; import { expandHomeVariable } from "@t3tools/provider-core/server/pathExpansion"; @@ -1106,7 +1107,7 @@ function shouldStripCsiSequence(body: string, finalByte: string): boolean { if (finalByte === "R" && /^[0-9;?]*$/.test(body)) { return true; } - if (finalByte === "c" && /^[>0-9;?]*$/.test(body)) { + if (finalByte === "c" && /^[>=0-9;?]*$/.test(body)) { return true; } // Strip DECRQM/DECRPM query traffic to prevent echoed replies during replay; $ guards preserve setters. @@ -1451,6 +1452,7 @@ interface TerminalManagerOptions { export const resolveProviderInstanceTerminalEnvironment = Effect.fn( "terminal.resolveProviderInstanceTerminalEnvironment", )(function* (input: { + readonly deriveProviderInstanceConfigMap: typeof deriveProviderInstanceConfigMap; readonly serverSettings: ServerSettings.ServerSettingsService["Service"]; readonly path: Path.Path; readonly rawProviderInstanceId: string; @@ -1460,7 +1462,7 @@ export const resolveProviderInstanceTerminalEnvironment = Effect.fn( const settings = yield* input.serverSettings.getSettings.pipe( Effect.mapError((cause) => new TerminalProviderEnvironmentError({ providerInstanceId, cause })), ); - const instance = deriveProviderInstanceConfigMap(settings)[providerInstanceId]; + const instance = input.deriveProviderInstanceConfigMap(settings)[providerInstanceId]; if (instance === undefined) { return yield* new TerminalProviderInstanceNotFoundError({ providerInstanceId }); } @@ -1490,7 +1492,9 @@ export const resolveProviderInstanceTerminalEnvironment = Effect.fn( }); /** @public */ -export const make = Effect.fn("TerminalManager.make")(function* () { +export const make = Effect.fn("TerminalManager.make")(function* ( + deriveConfigMap: typeof deriveProviderInstanceConfigMap, +) { const { terminalLogsDir, providerStatusCacheDir, baseDir } = yield* ServerConfig.ServerConfig; const ptyAdapter = yield* PtyAdapter.PtyAdapter; const portDiscovery = yield* PortScanner.PortDiscovery; @@ -1501,6 +1505,7 @@ export const make = Effect.fn("TerminalManager.make")(function* () { "terminal.resolveProviderInstanceEnvironment", )((rawProviderInstanceId: string, env: Record | undefined) => resolveProviderInstanceTerminalEnvironment({ + deriveProviderInstanceConfigMap: deriveConfigMap, serverSettings, path, rawProviderInstanceId, @@ -3236,20 +3241,41 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func registerCleanup, ); - const attachOutputStream: TerminalManager["Service"]["attachOutputStream"] = (input, viewerId) => - Stream.unwrap( + const attachOutputStream: TerminalManager["Service"]["attachOutputStream"] = ( + input, + viewerId, + ) => { + const { maxHistoryBytes } = input; + const retained = (listener: (event: TerminalAttachStreamEvent) => Effect.Effect) => + maxHistoryBytes === undefined + ? listener + : (event: TerminalAttachStreamEvent) => + listener( + "snapshot" in event + ? { + ...event, + snapshot: { + ...event.snapshot, + history: retainedTerminalHistory(event.snapshot.history, maxHistoryBytes), + }, + } + : event, + ); + return Stream.unwrap( Effect.acquireRelease( Effect.sync(() => retainViewerOnce(input, viewerId, null)), (release) => Effect.sync(release), ).pipe( Effect.as( terminalOutputStream( - (listener, registerCleanup) => attachStream(input, listener, registerCleanup, viewerId), - (listener, registerCleanup) => resyncStream(input, listener, registerCleanup), + (listener, registerCleanup) => + attachStream(input, retained(listener), registerCleanup, viewerId), + (listener, registerCleanup) => resyncStream(input, retained(listener), registerCleanup), ), ), ), ); + }; const metadataEventFromTerminalEvent = ( event: TerminalEvent, @@ -3509,4 +3535,5 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func }); }); -export const layer = Layer.effect(TerminalManager, make()).pipe(Layer.provide(ProcessRunner.layer)); +export const layer = (deriveConfigMap: typeof deriveProviderInstanceConfigMap) => + Layer.effect(TerminalManager, make(deriveConfigMap)).pipe(Layer.provide(ProcessRunner.layer)); diff --git a/apps/server/src/textGeneration/CodexTextGeneration.test.ts b/apps/server/src/textGeneration/CodexTextGeneration.test.ts index b67d3f0ac5830..389a6458677e7 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.test.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.test.ts @@ -1,5 +1,4 @@ import { - DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER, ProjectId, ProviderDriverKind, type ModelSelection, @@ -559,6 +558,11 @@ it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (prima model: "chat-model", options: [{ id: "effort", value: "high" }], }; + const threadDefault = { + instanceId: fallback, + model: "z-ai/glm-5.3-flash", + options: [{ id: "thinking", value: false }], + }; const calls: ModelSelection[] = []; const instances: ProviderInstance[] = [primary, fallback].map((instanceId) => { const driver = ProviderDriverKind.make(instanceId === primary ? "codex" : "claudeAgent"); @@ -627,8 +631,12 @@ it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (prima }), ServerSettings.layerTest({ providerInstances: { - [fallback]: { driver: ProviderDriverKind.make("claudeAgent"), config: {} }, + [fallback]: { + driver: ProviderDriverKind.make("claudeAgent"), + config: { customModels: [threadDefault.model] }, + }, }, + defaultModelSelection: threadDefault, ...(primaryState === "not installed, fallback disabled for project" ? { projectSettingsOverrides: { @@ -660,11 +668,7 @@ it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (prima primaryState === "not installed, fallback disabled for project" || primaryState === "signed out, fallback failed" ? selection - : { - instanceId: fallback, - model: - DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER[ProviderDriverKind.make("claudeAgent")], - }, + : threadDefault, ]); }), ); diff --git a/apps/server/src/textGeneration/TextGeneration.ts b/apps/server/src/textGeneration/TextGeneration.ts index 3042c97191cbd..b89e264db8d57 100644 --- a/apps/server/src/textGeneration/TextGeneration.ts +++ b/apps/server/src/textGeneration/TextGeneration.ts @@ -9,10 +9,7 @@ import { } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import { exhaustedUsageWindow } from "@t3tools/shared/usageLimits"; -import { - defaultTextGenerationModel, - fallbackTextGenerationModelSelection, -} from "@t3tools/shared/serverSettings"; +import { fallbackTextGenerationModelSelection } from "@t3tools/shared/serverSettings"; import * as ServerSettings from "../serverSettings.ts"; import type { ProviderTextGeneration } from "@t3tools/provider-core/server/textGeneration"; import { TextGenerationError } from "@t3tools/contracts"; @@ -125,21 +122,25 @@ export const make = Effect.gen(function* () { ), ); selection = - fallbackTextGenerationModelSelection(settings.providerInstances, (instanceId, driver) => { - const provider = snapshots.find((candidate) => candidate.instanceId === instanceId); - return ( - instanceId !== selection.instanceId && - provider?.enabled === true && - resolveProjectProviderInstanceEnabled(settings, projectId ?? null, instanceId) && - provider.installed && - provider.auth.status !== "unauthenticated" && - provider.status !== "error" && - isProviderAvailable(provider) && - isProviderTextGenerationCapable(provider) && - (operation !== "generateReviewGuide" || INVESTIGATING_DRIVERS.has(driver)) && - !exhaustedUsageWindow(provider, now, defaultTextGenerationModel(driver)) - ); - }) ?? selection; + fallbackTextGenerationModelSelection( + settings.providerInstances, + (instanceId, driver, model) => { + const provider = snapshots.find((candidate) => candidate.instanceId === instanceId); + return ( + instanceId !== selection.instanceId && + provider?.enabled === true && + resolveProjectProviderInstanceEnabled(settings, projectId ?? null, instanceId) && + provider.installed && + provider.auth.status !== "unauthenticated" && + provider.status !== "error" && + isProviderAvailable(provider) && + isProviderTextGenerationCapable(provider) && + (operation !== "generateReviewGuide" || INVESTIGATING_DRIVERS.has(driver)) && + !exhaustedUsageWindow(provider, now, model) + ); + }, + { defaultModelSelection: settings.defaultModelSelection }, + ) ?? selection; } if (textGeneratorCannotRun && selection.instanceId === textGeneratorId) { return yield* new TextGenerationError({ diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index ae0126d438254..281884dcc3bc2 100644 --- a/apps/server/src/usage/UsageService.test.ts +++ b/apps/server/src/usage/UsageService.test.ts @@ -249,6 +249,7 @@ const layerService = (input: { ); const BEFORE_NARROW_WINDOW = Date.parse("2026-08-01T10:00:00Z") / 1000; +const NARROW_WINDOW_MTIME = Date.parse("2026-09-01T10:00:00Z") / 1000; const NARROW_WINDOW: UsageSummaryInput = { timeZone: "UTC", sinceDay: UsageDay.make("2026-09-01"), @@ -577,9 +578,55 @@ describe("UsageService", () => { assert.strictEqual(totalOutputTokens(rewritten), 71); assert.deepStrictEqual((yield* service.readSummary(WINDOW)).buckets, rewritten.buckets); yield* service.awaitPersisted; + const { stateDir } = yield* ServerConfig.ServerConfig; + const cachePath = NodePath.join(stateDir, SCAN_CACHE_FILE_NAME); + const originalPath = (yield* Effect.promise(() => NodeFSP.realpath(compressedPath))).slice( + 0, + -4, + ); + yield* Effect.promise(async () => { + const document = decodeUnknownJsonString(await NodeFSP.readFile(cachePath, "utf8")) as { + files: Record< + string, + { cs: Record; r: unknown[]; t: unknown[]; mr: number } + >; + }; + const archived = document.files[await NodeFSP.realpath(compressedPath)]; + assert.ok(archived); + document.files[originalPath] = { + ...archived, + r: [], + t: [], + mr: 1, + cs: { ...archived.cs, malformedRecords: 1 }, + }; + await NodeFSP.writeFile(cachePath, encodeUnknownJsonString(document)); + }); const restarted = yield* UsageService.make; - assert.deepStrictEqual((yield* restarted.readSummary(WINDOW)).buckets, rewritten.buckets); + const restored = yield* restarted.readSummary(WINDOW); + assert.deepStrictEqual(restored.buckets, rewritten.buckets); + assert.strictEqual( + restored.sources.find((source) => source.fingerprint.provider === "codex") + ?.malformedRecords, + 0, + ); yield* restarted.awaitPersisted; + yield* Effect.promise(async () => { + const document = decodeUnknownJsonString(await NodeFSP.readFile(cachePath, "utf8")) as { + files: Record; + }; + assert.strictEqual(document.files[originalPath], undefined); + await NodeFSP.rm(compressedPath); + }); + const removed = yield* UsageService.make; + const retained = yield* removed.readSummary(WINDOW); + assert.deepStrictEqual(retained.buckets, rewritten.buckets); + assert.strictEqual( + retained.sources.find((source) => source.fingerprint.provider === "codex") + ?.malformedRecords, + 0, + ); + yield* removed.awaitPersisted; }).pipe( Effect.scoped, Effect.provide(layerService({ prefix: "usage-compressed-codex", home, settings })), @@ -2403,6 +2450,75 @@ describe("UsageService", () => { }).pipe(Effect.scoped), ); + it.live( + "answers a provisional read from the last scan, then the exact read adds what changed", + () => + Effect.gen(function* () { + const { transcript, settings, home } = yield* setup; + yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5))); + const provisional = { ...WINDOW, provisional: true }; + const claude = (summary: UsageSummary) => + summary.sources.find((source) => source.fingerprint.provider === "claude"); + yield* Effect.gen(function* () { + // With nothing persisted, the first answer is a full scan. + const service = yield* UsageService.make; + const loop = NodePath.join(NodePath.dirname(transcript), "loop.jsonl"); + yield* Effect.promise(() => NodeFSP.symlink(loop, loop, "junction")); + assert.strictEqual(claude(yield* service.readSummary(provisional))?.status, "partial"); + yield* Effect.promise(() => NodeFSP.rm(loop)); + // A scan that missed a path covers nothing, so this is a full scan too. + assert.isUndefined(claude(yield* service.readSummary(provisional))?.refreshing); + yield* service.awaitPersisted; + + yield* Effect.promise(() => NodeFSP.appendFile(transcript, claudeLine(2, 7))); + const restarted = yield* UsageService.make; + const saved = yield* restarted.readSummary(provisional); + assert.strictEqual(totalOutputTokens(saved), 5); + assert.isTrue(claude(saved)?.refreshing); + // A window that starts before the saved scan could only show part of its usage. + const wider = yield* restarted.readSummary({ + ...provisional, + sinceDay: UsageDay.make("2026-07-01"), + }); + assert.strictEqual(totalOutputTokens(wider), 12); + assert.isUndefined(claude(wider)?.refreshing); + const refreshed = yield* restarted.readSummary({ ...WINDOW, awaitRefresh: true }); + assert.strictEqual(totalOutputTokens(refreshed), 12); + assert.isUndefined(claude(refreshed)?.refreshing); + // Saved usage with nothing to show marks nothing refreshing, so it must not be the answer. + yield* Effect.promise(() => + NodeFSP.appendFile(transcript, claudeLine(3, 11, "claude-other")), + ); + const unseen = yield* restarted.readSummary({ + ...provisional, + modelFilter: { include: [{ model: "claude-other" }] }, + }); + assert.strictEqual(totalOutputTokens(unseen), 11); + yield* restarted.awaitPersisted; + + // A saved scan with an entry this server cannot read covers nothing. + const { stateDir } = yield* ServerConfig.ServerConfig; + const cachePath = NodePath.join(stateDir, SCAN_CACHE_FILE_NAME); + yield* Effect.promise(async () => { + const document = decodeUnknownJsonString(await NodeFSP.readFile(cachePath, "utf8")) as { + files: Record>; + }; + const [entry] = Object.values(document.files); + document.files[NodePath.join(NodePath.dirname(transcript), "broken.jsonl")] = { + ...entry, + r: "broken", + }; + await NodeFSP.writeFile(cachePath, JSON.stringify(document)); + }); + const reloaded = yield* UsageService.make; + assert.isUndefined(claude(yield* reloaded.readSummary(provisional))?.refreshing); + }).pipe( + Effect.scoped, + Effect.provide(layerService({ prefix: "usage-service-provisional", home, settings })), + ); + }).pipe(Effect.scoped), + ); + it.live("filters original model IDs before aliases, pricing, buckets and session counts", () => Effect.gen(function* () { const { transcript, settings, home } = yield* setup; @@ -2789,7 +2905,7 @@ describe("UsageService", () => { }).pipe(Effect.scoped), ); - it.live.each([4, 5, 6, 7, 8, 10])( + it.live.each([4, 5, 6, 7, 8, 10, 11, 12, 13])( "upgrades a v%s cache: reparses live Codex usage, keeps deleted rollouts, removes the old file", (version) => Effect.gen(function* () { @@ -2890,7 +3006,7 @@ describe("UsageService", () => { 60 + 20 * (version === 4 ? 1 : 2), ); yield* upgraded.awaitPersisted; - assert.strictEqual(SCAN_CACHE_FILE_NAME, "usage-scan-cache-v12.json"); + assert.strictEqual(SCAN_CACHE_FILE_NAME, "usage-scan-cache-v14.json"); assert.deepStrictEqual( (yield* Effect.promise(() => NodeFSP.readdir(stateDir))) .filter((name) => name.startsWith("usage-scan-cache")) @@ -3158,6 +3274,64 @@ describe("UsageService", () => { }).pipe(Effect.scoped), ); + it.live("credits the same copy of a duplicate from the last scan as an exact read does", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse("2026-08-15T00:00:00Z")); + const { transcript, settings, home } = yield* setup; + const dir = NodePath.dirname(transcript); + const [first = "", second = ""] = yield* Effect.promise(async () => { + await NodeFSP.writeFile(NodePath.join(dir, "a.jsonl"), ""); + await NodeFSP.writeFile(NodePath.join(dir, "b.jsonl"), ""); + return (await NodeFSP.readdir(dir)).map((name) => NodePath.join(dir, name)); + }); + const forked = (line: string) => line.replace('"session-1"', '"session-2"'); + yield* Effect.promise(async () => { + await NodeFSP.writeFile(first, claudeLine(1, 5)); + await NodeFSP.utimes(first, BEFORE_NARROW_WINDOW, BEFORE_NARROW_WINDOW); + await NodeFSP.writeFile(second, forked(claudeLine(1, 5)) + forked(claudeLine(2, 7))); + }); + yield* Effect.gen(function* () { + const service = yield* UsageService.make; + // The narrow window saves the second copy before the wide one reads the first. + yield* service.readSummary(NARROW_WINDOW); + const exact = yield* service.readSummary(WINDOW); + yield* service.awaitPersisted; + const restarted = yield* UsageService.make; + const saved = yield* restarted.readSummary({ ...WINDOW, provisional: true }); + assert.isTrue(saved.sources.some((source) => source.refreshing === true)); + assert.deepStrictEqual(saved.buckets, exact.buckets); + }).pipe( + Effect.provide(layerService({ prefix: "usage-service-saved-order-test", home, settings })), + ); + + // A narrow scan that first saves the earlier copy still puts it before a later file it skipped. + yield* Effect.promise(async () => { + await NodeFSP.writeFile(first, forked(claudeLine(1, 5)) + forked(claudeLine(2, 7))); + await NodeFSP.utimes( + first, + Date.parse("2026-07-01T00:00:00Z") / 1000, + Date.parse("2026-07-01T00:00:00Z") / 1000, + ); + await NodeFSP.writeFile(second, claudeLine(1, 5)); + await NodeFSP.utimes(second, BEFORE_NARROW_WINDOW, BEFORE_NARROW_WINDOW); + }); + yield* Effect.gen(function* () { + const service = yield* UsageService.make; + yield* service.readSummary(WINDOW); + yield* Effect.promise(() => + NodeFSP.utimes(first, NARROW_WINDOW_MTIME, NARROW_WINDOW_MTIME), + ); + yield* service.readSummary(NARROW_WINDOW); + const saved = yield* service.readSummary({ ...WINDOW, provisional: true }); + assert.isTrue(saved.sources.some((source) => source.refreshing === true)); + const exact = yield* service.readSummary(WINDOW); + assert.deepStrictEqual(saved.buckets, exact.buckets); + }).pipe( + Effect.provide(layerService({ prefix: "usage-service-narrow-order-test", home, settings })), + ); + }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), + ); + it.live.skipIf(HostProcess.Platform.defaultValue() === "win32")( "keeps a newer cached read when a slower scan of another window finishes later", () => @@ -3299,7 +3473,14 @@ describe("UsageService", () => { HttpClient.HttpClient, HttpClient.make((request) => Deferred.await(releaseRates).pipe( - Effect.as(HttpClientResponse.fromWeb(request, Response.json({}))), + Effect.as( + HttpClientResponse.fromWeb( + request, + Response.json({ + "example-model": { input_cost_per_token: 1e-6, output_cost_per_token: 1e-5 }, + }), + ), + ), ), ), ), @@ -3318,7 +3499,8 @@ describe("UsageService", () => { const original = yield* Fiber.join(first); const updated = yield* Fiber.join(second); - assert.strictEqual(original.buckets[0]?.costUsd, 0); + // Fetched rates price the first read, so scans must start while the fetch is pending. + assert.isAbove(original.buckets[0]?.costUsd ?? 0, 0); assert.closeTo(updated.buckets[0]?.costUsd ?? -1, 0.00006, 1e-12); }).pipe( Effect.provide(layerService({ prefix: "usage-service-price-race-test", home, settings })), diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts index 341b14d8c6280..cd04e4bc4c1c9 100644 --- a/apps/server/src/usage/UsageService.ts +++ b/apps/server/src/usage/UsageService.ts @@ -137,7 +137,10 @@ function sharedSessions( return shared; } const decodeCachedSources = Schema.decodeUnknownOption( - Schema.Struct({ sources: Schema.Record(Schema.String, CachedSource) }), + Schema.Struct({ + sources: Schema.Record(Schema.String, CachedSource), + coveredSince: Schema.optional(Schema.Record(Schema.String, Schema.Number)), + }), ); export class UsageService extends Context.Service< @@ -165,7 +168,15 @@ export const make = Effect.gen(function* () { const correctedBatch = (records: readonly UsageRecord[]) => records.some((record) => resolvedRecords.has(record)) ? records.map(correctedRecord) : records; const sourceCache = new Map(); + // Earliest window start a complete scan read each transcript directory from. + const coveredSince = new Map(); + const coverageKey = (source: TranscriptSource) => `${source.provider}\0${source.dir}`; let cacheDirty = false; + const cover = (source: TranscriptSource, windowStartMs: number) => { + if ((coveredSince.get(coverageKey(source)) ?? Infinity) <= windowStartMs) return; + coveredSince.set(coverageKey(source), windowStartMs); + cacheDirty = true; + }; const isWithinDirectory = (filePath: string, dir: string) => { const relative = path.relative(dir, filePath); return relative !== ".." && !relative.startsWith(".." + path.sep) && !path.isAbsolute(relative); @@ -235,27 +246,26 @@ export const make = Effect.gen(function* () { Effect.catchCause(() => Effect.succeed(null)), ); + // Outside ratesLock, which a slow fetch holds: a provisional answer prices with these. + const loadSavedRates = yield* Effect.cached( + fileSystem.readFileString(ratesCachePath).pipe( + Effect.flatMap((raw) => decodeRatesCache(raw)), + Effect.map((saved) => { + const parsed = parseRateTable(saved.document); + if (parsed.size === 0) return; + rates = parsed; + ratesFetchedAtMs = saved.fetchedAtMs; + ratesStatus = "cached"; + }), + Effect.ignoreCause, + ), + ); + const loadRates = Effect.fn("UsageService.loadRates")(function* (force: boolean) { const now = yield* Clock.currentTimeMillis; const maxAgeMs = force ? RATES_REFRESH_FLOOR_MS : RATES_TTL_MS; + yield* loadSavedRates; if (ratesFetchedAtMs !== null && now - ratesFetchedAtMs < maxAgeMs) return; - - if (ratesFetchedAtMs === null) { - const fromDisk = yield* fileSystem.readFileString(ratesCachePath).pipe( - Effect.flatMap((raw) => decodeRatesCache(raw)), - Effect.catchCause(() => Effect.succeed(null)), - ); - if (fromDisk !== null) { - const parsed = parseRateTable(fromDisk.document); - if (parsed.size > 0) { - rates = parsed; - ratesFetchedAtMs = fromDisk.fetchedAtMs; - ratesStatus = "cached"; - if (now - fromDisk.fetchedAtMs < maxAgeMs) return; - } - } - } - if (ratesLastFailedAtMs !== null && now - ratesLastFailedAtMs < RATES_REFRESH_FLOOR_MS) return; let fetched = yield* fetchRates(LITELLM_RATES_URL); @@ -396,19 +406,27 @@ export const make = Effect.gen(function* () { Effect.catchCause(() => Effect.succeed(null)), ); let document = yield* readDocument(scanCachePath); + const current = document !== null; for (const fileName of LEGACY_SCAN_CACHE_FILE_NAMES) { if (document !== null) break; document = yield* readDocument(path.join(config.stateDir, fileName)); cacheDirty = document !== null; } if (document === null) return; - for (const [path, entry] of decodeScanCache(document, transcriptFormats)) { - fileCache.set(path, entry); - } + const decoded = decodeScanCache(document, transcriptFormats); + for (const [path, entry] of decoded) fileCache.set(path, entry); + const saved = (document as { readonly files?: unknown }).files; + const complete = + typeof saved === "object" && saved !== null && Object.keys(saved).length === decoded.size; const sources = decodeCachedSources(document); if (Option.isSome(sources)) { for (const [key, source] of Object.entries(sources.value.sources)) sourceCache.set(key, source); + // Coverage describes the saved files, so it needs every one, in this version's format. + if (current && complete && fileCache.size > 0) { + for (const [key, since] of Object.entries(sources.value.coveredSince ?? {})) + coveredSince.set(key, since); + } } }), ); @@ -448,7 +466,10 @@ export const make = Effect.gen(function* () { if (cacheDirty) { cacheDirty = false; yield* Effect.sync(() => - writeScanCache(fileCache, { sources: Object.fromEntries(sourceCache) }), + writeScanCache(fileCache, { + sources: Object.fromEntries(sourceCache), + coveredSince: Object.fromEntries(coveredSince), + }), ).pipe( Effect.flatMap((contents) => writeCacheFile(scanCachePath, contents)), Effect.andThen( @@ -595,19 +616,27 @@ export const make = Effect.gen(function* () { readonly malformedRecords: number; }[] | null; + /** Every transcript path the walk listed, in walk order, whatever its mtime. */ + readonly walked?: readonly string[]; readonly refreshing?: true; } const scanTranscriptDir = Effect.fn("UsageService.scanTranscriptDir")(function* ( source: TranscriptSource, windowStartMs: number, + fromMemory: boolean, ) { const { provider, format, dir, volumeId, fileName } = source; const exists = yield* fileSystem .exists(dir) .pipe(Effect.catchCause(() => Effect.succeed(false))); - if (!exists) return { provider, dir, volumeId, files: null } satisfies ScannedDir; - const { files, failedPaths } = yield* Effect.promise(() => + if (!exists) { + cover(source, windowStartMs); + return { provider, dir, volumeId, files: null } satisfies ScannedDir; + } + // scanSummary aggregates the saved files, as it does for a deleted directory. + if (fromMemory) return { provider, dir, volumeId, files: [] } satisfies ScannedDir; + const { files, walked, failedPaths } = yield* Effect.promise(() => listTranscriptFiles(dir, windowStartMs, fileName === undefined ? undefined : { fileName }), ); const read = yield* Effect.forEach( @@ -638,7 +667,15 @@ export const make = Effect.gen(function* () { } return { path, records, malformedRecords }; }); + const livePaths = new Set(files.map((file) => file.path)); + for (const file of read) { + if (file.failed || !file.path.endsWith(".jsonl.zst")) continue; + const originalPath = file.path.slice(0, -4); + // A successfully read archive replaces the original's saved records and diagnostics. + if (!livePaths.has(originalPath) && fileCache.delete(originalPath)) cacheDirty = true; + } const unread = failedPaths + read.filter((file) => file.failed).length; + if (unread === 0) cover(source, windowStartMs); yield* Effect.annotateCurrentSpan({ "usage.files": files.length, "usage.files_parsed": read.filter((file) => file.update !== undefined).length, @@ -648,6 +685,7 @@ export const make = Effect.gen(function* () { dir, volumeId, files: parsedFiles, + walked, ...(unread > 0 ? { status: "partial", @@ -658,17 +696,13 @@ export const make = Effect.gen(function* () { }); const collectDirs = Effect.fn("UsageService.collectDirs")(function* ( + { dirs, pending }: Effect.Success>, windowStartMs: number, settings: ServerSettingsValue, retentionCutoffMs: number, awaitRefresh: boolean, + fromMemory: boolean, ) { - const { dirs, pending } = yield* resolveTranscriptDirs( - settings, - retentionCutoffMs, - awaitRefresh, - ).pipe(Effect.provideContext(readerContext)); - const scans = Effect.forEach( scanReaders, ({ driver, reader }) => @@ -698,7 +732,7 @@ export const make = Effect.gen(function* () { // Scan independent sources together, directories sequentially to bound open files; keep order, since the first copy decides a duplicate's bucket. const [transcripts, scanDirs] = yield* Effect.all( - [Effect.forEach(dirs, (dir) => scanTranscriptDir(dir, windowStartMs)), scans], + [Effect.forEach(dirs, (dir) => scanTranscriptDir(dir, windowStartMs, fromMemory)), scans], { concurrency: "unbounded" }, ); const scanned: readonly ScannedDir[] = [...transcripts, ...pending, ...scanDirs.flat()]; @@ -708,6 +742,7 @@ export const make = Effect.gen(function* () { const scanSummary = Effect.fn("UsageService.scanSummary")(function* ( input: UsageSummaryInput, settings: ServerSettingsValue, + provisional: boolean, ) { if (input.sinceDay > input.untilDay) { return yield* new UsageReadError({ @@ -755,11 +790,38 @@ export const make = Effect.gen(function* () { const retentionCutoffMs = startedAtMs - CACHE_RETENTION_DAYS * 24 * 60 * 60 * 1000; - const [, scannedDirs] = yield* Effect.all( - [ - ensureRates(false), - collectDirs(windowStartMs, settings, retentionCutoffMs, input.awaitRefresh === true), - ], + const awaitRefresh = input.awaitRefresh === true; + const collect = Effect.gen(function* () { + const resolved = yield* resolveTranscriptDirs(settings, retentionCutoffMs, awaitRefresh).pipe( + Effect.provideContext(readerContext), + ); + // A window no complete scan has read would show partial totals, so every directory must cover it. + // Saved files are keyed by path, so two providers reading one directory keep only one parse. + const fromMemory = + provisional && + resolved.dirs.length > 0 && + new Set(resolved.dirs.map((source) => source.dir)).size === resolved.dirs.length && + resolved.dirs.every( + (source) => (coveredSince.get(coverageKey(source)) ?? Infinity) <= windowStartMs, + ); + const [, scanned] = yield* Effect.all( + [ + fromMemory ? loadSavedRates : provisional ? ensureRates(false) : Effect.void, + collectDirs( + resolved, + windowStartMs, + settings, + retentionCutoffMs, + awaitRefresh, + fromMemory, + ), + ], + { concurrency: 2 }, + ); + return { scannedDirs: scanned, fromMemory }; + }); + const [{ scannedDirs, fromMemory }] = yield* Effect.all( + [collect, provisional ? Effect.void : ensureRates(false)], { concurrency: 2 }, ); @@ -779,31 +841,73 @@ export const make = Effect.gen(function* () { // Deleted transcripts' saved usage still aggregates and deduplicates normally. const retainedSinceMs = Math.max(windowStartMs, retentionCutoffMs); + // Saved paths are files below a scanned root, so their folder decides; folders repeat thousands of times. + const withinDir = (dir: string) => { + const foldersWithin = new Map(); + return (filePath: string) => { + const folder = path.dirname(filePath); + let within = foldersWithin.get(folder); + if (within === undefined) { + within = isWithinDirectory(folder, dir); + foldersWithin.set(folder, within); + } + return within; + }; + }; const filesByDir = scannedDirs.map(({ provider, dir, files }) => { const retainedFiles = [...(files ?? [])]; const livePaths = new Set(retainedFiles.map((file) => file.path)); + const isRetained = withinDir(dir); for (const [filePath, entry] of fileCache) { if ( entry.provider !== provider || entry.mtimeMs < retainedSinceMs || livePaths.has(filePath) || - !isWithinDirectory(filePath, dir) + !isRetained(filePath) ) continue; retainedFiles.push({ path: filePath, - records: [...entry.records, ...entry.tailRecords], + records: + entry.tailRecords.length === 0 + ? entry.records + : [...entry.records, ...entry.tailRecords], malformedRecords: entry.malformedRecords, }); } return retainedFiles; }); + // Usage two transcripts share counts in the first one, so saved files take the order an exact + // scan reads them in: walked files in walk order, then the directory's deleted files. + for (const { provider, dir, walked } of fromMemory ? [] : scannedDirs) { + if (walked === undefined) continue; + const within = withinDir(dir); + const saved = [...fileCache.keys()]; + const members = new Set( + saved.filter( + (filePath) => fileCache.get(filePath)!.provider === provider && within(filePath), + ), + ); + if (members.size < 2) continue; + const listed = new Set(walked); + const target = [ + ...walked.filter((filePath) => members.has(filePath)), + ...saved.filter((filePath) => members.has(filePath) && !listed.has(filePath)), + ]; + let next = 0; + const ordered = saved.map((filePath) => (members.has(filePath) ? target[next++]! : filePath)); + if (ordered.every((filePath, index) => filePath === saved[index])) continue; + const entries = new Map(fileCache); + fileCache.clear(); + for (const filePath of ordered) fileCache.set(filePath, entries.get(filePath)!); + cacheDirty = true; + } const windowEndMs = hourlyWindow?.untilTimeMs ?? Date.parse(`${input.untilDay}T00:00:00Z`) + 86400000 + MTIME_SLACK_MS; let resolvedAny = false; for (const { reader } of transcriptReaders) { - if (reader.resolveServiceTiers === undefined) continue; + if (reader.resolveServiceTiers === undefined || fromMemory) continue; const pending = new Set(); for (const [index, files] of filesByDir.entries()) { if (scannedDirs[index]?.provider !== reader.provider) continue; @@ -853,6 +957,7 @@ export const make = Effect.gen(function* () { // Distinct per directory. Buckets carry per-cell session counts, but a // session spans days and models, so clients total this figure instead. const sessionIds = new Set(); + let counted = false; for (const file of filesByDir[index] ?? []) { malformedRecords += file.malformedRecords; @@ -881,8 +986,9 @@ export const make = Effect.gen(function* () { eventOccurrences.set(key, occurrence); usageRecord = { ...record, dedupeKey: key + ":" + occurrence }; } - if (aggregator.add(usageRecord, dir) && record.sessionId.length > 0) { - sessionIds.add(record.sessionId); + if (aggregator.add(usageRecord, dir)) { + counted = true; + if (record.sessionId.length > 0) sessionIds.add(record.sessionId); } } } @@ -909,18 +1015,28 @@ export const make = Effect.gen(function* () { .filter(Boolean) .join(" ") : sourceMessage, - ...(refreshing ? { refreshing } : {}), + // A saved answer misses what changed since its scan, so the client must ask again. An + // empty source stays unmarked: it would only flash a loading row. + ...(refreshing || (fromMemory && counted && transcriptFormats.has(provider)) + ? { refreshing: true } + : {}), }); } const pruned = pruneScanCache(fileCache, retentionCutoffMs); - if (pruned > 0) cacheDirty = true; + if (pruned > 0) { + cacheDirty = true; + // Pruned files are no longer saved, so nothing before the cutoff stays covered. + for (const [key, since] of coveredSince) { + if (since < retentionCutoffMs) coveredSince.set(key, retentionCutoffMs); + } + } const aggregated = aggregator.finish(); const readAt = yield* DateTime.now; const finishedAtMs = yield* Clock.currentTimeMillis; - return { + const summary = { contractVersion: USAGE_CONTRACT_VERSION, readAt: DateTime.formatIso(readAt), timeZone: input.timeZone, @@ -932,11 +1048,28 @@ export const make = Effect.gen(function* () { scanDurationMs: Math.max(0, finishedAtMs - startedAtMs), ...(input.modelFilter === undefined ? {} : { modelFilter: input.modelFilter }), } satisfies UsageSummary; + return { summary, fromMemory }; + }); + + const readWindow = Effect.fn("UsageService.readWindow")(function* ( + input: UsageSummaryInput, + settings: ServerSettingsValue, + provisional: boolean, + ) { + const { summary, fromMemory } = yield* scanSummary(input, settings, provisional); + // With nothing marked refreshing the client would keep a saved answer as final. + return fromMemory && !summary.sources.some((source) => source.refreshing === true) + ? (yield* scanSummary(input, settings, false)).summary + : summary; }); const inflightScans = new Map>(); - const scanKey = (input: UsageSummaryInput, settings: ServerSettingsValue): string => + const scanKey = ( + input: UsageSummaryInput, + settings: ServerSettingsValue, + provisional: boolean, + ): string => JSON.stringify([ input.timeZone, input.sinceDay, @@ -946,6 +1079,7 @@ export const make = Effect.gen(function* () { input.untilTime ?? null, settings, input.awaitRefresh === true, + provisional, input.modelFilter ?? null, ]); @@ -956,7 +1090,8 @@ export const make = Effect.gen(function* () { const modelFilter = canonicalModelFilter(requestedFilter); const input = modelFilter === undefined ? unfiltered : { ...unfiltered, modelFilter }; const settings = yield* readSettings; - const key = scanKey(input, settings); + const provisional = input.provisional === true && input.awaitRefresh !== true; + const key = scanKey(input, settings, provisional); const deferred = yield* Effect.uninterruptible( Effect.gen(function* () { const existing = inflightScans.get(key); @@ -967,7 +1102,7 @@ export const make = Effect.gen(function* () { inflightScans.set(key, created); // Detach so caller departure cannot cancel shared scans; finished scans warm the cache. // Register writes before releasing waiters, but start writing after delivering their summary. - yield* scanSummary(input, settings).pipe( + yield* readWindow(input, settings, provisional).pipe( Effect.onExit((exit) => Effect.sync(() => inflightScans.delete(key)).pipe( Effect.andThen(Exit.isSuccess(exit) ? schedulePersist : Effect.void), diff --git a/apps/server/src/usage/usageAggregation.test.ts b/apps/server/src/usage/usageAggregation.test.ts index 625f7a9d63eca..f99615085bd2a 100644 --- a/apps/server/src/usage/usageAggregation.test.ts +++ b/apps/server/src/usage/usageAggregation.test.ts @@ -12,11 +12,13 @@ const rates: RateTable = new Map([ outputCostPerToken: 5e-5, cacheReadCostPerToken: 1e-6, cacheCreationCostPerToken: 1.25e-5, + cacheCreation1hCostPerToken: 2e-5, fast: { inputCostPerToken: 2e-5, outputCostPerToken: 1e-4, cacheReadCostPerToken: 2e-6, cacheCreationCostPerToken: 2.5e-5, + cacheCreation1hCostPerToken: 4e-5, }, ultrafast: null, contextTiers: [], diff --git a/apps/server/src/usage/usageAggregation.ts b/apps/server/src/usage/usageAggregation.ts index 8d1d799859737..9ff9cb9369462 100644 --- a/apps/server/src/usage/usageAggregation.ts +++ b/apps/server/src/usage/usageAggregation.ts @@ -147,12 +147,18 @@ export function mergeUsageCopies(held: UsageRecord, copy: UsageRecord): UsageRec b.cacheCreationTokens <= a.cacheCreationTokens && b.outputTokens <= a.outputTokens && b.reasoningTokens <= a.reasoningTokens && + (copy.cacheCreation1hTokens ?? 0) <= (held.cacheCreation1hTokens ?? 0) && reportedCostUsd === held.reportedCostUsd ) { return held; } + const cacheCreation1hTokens = Math.max( + held.cacheCreation1hTokens ?? 0, + copy.cacheCreation1hTokens ?? 0, + ); return { ...held, + ...(cacheCreation1hTokens > 0 ? { cacheCreation1hTokens } : {}), totals: { uncachedInputTokens: Math.max(a.uncachedInputTokens, b.uncachedInputTokens), cachedInputTokens: Math.max(a.cachedInputTokens, b.cachedInputTokens), diff --git a/apps/server/src/usage/usagePricing.ts b/apps/server/src/usage/usagePricing.ts index 4a04116db2df9..21a1bd02bb178 100644 --- a/apps/server/src/usage/usagePricing.ts +++ b/apps/server/src/usage/usagePricing.ts @@ -12,6 +12,8 @@ export interface TokenRates { readonly outputCostPerToken: number; readonly cacheReadCostPerToken: number; readonly cacheCreationCostPerToken: number; + /** Cache writes with a 1-hour TTL; the 5-minute rate when unpublished. */ + readonly cacheCreation1hCostPerToken: number; } interface SpeedRates extends TokenRates { @@ -37,20 +39,24 @@ export function createOverrideRateTable( overrides: Readonly>, ): RateTable { return new Map( - Object.entries(overrides).map(([model, prices]) => [ - model.trim(), - { - inputCostPerToken: prices.inputCostPerMillionTokens / 1_000_000, - outputCostPerToken: prices.outputCostPerMillionTokens / 1_000_000, - cacheReadCostPerToken: - (prices.cacheReadCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000, - cacheCreationCostPerToken: - (prices.cacheWriteCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000, - fast: null, - ultrafast: null, - contextTiers: [], - }, - ]), + Object.entries(overrides).map(([model, prices]) => { + const cacheCreationCostPerToken = + (prices.cacheWriteCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000; + return [ + model.trim(), + { + inputCostPerToken: prices.inputCostPerMillionTokens / 1_000_000, + outputCostPerToken: prices.outputCostPerMillionTokens / 1_000_000, + cacheReadCostPerToken: + (prices.cacheReadCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000, + cacheCreationCostPerToken, + cacheCreation1hCostPerToken: cacheCreationCostPerToken, + fast: null, + ultrafast: null, + contextTiers: [], + }, + ]; + }), ); } @@ -60,7 +66,7 @@ function finiteNumber(value: unknown): number | null { return typeof value === "number" && Number.isFinite(value) ? value : null; } -// Missing cache rates fall back to input pricing; Anthropic normally discounts reads and charges extra for writes. +// Missing cache rates fall back to input pricing, and a missing 1-hour write rate to the 5-minute one. function readTokenRates( entry: LiteLlmEntry, suffix: string, @@ -70,18 +76,28 @@ function readTokenRates( const input = finiteNumber(entry[`input_cost_per_token${suffix}`]); const output = finiteNumber(entry[`output_cost_per_token${suffix}`]) ?? outputFallback ?? null; if (input === null || output === null) return null; - const cacheRate = (name: string, field: "cacheReadCostPerToken" | "cacheCreationCostPerToken") => + const cacheRate = ( + name: string, + field: "cacheReadCostPerToken" | "cacheCreationCostPerToken" | "cacheCreation1hCostPerToken", + fallback = input, + ) => finiteNumber(entry[`${name}${suffix}`]) ?? (standard !== undefined && standard.inputCostPerToken > 0 ? (standard[field] / standard.inputCostPerToken) * input - : input); + : fallback); + const cacheCreationCostPerToken = cacheRate( + "cache_creation_input_token_cost", + "cacheCreationCostPerToken", + ); return { inputCostPerToken: input, outputCostPerToken: output, cacheReadCostPerToken: cacheRate("cache_read_input_token_cost", "cacheReadCostPerToken"), - cacheCreationCostPerToken: cacheRate( - "cache_creation_input_token_cost", - "cacheCreationCostPerToken", + cacheCreationCostPerToken, + cacheCreation1hCostPerToken: cacheRate( + "cache_creation_input_token_cost_above_1hr", + "cacheCreation1hCostPerToken", + cacheCreationCostPerToken, ), }; } @@ -92,6 +108,7 @@ function scaleTokenRates(rates: TokenRates, multiple: number): TokenRates { outputCostPerToken: rates.outputCostPerToken * multiple, cacheReadCostPerToken: rates.cacheReadCostPerToken * multiple, cacheCreationCostPerToken: rates.cacheCreationCostPerToken * multiple, + cacheCreation1hCostPerToken: rates.cacheCreation1hCostPerToken * multiple, }; } @@ -192,7 +209,8 @@ function sameTokenRates(a: TokenRates | null, b: TokenRates | null): boolean { a.inputCostPerToken === b.inputCostPerToken && a.outputCostPerToken === b.outputCostPerToken && a.cacheReadCostPerToken === b.cacheReadCostPerToken && - a.cacheCreationCostPerToken === b.cacheCreationCostPerToken + a.cacheCreationCostPerToken === b.cacheCreationCostPerToken && + a.cacheCreation1hCostPerToken === b.cacheCreation1hCostPerToken ); } @@ -301,7 +319,7 @@ function resolveRate(table: RateTable, model: string): ModelRate | null { export type PricedRecord = Pick< UsageRecord, - "model" | "rateModel" | "totals" | "speed" | "reportedCostUsd" + "model" | "rateModel" | "totals" | "cacheCreation1hTokens" | "speed" | "reportedCostUsd" >; function recordRate(table: RateTable, record: PricedRecord): ModelRate | null { @@ -316,11 +334,15 @@ export interface PricedUsage { readonly speedPremiumUsd: number; } -function costByCategory(totals: UsageTokenTotals, rates: TokenRates): UsageCategoryCost { +function costByCategory(record: PricedRecord, rates: TokenRates): UsageCategoryCost { + const { totals } = record; + const oneHour = Math.min(record.cacheCreation1hTokens ?? 0, totals.cacheCreationTokens); return { input: totals.uncachedInputTokens * rates.inputCostPerToken, cacheRead: totals.cachedInputTokens * rates.cacheReadCostPerToken, - cacheWrite: totals.cacheCreationTokens * rates.cacheCreationCostPerToken, + cacheWrite: + (totals.cacheCreationTokens - oneHour) * rates.cacheCreationCostPerToken + + oneHour * rates.cacheCreation1hCostPerToken, output: totals.outputTokens * rates.outputCostPerToken, }; } @@ -352,13 +374,13 @@ export function priceUsage( return reported === null ? unsplit(0, "unpriced") : unsplit(reported, "providerReported"); } - const listCost = costByCategory(totals, ratesAt(rate, record.speed, totals)); + const listCost = costByCategory(record, ratesAt(rate, record.speed, totals)); const listCostUsd = sumCategories(listCost); if (reported !== null && listCostUsd <= 0) return unsplit(reported, "providerReported"); const premiumUsd = record.speed === "standard" ? 0 - : listCostUsd - sumCategories(costByCategory(totals, ratesAt(rate, "standard", totals))); + : listCostUsd - sumCategories(costByCategory(record, ratesAt(rate, "standard", totals))); const scale = reported === null ? 1 : reported / listCostUsd; return { costUsd: reported ?? listCostUsd, diff --git a/apps/server/src/usage/usageScanCache.test.ts b/apps/server/src/usage/usageScanCache.test.ts index 2866a295da8fe..a6a0f6d3c41df 100644 --- a/apps/server/src/usage/usageScanCache.test.ts +++ b/apps/server/src/usage/usageScanCache.test.ts @@ -65,7 +65,15 @@ describe("scan cache round trip", () => { [ "/a.jsonl", 100, - [record(), record({ dedupeKey: "msg_2:", model: "claude-opus-5-5", speed: "fast" })], + [ + record(), + record({ + dedupeKey: "msg_2:", + model: "claude-opus-5-5", + speed: "fast", + cacheCreation1hTokens: 8, + }), + ], ], [ "/b.jsonl", @@ -160,7 +168,7 @@ describe("scan cache round trip", () => { expect(restored).toEqual(original); }); - it.each([5, 6, 7, 8, 10])( + it.each([5, 6, 7, 8, 10, 11, 12, 13])( "retains v%s history and compatible positions but invalidates obsolete state", (version) => { const original = cacheWith([["/gone.jsonl", 100, [record({ speed: "fast" })]]]); @@ -217,11 +225,15 @@ describe("scan cache round trip", () => { }; const restored = decodeScanCache(JSON.parse(JSON.stringify(legacy)), TEST_FORMAT_MAP); - expect(restored.get("/gone.jsonl")).toEqual({ - ...original.get("/gone.jsonl"), - size: -1, - position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, - }); + expect(restored.get("/gone.jsonl")).toEqual( + version >= 13 + ? original.get("/gone.jsonl") + : { + ...original.get("/gone.jsonl"), + size: -1, + position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, + }, + ); expect(restored.get("/gone-codex.jsonl")).toEqual({ ...original.get("/gone-codex.jsonl"), size: -1, @@ -229,7 +241,7 @@ describe("scan cache round trip", () => { }); expect(restored.get("/clean-codex.jsonl")).toEqual({ ...cleanCodex, - size: version >= 8 ? cleanCodex.size : -1, + size: -1, position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, }); expect(restored.get("/gone-pi.jsonl")).toEqual( @@ -244,11 +256,11 @@ describe("scan cache round trip", () => { }, ); - it("re-parses a Claude transcript cached before partial copies were merged", () => { + it("re-parses a Claude transcript cached before 1-hour cache writes were counted", () => { const original = cacheWith([["/claude.jsonl", 100, [record()]]]); - const v11 = { ...parse(makeScanCacheWriter()(original, {})), version: 11 }; + const v12 = { ...parse(makeScanCacheWriter()(original, {})), version: 12 }; - const restored = decodeScanCache(JSON.parse(JSON.stringify(v11)), TEST_FORMAT_MAP); + const restored = decodeScanCache(JSON.parse(JSON.stringify(v12)), TEST_FORMAT_MAP); expect(restored.get("/claude.jsonl")).toEqual({ ...original.get("/claude.jsonl"), size: -1, diff --git a/apps/server/src/usage/usageScanCache.ts b/apps/server/src/usage/usageScanCache.ts index 4cd959c75aa25..604937a6a5e41 100644 --- a/apps/server/src/usage/usageScanCache.ts +++ b/apps/server/src/usage/usageScanCache.ts @@ -10,7 +10,7 @@ import { CLAUDE_SYNTHETIC_MODEL } from "../provider/Drivers/claudeUsage.ts"; import { mergeUsageCopies } from "./usageAggregation.ts"; import { GUARD_LENGTH, type TranscriptParsePosition } from "./usageTranscriptReader.ts"; -const USAGE_SCAN_CACHE_VERSION = 12 as const; +const USAGE_SCAN_CACHE_VERSION = 14 as const; const SPEED_COMPATIBLE_SINCE_VERSION = 4; /** @@ -18,8 +18,10 @@ const SPEED_COMPATIBLE_SINCE_VERSION = 4; * replace it, dropping saved usage for deleted transcripts. Separate files keep * the newer one; older files are removed once it is saved. */ -export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v12.json"; +export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v14.json"; export const LEGACY_SCAN_CACHE_FILE_NAMES = [ + "usage-scan-cache-v13.json", + "usage-scan-cache-v12.json", "usage-scan-cache-v11.json", "usage-scan-cache-v10.json", "usage-scan-cache-v9.json", @@ -59,7 +61,8 @@ type SerializedRecord = readonly [ reportedCostUsd: number | null, speed: number, rateModelIndex?: number | null, - unresolvedServiceTierTurnId?: string, + unresolvedServiceTierTurnId?: string | null, + cacheCreation1hTokens?: number, ]; interface SerializedFile { @@ -118,9 +121,11 @@ function serializeFile(entry: CachedFile, tables: InternTables): SerializedFile record.rateModel === undefined ? null : intern(tables.models, tables.modelIndex, record.rateModel), - ...(record.unresolvedServiceTierTurnId === undefined - ? ([] as const) - : ([record.unresolvedServiceTierTurnId] as const)), + ...(record.cacheCreation1hTokens !== undefined + ? ([record.unresolvedServiceTierTurnId ?? null, record.cacheCreation1hTokens] as const) + : record.unresolvedServiceTierTurnId !== undefined + ? ([record.unresolvedServiceTierTurnId] as const) + : ([] as const)), ]; return { s: entry.size, @@ -211,6 +216,7 @@ export function decodeScanCache( speedIndex, rateModelIndex, unresolvedServiceTierTurnId, + cacheCreation1h = 0, ] = row as SerializedRecord; const speed = typeof speedIndex === "number" ? SPEEDS[speedIndex] : undefined; @@ -220,8 +226,8 @@ export function decodeScanCache( typeof timestampMs !== "number" || !Number.isFinite(timestampMs) || model === undefined || - (unresolvedServiceTierTurnId !== undefined && - typeof unresolvedServiceTierTurnId !== "string") || + (unresolvedServiceTierTurnId != null && typeof unresolvedServiceTierTurnId !== "string") || + !Number.isFinite(cacheCreation1h) || (rateModelIndex != null && rateModel === undefined) || !Number.isFinite(uncached) || !Number.isFinite(cached) || @@ -250,9 +256,10 @@ export function decodeScanCache( outputTokens: output, reasoningTokens: reasoning, }, + ...(cacheCreation1h > 0 ? { cacheCreation1hTokens: cacheCreation1h } : {}), reportedCostUsd: typeof reportedCostUsd === "number" ? reportedCostUsd : null, speed, - ...(version >= 7 && unresolvedServiceTierTurnId !== undefined + ...(version >= 7 && unresolvedServiceTierTurnId != null ? { unresolvedServiceTierTurnId } : {}), dedupeKey: typeof dedupeKey === "string" ? dedupeKey : null, @@ -290,13 +297,12 @@ export function decodeScanCache( continue; } // Keep history for deleted rollouts, but re-parse incompatible reducer state. - // v9 and v11 repair skipped Codex requests; clean v8+ entries stay served while unchanged. + // v14 uses Codex request ledgers, including compaction spending omitted by context snapshots. // v10 adds Claude advisor calls; before v12 a repeated Claude key kept its first, possibly partial, copy. + // v13 adds Claude 1-hour cache writes. const legacy = - (entry.p === "claude" && version < 12) || - (format.state !== undefined && - (version < 6 || - (entry.p === "codex" && (version < 8 || (version < 11 && malformedRecords > 0))))); + (entry.p === "claude" && version < 13) || + (format.state !== undefined && (version < 6 || (entry.p === "codex" && version < 14))); // A corrupt state disqualifies the entry: resuming with it would attach // appended usage to the wrong model or replay fork-copied history. if (!legacy && !isValidState.get(entry.p)?.(entry.cs)) continue; diff --git a/apps/server/src/usage/usageTranscriptReader.test.ts b/apps/server/src/usage/usageTranscriptReader.test.ts index 105884d81ccfb..f4cb72ec1e25c 100644 --- a/apps/server/src/usage/usageTranscriptReader.test.ts +++ b/apps/server/src/usage/usageTranscriptReader.test.ts @@ -99,6 +99,30 @@ describe("compressed transcripts", () => { assert.isAbove(listed.files.find((file) => file.path === compressed)?.size ?? 0, 0); }); + it("lists files in directory order when more directories wait than it reads at once", async () => { + for (let index = 0; index < 40; index += 1) { + const nested = NodePath.join(dir, `project-${index}`, "sessions"); + await NodeFSP.mkdir(nested, { recursive: true }); + await NodeFSP.writeFile(NodePath.join(nested, "a.jsonl"), ""); + await NodeFSP.writeFile(NodePath.join(nested, "..", "b.jsonl"), ""); + } + // Usage that two transcripts share counts in the first one listed, so the order is part of the result. + const inOrder = async (folder: string): Promise => { + const paths: string[] = []; + for (const entry of await NodeFSP.readdir(folder, { withFileTypes: true })) { + const child = NodePath.join(folder, entry.name); + if (entry.isDirectory()) paths.push(...(await inOrder(child))); + else paths.push(child); + } + return paths; + }; + const listed = await listTranscriptFiles(dir, 0); + assert.deepStrictEqual( + listed.files.map((file) => file.path), + await inOrder(dir), + ); + }); + it.each([ { parser: "native", streamingThresholdBytes: undefined }, { parser: "projected", streamingThresholdBytes: 1024 }, diff --git a/apps/server/src/usage/usageTranscriptReader.ts b/apps/server/src/usage/usageTranscriptReader.ts index 38b80d36c8665..d80c51964a20c 100644 --- a/apps/server/src/usage/usageTranscriptReader.ts +++ b/apps/server/src/usage/usageTranscriptReader.ts @@ -1,8 +1,10 @@ // @effect-diagnostics nodeBuiltinImport:off // Cold windows span ~1.4 GB/1,500 files; node:fs buffer streaming is ~10x cheaper than materializing files. +import * as NodeFS from "node:fs"; import * as NodeFSP from "node:fs/promises"; import * as NodePath from "node:path"; import * as NodeStringDecoder from "node:string_decoder"; +import * as NodeUtil from "node:util"; import * as NodeZlib from "node:zlib"; import type { @@ -43,6 +45,9 @@ export const GUARD_LENGTH = 64; const STREAMING_THRESHOLD_BYTES = 8 * 1024 * 1024; const NEWLINE = 0x0a; const STAT_CONCURRENCY = 32; +const WALK_CONCURRENCY = 16; +// Measured about 3x faster than the promise API's stat across 20,000 transcripts. +const statFile = NodeUtil.promisify(NodeFS.stat); const CARRIAGE_RETURN = 0x0d; function selectUsageFields(fields: SelectedFields) { @@ -71,38 +76,54 @@ export async function listTranscriptFiles( root: string, sinceMs: number, options?: { readonly fileName?: string }, -): Promise<{ readonly files: readonly TranscriptFile[]; readonly failedPaths: number }> { +): Promise<{ + readonly files: readonly TranscriptFile[]; + readonly walked: readonly string[]; + readonly failedPaths: number; +}> { const fileName = options?.fileName; - const candidates: string[] = []; let failedPaths = 0; - const walk = async (dir: string): Promise => { + let reading = 0; + const waiting: Array<() => void> = []; + // Sibling directories read together; each returns its own list so the result keeps readdir order. + const walk = async (dir: string): Promise => { + if (reading < WALK_CONCURRENCY) reading += 1; + else await new Promise((resume) => waiting.push(resume)); let entries; try { entries = await NodeFSP.readdir(dir, { withFileTypes: true }); } catch { failedPaths += 1; - return; - } - for (const entry of entries) { - const child = NodePath.join(dir, entry.name); - if (entry.isDirectory()) await walk(child); - else if ( - fileName !== undefined - ? entry.name === fileName - : entry.name.endsWith(".jsonl") || entry.name.endsWith(".jsonl.zst") - ) { - candidates.push(child); - } + return []; + } finally { + // A waiting directory takes over this slot, so the count only drops when none waits. + const next = waiting.shift(); + if (next === undefined) reading -= 1; + else next(); } + const found = await Promise.all( + entries.map((entry) => { + const child = NodePath.join(dir, entry.name); + if (entry.isDirectory()) return walk(child); + return ( + fileName !== undefined + ? entry.name === fileName + : entry.name.endsWith(".jsonl") || entry.name.endsWith(".jsonl.zst") + ) + ? [child] + : []; + }), + ); + return found.flat(); }; - await walk(root); + const candidates = await walk(root); const found: Array = Array.from({ length: candidates.length }); const queue = candidates.entries(); const statQueued = async (): Promise => { for (const [index, path] of queue) { try { - const stats = await NodeFSP.stat(path); + const stats = await statFile(path); if (stats.mtimeMs >= sinceMs) { found[index] = { path, size: stats.size, mtimeMs: stats.mtimeMs }; } @@ -116,7 +137,7 @@ export async function listTranscriptFiles( await Promise.all( Array.from({ length: Math.min(STAT_CONCURRENCY, candidates.length) }, statQueued), ); - return { files: found.filter((file) => file !== undefined), failedPaths }; + return { files: found.filter((file) => file !== undefined), walked: candidates, failedPaths }; } export async function readDirectoryVolumeId(path: string): Promise { diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 25401ec98544c..54c05f777b46b 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -2184,6 +2184,31 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect( + "switches a remote ref to its tracking branch when a tag shares the branch name", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const remote = yield* makeTmpDir("git-remote-"); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "origin", "HEAD:refs/heads/v1.2"]); + yield* git(cwd, ["fetch", "origin"]); + yield* git(cwd, ["branch", "--track", "v1.2", "origin/v1.2"]); + yield* git(cwd, ["tag", "v1.2"]); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), initialBranch); + + const result = yield* (yield* GitVcsDriver.GitVcsDriver).switchRef({ + cwd, + refName: "origin/v1.2", + }); + + assert.equal(result.refName, "v1.2"); + assert.equal(yield* git(cwd, ["symbolic-ref", "HEAD"]), "refs/heads/v1.2"); + }), + ); + it.effect.each([ // Git cannot tell a missing revision from a missing file in these. { label: "an argument that may be a path", args: ["log", "-1", "missing"] }, @@ -4391,6 +4416,37 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("leaves FETCH_HEAD to the user's own pulls in background upstream fetches", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const remote = yield* makeTmpDir("git-vcs-driver-remote-"); + const updater = yield* makeTmpDir("git-vcs-driver-updater-"); + const { initialBranch } = yield* initRepoWithCommit(cwd); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "-u", "origin", initialBranch]); + + yield* git(updater, ["clone", remote, "."]); + yield* git(updater, ["config", "user.email", "test@test.com"]); + yield* git(updater, ["config", "user.name", "Test"]); + yield* writeTextFile(updater, "remote.txt", "remote\n"); + yield* git(updater, ["add", "remote.txt"]); + yield* git(updater, ["commit", "-m", "remote commit"]); + yield* git(updater, ["push", "origin", initialBranch]); + const fetchHeadPath = (yield* Path.Path).join(cwd, ".git", "FETCH_HEAD"); + assert.equal(NodeFS.existsSync(fetchHeadPath), false); + + const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetailsRemote(cwd); + + assert.equal(status.behindCount, 1); + assert.equal( + NodeFS.existsSync(fetchHeadPath), + false, + "background status fetch wrote .git/FETCH_HEAD, which an overlapping `git pull` merges from", + ); + }), + ); + it.effect("uses origin HEAD for default-branch detection with a non-origin upstream", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -6070,39 +6126,82 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("tracks a remote start point once another process releases the config lock", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - const { initialBranch } = yield* initRepoWithCommit(cwd); - const remote = yield* makeTmpDir("git-remote-"); - yield* git(remote, ["init", "--bare"]); - yield* git(cwd, ["remote", "add", "origin", remote]); - yield* git(cwd, ["push", "origin", initialBranch]); - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const lockPath = path.join(cwd, ".git", "config.lock"); - yield* fileSystem.writeFileString(lockPath, ""); - const { driver, failures } = yield* makeDriverReleasingLock( - (args) => args.some((arg) => arg.startsWith("--set-upstream-to")), - lockPath, - ); + it.effect.each(["createWorktree", "switchRef"] as const)( + "tracks a remote start point once another process releases the config lock: %s", + (operation) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const remote = yield* makeTmpDir("git-remote-"); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "origin", `${initialBranch}:refs/heads/feature/tracked`]); + yield* git(cwd, ["fetch", "origin"]); + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const lockPath = path.join(cwd, ".git", "config.lock"); + yield* fileSystem.writeFileString(lockPath, ""); + const { driver, failures } = yield* makeDriverReleasingLock( + (args) => args.some((arg) => arg.startsWith("--set-upstream-to")), + lockPath, + ); - // The upstream retry waits on the real clock; the lock is already gone by then. - yield* TestClock.withLive( - driver.createWorktree({ - cwd, - path: path.join(yield* makeTmpDir("git-worktrees-"), "tracked"), - refName: `origin/${initialBranch}`, - newRefName: "feature/tracked", - }), - ); + // The upstream retry waits on the real clock; the lock is already gone by then. + if (operation === "createWorktree") { + yield* TestClock.withLive( + driver.createWorktree({ + cwd, + path: path.join(yield* makeTmpDir("git-worktrees-"), "tracked"), + refName: "origin/feature/tracked", + newRefName: "feature/tracked", + }), + ); + } else { + const switched = yield* TestClock.withLive( + driver.switchRef({ cwd, refName: "origin/feature/tracked" }), + ); + assert.equal(switched.refName, "feature/tracked"); + } - assert.equal(yield* Ref.get(failures), 1); - assert.equal( - yield* git(cwd, ["rev-parse", "--abbrev-ref", "feature/tracked@{upstream}"]), - `origin/${initialBranch}`, - ); - }), + assert.equal(yield* Ref.get(failures), 1); + assert.equal( + yield* git(cwd, ["rev-parse", "--abbrev-ref", "feature/tracked@{upstream}"]), + "origin/feature/tracked", + ); + }), + ); + + it.effect( + "leaves no untracked branch behind when the config stays locked during a switch", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const remote = yield* makeTmpDir("git-remote-"); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "upstream", remote]); + yield* git(cwd, ["push", "upstream", `${initialBranch}:refs/heads/feature`]); + yield* git(cwd, ["fetch", "upstream"]); + const fileSystem = yield* FileSystem.FileSystem; + const lockPath = (yield* Path.Path).join(cwd, ".git", "config.lock"); + yield* fileSystem.writeFileString(lockPath, ""); + const driver = yield* GitVcsDriver.GitVcsDriver; + + // The upstream retry waits on the real clock before giving up. + yield* TestClock.withLive(driver.switchRef({ cwd, refName: "upstream/feature" })).pipe( + Effect.flip, + ); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), initialBranch); + assert.equal(yield* git(cwd, ["branch", "--list", "feature"]), ""); + + yield* fileSystem.remove(lockPath); + const switched = yield* driver.switchRef({ cwd, refName: "upstream/feature" }); + assert.equal(switched.refName, "feature"); + assert.equal( + yield* git(cwd, ["rev-parse", "--abbrev-ref", "feature@{upstream}"]), + "upstream/feature", + ); + }), ); it.effect("fetches a remote branch into a tracking branch past another process's lock", () => @@ -6341,28 +6440,42 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("prepares selected files without staging and commits only those files", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - yield* initRepoWithCommit(cwd); - const driver = yield* GitVcsDriver.GitVcsDriver; - - yield* writeTextFile(cwd, "a.txt", "a\n"); - yield* writeTextFile(cwd, "b.txt", "b\n"); - - const context = yield* driver.prepareCommitContext(cwd, ["a.txt"]); - assert.include(context?.stagedSummary ?? "", "a.txt"); - assert.notInclude(context?.stagedSummary ?? "", "b.txt"); - assert.equal(yield* git(cwd, ["diff", "--cached", "--name-only"]), ""); + it.effect.each(["root", "aliased-nested"] as const)( + "prepares selected files without staging and commits only those files from %s", + (location) => + Effect.gen(function* () { + const sandbox = yield* makeTmpDir(); + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const repository = path.join(sandbox, "repo"); + const nested = path.join(repository, "sub", "dir"); + yield* fileSystem.makeDirectory(nested, { recursive: true }); + yield* initRepoWithCommit(repository); + const cwd = location === "aliased-nested" ? path.join(sandbox, "link") : repository; + if (location === "aliased-nested") NodeFS.symlinkSync(nested, cwd, "junction"); + const driver = yield* GitVcsDriver.GitVcsDriver; + const selected = "sub/dir/a.txt"; + yield* writeTextFile(repository, selected, "a\n"); + yield* writeTextFile(repository, "b.txt", "b\n"); - const commit = yield* driver.commit(cwd, "Add a", "", { stage: { filePaths: ["a.txt"] } }); - assert.match(commit.commitSha, /^[a-f0-9]{40}$/); - assert.equal(yield* git(cwd, ["log", "-1", "--pretty=%s"]), "Add a"); + const context = yield* driver.prepareCommitContext(cwd, [selected]); + assert.include(context?.stagedSummary ?? "", "a.txt"); + assert.notInclude(context?.stagedSummary ?? "", "b.txt"); + assert.equal(yield* git(repository, ["diff", "--cached", "--name-only"]), ""); - const status = yield* git(cwd, ["status", "--porcelain"]); - assert.include(status, "?? b.txt"); - assert.notInclude(status, "a.txt"); - }), + const commit = yield* driver.commit(cwd, "Add a", "", { + stage: { filePaths: [selected] }, + }); + assert.match(commit.commitSha, /^[a-f0-9]{40}$/); + assert.equal(yield* git(repository, ["log", "-1", "--pretty=%s"]), "Add a"); + assert.equal( + yield* git(repository, ["diff-tree", "--no-commit-id", "--name-only", "-r", "HEAD"]), + selected, + ); + const status = yield* git(repository, ["status", "--porcelain"]); + assert.include(status, "?? b.txt"); + assert.notInclude(status, "a.txt"); + }), ); it.effect("stops a selected-file commit when another process holds the index lock", () => diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index a8e4fb9265f3d..2c2c2a7b61da2 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -1387,6 +1387,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* "--quiet", "--no-tags", "--no-auto-gc", + // FETCH_HEAD is written without a lock; overlapping a user's `git pull` makes that pull fail. + "--no-write-fetch-head", "--", remoteName, ]; @@ -2633,7 +2635,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["rev-parse", "--git-path", "index", "--git-path", "objects"], )).split("\n"); - const indexPath = path.resolve(cwd, indexValue.trim()); + // Git's relative paths use the physical cwd, even when the project uses a symlink. + const physicalCwd = yield* fileSystem.realPath(cwd); + const indexPath = path.resolve(physicalCwd, indexValue.trim()); const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-commit-index-", }); @@ -2651,7 +2655,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const quoted = (entry: string) => entry.startsWith('"') ? entry : `"${entry.replace(/[\\"]/g, "\\$&")}"`; const alternates = [ - path.resolve(cwd, objectsValue.trim()), + path.resolve(physicalCwd, objectsValue.trim()), ...objectDirectories .split("\n") .flatMap((line) => @@ -5255,7 +5259,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ? yield* executeGit( "GitVcsDriver.switchRef.localTrackingBranch", input.cwd, - ["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"], + // `:short` prefixes a name a tag shares with `heads/`, so names are unambiguous here. + ["for-each-ref", "--format=%(refname:lstrip=2)\t%(upstream)", "refs/heads"], { timeoutMs: 5_000, allowNonZeroExit: true, @@ -5263,7 +5268,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ).pipe( Effect.map((result) => result.exitCode === 0 - ? parseTrackingBranchByUpstreamRef(result.stdout, input.refName) + ? parseTrackingBranchByUpstreamRef(result.stdout, `refs/remotes/${input.refName}`) : null, ), ) @@ -5305,15 +5310,29 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* // Created before the checkout so the shared-config lock is not held while files are written. // Not rolled back on failure: Git may already have switched HEAD to it (post-checkout hooks). if (newTrackingBranch) { - yield* executeGit( + const startRef = `refs/remotes/${input.refName}`; + yield* executeGitWithStableDiagnostics( "GitVcsDriver.switchRef.createTrackingBranch", input.cwd, - ["branch", "--track", "--", newTrackingBranch, input.refName], - { - timeoutMs: 10_000, - fallbackErrorDetail: "git branch create failed", - writesSharedConfig: true, - }, + ["branch", "--no-track", "--", newTrackingBranch, startRef], + { fallbackErrorDetail: "git branch create failed" }, + ); + // An untracked branch of this name would make every later switch to the remote detach. + yield* executeGitWithStableDiagnostics( + "GitVcsDriver.switchRef.trackRemote", + input.cwd, + ["branch", `--set-upstream-to=${startRef}`, "--", newTrackingBranch], + { writesSharedConfig: true }, + ).pipe( + retryWhileConfigLocked, + Effect.tapError(() => + executeGit( + "GitVcsDriver.switchRef.removeUntrackedBranch", + input.cwd, + ["update-ref", "-d", `refs/heads/${newTrackingBranch}`, startRef], + { allowNonZeroExit: true }, + ), + ), ); } diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index e70afb2ddde02..87620e5d4fc4f 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -1365,13 +1365,10 @@ describe("VcsStatusBroadcaster", () => { it.effect("a checkout read that fails while index.lock is held retries until it succeeds", () => Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const gitDir = yield* fs.makeTempDirectoryScoped({ prefix: "vcs-head-watch-" }); - const headPath = path.join(gitDir, "HEAD"); - yield* fs.writeFileString(headPath, "ref: refs/heads/main\n"); + const events = yield* Queue.unbounded(); + const headPath = "/repo/.git/HEAD"; const failed = yield* Deferred.make(); - const state = { + const state: Parameters[0] = { currentLocalStatus: { ...baseLocalStatus, isDefaultRef: true, refName: "main" }, currentRemoteStatus: null, localStatusCalls: 0, @@ -1379,6 +1376,12 @@ describe("VcsStatusBroadcaster", () => { localInvalidationCalls: 0, remoteInvalidationCalls: 0, headPath, + fileSystem: FileSystem.makeNoop({ + realPath: (target) => Effect.succeed(target), + exists: () => Effect.succeed(true), + watch: (_target, options) => + Stream.fromQueue(events).pipe(Stream.onStart(Effect.sync(() => options?.onReady?.()))), + }), failLocalStatus: false, onLocalStatusFailure: Deferred.succeed(failed, undefined).pipe(Effect.asVoid), }; @@ -1402,9 +1405,7 @@ describe("VcsStatusBroadcaster", () => { // A terminal commit holds index.lock across the checkout, so the HEAD event's read fails. state.failLocalStatus = true; state.currentLocalStatus = { ...baseLocalStatus, isDefaultRef: false, refName: "repro" }; - const lockPath = path.join(gitDir, "HEAD.lock"); - yield* fs.writeFileString(lockPath, "ref: refs/heads/repro\n"); - yield* fs.rename(lockPath, headPath); + yield* Queue.offer(events, { _tag: "Update", path: "HEAD" }); yield* Deferred.await(failed); const failedCalls = state.localStatusCalls; @@ -1414,7 +1415,7 @@ describe("VcsStatusBroadcaster", () => { yield* Deferred.await(checkedOut); assert.strictEqual(state.localStatusCalls, failedCalls + 1); }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + }).pipe(Effect.scoped), ); it.effect("subscribers share one HEAD watch that ends with the last of them", () => @@ -1527,6 +1528,50 @@ describe("VcsStatusBroadcaster", () => { }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), ); + it.effect("a HEAD watch ends when its git directory is removed", () => + Effect.gen(function* () { + const gitDir = "/repo/.git/worktrees/feature"; + const events = yield* Queue.unbounded(); + const closed = yield* Deferred.make(); + let gitDirExists = true; + const state: Parameters[0] = { + currentLocalStatus: { ...baseLocalStatus, refName: "main" }, + currentRemoteStatus: null, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + headPath: `${gitDir}/HEAD`, + fileSystem: FileSystem.makeNoop({ + realPath: (target) => Effect.succeed(target), + exists: (target) => Effect.succeed(target !== gitDir || gitDirExists), + watch: (_target, options) => + Stream.fromQueue(events).pipe( + Stream.onStart(Effect.sync(() => options?.onReady?.())), + Stream.ensuring(Deferred.succeed(closed, undefined)), + ), + }), + }; + + yield* Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const branches = yield* Stream.toPull(broadcaster.streamBranchStatus({ cwd: "/repo" })); + assert.deepEqual(yield* branches, [{ refName: "main", isRepo: true }]); + + // Every checkout removes HEAD.lock, which leaves the watch running. + state.currentLocalStatus = { ...baseLocalStatus, refName: "other" }; + yield* Queue.offer(events, { _tag: "Remove", path: "HEAD.lock" }); + yield* Queue.offer(events, { _tag: "Update", path: "HEAD" }); + assert.deepEqual(yield* branches, [{ refName: "other", isRepo: true }]); + + // `git worktree remove` deletes the watched directory; Windows keeps reporting it. + gitDirExists = false; + yield* Queue.offer(events, { _tag: "Remove", path: gitDir }); + yield* Deferred.await(closed); + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }), + ); + it.effect("releases remote demand while passive observers remain", () => { const state = { currentLocalStatus: baseLocalStatus, diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index ffe685ef60d57..99b3a2374162a 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -822,12 +822,19 @@ export const make = Effect.gen(function* () { const watchHead = Effect.fnUntraced(function* (cwd: string, ready: Deferred.Deferred) { const headPath = yield* workflow.headPath(cwd); if (headPath === null) return; + const headDirectory = path.dirname(headPath); // Git replaces HEAD by renaming HEAD.lock, which a watch on the file itself would lose. yield* fs - .watch(path.dirname(headPath), { + .watch(headDirectory, { onReady: () => Deferred.doneUnsafe(ready, Exit.void), }) .pipe( + // On Windows a watch outlives its deleted directory and reports it ~150k times a second. + Stream.takeUntilEffect((event) => + event._tag === "Remove" + ? fs.exists(headDirectory).pipe(Effect.map((exists) => !exists)) + : Effect.succeed(false), + ), Stream.filter((event) => path.basename(event.path) === "HEAD"), // A rebase moves HEAD many times; refresh once for whatever arrived during a refresh. Stream.buffer({ capacity: 1, strategy: "sliding" }), diff --git a/apps/server/src/workspace/WorkspaceEntries.test.ts b/apps/server/src/workspace/WorkspaceEntries.test.ts index 62d6ab0a63b33..610568078e31a 100644 --- a/apps/server/src/workspace/WorkspaceEntries.test.ts +++ b/apps/server/src/workspace/WorkspaceEntries.test.ts @@ -457,17 +457,31 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { }), ); - it.effect("matches square brackets in the query literally", () => + it.effect("matches glob metacharacters in the query literally", () => Effect.gen(function* () { const cwd = yield* makeTempDir({ prefix: "t3code-workspace-brackets-" }); yield* writeTextFile(cwd, "src/app/game/[id]/index.tsx"); + yield* writeTextFile(cwd, "src/foo{bar}.ts"); + yield* writeTextFile(cwd, "src/main.ts"); + yield* writeTextFile(cwd, "src/notes.md"); - for (const query of ["game/[i", "game/[id]"]) { - const result = yield* searchWorkspaceEntries({ cwd, query, limit: 10 }); - expect(result.entries.map((entry) => entry.path)).toContain( - "src/app/game/[id]/index.tsx", + const search = (query: string) => + searchWorkspaceEntries({ cwd, query, limit: 10 }).pipe( + Effect.map((result) => result.entries.map((entry) => entry.path)), ); + + for (const query of ["game/[i", "game/[id]"]) { + expect(yield* search(query)).toContain("src/app/game/[id]/index.tsx"); } + expect(yield* search("foo{bar}.ts")).toContain("src/foo{bar}.ts"); + expect((yield* search("*.{ts,tsx}")).toSorted()).toEqual([ + "src/app/game/[id]/index.tsx", + "src/foo{bar}.ts", + "src/main.ts", + ]); + expect((yield* search("*.{ts}")).toSorted()).toEqual(["src/foo{bar}.ts", "src/main.ts"]); + expect(yield* search("src/{main}.ts")).toEqual(["src/main.ts"]); + expect(yield* search("src/{foo{bar},notes}.md")).toEqual(["src/notes.md"]); }), ); @@ -799,10 +813,14 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { if (created.ok) { const finder = created.value; finders += 1; - const scanFiles = finder.scanFiles.bind(finder); + // The synchronous rescan waits on fff's picker lock on the event loop. finder.scanFiles = () => { + throw new Error("refresh must not rescan on the JS thread"); + }; + const scanFilesAsync = finder.scanFilesAsync.bind(finder); + finder.scanFilesAsync = () => { rescans += 1; - return scanFiles(); + return scanFilesAsync(); }; const waitForIndexReady = finder.waitForIndexReady.bind(finder); finder.waitForIndexReady = (timeoutMs) => diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.ts b/apps/server/src/workspace/WorkspaceSearchIndex.ts index 11a19e1839861..f276bfd9654ee 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.ts @@ -399,12 +399,13 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( const refresh: WorkspaceSearchIndex["Service"]["refresh"] = Effect.fn( "WorkspaceSearchIndex.refresh", )(function* () { - const result = yield* Effect.try({ - try: () => finder.scanFiles(), + // scanFiles waits on fff's picker lock, which its watcher can hold for seconds. + const result = yield* Effect.tryPromise({ + try: () => finder.scanFilesAsync(), catch: (cause) => new WorkspaceSearchIndexRefreshFailed({ cwd, - reason: "FileFinder.scanFiles threw unexpectedly.", + reason: "FileFinder.scanFilesAsync rejected unexpectedly.", cause, }), }); @@ -447,32 +448,43 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( }, ); - const search: WorkspaceSearchIndex["Service"]["search"] = Effect.fn( - "WorkspaceSearchIndex.search", - )(function* (rawQuery, limit, kind, imageOnly) { - // fff parses any word containing "[" as a glob and has no escape for it; fuzzy - // matching is subsequence-based, so dropping "[" still matches "[id]" folders. - const query = rawQuery.replaceAll("[", ""); + const searchNames = Effect.fn("WorkspaceSearchIndex.searchNames")(function* ( + query: string, + limit: number, + kind: ProjectEntryKind | undefined, + imageOnly: boolean | undefined, + ) { const pageSize = imageOnly ? WORKSPACE_INDEX_PAGE_SIZE : Math.max(1, limit + 1); - const incompleteBeforeQuery = hasIncompleteInitialScan(); if (kind === "file" || imageOnly) { const result = yield* runSearch(query, pageSize, "fileSearch", () => finder.fileSearch(query, { pageSize }), ); - const mapped = mapFileSearchResult(result, limit, imageOnly); - return { ...mapped, truncated: incompleteBeforeQuery || mapped.truncated }; + return mapFileSearchResult(result, limit, imageOnly); } if (kind === "directory") { const result = yield* runSearch(query, pageSize, "directorySearch", () => finder.directorySearch(query, { pageSize }), ); - const mapped = mapDirectorySearchResult(result, limit); - return { ...mapped, truncated: incompleteBeforeQuery || mapped.truncated }; + return mapDirectorySearchResult(result, limit); } const result = yield* runSearch(query, pageSize, "mixedSearch", () => finder.mixedSearch(query, { pageSize }), ); - const mapped = mapMixedSearchResult(result, limit); + return mapMixedSearchResult(result, limit); + }); + + const search: WorkspaceSearchIndex["Service"]["search"] = Effect.fn( + "WorkspaceSearchIndex.search", + )(function* (rawQuery, limit, kind, imageOnly) { + // fff parses any word containing "[" or "{" as a glob and has no escape for them; fuzzy + // matching is subsequence-based, so dropping them still matches "[id]" and "a{b}" paths. + // "{" is dropped only when the query finds nothing as a glob, so "*.{ts,tsx}" keeps working. + const query = rawQuery.replaceAll("[", ""); + const incompleteBeforeQuery = hasIncompleteInitialScan(); + let mapped = yield* searchNames(query, limit, kind, imageOnly); + if (mapped.entries.length === 0 && query.includes("{")) { + mapped = yield* searchNames(query.replaceAll("{", ""), limit, kind, imageOnly); + } return { ...mapped, truncated: incompleteBeforeQuery || mapped.truncated }; }); diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index 492b874cc451e..7f52d5963a07d 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -135,6 +135,7 @@ import * as TriageService from "./triage/TriageService.ts"; import * as TextGenerators from "./textGeneration/TextGenerators.ts"; import * as WorkspacePaths from "./workspace/WorkspacePaths.ts"; import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; +import * as SecretCheck from "./secrets/SecretCheck.ts"; import * as ServerConfigModule from "./config.ts"; import * as Keybindings from "./keybindings.ts"; import { USAGE_LIMITS_COMMAND } from "@t3tools/shared/usageLimits"; @@ -790,6 +791,7 @@ it.effect("shell snapshots omit idle children and older settled threads only on const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(DocumentText.DocumentText)({}), Layer.mock(ServerSecretStore.ServerSecretStore)({}), + Layer.mock(SecretCheck.SecretCheck)({}), Layer.mock(WorkspacePaths.WorkspacePaths)({}), Layer.mock(TraceDiagnostics.TraceDiagnostics)({}), Layer.mock(TriageService.TriageService)({}), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 4cfceb4ed8001..5e81541ff3530 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -173,6 +173,7 @@ import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts"; import * as OrchestrationEventStore from "./persistence/OrchestrationEventStore.ts"; import { userFacingDispatchErrorMessage } from "./orchestration-v2/UserFacingErrors.ts"; import * as ProviderRegistry from "./provider/ProviderRegistry.ts"; +import * as SecretCheck from "./secrets/SecretCheck.ts"; import * as AcpRegistrySessions from "./provider/AcpRegistrySessions.ts"; import * as ProviderInstanceRegistry from "./provider/ProviderInstanceRegistry.ts"; import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRegistrySupport"; @@ -1556,6 +1557,7 @@ export const layerWsRpc = ( ); const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; const sourceControlDiscovery = yield* SourceControlDiscovery.SourceControlDiscovery; + const secretCheck = yield* SecretCheck.SecretCheck; const otlpEndpointCheck = yield* OtlpEndpointCheck.OtlpEndpointCheck; const textGenerators = yield* TextGenerators.TextGenerators; const sourceControlRepositories = @@ -2661,6 +2663,7 @@ export const layerWsRpc = ( return ServerSettings.redactServerSettingsForClient(settings, settingsClient); }), [WS_METHODS.serverDiscoverSourceControl]: (_input) => sourceControlDiscovery.discover, + [WS_METHODS.serverCheckSecretSource]: (input) => secretCheck.check(input.source), [WS_METHODS.serverGetTraceDiagnostics]: (_input) => TraceDiagnostics.readTraceDiagnostics({ traceFilePath: config.serverTracePath, diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index ac1496b04a5c6..2b59c126e2a6b 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -125,7 +125,7 @@ export function BranchToolbarBranchSelector({ const switchRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false, }); - const refreshStatus = useAtomCommand(vcsEnvironment.refreshStatus, { + const refreshLocalStatusForPicker = useAtomCommand(vcsEnvironment.refreshLocalStatusForPicker, { reportFailure: false, }); const createRefMutation = useAtomCommand(vcsEnvironment.createRef, { @@ -562,7 +562,10 @@ export function BranchToolbarBranchSelector({ const handleOpenChange = (open: boolean) => { setIsBranchMenuOpen(open); if (open && !isBranchMenuOpen && branchCwd !== null) { - void refreshStatus({ environmentId, input: { cwd: branchCwd, localOnly: true } }); + void refreshLocalStatusForPicker({ + environmentId, + input: { cwd: branchCwd, localOnly: true }, + }); } if (!open) { setBranchQuery(""); diff --git a/apps/web/src/components/ChatView.logic.browser.test.ts b/apps/web/src/components/ChatView.logic.browser.test.ts index 2d887cb5acc2c..880a640cc6e20 100644 --- a/apps/web/src/components/ChatView.logic.browser.test.ts +++ b/apps/web/src/components/ChatView.logic.browser.test.ts @@ -28,6 +28,19 @@ it("keeps keyboard focus on a sidebar row on window return, but not a clicked ro expect(shouldRefocusComposerOnWindowFocus(document.activeElement)).toBe(false); }); +it("keeps focus in a region with its own keys on window return", async () => { + const region = document.createElement("div"); + region.tabIndex = -1; + region.setAttribute("aria-keyshortcuts", "J K"); + region.textContent = "Guide prose"; + document.body.append(region); + using _region = { [Symbol.dispose]: () => region.remove() }; + + await userEvent.click(region); + expect(document.activeElement).toBe(region); + expect(shouldRefocusComposerOnWindowFocus(document.activeElement)).toBe(false); +}); + it("refocuses the composer on window return from a clicked area after a bare key press", async () => { const controller = createWorkspaceFocusController(document); const root = document.createElement("div"); diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index b1d44d95441c5..0848d27c05bdb 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -1069,10 +1069,10 @@ export function hasServerAcknowledgedLocalDispatch(input: { ); } -// Returning to the window should land the caret in the composer, so the reader can type right -// away. The exceptions are places where focus is deliberate: another text field, a terminal in -// the drawer or the right panel, an open dialog, menu, or popup, or a region or sidebar row -// reached from the keyboard. A plain focused button or a clicked row yields to the composer. +// Window return puts the caret in the composer unless focus is deliberate: another text field, +// a terminal, an open dialog, menu, or popup, a region or sidebar row reached from the keyboard, +// or a region with its own keys (aria-keyshortcuts). A plain focused button or a clicked row +// yields to the composer. export function shouldRefocusComposerOnWindowFocus( activeElement: | (Pick & { isContentEditable?: boolean }) @@ -1092,7 +1092,7 @@ export function shouldRefocusComposerOnWindowFocus( } return ( activeElement.closest( - '[data-workspace-keyboard-focus], [data-sidebar-row]:focus-visible, [role="dialog"], [role="alertdialog"], [role="application"], [role="menu"], [role="listbox"], [data-slot$="-popup"], [data-terminal-owner]', + '[data-workspace-keyboard-focus], [data-sidebar-row]:focus-visible, [role="dialog"], [role="alertdialog"], [role="application"], [role="menu"], [role="listbox"], [data-slot$="-popup"], [data-terminal-owner], [aria-keyshortcuts]', ) === null ); } diff --git a/apps/web/src/components/CommandPaletteContent.tsx b/apps/web/src/components/CommandPaletteContent.tsx index 25a72d151b6d5..cd3f99a0438b9 100644 --- a/apps/web/src/components/CommandPaletteContent.tsx +++ b/apps/web/src/components/CommandPaletteContent.tsx @@ -91,7 +91,7 @@ export function CommandPaletteContent({ {children} -
+
diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.citationDraft.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.citationDraft.browser.test.tsx index 8da54f5f72141..69c2ac1fd4d59 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.citationDraft.browser.test.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.citationDraft.browser.test.tsx @@ -31,10 +31,12 @@ const promptBefore = `See ${serializeAssistantCitation(citation)} `; function Composer({ question, editorRef, + disabled = false, send = "clears", }: { question: boolean; editorRef: React.RefObject; + disabled?: boolean; send?: "clears" | "blocked" | "refusedLater"; }) { const [prompt, setPrompt] = useState(promptBefore); @@ -57,7 +59,7 @@ function Composer({ cursor={0} contextRecords={new Map()} skills={[]} - disabled={false} + disabled={disabled} placeholder="" onChange={(next) => (question ? setAnswer(next) : setPrompt(next))} onCitationDraftSave={(replacedValue, savedValue) => { @@ -159,3 +161,26 @@ it.each(["blocked", "refusedLater"] as const)( .toHaveAttribute("data-prompt", `See ${serializeAssistantCitation(citation)}x `); }, ); + +it("cancels a new citation while dictation makes the composer read-only", async () => { + const editorRef = createRef(); + await using screen = await render(); + + const sourceAnchor = findAssistantCitationSourceAnchor(document, citation); + if (!sourceAnchor) throw new Error("Citation source did not resolve"); + await act(async () => + editorRef.current?.requestCitationComment({ + previousValue: "See ", + value: promptBefore, + citationStart: "See ".length, + sourceAnchor, + insertedSpaces: { before: false, after: true }, + }), + ); + await expect.element(page.getByLabelText("Comment on selected text")).toBeVisible(); + + await page.getByRole("button", { name: "Cancel" }).click(); + + await expect.element(page.getByLabelText("Comment on selected text")).not.toBeInTheDocument(); + expect(screen.container.querySelector("output")?.dataset.prompt).toBe("See "); +}); diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 5895b63cbb9a0..a974c9308844f 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -468,7 +468,7 @@ function ComposerCitationNodeView({ node, editor, getPos }: NodeViewProps) { const removeOnCancel = commentTarget?.removeOnCancel; const onRemove = () => { - if (!editor.isEditable || !removeOnCancel) return; + if (!removeOnCancel) return; const pos = nodePos(); if (pos === null) return; const { doc } = editor.state; @@ -477,7 +477,9 @@ function ComposerCitationNodeView({ node, editor, getPos }: NodeViewProps) { const end = pos + current.nodeSize; const from = removeOnCancel.before && doc.textBetween(pos - 1, pos) === " " ? pos - 1 : pos; const to = removeOnCancel.after && doc.textBetween(end, end + 1) === " " ? end + 1 : end; - editor.chain().focus().deleteRange({ from, to }).run(); + // A read-only composer (dictation) can still receive a new citation, so Cancel must undo it. + const chain = editor.chain(); + (editor.isEditable ? chain.focus() : chain).deleteRange({ from, to }).run(); }; const sentRef = useRef(false); diff --git a/apps/web/src/components/RightPanelTabs.browser.test.tsx b/apps/web/src/components/RightPanelTabs.browser.test.tsx index cceb8c22c707b..f803cb41520bc 100644 --- a/apps/web/src/components/RightPanelTabs.browser.test.tsx +++ b/apps/web/src/components/RightPanelTabs.browser.test.tsx @@ -2,6 +2,7 @@ import "~/index.css"; import { EnvironmentId } from "@t3tools/contracts"; import { describe, expect, it, vi } from "vite-plus/test"; +import { userEvent } from "vite-plus/test/browser"; import { InputGroup, InputGroupAddon, InputGroupInput } from "~/components/ui/input-group"; import type { RightPanelSurface } from "~/rightPanelStore"; @@ -249,3 +250,41 @@ describe("right panel thumb buttons", () => { expect(actions).toEqual(["back", "forward", "back"]); }); }); + +const DEVICE_SURFACE: RightPanelSurface = { + id: "device:host:phone", + kind: "device", + target: { hostId: "host", deviceId: "phone", platform: "ios", name: "Phone" }, +}; + +describe("device tab rename", () => { + it("keeps the editor open on an Enter that confirms an IME candidate", async () => { + const onRenameDevice = vi.fn(); + const props = panel(DEVICE_SURFACE).props as RightPanelTabsProps; + await using screen = await render( + + {null} + , + ); + await userEvent.dblClick(screen.getByRole("button", { name: "Phone", exact: true })); + const input = screen.getByRole("textbox", { name: "Device tab name" }); + await userEvent.fill(input, "にほん"); + + for (const shape of [ + { isComposing: true, keyCode: 13 }, + { isComposing: false, keyCode: 229 }, + ]) { + input + .element() + .dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true, ...shape }), + ); + } + + await expect.element(input).toHaveFocus(); + expect(onRenameDevice).not.toHaveBeenCalled(); + await userEvent.fill(input, "日本語"); + await userEvent.keyboard("{Enter}"); + expect(onRenameDevice).toHaveBeenCalledExactlyOnceWith(DEVICE_SURFACE.id, "日本語"); + }); +}); diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index 223799efb26f6..d220385e28142 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -965,6 +965,7 @@ function RightPanelTab( onBlur={(event) => onFinishRename(surface.id, event.currentTarget.value)} onKeyDown={(event) => { event.stopPropagation(); + if (event.nativeEvent.isComposing || event.keyCode === 229) return; if (event.key === "Enter") event.currentTarget.blur(); if (event.key === "Escape") { event.currentTarget.value = title; diff --git a/apps/web/src/components/ServerUpdateAction.tsx b/apps/web/src/components/ServerUpdateAction.tsx index 14e0dd3c192cb..ef999e5bcdc31 100644 --- a/apps/web/src/components/ServerUpdateAction.tsx +++ b/apps/web/src/components/ServerUpdateAction.tsx @@ -276,17 +276,17 @@ export function ServerUpdateAction({ const canUpdate = useAtomValue(sessionStateAtom, canUpdateServer); const updatesDenial = managedUpdatesDenial(useManagedPolicy(environmentId)); const update = useServerUpdate(); + const updatesInstall = + installation?.kind === "npm-global" || installation?.kind === "t3-launcher"; const { copyToClipboard } = useCopyToClipboard<{ command: string }>({ - target: installation?.kind === "npm-global" ? "update command" : "relaunch command", + target: updatesInstall ? "update command" : "relaunch command", onCopy: ({ command }) => { toastManager.add({ type: "success", - title: - installation?.kind === "npm-global" ? "Update command copied" : "Relaunch command copied", - description: - installation?.kind === "npm-global" - ? `Run \`${command}\` on ${serverLabel}, then restart t3 with your usual options.` - : `Stop t3 on ${serverLabel}, then relaunch with \`${command}\` using the same subcommand and options. This does not update an installed t3 command.`, + title: updatesInstall ? "Update command copied" : "Relaunch command copied", + description: updatesInstall + ? `Run \`${command}\` on ${serverLabel}, then restart t3 with your usual options.` + : `Stop t3 on ${serverLabel}, then relaunch with \`${command}\` using the same subcommand and options. This does not update an installed t3 command.`, }); }, onError: (error) => { @@ -353,7 +353,7 @@ export function ServerUpdateAction({ selfUpdate === null ? manualServerUpdateCommand(targetVersion, installation) : null; const actionLabel = manualCommand !== null - ? installation?.kind === "npm-global" + ? updatesInstall ? "Copy update command" : "Copy relaunch command" : label; diff --git a/apps/web/src/components/Sidebar.browser.test.tsx b/apps/web/src/components/Sidebar.browser.test.tsx index 64bead88b35c9..f152cabf01851 100644 --- a/apps/web/src/components/Sidebar.browser.test.tsx +++ b/apps/web/src/components/Sidebar.browser.test.tsx @@ -1,3 +1,7 @@ +import appCss from "../index.css?inline"; +import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection"; +import * as shelfHooks from "../state/olderSettledShelf"; +import { createWorkspaceFocusController, workspaceAreaProps } from "../lib/workspaceFocus"; import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; import { DEFAULT_CLIENT_SETTINGS, @@ -16,7 +20,7 @@ import { makeThreadFixture } from "../test-fixtures"; import { useHandleNewThread } from "../hooks/useHandleNewThread"; import { __setClientSettingsForTests, getClientSettings } from "../hooks/useSettings"; import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget"; -import { useProjects, useQuietThreadShells } from "../state/entities"; +import { useProjects, useServerConfigs, useQuietThreadShells } from "../state/entities"; import { readEnvironmentScope, useEnvironmentScope } from "../state/session"; import { useOrchestrationCommand } from "../state/use-orchestration-command"; import { useTerminalUiStateStore } from "../terminalUiStateStore"; @@ -26,6 +30,10 @@ import { THREAD_JUMP_HINT_SHOW_DELAY_MS } from "./Sidebar.logic"; import { SortableThreadRow } from "./sidebar/SidebarThreadRow"; import { SidebarProvider } from "./ui/sidebar"; +vi.mock(import("../state/olderSettledShelf"), async (original) => { + const actual = await original(); + return { ...actual, useOlderSettledShelf: vi.fn(actual.useOlderSettledShelf) }; +}); vi.mock("../state/entities", { spy: true }); vi.mock("../hooks/useHandleNewThread", { spy: true }); vi.mock("../hooks/useThreadRouteTarget", { spy: true }); @@ -135,6 +143,7 @@ describe("sidebar render isolation", () => { environmentId: activeProject.environmentId, threadId: threads[0]!.id, }; + threads.unshift(threadShell(activeProject.id, 100)); vi.mocked(useProjects).mockReturnValue([activeProject]); vi.mocked(useQuietThreadShells).mockReturnValue(threads); vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef: routeThreadRef }); @@ -247,3 +256,98 @@ describe("sidebar thread rename", () => { }, ); }); + +describe("sidebar settled pagination", () => { + it("keeps the viewport in place when showing more settled threads", async () => { + using stack = new DisposableStack(); + const style = document.createElement("style"); + style.textContent = appCss; + document.head.append(style); + stack.defer(() => style.remove()); + const focusController = createWorkspaceFocusController(document); + stack.defer(() => focusController.dispose()); + let loading = false; + const originalShelf = vi.mocked(shelfHooks.useOlderSettledShelf).getMockImplementation()!; + using _shelf = vi.spyOn(shelfHooks, "useOlderSettledShelf").mockImplementation((input) => ({ + ...originalShelf(input), + loading, + retry: () => { + loading = true; + }, + })); + const activeProject = project("active"); + const threads = Array.from({ length: 70 }, (_, index) => + makeThreadFixture({ + environmentId: activeProject.environmentId, + projectId: activeProject.id, + id: ThreadId.make(`settled-${index}`), + title: `Settled thread ${index}`, + settledOverride: "settled", + settledAt: "2026-01-01T00:00:00.000Z", + }), + ); + threads.unshift(threadShell(activeProject.id, 100)); + vi.mocked(useProjects).mockReturnValue([activeProject]); + vi.mocked(useQuietThreadShells).mockReturnValue(threads); + vi.mocked(useThreadRouteTarget).mockReturnValue({ + kind: "server", + threadRef: { environmentId: activeProject.environmentId, threadId: threads[0]!.id }, + }); + vi.mocked(useHandleNewThread).mockReturnValue({ + activeDraftThread: null, + activeThread: null, + defaultProjectRef: { + environmentId: activeProject.environmentId, + projectId: activeProject.id, + }, + defaultProjectFallbackReady: true, + handleNewThread: vi.fn().mockResolvedValue(null), + routeDraftId: null, + routeThreadRef: { environmentId: activeProject.environmentId, threadId: threads[0]!.id }, + }); + vi.mocked(useServerConfigs).mockReturnValue( + new Map([ + [ + activeProject.environmentId, + { + scratchWorkspaceRoot: null, + shellThreadFamilies: false, + } as unknown as EnvironmentServerConfig, + ], + ]), + ); + await using screen = await render( + + + , + ); + const shelf = screen.container.querySelector( + '[data-sidebar-row="shelf:settled"]', + )!; + if (shelf.getAttribute("aria-expanded") === "false") await act(() => shelf.click()); + const more = screen.getByRole("button", { name: "Show 25 more", exact: true }); + await expect.element(more).toBeInTheDocument(); + const moreButton = more.element() as HTMLButtonElement; + const viewport = moreButton.closest('[data-slot="scroll-area-viewport"]')!; + viewport.style.height = "300px"; + viewport.style.maxHeight = "300px"; + moreButton.scrollIntoView({ block: "nearest" }); + const before = viewport.scrollTop; + expect(before).toBeGreaterThan(0); + moreButton.focus({ preventScroll: true }); + await act(() => moreButton.click()); + await expect + .element(screen.getByRole("button", { name: "Loading", exact: true })) + .toBeInTheDocument(); + await expect + .element(screen.getByRole("button", { name: "Loading", exact: true })) + .toHaveFocus(); + expect(viewport.scrollTop).toBe(before); + const loadedRows = screen.container.querySelectorAll("[data-thread-item]").length; + await act(() => moreButton.click()); + expect(screen.container.querySelectorAll("[data-thread-item]")).toHaveLength(loadedRows); + }); +}); diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 6cb1e722322b7..ff193edc73ccb 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -232,6 +232,7 @@ import { useActiveRowReveal, } from "./sidebar/routeReveal"; import { stackedThreadToast, toastManager } from "./ui/toast"; +import { titleRegenerationToast } from "./threadTitleRegenerationToast"; import { copyThreadReference } from "../lib/copyThreadReference"; import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference"; import { Button } from "./ui/button"; @@ -936,6 +937,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, { reportFailure: false, }); + const regenerateThreadTitle = useOrchestrationCommand(threadEnvironment.regenerateTitle, { + reportFailure: false, + }); const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({ onCopy: ({ path }) => { toastManager.add({ @@ -2453,25 +2457,18 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve return; } if (clicked.value === "regenerate-title") { - for (const thread of regeneratableTitleThreads) { - const result = await updateThreadMetadata({ - environmentId: thread.environmentId, - input: { threadId: thread.id, regenerateTitle: true }, - }); - if (result._tag === "Success") continue; - if (!isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to regenerate thread titles", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - } - return; - } clearSelection(); + const toast = titleRegenerationToast( + await Promise.all( + regeneratableTitleThreads.map((thread) => + regenerateThreadTitle({ + environmentId: thread.environmentId, + input: { threadId: thread.id }, + }), + ), + ), + ); + if (toast) toastManager.add(toast); return; } if (clicked.value === "settle") { @@ -2784,20 +2781,13 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve return; case "regenerate-title": { if (isRegeneratingTitle) return; - const result = await updateThreadMetadata({ - environmentId: threadRef.environmentId, - input: { threadId: threadRef.threadId, regenerateTitle: true }, - }); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to regenerate thread title", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - } + const toast = titleRegenerationToast([ + await regenerateThreadTitle({ + environmentId: threadRef.environmentId, + input: { threadId: threadRef.threadId }, + }), + ]); + if (toast) toastManager.add(toast); return; } case "mark-unread": @@ -3285,6 +3275,51 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve

) ) : null} + {/* A scope can hide every active thread; say so even when its project still has settled ones. */} + {!isSearchingThreads && + !hasProjectFolders && + visibleDraftSessionCount === 0 && + pinnedThreads.length + + activeThreads.length + + workingThreads.length + + snoozedThreads.length === + 0 && + (settledCount === 0 || scopedProjectGroups.length > 0) ? ( +
+ {projects.length === 0 ? ( + <> + No projects yet + + + ) : scopedProjectGroups.length > 0 ? ( + <> + + {`No ${settledCount > 0 ? "active threads" : "threads"} in ${ + scopedProjectGroups.length > 1 + ? "these projects" + : scopedProjectGroups[0]!.displayName + }${settledCount > 0 ? "" : " yet"}`} + + + + ) : ( + "No threads yet" + )} +
+ ) : null} {!isSearchingThreads ? ( { + if (olderSettledShelf.loading) return; olderSettledShelf.retry(); showMoreSettled(); }} - className="flex h-9 w-full cursor-pointer items-center gap-2.5 rounded-md px-2.5 text-left text-sm text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground disabled:cursor-default" + className="flex h-9 w-full cursor-pointer items-center gap-2.5 rounded-md px-2.5 text-left text-sm text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground aria-disabled:cursor-default" > {/* Plus means "add", so revealing more uses a chevron. */} @@ -3621,37 +3657,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ) : null} - {!isSearchingThreads && - !hasProjectFolders && - visibleDraftSessionCount === 0 && - pinnedThreads.length + - activeThreads.length + - workingThreads.length + - snoozedThreads.length + - settledCount === - 0 ? ( -
- {projects.length === 0 ? ( - <> - No projects yet - - - ) : scopedProjectGroups.length > 1 ? ( - "No threads in these projects yet" - ) : scopedProjectGroups[0] ? ( - `No threads in ${scopedProjectGroups[0].displayName} yet` - ) : ( - "No threads yet" - )} -
- ) : null} diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index bafafcb9612cf..4150db637d45e 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -698,7 +698,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) uncommittedSnapShotIds, standaloneComposerImages, } = useComposerImageGroups(attachmentDraftTarget, composerImages, composerPreviewAnnotations); - const preparingComposerImages = usePreparingComposerImages(attachmentTargetKey); + const preparingComposerImages = usePreparingComposerImages(attachmentTargetKey).filter( + (image) => !image.hidden, + ); const nonPersistedComposerImageIds = attachmentDraft.nonPersistedImageIds; const uploadsByImageId = useAttachmentUploadStore((state) => state.uploadsByImageId); const openPrLink = useOpenPrLink(routeThreadRef); @@ -1808,7 +1810,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) projectId: activeProjectId, projectName, ownerKey: questionAttachmentTarget ?? composerDraftTargetKey, - draftText: prompt, disabled: dictationDisabled, readDraft: () => { const snapshot = readComposerSnapshot(); diff --git a/apps/web/src/components/chat/ComposerStashMenu.tsx b/apps/web/src/components/chat/ComposerStashMenu.tsx index a68bf9159b483..938c42d32c8c9 100644 --- a/apps/web/src/components/chat/ComposerStashMenu.tsx +++ b/apps/web/src/components/chat/ComposerStashMenu.tsx @@ -124,7 +124,11 @@ export const ComposerStashMenu = memo(function ComposerStashMenu(props: { }, []); return ( - + } aria-label="Close stash" @@ -141,7 +145,7 @@ export const ComposerStashMenu = memo(function ComposerStashMenu(props: { - + } aria-label="Stashed prompts"> {entries.length === 0 ? ( }> diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 3d9eeb2f1b3b9..49227eb76eadd 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -228,9 +228,18 @@ describe("MessagesTimeline work rows", () => { const props = baseProps(); const html = injectHtmlRenderBootstrap(`
Earlier preview content
More rows
More rows
- `); + `); const src = URL.createObjectURL(new Blob([html], { type: "text/html" })); using _url = { [Symbol.dispose]: () => URL.revokeObjectURL(src) }; + // The frame loads on its own clock, and a toggle posted before its script runs is lost. + const listening = new Promise((resolve) => { + const onMessage = (event: MessageEvent) => { + if (event.data !== "listening") return; + window.removeEventListener("message", onMessage); + resolve(); + }; + window.addEventListener("message", onMessage); + }); function Preview() { const [height, setHeight] = useState(1437); return ( @@ -270,6 +279,7 @@ describe("MessagesTimeline work rows", () => { expect(viewport.scrollTop).toBeGreaterThan(0); expect(viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop).toBeLessThan(2); }); + await listening; const top = frame.getBoundingClientRect().top; frame.focus(); frame.contentWindow!.postMessage("toggle", "*"); diff --git a/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx b/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx index f2ddde4b72a6a..c226a26160773 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx @@ -1,5 +1,9 @@ import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts"; import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations"; +import { + formatComposerContextReference, + toComposerContextId, +} from "@t3tools/shared/composerContextReferences"; import * as DateTime from "effect/DateTime"; import type { ComponentProps } from "react"; import { expect, it, vi } from "vite-plus/test"; @@ -89,6 +93,11 @@ it("previews assistant quotes as readable text and preserves the citation when e suffix: "", }); const quoteAndText = `${quote}\n\nWhy per worktree?`; + const inlineImage = formatComposerContextReference({ + kind: "image", + contextId: toComposerContextId("header"), + label: "header.png", + }); state.projection = { projection: { messages: [] } }; state.workflow = { activeRun: { id: "run:active" }, @@ -104,6 +113,11 @@ it("previews assistant quotes as readable text and preserves the citation when e text: quoteAndText, attachments: [], }, + { + run: { id: "run:inline-image", userMessageId: "message:inline-image" }, + text: `Make the header look like ${inlineImage} and keep the logo.`, + attachments: [{ type: "image", id: "attachment:header", name: "header.png" }], + }, ], }; const onEditQueuedRun = vi.fn(); @@ -113,6 +127,11 @@ it("previews assistant quotes as readable text and preserves the citation when e await expect .element(page.getByText(`${quotedText} Why per worktree?`, { exact: true })) .toBeVisible(); + await expect + .element( + page.getByText("Make the header look like header.png and keep the logo.", { exact: true }), + ) + .toBeVisible(); await page.getByRole("button", { name: "Edit queued message", exact: true }).nth(1).click(); expect(onEditQueuedRun).toHaveBeenCalledExactlyOnceWith( diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsx index 66e023a756f6b..29a99d385573d 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.tsx @@ -253,9 +253,7 @@ export function QueuedRunsControl({ const previewText = isAttachmentOnlyBootstrapPrompt(item.text) ? "" : assistantCitationsToPlainText( - replaceComposerContextReferences(item.text, (reference) => - reference.kind === "image" && item.thumbnails.length > 0 ? "" : reference.label, - ), + replaceComposerContextReferences(item.text, (reference) => reference.label), ).trim(); const isEditing = item.runId !== null && item.runId === props.editingRunId; return ( diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx index 23f749d8c910b..6733638957238 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx @@ -72,6 +72,7 @@ import { AlertDialogTitle, } from "../ui/alert-dialog"; import { Button } from "../ui/button"; +import { Spinner } from "../ui/spinner"; import { toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { @@ -371,10 +372,15 @@ export function ThreadDetailsPrRow({ : rowAction === "fix" ? { label: "Fix", - pendingLabel: "Preparing...", + pendingLabel: "Fix", pending: handoff === "findings", destructive: true, - suffix: newThreadSuffix, + suffix: + handoff === "findings" ? ( + + ) : ( + newThreadSuffix + ), tooltip: composerTarget === undefined ? "Fix the failing checks in a new thread" @@ -478,7 +484,7 @@ export function ThreadDetailsPrRow({ checksState={checksRollup} checks={detail.checks} variant="count" - render={} + render={} /> ) : null} {watchControl("icon")} diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx index 253c83de3f4db..dfefdedeed529 100644 --- a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx +++ b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx @@ -535,21 +535,17 @@ function WorkEntryLogRow(props: WorkEntryRowProps) { !toolIconAcceptsTint(entryToolIcon) ? ( ) : null} + {canExpandProjectedItem ? ( + + + + ) : null} - - - } > diff --git a/apps/web/src/components/chat/composerAttachmentFiles.ts b/apps/web/src/components/chat/composerAttachmentFiles.ts index 96575d393018e..f613b695ffd51 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.ts @@ -61,6 +61,28 @@ export function normalizeComposerImageFileMimeType(file: File): File { }); } +export function composerImageDedupKey( + image: Pick, +): string { + // Hydrated images get fresh lastModified values, so exclude it from dedupe. + return `${image.mimeType}\u0000${image.sizeBytes}\u0000${image.name}`; +} + +// Compression changes an image's bytes, so a compressed image answers for the file it came from. +const composerImageSourceKeys = new WeakMap(); + +/** The draft store's image dedupe key, taken from the file as pasted rather than as compressed. */ +export function composerImageSourceKey(file: File): string { + return ( + composerImageSourceKeys.get(file) ?? + composerImageDedupKey({ mimeType: file.type, sizeBytes: file.size, name: file.name || "image" }) + ); +} + +export function rememberComposerImageSource(source: File, prepared: File): void { + if (prepared !== source) composerImageSourceKeys.set(prepared, composerImageSourceKey(source)); +} + function isDngFile(file: Pick): boolean { const mimeType = file.type.split(";", 1)[0]?.trim().toLowerCase(); return ( diff --git a/apps/web/src/components/chat/composerFocusRedirect.ts b/apps/web/src/components/chat/composerFocusRedirect.ts index f7730b367925e..cb187e73ea6a7 100644 --- a/apps/web/src/components/chat/composerFocusRedirect.ts +++ b/apps/web/src/components/chat/composerFocusRedirect.ts @@ -59,6 +59,18 @@ function isSurfaceLauncherKey(event: KeyboardEvent): boolean { return key !== null && (launcherKeys?.includes(key) ?? false); } +function isKeyClaimedInPath(event: KeyboardEvent): boolean { + if (event.shiftKey) return false; + const key = event.key.toUpperCase(); + return event + .composedPath() + .some( + (target) => + target instanceof Element && + (target.getAttribute("aria-keyshortcuts")?.split(/\s+/).includes(key) ?? false), + ); +} + export function shouldRedirectInputToComposer(event: Event): boolean { if (event.defaultPrevented) return false; // Never persist or send secret-request typing through the composer. @@ -66,6 +78,7 @@ export function shouldRedirectInputToComposer(event: Event): boolean { if (eventPathContainsSelector(event, TYPE_TO_FOCUS_EDITABLE_SELECTOR)) return false; if (eventPathContainsSelector(event, TYPE_TO_FOCUS_INTERACTIVE_SELECTOR)) return false; if (document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR)) return false; + if (document.querySelector('[data-chat-column-maximized-away="true"]')) return false; return true; } @@ -75,6 +88,7 @@ export function shouldTypeToFocusComposer(event: KeyboardEvent): boolean { if (event.key.length !== 1) return false; if (!shouldRedirectInputToComposer(event)) return false; if (isSurfaceLauncherKey(event)) return false; + if (isKeyClaimedInPath(event)) return false; return true; } diff --git a/apps/web/src/components/chat/preparingComposerImages.ts b/apps/web/src/components/chat/preparingComposerImages.ts index 4ba7696a1789a..def7f023e8612 100644 --- a/apps/web/src/components/chat/preparingComposerImages.ts +++ b/apps/web/src/components/chat/preparingComposerImages.ts @@ -5,6 +5,8 @@ export interface PreparingComposerImage { readonly name: string; /** The uncompressed source, thumbnailed so the placeholder shows the image itself. */ readonly file: File; + /** Looks like an image the draft already has: it holds its slot but shows no tile. */ + readonly hidden: boolean; } const NO_PREPARING_IMAGES: ReadonlyArray = []; @@ -24,8 +26,14 @@ export function usePreparingComposerImages(targetKey: string) { ); } +export function getPreparingComposerImages( + targetKey: string, +): ReadonlyArray { + return usePreparingComposerImageStore.getState().byTargetKey[targetKey] ?? NO_PREPARING_IMAGES; +} + export function countPreparingComposerImages(targetKey: string): number { - return usePreparingComposerImageStore.getState().byTargetKey[targetKey]?.length ?? 0; + return getPreparingComposerImages(targetKey).length; } export function addPreparingComposerImages( diff --git a/apps/web/src/components/chat/useComposerAttachmentIntake.browser.test.tsx b/apps/web/src/components/chat/useComposerAttachmentIntake.browser.test.tsx new file mode 100644 index 0000000000000..cfacb19bc4101 --- /dev/null +++ b/apps/web/src/components/chat/useComposerAttachmentIntake.browser.test.tsx @@ -0,0 +1,125 @@ +import { useEffect } from "react"; +import { ThreadId } from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; + +import { act, render } from "../../../test/render"; +import { + type ComposerImageAttachment, + DraftId, + useComposerDraftStore, +} from "../../composerDraftStore"; +import { getPreparingComposerImages } from "./preparingComposerImages"; +import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake"; + +const compression = vi.hoisted(() => ({ prepare: vi.fn() })); +vi.mock("../../lib/imageCompression", async (importOriginal) => ({ + ...(await importOriginal()), + prepareImageForAttachment: compression.prepare, +})); + +type IntakeInput = Parameters[0]; +type Intake = ReturnType; + +function Harness({ input, ready }: { input: IntakeInput; ready: (value: Intake) => void }) { + const intake = useComposerAttachmentIntake(input); + useEffect(() => ready(intake)); + return null; +} + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((fulfill) => { + resolve = fulfill; + }); + return { promise, resolve }; +} + +// A clipboard image arrives as a new File named image.png on every paste. +const pastedImage = (fill = 0) => + new File([new Uint8Array(100).fill(fill)], "image.png", { type: "image/png" }); +// Compression shrinks an image, so the draft's copy no longer matches the pasted bytes; images +// with different pixels compress to different sizes. +const compress = async (source: File) => { + const [firstByte = 0] = new Uint8Array(await source.arrayBuffer()); + return { + ok: true as const, + file: new File([new Uint8Array(60 + firstByte)], "image.png", { type: "image/png" }), + recompressed: true as const, + }; +}; +const visiblePreparing = (targetKey: string) => + getPreparingComposerImages(targetKey).filter((image) => !image.hidden); + +it("prepares a repeated paste without a tile, and still keeps a different image", async () => { + const target = DraftId.make("intake-repeat-paste"); + const store = useComposerDraftStore.getState(); + using _draft = { [Symbol.dispose]: () => store.clearComposerContent(target) }; + const firstCompression = deferred(); + compression.prepare + .mockReset() + .mockImplementationOnce(async (file: File) => { + await firstCompression.promise; + return compress(file); + }) + .mockImplementation(compress); + const composerImagesRef = { current: [] as ComposerImageAttachment[] }; + const addImages = (images: ComposerImageAttachment[]) => { + const ids = store.addImages(target, images); + composerImagesRef.current = + useComposerDraftStore.getState().getComposerDraft(target)?.images ?? []; + return ids; + }; + const input = { + activeThreadId: ThreadId.make("thread"), + activePendingProgress: null, + activePendingIsResponding: false, + pendingUserInputs: [], + supportsQuestionAttachments: false, + isLiteralPendingAnswer: false, + projectSelectionRequired: false, + questionAttachmentTarget: null, + attachmentTargetKey: target, + fileStagingLimit: null, + promptRef: { current: "" }, + composerImagesRef, + composerFilesRef: { current: [] }, + composerEditorRef: { current: null }, + isRevertingCheckpointRef: { current: false }, + setThreadError: () => {}, + countReservedAttachments: () => + composerImagesRef.current.length + getPreparingComposerImages(target).length, + addComposerImage: (image) => addImages([image]), + addComposerImagesToDraft: addImages, + addComposerFilesToDraft: () => [], + removeComposerImageFromDraft: () => {}, + insertAttachmentReferences: () => false, + } satisfies IntakeInput; + let intake!: Intake; + await using _screen = await render( + { + intake = value; + }} + />, + ); + + const first = intake.addComposerAttachments([pastedImage()]); + const whileCompressing = intake.addComposerAttachments([pastedImage()]); + expect(visiblePreparing(target)).toHaveLength(1); + await act(async () => { + firstCompression.resolve(); + await Promise.all([first, whileCompressing]); + }); + + const afterCompression = intake.addComposerAttachments([pastedImage()]); + expect(visiblePreparing(target)).toHaveLength(0); + await act(() => afterCompression); + expect(composerImagesRef.current).toHaveLength(1); + + // Same name, type and size, different pixels: it compresses differently and is kept. + const different = intake.addComposerAttachments([pastedImage(7)]); + expect(visiblePreparing(target)).toHaveLength(0); + await act(() => different); + expect(composerImagesRef.current).toHaveLength(2); +}); diff --git a/apps/web/src/components/chat/useComposerAttachmentIntake.ts b/apps/web/src/components/chat/useComposerAttachmentIntake.ts index fe3a56a392203..a4e542b1cbe66 100644 --- a/apps/web/src/components/chat/useComposerAttachmentIntake.ts +++ b/apps/web/src/components/chat/useComposerAttachmentIntake.ts @@ -26,7 +26,9 @@ import { import { classifyComposerAttachmentFile, composerFileAttachmentMimeType, + composerImageSourceKey, normalizeComposerImageFileMimeType, + rememberComposerImageSource, } from "./composerAttachmentFiles"; import { fileAttachmentTooLargeMessage, @@ -48,6 +50,7 @@ import { toastManager } from "../ui/toast"; import { type RefObject, useRef } from "react"; import { addPreparingComposerImages, + getPreparingComposerImages, isPreparingComposerImage, removePreparingComposerImages, } from "./preparingComposerImages"; @@ -241,13 +244,21 @@ export function useComposerAttachmentIntake(input: { } if (acceptedImages.length === 0) return insertedAny; + // The store drops a repeated image only after compressing it, so a likely repeat prepares + // without a tile instead of flashing one. Only the store decides it is a duplicate. + const imageSourceKeys = new Set( + [...composerImagesRef.current, ...getPreparingComposerImages(attachmentTargetKey)].map( + (image) => composerImageSourceKey(image.file), + ), + ); // The draft image reuses its placeholder's id and thumbnail so the strip tile stays exactly // as it is when the compressed file replaces it. - const preparingImages = acceptedImages.map((file) => ({ - id: randomUUID(), - name: file.name || "image", - file, - })); + const preparingImages = acceptedImages.map((file) => { + const sourceKey = composerImageSourceKey(file); + const hidden = imageSourceKeys.has(sourceKey); + imageSourceKeys.add(sourceKey); + return { id: randomUUID(), name: file.name || "image", file, hidden }; + }); addPreparingComposerImages(attachmentTargetKey, preparingImages); if (questionAttachmentTarget) changeQuestionAttachmentPreparation(questionAttachmentTarget, acceptedImages.length); @@ -272,7 +283,8 @@ export function useComposerAttachmentIntake(input: { ); continue; } - inheritComposerImageThumbnail(file, result.file); + await inheritComposerImageThumbnail(file, result.file); + rememberComposerImageSource(file, result.file); compressed.push({ id, file: result.file }); } const questionDiscarded = diff --git a/apps/web/src/components/chat/useThreadLifecycle.tsx b/apps/web/src/components/chat/useThreadLifecycle.tsx index c0b9baec3111c..66b2a9f6b3fd3 100644 --- a/apps/web/src/components/chat/useThreadLifecycle.tsx +++ b/apps/web/src/components/chat/useThreadLifecycle.tsx @@ -49,6 +49,7 @@ import { useUiStateStore } from "../../uiStateStore"; import { type ChatMessage, DEFAULT_INTERACTION_MODE } from "../../types"; import { AlarmClockIcon, CheckCircle2Icon } from "lucide-react"; import { stackedThreadToast, toastManager } from "../ui/toast"; +import { titleRegenerationToast } from "../threadTitleRegenerationToast"; import { newMessageId } from "~/lib/utils"; import { buildThreadRouteParams } from "../../threadRoutes"; import { composerDraftHasUserContent, useComposerDraftStore } from "../../composerDraftStore"; @@ -186,6 +187,9 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) { const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, { reportFailure: false, }); + const regenerateThreadTitle = useOrchestrationCommand(threadEnvironment.regenerateTitle, { + reportFailure: false, + }); const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, { reportFailure: false, }); @@ -688,10 +692,13 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) { if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false; if (!activeThreadShell || !activeThreadRef || !serverConfigLoaded) return; if (activeThreadShell.titleRegeneration != null) return; - void updateThreadMetadata({ + void regenerateThreadTitle({ environmentId: activeThreadRef.environmentId, - input: { threadId: activeThreadRef.threadId, regenerateTitle: true }, - }).then(toastThreadActionFailure("Failed to regenerate thread title")); + input: { threadId: activeThreadRef.threadId }, + }).then((result) => { + const toast = titleRegenerationToast([result]); + if (toast) toastManager.add(toast); + }); }, } satisfies ChatShortcutCommands; return { diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index a83cea59311e2..72683a255e3c8 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -931,10 +931,13 @@ describe("standalone Mermaid previews", () => { .spyOn(HTMLImageElement.prototype, "src", "set") .mockImplementation(() => {}); await using screen = await render(); - await vi.waitFor(() => - expect(screen.container.querySelector('[role="alert"]')?.textContent).toContain( - "Show Mermaid source", - ), + // The first case loads the Mermaid viewer chunk, which can take over a second on a slow runner. + await vi.waitFor( + () => + expect(screen.container.querySelector('[role="alert"]')?.textContent).toContain( + "Show Mermaid source", + ), + { timeout: 10_000 }, ); expect(imageSource).not.toHaveBeenCalled(); expect(screen.container.querySelector("svg")).toBeNull(); diff --git a/apps/web/src/components/files/ReadOnlySourcePreview.browser.test.tsx b/apps/web/src/components/files/ReadOnlySourcePreview.browser.test.tsx new file mode 100644 index 0000000000000..3547540e8d72a --- /dev/null +++ b/apps/web/src/components/files/ReadOnlySourcePreview.browser.test.tsx @@ -0,0 +1,67 @@ +import type { ReactNode } from "react"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { userEvent } from "vite-plus/test/browser"; +import "~/index.css"; + +import { render } from "../../../test/render"; + +import { getSyntaxHighlighterPromise } from "~/lib/syntaxHighlighting"; + +// The pool starts its workers before showing any code, which can outlast a cold CI browser. +vi.mock(import("~/components/DiffWorkerPoolProvider"), () => ({ + DiffWorkerPoolProvider: ({ children }: { children?: ReactNode }) => <>{children}, +})); + +import ReadOnlySourcePreview from "./ReadOnlySourcePreview"; + +const LINE_COUNT = 301; +const text = `${Array.from({ length: LINE_COUNT }, (_, index) => `line ${index + 1}`).join("\n")}\n`; + +// The browser ignores a copy event's data unless the event is cancelled, and copies the selection itself. +function copiedText(target: Element) { + const clipboardData = new DataTransfer(); + const handled = !target.dispatchEvent( + new ClipboardEvent("copy", { clipboardData, bubbles: true, cancelable: true, composed: true }), + ); + return handled ? clipboardData.getData("text/plain") : null; +} + +describe("ReadOnlySourcePreview", () => { + it("copies the whole file after Select All, wherever the preview is scrolled", async () => { + // File paints nothing until the shared highlighter has loaded; once it has, mount renders synchronously. + await getSyntaxHighlighterPromise("text"); + await using screen = await render( +
+ +
, + ); + const root = screen.container.querySelector("diffs-container")!.shadowRoot!; + const rows = () => root.querySelectorAll("[data-line]"); + await vi.waitFor(() => expect(rows()[0]?.textContent).toBe("line 1")); + // Only rows near the viewport are mounted, so the browser's own copy would stop there. + expect(rows().length).toBeLessThan(LINE_COUNT); + + await userEvent.click(rows()[0]!); + await userEvent.keyboard("{ControlOrMeta>}a{/ControlOrMeta}"); + expect(copiedText(rows()[0]!)).toBe(text); + + const scroller = screen.container.querySelector(".file-preview-virtualizer")!; + scroller.scrollTop = scroller.scrollHeight; + await vi.waitFor(() => expect(rows()[0]?.textContent).not.toBe("line 1")); + expect(copiedText(rows()[0]!)).toBe(text); + + document.getSelection()!.removeAllRanges(); + await userEvent.click(rows()[rows().length - 1]!); + await userEvent.keyboard("{ControlOrMeta>}a{/ControlOrMeta}"); + expect(copiedText(rows()[0]!)).toBe(text); + + // A selection that stops inside the mounted rows at either end stays the browser's to copy. + const pre = root.querySelector("pre")!; + const firstText = rows()[0]!.querySelector("span")!.firstChild!; + const lastText = rows()[rows().length - 1]!.querySelector("span")!.firstChild!; + document.getSelection()!.setBaseAndExtent(pre, 0, lastText, 4); + expect(copiedText(rows()[0]!)).toBeNull(); + document.getSelection()!.setBaseAndExtent(firstText, 4, pre, pre.childNodes.length); + expect(copiedText(rows()[0]!)).toBeNull(); + }); +}); diff --git a/apps/web/src/components/files/ReadOnlySourcePreview.tsx b/apps/web/src/components/files/ReadOnlySourcePreview.tsx index 2fdfe04a238d6..453fc26ecc6ad 100644 --- a/apps/web/src/components/files/ReadOnlySourcePreview.tsx +++ b/apps/web/src/components/files/ReadOnlySourcePreview.tsx @@ -1,4 +1,5 @@ import { File, type FileOptions, Virtualizer } from "@pierre/diffs/react"; +import type { ClipboardEvent } from "react"; import { DiffWorkerPoolProvider } from "~/components/DiffWorkerPoolProvider"; import { useClientSettings } from "~/hooks/useSettings"; @@ -8,6 +9,31 @@ import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting"; import { FILE_LINK_REVEAL_UNSAFE_CSS } from "./fileSurfaceChrome"; +/** Select All spans the file's shadow tree, where the virtualizer mounts only rows near the viewport. */ +function selectsEveryMountedRow(root: ShadowRoot) { + const rows = root.querySelectorAll("[data-line]"); + const first = rows[0]; + const last = rows[rows.length - 1]; + if (!first || !last) return false; + try { + const selected = document.getSelection()?.getComposedRanges({ shadowRoots: [root] })[0]; + if (!selected) return false; + if (!root.contains(selected.startContainer) || !root.contains(selected.endContainer)) { + return false; + } + const range = document.createRange(); + range.setStart(selected.startContainer, selected.startOffset); + range.setEnd(selected.endContainer, selected.endOffset); + // A dragged selection ends inside rows, so it never holds a row's own boundaries. + return ( + range.comparePoint(first, 0) === 0 && range.comparePoint(last, last.childNodes.length) === 0 + ); + } catch { + // Engines without composed ranges keep their own copy. + return false; + } +} + export default function ReadOnlySourcePreview(props: { readonly name: string; readonly text: string; @@ -19,31 +45,39 @@ export default function ReadOnlySourcePreview(props: { const resolvedTheme = useRenderedAppearance(); const defaultWordWrap = useClientSettings((settings) => settings.wordWrap); const wordWrap = props.wordWrap ?? defaultWordWrap; + const copyWholeFile = (event: ClipboardEvent) => { + const root = event.currentTarget.querySelector("diffs-container")?.shadowRoot; + if (!root || !selectsEveryMountedRow(root)) return; + event.clipboardData.setData("text/plain", props.text); + event.preventDefault(); + }; return ( - - - +
+ + + +
); } diff --git a/apps/web/src/components/files/office/Spreadsheet.tsx b/apps/web/src/components/files/office/Spreadsheet.tsx index 88e7d085b6d4c..eaae7533b7b5b 100644 --- a/apps/web/src/components/files/office/Spreadsheet.tsx +++ b/apps/web/src/components/files/office/Spreadsheet.tsx @@ -34,6 +34,7 @@ import { type Painted, } from "./sheet-paint"; import { externalUrl } from "./links"; +import { bufferedViewport, cachedViewport, retainCachedViewport } from "./sheet-viewport"; const isSupersededError = Schema.is(SupersededError); @@ -164,6 +165,8 @@ function SpreadsheetGrid(props: { const scroller = useRef(null); const canvas = useRef(null); const spacer = useRef(null); + const columnHeaderBand = useRef(null); + const rowHeaderBand = useRef(null); const [notice, setNotice] = useState(""); const [reader, setReader] = useState<{ row: number; col: number; text: string }[]>([]); const [active, setActive] = useState({ row: 0, col: 0 }); @@ -177,11 +180,15 @@ function SpreadsheetGrid(props: { const root = scroller.current; const target = canvas.current; const space = spacer.current; - if (!root || !target || !space) return; + const columns = columnHeaderBand.current; + const rows = rowHeaderBand.current; + if (!root || !target || !space || !columns || !rows) return; const context = target.getContext("2d"); if (!context) return; const controller = new AbortController(); - const info = layout.info; + let info = layout.info; + let chartWidth = layout.chartWidth; + let chartHeight = layout.chartHeight; const sheet = info.activeSheet; const frozen = { rows: info.frozenRows, cols: info.frozenCols }; const headers = { width: 44, height: headerHeight }; @@ -193,11 +200,23 @@ function SpreadsheetGrid(props: { let sent = 0; let received = 0; let drag = false; + let resizing: + | { + axis: "row" | "column"; + pointerId: number; + index: number; + start: number; + edge: number; + delta: number; + } + | undefined; + let resizingPending = false; let header: "row" | "column" | "all" | undefined; let pressed: { row: number; col: number } | undefined; let end: { x: number; y: number } | undefined; let left = info.initialScrollX; let top = info.initialScrollY; + let drawn = { x: left, y: top }; let reachX = 0; let reachY = 0; let readController: AbortController | undefined; @@ -216,12 +235,11 @@ function SpreadsheetGrid(props: { const resizeArea = () => { const width = Math.min( (end?.x ?? Infinity) + (painted?.frame.frozen.width ?? 0), - Math.max(info.contentWidth, layout.chartWidth, reachX, left + root.clientWidth) + - root.clientWidth, + Math.max(info.contentWidth, chartWidth, reachX, left + root.clientWidth) + root.clientWidth, ); const height = Math.min( (end?.y ?? Infinity) + (painted?.frame.frozen.height ?? 0), - Math.max(info.contentHeight, layout.chartHeight, reachY, top + root.clientHeight) + + Math.max(info.contentHeight, chartHeight, reachY, top + root.clientHeight) + root.clientHeight, ); space.style.width = `${headers.width + width}px`; @@ -233,9 +251,13 @@ function SpreadsheetGrid(props: { const height = root.clientHeight; const size = { width: width - headers.width, height: height - headers.height }; if (size.width <= 0 || size.height <= 0) return; + columns.style.width = `${size.width}px`; + rows.style.height = `${size.height}px`; left = root.scrollLeft; top = root.scrollTop; resizeArea(); + const viewport = { x: left, y: top, ...size }; + drawn = painted ? cachedViewport(painted.frame.viewport, viewport) : viewport; const input: SheetFrameRequest = { sheet, x: left, @@ -243,10 +265,18 @@ function SpreadsheetGrid(props: { ...size, ratio, offset: { x: 0, y: 0 }, - wider: undefined, + wider: bufferedViewport(viewport), }; const key = JSON.stringify(input); - if (key !== requested) { + const needsFrame = + !painted || + requested === "" || + drawn.x !== left || + drawn.y !== top || + painted.request.width !== size.width || + painted.request.height !== size.height || + painted.request.ratio !== ratio; + if (needsFrame && key !== requested) { requested = key; sent += 1; const order = sent; @@ -259,9 +289,23 @@ function SpreadsheetGrid(props: { } received = order; if (!reply) { + if (requested === key) requested = ""; setNotice("These cells could not be drawn. Try scrolling to another area."); return; } + if ( + painted && + retainCachedViewport(painted.frame.viewport, reply.viewport, { + x: root.scrollLeft, + y: root.scrollTop, + width: root.clientWidth - headers.width, + height: root.clientHeight - headers.height, + }) + ) { + reply.bitmap.close(); + if (requested === key) requested = JSON.stringify(painted.request); + return; + } setNotice(""); painted?.frame.bitmap.close(); painted = { request: input, frame: reply }; @@ -269,8 +313,10 @@ function SpreadsheetGrid(props: { schedule(); }) .catch((cause: unknown) => { - if (!isSupersededError(cause) && !controller.signal.aborted) + if (!isSupersededError(cause) && !controller.signal.aborted) { + if (requested === key) requested = ""; setNotice("These cells could not be drawn."); + } }); } if ( @@ -287,12 +333,12 @@ function SpreadsheetGrid(props: { context.fillRect(0, 0, target.width, target.height); return; } - paintCells(context, painted, { ratio, headers, x: left, y: top, ...size }); + paintCells(context, painted, { ratio, headers, ...drawn, ...size }); grid = painted.frame.grid && shiftGrid(painted.frame.grid, frozen, painted.frame.frozen, { - x: painted.frame.viewport.x - left, - y: painted.frame.viewport.y - top, + x: painted.frame.viewport.x - drawn.x, + y: painted.frame.viewport.y - drawn.y, }); if (!grid) return; const anchor = selection.anchor; @@ -308,6 +354,24 @@ function SpreadsheetGrid(props: { ), }); paintHeaders(context, { grid, ratio, headers, width, height, selected: range() }); + if (resizing) { + const edge = resizing.edge + resizing.delta; + context.save(); + context.setTransform(ratio, 0, 0, ratio, 0, 0); + context.strokeStyle = "#217346"; + context.lineWidth = 1; + context.setLineDash([4, 3]); + context.beginPath(); + if (resizing.axis === "column") { + context.moveTo(edge + headers.width, 0); + context.lineTo(edge + headers.width, height); + } else { + context.moveTo(0, edge + headers.height); + context.lineTo(width, edge + headers.height); + } + context.stroke(); + context.restore(); + } }; const read = () => { const focus = selection.focus; @@ -382,8 +446,8 @@ function SpreadsheetGrid(props: { const frame = painted?.frame; if ( frame && - ((x >= frame.frozen.width && x < frame.frozen.width + frame.viewport.x - left) || - (y >= frame.frozen.height && y < frame.frozen.height + frame.viewport.y - top)) + ((x >= frame.frozen.width && x < frame.frozen.width + frame.viewport.x - drawn.x) || + (y >= frame.frozen.height && y < frame.frozen.height + frame.viewport.y - drawn.y)) ) return; const cell = cellAtPoint( @@ -393,8 +457,44 @@ function SpreadsheetGrid(props: { ); return cell ? { cell, x, y } : undefined; }; + const resizeHit = (event: PointerEvent) => { + if (!grid || resizingPending) return; + const rect = target.getBoundingClientRect(); + const x = event.clientX - rect.left - headers.width; + const y = event.clientY - rect.top - headers.height; + const axis: "row" | "column" | undefined = + x >= 0 && y < 0 ? "column" : y >= 0 && x < 0 ? "row" : undefined; + if (!axis) return; + const offsets = axis === "column" ? grid.colOffsets : grid.rowOffsets; + const indices = axis === "column" ? grid.colIndices : grid.rowIndices; + const start = axis === "column" ? grid.startCol : grid.startRow; + const point = axis === "column" ? x : y; + for (let i = 1; i < offsets.length; i++) { + const edge = offsets[i]!; + const size = edge - offsets[i - 1]!; + if (edge > 0 && size > 0 && Math.abs(point - edge) <= 4) + return { + axis, + pointerId: event.pointerId, + index: indices?.[i - 1] ?? start + i - 1, + start: axis === "column" ? event.clientX : event.clientY, + delta: 0, + edge, + } satisfies NonNullable; + } + }; const pointerDown = (event: PointerEvent) => { - if (event.button !== 0) return; + if (event.button !== 0 || resizingPending || resizing) return; + const track = resizeHit(event); + if (track) { + event.preventDefault(); + root.focus({ preventScroll: true }); + root.setPointerCapture(event.pointerId); + resizing = track; + pressed = undefined; + schedule(); + return; + } const found = hit(event); if (!found) return; root.focus({ preventScroll: true }); @@ -417,6 +517,15 @@ function SpreadsheetGrid(props: { else select(event.shiftKey ? extendTo(selection, found.cell) : at(found.cell)); }; const pointerMove = (event: PointerEvent) => { + if (resizing) { + if (event.pointerId !== resizing.pointerId) return; + const point = resizing.axis === "column" ? event.clientX : event.clientY; + resizing.delta = Math.round(point - resizing.start); + schedule(); + return; + } + const hovered = resizeHit(event); + root.style.cursor = hovered ? (hovered.axis === "column" ? "col-resize" : "row-resize") : ""; if (!drag) return; const found = hit(event); if (found && header !== "all") @@ -428,6 +537,44 @@ function SpreadsheetGrid(props: { ); }; const pointerUp = (event: PointerEvent) => { + if (resizing) { + if (event.pointerId !== resizing.pointerId) return; + const track = resizing; + resizing = undefined; + root.style.cursor = ""; + root.releasePointerCapture(event.pointerId); + schedule(); + if (track.delta === 0) return; + resizingPending = true; + setNotice("Resizing preview..."); + void engine + .call( + "resize", + { sheet, axis: track.axis, index: track.index, delta: track.delta }, + { signal: controller.signal }, + ) + .then((nextLayout) => { + if (controller.signal.aborted) return; + info = nextLayout.info; + chartWidth = nextLayout.chartWidth; + chartHeight = nextLayout.chartHeight; + painted?.frame.bitmap.close(); + painted = undefined; + grid = undefined; + sent += 1; + received = sent; + requested = ""; + end = undefined; + schedule(); + }) + .catch(() => { + if (!controller.signal.aborted) setNotice("This row or column could not be resized."); + }) + .finally(() => { + resizingPending = false; + }); + return; + } drag = false; const found = hit(event); if (!found || !pressed || found.cell.row !== pressed.row || found.cell.col !== pressed.col) @@ -480,6 +627,13 @@ function SpreadsheetGrid(props: { }); }; const key = (event: KeyboardEvent) => { + if (event.key === "Escape" && resizing) { + event.preventDefault(); + resizing = undefined; + root.style.cursor = ""; + schedule(); + return; + } const command = event.ctrlKey || event.metaKey; if (command && event.key.toLowerCase() === "c") { event.preventDefault(); @@ -503,8 +657,16 @@ function SpreadsheetGrid(props: { ); reveal(); }; - const cancel = () => { + const cancel = (event: PointerEvent) => { + if (resizing && event.pointerId !== resizing.pointerId) return; drag = false; + pressed = undefined; + resizing = undefined; + root.style.cursor = ""; + schedule(); + }; + const leave = () => { + if (!drag && !resizing) root.style.cursor = ""; }; root.addEventListener("scroll", schedule); root.addEventListener("keydown", key); @@ -512,6 +674,8 @@ function SpreadsheetGrid(props: { root.addEventListener("pointermove", pointerMove); root.addEventListener("pointerup", pointerUp); root.addEventListener("pointercancel", cancel); + root.addEventListener("lostpointercapture", cancel); + root.addEventListener("pointerleave", leave); const unobserve = observeResize(root, schedule); window.addEventListener("resize", schedule); resizeArea(); @@ -535,6 +699,8 @@ function SpreadsheetGrid(props: { root.removeEventListener("pointermove", pointerMove); root.removeEventListener("pointerup", pointerUp); root.removeEventListener("pointercancel", cancel); + root.removeEventListener("lostpointercapture", cancel); + root.removeEventListener("pointerleave", leave); }; }, [engine, layout, initialCell]); return ( @@ -559,6 +725,8 @@ function SpreadsheetGrid(props: { />