diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e2f87694..09bec8e9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -102,6 +102,17 @@ jobs: - name: Test run: cargo test --all + - name: Test actual GodPrompt 1.0.3 to 1.1.1 hot reload and rollback + env: + CODEXIFY_CANARY_OLD_GODPROMPT: ${{ runner.temp }}/godprompt-old/node_modules/god-prompt-mcp/dist/stdio.js + CODEXIFY_CANARY_NEW_GODPROMPT: ${{ runner.temp }}/godprompt-new/node_modules/god-prompt-mcp/dist/stdio.js + run: | + npm install --prefix "$RUNNER_TEMP/godprompt-old" --no-save --no-package-lock --ignore-scripts --no-audit --no-fund god-prompt-mcp@1.0.3 + npm install --prefix "$RUNNER_TEMP/godprompt-new" --no-save --no-package-lock --ignore-scripts --no-audit --no-fund god-prompt-mcp@1.1.1 + test -f "$CODEXIFY_CANARY_OLD_GODPROMPT" + test -f "$CODEXIFY_CANARY_NEW_GODPROMPT" + cargo test --locked --lib service_local_godprompt_candidate_upgrade_and_failed_rollback -- --nocapture + - name: Test Rust and TypeScript browser companion contract env: CODEXIFY_TEST_BROWSER_COMPANION_BUN: ${{ steps.browser-bun.outputs.bun-path }} diff --git a/.github/workflows/perchat-integration-validation.yml b/.github/workflows/perchat-integration-validation.yml new file mode 100644 index 00000000..6b4a46b2 --- /dev/null +++ b/.github/workflows/perchat-integration-validation.yml @@ -0,0 +1,44 @@ +name: Scoped Playwright and hot-reload integration checks + +on: + push: + branches: + - fix/per-chat-playwright-hotreload-20261122 + paths: + - .github/workflows/perchat-integration-validation.yml + - src/bridge.rs + - src/bridge/** + - src/playwright_sessions.rs + - src/mcp_catalog.rs + - src/upstream_control.rs + +permissions: + contents: read + +env: + CARGO_TERM_COLOR: always + CARGO_PROFILE_TEST_DEBUG: line-tables-only + +jobs: + scoped-ownership: + runs-on: ubuntu-latest + timeout-minutes: 35 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt + - uses: Swatinem/rust-cache@v2 + - uses: actions/setup-node@v4 + with: + node-version: '22' + - name: Rust formatting + run: cargo fmt --all -- --check + - name: Per-task browser session tests + run: | + cargo test --locked --lib playwright_sessions:: -- --test-threads=1 + - name: Hot reload and real two-owner stdio tests + run: | + cargo test --locked --lib bridge::hot_reload_tests:: -- --test-threads=1 diff --git a/.github/workflows/preview-hot-reload-windows.yml b/.github/workflows/preview-hot-reload-windows.yml new file mode 100644 index 00000000..37029728 --- /dev/null +++ b/.github/workflows/preview-hot-reload-windows.yml @@ -0,0 +1,53 @@ +name: Build experimental Codexify hot reload for Windows + +on: + push: + branches: + - feat/per-mcp-hot-reload-20261119 + - fix/per-chat-playwright-hotreload-20261122 + paths: + - .github/workflows/preview-hot-reload-windows.yml + - src/markdown_chat/mod.rs + - src/agent_automation/install.rs + - src/bridge.rs + - src/bridge/** + - src/mcp_catalog.rs + - src/playwright_sessions.rs + +permissions: + contents: read + +jobs: + preview-windows: + name: Package pinned Windows feature binary + runs-on: windows-latest + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - name: Build from exact branch commit + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + cargo build --release --locked --bin codexify + if ($LASTEXITCODE -ne 0) { throw 'Cargo build failed' } + $out = Join-Path $env:RUNNER_TEMP 'codexify-hot-reload-preview' + New-Item -ItemType Directory -Force -Path $out | Out-Null + $binary = Join-Path (Get-Location) 'target\release\codexify.exe' + if (!(Test-Path -LiteralPath $binary -PathType Leaf)) { throw 'Expected executable missing' } + Copy-Item -LiteralPath $binary -Destination (Join-Path $out 'codexify.exe') + & (Join-Path $out 'codexify.exe') --help | Out-Null + if ($LASTEXITCODE -ne 0) { throw 'Preview binary self-probe failed' } + $hash = (Get-FileHash -LiteralPath (Join-Path $out 'codexify.exe') -Algorithm SHA256).Hash.ToLowerInvariant() + Set-Content -LiteralPath (Join-Path $out 'SHA256SUMS.txt') -Value ("$hash codexify.exe") -Encoding ascii + Set-Content -LiteralPath (Join-Path $out 'SOURCE_COMMIT.txt') -Value "${{ github.sha }}" -Encoding ascii + Set-Content -LiteralPath (Join-Path $out 'PREVIEW_NOTICE.txt') -Value 'EXPERIMENTAL binary from integration branch PR #12. Not an official release. Activate only after backing up the existing executable; coordinate with other Codexify workers.' -Encoding ascii + - uses: actions/upload-artifact@v4 + with: + name: codexify-pr12-perchat-hotreload-windows-preview + path: ${{ runner.temp }}/codexify-hot-reload-preview/* + if-no-files-found: error + retention-days: 7 diff --git a/.github/workflows/single-lane-v240-ci.yml b/.github/workflows/single-lane-v240-ci.yml new file mode 100644 index 00000000..700fde4f --- /dev/null +++ b/.github/workflows/single-lane-v240-ci.yml @@ -0,0 +1,151 @@ +name: Single-lane v2.4 validation (no deployment) + +on: + push: + branches: [fix/single-lane-v240-stable-20261118, fix/single-lane-v240-goal-parity-20261118, fix/godv5-cloudflare-oauth-meta-v240-20261118] + workflow_dispatch: + +permissions: + contents: read + +jobs: + native-windows: + name: Verify single-lane native and durable goal state + runs-on: windows-latest + timeout-minutes: 120 + defaults: + run: + shell: pwsh + env: + CARGO_BUILD_JOBS: '2' + CARGO_INCREMENTAL: '0' + CARGO_PROFILE_DEV_DEBUG: line-tables-only + CARGO_PROFILE_TEST_DEBUG: line-tables-only + steps: + - uses: actions/checkout@v5 + with: + fetch-depth: 0 + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + - uses: Swatinem/rust-cache@v2 + - name: Bound changes to durability and Windows tests + run: | + $ErrorActionPreference = 'Stop' + $allowed = @('src/agent_automation/store.rs','src/project_clone.rs','src/self_update.rs','src/owner_chat.rs','src/agent_automation/supervisor.rs','src/agent_automation/turn_renewal.rs','src/bridge.rs','.github/workflows/single-lane-v240-ci.yml','docs/SINGLE_LANE_V240_RECOVERY.md') + $upstreamBase = 'b14eacde810531a451535ee546ca7e07c65c5a1d' + git merge-base --is-ancestor $upstreamBase HEAD + if ($LASTEXITCODE -ne 0) { throw 'Branch no longer descends from upstream v2.4.0; rebase required' } + $changed = @(git diff --name-only $upstreamBase HEAD) + if ($LASTEXITCODE -ne 0) { throw 'Failed to inspect commit scope' } + foreach ($file in $changed) { + if ($file -notin $allowed) { throw "Unexpected changed file: $file" } + } + git diff --check $upstreamBase HEAD + if ($LASTEXITCODE -ne 0) { throw 'Whitespace errors' } + rustfmt --check --edition 2024 --config skip_children=true src/agent_automation/store.rs src/project_clone.rs src/self_update.rs src/owner_chat.rs src/agent_automation/supervisor.rs src/agent_automation/turn_renewal.rs src/bridge.rs + if ($LASTEXITCODE -ne 0) { throw 'Rustfmt check failed' } + - name: Validate native source and test compilation + run: | + cargo check --locked --all-targets -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Cargo check failed' } + - name: Reject new Clippy findings relative to pinned upstream v2.4 + run: | + $ErrorActionPreference = 'Stop' + $baselineSha = 'b14eacde810531a451535ee546ca7e07c65c5a1d' + $baselinePath = Join-Path $env:RUNNER_TEMP 'codexify-clippy-upstream-base' + if (Test-Path -LiteralPath $baselinePath) { throw 'Clippy baseline path is not empty' } + git worktree add --detach $baselinePath $baselineSha + if ($LASTEXITCODE -ne 0) { throw 'Failed to open pinned upstream baseline' } + $env:CARGO_TARGET_DIR = Join-Path $env:GITHUB_WORKSPACE 'target' + $baseLog = Join-Path $env:RUNNER_TEMP 'clippy-upstream.jsonl' + $headLog = Join-Path $env:RUNNER_TEMP 'clippy-candidate.jsonl' + try { + Push-Location $baselinePath + try { + cargo clippy --locked --all-targets -j 2 --message-format=json -- -D warnings 1> $baseLog + $baseExit = $LASTEXITCODE + } finally { + Pop-Location + } + cargo clippy --locked --all-targets -j 2 --message-format=json -- -D warnings 1> $headLog + $headExit = $LASTEXITCODE + function Get-FindingCounts { + param([string]$LogPath) + $counts = @{} + foreach ($line in [System.IO.File]::ReadLines($LogPath)) { + if (-not $line.StartsWith('{')) { continue } + try { $entry = $line | ConvertFrom-Json -ErrorAction Stop } catch { continue } + if ($entry.reason -ne 'compiler-message') { continue } + $diagnostic = $entry.message + if ($diagnostic.level -notin @('error', 'warning')) { continue } + $primary = $diagnostic.spans | Where-Object { $_.is_primary } | Select-Object -First 1 + $file = if ($null -ne $primary) { [string]$primary.file_name } else { '' } + $file = $file -replace '\\', '/' + if ($file -match '((?:src|tests|examples)/.*)$') { $file = $Matches[1] } + $code = if ($null -ne $diagnostic.code) { [string]$diagnostic.code.code } else { '' } + $key = "${file}|${code}|$($diagnostic.message)" + $counts[$key] = [int]$counts[$key] + 1 + } + return $counts + } + $upstream = Get-FindingCounts $baseLog + $candidate = Get-FindingCounts $headLog + if ($baseExit -ne 0 -and $upstream.Count -eq 0) { + throw 'Upstream Clippy failed without structured diagnostics; baseline unusable' + } + if ($headExit -ne 0 -and $candidate.Count -eq 0) { + throw 'Candidate Clippy failed without structured diagnostics' + } + $regressions = @() + foreach ($finding in $candidate.GetEnumerator()) { + $increase = $finding.Value - [int]$upstream[$finding.Key] + if ($increase -gt 0) { $regressions += "$($finding.Key) (+$increase)" } + } + Write-Output "Pinned upstream findings: $((@($upstream.Values) | Measure-Object -Sum).Sum)" + Write-Output "Candidate findings: $((@($candidate.Values) | Measure-Object -Sum).Sum)" + if ($regressions.Count -gt 0) { + $regressions | Sort-Object | ForEach-Object { Write-Output "NEW: $_" } + throw 'Candidate introduced Clippy/compiler diagnostic regressions' + } + Write-Output 'No new Clippy diagnostics. Existing upstream warnings are tracked, not claimed resolved.' + } finally { + git worktree remove -- $baselinePath + if ($LASTEXITCODE -ne 0) { Write-Warning 'Ephemeral CI worktree cleanup failed' } + } + - name: Verify Windows locked file and canonical path regressions + run: | + cargo test --locked --lib windows_state_publication_tests -j 2 -- --nocapture + if ($LASTEXITCODE -ne 0) { throw 'State publication test failed' } + cargo test --locked --lib rejects_ambiguous_matching_checkouts -j 2 -- --nocapture + if ($LASTEXITCODE -ne 0) { throw 'Windows path test failed' } + cargo test --locked --lib windows_worker_reports_start_and_completes_a_unicode_file_update -j 2 -- --nocapture + if ($LASTEXITCODE -ne 0) { throw 'Windows status publication test failed' } + cargo test --locked --lib owner_goal_commands_are_authenticated_idempotent_local_and_visible_in_state -j 2 -- --nocapture + if ($LASTEXITCODE -ne 0) { throw 'Goal activation wake test failed' } + cargo test --locked --lib completed_goal_renewal_tests -j 2 -- --nocapture + if ($LASTEXITCODE -ne 0) { throw 'Terminal handoff retirement regression failed' } + cargo test --locked --lib browser_action_lanes_default_to_one_and_are_bounded -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Single browser lane default test failed' } + - name: Run MCP bridge authorization metadata regressions + run: | + cargo test --locked --lib bridge::tests:: -j 2 -- --nocapture + if ($LASTEXITCODE -ne 0) { throw 'MCP authorization bridge tests failed' } + - name: Run full Rust library regression suite + run: | + cargo test --locked --lib -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Full library tests failed' } + - name: Build official-v2.4-based native candidate without installing + run: | + cargo build --locked --release --bin codexify -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Native build failed' } + & .\target\release\codexify.exe --help | Select-Object -First 5 + if ($LASTEXITCODE -ne 0) { throw 'Binary help smoke failed' } + Get-FileHash .\target\release\codexify.exe -Algorithm SHA256 | Format-List | Out-String | Write-Output + - name: Retain reviewed native candidate for one day + uses: actions/upload-artifact@v4 + with: + name: codexify-v240-minimal-single-lane-windows + path: target/release/codexify.exe + if-no-files-found: error + retention-days: 1 diff --git a/.github/workflows/v240-playwright-compatible.yml b/.github/workflows/v240-playwright-compatible.yml new file mode 100644 index 00000000..4eb60bec --- /dev/null +++ b/.github/workflows/v240-playwright-compatible.yml @@ -0,0 +1,80 @@ +name: v2.4 Playwright per-chat Windows candidate (validation only) + +on: + push: + branches: + - fix/v240-playwright-compatible-20261119 + - fix/v240-playwright-parallel-startup-20261119 + - fix/v240-configured-playwright-scope-20261119 + +permissions: + contents: read + +jobs: + windows-candidate: + runs-on: windows-latest + timeout-minutes: 90 + defaults: + run: + shell: pwsh + env: + CARGO_BUILD_JOBS: '2' + CARGO_INCREMENTAL: '0' + CARGO_PROFILE_DEV_DEBUG: line-tables-only + CARGO_PROFILE_TEST_DEBUG: line-tables-only + steps: + - uses: actions/checkout@v5 + with: + fetch-depth: 0 + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt + - uses: Swatinem/rust-cache@v2 + - name: Verify source provenance and formatting + run: | + $ErrorActionPreference = 'Stop' + git merge-base --is-ancestor ef323c124f73396e5c3cdada6f471c4b2783d910 HEAD + if ($LASTEXITCODE -ne 0) { throw 'Missing verified v2.4 OAuth/goal baseline' } + git merge-base --is-ancestor cd4e483 HEAD + if ($LASTEXITCODE -ne 0) { throw 'Missing per-chat Playwright isolation baseline' } + git diff --check ef323c124f73396e5c3cdada6f471c4b2783d910 HEAD + if ($LASTEXITCODE -ne 0) { throw 'Diff whitespace validation failed' } + cargo fmt --all -- --check + if ($LASTEXITCODE -ne 0) { throw 'Rustfmt validation failed' } + - name: Validate all Rust test targets + run: | + cargo check --locked --tests -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Rust test targets do not compile' } + - name: Verify explicit per-chat configuration overlay + run: | + cargo test --locked --lib config::tests::explicit_playwright_session_scope_survives_json_overlay -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Playwright sessionScope was silently downgraded to global' } + cargo test --locked --lib config::tests::explicit_scope_overlay_preserves_or_overrides_imported_scope -j 2 + if ($LASTEXITCODE -ne 0) { throw 'MCP imported scope overlay regression' } + - name: Verify browser ownership and preserved Send gate + run: | + cargo test --locked --lib playwright_sessions::tests -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Per-chat browser ownership regression' } + cargo test --locked --lib provider_send_gate -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Provider Send gate compatibility regression' } + cargo test --locked --lib bridge::tests -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Upstream MCP bridge regression' } + - name: Verify complete v2.4 library suite + run: | + cargo test --locked --lib -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Full library regression suite failed' } + - name: Build official v2.4-based Windows executable + run: | + cargo build --locked --release --bin codexify -j 2 + if ($LASTEXITCODE -ne 0) { throw 'Windows native release build failed' } + & .\target\release\codexify.exe --help | Select-Object -First 5 + if ($LASTEXITCODE -ne 0) { throw 'Built executable is not runnable' } + $sha = (Get-FileHash .\target\release\codexify.exe -Algorithm SHA256).Hash + Write-Output "Verified Windows candidate SHA256: $sha" + - name: Upload reviewable binary without installing + uses: actions/upload-artifact@v4 + with: + name: codexify-v240-playwright-compatible-windows + path: target/release/codexify.exe + if-no-files-found: error + retention-days: 1 diff --git a/.gitignore b/.gitignore index fdeb8f49..548ced1e 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,5 @@ node_modules/ # Source archive drops (reference material, not part of the repo) *.zip /browser-companion/.browsers/ +/browser-companion/dist/ +/browser-companion/artifacts/ diff --git a/browser-companion/scripts/activate-readiness-diagnostic.ps1 b/browser-companion/scripts/activate-readiness-diagnostic.ps1 new file mode 100644 index 00000000..c7e2e6d6 --- /dev/null +++ b/browser-companion/scripts/activate-readiness-diagnostic.ps1 @@ -0,0 +1,108 @@ +# Deploy only the verified Codexify browser ASAR. Never replace the native service or Chrome profile. +$ErrorActionPreference = 'Stop' +$project = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) +$receiptPath = Join-Path $project 'artifacts\runtime-patch-ready.json' +$receipt = Get-Content -LiteralPath $receiptPath -Raw | ConvertFrom-Json +$version = [string]$receipt.version +if ($version -ne '2.4.0') { throw 'Unexpected runtime version' } +$artifactRoot = [IO.Path]::GetFullPath((Join-Path $project 'artifacts')) + [IO.Path]::DirectorySeparatorChar +$candidate = [IO.Path]::GetFullPath([string]$receipt.candidate) +if (-not $candidate.StartsWith($artifactRoot, [StringComparison]::OrdinalIgnoreCase)) { + throw 'Candidate is outside verified project artifact root' +} +$resources = Join-Path $env:USERPROFILE ('.codexify\browser\runtime\' + $version + '\app\resources') +$live = Join-Path $resources 'app.asar' +$exe = Join-Path $env:USERPROFILE '.codexify\bin\codexify.exe' +if (-not (Test-Path -LiteralPath $candidate -PathType Leaf) -or -not (Test-Path -LiteralPath $live -PathType Leaf) -or -not (Test-Path -LiteralPath $exe -PathType Leaf)) { + throw 'Expected candidate, installed archive or CLI missing' +} +function Sha256([string]$path) { return (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant() } +$beforeSha = Sha256 $live +$wantedSha = [string]$receipt.sha256 +if ($beforeSha -ne [string]$receipt.previousSha256 -or (Sha256 $candidate) -ne $wantedSha) { + throw 'Preimage or candidate hash does not match the verified receipt' +} +$stamp = [DateTime]::UtcNow.ToString('yyyyMMddTHHmmssZ') +$backupDir = Join-Path $env:USERPROFILE ('.codexify\backups\browser-readiness-diagnostic-' + $stamp) +[void](New-Item -ItemType Directory -Path $backupDir) +$backup = Join-Path $backupDir 'app.asar.original' +Copy-Item -LiteralPath $live -Destination $backup -ErrorAction Stop +if ((Sha256 $backup) -ne $beforeSha) { throw 'Rollback archive could not be verified' } +function Invoke-CompanionCommand([string]$verb) { + if ($verb -notin @('stop','start')) { throw 'Unsupported companion operation' } + $output = Join-Path $backupDir ($verb + '-stdout.log') + $errors = Join-Path $backupDir ($verb + '-stderr.log') + # The companion may inherit stdout from its launcher. Wait for the launcher + # process, not an open PowerShell pipeline attached to a long-lived browser. + $process = Start-Process -FilePath $exe -ArgumentList @('browser', $verb) -PassThru -WindowStyle Hidden -RedirectStandardOutput $output -RedirectStandardError $errors + if (-not $process.WaitForExit(45000)) { throw ('Companion ' + $verb + ' launcher did not exit') } + # Some Windows PowerShell process wrappers report a null ExitCode even after + # WaitForExit succeeds. Subsequent process/hash/HTTP checks prove the result. + if ($null -ne $process.ExitCode -and [int]$process.ExitCode -ne 0) { + if ($verb -eq 'start') { + # A busy but live companion sometimes returns a nonzero launcher status. + # Accept it only if the *new* private endpoint responds with liveness. + $descriptorFile = Join-Path $env:USERPROFILE '.codexify\browser\descriptor.json' + if (Test-Path -LiteralPath $descriptorFile) { + $descriptor = Get-Content -LiteralPath $descriptorFile -Raw | ConvertFrom-Json + try { + $liveness = Invoke-RestMethod -Uri ($descriptor.endpoint.TrimEnd('/') + '/v1/liveness') -Headers @{ Authorization = 'Bearer ' + $descriptor.token } -TimeoutSec 6 + if ($liveness.available -eq $true) { return } + } catch { } + } + } + throw ('Companion ' + $verb + ' launcher returned a failure') + } +} +$replaced = $false +$oldDesc = Join-Path $env:USERPROFILE '.codexify\browser\descriptor.json' +$oldPid = $null +if (Test-Path -LiteralPath $oldDesc) { + $previous = Get-Content -LiteralPath $oldDesc -Raw | ConvertFrom-Json + $oldPid = $previous.pid + $health = Invoke-RestMethod -Method Get -Uri ($previous.endpoint.TrimEnd('/') + '/v1/health') -Headers @{ Authorization = 'Bearer ' + $previous.token } -TimeoutSec 8 + if ($health.activeActionId -or @($health.activeActionIds).Count -gt 0) { + throw 'A browser action is active; companion replacement deferred' + } +} +Write-Output 'BACKUP_VERIFIED=true' +try { + Invoke-CompanionCommand 'stop' + if ($oldPid) { + for ($i=0;$i -lt 15;$i++) { + if (-not (Get-Process -Id $oldPid -ErrorAction SilentlyContinue)) { break } + Start-Sleep -Milliseconds 500 + } + if (Get-Process -Id $oldPid -ErrorAction SilentlyContinue) { throw 'Old browser companion process did not exit' } + } + $staging = Join-Path $resources ('app.asar.staged-' + $stamp) + Copy-Item -LiteralPath $candidate -Destination $staging -ErrorAction Stop + if ((Sha256 $staging) -ne $wantedSha) { throw 'Staged archive hash mismatch' } + $preimageAtomic = Join-Path $backupDir 'app.asar.atomic-original' + [IO.File]::Replace($staging, $live, $preimageAtomic, $true) + $replaced = $true + if ((Sha256 $live) -ne $wantedSha) { throw 'Installed archive verification failed' } + Invoke-CompanionCommand 'start' + Start-Sleep -Seconds 3 + $descriptor = Get-Content -LiteralPath $oldDesc -Raw | ConvertFrom-Json + $headers = @{ Authorization = 'Bearer ' + $descriptor.token } + $state = Invoke-RestMethod -Method Get -Uri ($descriptor.endpoint.TrimEnd('/') + '/v1/diagnostics/readiness') -Headers $headers -TimeoutSec 8 + Write-Output ('BROWSER_READINESS=' + ($state | ConvertTo-Json -Depth 6 -Compress)) + Write-Output 'INSTALLED_AND_DIAGNOSTIC_VERIFIED=true' + Write-Output ('ROLLBACK_LOCATION=' + $backupDir) +} catch { + Write-Output ('ACTIVATION_FAILED=' + $_.Exception.GetType().Name) + if ($replaced) { + try { + Invoke-CompanionCommand 'stop' + $restore = Join-Path $resources ('app.asar.restore-' + $stamp) + Copy-Item -LiteralPath $backup -Destination $restore -ErrorAction Stop + if ((Sha256 $restore) -ne $beforeSha) { throw 'Rollback archive hash mismatch' } + [IO.File]::Replace($restore, $live, (Join-Path $backupDir 'app.asar.rejected'), $true) + if ((Sha256 $live) -ne $beforeSha) { throw 'Rollback validation failed' } + Write-Output 'ROLLBACK_VERIFIED=true' + } catch { Write-Output ('ROLLBACK_FAILED=' + $_.Exception.GetType().Name) } + } + Invoke-CompanionCommand 'start' + throw +} diff --git a/browser-companion/src/account-settings.ts b/browser-companion/src/account-settings.ts index 2683f885..ab5c92d2 100644 --- a/browser-companion/src/account-settings.ts +++ b/browser-companion/src/account-settings.ts @@ -186,7 +186,48 @@ async function markRefreshButton(page:Page):Promise { async function allowAllChoice(page:Page,signal?:AbortSignal) { const radios=page.locator('[role="radio"],input[type="radio"]').filter({visible:true}); - await radios.first().waitFor({state:"visible",timeout:10_000,signal}); + // Some versions render the permission choices only after opening the + // permission selector. Never guess which other button opens that selector. + if(await observeReadOnly(radios.count(),signal)===0){ + const trigger=page.locator('[data-action="plugin-permissions"],[data-testid="plugin-permission-trigger"]').filter({visible:true}); + if(await observeReadOnly(trigger.count(),signal)===1) { + signal?.throwIfAborted(); + await trigger.click({timeout:3_000,signal}); + } + } + try{ + await radios.first().waitFor({state:"visible",timeout:10_000,signal}); + }catch(error){ + // Browser-side UI compatibility diagnostics, never account contents. This + // records only DOM control counts and fixed permission-option matches. + if(!signal?.aborted){ + try{ + const shape=await observeReadOnly(page.evaluate(()=>{ + const visible=(node:Element)=>node.getClientRects().length>0; + const count=(selector:string)=>[...document.querySelectorAll(selector)].filter(visible).length; + const labels=new Set(["allow all actions","allow all tools","never ask","permitir todo","tout autoriser","consenti tutto","dovoli vsa dejanja"]); + const choices=[...document.querySelectorAll('button,label,span,[role="radio"],[role="option"],[role="menuitemradio"]')].filter(visible) + .filter(node=>node.children.length<=2&&labels.has((node.textContent??"").normalize("NFKC").replace(/\s+/g," ").trim().toLowerCase())); + const path=location.pathname; + return { + pageType:path.endsWith("/permissions")?"permissions":path.includes("/settings/plugins-settings/")?"plugin-settings":"other", + visibleRadios:count('[role="radio"],input[type="radio"]'), + allRadios:document.querySelectorAll('[role="radio"],input[type="radio"]').length, + permissionTriggers:count('[data-action="plugin-permissions"],[data-testid="plugin-permission-trigger"]'), + menuItemRadios:count('[role="menuitemradio"]'), + ariaCheckedControls:count('[aria-checked]'), + ariaSelectedOptions:count('[role="option"][aria-selected]'), + visibleDialogs:count('[role="dialog"]'), + visibleButtons:count('button'), + recognizedAllowAllLabels:choices.length, + recognizedAllowAllSelected:choices.filter(node=>node.getAttribute("aria-checked")==="true"||node.getAttribute("aria-selected")==="true"||node.getAttribute("data-state")==="checked").length, + }; + }),signal,1_500); + console.warn(`[connector-permission-shape] ${JSON.stringify(shape)}`); + }catch{console.warn("[connector-permission-shape] observation unavailable");} + } + throw error; + } if(await observeReadOnly(radios.count(),signal)!==4)throw selectorDrift("ChatGPT permission choices changed; Allow all was not selected"); const choice=radios.nth(3); const checked=()=>observeReadOnly(choice.getAttribute("aria-checked").then(value=>value==="true").then(async value=>value||await choice.isChecked().catch(()=>false)),signal); @@ -242,7 +283,7 @@ export async function identifyConnectorApp(page:Page,connectorName:string,expect return appId; } -async function connectorPage(page:Page,appId:string,account:string,permissions:boolean,signal?:AbortSignal) { +async function connectorPage(page:Page,appId:string,account:string,permissions:boolean,signal?:AbortSignal,reload=false) { signal?.throwIfAborted(); const url=`https://chatgpt.com/settings/plugins-settings/plugin_${appId}${permissions?'/permissions':''}`; const assertPage=async()=>{ @@ -250,7 +291,9 @@ async function connectorPage(page:Page,appId:string,account:string,permissions:b if(new URL(page.url()).origin!=="https://chatgpt.com"||new URL(page.url()).pathname!==new URL(url).pathname)throw selectorDrift("ChatGPT changed the plugin page during connector maintenance"); if((await readChatGptAccount(page,signal)).fingerprint!==account)throw selectorDrift("ChatGPT account changed during connector maintenance"); }; - await navigatePage(page,url,{timeout:30_000,signal}); + // A reload is valid only when this is already the exact target page; on a + // different page, ordinary navigation also produces a fresh document. + await navigatePage(page,url,{timeout:30_000,signal,reload:reload&&page.url()===url}); await assertPage(); return assertPage; } @@ -337,14 +380,24 @@ export async function requestConnectorToolRefresh(page:Page,appId:string,name:st } export async function verifyConnectorAllowAll(page:Page,appId:string,account:string,signal?:AbortSignal):Promise { - await connectorPage(page,appId,account,true,signal); + // Do not count the radio's optimistic checked state as persisted permission. + // A new document must independently confirm the selection on this account. + await connectorPage(page,appId,account,true,signal,true); if(!await (await allowAllChoice(page,signal)).checked())throw selectorDrift("Allow all tools was not confirmed after reloading plugin settings"); } export async function connectorPermissionSummary(page:Page,signal?:AbortSignal):Promise<{summary:string;allowAll:boolean}|null> { - return observeReadOnly(page.evaluate(()=>{ + // These are *selected value* labels, not text to search for anywhere on the + // page: help text can describe an unselected "Allow all" option as well. + const allowAllLabels=[ + "Allow all actions","Allow all tools","Never ask", + "Permitir todo","Tout autoriser","Να επιτρέπονται όλα", + "Consenti tutto","Dovoli vsa dejanja", + ]; + return observeReadOnly(page.evaluate(labels=>{ const candidates=new Set(); - const direct=[...document.querySelectorAll('[data-permission],[data-action="plugin-permissions"],a[href$="/permissions"]')].filter(node=>node.getClientRects().length>0); + const directState=[...document.querySelectorAll('[data-permission],[data-current-permission]')].filter(node=>node.getClientRects().length>0); + const direct=directState.length?directState:[...document.querySelectorAll('[data-action="plugin-permissions"],a[href$="/permissions"]')].filter(node=>node.getClientRects().length>0); for(const node of direct)candidates.add(node); if(!candidates.size)for(const node of document.querySelectorAll('div,section')) { const controls=[...node.querySelectorAll('button,[role="button"]')].filter(button=>button.getClientRects().length>0); @@ -360,15 +413,28 @@ export async function connectorPermissionSummary(page:Page,signal?:AbortSignal): } if(candidates.size!==1)return null; const control=[...candidates][0]!; - return {summary:(control.textContent??'').normalize('NFKC').replace(/\s+/g,' ').trim(),allowAll:control.getAttribute('data-permission')==='allow_all'}; - }),signal); + const summary=(control.textContent??'').normalize('NFKC').replace(/\s+/g,' ').trim(); + const permission=control.getAttribute('data-permission')??control.getAttribute('data-current-permission'); + const leaves:string[]=[]; + const walker=document.createTreeWalker(control,NodeFilter.SHOW_TEXT); + while(walker.nextNode()){ + const text=walker.currentNode.textContent?.normalize('NFKC').replace(/\s+/g,' ').trim(); + if(text&&walker.currentNode.parentElement?.getClientRects().length)leaves.push(text); + } + const selected=leaves.at(-1)?.toLocaleLowerCase('en-US'); + const marked=permission==='allow_all'||permission==='full_access'; + // Explicit non-allow permission metadata always wins over descriptive text. + return {summary,allowAll:marked||(permission===null&&Boolean(selected&&labels.some(label=>label.toLocaleLowerCase('en-US')===selected)))}; + },allowAllLabels),signal); } export type PermissionWitness={summary?:string;remember:(summary:string)=>void}; export async function inspectConnectorSettings(page:Page,appId:string,name:string,account:string,signal?:AbortSignal) { if(!/^asdk_app_[A-Za-z0-9_]{1,128}$/.test(appId))throw selectorDrift("Invalid connector App ID"); traceRefresh("open settings"); - const assertPage=await connectorPage(page,appId,account,false,signal); + // The same URL can still show stale React state after permissions change in + // another ChatGPT tab. Only a fresh document can prove current permissions. + const assertPage=await connectorPage(page,appId,account,false,signal,true); traceRefresh("settings opened"); // The document can finish while settings still shows only a loading shell. // Hydration gets a bounded read inside the coordinator's existing phase @@ -384,19 +450,12 @@ export async function prepareConnectorRefresh(page:Page,name:string,expectedAcco const account=expectedAccountFingerprint??(await readChatGptAccount(page,signal)).fingerprint; const appId=knownAppId??await identifyConnectorApp(page,name,account,signal); const before=await inspectConnectorSettings(page,appId,name,account,signal); - let permissionChanged=false; - if(!before?.allowAll&&(!witness?.summary||before?.summary!==witness.summary)) { - traceRefresh("permission needs selection"); - permissionChanged=await setConnectorAllowAll(page,appId,account,signal); - await connectorPage(page,appId,account,false,signal); - await page.getByText(name,{exact:true}).and(page.locator(':visible')).first().waitFor({state:"visible",timeout:5_000,signal}); - await markRefreshButton(page); - } - const verified=await connectorPermissionSummary(page); - if(verified?.summary)witness?.remember(verified.summary); - traceRefresh("permission allows all"); + // Tool refresh must not change the permission grant. The current UI may + // manage app/account permissions elsewhere or restrict them by policy. + if(before?.allowAll===true&&before.summary)witness?.remember(before.summary); + traceRefresh("refresh tools without changing ChatGPT-managed permissions"); const observation=await beginConnectorToolRefresh(page,appId,name,account,signal); - return {appId,permissionChanged,observation}; + return {appId,permissionChanged:false,observation}; } export async function refreshConnectorTools(page:Page,name:string,expectedAccountFingerprint?:string,signal?:AbortSignal,knownAppId?:string,witness?:PermissionWitness):Promise<{appId:string;refreshObserved:boolean;permissionChanged:boolean;schemaVerified:false}> { diff --git a/browser-companion/src/browser-pool.ts b/browser-companion/src/browser-pool.ts index 26308ddd..7c81512d 100644 --- a/browser-companion/src/browser-pool.ts +++ b/browser-companion/src/browser-pool.ts @@ -5,7 +5,7 @@ import {canonicalChatGptConversationUrl,executeActionRequestSchema,cancelActionR COMPANION_KIND,PROTOCOL_VERSION,type CompanionHealth,type ActionSnapshot,type ExecuteActionRequest} from "./protocol"; type Coordinator = SingleWindowCoordinator; -type Lane = {coordinator:Coordinator;reserved:boolean;lastUsed:number}; +type Lane = {coordinator:Coordinator;reserved:boolean;reservationPurpose:"approval"|"handoff"|"action"|null;lastUsed:number}; type OwnedAction = {lane:Lane;digest:string;key:string;conversation:string}; /** Fixed pages share one private profile, while action state and DOM ownership @@ -20,13 +20,17 @@ export class PooledWindowCoordinator { private dispatchTail:Promise=Promise.resolve(); private maintenance=false; private closed=false; + private nextHandoffEligibleAt=0; - constructor(coordinators:readonly Coordinator[],readonly build:string,private readonly closeContext?:()=>Promise) { + constructor(coordinators:readonly Coordinator[],readonly build:string,private readonly closeContext?:()=>Promise,private readonly handoffGapMs=8_000) { if(coordinators.length<1||coordinators.length>4)throw new Error("Browser action pages must be between one and four"); - this.lanes=coordinators.map(coordinator=>({coordinator,reserved:false,lastUsed:0})); + if(!Number.isInteger(handoffGapMs)||handoffGapMs<0||handoffGapMs>30_000)throw new Error("Invalid browser handoff inspection gap"); + this.lanes=coordinators.map(coordinator=>({coordinator,reserved:false,reservationPurpose:null,lastUsed:0})); } private free(lane:Lane):boolean {return !lane.reserved&&!lane.coordinator.busy;} + /** Keep passive approval monitoring out of an already owned browser lane. */ + get busy():boolean {return this.closed||this.maintenance||this.lanes.some(l=>!this.free(l));} private capacity(health:CompanionHealth,available:number):CompanionHealth { const activeActionIds=this.lanes.map(l=>l.coordinator.ownedActionId).filter((id):id is string=>id!==null); return {...health,actionCapacity:this.lanes.length,availableActionSlots:available,activeActionIds, @@ -49,6 +53,12 @@ export class PooledWindowCoordinator { } health=()=>this.observe(false); readyHealth=()=>this.observe(true); + /** Authenticated local diagnostic; never read a page or expose account details. */ + readinessSnapshot() { + return {maintenance:this.maintenance,closed:this.closed, + handoffCooldownRemainingMs:Math.max(0,this.nextHandoffEligibleAt-Date.now()), + lanes:this.lanes.map(l=>({reserved:l.reserved,reservationPurpose:l.reservationPurpose,...l.coordinator.readinessSnapshot()}))}; + } async liveness() { const results=await Promise.all(this.lanes.map(l=>l.coordinator.liveness())); return {protocolVersion:PROTOCOL_VERSION,build:this.build,available:!this.closed&&results.some(r=>r.available)}; @@ -67,7 +77,11 @@ export class PooledWindowCoordinator { const entry=[...this.actions.values()].reverse().find(a=>a.conversation===key); return entry?.lane; } - private async onConversation(url:string,operation:(coordinator:Coordinator)=>Promise):Promise { + private async onConversation(url:string,operation:(coordinator:Coordinator)=>Promise,purpose:"approval"|"handoff"):Promise { + // Repeated unfinished handoff probes can otherwise monopolize the one + // shared browser tab. Deferral is an error, never a fake negative proof. + if(purpose==="handoff"&&Date.now()this.free(l)); if(this.closed||this.maintenance||!lane)throw new BrowserCompanionError("Browser companion action pages are busy"); - lane.reserved=true; + lane.reserved=true;lane.reservationPurpose=purpose; this.observations.add(key); - try {return await operation(lane.coordinator);}finally{this.observations.delete(key);lane.reserved=false;} + try {return await operation(lane.coordinator);}finally{ + if(purpose==="handoff")this.nextHandoffEligibleAt=Date.now()+this.handoffGapMs; + this.observations.delete(key);lane.reserved=false;lane.reservationPurpose=null; + } } login:Coordinator["login"]=signal=>this.exclusive(c=>c.login(signal)); capabilities:Coordinator["capabilities"]=signal=>this.exclusive(c=>c.capabilities(signal)); @@ -87,8 +104,8 @@ export class PooledWindowCoordinator { setPresentationStyle:Coordinator["setPresentationStyle"]=(css,signal)=>this.exclusive(c=>c.setPresentationStyle(css,signal)); presentation:Coordinator["presentation"]=(signal,screenshot)=>this.exclusive(c=>c.presentation(signal,screenshot)); reveal:Coordinator["reveal"]=(url,signal)=>this.exclusive(c=>c.reveal(url,signal)); - turnHandoffComplete:Coordinator["turnHandoffComplete"]=(url,account,id,signal)=>this.onConversation(url,c=>c.turnHandoffComplete(url,account,id,signal)); - approvePendingConversation:Coordinator["approvePendingConversation"]=(request,signal,navigate,once)=>this.onConversation(request.url,c=>c.approvePendingConversation(request,signal,navigate,once)); + turnHandoffComplete:Coordinator["turnHandoffComplete"]=(url,account,id,signal)=>this.onConversation(url,c=>c.turnHandoffComplete(url,account,id,signal),"handoff"); + approvePendingConversation:Coordinator["approvePendingConversation"]=(request,signal,navigate,once)=>this.onConversation(request.url,c=>c.approvePendingConversation(request,signal,navigate,once),"approval"); // Navigation budgets are shared by every page in the profile. navigationAvailability:Coordinator["navigationAvailability"]=url=>(this.laneFor(url)??this.lanes[0]!).coordinator.navigationAvailability(url); // A retained pairing window belongs to the page that created the chat. @@ -138,7 +155,7 @@ export class PooledWindowCoordinator { } if(this.actions.size>=this.lanes.length*1100)throw new Error("Browser action history is full"); } - lane.reserved=true;lane.lastUsed=Date.now(); + lane.reserved=true;lane.reservationPurpose="action";lane.lastUsed=Date.now(); // Persist pool ownership before any asynchronous page preflight. Failed // preflight can be retried only if the single-page coordinator recorded it. const owned={lane,digest,key:request.idempotencyKey,conversation}; @@ -149,7 +166,7 @@ export class PooledWindowCoordinator { this.actions.delete(request.actionId);this.keys.delete(request.idempotencyKey); } throw error; - } finally {lane.reserved=false;} + } finally {lane.reserved=false;lane.reservationPurpose=null;} } finally {release();} } private async owner(actionId:string):Promise { diff --git a/browser-companion/src/browser-window.ts b/browser-companion/src/browser-window.ts index fce87b83..707c67be 100644 --- a/browser-companion/src/browser-window.ts +++ b/browser-companion/src/browser-window.ts @@ -292,6 +292,22 @@ export class SingleWindowCoordinator { || this.actionCleanupPending || this.observationCleanupPending; } + /** Private, browser-free evidence for diagnosing a stuck lease. No page or account data. */ + readinessSnapshot() { + return { + busy:this.busy, + retired:this.retired, + activeAction:this.activeActionId !== null, + pendingAction:this.pendingActionId !== null, + windowOperationActive:this.windowOperationActive, + observationCleanupPending:this.observationCleanupPending, + actionCleanupPending:this.actionCleanupPending, + connectorRefreshPending:this.connectorRefreshPending, + driverClosed:this.driverClosed, + closing:this.closing, + }; + } + // An admitted action owns its page before its asynchronous preflight starts. get ownedActionId():string | null { return this.activeActionId ?? this.pendingActionId; } get retiredWindow():boolean {return this.retired;} diff --git a/browser-companion/src/chatgpt-driver.ts b/browser-companion/src/chatgpt-driver.ts index 0c00bfb6..b7e8e226 100644 --- a/browser-companion/src/chatgpt-driver.ts +++ b/browser-companion/src/chatgpt-driver.ts @@ -1,7 +1,7 @@ import {observeReadOnly,RendererProbeGate} from "./observation"; import type { Frame, Locator, Page } from "patchright"; import {completedHandoff,createCompletedHandoffVerifier} from "./turn-renewal"; -import {classifyPlan,identifyConnectorApp,observedConnectorApp,inspectConnectorSettings,setConnectorAllowAll,verifyConnectorAllowAll,beginConnectorToolRefresh,type ConnectorRefreshObservation,type AccountPlan} from "./account-settings"; +import {classifyPlan,identifyConnectorApp,observedConnectorApp,inspectConnectorSettings,beginConnectorToolRefresh,type ConnectorRefreshObservation,type AccountPlan} from "./account-settings"; import {ConnectorAppCache} from "./connector-cache"; import {DraftRecoveryJournal} from './draft-recovery'; import {approveConversationCard,latestConversationApprovalCards,throwIfConversationApproval} from "./conversation-approval"; @@ -602,6 +602,11 @@ export class ChatGptBrowserDriver implements BrowserDriver { console.error(`[connector-maintenance] ${label}: ${error.name}: ${detail}`); } const failure=asCompanionError(error); + // Typed browser conflicts previously disappeared behind a generic + // native HTTP 409. Record only the fixed phase label and failure code: + // never a tab URL, account identifier, connector name, or page text. + if(error instanceof BrowserCompanionError) + console.warn(`[connector-maintenance] ${label}: code=${failure.code}`); throw new BrowserCompanionError(`${label}: ${failure.message}`,failure.code,{cause:error}); }); const appId=await step("Identify connector",async(page,account,signal)=>{ @@ -631,22 +636,20 @@ export class ChatGptBrowserDriver implements BrowserDriver { }); void interrupted.catch(()=>{}); // Cancellation during preparation is handled by its bounded phase. try { - const before=await phase("Inspect connector settings",(page,account,operationSignal)=>inspectConnectorSettings(page,appId,name,account.fingerprint,operationSignal)); - const knownSummary=this.connectorApps.getAllowAllSummary(expectedAccount!,name); - const needsVerification=!before?.allowAll&&(!knownSummary||before?.summary!==knownSummary); - let permissionChanged=false; - if(needsVerification)permissionChanged=await phase("Verify connector permission",(page,account,operationSignal)=>setConnectorAllowAll(page,appId,account.fingerprint,operationSignal)); + await phase("Inspect connector settings",(page,account,operationSignal)=>inspectConnectorSettings(page,appId,name,account.fingerprint,operationSignal)); + // Refreshing the tool schema is not a request to elevate app permissions. + // Permissions may be on a separate connected-account UI or enforced by + // workspace policy, and the legacy /permissions radio page is optional. + // Never change a user's grant just to refresh tool metadata. observation=await phase("Start connector refresh",async(page,account,operationSignal)=>{ - if(needsVerification)await verifyConnectorAllowAll(page,appId,account.fingerprint,operationSignal); const current=await inspectConnectorSettings(page,appId,name,account.fingerprint,operationSignal); - if(!needsVerification&&!current?.allowAll&&(!knownSummary||current?.summary!==knownSummary))throw new BrowserCompanionError("Connector permission changed before refresh","external_interference"); - if(current?.summary)this.connectorApps.rememberAllowAllSummary(account.fingerprint,name,current.summary); + if(current?.allowAll===true&¤t.summary)this.connectorApps.rememberAllowAllSummary(account.fingerprint,name,current.summary); return beginConnectorToolRefresh(page,appId,name,account.fingerprint,operationSignal); }); // The coordinator retains the shared window through confirmation and the // restoration below; other operations must not navigate away mid-refresh. const refreshObserved=await Promise.race([observation.wait(waitSignal),interrupted]); - return {appId,permissionChanged,refreshObserved,schemaVerified:false as const}; + return {appId,permissionChanged:false,refreshObserved,schemaVerified:false as const}; }catch(error){refreshFailure=error;throw error;} finally { waitSignal.removeEventListener("abort",onAbort); diff --git a/browser-companion/src/control-server.ts b/browser-companion/src/control-server.ts index 01503b34..e8eb0f6c 100644 --- a/browser-companion/src/control-server.ts +++ b/browser-companion/src/control-server.ts @@ -13,7 +13,7 @@ import { createServer, type IncomingMessage, type Server, type ServerResponse } import { basename, dirname, join } from "node:path"; import { z } from "zod"; import { SingleWindowCoordinator } from "./browser-window"; -type BrowserCoordinator = Pick; +type BrowserCoordinator = Pick & {readinessSnapshot:()=>unknown}; import {validateNewChatProjectUrl} from "./new-chat"; import { asCompanionError,type BrowserStage,type BrowserFailureCode } from "./errors"; import { @@ -172,6 +172,9 @@ async function route( if(request.method === "GET" && url.pathname === "/v1/liveness") { json(response,200,await coordinator.liveness());return; } + if(request.method === "GET" && url.pathname === "/v1/diagnostics/readiness") { + json(response,200,coordinator.readinessSnapshot());return; + } if(request.method === "GET" && url.pathname === "/v1/diagnostics/presentation") { const screenshot=z.enum(["0","1"]).parse(url.searchParams.get("screenshot")??"0")==="1"; json(response,200,await coordinator.presentation(operation.signal,screenshot));return; @@ -205,7 +208,8 @@ async function route( } if(request.method === "POST" && url.pathname === "/v1/turns/handoff") { const body=z.strictObject({url:chatGptUrlSchema,expectedAccountFingerprint:opaqueIdSchema,handoffId:z.string().regex(/^renew-[a-f0-9]{64}$/)}).parse(await readJson(request)); - json(response,200,await coordinator.turnHandoffComplete(body.url,body.expectedAccountFingerprint,body.handoffId,operation.signal));return; + try {json(response,200,await coordinator.turnHandoffComplete(body.url,body.expectedAccountFingerprint,body.handoffId,operation.signal));} + catch(error){if(error instanceof Error&&error.message.toLowerCase().includes("busy"))throw new ClientError(423,"Handoff inspection deferred while the shared browser is busy");throw error;}return; } if(request.method === "POST" && url.pathname === "/v1/approvals/conversation") { const body=conversationApprovalRequestSchema.parse(await readJson(request)); diff --git a/browser-companion/src/windows-chrome-recovery.ts b/browser-companion/src/windows-chrome-recovery.ts index 8458b675..e5e79ec6 100644 --- a/browser-companion/src/windows-chrome-recovery.ts +++ b/browser-companion/src/windows-chrome-recovery.ts @@ -20,7 +20,8 @@ foreach($item in $all){ if($path -ine $expected -and (-not $runtime -or -not $path.StartsWith($runtime,[StringComparison]::OrdinalIgnoreCase))){continue} $parent=$parents[[int]$item.ParentProcessId] # A PID reused after Chrome was created is not its owner. - if($parent -and $parent.CreationDate -le $item.CreationDate){continue} + # Compare UTC instants: local wall-clock times repeat during the DST fold. + if($parent -and $parent.CreationDate.ToUniversalTime() -le $item.CreationDate.ToUniversalTime()){continue} $profiles=[regex]::Matches($item.CommandLine,'(?:^|\s)(?:"--user-data-dir=([^"]+)"|--user-data-dir="([^"]+)"|--user-data-dir=([^\s"]+))(?=\s|$)') if($profiles.Count -ne 1){continue} $value=@($profiles[0].Groups[1].Value,$profiles[0].Groups[2].Value,$profiles[0].Groups[3].Value | Where-Object {$_})[0] @@ -31,7 +32,7 @@ foreach($item in $all){ $current=Get-CimInstance Win32_Process -Filter ("ProcessId="+[int]$item.ProcessId) if(-not $current -or $current.CreationDate -ne $item.CreationDate -or $current.ExecutablePath -ine $item.ExecutablePath -or $current.CommandLine -cne $item.CommandLine){continue} $parent=Get-CimInstance Win32_Process -Filter ("ProcessId="+[int]$current.ParentProcessId) - if($parent -and $parent.CreationDate -le $current.CreationDate){continue} + if($parent -and $parent.CreationDate.ToUniversalTime() -le $current.CreationDate.ToUniversalTime()){continue} $process=Get-Process -Id $current.ProcessId -ErrorAction SilentlyContinue if(-not $process){continue} try { diff --git a/browser-companion/tests/account-settings.test.ts b/browser-companion/tests/account-settings.test.ts index 8da0a6fe..e83ac5fd 100644 --- a/browser-companion/tests/account-settings.test.ts +++ b/browser-companion/tests/account-settings.test.ts @@ -41,7 +41,8 @@ test.skipIf(process.env.CODEXIFY_TEST_BROWSER_COMPANION_CHROME!=="1")("passive p const browser=await chromium.launch({executablePath,headless:true}); try { const context=await browser.newContext();const page=await context.newPage();let permission='read_only',refreshes=0,deletes=0,billingReads=0,failConnector=false,fastRefresh=false,replaceRefresh=false,refreshDelay=300,permissionVisits=0;const visits:string[]=[]; - let planAccount='fixture-account',permissionLabel='Permiso',allowLabel='Permitir todo',originalHtml='
',sessionAvailable=true; + let planAccount='fixture-account',permissionLabel='Permiso',allowLabel='Permitir todo',originalHtml='
',sessionAvailable=true,collapsedPermissions=false,noPermissionControls=false; + let permissionMetadata:string|undefined,displayedPermission:string|undefined; const witness:{summary?:string;remember:(summary:string)=>void}={remember:summary=>witness.summary=summary}; await page.context().route('https://chatgpt.com/**',async route=>{ const path=new URL(route.request().url()).pathname; @@ -49,20 +50,21 @@ test.skipIf(process.env.CODEXIFY_TEST_BROWSER_COMPANION_CHROME!=="1")("passive p if(path==='/api/auth/session')return route.fulfill({json:sessionAvailable?{user:{id:'fixture-user'},account:{id:new URL(route.request().frame().page().url()).pathname==='/settings/billing'?planAccount:'fixture-account',planType:'pro',structure:'personal'}}:{}}); if(path==='/settings/billing'){billingReads++;return route.fulfill({contentType:'text/html; charset=utf-8',body:'

ChatGPT Pro 200

'});} if(path==='/c/original')return route.fulfill({contentType:'text/html; charset=utf-8',body:originalHtml}); - if(path==='/set-permission'){permission='allow_all';return route.fulfill({json:{ok:true}});} + if(path==='/set-permission'){permission='allow_all';permissionMetadata=undefined;displayedPermission=undefined;return route.fulfill({json:{ok:true}});} if(path==='/refresh'){refreshes++;return route.fulfill({json:{ok:true}});} if(path==='/delete'){deletes++;return route.fulfill({json:{ok:true}});} if(path==='/')return route.fulfill({contentType:'text/html; charset=utf-8',body:'
Fixture connector
'}); - if(path.endsWith('/permissions')){permissionVisits++;return route.fulfill({contentType:'text/html; charset=utf-8',body:`

Permissions

${['Preguntar','Solo lectura','Bajo riesgo','Permitir todo'].map((label,index)=>`
${label}
`).join('')}`});} - return route.fulfill({contentType:'text/html; charset=utf-8',body:`

Fixture connector

${permissionLabel}Elegir permisos${permission==='allow_all'?allowLabel:'Solo lectura'}
Nombre
Descripción
Actualizar herramientas
Eliminar
`}); + if(path.endsWith('/permissions')){permissionVisits++;const choices=['Preguntar','Solo lectura','Bajo riesgo','Permitir todo'].map((label,index)=>`
${label}
`).join('');return route.fulfill({contentType:'text/html; charset=utf-8',body:`

Permissions

${collapsedPermissions?'':''}`});} + if(noPermissionControls)return route.fulfill({contentType:'text/html; charset=utf-8',body:`

Fixture connector

`}); + return route.fulfill({contentType:'text/html; charset=utf-8',body:`

Fixture connector

${permissionLabel}Elegir permisos${displayedPermission??(permission==='allow_all'?allowLabel:'Solo lectura')}
Nombre
Descripción
Actualizar herramientas
Eliminar
`}); }); await page.goto('https://chatgpt.com/c/original'); const plan=await readBillingPlan(page);expect(plan.label).toBe('Pro 20x'); - const result=await refreshConnectorTools(page,'Fixture connector',undefined,undefined,undefined,witness);expect(result.refreshObserved).toBeTrue();expect(result.permissionChanged).toBeTrue();expect(result.schemaVerified).toBeFalse(); - expect(permission).toBe('allow_all');expect(refreshes).toBe(1);expect(deletes).toBe(0); + const result=await refreshConnectorTools(page,'Fixture connector',undefined,undefined,undefined,witness);expect(result.refreshObserved).toBeTrue();expect(result.permissionChanged).toBeFalse();expect(result.schemaVerified).toBeFalse(); + expect(permission).toBe('read_only');expect(permissionVisits).toBe(0);expect(refreshes).toBe(1);expect(deletes).toBe(0); const beforePermission=permissionVisits;visits.length=0; const again=await refreshConnectorTools(page,'Fixture connector',undefined,undefined,'asdk_app_fixture',witness);expect(again.permissionChanged).toBeFalse();expect(refreshes).toBe(2);expect(deletes).toBe(0); - expect(permissionVisits).toBe(beforePermission);expect(visits).toEqual([]); // Already on the verified settings page. + expect(permissionVisits).toBe(beforePermission);expect(visits).toEqual(['/settings/plugins-settings/plugin_asdk_app_fixture']); // A fresh settings document validates the grant. fastRefresh=true;replaceRefresh=true;await page.reload();await refreshConnectorTools(page,'Fixture connector',undefined,undefined,'asdk_app_fixture',witness);fastRefresh=false;replaceRefresh=false;expect(refreshes).toBe(3); await page.goto('https://chatgpt.com/c/original'); let owned=false,beginCalls=0,endCalls=0; @@ -77,14 +79,15 @@ test.skipIf(process.env.CODEXIFY_TEST_BROWSER_COMPANION_CHROME!=="1")("passive p await driver.accountPlan('startup-two');expect(billingReads-before).toBe(0);expect(page.url()).toBe(original); await driver.refreshConnector('Fixture connector');expect(page.url()).toBe(original);expect(refreshes).toBe(4); const permissionBeforeCached=permissionVisits;visits.length=0; - await driver.refreshConnector('Fixture connector');expect(visits).toEqual(['/settings/plugins-settings/plugin_asdk_app_fixture','/c/original']); + await driver.refreshConnector('Fixture connector');expect(visits).toEqual(['/settings/plugins-settings/plugin_asdk_app_fixture','/settings/plugins-settings/plugin_asdk_app_fixture','/c/original']); expect(permissionVisits).toBe(permissionBeforeCached);expect(refreshes).toBe(5); - // Completion can outlast one UI phase, while retaining exclusive ownership. - const coordinator=new SingleWindowCoordinator(driver,protocolBuild('queued-refresh-test'),{operationMs:1500,cleanupMs:100,hardStopMs:100}); + // Maintenance still owns the tab while refresh finishes. Give the fixture + // realistic Windows Chrome navigation budgets; ownership is the invariant. + const coordinator=new SingleWindowCoordinator(driver,protocolBuild('queued-refresh-test'),{operationMs:10_000,cleanupMs:500,hardStopMs:250}); refreshDelay=2200; const pendingRefresh=coordinator.refreshConnector('Fixture connector'); const duplicate=expectFailure(coordinator.refreshConnector('Fixture connector'),'busy'); - const waitStarted=async()=>{const started=Date.now();while(owned||!await page.evaluate(()=>document.querySelector('#refresh')?.matches(':disabled')===true)){if(Date.now()-started>1500)throw Error('Refresh did not start');await new Promise(resolve=>setTimeout(resolve,20));}}; + const waitStarted=async()=>{const started=Date.now();while(owned||!await page.evaluate(()=>document.querySelector('#refresh')?.matches(':disabled')===true)){if(Date.now()-started>8_000)throw Error('Refresh did not start');await new Promise(resolve=>setTimeout(resolve,20));}}; await waitStarted();await duplicate; await expectFailure(coordinator.refreshConnector('Other connector'),'busy'); expect(owned).toBeFalse();expect((await coordinator.health()).status).toBe('busy'); @@ -106,16 +109,30 @@ test.skipIf(process.env.CODEXIFY_TEST_BROWSER_COMPANION_CHROME!=="1")("passive p await page.goto(original); const cancel=new AbortController(),cancelled=coordinator.refreshConnector('Fixture connector',cancel.signal); const cancellation=expectFailure(cancelled,'cancelled');await waitStarted();cancel.abort();await cancellation; + // A cancellation may be reported before its separately bounded restoration + // finishes, especially when Windows Chrome has a slow navigation. + const restoredBy=Date.now()+8_000; + while(page.url()!==original&&Date.now()setTimeout(resolve,50)); expect(page.url()).toBe(original);expect((await coordinator.health()).status).toBe('idle');refreshDelay=300; permissionLabel='Autorisation';allowLabel='Tout autoriser';const beforeLocale=permissionVisits; - await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeLocale+1); // Learn the new locale from checked radio state. - await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeLocale+1); // Then the direct path needs no permissions visit. + await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeLocale); // Tool refresh never opens or changes the grant. + await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeLocale); permissionLabel='Δικαιώματα';allowLabel='Να επιτρέπονται όλα';const beforeGreek=permissionVisits; - await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeGreek+1); - await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeGreek+1); + await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeGreek); + await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeGreek); permissionLabel='Autorizzazioni';allowLabel='Consenti tutto';const beforeItalian=permissionVisits; - await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeItalian+1); - await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeItalian+1); + await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeItalian); + await driver.refreshConnector('Fixture connector');expect(permissionVisits).toBe(beforeItalian); + // An obsolete selector and misleading cached label must not trigger + // permission elevation. Schema refresh remains a permission-neutral action. + permission='read_only';permissionMetadata='read_only';displayedPermission='Allow all actions'; + permissionLabel='You can choose Allow all actions';collapsedPermissions=true;noPermissionControls=true; + const beforeCollapsed=permissionVisits,beforeRefresh=refreshes; + const recovered=await driver.refreshConnector('Fixture connector'); + expect(recovered.permissionChanged).toBeFalse(); + expect(permission).toBe('read_only');expect(permissionVisits).toBe(beforeCollapsed); + expect(refreshes).toBe(beforeRefresh+1);expect(deletes).toBe(0); + collapsedPermissions=false;permissionLabel='Permiso'; // The current app-manager view has no permission row. expect(newPage).not.toHaveBeenCalled();expect(addedPages).toBe(0);expect(context.pages()).toEqual(initialPages);expect(page.isClosed()).toBeFalse(); // Passive account reads neither acquire a maintenance lease nor navigate. const beforePassive={beginCalls,endCalls,billingReads};visits.length=0; @@ -177,7 +194,7 @@ test.skipIf(process.env.CODEXIFY_TEST_BROWSER_COMPANION_CHROME!=="1")("passive p expect(beginCalls).toBe(endCalls);expect(owned).toBeFalse();expect(newPage).not.toHaveBeenCalled();expect(addedPages).toBe(0);expect(context.pages()).toEqual(initialPages); } finally {newPage.mockRestore();} }finally{await browser.close();} -},30000); +},90_000); test.skipIf(process.env.CODEXIFY_TEST_BROWSER_COMPANION_CHROME!=="1")("confirmed sign-out survives conversation errors while failed session reads remain unavailable",async()=>{ diff --git a/browser-companion/tests/connector-permission-regression.test.ts b/browser-companion/tests/connector-permission-regression.test.ts new file mode 100644 index 00000000..d31faa93 --- /dev/null +++ b/browser-companion/tests/connector-permission-regression.test.ts @@ -0,0 +1,109 @@ +import {test,expect} from "bun:test"; +import {chromium} from "patchright"; +import {join} from "node:path"; +import {readChatGptAccount} from "../src/account"; +import {inspectConnectorSettings,setConnectorAllowAll,verifyConnectorAllowAll} from "../src/account-settings"; +import {privateChromeExecutable} from "../src/chrome-executable"; + +test.skipIf(process.env.CODEXIFY_TEST_BROWSER_COMPANION_CHROME!=="1")( + "already-granted permission is proved on the app page; collapsed choices cannot be forged by a label", + async () => { + const executablePath=await privateChromeExecutable(join(import.meta.dirname,"../.browsers",`${process.platform}-${process.arch}`)); + const browser=await chromium.launch({executablePath,headless:true}); + try { + const page=await browser.newPage(); + const appId="asdk_app_fixture",name="Fixture connector"; + let mode:"allow_all"|"read_only"="allow_all"; + let permissionMetadata:string|null=null,selectedLabel="Allow all actions"; + let permissionVisits=0,permissionChanges=0,deleteRequests=0,omitControls=false; + + await page.context().route("https://chatgpt.com/**",async route=>{ + const path=new URL(route.request().url()).pathname; + if(path==="/api/auth/session")return route.fulfill({json:{ + user:{id:"fixture-user"},account:{id:"fixture-account",planType:"pro",structure:"personal"}, + }}); + if(path==="/set-permission"){ + permissionChanges++;mode="allow_all";permissionMetadata=null;selectedLabel="Allow all actions"; + return route.fulfill({json:{ok:true}}); + } + if(path==="/delete"){deleteRequests++;return route.fulfill({json:{ok:true}});} + if(path.endsWith("/permissions")){ + permissionVisits++; + if(omitControls)return route.fulfill({contentType:"text/html; charset=utf-8", + body:'

Permissions

Private example description that must never be logged

'}); + const options=["Ask every time","Read only","Low risk","Allow all actions"].map((label,index)=> + '
'+label+'
', + ).join(""); + const html='

Permissions

'+ + ''+ + ''+ + ''; + return route.fulfill({contentType:"text/html; charset=utf-8",body:html}); + } + if(path==="/settings/plugins-settings/plugin_"+appId){ + const meta=permissionMetadata===null?"":' data-permission="'+permissionMetadata+'"'; + const html='

'+name+'

'+ + '
'+ + ''+ + 'PermissionsChoose permissions'+selectedLabel+'
'+ + '
'+ + ''+ + '
'+ + '
'; + return route.fulfill({contentType:"text/html; charset=utf-8",body:html}); + } + return route.fulfill({contentType:"text/html; charset=utf-8",body:"
ChatGPT
"}); + }); + + await page.goto("https://chatgpt.com/"); + const account=(await readChatGptAccount(page)).fingerprint; + const granted=await inspectConnectorSettings(page,appId,name,account); + expect(granted?.allowAll).toBe(true); + expect(permissionVisits).toBe(0); + + // An explicit read-only marker defeats a misleading "Allow all" label. + mode="read_only";permissionMetadata="read_only";selectedLabel="Allow all actions"; + const denied=await inspectConnectorSettings(page,appId,name,account); + expect(denied?.allowAll).toBe(false); + + // An unknown label cannot silently become a permission proof. + permissionMetadata=null;selectedLabel="Allow all actions is an available option"; + const ambiguous=await inspectConnectorSettings(page,appId,name,account); + expect(ambiguous?.allowAll).toBe(false); + + // The collapsed picker must be opened explicitly, and the selected value + // must still be verified after a new server-backed document navigation. + const changed=await setConnectorAllowAll(page,appId,account); + expect(changed).toBe(true); + await verifyConnectorAllowAll(page,appId,account); + expect(permissionChanges).toBe(1); + expect(permissionVisits).toBe(2); + const verified=await inspectConnectorSettings(page,appId,name,account); + expect(verified?.allowAll).toBe(true); + expect(deleteRequests).toBe(0); + expect(page.context().pages()).toEqual([page]); + // Unknown permission markup remains fail-closed and reports only a + // bounded structural shape, never arbitrary private page content. + omitControls=true; + const warnings:string[]=[]; + const originalWarn=console.warn; + console.warn=(...items:unknown[])=>{warnings.push(items.map(String).join(" "));}; + try{ + await expect(setConnectorAllowAll(page,appId,account)).rejects.toThrow("Timeout"); + }finally{console.warn=originalWarn;} + const diagnostic=warnings.find(line=>line.startsWith("[connector-permission-shape]")); + expect(diagnostic).toBeDefined(); + expect(diagnostic).toContain('"pageType":"permissions"'); + expect(diagnostic).toContain('"visibleRadios":0'); + expect(diagnostic).not.toContain("Private example description"); + } finally { + await browser.close(); + } + }, + 60_000, +); diff --git a/browser-companion/tests/control-server.test.ts b/browser-companion/tests/control-server.test.ts index 0ab884f5..4c61d630 100644 --- a/browser-companion/tests/control-server.test.ts +++ b/browser-companion/tests/control-server.test.ts @@ -5,6 +5,7 @@ import { mkdtemp } from "node:fs/promises"; import { expect, test } from "bun:test"; import type { CapabilityCatalog, ConversationApprovalRequest, ExecuteActionRequest } from "../src/protocol"; import { SingleWindowCoordinator, type BrowserDriver, type DriverExecution } from "../src/browser-window"; +import {PooledWindowCoordinator} from "../src/browser-pool"; import { startControlServer } from "../src/control-server"; import { protocolBuild } from "../src/protocol"; import { BrowserCompanionError } from "../src/errors"; @@ -75,6 +76,98 @@ class BlockingDriver extends ImmediateDriver { } } +test("private readiness diagnostic identifies maintenance without an action or account data",async()=>{ + let entered!:()=>void,release!:()=>void; + const enteredPromise=new Promise(resolve=>entered=resolve); + const gate=new Promise(resolve=>release=resolve); + class MaintenanceDriver extends ImmediateDriver { + override async capabilities():Promise { + entered(); + await gate; + return super.capabilities(); + } + } + const root=await mkdtemp(join(tmpdir(),"browser-readiness-")); + const coordinator=new PooledWindowCoordinator([new SingleWindowCoordinator(new MaintenanceDriver(),TEST_BUILD)],TEST_BUILD); + const server=await startControlServer(coordinator,join(root,"descriptor.json")); + try { + const url=server.endpoint+"/v1/diagnostics/readiness"; + expect((await fetch(url)).status).toBe(401); + const headers={Authorization:"Bearer "+server.token}; + expect(await(await fetch(url,{headers})).json()).toMatchObject({ + maintenance:false,closed:false,lanes:[{reserved:false,busy:false,windowOperationActive:false}], + }); + const task=coordinator.capabilities(); + await enteredPromise; + const blocked=await(await fetch(url,{headers})).json(); + expect(blocked).toMatchObject({ + maintenance:true,lanes:[{busy:true,windowOperationActive:true,activeAction:false,pendingAction:false}], + }); + expect(JSON.stringify(blocked)).not.toContain("account-test"); + expect(JSON.stringify(blocked)).not.toContain("chatgpt.com"); + release(); + await task; + expect(await(await fetch(url,{headers})).json()).toMatchObject({ + maintenance:false,lanes:[{busy:false,windowOperationActive:false}], + }); + }finally{release();await server.close();} +}); + +test("readiness identifies a handoff reservation without revealing conversation identifiers",async()=>{ + let entered!:()=>void,release!:()=>void; + const started=new Promise(resolve=>entered=resolve); + const gate=new Promise(resolve=>release=resolve); + class HandoffDriver extends ImmediateDriver { + async turnHandoffComplete(){ + entered(); + await gate; + return false; + } + } + const root=await mkdtemp(join(tmpdir(),"browser-handoff-readiness-")); + const coordinator=new PooledWindowCoordinator([new SingleWindowCoordinator(new HandoffDriver(),TEST_BUILD)],TEST_BUILD); + const server=await startControlServer(coordinator,join(root,"descriptor.json")); + const url="https://chatgpt.com/c/private-handoff"; + try { + const pending=coordinator.turnHandoffComplete(url,"account-test","renew-"+ "f".repeat(64)); + await started; + const state=await(await fetch(server.endpoint+"/v1/diagnostics/readiness",{headers:{Authorization:"Bearer "+server.token}})).json(); + expect(coordinator.busy).toBe(true); + expect(state).toMatchObject({maintenance:false,lanes:[{ + reserved:true,reservationPurpose:"handoff",activeAction:false,pendingAction:false,windowOperationActive:true, + }]}); + expect(JSON.stringify(state)).not.toContain("private-handoff"); + release(); + await pending; + expect(coordinator.busy).toBe(false); + }finally{release();await server.close();} +}); + +test("handoff probes defer with HTTP 423 instead of manufacturing a negative receipt",async()=>{ + let reads=0; + class HandoffDriver extends ImmediateDriver { + async turnHandoffComplete(){reads++;return false;} + } + const root=await mkdtemp(join(tmpdir(),"browser-handoff-gap-")); + const coordinator=new PooledWindowCoordinator([new SingleWindowCoordinator(new HandoffDriver(),TEST_BUILD)],TEST_BUILD,undefined,45); + const server=await startControlServer(coordinator,join(root,"descriptor.json")); + const headers={Authorization:"Bearer "+server.token,"Content-Type":"application/json"}; + const body=JSON.stringify({url:"https://chatgpt.com/c/handoff-gap",expectedAccountFingerprint:"account-test",handoffId:"renew-"+"f".repeat(64)}); + const request=()=>fetch(server.endpoint+"/v1/turns/handoff",{method:"POST",headers,body}); + try { + expect((await request()).status).toBe(200); + const deferred=await request(); + expect(deferred.status).toBe(423); + expect(reads).toBe(1); + expect((await coordinator.readinessSnapshot()).handoffCooldownRemainingMs).toBeGreaterThan(0); + // Delaying a handoff must leave exclusive maintenance and refresh free to run. + expect((await coordinator.capabilities()).models).toHaveLength(1); + await Bun.sleep(65); + expect((await request()).status).toBe(200); + expect(reads).toBe(2); + }finally{await server.close();} +}); + test("pairing lease renewal is authenticated and preserves the held page",async()=>{ class PairDriver extends ImmediateDriver { override async execute(execution:DriverExecution){ diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index d78e42ef..a535a97e 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1125,6 +1125,35 @@ The catalogue is a startup snapshot. Dynamic `tools/list_changed` notifications are not used to mutate the downstream fixed surface; restart the process to rematerialize an upstream catalogue. +**Playwright browser-context capability boundary.** A `browser_tabs` call with +`action: "new"` and a non-default `isolatedContext` requires a real browser-level +connection. An upstream launched with `--extension`, `PLAYWRIGHT_MCP_EXTENSION=true`, +or `extension: true` in its Playwright JSON config only attaches to existing tabs, +so Codexify rejects the isolated request **before upstream dispatch**, whether +invoked through direct, gateway or catalog exposure. If an explicitly supplied +Playwright JSON configuration cannot be read or parsed, isolated-context +creation also fails closed instead of assuming the backend has browser-level +permissions. An ordinary new/default-context +tab is unaffected. Browser-level Playwright may create isolated contexts; a CDP +endpoint may or may not have browser-level permission. If CDP reports the exact +`Target.createBrowserContext` `-32000 Not allowed` error, Codexify explains +the missing capability and does not retry or substitute the extension. + +A connected extension is **not** a fallback for an unavailable browser-level +backend. These are separate upstreams with distinct session identities; routing +one tab-creation call to another upstream would not route subsequent navigation, +selection or cleanup there. Backend and tab ownership must remain stable for +the entire workflow. Playwright's index-based global tab selection is not +per-agent ownership enforcement; callers sharing one backend must still prevent +cross-agent tab interference until stable target identity is integrated upstream. + +MCP initialization is a startup snapshot as well: a `playwright` server that +misses `startupTimeoutSec` is omitted from the downstream catalogue, even if +`playwright-extension` succeeds. Investigate its startup diagnostics and set +a bounded per-upstream `startupTimeoutSec` appropriate for the machine before +restarting Codexify during a safe maintenance window. Never restart an active +browser or resubmit an external action just to repair a missing MCP tool. + ### 7.3 Direct compatibility mode (`"mode": "direct"`) Each selected upstream tool becomes a `BridgedTool` named `__` diff --git a/docs/MCP_HOT_RELOAD.md b/docs/MCP_HOT_RELOAD.md new file mode 100644 index 00000000..75b2476d --- /dev/null +++ b/docs/MCP_HOT_RELOAD.md @@ -0,0 +1,123 @@ +# Per-source MCP hot reload (operator guide) + +**Status:** experimental, opt-in through a staged build. This document describes +source behavior, not a deployed feature. Do not replace an active Codexify +service without separate approval and validation. + +## Scope + +`reload_mcp` reloads exactly one existing upstream source. Its `source` +argument must match the **exact configured MCP server key** from the resolved +`mcpServers` configuration (including inherited Codex MCP sources). For example, +if the configured key is `god-prompt-mcp`, call +`{"source":"god-prompt-mcp"}`. Do not substitute a normalized catalog source ID +such as `god_prompt_mcp` from `mcp_list_sources`: it is not necessarily the +configuration key and can return `SOURCE_UNKNOWN` without changing the running +connection. The call cannot supply a command, executable, working directory, +URL, environment variables, or credentials. + +The server rereads its operator configuration (including inherited Codex MCP +sources) **read-only** using its startup CLI selection. A target that was +removed or disabled fails closed. No global service restart, tunnel reconnect, +task replacement, or unrelated source reconnection is part of this operation. + +The replacement uses the existing MCP transport implementation for **stdio** +and **Streamable HTTP**. Unsupported legacy SSE and WebSocket sources remain +unsupported; the operation never silently falls back to a process-wide restart. + +## Lifecycle and safety + +1. The scoped reload lock rejects concurrent attempts for the same source + (`RELOAD_IN_PROGRESS`); unrelated source reloads can progress concurrently. +2. The updated source specification is validated, started, initialized, and + queried with `tools/list`. A bounded MCP ping must also receive a + successful response or a protocol-level MCP error indicating a live peer. +3. The new tool definitions are validated and an immutable registry view is + constructed. The new view replaces the old view in one atomic pointer swap. + Concurrent distinct-source reloads rebuild against the latest view. +4. Each dispatch retains only its selected validated upstream tool and that + source's connection generation. Write-capable calls are **never replayed**; + unrelated direct/gateway sources are not retained by a long-running call. + Cancellation and timeout semantics remain those of the forwarded request. +5. The old generation is released when no selected old tool or catalog + snapshot retains it. The operation reports whether forwarded calls drained + within the source's configured `requestLimits.slowCancellationMs` interval. + The separate `oldGenerationStillReferenced` flag covers retained references + even when no forwarded calls remain. A drain timeout does **not** kill or + replay an in-progress side-effecting call. +6. On failure **before** the swap, the new candidate is dropped and the old + view is never replaced. Errors use bounded diagnostic codes and do not + echo credentials, command lines, headers, environment variables, or raw + tool-response bodies. + +For stdio, the spawned Tokio child has `kill_on_drop` enabled, so aborted +initializations should not leave the candidate running. A platform-specific +Windows child-lifecycle integration and repeated process-tree soak remain +required acceptance gates before production activation. + +## Result and tool discovery + +A successful result includes `source`, `outcome`, +`previousGeneration`, `replacementGeneration`, old/new reported MCP +server versions, readiness, counts of added/removed/changed/unchanged +tool definitions, `oldCallsDrained`, `oldCallsStillRunning`, +`oldGenerationStillReferenced`, `oldGenerationRetiring`, `rollback`, +`diagnosticCode`, and measured +`timingsMs` for initialization/readiness, registry switch, draining and total +reload duration. + +The source's discovery data and forwarded-call routes change together in the +server's tool registry. Existing transport sessions can observe changed +definitions on **another `tools/list`** request. **An already-open ChatGPT +chat is not guaranteed to receive new tool definitions automatically.** +Its connector may need Refresh, reconnection or a new conversation before +new direct tools appear. The result explicitly sets +`clientRediscoveryRequired: true`. + +Catalog-mode source and tool identifiers remain generated by the existing +catalog and may change when a source's tool set changes. Re-query +`mcp_list_sources`, `mcp_search_tools`, and `mcp_get_tool` before calling +a new or modified tool. Gateway clients must refresh their advertised schema +and generated skill after reload. + +## Failure and boundary conditions + +- `SOURCE_UNKNOWN` / `SOURCE_REMOVED` / `SOURCE_DISABLED`: verify the + exact configured MCP key, not a normalized catalog ID. Do not spawn an + arbitrary process or reinterpret the input as a path. +- `RELOAD_IN_PROGRESS`: no duplicate replacement of the same source. +- `CONFIG_INVALID`, `CONFIG_CLI_INVALID`, `INITIALIZE_FAILED`, + `READINESS_FAILED`: old healthy generation is retained. +- `TOOL_NAME_LIMIT`: bound on unique registered direct/gateway tool names; + the attempted registry swap is discarded. +- `CANCELLED`: an aborted preparation does not switch generations. +- If the old generation became unhealthy independently, a successful new + connection is preferred; the operation does not imply that the old peer can + be resurrected. +- Resource links issued before a reload are separate capabilities. An upstream + resource fetched **after** its old connection retires can fail; request a + fresh resource link from the new source. Already-running resource reads + retain their own peer and cancellation semantics, but cross-generation + resource-link durability is not claimed by this implementation. +- Invalid data from upstream tool descriptions must remain untrusted. + Reload permission uses existing Codexify connector authorization and audit + boundaries. Do not expose the control plane to unauthenticated clients. + +## Verification gate + +The following must pass on the **exact candidate commit** before any +deployment: Rust formatting and compilation, strict lint, full Rust suite, +downstream HTTP MCP handshake, selected-source version and tool-diff checks, +two independent unrelated MCP sources, read/write in-flight calls, duplicate +reload and failure injection, cleanup/leak soak, and Windows native-process +termination. Reproduce an isolated old-to-new GodPrompt candidate switch +without touching the running GodPrompt instance; verify new version and +rollback. Measure switchover, drain and end-to-end request latency using a +repeatable workload. Do not report "zero downtime" without observed proof. + +**Not included:** automatic filesystem watching. It remains disabled rather +than introducing unverified debouncing and partially written config races. + +This feature does not merge the separate Windows scheduled-supervisor orphan +cleanup branch. Keep that work independent and verify its eventual integration +before any production cutover. diff --git a/docs/SINGLE_LANE_V240_RECOVERY.md b/docs/SINGLE_LANE_V240_RECOVERY.md new file mode 100644 index 00000000..512dfc95 --- /dev/null +++ b/docs/SINGLE_LANE_V240_RECOVERY.md @@ -0,0 +1,43 @@ +# Minimal v2.4 single-lane recovery candidate + +This branch starts from the official Codexify v2.4.0 source commit +`b14eacde810531a451535ee546ca7e07c65c5a1d`. It intentionally does **not** import the experimental two-browser +integration, global primary-goal pin, second companion/watchdog, or private +profile logic. + +The native v2.4 scheduler defaults to one browser action page and protects +dispatch with a one-permit semaphore. Other saved goals remain durable and +eligible in their existing queue; no second browser process or goal pin is +needed to serialize actions. + +## Changes + +- Preserve state publication through short Windows sharing locks: if a + read-only no-op comparison is blocked by a genuine Win32 sharing violation, + let the existing bounded atomic-replacement retry handle the lock. Other + file-read errors still fail closed. +- Test transient/persistent sharing violations with old state preserved. +- Make an existing ambiguous Git checkout test compare canonicalized paths + on Windows, without changing real checkout selection. +- Retry a brief Windows status-file rename gap during self-update reads, + bounded to missing-file or sharing-violation errors. +- Run targeted and full library tests on Windows and stage a native binary, + without performing a service installation. + +## Production cutover gates + +1. Verify the current authenticated primary companion and native service are + healthy, and confirm exactly one configured browser action lane. +2. Preserve the existing service binary, version-matched browser runtime, + config and all original goal/journal/action receipt files. +3. Verify there is no actively dispatched or uncertain accepted browser Send, + and no unverified terminal/renewal handoff in the intended maintenance + interval. A queued action is not proof of being safely idle. +4. Use only the official version-matched browser companion; never install the + older two-browser candidate or restart another agent's Chrome profile. +5. Upgrade via a guarded verified native service procedure, run doctor, + confirm authenticated browser health, and verify read-only goal continuity + before resuming admissions. Roll back executable/runtime if health fails, + without rewriting goal journals or replaying accepted Sends. + +**No production change is authorized or executed by this branch.** diff --git a/docs/per-chat-playwright.md b/docs/per-chat-playwright.md new file mode 100644 index 00000000..7d48c01f --- /dev/null +++ b/docs/per-chat-playwright.md @@ -0,0 +1,77 @@ +# Per-chat Playwright MCP isolation (source-only prototype) + +This implementation is opt-in and is NOT enabled by Codexify 2.3.29. +Do not enable new configuration fields until a compatible build is deployed. +Preserve custom automation settings including providerSendGatePath. + +## Root cause + +Previously Codexify opened one stdio upstream peer for each Playwright source at +server startup. Every ChatGPT task forwarded to the same upstream peer. Since +Playwright tracks a mutable current tab for each MCP connection, different +agents could interfere by selecting each other's tabs. + +The opt-in sessionScope: per-chat now creates a distinct Playwright MCP peer +per durable ChatGPT task identity. Without trusted task or conversation +identity, all calls fail closed instead of falling back to the global peer. + +## Managed-browser mode (stronger isolation) + +Use a local Playwright MCP source without --extension and set sessionScope to +per-chat. Codexify creates a distinct, persistent user-data-dir for each task: +%USERPROFILE%\.codexify\playwright-agent-profiles\\\ + +The service port is part of the namespace so multiple Codexify instances +on one machine never contend for the same task browser profile. +This does not reuse the personal Chrome profile. Memory usage grows with +the number of concurrently active Chrome processes. + +## Extension mode (tab-group isolation, weaker security) + +Use the official Playwright Extension only on a dedicated, non-default +automation-only Chrome profile. The extension has broad access to the whole +profile; different tab groups are not strong sandbox boundaries. + +It supports distinct MCP client session names/tab groups and can auto-authorize +using PLAYWRIGHT_MCP_EXTENSION_TOKEN. The token must never appear in Git, logs, +CI or messages. The optional enrollment script saves it as a user-only Windows +secret file, not in the live Codexify configuration. + +Read-only dry run: + powershell.exe -NoProfile -File scripts\enroll-playwright-extension-token.ps1 + +One-time enrollment (when ready to enable this feature): + powershell.exe -NoProfile -File scripts\enroll-playwright-extension-token.ps1 -Apply -DedicatedProfile "Profile 3" + +After deploying a compatible Codexify build, opt in ONLY the selected +mcpServers.playwright-extension entry with sessionScope: per-chat, and set +env.PLAYWRIGHT_MCP_EXTENSION_TOKEN_FILE to the absolute path printed by the +enrollment script. Preserve its existing extension args and profile settings. +Do not configure a second plaintext token at the same time. + +A distinct named group is allocated per task and background mode requested. +Playwright Extension 0.5.0+ is needed for the background feature; Chromium +158+ is recommended when true background startup without focus is essential. +Older Chromium may still show/focus a connection page. + +## Failure containment and capacity + +- Never use global browser fallback after a per-chat routing failure +- Never connect extension mode without an explicit dedicated profile and token +- Reject unsupported shared-browser-context and existing CDP endpoint flags +- Direct, gateway and catalog bridge calls all carry trusted caller identity +- Keep no more than 16 per-source sessions and at most 3 concurrent starts; + impose a 90-second cancellable startup deadline; release inactive sessions after + one hour, never deleting browser profile directories +- This feature does not modify native Codexify browser companion profiles, + production service, or saved browser Send receipts + +## Deployment gates + +1. Run Rust formatting, compile and focused isolation unit tests +2. Prove two synthetic task identities resolve to distinct MCP clients +3. Confirm that unknown identity fails before browser mutation +4. Exercise two disposable browser profiles on harmless local pages +5. Verify unchanged production config, including providerSendGatePath, + against the final v2.4 candidate before any service cutover +6. Never silently retry or replay already-accepted browser Send actions diff --git a/scripts/enroll-playwright-extension-token.ps1 b/scripts/enroll-playwright-extension-token.ps1 new file mode 100644 index 00000000..a9607535 --- /dev/null +++ b/scripts/enroll-playwright-extension-token.ps1 @@ -0,0 +1,82 @@ +# Enrol a token for a dedicated Playwright automation Chrome profile. +# Stores the token only in an ACL-restricted file outside the Git repository. +# Does not modify Codexify configuration or launch a browser. +param( + [switch]$Apply, + [switch]$Rotate, + [string]$DedicatedProfile = '' +) +$ErrorActionPreference='Stop' +$root=Join-Path $env:USERPROFILE '.codexify' +$configPath=Join-Path $root 'codexify.config.json' +$secretDir=Join-Path $root 'secrets\playwright-extension' +$secretPath=Join-Path $secretDir 'connection-token.txt' +if(-not (Test-Path -LiteralPath $configPath -PathType Leaf)){throw 'Codexify config missing'} +$config=Get-Content -LiteralPath $configPath -Raw|ConvertFrom-Json +$server=$config.mcpServers.'playwright-extension' +if(-not $server){throw 'playwright-extension source not configured'} +if(-not @($server.args|Where-Object {$_ -eq '--extension' -or $_ -eq '--extension=true'}).Count){throw 'Selected MCP source is not extension mode'} +$profile=[string]$server.env.PLAYWRIGHT_MCP_PROFILE_DIR_NAME +if(-not $profile -or $profile -eq 'Default'){throw 'A dedicated non-default Chrome profile must be explicitly configured'} +if($Apply -and $DedicatedProfile -ne $profile){throw 'Explicit -DedicatedProfile must match configured dedicated profile'} +if($Rotate -and -not $Apply){throw '-Rotate requires -Apply'} +Write-Output ('Dedicated Chrome profile: '+$profile) +Write-Output ('Enrolment already exists: '+[bool](Test-Path -LiteralPath $secretPath)) +if(-not $Apply){ + Write-Output 'DRY RUN ONLY. No secrets stored, no browser started, no configuration changes.' + Write-Output ('To opt in later: powershell.exe -NoProfile -File "'+$PSCommandPath+'" -Apply -DedicatedProfile "'+$profile+'"') + return +} +if((Test-Path -LiteralPath $secretPath) -and -not $Rotate){throw 'Token already stored; use -Rotate only when explicitly replacing it'} +if($Rotate -and -not (Test-Path -LiteralPath $secretPath)){throw 'Cannot rotate an absent token'} +$inputToken=Read-Host 'Paste the token from Playwright Extension in this DEDICATED profile' -AsSecureString +if(-not $inputToken){throw 'No token supplied'} +$ptr=[Runtime.InteropServices.Marshal]::SecureStringToBSTR($inputToken) +try { $token=[Runtime.InteropServices.Marshal]::PtrToStringBSTR($ptr) } +finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ptr) } +if($token -notmatch '^[A-Za-z0-9_-]{16,512}$'){throw 'Unexpected Playwright token format; no file written'} +if(-not(Test-Path -LiteralPath $secretDir -PathType Container)){ + [void](New-Item -ItemType Directory -Path $secretDir -Force) +} +# Remove inherited ACLs and grant only the current Windows account plus +# SYSTEM and Administrators. Never widen access to Users or Everyone. +$identity=[Security.Principal.WindowsIdentity]::GetCurrent() +$account=New-Object Security.Principal.NTAccount($identity.Name) +$acl=New-Object Security.AccessControl.DirectorySecurity +$acl.SetAccessRuleProtection($true,$false) +$acl.SetOwner($account) +$inherit=[Security.AccessControl.InheritanceFlags]'ContainerInherit, ObjectInherit' +$prop=[Security.AccessControl.PropagationFlags]::None +$allow=[Security.AccessControl.AccessControlType]::Allow +foreach($who in @($account,(New-Object Security.Principal.SecurityIdentifier('S-1-5-18')),(New-Object Security.Principal.SecurityIdentifier('S-1-5-32-544')))){ + $rule=New-Object Security.AccessControl.FileSystemAccessRule($who,[Security.AccessControl.FileSystemRights]::FullControl,$inherit,$prop,$allow) + $acl.AddAccessRule($rule) +} +Set-Acl -LiteralPath $secretDir -AclObject $acl -ErrorAction Stop +$tmp=Join-Path $secretDir ('.connection-token-'+[Guid]::NewGuid().ToString('N')+'.pending') +$backup=$null +$committed=$false +try{ + [IO.File]::WriteAllText($tmp,$token,[Text.Encoding]::ASCII) + $token=$null + if((Get-Item -LiteralPath $tmp).Length -lt 16){throw 'Token staging failed'} + if($Rotate){ + $backup=Join-Path $secretDir ('old-token-'+[Guid]::NewGuid().ToString('N')+'.pending') + Move-Item -LiteralPath $secretPath -Destination $backup -ErrorAction Stop + } + Move-Item -LiteralPath $tmp -Destination $secretPath -ErrorAction Stop + $committed=$true +}finally{ + $token=$null + if(Test-Path -LiteralPath $tmp){Remove-Item -LiteralPath $tmp -Force} + if($backup -and (Test-Path -LiteralPath $backup)){ + if(-not $committed -and -not (Test-Path -LiteralPath $secretPath)){ + Move-Item -LiteralPath $backup -Destination $secretPath -ErrorAction Stop + }elseif($committed){ + Remove-Item -LiteralPath $backup -Force -ErrorAction Stop + } + } +} +Write-Output 'Token stored in Windows user-restricted directory. Token value not printed.' +Write-Output ('To use after deploying a COMPATIBLE Codexify candidate, set mcpServers.playwright-extension.sessionScope=per-chat and env.PLAYWRIGHT_MCP_EXTENSION_TOKEN_FILE to '+$secretPath) +Write-Output 'Existing live configuration and browser remain unchanged.' \ No newline at end of file diff --git a/scripts/fixtures/hot-reload-stdio-mcp.mjs b/scripts/fixtures/hot-reload-stdio-mcp.mjs new file mode 100644 index 00000000..48a41325 --- /dev/null +++ b/scripts/fixtures/hot-reload-stdio-mcp.mjs @@ -0,0 +1,49 @@ +// No dependencies or network: isolated MCP stdio child for Rust hot-reload tests. +// Every invocation is a separate operating-system process. +import { createInterface } from 'node:readline'; +import { writeFileSync } from 'node:fs'; + +const version = process.argv[2] ?? 'old'; +const pid = process.pid; +const input = createInterface({ input: process.stdin, crlfDelay: Infinity }); + +function respond(id, result) { + process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, result }) + '\n'); +} +function tool(name, description) { + return { name, description, inputSchema: { type: 'object', properties: {}, additionalProperties: false } }; +} +function replyToTool(id) { + respond(id, { content: [{ type: 'text', text: version + ':' + pid }], isError: false }); +} + +for await (const line of input) { + let request; + try { request = JSON.parse(line); } catch { continue; } + if (!request || !Object.hasOwn(request, 'id')) continue; + const { id, method } = request; + if (method === 'initialize') { + respond(id, { + protocolVersion: request.params?.protocolVersion ?? '2025-03-26', + capabilities: { tools: {} }, + serverInfo: { name: 'isolated-hot-reload-stdio-fixture', version }, + }); + } else if (method === 'tools/list') { + const tools = [tool('probe', 'Version probe ' + version), tool('slow', 'Slow probe ' + version)]; + if (version === 'new') tools.push(tool('new_tool', 'New tool in replacement generation')); + respond(id, { tools }); + } else if (method === 'tools/call') { + if (request.params?.name === 'slow') { + if (process.env.HOT_RELOAD_SLOW_MARKER_FILE) { + writeFileSync(process.env.HOT_RELOAD_SLOW_MARKER_FILE, String(pid)); + } + setTimeout(() => replyToTool(id), 300); + } else { + replyToTool(id); + } + } else if (method === 'ping') { + respond(id, {}); + } else { + process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, error: { code: -32601, message: 'Method not found' } }) + '\n'); + } +} diff --git a/scripts/test-windows-service-lifecycle-contract.ps1 b/scripts/test-windows-service-lifecycle-contract.ps1 new file mode 100644 index 00000000..fbf1b9f3 --- /dev/null +++ b/scripts/test-windows-service-lifecycle-contract.ps1 @@ -0,0 +1,152 @@ +# Offline contract verification for generated Windows Codexify service scripts. +# This extracts the actual Rust generator functions, compiles only those with +# rustc (not the heavy workspace test target), and executes PowerShell scripts +# against local mocks. It NEVER operates on the real Scheduled Task or processes. +param() +$ErrorActionPreference = 'Stop' +$ProgressPreference = 'SilentlyContinue' +$sourcePath = Join-Path $PSScriptRoot '..\src\service.rs' +$source = [IO.File]::ReadAllText([IO.Path]::GetFullPath($sourcePath)) +$functions = @( + 'powershell_quote', + 'windows_stop_script', + 'windows_verify_native_stopped_script', + 'windows_restart_script' +) +$definitions = foreach ($name in $functions) { + $pattern = if ($name -eq 'windows_verify_native_stopped_script') { + "(?ms)^fn $name\([^\r\n]*\) -> [^\r\n]+ \{.*?^\x22#\r?\n^\}" + } else { + "(?ms)^fn $name\([^\r\n]*\) -> [^\r\n]+ \{.*?^\}" + } + $match = [regex]::Match($source, $pattern) + if (-not $match.Success) { + throw "Could not isolate source function $name" + } + $match.Value +} +$root = Join-Path ([IO.Path]::GetTempPath()) ('codexify-windows-contract-' + [guid]::NewGuid().ToString('N')) +[void](New-Item -Path $root -ItemType Directory -ErrorAction Stop) +try { + $rust = 'const WINDOWS_TASK: &str = "Codexify";' + [Environment]::NewLine + + ($definitions -join ([Environment]::NewLine + [Environment]::NewLine)) + [Environment]::NewLine + + @' +fn main() { + let output = std::env::args().nth(1).expect("temp path"); + std::fs::write(format!("{output}/stop.ps1"), windows_stop_script()).unwrap(); + std::fs::write(format!("{output}/restart.ps1"), windows_restart_script()).unwrap(); +} +'@ + $rustPath = Join-Path $root 'lifecycle.rs' + [IO.File]::WriteAllText($rustPath, $rust, [Text.UTF8Encoding]::new($false)) + $program = Join-Path $root 'lifecycle.exe' + $compiler = (Get-Command rustc -ErrorAction Stop).Source + & $compiler --edition=2021 $rustPath -o $program + if ($LASTEXITCODE -ne 0) { throw "Isolated rustc compile failed ($LASTEXITCODE)" } + & $program $root + if ($LASTEXITCODE -ne 0) { throw "Generator execution failed ($LASTEXITCODE)" } + + $stopText = [IO.File]::ReadAllText((Join-Path $root 'stop.ps1')) + $restartText = [IO.File]::ReadAllText((Join-Path $root 'restart.ps1')) + foreach ($name in @('stop','restart')) { + $path = Join-Path $root "$name.ps1" + $tokens = $null + $errors = $null + [void][Management.Automation.Language.Parser]::ParseFile($path, [ref]$tokens, [ref]$errors) + if (@($errors).Count -gt 0) { + throw ("Generated $name script has syntax errors: " + (@($errors) | ForEach-Object Message) -join '; ') + } + } + Write-Output 'GENERATED_POWERSHELL_PARSE=2/2_PASS' + + # Test-only reduction of the deadline avoids making each mock negative case + # wait 15 seconds. The actual generated scripts are parsed above unmodified. + if (-not $stopText.Contains('AddSeconds(15)') -or + -not $restartText.Contains('AddSeconds(15)')) { + throw 'Missing source stop timeout' + } + $stopText = $stopText.Replace('AddSeconds(15)','AddMilliseconds(30)') + $restartText = $restartText.Replace('AddSeconds(15)','AddMilliseconds(30)') + if ($restartText.IndexOf('if ($remainingNative.Count -gt 0)') -gt + $restartText.IndexOf('Start-ScheduledTask -InputObject $task')) { + throw 'Restart ordering is unsafe' + } + + $script:mockState = 'Ready' + $script:mockNativeRemains = $false + $script:mockDenyStop = $false + $script:mockStopped = 0 + $script:mockStarted = 0 + + # Local functions shadow the real Windows cmdlets inside this script's scope. + function Get-ScheduledTask { + param([string]$TaskName, [string]$ErrorAction) + if ($TaskName -ne 'Codexify') { throw 'Unexpected task name' } + [pscustomobject]@{ + State = $script:mockState + Actions = @([pscustomobject]@{WorkingDirectory='C:\CodexifySyntheticOnly'}) + } + } + function Stop-ScheduledTask { + param($InputObject, [string]$ErrorAction) + $script:mockStopped++ + if ($script:mockDenyStop) { throw 'Synthetic access denied' } + } + function Get-CimInstance { + param([string]$ClassName, [string]$Filter, [string]$ErrorAction) + if ($ClassName -ne 'Win32_Process') { throw 'Unexpected query' } + if ($script:mockNativeRemains) { + [pscustomobject]@{ProcessId=4382; ExecutablePath='C:\CodexifySyntheticOnly\bin\codexify.exe'} + } + } + function Start-ScheduledTask { + param($InputObject, [string]$ErrorAction) + $script:mockStarted++ + } + function Start-Sleep { param([int]$Milliseconds) } + + $cases = @( + @{name='stopped_no_process'; script=$stopText; state='Ready'; residual=$false; deny=$false; stops=0; starts=0; error=$null}, + @{name='running_stop_exits'; script=$stopText; state='Running'; residual=$false; deny=$false; stops=1; starts=0; error=$null}, + @{name='running_stop_orphan'; script=$stopText; state='Running'; residual=$true; deny=$false; stops=1; starts=0; error='native processes remain'}, + @{name='stopped_orphan'; script=$stopText; state='Ready'; residual=$true; deny=$false; stops=0; starts=0; error='native processes remain'}, + @{name='stop_denied'; script=$stopText; state='Running'; residual=$false; deny=$true; stops=1; starts=0; error='Synthetic access denied'}, + @{name='running_restart_exits'; script=$restartText; state='Running'; residual=$false; deny=$false; stops=1; starts=1; error=$null}, + @{name='stopped_restart_exits'; script=$restartText; state='Ready'; residual=$false; deny=$false; stops=0; starts=1; error=$null}, + @{name='restart_orphan_refuses_duplicate'; script=$restartText; state='Running'; residual=$true; deny=$false; stops=1; starts=0; error='native processes remain'}, + @{name='restart_denied_refuses_duplicate'; script=$restartText; state='Running'; residual=$false; deny=$true; stops=1; starts=0; error='Synthetic access denied'} + ) + $passed = 0 + foreach ($case in $cases) { + $script:mockState = $case.state + $script:mockNativeRemains = $case.residual + $script:mockDenyStop = $case.deny + $script:mockStopped = 0 + $script:mockStarted = 0 + $caught = $null + try { + & ([scriptblock]::Create($case.script)) | Out-Null + } catch { + $caught = $_.Exception.Message + } + if ($case.error -and (-not $caught -or -not $caught.Contains($case.error))) { + throw "CASE $($case.name): wanted '$($case.error)', got '$caught'" + } + if (-not $case.error -and $caught) { + throw "CASE $($case.name): unexpected error '$caught'" + } + if ($script:mockStopped -ne $case.stops -or $script:mockStarted -ne $case.starts) { + throw "CASE $($case.name): stop/start $script:mockStopped/$script:mockStarted expected $($case.stops)/$($case.starts)" + } + $passed++ + Write-Output "PASS $($case.name)" + } + Write-Output "MOCK_CASES=$passed/$($cases.Count) PASS" + Write-Output 'LIVE_TASK_OR_SERVICE_MUTATIONS=0' +} finally { + $tempBase = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd('\') + '\' + if ([IO.Path]::GetFullPath($root).StartsWith($tempBase, [StringComparison]::OrdinalIgnoreCase) -and + [IO.Path]::GetFileName($root).StartsWith('codexify-windows-contract-', [StringComparison]::Ordinal)) { + Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction SilentlyContinue + } +} diff --git a/scripts/windows-build-native-memory-guard.ps1 b/scripts/windows-build-native-memory-guard.ps1 new file mode 100644 index 00000000..867fe9d7 --- /dev/null +++ b/scripts/windows-build-native-memory-guard.ps1 @@ -0,0 +1,124 @@ +# Bounded offline Codexify build. Never touches the installed native service. +param([switch]$Build) +$ErrorActionPreference = 'Stop' +$ProgressPreference = 'SilentlyContinue' +$minimumStartGb = 5.0 +$abortBelowGb = 1.75 +$maximumMinutes = 12 +$project = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) +$native = Join-Path $env:USERPROFILE '.codexify\bin\codexify.exe' +$candidate = Join-Path $project 'target\debug\codexify.exe' +$git = (Get-Command git -ErrorAction Stop).Source +$cargo = (Get-Command cargo -ErrorAction Stop).Source +function FreeRamGb { + $os = Get-CimInstance Win32_OperatingSystem -ErrorAction Stop + return [math]::Round(([double]$os.FreePhysicalMemory / 1MB), 2) +} +if(-not(Test-Path -LiteralPath $native -PathType Leaf)){ + throw 'Installed native executable is missing' +} +$head = (& $git -C $project rev-parse HEAD).Trim() +if($LASTEXITCODE -ne 0 -or $head -notmatch '^[a-f0-9]{40}$'){ + throw 'Source HEAD is not verified' +} +$dirty = ((& $git -C $project status --porcelain) -join '') +if($LASTEXITCODE -ne 0 -or $dirty){throw 'Source tree is not clean'} +$task = Get-ScheduledTask -TaskName 'Codexify' -TaskPath '\' -ErrorAction Stop +if($task.State -ne 'Running' -or -not $task.Settings.Enabled){ + throw 'The installed native task is not running/enabled' +} +$health = Invoke-RestMethod 'http://127.0.0.1:3000/health' -TimeoutSec 5 +if($health.status -ne 'ok'){throw 'Native service is not healthy'} +$activeCompilers = @(Get-CimInstance Win32_Process -ErrorAction Stop | + Where-Object {$_.Name -in @('cargo.exe','rustc.exe')}) +$free = FreeRamGb +'CURRENT_RAM_FREE_GB='+$free +'MINIMUM_START_GB='+$minimumStartGb +'ABORT_BELOW_GB='+$abortBelowGb +'HEAD='+$head +'OTHER_COMPILERS='+$activeCompilers.Count +if(-not $Build) { + 'DRY_RUN_ONLY=true' + 'NATIVE_BINARY_UNCHANGED=true' + return +} +if($free -lt $minimumStartGb){ + throw ("Build not started: only " + $free + " GB free RAM; require " + $minimumStartGb + " GB") +} +if($activeCompilers.Count -ne 0){throw 'Other Rust compiler tasks are running'} +if((Get-PSDrive -Name C).Free -lt 6GB){throw 'Not enough free disk for offline build'} +$report = Join-Path $env:USERPROFILE ('.codexify\backups\guarded-native-build-' + [DateTime]::UtcNow.ToString('yyyyMMddTHHmmssZ')) +[void](New-Item -Path $report -ItemType Directory -ErrorAction Stop) +$stdout = Join-Path $report 'stdout.log' +$stderr = Join-Path $report 'stderr.log' +$receipt = Join-Path $report 'receipt.txt' +$startTime = [DateTime]::UtcNow +$env:CARGO_BUILD_JOBS = '1' +$env:CARGO_NET_OFFLINE = 'true' +$proc = $null +$originalSha = (Get-FileHash -LiteralPath $native -Algorithm SHA256).Hash.ToLowerInvariant() +function StopOwnCompiler([int]$cargoPid,[datetime]$creationTime) { + # Only the Cargo process launched here and its immediate Rust children. + $children = @(Get-CimInstance Win32_Process -ErrorAction Stop | Where-Object { + $_.ParentProcessId -eq $cargoPid -and $_.Name -eq 'rustc.exe' -and + [datetime]$_.CreationDate -ge $creationTime + }) + foreach($child in $children) { + $again = Get-CimInstance Win32_Process -Filter ('ProcessId='+[int]$child.ProcessId) + if($again -and $again.Name -eq 'rustc.exe' -and + $again.ParentProcessId -eq $cargoPid -and + $again.CreationDate -eq $child.CreationDate){ + Stop-Process -Id $child.ProcessId -Force -ErrorAction SilentlyContinue + } + } + $cargoProcess = Get-CimInstance Win32_Process -Filter ('ProcessId='+$cargoPid) + if($cargoProcess -and $cargoProcess.Name -eq 'cargo.exe' -and + [math]::Abs((([datetime]$cargoProcess.CreationDate)-$creationTime).TotalSeconds) -lt 2){ + Stop-Process -Id $cargoPid -Force -ErrorAction SilentlyContinue + } +} +try { + $proc = Start-Process -FilePath $cargo -ArgumentList 'build','--bin','codexify','--offline','--jobs','1' -WorkingDirectory $project -PassThru -WindowStyle Hidden -RedirectStandardOutput $stdout -RedirectStandardError $stderr -ErrorAction Stop + $creation = (Get-CimInstance Win32_Process -Filter ('ProcessId='+[int]$proc.Id)).CreationDate + 'BUILD_STARTED_PID='+$proc.Id + 'BUILD_RECEIPT='+$receipt + $deadline = [DateTime]::UtcNow.AddMinutes($maximumMinutes) + while(-not $proc.HasExited) { + Start-Sleep -Seconds 4 + $proc.Refresh() + if($proc.HasExited){break} + $free = FreeRamGb + if($free -lt $abortBelowGb -or [DateTime]::UtcNow -ge $deadline) { + StopOwnCompiler $proc.Id $creation + $reason = if($free -lt $abortBelowGb){'low_memory'}else{'timeout'} + Set-Content -LiteralPath $receipt -Value ("status=aborted;reason="+$reason+";freeGb="+$free+";head="+$head) + throw ("Build aborted safely: " + $reason + ", free RAM " + $free + " GB") + } + } + $proc.Refresh() + if($proc.ExitCode -ne 0){ + Set-Content -LiteralPath $receipt -Value ("status=failed;exit="+$proc.ExitCode+";head="+$head) + throw ('Cargo returned exit code '+$proc.ExitCode) + } + if(-not(Test-Path -LiteralPath $candidate -PathType Leaf)){ + throw 'Build reported success but candidate is missing' + } + $newSha = (Get-FileHash -LiteralPath $candidate -Algorithm SHA256).Hash.ToLowerInvariant() + if((Get-FileHash -LiteralPath $native -Algorithm SHA256).Hash.ToLowerInvariant() -ne $originalSha){ + throw 'Installed executable unexpectedly changed' + } + $commitSeconds = (& $git -C $project show -s --format=%ct HEAD).Trim() + if($LASTEXITCODE -ne 0){throw 'Unable to verify commit freshness'} + $commitTime = [DateTimeOffset]::FromUnixTimeSeconds([long]$commitSeconds).UtcDateTime + if((Get-Item -LiteralPath $candidate).LastWriteTimeUtc -le $commitTime){ + throw 'Candidate was not freshly built for current HEAD' + } + Set-Content -LiteralPath $receipt -Value ("status=built;head="+$head+";sha256="+$newSha) + 'BUILD_SUCCESS=true' + 'CANDIDATE_SHA='+$newSha + 'BUILD_RECEIPT='+$receipt +} finally { + if($proc -and -not $proc.HasExited) { + try {StopOwnCompiler $proc.Id $creation}catch{} + } +} diff --git a/scripts/windows-deploy-native-readiness-fix.ps1 b/scripts/windows-deploy-native-readiness-fix.ps1 new file mode 100644 index 00000000..e1a20671 --- /dev/null +++ b/scripts/windows-deploy-native-readiness-fix.ps1 @@ -0,0 +1,357 @@ +param( + [Parameter(Mandatory=$true)][string]$Candidate, + [switch]$Deploy, + [switch]$InterruptNativeCommands, + [string]$ExpectedProfile +) +$ErrorActionPreference='Stop' +$ProgressPreference='SilentlyContinue' +$root=Join-Path $env:USERPROFILE '.codexify' +$live=Join-Path $root 'bin\codexify.exe' +if($ExpectedProfile -and + [IO.Path]::GetFullPath($env:USERPROFILE) -ine [IO.Path]::GetFullPath($ExpectedProfile)){ + throw 'Administrator approval used a different Windows account; refusing to modify that profile' +} +$rootFull=[IO.Path]::GetFullPath($root) +$candidateFull=[IO.Path]::GetFullPath($Candidate) +$project=[IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) +if(-not $candidateFull.StartsWith((Join-Path $project 'target\debug\'),[StringComparison]::OrdinalIgnoreCase) -or + [IO.Path]::GetFileName($candidateFull) -cne 'codexify.exe'){ + throw 'Candidate must be the verified local Codexify debug executable' +} +foreach($p in @($live,$candidateFull)){ + if(-not(Test-Path -LiteralPath $p -PathType Leaf)){throw 'Required native executable missing'} + if((Get-Item -LiteralPath $p).Length -lt 10000000){throw 'Native binary unexpectedly small'} +} +function Hash([string]$path){return (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()} +$oldHash=Hash $live +$newHash=Hash $candidateFull +if($oldHash -eq $newHash){Write-Output 'ALREADY_INSTALLED=true';return} +if(-not $Deploy){ + Write-Output ('DRY_RUN_CANDIDATE_SHA='+$newHash) + Write-Output ('DRY_RUN_INSTALLED_SHA='+$oldHash) + Write-Output 'NO_SERVICE_OR_FILE_CHANGES=true' + return +} +$identity=[Security.Principal.WindowsIdentity]::GetCurrent() +$principal=[Security.Principal.WindowsPrincipal]::new($identity) +if(-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)){ + throw 'Administrator approval is required to manage the existing Codexify scheduled task' +} +# A native service replacement kills its owning Windows Job Object. When this +# installer is spawned by a Codexify tool, it belongs to the same tree and +# may be terminated halfway through the atomic swap. Require an independent +# launcher (for example, a temporary one-shot Task Scheduler task). +$ancestorPid=[int]$PID +for($depth=0;$depth -lt 16;$depth++){ + $ancestor=Get-CimInstance Win32_Process -Filter ('ProcessId='+$ancestorPid) + if(-not $ancestor){break} + if($ancestor.ExecutablePath -ieq $live){ + throw 'Refusing native replacement from inside its own service process tree; use independent maintenance launcher' + } + if(-not $ancestor.ParentProcessId -or [int]$ancestor.ParentProcessId -eq $ancestorPid){break} + $ancestorPid=[int]$ancestor.ParentProcessId +} +$backup=Join-Path $root ('backups\native-readiness-fix-'+[DateTime]::UtcNow.ToString('yyyyMMddTHHmmssZ')) +[void](New-Item -ItemType Directory -Path $backup) +$old=Join-Path $backup 'codexify.before.exe' +$failed=Join-Path $backup 'codexify.failed.exe' +$stage=Join-Path $root 'bin\codexify.incoming-readiness.exe' +if(Test-Path -LiteralPath $stage){throw 'A staged native executable already exists; aborting'} +Copy-Item -LiteralPath $live -Destination $old +if((Hash $old) -ne $oldHash){throw 'Rollback executable hash mismatch'} +Copy-Item -LiteralPath $candidateFull -Destination $stage +if((Hash $stage) -ne $newHash){throw 'Staged executable hash mismatch'} +$oldReceipt=@{beforeSha=$oldHash;afterSha=$newHash;startUtc=[DateTime]::UtcNow.ToString('o');phase='prepared';backup=$backup} +$oldReceipt|ConvertTo-Json -Depth 5|Set-Content -LiteralPath (Join-Path $backup 'receipt.json') +function RunCli([string]$exe,[string[]]$arguments){ + $stdout=Join-Path $backup (($arguments -join '-')+'.stdout') + $stderr=Join-Path $backup (($arguments -join '-')+'.stderr') + $p=Start-Process -FilePath $exe -ArgumentList $arguments -WindowStyle Hidden -PassThru -RedirectStandardOutput $stdout -RedirectStandardError $stderr + $null=$p.Handle + if(-not $p.WaitForExit(60000)){throw 'Codexify CLI did not exit within deadline'} + $p.Refresh() + if($null -ne $p.ExitCode -and $p.ExitCode -ne 0){throw ('Codexify CLI failed; inspect '+$stderr)} +} +function Ready { + try { + $h=Invoke-RestMethod -Uri 'http://127.0.0.1:3000/health' -TimeoutSec 4 + return $h.status -eq 'ok' + } catch{return $false} +} +function Active-NativeChildCommands { + # Native /health can report zero occupied MCP slots while tool sessions still + # own long-running subprocesses (pytest, cargo, shell, etc.). Never terminate + # the listener in that state. Persistent upstream servers created during the + # native startup grace period are not treated as unfinished user commands. + $listenerId=Get-NetTCPConnection -State Listen -LocalPort 3000 -ErrorAction Stop | + Select-Object -First 1 -ExpandProperty OwningProcess + if(-not $listenerId){return $true} + $listener=Get-CimInstance Win32_Process -Filter ('ProcessId='+[int]$listenerId) + if(-not $listener){return $true} + $supervisor=Get-CimInstance Win32_Process -Filter ('ProcessId='+[int]$listener.ParentProcessId) + if(-not $supervisor -or $supervisor.ExecutablePath -ine $live){return $true} + $startupCutoff=$supervisor.CreationDate.AddMinutes(5) + $all=@(Get-CimInstance Win32_Process) + $descendants=[Collections.Generic.HashSet[int]]::new() + [void]$descendants.Add([int]$listenerId) + do { + $changed=$false + foreach($process in $all){ + if($descendants.Contains([int]$process.ParentProcessId) -and + $descendants.Add([int]$process.ProcessId)){$changed=$true} + } + }while($changed) + $commands=@($all | Where-Object { + $_.ProcessId -ne $listenerId -and $descendants.Contains([int]$_.ProcessId) -and + $_.CreationDate -ge $startupCutoff -and + $_.Name -match '^(powershell|pwsh|cmd|python|pytest|uv|cargo|rustc|git|node|bun|link|ninja|make|wsl)(\.exe)?$' + }) + return $commands.Count -gt 0 +} +function Idle { + try { + $h=Invoke-RestMethod -Uri 'http://127.0.0.1:3000/health' -TimeoutSec 5 + if($h.status -ne 'ok'){return $false} + if(-not $InterruptNativeCommands){ + if($h.filesystem.occupiedWorkerSlots -gt 0 -or $h.filesystem.queuedRequests -gt 0){return $false} + foreach($u in $h.upstreams.PSObject.Properties){if($u.Value.activeRequests -gt 0 -or $u.Value.queuedRequests -gt 0){return $false}} + if(Active-NativeChildCommands){return $false} + } + $desc=Join-Path $root 'browser\descriptor.json' + if(Test-Path -LiteralPath $desc){ + $d=Get-Content -LiteralPath $desc -Raw|ConvertFrom-Json + $state=Invoke-RestMethod -Uri ($d.endpoint.TrimEnd('/')+'/v1/health') -Headers @{Authorization='Bearer '+$d.token} -TimeoutSec 5 + if($state.status -ne 'idle' -or -not $state.authenticated -or $state.availableActionSlots -lt 1 -or + $state.activeActionId -or @($state.activeActionIds).Count -gt 0){return $false} + } + return $true + }catch{return $false} +} +function Browser-Has-No-Active-Send { + # During a native stop, its /health may legitimately stop responding and a + # read-only turn-handoff can reserve the only browser lane. Neither condition + # is proof of an in-flight Send. Fail closed on any unobservable browser lane + # or on an owned/pending Send or action cleanup. + try { + $path=Join-Path $root 'browser\descriptor.json' + if(-not(Test-Path -LiteralPath $path -PathType Leaf)){return $false} + $descriptor=Get-Content -LiteralPath $path -Raw|ConvertFrom-Json + $headers=@{Authorization='Bearer '+$descriptor.token} + $snapshot=Invoke-RestMethod -Uri ($descriptor.endpoint.TrimEnd('/')+'/v1/diagnostics/readiness') -Headers $headers -TimeoutSec 5 + if($snapshot.closed -or $snapshot.maintenance -or -not $snapshot.lanes){return $false} + foreach($lane in $snapshot.lanes){ + if($lane.activeAction -or $lane.pendingAction -or + $lane.actionCleanupPending -or $lane.connectorRefreshPending -or $lane.retired){ + return $false + } + } + return $true + }catch{return $false} +} +function Stop-VerifiedUnresponsiveNativePair { + # The installed service's Windows Stop-ScheduledTask script suppresses + # errors, so a successful CLI receipt does not prove that its processes quit. + # Only terminate the exact installed supervisor/listener pair that was + # verified *before* invoking service stop, and only if no work is active. + if($InterruptNativeCommands){ + if(-not(Browser-Has-No-Active-Send)){ + throw 'Browser action ownership could not be ruled out; refusing forced native stop' + } + Write-Output 'NO_BROWSER_SEND_OWNERSHIP_VERIFIED=true' + } elseif(-not(Idle)){ + throw 'Native/browser work became active; refusing forced native stop' + } + $task=Get-ScheduledTask -TaskName 'Codexify' -TaskPath '\' -ErrorAction Stop + if((-not $task.Settings.Enabled -and -not $script:taskTemporarilyDisabled) -or + $task.Principal.LogonType -ne 'Interactive' -or + $task.Principal.RunLevel -ne 'Limited' -or + [IO.Path]::GetFullPath([string]$task.Actions[0].WorkingDirectory) -ine [IO.Path]::GetFullPath($root) -or + [IO.Path]::GetFullPath([string]$task.Actions[0].Execute) -ine (Join-Path $env:WINDIR 'System32\WindowsPowerShell\v1.0\powershell.exe')){ + throw 'Installed scheduled task identity is not trusted for a native stop' + } + $owners=@(Get-NetTCPConnection -State Listen -ErrorAction Stop | + Where-Object {$_.LocalPort -in @(3000,3120)} | Select-Object -ExpandProperty OwningProcess -Unique) + if($owners.Count -ne 1){throw 'Unexpected owner of Codexify listening ports'} + $listener=Get-CimInstance Win32_Process -Filter ('ProcessId='+[int]$owners[0]) + if(-not $listener -or $listener.ExecutablePath -ine $live){throw 'Listener executable changed'} + $supervisor=Get-CimInstance Win32_Process -Filter ('ProcessId='+[int]$listener.ParentProcessId) + if(-not $supervisor -or $supervisor.ExecutablePath -ine $live -or + $supervisor.CommandLine -notmatch 'service run --config'){ + throw 'Native supervisor identity changed' + } + $pair=@(Get-CimInstance Win32_Process -Filter "Name='codexify.exe'" | + Where-Object {$_.ExecutablePath -ieq $live}) + if($pair.Count -ne 2 -or ($pair.ProcessId -notcontains $listener.ProcessId) -or + ($pair.ProcessId -notcontains $supervisor.ProcessId)){ + throw 'More than the verified supervisor and listener are running' + } + # Verify PID ownership again immediately before termination. Never kill a + # later process that reused a PID. + foreach($verified in @($listener,$supervisor)){ + $current=Get-CimInstance Win32_Process -Filter ('ProcessId='+[int]$verified.ProcessId) + if(-not $current -or $current.ExecutablePath -ine $live -or + $current.CreationDate -ne $verified.CreationDate){ + throw 'Native process identity changed before stop' + } + } + foreach($verified in @($supervisor,$listener)){ + $current=Get-CimInstance Win32_Process -Filter ('ProcessId='+[int]$verified.ProcessId) + if(-not $current){continue} # Supervisor exit can close the listener too. + if($current.ExecutablePath -ine $live -or + $current.CreationDate -ne $verified.CreationDate){ + throw 'Native process identity changed during stop; refusing unrelated process' + } + Stop-Process -Id $verified.ProcessId -Force -ErrorAction Stop + } + Write-Output 'VERIFIED_STALE_NATIVE_PAIR_STOPPED=true' +} +$stopped=$false +$replaced=$false +$script:taskTemporarilyDisabled=$false +function Restore-TaskEnablement { + if(-not $script:taskTemporarilyDisabled){return} + Enable-ScheduledTask -TaskName 'Codexify' -TaskPath '\' -ErrorAction Stop | Out-Null + $task=Get-ScheduledTask -TaskName 'Codexify' -TaskPath '\' -ErrorAction Stop + if(-not $task.Settings.Enabled){throw 'Existing Codexify task could not be re-enabled'} + $script:taskTemporarilyDisabled=$false + Write-Output 'ORIGINAL_CODEXIFY_TASK_REENABLED=true' +} +try { + Write-Output 'STAGE_VERIFIED=true' + if($InterruptNativeCommands){Write-Output 'AUTHORIZED_NATIVE_COMMAND_INTERRUPTION=true'} + $deadline=[DateTime]::UtcNow.AddMinutes(3) + while(-not(Idle) -and [DateTime]::UtcNow -lt $deadline){Start-Sleep -Seconds 3} + if(-not(Idle)){throw 'Native or browser activity remained busy; original service preserved'} + Write-Output 'IDLE_WINDOW_VERIFIED=true' + # Disable the existing task *temporarily* to prevent its one-minute failure + # recovery policy from racing the binary swap. Preserve task definition. + $existingTask=Get-ScheduledTask -TaskName 'Codexify' -TaskPath '\' -ErrorAction Stop + if(-not $existingTask.Settings.Enabled -or $existingTask.Principal.LogonType -ne 'Interactive' -or + $existingTask.Principal.RunLevel -ne 'Limited' -or + [IO.Path]::GetFullPath([string]$existingTask.Actions[0].WorkingDirectory) -ine [IO.Path]::GetFullPath($root)){ + throw 'Existing Codexify task identity or enabled state is unexpected' + } + Disable-ScheduledTask -TaskName 'Codexify' -TaskPath '\' -ErrorAction Stop | Out-Null + $script:taskTemporarilyDisabled=$true + $verifiedTask=Get-ScheduledTask -TaskName 'Codexify' -TaskPath '\' -ErrorAction Stop + if($verifiedTask.Settings.Enabled){throw 'Native task did not disable; aborting before shutdown'} + Write-Output 'NATIVE_TASK_TEMPORARILY_DISABLED=true' + $originalNative=@(Get-CimInstance Win32_Process -Filter "Name='codexify.exe'"| + Where-Object {$_.ExecutablePath -ieq $live}) + $stopped=$true + RunCli $live @('service','stop') + $deadline=[DateTime]::UtcNow.AddSeconds(7) + while([DateTime]::UtcNow -lt $deadline){ + $p=@(Get-CimInstance Win32_Process -Filter "Name='codexify.exe'"|Where-Object {$_.ExecutablePath -ieq $live}) + if($p.Count -eq 0){break} + Start-Sleep -Milliseconds 500 + } + if($p.Count -gt 0){ + # The CLI currently suppresses Stop-ScheduledTask errors and can report + # success while the scheduled task remains running. A real failure should + # not be ignored; explicitly stop the existing task from this independent + # maintenance process before falling back to the verified process pair. + try { + $task=Get-ScheduledTask -TaskName 'Codexify' -TaskPath '\' -ErrorAction Stop + Stop-ScheduledTask -InputObject $task -ErrorAction Stop + Write-Output 'SCHEDULED_TASK_STOP_REQUESTED=true' + } catch { + Write-Output ('SCHEDULED_TASK_STOP_FAILED='+$_.Exception.GetType().Name) + } + Start-Sleep -Seconds 3 + $p=@(Get-CimInstance Win32_Process -Filter "Name='codexify.exe'"|Where-Object {$_.ExecutablePath -ieq $live}) + } + if($p.Count -gt 0){ + $currentIds=@($p | Select-Object -ExpandProperty ProcessId | Sort-Object) -join ',' + $originalIds=@($originalNative | Select-Object -ExpandProperty ProcessId | Sort-Object) -join ',' + # A scheduled-task stop can race a short-lived CLI helper. Wait for that + # helper to finish, but never terminate an unrecognized native process. + $helperDeadline=[DateTime]::UtcNow.AddSeconds(8) + while($currentIds -ne $originalIds -and [DateTime]::UtcNow -lt $helperDeadline){ + Start-Sleep -Milliseconds 400 + $p=@(Get-CimInstance Win32_Process -Filter "Name='codexify.exe'"|Where-Object {$_.ExecutablePath -ieq $live}) + if($p.Count -eq 0){break} + $currentIds=@($p | Select-Object -ExpandProperty ProcessId | Sort-Object) -join ',' + } + if($p.Count -eq 0){Write-Output 'NATIVE_PROCESSES_EXITED_DURING_HELPER_GRACE=true'} + } + if($p.Count -gt 0){ + if($currentIds -ne $originalIds){ + throw 'A new native process started during service stop; binary untouched' + } + Stop-VerifiedUnresponsiveNativePair + $deadline=[DateTime]::UtcNow.AddSeconds(12) + do { + $p=@(Get-CimInstance Win32_Process -Filter "Name='codexify.exe'"|Where-Object {$_.ExecutablePath -ieq $live}) + if($p.Count -eq 0){break} + Start-Sleep -Milliseconds 500 + }while([DateTime]::UtcNow -lt $deadline) + } + if($p.Count -ne 0){throw 'Original Codexify service did not stop; binary untouched'} + if((Hash $live) -ne $oldHash){throw 'Installed binary changed after the preflight; refusing replacement'} + # File.Replace is an atomic same-volume swap; an interrupted copy cannot + # leave the only installed executable missing. + [IO.File]::Replace($stage,$live,(Join-Path $backup 'codexify.original-slot.exe'),$true) + $replaced=$true + if((Hash $live) -ne $newHash){throw 'Installed executable hash mismatch'} + Restore-TaskEnablement + RunCli $live @('service','start') + $deadline=[DateTime]::UtcNow.AddSeconds(80) + while(-not(Ready) -and [DateTime]::UtcNow -lt $deadline){Start-Sleep -Seconds 2} + if(-not(Ready)){throw 'Updated native service did not reach healthy status'} + $descriptorPath=Join-Path $root 'browser\descriptor.json' + $browserLive=$false + if(Test-Path -LiteralPath $descriptorPath){ + try { + $d=Get-Content -LiteralPath $descriptorPath -Raw|ConvertFrom-Json + $l=Invoke-RestMethod -Uri ($d.endpoint.TrimEnd('/')+'/v1/liveness') -Headers @{Authorization='Bearer '+$d.token} -TimeoutSec 6 + $browserLive=$l.available -eq $true + }catch{} + } + if(-not $browserLive){ + RunCli $live @('browser','start') + Start-Sleep -Seconds 3 + $d=Get-Content -LiteralPath $descriptorPath -Raw|ConvertFrom-Json + $l=Invoke-RestMethod -Uri ($d.endpoint.TrimEnd('/')+'/v1/liveness') -Headers @{Authorization='Bearer '+$d.token} -TimeoutSec 6 + if($l.available -ne $true){throw 'Browser companion liveness was not restored'} + } + $oldReceipt.phase='completed';$oldReceipt.endUtc=[DateTime]::UtcNow.ToString('o') + $oldReceipt|ConvertTo-Json -Depth 5|Set-Content -LiteralPath (Join-Path $backup 'receipt.json') + Write-Output ('NATIVE_INSTALLED_AND_HEALTHY=true;BACKUP='+$backup) +} catch { + $failure=$_.Exception.Message + Write-Output ('INSTALL_FAILURE='+$failure) + $oldReceipt.phase='failed';$oldReceipt.error=$failure + if($replaced){ + try { + try {RunCli $live @('service','stop')} catch {} + Start-Sleep -Seconds 2 + $alive=@(Get-CimInstance Win32_Process -Filter "Name='codexify.exe'"|Where-Object {$_.ExecutablePath -ieq $live}) + if($alive.Count){throw 'Replacement still executing; no overwrite performed'} + $restore=Join-Path $root 'bin\codexify.restore-readiness.exe' + if(Test-Path -LiteralPath $restore){throw 'A native rollback stage already exists'} + Copy-Item -LiteralPath $old -Destination $restore + if((Hash $restore) -ne $oldHash){throw 'Rollback stage hash mismatch'} + [IO.File]::Replace($restore,$live,$failed,$true) + if((Hash $live) -ne $oldHash){throw 'Rollback verification failed'} + Restore-TaskEnablement + RunCli $live @('service','start') + Write-Output 'ROLLBACK_BINARY_VERIFIED=true' + $oldReceipt.phase='rolled_back' + }catch{ + $oldReceipt.rollbackError=$_.Exception.Message + Write-Output ('ROLLBACK_REQUIRES_ATTENTION='+$_.Exception.Message) + } + }elseif($stopped){ + try {Restore-TaskEnablement}catch {Write-Output ('TASK_REENABLE_FAILED='+$_.Exception.Message)} + try {RunCli $live @('service','start')}catch {Write-Output ('SERVICE_RESTART_FAILED='+$_.Exception.Message)} + } + $oldReceipt|ConvertTo-Json -Depth 5|Set-Content -LiteralPath (Join-Path $backup 'receipt.json') + throw +} finally{ + if($script:taskTemporarilyDisabled){ + try {Restore-TaskEnablement}catch {Write-Output ('TASK_RESTORE_REQUIRES_ATTENTION='+$_.Exception.Message)} + } + if(Test-Path -LiteralPath $stage){Remove-Item -LiteralPath $stage -Force -ErrorAction SilentlyContinue} +} diff --git a/scripts/windows-native-readiness-task-wrapper.ps1 b/scripts/windows-native-readiness-task-wrapper.ps1 new file mode 100644 index 00000000..55a45d3c --- /dev/null +++ b/scripts/windows-native-readiness-task-wrapper.ps1 @@ -0,0 +1,64 @@ +param( + [Parameter(Mandatory=$true)][string]$Candidate, + [Parameter(Mandatory=$true)][string]$ReportDirectory, + [switch]$Deploy, + [switch]$InterruptNativeCommands, + [string]$ExpectedProfile +) +$ErrorActionPreference='Stop' +$ProgressPreference='SilentlyContinue' +$root=Join-Path $env:USERPROFILE '.codexify\backups' +$report=[IO.Path]::GetFullPath($ReportDirectory) +if(-not $report.StartsWith(([IO.Path]::GetFullPath($root).TrimEnd('\')+'\'),[StringComparison]::OrdinalIgnoreCase)){ + throw 'Maintenance report path is not under Codexify backups' +} +[void](New-Item -ItemType Directory -Path $report -Force) +$log=Join-Path $report ($(if($Deploy){'deploy'}else{'dryrun'})+'.log') +function Record([string]$message) { + $line=([DateTime]::UtcNow.ToString('o')+' '+$message) + Add-Content -LiteralPath $log -Value $line -Encoding UTF8 + Write-Output $line +} +$parent=Get-CimInstance Win32_Process -Filter ('ProcessId='+$PID) +$parentPid=if($parent){[int]$parent.ParentProcessId}else{0} +$ancestor=if($parentPid){Get-CimInstance Win32_Process -Filter ('ProcessId='+$parentPid)}else{$null} +Record ('MAINTENANCE_MODE='+$(if($Deploy){'deploy'}else{'dryrun'})+ + ' SCRIPT_PID='+$PID+' PARENT_PID='+$parentPid+ + ' PARENT_IMAGE='+$(if($ancestor){$ancestor.Name}else{'unknown'})) +$taskName='Codexify-Native-Readiness-Maintenance' +if($Deploy){ + # Start-Process -Verb RunAs from a Codexify tool can still belong to the + # service's Windows job. That elevated helper can die when the native server + # stops, leaving Task Scheduler disabled. Only an independently launched + # on-demand, highest-privilege Scheduled Task is allowed to deploy. + $identity=[Security.Principal.WindowsIdentity]::GetCurrent() + $principal=[Security.Principal.WindowsPrincipal]::new($identity) + if(-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)){ + throw 'Deployment requires an elevated independent Task Scheduler launcher' + } + $task=Get-ScheduledTask -TaskName $taskName -TaskPath '\' -ErrorAction Stop + $taskArguments=[string]$task.Actions[0].Arguments + if(-not $ancestor -or $ancestor.Name -ine 'svchost.exe' -or + $task.State -ne 'Running' -or $task.Principal.RunLevel -ne 'Highest' -or + @($task.Triggers|Where-Object {$_}).Count -ne 0 -or + @($task.Actions).Count -ne 1 -or + $taskArguments -notlike '*windows-native-readiness-task-wrapper.ps1*' -or + $taskArguments -notlike '*-Deploy*' -or + $taskArguments -notlike ('*'+$ReportDirectory+'*') -or + $taskArguments -notlike ('*'+$Candidate+'*')){ + throw 'Unverified task origin; refusing deployment from a direct elevated process' + } + Record 'INDEPENDENT_ELEVATED_TASK_ORIGIN_VERIFIED=true' +} +$installer=Join-Path $PSScriptRoot 'windows-deploy-native-readiness-fix.ps1' +try { + & $installer -Candidate $Candidate -Deploy:$Deploy -InterruptNativeCommands:$InterruptNativeCommands -ExpectedProfile $ExpectedProfile 2>&1 | ForEach-Object { + $line=($_|Out-String).Trim() + if($line){Record $line} + } + Record 'MAINTENANCE_RESULT=completed' + exit 0 +} catch { + Record ('MAINTENANCE_RESULT=failed ERROR='+$_.Exception.Message) + exit 1 +} diff --git a/scripts/windows-register-independent-native-maintenance.ps1 b/scripts/windows-register-independent-native-maintenance.ps1 new file mode 100644 index 00000000..05ba097e --- /dev/null +++ b/scripts/windows-register-independent-native-maintenance.ps1 @@ -0,0 +1,107 @@ +# Safely launch an authorized native Codexify maintenance from an independent +# Administrator-level Windows Scheduled Task. Without -Deploy: read-only. +# Do not call the native installer directly from a Codexify tool or UAC child. +param( + [switch]$Deploy, + [switch]$InterruptNativeCommands, + [string]$ExpectedCandidateSha256 +) +$ErrorActionPreference = 'Stop' +$ProgressPreference = 'SilentlyContinue' + +$project = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) +$profile = [IO.Path]::GetFullPath($env:USERPROFILE) +$root = Join-Path $profile '.codexify' +$installed = Join-Path $root 'bin\codexify.exe' +$candidate = Join-Path $project 'target\debug\codexify.exe' +$wrapper = Join-Path $PSScriptRoot 'windows-native-readiness-task-wrapper.ps1' +$taskName = 'Codexify-Native-Readiness-Maintenance' +$gitExe = (Get-Command git -ErrorAction Stop).Source + +foreach($path in @($installed,$candidate,$wrapper)){ + if(-not(Test-Path -LiteralPath $path -PathType Leaf)){ + throw "Missing local maintenance prerequisite: $path" + } +} +$sha = (Get-FileHash -LiteralPath $candidate -Algorithm SHA256).Hash.ToLowerInvariant() +$installedSha = (Get-FileHash -LiteralPath $installed -Algorithm SHA256).Hash.ToLowerInvariant() +$head = (& $gitExe -C $project rev-parse HEAD).Trim() +if($LASTEXITCODE -ne 0 -or $head -notmatch '^[0-9a-f]{40}$'){ + throw 'Cannot verify local source commit' +} +$commitSeconds = (& $gitExe -C $project show -s --format=%ct HEAD).Trim() +if($LASTEXITCODE -ne 0 -or $commitSeconds -notmatch '^\d+$'){ + throw 'Cannot verify commit timestamp' +} +$commitTime = [DateTimeOffset]::FromUnixTimeSeconds([long]$commitSeconds).UtcDateTime +$candidateTime = (Get-Item -LiteralPath $candidate).LastWriteTimeUtc +$sourceDirty = -not [string]::IsNullOrWhiteSpace(((& $gitExe -C $project status --porcelain) -join '')) +if($LASTEXITCODE -ne 0){throw 'Cannot verify source cleanliness'} +$candidateFresh = $candidateTime -gt $commitTime + +'HEAD='+$head +'CANDIDATE_SHA='+$sha +'INSTALLED_SHA='+$installedSha +'CANDIDATE_NEWER_THAN_HEAD='+$candidateFresh +'SOURCE_CLEAN='+(-not $sourceDirty) + +if(-not $Deploy){ + 'DRY_RUN_ONLY=true' + 'WINDOWS_TASK_AND_NATIVE_EXECUTABLE_UNCHANGED=true' + return +} +if($sourceDirty){throw 'Worktree has uncommitted changes; cannot deploy'} +if(-not $candidateFresh){throw 'Candidate was built before the current source commit; rebuild first'} +if([string]::IsNullOrWhiteSpace($ExpectedCandidateSha256) -or + $ExpectedCandidateSha256 -notmatch '^[A-Fa-f0-9]{64}$' -or + $sha -ne $ExpectedCandidateSha256.ToLowerInvariant()){ + throw 'Candidate SHA must be explicitly confirmed before elevated deployment' +} +if($sha -eq $installedSha){throw 'Candidate is already installed; no restart needed'} +$identity = [Security.Principal.WindowsIdentity]::GetCurrent() +$principal = [Security.Principal.WindowsPrincipal]::new($identity) +if(-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)){ + throw 'Run as Administrator to register the independent highest-privilege maintenance task' +} +if(Get-ScheduledTask -TaskName $taskName -TaskPath '\' -ErrorAction SilentlyContinue){ + throw 'Maintenance task already exists; refusing duplicate' +} +$nativeTask = Get-ScheduledTask -TaskName 'Codexify' -TaskPath '\' -ErrorAction Stop +if($nativeTask.State -ne 'Running' -or -not $nativeTask.Settings.Enabled){ + throw 'Existing native scheduled task is not healthy and enabled' +} +try{ + $health = Invoke-RestMethod 'http://127.0.0.1:3000/health' -TimeoutSec 5 + if($health.status -ne 'ok'){throw 'Native health is not ok'} +}catch{throw 'Native HTTP health is unavailable; refusing restart'} +$descriptor = Get-Content -LiteralPath (Join-Path $root 'browser\descriptor.json') -Raw | + ConvertFrom-Json +$browser = Invoke-RestMethod ($descriptor.endpoint.TrimEnd('/')+'/v1/health?ready=1') -Headers @{ + Authorization='Bearer '+$descriptor.token +} -TimeoutSec 5 +if($browser.status -ne 'idle' -or -not $browser.authenticated -or + $browser.availableActionSlots -lt 1 -or + @($browser.activeActionIds|Where-Object {$_}).Count -ne 0){ + throw 'Browser is busy or unverified; refusing native maintenance' +} + +$report = Join-Path $root ('backups\native-readiness-task-'+[DateTime]::UtcNow.ToString('yyyyMMddTHHmmssZ')) +[void](New-Item -Path $report -ItemType Directory) +$engine = Join-Path $env:WINDIR 'System32\WindowsPowerShell\v1.0\powershell.exe' +$arguments = '-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File "'+ + $wrapper+'" -Candidate "'+$candidate+'" -ReportDirectory "'+$report+ + '" -ExpectedProfile "'+$profile+'" -Deploy' +if($InterruptNativeCommands){$arguments += ' -InterruptNativeCommands'} +$action = New-ScheduledTaskAction -Execute $engine -Argument $arguments -WorkingDirectory $PSScriptRoot +$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes 12) -MultipleInstances IgnoreNew +$taskPrincipal = New-ScheduledTaskPrincipal -UserId $identity.Name -LogonType Interactive -RunLevel Highest +$registered = Register-ScheduledTask -TaskName $taskName -TaskPath '\' -Action $action -Settings $settings -Principal $taskPrincipal -Description 'Explicit one-time native maintenance; zero automatic triggers' -ErrorAction Stop +if(@($registered.Triggers|Where-Object {$_}).Count -ne 0 -or + $registered.Principal.RunLevel -ne 'Highest'){ + throw 'Unexpected task privileges or triggers; task not started' +} +Start-ScheduledTask -TaskName $taskName -TaskPath '\' -ErrorAction Stop +'INDEPENDENT_ELEVATED_MAINTENANCE_STARTED=true' +'RECEIPT_PATH='+$report +'NO_AUTOMATIC_TRIGGERS=true' +'FOLLOW_DEPLOYMENT_LOG_AND_REMOVE_TASK_AFTER_COMPLETION=true' diff --git a/src/agent_automation/install.rs b/src/agent_automation/install.rs index 05c9a0a3..34ad2576 100644 --- a/src/agent_automation/install.rs +++ b/src/agent_automation/install.rs @@ -326,6 +326,11 @@ impl BrowserCompanionManager { .stdin(Stdio::null()) .stdout(Stdio::from(log)) .stderr(Stdio::from(stderr)); + // Preserve the original browser-companion Send gate. The lock file + // intentionally need not exist until the provider first uses it. + if let Some(path) = &self.config.provider_send_gate_path { + command.env("CODEXIFY_BROWSER_SEND_GATE_PATH", path); + } configure_detached_process(&mut command); let mut child = command .spawn() diff --git a/src/agent_automation/store.rs b/src/agent_automation/store.rs index cf167745..71e4554a 100644 --- a/src/agent_automation/store.rs +++ b/src/agent_automation/store.rs @@ -339,6 +339,8 @@ pub struct AutomationTaskState { offline_response_grace_ms: u64, #[serde(skip_serializing_if = "super::turn_renewal::TurnRenewalState::is_empty")] pub turn_renewal: super::turn_renewal::TurnRenewalState, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub retired_terminal_handoffs: Vec, #[serde(default)] owner_goal_requests: Vec, } @@ -363,6 +365,7 @@ impl Default for AutomationTaskState { retry_timings: RetryTimings::default(), offline_response_grace_ms: 0, turn_renewal: Default::default(), + retired_terminal_handoffs: Vec::new(), owner_goal_requests: Vec::new(), } } @@ -1190,6 +1193,16 @@ impl AgentAutomationStore { ) -> Result { validate_goal_markdown(markdown)?; self.mutate(task, |state| { + let previous_handoff_retired = if state.goal.as_ref().is_some_and(|goal| { + matches!(goal.status, GoalStatus::Completed | GoalStatus::Blocked | GoalStatus::Error) + }) && state.turn_renewal.handoff.is_some() { + if !super::turn_renewal::retire_obsolete_terminal_handoff(state, now_ms) { + return Err("A previous goal still has an unverified or active handoff; preserve its Send and resolve it before replacing the goal".into()); + } + true + } else { + false + }; let revision = state.goal.as_ref().map_or(Ok(1), |goal| { goal.revision .checked_add(1) @@ -1217,7 +1230,7 @@ impl AgentAutomationStore { state.agents.latest_report = None; state.agents.report_at_ms = None; state.goal_wake = GoalWakeState::default(); - if state.action.goal_revision.is_some() { + if previous_handoff_retired || state.action.goal_revision.is_some() { state.action = AutomationActionState::default(); } Ok(goal) @@ -1463,6 +1476,16 @@ impl AgentAutomationStore { let mut updated_active_goal = false; let (kind, goal) = match command { OwnerGoalCommand::Set { markdown } => { + let previous_handoff_retired = if state.goal.as_ref().is_some_and(|goal| { + matches!(goal.status, GoalStatus::Completed | GoalStatus::Blocked | GoalStatus::Error) + }) && state.turn_renewal.handoff.is_some() { + if !super::turn_renewal::retire_obsolete_terminal_handoff(state, now_ms) { + return Err("A previous goal still has an unverified or active handoff; preserve its Send and resolve it before replacing the goal".into()); + } + true + } else { + false + }; let revision = state.goal.as_ref().map_or(Ok(1), |goal| { goal.revision .checked_add(1) @@ -1510,7 +1533,7 @@ impl AgentAutomationStore { && !state.action.automatic_retry_in_progress && !state.action.automatic_retry_paused && state.suspended_retry.is_none(); - if (!preserve_action && state.action.goal_revision.is_some()) || superseded_unsent_goal { + if (!preserve_action && state.action.goal_revision.is_some()) || superseded_unsent_goal || previous_handoff_retired { state.action = AutomationActionState::default(); } (OwnerGoalCommandKind::Set, Some(goal)) @@ -4193,7 +4216,39 @@ fn persist_private_record(path: &Path, record: &impl Serialize) -> Result<(), St // atomic replacement and sync_all for identical bytes. Comparing the // serialized record also preserves migrations and ignores runtime-only // fields rather than confusing them with durable changes. - if read_private_record(path)?.as_deref() == Some(bytes.as_slice()) { + // An exclusive Windows reader can temporarily prevent the no-op comparison. + // In that specific case, preserve validation and let the atomic publisher's + // bounded sharing-violation retry decide whether replacement is safe. + let unchanged = match read_private_record(path) { + Ok(existing) => existing.as_deref() == Some(bytes.as_slice()), + Err(read_error) => { + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + let mut options = OpenOptions::new(); + options.read(true); + options.custom_flags( + windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT, + ); + if matches!( + options + .open(path) + .err() + .and_then(|error| error.raw_os_error()), + Some(32 | 33) + ) { + false + } else { + return Err(read_error); + } + } + #[cfg(not(windows))] + { + return Err(read_error); + } + } + }; + if unchanged { return Ok(()); } let mut temporary = tempfile::NamedTempFile::new_in(parent) @@ -4329,6 +4384,26 @@ fn validate_state(state: &AutomationTaskState) -> Result<(), String> { } validate_action(&state.action)?; validate_goal_wake(&state.goal_wake)?; + if state.retired_terminal_handoffs.len() > super::turn_renewal::MAX_RETIRED_TERMINAL_HANDOFFS { + return Err("Agent automation retired handoff history is too large".into()); + } + for retired in &state.retired_terminal_handoffs { + let Some(handoff) = retired.renewal.handoff.as_ref() else { + return Err("Retired handoff is missing its original receipt".into()); + }; + if !matches!( + retired.goal_status, + GoalStatus::Completed | GoalStatus::Blocked | GoalStatus::Error + ) || handoff.report_complete + || handoff.requested_at_ms <= retired.goal_finished_at_ms + || retired.retired_at_ms < handoff.requested_at_ms + || retired.action.send_accepted != Some(true) + || retired.action.status != AutomationActionStatus::Idle + { + return Err("Retired terminal-goal handoff history is invalid".into()); + } + validate_action(&retired.action)?; + } if let Some(previous) = &state.suspended_retry { validate_action(&previous.action)?; validate_goal_wake(&previous.goal_wake)?; @@ -5034,3 +5109,54 @@ mod schema_rollover_tests { } } } + +#[cfg(all(test, windows))] +mod windows_state_publication_tests { + use super::*; + use std::os::windows::fs::OpenOptionsExt; + + #[test] + fn transient_sharing_violation_does_not_lose_automation_state() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("state.json"); + persist_private_record(&path, &serde_json::json!({"version":1})).unwrap(); + + // Another Windows process can briefly open the old destination without + // FILE_SHARE_DELETE (e.g. antivirus or a file indexer). The new atomic + // replacement must preserve its temporary file until that handle exits. + let held = std::fs::OpenOptions::new() + .read(true) + .share_mode(0) + .open(&path) + .unwrap(); + let target = path.clone(); + let publisher = std::thread::spawn(move || { + persist_private_record(&target, &serde_json::json!({"version":2})) + }); + std::thread::sleep(std::time::Duration::from_millis(80)); + drop(held); + publisher.join().unwrap().unwrap(); + let value: serde_json::Value = + serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(value["version"], 2); + } + + #[test] + fn persistent_sharing_violation_fails_without_overwriting_state() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("state.json"); + persist_private_record(&path, &serde_json::json!({"version":1})).unwrap(); + let held = std::fs::OpenOptions::new() + .read(true) + .share_mode(0) + .open(&path) + .unwrap(); + let error = persist_private_record(&path, &serde_json::json!({"version":2})) + .expect_err("permanent destination lock must remain a hard error"); + assert!(error.contains("Could not publish agent automation state")); + drop(held); + let value: serde_json::Value = + serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(value["version"], 1); + } +} diff --git a/src/agent_automation/supervisor.rs b/src/agent_automation/supervisor.rs index 077a9cda..e00ba924 100644 --- a/src/agent_automation/supervisor.rs +++ b/src/agent_automation/supervisor.rs @@ -1083,12 +1083,17 @@ impl AgentAutomationSupervisor { { return Ok(false); } - let root = context - .bindings - .selected_project_root(&context.config, &task.task)? - .ok_or("The conversation continuation workspace is unavailable")? - .canonicalize() - .map_err(|_| "The conversation continuation workspace is unavailable")?; + // Historical chats can outlive ephemeral managed worktrees. A broken + // binding must fence *that* replacement, not abort the shared scan and + // starve unrelated, correctly bound automation goals. + let Some(root) = replacement_workspace_root( + task.task.stable_key(), + context + .bindings + .selected_project_root(&context.config, &task.task), + ) else { + return Ok(false); + }; let token = context.continuations.issue_token_for_owner( &task.task, task.owner_generation, @@ -2307,6 +2312,16 @@ impl AgentAutomationSupervisor { )? { state = task.store.load(&task.task)?; } + // A terminal goal cannot produce a new model handoff. Archive a + // mistakenly requested post-finish renewal as unverified evidence, + // rather than blocking the slot or pretending its final was sent. + if super::turn_renewal::can_retire_obsolete_terminal_handoff(&state) + && task + .store + .retire_finished_goal_handoff(&task.task, now_ms)? + { + state = task.store.load(&task.task)?; + } task.store.notify_state(&task.chat, &state).await; let renewal_config = task.store.turn_renewal_settings()?; let renewal_enabled = state.turn_renewal.send.as_ref().is_some_and(|send| { @@ -4738,6 +4753,60 @@ fn failed_companion_status(code: &str) -> AutomationActionStatus { } } +/// An unavailable binding fences only this replacement. Treating it as a +/// global scan error would prevent every other healthy task from dispatching. +fn replacement_workspace_root( + task_key: &str, + selected: Result, String>, +) -> Option { + let selected = match selected { + Ok(Some(root)) => root, + Ok(None) => { + tracing::warn!( + task_key, + "deferred conversation replacement: no selected workspace" + ); + return None; + } + Err(error) => { + tracing::warn!(task_key, %error, "deferred conversation replacement: invalid workspace binding"); + return None; + } + }; + match selected.canonicalize() { + Ok(root) => Some(root), + Err(error) => { + tracing::warn!(task_key, %error, "deferred conversation replacement: workspace is unavailable"); + None + } + } +} + +#[cfg(test)] +mod replacement_workspace_isolation_tests { + use super::replacement_workspace_root; + #[test] + fn missing_historical_binding_is_deferred_without_losing_healthy_workspace() { + let healthy = tempfile::tempdir().unwrap(); + let valid = healthy.path().canonicalize().unwrap(); + let missing = healthy.path().join("removed-worktree"); + assert!( + replacement_workspace_root("old-chat", Err("missing historical binding".into())) + .is_none() + ); + assert!(replacement_workspace_root("old-chat", Ok(None)).is_none()); + assert!(replacement_workspace_root("old-chat", Ok(Some(missing.clone()))).is_none()); + assert!( + !missing.exists(), + "no placeholder worktree may be manufactured" + ); + assert_eq!( + replacement_workspace_root("valid-chat", Ok(Some(healthy.path().into()))), + Some(valid) + ); + } +} + fn blocks_automatic_requeue(status: AutomationActionStatus) -> bool { matches!( status, diff --git a/src/agent_automation/turn_renewal.rs b/src/agent_automation/turn_renewal.rs index 60d3b1f6..72b96ffb 100644 --- a/src/agent_automation/turn_renewal.rs +++ b/src/agent_automation/turn_renewal.rs @@ -137,6 +137,77 @@ pub struct TurnHandoff { pub requested_at_ms: u64, pub report_complete: bool, } + +/// A renewal requested after an already finished goal is not another task +/// continuation. Keep its exact unverified receipt rather than claim that a +/// final handoff was delivered or quietly discard the accepted Send. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct RetiredTerminalHandoff { + pub goal_revision: u64, + pub goal_status: GoalStatus, + pub goal_finished_at_ms: u64, + pub retired_at_ms: u64, + pub renewal: TurnRenewalState, + pub action: super::AutomationActionState, +} + +pub(super) const MAX_RETIRED_TERMINAL_HANDOFFS: usize = 16; + +/// Check an already loaded snapshot without acquiring a write lock or +/// republishing automation.json on every scheduler tick. +pub(super) fn can_retire_obsolete_terminal_handoff(state: &super::AutomationTaskState) -> bool { + let Some(goal) = state.goal.as_ref() else { + return false; + }; + if !matches!( + goal.status, + GoalStatus::Completed | GoalStatus::Blocked | GoalStatus::Error + ) { + return false; + } + let Some(finished_at_ms) = goal.finished_at_ms else { + return false; + }; + let Some(handoff) = state.turn_renewal.handoff.as_ref() else { + return false; + }; + !(handoff.report_complete + || handoff.requested_at_ms <= finished_at_ms + || state.action.send_accepted != Some(true) + || state.action.status != AutomationActionStatus::Idle) +} + +pub(super) fn retire_obsolete_terminal_handoff( + state: &mut super::AutomationTaskState, + now_ms: u64, +) -> bool { + if !can_retire_obsolete_terminal_handoff(state) { + return false; + } + let goal = state + .goal + .as_ref() + .expect("eligibility requires terminal goal"); + let finished_at_ms = goal + .finished_at_ms + .expect("eligibility requires finish time"); + state + .retired_terminal_handoffs + .push(RetiredTerminalHandoff { + goal_revision: goal.revision, + goal_status: goal.status, + goal_finished_at_ms: finished_at_ms, + retired_at_ms: now_ms, + renewal: state.turn_renewal.clone(), + action: state.action.clone(), + }); + if state.retired_terminal_handoffs.len() > MAX_RETIRED_TERMINAL_HANDOFFS { + state.retired_terminal_handoffs.remove(0); + } + state.turn_renewal = TurnRenewalState::default(); + true +} impl TurnRenewalState { pub fn is_empty(&self) -> bool { self.send.is_none() && self.handoff.is_none() && self.resume_wait_until_ms.is_none() @@ -144,6 +215,21 @@ impl TurnRenewalState { } impl AgentAutomationStore { + pub(crate) fn retire_finished_goal_handoff( + &self, + task: &ConversationIdentity, + now_ms: u64, + ) -> Result { + // mutate() always persists state. Do not call it for an ineligible + // task; recheck eligibility under its lock to handle concurrent state. + if !can_retire_obsolete_terminal_handoff(&self.load(task)?) { + return Ok(false); + } + self.mutate(task, |state| { + Ok(retire_obsolete_terminal_handoff(state, now_ms)) + }) + } + pub fn turn_renewal_settings(&self) -> Result { crate::global_settings::turn_renewal_settings( self.settings_path.as_deref(), @@ -336,8 +422,13 @@ impl AgentAutomationStore { return Ok(None); } self.mutate(task, |state| { - if state.goal.as_ref().is_some_and(|goal| goal.status != GoalStatus::Active) { - clear_pending_renewal(state); + // Once a goal is terminal, no model continuation is possible. + // Non-goal chats (goal=None) still use ordinary timed renewal. + if state + .goal + .as_ref() + .is_some_and(|goal| goal.status != GoalStatus::Active) + { return Ok(None); } let Some(send) = &state.turn_renewal.send else {return Ok(None)}; @@ -539,6 +630,7 @@ impl AgentAutomationStore { #[cfg(test)] mod completed_goal_renewal_tests { + use super::super::OwnerGoalCommand; use super::*; use crate::agent_automation::GoalFinish; @@ -655,4 +747,193 @@ mod completed_goal_renewal_tests { assert!(state.turn_renewal.is_empty()); } } + + fn finished_goal_with_post_finish_handoff() -> ( + tempfile::TempDir, + AgentAutomationStore, + ConversationIdentity, + ) { + let root = tempfile::tempdir().unwrap(); + let mut store = AgentAutomationStore::new(root.path().join("chats")).unwrap(); + store.renewal_config.enabled = true; + let task = + ConversationIdentity::from_openai_session("completed-goal-stale-handoff").unwrap(); + let goal = store.set_goal(&task, "Completed test goal", 100).unwrap(); + store.run_goal(&task, goal.revision, 150).unwrap(); + store + .finish_goal( + &task, + goal.revision, + GoalFinish::Completed { + summary: Some("Verified work completed".into()), + }, + 3_000, + ) + .unwrap(); + store + .mutate(&task, |state| { + state.pairing.generation = 1; + state.pairing.verified_owner_generation = Some(0); + state.pairing.verified_at_ms = Some(200); + state.pairing.canonical_url = + Some("https://chatgpt.com/c/completed-goal-stale-handoff".into()); + state.action.id = Some("accepted-completed-goal".into()); + state.action.kind = Some(AutomationActionKind::OfflineGoal); + state.action.goal_revision = Some(goal.revision); + state.action.status = AutomationActionStatus::Idle; + state.action.send_accepted = Some(true); + state.action.pairing_generation = Some(1); + state.turn_renewal.send = Some(TurnSend { + action_id: "accepted-completed-goal".into(), + at_ms: 250, + model: Some("gpt-6-astra".into()), + effort: Some("max".into()), + pairing_generation: 1, + owner_generation: 0, + }); + state.turn_renewal.handoff = Some(TurnHandoff { + id: "renew-completed-goal".into(), + requested_at_ms: 4_000, + report_complete: false, + }); + Ok(()) + }) + .unwrap(); + (root, store, task) + } + + #[test] + fn a_finished_goal_does_not_emit_another_turn_handoff() { + let (_root, store, task) = finished_goal_with_post_finish_handoff(); + let old = store.load(&task).unwrap(); + assert!( + store + .turn_renewal_notice(&task, 99 * 60_000) + .unwrap() + .is_none(), + "expired send time must not renew an already completed goal" + ); + let after = store.load(&task).unwrap(); + assert_eq!(after.action, old.action); + assert_eq!(after.turn_renewal, old.turn_renewal); + } + + #[test] + fn post_completion_handoff_is_archived_unverified_and_never_resends() { + let (_root, store, task) = finished_goal_with_post_finish_handoff(); + let old = store.load(&task).unwrap(); + assert!(can_retire_obsolete_terminal_handoff(&old)); + assert!(store.retire_finished_goal_handoff(&task, 6_000).unwrap()); + assert!(!store.retire_finished_goal_handoff(&task, 6_001).unwrap()); + let recovered = store.load(&task).unwrap(); + assert!(!can_retire_obsolete_terminal_handoff(&recovered)); + assert!(recovered.turn_renewal.is_empty()); + assert_eq!(recovered.goal, old.goal); + assert_eq!(recovered.action, old.action); + assert_eq!(recovered.retired_terminal_handoffs.len(), 1); + let receipt = &recovered.retired_terminal_handoffs[0]; + assert_eq!(receipt.renewal, old.turn_renewal); + assert_eq!(receipt.action, old.action); + assert_eq!(receipt.goal_revision, 1); + assert!(!receipt.renewal.handoff.as_ref().unwrap().report_complete); + let json = serde_json::to_string(&recovered).unwrap(); + let decoded: super::super::AutomationTaskState = serde_json::from_str(&json).unwrap(); + assert_eq!( + decoded.retired_terminal_handoffs, + recovered.retired_terminal_handoffs + ); + let next = store + .apply_owner_goal_command( + &task, + "new-verified-work", + OwnerGoalCommand::Set { + markdown: "New owner-approved work".into(), + }, + 7_000, + ) + .unwrap(); + assert_eq!(next.goal.unwrap().status, GoalStatus::Active); + assert_eq!( + store.load(&task).unwrap().retired_terminal_handoffs.len(), + 1 + ); + } + + #[test] + fn owner_replacement_archives_stale_terminal_handoff_atomically() { + let (_root, store, task) = finished_goal_with_post_finish_handoff(); + let receipt = store + .apply_owner_goal_command( + &task, + "supersede-stale-terminal", + OwnerGoalCommand::Set { + markdown: "Continue new owner goal".into(), + }, + 6_000, + ) + .unwrap(); + assert_eq!(receipt.goal.unwrap().revision, 2); + let after = store.load(&task).unwrap(); + assert!(after.turn_renewal.is_empty()); + assert_eq!(after.retired_terminal_handoffs.len(), 1); + assert_eq!( + after.retired_terminal_handoffs[0] + .renewal + .handoff + .as_ref() + .unwrap() + .id, + "renew-completed-goal" + ); + assert!( + !after.retired_terminal_handoffs[0] + .renewal + .handoff + .as_ref() + .unwrap() + .report_complete + ); + } + + #[test] + fn active_goal_and_pre_finish_handoffs_are_not_retired() { + let (_root, store, task) = finished_goal_with_post_finish_handoff(); + store + .mutate(&task, |state| { + state.goal.as_mut().unwrap().status = GoalStatus::Active; + state.goal.as_mut().unwrap().finished_at_ms = None; + state.goal.as_mut().unwrap().summary = None; + Ok(()) + }) + .unwrap(); + assert!(!can_retire_obsolete_terminal_handoff( + &store.load(&task).unwrap() + )); + let state_file = store.task_directory(&task).unwrap().join("automation.json"); + let before = std::fs::metadata(&state_file).unwrap().modified().unwrap(); + std::thread::sleep(std::time::Duration::from_millis(75)); + assert!(!store.retire_finished_goal_handoff(&task, 6_000).unwrap()); + assert_eq!( + before, + std::fs::metadata(&state_file).unwrap().modified().unwrap(), + "an ineligible scheduler tick must not republish automation state" + ); + store + .mutate(&task, |state| { + state.goal.as_mut().unwrap().status = GoalStatus::Completed; + state.goal.as_mut().unwrap().finished_at_ms = Some(3_000); + state.goal.as_mut().unwrap().summary = Some("Verified work completed".into()); + state.turn_renewal.handoff.as_mut().unwrap().requested_at_ms = 2_900; + Ok(()) + }) + .unwrap(); + assert!(!can_retire_obsolete_terminal_handoff( + &store.load(&task).unwrap() + )); + assert!(!store.retire_finished_goal_handoff(&task, 6_000).unwrap()); + assert_eq!( + store.load(&task).unwrap().retired_terminal_handoffs.len(), + 0 + ); + } } diff --git a/src/bridge.rs b/src/bridge.rs index 68bdcef4..889c7e4a 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -32,29 +32,30 @@ use crate::bridged_resources::BridgedResourceStore; use crate::exec_sessions::SessionState; use crate::mcp_catalog::{CatalogSourceInput, build_catalog_tools}; use crate::process_env::scrub_untrusted_child_env; +use crate::project_bindings::ConversationIdentity; use crate::tool::{Tool, ToolBehavior, ToolCallIdentity, ToolRequestContext}; +use crate::types::McpSessionScope; use crate::types::{AppConfig, McpToolExposure, ToolContent, ToolResult}; +mod hot_reload; +#[cfg(test)] +mod hot_reload_tests; mod stderr; +pub(crate) use hot_reload::{Generation, HotReloadRuntime, ReloadMcpTool}; /// How long to wait for an upstream to start up and answer `tools/list` before /// giving up on it. const CONNECT_TIMEOUT: Duration = Duration::from_secs(20); -/// The result of connecting to every configured upstream: the tools to merge -/// into the registry, plus the running services kept alive for the server's -/// lifetime (dropping one closes its transport and any child process). +/// Connected MCP sources are owned by a transactional registry. Its immutable +/// view is shared across transport sessions, while calls pin their generation. pub struct Bridge { - pub tools: Vec>, - /// Shared opaque-capability store for resource links returned by upstream tools. + pub tools: Arc>>, pub resources: Arc, - /// Held only to keep upstream transports alive; never read directly. - pub services: Vec>, - /// One human-readable line per configured server (connected or failed), - /// printed in the startup banner so a bad path or handshake is never silent. pub report: Vec, - pub(crate) upstreams: Arc>>, - pub(crate) monitors: Vec, + pub(crate) runtime: Arc, + pub(crate) upstreams: + Arc>>>, } pub(crate) struct UpstreamMonitor(tokio::task::JoinHandle<()>); @@ -116,14 +117,112 @@ struct BridgedTool { annotations: Option, icons: Option>, meta: Option, + server_bound_upstream_auth: bool, peer: Peer, tool_timeout: Option, control: Arc, resources: Arc, + generation: Arc, +} + +/// Cloudflare and other remote MCPs can advertise their *own* OAuth requirements, +/// even when Codexify already authenticates upstream using a configured bearer token. +/// Forwarding those schemes as God v5 tool metadata causes ChatGPT to request OAuth +/// for the wrong application (which has no upstream-browser setup URL). +/// Keep other upstream metadata and do not alter tools without bound credentials. +fn forward_server_bound_tool_metadata( + meta: Option, + server_bound_auth: bool, +) -> Option { + let mut meta = meta?; + if server_bound_auth { + // These belong to the upstream MCP's identity, not the Codexify app. + // A bridged Cloudflare profile tool is not the God v5 profile tool. + meta.0.remove("securitySchemes"); + meta.0.remove("openai/profile"); + } + (!meta.0.is_empty()).then_some(meta) +} + +/// Only display literal, bounded scope identifiers from an upstream challenge. +/// Never forward resource_metadata URLs or raw WWW-Authenticate values. +fn safe_declared_scope(challenge: &Value) -> Option { + let headers: Vec<&str> = match challenge { + Value::String(header) => vec![header], + Value::Array(values) => values.iter().filter_map(Value::as_str).collect(), + _ => return None, + }; + headers.into_iter().find_map(|header| { + let (_, remainder) = header.split_once("scope=\"")?; + let (scope, _) = remainder.split_once('"')?; + (!scope.is_empty() + && scope.len() <= 128 + && scope.chars().all(|ch| { + ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-' | ':' | '.' | '/' | ' ') + })) + .then(|| scope.to_owned()) + }) +} + +/// An upstream OAuth challenge is not a valid OAuth challenge for Codexify's +/// already-authorized downstream MCP connection. Fail closed with a sanitized, +/// structured upstream diagnostic rather than a broken ChatGPT relink action. +fn sanitize_server_bound_auth_result( + mut result: ToolResult, + server_bound_auth: bool, +) -> ToolResult { + if !server_bound_auth { + return result; + } + let challenge = result + .meta + .as_mut() + .and_then(|meta| meta.0.remove("mcp/www_authenticate")); + let Some(challenge) = challenge else { + return result; + }; + + let challenge_code = challenge.to_string().to_ascii_lowercase(); + let code = if challenge_code.contains("insufficient_scope") { + "insufficient_scope" + } else if challenge_code.contains("invalid_token") { + "invalid_token" + } else { + "authorization_required" + }; + let required_scope = safe_declared_scope(&challenge); + let scope_note = required_scope + .as_ref() + .map(|scope| format!(" Required scope: {scope}.")) + .unwrap_or_default(); + + result.is_error = true; + result.structured_content = None; + result.content = vec![ToolContent::Text(format!( + "Upstream MCP authorization failed ({code}). Codexify already manages the \ + upstream credential; verify the existing server-side token and its read \ + permissions instead of using ChatGPT Connect.{scope_note}" + ))]; + let meta = result.meta.get_or_insert_with(MetaObject::new); + meta.0.insert( + "io.github.devnoname120/codexify/upstream_auth_error".into(), + json!({ + "code": code, + "credential_source": "server_bound", + "required_scope": required_scope + }), + ); + result } impl BridgedTool { - async fn run(&self, args: Value, cancellation: Option<&CancellationToken>) -> ToolResult { + async fn run( + &self, + args: Value, + cancellation: Option<&CancellationToken>, + conversation: Option<&ConversationIdentity>, + ) -> ToolResult { + let _lease = self.generation.begin_call(); let mut params = CallToolRequestParams::new(self.original_name.clone()); if let Some(obj) = args.as_object() && !obj.is_empty() @@ -131,7 +230,7 @@ impl BridgedTool { params = params.with_arguments(obj.clone()); } - forward_tool_call( + let result = forward_tool_call( &self.peer, params, &self.server, @@ -141,9 +240,11 @@ impl BridgedTool { UpstreamCallContext { resources: &self.resources, control: &self.control, + conversation, }, ) - .await + .await; + sanitize_server_bound_auth_result(result, self.server_bound_upstream_auth) } } @@ -245,7 +346,7 @@ impl Tool for BridgedTool { } async fn call(&self, args: Value, _config: &AppConfig, _session: &SessionState) -> ToolResult { - self.run(args, None).await + self.run(args, None, None).await } async fn call_with_context( @@ -255,13 +356,22 @@ impl Tool for BridgedTool { _session: &SessionState, context: &ToolRequestContext, ) -> ToolResult { - self.run(args, Some(&context.cancellation)).await + self.run( + args, + Some(&context.cancellation), + context + .task_conversation + .as_ref() + .or(context.conversation.as_ref()), + ) + .await } } pub(crate) struct UpstreamCallContext<'a> { pub(crate) resources: &'a BridgedResourceStore, pub(crate) control: &'a crate::upstream_control::UpstreamControl, + pub(crate) conversation: Option<&'a ConversationIdentity>, } pub(crate) async fn forward_tool_call( @@ -273,7 +383,51 @@ pub(crate) async fn forward_tool_call( cancellation: Option<&CancellationToken>, context: UpstreamCallContext<'_>, ) -> ToolResult { - let UpstreamCallContext { resources, control } = context; + let UpstreamCallContext { + resources, + control, + conversation, + } = context; + // This preflight is shared by direct, gateway and catalog MCP exposure. + // Never send an isolation request to a browser extension as a fallback. + if let Err(error) = control.check_browser_context_request(tool, ¶ms) { + return ToolResult::error(format!("Upstream MCP server '{server}': {error}")); + } + let isolated_requested = control.isolated_tab_requested(tool, ¶ms); + // A scoped Playwright source never falls back to the global peer when the + // downstream caller lacks an authoritative task identity. + let scoped_connection = match &control.scoped_playwright { + Some(pool) => { + let scoped_call = + tokio::time::timeout(Duration::from_secs(90), pool.acquire(conversation)); + let cancelled = cancellation.cloned().unwrap_or_default(); + let response = tokio::select! { + biased; + _ = cancelled.cancelled() => { + return ToolResult::error(format!( + "Upstream MCP server '{server}': owner request cancelled before browser dispatch" + )); + } + response = scoped_call => response, + }; + match response { + Ok(Ok(connection)) => Some(connection), + Ok(Err(error)) => { + return ToolResult::error(format!("Upstream MCP server '{server}': {error}")); + } + Err(_) => { + return ToolResult::error(format!( + "Upstream MCP server '{server}': per-chat browser startup timed out; no browser tool call dispatched" + )); + } + } + } + None => None, + }; + let (peer, control) = match &scoped_connection { + Some(connection) => (&connection.peer, connection.control.as_ref()), + None => (peer, control), + }; let timeout = tool_timeout.unwrap_or(Duration::from_secs(60)); let deadline = tokio::time::Instant::now() + timeout; let token = cancellation.cloned().unwrap_or_default(); @@ -307,10 +461,34 @@ pub(crate) async fn forward_tool_call( }); match result { - Ok(result) => map_call_result(result, peer, server, tool_timeout, resources), - Err(error) => ToolResult::error(format!( - "Upstream MCP server '{server}' failed to run '{tool}': {error}" - )), + Ok(result) => { + if isolated_requested && result.is_error == Some(true) { + let message = result + .content + .iter() + .filter_map(|block| match block { + ContentBlock::Text(text) => Some(text.text.as_str()), + _ => None, + }) + .collect::>() + .join("\n"); + if let Some(error) = control.browser_context_refusal(isolated_requested, &message) { + return ToolResult::error(format!( + "Upstream MCP server '{server}' failed to run '{tool}': {error}" + )); + } + } + map_call_result(result, peer, server, tool_timeout, resources) + } + Err(error) => { + let detail = error.to_string(); + let detail = control + .browser_context_refusal(isolated_requested, &detail) + .unwrap_or(detail); + ToolResult::error(format!( + "Upstream MCP server '{server}' failed to run '{tool}': {detail}" + )) + } } } @@ -517,158 +695,161 @@ fn unique_name(base: String, used: &std::collections::HashSet) -> String /// Connect to every configured upstream MCP server, discover its tools, and /// materialize its effective exposure mode. A server that fails to launch or /// answer is logged and skipped — it never blocks startup. +// Per-task Playwright sessions must be discovered with a separate transport +// and routed by the verified task owner on EVERY browser tool call. +async fn connect_owned_source( + server: &str, + spec: &crate::types::McpServerSpec, + config: &AppConfig, +) -> Result< + ( + RunningService, + Vec, + Option, + Option>, + ), + String, +> { + let scoped = if spec.session_scope == McpSessionScope::PerChat { + Some(Arc::new( + crate::playwright_sessions::ScopedPlaywrightPool::new(server, spec, config)?, + )) + } else { + None + }; + let discovery = match &scoped { + Some(pool) => pool.discovery_spec()?, + None => spec.clone(), + }; + let (service, tools, timeout) = connect_one(server, &discovery, config).await?; + Ok((service, tools, timeout, scoped)) +} + pub async fn connect_upstreams(config: &AppConfig) -> Bridge { - let mut tools: Vec> = Vec::new(); - let mut services: Vec> = Vec::new(); - let mut upstreams = HashMap::new(); - let mut monitors = Vec::new(); - let mut report: Vec = Vec::new(); - let mut catalog_sources = Vec::new(); let resources = Arc::new(BridgedResourceStore::new(config.artifact_egress.clone())); - - // Deterministic order so logs and tool ordering are stable across runs. - let mut names: Vec<&String> = config.mcp_servers.keys().collect(); + let mut sources = HashMap::new(); + let mut report = Vec::new(); + // Preserve the scoped branch's bounded concurrent cold-start behavior; + // hot-reload registry construction only happens after each result is + // received, in deterministic source-name order. + const MAX_PARALLEL_UPSTREAM_STARTS: usize = 3; + let mut names: Vec = config.mcp_servers.keys().cloned().collect(); names.sort(); - - for server_name in names { - let spec = &config.mcp_servers[server_name]; + let source_config = Arc::new(config.clone()); + let startup_slots = Arc::new(tokio::sync::Semaphore::new(MAX_PARALLEL_UPSTREAM_STARTS)); + let mut joins = tokio::task::JoinSet::new(); + for (index, name) in names.iter().cloned().enumerate() { + let source_config = Arc::clone(&source_config); + let startup_slots = Arc::clone(&startup_slots); + joins.spawn(async move { + let spec = &source_config.mcp_servers[&name]; + if spec.disabled { + return (index, Err("MCP source is disabled".to_string())); + } + let connected = match startup_slots.acquire_owned().await { + Ok(_permit) => connect_owned_source(&name, spec, &source_config).await, + Err(_) => Err("upstream startup limiter closed".to_string()), + }; + (index, connected) + }); + } + let mut results: Vec<_> = std::iter::repeat_with(|| None).take(names.len()).collect(); + while let Some(joined) = joins.join_next().await { + match joined { + Ok((index, result)) => results[index] = Some(result), + Err(error) => { + tracing::warn!("upstream initialization task failed without a result: {error}") + } + } + } + for (index, name) in names.into_iter().enumerate() { + let spec = &config.mcp_servers[&name]; if spec.disabled { - report.push(format!("{server_name} -> disabled")); + report.push(format!("{name} -> disabled")); continue; } - let sanitized = sanitize(server_name); - let exposure = spec.exposure(); - - match connect_one(server_name, spec, config).await { - Ok((service, upstream_tools, tool_timeout)) => { - let peer = service.peer().clone(); - let control = Arc::new(crate::upstream_control::UpstreamControl::new( - spec.request_limits.clone(), - )); - upstreams.insert(server_name.clone(), control.clone()); - monitors.push(monitor_upstream(peer.clone(), control.clone())); - let count = upstream_tools.len(); - - match exposure { - McpToolExposure::Gateway => { - let functions: Vec = upstream_tools - .iter() - .map(|t| GatewayFunction { - name: t.name.to_string(), - description: t - .description - .as_ref() - .map(|c| c.to_string()) - .unwrap_or_default(), - input_schema: Value::Object((*t.input_schema).clone()), - }) - .collect(); - - write_gateway_skill(config, server_name, &sanitized, &functions); - - let leaked: &'static str = Box::leak(sanitized.clone().into_boxed_str()); - tools.push(Box::new(GatewayTool { - name: leaked, - server: server_name.clone(), - description: gateway_description(server_name, &functions), - function_names: functions.iter().map(|f| f.name.clone()).collect(), - peer: peer.clone(), - tool_timeout, - control: control.clone(), - resources: resources.clone(), - })); - report.push(format!( - "{server_name} -> gateway ({count} functions via `{sanitized}`)" - )); - tracing::info!( - "bridged MCP server '{server_name}' as gateway: {count} function(s)" - ); - } - McpToolExposure::Direct => { - report.push(format!("{server_name} -> direct ({count} tool(s))")); - let mut used: std::collections::HashSet = - std::collections::HashSet::new(); - for tool in upstream_tools { - let original_name = tool.name.to_string(); - let display = - unique_name(bridged_name(&sanitized, &original_name), &used); - used.insert(display.clone()); - let leaked: &'static str = Box::leak(display.into_boxed_str()); - let title = tool.title.filter(|title| !title.trim().is_empty()); - let description = tool - .description - .map(|description| description.to_string()) - .filter(|description| !description.trim().is_empty()) - .unwrap_or_else(|| { - format!( - "Call the `{original_name}` tool on the `{server_name}` MCP server." - ) - }); - tools.push(Box::new(BridgedTool { - name: leaked, - original_name, - server: server_name.clone(), - title, - description, - input_schema: Value::Object((*tool.input_schema).clone()), - output_schema: tool - .output_schema - .map(|schema| Value::Object((*schema).clone())), - annotations: tool.annotations, - icons: tool.icons, - meta: tool.meta, - peer: peer.clone(), - tool_timeout, - control: control.clone(), - resources: resources.clone(), - })); - } - tracing::info!( - "bridged MCP server '{server_name}' directly: {count} tool(s)" - ); - } - McpToolExposure::Catalog => { - report.push(format!( - "{server_name} -> catalog ({count} private tool(s))" - )); - catalog_sources.push(CatalogSourceInput { - raw_name: server_name.clone(), - provenance: spec.provenance, - transport: transport_label(spec), - peer_info: peer.peer_info(), - tools: upstream_tools, - peer: peer.clone(), - tool_timeout, - control: control.clone(), - }); - tracing::info!( - "indexed MCP server '{server_name}' privately: {count} tool(s)" - ); - } + let result = results[index] + .take() + .unwrap_or_else(|| Err("upstream startup task failed".to_string())); + match result { + Ok((service, tools, timeout, scoped)) => { + let count = tools.len(); + let mode = spec.exposure(); + if mode == McpToolExposure::Gateway { + let functions = gateway_functions(&tools); + write_gateway_skill(config, &name, &sanitize(&name), &functions); } - services.push(service); + let generation = hot_reload::Generation::for_source( + &name, + spec.clone(), + service, + tools, + timeout, + scoped, + 1, + ); + sources.insert(name.clone(), generation); + let visibility = if mode == McpToolExposure::Catalog { + " private" + } else { + "" + }; + report.push(format!( + "{name} -> {} ({count}{visibility} tool(s))", + mode.as_str() + )); + tracing::info!(source = %name, %count, exposure = mode.as_str(), "MCP source connected"); } - Err(e) => { - report.push(format!("{server_name} -> FAILED: {e}")); - tracing::warn!("skipping MCP server '{server_name}': {e}"); + Err(_) => { + // Upstream configuration can contain private header or command + // values; do not echo a failed spawn/handshake error to clients. + // An unsupported transport type is a safe, useful static + // diagnostic and should not be hidden as an initialization + // failure; neither diagnostic includes the configured URL. + let legacy_transport = spec.transport.as_deref().is_some_and(|kind| { + matches!( + kind.to_ascii_lowercase().as_str(), + "sse" | "websocket" | "ws" + ) + }); + if legacy_transport { + report.push(format!("{name} -> not supported (transport)")); + tracing::warn!(source = %name, "MCP source transport is not supported"); + } else { + report.push(format!("{name} -> FAILED (initialization)")); + tracing::warn!(source = %name, "MCP source failed initialization"); + } } } } - let mut catalog_tools = build_catalog_tools(catalog_sources, resources.clone()); - catalog_tools.append(&mut tools); - tools = catalog_tools; - + let runtime = HotReloadRuntime::new(Arc::new(config.clone()), resources.clone(), sources); Bridge { - tools, + tools: runtime.snapshot().tools.clone(), resources, - services, report, - upstreams: Arc::new(upstreams), - monitors, + upstreams: runtime.upstreams.clone(), + runtime, } } +/// Use one conversion for startup registration, registry replacement and +/// generated gateway skills, so schema/description metadata cannot diverge. +fn gateway_functions(tools: &[rmcp::model::Tool]) -> Vec { + tools + .iter() + .map(|tool| GatewayFunction { + name: tool.name.to_string(), + description: tool + .description + .as_ref() + .map(ToString::to_string) + .unwrap_or_default(), + input_schema: Value::Object((*tool.input_schema).clone()), + }) + .collect() +} + /// One function exposed by a gateway-mode server. struct GatewayFunction { name: String, @@ -767,10 +948,17 @@ struct GatewayTool { tool_timeout: Option, control: Arc, resources: Arc, + generation: Arc, } impl GatewayTool { - async fn run(&self, args: Value, cancellation: Option<&CancellationToken>) -> ToolResult { + async fn run( + &self, + args: Value, + cancellation: Option<&CancellationToken>, + conversation: Option<&ConversationIdentity>, + ) -> ToolResult { + let _lease = self.generation.begin_call(); let Some(function) = args.get("function").and_then(|v| v.as_str()) else { return ToolResult::error("`function` is required (the name of the function to call)"); }; @@ -806,6 +994,7 @@ impl GatewayTool { UpstreamCallContext { resources: &self.resources, control: &self.control, + conversation, }, ) .await @@ -874,7 +1063,7 @@ impl Tool for GatewayTool { } async fn call(&self, args: Value, _config: &AppConfig, _session: &SessionState) -> ToolResult { - self.run(args, None).await + self.run(args, None, None).await } async fn call_with_context( @@ -884,12 +1073,20 @@ impl Tool for GatewayTool { _session: &SessionState, context: &ToolRequestContext, ) -> ToolResult { - self.run(args, Some(&context.cancellation)).await + self.run( + args, + Some(&context.cancellation), + context + .task_conversation + .as_ref() + .or(context.conversation.as_ref()), + ) + .await } } /// Launch and initialise one upstream, returning its running service and tools. -async fn connect_one( +pub(crate) async fn connect_one( server_name: &str, spec: &crate::types::McpServerSpec, config: &AppConfig, @@ -1112,7 +1309,7 @@ async fn connect_one_with_env( server_name: &str, spec: &crate::types::McpServerSpec, config: &AppConfig, - env_lookup: &dyn Fn(&str) -> Option, + env_lookup: &(dyn Fn(&str) -> Option + Send + Sync), ) -> Result< ( RunningService, @@ -1133,6 +1330,7 @@ async fn connect_one_with_env( let connect = match select_transport(spec)? { UpstreamTransport::Stdio(command_path) => { let mut command = Command::new(command_path); + command.kill_on_drop(true); command.args(&spec.args); for (key, value) in &spec.env { command.env(key, value); @@ -1322,6 +1520,12 @@ mod tests { if request.name.as_ref() == "slow" { tokio::time::sleep(Duration::from_secs(1)).await; } + if request.name.as_ref() == "browser_tabs" && text == "cdp_refused" { + return Ok(CallToolResult::error(vec![ContentBlock::text( + r#"Protocol error (Target.createBrowserContext): {"code":-32000,"message":"Not allowed"}"#, + )]) + .into()); + } Ok(CallToolResult::success(vec![ContentBlock::text(text)]).into()) } } @@ -1352,6 +1556,139 @@ mod tests { (format!("http://{address}/mcp"), task) } + #[tokio::test] + async fn playwright_capability_is_enforced_at_real_mcp_forwarding_boundary() { + // The test server echoes a marker for any browser_tabs request. If an + // extension-only isolated request reaches it, the test will fail. + let (url, server_task) = spawn_http_upstream().await; + let mut spec = McpServerSpec { + url: Some(url), + transport: Some("http".into()), + ..Default::default() + }; + spec.http_headers + .insert("authorization".into(), "Bearer remote-token".into()); + spec.http_headers + .insert("x-static".into(), "static-value".into()); + spec.http_headers.insert("x-env".into(), "env-value".into()); + let config = crate::config::default_config(std::env::temp_dir()); + let (service, _, _) = connect_one_with_env("playwright-test", &spec, &config, &|_| None) + .await + .unwrap(); + let resources = BridgedResourceStore::new(config.artifact_egress.clone()); + + let extension_spec = McpServerSpec { + command: Some("node".into()), + args: vec!["@playwright/mcp".into(), "--extension".into()], + ..Default::default() + }; + let full_spec = McpServerSpec { + command: Some("node".into()), + args: vec!["@playwright/mcp".into()], + ..Default::default() + }; + let cdp_spec = McpServerSpec { + command: Some("node".into()), + args: vec!["@playwright/mcp".into(), "--cdp-endpoint=chrome".into()], + ..Default::default() + }; + let extension_control = crate::upstream_control::UpstreamControl::default() + .for_server("playwright-extension", &extension_spec); + let full_control = crate::upstream_control::UpstreamControl::default() + .for_server("playwright", &full_spec); + let cdp_control = + crate::upstream_control::UpstreamControl::default().for_server("playwright", &cdp_spec); + let tab_request = |name: &str, context: &str| { + CallToolRequestParams::new("browser_tabs").with_arguments( + json!({ + "action": "new", + "isolatedContext": context, + "url": "https://example.invalid/local-fixture", + "text": name, + }) + .as_object() + .unwrap() + .clone(), + ) + }; + + let blocked = forward_tool_call( + service.peer(), + tab_request("never-dispatch", "lane06_grants_funding"), + "playwright-extension", + "browser_tabs", + None, + None, + UpstreamCallContext { + resources: &resources, + control: &extension_control, + conversation: None, + }, + ) + .await; + assert!(blocked.is_error); + assert!(blocked.joined_text().contains("No request was dispatched")); + assert!(!blocked.joined_text().contains("never-dispatch")); + + let capable = forward_tool_call( + service.peer(), + tab_request("capable-backend-called", "lane06_grants_funding"), + "playwright", + "browser_tabs", + None, + None, + UpstreamCallContext { + resources: &resources, + control: &full_control, + conversation: None, + }, + ) + .await; + assert!(!capable.is_error); + assert_eq!(capable.joined_text(), "capable-backend-called"); + + let refused = forward_tool_call( + service.peer(), + tab_request("cdp_refused", "lane07_funded_events"), + "playwright", + "browser_tabs", + None, + None, + UpstreamCallContext { + resources: &resources, + control: &cdp_control, + conversation: None, + }, + ) + .await; + assert!(refused.is_error); + assert!(refused.joined_text().contains("CDP -32000 Not allowed")); + assert!( + refused + .joined_text() + .contains("No isolated context was confirmed") + ); + + // No isolation requested: ordinary existing-tab operation still works. + let nonisolated = forward_tool_call( + service.peer(), + tab_request("ordinary-tab", "default"), + "playwright-extension", + "browser_tabs", + None, + None, + UpstreamCallContext { + resources: &resources, + control: &extension_control, + conversation: None, + }, + ) + .await; + assert!(!nonisolated.is_error); + assert_eq!(nonisolated.joined_text(), "ordinary-tab"); + server_task.abort(); + } + #[derive(Clone)] struct ResourceTestMcp; @@ -1525,6 +1862,11 @@ mod tests { tool_meta .0 .insert("vendor".into(), Value::String("hex-rays".into())); + tool_meta.0.insert( + "securitySchemes".into(), + json!([{"type": "oauth2", "scopes": ["account:read"]}]), + ); + tool_meta.0.insert("openai/profile".into(), json!(true)); tools.push( rmcp::model::Tool::new( "decompile_function", @@ -2395,6 +2737,171 @@ mod tests { let _ = second_server_task.await; } + #[test] + fn server_bound_oauth_metadata_is_not_misadvertised_as_chatgpt_access() { + let mut upstream = MetaObject::new(); + upstream.0.insert( + "securitySchemes".into(), + json!([{"type": "oauth2", "scopes": ["account:read"]}]), + ); + upstream + .0 + .insert("vendor".into(), Value::String("fixture".into())); + upstream.0.insert("openai/profile".into(), json!(true)); + let existing = forward_server_bound_tool_metadata(Some(upstream.clone()), false).unwrap(); + assert!(existing.0.contains_key("securitySchemes")); + assert_eq!(existing.0.get("openai/profile"), Some(&json!(true))); + + let forwarded = forward_server_bound_tool_metadata(Some(upstream), true).unwrap(); + assert!(!forwarded.0.contains_key("securitySchemes")); + assert!(!forwarded.0.contains_key("openai/profile")); + assert_eq!(forwarded.0.get("vendor"), Some(&json!("fixture"))); + } + + fn upstream_auth_fixture(challenge: &str) -> ToolResult { + let mut result = ToolResult::error("Upstream declined authorization"); + let mut meta = MetaObject::new(); + meta.0 + .insert("mcp/www_authenticate".into(), json!([challenge])); + result.meta = Some(meta); + result.structured_content = Some(json!({"untrusted": "private-fixture"})); + result + } + + #[test] + fn insufficient_scope_returns_specific_safe_error_without_consent_url() { + let result = sanitize_server_bound_auth_result( + upstream_auth_fixture( + "Bearer error=\"insufficient_scope\", scope=\"Account:Read\", \ + resource_metadata=\"https://auth.example.invalid/secret?token=do-not-log\"", + ), + true, + ); + assert!(result.is_error); + assert!(result.structured_content.is_none()); + assert!( + !result + .meta + .as_ref() + .unwrap() + .0 + .contains_key("mcp/www_authenticate") + ); + let ToolContent::Text(message) = &result.content[0] else { + panic!("expected safe text diagnostic"); + }; + assert!(message.contains("insufficient_scope")); + assert!(message.contains("Account:Read")); + assert!(!message.contains("auth.example.invalid")); + assert!(!message.contains("do-not-log")); + assert_eq!( + result.meta.as_ref().unwrap().0["io.github.devnoname120/codexify/upstream_auth_error"] + ["required_scope"], + json!("Account:Read") + ); + } + + #[test] + fn expired_upstream_grant_returns_recoverable_error_not_chatgpt_relink() { + let result = sanitize_server_bound_auth_result( + upstream_auth_fixture("Bearer error=\"invalid_token\""), + true, + ); + assert!(result.is_error); + let ToolContent::Text(message) = &result.content[0] else { + panic!("expected error"); + }; + assert!(message.contains("invalid_token")); + assert!(message.contains("existing server-side token")); + assert!(!message.contains("https://")); + } + + #[test] + fn malformed_upstream_consent_url_is_not_forwarded_to_downstream() { + let result = sanitize_server_bound_auth_result( + upstream_auth_fixture( + "Bearer error=\"invalid_token\", resource_metadata=\"javascript:alert(1)\"", + ), + true, + ); + let ToolContent::Text(message) = &result.content[0] else { + panic!("expected error"); + }; + assert!(!message.contains("javascript:")); + assert!(!message.contains("resource_metadata")); + assert!(!result.meta.unwrap().0.contains_key("mcp/www_authenticate")); + } + + #[test] + fn repeated_upstream_denial_stays_stable_without_oauth_prompt() { + let first = sanitize_server_bound_auth_result( + upstream_auth_fixture("Bearer error=\"invalid_token\""), + true, + ); + let second = sanitize_server_bound_auth_result(first, true); + assert!(second.is_error); + assert_eq!(second.content.len(), 1); + assert!(!second.meta.unwrap().0.contains_key("mcp/www_authenticate")); + } + + #[test] + fn unrelated_mcp_and_cloudflare_403_500_errors_are_not_rewritten() { + let unbound = sanitize_server_bound_auth_result( + upstream_auth_fixture("Bearer error=\"invalid_token\""), + false, + ); + assert!(unbound.meta.unwrap().0.contains_key("mcp/www_authenticate")); + + for code in [403, 500] { + let message = format!("Cloudflare HTTP {code} test fixture"); + let result = sanitize_server_bound_auth_result(ToolResult::error(&message), true); + let ToolContent::Text(actual) = &result.content[0] else { + panic!("expected original provider error"); + }; + assert_eq!(actual, &message); + } + } + + #[tokio::test] + async fn direct_mode_with_server_bound_auth_uses_existing_grant_without_oauth_meta() { + let (url, _calls, server_task) = spawn_catalog_upstream().await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config.mcp_servers.insert( + "cloudflare-api".to_string(), + McpServerSpec { + url: Some(url), + mode: Some(McpToolExposure::Direct), + http_headers: HashMap::from([( + "Authorization".to_string(), + "Bearer fixture-token".to_string(), + )]), + ..Default::default() + }, + ); + let bridge = connect_upstreams(&config).await; + let tool = bridge + .tools + .iter() + .find(|tool| tool.name() == "cloudflare_api__decompile_function") + .expect("Cloudflare mock tool should be exposed"); + let meta = tool.meta().expect("unrelated upstream metadata retained"); + assert_eq!(meta.0.get("vendor"), Some(&json!("hex-rays"))); + assert!(!meta.0.contains_key("securitySchemes")); + assert!(!meta.0.contains_key("openai/profile")); + assert_eq!(tool.annotations().unwrap().read_only_hint, Some(true)); + + let response = call_bridge_tool( + &bridge, + "cloudflare_api__decompile_function", + json!({"location": {"virtual_address": "0x01"}}), + ) + .await; + assert!(!response.is_error); + drop(bridge); + server_task.abort(); + let _ = server_task.await; + } + #[tokio::test] async fn explicit_direct_mode_retains_per_tool_exposure_and_metadata() { let (url, calls, server_task) = spawn_catalog_upstream().await; @@ -2694,6 +3201,7 @@ mod tests { UpstreamCallContext { resources: &resources, control: &crate::upstream_control::UpstreamControl::default(), + conversation: None, }, ) .await; @@ -2711,6 +3219,7 @@ mod tests { UpstreamCallContext { resources: &resources, control: &crate::upstream_control::UpstreamControl::default(), + conversation: None, }, ) .await; @@ -2737,6 +3246,7 @@ mod tests { UpstreamCallContext { resources: &resources, control: &crate::upstream_control::UpstreamControl::default(), + conversation: None, }, ) .await; @@ -2823,6 +3333,7 @@ mod tests { UpstreamCallContext { resources: &resources, control: &control, + conversation: None, }, ); let fail = async { @@ -2837,6 +3348,95 @@ mod tests { task.abort(); } + #[derive(Clone)] + struct DelayedCatalogMcp { + active: Arc, + peak: Arc, + } + + impl ServerHandler for DelayedCatalogMcp { + fn get_info(&self) -> ServerInfo { + InitializeResult::new(ServerCapabilities::builder().enable_tools().build()) + .with_server_info(Implementation::new("delayed-catalog", "1.0.0")) + } + + async fn list_tools( + &self, + _request: Option, + _context: RequestContext, + ) -> Result { + use std::sync::atomic::Ordering; + let count = self.active.fetch_add(1, Ordering::SeqCst) + 1; + self.peak.fetch_max(count, Ordering::SeqCst); + tokio::time::sleep(Duration::from_millis(400)).await; + self.active.fetch_sub(1, Ordering::SeqCst); + let schema = json!({"type":"object"}).as_object().unwrap().clone(); + Ok(ListToolsResult::with_all_items(vec![ + rmcp::model::Tool::new("noop", "No-op for bounded startup regression", schema), + ])) + } + } + + #[tokio::test] + async fn initializes_multiple_mcp_sources_concurrently_without_reordering_the_catalog() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let active = Arc::new(AtomicUsize::new(0)); + let peak = Arc::new(AtomicUsize::new(0)); + let upstream = DelayedCatalogMcp { + active: Arc::clone(&active), + peak: Arc::clone(&peak), + }; + let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)) + .await + .unwrap(); + let address = listener.local_addr().unwrap(); + let mut http = StreamableHttpServerConfig::default(); + http.json_response = true; + let service = StreamableHttpService::new( + move || Ok(upstream.clone()), + Arc::new(LocalSessionManager::default()), + http, + ); + let server_task = tokio::spawn(async move { + axum::serve(listener, Router::new().nest_service("/mcp", service)) + .await + .unwrap(); + }); + let mut config = crate::config::default_config(std::env::temp_dir()); + for name in ["delta", "bravo", "alpha", "charlie"] { + config.mcp_servers.insert( + name.into(), + McpServerSpec { + url: Some(format!("http://{address}/mcp")), + transport: Some("http".into()), + mode: Some(McpToolExposure::Direct), + startup_timeout_sec: Some(5.0), + ..Default::default() + }, + ); + } + let bridge = connect_upstreams(&config).await; + assert_eq!( + bridge.runtime.snapshot().sources.len(), + 4, + "all four MCP sources should connect" + ); + let reported: Vec<_> = bridge + .report + .iter() + .map(|line| line.split_once(" ->").unwrap().0) + .collect(); + assert_eq!(reported, ["alpha", "bravo", "charlie", "delta"]); + let maximum = peak.load(Ordering::SeqCst); + assert!( + (2..=3).contains(&maximum), + "MCP cold-start requests must overlap without exceeding the three-slot limit: {maximum}" + ); + assert_eq!(active.load(Ordering::SeqCst), 0); + drop(bridge); + server_task.abort(); + } + #[tokio::test] async fn skips_upstream_that_fails_to_launch() { let mut config = crate::config::default_config(std::env::temp_dir()); @@ -2852,7 +3452,7 @@ mod tests { bridge.tools.is_empty(), "a failing upstream must be skipped, not fatal" ); - assert!(bridge.services.is_empty()); + assert!(bridge.runtime.snapshot().sources.is_empty()); // The failure is surfaced in the report, not swallowed. assert!(bridge.report.iter().any(|l| l.contains("bad -> FAILED"))); } diff --git a/src/bridge/hot_reload.rs b/src/bridge/hot_reload.rs new file mode 100644 index 00000000..3966c9a0 --- /dev/null +++ b/src/bridge/hot_reload.rs @@ -0,0 +1,602 @@ +//! Transactional replacement of one upstream MCP connection. +//! +//! Tool definitions are rebuilt into an immutable registry snapshot. Dispatch +//! clones only its selected tool into the call, preserving that source's old +//! generation without retaining unrelated MCP connections. +use super::*; +use clap::Parser; +use std::collections::{HashMap, HashSet}; +use std::sync::{Arc, Mutex, RwLock}; +use tokio::sync::{Mutex as AsyncMutex, Notify}; + +const MAX_INTERNED_TOOL_NAMES: usize = 4096; +const REPLACEMENT_PING_TIMEOUT: Duration = Duration::from_secs(3); + +pub(crate) struct Generation { + pub(super) spec: crate::types::McpServerSpec, + pub(super) peer: Peer, + pub(super) tools: Vec, + pub(super) timeout: Option, + pub(super) control: Arc, + pub(super) number: u64, + // Keep the transport alive until every snapshot/call using it is dropped. + _service: Mutex>, + _monitor: UpstreamMonitor, + calls: Mutex, + drained: Notify, +} + +pub(crate) struct CallLease<'a>(&'a Generation); + +impl Drop for CallLease<'_> { + fn drop(&mut self) { + let mut calls = self.0.calls.lock().unwrap(); + *calls -= 1; + if *calls == 0 { + self.0.drained.notify_one(); + } + } +} + +impl Generation { + #[cfg(test)] + pub(super) fn new( + spec: crate::types::McpServerSpec, + service: RunningService, + tools: Vec, + timeout: Option, + number: u64, + ) -> Arc { + Self::for_source("", spec, service, tools, timeout, None, number) + } + + pub(super) fn for_source( + name: &str, + spec: crate::types::McpServerSpec, + service: RunningService, + tools: Vec, + timeout: Option, + scoped: Option>, + number: u64, + ) -> Arc { + let peer = service.peer().clone(); + let control = Arc::new( + crate::upstream_control::UpstreamControl::new(spec.request_limits.clone()) + .for_server(name, &spec) + .with_scoped_playwright(scoped), + ); + let monitor = monitor_upstream(peer.clone(), control.clone()); + Arc::new(Self { + spec, + peer, + tools, + timeout, + control, + number, + _service: Mutex::new(service), + _monitor: monitor, + calls: Mutex::new(0), + drained: Notify::new(), + }) + } + + pub(crate) fn begin_call(&self) -> CallLease<'_> { + *self.calls.lock().unwrap() += 1; + CallLease(self) + } + + async fn wait_for_calls(&self, limit: Duration) -> bool { + tokio::time::timeout(limit, async { + loop { + // Register the waiter before checking the counter. Otherwise + // the last call can finish between the check and registration, + // losing its wakeup and spuriously timing out the drain. + let notified = self.drained.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); + if *self.calls.lock().unwrap() == 0 { + break; + } + notified.await; + } + }) + .await + .is_ok() + } + + fn version(&self) -> Option { + self.peer.peer_info().and_then(|info| { + info.server_info + .as_ref() + .map(|info| info.version.to_string()) + }) + } +} + +struct NamePool(HashMap); + +impl NamePool { + fn intern(&mut self, name: String) -> Result<&'static str, &'static str> { + if let Some(value) = self.0.get(&name) { + return Ok(*value); + } + if self.0.len() >= MAX_INTERNED_TOOL_NAMES { + return Err("TOOL_NAME_LIMIT"); + } + let leaked: &'static str = Box::leak(name.clone().into_boxed_str()); + self.0.insert(name, leaked); + Ok(leaked) + } +} + +pub(crate) struct BridgeView { + pub(crate) tools: Arc>>, + pub(crate) sources: HashMap>, +} + +pub(crate) struct HotReloadRuntime { + view: RwLock>, + config: Arc, + resources: Arc, + names: Mutex, + locks: HashMap>>, + pub(crate) upstreams: + Arc>>>, +} + +impl HotReloadRuntime { + pub(super) fn new( + config: Arc, + resources: Arc, + sources: HashMap>, + ) -> Arc { + let upstreams = sources + .iter() + .map(|(name, generation)| (name.clone(), generation.control.clone())) + .collect(); + let locks = config + .mcp_servers + .keys() + .map(|name| (name.clone(), Arc::new(AsyncMutex::new(())))) + .collect(); + let runtime = Arc::new(Self { + view: RwLock::new(Arc::new(BridgeView { + tools: Arc::new(Vec::new()), + sources: sources.clone(), + })), + config, + resources, + names: Mutex::new(NamePool(HashMap::new())), + locks, + upstreams: Arc::new(RwLock::new(upstreams)), + }); + match runtime.build_view(sources) { + Ok(view) => *runtime.view.write().unwrap() = Arc::new(view), + Err(code) => tracing::error!(%code, "initial MCP registry could not be built"), + } + runtime + } + + pub(crate) fn snapshot(&self) -> Arc { + self.view.read().unwrap().clone() + } + + fn build_view( + &self, + sources: HashMap>, + ) -> Result { + let mut exposed = Vec::new(); + let mut catalog = Vec::new(); + let mut names = self.names.lock().unwrap(); + let mut sorted: Vec<_> = sources.keys().collect(); + sorted.sort(); + for name in sorted { + let source = &sources[name]; + let sanitized = sanitize(name); + match source.spec.exposure() { + McpToolExposure::Gateway => { + let functions = gateway_functions(&source.tools); + let tool = GatewayTool { + name: names.intern(sanitized)?, + server: name.clone(), + description: gateway_description(name, &functions), + function_names: functions.iter().map(|tool| tool.name.clone()).collect(), + peer: source.peer.clone(), + tool_timeout: source.timeout, + control: source.control.clone(), + resources: self.resources.clone(), + generation: source.clone(), + }; + exposed.push(Box::new(tool) as Box); + } + McpToolExposure::Direct => { + let server_bound_upstream_auth = source.spec.bearer_token_env_var.is_some() + || configures_authorization_header(&source.spec); + let mut used = HashSet::new(); + for tool in &source.tools { + let raw_name = tool.name.to_string(); + let display = unique_name(bridged_name(&sanitized, &raw_name), &used); + used.insert(display.clone()); + let description = tool + .description + .as_ref() + .map(ToString::to_string) + .filter(|description| !description.trim().is_empty()) + .unwrap_or_else(|| { + format!("Call the '{raw_name}' tool on the '{name}' MCP server.") + }); + exposed.push(Box::new(BridgedTool { + name: names.intern(display)?, + original_name: raw_name, + server: name.clone(), + title: tool.title.clone().filter(|value| !value.trim().is_empty()), + description, + input_schema: Value::Object((*tool.input_schema).clone()), + output_schema: tool + .output_schema + .as_ref() + .map(|schema| Value::Object((**schema).clone())), + annotations: tool.annotations.clone(), + icons: tool.icons.clone(), + meta: forward_server_bound_tool_metadata( + tool.meta.clone(), + server_bound_upstream_auth, + ), + peer: source.peer.clone(), + tool_timeout: source.timeout, + control: source.control.clone(), + resources: self.resources.clone(), + server_bound_upstream_auth, + generation: source.clone(), + }) as Box); + } + } + McpToolExposure::Catalog => { + catalog.push(CatalogSourceInput { + raw_name: name.clone(), + provenance: source.spec.provenance, + transport: transport_label(&source.spec), + peer_info: source.peer.peer_info(), + tools: source.tools.clone(), + peer: source.peer.clone(), + tool_timeout: source.timeout, + control: source.control.clone(), + generation: source.clone(), + }); + } + } + } + let mut tools = build_catalog_tools(catalog, self.resources.clone()); + tools.append(&mut exposed); + let mut seen = HashSet::new(); + let tools = tools + .into_iter() + .filter_map(|tool| { + if !seen.insert(tool.name()) { + tracing::warn!( + name = tool.name(), + "duplicate upstream MCP tool name skipped" + ); + return None; + } + match crate::tool::validate_and_wrap_tool(tool) { + Ok(tool) => Some(Arc::::from(tool)), + Err(error) => { + tracing::warn!(%error, "invalid upstream MCP tool skipped"); + None + } + } + }) + .collect(); + Ok(BridgeView { + sources, + tools: Arc::new(tools), + }) + } + + fn latest_spec(&self, name: &str) -> Result { + // Parse the same CLI arguments as startup; this is read-only and never + // rewrites a config migration. No executable or path comes from the MCP + // request: only the operator's configured source ID is accepted. + let cli = crate::config::Cli::try_parse_from(std::env::args_os()) + .map_err(|_| "CONFIG_CLI_INVALID")?; + let config = + crate::config::load_config_quiet_read_only(cli).map_err(|_| "CONFIG_INVALID")?; + config + .mcp_servers + .get(name) + .cloned() + .ok_or("SOURCE_REMOVED") + } + + pub(crate) async fn reload( + &self, + name: &str, + cancellation: Option<&CancellationToken>, + ) -> Result { + if name.is_empty() || name.len() > 128 || name.chars().any(char::is_control) { + return Err("SOURCE_ID_INVALID"); + } + if !self.locks.contains_key(name) { + return Err("SOURCE_UNKNOWN"); + } + let spec = self.latest_spec(name)?; + self.reload_with_spec(name, spec, cancellation).await + } + + // A test harness can supply an isolated spec without reloading real + // operator configuration. Production accepts source ID only and always + // resolves the current configured spec before reaching this boundary. + pub(super) async fn reload_with_spec( + &self, + name: &str, + spec: crate::types::McpServerSpec, + cancellation: Option<&CancellationToken>, + ) -> Result { + let lock = self.locks.get(name).ok_or("SOURCE_UNKNOWN")?; + let _lease = lock.try_lock().map_err(|_| "RELOAD_IN_PROGRESS")?; + self.reload_with_spec_locked(name, spec, cancellation).await + } + + async fn reload_with_spec_locked( + &self, + name: &str, + spec: crate::types::McpServerSpec, + cancellation: Option<&CancellationToken>, + ) -> Result { + if spec.disabled { + return Err("SOURCE_DISABLED"); + } + if cancellation.is_some_and(CancellationToken::is_cancelled) { + return Err("CANCELLED"); + } + let started = std::time::Instant::now(); + let previous = self.snapshot().sources.get(name).cloned(); + let old_generation = previous.as_ref().map_or(0, |source| source.number); + // Reloading a per-task browser source would retire idle agent sessions + // when the old generation drops. Never steal or close active browser tabs. + if spec.session_scope == McpSessionScope::PerChat { + return Err("SCOPED_BROWSER_RELOAD_REQUIRES_QUIESCENCE"); + } + let future = connect_owned_source(name, &spec, &self.config); + let (service, tools, timeout, scoped) = if let Some(token) = cancellation { + tokio::select! { + _ = token.cancelled() => return Err("CANCELLED"), + result = future => result.map_err(|_| "INITIALIZE_FAILED")?, + } + } else { + future.await.map_err(|_| "INITIALIZE_FAILED")? + }; + let ready = matches!( + tokio::time::timeout( + REPLACEMENT_PING_TIMEOUT, + service + .peer() + .send_request(ClientRequest::PingRequest(Default::default())) + ) + .await, + Ok(Ok(_) | Err(ServiceError::McpError(_))) + ); + if !ready { + return Err("READINESS_FAILED"); + } + + let added; + let removed; + let changed; + let unchanged; + { + let before: HashMap<_, _> = previous + .as_ref() + .map(|generation| &generation.tools) + .into_iter() + .flatten() + .map(|tool| { + ( + tool.name.as_ref(), + serde_json::to_value(tool).unwrap_or(Value::Null), + ) + }) + .collect(); + let after: HashMap<_, _> = tools + .iter() + .map(|tool| { + ( + tool.name.as_ref(), + serde_json::to_value(tool).unwrap_or(Value::Null), + ) + }) + .collect(); + added = after + .keys() + .filter(|key| !before.contains_key(**key)) + .count(); + removed = before + .keys() + .filter(|key| !after.contains_key(**key)) + .count(); + changed = after + .iter() + .filter(|(key, value)| before.get(**key).is_some_and(|old| old != *value)) + .count(); + unchanged = after + .iter() + .filter(|(key, value)| before.get(**key).is_some_and(|old| old == *value)) + .count(); + } + let initialization_ms = started.elapsed().as_millis() as u64; + let new = Generation::for_source( + name, + spec, + service, + tools, + timeout, + scoped, + old_generation + 1, + ); + let new_version = new.version(); + // Connection preparation and view construction are outside the write + // lock. Compare-and-rebuild prevents concurrent distinct-source reloads + // from overwriting each other. + if cancellation.is_some_and(CancellationToken::is_cancelled) { + return Err("CANCELLED"); + } + let switching = std::time::Instant::now(); + loop { + let before = self.snapshot(); + let mut sources = before.sources.clone(); + sources.insert(name.to_owned(), new.clone()); + let candidate = Arc::new(self.build_view(sources)?); + let mut current = self.view.write().unwrap(); + if !Arc::ptr_eq(&before, ¤t) { + continue; + } + *current = candidate; + break; + } + self.upstreams + .write() + .unwrap() + .insert(name.to_owned(), new.control.clone()); + let switching_ms = switching.elapsed().as_millis() as u64; + + if new.spec.exposure() == McpToolExposure::Gateway { + let funcs = gateway_functions(&new.tools); + write_gateway_skill(&self.config, name, &sanitize(name), &funcs); + } + + // The old generation stays alive in requests pinned to its tools. + // On a bounded drain timeout its existing calls are NOT cancelled or + // replayed; the generation retires when the last call releases it. + let drain_ms = previous + .as_ref() + .map_or(0, |source| source.spec.request_limits.slow_cancellation_ms); + let draining = std::time::Instant::now(); + let drained = if let Some(old) = &previous { + old.wait_for_calls(Duration::from_millis(drain_ms)).await + } else { + true + }; + let in_flight = previous + .as_ref() + .map_or(0, |old| *old.calls.lock().unwrap()); + // A selected but not yet forwarded call, an old catalog snapshot, + // or an active resource may still pin the retiring generation. + // Do not misreport that its process has already been released. + let still_referenced = previous + .as_ref() + .is_some_and(|old| Arc::strong_count(old) > 1); + Ok(json!({ + "source": name, + "outcome": "reloaded", + "previousGeneration": old_generation, + "replacementGeneration": new.number, + "previousVersion": previous.as_ref().and_then(|old| old.version()), + "replacementVersion": new_version, + "ready": true, + "toolChanges": { + "added": added, "removed": removed, "changed": changed, "unchanged": unchanged + }, + "oldCallsDrained": drained, + "oldCallsStillRunning": in_flight, + "oldGenerationStillReferenced": still_referenced, + "oldGenerationRetiring": !drained || still_referenced, + "rollback": "not_required", + "timingsMs": { + "initializationAndReadiness": initialization_ms, + "registrySwitch": switching_ms, + "drain": draining.elapsed().as_millis() as u64, + "total": started.elapsed().as_millis() as u64 + }, + "clientRediscoveryRequired": true, + "diagnosticCode": "OK" + })) + } +} + +pub(crate) struct ReloadMcpTool { + pub(crate) runtime: Arc, +} + +#[async_trait] +impl Tool for ReloadMcpTool { + fn name(&self) -> &'static str { + "reload_mcp" + } + + fn title(&self) -> String { + "Reload one MCP source".into() + } + + fn description(&self) -> String { + "Transactionally replace one configured upstream MCP source without restarting Codexify or reconnecting any other source. The source is its exact configured MCP server key, not an executable path. Existing calls keep the previous generation. Tool definition changes require the client to rediscover tools/list; in-chat ChatGPT schema updates are not guaranteed.".into() + } + + fn behavior(&self) -> ToolBehavior { + ToolBehavior::new( + false, + true, + false, + false, + "Process replacement is an operator action; no arbitrary executable arguments are accepted.", + ) + } + + fn input_schema(&self) -> Value { + json!({ + "type": "object", + "properties": { + "source": {"type": "string", "minLength": 1, "maxLength": 128, + "description": "Exact stable key of an existing configured MCP server"} + }, + "required": ["source"], + "additionalProperties": false + }) + } + + fn requires_project_root(&self) -> bool { + false + } + + async fn call(&self, args: Value, _config: &AppConfig, _session: &SessionState) -> ToolResult { + self.run(&args, None).await + } + + async fn call_with_context( + &self, + args: Value, + _config: &AppConfig, + _session: &SessionState, + context: &ToolRequestContext, + ) -> ToolResult { + self.run(&args, Some(&context.cancellation)).await + } +} + +impl ReloadMcpTool { + async fn run(&self, args: &Value, cancellation: Option<&CancellationToken>) -> ToolResult { + let Some(source) = args.get("source").and_then(Value::as_str) else { + return ToolResult::error("SOURCE_ID_INVALID"); + }; + match self.runtime.reload(source, cancellation).await { + Ok(report) => { + ToolResult::text("MCP source reloaded; rediscover tools to refresh client schemas.") + .with_structured(report) + } + Err(code) => { + let old = self.runtime.snapshot().sources.get(source).cloned(); + let report = json!({ + "source": source, + "outcome": "failed_without_switch", + "previousGeneration": old.as_ref().map(|generation| generation.number), + "previousVersion": old.as_ref().and_then(|generation| generation.version()), + "rollback": "previous_registry_retained", + "clientRediscoveryRequired": false, + "diagnosticCode": code + }); + ToolResult::error(format!("MCP reload did not switch connections: {code}")) + .with_structured(report) + } + } + } +} diff --git a/src/bridge/hot_reload_tests.rs b/src/bridge/hot_reload_tests.rs new file mode 100644 index 00000000..3097e557 --- /dev/null +++ b/src/bridge/hot_reload_tests.rs @@ -0,0 +1,1032 @@ +//! Isolated, real HTTP MCP fault-injection coverage for per-source reload. +use super::*; +use axum::Router; +use rmcp::{ + ErrorData as McpError, ServerHandler, + model::{ + CallToolResponse, Implementation, InitializeResult, ListToolsResult, + PaginatedRequestParams, ServerCapabilities, ServerInfo, + }, + service::{RequestContext, RoleServer}, + transport::streamable_http_server::{ + StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager, + }, +}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +#[derive(Clone)] +struct Fixture { + version: &'static str, + new_tool: bool, + list_delay: Duration, + call_delay: Duration, + started: Arc, +} + +impl ServerHandler for Fixture { + fn get_info(&self) -> ServerInfo { + InitializeResult::new(ServerCapabilities::builder().enable_tools().build()) + .with_server_info(Implementation::new("hot-reload-fixture", self.version)) + } + + async fn list_tools( + &self, + _request: Option, + _context: RequestContext, + ) -> Result { + tokio::time::sleep(self.list_delay).await; + let schema = serde_json::json!({ + "type": "object", + "properties": {}, + "additionalProperties": false + }) + .as_object() + .cloned() + .unwrap(); + let mut tools = vec![ + rmcp::model::Tool::new("probe", "Report this fixture's version", schema.clone()), + rmcp::model::Tool::new( + "slow", + "Report this fixture's version after a delay", + schema.clone(), + ), + ]; + if self.new_tool { + tools.push(rmcp::model::Tool::new( + "new_tool", + "Added in version two", + schema, + )); + } + Ok(ListToolsResult::with_all_items(tools)) + } + + async fn call_tool( + &self, + request: CallToolRequestParams, + _context: RequestContext, + ) -> Result { + self.started.fetch_add(1, Ordering::SeqCst); + if request.name.as_ref() == "slow" { + tokio::time::sleep(self.call_delay).await; + } + Ok(CallToolResult::success(vec![ContentBlock::text(self.version)]).into()) + } +} + +async fn fixture( + version: &'static str, + new_tool: bool, + list_delay: Duration, + call_delay: Duration, +) -> (String, Arc, tokio::task::JoinHandle<()>) { + let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)) + .await + .unwrap(); + let address = listener.local_addr().unwrap(); + let calls = Arc::new(AtomicUsize::new(0)); + let fixture = Fixture { + version, + new_tool, + list_delay, + call_delay, + started: calls.clone(), + }; + let mut transport = StreamableHttpServerConfig::default(); + transport.json_response = true; + let service = StreamableHttpService::new( + move || Ok(fixture.clone()), + Arc::new(LocalSessionManager::default()), + transport, + ); + let app = Router::new().nest_service("/mcp", service); + let task = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + (format!("http://{address}/mcp"), calls, task) +} + +fn spec(url: &str, exposure: McpToolExposure) -> crate::types::McpServerSpec { + crate::types::McpServerSpec { + url: Some(url.to_string()), + mode: Some(exposure), + ..Default::default() + } +} + +async fn invoke(view: Arc, name: &str) -> ToolResult { + invoke_args(view, name, json!({})).await +} + +async fn invoke_args(view: Arc, name: &str, args: Value) -> ToolResult { + let tool = view + .tools + .iter() + .find(|tool| tool.name() == name) + .unwrap_or_else(|| panic!("tool {name} missing from view")); + tool.call( + args, + &crate::config::default_config(std::env::temp_dir()), + &SessionState::new(), + ) + .await +} + +#[tokio::test] +async fn scoped_browser_reload_fails_closed_without_retiring_live_task_sessions() { + let (url, _, task) = fixture("before", false, Duration::ZERO, Duration::ZERO).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config + .mcp_servers + .insert("alpha".into(), spec(&url, McpToolExposure::Direct)); + let bridge = connect_upstreams(&config).await; + let runtime = bridge.runtime.clone(); + let before = runtime.snapshot(); + let mut scoped = spec(&url, McpToolExposure::Direct); + scoped.session_scope = McpSessionScope::PerChat; + let error = runtime + .reload_with_spec("alpha", scoped, None) + .await + .unwrap_err(); + assert_eq!(error, "SCOPED_BROWSER_RELOAD_REQUIRES_QUIESCENCE"); + let after = runtime.snapshot(); + assert!(Arc::ptr_eq( + &before.sources["alpha"], + &after.sources["alpha"] + )); + assert_eq!(invoke(after, "alpha__probe").await.joined_text(), "before"); + task.abort(); +} + +#[tokio::test] +async fn single_source_reload_updates_tools_but_not_other_mcp() { + let (old_url, _, old_task) = fixture("1", false, Duration::ZERO, Duration::ZERO).await; + let (new_url, _, new_task) = fixture("2", true, Duration::ZERO, Duration::ZERO).await; + let (other_url, _, other_task) = fixture("other", false, Duration::ZERO, Duration::ZERO).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config + .mcp_servers + .insert("alpha".into(), spec(&old_url, McpToolExposure::Direct)); + config + .mcp_servers + .insert("beta".into(), spec(&other_url, McpToolExposure::Direct)); + let bridge = connect_upstreams(&config).await; + let runtime = bridge.runtime.clone(); + let before = runtime.snapshot(); + assert_eq!( + invoke(before.clone(), "alpha__probe").await.joined_text(), + "1" + ); + assert_eq!( + invoke(before.clone(), "beta__probe").await.joined_text(), + "other" + ); + + let result = runtime + .reload_with_spec("alpha", spec(&new_url, McpToolExposure::Direct), None) + .await + .unwrap(); + assert_eq!(result["outcome"], "reloaded"); + assert_eq!(result["previousGeneration"], 1); + assert_eq!(result["replacementGeneration"], 2); + assert_eq!(result["previousVersion"], "1"); + assert_eq!(result["replacementVersion"], "2"); + assert_eq!(result["toolChanges"]["added"], 1); + assert_eq!(result["oldCallsDrained"], true); + + let after = runtime.snapshot(); + assert!(Arc::ptr_eq(&before.sources["beta"], &after.sources["beta"])); + assert!(!Arc::ptr_eq( + &before.sources["alpha"], + &after.sources["alpha"] + )); + assert_eq!( + invoke(after.clone(), "alpha__probe").await.joined_text(), + "2" + ); + assert_eq!( + invoke(after.clone(), "alpha__new_tool").await.joined_text(), + "2" + ); + assert_eq!(invoke(after, "beta__probe").await.joined_text(), "other"); + assert_eq!(invoke(before, "alpha__probe").await.joined_text(), "1"); + old_task.abort(); + new_task.abort(); + other_task.abort(); +} + +#[tokio::test] +async fn active_calls_keep_their_original_generation_without_replay() { + let (old_url, old_count, old_task) = + fixture("1", false, Duration::ZERO, Duration::from_millis(450)).await; + let (new_url, new_count, new_task) = fixture("2", true, Duration::ZERO, Duration::ZERO).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config + .mcp_servers + .insert("alpha".into(), spec(&old_url, McpToolExposure::Direct)); + let runtime = connect_upstreams(&config).await.runtime; + let initial = runtime.snapshot(); + let pending = tokio::spawn(invoke(initial, "alpha__slow")); + tokio::time::timeout(Duration::from_secs(2), async { + while old_count.load(Ordering::SeqCst) == 0 { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .unwrap(); + let started = std::time::Instant::now(); + let result = runtime + .reload_with_spec("alpha", spec(&new_url, McpToolExposure::Direct), None) + .await + .unwrap(); + assert_eq!(result["oldCallsDrained"], true); + assert!(started.elapsed() >= Duration::from_millis(100)); + assert_eq!(pending.await.unwrap().joined_text(), "1"); + assert_eq!(old_count.load(Ordering::SeqCst), 1); + assert_eq!( + invoke(runtime.snapshot(), "alpha__probe") + .await + .joined_text(), + "2" + ); + assert_eq!(new_count.load(Ordering::SeqCst), 1); + old_task.abort(); + new_task.abort(); +} + +#[tokio::test] +async fn failed_replacement_and_unknown_ids_cannot_mutate_active_generation() { + let (old_url, _, old_task) = fixture("1", false, Duration::ZERO, Duration::ZERO).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config + .mcp_servers + .insert("alpha".into(), spec(&old_url, McpToolExposure::Direct)); + let runtime = connect_upstreams(&config).await.runtime; + let old = runtime.snapshot(); + + assert_eq!( + runtime + .reload_with_spec( + "missing", + spec("http://127.0.0.1:9/mcp", McpToolExposure::Direct), + None + ) + .await + .unwrap_err(), + "SOURCE_UNKNOWN" + ); + assert_eq!( + runtime + .reload_with_spec( + "alpha", + spec("http://127.0.0.1:9/mcp", McpToolExposure::Direct), + None + ) + .await + .unwrap_err(), + "INITIALIZE_FAILED" + ); + let after = runtime.snapshot(); + assert!(Arc::ptr_eq(&old, &after)); + assert_eq!(invoke(after, "alpha__probe").await.joined_text(), "1"); + old_task.abort(); +} + +#[tokio::test] +async fn same_source_reload_conflicts_while_other_source_can_reload() { + let (a1, _, first_task) = fixture("1", false, Duration::ZERO, Duration::ZERO).await; + let (a2, _, second_task) = fixture("2", true, Duration::from_millis(300), Duration::ZERO).await; + let (b1, _, third_task) = fixture("other1", false, Duration::ZERO, Duration::ZERO).await; + let (b2, _, fourth_task) = fixture("other2", false, Duration::ZERO, Duration::ZERO).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config + .mcp_servers + .insert("alpha".into(), spec(&a1, McpToolExposure::Direct)); + config + .mcp_servers + .insert("beta".into(), spec(&b1, McpToolExposure::Direct)); + let runtime = connect_upstreams(&config).await.runtime; + let clone = runtime.clone(); + let initial = tokio::spawn(async move { + clone + .reload_with_spec("alpha", spec(&a2, McpToolExposure::Direct), None) + .await + }); + tokio::time::sleep(Duration::from_millis(50)).await; + assert_eq!( + runtime + .reload_with_spec("alpha", spec(&a1, McpToolExposure::Direct), None) + .await + .unwrap_err(), + "RELOAD_IN_PROGRESS" + ); + let other = runtime + .reload_with_spec("beta", spec(&b2, McpToolExposure::Direct), None) + .await + .unwrap(); + assert_eq!(other["replacementGeneration"], 2); + assert_eq!(initial.await.unwrap().unwrap()["replacementGeneration"], 2); + let view = runtime.snapshot(); + assert_eq!( + invoke(view.clone(), "alpha__probe").await.joined_text(), + "2" + ); + assert_eq!(invoke(view, "beta__probe").await.joined_text(), "other2"); + first_task.abort(); + second_task.abort(); + third_task.abort(); + fourth_task.abort(); +} + +#[tokio::test] +async fn catalog_reload_refreshes_search_schema_and_call_routing() { + let (old_url, _, old_task) = fixture("1", false, Duration::ZERO, Duration::ZERO).await; + let (new_url, _, new_task) = fixture("2", true, Duration::ZERO, Duration::ZERO).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config + .mcp_servers + .insert("catalog".into(), spec(&old_url, McpToolExposure::Catalog)); + let runtime = connect_upstreams(&config).await.runtime; + let before = runtime.snapshot(); + let source = invoke(before, "mcp_list_sources") + .await + .structured_content + .unwrap(); + assert_eq!(source["sources"][0]["toolCount"], 2); + let result = runtime + .reload_with_spec("catalog", spec(&new_url, McpToolExposure::Catalog), None) + .await + .unwrap(); + assert_eq!(result["toolChanges"]["added"], 1); + let after = runtime.snapshot(); + let list = invoke(after.clone(), "mcp_list_sources") + .await + .structured_content + .unwrap(); + assert_eq!(list["sources"][0]["toolCount"], 3); + let source_id = list["sources"][0]["id"].as_str().unwrap(); + let found = invoke_args( + after.clone(), + "mcp_search_tools", + json!({"query":"new_tool","source":source_id}), + ) + .await + .structured_content + .unwrap(); + assert!(found["total"].as_u64().unwrap_or(0) >= 1); + let tool_id = found["matches"][0]["toolId"].as_str().unwrap(); + let call = invoke_args( + after, + "mcp_call_tool", + json!({"source":source_id,"tool":tool_id,"arguments":{}}), + ) + .await; + assert!(!call.is_error); + assert_eq!(call.joined_text(), "2"); + old_task.abort(); + new_task.abort(); +} + +#[tokio::test] +async fn gateway_reload_reflects_added_functions() { + let (old_url, _, old_task) = fixture("1", false, Duration::ZERO, Duration::ZERO).await; + let (new_url, _, new_task) = fixture("2", true, Duration::ZERO, Duration::ZERO).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config + .mcp_servers + .insert("gateway".into(), spec(&old_url, McpToolExposure::Gateway)); + let runtime = connect_upstreams(&config).await.runtime; + let before = runtime.snapshot(); + let old = invoke_args( + before, + "gateway", + json!({"function":"probe","arguments":{}}), + ) + .await; + assert_eq!(old.joined_text(), "1"); + runtime + .reload_with_spec("gateway", spec(&new_url, McpToolExposure::Gateway), None) + .await + .unwrap(); + let after = runtime.snapshot(); + let tool = after + .tools + .iter() + .find(|tool| tool.name() == "gateway") + .unwrap(); + assert!( + tool.input_schema()["properties"]["function"]["enum"] + .as_array() + .unwrap() + .contains(&json!("new_tool")) + ); + let new = invoke_args( + after, + "gateway", + json!({"function":"new_tool","arguments":{}}), + ) + .await; + assert_eq!(new.joined_text(), "2"); + old_task.abort(); + new_task.abort(); +} + +#[tokio::test] +async fn reconnect_failed_initial_source_and_cancel_without_switching() { + let (url, _, task) = fixture("recovered", false, Duration::ZERO, Duration::ZERO).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config.mcp_servers.insert( + "unavailable".into(), + crate::types::McpServerSpec { + url: Some("http://127.0.0.1:9/mcp".into()), + startup_timeout_sec: Some(0.5), + ..Default::default() + }, + ); + let runtime = connect_upstreams(&config).await.runtime; + assert!(!runtime.snapshot().sources.contains_key("unavailable")); + let result = runtime + .reload_with_spec("unavailable", spec(&url, McpToolExposure::Direct), None) + .await + .unwrap(); + assert_eq!(result["previousGeneration"], 0); + assert_eq!(result["replacementGeneration"], 1); + assert_eq!( + invoke(runtime.snapshot(), "unavailable__probe") + .await + .joined_text(), + "recovered" + ); + + let old = runtime.snapshot(); + let cancelled = CancellationToken::new(); + cancelled.cancel(); + assert_eq!( + runtime + .reload_with_spec( + "unavailable", + spec(&url, McpToolExposure::Direct), + Some(&cancelled) + ) + .await + .unwrap_err(), + "CANCELLED" + ); + assert!(Arc::ptr_eq(&old, &runtime.snapshot())); + task.abort(); +} + +#[tokio::test] +async fn repeated_reloads_keep_one_active_generation_per_source() { + let (url, _, task) = fixture("stable", false, Duration::ZERO, Duration::ZERO).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config + .mcp_servers + .insert("alpha".into(), spec(&url, McpToolExposure::Direct)); + let runtime = connect_upstreams(&config).await.runtime; + for expected in 2..=6 { + let result = runtime + .reload_with_spec("alpha", spec(&url, McpToolExposure::Direct), None) + .await + .unwrap(); + assert_eq!(result["replacementGeneration"], expected); + assert_eq!(result["oldCallsDrained"], true); + let view = runtime.snapshot(); + assert_eq!(view.sources.len(), 1); + assert_eq!(invoke(view, "alpha__probe").await.joined_text(), "stable"); + } + task.abort(); +} + +#[tokio::test] +async fn direct_name_collisions_are_not_ambiguous_after_reload() { + let (url1, _, task1) = fixture("one", false, Duration::ZERO, Duration::ZERO).await; + let (url2, _, task2) = fixture("two", true, Duration::ZERO, Duration::ZERO).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + // sanitize("dup!")==sanitize("dup?"), so both would generate dup___probe. + config + .mcp_servers + .insert("dup!".into(), spec(&url1, McpToolExposure::Direct)); + config + .mcp_servers + .insert("dup?".into(), spec(&url2, McpToolExposure::Direct)); + let runtime = connect_upstreams(&config).await.runtime; + let view = runtime.snapshot(); + let names = view + .tools + .iter() + .map(|tool| tool.name()) + .collect::>(); + let unique = names + .iter() + .copied() + .collect::>(); + assert_eq!(unique.len(), names.len()); + assert_eq!( + names.iter().filter(|name| **name == "dup___probe").count(), + 1 + ); + task1.abort(); + task2.abort(); +} + +#[tokio::test] +async fn old_generation_is_released_after_draining_without_stale_snapshots() { + let (old_url, _, old_task) = fixture("old", false, Duration::ZERO, Duration::ZERO).await; + let (new_url, _, new_task) = fixture("new", true, Duration::ZERO, Duration::ZERO).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config + .mcp_servers + .insert("alpha".into(), spec(&old_url, McpToolExposure::Direct)); + let bridge = connect_upstreams(&config).await; + let runtime = bridge.runtime.clone(); + let first = runtime.snapshot(); + let weak = Arc::downgrade(&first.sources["alpha"]); + drop(first); + // The service keeps only the runtime after consuming the startup report. + drop(bridge); + assert!(weak.upgrade().is_some()); + + let result = runtime + .reload_with_spec("alpha", spec(&new_url, McpToolExposure::Direct), None) + .await + .unwrap(); + assert_eq!(result["oldCallsDrained"], true); + assert!( + weak.upgrade().is_none(), + "retired service generation leaked" + ); + assert_eq!( + invoke(runtime.snapshot(), "alpha__probe") + .await + .joined_text(), + "new" + ); + old_task.abort(); + new_task.abort(); +} + +#[tokio::test] +async fn unrelated_in_flight_call_does_not_retain_a_retired_source() { + let (a1, _, task_a1) = fixture("alpha-1", false, Duration::ZERO, Duration::ZERO).await; + let (a2, _, task_a2) = fixture("alpha-2", false, Duration::ZERO, Duration::ZERO).await; + let (b, b_calls, task_b) = + fixture("beta", false, Duration::ZERO, Duration::from_millis(400)).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config + .mcp_servers + .insert("alpha".into(), spec(&a1, McpToolExposure::Direct)); + config + .mcp_servers + .insert("beta".into(), spec(&b, McpToolExposure::Direct)); + let runtime = connect_upstreams(&config).await.runtime; + let initial = runtime.snapshot(); + let alpha = Arc::downgrade(&initial.sources["alpha"]); + // Copy only beta's validated descriptor, just as server dispatch does. + let beta = initial + .tools + .iter() + .find(|tool| tool.name() == "beta__slow") + .unwrap() + .clone(); + drop(initial); + + let pending = tokio::spawn(async move { + beta.call( + json!({}), + &crate::config::default_config(std::env::temp_dir()), + &SessionState::new(), + ) + .await + }); + tokio::time::timeout(Duration::from_secs(2), async { + while b_calls.load(Ordering::SeqCst) == 0 { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .unwrap(); + + let result = runtime + .reload_with_spec("alpha", spec(&a2, McpToolExposure::Direct), None) + .await + .unwrap(); + assert_eq!(result["oldCallsDrained"], true); + assert!( + alpha.upgrade().is_none(), + "a beta request must not retain alpha's retired connection" + ); + assert_eq!(pending.await.unwrap().joined_text(), "beta"); + assert_eq!( + invoke(runtime.snapshot(), "alpha__probe") + .await + .joined_text(), + "alpha-2" + ); + task_a1.abort(); + task_a2.abort(); + task_b.abort(); +} + +fn isolated_stdio_spec(version: &str) -> crate::types::McpServerSpec { + let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("scripts") + .join("fixtures") + .join("hot-reload-stdio-mcp.mjs"); + crate::types::McpServerSpec { + command: Some("node".into()), + args: vec![fixture.to_string_lossy().into_owned(), version.into()], + mode: Some(McpToolExposure::Direct), + startup_timeout_sec: Some(25.0), + ..Default::default() + } +} + +fn stdio_process_id(result: ToolResult, expected_version: &str) -> u32 { + assert!( + !result.is_error, + "stdio call failed: {}", + result.joined_text() + ); + let response = result.joined_text(); + let (version, pid) = response + .trim() + .split_once(':') + .unwrap_or_else(|| panic!("invalid stdio fixture response: {response}")); + assert_eq!(version, expected_version); + pid.parse() + .expect("stdio fixture process id must be numeric") +} + +async fn stdio_process_still_alive(pid: u32) -> bool { + // Signal 0 checks existence without terminating or signaling a process. + tokio::process::Command::new("node") + .arg("-e") + .arg("try { process.kill(Number(process.argv[1]), 0); } catch { process.exit(1); }") + .arg(pid.to_string()) + .status() + .await + .is_ok_and(|status| status.success()) +} + +#[tokio::test] +async fn distinct_task_owners_get_distinct_stdio_browser_peers_without_global_fallback() { + // A real MCP stdio process is spawned once for tool discovery and once + // for EACH owner. No user Chrome profile or network destination is used. + let mut config = crate::config::default_config(std::env::temp_dir()); + let mut source_spec = isolated_stdio_spec("perchat"); + source_spec.session_scope = McpSessionScope::PerChat; + config + .mcp_servers + .insert("playwright-ownership-fixture".into(), source_spec); + let bridge = connect_upstreams(&config).await; + let view = bridge.runtime.snapshot(); + let source = view + .sources + .get("playwright-ownership-fixture") + .unwrap() + .clone(); + assert!(source.control.scoped_playwright.is_some()); + + let owner_a = ConversationIdentity::from_openai_session("isolated-fixture-owner-a") + .expect("unique valid owner A"); + let owner_b = ConversationIdentity::from_openai_session("isolated-fixture-owner-b") + .expect("unique valid owner B"); + + async fn probe( + source: &hot_reload::Generation, + resources: &BridgedResourceStore, + owner: Option<&ConversationIdentity>, + ) -> ToolResult { + forward_tool_call( + &source.peer, + CallToolRequestParams::new("probe"), + "playwright-ownership-fixture", + "probe", + source.timeout, + None, + UpstreamCallContext { + resources, + control: &source.control, + conversation: owner, + }, + ) + .await + } + + let denied = probe(&source, &bridge.resources, None).await; + assert!(denied.is_error); + assert!( + denied + .joined_text() + .contains("refusing the shared global browser") + ); + + let a1 = stdio_process_id( + probe(&source, &bridge.resources, Some(&owner_a)).await, + "perchat", + ); + let b1 = stdio_process_id( + probe(&source, &bridge.resources, Some(&owner_b)).await, + "perchat", + ); + let a2 = stdio_process_id( + probe(&source, &bridge.resources, Some(&owner_a)).await, + "perchat", + ); + let b2 = stdio_process_id( + probe(&source, &bridge.resources, Some(&owner_b)).await, + "perchat", + ); + assert_ne!( + a1, b1, + "two task owners must never share an MCP child process" + ); + assert_eq!(a1, a2, "one task must keep its own browser connection"); + assert_eq!( + b1, b2, + "the second task must retain its distinct connection" + ); +} + +#[tokio::test] +async fn service_isolated_real_stdio_process_reload_preserves_unrelated_sources() { + // This fixture actually spawns three independent OS processes through the + // production TokioChildProcess transport; no live Codexify is involved. + let directory = tempfile::tempdir().unwrap(); + let started = directory.path().join("slow_started"); + let mut old_spec = isolated_stdio_spec("old"); + old_spec.env.insert( + "HOT_RELOAD_SLOW_MARKER_FILE".into(), + started.to_string_lossy().into_owned(), + ); + + let mut config = crate::config::default_config(std::env::temp_dir()); + config.mcp_servers.insert("alpha".into(), old_spec); + config + .mcp_servers + .insert("beta".into(), isolated_stdio_spec("beta")); + config + .mcp_servers + .insert("gamma".into(), isolated_stdio_spec("gamma")); + let bridge = connect_upstreams(&config).await; + assert_eq!( + bridge.runtime.snapshot().sources.len(), + 3, + "all isolated stdio fixtures must start: {:?}", + bridge.report + ); + let runtime = bridge.runtime.clone(); + drop(bridge); + + let initial = runtime.snapshot(); + let retired = Arc::downgrade(&initial.sources["alpha"]); + let old_probe = initial + .tools + .iter() + .find(|tool| tool.name() == "alpha__probe") + .unwrap() + .clone(); + let old_slow = initial + .tools + .iter() + .find(|tool| tool.name() == "alpha__slow") + .unwrap() + .clone(); + drop(initial); + let config_for_call = crate::config::default_config(std::env::temp_dir()); + let original_pid = stdio_process_id( + old_probe + .call(json!({}), &config_for_call, &SessionState::new()) + .await, + "old", + ); + let beta_pid = stdio_process_id(invoke(runtime.snapshot(), "beta__probe").await, "beta"); + let gamma_pid = stdio_process_id(invoke(runtime.snapshot(), "gamma__probe").await, "gamma"); + + let pending = tokio::spawn(async move { + old_slow + .call( + json!({}), + &crate::config::default_config(std::env::temp_dir()), + &SessionState::new(), + ) + .await + }); + // The marker is written by the actual old process when it receives the + // slow request, making this test independent of host scheduling. + tokio::time::timeout(Duration::from_secs(4), async { + while !started.exists() { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("old stdio process did not begin the slow call"); + + let result = runtime + .reload_with_spec("alpha", isolated_stdio_spec("new"), None) + .await + .unwrap(); + assert_eq!(result["previousVersion"], "old"); + assert_eq!(result["replacementVersion"], "new"); + assert_eq!(result["previousGeneration"], 1); + assert_eq!(result["replacementGeneration"], 2); + assert_eq!(result["toolChanges"]["added"], 1); + assert_eq!(result["oldCallsDrained"], true); + assert_eq!( + stdio_process_id(pending.await.unwrap(), "old"), + original_pid + ); + assert_eq!( + stdio_process_id( + old_probe + .call(json!({}), &config_for_call, &SessionState::new()) + .await, + "old", + ), + original_pid, + "a pinned retired generation must remain callable until released" + ); + let new_pid = stdio_process_id(invoke(runtime.snapshot(), "alpha__probe").await, "new"); + assert_ne!( + new_pid, original_pid, + "replacement must be a new OS process" + ); + assert_eq!( + stdio_process_id(invoke(runtime.snapshot(), "alpha__new_tool").await, "new"), + new_pid + ); + assert_eq!( + stdio_process_id(invoke(runtime.snapshot(), "beta__probe").await, "beta"), + beta_pid, + "beta must not reconnect" + ); + assert_eq!( + stdio_process_id(invoke(runtime.snapshot(), "gamma__probe").await, "gamma"), + gamma_pid, + "gamma must not reconnect" + ); + + let mut invalid_spec = isolated_stdio_spec("broken"); + invalid_spec.command = Some("codexify-nonexistent-hot-reload-fixture".into()); + assert_eq!( + runtime + .reload_with_spec("alpha", invalid_spec, None) + .await + .err(), + Some("INITIALIZE_FAILED") + ); + assert_eq!( + stdio_process_id(invoke(runtime.snapshot(), "alpha__probe").await, "new"), + new_pid, + "an unsuccessful replacement must preserve the healthy process" + ); + + assert!( + stdio_process_still_alive(original_pid).await, + "retiring process must remain alive while a pinned old handle exists" + ); + drop(old_probe); + tokio::task::yield_now().await; + assert!( + retired.upgrade().is_none(), + "the retired generation must be released after its last handle drops" + ); + tokio::time::timeout(Duration::from_secs(5), async { + while stdio_process_still_alive(original_pid).await { + tokio::time::sleep(Duration::from_millis(25)).await; + } + }) + .await + .expect("retired OS child process remained alive after the last handle dropped"); + + let repeated = runtime + .reload_with_spec("alpha", isolated_stdio_spec("new"), None) + .await + .unwrap(); + assert_eq!(repeated["previousGeneration"], 2); + assert_eq!(repeated["replacementGeneration"], 3); + assert_eq!(repeated["toolChanges"]["unchanged"], 3); + assert_eq!( + stdio_process_id(invoke(runtime.snapshot(), "beta__probe").await, "beta"), + beta_pid + ); + assert_eq!( + stdio_process_id(invoke(runtime.snapshot(), "gamma__probe").await, "gamma"), + gamma_pid + ); +} + +/// Opt-in, isolated acceptance test using two real, read-only GodPrompt stdio +/// installs. Only initialize, tools/list, and ping are sent; no GodPrompt tool +/// calls, external APIs, operator configuration, or running service are touched. +/// +/// CI installs and selects the pinned published 1.0.3 / 1.1.1 npm versions. +/// A developer can instead supply two existing entrypoint paths locally. +#[tokio::test] +async fn service_local_godprompt_candidate_upgrade_and_failed_rollback() { + let old_entry = std::env::var_os("CODEXIFY_CANARY_OLD_GODPROMPT"); + let new_entry = std::env::var_os("CODEXIFY_CANARY_NEW_GODPROMPT"); + let (Some(old_entry), Some(new_entry)) = (old_entry, new_entry) else { + assert!( + std::env::var_os("CODEXIFY_CANARY_OLD_GODPROMPT").is_none() + && std::env::var_os("CODEXIFY_CANARY_NEW_GODPROMPT").is_none(), + "provide both isolated GodPrompt entrypoints, or neither" + ); + return; + }; + let node = std::env::var("CODEXIFY_CANARY_NODE").unwrap_or_else(|_| "node".into()); + for entry in [&old_entry, &new_entry] { + assert!( + std::path::Path::new(entry).is_file(), + "GodPrompt candidate stdio entrypoint does not exist" + ); + } + let make_candidate = |entry: &std::ffi::OsStr| crate::types::McpServerSpec { + command: Some(node.clone()), + args: vec![entry.to_string_lossy().into_owned()], + mode: Some(McpToolExposure::Direct), + startup_timeout_sec: Some(18.0), + ..Default::default() + }; + + let (beta_url, _, beta_server) = fixture("beta", false, Duration::ZERO, Duration::ZERO).await; + let (gamma_url, _, gamma_server) = + fixture("gamma", false, Duration::ZERO, Duration::ZERO).await; + let mut config = crate::config::default_config(std::env::temp_dir()); + config.mcp_servers.insert( + "godprompt_canary".into(), + make_candidate(old_entry.as_os_str()), + ); + config + .mcp_servers + .insert("beta".into(), spec(&beta_url, McpToolExposure::Direct)); + config + .mcp_servers + .insert("gamma".into(), spec(&gamma_url, McpToolExposure::Direct)); + + let bridge = connect_upstreams(&config).await; + assert_eq!( + bridge.runtime.snapshot().sources.len(), + 3, + "{:?}", + bridge.report + ); + let runtime = bridge.runtime.clone(); + drop(bridge); + let before = runtime.snapshot(); + let old = before.sources["godprompt_canary"].clone(); + let beta = before.sources["beta"].clone(); + let gamma = before.sources["gamma"].clone(); + let old_tool_count = old.tools.len(); + assert!(old_tool_count > 0, "old GodPrompt must advertise tools"); + drop(before); + + let result = runtime + .reload_with_spec( + "godprompt_canary", + make_candidate(new_entry.as_os_str()), + None, + ) + .await + .expect("replacement GodPrompt must initialize, discover tools and pass ping"); + assert_eq!(result["previousGeneration"], 1); + assert_eq!(result["replacementGeneration"], 2); + assert_eq!(result["ready"], true); + assert_eq!(result["previousVersion"], "1.0.3"); + assert_eq!(result["replacementVersion"], "1.1.1"); + let updated = runtime.snapshot(); + let new = updated.sources["godprompt_canary"].clone(); + assert!(!Arc::ptr_eq(&old, &new)); + assert!(Arc::ptr_eq(&beta, &updated.sources["beta"])); + assert!(Arc::ptr_eq(&gamma, &updated.sources["gamma"])); + assert!(!new.tools.is_empty(), "new GodPrompt must advertise tools"); + println!( + "isolated GodPrompt {} -> {}: {} -> {} tools; timings {:?}; testing rollback", + result["previousVersion"], + result["replacementVersion"], + old_tool_count, + new.tools.len(), + result["timingsMs"] + ); + drop(updated); + + let mut broken = make_candidate(new_entry.as_os_str()); + broken.command = Some("codexify-nonexistent-godprompt-canary".into()); + assert_eq!( + runtime + .reload_with_spec("godprompt_canary", broken, None) + .await + .err(), + Some("INITIALIZE_FAILED") + ); + let after_rollback = runtime.snapshot(); + assert!(Arc::ptr_eq( + &new, + &after_rollback.sources["godprompt_canary"] + )); + assert!(Arc::ptr_eq(&beta, &after_rollback.sources["beta"])); + assert!(Arc::ptr_eq(&gamma, &after_rollback.sources["gamma"])); + beta_server.abort(); + gamma_server.abort(); +} diff --git a/src/codex_mcp.rs b/src/codex_mcp.rs index adb4be65..0e06e3eb 100644 --- a/src/codex_mcp.rs +++ b/src/codex_mcp.rs @@ -355,6 +355,7 @@ fn codex_cli_server_to_spec( tools: server.enabled_tools, disabled_tools: server.disabled_tools, mode: None, + session_scope: Default::default(), provenance: McpServerProvenance::CodexCli, request_limits: crate::types::McpRequestLimits::default(), }); @@ -422,6 +423,7 @@ fn codex_cli_server_to_spec( tools: server.enabled_tools, disabled_tools: server.disabled_tools, mode: None, + session_scope: Default::default(), provenance: McpServerProvenance::CodexCli, request_limits: crate::types::McpRequestLimits::default(), }) @@ -626,6 +628,7 @@ fn parse_server( tools, disabled_tools, mode: None, + session_scope: Default::default(), provenance: McpServerProvenance::CodexConfig, request_limits: crate::types::McpRequestLimits::default(), }), @@ -675,6 +678,7 @@ fn parse_server( tools, disabled_tools, mode: None, + session_scope: Default::default(), provenance: McpServerProvenance::CodexConfig, request_limits: crate::types::McpRequestLimits::default(), }), diff --git a/src/config.rs b/src/config.rs index 000fcabe..c7692aa1 100644 --- a/src/config.rs +++ b/src/config.rs @@ -23,7 +23,7 @@ use crate::project_catalog::{ProjectCatalog, discover_project_catalog_at}; use crate::types::{ AppConfig, ArtifactEgressConfig, ArtifactIngressConfig, AuditConfig, CodexProjectCatalogConfig, CommandConfig, ConversationAuthToken, DiffConfig, ExecConfig, ExperimentalConfig, - FilesystemConfig, IgnoreConfig, McpServerSpec, McpToolExposure, MemoryConfig, + FilesystemConfig, IgnoreConfig, McpServerSpec, McpSessionScope, McpToolExposure, MemoryConfig, OpenAiTunnelConfig, OutputConfig, ProjectCatalogConfig, ProjectCatalogEntryConfig, ProjectDocConfig, SkillsConfig, ToolLogLevel, ToolLogMode, ToolLoggingConfig, TreeConfig, WorktreeConfig, WorktreeMode, WorktreeUpstreamRefreshMode, @@ -615,6 +615,9 @@ struct PartialMcpServerSpec { tools: Option>, disabled_tools: Option>, mode: Option, + // Dropping this explicit field silently downgrades per-chat browser + // ownership and its token-file authorization to a shared global client. + session_scope: Option, } impl PartialMcpServerSpec { @@ -636,6 +639,7 @@ impl PartialMcpServerSpec { tools, disabled_tools, mode, + session_scope, } = self; let sets_command = command.is_some(); let sets_args = args.is_some(); @@ -695,6 +699,9 @@ impl PartialMcpServerSpec { if let Some(mode) = mode { base.mode = Some(mode); } + if let Some(scope) = session_scope { + base.session_scope = scope; + } // Naming a different transport replaces the imported transport rather // than leaving an impossible command+URL hybrid behind. @@ -2006,6 +2013,7 @@ mod tests { tools: Some(vec!["read".to_string()]), disabled_tools: Some(vec!["write".to_string()]), mode: None, + session_scope: Default::default(), provenance: crate::types::McpServerProvenance::CodexConfig, request_limits: crate::types::McpRequestLimits::default(), } @@ -3153,6 +3161,63 @@ mod tests { } } + #[test] + fn explicit_playwright_session_scope_survives_json_overlay() { + let partial: PartialMcpServerSpec = serde_json::from_value(serde_json::json!({ + "command": "node", + "args": ["@playwright/mcp", "--extension"], + "sessionScope": "per-chat", + "env": { + "PLAYWRIGHT_MCP_PROFILE_DIR_NAME": "Profile 3", + "PLAYWRIGHT_MCP_EXTENSION_TOKEN_FILE": "C:/private/extension-token" + } + })) + .unwrap(); + let (servers, _) = merge_mcp_servers( + HashMap::new(), + HashMap::from([("playwright-extension".to_string(), partial)]), + ); + let spec = &servers["playwright-extension"]; + assert_eq!(spec.session_scope, McpSessionScope::PerChat); + assert_eq!(spec.exposure(), McpToolExposure::Direct); + assert_eq!( + spec.env + .get("PLAYWRIGHT_MCP_PROFILE_DIR_NAME") + .map(String::as_str), + Some("Profile 3") + ); + assert!(spec.env.contains_key("PLAYWRIGHT_MCP_EXTENSION_TOKEN_FILE")); + } + + #[test] + fn explicit_scope_overlay_preserves_or_overrides_imported_scope() { + let mut imported = imported_server(); + imported.session_scope = McpSessionScope::PerChat; + let untouched = PartialMcpServerSpec { + disabled: Some(false), + ..Default::default() + }; + let (servers, _) = merge_mcp_servers( + HashMap::from([("demo".to_string(), imported.clone())]), + HashMap::from([("demo".to_string(), untouched)]), + ); + assert_eq!(servers["demo"].session_scope, McpSessionScope::PerChat); + + let explicit: PartialMcpServerSpec = + serde_json::from_value(serde_json::json!({"sessionScope": "global"})).unwrap(); + let (servers, _) = merge_mcp_servers( + HashMap::from([("demo".to_string(), imported)]), + HashMap::from([("demo".to_string(), explicit)]), + ); + assert_eq!(servers["demo"].session_scope, McpSessionScope::Global); + assert!( + serde_json::from_value::( + serde_json::json!({"sessionScope": "shared"}) + ) + .is_err() + ); + } + #[test] fn local_entry_can_add_gateway_mode_without_repeating_launch_config() { let imported = HashMap::from([("demo".to_string(), imported_server())]); diff --git a/src/global_settings_ui.js b/src/global_settings_ui.js index 77db0df6..4722a10a 100644 --- a/src/global_settings_ui.js +++ b/src/global_settings_ui.js @@ -556,7 +556,7 @@ body.system-progress-visible{height:100dvh;display:flex;flex-direction:column}bo else if(refresh?.phase==='failed')message(refresh.source==='manual'||refresh.source==='settings' ?refresh.result?.error||'Connector refresh failed. Use Refresh connector to retry.' :'Codexify updated, but connector refresh failed. Use Refresh connector to retry.',true); - else if(refresh?.phase==='completed')message('Connector refresh completed; Allow all tools is selected.'); + else if(refresh?.phase==='completed')message('Connector refresh completed. Check readiness for schema verification; permissions were not changed.'); } function renderPlan(plan) { const label=plan?.label?.trim()||'',node=byId('account-plan'); diff --git a/src/lib.rs b/src/lib.rs index 0654d468..465a4fd0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -44,6 +44,7 @@ pub mod openai_tunnel; pub mod output_budget; pub mod owner_chat; pub(crate) mod persist; +mod playwright_sessions; pub mod process_env; pub mod project_bindings; pub mod project_catalog; diff --git a/src/markdown_chat/mod.rs b/src/markdown_chat/mod.rs index 5e11b839..eba4843b 100644 --- a/src/markdown_chat/mod.rs +++ b/src/markdown_chat/mod.rs @@ -178,6 +178,10 @@ pub struct AgentAutomationConfig { #[serde(skip_serializing_if = "Option::is_none")] pub browser_simplicity: Option, pub recovery_enhancements: bool, + /// Shared provider Send lock for the browser companion. This file may + /// be created on first use, so only the path itself is validated here. + #[serde(skip_serializing_if = "Option::is_none")] + pub provider_send_gate_path: Option, } impl Default for AgentAutomationConfig { @@ -204,6 +208,7 @@ impl Default for AgentAutomationConfig { minimal_ui: false, browser_simplicity: None, recovery_enhancements: false, + provider_send_gate_path: None, } } } @@ -227,6 +232,18 @@ impl AgentAutomationConfig { fn validate(&self) -> Result<(), String> { self.retry_timings.validate()?; + if let Some(path) = self.provider_send_gate_path.as_deref() { + if path.is_empty() + || path.len() > 4096 + || path.contains('\0') + || !std::path::Path::new(path).is_absolute() + { + return Err( + "agentChat.automation.providerSendGatePath must be an absolute path up to 4096 bytes" + .into(), + ); + } + } if !(1..=4).contains(&self.browser_action_lanes) { return Err("agentChat.automation.browserActionLanes must be between 1 and 4".into()); } @@ -773,6 +790,55 @@ pub(crate) async fn history_call( #[cfg(test)] mod tests { use super::*; + + #[test] + fn provider_send_gate_path_preserves_live_config_without_requiring_a_lockfile() { + let target = std::env::temp_dir().join("codexify-provider-send-gate-uncreated.lock"); + let path = target.to_string_lossy().into_owned(); + let config: AgentAutomationConfig = + serde_json::from_value(serde_json::json!({"providerSendGatePath": path})).unwrap(); + config.validate().unwrap(); + assert_eq!( + config.provider_send_gate_path.as_deref(), + Some(path.as_str()) + ); + let encoded = serde_json::to_value(&config).unwrap(); + assert_eq!(encoded["providerSendGatePath"], path.as_str()); + let restored: AgentAutomationConfig = serde_json::from_value(encoded).unwrap(); + restored.validate().unwrap(); + assert_eq!(restored.provider_send_gate_path, Some(path)); + + let default = AgentAutomationConfig::default(); + assert!(default.provider_send_gate_path.is_none()); + let omitted = serde_json::to_value(default).unwrap(); + assert!(omitted.get("providerSendGatePath").is_none()); + } + + #[test] + fn provider_send_gate_rejects_relative_nul_and_overlong_paths() { + for value in ["", "./send-gate.lock", "relative.lock", "bad\0path"] { + let config: AgentAutomationConfig = + serde_json::from_value(serde_json::json!({"providerSendGatePath": value})).unwrap(); + assert!(config.validate().is_err(), "{value:?} must be rejected"); + } + let overlong = std::env::temp_dir().join("x".repeat(4096)); + let config: AgentAutomationConfig = serde_json::from_value( + serde_json::json!({"providerSendGatePath": overlong.to_string_lossy()}), + ) + .unwrap(); + assert!(config.validate().is_err()); + } + + #[test] + fn provider_send_gate_does_not_weaken_other_schema_validation() { + assert!( + serde_json::from_value::( + serde_json::json!({"unknownSendGateProperty": "unsafe"}) + ) + .is_err() + ); + } + #[test] fn browser_simplicity_levels_preserve_legacy_choices_and_validate_values() { for (value, expected) in [ diff --git a/src/mcp_catalog.rs b/src/mcp_catalog.rs index 2144716f..01ddf9a6 100644 --- a/src/mcp_catalog.rs +++ b/src/mcp_catalog.rs @@ -15,6 +15,7 @@ use tokio_util::sync::CancellationToken; use crate::bridge::{UpstreamCallContext, forward_tool_call}; use crate::bridged_resources::BridgedResourceStore; use crate::exec_sessions::SessionState; +use crate::project_bindings::ConversationIdentity; use crate::tool::{Tool, ToolBehavior, ToolCallIdentity, ToolRequestContext}; use crate::types::{AppConfig, McpServerProvenance, ToolResult}; @@ -40,6 +41,7 @@ pub(crate) struct CatalogSourceInput { pub peer: Peer, pub tool_timeout: Option, pub control: Arc, + pub generation: Arc, } struct CatalogTool { @@ -59,6 +61,7 @@ struct CatalogSource { peer: Peer, tool_timeout: Option, control: Arc, + generation: Arc, } struct SearchDocument { @@ -128,6 +131,7 @@ impl Catalog { peer: input.peer, tool_timeout: input.tool_timeout, control: input.control, + generation: input.generation, }); } @@ -1014,7 +1018,12 @@ struct McpCallToolTool { } impl McpCallToolTool { - async fn run(&self, args: Value, cancellation: Option<&CancellationToken>) -> ToolResult { + async fn run( + &self, + args: Value, + cancellation: Option<&CancellationToken>, + conversation: Option<&ConversationIdentity>, + ) -> ToolResult { let source_id = match required_string(&args, "source") { Ok(source) => source, Err(error) => return ToolResult::error(error), @@ -1032,6 +1041,7 @@ impl McpCallToolTool { Err(error) => return ToolResult::error(error), }; + let _lease = source.generation.begin_call(); let mut params = CallToolRequestParams::new(tool.raw.name.to_string()); match args.get("arguments") { None | Some(Value::Null) => {} @@ -1057,6 +1067,7 @@ impl McpCallToolTool { UpstreamCallContext { resources: &self.resources, control: &source.control, + conversation, }, ) .await @@ -1134,7 +1145,7 @@ impl Tool for McpCallToolTool { } async fn call(&self, args: Value, _config: &AppConfig, _session: &SessionState) -> ToolResult { - self.run(args, None).await + self.run(args, None, None).await } async fn call_with_context( @@ -1144,7 +1155,15 @@ impl Tool for McpCallToolTool { _session: &SessionState, context: &ToolRequestContext, ) -> ToolResult { - self.run(args, Some(&context.cancellation)).await + self.run( + args, + Some(&context.cancellation), + context + .task_conversation + .as_ref() + .or(context.conversation.as_ref()), + ) + .await } } diff --git a/src/owner_chat.rs b/src/owner_chat.rs index 9d4268f3..1bd8fa8a 100644 --- a/src/owner_chat.rs +++ b/src/owner_chat.rs @@ -1990,16 +1990,63 @@ async fn chat_send( crate::markdown_chat::now_ms(), ) .map_err(internal_error)?; - if receipt.updated_active_goal { + // A blocked goal can leave its agent in chat_await. Activating a new + // goal must deliver that changed intent to the waiting agent; merely + // notifying the offline supervisor cannot interrupt an input wait. + let wake_input_wait = if !receipt.updated_active_goal + && matches!( + receipt.kind, + crate::agent_automation::OwnerGoalCommandKind::Set + | crate::agent_automation::OwnerGoalCommandKind::Run + ) + && let Some(goal) = receipt + .goal + .as_ref() + .filter(|goal| goal.status == crate::agent_automation::GoalStatus::Active) + { + // An idempotent retry may repair a lost notice, but an old + // request must never wake a later, different goal revision. + let current = context.store.load(&context.task).map_err(internal_error)?; + current.goal.as_ref().is_some_and(|saved| { + saved.revision == goal.revision + && saved.status == crate::agent_automation::GoalStatus::Active + }) && (context + .chat + .queue_input_required() + .await + .map_err(internal_error)? + || context + .chat + .offline_activity() + .await + .map_err(internal_error)? + .agent_waiting_until_ms + .is_some_and(|until| until > crate::markdown_chat::now_ms())) + } else { + false + }; + if receipt.updated_active_goal || wake_input_wait { let goal = receipt.goal.as_ref().expect("updated active goal receipt"); let notification_id = format!( "goal-update-{:x}", Sha256::digest(body.request_id.as_bytes()) ); - context.chat.append_user(notification_id, format!( - "The goal has changed (revision {}). The new goal is:\n\n{}\n\nCall `goal_read` for the current revision and continue toward the updated goal.", - goal.revision, goal.markdown, - )).await.map_err(internal_error)?; + let notice = if receipt.updated_active_goal { + format!( + "The goal has changed (revision {}). The new goal is:\n\n{}\n\nCall `goal_read` for the current revision and continue toward the updated goal.", + goal.revision, goal.markdown, + ) + } else { + format!( + "The owner activated goal revision {} while this chat was waiting for input. The new active goal is:\n\n{}\n\nCall `goal_read` and continue the new goal; do not remain in the previous blocked goal's input wait.", + goal.revision, goal.markdown, + ) + }; + context + .chat + .append_user(notification_id, notice) + .await + .map_err(internal_error)?; } if !receipt.replayed && matches!( @@ -3991,6 +4038,8 @@ mod tests { config.markdown_chat.automation.enabled = true; config.markdown_chat.automation.connector_name = "Codexify".into(); config.memory.dir = Some(temp.path().join("state").display().to_string()); + let goal_store = + crate::agent_automation::AgentAutomationStore::for_config(&config).unwrap(); let identity = ConversationIdentity::from_openai_session("owner-goal-api").unwrap(); let chats = Arc::new(MarkdownChatStore::default()); let chat = chats @@ -4361,6 +4410,94 @@ mod tests { .unwrap(); assert!(listed["chats"][0]["goalStatus"].is_null()); assert!(listed["chats"][0]["goal"].is_null()); + + // A blocked goal's chat_await must not keep a newly activated goal + // waiting forever. The notification is a local owner wake, not a + // browser Send or a fabricated turn-renewal receipt. + let blocked: Value = client + .post(format!("{base}/api/chats/{id}/send")) + .bearer_auth("test-token") + .json(&json!({ + "request_id": "goal-before-input-wait", + "message": "/goal set Old goal awaiting owner input" + })) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + let blocked_revision = blocked["_meta"][CHAT_WIDGET_META]["goal"]["revision"] + .as_u64() + .unwrap(); + goal_store + .finish_goal( + &identity, + blocked_revision, + crate::agent_automation::GoalFinish::Blocked { + reason: "Owner input required".into(), + }, + crate::markdown_chat::now_ms(), + ) + .unwrap(); + // Drain earlier fixture messages so the new waiter really blocks. + let _ = chat.read(true).await.unwrap(); + assert!( + !chat.queue_input_required().await.unwrap(), + "the old input wait should be observable through runtime state alone" + ); + let waiter = chat.clone(); + let waiting = tokio::spawn(async move { + waiter + .wait( + std::time::Duration::from_secs(5), + tokio_util::sync::CancellationToken::new(), + ) + .await + .unwrap() + }); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + assert!( + chat.offline_activity() + .await + .unwrap() + .agent_waiting_until_ms + .is_some(), + "the old chat_await must be active before a new goal is set" + ); + let activate = || { + client + .post(format!("{base}/api/chats/{id}/send")) + .bearer_auth("test-token") + .json(&json!({ + "request_id": "replace-blocked-input-goal", + "message": "/goal set Continue autonomous work after blocked input wait" + })) + .send() + }; + let replacement: Value = activate().await.unwrap().json().await.unwrap(); + assert_eq!( + replacement["_meta"][CHAT_WIDGET_META]["goal"]["revision"], + blocked_revision + 1 + ); + assert_eq!( + replacement["_meta"][CHAT_WIDGET_META]["goal"]["status"], + "active" + ); + let wake = tokio::time::timeout(std::time::Duration::from_secs(7), waiting) + .await + .unwrap() + .unwrap(); + let crate::markdown_chat::WaitOutcome::Message(delivered) = wake else { + panic!("new active goal did not wake the old blocked input wait"); + }; + assert!(delivered.text.contains("The owner activated goal revision")); + assert!(delivered.text.contains("Continue autonomous work")); + chat.queue_reply_received().await.unwrap(); + assert!(!chat.queue_input_required().await.unwrap()); + let replay: Value = activate().await.unwrap().json().await.unwrap(); + assert_eq!(replay["_meta"][CHAT_WIDGET_META]["replayed"], true); + assert!(chat.unread_snapshot().await.unwrap().messages.is_empty()); task.abort(); } diff --git a/src/owner_chat/settings.rs b/src/owner_chat/settings.rs index 6d2217d6..c401dc1c 100644 --- a/src/owner_chat/settings.rs +++ b/src/owner_chat/settings.rs @@ -201,7 +201,9 @@ pub(super) fn start(state: OwnerState) { pub(super) async fn health(State(state): State) -> ApiResult { let schema = crate::global_settings::read_schema_intent(&state.config); - let (mut body, readiness) = super::readiness::snapshot(&state, schema.as_ref()).await; + let manual = state.global.lock().await.manual_refresh.clone(); + let refresh = visible_connector_refresh(schema, manual, None, None); + let (mut body, readiness) = super::readiness::snapshot(&state, refresh.as_ref()).await; body["readiness"] = readiness; if let Some(automation) = &state.automation { body["automationActivity"] = @@ -223,6 +225,36 @@ fn update_progress(current: Option<&Value>, intent: Option<&Value>) -> Option, + manual: Option, + recent: Option, + after_update: Option, +) -> Option { + let in_progress = |value: &Value| { + matches!( + value["phase"].as_str(), + Some("queued" | "running" | "starting_browser" | "waiting_for_restart") + ) + }; + if let Some(value) = manual.as_ref().filter(|value| in_progress(value)) { + return Some(value.clone()); + } + if let Some(value) = schema.as_ref().filter(|value| in_progress(value)) { + return Some(value.clone()); + } + if let Some(value) = manual.as_ref().filter(|value| value["phase"] == "failed") { + return Some(value.clone()); + } + if let Some(value) = schema.as_ref().filter(|value| value["phase"] == "failed") { + return Some(value.clone()); + } + manual.or(recent).or(after_update).or(schema) +} + pub(super) async fn status(State(state): State) -> ApiResult { let latest = crate::self_update::inspect_latest_version().await; let latest = match latest { @@ -235,23 +267,12 @@ pub(super) async fn status(State(state): State) -> ApiResult { let global = state.global.lock().await; let update_intent = crate::global_settings::read_refresh_intent(); let update = update_progress(global.update.as_ref(), update_intent.as_ref()); - let refresh = schema - .as_ref() - .filter(|value| { - matches!( - value["phase"].as_str(), - Some("queued" | "running" | "starting_browser" | "waiting_for_restart" | "failed") - ) - }) - .cloned() - .or_else(|| { - global - .manual_refresh - .clone() - .or_else(|| global.refresh.clone()) - .or_else(crate::global_settings::read_refresh_intent) - }) - .or(schema); + let refresh = visible_connector_refresh( + schema, + global.manual_refresh.clone(), + global.refresh.clone(), + crate::global_settings::read_refresh_intent(), + ); let plan = global.plan.clone(); drop(global); let (_, readiness) = super::readiness::snapshot(&state, refresh.as_ref()).await; @@ -500,16 +521,41 @@ async fn set_manual_refresh_phase( } } +fn check_manual_refresh_readiness( + health: &crate::agent_automation::CompanionHealth, +) -> Result<(), String> { + use crate::agent_automation::CompanionSessionStatus; + match health.status { + CompanionSessionStatus::Busy => Err("Browser companion is busy".into()), + CompanionSessionStatus::Unavailable => { + Err("Browser companion is unavailable; check Browser settings".into()) + } + CompanionSessionStatus::AuthenticationRequired => { + Err("ChatGPT sign-in is required in the browser companion".into()) + } + CompanionSessionStatus::Idle if !health.authenticated => { + Err("ChatGPT sign-in could not be verified in the browser companion".into()) + } + CompanionSessionStatus::Idle + if health.active_action_id.is_some() + || !health.active_action_ids.is_empty() + || health.free_action_slots() == 0 => + { + Err("Browser companion is busy".into()) + } + CompanionSessionStatus::Idle => Ok(()), + } +} + async fn run_manual_refresh(state: OwnerState, id: String, retry_after: Duration) { loop { let result = async { let client = super::schema_refresh::refresh_client(&state.config).await?; - let health = client.health(&CancellationToken::new()).await?; - if health.active_action_id.is_some() - || health.status == crate::agent_automation::CompanionSessionStatus::Busy - { - return Err("Browser companion is busy".to_string()); - } + // Passive health is deliberately short-budgeted and may say `busy` + // while Chrome is warming. The refresh scheduler needs the fresh + // idle/account observation before deciding to requeue this job. + let health = client.ready_health(&CancellationToken::new()).await?; + check_manual_refresh_readiness(&health)?; set_manual_refresh_phase(&state, &id, "running", None).await; refresh_saved_connector(&state, &client).await } @@ -560,6 +606,82 @@ mod tests { ); assert_eq!(update_progress(None, None), None); } + #[test] + fn manual_connector_retry_is_not_masked_by_old_schema_failure() { + let schema = json!({"phase":"failed","refreshId":"settings-old", + "result":{"error":"Old browser state changed"}}); + let manual = json!({"phase":"queued","refreshId":"manual-new","source":"manual"}); + assert_eq!( + visible_connector_refresh(Some(schema.clone()), Some(manual.clone()), None, None), + Some(manual.clone()), + ); + let running = json!({"phase":"running","refreshId":"manual-new","source":"manual"}); + assert_eq!( + visible_connector_refresh(Some(schema.clone()), Some(running.clone()), None, None), + Some(running), + ); + let new_failure = json!({"phase":"failed","refreshId":"manual-new","source":"manual", + "result":{"error":"Current refresh failed"}}); + assert_eq!( + visible_connector_refresh(Some(schema), Some(new_failure.clone()), None, None), + Some(new_failure), + ); + } + + #[test] + fn manual_completion_does_not_hide_an_unresolved_schema_barrier() { + let schema = json!({"phase":"failed","refreshId":"settings-old"}); + let manual = json!({"phase":"completed","refreshId":"manual-new", + "result":{"refreshObserved":true,"schemaVerified":false}}); + assert_eq!( + visible_connector_refresh(Some(schema.clone()), Some(manual), None, None), + Some(schema), + ); + } + #[test] + fn manual_refresh_requires_a_fresh_authenticated_free_browser_lane() { + let fixture = |status: &str, authenticated: bool, slots: usize, active: Vec<&str>| { + serde_json::from_value::(json!({ + "protocolVersion":1,"kind":"codexify-browser-companion", + "build":"test","status":status,"authenticated":authenticated, + "accountFingerprint":if authenticated {Some("account")} else {None}, + "activeActionId":null,"activeActionIds":active, + "availableActionSlots":slots,"actionCapacity":1, + })) + .unwrap() + }; + assert!(check_manual_refresh_readiness(&fixture("idle", true, 1, vec![])).is_ok()); + assert!( + check_manual_refresh_readiness(&fixture("busy", true, 0, vec![])) + .unwrap_err() + .contains("busy") + ); + assert!( + check_manual_refresh_readiness(&fixture("idle", true, 0, vec![])) + .unwrap_err() + .contains("busy") + ); + assert!( + check_manual_refresh_readiness(&fixture("idle", true, 1, vec!["owned"])) + .unwrap_err() + .contains("busy") + ); + assert!( + check_manual_refresh_readiness(&fixture("idle", false, 1, vec![])) + .unwrap_err() + .contains("sign-in") + ); + assert!( + check_manual_refresh_readiness(&fixture("authentication_required", false, 0, vec![])) + .unwrap_err() + .contains("sign-in") + ); + assert!( + check_manual_refresh_readiness(&fixture("unavailable", false, 0, vec![])) + .unwrap_err() + .contains("unavailable") + ); + } #[derive(Clone, Default)] struct RefreshFixture { mode: Arc, @@ -568,14 +690,19 @@ mod tests { successes: Arc, release: Arc, } - async fn refresh_health(State(fixture): State) -> Json { + async fn refresh_health( + State(fixture): State, + uri: axum::http::Uri, + ) -> Json { use std::sync::atomic::Ordering; fixture.health_calls.fetch_add(1, Ordering::SeqCst); + let mode = fixture.mode.load(Ordering::SeqCst); + let ready = uri.query().is_some_and(|query| query == "ready=1"); Json( json!({"protocolVersion":1,"kind":"codexify-browser-companion", "build":format!("{}{}",env!("CARGO_PKG_VERSION"),crate::agent_automation::PROTOCOL_BUILD_SUFFIX), "authenticated":true,"accountFingerprint":"fixture-account","activeActionId":null, - "status":if fixture.mode.load(Ordering::SeqCst)==0 {"busy"} else {"idle"}}), + "status":if mode==0 || (mode==5 && !ready) {"busy"} else {"idle"}}), ) } async fn fixture_refresh( @@ -776,6 +903,32 @@ mod tests { companion.abort(); } #[tokio::test] + async fn manual_refresh_does_not_starve_on_a_warming_passive_health_result() { + use std::sync::atomic::Ordering; + let root = tempfile::tempdir().unwrap(); + let (state, fixture, base, owner, companion) = refresh_fixture(root.path()).await; + // Chrome can be idle and authenticated while the passive health probe + // returns `busy` because its short observation budget expired. + fixture.mode.store(5, Ordering::SeqCst); + let receipt: Value = reqwest::Client::new() + .post(format!("{base}/api/settings/refresh-connector")) + .bearer_auth("owner-test-token") + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(receipt["phase"], "queued"); + let done = wait_refresh_phase(&state, "completed").await; + assert_eq!(done["refreshId"], receipt["refreshId"]); + assert_eq!(done["result"]["refreshObserved"], true); + assert_eq!(fixture.calls.load(Ordering::SeqCst), 1); + assert!(fixture.health_calls.load(Ordering::SeqCst) >= 1); + owner.abort(); + companion.abort(); + } + #[tokio::test] async fn manual_refresh_reports_real_failure_and_allows_a_new_retry() { use std::sync::atomic::Ordering; let root = tempfile::tempdir().unwrap(); diff --git a/src/playwright_sessions.rs b/src/playwright_sessions.rs new file mode 100644 index 00000000..e1a69785 --- /dev/null +++ b/src/playwright_sessions.rs @@ -0,0 +1,528 @@ +//! Per-ChatGPT-task Playwright MCP stdio connections. +//! A single upstream Playwright peer has mutable current-tab state. Never share +//! that peer across physical conversations or durable task continuations. +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use rmcp::RoleClient; +use rmcp::service::{Peer, RunningService}; +use tokio::sync::{Mutex as AsyncMutex, OnceCell, Semaphore}; + +use crate::bridge::connect_one; +use crate::project_bindings::ConversationIdentity; +use crate::types::{AppConfig, McpServerSpec, McpSessionScope}; +use crate::upstream_control::UpstreamControl; + +const MAX_LIVE_SESSIONS: usize = 16; +const MAX_PARALLEL_BROWSER_STARTS: usize = 3; +const IDLE_SESSION_TTL: Duration = Duration::from_secs(60 * 60); + +pub(crate) struct ScopedConnection { + // Hold the upstream process and transport alive for this conversation. + _service: RunningService, + pub(crate) peer: Peer, + pub(crate) control: Arc, +} + +struct SessionSlot { + connection: OnceCell>, + last_used: Mutex, +} + +impl SessionSlot { + fn new() -> Self { + Self { + connection: OnceCell::new(), + last_used: Mutex::new(Instant::now()), + } + } + + fn touch(&self) { + *self.last_used.lock().unwrap_or_else(|e| e.into_inner()) = Instant::now(); + } + + fn expired(&self) -> bool { + self.last_used + .lock() + .unwrap_or_else(|e| e.into_inner()) + .elapsed() + >= IDLE_SESSION_TTL + } +} + +pub(crate) struct ScopedPlaywrightPool { + server: String, + instance_port: u16, + config: AppConfig, + spec: McpServerSpec, + extension: bool, + profiles_root: PathBuf, + sessions: AsyncMutex>>, + startup_capacity: Semaphore, +} + +impl ScopedPlaywrightPool { + pub(crate) fn new( + server: &str, + spec: &McpServerSpec, + config: &AppConfig, + ) -> Result { + if spec.session_scope != McpSessionScope::PerChat { + return Err("per-chat Playwright requires sessionScope=per-chat".into()); + } + if spec.command.is_none() || spec.url.is_some() { + return Err("per-chat Playwright requires a local stdio MCP server".into()); + } + let playwright = server.to_ascii_lowercase().contains("playwright") + || spec + .args + .iter() + .any(|arg| arg.to_ascii_lowercase().contains("playwright")); + if !playwright { + return Err("sessionScope=per-chat is only supported for Playwright MCP".into()); + } + let extension = is_extension(server, spec); + for forbidden in [ + "--user-data-dir", + "--shared-browser-context", + "--cdp-endpoint", + "--endpoint", + "--storage-state", + "--isolated", + "--no-tab-group", + "--session-name", + "--profile-dir-name", + "--config", + ] { + if spec + .args + .iter() + .any(|arg| arg == forbidden || arg.starts_with(&format!("{forbidden}="))) + { + return Err(format!( + "per-chat Playwright must own its session lifecycle; remove {forbidden}" + )); + } + } + if spec + .env + .get("PLAYWRIGHT_MCP_NO_TAB_GROUP") + .is_some_and(|v| v == "1") + { + return Err("per-chat extension mode requires tab groups for ownership".into()); + } + if extension { + let profile = spec.env.get("PLAYWRIGHT_MCP_PROFILE_DIR_NAME"); + if profile.is_none_or(|name| name.is_empty() || name == "Default") { + return Err("per-chat extension mode requires an explicitly dedicated non-default Chrome profile (PLAYWRIGHT_MCP_PROFILE_DIR_NAME)".into()); + } + let configured_token = spec + .env + .get("PLAYWRIGHT_MCP_EXTENSION_TOKEN") + .is_some_and(|v| !v.trim().is_empty()); + let configured_file = spec + .env + .get("PLAYWRIGHT_MCP_EXTENSION_TOKEN_FILE") + .is_some_and(|v| !v.trim().is_empty()); + // Consent must be explicit in this dedicated MCP source, never an + // ambient token inherited from the interactive user session. + if !configured_token && !configured_file { + return Err("per-chat Playwright extension needs PLAYWRIGHT_MCP_EXTENSION_TOKEN or PLAYWRIGHT_MCP_EXTENSION_TOKEN_FILE for a dedicated browser profile; refusing manual approval prompts".into()); + } + if configured_token && configured_file { + return Err("configure only one Playwright extension token source".into()); + } + } + let root = std::env::var_os("USERPROFILE") + .or_else(|| std::env::var_os("HOME")) + .map(PathBuf::from) + .unwrap_or_else(|| config.work_dir.clone()) + .join(".codexify") + .join("playwright-agent-profiles"); + Ok(Self { + server: server.to_string(), + instance_port: config.port, + config: config.clone(), + spec: spec.clone(), + extension, + profiles_root: root, + sessions: AsyncMutex::new(HashMap::new()), + startup_capacity: Semaphore::new(MAX_PARALLEL_BROWSER_STARTS), + }) + } + + fn scoped_spec(&self, owner: &ConversationIdentity) -> Result { + let key = owner.stable_key(); + if key.len() != 64 || !key.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err("invalid per-chat browser owner identity".into()); + } + let mut spec = self.spec.clone(); + // Managed Chromium can take longer than the generic 20-second MCP + // default to cold-start under desktop load. Keep explicit overrides. + if !self.extension && spec.startup_timeout_sec.is_none() { + spec.startup_timeout_sec = Some(60.0); + } + if self.extension { + load_extension_token(&mut spec)?; + spec.env.insert( + "PLAYWRIGHT_MCP_SESSION_NAME".into(), + format!("Codexify-{}-{}", self.instance_port, &key[..12]), + ); + // The extension owns each client's tab group and token-based + // connections start on a new blank tab (never an existing tab). + spec.env + .insert("PLAYWRIGHT_MCP_NO_TAB_GROUP".into(), "0".into()); + spec.env + .insert("PLAYWRIGHT_MCP_BACKGROUND".into(), "1".into()); + } else { + let safe_server: String = self + .server + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '-' { + c + } else { + '_' + } + }) + .collect(); + let profile = self + .profiles_root + .join(safe_server) + .join(self.instance_port.to_string()) + .join(key); + std::fs::create_dir_all(&profile) + .map_err(|e| format!("could not prepare per-chat browser profile: {e}"))?; + spec.args + .push(format!("--user-data-dir={}", profile.display())); + } + Ok(spec) + } + + /// An isolated catalog-discovery connection is only used to fetch schemas. + /// It must not attach to any real task or browser session. + pub(crate) fn discovery_spec(&self) -> Result { + let identity = ConversationIdentity::from_openai_session( + "codexify-playwright-catalog-discovery-not-a-user", + ) + .ok_or("could not create discovery owner")?; + self.scoped_spec(&identity) + } + + pub(crate) async fn acquire( + &self, + owner: Option<&ConversationIdentity>, + ) -> Result, String> { + let owner = owner.ok_or( + "per-chat Playwright needs a verified ChatGPT conversation/task identity; \ + refusing the shared global browser", + )?; + let key = owner.stable_key().to_owned(); + let slot = { + let mut sessions = self.sessions.lock().await; + // Never reclaim an in-use connection. This cap prevents unattended + // chats from spawning arbitrarily many Chromium processes. + sessions.retain(|_, entry| { + !entry.expired() + || Arc::strong_count(entry) > 1 + // A request may hold the connection but not its slot. + // Do not evict and respawn while that browser is in use. + || entry + .connection + .get() + .is_some_and(|connection| Arc::strong_count(connection) > 1) + }); + let slot = if let Some(entry) = sessions.get(&key) { + entry.clone() + } else { + if sessions.len() >= MAX_LIVE_SESSIONS { + return Err( + "per-chat Playwright capacity reached; wait for an idle session to \ + expire rather than sharing another agent's browser" + .into(), + ); + } + let entry = Arc::new(SessionSlot::new()); + sessions.insert(key, entry.clone()); + entry + }; + slot.touch(); + slot + }; + let connection = slot + .connection + .get_or_try_init(|| async { + let _start = self + .startup_capacity + .acquire() + .await + .map_err(|_| "per-chat browser startup limiter closed")?; + let scoped = self.scoped_spec(owner)?; + let (service, _tools, _timeout) = + connect_one(&self.server, &scoped, &self.config).await?; + let peer = service.peer().clone(); + let control = Arc::new( + UpstreamControl::new(scoped.request_limits.clone()) + .for_server(&self.server, &scoped), + ); + Ok::<_, String>(Arc::new(ScopedConnection { + _service: service, + peer, + control, + })) + }) + .await?; + Ok(connection.clone()) + } +} + +// Never log, store in the upstream catalog, or place in MCP metadata. +// The file is provisioned once with a user-only ACL by the optional setup +// script. Reading it at connection time also supports safe token rotation. +fn load_extension_token(spec: &mut McpServerSpec) -> Result<(), String> { + let token_file = spec.env.remove("PLAYWRIGHT_MCP_EXTENSION_TOKEN_FILE"); + if let Some(filename) = token_file { + if spec.env.contains_key("PLAYWRIGHT_MCP_EXTENSION_TOKEN") { + return Err("multiple Playwright extension token sources".into()); + } + let path = PathBuf::from(filename); + if !path.is_absolute() { + return Err("Playwright extension token file must be an absolute path".into()); + } + let metadata = std::fs::symlink_metadata(&path) + .map_err(|_| "Playwright extension token file could not be opened")?; + if !metadata.is_file() || metadata.file_type().is_symlink() || metadata.len() > 1024 { + return Err("Playwright extension token file must be a regular, small file".into()); + } + let source = std::fs::read_to_string(&path) + .map_err(|_| "Playwright extension token file could not be read")?; + let token = source.trim_end_matches(['\r', '\n']); + if !(16..=512).contains(&token.len()) + || !token + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') + { + return Err("Playwright extension token file has an invalid token format".into()); + } + spec.env + .insert("PLAYWRIGHT_MCP_EXTENSION_TOKEN".into(), token.into()); + } + Ok(()) +} + +fn is_extension(server: &str, spec: &McpServerSpec) -> bool { + server.to_ascii_lowercase().contains("extension") + || spec + .args + .iter() + .any(|arg| arg == "--extension" || arg == "--extension=true") + || spec + .env + .get("PLAYWRIGHT_MCP_EXTENSION") + .is_some_and(|value| value == "1" || value.eq_ignore_ascii_case("true")) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::types::McpSessionScope; + + fn stub_config() -> AppConfig { + crate::config::default_config(std::env::temp_dir()) + } + + fn spec(extension: bool) -> McpServerSpec { + let mut spec = McpServerSpec { + command: Some("node".into()), + args: vec!["@playwright/mcp".into()], + session_scope: McpSessionScope::PerChat, + ..Default::default() + }; + if extension { + spec.args.push("--extension".into()); + spec.env + .insert("PLAYWRIGHT_MCP_PROFILE_DIR_NAME".into(), "Codexify".into()); + spec.env.insert( + "PLAYWRIGHT_MCP_EXTENSION_TOKEN".into(), + "test-token-not-a-real-secret".into(), + ); + } + spec + } + + #[test] + fn managed_playwright_cold_start_is_bounded_but_respects_owner_override() { + let initial = spec(false); + let pool = ScopedPlaywrightPool::new("playwright", &initial, &stub_config()).unwrap(); + let discovery = pool.discovery_spec().unwrap(); + assert_eq!(discovery.startup_timeout_sec, Some(60.0)); + let owner = ConversationIdentity::from_openai_session("agent-a").unwrap(); + assert_eq!( + pool.scoped_spec(&owner).unwrap().startup_timeout_sec, + Some(60.0) + ); + let mut overridden = spec(false); + overridden.startup_timeout_sec = Some(95.0); + let pool = ScopedPlaywrightPool::new("playwright", &overridden, &stub_config()).unwrap(); + assert_eq!( + pool.discovery_spec().unwrap().startup_timeout_sec, + Some(95.0) + ); + } + + #[test] + fn distinct_conversations_receive_distinct_persistent_profiles() { + let pool = ScopedPlaywrightPool::new("playwright", &spec(false), &stub_config()).unwrap(); + let a = ConversationIdentity::from_openai_session("account-A-chat-A").unwrap(); + let b = ConversationIdentity::from_openai_session("account-A-chat-B").unwrap(); + let aa = pool.scoped_spec(&a).unwrap(); + let bb = pool.scoped_spec(&b).unwrap(); + assert_ne!(aa.args, bb.args); + assert_eq!(aa.args, pool.scoped_spec(&a).unwrap().args); + assert!( + aa.args + .iter() + .any(|arg| arg.starts_with("--user-data-dir=")) + ); + } + + #[test] + fn extension_is_grouped_per_client_without_overwriting_the_token() { + let config = stub_config(); + let pool = ScopedPlaywrightPool::new("playwright-extension", &spec(true), &config).unwrap(); + let a = ConversationIdentity::from_openai_session("chat-A").unwrap(); + let b = ConversationIdentity::from_openai_session("chat-B").unwrap(); + let aa = pool.scoped_spec(&a).unwrap(); + let bb = pool.scoped_spec(&b).unwrap(); + assert_ne!( + aa.env.get("PLAYWRIGHT_MCP_SESSION_NAME"), + bb.env.get("PLAYWRIGHT_MCP_SESSION_NAME") + ); + assert_eq!( + aa.env.get("PLAYWRIGHT_MCP_EXTENSION_TOKEN"), + bb.env.get("PLAYWRIGHT_MCP_EXTENSION_TOKEN") + ); + assert_eq!(aa.env.get("PLAYWRIGHT_MCP_BACKGROUND"), Some(&"1".into())); + assert!(!aa.args.iter().any(|a| a.starts_with("--user-data-dir="))); + } + + #[tokio::test] + async fn missing_owner_is_rejected_before_launching_any_browser() { + let pool = ScopedPlaywrightPool::new("playwright", &spec(false), &stub_config()).unwrap(); + let error = pool + .acquire(None) + .await + .err() + .expect("missing owner rejected"); + assert!(error.contains("refusing the shared global browser")); + assert_eq!(pool.sessions.lock().await.len(), 0); + } + + #[tokio::test] + async fn bounded_capacity_rejects_new_owner_without_reusing_another_session() { + let pool = ScopedPlaywrightPool::new("playwright", &spec(false), &stub_config()).unwrap(); + { + let mut sessions = pool.sessions.lock().await; + for index in 0..MAX_LIVE_SESSIONS { + sessions.insert(format!("{index:064x}"), Arc::new(SessionSlot::new())); + } + } + let new_owner = ConversationIdentity::from_openai_session("seventeenth-owner").unwrap(); + let error = pool + .acquire(Some(&new_owner)) + .await + .err() + .expect("limit enforced"); + assert!(error.contains("capacity reached")); + assert_eq!(pool.sessions.lock().await.len(), MAX_LIVE_SESSIONS); + } + + #[test] + fn extension_without_token_fails_closed_before_any_mcp_connection() { + let mut s = spec(true); + s.env.remove("PLAYWRIGHT_MCP_EXTENSION_TOKEN"); + s.env.remove("PLAYWRIGHT_MCP_EXTENSION_TOKEN_FILE"); + assert!(ScopedPlaywrightPool::new("playwright-extension", &s, &stub_config()).is_err()); + } + + #[test] + fn token_file_is_loaded_only_for_a_scoped_child_and_errors_are_secret_free() { + let mut s = spec(true); + s.env + .insert("PLAYWRIGHT_MCP_PROFILE_DIR_NAME".into(), "Codexify".into()); + s.env.remove("PLAYWRIGHT_MCP_EXTENSION_TOKEN"); + let file = std::env::temp_dir().join(format!( + "codexify-playwright-token-test-{}-{}.txt", + std::process::id(), + "f48a" + )); + assert!(!file.exists()); + std::fs::write(&file, "testtoken_with_123456789").unwrap(); + s.env.insert( + "PLAYWRIGHT_MCP_EXTENSION_TOKEN_FILE".into(), + file.display().to_string(), + ); + let pool = ScopedPlaywrightPool::new("playwright-extension", &s, &stub_config()).unwrap(); + let owner = ConversationIdentity::from_openai_session("chat-A").unwrap(); + let child = pool.scoped_spec(&owner).unwrap(); + assert_eq!( + child + .env + .get("PLAYWRIGHT_MCP_EXTENSION_TOKEN") + .map(String::as_str), + Some("testtoken_with_123456789") + ); + assert!( + !child + .env + .contains_key("PLAYWRIGHT_MCP_EXTENSION_TOKEN_FILE") + ); + assert!( + pool.spec + .env + .contains_key("PLAYWRIGHT_MCP_EXTENSION_TOKEN_FILE") + ); + std::fs::remove_file(&file).unwrap(); + let error = pool.scoped_spec(&owner).unwrap_err(); + assert!(!error.contains("testtoken_with")); + assert!(!error.contains(&file.display().to_string())); + } + + #[test] + fn per_chat_extension_must_select_a_dedicated_profile() { + let mut s = spec(true); + s.env.remove("PLAYWRIGHT_MCP_PROFILE_DIR_NAME"); + assert!(ScopedPlaywrightPool::new("playwright-extension", &s, &stub_config()).is_err()); + s.env + .insert("PLAYWRIGHT_MCP_PROFILE_DIR_NAME".into(), "Default".into()); + assert!(ScopedPlaywrightPool::new("playwright-extension", &s, &stub_config()).is_err()); + s.env + .insert("PLAYWRIGHT_MCP_PROFILE_DIR_NAME".into(), "Profile 3".into()); + assert!(ScopedPlaywrightPool::new("playwright-extension", &s, &stub_config()).is_ok()); + } + + #[test] + fn refuses_context_sharing_and_arbitrary_non_browser_sources() { + for flag in [ + "--shared-browser-context", + "--cdp-endpoint=ws://localhost:22", + ] { + let mut s = spec(false); + s.args.push(flag.into()); + assert!(ScopedPlaywrightPool::new("playwright", &s, &stub_config()).is_err()); + } + assert!( + ScopedPlaywrightPool::new( + "non-browser", + &McpServerSpec { + args: vec!["echo".into()], + ..spec(false) + }, + &stub_config() + ) + .is_err() + ); + } +} diff --git a/src/project_clone.rs b/src/project_clone.rs index c300d57b..ffb0de57 100644 --- a/src/project_clone.rs +++ b/src/project_clone.rs @@ -2390,8 +2390,16 @@ mod tests { .await .unwrap_err(); assert!(error.contains("Multiple local checkouts match"), "{error}"); - assert!(error.contains(first.to_string_lossy().as_ref()), "{error}"); - assert!(error.contains(second.to_string_lossy().as_ref()), "{error}"); + let canonical_first = fs::canonicalize(&first).unwrap(); + let canonical_second = fs::canonicalize(&second).unwrap(); + assert!( + error.contains(canonical_first.to_string_lossy().as_ref()), + "{error}" + ); + assert!( + error.contains(canonical_second.to_string_lossy().as_ref()), + "{error}" + ); } #[tokio::test] diff --git a/src/self_update.rs b/src/self_update.rs index 1bee6fec..2349dc4f 100644 --- a/src/self_update.rs +++ b/src/self_update.rs @@ -624,6 +624,33 @@ fn write_status_record_to(status_dir: &Path, record: &UpdateStatusRecord) -> any fn read_status_record_from( status_dir: &Path, update_id: &str, +) -> anyhow::Result { + // An atomic status replacement can briefly hide its target on Windows. + // Retry only missing-file or sharing-violation errors, without changing + // the durable record or hiding a persistent failure. + #[cfg(windows)] + { + for _ in 0..6 { + match read_status_record_once(status_dir, update_id) { + Ok(record) => return Ok(record), + Err(error) + if error.downcast_ref::().is_some_and(|io| { + io.kind() == std::io::ErrorKind::NotFound + || matches!(io.raw_os_error(), Some(32 | 33)) + }) => + { + std::thread::sleep(Duration::from_millis(20)); + } + Err(error) => return Err(error), + } + } + } + read_status_record_once(status_dir, update_id) +} + +fn read_status_record_once( + status_dir: &Path, + update_id: &str, ) -> anyhow::Result { if !valid_update_id(update_id) { bail!("invalid update id"); diff --git a/src/server.rs b/src/server.rs index 456491a4..01af6819 100644 --- a/src/server.rs +++ b/src/server.rs @@ -146,6 +146,7 @@ type HttpServerTask = JoinHandle>; pub struct CodexHandler { config: Arc, tools: Arc>>, + bridge_runtime: Option>, project_bindings: Arc, connector_schemas: Arc, markdown_chat: Arc, @@ -653,11 +654,20 @@ impl ServerHandler for CodexHandler { }) .await .unwrap_or_else(|_| self.config.as_ref().clone()); - let tools = self - .tools - .iter() - .map(|tool| advertised_tool(tool.as_ref(), &advertising)) - .collect(); + let mut names = std::collections::HashSet::new(); + let mut tools = Vec::new(); + for tool in self.tools.iter() { + names.insert(tool.name()); + tools.push(advertised_tool(tool.as_ref(), &advertising)); + } + if let Some(runtime) = &self.bridge_runtime { + let view = runtime.snapshot(); + for tool in view.tools.iter() { + if names.insert(tool.name()) { + tools.push(advertised_tool(tool.as_ref(), &advertising)); + } + } + } let mut result = ListToolsResult::with_all_items(tools); let caller = crate::connector_schema::caller_key(&context.meta).or_else(|| { request @@ -826,9 +836,21 @@ impl ServerHandler for CodexHandler { .arguments .map(Value::Object) .unwrap_or_else(|| json!({})); - let tool = self.tools.iter().find(|t| t.name() == name); + // Pin only the selected upstream tool for this entire async dispatch. + // Holding the full registry snapshot here would keep *unrelated* retired + // MCP processes alive while another source runs a long request. + let bridge_tool = self.bridge_runtime.as_ref().and_then(|runtime| { + let view = runtime.snapshot(); + view.tools.iter().find(|tool| tool.name() == name).cloned() + }); + let tool = self + .tools + .iter() + .find(|tool| tool.name() == name) + .map(|tool| tool.as_ref()) + .or(bridge_tool.as_deref()); let ticket_wait = name == TicketWait::NAME && tool.is_some(); - let model_call = !tool.is_some_and(|tool| app_only_tool(tool.as_ref())); + let model_call = !tool.is_some_and(app_only_tool); let mut task_conversation = conversation.clone(); let mut task_owner_generation = None; let mut conversation_retired = false; @@ -1024,7 +1046,7 @@ impl ServerHandler for CodexHandler { // Keep `tool` as an Option so that even an unknown-tool call flows through // the audit begin/finish pairing below rather than short-circuiting. let agent_call = self.config.markdown_chat.enabled - && tool.is_some_and(|tool| !app_only_tool(tool.as_ref())) + && tool.is_some_and(|tool| !app_only_tool(tool)) && !ticket_wait && !context.ct.is_cancelled(); let called_at_ms = crate::markdown_chat::now_ms(); @@ -1657,7 +1679,7 @@ impl ServerHandler for CodexHandler { .await; } } - finalize_model_visible_result(tool.map(|tool| tool.as_ref()), &mut result, &self.config); + finalize_model_visible_result(tool, &mut result, &self.config); if !result.is_error && let Some(tool) = tool && let Err(error) = tool.validate_structured_output(result.structured_content.as_ref()) @@ -1790,7 +1812,7 @@ impl ServerHandler for CodexHandler { && name != "automation_verify_pairing" && !pairing_continuation && !ticket_wait - && !tool.is_some_and(|tool| app_only_tool(tool.as_ref())) + && !tool.is_some_and(app_only_tool) && !context.ct.is_cancelled() && self .conversation_auth_error("chat_read", conversation.as_ref()) @@ -2062,7 +2084,9 @@ struct HealthState { tool_count: usize, ready: Arc, multi_tunnel: Option<(Arc, usize)>, - upstreams: Arc>>, + upstreams: + Arc>>>, + runtime: Option>, filesystem: Option>, } @@ -2083,14 +2107,18 @@ async fn health(State(state): State) -> (StatusCode, Json) { || state.ready.load(Ordering::Acquire), |(active, _)| *active > 0, ); + let exposed = state + .runtime + .as_ref() + .map_or(0, |runtime| runtime.snapshot().tools.len()); let mut payload = json!({ "status": if is_ready { "ok" } else { "starting" }, - "tools": state.tool_count, + "tools": state.tool_count + exposed, }); - if !state.upstreams.is_empty() { + let upstreams = state.upstreams.read().unwrap(); + if !upstreams.is_empty() { payload["upstreams"] = Value::Object( - state - .upstreams + upstreams .iter() .map(|(name, state)| (name.clone(), state.snapshot())) .collect(), @@ -2162,6 +2190,21 @@ pub async fn start_http_server(mut config: AppConfig) -> anyhow::Result<()> { Err(error) => tracing::warn!("managed-worktree cleanup skipped: {error}"), } } + // Persisted configuration remains the source of truth. The historical + // override exists for explicitly isolated canary launches; validate it + // before handing it to the browser companion. + if let Ok(path) = std::env::var("CODEXIFY_BROWSER_SEND_GATE_PATH") { + if path.is_empty() + || path.len() > 4096 + || path.contains('\0') + || !std::path::Path::new(&path).is_absolute() + { + anyhow::bail!( + "CODEXIFY_BROWSER_SEND_GATE_PATH must be an absolute path up to 4096 bytes" + ); + } + config.markdown_chat.automation.provider_send_gate_path = Some(path); + } let config = Arc::new(config); let _browser_recovery = crate::agent_automation::watch_browser_companion(&config.markdown_chat.automation); @@ -2180,35 +2223,24 @@ pub async fn start_http_server(mut config: AppConfig) -> anyhow::Result<()> { let bridge = crate::bridge::connect_upstreams(&config).await; let bridge_report = bridge.report; let bridged_resources = bridge.resources; - let _bridge_services = bridge.services; - let _bridge_monitors = bridge.monitors; let upstreams = bridge.upstreams; + let bridge_runtime = bridge.runtime; + // The test-facing startup tool vector holds references to generation 1. + // Drop it immediately: only the runtime's replaceable snapshot may retain + // active sources, or retired child processes would remain pinned forever. + drop(bridge.tools); let mut all_tools = validate_and_wrap_tools(load_tools_for_config(&config)) .map_err(|error| anyhow::anyhow!("invalid native tool contract: {error}"))?; - let native: std::collections::HashSet<&'static str> = - all_tools.iter().map(|t| t.name()).collect(); - let mut seen = native.clone(); - for tool in bridge.tools { - let name = tool.name(); - if seen.contains(name) { - tracing::warn!("bridged tool '{name}' collides with an existing tool; skipping"); - continue; - } - match validate_and_wrap_tool(tool) { - Ok(tool) => { - seen.insert(name); - all_tools.push(tool); - } - Err(error) => { - tracing::warn!( - "bridged tool '{name}' has an invalid contract and was skipped: {error}" - ); - } - } + let bridged_count = bridge_runtime.snapshot().tools.len(); + if !config.mcp_servers.is_empty() { + all_tools.push( + validate_and_wrap_tool(Box::new(crate::bridge::ReloadMcpTool { + runtime: bridge_runtime.clone(), + })) + .map_err(|error| anyhow::anyhow!("invalid reload MCP tool contract: {error}"))?, + ); } - let bridged_count = all_tools.len() - native.len(); - let tools = Arc::new(all_tools); if let Some(supervisor) = &agent_automation { supervisor @@ -2272,6 +2304,7 @@ pub async fn start_http_server(mut config: AppConfig) -> anyhow::Result<()> { let factory_diff_checkpoints = diff_checkpoints.clone(); let factory_artifact_egress = artifact_egress.clone(); let factory_bridged_resources = bridged_resources.clone(); + let factory_bridge_runtime = bridge_runtime.clone(); let factory_audit = audit.clone(); let factory_tool_logging = tool_logging.clone(); let factory_next_tool_call_id = next_tool_call_id.clone(); @@ -2294,6 +2327,7 @@ pub async fn start_http_server(mut config: AppConfig) -> anyhow::Result<()> { diff_checkpoints: factory_diff_checkpoints.clone(), artifact_egress: factory_artifact_egress.clone(), bridged_resources: factory_bridged_resources.clone(), + bridge_runtime: Some(factory_bridge_runtime.clone()), audit: factory_audit.clone(), tool_logging: factory_tool_logging.clone(), next_tool_call_id: factory_next_tool_call_id.clone(), @@ -2320,6 +2354,7 @@ pub async fn start_http_server(mut config: AppConfig) -> anyhow::Result<()> { .with_state(HealthState { tool_count, upstreams: upstreams.clone(), + runtime: Some(bridge_runtime.clone()), filesystem: Some(config.filesystem_worker.clone()), ready: ready.clone(), multi_tunnel: multi_availability.as_ref().map(|availability| { @@ -2385,8 +2420,8 @@ pub async fn start_http_server(mut config: AppConfig) -> anyhow::Result<()> { ); } println!( - "Tools loaded ({tool_count}): {} native + {bridged_count} upstream-facing MCP tools", - tool_count - bridged_count + "Tools loaded ({}): {tool_count} native + {bridged_count} upstream-facing MCP tools", + tool_count + bridged_count ); if !bridge_report.is_empty() { println!("Upstream MCP servers:"); @@ -3292,6 +3327,7 @@ mod tests { let tools = validate_and_wrap_tools(tools).expect("test tool contracts must be valid"); CodexHandler { config: Arc::new(config), + bridge_runtime: None, tools: Arc::new(tools), connector_schemas: Arc::new(crate::connector_schema::ConnectorSchemaStore::default()), markdown_chat: Arc::new(crate::markdown_chat::MarkdownChatStore::default()), @@ -4039,6 +4075,7 @@ mod tests { let root = tempfile::tempdir().unwrap(); let mut handler = CodexHandler { config: Arc::new(crate::config::default_config(root.path().to_path_buf())), + bridge_runtime: None, tools: Arc::new(crate::registry::load_tools()), connector_schemas: Arc::new(crate::connector_schema::ConnectorSchemaStore::default()), markdown_chat: Arc::new(crate::markdown_chat::MarkdownChatStore::default()), @@ -4158,6 +4195,7 @@ mod tests { let handler = CodexHandler { config: Arc::new(config), + bridge_runtime: None, tools: Arc::new(crate::registry::load_tools()), connector_schemas: Arc::new(crate::connector_schema::ConnectorSchemaStore::default()), markdown_chat: Arc::new(crate::markdown_chat::MarkdownChatStore::default()), @@ -4202,6 +4240,7 @@ mod tests { let authorizations = Arc::new(ConversationAuthorizationStore::new()); let handler = CodexHandler { config: Arc::new(config), + bridge_runtime: None, tools: Arc::new(tools), connector_schemas: Arc::new(crate::connector_schema::ConnectorSchemaStore::default()), markdown_chat: Arc::new(crate::markdown_chat::MarkdownChatStore::default()), @@ -4808,7 +4847,8 @@ mod tests { let ready = Arc::new(AtomicBool::new(false)); let state = HealthState { tool_count: 38, - upstreams: Arc::new(HashMap::new()), + upstreams: Arc::new(std::sync::RwLock::new(HashMap::new())), + runtime: None, filesystem: None, ready: ready.clone(), multi_tunnel: None, @@ -4833,7 +4873,8 @@ mod tests { }); let state = HealthState { tool_count: 38, - upstreams: Arc::new(HashMap::new()), + upstreams: Arc::new(std::sync::RwLock::new(HashMap::new())), + runtime: None, filesystem: None, ready, multi_tunnel: Some((availability.clone(), 2)), diff --git a/src/service.rs b/src/service.rs index fbea5d2c..5c7d555a 100644 --- a/src/service.rs +++ b/src/service.rs @@ -1042,15 +1042,40 @@ fn windows_start_script() -> String { fn windows_stop_script() -> String { let task = powershell_quote(WINDOWS_TASK); format!( - "$ErrorActionPreference = 'Stop'\n$task = Get-ScheduledTask -TaskName {task} -ErrorAction Stop\nStop-ScheduledTask -InputObject $task -ErrorAction SilentlyContinue\n" + "$ErrorActionPreference = 'Stop'\n$task = Get-ScheduledTask -TaskName {task} -ErrorAction Stop\nif ([string]$task.State -eq 'Running') {{ Stop-ScheduledTask -InputObject $task -ErrorAction Stop }}\n{}", + windows_verify_native_stopped_script() ) } +#[cfg(any(target_os = "windows", test))] +fn windows_verify_native_stopped_script() -> &'static str { + // Task Scheduler may mark the task Ready while the script's native + // supervisor and listener are still running. Never report a successful + // stop or launch another instance until the exact installed pair exits. + r#"$taskRoot = [string]$task.Actions[0].WorkingDirectory +if ([string]::IsNullOrWhiteSpace($taskRoot) -or -not [IO.Path]::IsPathRooted($taskRoot)) { + throw 'Codexify scheduled task has no trusted working directory' +} +$nativeExecutable = [IO.Path]::GetFullPath((Join-Path $taskRoot 'bin\codexify.exe')) +$stopDeadline = [DateTime]::UtcNow.AddSeconds(15) +do { + $remainingNative = @(Get-CimInstance Win32_Process -Filter "Name='codexify.exe'" -ErrorAction Stop | + Where-Object { $_.ExecutablePath -ieq $nativeExecutable }) + if ($remainingNative.Count -eq 0) { break } + Start-Sleep -Milliseconds 500 +} while ([DateTime]::UtcNow -lt $stopDeadline) +if ($remainingNative.Count -gt 0) { + $remainingIds = ($remainingNative.ProcessId -join ',') + throw "Codexify scheduled task stopped but native processes remain (PIDs: $remainingIds); refusing to report success or start a duplicate" +} +"# +} + #[cfg(any(target_os = "windows", test))] fn windows_restart_script() -> String { - let task = powershell_quote(WINDOWS_TASK); format!( - "$ErrorActionPreference = 'Stop'\n$task = Get-ScheduledTask -TaskName {task} -ErrorAction Stop\nStop-ScheduledTask -InputObject $task -ErrorAction SilentlyContinue\nStart-ScheduledTask -InputObject $task\n" + "{}Start-ScheduledTask -InputObject $task -ErrorAction Stop\n", + windows_stop_script() ) } @@ -2622,10 +2647,26 @@ mod tests { let stop = windows_stop_script(); assert!(stop.contains("Stop-ScheduledTask")); assert!(!stop.contains("Start-ScheduledTask")); + assert!(stop.contains("if ([string]$task.State -eq 'Running')")); + assert!(stop.contains("Stop-ScheduledTask -InputObject $task -ErrorAction Stop")); + assert!(stop.contains("Get-CimInstance Win32_Process")); + assert!(stop.contains("native processes remain")); + assert!( + !stop.contains("Stop-ScheduledTask -InputObject $task -ErrorAction SilentlyContinue") + ); let restart = windows_restart_script(); assert!(restart.contains("Stop-ScheduledTask")); assert!(restart.contains("Start-ScheduledTask")); + let stop_check = restart.find("if ($remainingNative.Count -gt 0)").unwrap(); + let start_task = restart + .find("Start-ScheduledTask -InputObject $task") + .unwrap(); + assert!( + stop_check < start_task, + "restart must validate native exit first" + ); + assert!(restart.contains("refusing to report success or start a duplicate")); for script in [start, stop, restart] { assert!(!script.contains("Enable-ScheduledTask"), "{script}"); diff --git a/src/types.rs b/src/types.rs index b4938c8c..4cd997ca 100644 --- a/src/types.rs +++ b/src/types.rs @@ -556,6 +556,14 @@ impl McpServerProvenance { } } +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum McpSessionScope { + #[default] + Global, + PerChat, +} + /// One upstream MCP server to bridge, in the standard `mcpServers` shape. Its /// tools are discovered at startup and materialized according to the effective /// exposure mode. A `command` selects stdio; a `url` selects Codex-compatible @@ -626,6 +634,10 @@ pub struct McpServerSpec { /// catalog mode. #[serde(default)] pub mode: Option, + /// Explicit opt-in to a separate Playwright MCP process and browser + /// profile/tab group for each durable ChatGPT task. + #[serde(default)] + pub session_scope: McpSessionScope, /// Internal origin used only to select the backward-compatible default mode. #[serde(skip)] pub provenance: McpServerProvenance, diff --git a/src/upstream_control.rs b/src/upstream_control.rs index f1bf211a..f392864a 100644 --- a/src/upstream_control.rs +++ b/src/upstream_control.rs @@ -1,12 +1,119 @@ //! Per-connection admission and failure containment; never retries tool calls. -use crate::types::McpRequestLimits; +use crate::types::{McpRequestLimits, McpServerSpec}; +use rmcp::model::CallToolRequestParams; use serde_json::{Value, json}; -use std::sync::Mutex; +use std::sync::{Arc, Mutex}; use std::time::Duration; use tokio::sync::{Semaphore, SemaphorePermit}; use tokio::time::Instant; use tokio_util::sync::CancellationToken; +// Capability is tied to a configured upstream, never inferred from a tab name. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +enum PlaywrightBackendMode { + #[default] + Other, + Browser, + Cdp, + Extension, + Unverified, +} + +impl PlaywrightBackendMode { + // Playwright accepts --config and PLAYWRIGHT_MCP_CONFIG as well as + // command-line flags. A hidden extension configuration must not be + // mistaken for a browser-level backend. + fn config_document(spec: &McpServerSpec) -> Option> { + let path = spec + .args + .iter() + .enumerate() + .filter_map(|(index, arg)| { + if arg == "--config" { + Some(spec.args.get(index + 1).map_or("", String::as_str)) + } else { + arg.strip_prefix("--config=") + } + }) + .next_back() + .map(str::to_owned) + .or_else(|| spec.env.get("PLAYWRIGHT_MCP_CONFIG").cloned()) + .or_else(|| std::env::var("PLAYWRIGHT_MCP_CONFIG").ok())?; + + let mut path = std::path::PathBuf::from(path); + if path.is_relative() + && let Some(cwd) = spec.cwd.as_ref() + { + path = std::path::Path::new(cwd).join(path); + } + let parsed = std::fs::read_to_string(path) + .ok() + .and_then(|source| serde_json::from_str::(&source).ok()); + Some(parsed) + } + + fn from_spec(name: &str, spec: &McpServerSpec) -> Self { + let playwright = name.to_ascii_lowercase().contains("playwright") + || spec + .args + .iter() + .any(|arg| arg.to_ascii_lowercase().contains("playwright")) + || spec + .command + .as_deref() + .is_some_and(|command| command.to_ascii_lowercase().contains("playwright")); + if !playwright { + return Self::Other; + } + + let configured = Self::config_document(spec); + let read_config = configured.as_ref().and_then(Option::as_ref); + + let cli_extension = spec.args.iter().rev().find_map(|arg| match arg.as_str() { + "--extension" | "--extension=true" => Some(true), + "--extension=false" => Some(false), + _ => None, + }); + let env_extension = spec + .env + .get("PLAYWRIGHT_MCP_EXTENSION") + .cloned() + .or_else(|| std::env::var("PLAYWRIGHT_MCP_EXTENSION").ok()) + .and_then(|value| match value.to_ascii_lowercase().as_str() { + "1" | "true" | "yes" => Some(true), + "0" | "false" | "no" => Some(false), + _ => None, + }); + let config_extension = read_config + .and_then(|value| value.get("extension")) + .and_then(Value::as_bool); + if cli_extension.or(env_extension).or(config_extension) == Some(true) + || name.eq_ignore_ascii_case("playwright-extension") + || name.eq_ignore_ascii_case("playwright_extension") + { + return Self::Extension; + } + + // Failure to read an explicitly configured backend leaves its + // permissions unknown. Do not dispatch real isolation requests. + if configured.as_ref().is_some_and(Option::is_none) { + return Self::Unverified; + } + + let cdp = spec + .args + .iter() + .any(|arg| arg == "--cdp-endpoint" || arg.starts_with("--cdp-endpoint=")) + || spec.env.contains_key("PLAYWRIGHT_MCP_CDP_ENDPOINT") + || std::env::var_os("PLAYWRIGHT_MCP_CDP_ENDPOINT").is_some() + || read_config + .and_then(|value| value.pointer("/browser/cdpEndpoint")) + .and_then(Value::as_str) + .is_some_and(|url| !url.is_empty()); + if cdp { Self::Cdp } else { Self::Browser } + } +} + #[derive(Default)] struct State { failures: u32, @@ -17,6 +124,8 @@ struct State { pub(crate) struct UpstreamControl { limits: McpRequestLimits, + playwright_mode: PlaywrightBackendMode, + pub(crate) scoped_playwright: Option>, active: Semaphore, pending: Semaphore, state: Mutex, @@ -55,10 +164,96 @@ impl UpstreamControl { active: Semaphore::new(limits.max_concurrent_requests), pending: Semaphore::new(limits.max_concurrent_requests + limits.max_pending_requests), limits, + playwright_mode: PlaywrightBackendMode::Other, + scoped_playwright: None, state: Mutex::new(State::default()), unavailable: tokio::sync::watch::channel(false).0, } } + /// Keep capability stable for this upstream connection and all exposure modes. + pub(crate) fn for_server(mut self, name: &str, spec: &McpServerSpec) -> Self { + self.playwright_mode = PlaywrightBackendMode::from_spec(name, spec); + self + } + + pub(crate) fn with_scoped_playwright( + mut self, + pool: Option>, + ) -> Self { + self.scoped_playwright = pool; + self + } + + /// Advertise only what the connection mode can establish, not what a + /// similar tool on another upstream may be able to do. + pub(crate) fn browser_context_capability(&self) -> Option<&'static str> { + match self.playwright_mode { + PlaywrightBackendMode::Other => None, + PlaywrightBackendMode::Browser => Some("browser-level"), + PlaywrightBackendMode::Cdp => Some("cdp-permission-dependent"), + PlaywrightBackendMode::Extension => Some("existing-tabs-only"), + PlaywrightBackendMode::Unverified => Some("unverified-config"), + } + } + + pub(crate) fn isolated_tab_requested( + &self, + tool: &str, + params: &CallToolRequestParams, + ) -> bool { + self.playwright_mode != PlaywrightBackendMode::Other + && tool == "browser_tabs" + && params.arguments.as_ref().is_some_and(|args| { + args.get("action").and_then(Value::as_str) == Some("new") + && args + .get("isolatedContext") + .and_then(Value::as_str) + .is_some_and(|name| !name.is_empty() && name != "default") + }) + } + + /// An extension is attached to existing tabs; it cannot provide real + /// BrowserContexts. No attempt or fallback is safe for an isolation request. + pub(crate) fn check_browser_context_request( + &self, + tool: &str, + params: &CallToolRequestParams, + ) -> Result<(), String> { + if self.isolated_tab_requested(tool, params) + && self.playwright_mode == PlaywrightBackendMode::Unverified + { + return Err( + "Playwright config file is missing, invalid or unreadable, so browser-context capabilities cannot be verified. No request was dispatched. Restore the configured MCP file before creating an isolated browser context.".into() + ); + } + if self.isolated_tab_requested(tool, params) + && self.playwright_mode == PlaywrightBackendMode::Extension + { + return Err( + "Playwright extension/existing-tab mode cannot create a genuinely isolated browser context (Target.createBrowserContext requires browser-level access). No request was dispatched. Use a connected browser-level Playwright MCP backend for browser_tabs(new, isolatedContext), then keep subsequent tab operations on that backend. If it is unavailable, repair its startup; do not fall back to shared extension tabs." + .into(), + ); + } + Ok(()) + } + + /// Some CDP endpoints are page-scoped; translate the exact refusal but + /// do not assume a context was created or automatically retry any tool. + pub(crate) fn browser_context_refusal( + &self, + isolated_requested: bool, + message: &str, + ) -> Option { + (isolated_requested + && message.contains("Target.createBrowserContext") + && message.contains("-32000") + && message.contains("Not allowed")) + .then(|| { + "CDP -32000 Not allowed: this Playwright/CDP session lacks browser-level Target.createBrowserContext permission. No isolated context was confirmed. Do not reuse an extension tab or assume creation succeeded; connect a browser-level Playwright backend, verify session identity and existing resources before retrying." + .into() + }) + } + pub(crate) async fn wait_unavailable(&self) { let mut receiver = self.unavailable.subscribe(); loop { @@ -128,10 +323,14 @@ impl UpstreamControl { .saturating_sub(self.active.available_permits()); let admitted = (self.limits.max_concurrent_requests + self.limits.max_pending_requests) .saturating_sub(self.pending.available_permits()); - json!({"state": if state.probe_active {"probing"} else if state.open_until.is_some() {"unresponsive"} else if state.failures > 0 {"degraded"} else {"connected"}, + let mut snapshot = json!({"state": if state.probe_active {"probing"} else if state.open_until.is_some() {"unresponsive"} else if state.failures > 0 {"degraded"} else {"connected"}, "activeRequests":active,"queuedRequests":admitted.saturating_sub(active),"consecutiveFailures":state.failures, "retryAfterMs":state.open_until.map(|until| until.saturating_duration_since(Instant::now()).as_millis() as u64).unwrap_or(0), - "lastOutcome":state.last_outcome}) + "lastOutcome":state.last_outcome}); + if let Some(capability) = self.browser_context_capability() { + snapshot["browserContextCapability"] = json!(capability); + } + snapshot } } @@ -181,6 +380,278 @@ impl Drop for Admission<'_> { } } +#[cfg(test)] +mod browser_context_tests { + use super::*; + use serde_json::json; + + #[test] + fn exposed_capability_matches_configured_backend() { + let full = UpstreamControl::default().for_server( + "playwright", + &McpServerSpec { + command: Some("node".into()), + args: vec!["@playwright/mcp".into()], + ..Default::default() + }, + ); + let extension = UpstreamControl::default().for_server( + "playwright-extension", + &McpServerSpec { + command: Some("node".into()), + args: vec!["@playwright/mcp".into(), "--extension".into()], + ..Default::default() + }, + ); + assert_eq!(full.snapshot()["browserContextCapability"], "browser-level"); + assert_eq!( + extension.snapshot()["browserContextCapability"], + "existing-tabs-only" + ); + assert!( + UpstreamControl::default() + .snapshot() + .get("browserContextCapability") + .is_none() + ); + } + + fn spec(args: &[&str]) -> McpServerSpec { + McpServerSpec { + command: Some("node".into()), + args: args.iter().map(|arg| (*arg).to_string()).collect(), + ..Default::default() + } + } + + fn request(action: &str, context: Option<&str>) -> CallToolRequestParams { + let mut arguments = json!({ "action": action, "url": "https://example.invalid/form" }); + if let Some(context) = context { + arguments["isolatedContext"] = json!(context); + } + CallToolRequestParams::new("browser_tabs") + .with_arguments(arguments.as_object().unwrap().clone()) + } + + #[test] + fn extension_mode_fails_before_isolated_creation() { + let control = UpstreamControl::default().for_server( + "playwright-extension", + &spec(&["playwright/mcp.js", "--extension"]), + ); + let request = request("new", Some("lane06_grants_funding")); + assert!(control.isolated_tab_requested("browser_tabs", &request)); + let error = control + .check_browser_context_request("browser_tabs", &request) + .unwrap_err(); + assert!(error.contains("No request was dispatched")); + assert!(error.contains("cannot create a genuinely isolated")); + } + + #[test] + fn extension_env_and_renamed_server_also_fail_closed() { + let mut settings = spec(&["playwright/mcp.js"]); + settings + .env + .insert("PLAYWRIGHT_MCP_EXTENSION".into(), "true".into()); + let control = UpstreamControl::default().for_server("my_browser", &settings); + assert!( + control + .check_browser_context_request("browser_tabs", &request("new", Some("lane01"))) + .is_err() + ); + settings + .env + .insert("PLAYWRIGHT_MCP_EXTENSION".into(), "false".into()); + let control = UpstreamControl::default().for_server("my_browser", &settings); + assert!( + control + .check_browser_context_request("browser_tabs", &request("new", Some("lane01"))) + .is_ok() + ); + } + + #[test] + fn normal_extension_tab_operations_remain_compatible() { + let control = UpstreamControl::default().for_server( + "playwright-extension", + &spec(&["playwright/mcp.js", "--extension"]), + ); + for request in [ + request("list", Some("lane06")), + request("new", None), + request("new", Some("default")), + request("select", Some("lane06")), + ] { + assert!( + control + .check_browser_context_request("browser_tabs", &request) + .is_ok() + ); + } + assert!( + control + .check_browser_context_request("browser_navigate", &request("new", Some("lane06"))) + .is_ok() + ); + } + + #[test] + fn playwright_json_extension_mode_cannot_bypass_guard() { + let temp = tempfile::tempdir().unwrap(); + let file = temp.path().join("playwright.json"); + std::fs::write(&file, r#"{"extension":true}"#).unwrap(); + let config_name = file.to_str().unwrap(); + let settings = spec(&["@playwright/mcp", "--config", config_name]); + let control = UpstreamControl::default().for_server("playwright", &settings); + assert_eq!( + control.browser_context_capability(), + Some("existing-tabs-only") + ); + assert!( + control + .check_browser_context_request("browser_tabs", &request("new", Some("lane06"))) + .unwrap_err() + .contains("No request was dispatched") + ); + + std::fs::write( + &file, + r#"{"extension":false,"browser":{"cdpEndpoint":"chrome"}}"#, + ) + .unwrap(); + let control = UpstreamControl::default().for_server("playwright", &settings); + assert_eq!( + control.browser_context_capability(), + Some("cdp-permission-dependent") + ); + + std::fs::write(&file, r#"{"extension":true}"#).unwrap(); + let mut overriding = settings.clone(); + overriding + .env + .insert("PLAYWRIGHT_MCP_EXTENSION".into(), "false".into()); + let control = UpstreamControl::default().for_server("playwright", &overriding); + assert_eq!(control.browser_context_capability(), Some("browser-level")); + } + + #[test] + fn missing_or_invalid_json_config_fails_closed_without_blocking_default_tab() { + let temp = tempfile::tempdir().unwrap(); + let file = temp.path().join("config.json"); + let mut settings = spec(&["@playwright/mcp", "--config"]); + settings.args.push(file.to_string_lossy().into_owned()); + let control = UpstreamControl::default().for_server("playwright", &settings); + assert_eq!( + control.snapshot()["browserContextCapability"], + "unverified-config" + ); + assert!( + control + .check_browser_context_request("browser_tabs", &request("new", Some("lane06"))) + .unwrap_err() + .contains("No request was dispatched") + ); + assert!( + control + .check_browser_context_request("browser_tabs", &request("new", None)) + .is_ok() + ); + + std::fs::write(&file, "not json").unwrap(); + let control = UpstreamControl::default().for_server("playwright", &settings); + assert_eq!( + control.snapshot()["browserContextCapability"], + "unverified-config" + ); + + std::fs::write(&file, r#"{"extension":true}"#).unwrap(); + settings.args.push("--extension=false".into()); + let control = UpstreamControl::default().for_server("playwright", &settings); + assert_eq!( + control.snapshot()["browserContextCapability"], + "browser-level" + ); + } + + #[test] + fn playwright_config_relative_to_upstream_cwd_is_resolved() { + let temp = tempfile::tempdir().unwrap(); + std::fs::write(temp.path().join("playwright.json"), r#"{"extension":true}"#).unwrap(); + let mut settings = spec(&["@playwright/mcp", "--config=playwright.json"]); + settings.cwd = Some(temp.path().to_string_lossy().into_owned()); + let control = UpstreamControl::default().for_server("playwright", &settings); + assert_eq!( + control.snapshot()["browserContextCapability"], + "existing-tabs-only" + ); + } + + #[test] + fn browser_and_cdp_backend_allow_capable_context_attempts() { + for settings in [ + spec(&["playwright/mcp.js"]), + spec(&["playwright/mcp.js", "--cdp-endpoint=http://127.0.0.1:9222"]), + ] { + let control = UpstreamControl::default().for_server("playwright", &settings); + assert!( + control + .check_browser_context_request( + "browser_tabs", + &request("new", Some("lane06_grants_funding")) + ) + .is_ok() + ); + } + } + + #[test] + fn cdp_minus_32000_is_precise_but_unrelated_errors_stay_untouched() { + let control = UpstreamControl::default().for_server( + "playwright", + &spec(&["playwright/mcp.js", "--cdp-endpoint=chrome"]), + ); + let error = r#"Protocol error (Target.createBrowserContext): {"code":-32000,"message":"Not allowed"}"#; + assert!( + control + .browser_context_refusal(true, error) + .unwrap() + .contains("No isolated context was confirmed") + ); + assert!(control.browser_context_refusal(false, error).is_none()); + assert!( + control + .browser_context_refusal( + true, + "Protocol error -32000: Not allowed for Page.navigate" + ) + .is_none() + ); + } + + #[test] + fn unrelated_mcp_backend_and_disconnect_cannot_silently_switch_modes() { + let ordinary = UpstreamControl::default() + .for_server("other-mcp", &spec(&["unrelated-server.js", "--extension"])); + assert!( + ordinary + .check_browser_context_request("browser_tabs", &request("new", Some("lane06"))) + .is_ok() + ); + let extension = UpstreamControl::default().for_server( + "playwright_extension", + &spec(&["playwright/mcp.js", "--extension"]), + ); + extension.health_result(false); + extension.health_result(true); + assert!( + extension + .check_browser_context_request("browser_tabs", &request("new", Some("lane06"))) + .is_err() + ); + } +} + #[cfg(test)] mod tests { use super::*;