Merge origin/main into nwparker/expo-58-upgrade

This commit is contained in:
Kelvin Amoaba
2026-11-11 20:10:24 +00:00
3024 changed files with 28796 additions and 145848 deletions
@@ -0,0 +1,28 @@
#!/usr/bin/env bash
set -euo pipefail
if [ "$#" -eq 0 ]; then
echo 'Usage: install-ubuntu-apt-packages.sh <package>...' >&2
exit 2
fi
bash "$(dirname "${BASH_SOURCE[0]}")/prepare-ubuntu-apt.sh"
# Bound both routes while allowing large fallback downloads.
# Run deadlines as root so sudo cannot leave apt in a separate session.
if sudo timeout --kill-after=10s 45 apt-get update -o Acquire::Languages=none && sudo timeout --kill-after=10s 120 apt-get install -y "$@"; then
exit 0
fi
echo 'Ubuntu package setup failed; trying the same packages through the MIT mirror.' >&2
for host in archive.ubuntu.com ports.ubuntu.com mirrors.mit.edu; do
timeout 5 getent ahosts "$host" || true
done
bash "$(dirname "${BASH_SOURCE[0]}")/use-ubuntu-apt-mirror.sh"
bash "$(dirname "${BASH_SOURCE[0]}")/recover-ubuntu-dpkg.sh" || true
# Unrelated repositories may fail refresh; apt still verifies the requested packages.
if ! sudo timeout --kill-after=10s 120 apt-get update -o Acquire::Languages=none; then
echo 'Index refresh incomplete; attempting the requested packages with available authenticated indexes.' >&2
fi
sudo timeout --kill-after=10s 600 apt-get install -y "$@"
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/env bash
set -euo pipefail
# A timed-out apt frontend can leave dpkg running in a separate session.
sudo timeout --kill-after=10s 30 bash -euo pipefail -c '
while lslocks --noheadings --raw --notruncate --output PATH | grep -E "^/var/lib/dpkg/lock(-frontend)?$" >/dev/null; do
sleep 1
done
dpkg --configure -a
'
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
set -euo pipefail
# Change repository locations while retaining suites, architectures and signing keys.
for source in /etc/apt/apt-mirrors.txt /etc/apt/sources.list /etc/apt/sources.list.d/*.list /etc/apt/sources.list.d/*.sources; do
if [ -f "$source" ]; then
sudo sed -i -E \
-e 's#https?://(azure\.archive|archive|security)\.ubuntu\.com/ubuntu#https://mirrors.mit.edu/ubuntu#g' \
-e 's#https?://ports\.ubuntu\.com/ubuntu-ports#https://mirrors.mit.edu/ubuntu-ports#g' \
"$source"
fi
done
+3 -9
View File
@@ -93,16 +93,10 @@ jobs:
pnpm vitest run --config config/vitest.config.ts
config/scripts/performance/macos-computer-owner/macos-computer-helper-owner-loss-group-recovery.test.mjs
config/scripts/performance/macos-computer-owner/macos-computer-helper-owner-loss-processes.test.mjs
src/main/computer/sidecar-client.test.ts
src/main/computer/macos-native-provider-client.test.ts
src/main/computer/macos-native-provider-socket.test.ts
src/main/computer/macos-computer-use-permissions.test.ts
src/main/computer/macos-computer-use-permission-status.test.ts
src/main/computer/sidecar-transport/sidecar-client.test.ts
src/main/computer/macos-native/macos-native-provider-client.test.ts
src/main/providers/windows-shell-preflight-runtime.windows.test.ts
src/main/computer/desktop-script-provider-actions.test.ts
src/main/computer/desktop-script-provider-cache-lifecycle.test.ts
src/main/computer/desktop-script-provider-errors.test.ts
src/main/computer/desktop-script-provider-action-errors.test.ts
src/main/computer/desktop-script/actions/desktop-script-provider-actions.test.ts
src/cli/format.test.ts
src/cli/handlers/computer-action-validation.test.ts
src/cli/handlers/computer-state-formatting.test.ts
@@ -27,23 +27,6 @@ env:
BASELINE_SHA: 030c88deecf3adc212d22f57b085e4bd5c6e48e6
jobs:
contract:
if: github.event_name != 'pull_request' || github.event.pull_request.draft != true
runs-on: ${{ matrix.os }}
timeout-minutes: 180
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
steps:
- uses: actions/checkout@v6
with:
persist-credentials: false
- uses: actions/setup-python@v6
with:
python-version: '3.12'
- run: python -m unittest discover -s config/benchmarks/computer-use -p 'test_*.py'
linux:
if: github.event_name != 'pull_request' || github.event.pull_request.draft != true
runs-on: ubuntu-latest
+11 -2
View File
@@ -123,6 +123,10 @@ jobs:
exit 0
fi
read -r -a packages <<< "$ORCA_E2E_APT_PACKAGES"
if [ -f .github/scripts/install-ubuntu-apt-packages.sh ]; then
bash .github/scripts/install-ubuntu-apt-packages.sh "${packages[@]}"
exit 0
fi
if [ -f .github/scripts/prepare-ubuntu-apt.sh ]; then
bash .github/scripts/prepare-ubuntu-apt.sh
else
@@ -529,7 +533,12 @@ jobs:
ref: ${{ inputs.ref || github.ref }}
persist-credentials: false
- name: Install headless tools
run: sudo apt-get update && sudo apt-get install -y build-essential ripgrep xvfb openbox x11-utils
run: &install_headless_tools |
if [ -f .github/scripts/install-ubuntu-apt-packages.sh ]; then
bash .github/scripts/install-ubuntu-apt-packages.sh build-essential ripgrep xvfb openbox x11-utils
else
sudo apt-get update && sudo apt-get install -y build-essential ripgrep xvfb openbox x11-utils
fi
- uses: ./.github/actions/install-node-dependencies
with:
native-runtime: electron
@@ -636,7 +645,7 @@ jobs:
- name: Fetch the 1.4.224 relay sources
run: git fetch --no-tags --depth=1 origin +refs/tags/v1.4.224:refs/tags/v1.4.224
- name: Install headless tools
run: sudo apt-get update && sudo apt-get install -y build-essential ripgrep xvfb openbox x11-utils
run: *install_headless_tools
- uses: ./.github/actions/install-node-dependencies
with:
native-runtime: electron
@@ -70,7 +70,6 @@ jobs:
- name: Run golden E2E tests on Linux
if: runner.os == 'Linux'
run: |
xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e tests/e2e/golden-core-flows.spec.ts
xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:workspace-session-golden
if [ -f tests/e2e/golden-fresh-profile-terminal.spec.ts ]; then
xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e tests/e2e/golden-fresh-profile-terminal.spec.ts tests/e2e/golden-shell-command.spec.ts
@@ -84,7 +83,6 @@ jobs:
- name: Run golden E2E tests on macOS
if: runner.os == 'macOS'
run: |
env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e tests/e2e/golden-core-flows.spec.ts
env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:workspace-session-golden
if [ -f tests/e2e/golden-fresh-profile-terminal.spec.ts ]; then
env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e tests/e2e/golden-fresh-profile-terminal.spec.ts tests/e2e/golden-shell-command.spec.ts
-2
View File
@@ -27,7 +27,6 @@ on:
- 'src/main/runtime/agent-session/agent-session-account-*.ts'
- 'src/main/runtime/agent-session/agent-session-acquisition-*.ts'
- 'src/main/runtime/agent-session/agent-session-conversation-*.ts'
- 'src/main/runtime/agent-session/agent-session-death-*.ts'
- 'src/main/runtime/agent-session/agent-session-launch-*.ts'
- 'src/main/runtime/agent-session/agent-session-operation-*.ts'
- 'src/main/runtime/agent-session/agent-session-rewind-*.ts'
@@ -116,7 +115,6 @@ on:
- 'src/main/runtime/agent-session/agent-session-account-*.ts'
- 'src/main/runtime/agent-session/agent-session-acquisition-*.ts'
- 'src/main/runtime/agent-session/agent-session-conversation-*.ts'
- 'src/main/runtime/agent-session/agent-session-death-*.ts'
- 'src/main/runtime/agent-session/agent-session-launch-*.ts'
- 'src/main/runtime/agent-session/agent-session-operation-*.ts'
- 'src/main/runtime/agent-session/agent-session-rewind-*.ts'
+1 -6
View File
@@ -20,17 +20,12 @@ on:
# without these a rename lands green and only breaks the next nightly.
- 'src/main/runtime/session-tabs/session-tabs-phone-layout-moves.test.ts'
- 'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-terminal-writer-acquire.test.ts'
- 'src/shared/agent-launch/permissions/tui-agent-permission-choice.test.ts'
- 'src/main/runtime/rpc/methods/projects/repo.test.ts'
- 'src/renderer/src/components/tab-bar/use-new-tab-agent-menu-host-preferences.test.tsx'
- 'src/main/sqlite/sync-database.test.ts'
- 'src/main/runtime/orchestration/db/row-column-lists.test.ts'
- 'src/main/codex-usage/codex-rollout-file-lifetime.test.ts'
- 'src/main/codex-usage/scanner-incremental-append.test.ts'
- 'src/main/usage/jsonl-file-reader.test.ts'
- 'src/main/usage/jsonl-file-snapshot.test.ts'
- 'src/main/usage/source-input/jsonl/jsonl-file-reader.test.ts'
- 'src/main/claude-usage/scanner-incremental-append.test.ts'
- 'src/main/claude-usage/store-checkpoint-persistence.test.ts'
permissions:
contents: read
+1 -1
View File
@@ -5,7 +5,7 @@ on:
paths:
- 'src/shared/source-control/ai/generation/commit-message-agent-specs-primary.ts'
- 'tests/tools/pi-provider-runtime-smoke.mjs'
- 'src/main/pi/rpc-history-*.ts'
- 'src/main/pi/rpc/history/rpc-history-*.ts'
- '.github/workflows/pi-provider-runtime.yml'
permissions:
contents: read
+13 -11
View File
@@ -790,15 +790,7 @@ jobs:
id: shells
background: true
run: |
# Per-connection limits complement the whole-command apt deadlines below.
sudo tee /etc/apt/apt.conf.d/99-orca-shell-contracts >/dev/null <<'APTCONF'
Acquire::http::Timeout "15";
Acquire::https::Timeout "15";
Acquire::Retries "1";
APTCONF
# Unrelated runner repositories may fail refresh; installing zsh must still succeed.
timeout 120 sudo apt-get update || true
timeout 300 sudo apt-get install -y zsh
bash .github/scripts/install-ubuntu-apt-packages.sh zsh
# A fixed 4.x release meets the contract without tracking package-repository updates.
case "$(uname -m)" in
aarch64) arch=aarch64 sha=57349f0111728c64b703a84e611aa97ff4d1fa8466385d64e67bd5bc3ffa49fc ;;
@@ -936,7 +928,18 @@ jobs:
background: true
run: |
bash .github/scripts/prepare-ubuntu-apt.sh
pnpm exec playwright-core install --with-deps webkit
if [ ! -f .github/scripts/use-ubuntu-apt-mirror.sh ]; then
pnpm exec playwright-core install --with-deps webkit
exit 0
fi
echo 'Installing WebKit dependencies through the primary route.'
if ! sudo env "PATH=$PATH" timeout --kill-after=10s 240 ./node_modules/.bin/playwright-core install-deps webkit; then
echo 'Dependency installation did not complete; retrying with the Ubuntu mirror fallback.'
bash .github/scripts/use-ubuntu-apt-mirror.sh
bash .github/scripts/recover-ubuntu-dpkg.sh || true
sudo env "PATH=$PATH" timeout --kill-after=10s 600 ./node_modules/.bin/playwright-core install-deps webkit
fi
timeout --kill-after=10s 180 pnpm exec playwright-core install webkit
# The entry lives in mobile/ so one React resolves; without this every RN import is nothing.
- uses: ./.github/actions/install-mobile-dependencies
@@ -1110,7 +1113,6 @@ jobs:
xvfb-run --auto-servernum pnpm exec vitest run --config config/vitest.config.ts
--no-file-parallelism
src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts
src/main/persistence/profile-state/profile-state-writer-stall.electron.test.ts
src/main/browser/cookies/browser-google-cookie-clear.electron.test.ts
src/main/browser/guest-lifecycle/popups/presentation/popup-origin-chrome.electron.test.ts
src/main/browser/guest-lifecycle/navigation/browser-link-materialization.electron.test.ts
+3 -6
View File
@@ -62,7 +62,6 @@ on:
- 'src/shared/shell/launch/shell-argument-quoting.ts'
- '!src/**/*.test.ts'
- 'src/main/managed-server/host-state/orcad-windows-host-lane.test.ts'
- 'tests/e2e/ssh-orcad-auto-convert.spec.ts'
- 'tests/e2e/helpers/orcad-convert-host.ts'
- 'tests/e2e/helpers/orcad-convert-flow.ts'
- 'tests/e2e/helpers/orcad-upgrade-profile.ts'
@@ -78,7 +77,7 @@ on:
workflow_dispatch:
inputs:
cells:
description: Comma-separated cell ids from src/main/ssh/hostile-host-test-support/ssh-windows-host-cells.ts; empty runs the default set (orcad-cli-* cells run only when named).
description: Comma-separated cells orcad-cmd, orcad-powershell, or orcad-cli-managed; empty runs the two shell cells.
required: false
default: ''
preparation_mode:
@@ -144,7 +143,7 @@ jobs:
with:
persist-credentials: false
# Keep complete server/test trees; missing future imports fail the unchanged builds.
# All of src: the orcad-convert cell builds the full e2e app and the bundled CLI.
# All of src: the managed CLI cell builds the full e2e app and bundled CLI.
# mobile: the template ships the mobile web page, which builds from mobile/.
# cloud: config/tsconfig.vitest-transform.json references the cloud projects, so vitest needs them.
sparse-checkout: |
@@ -242,10 +241,8 @@ jobs:
New-Item -ItemType Directory -Force -Path $receipts | Out-Null
$cells=@($env:CELLS -split ',' | ForEach-Object {$_.Trim()} | Where-Object {$_})
if(-not $cells.Count){$cells=@('orcad-cmd','orcad-powershell')}
# One Windows host runs the app-level conversion; it is last because it switches native modules.
if(-not $env:CELLS -and '${{ matrix.arch }}' -eq 'x64' -and '${{ matrix.server }}' -eq 'inbox'){$cells+='orcad-convert'}
# App cells reach the managed server through an SSH local forward, which provisioning grants to the last accounts only.
$appCellIds=@('orcad-convert','orcad-cli-managed','orcad-cli-convert')
$appCellIds=@('orcad-cli-managed')
$cells=@($cells | Where-Object {$appCellIds -notcontains $_})+@($cells | Where-Object {$appCellIds -contains $_})
$forwarding=@($cells | Where-Object {$appCellIds -contains $_}).Count
$archive=''
+1 -14
View File
@@ -35,7 +35,6 @@ on:
- '!**/*.test.ts'
- '!**/*.test.tsx'
- 'src/main/wsl/orcad/wsl-orcad-real-distro-lane.test.ts'
- 'src/main/persistence/moving-wsl-projects/wsl-move-real-pause.test.ts'
- 'src/main/wsl/orcad/wsl-orcad-real-distro-idle-release-lane.test.ts'
- '.github/workflows/wsl-orcad-e2e.yml'
- 'config/ci/wsl-lifecycle/**'
@@ -343,20 +342,8 @@ jobs:
run: |
node node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/wsl/orcad/wsl-orcad-real-distro-lane.test.ts --reporter=verbose 2>&1 | Tee-Object (Join-Path $env:ORCA_WSL_ORCAD_LANE_RECEIPTS 'survive.log')
if ($global:LASTEXITCODE -ne 0) { throw "survive phase failed: $global:LASTEXITCODE" }
# The WSL move's pause on real distro shells: Sleep ends them, the daemon proves the exit,
# the journal keeps each pane's folder, and a new shell opens there.
- name: 'WSL move: pause real distro terminals'
if: ${{ !cancelled() && steps.import.outcome == 'success' }}
timeout-minutes: 10
env:
ORCA_WSL_MOVE_REAL_PAUSE_DISTRO: ${{ env.PLAIN_DISTRO }}
run: |
New-Item -ItemType Directory -Force $env:ORCA_WSL_ORCAD_LANE_RECEIPTS | Out-Null
node node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/persistence/moving-wsl-projects/wsl-move-real-pause.test.ts --reporter=verbose 2>&1 | Tee-Object (Join-Path $env:ORCA_WSL_ORCAD_LANE_RECEIPTS 'wsl-move-real-pause.log')
if ($global:LASTEXITCODE -ne 0) { throw "WSL move real pause failed: $global:LASTEXITCODE" }
wsl.exe --terminate $env:PLAIN_DISTRO
# R40: with no terminal left, orcad idle-exits and the holder lets the distro stop on its own.
- name: 'Phase 3: idle orcad releases the distro; distro restart to first output baseline'
- name: 'Phase 3: idle orcad releases the distro'
timeout-minutes: 30
env:
ORCA_RUN_WSL_ORCAD_LANE: '1'
+3 -3
View File
@@ -79,7 +79,7 @@
{
"name": "@linear/sdk",
"allowTypeImports": true,
"message": "Value-importing @linear/sdk hoists its ~2.6MB CJS bundle into the eager top-level require block and defeats the lazy loader. Use `import type` plus loadLinearSdk() from src/main/linear/linear-sdk.ts."
"message": "Value-importing @linear/sdk hoists its ~2.6MB CJS bundle into the eager top-level require block and defeats the lazy loader. Use `import type` plus loadLinearSdk() from src/main/linear/requests/linear-sdk.ts."
}
]
}
@@ -129,7 +129,7 @@
{
"name": "@linear/sdk",
"allowTypeImports": true,
"message": "Value-importing @linear/sdk hoists its ~2.6MB CJS bundle into the eager top-level require block and defeats the lazy loader. Use `import type` plus loadLinearSdk() from src/main/linear/linear-sdk.ts."
"message": "Value-importing @linear/sdk hoists its ~2.6MB CJS bundle into the eager top-level require block and defeats the lazy loader. Use `import type` plus loadLinearSdk() from src/main/linear/requests/linear-sdk.ts."
},
{
"name": "ssh2",
@@ -228,7 +228,7 @@
{
"name": "@linear/sdk",
"allowTypeImports": true,
"message": "Value-importing @linear/sdk hoists its ~2.6MB CJS bundle into the eager top-level require block and defeats the lazy loader. Use `import type` plus loadLinearSdk() from src/main/linear/linear-sdk.ts."
"message": "Value-importing @linear/sdk hoists its ~2.6MB CJS bundle into the eager top-level require block and defeats the lazy loader. Use `import type` plus loadLinearSdk() from src/main/linear/requests/linear-sdk.ts."
},
{
"name": "ssh2",
@@ -1,10 +1,5 @@
import { expect, it } from 'vitest'
import { OBJECT_STORE_SCHEMA } from '../src/object-store-schema.generated'
import { relayObjectStoreSchema } from './object-store-schema'
it('object store schema matches the relay schema', async () => {
expect([...OBJECT_STORE_SCHEMA]).toEqual(await relayObjectStoreSchema())
})
it('stamps fresh objects, keeps pre-version ones, refuses objects newer than the code', async () => {
const { DatabaseSync } = await import('node:sqlite')
+8 -2
View File
@@ -46,6 +46,7 @@ import {
EdgeMoveDeferredError,
EdgeMoveBusyError,
inEdgeCohort,
mayBeOnEdge,
mapEpochFloor,
type EdgeAssignments
} from './edge-relay.js'
@@ -485,8 +486,9 @@ export function createRelayApp(
edge?.ready === true &&
body.data.regionCorrection?.action !== 'report' &&
inEdgeCohort(edge.config, claims.relayHostId, requestedRegion, claims.sub)
if (edge?.pushes && !toEdge) {
if (edge?.pushes && !toEdge && mayBeOnEdge(edge.config, claims.relayHostId, claims.sub)) {
// Any lane below may re-place a host whose row is on the edge; its devices come back first.
// Hosts that were never in a cohort skip this row read (most asks; the pool is small).
try {
leftEdge = await edge.leaveEdge(identity)
} catch (error) {
@@ -820,7 +822,11 @@ export function createRelayApp(
relayHostId: body.data.relayHostId
}
// A host on the relay edge: the liveness rule below would read its row as no answer.
const onEdge = await operations.edgeAssignments?.edgeAssignment(identity)
const edgeAssignments = operations.edgeAssignments
const onEdge =
edgeAssignments && mayBeOnEdge(edgeAssignments.config, identity.relayHostId, identity.userId)
? await edgeAssignments.edgeAssignment(identity)
: null
if (onEdge) {
return context.json({
v: 1,
@@ -46,462 +46,7 @@ async function setup(
return { database, store }
}
async function setupHeadroomReassignment(): Promise<{
database: RelayDatabase
store: RelayAssignmentStore
source: RelayCellConfig
target: RelayCellConfig
}> {
const database = await openInMemoryRelayDatabase()
databases.push(database)
const store = new RelayAssignmentStore(database, () => 100, {
requireLiveCells: true,
heartbeatTtlMs: 45_000
})
const source = {
...LIMITED_CELL,
id: 'saturated-source',
url: 'https://saturated-source.example.com'
}
const target = {
...LIMITED_CELL,
id: 'available-target',
url: 'https://available-target.example.com'
}
await store.reconcileCells([source, target], true)
await store.recordCellHeartbeat({
cellId: source.id,
cellUrl: source.url,
cellIncarnation: '11111111-1111-4111-8111-111111111111',
startedAt: 50,
ready: true,
observedRequests: 0,
totalConnections: 450,
inFlightConnections: 0,
reservedConnectionUnits: 0,
enforcedConnectionUnits: 450,
connectionHardCap: 600,
connectionUnobservedBound: 50
})
await store.recordCellHeartbeat({
cellId: target.id,
cellUrl: target.url,
cellIncarnation: '22222222-2222-4222-8222-222222222222',
startedAt: 50,
ready: true,
observedRequests: 0,
totalConnections: 0,
inFlightConnections: 0,
reservedConnectionUnits: 0,
enforcedConnectionUnits: 0,
connectionHardCap: 600,
connectionUnobservedBound: 50
})
return { database, store, source, target }
}
describe('relay assignment connection headroom', () => {
it('requires exact, internally consistent telemetry from limited cells', async () => {
const database = await openInMemoryRelayDatabase()
databases.push(database)
const store = new RelayAssignmentStore(database, () => 100)
await store.reconcileCells([LIMITED_CELL], true)
const heartbeat = {
cellId: LIMITED_CELL.id,
cellUrl: LIMITED_CELL.url,
cellIncarnation: '11111111-1111-4111-8111-111111111111',
startedAt: 50,
ready: true,
observedRequests: 0
}
await expect(store.recordCellHeartbeat(heartbeat)).rejects.toThrow(
'cell_connection_telemetry_mismatch'
)
await expect(
store.recordCellHeartbeat({
...heartbeat,
totalConnections: 550,
inFlightConnections: 2,
reservedConnectionUnits: 3,
enforcedConnectionUnits: 554,
connectionHardCap: 600,
connectionUnobservedBound: 50
})
).rejects.toThrow('cell_connection_telemetry_mismatch')
await expect(
store.recordCellHeartbeat({
...heartbeat,
totalConnections: 601,
inFlightConnections: 0,
reservedConnectionUnits: 0,
enforcedConnectionUnits: 601,
connectionHardCap: 600,
connectionUnobservedBound: 50
})
).resolves.toBeUndefined()
})
it('keeps placing against the old cap until the cell reports a raised one', async () => {
const { store } = await setup(449)
const expanded = {
...LIMITED_CELL,
connectionHardCap: 1_000 as const
}
await store.reconcileCells([expanded], true)
await expect(store.cellDeploymentStatus(expanded.id)).resolves.toMatchObject({
connectionCapacity: { hardCap: 1_000, effectiveHardCap: 600, heartbeatFresh: true }
})
await expect(
store.assign({ userId: 'transition-user', relayHostId: 'host000000000099' })
).resolves.toMatchObject({ cellId: expanded.id })
await expect(
store.assign({ userId: 'transition-user-2', relayHostId: 'host000000000096' })
).rejects.toThrow('relay_capacity_exhausted')
await store.recordCellHeartbeat({
cellId: expanded.id,
cellUrl: expanded.url,
cellIncarnation: '22222222-2222-4222-8222-222222222222',
startedAt: 200,
ready: true,
observedRequests: 0,
totalConnections: 449,
inFlightConnections: 0,
reservedConnectionUnits: 0,
enforcedConnectionUnits: 449,
connectionHardCap: 1_000,
connectionUnobservedBound: 50
})
await expect(store.cellDeploymentStatus(expanded.id)).resolves.toMatchObject({
connectionCapacity: {
hardCap: 1_000,
ordinaryConnectionLimit: 900,
normalAdmissionPause: 850,
heartbeatFresh: true
}
})
})
it('fails placement closed while the admin path changes the unobserved bound', async () => {
const { store } = await setup(0)
const lowered = {
...LIMITED_CELL,
connectionUnobservedBound: 49
}
await store.configureCell(lowered, 'general')
await expect(
store.assign({ userId: 'admin-transition', relayHostId: 'host000000000098' })
).rejects.toThrow('relay_capacity_exhausted')
await expect(store.cellDeploymentStatus(lowered.id)).resolves.toMatchObject({
connectionCapacity: { hardCap: 600, heartbeatFresh: false }
})
await store.recordCellHeartbeat({
cellId: lowered.id,
cellUrl: lowered.url,
cellIncarnation: '22222222-2222-4222-8222-222222222222',
startedAt: 200,
ready: true,
observedRequests: 0,
totalConnections: 0,
inFlightConnections: 0,
reservedConnectionUnits: 0,
enforcedConnectionUnits: 0,
connectionHardCap: 600,
connectionUnobservedBound: 49
})
await expect(
store.assign({ userId: 'admin-restored', relayHostId: 'host000000000097' })
).resolves.toMatchObject({ cellId: lowered.id })
})
it('admits exactly one reservation at the admission boundary', async () => {
const { database, store } = await setup(449)
const results = await Promise.allSettled([
store.assign({ userId: 'user-1', relayHostId: 'host000000000001' }),
store.assign({ userId: 'user-2', relayHostId: 'host000000000002' })
])
expect(results.filter(({ status }) => status === 'fulfilled')).toHaveLength(1)
expect(
results
.filter(({ status }) => status === 'rejected')
.map((result) => (result.status === 'rejected' ? result.reason : null))
).toEqual([expect.objectContaining({ message: 'relay_capacity_exhausted' })])
expect(
await database.query(
`SELECT activity_id FROM relay_assignment_activity_leases
WHERE activity_kind = 'control' AND activity_id LIKE 'control-pending:%'`
)
).toHaveLength(1)
})
it('rejects at the boundary before mutating durable assignment state', async () => {
const { database, store } = await setup(450)
await expect(
store.assign({ userId: 'user-1', relayHostId: 'host000000000001' })
).rejects.toThrow('relay_capacity_exhausted')
expect(await database.query(`SELECT * FROM relay_assignments`)).toEqual([])
expect(await database.query(`SELECT * FROM relay_assignment_activity_leases`)).toEqual([])
})
it('charges every active reservation state at the admission boundary', async () => {
const { database, store } = await setup(447)
await database.query(
`INSERT INTO relay_control_connection_reservations
(reservation_id, idempotency_key, user_id, relay_host_id,
assignment_epoch, cell_id, state, created_at, timeout_at, updated_at)
VALUES
('active-reserved', 'active-reserved', 'state-user', 'state-host-1',
1, ?, 'reserved', 1, 2, 1),
('active-debt', 'active-debt', 'state-user', 'state-host-2',
1, ?, 'late-arrival-debt', 1, 2, 1),
('active-claimed', 'active-claimed', 'state-user', 'state-host-3',
1, ?, 'claimed', 1, 2, 1)`,
[LIMITED_CELL.id, LIMITED_CELL.id, LIMITED_CELL.id]
)
await expect(
store.assign({ userId: 'blocked-user', relayHostId: 'blockedhost00001' })
).rejects.toThrow('relay_capacity_exhausted')
expect(await database.query(`SELECT * FROM relay_assignment_activity_leases`)).toEqual([])
})
it('does not charge released reservation history', async () => {
const { database, store } = await setup(449)
await database.query(
`INSERT INTO relay_control_connection_reservations
(reservation_id, idempotency_key, user_id, relay_host_id,
assignment_epoch, cell_id, state, created_at, timeout_at, updated_at)
VALUES ('released-history', 'released-history', 'state-user', 'state-host',
1, ?, 'released', 1, 2, 1)`,
[LIMITED_CELL.id]
)
await expect(
store.assign({ userId: 'admitted-user', relayHostId: 'admittedhost0001' })
).resolves.toMatchObject({ cellId: LIMITED_CELL.id })
})
it('rejects sticky control restoration before mutating assignment state', async () => {
const { database, store } = await setup(450)
const identity = { userId: 'sticky-user', relayHostId: 'stickyhost000001' }
await database.query(
`INSERT INTO relay_assignments
(user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at,
last_activity_at, reserved_controls, reserved_splices, reserved_invites,
pending_installs, pending_confirmations, migration_leases)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[identity.userId, identity.relayHostId, LIMITED_CELL.id, 1, 10_000, 100, 0, 0, 1, 0, 0, 0]
)
await expect(store.assign(identity)).rejects.toThrow('relay_connection_headroom_exhausted')
expect(
await database.query(
`SELECT cell_id, assignment_epoch, reserved_controls, reserved_invites
FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?`,
[identity.userId, identity.relayHostId]
)
).toEqual([
{
cell_id: LIMITED_CELL.id,
assignment_epoch: 1,
reserved_controls: 0,
reserved_invites: 1
}
])
expect(await database.query(`SELECT * FROM relay_assignment_activity_leases`)).toEqual([])
})
it('moves a zero-activity assignment off a general cell without connection headroom', async () => {
const { database, store, source, target } = await setupHeadroomReassignment()
const identity = { userId: 'movable-user', relayHostId: 'movablehost000001' }
await database.query(
`INSERT INTO relay_assignments
(user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at,
last_activity_at, reserved_controls, reserved_splices, reserved_invites,
pending_installs, pending_confirmations, migration_leases)
VALUES (?, ?, ?, ?, ?, ?, 0, 0, 0, 0, 0, 0)`,
[identity.userId, identity.relayHostId, source.id, 7, 10_000, 100]
)
await database.query(
`INSERT INTO relay_control_connection_reservations
(reservation_id, idempotency_key, user_id, relay_host_id,
assignment_epoch, cell_id, state, inclusion_watermark,
claim_activity_id, created_at, timeout_at, claimed_at, released_at,
updated_at)
VALUES (?, ?, ?, ?, ?, ?, 'late-arrival-debt', NULL, NULL, ?, ?, NULL, NULL, ?)`,
[
'superseded-reservation',
'superseded-reservation',
identity.userId,
identity.relayHostId,
7,
source.id,
50,
99,
100
]
)
await expect(store.assign(identity)).resolves.toMatchObject({
cellId: target.id,
assignmentEpoch: 8
})
expect(
await database.query(
`SELECT cell_id, assignment_epoch, reserved_controls
FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?`,
[identity.userId, identity.relayHostId]
)
).toEqual([{ cell_id: target.id, assignment_epoch: 8, reserved_controls: 1 }])
expect(
await database.query(
`SELECT cell_id, activity_kind FROM relay_assignment_activity_leases
WHERE user_id = ? AND relay_host_id = ?`,
[identity.userId, identity.relayHostId]
)
).toEqual([{ cell_id: target.id, activity_kind: 'control' }])
expect(
await database.query(
`SELECT cell_id, assignment_epoch, state
FROM relay_control_connection_reservations
WHERE user_id = ? AND relay_host_id = ?
ORDER BY assignment_epoch`,
[identity.userId, identity.relayHostId]
)
).toEqual([
{ cell_id: source.id, assignment_epoch: 7, state: 'released' },
{ cell_id: target.id, assignment_epoch: 8, state: 'reserved' }
])
})
it('keeps non-control activity pinned when its cell has no connection headroom', async () => {
const { database, store, source } = await setupHeadroomReassignment()
const identity = { userId: 'pinned-user', relayHostId: 'pinnedhost0000001' }
await database.query(
`INSERT INTO relay_assignments
(user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at,
last_activity_at, reserved_controls, reserved_splices, reserved_invites,
pending_installs, pending_confirmations, migration_leases)
VALUES (?, ?, ?, ?, ?, ?, 0, 0, 1, 0, 0, 0)`,
[identity.userId, identity.relayHostId, source.id, 7, 10_000, 100]
)
await expect(store.assign(identity)).rejects.toThrow('relay_connection_headroom_exhausted')
expect(await store.resolve(identity)).toMatchObject({
cellId: source.id,
assignmentEpoch: 7
})
})
it('keeps a zero-activity assignment pinned on an existing-only cell', async () => {
const { database, store, source } = await setupHeadroomReassignment()
const identity = { userId: 'pinned-existing-only-user', relayHostId: 'pinnedexistingonl' }
await store.setCellAdmissionState(source.id, 'existing-only')
await database.query(
`INSERT INTO relay_assignments
(user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at,
last_activity_at, reserved_controls, reserved_splices, reserved_invites,
pending_installs, pending_confirmations, migration_leases)
VALUES (?, ?, ?, ?, ?, ?, 0, 0, 0, 0, 0, 0)`,
[identity.userId, identity.relayHostId, source.id, 7, 10_000, 100]
)
await expect(store.assign(identity)).rejects.toThrow('relay_connection_headroom_exhausted')
expect(await store.resolve(identity)).toMatchObject({
cellId: source.id,
assignmentEpoch: 7
})
expect(await database.query(`SELECT * FROM relay_assignment_activity_leases`)).toEqual([])
})
it('keeps a zero-activity assignment pinned on an unstamped migration-only cell', async () => {
// Why: an evacuation target is deliberately migration-only and deliberately
// full. Without the roll's isolate stamp it must keep the hosts it holds.
const { database, store, source } = await setupHeadroomReassignment()
const identity = { userId: 'pinned-migration-only-user', relayHostId: 'pinnedmigrationonly' }
await store.setCellAdmissionState(source.id, 'migration-only')
await database.query(
`INSERT INTO relay_assignments
(user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at,
last_activity_at, reserved_controls, reserved_splices, reserved_invites,
pending_installs, pending_confirmations, migration_leases)
VALUES (?, ?, ?, ?, ?, ?, 0, 0, 0, 0, 0, 0)`,
[identity.userId, identity.relayHostId, source.id, 7, 10_000, 100]
)
await expect(store.assign(identity)).rejects.toThrow('relay_connection_headroom_exhausted')
expect(await store.resolve(identity)).toMatchObject({
cellId: source.id,
assignmentEpoch: 7
})
})
it('renames a pending reservation exactly once on control activation', async () => {
const { database, store } = await setup(449)
const identity = { userId: 'user-1', relayHostId: 'host000000000001' }
const assignment = await store.assign(identity)
await store.activateControl(identity, {
cellId: LIMITED_CELL.id,
assignmentEpoch: assignment.assignmentEpoch,
generation: 1
})
await store.activateControl(identity, {
cellId: LIMITED_CELL.id,
assignmentEpoch: assignment.assignmentEpoch,
generation: 1
})
expect(
await database.query(
`SELECT activity_id, request_units FROM relay_assignment_activity_leases
WHERE user_id = ? AND relay_host_id = ?`,
[identity.userId, identity.relayHostId]
)
).toEqual([{ activity_id: 'control:limited:1', request_units: 1 }])
})
it('keeps expired pending reservations charged as late-arrival debt', async () => {
let now = 100
const { database, store } = await setup(449, () => now)
await store.assign({ userId: 'user-1', relayHostId: 'host000000000001' })
now += ASSIGNMENT_LIMITS.activityLeaseMs + 1
await store.releaseExpiredActivityLeases()
await store.recordCellHeartbeat({
cellId: LIMITED_CELL.id,
cellUrl: LIMITED_CELL.url,
cellIncarnation: '11111111-1111-4111-8111-111111111111',
startedAt: 50,
ready: true,
observedRequests: 0,
totalConnections: 449,
inFlightConnections: 0,
reservedConnectionUnits: 0,
enforcedConnectionUnits: 449,
connectionHardCap: 600,
connectionUnobservedBound: 50
})
await expect(
store.assign({ userId: 'user-2', relayHostId: 'host000000000002' })
).rejects.toThrow('relay_capacity_exhausted')
expect(
await database.query(
`SELECT activity_id FROM relay_assignment_activity_leases
WHERE activity_kind = 'control' AND activity_id LIKE 'control-pending:%'`
)
).toHaveLength(0)
expect(await database.query(`SELECT state FROM relay_control_connection_reservations`)).toEqual(
[{ state: 'late-arrival-debt' }]
)
})
it('reconciles late-arrival debt only after a covering absolute snapshot', async () => {
let now = 100
const { database, store } = await setup(449, () => now)
@@ -559,386 +104,4 @@ describe('relay assignment connection headroom', () => {
store.assign({ userId: 'blocked-user', relayHostId: 'blockedhost00001' })
).rejects.toThrow('relay_capacity_exhausted')
})
it('rejects duplicate and out-of-order absolute snapshots', async () => {
const { database, store } = await setup(0)
const heartbeat = {
cellId: LIMITED_CELL.id,
cellUrl: LIMITED_CELL.url,
cellIncarnation: '11111111-1111-4111-8111-111111111111',
startedAt: 50,
ready: true,
observedRequests: 0,
totalConnections: 10,
inFlightConnections: 0,
reservedConnectionUnits: 0,
enforcedConnectionUnits: 10,
connectionInclusionWatermark: 10,
connectionHardCap: 600 as const,
connectionUnobservedBound: 50
}
await store.recordCellHeartbeat(heartbeat)
await expect(store.recordCellHeartbeat(heartbeat)).rejects.toThrow('stale_connection_snapshot')
await expect(
store.recordCellHeartbeat({
...heartbeat,
totalConnections: 9,
enforcedConnectionUnits: 9,
connectionInclusionWatermark: 9
})
).rejects.toThrow('stale_connection_snapshot')
expect(
await database.query(
`SELECT inclusion_watermark, enforced_connection_units
FROM relay_cell_connection_snapshots`
)
).toEqual([{ inclusion_watermark: 10, enforced_connection_units: 10 }])
})
it('keeps crash retries bound to one reservation claim', async () => {
let now = 100
const { database, store } = await setup(448, () => now)
const identity = { userId: 'retry-user', relayHostId: 'retryhost0000001' }
const assignment = await store.assign(identity)
await new RelayAssignmentStore(database, () => now, {
requireLiveCells: true,
heartbeatTtlMs: 45_000
}).assign(identity)
expect(await database.query(`SELECT state FROM relay_control_connection_reservations`)).toEqual(
[{ state: 'reserved' }]
)
now += ASSIGNMENT_LIMITS.activityLeaseMs + 1
await store.releaseExpiredActivityLeases()
await store.recordCellHeartbeat({
cellId: LIMITED_CELL.id,
cellUrl: LIMITED_CELL.url,
cellIncarnation: '11111111-1111-4111-8111-111111111111',
startedAt: 50,
ready: true,
observedRequests: 0,
totalConnections: 448,
inFlightConnections: 0,
reservedConnectionUnits: 0,
enforcedConnectionUnits: 448,
connectionHardCap: 600,
connectionUnobservedBound: 50
})
await store.assign(identity)
const restarted = new RelayAssignmentStore(database, () => now, {
requireLiveCells: true,
heartbeatTtlMs: 45_000
})
const activation = {
cellId: LIMITED_CELL.id,
assignmentEpoch: assignment.assignmentEpoch,
generation: 1,
connectionInclusionWatermark: 5
}
await restarted.activateControl(identity, activation)
await restarted.activateControl(identity, activation)
expect(
await database.query(
`SELECT state, claim_activity_id
FROM relay_control_connection_reservations
ORDER BY created_at ASC, reservation_id ASC`
)
).toEqual([{ state: 'claimed', claim_activity_id: 'control:limited:1' }])
})
it('releases only redundant expired debt after a fresh absolute snapshot', async () => {
let now = 100
const { database, store } = await setup(449, () => now)
const identity = { userId: 'debt-user', relayHostId: 'debthost000000001' }
const assignment = await store.assign(identity)
now += ASSIGNMENT_LIMITS.activityLeaseMs + 1
await store.releaseExpiredActivityLeases()
await database.query(
`INSERT INTO relay_control_connection_reservations
(reservation_id, idempotency_key, user_id, relay_host_id,
assignment_epoch, cell_id, state, inclusion_watermark,
claim_activity_id, created_at, timeout_at, claimed_at, released_at,
updated_at)
VALUES (?, ?, ?, ?, ?, ?, 'late-arrival-debt', NULL, NULL, ?, ?, NULL, NULL, ?)`,
[
'duplicate-reservation',
'duplicate-reservation',
identity.userId,
identity.relayHostId,
assignment.assignmentEpoch,
LIMITED_CELL.id,
101,
now - 1,
now
]
)
await store.recordCellHeartbeat({
cellId: LIMITED_CELL.id,
cellUrl: LIMITED_CELL.url,
cellIncarnation: '11111111-1111-4111-8111-111111111111',
startedAt: 50,
ready: true,
observedRequests: 0,
totalConnections: 449,
inFlightConnections: 0,
reservedConnectionUnits: 0,
enforcedConnectionUnits: 449,
connectionInclusionWatermark: 5,
connectionHardCap: 600,
connectionUnobservedBound: 50
})
expect(
await database.query(
`SELECT state, COUNT(*) AS count
FROM relay_control_connection_reservations
GROUP BY state ORDER BY state`
)
).toEqual([
{ state: 'late-arrival-debt', count: 1 },
{ state: 'released', count: 1 }
])
})
it('releases expired debt for a snapshot-proven aborted older epoch', async () => {
const now = 1_000
const { database, store } = await setup(0, () => now)
const identity = { userId: 'aborted-user', relayHostId: 'abortedhost00001' }
await database.query(
`INSERT INTO relay_assignments
(user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at,
last_activity_at, reserved_controls, reserved_splices, reserved_invites,
pending_installs, pending_confirmations, migration_leases)
VALUES (?, ?, ?, ?, ?, ?, 0, 0, 0, 0, 0, 0)`,
[identity.userId, identity.relayHostId, LIMITED_CELL.id, 3, now, now]
)
await database.query(
`INSERT INTO relay_assignment_migrations
(user_id, relay_host_id, source_cell_id, target_cell_id,
previous_epoch, assignment_epoch, source_request_units,
target_reserved_units, expires_at, target_registered_at,
completed_at, aborted_at, created_at, updated_at)
VALUES (?, ?, ?, ?, 1, 2, 0, 1, ?, ?, NULL, ?, ?, ?)`,
[
identity.userId,
identity.relayHostId,
'source',
LIMITED_CELL.id,
now - 2,
now - 3,
now - 1,
now - 4,
now - 1
]
)
await database.query(
`INSERT INTO relay_control_connection_reservations
(reservation_id, idempotency_key, user_id, relay_host_id,
assignment_epoch, cell_id, state, inclusion_watermark,
claim_activity_id, created_at, timeout_at, claimed_at, released_at,
updated_at)
VALUES (?, ?, ?, ?, 2, ?, 'late-arrival-debt', NULL, NULL, ?, ?, NULL, NULL, ?)`,
[
'aborted-reservation',
'aborted-reservation',
identity.userId,
identity.relayHostId,
LIMITED_CELL.id,
now - 4,
now - 2,
now - 1
]
)
await store.recordCellHeartbeat({
cellId: LIMITED_CELL.id,
cellUrl: LIMITED_CELL.url,
cellIncarnation: '11111111-1111-4111-8111-111111111111',
startedAt: 50,
ready: true,
observedRequests: 0,
totalConnections: 0,
inFlightConnections: 0,
reservedConnectionUnits: 0,
enforcedConnectionUnits: 0,
connectionInclusionWatermark: 5,
connectionHardCap: 600,
connectionUnobservedBound: 50
})
expect(
await database.query(
`SELECT state FROM relay_control_connection_reservations
WHERE reservation_id = ?`,
['aborted-reservation']
)
).toEqual([{ state: 'released' }])
})
it('fails a limited cell closed on stale telemetry while leaving legacy cells unchanged', async () => {
let now = 100
const { store } = await setup(0, () => now)
now += 45_001
await expect(
store.assign({ userId: 'user-1', relayHostId: 'host000000000001' })
).rejects.toThrow('relay_capacity_exhausted')
const legacyDatabase = await openInMemoryRelayDatabase()
databases.push(legacyDatabase)
const legacyStore = new RelayAssignmentStore(legacyDatabase, () => now, {
requireLiveCells: true,
heartbeatTtlMs: 45_000
})
const legacy = {
id: 'legacy',
url: 'https://legacy.example.com',
capacityRequests: 10
}
await legacyStore.reconcileCells([legacy], true)
await legacyStore.recordCellHeartbeat({
cellId: legacy.id,
cellUrl: legacy.url,
cellIncarnation: '22222222-2222-4222-8222-222222222222',
startedAt: now,
ready: true,
observedRequests: 0
})
await expect(
legacyStore.assign({ userId: 'user-2', relayHostId: 'host000000000002' })
).resolves.toMatchObject({ cellId: 'legacy' })
})
it('does not create connection debt for mixed-version uncapped cells', async () => {
let now = 100
const legacy = {
id: 'legacy',
url: 'https://legacy.example.com',
capacityRequests: 10
}
const { database, store } = await setup(0, () => now)
await store.reconcileCells([legacy], true)
await store.recordCellHeartbeat({
cellId: legacy.id,
cellUrl: legacy.url,
cellIncarnation: '22222222-2222-4222-8222-222222222222',
startedAt: 50,
ready: true,
observedRequests: 0
})
await store.assign({ userId: 'legacy-user', relayHostId: 'legacyhost000001' })
expect(await database.query(`SELECT * FROM relay_control_connection_reservations`)).toEqual([])
expect(await store.releaseExpiredActivityLeases()).toBe(0)
now += ASSIGNMENT_LIMITS.activityLeaseMs + 1
expect(await store.releaseExpiredActivityLeases()).toBe(1)
expect(await database.query(`SELECT * FROM relay_control_connection_reservations`)).toEqual([])
})
it('rejects dormant rebalance before changing the assignment epoch', async () => {
const now = ASSIGNMENT_LIMITS.dormantTtlMs + 100
const database = await openInMemoryRelayDatabase()
databases.push(database)
const store = new RelayAssignmentStore(database, () => now, {
requireLiveCells: true,
heartbeatTtlMs: 45_000
})
const source = {
id: 'source',
url: 'https://source.example.com',
capacityRequests: 10
}
await store.reconcileCells([source, LIMITED_CELL], true)
await store.recordCellHeartbeat({
cellId: source.id,
cellUrl: source.url,
cellIncarnation: '22222222-2222-4222-8222-222222222222',
startedAt: now - 50,
ready: true,
observedRequests: 0
})
await store.recordCellHeartbeat({
cellId: LIMITED_CELL.id,
cellUrl: LIMITED_CELL.url,
cellIncarnation: '11111111-1111-4111-8111-111111111111',
startedAt: now - 50,
ready: true,
observedRequests: 0,
totalConnections: 450,
inFlightConnections: 0,
reservedConnectionUnits: 0,
enforcedConnectionUnits: 450,
connectionHardCap: 600,
connectionUnobservedBound: 50
})
const identity = { userId: 'dormant-user', relayHostId: 'dormanthost00001' }
await database.query(
`INSERT INTO relay_assignments
(user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at,
last_activity_at, reserved_controls, reserved_splices, reserved_invites,
pending_installs, pending_confirmations, migration_leases)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[identity.userId, identity.relayHostId, source.id, 7, 0, 0, 0, 0, 0, 0, 0, 0]
)
await expect(store.rebalanceDormant(identity, LIMITED_CELL.id)).rejects.toThrow(
'relay_connection_headroom_exhausted'
)
expect(await store.resolve(identity)).toMatchObject({
cellId: source.id,
assignmentEpoch: 7
})
expect(await database.query(`SELECT * FROM relay_assignment_activity_leases`)).toEqual([])
})
it('rejects an evacuation target at its pause before migration mutation', async () => {
const database = await openInMemoryRelayDatabase()
databases.push(database)
const store = new RelayAssignmentStore(database, () => 100, {
requireLiveCells: true,
heartbeatTtlMs: 45_000
})
const source = {
id: 'source',
url: 'https://source.example.com',
capacityRequests: 10
}
await store.reconcileCells([source, { ...LIMITED_CELL, initiallyEnabled: false }], true)
await store.recordCellHeartbeat({
cellId: source.id,
cellUrl: source.url,
cellIncarnation: '22222222-2222-4222-8222-222222222222',
startedAt: 50,
ready: true,
observedRequests: 0
})
await store.recordCellHeartbeat({
cellId: LIMITED_CELL.id,
cellUrl: LIMITED_CELL.url,
cellIncarnation: '11111111-1111-4111-8111-111111111111',
startedAt: 50,
ready: true,
observedRequests: 0,
totalConnections: 450,
inFlightConnections: 0,
reservedConnectionUnits: 0,
enforcedConnectionUnits: 450,
connectionHardCap: 600,
connectionUnobservedBound: 50
})
const identity = { userId: 'user-1', relayHostId: 'host000000000001' }
const assignment = await store.assign(identity)
expect(assignment.cellId).toBe(source.id)
await store.setCellEnabled(LIMITED_CELL.id, true)
await expect(store.startEvacuation(identity, LIMITED_CELL.id)).rejects.toThrow(
'relay_connection_headroom_exhausted'
)
expect(await database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([])
expect(await store.resolve(identity)).toMatchObject({
cellId: source.id,
assignmentEpoch: assignment.assignmentEpoch
})
})
})
@@ -1,4 +1,3 @@
import { ASSIGNMENT_LIMITS } from '@orca-cloud/relay-contract/assignment-invariants'
import { createHash } from 'node:crypto'
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
import { RelayAssignmentRowBusyError, RelayAssignmentStore } from './assignment-store.js'
@@ -52,7 +51,6 @@ const OTHER_REGION: RelayCellConfig = {
...CAPPED
}
const CELLS = [ISOLATED, ...TARGETS, OTHER_REGION]
const HOST_COUNT = 50
function hostIdentity(index: number): { userId: string; relayHostId: string } {
return {
@@ -74,48 +72,6 @@ describePostgres('PostgreSQL re-placement off a cell isolated for a roll', () =>
return Number(rows[0]!['reserved_requests'])
}
// The accounting invariant the migration paths assert: a cell's counter is
// exactly the units of the leases held on it.
async function expectReservationAccounting(): Promise<void> {
for (const cell of CELLS) {
const leased = await databases[0]!.query(
`SELECT COALESCE(SUM(request_units), 0) AS units
FROM relay_assignment_activity_leases WHERE cell_id = ?`,
[cell.id]
)
expect({ cell: cell.id, reserved: await reservedRequests(cell.id) }).toEqual({
cell: cell.id,
reserved: Number(leased[0]!['units'])
})
}
}
async function expectReservationAccountingExcept(cellId: string): Promise<void> {
for (const cell of CELLS.filter(({ id }) => id !== cellId)) {
const leased = await databases[0]!.query(
`SELECT COALESCE(SUM(request_units), 0) AS units
FROM relay_assignment_activity_leases WHERE cell_id = ?`,
[cell.id]
)
expect(await reservedRequests(cell.id)).toBe(Number(leased[0]!['units']))
}
}
async function counters(identity: {
userId: string
relayHostId: string
}): Promise<{ controls: number; splices: number }> {
const rows = await databases[0]!.query(
`SELECT reserved_controls, reserved_splices FROM relay_assignments
WHERE user_id = ? AND relay_host_id = ?`,
[identity.userId, identity.relayHostId]
)
return {
controls: Number(rows[0]!['reserved_controls']),
splices: Number(rows[0]!['reserved_splices'])
}
}
// Holds the named relay_cells rows in another session until released, the
// way a release from a far cell holds its row across a round trip.
async function holdCellRows(cellIds: string[]): Promise<() => Promise<void>> {
@@ -144,40 +100,18 @@ describePostgres('PostgreSQL re-placement off a cell isolated for a roll', () =>
}
async function waitForLock(table: 'relay_cells' | 'relay_assignments'): Promise<void> {
await vi.waitFor(async () => {
const rows = await databases[0]!.query(
`SELECT COUNT(*) AS waiting FROM pg_stat_activity
await vi.waitFor(
async () => {
const rows = await databases[0]!.query(
`SELECT COUNT(*) AS waiting FROM pg_stat_activity
WHERE datname = current_database() AND wait_event_type = 'Lock'
AND application_name = ? AND query LIKE ? AND query LIKE '%FOR UPDATE%'`,
[databaseApplicationName(1), `%${table}%`]
)
expect(Number(rows[0]?.['waiting'])).toBeGreaterThan(0)
}, { timeout: 4_000, interval: 10 })
}
// Puts a host on the source with a live control and a splice, then isolates
// the source for a roll with both targets open.
async function seedActiveHostOnIsolatedSource(index: number): Promise<{
identity: { userId: string; relayHostId: string }
first: { cellId: string; assignmentEpoch: number }
}> {
const identity = hostIdentity(index)
await applySelector({ [TARGETS[0]!.id]: 'migration-only', [TARGETS[1]!.id]: 'migration-only' })
const first = await stores[0]!.assign(identity, 'us-central1')
expect(first.cellId).toBe(ISOLATED.id)
await stores[0]!.activateControl(identity, {
cellId: ISOLATED.id,
assignmentEpoch: first.assignmentEpoch,
generation: 1
})
await stores[0]!.acquireActivity(identity, {
activityId: 'splice:keep-1',
kind: 'splice',
cellId: ISOLATED.id
})
await applySelector({ [TARGETS[0]!.id]: 'general', [TARGETS[1]!.id]: 'general' })
await applySelector({ [ISOLATED.id]: 'migration-only' }, [ISOLATED.id])
return { identity, first }
[databaseApplicationName(1), `%${table}%`]
)
expect(Number(rows[0]?.['waiting'])).toBeGreaterThan(0)
},
{ timeout: 4_000, interval: 10 }
)
}
// `enforced` puts a cell at its connection cap, which leaves it no headroom.
@@ -211,9 +145,7 @@ describePostgres('PostgreSQL re-placement off a cell isolated for a roll', () =>
const current = await stores[0]!.inspectCellAdmissionSelector()
// Built from relay_cells, not from the selector's own membership: the apply
// requires exact coverage of the fleet, and this database is shared.
const fleet = await databases[0]!.query(
`SELECT cell_id FROM relay_cells ORDER BY cell_id ASC`
)
const fleet = await databases[0]!.query(`SELECT cell_id FROM relay_cells ORDER BY cell_id ASC`)
const membership: CellAdmissionMembership = {
existingOnly: [],
migrationOnly: [],
@@ -251,15 +183,6 @@ describePostgres('PostgreSQL re-placement off a cell isolated for a roll', () =>
})
}
async function rollIsolatedAt(cellId: string): Promise<number | null> {
const rows = await databases[0]!.query(
`SELECT roll_isolated_at FROM relay_cell_admission WHERE cell_id = ?`,
[cellId]
)
const value = rows[0]?.['roll_isolated_at']
return value === undefined || value === null ? null : Number(value)
}
// Every case starts from the whole fleet general; a case that leaves a cell
// isolated would otherwise starve the next one of placement candidates.
async function resetFleet(): Promise<void> {
@@ -301,11 +224,13 @@ describePostgres('PostgreSQL re-placement off a cell isolated for a roll', () =>
// Four connections so the concurrent dials below really contend on the
// fleet-wide relay_cells lock rather than queueing in one client.
for (let index = 0; index < 4; index += 1) {
databases.push(await openRelayDatabase({
databaseUrl,
dataDir: '',
applicationName: databaseApplicationName(index)
}))
databases.push(
await openRelayDatabase({
databaseUrl,
dataDir: '',
applicationName: databaseApplicationName(index)
})
)
}
stores = databases.map(
(database) =>
@@ -344,129 +269,6 @@ describePostgres('PostgreSQL re-placement off a cell isolated for a roll', () =>
for (const connection of databases) await connection.close()
})
it('stamps only the named cell on isolate and clears it on restore', async () => {
await resetFleet()
expect(await rollIsolatedAt(ISOLATED.id)).toBeNull()
await applySelector({ [ISOLATED.id]: 'migration-only' }, [ISOLATED.id])
const stamped = await rollIsolatedAt(ISOLATED.id)
expect(stamped).toBe(NOW)
// Cells the isolate did not name stay unmarked even when parked in the same
// apply: that is every non-roll flow, and its hosts must keep their pin.
await applySelector({ [TARGETS[0]!.id]: 'migration-only' })
expect(await rollIsolatedAt(TARGETS[0]!.id)).toBeNull()
// A failed wave re-isolates rather than restoring; the stamp survives, and
// does not move, so the hosts left behind stay eligible.
await applySelector({ [ISOLATED.id]: 'migration-only' }, [ISOLATED.id])
expect(await rollIsolatedAt(ISOLATED.id)).toBe(stamped)
// Restore writes 'general', and the same statement clears the stamp.
await applySelector({ [ISOLATED.id]: 'general' })
expect(await rollIsolatedAt(ISOLATED.id)).toBeNull()
}, 30_000)
it('classifies a reconnect by its home cell’s stamp in the verification read', async () => {
await resetFleet()
const identity = hostIdentity(903)
const classify = { classifyHomeRollIsolation: true }
await applySelector({ [TARGETS[0]!.id]: 'migration-only', [TARGETS[1]!.id]: 'migration-only' })
const first = await stores[0]!.assign(identity, 'us-central1')
await applySelector({ [TARGETS[0]!.id]: 'general', [TARGETS[1]!.id]: 'general' })
expect(first.cellId).toBe(ISOLATED.id)
expect(await stores[0]!.resolve(identity, classify)).not.toHaveProperty('homeCellRollIsolated')
await applySelector({ [ISOLATED.id]: 'migration-only' }, [ISOLATED.id])
expect(await stores[0]!.resolve(identity, classify)).toMatchObject({
cellId: ISOLATED.id,
homeCellRollIsolated: true
})
await applySelector({ [ISOLATED.id]: 'general' })
expect(await stores[0]!.resolve(identity, classify)).not.toHaveProperty('homeCellRollIsolated')
}, 30_000)
it('ignores a stamp older than the roll it is supposed to describe', async () => {
// A failed wave keeps its stamp on purpose and can sit for hours; past the
// bound the cell stops shedding hosts one dial at a time.
await resetFleet()
const identity = hostIdentity(902)
const first = await stores[0]!.assign(identity, 'us-central1')
await applySelector({ [ISOLATED.id]: 'migration-only' }, [ISOLATED.id])
await databases[0]!.query(
`UPDATE relay_cell_admission SET roll_isolated_at = ? WHERE cell_id = ?`,
[NOW - (2 * 60 * 60_000 + 1), ISOLATED.id]
)
expect(await stores[0]!.assign(identity, 'us-central1')).toMatchObject({
cellId: first.cellId,
assignmentEpoch: first.assignmentEpoch
})
}, 30_000)
it('re-places every host off an isolated cell without leaking a reservation', async () => {
await resetFleet()
const identities = Array.from({ length: HOST_COUNT }, (_, index) => hostIdentity(index))
const sourceBaseline = await reservedRequests(ISOLATED.id)
const targetBaseline =
(await reservedRequests(TARGETS[0]!.id)) + (await reservedRequests(TARGETS[1]!.id))
// Everyone lands on the cell about to be isolated.
await applySelector({ [TARGETS[0]!.id]: 'migration-only', [TARGETS[1]!.id]: 'migration-only' })
const first = new Map<string, { cellId: string; assignmentEpoch: number }>()
for (const identity of identities) {
const grant = await stores[0]!.assign(identity, 'us-central1')
expect(grant.cellId).toBe(ISOLATED.id)
first.set(identity.relayHostId, grant)
}
await applySelector({ [TARGETS[0]!.id]: 'general', [TARGETS[1]!.id]: 'general' })
// The isolate step. The state and the stamp are written by one UPDATE under
// the fleet-wide relay_cells lock, so there is no torn state to race against.
await applySelector({ [ISOLATED.id]: 'migration-only' }, [ISOLATED.id])
expect(await rollIsolatedAt(ISOLATED.id)).not.toBeNull()
const grants = await Promise.all(
identities.map(
async (identity, index) =>
await stores[1 + (index % (stores.length - 1))]!.assign(identity, 'us-central1')
)
)
for (const [index, grant] of grants.entries()) {
const identity = identities[index]!
expect(grant.cellId).not.toBe(ISOLATED.id)
expect(TARGETS.map(({ id }) => id)).toContain(grant.cellId)
// Exactly once: a double bump would mean two transactions both moved it.
expect(grant.assignmentEpoch).toBe(first.get(identity.relayHostId)!.assignmentEpoch + 1)
}
// The placement leaves the source row alone: each host's pending control
// there still counts until the source releases it.
expect(await reservedRequests(ISOLATED.id)).toBe(sourceBaseline + HOST_COUNT)
expect(
(await reservedRequests(TARGETS[0]!.id)) + (await reservedRequests(TARGETS[1]!.id))
).toBe(targetBaseline + HOST_COUNT)
await expectReservationAccounting()
for (const identity of identities) {
expect(
await stores[0]!.releaseActivity(
identity,
`control-pending:${first.get(identity.relayHostId)!.assignmentEpoch}`
)
).toBe(true)
}
expect(await reservedRequests(ISOLATED.id)).toBe(sourceBaseline)
await expectReservationAccounting()
const rows = await databases[0]!.query(
`SELECT COUNT(*) AS count FROM relay_assignments
WHERE user_id LIKE '${USER_PREFIX}-%' AND cell_id = ?`,
[ISOLATED.id]
)
expect(Number(rows[0]!['count'])).toBe(0)
}, 60_000)
it('lets exactly one of a host’s racing dials win the re-placement', async () => {
await resetFleet()
const identity = hostIdentity(900)
@@ -486,9 +288,7 @@ describePostgres('PostgreSQL re-placement off a cell isolated for a roll', () =>
stores[1]!.assign(identity, 'us-central1'),
stores[2]!.assign(identity, 'us-central1')
])
const granted = raced.flatMap((result) =>
result.status === 'fulfilled' ? [result.value] : []
)
const granted = raced.flatMap((result) => (result.status === 'fulfilled' ? [result.value] : []))
expect(granted.length).toBeGreaterThan(0)
// Concurrent dials may grant repeatedly but commit one move: one epoch/unit on target, preserving source leases until release.
@@ -502,399 +302,6 @@ describePostgres('PostgreSQL re-placement off a cell isolated for a roll', () =>
).toBe(targetBaseline + 1)
}, 30_000)
it('grants no host the isolated cell after the admission flip commits', async () => {
await resetFleet()
const identity = hostIdentity(901)
const first = await stores[0]!.assign(identity, 'us-central1')
await applySelector({ [ISOLATED.id]: 'migration-only' }, [ISOLATED.id])
for (let dial = 0; dial < 5; dial += 1) {
const grant = await stores[1 + (dial % (stores.length - 1))]!.assign(
identity,
'us-central1'
)
expect(grant.cellId).not.toBe(ISOLATED.id)
}
// Only the first dial re-places; the rest are ordinary sticky re-grants.
expect((await stores[0]!.resolve(identity))?.assignmentEpoch).toBe(
first.assignmentEpoch + 1
)
}, 30_000)
it('leaves the source row to the source’s own releases and keeps the host’s counters', async () => {
await resetFleet()
const { identity, first } = await seedActiveHostOnIsolatedSource(910)
const sourceBefore = await reservedRequests(ISOLATED.id)
const targetsBefore =
(await reservedRequests(TARGETS[0]!.id)) + (await reservedRequests(TARGETS[1]!.id))
expect(sourceBefore).toBe(3)
expect(await counters(identity)).toEqual({ controls: 1, splices: 1 })
const moved = await stores[1]!.assign(identity, 'us-central1')
expect(TARGETS.map(({ id }) => id)).toContain(moved.cellId)
expect(moved.assignmentEpoch).toBe(first.assignmentEpoch + 1)
expect(await reservedRequests(ISOLATED.id)).toBe(sourceBefore)
expect(
(await reservedRequests(TARGETS[0]!.id)) + (await reservedRequests(TARGETS[1]!.id))
).toBe(targetsBefore + 1)
// One control added on the target; the source's control and splice kept.
expect(await counters(identity)).toEqual({ controls: 2, splices: 1 })
await expectReservationAccounting()
// The source closes the host's sockets: each release takes its own units.
expect(await stores[0]!.releaseActivity(identity, `control:${ISOLATED.id}:1`)).toBe(true)
expect(await reservedRequests(ISOLATED.id)).toBe(sourceBefore - 1)
expect(await counters(identity)).toEqual({ controls: 1, splices: 1 })
expect(await stores[0]!.releaseActivity(identity, 'splice:keep-1')).toBe(true)
expect(await reservedRequests(ISOLATED.id)).toBe(0)
// The target's control survives the source's releases.
expect(await counters(identity)).toEqual({ controls: 1, splices: 0 })
await expectReservationAccounting()
}, 30_000)
it('re-places an isolated incumbent while the source row is held', async () => {
await resetFleet()
const { identity, first } = await seedActiveHostOnIsolatedSource(911)
const sourceBefore = await reservedRequests(ISOLATED.id)
const release = await holdCellRows([ISOLATED.id])
try {
// Held far past the 500ms bounded wait: a placement that asked for the
// source row could not finish inside this window.
const moved = await Promise.race([
stores[1]!.assign(identity, 'us-central1'),
new Promise<'blocked'>((resolve) => setTimeout(() => resolve('blocked'), 3_000))
])
expect(moved).not.toBe('blocked')
expect(moved).toMatchObject({ assignmentEpoch: first.assignmentEpoch + 1 })
} finally {
await release()
}
expect(await reservedRequests(ISOLATED.id)).toBe(sourceBefore)
await expectReservationAccounting()
}, 30_000)
it('waits for the target rows it increments', async () => {
await resetFleet()
const { identity, first } = await seedActiveHostOnIsolatedSource(912)
const targetsBefore =
(await reservedRequests(TARGETS[0]!.id)) + (await reservedRequests(TARGETS[1]!.id))
const release = await holdCellRows(TARGETS.map(({ id }) => id))
const placement = stores[1]!.assign(identity, 'us-central1')
try {
await waitForLock('relay_cells')
} finally {
await release()
await placement.catch(() => undefined)
}
expect(await placement).toMatchObject({ assignmentEpoch: first.assignmentEpoch + 1 })
expect(
(await reservedRequests(TARGETS[0]!.id)) + (await reservedRequests(TARGETS[1]!.id))
).toBe(targetsBefore + 1)
await expectReservationAccounting()
}, 30_000)
it('keeps the pin when no general cell in any region has headroom', async () => {
await resetFleet()
const { identity, first } = await seedActiveHostOnIsolatedSource(913)
const sourceBefore = await reservedRequests(ISOLATED.id)
await databases[0]!.query(
`UPDATE relay_cells SET reserved_requests = capacity_requests WHERE cell_id IN (?, ?, ?)`,
[...TARGETS, OTHER_REGION].map(({ id }) => id)
)
try {
expect(await stores[1]!.assign(identity, 'us-central1')).toMatchObject({
cellId: ISOLATED.id,
assignmentEpoch: first.assignmentEpoch
})
expect(await reservedRequests(ISOLATED.id)).toBe(sourceBefore)
expect(await counters(identity)).toEqual({ controls: 1, splices: 1 })
} finally {
await databases[0]!.query(
`UPDATE relay_cells SET reserved_requests = 0 WHERE cell_id IN (?, ?, ?)`,
[...TARGETS, OTHER_REGION].map(({ id }) => id)
)
}
}, 30_000)
it('moves to another region when its own is at the connection cap, without the source row', async () => {
await resetFleet()
const { identity, first } = await seedActiveHostOnIsolatedSource(917)
const sourceBefore = await reservedRequests(ISOLATED.id)
await heartbeatAll(Object.fromEntries(TARGETS.map(({ id }) => [id, 600])))
const release = await holdCellRows([ISOLATED.id])
try {
const moved = await Promise.race([
stores[1]!.assign(identity, 'us-central1'),
new Promise<'blocked'>((resolve) => setTimeout(() => resolve('blocked'), 3_000))
])
expect(moved).toMatchObject({
cellId: OTHER_REGION.id,
region: 'asia-east2',
assignmentEpoch: first.assignmentEpoch + 1
})
} finally {
await release()
await heartbeatAll()
}
expect(await reservedRequests(ISOLATED.id)).toBe(sourceBefore)
expect(await reservedRequests(OTHER_REGION.id)).toBe(1)
await expectReservationAccounting()
}, 30_000)
it('places a dormant host without asking for its old cell row', async () => {
await resetFleet()
const identity = hostIdentity(914)
await applySelector({ [TARGETS[0]!.id]: 'migration-only', [TARGETS[1]!.id]: 'migration-only' })
const first = await stores[0]!.assign(identity, 'us-central1')
expect(first.cellId).toBe(ISOLATED.id)
// Dormant: no units held and no activity inside the dormancy window.
await databases[0]!.query(
`DELETE FROM relay_assignment_activity_leases WHERE user_id = ? AND relay_host_id = ?`,
[identity.userId, identity.relayHostId]
)
await databases[0]!.query(
`UPDATE relay_assignments SET reserved_controls = 0, last_activity_at = ?
WHERE user_id = ? AND relay_host_id = ?`,
[NOW - ASSIGNMENT_LIMITS.dormantTtlMs, identity.userId, identity.relayHostId]
)
await databases[0]!.query(`UPDATE relay_cells SET reserved_requests = 0 WHERE cell_id = ?`, [
ISOLATED.id
])
await applySelector({ [TARGETS[0]!.id]: 'general', [TARGETS[1]!.id]: 'general' })
await applySelector({ [ISOLATED.id]: 'migration-only' }, [ISOLATED.id])
const release = await holdCellRows([ISOLATED.id])
try {
const moved = await Promise.race([
stores[1]!.assign(identity, 'us-central1'),
new Promise<'blocked'>((resolve) => setTimeout(() => resolve('blocked'), 3_000))
])
expect(moved).toMatchObject({ assignmentEpoch: first.assignmentEpoch + 1 })
expect(TARGETS.map(({ id }) => id)).toContain(moved === 'blocked' ? moved : moved.cellId)
} finally {
await release()
}
await expectReservationAccounting()
}, 30_000)
// Moves a seeded host onto TARGETS[0] next to another host whose splice there
// outlives the test, so an over-charge shows instead of clamping at zero.
async function seedMovedHostBesideNeighbour(index: number): Promise<{
identity: { userId: string; relayHostId: string }
neighbour: { userId: string; relayHostId: string }
}> {
const { identity } = await seedActiveHostOnIsolatedSource(index)
await applySelector({ [TARGETS[1]!.id]: 'migration-only' })
const neighbour = hostIdentity(index + 50)
expect((await stores[0]!.assign(neighbour, 'us-central1')).cellId).toBe(TARGETS[0]!.id)
await stores[0]!.acquireActivity(neighbour, {
activityId: 'splice:neighbour',
kind: 'splice',
cellId: TARGETS[0]!.id,
expiresAt: NOW + 10 * 60 * 60_000
})
expect((await stores[1]!.assign(identity, 'us-central1')).cellId).toBe(TARGETS[0]!.id)
expect(await counters(identity)).toEqual({ controls: 2, splices: 1 })
await expectReservationAccounting()
return { identity, neighbour }
}
it('leaves a host with leases on two cells to the lease sweep', async () => {
await resetFleet()
const { identity } = await seedMovedHostBesideNeighbour(915)
// Past every lease but the neighbour's splice.
const later = new RelayAssignmentStore(databases[0]!, () => NOW + 60 * 60_000, {
requireLiveCells: true,
heartbeatTtlMs: 45_000
})
try {
// Aggregate expiry first, with the source's leases still present: the
// order a lease sweep skipped on a busy row leaves behind.
await later.releaseExpiredActivity()
expect(await counters(identity)).toEqual({ controls: 2, splices: 1 })
await expectReservationAccounting()
await later.releaseExpiredActivityLeases()
await later.releaseExpiredActivity()
expect(await counters(identity)).toEqual({ controls: 0, splices: 0 })
expect(await reservedRequests(ISOLATED.id)).toBe(0)
// Only the neighbour's splice is left on the target.
expect(await reservedRequests(TARGETS[0]!.id)).toBe(2)
await expectReservationAccounting()
} finally {
await applySelector({ [TARGETS[1]!.id]: 'general' })
}
}, 30_000)
it('frees the source leases on their own cell when the target dies', async () => {
await resetFleet()
const { identity } = await seedMovedHostBesideNeighbour(916)
// The roll finishes, then the target stops heartbeating before the source
// has released the host. Uncapped, so no fence is needed to move off it.
await applySelector({ [ISOLATED.id]: 'general' })
await databases[0]!.query(`UPDATE relay_cell_runtime SET ready = 0 WHERE cell_id = ?`, [
TARGETS[0]!.id
])
await databases[0]!.query(`DELETE FROM relay_cell_connection_limits WHERE cell_id = ?`, [
TARGETS[0]!.id
])
try {
const moved = await stores[1]!.assign(identity, 'us-central1')
expect(moved.cellId).toBe(ISOLATED.id)
expect(await counters(identity)).toEqual({ controls: 1, splices: 0 })
// The deleted source leases took their units with them; a late release
// from the source finds nothing and charges nothing.
expect(await stores[0]!.releaseActivity(identity, `control:${ISOLATED.id}:1`)).toBe(false)
expect(await reservedRequests(ISOLATED.id)).toBe(1)
expect(await reservedRequests(TARGETS[0]!.id)).toBe(3)
await expectReservationAccounting()
} finally {
// Re-registers the connection limit, then the heartbeat restores ready.
await stores[0]!.reconcileCells(CELLS, false)
await heartbeatAll()
await applySelector({ [TARGETS[1]!.id]: 'general' })
}
}, 30_000)
// A host main's old placement left behind: its counters were reset while its
// source lease stayed, and the lease's release floored them at zero.
async function seedDriftedHost(
index: number,
counted: { controls: number; unbackedSourceUnits: number }
): Promise<{ identity: { userId: string; relayHostId: string }; epoch: number }> {
const identity = hostIdentity(index)
await applySelector({ [TARGETS[0]!.id]: 'migration-only', [TARGETS[1]!.id]: 'migration-only' })
const first = await stores[0]!.assign(identity, 'us-central1')
expect(first.cellId).toBe(ISOLATED.id)
await stores[0]!.activateControl(identity, {
cellId: ISOLATED.id,
assignmentEpoch: first.assignmentEpoch,
generation: 1
})
await databases[0]!.query(
`UPDATE relay_assignments SET reserved_controls = ? WHERE user_id = ? AND relay_host_id = ?`,
[counted.controls, identity.userId, identity.relayHostId]
)
// Units the source still counts with no lease behind them.
await databases[0]!.query(
`UPDATE relay_cells SET reserved_requests = reserved_requests + ? WHERE cell_id = ?`,
[counted.unbackedSourceUnits, ISOLATED.id]
)
await applySelector({ [TARGETS[0]!.id]: 'general', [TARGETS[1]!.id]: 'general' })
await applySelector({ [ISOLATED.id]: 'migration-only' }, [ISOLATED.id])
return { identity, epoch: first.assignmentEpoch }
}
it('heals counters below the leases on the narrowed path', async () => {
await resetFleet()
const { identity, epoch } = await seedDriftedHost(918, { controls: 0, unbackedSourceUnits: 0 })
expect(await counters(identity)).toEqual({ controls: 0, splices: 0 })
await expectReservationAccounting()
const release = await holdCellRows([ISOLATED.id])
try {
const moved = await Promise.race([
stores[1]!.assign(identity, 'us-central1'),
new Promise<'blocked'>((resolve) => setTimeout(() => resolve('blocked'), 3_000))
])
expect(moved).toMatchObject({ assignmentEpoch: epoch + 1 })
expect(TARGETS.map(({ id }) => id)).toContain(moved === 'blocked' ? moved : moved.cellId)
} finally {
await release()
}
// The kept source control plus the new one.
expect(await counters(identity)).toEqual({ controls: 2, splices: 0 })
await expectReservationAccounting()
expect(await stores[0]!.releaseActivity(identity, `control:${ISOLATED.id}:1`)).toBe(true)
expect(await counters(identity)).toEqual({ controls: 1, splices: 0 })
expect(await reservedRequests(ISOLATED.id)).toBe(0)
await expectReservationAccounting()
}, 30_000)
it('takes the all-rows path for units no lease backs', async () => {
await resetFleet()
const { identity, epoch } = await seedDriftedHost(919, { controls: 3, unbackedSourceUnits: 2 })
await expectReservationAccountingExcept(ISOLATED.id)
const release = await holdCellRows([ISOLATED.id])
const held = stores[1]!.assign(identity, 'us-central1').then(
() => 'placed' as const,
() => 'failed' as const
)
try {
// It needs the source row to take the unbacked units off it, so while the
// row is held it either waits or times out; it never places.
expect(
await Promise.race([
held,
new Promise<'waiting'>((resolve) => setTimeout(() => resolve('waiting'), 1_000))
])
).not.toBe('placed')
} finally {
await release()
}
await held
// Whether the held dial finished after the release or failed, the next one
// lands the single move.
expect(await stores[1]!.assign(identity, 'us-central1')).toMatchObject({
assignmentEpoch: epoch + 1
})
expect(await counters(identity)).toEqual({ controls: 2, splices: 0 })
await expectReservationAccounting()
}, 30_000)
it('refuses at once while the host’s own release holds its assignment row', async () => {
await resetFleet()
const { identity, epoch } = await seedDriftedHost(921, { controls: 1, unbackedSourceUnits: 0 })
const release = await holdRows(
`SELECT user_id FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?`,
[identity.userId, identity.relayHostId]
)
try {
const startedAt = performance.now()
await expect(stores[1]!.assign(identity, 'us-central1')).rejects.toBeInstanceOf(
RelayAssignmentRowBusyError
)
// An isolated pin gets no wait: far under the 1s a release can hold it.
expect(performance.now() - startedAt).toBeLessThan(500)
} finally {
await release()
}
expect((await stores[0]!.resolve(identity))?.assignmentEpoch).toBe(epoch)
expect((await stores[1]!.assign(identity, 'us-central1')).assignmentEpoch).toBe(epoch + 1)
await expectReservationAccounting()
}, 30_000)
it('waits up to a second for the row of a host pinned to a live general cell', async () => {
await resetFleet()
const identity = hostIdentity(922)
const first = await stores[0]!.assign(identity, 'us-central1')
const holdAssignment = async (): Promise<() => Promise<void>> =>
await holdRows(
`SELECT user_id FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?`,
[identity.userId, identity.relayHostId]
)
// A short hold, like a calm host's own release: the sticky re-grant waits.
const shortHold = await holdAssignment()
const regrant = stores[1]!.assign(identity, 'us-central1')
try {
await waitForLock('relay_assignments')
} finally {
await shortHold()
await regrant.catch(() => undefined)
}
expect(await regrant).toMatchObject({
cellId: first.cellId,
assignmentEpoch: first.assignmentEpoch
})
// Held past the bound: refused, after about the bound and not the pool's.
const longHold = await holdAssignment()
try {
const startedAt = performance.now()
await expect(stores[1]!.assign(identity, 'us-central1')).rejects.toBeInstanceOf(
RelayAssignmentRowBusyError
)
const waitedMs = performance.now() - startedAt
expect(waitedMs).toBeGreaterThanOrEqual(900)
expect(waitedMs).toBeLessThan(2_000)
} finally {
await longHold()
}
}, 30_000)
it('never waits on the assignment row while its retry holds the pinned cell row', async () => {
await resetFleet()
const identity = hostIdentity(923)
@@ -1,7 +1,7 @@
import { createHash } from 'node:crypto'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { RelayAssignmentStore, RelayHomeCellUnavailableError } from './assignment-store.js'
import { ReservePaceError } from './reserve-placement/reserve-assignment.js'
import { RelayAssignmentStore } from './assignment-store.js'
import {
encodeMembership,
type CellAdmissionMembership,
@@ -41,16 +41,10 @@ afterEach(async () => {
for (const database of databases.splice(0)) await database.close()
})
// Counts the reads this change adds, so the general hot path can be held to a
// single admission lookup and no migration lookup at all.
class QueryCountingDatabase implements RelayDatabase {
readonly sql: string[] = []
class WriteFailureDatabase implements RelayDatabase {
// Fails the first statement containing this fragment, so a test can roll a
// transaction back at a chosen point.
failOnce: string | undefined
// Locked statements that report the row busy, in order: each fragment fires
// once, on the first locked statement containing it after the one before.
lockUnavailableSequence: string[] = []
constructor(private readonly delegate: RelayDatabase) {}
@@ -58,12 +52,7 @@ class QueryCountingDatabase implements RelayDatabase {
return this.delegate.dialect
}
count(fragment: string): number {
return this.sql.filter((statement) => statement.includes(fragment)).length
}
record(sql: string): void {
this.sql.push(sql)
if (this.failOnce !== undefined && sql.includes(this.failOnce)) {
this.failOnce = undefined
throw new Error('injected_placement_write_failure')
@@ -80,17 +69,8 @@ class QueryCountingDatabase implements RelayDatabase {
params?: unknown[],
options?: RelayLockOptions
): Promise<SqlRow[]> {
this.recordLocked(sql)
return await this.delegate.queryLocked(sql, params, options)
}
recordLocked(sql: string): void {
this.record(sql)
const next = this.lockUnavailableSequence[0]
if (next !== undefined && sql.includes(next)) {
this.lockUnavailableSequence.shift()
throw new Error('database_lock_unavailable')
}
return await this.delegate.queryLocked(sql, params, options)
}
async transaction<T>(
@@ -107,8 +87,7 @@ class QueryCountingDatabase implements RelayDatabase {
await this.delegate.close()
}
// A nested transaction shares this one's tape, so a whole assign() is
// measured as a unit.
// Inject the failure inside the transaction so the real database rolls it back.
private recording(inner: RelayDatabase): RelayDatabase {
return {
dialect: inner.dialect,
@@ -117,7 +96,7 @@ class QueryCountingDatabase implements RelayDatabase {
return await inner.query(sql, params)
},
queryLocked: async (sql, params, options) => {
this.recordLocked(sql)
this.record(sql)
return await inner.queryLocked(sql, params, options)
},
transaction: async (operation, options) => await inner.transaction(operation, options),
@@ -129,7 +108,7 @@ class QueryCountingDatabase implements RelayDatabase {
interface Harness {
store: RelayAssignmentStore
database: RelayDatabase
counter: QueryCountingDatabase
counter: WriteFailureDatabase
heartbeat: (cell: RelayCellConfig, at?: number) => Promise<void>
setNow: (value: number) => void
/** The real isolate path: one selector apply that names the cell it stamps. */
@@ -144,7 +123,7 @@ interface Harness {
async function setup(cells: RelayCellConfig[] = CELLS): Promise<Harness> {
const inner = await openInMemoryRelayDatabase()
databases.push(inner)
const counter = new QueryCountingDatabase(inner)
const counter = new WriteFailureDatabase(inner)
let now = START_MS
const store = new RelayAssignmentStore(counter, () => now, {
requireLiveCells: true,
@@ -233,43 +212,6 @@ async function setup(cells: RelayCellConfig[] = CELLS): Promise<Harness> {
}
}
async function insertMigration(
database: RelayDatabase,
input: {
sourceCellId: string
targetCellId: string
assignmentEpoch: number
leases: number
settled?: 'completed' | 'aborted'
}
): Promise<void> {
await database.query(
`INSERT INTO relay_assignment_migrations
(user_id, relay_host_id, source_cell_id, target_cell_id, previous_epoch,
assignment_epoch, source_request_units, target_reserved_units, expires_at,
target_registered_at, completed_at, aborted_at, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, 1, 1, ?, NULL, ?, ?, ?, ?)`,
[
IDENTITY.userId,
IDENTITY.relayHostId,
input.sourceCellId,
input.targetCellId,
input.assignmentEpoch - 1,
input.assignmentEpoch,
START_MS + 900_000,
input.settled === 'completed' ? START_MS : null,
input.settled === 'aborted' ? START_MS : null,
START_MS,
START_MS
]
)
await database.query(
`UPDATE relay_assignments SET migration_leases = ?
WHERE user_id = ? AND relay_host_id = ?`,
[input.leases, IDENTITY.userId, IDENTITY.relayHostId]
)
}
type ConsoleWarnSpy = { mock: { calls: unknown[][] } }
function jsonEvents(warn: ConsoleWarnSpy, event: string): unknown[] {
@@ -280,381 +222,6 @@ function jsonEvents(warn: ConsoleWarnSpy, event: string): unknown[] {
}
describe('re-placing a host off a cell isolated for a roll', () => {
it('leaves a host on a live general cell untouched, at one added admission read', async () => {
const { store, counter } = await setup()
const first = await store.assign(IDENTITY, 'us-central1')
counter.sql.length = 0
const second = await store.assign(IDENTITY, 'us-central1')
// Identical, not merely same-celled: the clock has not moved, so every
// field including the lease deadline must match; only the first was placed.
expect(second).toEqual({ ...first, placed: undefined })
// One row read answers both the stranded rule and the roll-stamp check.
expect(counter.count('relay_cell_admission')).toBe(1)
expect(counter.count('relay_assignment_migrations')).toBe(0)
// No placement: the sticky lane never reaches the fleet-wide inventory.
expect(counter.count('ORDER BY cell_id ASC')).toBe(0)
})
it('keeps a host pinned to a migration-only cell with no roll stamp', async () => {
// Unstamped non-roll parking must retain hosts or undo evacuation/Asia rollback/operator intent.
const { store, park, rollIsolatedAt } = await setup()
const first = await store.assign(IDENTITY, 'us-central1')
await park(first.cellId, 'migration-only')
expect(await rollIsolatedAt(first.cellId)).toBeNull()
const pinned = await store.assign(IDENTITY, 'us-central1')
expect(pinned).toMatchObject({ cellId: first.cellId, assignmentEpoch: first.assignmentEpoch })
expect(pinned.placed).toBeUndefined()
})
it('re-places a host once the roll stamp is set', async () => {
const { store, counter, isolateForRoll, rollIsolatedAt } = await setup()
const first = await store.assign(IDENTITY, 'us-central1')
await isolateForRoll(first.cellId)
expect(await rollIsolatedAt(first.cellId)).toBe(START_MS)
counter.sql.length = 0
const moved = await store.assign(IDENTITY, 'us-central1')
expect(moved.cellId).not.toBe(first.cellId)
expect(moved.assignmentEpoch).toBe(first.assignmentEpoch + 1)
expect(moved.placed).toBe(true)
expect(counter.count('relay_assignment_migrations')).toBeGreaterThan(0)
// Durable: the next dial does not bounce back to the isolated cell.
const kept = await store.assign(IDENTITY, 'us-central1')
expect(kept).toMatchObject({ cellId: moved.cellId, assignmentEpoch: moved.assignmentEpoch })
expect(kept.placed).toBeUndefined()
})
it.each([
{ label: 'just inside the bound', age: 2 * 60 * 60_000 - 1, moves: true },
{ label: 'just outside the bound', age: 2 * 60 * 60_000 + 1, moves: false }
])('treats a stamp $label as $moves', async ({ age, moves }) => {
// Past a normal ~15-minute roll, stamps may be failed-wave or old-restore orphans; keep possibly healthy hosts pinned for operator recovery.
const { store, heartbeat, isolateForRoll, setNow } = await setup()
const first = await store.assign(IDENTITY, 'us-central1')
await isolateForRoll(first.cellId)
const later = START_MS + age
setNow(later)
for (const cell of CELLS) await heartbeat(cell, later)
const grant = await store.assign(IDENTITY, 'us-central1')
if (moves) {
expect(grant.cellId).not.toBe(first.cellId)
expect(grant.assignmentEpoch).toBe(first.assignmentEpoch + 1)
} else {
expect(grant.cellId).toBe(first.cellId)
expect(grant.assignmentEpoch).toBe(first.assignmentEpoch)
}
})
it('stops re-placing once restore clears the stamp', async () => {
const { store, isolateForRoll, restore, rollIsolatedAt } = await setup()
const first = await store.assign(IDENTITY, 'us-central1')
await isolateForRoll(first.cellId)
await restore(first.cellId)
expect(await rollIsolatedAt(first.cellId)).toBeNull()
expect(await store.assign(IDENTITY, 'us-central1')).toMatchObject({
cellId: first.cellId,
assignmentEpoch: first.assignmentEpoch
})
})
it('keeps a host pinned to an existing-only cell that still serves it', async () => {
// Why: existing-only cells serve the hosts they already hold (PR #194). Only
// assignmentStrandedOnUnservedCell may release that pin, and only on proof
// the cell stopped serving this host.
const { store, database, heartbeat, park, setNow } = await setup()
const first = await store.assign(IDENTITY, 'us-central1')
await park(first.cellId, 'existing-only')
await database.query(
`INSERT INTO relay_assignment_activity_leases
(user_id, relay_host_id, activity_id, activity_kind, cell_id,
request_units, expires_at, updated_at)
VALUES (?, ?, 'control:live-1', 'control', ?, 1, ?, ?)`,
[IDENTITY.userId, IDENTITY.relayHostId, first.cellId, START_MS + 600_000, START_MS]
)
// Past the stranded rule's minimum grant age, which outlives the heartbeat TTL.
setNow(START_MS + 61_000)
for (const cell of CELLS) await heartbeat(cell, START_MS + 61_000)
expect(await store.assign(IDENTITY, 'us-central1')).toMatchObject({
cellId: first.cellId,
assignmentEpoch: first.assignmentEpoch
})
})
it('keeps a host pinned on an unstamped cell whose migration has completed', async () => {
// Completed evacuations await separate promotion in migration-only; re-placement would undo them.
const { store, database, park } = await setup()
const first = await store.assign(IDENTITY, 'us-central1')
await insertMigration(database, {
sourceCellId: 'us-c2',
targetCellId: first.cellId,
assignmentEpoch: first.assignmentEpoch,
leases: 0,
settled: 'completed'
})
await park(first.cellId, 'migration-only')
expect(await store.assign(IDENTITY, 'us-central1')).toMatchObject({
cellId: first.cellId,
assignmentEpoch: first.assignmentEpoch
})
})
it('re-places a stamped cell whose migration has completed', async () => {
const { store, database, isolateForRoll } = await setup()
const first = await store.assign(IDENTITY, 'us-central1')
await insertMigration(database, {
sourceCellId: 'us-c2',
targetCellId: first.cellId,
assignmentEpoch: first.assignmentEpoch,
leases: 0,
settled: 'completed'
})
await isolateForRoll(first.cellId)
expect((await store.assign(IDENTITY, 'us-central1')).cellId).not.toBe(first.cellId)
})
it('keeps the pin while a migration lease is outstanding', async () => {
const { store, database, isolateForRoll } = await setup()
const first = await store.assign(IDENTITY, 'us-central1')
await insertMigration(database, {
sourceCellId: first.cellId,
targetCellId: 'us-c2',
assignmentEpoch: first.assignmentEpoch,
leases: 1
})
await isolateForRoll(first.cellId)
expect(await store.assign(IDENTITY, 'us-central1')).toMatchObject({
cellId: first.cellId,
assignmentEpoch: first.assignmentEpoch
})
})
it('keeps the pin while a migration row is open but its lease has lapsed', async () => {
// Migration rows outlive their 15-minute counters and cannot roll back from non-general sources; re-placement would strand them.
const { store, database, isolateForRoll } = await setup()
const first = await store.assign(IDENTITY, 'us-central1')
await insertMigration(database, {
sourceCellId: first.cellId,
targetCellId: 'us-c2',
assignmentEpoch: first.assignmentEpoch,
leases: 0
})
await isolateForRoll(first.cellId)
expect(await store.assign(IDENTITY, 'us-central1')).toMatchObject({
cellId: first.cellId,
assignmentEpoch: first.assignmentEpoch
})
})
it('crosses a region boundary only when its own region has no room', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const { store, isolateForRoll, park } = await setup()
const first = await store.assign(IDENTITY, 'us-central1')
const other = CELLS.find((cell) => cell.region === 'us-central1' && cell.id !== first.cellId)!
await park(other.id, 'migration-only')
await isolateForRoll(first.cellId)
warn.mockClear()
expect(await store.assign(IDENTITY, 'us-central1')).toMatchObject({
cellId: 'asia-c1',
assignmentEpoch: first.assignmentEpoch + 1
})
expect(jsonEvents(warn, 'orca_relay_sticky_replaced_off_isolated_cell')).toEqual([
{
event: 'orca_relay_sticky_replaced_off_isolated_cell',
fromCellId: first.cellId,
fromRegion: 'us-central1',
admissionState: 'migration-only',
toCellId: 'asia-c1',
region: 'asia-east2'
}
])
})
it('keeps the pin, and says so, when no region has a general cell with room', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const { store, isolateForRoll, park } = await setup()
const first = await store.assign(IDENTITY, 'us-central1')
for (const cell of CELLS) {
if (cell.id !== first.cellId) await park(cell.id, 'migration-only')
}
await isolateForRoll(first.cellId)
warn.mockClear()
expect(await store.assign(IDENTITY, 'us-central1')).toMatchObject({
cellId: first.cellId,
assignmentEpoch: first.assignmentEpoch
})
expect(jsonEvents(warn, 'orca_relay_sticky_replacement_deferred')).toEqual([
{
event: 'orca_relay_sticky_replacement_deferred',
reason: 'no_same_region_headroom',
cellId: first.cellId,
region: 'us-central1'
}
])
expect(jsonEvents(warn, 'orca_relay_sticky_replaced_off_isolated_cell')).toEqual([])
})
it('prefers its own region over a less loaded cell elsewhere', async () => {
const { store, isolateForRoll } = await setup()
const first = await store.assign(IDENTITY, 'us-central1')
await isolateForRoll(first.cellId)
const moved = await store.assign(IDENTITY, 'us-central1')
expect(moved.region).toBe('us-central1')
expect(moved.cellId).not.toBe(first.cellId)
})
it('moves the only cell of a region to another region', async () => {
const { store, isolateForRoll } = await setup()
const first = await store.assign(IDENTITY, 'asia-east2')
expect(first.region).toBe('asia-east2')
await isolateForRoll(first.cellId)
// asia-c1 is the only Asia cell, so the only in-region candidate is gone.
const moved = await store.assign(IDENTITY, 'asia-east2')
expect(moved.region).toBe('us-central1')
expect(moved.assignmentEpoch).toBe(first.assignmentEpoch + 1)
})
describe('with a reserve cell in its own region', () => {
const onReserve = {
...IDENTITY,
cellId: 'asia-reserve',
cellUrl: 'https://asia-reserve.example.com',
assignmentEpoch: 9,
leaseExpiresAt: START_MS + 1_000_000,
region: 'asia-east2' as const
}
it('leaves the region as before when the reserve cell has no room either', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const { store, isolateForRoll } = await setup()
const first = await store.assign(IDENTITY, 'asia-east2')
await isolateForRoll(first.cellId)
warn.mockClear()
const regionReserve = vi.fn(async () => null)
const moved = await store.assign(IDENTITY, 'asia-east2', 'asia-east2', undefined, {
regionReserve
})
expect(moved).toMatchObject({
region: 'us-central1',
assignmentEpoch: first.assignmentEpoch + 1
})
expect(regionReserve).toHaveBeenCalledOnce()
expect(jsonEvents(warn, 'orca_relay_sticky_replaced_off_isolated_cell')).toMatchObject([
{ fromCellId: first.cellId, region: 'us-central1' }
])
})
it('treats a throttled reserve cell as no room, so the drain does not wait on its intake', async () => {
const { store, isolateForRoll } = await setup()
const first = await store.assign(IDENTITY, 'asia-east2')
await isolateForRoll(first.cellId)
const regionReserve = vi.fn(async () => {
throw new ReservePaceError(4)
})
await expect(
store.assign(IDENTITY, 'asia-east2', 'asia-east2', undefined, { regionReserve })
).resolves.toMatchObject({
region: 'us-central1',
assignmentEpoch: first.assignmentEpoch + 1
})
expect(regionReserve).toHaveBeenCalledOnce()
})
describe('when no database cell has room anywhere', () => {
const onUsReserve = { ...onReserve, cellId: 'us-reserve', region: 'us-central1' as const }
const isolateWithNoDatabaseRoom = async () => {
const harness = await setup()
const first = await harness.store.assign(IDENTITY, 'asia-east2')
await harness.isolateForRoll(first.cellId)
for (const cell of CELLS.filter((entry) => entry.region === 'us-central1')) {
await harness.park(cell.id, 'migration-only')
}
return { ...harness, first }
}
// Today's rule: a live isolated cell keeps a host no other cell can take.
it('keeps the pin and never asks the spill', async () => {
const { store, first } = await isolateWithNoDatabaseRoom()
const reserveSpill = vi.fn(async () => onUsReserve)
const kept = await store.assign(IDENTITY, 'asia-east2', 'asia-east2', undefined, {
reserveSpill
})
expect(kept).toMatchObject({ cellId: first.cellId, assignmentEpoch: first.assignmentEpoch })
expect(reserveSpill).not.toHaveBeenCalled()
})
})
it('does not hold a host whose preferred region is elsewhere', async () => {
const { store, isolateForRoll, park } = await setup()
const first = await store.assign(IDENTITY, 'us-central1')
const other = CELLS.find((cell) => cell.region === 'us-central1' && cell.id !== first.cellId)!
await park(other.id, 'migration-only')
await isolateForRoll(first.cellId)
const regionReserve = vi.fn(async () => onReserve)
await expect(
store.assign(IDENTITY, 'asia-east2', 'asia-east2', undefined, { regionReserve })
).resolves.toMatchObject({ cellId: 'asia-c1' })
expect(regionReserve).not.toHaveBeenCalled()
})
})
it('takes the dead-cell path when a stamped cell stops heartbeating', async () => {
// Why: the fence is the only proof that a cell we cannot reach has stopped
// serving the sockets it still holds. A stamp does not make it reachable.
const { store, heartbeat, isolateForRoll, setNow } = await setup()
const first = await store.assign(IDENTITY, 'us-central1')
await isolateForRoll(first.cellId)
const stale = START_MS + HEARTBEAT_TTL_MS + 1_000
setNow(stale)
for (const cell of CELLS) {
if (cell.id !== first.cellId) await heartbeat(cell, stale)
}
await expect(store.assign(IDENTITY, 'us-central1')).rejects.toBeInstanceOf(
RelayHomeCellUnavailableError
)
})
it('leaves the source cell activity leases in place', async () => {
// Contrast with the fence and stranded paths, which delete them: an isolated
// cell is alive and still owns drainable work behind those leases.
const { store, database, isolateForRoll } = await setup()
const first = await store.assign(IDENTITY, 'us-central1')
await database.query(
`INSERT INTO relay_assignment_activity_leases
(user_id, relay_host_id, activity_id, activity_kind, cell_id,
request_units, expires_at, updated_at)
VALUES (?, ?, 'splice:keep-1', 'splice', ?, 1, ?, ?)`,
[IDENTITY.userId, IDENTITY.relayHostId, first.cellId, START_MS + 600_000, START_MS]
)
await isolateForRoll(first.cellId)
await store.assign(IDENTITY, 'us-central1')
expect(
await database.query(
`SELECT activity_id FROM relay_assignment_activity_leases
WHERE user_id = ? AND relay_host_id = ? AND activity_id = 'splice:keep-1'`,
[IDENTITY.userId, IDENTITY.relayHostId]
)
).toHaveLength(1)
})
it('emits nothing when the placement rolls back after the decision', async () => {
// Log only committed moves; stdout cannot roll back with a failed lease/reservation transaction.
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
@@ -682,169 +249,4 @@ describe('re-placing a host off a cell isolated for a roll', () => {
expect(moved.cellId).not.toBe(first.cellId)
expect(jsonEvents(warn, 'orca_relay_sticky_replaced_off_isolated_cell')).toHaveLength(1)
})
describe('a host whose leases span two cells after the move', () => {
const NEIGHBOUR = { userId: 'user-b', relayHostId: 'host000000000002' }
async function reserved(database: RelayDatabase, cellId: string): Promise<number> {
const rows = await database.query(
`SELECT reserved_requests FROM relay_cells WHERE cell_id = ?`,
[cellId]
)
return Number(rows[0]!['reserved_requests'])
}
async function expectAccounting(database: RelayDatabase): Promise<void> {
for (const cell of CELLS) {
const leased = await database.query(
`SELECT COALESCE(SUM(request_units), 0) AS units
FROM relay_assignment_activity_leases WHERE cell_id = ?`,
[cell.id]
)
expect({ cell: cell.id, reserved: await reserved(database, cell.id) }).toEqual({
cell: cell.id,
reserved: Number(leased[0]!['units'])
})
}
}
async function counters(database: RelayDatabase): Promise<number[]> {
const rows = await database.query(
`SELECT reserved_controls, reserved_splices FROM relay_assignments
WHERE user_id = ? AND relay_host_id = ?`,
[IDENTITY.userId, IDENTITY.relayHostId]
)
return [Number(rows[0]!['reserved_controls']), Number(rows[0]!['reserved_splices'])]
}
// us-c1 is isolated with the host's control and splice on it; the host
// moves to us-c2, where a neighbour's splice outlives every other lease.
async function movedHost(): Promise<Harness> {
const harness = await setup()
const { store, isolateForRoll } = harness
const first = await store.assign(IDENTITY, 'us-central1')
expect(first.cellId).toBe('us-c1')
await store.activateControl(IDENTITY, {
cellId: 'us-c1',
assignmentEpoch: first.assignmentEpoch,
generation: 1
})
await store.acquireActivity(IDENTITY, {
activityId: 'splice:keep-1',
kind: 'splice',
cellId: 'us-c1'
})
await isolateForRoll('us-c1')
expect((await store.assign(NEIGHBOUR, 'us-central1')).cellId).toBe('us-c2')
await store.acquireActivity(NEIGHBOUR, {
activityId: 'splice:neighbour',
kind: 'splice',
cellId: 'us-c2',
expiresAt: START_MS + 10 * 60 * 60_000
})
expect((await store.assign(IDENTITY, 'us-central1')).cellId).toBe('us-c2')
expect(await counters(harness.database)).toEqual([2, 1])
await expectAccounting(harness.database)
return harness
}
it('is left to the lease sweep by aggregate expiry', async () => {
const { store, database, setNow } = await movedHost()
setNow(START_MS + 60 * 60_000)
await store.releaseExpiredActivity()
expect(await counters(database)).toEqual([2, 1])
await expectAccounting(database)
await store.releaseExpiredActivityLeases()
await store.releaseExpiredActivity()
expect(await counters(database)).toEqual([0, 0])
expect(await reserved(database, 'us-c1')).toBe(0)
expect(await reserved(database, 'us-c2')).toBe(2)
await expectAccounting(database)
})
it('frees the source leases on their own cell when the target dies', async () => {
const { store, database, setNow, heartbeat, restore } = await movedHost()
await restore('us-c1')
// Uncapped, so the dead-cell path needs no fence to move off it.
await database.query(`DELETE FROM relay_cell_connection_limits WHERE cell_id = 'us-c2'`)
setNow(START_MS + HEARTBEAT_TTL_MS + 5_000)
await heartbeat(CELLS[0]!)
await heartbeat(CELLS[2]!)
expect((await store.assign(IDENTITY, 'us-central1')).cellId).toBe('us-c1')
expect(await counters(database)).toEqual([1, 0])
expect(await store.releaseActivity(IDENTITY, 'control:us-c1:1')).toBe(false)
expect(await reserved(database, 'us-c1')).toBe(1)
expect(await reserved(database, 'us-c2')).toBe(3)
await expectAccounting(database)
})
})
it('retries a busy isolated attempt in its own tier, never under the all-rows lock', async () => {
const { store, counter, isolateForRoll } = await setup()
const first = await store.assign(IDENTITY, 'us-central1')
await isolateForRoll(first.cellId)
counter.sql.length = 0
// The first attempt finds a target row busy, then its retry finds the host's
// lease rows busy after it has already taken the tier's rows.
counter.lockUnavailableSequence = [
'SELECT * FROM relay_cells WHERE cell_id IN (',
'FROM relay_assignment_activity_leases'
]
const moved = await store.assign(IDENTITY, 'us-central1')
expect(counter.lockUnavailableSequence).toEqual([])
expect(moved).toMatchObject({
region: 'us-central1',
assignmentEpoch: first.assignmentEpoch + 1
})
expect(counter.count('SELECT * FROM relay_cells ORDER BY cell_id ASC')).toBe(0)
})
})
describe('classifying a reconnect whose home is isolated for a roll', () => {
const classify = { classifyHomeRollIsolation: true }
it('reads the classification in the verification query itself', async () => {
const { store, counter, isolateForRoll } = await setup()
const first = await store.assign(IDENTITY, 'us-central1')
await isolateForRoll(first.cellId)
counter.sql.length = 0
await store.resolve(IDENTITY, classify)
expect(counter.sql.filter((sql) => sql.includes('FROM relay_assignments'))).toHaveLength(1)
expect(counter.count('relay_cell_admission')).toBe(1)
})
it('still treats a host its draining cell already released as a drain return', async () => {
// A drain releases the host's control lease before it tells the host, so the redial
// finds no activity: the stamp, not a live lease, has to carry the classification.
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const { store, database, isolateForRoll } = await setup()
const first = await store.assign(IDENTITY, 'us-central1')
await store.activateControl(IDENTITY, {
cellId: first.cellId,
assignmentEpoch: first.assignmentEpoch,
generation: 1
})
await isolateForRoll(first.cellId)
expect(await store.releaseActivity(IDENTITY, `control:${first.cellId}:1`)).toBe(true)
expect(
await database.query(
`SELECT activity_id FROM relay_assignment_activity_leases WHERE user_id = ?`,
[IDENTITY.userId]
)
).toEqual([])
expect(await store.resolve(IDENTITY, classify)).toMatchObject({
cellId: first.cellId,
homeCellRollIsolated: true
})
warn.mockClear()
const moved = await store.assign(IDENTITY, 'us-central1')
expect(moved.cellId).not.toBe(first.cellId)
expect(moved.assignmentEpoch).toBe(first.assignmentEpoch + 1)
expect(jsonEvents(warn, 'orca_relay_sticky_replaced_off_isolated_cell')).toMatchObject([
{ fromCellId: first.cellId, toCellId: moved.cellId }
])
})
})
File diff suppressed because it is too large Load Diff
@@ -17,42 +17,6 @@ vi.mock('../../authentication/relay-token-verifier.js', () => ({
import { createRelayApp } from '../../app.js'
describe('public assignment overload', () => {
it('rejects duplicate and excess work before it reaches assignment state', async () => {
const hostA = 'aaaaaaaaaaaaaaaa'
const hostB = 'bbbbbbbbbbbbbbbb'
const hostC = 'cccccccccccccccc'
const pending = new Map<string, ReturnType<typeof deferred<RelayAssignment>>>()
const assign = vi.fn(async ({ relayHostId }: { relayHostId: string }) => {
const operation = deferred<RelayAssignment>()
pending.set(relayHostId, operation)
return await operation.promise
})
const app = createRelayApp(config({ publicAssignmentQueueMax: 0 }), {
store: {} as never,
assignments: { assign } as never,
drain: vi.fn(),
ready: vi.fn(async () => true)
})
const first = app.request('/v1/assign', assignmentRequest(hostA))
await vi.waitFor(() => expect(pending.has(hostA)).toBe(true))
const duplicate = await app.request('/v1/assign', assignmentRequest(hostA))
expect(duplicate.status).toBe(503)
const second = app.request('/v1/assign', assignmentRequest(hostB))
await vi.waitFor(() => expect(pending.has(hostB)).toBe(true))
const excess = await app.request('/v1/assign', assignmentRequest(hostC))
expect(excess.status).toBe(503)
expect(excess.headers.get('retry-after')).toBe('5')
expect(assign).toHaveBeenCalledTimes(2)
pending.get(hostA)?.resolve(assignment('cell-a', hostA))
pending.get(hostB)?.resolve(assignment('cell-b', hostB))
expect((await first).status).toBe(200)
expect((await second).status).toBe(200)
expect((await app.request('/v1/assign', assignmentRequest(hostA))).status).toBe(503)
expect(assign).toHaveBeenCalledTimes(2)
})
it('fairly drains a bounded incident-scale burst without raising database concurrency', async () => {
const pending = new Map<string, ReturnType<typeof deferred<RelayAssignment>>>()
@@ -40,37 +40,7 @@ function app(config: RelayConfig = cell) {
return { post, postChunked, reserve, demote, routes }
}
const booking = {
v: 1,
directorId: 'director-a',
items: [{ userId: 'user-1', relayHostId: 'abcdefghijklmnop', epoch: 3, ttlMs: 30_000 }]
}
describe('cell reserve routes', () => {
it('books for a director holding the rehome credential and refuses everyone else', async () => {
const { post, reserve } = app()
const ok = await post('/internal/reserve', booking)
expect(await ok.json()).toEqual({ v: 1, results: [{ outcome: 'ok' }] })
expect((await post('/internal/reserve', booking, 'someone-else')).status).toBe(401)
expect((await post('/internal/reserve', { ...booking, items: [] })).status).toBe(400)
expect((await post('/internal/reserve', { ...booking, v: 2 })).status).toBe(400)
expect(reserve).toHaveBeenCalledTimes(1)
})
it('is absent on a director and on a cell without the rehome pair', async () => {
expect((await app({ ...cell, role: 'director' }).post('/internal/reserve', booking)).status).toBe(404)
const noPair = app({ ...cell, rehomeDirectorServiceAccount: undefined })
expect((await noPair.post('/internal/demote', {})).status).toBe(404)
})
it('demotes only a fully named seat', async () => {
const { post, demote } = app()
const seat = { v: 1, userId: 'user-1', relayHostId: 'abcdefghijklmnop', epoch: 3 }
expect((await post('/internal/demote', seat)).status).toBe(400)
const reply = await post('/internal/demote', { ...seat, joinedAt: 1_000 })
expect(await reply.json()).toEqual({ v: 1, outcome: 'demoted' })
expect(demote).toHaveBeenCalledWith({ ...seat, joinedAt: 1_000 })
})
it.each(['/internal/reserve', '/internal/demote'])(
'rejects an oversized chunked body on %s without calling the handler',
@@ -110,43 +80,4 @@ describe('cell reserve routes', () => {
}
)
it.each(['/internal/reserve', '/internal/demote'])(
'refuses an unauthorized oversized %s before the size check',
async (path) => {
const { routes, reserve, demote } = app()
const response = await routes.request(path, {
method: 'POST',
headers: {
authorization: 'Bearer someone-else',
'content-type': 'application/json',
'content-length': String(16 * 1024 + 1)
},
body: '{}'
})
expect(response.status).toBe(401)
expect(await response.json()).toEqual({ error: 'invalid_token' })
expect(reserve).not.toHaveBeenCalled()
expect(demote).not.toHaveBeenCalled()
}
)
it.each(['/internal/reserve', '/internal/demote'])(
'hides a missing %s route before measuring an oversized body',
async (path) => {
const { routes } = app({ ...cell, role: 'director' })
const response = await routes.request(path, {
method: 'POST',
headers: {
authorization: 'Bearer director-token',
'content-type': 'application/json',
'content-length': String(16 * 1024 + 1)
},
body: '{}'
})
expect(response.status).toBe(404)
expect(await response.json()).toEqual({ error: 'reserve_unavailable' })
}
)
})
-189
View File
@@ -1,189 +0,0 @@
import { describe, expect, it } from 'vitest'
import { loadRelayConfig } from './config.js'
import { RELAY_CELL_CONNECTION_HARD_CAP } from '@orca-cloud/relay-contract/admission-budgets'
import { RELAY_READINESS_JWKS_GRACE_MS, RELAY_READINESS_SQL_GRACE_MS } from './process-lifecycle/relay-readiness.js'
function cellEnvironment(capacity: number): NodeJS.ProcessEnv {
return {
ORCA_RELAY_PUBLIC_URL: 'https://c1.relay.example.com',
ORCA_RELAY_CELL_URL: 'https://c1.relay.example.com',
ORCA_RELAY_AUTH_ISSUER: 'https://auth.example.com',
ORCA_RELAY_JWKS_URL: 'https://auth.example.com/.well-known/jwks.json',
ORCA_RELAY_ASSIGNMENT_SIGNING_KEY: 'assignment-key-with-at-least-thirty-two-bytes',
ORCA_RELAY_ROLE: 'cell',
ORCA_RELAY_CELL_ID: 'gce-c1',
ORCA_RELAY_CELL_CAPACITY: String(capacity),
ORCA_RELAY_ADMIN_AUDIENCE: 'https://relay.example.com/v1/admin/drain',
ORCA_RELAY_DEPLOY_SERVICE_ACCOUNT: 'deploy@example.iam.gserviceaccount.com'
}
}
describe('GCE relay capacity configuration', () => {
it('reads an unset readiness grace variable as the default, never as zero', () => {
const env = cellEnvironment(4_000)
env.ORCA_RELAY_READINESS_JWKS_GRACE_MS = ''
env.ORCA_RELAY_READINESS_SQL_GRACE_MS = ''
expect(loadRelayConfig(env)).toMatchObject({
readinessJwksGraceMs: RELAY_READINESS_JWKS_GRACE_MS,
readinessSqlGraceMs: RELAY_READINESS_SQL_GRACE_MS
})
})
it('requires a distinct paired identity and exact audience for regional host drain', () => {
const env = cellEnvironment(4_000)
env.ORCA_RELAY_REHOME_DIRECTOR_SERVICE_ACCOUNT =
'relay-director@example.iam.gserviceaccount.com'
expect(() => loadRelayConfig(env)).toThrow(
'relay rehome identity and audience must be configured together'
)
env.ORCA_RELAY_REHOME_AUDIENCE = 'https://relay.example.com/v1/admin/host-drain'
expect(loadRelayConfig(env)).toMatchObject({
rehomeDirectorServiceAccount: 'relay-director@example.iam.gserviceaccount.com',
rehomeAudience: 'https://relay.example.com/v1/admin/host-drain'
})
env.ORCA_RELAY_REHOME_AUDIENCE = 'https://relay.example.com/v1/admin/drain'
expect(() => loadRelayConfig(env)).toThrow(
'relay rehome audience must target the host drain route'
)
env.ORCA_RELAY_REHOME_AUDIENCE = 'https://relay.example.com/v1/admin/host-drain'
env.ORCA_RELAY_RUNTIME_SERVICE_ACCOUNT =
env.ORCA_RELAY_REHOME_DIRECTOR_SERVICE_ACCOUNT
expect(() => loadRelayConfig(env)).toThrow(
'relay rehome director identity must differ from the cell runtime identity'
)
})
it('keeps legacy cells uncapped and requires a supported hard-cap pair', () => {
const env = cellEnvironment(4_000)
expect(loadRelayConfig(env)).toMatchObject({
connectionHardCap: undefined,
connectionUnobservedBound: undefined
})
env.ORCA_RELAY_CELL_CONNECTION_HARD_CAP = String(RELAY_CELL_CONNECTION_HARD_CAP)
expect(() => loadRelayConfig(env)).toThrow(
'connection hard cap and unobserved bound must be configured together'
)
env.ORCA_RELAY_CELL_CONNECTION_UNOBSERVED_BOUND = '60'
expect(loadRelayConfig(env)).toMatchObject({
connectionHardCap: 600,
connectionUnobservedBound: 60
})
env.ORCA_RELAY_CELL_CONNECTION_HARD_CAP = '599'
expect(() => loadRelayConfig(env)).toThrow()
env.ORCA_RELAY_CELL_CONNECTION_HARD_CAP = '600'
env.ORCA_RELAY_CELL_CONNECTION_UNOBSERVED_BOUND = '500'
expect(() => loadRelayConfig(env)).toThrow()
env.ORCA_RELAY_CELL_CONNECTION_UNOBSERVED_BOUND = '600'
expect(() => loadRelayConfig(env)).toThrow()
env.ORCA_RELAY_CELL_CONNECTION_HARD_CAP = '1000'
env.ORCA_RELAY_CELL_CONNECTION_UNOBSERVED_BOUND = '60'
expect(loadRelayConfig(env)).toMatchObject({
connectionHardCap: 1_000,
connectionUnobservedBound: 60
})
env.ORCA_RELAY_CELL_CONNECTION_UNOBSERVED_BOUND = '900'
expect(() => loadRelayConfig(env)).toThrow()
})
it('fails closed when public request lanes exceed the director database pool', () => {
const env = cellEnvironment(4_000)
env.ORCA_RELAY_ROLE = 'director'
env.ORCA_RELAY_CELLS_JSON = JSON.stringify([
{
id: 'gce-c1',
url: 'https://c1.relay.example.com',
capacityRequests: 4_000
}
])
env.ORCA_RELAY_DATABASE_POOL_MAX = '2'
expect(() => loadRelayConfig(env)).toThrow(
'public relay admission must leave database pool headroom'
)
})
})
describe('relay edge configuration', () => {
function directorEnvironment(): NodeJS.ProcessEnv {
return {
...cellEnvironment(4_000),
ORCA_RELAY_PUBLIC_URL: 'https://relay.example.com',
ORCA_RELAY_ROLE: 'director',
ORCA_RELAY_CELLS_JSON: JSON.stringify([
{ id: 'gce-c1', url: 'https://c1.relay.example.com', capacityRequests: 4_000 }
])
}
}
it('is off unless a director names an edge URL, and then defaults to no cohort in us-central1', () => {
expect(loadRelayConfig(directorEnvironment()).edge).toBeUndefined()
expect(
loadRelayConfig({ ...cellEnvironment(4_000), ORCA_RELAY_EDGE_CELL_URL: 'https://edge.relay.example.com' }).edge
).toBeUndefined()
expect(() =>
loadRelayConfig({ ...directorEnvironment(), ORCA_RELAY_EDGE_CELL_URL: 'https://edge.relay.example.com' })
).toThrow('ORCA_RELAY_EDGE_ADMIN_SIGNING_KEY')
const edge = loadRelayConfig({
...directorEnvironment(),
ORCA_RELAY_EDGE_CELL_URL: 'https://edge.relay.example.com',
ORCA_RELAY_EDGE_ADMIN_SIGNING_KEY: 'edge-admin-key-with-at-least-32-bytes!!'
}).edge
expect(edge).toEqual({
cellUrl: 'https://edge.relay.example.com',
adminSigningKey: new TextEncoder().encode('edge-admin-key-with-at-least-32-bytes!!'),
rolloutPercent: 0,
allowHosts: new Set(),
allowUsers: new Set(),
denyHosts: new Set(),
regions: new Set(['us-central1'])
})
})
it('parses the cohort and refuses unsafe edge settings', () => {
const env = {
...directorEnvironment(),
ORCA_RELAY_EDGE_CELL_URL: 'https://edge.relay.example.com',
ORCA_RELAY_EDGE_ADMIN_SIGNING_KEY: 'edge-admin-key-with-at-least-32-bytes!!',
ORCA_RELAY_EDGE_ROLLOUT_PERCENT: '10',
ORCA_RELAY_EDGE_ALLOW_HOSTS: 'abcdefghijklmnop, ABCDEFGHIJKLMNOP',
ORCA_RELAY_EDGE_DENY_HOSTS: 'zzzzzzzzzzzzzzzz',
ORCA_RELAY_EDGE_ALLOW_USERS: ' user_01ABC , 6b1f-uuid ',
ORCA_RELAY_EDGE_REGIONS: 'us-central1,asia-east2'
}
expect(loadRelayConfig(env).edge).toMatchObject({
rolloutPercent: 10,
allowHosts: new Set(['abcdefghijklmnop', 'ABCDEFGHIJKLMNOP']),
allowUsers: new Set(['user_01ABC', '6b1f-uuid']),
denyHosts: new Set(['zzzzzzzzzzzzzzzz']),
regions: new Set(['us-central1', 'asia-east2'])
})
expect(() => loadRelayConfig({ ...env, ORCA_RELAY_EDGE_ROLLOUT_PERCENT: '101' })).toThrow()
expect(() => loadRelayConfig({ ...env, ORCA_RELAY_EDGE_ALLOW_HOSTS: 'short' })).toThrow()
expect(() => loadRelayConfig({ ...env, ORCA_RELAY_EDGE_ALLOW_USERS: 'a b' })).toThrow()
expect(() => loadRelayConfig({ ...env, ORCA_RELAY_EDGE_REGIONS: 'europe-west1' })).toThrow()
expect(() => loadRelayConfig({ ...env, ORCA_RELAY_EDGE_CELL_URL: 'https://edge.relay.example.com/path' })).toThrow()
expect(() => loadRelayConfig({ ...env, ORCA_RELAY_EDGE_CELL_URL: 'https://c1.relay.example.com' })).toThrow()
expect(() => loadRelayConfig({ ...env, ORCA_RELAY_EDGE_CELL_URL: 'https://relay.example.com' })).toThrow()
})
it('parses the export skip threshold, leaving the default when unset or empty', () => {
const env = {
...directorEnvironment(),
ORCA_RELAY_EDGE_CELL_URL: 'https://edge.relay.example.com',
ORCA_RELAY_EDGE_ADMIN_SIGNING_KEY: 'edge-admin-key-with-at-least-32-bytes!!'
}
expect(loadRelayConfig(env).edge).not.toHaveProperty('exportSkipAfterMs')
expect(loadRelayConfig({ ...env, ORCA_RELAY_EDGE_EXPORT_SKIP_AFTER_MS: '' }).edge).not.toHaveProperty(
'exportSkipAfterMs'
)
expect(loadRelayConfig({ ...env, ORCA_RELAY_EDGE_EXPORT_SKIP_AFTER_MS: '0' }).edge?.exportSkipAfterMs).toBe(0)
expect(loadRelayConfig({ ...env, ORCA_RELAY_EDGE_EXPORT_SKIP_AFTER_MS: '300000' }).edge?.exportSkipAfterMs).toBe(
300_000
)
expect(() => loadRelayConfig({ ...env, ORCA_RELAY_EDGE_EXPORT_SKIP_AFTER_MS: '-1' })).toThrow()
expect(() => loadRelayConfig({ ...env, ORCA_RELAY_EDGE_EXPORT_SKIP_AFTER_MS: '1.5' })).toThrow()
expect(() => loadRelayConfig({ ...env, ORCA_RELAY_EDGE_EXPORT_SKIP_AFTER_MS: 'soon' })).toThrow()
})
})
-130
View File
@@ -1,130 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { RelayConfig } from './config.js'
import { openInMemoryRelayDatabase, type RelayDatabase } from './database/database.js'
import { EdgeAssignments, type EdgeRelayConfig } from './edge-relay.js'
const fakes = vi.hoisted(() => ({
verifyRelayToken: vi.fn(async (token: string) => ({ sub: 'user-1', relayHostId: token }))
}))
vi.mock('./authentication/relay-token-verifier.js', () => ({
createRelayTokenVerifier: () => fakes.verifyRelayToken,
readBearer: (value: string | undefined) => value?.replace(/^Bearer /, '') ?? null
}))
import { createRelayApp } from './app.js'
const EDGE_URL = 'https://edge.relay.example.test'
const COHORT_HOST = 'edgecohorthost01'
const databases: RelayDatabase[] = []
afterEach(async () => {
for (const database of databases.splice(0)) { await database.close() }
})
function config(): RelayConfig {
return {
port: 8080,
publicUrl: 'https://relay.example.test',
cellUrl: 'https://relay.example.test',
region: 'us-central1',
authIssuer: 'https://auth.example.test',
authAudience: 'orca-relay',
jwksUrl: 'https://auth.example.test/jwks',
assignmentSigningKey: new TextEncoder().encode('assignment-key-with-at-least-32-bytes'),
role: 'director',
cellId: 'director',
cells: [],
adminAudience: 'https://relay.example.test/v1/admin/drain',
deployServiceAccount: 'deploy@example.test',
runtimeServiceAccount: 'runtime@example.test',
adminJwksUrl: 'https://auth.example.test/jwks',
databasePoolMax: 3,
publicAssignmentsEnabled: true,
regionalPlacementEnabled: true,
publicAssignmentConcurrency: 2,
publicAssignmentQueueMax: 128,
publicAssignmentWaitMs: 4_000,
publicResolveConcurrency: 1,
publicResolveWaitMs: 5_000,
publicAssignmentRetryAfterSeconds: 5,
dataDir: './data'
}
}
async function harness(options: { seeded?: boolean } = {}) {
const database = await openInMemoryRelayDatabase()
databases.push(database)
const edgeConfig: EdgeRelayConfig = {
cellUrl: EDGE_URL,
rolloutPercent: 0,
allowHosts: new Set([COHORT_HOST]),
denyHosts: new Set(),
regions: new Set(['us-central1'])
}
const edge = new EdgeAssignments(database, edgeConfig)
if (options.seeded !== false) { await edge.ensureEdgeCell() }
const gce = {
userId: 'user-1',
cellId: 'us-c1',
cellUrl: 'https://us-c1.relay.example.test',
region: 'us-central1' as const,
assignmentEpoch: 3,
leaseExpiresAt: Date.now() + 90_000
}
const assignments = {
assign: vi.fn(async (identity: { relayHostId: string }) => ({ ...gce, relayHostId: identity.relayHostId })),
resolve: vi.fn(async () => null),
exchangeRegionCorrection: vi.fn()
}
const plan = vi.fn(async () => ({ kind: 'database' }))
const raiseEpochFloor = vi.fn()
const store = { resolveResume: vi.fn(async () => ({ userId: 'user-1' })) }
const app = createRelayApp(config(), {
store: store as never,
assignments: assignments as never,
reservePlacement: { plan, raiseEpochFloor, rowEpochFloor: () => 0 } as never,
edgeAssignments: edge,
drain: vi.fn(),
ready: vi.fn(async () => true)
})
const assign = async (relayHostId: string, extra: Record<string, unknown> = {}) =>
await app.request('/v1/assign', {
method: 'POST',
headers: { authorization: `Bearer ${relayHostId}`, 'content-type': 'application/json' },
body: JSON.stringify({ v: 1, relayHostId, preferredRegion: 'us-central1', ...extra })
})
const resolve = async (relayHostId: string) =>
await app.request('/v1/resolve', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ v: 1, relayHostId, resumeToken: 'r'.repeat(43) })
})
return { database, edge, assignments, plan, raiseEpochFloor, assign, resolve }
}
describe('director routes with the relay edge', () => {
it('keeps a host still holding units on its old cell there (no 503), moving it on a later ask', async () => {
const h = await harness()
await h.database.query(
`INSERT INTO relay_assignments
(user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at, last_activity_at,
reserved_controls, reserved_splices, reserved_invites, pending_installs,
pending_confirmations, migration_leases)
VALUES ('user-1', ?, 'us-c1', 5, 0, 0, 1, 0, 0, 0, 0, 0)`,
[COHORT_HOST]
)
const response = await h.assign(COHORT_HOST)
expect(response.status).toBe(200)
expect(await response.json()).toMatchObject({ cellUrl: 'https://us-c1.relay.example.test' })
expect(h.assignments.assign).toHaveBeenCalled()
})
it('never moves a host on a phone resolve', async () => {
const h = await harness()
const response = await h.resolve(COHORT_HOST)
expect(await response.json()).toMatchObject({ cellUrl: 'https://us-c1.relay.example.test' })
expect(await h.edge.edgeAssignment({ userId: 'user-1', relayHostId: COHORT_HOST })).toBeNull()
})
})
+18
View File
@@ -66,6 +66,24 @@ export function inEdgeCohort(
return edgeCohortBucketPermille(relayHostId) < edgeRolloutPermille(config.rolloutPercent, flags)
}
// Whether the host's assignment row may be on the edge, so an ask that is not moving it there must
// read the row (leave) first. A host reaches the edge only through the cohort (its bucket under the
// rollout) or an allow list, and cohorts only grow with the rollout, so a host above the highest
// rollout ever applied (leaveCeilingPermille) never had an edge row. Unset: every host may.
// Mode is ignored: hosts leave under off and down too.
export function mayBeOnEdge(config: EdgeRelayConfig, relayHostId: string, userId?: string): boolean {
const flags = config.control?.() ?? EDGE_CONTROL_DEFAULTS
if (flags.leaveCeilingPermille === undefined) { return true }
if (config.allowHosts.has(relayHostId) || config.denyHosts.has(relayHostId)) { return true }
if (userId !== undefined && config.allowUsers?.has(userId)) { return true }
const ceiling = Math.max(
flags.leaveCeilingPermille,
edgeRolloutPermille(config.rolloutPercent, flags),
config.rolloutPercent * 10
)
return edgeCohortBucketPermille(relayHostId) < ceiling
}
// Another director holds the host's row, or the host is on the edge and cannot leave yet (its
// desktop is still connected there): retry shortly.
export class EdgeMoveBusyError extends Error {
+28 -4
View File
@@ -17,6 +17,14 @@ export type EdgeControlFlags = {
mode: EdgeControlMode
// Replaces the env rollout percent when present (1‰ steps).
rolloutPermille?: number
// Highest rollout (permille) ever applied. Present: a host above it (and above the current
// rollout, and on no allow or deny list) cannot have a row on the edge, so its asks skip the
// edge row read (mayBeOnEdge). Absent: every host's ask reads it. Operating rules:
// - never lower it below a rollout that was applied (a file with it below rolloutPermille is void);
// - raise it in its own write, at least a minute (many polls) before a higher rollout, so no
// director still skips a host another director has just moved;
// - unset it before removing an allow list entry (the ceiling covers buckets, not the lists).
leaveCeilingPermille?: number
}
export const EDGE_CONTROL_DEFAULTS: EdgeControlFlags = { mode: 'on' }
@@ -25,10 +33,19 @@ export const EDGE_CONTROL_APPLIED_EVENT = 'orca_relay_edge_control_applied'
const EdgeControlFlagsSchema = z.object({
mode: z.enum(['on', 'off', 'down']).default(EDGE_CONTROL_DEFAULTS.mode),
rolloutPermille: z.number().int().min(0).max(1_000).optional()
rolloutPermille: z.number().int().min(0).max(1_000).optional(),
leaveCeilingPermille: z.number().int().min(0).max(1_000).optional()
})
const KNOWN_FLAG_KEYS = new Set(Object.keys(EdgeControlFlagsSchema.shape))
const EdgeControlObjectSchema = z.object({ v: z.literal(1), flags: EdgeControlFlagsSchema })
const EdgeControlObjectSchema = z.object({
v: z.literal(1),
flags: EdgeControlFlagsSchema.refine(
(flags) =>
flags.leaveCeilingPermille === undefined ||
flags.rolloutPermille === undefined ||
flags.leaveCeilingPermille >= flags.rolloutPermille
)
})
// Unknown keys (a newer writer's, or a typo) are dropped and reported; a known key with a bad value
// voids the whole object, so the last applied flags stay.
@@ -42,8 +59,15 @@ export const parseEdgeControl: ControlFlagParse<EdgeControlFlags> = (body) => {
named !== null && typeof named === 'object'
? Object.keys(named).filter((key) => !KNOWN_FLAG_KEYS.has(key)).sort()
: []
const { mode, rolloutPermille } = parsed.data.flags
return { flags: rolloutPermille === undefined ? { mode } : { mode, rolloutPermille }, ignoredKeys }
const { mode, rolloutPermille, leaveCeilingPermille } = parsed.data.flags
return {
flags: {
mode,
...(rolloutPermille === undefined ? {} : { rolloutPermille }),
...(leaveCeilingPermille === undefined ? {} : { leaveCeilingPermille })
},
ignoredKeys
}
}
export type EdgeControl = {
@@ -1,188 +0,0 @@
import { createHash } from 'node:crypto'
import { jwtVerify } from 'jose'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { openInMemoryRelayDatabase, type RelayDatabase } from './database/database.js'
import {
EDGE_ADMIN_AUDIENCE,
EdgeAdminUnavailableError,
createEdgeAdmin,
type EdgeAdmin,
type EdgeDrainResult
} from './edge-admin-client.js'
import { EDGE_EVACUATION_BUSY_INTERVAL_MS, EDGE_EVACUATION_CONCURRENCY, EDGE_EVACUATION_CONTROL_DELAY_MS, EdgeEvacuation } from './edge-relay-evacuation.js'
import { EDGE_CELL_ID, type EdgeRelayConfig } from './edge-relay.js'
import type { EdgeControlFlags } from './edge-relay-control.js'
const EDGE_URL = 'https://edge.relay.example.test'
const SIGNING_KEY = new TextEncoder().encode('edge-admin-key-with-at-least-32-bytes!!')
const databases: RelayDatabase[] = []
afterEach(async () => {
vi.useRealTimers()
vi.restoreAllMocks()
for (const database of databases.splice(0)) { await database.close() }
})
function hostId(index: number): string {
return `host${String(index).padStart(12, '0')}`
}
class FakeAdmin implements EdgeAdmin {
drained: string[] = []
unavailable = new Set<string>()
answer: EdgeDrainResult = { outcome: 'drained', controls: 1 }
// Set: each drain waits for release(), so the test can count drains in flight.
holding = false
readonly held: (() => void)[] = []
release(): void {
for (const resolve of this.held.splice(0)) { resolve() }
}
async assign(): Promise<never> {
throw new Error('unexpected assign')
}
async exportHost(): Promise<never> {
throw new Error('unexpected export')
}
async drain(relayHostId: string): Promise<EdgeDrainResult> {
if (this.unavailable.has(relayHostId)) { throw new EdgeAdminUnavailableError('status_404') }
this.drained.push(relayHostId)
if (this.holding) { await new Promise<void>((resolve) => this.held.push(resolve)) }
return this.answer
}
}
async function harness(overrides: Partial<EdgeRelayConfig> = {}, random = 0.5) {
const database = await openInMemoryRelayDatabase()
databases.push(database)
const config: EdgeRelayConfig = {
cellUrl: EDGE_URL,
rolloutPercent: 0,
allowHosts: new Set(),
denyHosts: new Set(),
regions: new Set(['us-central1']),
...overrides
}
const admin = new FakeAdmin()
const clock = { now: 1_700_000_000_000 }
const evacuation = new EdgeEvacuation(database, config, admin, EDGE_CELL_ID, () => clock.now, () => random)
const insert = async (relayHostId: string, cellId = EDGE_CELL_ID, userId = 'user-1') =>
await database.query(
`INSERT INTO relay_assignments
(user_id, relay_host_id, cell_id, assignment_epoch, lease_expires_at, last_activity_at,
reserved_controls, reserved_splices, reserved_invites, pending_installs,
pending_confirmations, migration_leases)
VALUES (?, ?, ?, 1, 0, 0, 0, 0, 0, 0, 0, 0)`,
[userId, relayHostId, cellId]
)
const prefer = async (relayHostId: string, region: string, userId = 'user-1') =>
await database.query(
`INSERT INTO relay_assignment_region_preferences (user_id, relay_host_id, preferred_region, observed_at)
VALUES (?, ?, ?, 0)`,
[userId, relayHostId, region]
)
return { database, config, admin, clock, evacuation, insert, prefer }
}
describe('edge evacuation under runtime control', () => {
it('re-arms after a pass that was running when the control changed', async () => {
vi.useFakeTimers()
vi.spyOn(console, 'warn').mockImplementation(() => {})
const flags: EdgeControlFlags = { mode: 'on', rolloutPermille: 0 }
const h = await harness({ control: () => flags })
await h.insert(hostId(1))
h.admin.holding = true
const sweep = vi.spyOn(h.evacuation, 'sweep')
h.evacuation.start()
await vi.advanceTimersByTimeAsync(EDGE_EVACUATION_BUSY_INTERVAL_MS)
expect(h.admin.held).toHaveLength(1)
flags.mode = 'down'
h.evacuation.controlChanged()
h.admin.release()
await vi.advanceTimersByTimeAsync(EDGE_EVACUATION_CONTROL_DELAY_MS)
expect(sweep).toHaveBeenCalledTimes(2)
h.evacuation.stop()
})
it('leaves region scope to the assign path: a stored preference outside it drains nobody', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => {})
const flags: EdgeControlFlags = { mode: 'on', rolloutPermille: 1000 }
const h = await harness({ control: () => flags })
// On the edge by its ask (no region, or us-central1); its stored preference says otherwise.
await h.insert(hostId(1))
await h.prefer(hostId(1), 'asia-east2')
await h.insert(hostId(2))
expect(await h.evacuation.sweep()).toBe(0)
expect(h.admin.drained).toEqual([])
// Leaving the cohort still drains, whatever the stored region.
flags.rolloutPermille = 0
expect(await h.evacuation.sweep()).toBe(2)
expect(h.admin.drained.sort()).toEqual([hostId(1), hostId(2)])
})
it(`sends at most ${EDGE_EVACUATION_CONCURRENCY} drains at once`, async () => {
vi.spyOn(console, 'warn').mockImplementation(() => {})
const h = await harness()
for (let index = 0; index < 35; index += 1) { await h.insert(hostId(index)) }
h.admin.holding = true
let done = false
const pass = h.evacuation.sweep().then((answered) => {
done = true
return answered
})
let most = 0
while (!done) {
await new Promise((resolve) => setTimeout(resolve, 0))
most = Math.max(most, h.admin.held.length)
h.admin.release()
}
expect(await pass).toBe(35)
expect(most).toBe(EDGE_EVACUATION_CONCURRENCY)
})
})
describe('edge admin drain call', () => {
it('posts the signed drain op and reads both answers; anything else is unavailable', async () => {
const answers: [number, unknown][] = [
[200, { outcome: 'drained', controls: 2 }],
[200, { outcome: 'idle' }],
[404, {}],
[401, {}],
[200, { outcome: 'drained' }]
]
const requests: { url: string; init: RequestInit }[] = []
const admin = createEdgeAdmin({
cellUrl: EDGE_URL,
signingKey: SIGNING_KEY,
issuer: 'https://relay.example.test',
fetch: async (url, init) => {
requests.push({ url: String(url), init: init! })
const [status, body] = answers.shift()!
return new Response(JSON.stringify(body), { status })
}
})
expect(await admin.drain(hostId(1))).toEqual({ outcome: 'drained', controls: 2 })
expect(await admin.drain(hostId(1))).toEqual({ outcome: 'idle' })
await expect(admin.drain(hostId(1))).rejects.toBeInstanceOf(EdgeAdminUnavailableError)
await expect(admin.drain(hostId(1))).rejects.toBeInstanceOf(EdgeAdminUnavailableError)
await expect(admin.drain(hostId(1))).rejects.toBeInstanceOf(EdgeAdminUnavailableError)
const first = requests[0]!
expect(first.url).toBe(`${EDGE_URL}/__admin/drain`)
expect(first.init.method).toBe('POST')
expect(first.init.body).toBe(JSON.stringify({ relayHostId: hostId(1) }))
const token = String((first.init.headers as Record<string, string>).authorization).replace('Bearer ', '')
const { payload } = await jwtVerify(token, SIGNING_KEY, {
audience: EDGE_ADMIN_AUDIENCE,
issuer: 'https://relay.example.test'
})
expect(payload).toMatchObject({
purpose: 'edge-admin',
op: 'drain',
bodySha256: createHash('sha256').update(String(first.init.body)).digest('base64url')
})
})
})
@@ -5,7 +5,7 @@
// retries fences that did not land after a host left (edge-relay-fence.ts).
import type { RelayDatabase } from './database/database.js'
import { EdgeAdminUnavailableError, type EdgeAdmin } from './edge-admin-client.js'
import { inEdgeCohort, text, type EdgeRelayConfig, type Identity } from './edge-relay-cohort.js'
import { inEdgeCohort, mayBeOnEdge, text, type EdgeRelayConfig, type Identity } from './edge-relay-cohort.js'
import { forEachBounded, retryPendingFences } from './edge-relay-fence.js'
// A cohort change (director/edge.json, or a new revision) re-arms the sweep (controlChanged), so a
@@ -120,6 +120,11 @@ export class EdgeEvacuation {
// hosts that the next ask put straight back (a drain every few minutes). A host that asks
// for a region outside the scope leaves on that ask.
if (inEdgeCohort(this.config, identity.relayHostId, 'any', identity.userId)) { continue }
if (!mayBeOnEdge(this.config, identity.relayHostId, identity.userId)) {
// leaveCeilingPermille is set below a rollout this host was moved under: its asks skip
// the leave read, so it would be re-placed without its devices. Raise the ceiling.
console.error(JSON.stringify({ event: 'orca_relay_edge_row_above_ceiling' }))
}
if (this.drainedAt.has(drainKey(identity))) { continue }
leaving.push(identity)
// Resume after the last host taken, so the rest of the page is read next tick.
+4 -103
View File
@@ -1,7 +1,7 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { openInMemoryRelayDatabase, type RelayDatabase } from './database/database.js'
import { EdgeAdminUnavailableError, type EdgeAdmin, type EdgeAdminCallOptions, type EdgeAssignBody, type EdgeAssignResult } from './edge-admin-client.js'
import { EDGE_FENCE_RETRY_BASE_MS, EDGE_FENCE_RETRY_BATCH, recordPendingFence, retryPendingFences } from './edge-relay-fence.js'
import type { EdgeAdmin, EdgeAdminCallOptions, EdgeAssignBody, EdgeAssignResult } from './edge-admin-client.js'
import { EDGE_FENCE_RETRY_BASE_MS, retryPendingFences } from './edge-relay-fence.js'
import { EDGE_CELL_ID, EdgeAssignments, type EdgeRelayConfig } from './edge-relay.js'
const EDGE_URL = 'https://edge.relay.example.test'
@@ -16,31 +16,16 @@ afterEach(async () => {
for (const database of databases.splice(0)) { await database.close() }
})
type Answer = EdgeAssignResult['outcome'] | 'down' | 'hang'
// Answers each assign from `answers` (then 'applied'); 'hang' waits until `release()`.
class ScriptedEdge implements EdgeAdmin {
answers: Answer[] = []
answers: EdgeAssignResult['outcome'][] = []
calls: { body: EdgeAssignBody; options?: EdgeAdminCallOptions }[] = []
private waiting: (() => void)[] = []
async assign(body: EdgeAssignBody, options?: EdgeAdminCallOptions): Promise<EdgeAssignResult> {
this.calls.push({ body, ...(options ? { options } : {}) })
const answer = this.answers.shift() ?? 'applied'
if (answer === 'down') { throw new EdgeAdminUnavailableError('network') }
if (answer === 'hang') { await new Promise<void>((resolve) => this.waiting.push(resolve)) }
const outcome = answer === 'hang' ? 'applied' : answer
const outcome = this.answers.shift() ?? 'applied'
return { outcome, assignmentEpoch: outcome === 'stale' ? body.assignmentEpoch + 5 : body.assignmentEpoch }
}
get hanging(): number {
return this.waiting.length
}
release(): void {
for (const resolve of this.waiting.splice(0)) { resolve() }
}
async exportHost(): Promise<never> {
throw new Error('unexpected export')
}
@@ -96,63 +81,6 @@ function logged(spy: { mock: { calls: unknown[][] } }, event: string): Record<st
.filter((entry) => entry.event === event)
}
describe('relay edge fence after a host leaves', () => {
it('records nothing when the fence lands, and a newer failure replaces an older record', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
const h = await harness()
h.edge.answers = ['down', 'unchanged']
expect(await h.assignments.fenceAway({ userId: USER, relayHostId: HOST }, 'us-c1', 9)).toBe(true)
expect(await h.pending()).toEqual([])
h.edge.answers = ['down', 'down', 'down']
await h.assignments.fenceAway({ userId: USER, relayHostId: HOST }, 'us-c1', 9)
await h.database.query(`UPDATE relay_edge_fence_pending SET attempts = 3`)
h.clock.now += 5_000
h.edge.answers = ['stale']
await h.assignments.fenceAway({ userId: USER, relayHostId: HOST }, 'us-c2', 12)
expect(await h.pending()).toEqual([
{ relayHostId: HOST, cellId: 'us-c2', assignmentEpoch: 12, attempts: 0, nextAttemptAt: h.clock.now + EDGE_FENCE_RETRY_BASE_MS }
])
})
})
describe('relay edge fence over a same-epoch conflict', () => {
it('fences once more one epoch above a conflict at its epoch, and never bumps over a stale answer', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const h = await harness()
h.edge.answers = ['conflict', 'applied']
expect(await h.assignments.fenceAway({ userId: USER, relayHostId: HOST }, 'us-c1', 9)).toBe(true)
expect(h.edge.calls.map((call) => call.body.assignmentEpoch)).toEqual([9, 10])
expect(h.edge.calls.every((call) => call.body.cellId === 'us-c1')).toBe(true)
expect(logged(warn, 'orca_relay_edge_fence_above_conflict')).toEqual([
{ event: 'orca_relay_edge_fence_above_conflict', outcome: 'applied', assignmentEpoch: 10 }
])
expect(await h.pending()).toEqual([])
// Stale: the edge holds a newer epoch (the host may be back there); no bump, recorded for retry.
h.edge.calls = []
h.edge.answers = ['stale']
expect(await h.assignments.fenceAway({ userId: USER, relayHostId: HOST }, 'us-c1', 11)).toBe(false)
expect(h.edge.calls.map((call) => call.body.assignmentEpoch)).toEqual([11])
})
it('a pending fence retried into a same-epoch conflict lands one epoch above the row', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {})
vi.spyOn(console, 'warn').mockImplementation(() => {})
const h = await harness()
await h.placeRow('us-c1', 7)
h.edge.answers = ['down', 'down', 'down', 'down', 'down', 'down', 'down', 'down', 'down', 'down']
expect(await h.assignments.fenceAway({ userId: USER, relayHostId: HOST }, 'us-c1', 7)).toBe(false)
expect(await h.pending()).toHaveLength(1)
h.edge.calls = []
h.edge.answers = ['conflict', 'applied']
h.clock.now += 60_000
await h.retry()
expect(h.edge.calls.map((call) => call.body.assignmentEpoch)).toEqual([7, 8])
expect(await h.pending()).toEqual([])
})
})
describe('relay edge pending fence retries', () => {
it('re-fences to the current row, not the recorded one, and clears the record once it lands', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
@@ -174,33 +102,6 @@ describe('relay edge pending fence retries', () => {
])
})
it(`retries up to ${EDGE_FENCE_RETRY_BATCH} due fences per pass, 10 in flight at once`, async () => {
vi.spyOn(console, 'warn').mockImplementation(() => {})
const h = await harness()
const hosts = Array.from({ length: EDGE_FENCE_RETRY_BATCH + 10 }, (_, index) => `fencehost${String(index).padStart(7, '0')}`)
for (const host of hosts) {
await h.placeRow('us-c1', 9, host)
await recordPendingFence(h.database, { userId: USER, relayHostId: host }, 'us-c1', 9, h.clock.now)
}
h.clock.now += EDGE_FENCE_RETRY_BASE_MS
h.edge.answers = hosts.map(() => 'hang')
let settled = false
const pass = h.retry().then((left) => {
settled = true
return left
})
let maxInFlight = 0
while (!settled) {
await new Promise((resolve) => setTimeout(resolve, 0))
maxInFlight = Math.max(maxInFlight, h.edge.hanging)
h.edge.release()
}
expect(await pass).toBe(true)
expect(h.edge.calls).toHaveLength(EDGE_FENCE_RETRY_BATCH)
expect(maxInFlight).toBe(10)
expect(await h.pending()).toHaveLength(10)
})
it('lets only one director claim an attempt', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.spyOn(console, 'error').mockImplementation(() => {})
+1
View File
@@ -37,6 +37,7 @@ export {
edgeCohortBucket,
inEdgeCohort,
mapEpochFloor,
mayBeOnEdge,
type EdgeRelayConfig
} from './edge-relay-cohort.js'
File diff suppressed because it is too large Load Diff
@@ -1,6 +1,6 @@
id: claude-chat-entrypoint-callers
valid:
- 'stripInheritedClaudeSessionEnv(env)'
- 'stripInheritedAgentSessionEnv(env)'
invalid:
- 'withOrcaClaudeChatEntrypoint(env, platform)'
- "import { withOrcaClaudeChatEntrypoint as stamp } from './claude-chat-entrypoint'"
@@ -1,5 +0,0 @@
id: profile-full-save-callers
valid:
- "scheduleSave(scheduling, ['repos'])"
invalid:
- 'scheduleFullProfileSave(scheduling)'
@@ -88,7 +88,7 @@ ignores:
- '**/*.test-fixtures.*'
- '**/__fixtures__/**'
- 'src/shared/agent-launch/startup/claude-chat-entrypoint.ts'
- 'src/shared/agent-launch/startup/claude-parent-session-env.ts'
- 'src/shared/agent-launch/startup/parent-agent-session-env.ts'
rule:
all:
- any:
@@ -107,7 +107,7 @@ ignores:
- '**/*.test-fixtures.*'
- '**/__fixtures__/**'
- 'src/shared/agent-launch/startup/claude-chat-entrypoint.ts'
- 'src/shared/agent-launch/startup/claude-parent-session-env.ts'
- 'src/shared/agent-launch/startup/parent-agent-session-env.ts'
rule:
all:
- any:
@@ -7,8 +7,8 @@ files:
- src/**
ignores:
- '**/*.test.*'
- src/main/persistence/loading-store/write-scheduling.ts
- src/main/persistence/loading-store/profile-writing/write-scheduling.ts
- src/main/persistence/loading-store/store.ts
- src/main/persistence/loading-store/profile-state-maintenance.ts
- src/main/persistence/loading-store/profile-writing/profile-state-maintenance.ts
rule:
pattern: scheduleFullProfileSave($$$)
-9
View File
@@ -82,15 +82,6 @@ focus change, and singleton accessibility/native counts do not establish an atom
identity mapping if a window closes or the accessibility tree is stale. The probe
covers stable fixtures and detected ambiguity, not those concurrent lifecycle races.
## Headless contract checks
```sh
ORCA_BACKGROUND_LAUNCH=1 python3 -m unittest discover -s config/benchmarks/computer-use -p 'test_*.py'
```
These checks protect the historical false-success cases and process-tree cleanup.
They do not import desktop observers or generate native input.
Transports, fixtures and observers were adapted from the historical
`bench/computer-cua` prototype at `68a68ccf0f16c0a7f952d55adfe21850247b8ee9`.
Historical checkouts and result artifacts remain unchanged.
@@ -1,91 +0,0 @@
"""Regressions for false success claims and unsafe trial reuse in the original benchmark."""
import unittest
from trial_contract import (DECOY, DiscoveryError, MARKER, acknowledged, completed,
initial_state, prepared, select_unique, summarize, verdict)
class TaskContractTests(unittest.TestCase):
def test_reset_requires_current_command_on_current_fixture(self):
state = {**initial_state("targeted_type"), "instance": "new", "pid": 19, "ack": "current"}
self.assertTrue(prepared(state, "targeted_type", "new", 19, "current"))
for key, value in (("ack", "previous"), ("instance", "old"), ("pid", 20),
("logicalFocus", "field"), ("selLen", 1), ("top", 1), ("dropOpen", True),
("submittedText", "old"), ("clickedColor", "Blue")):
with self.subTest(key=key):
self.assertFalse(prepared({**state, key: value}, "targeted_type", "new", 19, "current"))
self.assertFalse(acknowledged(state, "new", 19, "previous"))
for key in ("submittedText", "clickedColor"):
without_payload = {name: value for name, value in state.items() if name != key}
self.assertFalse(prepared(without_payload, "targeted_type", "new", 19, "current"))
def test_selectors_never_substitute_another_control(self):
selector = (r"button", r"\bincrement\b")
desired = {"role": "button", "label": "Increment"}
self.assertEqual(select_unique([{"role": "button", "label": "Delete"}, desired], selector), desired)
for elements in ([{"role": "button", "label": "Delete"}],
[{"role": "pane", "label": "Increment"}], [desired, dict(desired)], []):
with self.subTest(elements=elements), self.assertRaises(DiscoveryError):
select_unique(elements, selector)
def test_completion_requires_exact_raw_text_and_unchanged_decoy(self):
final = {**initial_state("targeted_type"), "text": MARKER}
self.assertTrue(completed(final, "targeted_type"))
for text in ("q" + MARKER, MARKER + "q", "Orca qcafé Ω", ""):
with self.subTest(text=text):
self.assertFalse(completed({**final, "text": text}, "targeted_type"))
self.assertFalse(completed({**final, "decoyText": DECOY + MARKER}, "targeted_type"))
def test_exactly_once_actions_reject_intermediate_and_duplicate_effects(self):
for task, key in (("choose_and_click", "count"), ("type_submit", "returns"), ("replace_submit", "returns")):
final = {**initial_state(task), key: 1}
if task == "choose_and_click":
final["combo"] = "Blue"
payload, correct, wrong = "clickedColor", "Blue", "Red"
else:
final["text"] = MARKER
payload, correct, wrong = "submittedText", MARKER, ""
final[payload] = correct
self.assertTrue(completed(final, task))
for value in (wrong, None):
with self.subTest(task=task, payload=value):
self.assertFalse(completed({**final, payload: value}, task))
self.assertFalse(completed({name: value for name, value in final.items() if name != payload}, task))
for value in (0, 2):
with self.subTest(task=task, value=value):
self.assertFalse(completed({**final, key: value}, task))
for color in ("Red", "Blue"):
self.assertTrue(completed({**initial_state("click_interference"), "count": 1,
"clickedColor": color}, "click_interference"))
def test_observed_completion_is_independent_of_api_errors(self):
row = {"prepared": True, "task": "targeted_type", "api_errors": ["timeout"]}
self.assertEqual(verdict(row, {**initial_state(row["task"]), "text": MARKER}), "completed")
self.assertEqual(verdict(row, initial_state(row["task"])), "failed")
self.assertEqual(verdict(row, None), "unobserved")
self.assertEqual(verdict({**row, "prepared": False}, None), "invalid_setup")
def test_invalid_setup_does_not_inflate_scored_completion(self):
base = {"engine": "candidate", "task": "targeted_type", "profile": "background"}
result = summarize([{**base, "verdict": "invalid_setup"},
{**base, "verdict": "failed", "discovery_error": "no field"},
{**base, "verdict": "unobserved"},
{**base, "verdict": "completed", "api_errors": ["late error"]}])[0]
self.assertEqual((result["planned"], result["scored"], result["invalid"], result["completed"]), (4, 3, 1, 1))
self.assertEqual((result["discovery_failures"], result["unobserved"], result["api_errors"]), (1, 1, 1))
def test_partial_failures_cannot_make_task_latency_look_fast(self):
base = {"engine": "candidate", "task": "type_submit", "profile": "background"}
result = summarize([{**base, "verdict": "completed", "attempt_ms": 400, "action_read_ms": [100, 150]},
{**base, "verdict": "failed", "attempt_ms": 2, "action_read_ms": [1]},
{**base, "verdict": "unobserved", "attempt_ms": 30000}])[0]
self.assertEqual(result["task_ms"], 400)
self.assertEqual(result["action_read_ms"], 125)
self.assertEqual((result["timed_completions"], result["timed_failures"]), (1, 2))
self.assertEqual(result["failed_attempt_ms"], 15001)
if __name__ == "__main__":
unittest.main()
+9 -11
View File
@@ -1,7 +1,7 @@
// The CLI loads these paths after electron-vite replaces out/main.
export const CLI_MAIN_ENTRY_NAMES = [
'agent-hooks/installation/managed-agent-hook-controls',
'gitlab/project-ref-parser',
'gitlab/projects/project-ref-parser',
'orca-profiles/profile-index-store',
'claude-accounts/keychain',
// The CLI checks a relocated runtime socket dir before it sends the auth token.
@@ -15,16 +15,14 @@ export const CLI_MAIN_ENTRY_NAMES = [
// `orca vm env doctor` runs its checks in the CLI process.
'environment-doctor/environment-doctor',
'environment-doctor/environment-doctor-host',
...[
'access',
'active-location',
'storage-classification',
'offline-settings',
'backup-path',
'database-recovery',
'domain-reader',
'recovery-command'
].map((module) => `persistence/profile-state/profile-state-${module}`),
'persistence/profile-state/access/profile-state-access',
'persistence/profile-state/offline-access/profile-state-active-location',
'persistence/profile-state/database/profile-state-storage-classification',
'persistence/profile-state/offline-access/profile-state-offline-settings',
'persistence/profile-state/backup/profile-state-backup-path',
'persistence/profile-state/recovery/profile-state-database-recovery',
'persistence/profile-state/documents/profile-state-domain-reader',
'persistence/profile-state/recovery/profile-state-recovery-command',
'persistence/profile-state/legacy-json/profile-state-export-path',
'persistence/profile-state/legacy-json/profile-state-recovery',
'startup/http1-compatibility-marker'
@@ -19,7 +19,9 @@ export const MAIN_BUILD_ENTRY_POINTS: Record<string, string> = {
),
'stt-worker': resolve('src/main/speech/stt-worker.ts'),
'warp-theme-parser-worker': resolve('src/main/warp-themes/warp-theme-parser-worker.ts'),
'session-search-worker-entry': resolve('src/main/ai-vault-search/session-search-worker-entry.ts'),
'session-search-worker-entry': resolve(
'src/main/ai-vault-search/worker/session-search-worker-entry.ts'
),
'foreign-sqlite-reader-entry': resolve(
'src/main/foreign-sqlite-readers/foreign-sqlite-reader-entry.ts'
),
@@ -39,7 +41,7 @@ export const MAIN_BUILD_ENTRY_POINTS: Record<string, string> = {
'src/main/worker-thread-child-process/worker-thread-child-process-entry.ts'
),
// Usage scans synchronously walk histories/SQLite; keep them off the main loop.
'usage-scan-worker-entry': resolve('src/main/usage/usage-scan-worker-entry.ts'),
'usage-scan-worker-entry': resolve('src/main/usage/scan-worker/usage-scan-worker-entry.ts'),
'workspace-space-scan-worker-entry': resolve(
'src/main/workspaces/space-analysis/workspace-space-scan-worker-entry.ts'
),
@@ -48,10 +50,10 @@ export const MAIN_BUILD_ENTRY_POINTS: Record<string, string> = {
'src/main/claude-accounts/claude-profile-setup-worker-entry.ts'
),
'profile-state-backup-worker-entry': resolve(
'src/main/persistence/profile-state/profile-state-backup-worker-entry.ts'
'src/main/persistence/profile-state/backup/profile-state-backup-worker-entry.ts'
),
'profile-state-writer-worker-entry': resolve(
'src/main/persistence/profile-state/profile-state-writer-worker-entry.ts'
'src/main/persistence/profile-state/writer/profile-state-writer-worker-entry.ts'
),
// Isolate native @parcel/watcher faults from main (#7547).
'parcel-watcher-process-entry': resolve(
@@ -4,13 +4,13 @@ param(
[Parameter(Mandatory=$true)][hashtable]$Context,
[Parameter(Mandatory=$true)][ValidateSet('win32-arm64','win32-x64')][string]$Target,
[Parameter(Mandatory=$true)][string]$ReceiptRoot,
[ValidateSet('orcad-cmd','orcad-powershell','orcad-convert','orcad-cli-managed','orcad-cli-convert')][string[]]$Cells=@('orcad-cmd','orcad-powershell')
[ValidateSet('orcad-cmd','orcad-powershell','orcad-cli-managed')][string[]]$Cells=@('orcad-cmd','orcad-powershell')
)
$ErrorActionPreference='Stop'
if($env:GITHUB_ACTIONS -ne 'true' -or $env:ORCA_ISOLATED_SSH_CI -ne '1'){throw 'Disposable CI only'}
$shells=@{'orcad-cmd'='cmd';'orcad-powershell'='powershell';'orcad-convert'='cmd';'orcad-cli-managed'='cmd';'orcad-cli-convert'='cmd'}
$shells=@{'orcad-cmd'='cmd';'orcad-powershell'='powershell';'orcad-cli-managed'='cmd'}
# App-level cells drive the e2e build (and the bundled CLI) against the host; each greps one tagged test.
$appCells=@{'orcad-convert'=@('tests/e2e/ssh-orcad-auto-convert.spec.ts','');'orcad-cli-managed'=@('tests/e2e/ssh-orcad-windows-cli-matrix.spec.ts','@orcad-cli-managed');'orcad-cli-convert'=@('tests/e2e/ssh-orcad-windows-cli-matrix.spec.ts','@orcad-cli-convert')}
$appCells=@{'orcad-cli-managed'=@('tests/e2e/ssh-orcad-windows-cli-matrix.spec.ts','@orcad-cli-managed')}
$electronBuilt=$false
if($Context.accounts.Count -lt $Cells.Count){throw 'Each cell needs its own private account'}
$seenApp=$false
+1 -1
View File
@@ -341,7 +341,7 @@ module.exports = {
'out/main/cursor/**',
'out/main/droid/**',
'out/main/gemini/**',
'out/main/gitlab/project-ref-parser.js',
'out/main/gitlab/projects/project-ref-parser.js',
'out/main/grok/**',
'out/main/hermes/**',
'out/main/filesystem/asar-transparent-fs.js',
+13 -48
View File
@@ -2,18 +2,16 @@
# This is a RATCHET: counts may only go DOWN. Run `pnpm lint:ast-grep:flaky-tests` to list them.
# Prune after a fix: pnpm check:flaky-test-pattern-ratchet --prune
1 test-no-in-test-import-actual:src/cli/runtime/launch-serve-replaced-app-restart.test.ts
1 test-no-in-test-import-actual:src/main/bitbucket/credential-connection.test.ts
4 test-no-in-test-import-actual:src/main/bitbucket/credential-store.test.ts
1 test-no-in-test-import-actual:src/main/bitbucket/status-no-decrypt.test.ts
2 test-no-in-test-import-actual:src/main/browser/cookies/browser-cookie-import.comet.test.ts
3 test-no-in-test-import-actual:src/main/claude-usage/scanner-scan.test.ts
1 test-no-in-test-import-actual:src/main/claude/claude-agent-sdk-process-spawn.test.ts
5 test-no-in-test-import-actual:src/main/daemon/endpoint/publication/testing/daemon-endpoint-publish.test.ts
1 test-no-in-test-import-actual:src/main/daemon/history/storage/testing/terminal-history-permissions.test.ts
1 test-no-in-test-import-actual:src/main/git/command-runner/spawned-command-tree-kill.test.ts
1 test-no-in-test-import-actual:src/main/ipc/filesystem/filesystem-content-search-cancellation.test.ts
1 test-no-in-test-import-actual:src/main/linear/client.test.ts
1 test-no-in-test-import-actual:src/main/linear/linear-description-images.test.ts
1 test-no-in-test-import-actual:src/main/linear/accounts/linear-account-client.test.ts
1 test-no-in-test-import-actual:src/main/linear/issues/linear-description-images.test.ts
1 test-no-in-test-import-actual:src/main/omp/omp-session-cwd-lookup.test.ts
1 test-no-in-test-import-actual:src/main/orcad/electron-serve-provider-selection.test.ts
1 test-no-in-test-import-actual:src/main/pty/scrollback/overlay-mirror.test.ts
@@ -38,7 +36,6 @@
1 test-no-polling-loop:src/main/claude/structured/claude-structured-real-cli-stop-task.test.ts
5 test-no-polling-loop:src/main/claude/structured/claude-structured-real-cli.test.ts
1 test-no-polling-loop:src/main/claude/structured/launch/claude-structured-real-cli-options.test.ts
3 test-no-polling-loop:src/main/cli/packaged-cli-assets.test.ts
1 test-no-polling-loop:src/main/codex/hooks/reconciliation/codex-hook-toggle-off-wins.test.ts
1 test-no-polling-loop:src/main/codex/structured/launch/codex-structured-real-cli-command-env.test.ts
1 test-no-polling-loop:src/main/daemon/providers/adapter/testing/daemon-self-retirement-respawn.test.ts
@@ -93,7 +90,6 @@
1 test-no-polling-loop:tests/e2e/fixtures/daemon-generation-reconnect-client.ts
2 test-no-polling-loop:tests/e2e/floating-workspace-reopen-webgl-recovery.spec.ts
1 test-no-polling-loop:tests/e2e/floating-workspace-shared-glyph-atlas.spec.ts
1 test-no-polling-loop:tests/e2e/golden-core-flows.spec.ts
1 test-no-polling-loop:tests/e2e/helpers/computer-cli-driver.ts
2 test-no-polling-loop:tests/e2e/helpers/computer-driver.ts
1 test-no-polling-loop:tests/e2e/helpers/daemon-generation-processes.ts
@@ -170,14 +166,11 @@
2 test-no-real-time-wait:src/main/claude/structured/claude-structured-real-cli-stop-task.test.ts
5 test-no-real-time-wait:src/main/claude/structured/claude-structured-real-cli.test.ts
1 test-no-real-time-wait:src/main/claude/structured/launch/claude-structured-real-cli-options.test.ts
3 test-no-real-time-wait:src/main/cli/packaged-cli-assets.test.ts
3 test-no-real-time-wait:src/main/codex/hooks/installation/hook-service-concurrent-launch-install.test.ts
1 test-no-real-time-wait:src/main/codex/hooks/reconciliation/codex-hook-reconcile.test.ts
1 test-no-real-time-wait:src/main/codex/hooks/reconciliation/codex-hook-toggle-off-wins.test.ts
1 test-no-real-time-wait:src/main/codex/structured/launch/codex-structured-real-cli-command-env.test.ts
1 test-no-real-time-wait:src/main/codex/structured/turns/codex-structured-turn-open-wait.test.ts
1 test-no-real-time-wait:src/main/codex/trust/hooks/codex-hook-hash-lookup.test.ts
1 test-no-real-time-wait:src/main/computer/macos-computer-use-permission-status.test.ts
1 test-no-real-time-wait:src/main/daemon/executable-host/windows/testing/daemon-host-file-hash-cache.test.ts
4 test-no-real-time-wait:src/main/daemon/providers/adapter/testing/daemon-pty-adapter-history-checkpoints.test.ts
2 test-no-real-time-wait:src/main/daemon/providers/adapter/testing/daemon-pty-adapter-history-recovery.test.ts
@@ -199,10 +192,8 @@
3 test-no-real-time-wait:src/main/daemon/transport/client/testing/client.test.ts
1 test-no-real-time-wait:src/main/git/refs/maintenance/local-repo-ref-maintenance.test.ts
4 test-no-real-time-wait:src/main/git/refs/maintenance/repo-ref-maintenance-real-git.test.ts
1 test-no-real-time-wait:src/main/git/worktrees/creation/worktree-configured-paths-concurrency.test.ts
1 test-no-real-time-wait:src/main/git/worktrees/removal/remove-worktree-branch-cleanup.test.ts
1 test-no-real-time-wait:src/main/git/worktrees/removal/worktree-prune-guard.test.ts
1 test-no-real-time-wait:src/main/gitlab/work-item-details.test.ts
1 test-no-real-time-wait:src/main/grok/grok-hook-stdin-no-eof.test.ts
1 test-no-real-time-wait:src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-file-subscription.test.ts
1 test-no-real-time-wait:src/main/ipc/filesystem/watcher-process/rebinding-file-watch-noise.test.ts
@@ -259,7 +250,6 @@
4 test-no-real-time-wait:src/renderer/src/components/activity/activity-auto-mark-read-loop.react185.test.tsx
1 test-no-real-time-wait:src/renderer/src/components/editor/DiagramViewerModal.test.tsx
1 test-no-real-time-wait:src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-stale-analysis-work-budget.test.tsx
4 test-no-real-time-wait:src/renderer/src/components/native-chat/drafts/native-chat-composer-draft-store.test.ts
1 test-no-real-time-wait:src/renderer/src/components/terminal-pane/layout/split/resolve-split-cwd.test.ts
2 test-no-real-time-wait:src/renderer/src/components/terminal-pane/pty-connection/emulation/fish-color-scheme-child-stdin.node-pty.test.ts
1 test-no-real-time-wait:src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-connect-failure-recovery.test.ts
@@ -291,7 +281,6 @@
1 test-no-real-time-wait:tests/e2e/codex-ctrl-c-status.spec.ts
4 test-no-real-time-wait:tests/e2e/combined-diff-scroll-restore.spec.ts
1 test-no-real-time-wait:tests/e2e/computer-windows.e2e.ts
1 test-no-real-time-wait:tests/e2e/cross-version-wire/cross-version-agent-session-wire.unit.test.ts
3 test-no-real-time-wait:tests/e2e/cross-version-wire/host-model-catalog-released-phone.unit.test.ts
1 test-no-real-time-wait:tests/e2e/cross-version-wire/legacy-relay-bridge.unit.test.ts
1 test-no-real-time-wait:tests/e2e/cross-version-wire/released-relay-daemon.ts
@@ -308,7 +297,6 @@
4 test-no-real-time-wait:tests/e2e/floating-workspace-reopen-webgl-recovery.spec.ts
4 test-no-real-time-wait:tests/e2e/floating-workspace-shared-glyph-atlas.spec.ts
2 test-no-real-time-wait:tests/e2e/github-project-board.spec.ts
1 test-no-real-time-wait:tests/e2e/golden-core-flows.spec.ts
1 test-no-real-time-wait:tests/e2e/headless-paired-remote-terminal-reveal-grid.spec.ts
1 test-no-real-time-wait:tests/e2e/headless-paired-remote-terminal-viewer-size.spec.ts
2 test-no-real-time-wait:tests/e2e/helpers/computer-cli-driver.ts
@@ -377,10 +365,8 @@
2 test-no-real-time-wait:tests/e2e/sidebar-sort-stamps.spec.ts
1 test-no-real-time-wait:tests/e2e/sidebar-unread-older-paired-host.spec.ts
2 test-no-real-time-wait:tests/e2e/slept-workspace-remount-wake.spec.ts
1 test-no-real-time-wait:tests/e2e/sparse-preset-proof.spec.ts
1 test-no-real-time-wait:tests/e2e/ssh-orcad-explorer-selected-host.spec.ts
1 test-no-real-time-wait:tests/e2e/ssh-orcad-idle-exit.spec.ts
1 test-no-real-time-wait:tests/e2e/ssh-orcad-legacy-relay-bridge.spec.ts
1 test-no-real-time-wait:tests/e2e/ssh-orcad-pairing-repair.spec.ts
1 test-no-real-time-wait:tests/e2e/ssh-orcad-relay-tab-only-shell.spec.ts
1 test-no-real-time-wait:tests/e2e/ssh-orcad-sleep-disconnected.spec.ts
@@ -453,14 +439,11 @@
4 test-no-wall-clock:src/main/agent-hooks/server/testing/identity/server-launch-resume-identity.test.ts
5 test-no-wall-clock:src/main/agent-hooks/server/testing/replay/spool.test.ts
2 test-no-wall-clock:src/main/agent-hooks/installation/commands/windows-native-hook-exe-hosts.test.ts
2 test-no-wall-clock:src/main/ai-vault-search/session-search-indexer.test.ts
1 test-no-wall-clock:src/main/ai-vault/parse-cache/session-parse-cache-preview-upgrade.test.ts
1 test-no-wall-clock:src/main/ai-vault/scanners/copilot/session-scanner-copilot-cache-upgrade.test.ts
2 test-no-wall-clock:src/main/ai-vault/scanners/copilot/session-scanner-copilot-parser.test.ts
2 test-no-wall-clock:src/main/ai-vault/scanners/cursor/session-scanner-cursor-chat-meta.test.ts
1 test-no-wall-clock:src/main/ai-vault/scanners/devin/session-scanner-devin-db.test.ts
2 test-no-wall-clock:src/main/ai-vault/scanners/grok/session-scanner-grok-parser.test.ts
3 test-no-wall-clock:src/main/ai-vault/scanners/jcode/session-scanner-jcode-parser.test.ts
1 test-no-wall-clock:src/main/ai-vault/scanners/kimi/session-scanner-kimi-parser.test.ts
1 test-no-wall-clock:src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-process.test.ts
2 test-no-wall-clock:src/main/ai-vault/scanners/opencode/session-scanner-opencode-parser.test.ts
@@ -477,11 +460,8 @@
3 test-no-wall-clock:src/main/claude/structured/claude-structured-real-cli-stop-task.test.ts
10 test-no-wall-clock:src/main/claude/structured/claude-structured-real-cli.test.ts
3 test-no-wall-clock:src/main/claude/structured/launch/claude-structured-real-cli-options.test.ts
1 test-no-wall-clock:src/main/cli/appimage-generation-lease.test.ts
6 test-no-wall-clock:src/main/cli/packaged-cli-assets.test.ts
1 test-no-wall-clock:src/main/codex-accounts/legacy-wsl-runtime-auth-drain-rollback-script.test.ts
6 test-no-wall-clock:src/main/codex/app-server/codex-app-server-client.test.ts
1 test-no-wall-clock:src/main/codex/structured/catalog/codex-usage-limits.test.ts
2 test-no-wall-clock:src/main/codex/structured/launch/codex-structured-real-cli-command-env.test.ts
2 test-no-wall-clock:src/main/codex/trust/hooks/codex-hook-trust-derivation.test.ts
1 test-no-wall-clock:src/main/daemon/admission/testing/terminal-spawn-gate-legacy-restores.test.ts
@@ -507,7 +487,6 @@
3 test-no-wall-clock:src/main/github/pr-refresh-coordinator-active-visible-priority.test.ts
8 test-no-wall-clock:src/main/github/pr-refresh-coordinator-alias-coalescing.test.ts
5 test-no-wall-clock:src/main/github/pr-refresh-coordinator-completion-order.test.ts
1 test-no-wall-clock:src/main/github/pr-refresh-coordinator-error-cadence.test.ts
3 test-no-wall-clock:src/main/github/pr-refresh-coordinator-foreground-pacing.test.ts
3 test-no-wall-clock:src/main/github/pr-refresh-coordinator-refresh-events.test.ts
4 test-no-wall-clock:src/main/github/pr-refresh-coordinator-visibility-policy.test.ts
@@ -524,22 +503,17 @@
3 test-no-wall-clock:src/main/managed-server/install/remote-node-runtime-store-gc.test.ts
1 test-no-wall-clock:src/main/native-chat/agent-session-attachments/agent-session-attachment-sweep.test.ts
1 test-no-wall-clock:src/main/observability/bundle.test.ts
1 test-no-wall-clock:src/main/opencode/opencode-launch-model-context-supervision.test.ts
1 test-no-wall-clock:src/main/opencode/overlay-dir-gc.test.ts
2 test-no-wall-clock:src/main/orca-profiles/profile-cloud-service-connect-overlap.test.ts
2 test-no-wall-clock:src/main/orca-profiles/profile-cloud-service-sign-out-connect-race.test.ts
1 test-no-wall-clock:src/main/opencode/status-hooks/overlay-dir-gc.test.ts
2 test-no-wall-clock:src/main/orca-profiles/cloud-auth/profile-cloud-service-connect-overlap.test.ts
2 test-no-wall-clock:src/main/orca-profiles/cloud-auth/profile-cloud-service-sign-out-connect-race.test.ts
2 test-no-wall-clock:src/main/orcad/orcad-artifact-cache-retention.test.ts
1 test-no-wall-clock:src/main/orcad/orcad-artifact-materializer.test.ts
6 test-no-wall-clock:src/main/orcad/orcad-serve-parity.integration.test.ts
1 test-no-wall-clock:src/main/orcad/orcad-stale-lock-reclaim.test.ts
3 test-no-wall-clock:src/main/orcad/orcad-stop-request-shutdown.integration.test.ts
1 test-no-wall-clock:src/main/persistence/closed-terminal-tab-write-fence.test.ts
1 test-no-wall-clock:src/main/persistence/loading-store/profile-state-temp-cleanup-lifetime.test.ts
1 test-no-wall-clock:src/main/persistence/loading-store/pty-spawn-restore-durability.test.ts
1 test-no-wall-clock:src/main/persistence/profile-state/profile-state-backup-rotation.test.ts
2 test-no-wall-clock:src/main/persistence/profile-state/profile-state-backup-temporary-files.test.ts
1 test-no-wall-clock:src/main/persistence/profile-state/profile-state-pre-migration-backup.test.ts
1 test-no-wall-clock:src/main/persistence/profile-state/profile-state-section-repair.test.ts
1 test-no-wall-clock:src/main/persistence/profile-state/backup/profile-state-backup-rotation.test.ts
1 test-no-wall-clock:src/main/persistence/profile-state/recovery/profile-state-section-repair.test.ts
2 test-no-wall-clock:src/main/persistence/tracking-repos/persistence-deregistered-repo-residue.test.ts
1 test-no-wall-clock:src/main/persistence/tracking-repos/worktree-metadata-normalization.test.ts
2 test-no-wall-clock:src/main/provider-process/provider-group-orphan-guard.integration.test.ts
@@ -558,7 +532,6 @@
2 test-no-wall-clock:src/main/runtime/agent-session/structured-agent-session-held-signal.test.ts
1 test-no-wall-clock:src/main/runtime/agent-session/structured-child-records-switch.test.ts
1 test-no-wall-clock:src/main/runtime/mobile-cloud-relay/mobile-relay-e2ee.integration.test.ts
1 test-no-wall-clock:src/main/runtime/mobile-cloud-relay/relay-http-client.test.ts
2 test-no-wall-clock:src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-codex-real-pty.integration.test.ts
2 test-no-wall-clock:src/main/runtime/orchestration/workers/archives/worker-output-archive.test.ts
3 test-no-wall-clock:src/main/runtime/orchestration/workers/archives/worker-terminal-archive-release.test.ts
@@ -614,7 +587,6 @@
3 test-no-wall-clock:src/main/windows/windows-msys-job.win32.test.ts
1 test-no-wall-clock:src/main/windows/windows-process-table-native-addon.win32.test.ts
2 test-no-wall-clock:src/main/windows/windows-pty-job.win32.test.ts
2 test-no-wall-clock:src/main/workspace-hooks/hook-archive-timeout-observation.test.ts
2 test-no-wall-clock:src/main/workspaces/removal/local-worktree-removal-recovery-live.test.ts
1 test-no-wall-clock:src/main/workspaces/removal/worktree-removal-close-records.test.ts
2 test-no-wall-clock:src/main/wsl/execution/wsl-runner.wsl.test.ts
@@ -622,12 +594,10 @@
3 test-no-wall-clock:src/renderer/src/components/activity/activity-auto-mark-read-loop.react185.test.tsx
2 test-no-wall-clock:src/renderer/src/components/artifacts/ArtifactCollection.test.tsx
1 test-no-wall-clock:src/renderer/src/components/browser-pane/assemble-chrome/browser-workspace-pane.adoption-chrome.test.tsx
2 test-no-wall-clock:src/renderer/src/components/dashboard/useLiveDashboardSnapshot.test.ts
3 test-no-wall-clock:src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx
2 test-no-wall-clock:src/renderer/src/components/native-chat/tools/tasks/NativeChatStructuredSessionStatus.test.tsx
1 test-no-wall-clock:src/renderer/src/components/sidebar/workspace-card/review/use-workspace-reference-details.test.tsx
1 test-no-wall-clock:src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.lineage-agent-expansion-coupling.test.tsx
2 test-no-wall-clock:src/renderer/src/components/task-page/jira/task-page-jira-cache-selectors.test.ts
2 test-no-wall-clock:src/renderer/src/components/terminal-pane/pty-connection/emulation/fish-color-scheme-child-stdin.node-pty.test.ts
2 test-no-wall-clock:src/renderer/src/components/terminal-pane/snapshots/remote-snapshot-alt-screen-host-chain.test.ts
1 test-no-wall-clock:src/renderer/src/components/terminal/initial-terminal-structured-launch.test.tsx
@@ -655,7 +625,6 @@
4 test-no-wall-clock:tests/e2e/cross-version-wire/release-checkout.unit.test.ts
2 test-no-wall-clock:tests/e2e/cross-version-wire/release-source-retention.unit.test.ts
1 test-no-wall-clock:tests/e2e/host-cold-park-remote-subscriber.unit.test.ts
2 test-no-wall-clock:tests/e2e/omp-child-session-recovery.unit.test.ts
2 test-timeout-needs-reason:mobile/src/terminal/document/native-document-bundle.test.ts
1 test-timeout-needs-reason:mobile/src/test-support/rpc-recording/family-recordings.test.ts
1 test-timeout-needs-reason:mobile/src/test-support/rpc-recording/mutants/family-mutants.test.ts
@@ -665,7 +634,6 @@
2 test-timeout-needs-reason:src/main/acp/journal/acp-structured-broken-stream.test.ts
4 test-timeout-needs-reason:src/main/agent-hooks/server/testing/http/server-transport-interference.test.ts
1 test-timeout-needs-reason:src/main/agent-hooks/wsl-relay/testing/wsl-hook-relay-live.integration.test.ts
1 test-timeout-needs-reason:src/main/ai-vault/parse-cache/session-parse-cache-large-scan.test.ts
1 test-timeout-needs-reason:src/main/antigravity/native-macos-credentials.real.test.ts
1 test-timeout-needs-reason:src/main/antigravity/posix-hook-invocation.test.ts
2 test-timeout-needs-reason:src/main/antigravity/windows-hook-json-post.test.ts
@@ -722,7 +690,6 @@
1 test-timeout-needs-reason:src/main/orcad/orcad-stop-request-shutdown.integration.test.ts
1 test-timeout-needs-reason:src/main/orcad/orcad-windows-conpty-breakaway.integration.test.ts
1 test-timeout-needs-reason:src/main/persistence/applying-settings/persistence-source-control-ai-migration.test.ts
1 test-timeout-needs-reason:src/main/persistence/profile-state/profile-state-writer-stall.electron.test.ts
1 test-timeout-needs-reason:src/main/plugins/workers/plugin-worker-supervision.integration.test.ts
2 test-timeout-needs-reason:src/main/providers/agent-foreground-process-git-bash.win32.test.ts
1 test-timeout-needs-reason:src/main/providers/local-pty/local-pty-child-process-verdict.test.ts
@@ -750,7 +717,7 @@
1 test-timeout-needs-reason:src/main/windows/windows-msys-job.win32.test.ts
2 test-timeout-needs-reason:src/main/windows/windows-pty-job.win32.test.ts
5 test-timeout-needs-reason:src/main/worker-thread-child-process/worker-thread-child-process.test.ts
2 test-timeout-needs-reason:src/main/workspace-hooks/hook-archive-timeout-observation.test.ts
1 test-timeout-needs-reason:src/main/workspace-hooks/hook-archive-timeout-observation.test.ts
2 test-timeout-needs-reason:src/main/workspace-hooks/hook-termination-real-process.test.ts
2 test-timeout-needs-reason:src/main/workspaces/removal/local-worktree-filesystem-wsl-banner.wsl.test.ts
4 test-timeout-needs-reason:src/main/wsl/execution/wsl-runner.wsl.test.ts
@@ -799,7 +766,7 @@
1 test-timeout-needs-reason:tests/e2e/headless-serve-chat-tab-placement.spec.ts
1 test-timeout-needs-reason:tests/e2e/headless-serve-cli-terminal-retention-parity.spec.ts
1 test-timeout-needs-reason:tests/e2e/headless-serve-mobile-markdown.spec.ts
3 test-timeout-needs-reason:tests/e2e/headless-serve-mobile-native-chat-identity.spec.ts
1 test-timeout-needs-reason:tests/e2e/headless-serve-mobile-native-chat-identity.spec.ts
4 test-timeout-needs-reason:tests/e2e/helpers/electron-process-shutdown.unit.test.ts
1 test-timeout-needs-reason:tests/e2e/host-parked-pane-remote-viewer.spec.ts
2 test-timeout-needs-reason:tests/e2e/host-terminal-agent-phone-push.spec.ts
@@ -848,7 +815,6 @@
2 test-timeout-needs-reason:tests/e2e/paired-host-usage-credentials.spec.ts
7 test-timeout-needs-reason:tests/e2e/paired-instant-browser-tab.spec.ts
1 test-timeout-needs-reason:tests/e2e/paired-mobile-desktop-mirror-files-git-review.spec.ts
1 test-timeout-needs-reason:tests/e2e/paired-mobile-desktop-mirror-server-browser.spec.ts
1 test-timeout-needs-reason:tests/e2e/paired-mobile-desktop-mirror-workspace-visibility.spec.ts
2 test-timeout-needs-reason:tests/e2e/paired-mobile-desktop-mirror.spec.ts
1 test-timeout-needs-reason:tests/e2e/paired-mobile-desktop-tab-composition.spec.ts
@@ -877,7 +843,7 @@
1 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts
1 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-reconnect-idle-frame.spec.ts
1 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-retention-memory.spec.ts
2 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-serve-restart-binding.spec.ts
1 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-serve-restart-binding.spec.ts
1 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-stall-recovery.spec.ts
2 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts
1 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-wide-viewport.spec.ts
@@ -890,7 +856,7 @@
1 test-timeout-needs-reason:tests/e2e/paired-two-client-emptied-workspace-reseed.spec.ts
1 test-timeout-needs-reason:tests/e2e/paired-usage-owner-placeholders.spec.ts
1 test-timeout-needs-reason:tests/e2e/paired-worktree-activation-isolation.spec.ts
5 test-timeout-needs-reason:tests/e2e/persisted-session-production-upgrade.spec.ts
3 test-timeout-needs-reason:tests/e2e/persisted-session-production-upgrade.spec.ts
1 test-timeout-needs-reason:tests/e2e/pr11346-selected-runtime-add.spec.ts
1 test-timeout-needs-reason:tests/e2e/profile-state-automatic-backup-recovery.spec.ts
3 test-timeout-needs-reason:tests/e2e/relay-region-correction.unit.test.ts
@@ -912,7 +878,6 @@
2 test-timeout-needs-reason:tests/e2e/sidebar-unread-older-paired-host.spec.ts
1 test-timeout-needs-reason:tests/e2e/sidebar-workspace-rows.spec.ts
1 test-timeout-needs-reason:tests/e2e/source-control-large-file-count.spec.ts
5 test-timeout-needs-reason:tests/e2e/ssh-orcad-auto-convert.spec.ts
1 test-timeout-needs-reason:tests/e2e/ssh-orcad-browser-drop-owner.spec.ts
1 test-timeout-needs-reason:tests/e2e/ssh-orcad-browser-routing.spec.ts
1 test-timeout-needs-reason:tests/e2e/ssh-orcad-browser-service-status.spec.ts
@@ -923,7 +888,7 @@
1 test-timeout-needs-reason:tests/e2e/ssh-orcad-explorer-selected-host.spec.ts
1 test-timeout-needs-reason:tests/e2e/ssh-orcad-explorer-watch-recovery.spec.ts
4 test-timeout-needs-reason:tests/e2e/ssh-orcad-idle-exit.spec.ts
3 test-timeout-needs-reason:tests/e2e/ssh-orcad-legacy-relay-bridge.spec.ts
1 test-timeout-needs-reason:tests/e2e/ssh-orcad-legacy-relay-bridge.spec.ts
1 test-timeout-needs-reason:tests/e2e/ssh-orcad-markdown-conversion.spec.ts
1 test-timeout-needs-reason:tests/e2e/ssh-orcad-markdown-link-refresh.spec.ts
1 test-timeout-needs-reason:tests/e2e/ssh-orcad-markdown-live-documents.spec.ts
@@ -942,7 +907,7 @@
1 test-timeout-needs-reason:tests/e2e/ssh-orcad-terminal-root-owner.spec.ts
1 test-timeout-needs-reason:tests/e2e/ssh-orcad-unbindable-tunnel-port.spec.ts
1 test-timeout-needs-reason:tests/e2e/ssh-orcad-update-anyway.spec.ts
2 test-timeout-needs-reason:tests/e2e/ssh-orcad-windows-cli-matrix.spec.ts
1 test-timeout-needs-reason:tests/e2e/ssh-orcad-windows-cli-matrix.spec.ts
4 test-timeout-needs-reason:tests/e2e/ssh-orcad-workspace-tools.spec.ts
1 test-timeout-needs-reason:tests/e2e/staging-skill-sharing.spec.ts
1 test-timeout-needs-reason:tests/e2e/structured-chat-tabs-open-close.spec.ts
+1 -1
View File
@@ -3,5 +3,5 @@
# This is a RATCHET: entries may only be REMOVED. Take RepoHostTarget or HostWorktreeTarget,
# or match the row by id AND host (getRepoExecutionHostId).
# Prune after a fix: pnpm check:id-only-store-write-ratchet --prune
lookup:src/main/persistence/loading-store/terminal-binding-recovery.ts#getConnectionIdForWorktree
lookup:src/main/persistence/loading-store/terminal-bindings/terminal-binding-recovery.ts#getConnectionIdForWorktree
lookup:src/main/persistence/tracking-repos/project-host-operations.ts#getRepo
+3 -3
View File
@@ -41,11 +41,11 @@
"src/main/plugins/testing/plugin-test-register.ts",
"src/main/ai-vault/scan-service/session-scanner-service-entry.ts",
"src/main/native-chat/wsl-transcript-fs-process-entry.ts",
"src/main/usage/usage-scan-worker-entry.ts",
"src/main/usage/scan-worker/usage-scan-worker-entry.ts",
"src/main/workspaces/space-analysis/workspace-space-scan-worker-entry.ts",
"src/main/claude-accounts/claude-profile-setup-worker-entry.ts",
"src/main/persistence/profile-state/profile-state-backup-worker-entry.ts",
"src/main/persistence/profile-state/profile-state-writer-worker-entry.ts",
"src/main/persistence/profile-state/backup/profile-state-backup-worker-entry.ts",
"src/main/persistence/profile-state/writer/profile-state-writer-worker-entry.ts",
"src/main/orcad/orcad-local-serve-selection-entry.ts",
"src/main/orcad/launcher.ts",
"src/main/claude-accounts/claude-profile-wsl-entry.ts",
@@ -12,7 +12,6 @@ src/main/runtime/orchestration/terminal-authority/verify-orchestration-compatibi
src/main/runtime/orchestration/terminal-authority/orchestration-compatibility-authority.ts
src/main/managed-server/migration/cutover/orcad-migration-delta-move.test.ts
src/main/managed-server/migration/cutover/orcad-migration-delta-move.ts
src/main/managed-server/migration/linking/orcad-migration-repository-link.test.ts
src/main/ssh/migration-source/orcad-migration-terminal-gate.test.ts
src/main/ssh/migration-source/orcad-migration-terminal-gate.ts
src/main/ssh/host-server/ssh-host-server-on-connect.ts
@@ -2,7 +2,6 @@
# The relay retirement (2027-01-15) deletes the folder and edits exactly these files.
# Prune: pnpm check:legacy-relay-fence-ratchet --prune
src/main/ipc/runtime-environments/orcad-delta-move-handlers.ts
src/main/ipc/pty/runtime/kill-legacy-relay-bridged.test.ts
src/main/ipc/pty/runtime/kill.ts
src/main/ipc/ssh/ssh-connect-decision-cancellation.test.ts
src/main/ipc/ssh/ssh-connect-flow.ts
+30 -30
View File
@@ -11,37 +11,37 @@
1 src/main/ipc/runtime-environments/runtime-environment-removal-cleanup.ts
1 src/main/ipc/runtime-environments/runtime-environment-session-reconcile.ts
2 src/main/ipc/session.ts
6 src/main/orca-profiles/profile-project-session-state.ts
4 src/main/orca-profiles/profile-project-source-removal.ts
2 src/main/orca-profiles/profile-project-state-file.ts
4 src/main/orca-profiles/profile-project-transfer-payload.ts
2 src/main/orca-profiles/profile-project-transfer.ts
9 src/main/orca-profiles/profile-session-owner-transfer.ts
6 src/main/orca-profiles/project-transfer/profile-project-session-state.ts
4 src/main/orca-profiles/project-transfer/profile-project-source-removal.ts
2 src/main/orca-profiles/project-transfer/profile-project-state-file.ts
4 src/main/orca-profiles/project-transfer/profile-project-transfer-payload.ts
2 src/main/orca-profiles/project-transfer/profile-project-transfer.ts
9 src/main/orca-profiles/project-transfer/profile-session-owner-transfer.ts
3 src/main/persistence/leasing-ssh-ptys/ssh-pty-binding-cleanup.ts
1 src/main/persistence/loading-store/loaded-state-parsing.ts
1 src/main/persistence/loading-store/metadata-lineage-operations.ts
1 src/main/persistence/loading-store/mobile-tab-selection-persistence.ts
1 src/main/persistence/loading-store/normalize-loaded-profile-state.ts
8 src/main/persistence/loading-store/pty-binding-persistence.ts
10 src/main/persistence/loading-store/pty-binding-session-update.ts
10 src/main/persistence/loading-store/repo-lifecycle-operations.ts
10 src/main/persistence/loading-store/session-host-partitions.ts
9 src/main/persistence/loading-store/session-snapshot-operations.ts
2 src/main/persistence/loading-store/state-serialization-secret-handling.ts
4 src/main/persistence/loading-store/workspace-session-snapshot-publication.ts
4 src/main/persistence/loading-store/workspace-session-terminal-binding-replay.ts
2 src/main/persistence/migrating-orcad-catalog/orcad-destination-client-state.ts
1 src/main/persistence/migrating-orcad-catalog/orcad-destination-workspace-session.ts
3 src/main/persistence/migrating-orcad-catalog/orcad-dormant-state-records.ts
1 src/main/persistence/migrating-orcad-catalog/orcad-migration-source-retention.ts
2 src/main/persistence/migrating-orcad-catalog/orcad-source-client-subtraction.ts
1 src/main/persistence/migrating-orcad-catalog/orcad-source-dormant-state.ts
1 src/main/persistence/migrating-orcad-catalog/orcad-source-scrollback-state.ts
1 src/main/persistence/migrating-orcad-catalog/orcad-source-workspace-session-eligibility.ts
3 src/main/persistence/migrating-orcad-catalog/orcad-source-workspace-session-layout.ts
4 src/main/persistence/migrating-orcad-catalog/orcad-source-workspace-session-subtraction.ts
1 src/main/persistence/migrating-orcad-catalog/orcad-source-workspace-session.ts
2 src/main/persistence/moving-wsl-projects/wsl-move-main-rewrite-stores.ts
1 src/main/persistence/loading-store/profile-loading/loaded-state-parsing.ts
1 src/main/persistence/loading-store/workspace-lineage/metadata-lineage-operations.ts
1 src/main/persistence/loading-store/profile-preferences/mobile-tab-selection-persistence.ts
1 src/main/persistence/loading-store/profile-loading/normalize-loaded-profile-state.ts
8 src/main/persistence/loading-store/terminal-bindings/pty-binding-persistence.ts
10 src/main/persistence/loading-store/terminal-bindings/pty-binding-session-update.ts
10 src/main/persistence/loading-store/project-catalog/repo-lifecycle-operations.ts
10 src/main/persistence/loading-store/workspace-sessions/session-host-partitions.ts
9 src/main/persistence/loading-store/workspace-sessions/session-snapshot-operations.ts
2 src/main/persistence/loading-store/profile-writing/state-serialization-secret-handling.ts
4 src/main/persistence/loading-store/workspace-sessions/workspace-session-snapshot-publication.ts
4 src/main/persistence/loading-store/workspace-sessions/workspace-session-terminal-binding-replay.ts
2 src/main/persistence/migrating-orcad-catalog/destination/orcad-destination-client-state.ts
1 src/main/persistence/migrating-orcad-catalog/destination/orcad-destination-workspace-session.ts
3 src/main/persistence/migrating-orcad-catalog/destination/orcad-dormant-state-records.ts
1 src/main/persistence/migrating-orcad-catalog/retained-source/orcad-migration-source-retention.ts
2 src/main/persistence/migrating-orcad-catalog/source/clients/orcad-source-client-subtraction.ts
1 src/main/persistence/migrating-orcad-catalog/source/dormancy/orcad-source-dormant-state.ts
1 src/main/persistence/migrating-orcad-catalog/source/scrollback/orcad-source-scrollback-state.ts
1 src/main/persistence/migrating-orcad-catalog/source/sessions/orcad-source-workspace-session-eligibility.ts
3 src/main/persistence/migrating-orcad-catalog/source/sessions/orcad-source-workspace-session-layout.ts
4 src/main/persistence/migrating-orcad-catalog/source/sessions/orcad-source-workspace-session-subtraction.ts
1 src/main/persistence/migrating-orcad-catalog/source/sessions/orcad-source-workspace-session.ts
2 src/main/persistence/moving-wsl-projects/desktop-state/wsl-move-main-rewrite-stores.ts
1 src/main/persistence/restoring-sessions/folder-workspace-operations.ts
1 src/main/persistence/restoring-sessions/invalid-workspace-layout-purge.ts
5 src/main/persistence/restoring-sessions/session-owner-fields.ts
+74 -74
View File
@@ -14,7 +14,7 @@
14 src/main/agent-launch/trust/agent-trust-presets.ts
2 src/main/agent-launch/trust/antigravity-workspace-trust-ownership.ts
1 src/main/agent-launch/trust/execution-host-workspace-trust.ts
1 src/main/ai-vault-search/session-search-worker-client.ts
1 src/main/ai-vault-search/worker/session-search-worker-client.ts
4 src/main/ai-vault/parse-cache/session-parse-cache-legacy-json.ts
2 src/main/ai-vault/scan-service/session-scanner-service-entry-path.ts
1 src/main/ai-vault/scan-service/session-scanner-service-spawn.ts
@@ -97,18 +97,18 @@
1 src/main/claude/hook-service.ts
3 src/main/claude/statusline-install.ts
6 src/main/claude/windows-hook-files.ts
1 src/main/cli/appimage-copy-pre-extraction.ts
3 src/main/cli/appimage-extracted-root.ts
1 src/main/cli/appimage-extraction-pruning.ts
2 src/main/cli/appimage-generation-lease.ts
4 src/main/cli/appimage-generation-residency.ts
16 src/main/cli/appimage-stable-launcher.ts
1 src/main/cli/cli-command-inspection.ts
1 src/main/cli/cli-dev-launcher.ts
3 src/main/cli/cli-install-location.ts
2 src/main/cli/linux-bare-orca-dispatcher.ts
7 src/main/cli/linux-terminal-orca-cli-shim.ts
2 src/main/cli/wsl-managed-cli.ts
1 src/main/cli/appimage/appimage-copy-pre-extraction.ts
3 src/main/cli/appimage/appimage-extracted-root.ts
1 src/main/cli/appimage/appimage-extraction-pruning.ts
2 src/main/cli/appimage/appimage-generation-lease.ts
4 src/main/cli/appimage/appimage-generation-residency.ts
16 src/main/cli/appimage/appimage-stable-launcher.ts
1 src/main/cli/installation/cli-command-inspection.ts
1 src/main/cli/launchers/cli-dev-launcher.ts
3 src/main/cli/installation/cli-install-location.ts
2 src/main/cli/launchers/linux-bare-orca-dispatcher.ts
7 src/main/cli/launchers/linux-terminal-orca-cli-shim.ts
2 src/main/cli/wsl/wsl-managed-cli.ts
2 src/main/codex-accounts/codex-account-identity.ts
3 src/main/codex-accounts/codex-account-registration.ts
4 src/main/codex-accounts/codex-config-mirror.ts
@@ -166,14 +166,14 @@
1 src/main/codex/trust/identity/codex-trust-identity.ts
1 src/main/codex/trust/toml/config-toml-project-trust.ts
7 src/main/codex/trust/toml/config-toml-trust.ts
2 src/main/computer/desktop-script-provider-paths.ts
1 src/main/computer/macos-native-provider-client.ts
3 src/main/computer/macos-native-provider-paths.ts
5 src/main/computer/macos-native-provider-transport.ts
1 src/main/computer/sidecar-client.ts
2 src/main/computer/desktop-script/desktop-script-provider-paths.ts
1 src/main/computer/macos-native/macos-native-provider-client.ts
3 src/main/computer/macos-native/macos-native-provider-paths.ts
5 src/main/computer/macos-native/macos-native-provider-transport.ts
1 src/main/computer/sidecar-transport/sidecar-client.ts
3 src/main/connector-cloud/connector-turn-events.ts
1 src/main/copilot/hook-service.ts
4 src/main/crash-reporting/appimage-crashpad-handler-exit.ts
4 src/main/crash-reporting/capture/appimage-crashpad-handler-exit.ts
2 src/main/credentials/credential-file-protection.ts
6 src/main/credentials/encrypted-api-key-file-store.ts
10 src/main/credentials/integration-credential-file.ts
@@ -296,10 +296,10 @@
13 src/main/kimi/hook-service.ts
3 src/main/kiro/hook-service.ts
1 src/main/kiro/standalone-hooks.ts
4 src/main/linear/linear-credential-paths.ts
3 src/main/linear/linear-legacy-viewer-store.ts
1 src/main/linear/linear-token-store.ts
3 src/main/linear/linear-workspace-registry.ts
4 src/main/linear/accounts/linear-credential-paths.ts
3 src/main/linear/accounts/linear-legacy-viewer-store.ts
1 src/main/linear/accounts/linear-token-store.ts
3 src/main/linear/accounts/linear-workspace-registry.ts
1 src/main/macos-permissions/macos-tcc-prompt-notice.ts
3 src/main/managed-data-accounts/credential-capture.ts
18 src/main/managed-data-accounts/profile-removal.ts
@@ -323,22 +323,22 @@
1 src/main/observability/bounded-log-file-writer.ts
2 src/main/observability/bundle.ts
6 src/main/observability/local-file-sink.ts
14 src/main/opencode/hook-service.ts
1 src/main/opencode/legacy-plugin-acl-retry.ts
2 src/main/opencode/opencode-overlay-manifest.ts
1 src/main/opencode/opencode-plugin-config-writer.ts
14 src/main/opencode/status-hooks/hook-service.ts
1 src/main/opencode/status-hooks/legacy-plugin-acl-retry.ts
2 src/main/opencode/status-hooks/opencode-overlay-manifest.ts
1 src/main/opencode/status-hooks/opencode-plugin-config-writer.ts
1 src/main/opencode/opencode-private-server.ts
1 src/main/opencode/opencode-wsl-text-task.ts
2 src/main/orca-profiles/new-profile-state.ts
3 src/main/orca-profiles/other-profile-workspace-catalog.ts
3 src/main/orca-profiles/profile-artifact-cloud-cleanup.ts
1 src/main/orca-profiles/profile-cloud-index.ts
4 src/main/orca-profiles/profile-cloud-session-store.ts
1 src/main/opencode/text-tasks/wsl/opencode-wsl-text-task.ts
2 src/main/orca-profiles/storage/new-profile-state.ts
3 src/main/orca-profiles/catalog/other-profile-workspace-catalog.ts
3 src/main/orca-profiles/cloud-auth/profile-artifact-cloud-cleanup.ts
1 src/main/orca-profiles/cloud-auth/profile-cloud-index.ts
4 src/main/orca-profiles/cloud-session/profile-cloud-session-store.ts
12 src/main/orca-profiles/profile-index-store.ts
5 src/main/orca-profiles/profile-legacy-state-import.ts
4 src/main/orca-profiles/profile-project-move-intent.ts
3 src/main/orca-profiles/profile-project-move-record.ts
4 src/main/orca-profiles/profile-project-state-file.ts
5 src/main/orca-profiles/storage/profile-legacy-state-import.ts
4 src/main/orca-profiles/project-transfer/profile-project-move-intent.ts
3 src/main/orca-profiles/project-transfer/profile-project-move-record.ts
4 src/main/orca-profiles/project-transfer/profile-project-state-file.ts
2 src/main/orcad/launcher.ts
7 src/main/orcad/node-pty-prebuilt-slot.ts
2 src/main/orcad/node-pty-precondition.ts
@@ -375,18 +375,18 @@
1 src/main/orcad/serve-profile-ssh-targets.ts
6 src/main/persistence/atomic-snapshot-writer.ts
5 src/main/persistence/loading-store/user-data-path.ts
9 src/main/persistence/migrating-orcad-catalog/migration-journal-directory.ts
4 src/main/persistence/migrating-orcad-catalog/orcad-migration-blob-installers.ts
3 src/main/persistence/migrating-orcad-catalog/orcad-migration-blob-staging.ts
17 src/main/persistence/migrating-orcad-catalog/orcad-migration-staged-file.ts
1 src/main/persistence/migrating-orcad-catalog/orcad-scrollback-snapshot-transfer.ts
11 src/main/persistence/migrating-orcad-catalog/orcad-shell-history-installer.ts
7 src/main/persistence/migrating-orcad-catalog/orcad-terminal-history-installer.ts
1 src/main/persistence/migrating-orcad-catalog/orcad-terminal-restore-hint-store.ts
1 src/main/persistence/moving-wsl-projects/wsl-move-orchestration-history-rewrite.ts
1 src/main/persistence/moving-wsl-projects/wsl-move-orchestrator-store.ts
6 src/main/persistence/moving-wsl-projects/wsl-move-slept-scrollback.ts
2 src/main/persistence/moving-wsl-projects/wsl-move-slept-spool-sweep.ts
9 src/main/persistence/migrating-orcad-catalog/cutover-journals/migration-journal-directory.ts
4 src/main/persistence/migrating-orcad-catalog/blob-transfer/orcad-migration-blob-installers.ts
3 src/main/persistence/migrating-orcad-catalog/blob-transfer/orcad-migration-blob-staging.ts
17 src/main/persistence/migrating-orcad-catalog/blob-transfer/orcad-migration-staged-file.ts
1 src/main/persistence/migrating-orcad-catalog/terminal-history/orcad-scrollback-snapshot-transfer.ts
11 src/main/persistence/migrating-orcad-catalog/terminal-history/orcad-shell-history-installer.ts
7 src/main/persistence/migrating-orcad-catalog/terminal-history/orcad-terminal-history-installer.ts
1 src/main/persistence/migrating-orcad-catalog/terminal-history/orcad-terminal-restore-hint-store.ts
1 src/main/persistence/moving-wsl-projects/desktop-state/wsl-move-orchestration-history-rewrite.ts
1 src/main/persistence/moving-wsl-projects/orchestration/wsl-move-orchestrator-store.ts
6 src/main/persistence/moving-wsl-projects/terminal-state/wsl-move-slept-scrollback.ts
2 src/main/persistence/moving-wsl-projects/terminal-state/wsl-move-slept-spool-sweep.ts
5 src/main/persistence/preferences/active-view-preference.ts
4 src/main/persistence/profile-state/legacy-json/profile-state-authority-exports.ts
2 src/main/persistence/profile-state/legacy-json/profile-state-export-path.ts
@@ -394,33 +394,33 @@
2 src/main/persistence/profile-state/legacy-json/profile-state-legacy-import.ts
8 src/main/persistence/profile-state/legacy-json/profile-state-recovery.ts
6 src/main/persistence/profile-state/legacy-json/profile-state-versioned-export.ts
5 src/main/persistence/profile-state/profile-state-access-identity.ts
12 src/main/persistence/profile-state/profile-state-access-owner.ts
3 src/main/persistence/profile-state/profile-state-access.ts
2 src/main/persistence/profile-state/profile-state-active-location.ts
5 src/main/persistence/profile-state/profile-state-authority-bootstrap.ts
1 src/main/persistence/profile-state/profile-state-authority-marker.ts
2 src/main/persistence/profile-state/profile-state-backup-path.ts
2 src/main/persistence/profile-state/profile-state-backup-worker.ts
5 src/main/persistence/profile-state/profile-state-database-quarantine.ts
9 src/main/persistence/profile-state/profile-state-database-recovery.ts
2 src/main/persistence/profile-state/profile-state-database.ts
4 src/main/persistence/profile-state/profile-state-migration.ts
6 src/main/persistence/profile-state/profile-state-offline-settings.ts
6 src/main/persistence/profile-state/profile-state-recovery-command.ts
8 src/main/persistence/profile-state/profile-state-recovery-copy.ts
2 src/main/persistence/profile-state/profile-state-recovery-crash-process.ts
1 src/main/persistence/profile-state/profile-state-recovery-required.ts
2 src/main/persistence/profile-state/profile-state-section-repair.ts
5 src/main/persistence/profile-state/access/profile-state-access-identity.ts
12 src/main/persistence/profile-state/access/profile-state-access-owner.ts
3 src/main/persistence/profile-state/access/profile-state-access.ts
2 src/main/persistence/profile-state/offline-access/profile-state-active-location.ts
5 src/main/persistence/profile-state/startup/profile-state-authority-bootstrap.ts
1 src/main/persistence/profile-state/database/profile-state-authority-marker.ts
2 src/main/persistence/profile-state/backup/profile-state-backup-path.ts
2 src/main/persistence/profile-state/backup/profile-state-backup-worker.ts
5 src/main/persistence/profile-state/recovery/profile-state-database-quarantine.ts
9 src/main/persistence/profile-state/recovery/profile-state-database-recovery.ts
2 src/main/persistence/profile-state/database/profile-state-database.ts
4 src/main/persistence/profile-state/startup/profile-state-migration.ts
6 src/main/persistence/profile-state/offline-access/profile-state-offline-settings.ts
6 src/main/persistence/profile-state/recovery/profile-state-recovery-command.ts
8 src/main/persistence/profile-state/recovery/profile-state-recovery-copy.ts
2 src/main/persistence/profile-state/recovery/profile-state-recovery-crash-process.ts
1 src/main/persistence/profile-state/recovery/profile-state-recovery-required.ts
2 src/main/persistence/profile-state/recovery/profile-state-section-repair.ts
2 src/main/persistence/profile-state/profile-state-sqlite-authority.ts
1 src/main/persistence/profile-state/profile-state-startup-recovery-dialog.ts
2 src/main/persistence/profile-state/profile-state-storage-classification.ts
1 src/main/persistence/profile-state/profile-state-writer-worker-path.ts
1 src/main/persistence/profile-state/startup/profile-state-startup-recovery-dialog.ts
2 src/main/persistence/profile-state/database/profile-state-storage-classification.ts
1 src/main/persistence/profile-state/writer/profile-state-writer-worker-path.ts
2 src/main/persistence/restoring-sessions/floating-workspace-normalization.ts
1 src/main/persistence/tracking-repos/worktree-metadata-normalization.ts
1 src/main/persistence/window-save-divergence.ts
8 src/main/pi/legacy-omp-overlay-migration.ts
5 src/main/pi/titlebar-extension-service.ts
8 src/main/pi/managed-extensions/legacy-omp-overlay-migration.ts
5 src/main/pi/managed-extensions/titlebar-extension-service.ts
3 src/main/plugins/appearance/plugin-appearance-service.ts
2 src/main/plugins/installation/plugin-install-staging.ts
1 src/main/plugins/installation/plugin-install.ts
@@ -539,8 +539,8 @@
1 src/main/updater/linux-package/linux-package-install-command.ts
1 src/main/updater/linux-package/linux-update-package-type.ts
6 src/main/updater/serve-update-handoff.ts
2 src/main/usage/usage-provider-store-lifecycle.ts
1 src/main/usage/usage-scan-worker-spawn.ts
2 src/main/usage/provider-lifecycle/usage-provider-store-lifecycle.ts
1 src/main/usage/scan-worker/usage-scan-worker-spawn.ts
1 src/main/warp-themes/discovery.ts
1 src/main/window/desktop-integration/custom-app-icon.ts
3 src/main/window/desktop-integration/macos-press-and-hold-default.ts
+4 -4
View File
@@ -15,7 +15,7 @@
1 src/main/codex-accounts/runtime-home-service-home-routing.ts
1 src/main/codex-accounts/runtime-home-service-wsl.ts
1 src/main/codex-accounts/service.ts
1 src/main/computer/macos-computer-use-permissions.ts
1 src/main/computer/macos-permissions/macos-computer-use-permissions.ts
2 src/main/daemon/process-scopes/daemon-cgroup-scope.ts
1 src/main/daemon/endpoint/identity/daemon-process-identity-query.ts
1 src/main/daemon/endpoint/identity/daemon-process-start-time.ts
@@ -29,11 +29,11 @@
1 src/main/ipc/worktree-logic.ts
2 src/main/window/desktop-integration/macos-press-and-hold-default.ts
1 src/main/network/macos-tailscale-dns-diagnostic.ts
1 src/main/opencode/legacy-plugin-acl-retry.ts
1 src/main/opencode/status-hooks/legacy-plugin-acl-retry.ts
2 src/main/orcad/node-pty-precondition.ts
1 src/main/orcad/orcad-data-root-privacy.ts
2 src/main/persistence/profile-state/profile-state-access-identity.ts
1 src/main/persistence/profile-state/profile-state-recovery-copy.ts
2 src/main/persistence/profile-state/access/profile-state-access-identity.ts
1 src/main/persistence/profile-state/recovery/profile-state-recovery-copy.ts
1 src/main/plugins/catalog/plugin-private-marketplace-ssh-shim.cjs
1 src/main/pty/process-retirement/posix-pty-process-table.ts
1 src/main/pty/shell-startup/pwsh.ts
-2
View File
@@ -7,8 +7,6 @@ const nodeFiles = [
'src/mock-server-key-pair.test.ts',
'src/mobile-release/prepare-android-release-script.test.ts',
'src/navigation/query-string-named-exports.test.ts',
'src/components/mobile-markdown-parser-progress.test.ts',
'src/components/rich-markdown/native-document-bundle.test.ts',
'src/terminal/document/native-document-bundle.test.ts',
'src/transport/encryption/mobile-e2ee-v2-client-session.test.ts',
'src/transport/encryption/mobile-e2ee-v2-physical-channel.test.ts',
@@ -14,11 +14,11 @@ src/main/browser/network/egress/browser-route-egress-electron-launch.ts
src/main/codex-accounts/legacy-wsl-runtime-auth-drain-recovery-script-harness.ts
src/main/codex-accounts/legacy-wsl-runtime-auth-drain-script-harness.ts
src/main/codex-accounts/service.ts
src/main/computer/desktop-script-provider-bridge.ts
src/main/computer/macos-computer-use-permission-status.ts
src/main/computer/macos-computer-use-permissions.ts
src/main/computer/macos-native-provider-transport.ts
src/main/computer/sidecar-client.ts
src/main/computer/desktop-script/desktop-script-provider-bridge.ts
src/main/computer/macos-permissions/macos-computer-use-permission-status.ts
src/main/computer/macos-permissions/macos-computer-use-permissions.ts
src/main/computer/macos-native/macos-native-provider-transport.ts
src/main/computer/sidecar-transport/sidecar-client.ts
src/main/daemon/endpoint/identity/daemon-process-identity-query.ts
src/main/daemon/endpoint/identity/daemon-process-inspection.ts
src/main/daemon/endpoint/identity/daemon-process-start-time.ts
+5 -6
View File
@@ -99,18 +99,17 @@
1 src/renderer/src/components/editor/combined-diff/resolve-changes/use-combined-diff-section-row-keys.ts
1 src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-notes-actions.ts
1 src/renderer/src/components/editor/combined-diff/scroll-viewport/use-combined-diff-virtualizer.ts
1 src/renderer/src/components/editor/csv/CsvGrid.tsx
1 src/renderer/src/components/editor/csv/grid/CsvGrid.tsx
1 src/renderer/src/components/editor/csv/CsvViewer.tsx
1 src/renderer/src/components/editor/csv/useCsvClipboard.ts
1 src/renderer/src/components/editor/csv/useCsvPagedPreview.ts
3 src/renderer/src/components/editor/csv/useCsvTableEditor.ts
1 src/renderer/src/components/editor/csv/editing/clipboard/useCsvClipboard.ts
1 src/renderer/src/components/editor/csv/preview/useCsvPagedPreview.ts
3 src/renderer/src/components/editor/csv/editing/useCsvTableEditor.ts
1 src/renderer/src/components/editor/diff/large-files/useDiffViewerLargeDiffLifecycle.ts
3 src/renderer/src/components/editor/diff/monaco-view/DiffViewer.tsx
1 src/renderer/src/components/editor/diff/review/DiffNotesSendMenu.tsx
1 src/renderer/src/components/editor/editor-header-file-rename.ts
1 src/renderer/src/components/editor/external-changes/ExternalFileChangeCompareDialog.tsx
1 src/renderer/src/components/editor/git-graph/git-graph-filter.tsx
1 src/renderer/src/components/editor/git-graph/git-graph-tab.tsx
1 src/renderer/src/components/editor/markdown-preview/render-tree/use-markdown-preview-components.tsx
1 src/renderer/src/components/editor/markdown-preview/review/MarkdownPreviewAnnotationComposer.tsx
1 src/renderer/src/components/editor/markdown-preview/surface/MarkdownPreview.tsx
@@ -145,7 +144,7 @@
3 src/renderer/src/components/editor/useEditorPanelFileContentLoader.ts
4 src/renderer/src/components/editor/useLocalLogTail.ts
1 src/renderer/src/components/editor/usePreserveSectionDuringExternalEdit.ts
7 src/renderer/src/components/emulator-pane/emulator-screen-stream-content.tsx
1 src/renderer/src/components/emulator-pane/emulator-screen-stream-content.tsx
3 src/renderer/src/components/emulator-pane/use-emulator-pane-session.ts
1 src/renderer/src/components/emulator-pane/use-emulator-pane-shutdown.ts
1 src/renderer/src/components/emulator-pane/use-emulator-video-stream.ts
+4 -5
View File
@@ -12,12 +12,12 @@
1 src/main/browser/extensions/native-messaging/browser-extension-native-ports.ts
1 src/main/browser/extensions/web-store/browser-extension-webstore-updater.ts
1 src/main/claude/agent-view/agent-view-bridge.ts
1 src/main/cli/appimage-serve-preparation.ts
1 src/main/cli/appimage/appimage-serve-preparation.ts
1 src/main/codex-accounts/codex-login-session.ts
1 src/main/codex/configuration/homes/codex-windows-sandbox-read-grant.ts
1 src/main/crash-reporting/pre-gone-host-memory.ts
1 src/main/crash-reporting/process-gone-diagnostics.ts
1 src/main/crash-reporting/renderer-heap-allocation-profile.ts
1 src/main/crash-reporting/memory/pre-gone-host-memory.ts
1 src/main/crash-reporting/process-exits/process-gone-diagnostics.ts
1 src/main/crash-reporting/memory/renderer-heap-allocation-profile.ts
1 src/main/daemon/admission/host-terminal-ledger.ts
1 src/main/daemon/admission/host-terminal-policy.ts
1 src/main/daemon/endpoint/publication/daemon-endpoint-lifecycle.ts
@@ -72,7 +72,6 @@
1 src/renderer/src/app-shell/use-app-session-persistence.ts
1 src/renderer/src/components/browser-pane/browser-client-page-position-driver.ts
1 src/renderer/src/components/contextual-tours/use-contextual-tour.ts
1 src/renderer/src/components/editor/setup-contextual-copy.ts
1 src/renderer/src/components/right-sidebar/plugin-panels/health/plugin-panel-watchdog.ts
1 src/renderer/src/components/sidebar/SeveredTerminalDaemonBanner.tsx
1 src/renderer/src/components/sidebar/StalledTerminalDaemonBanner.tsx
File diff suppressed because one or more lines are too long
+3 -3
View File
@@ -23,10 +23,10 @@
1 src/main/ipc/worktrees/removal/register-worktree-removal-handlers.ts
1 src/main/ipc/worktrees/removal/registered-worktree-root-owner.ts
1 src/main/ipc/worktrees/repo-host-ownership.ts
2 src/main/orca-profiles/profile-project-transfer-payload.ts
1 src/main/orca-profiles/profile-project-worktree-identity.ts
2 src/main/orca-profiles/project-transfer/profile-project-transfer-payload.ts
1 src/main/orca-profiles/project-transfer/profile-project-worktree-identity.ts
1 src/main/persistence/leasing-ssh-ptys/ssh-target-reassignment.ts
1 src/main/persistence/migrating-orcad-catalog/orcad-source-ownership.ts
1 src/main/persistence/migrating-orcad-catalog/source/catalog/orcad-source-ownership.ts
2 src/main/persistence/restoring-sessions/folder-scope-migration.ts
1 src/main/persistence/restoring-sessions/tab-terminal-pane-binding-repair.ts
1 src/main/persistence/tracking-repos/local-worktree-metadata-scan-expectation.ts
File diff suppressed because it is too large Load Diff
@@ -51,7 +51,6 @@ export const UNIT_EXCLUDE = [
'src/main/browser/guest-lifecycle/popups/presentation/popup-origin-chrome.electron.test.ts',
'src/main/browser/guest-lifecycle/navigation/browser-link-materialization.electron.test.ts',
'src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts',
'src/main/persistence/profile-state/profile-state-writer-stall.electron.test.ts',
'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility.electron.test.ts',
'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-native-compatibility.electron.test.ts',
'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-background-compatibility.electron.test.ts',
@@ -8,8 +8,6 @@ import { writeMobileWebBundleFixtureTree } from '../../build/mobile-web-app/mobi
const require = createRequire(import.meta.url)
const { assertMobileWebBundleBuilt } = require('./verify-packaged-mobile-web-bundle.cjs')
const electronBuilderConfig = require('../../../electron-builder.config.cjs')
const { darkBuildMarkers } = require('../../../dark-build-switches.cjs')
async function withBundle(run, { brotli = false } = {}) {
const scratch = await mkdtemp(join(tmpdir(), 'orca-mobile-web-guard-'))
@@ -37,16 +35,6 @@ describe('assertMobileWebBundleBuilt', () => {
vi.restoreAllMocks()
})
it('fails on a file the manifest does not list, so no stale asset ships inside asar', async () => {
await withBundle(async ({ bundleDir }) => {
// Dropped content-addressed assets never overwrite themselves; reject leftovers rather than pack unverified unreachable bytes.
await writeFile(join(bundleDir, 'assets', 'stale.js'), '// from an earlier build\n', 'utf8')
expect(() => assertMobileWebBundleBuilt(bundleDir)).toThrow(
/does not list: assets\/stale\.js/
)
})
})
it('fails when an asset is tampered with on disk', async () => {
await withBundle(async ({ bundleDir, manifest }) => {
const asset = manifest.assets.find((entry) => entry.path.endsWith('.js'))
@@ -58,14 +46,6 @@ describe('assertMobileWebBundleBuilt', () => {
})
})
it('fails when a listed asset was never written', async () => {
await withBundle(async ({ bundleDir, manifest }) => {
const asset = manifest.assets.find((entry) => entry.path.endsWith('.png'))
await rm(join(bundleDir, asset.path))
expect(() => assertMobileWebBundleBuilt(bundleDir)).toThrow(/which is missing from/)
})
})
it('accepts the brotli copies the manifest lists, and fails one that inflates to other bytes', async () => {
await withBundle(
async ({ bundleDir, manifest }) => {
@@ -84,29 +64,4 @@ describe('assertMobileWebBundleBuilt', () => {
{ brotli: true }
)
})
it('refuses an asset path that escapes the bundle directory', async () => {
await withBundle(async ({ bundleDir }) => {
await rewriteManifest(bundleDir, (manifest) => {
manifest.assets[0].path = '../outside.js'
})
expect(() => assertMobileWebBundleBuilt(bundleDir)).toThrow(/not a safe relative path/)
})
})
})
describe('electron-builder packaging wiring', () => {
it('verifies a dark page build, and refuses to package it', async () => {
await withBundle(async ({ bundleDir }) => {
const [marker] = darkBuildMarkers({ ORCA_SIDEBAR_INPUTS: 'main' })
await writeFile(join(bundleDir, marker.fileName), marker.text, 'utf8')
expect(() => assertMobileWebBundleBuilt(bundleDir)).not.toThrow()
expect(() =>
electronBuilderConfig.beforePack(
{ electronPlatformName: process.platform, arch: process.arch === 'arm64' ? 3 : 1 },
bundleDir
)
).toThrow(`${bundleDir} holds an ORCA_SIDEBAR_INPUTS=main build`)
})
})
})
@@ -1,54 +0,0 @@
import { describe, expect, it } from 'vitest'
import { repairTranslatedValue } from './locale-translation-policy.mjs'
describe('locale-translation-policy ko round 5', () => {
it('re-glues Korean particles after Latin terms without gluing content words', () => {
// A wrong space before the 에 particle is re-glued onto the Latin term.
expect(
repairTranslatedValue({
key: 'auto.components.StarNagCard.cf82170065',
enValue: 'Could not star the repo. Make sure',
localeValue: 'repo 에 스타를 표시할 수 없습니다. 다음을 확인하세요',
locale: 'ko'
})
).toBe('repo에 스타를 표시할 수 없습니다. 다음을 확인하세요')
expect(
repairTranslatedValue({
key: 'auto.components.github.project.ProjectCell.4b5b871da8',
enValue: 'No labels in this repo.',
localeValue: '이 repo 에는 라벨이 없습니다.',
locale: 'ko'
})
).toBe('이 repo에는 라벨이 없습니다.')
expect(
repairTranslatedValue({
key: 'auto.components.terminal.pane.CloseTerminalDialog.6b9a6975f8',
enValue:
'The terminal still has a running process. If you close the terminal, the process will be killed.',
localeValue:
'terminal 에는 여전히 실행 중인 프로세스가 있습니다. terminal을 닫으면 프로세스가 종료됩니다.',
locale: 'ko'
})
).toBe(
'terminal에는 여전히 실행 중인 프로세스가 있습니다. terminal을 닫으면 프로세스가 종료됩니다.'
)
// A correct space before a content word that merely starts with a particle syllable is kept.
expect(
repairTranslatedValue({
key: 'auto.components.JiraIssueWorkspace.76513c7898',
enValue: 'Close Jira issue preview',
localeValue: 'Jira 이슈 미리보기 닫기',
locale: 'ko'
})
).toBe('Jira 이슈 미리보기 닫기')
expect(
repairTranslatedValue({
key: 'auto.components.GitHubItemDialog.3ab6ac0fc8',
enValue: 'Preview and edit the selected GitHub issue or pull request.',
localeValue: '선택한 GitHub 이슈 또는 PR을 미리보기하고 편집합니다.',
locale: 'ko'
})
).toBe('선택한 GitHub 이슈 또는 PR을 미리보기하고 편집합니다.')
})
})
@@ -1,76 +0,0 @@
import { describe, expect, it } from 'vitest'
import { repairTranslatedValue, shouldPreserveEnglishValue } from './locale-translation-policy.mjs'
const ja = (enValue, localeValue, key = 'auto.test.relocalization') =>
repairTranslatedValue({ key, enValue, localeValue, locale: 'ja' })
describe('locale-translation-policy ja relocalization', () => {
it('leaves the second word of a two-word command in Latin', () => {
expect(ja('a commit hook or git commit fails', 'コミットフックまたは git commit が失敗')).toBe(
'コミットフックまたは git commit が失敗'
)
expect(ja('Run orca terminal', 'orca terminal を実行')).toBe('orca terminal を実行')
expect(ja('Install with pnpm install', 'pnpm install でインストール')).toBe(
'pnpm install でインストール'
)
})
it('leaves identifiers, flags, filenames, and Latin-only labels alone', () => {
expect(ja('Pass --agent to select one.', '--agent を渡して選択します。')).toBe(
'--agent を渡して選択します。'
)
expect(ja('Edit agents.md', 'agents.md を編集')).toBe('agents.md を編集')
expect(ja('Agent SDK settings', 'Agent SDK の設定')).toBe('Agent SDK の設定')
expect(ja('Agent SDK settings', 'この Agent SDK の設定')).toBe('この Agent SDK の設定')
expect(ja('Run git commit -m', 'git commit -m を実行')).toBe('git commit -m を実行')
})
it('repairs translated code examples back to executable values', () => {
expect(ja('--model sonnet', '--モデルソネット')).toBe('--model sonnet')
expect(
ja("gh pr list --json number -q '.[0].number'", "gh pr list --json 番号 -q '.[0].number'")
).toBe("gh pr list --json number -q '.[0].number'")
expect(ja('{basePrompt}', '{ベースプロンプト}')).toBe('{basePrompt}')
expect(ja('/pricing', '/価格設定')).toBe('/pricing')
})
it('keeps style blocks in English because a translated selector breaks the view', () => {
expect(shouldPreserveEnglishValue('.pp-card[data-card="starter"] .pp-cta')).toBe(true)
expect(shouldPreserveEnglishValue('@keyframes browser-flash { to { opacity: 1; } }')).toBe(true)
expect(shouldPreserveEnglishValue('.card { background: var(--card); }')).toBe(true)
// Why: the declaration requirement is what keeps prose containing braces translatable.
expect(shouldPreserveEnglishValue('e.g. {{value0}}')).toBe(false)
})
it('leaves ranges and token samples out of the ellipsis rule', () => {
expect(ja('Compare main...HEAD', 'main...HEAD を比較')).toBe('main...HEAD を比較')
})
it('preserves a selector that has no declaration block', () => {
for (const value of [
'div.pricing-grid > div.card.starter:nth-of-type(1) > a.cta',
'.pp-cta',
'#dialog',
'.pp-card[data-card="starter"] .pp-cta',
'button.primary',
'a:hover',
'input[type="text"]',
'localhost:3000'
]) {
expect(shouldPreserveEnglishValue(value)).toBe(true)
}
// Why: two ordinary sentences carry two periods, which must not read as selector joins.
for (const value of [
'Open Settings > Git and try again.',
'Show live workspace ports. Click it for workspace-scoped ports and external listeners.',
'orca.yaml + local',
'.gitignore',
'Status:',
'Done.',
'#{{value0}}'
]) {
expect(shouldPreserveEnglishValue(value)).toBe(false)
}
})
})
@@ -124,30 +124,9 @@ async function framePixel(page) {
})
}
const sourceText = (page) => page.getByText(MARKER, { exact: false })
for (const engine of ['chromium', 'webkit']) {
const describeRender = bundles ? describe : describe.skip
describeRender(`an HTML file on the file-preview route on ${engine}`, () => {
it('paints the page, and Source shows its markup', async () => {
const { context, page, errors } = await openHtmlFile(browsers[engine])
const frame = page.locator('iframe')
await frame.waitFor({ timeout: 60_000 })
await expect.poll(() => framePixel(page), { timeout: 10_000 }).toBe(PAINT_RGB)
if (shots) {
await page.screenshot({ path: join(shots, `html-file-preview-${engine}.png`) })
}
await page.getByRole('tab', { name: 'View HTML source' }).click()
await sourceText(page).waitFor()
expect(await page.locator('iframe').count()).toBe(0)
if (shots) {
await page.screenshot({ path: join(shots, `html-file-source-${engine}.png`) })
}
expect(errors).toEqual([])
await context.close()
}, 90_000)
it('renders unsaved HTML edits and retains them when returning to Source', async () => {
const { context, page, errors } = await openHtmlFile(browsers[engine], { editable: true })
await page.locator('iframe').waitFor({ timeout: 60_000 })
@@ -165,36 +144,5 @@ for (const engine of ['chromium', 'webkit']) {
expect(errors).toEqual([])
await context.close()
}, 90_000)
it('opens a line-targeted file on Source, and a truncated one as text only', async () => {
const targeted = await openHtmlFile(browsers[engine], { line: '3' })
await targeted.page
.getByRole('tab', { name: 'View HTML source' })
.waitFor({ timeout: 60_000 })
await sourceText(targeted.page).waitFor()
expect(
await targeted.page
.getByRole('tab', { name: 'View HTML source' })
.getAttribute('aria-selected')
).toBe('true')
expect(await targeted.page.locator('iframe').count()).toBe(0)
if (shots) {
await targeted.page.screenshot({ path: join(shots, `html-file-line-${engine}.png`) })
}
await targeted.page.getByRole('tab', { name: 'Preview rendered HTML' }).click()
await expect.poll(() => framePixel(targeted.page), { timeout: 10_000 }).toBe(PAINT_RGB)
expect(targeted.errors).toEqual([])
await targeted.context.close()
const truncated = await openHtmlFile(browsers[engine], { truncated: true })
await sourceText(truncated.page).waitFor({ timeout: 60_000 })
expect(await truncated.page.locator('iframe').count()).toBe(0)
expect(await truncated.page.getByRole('tab').count()).toBe(0)
if (shots) {
await truncated.page.screenshot({ path: join(shots, `html-file-truncated-${engine}.png`) })
}
expect(truncated.errors).toEqual([])
await truncated.context.close()
}, 120_000)
})
}
@@ -1,198 +0,0 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { chromium } from 'playwright-core'
import { buildMobileWebAppBundle } from '../../build/mobile-web-app/build-mobile-web-app-bundle.mjs'
import { mobileWebAppDependenciesPresent } from '../mobile-web-app-bundle-dependencies.mjs'
import {
createBundleServer,
waitForPageFrames,
installShellDouble,
readBridgeFaultGrant,
readBridgePagePainted,
readBridgeProtocolVersion,
readShellCsp
} from '../preview/mobile-web-app-render-harness.mjs'
// Browser-only history checks prove real RN-Web closure evaluation, corpus-backed rows, shell Back handoff and deferred chunk delivery.
// Domain file uses shared C1.10 harness to avoid line-cap conflicts between concurrent series.
const HOST_ROUTE = '/h/render-check-host'
/** The pattern `init.pageRoutes` names, which is what the page matches a navigation against. */
const HOST_ROUTE_PATTERN = '/h/[hostId]'
const SHELL_SESSION_ID = 'render-check-session'
const SHELL_BUILD_ID = 'render-check-build'
const SHELL_HOST = {
id: 'render-check-host',
name: 'Render Check Host',
endpoint: 'ws://render-check',
lastConnected: 1
}
const bundles = mobileWebAppDependenciesPresent()
const describeRender = bundles ? describe : describe.skip
let scratch
let server
let browser
let origin
let cspHeader = null
let bridgeVersion = null
let faultGrant = null
let paintName = null
beforeAll(async () => {
if (!bundles) {
return
}
cspHeader = await readShellCsp()
bridgeVersion = await readBridgeProtocolVersion()
faultGrant = await readBridgeFaultGrant()
paintName = await readBridgePagePainted()
scratch = await mkdtemp(join(tmpdir(), 'orca-mobile-web-app-agent-history-'))
const built = await buildMobileWebAppBundle({ outDir: join(scratch, 'bundle') })
const served = await createBundleServer({ outDir: built.outDir, cspHeader })
server = served.server
origin = served.origin
const executablePath = process.env.ORCA_MOBILE_WEB_RENDER_BROWSER
browser = await chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}) })
}, 180_000)
afterAll(async () => {
await browser?.close()
server?.close()
if (scratch) {
await rm(scratch, { recursive: true, force: true })
}
})
/** A page carrying every signal these cases read: uncaught errors, console errors, script paths. */
async function openPage({ shellRoute, shellGrants, shellPageRoutes = null, replies } = {}) {
const page = await browser.newPage({ viewport: { width: 390, height: 844 } })
// Install channel at document start; entry reads it during evaluation, before load.
await page.addInitScript(installShellDouble, {
version: bridgeVersion,
sessionId: SHELL_SESSION_ID,
buildId: SHELL_BUILD_ID,
route: shellRoute,
host: SHELL_HOST,
storage: {},
faultGrant,
// The harness falls back to the fault grant alone, which is the ungranted page.
grants: shellGrants ?? [faultGrant],
pageRoutes: shellPageRoutes,
replies
})
const errors = []
const scripts = []
let reportUncaught = () => {}
const uncaught = new Promise((resolve) => {
reportUncaught = resolve
})
page.on('pageerror', (error) => {
errors.push(`${error.name}: ${error.message}`)
reportUncaught(error)
})
page.on('console', (message) => {
if (message.type() === 'error') {
errors.push(`console.error: ${message.text()}`)
}
})
page.on('response', (response) => {
const path = new URL(response.url()).pathname
if (response.status() === 200 && path.endsWith('.js')) {
scripts.push(path)
}
})
return { page, errors, scripts, uncaught }
}
// Wait beyond entry mount for route content; deferred import chunk may still be arriving.
async function waitForRoute({ page, errors, uncaught }, route, awaitText) {
const named = (cause, what) =>
new Error(`${route} ${what}: ${errors.join(' | ') || 'no page or console error'}`, { cause })
const race = async (wait) =>
Promise.race([
wait.then(
() => null,
(error) => error
),
uncaught
])
const cause = await race(
page.waitForFunction(() => document.documentElement.dataset.orcaWebEntry === 'mounted', {
timeout: 30_000,
polling: 250
})
)
if (cause) {
const state = await page.evaluate(
() => document.documentElement.dataset.orcaWebEntry ?? 'absent'
)
throw named(cause, `never mounted (entry ${state})`)
}
const paintCause = await race(
page.waitForFunction((needle) => document.body.innerText.includes(needle), awaitText, {
timeout: 30_000,
polling: 250
})
)
if (paintCause) {
throw named(paintCause, `mounted but never painted ${JSON.stringify(awaitText)}`)
}
for (const fault of await page.evaluate(() => globalThis.__orcaRenderCheckFaults ?? [])) {
errors.push(`page fault: ${fault}`)
}
}
/** Opens the document at `/`, the one path the shell serves, and lets the page route itself. */
async function openRoute(route, awaitText, options = {}) {
const opened = await openPage({ shellRoute: { pathname: route }, ...options })
await opened.page.goto(`${origin}/`, { waitUntil: 'load' })
await waitForRoute(opened, route, awaitText)
return opened
}
/** Every grant-gated notify the page posted, whole and in order, as the shell received them. The
* paint report and the location report are not: every page posts them for its route screen. */
async function readNotifies(page) {
const notifies = await page.evaluate(() => globalThis.__orcaRenderCheckNotifies ?? [])
return notifies.filter((frame) => frame.name !== paintName && frame.name !== 'location')
}
describeRender('the agent-history route in a real browser', () => {
// Prove real RN-Web import/evaluation absent from mocked native units; no-RPC case paints failure, next corpus case paints a row.
// Resume/scope-tab interactions remain native C5.3 device coverage.
it('hands its Back button to the shell, which no unit test can prove in a browser', async () => {
const route = `${HOST_ROUTE}/agent-history/wt-1`
const opened = await openRoute(route, 'Agent Session History', {
shellGrants: [faultGrant, 'navigate'],
shellPageRoutes: [HOST_ROUTE_PATTERN]
})
await opened.page.getByLabel('Back').click()
await expect
.poll(() => readNotifies(opened.page))
.toEqual([{ v: bridgeVersion, type: 'notify', name: 'navigate-back' }])
expect(await readNotifies(opened.page)).toEqual([
{ v: bridgeVersion, type: 'notify', name: 'navigate-back' }
])
// Document has only replaceState entry; page-local Back would do nothing and look like a successful shell handoff.
expect(await opened.page.evaluate(() => location.pathname)).toBe(route)
expect(opened.errors).toEqual([])
await opened.page.close()
}, 60_000)
it('posts nothing for Back when the shell granted no navigate, and stays put', async () => {
// Withhold grant while preserving tap/handler/seam to prove handoff depends on permission.
const route = `${HOST_ROUTE}/agent-history/wt-1`
const opened = await openRoute(route, 'Agent Session History')
await opened.page.getByLabel('Back').click()
await waitForPageFrames(opened.page)
expect(await readNotifies(opened.page)).toEqual([])
expect(await opened.page.evaluate(() => location.pathname)).toBe(route)
expect(opened.errors).toEqual([])
await opened.page.close()
}, 60_000)
})
@@ -1,202 +0,0 @@
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import * as esbuild from 'esbuild'
import { chromium, webkit } from 'playwright-core'
import {
MOBILE_WEB_APP_NATIVE_PARITY_STYLE,
MOBILE_WEB_APP_ROOT_RESET,
mobileWebAppBuildOptions
} from '../../build/mobile-web-app/build-mobile-web-app-bundle.mjs'
import { mobileWebAppDependenciesPresent } from '../mobile-web-app-bundle-dependencies.mjs'
import { createBundleServer, readShellCsp } from '../preview/mobile-web-app-render-harness.mjs'
import { SUPPORTED_UI_LOCALES } from '../../../../src/shared/ui-locale.ts'
const mobileDir = fileURLToPath(new URL('../../../../mobile', import.meta.url))
const engines = [
{
name: 'chromium',
launch: () => {
const executablePath = process.env.ORCA_MOBILE_WEB_RENDER_BROWSER
return chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}) })
}
},
{ name: 'webkit', launch: () => webkit.launch({ headless: true }) }
]
const entry = `
import { useEffect, useState } from 'react'
import { createRoot } from 'react-dom/client'
import { View } from 'react-native'
import { GestureHandlerRootView } from 'react-native-gesture-handler'
import { MobileNativeChatQueuedMessages } from './src/session/native-chat/input/MobileNativeChatQueuedMessages'
import { MobileNativeChatComposer } from './src/session/native-chat/composer/MobileNativeChatComposer'
import { mobileQueuedMessageCards } from './src/session/native-chat/input/mobile-structured-queued-message-cards'
import { activateMobileUiLocale, translate } from './src/i18n/mobile-i18n'
const [mode, locale] = location.hash.slice(1).split(':')
const texts = ['First queued message', 'Review the mobile transcript and keep every detail. '.repeat(30)]
function Queue() {
const messages = texts.map((text, index) => ({
messageId: 'message-' + index,
position: index + 1,
state: 'waiting',
body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text }] }
}))
return <View style={{ flex: 1, justifyContent: 'flex-end' }}>
<MobileNativeChatQueuedMessages
cards={mobileQueuedMessageCards(messages, [], { agentWorking: true })}
onMove={mode === 'drag' ? async () => true : undefined}
/>
</View>
}
function Editor() {
const [ready, setReady] = useState(false)
useEffect(() => {
void activateMobileUiLocale(locale).then(() => {
window.actionLabels = {
cancel: translate('chat.composer.cancelEditing', 'Cancel editing'),
save: translate('chat.composer.saveEditedMessage', 'Save edited message')
}
setReady(true)
})
}, [])
return ready ? <View style={{ flex: 1, justifyContent: 'flex-end', marginHorizontal: 16 }}>
<MobileNativeChatComposer
value="Edited message"
onChangeText={() => {}}
onSend={async () => true}
editSession={{ cancel: () => {}, refuseCommand: () => false, locked: false }}
sendSurfaceId="editor"
getSendCompletionGeneration={() => 0}
getComposerEditGeneration={() => 0}
onAttachImage={() => {}}
onMicPress={() => {}}
/>
</View> : null
}
createRoot(document.getElementById('root')).render(
<GestureHandlerRootView style={{ flex: 1 }}>{mode === 'editor' ? <Editor /> : <Queue />}</GestureHandlerRootView>
)
`
const bundles = mobileWebAppDependenciesPresent()
const describeLayout = bundles ? describe : describe.skip
const browsers = new Map()
let scratch
let server
let origin
beforeAll(async () => {
if (!bundles) {
return
}
await mkdir(join(mobileDir, '.tmp'), { recursive: true })
scratch = await mkdtemp(join(mobileDir, '.tmp', 'queued-messages-'))
const outDir = join(scratch, 'bundle')
await esbuild.build({
...mobileWebAppBuildOptions([]),
entryPoints: undefined,
stdin: { contents: entry, resolveDir: mobileDir, loader: 'tsx', sourcefile: 'queued.tsx' },
splitting: false,
write: true,
outdir: outDir,
entryNames: 'queued',
metafile: false
})
await writeFile(
join(outDir, 'index.html'),
`<!doctype html><html><head><meta charset="utf-8">${MOBILE_WEB_APP_ROOT_RESET}` +
`${MOBILE_WEB_APP_NATIVE_PARITY_STYLE}</head><body><div id="root"></div>` +
'<script type="module" src="/queued.js"></script></body></html>'
)
const served = await createBundleServer({ outDir, cspHeader: await readShellCsp() })
server = served.server
origin = served.origin
for (const engine of engines) {
browsers.set(engine.name, await engine.launch())
}
}, 180_000)
afterAll(async () => {
for (const browser of browsers.values()) {
await browser.close()
}
server?.close()
if (scratch) {
await rm(scratch, { recursive: true, force: true })
}
})
async function openPage(engine, hash, width) {
const page = await browsers.get(engine.name).newPage({ viewport: { width, height: 700 } })
await page.goto(`${origin}/#${hash}`, { waitUntil: 'load' })
return page
}
function editorActionProblems(page) {
return page.evaluate(() => {
const row = document.querySelector('[data-testid="native-chat-composer-actions"]')
const problems = []
const [cancel, save] = ['cancel', 'save'].map((name) => {
const button = row.querySelector(`[aria-label="${window.actionLabels[name]}"]`)
const label = button.querySelector('div[dir]')
const range = document.createRange()
range.selectNodeContents(label)
const text = range.getBoundingClientRect()
const box = button.getBoundingClientRect()
if (label.scrollWidth > label.clientWidth) {
problems.push(`${name} label truncated`)
}
if (text.left < box.left - 0.5 || text.right > box.right + 0.5) {
problems.push(`${name} label outside its button`)
}
return box
})
if (cancel.right > save.left + 0.5) {
problems.push('cancel overlaps save')
}
if (save.right > row.getBoundingClientRect().right + 0.5) {
problems.push('save past the row')
}
return problems
})
}
describeLayout.each(engines)('mobile queued messages in $name', (engine) => {
it.each(['plain', 'drag'])('scrolls only as far as the %s rows reach', async (mode) => {
const page = await openPage(engine, mode, 390)
try {
await page.locator('[data-testid="queued-card-row"]').nth(1).waitFor()
const range = () =>
page.evaluate(() => {
const box = document.querySelector('[data-testid="queued-box"]')
const rows = [...box.querySelectorAll('[data-testid="queued-card-row"]')]
const scroller = [...box.querySelectorAll('*')].find(
(node) => getComputedStyle(node).overflowY === 'auto'
)
const rowsHeight = rows.reduce((sum, row) => sum + row.getBoundingClientRect().height, 0)
return scroller.scrollHeight - rowsHeight
})
await expect.poll(range).toBeLessThanOrEqual(1)
} finally {
await page.close()
}
})
it('fits whole Save and Cancel labels at 360pt in every shipped locale', async () => {
const results = await Promise.all(
SUPPORTED_UI_LOCALES.map(async (locale) => {
const page = await openPage(engine, `editor:${locale}`, 360)
try {
await page.locator('[data-testid="native-chat-composer-actions"]').waitFor()
return { locale, problems: await editorActionProblems(page) }
} finally {
await page.close()
}
})
)
expect(results.filter(({ problems }) => problems.length > 0)).toEqual([])
}, 60_000)
})
@@ -17,7 +17,6 @@ import {
// Mount real ExpoRoot: only rendering proves synthesized RequireContext has expected shape.
const HOST_ROUTE = '/h/render-check-host'
const HOST_ROUTE_PATTERN = '/h/[hostId]'
const SHELL_SESSION_ID = 'render-check-session'
const SHELL_BUILD_ID = 'render-check-build'
@@ -191,30 +190,6 @@ async function waitForRoute({ page, errors, uncaught }, route, awaitText) {
}
}
// Open / as shell does, then route from init; direct route navigation would hide entry routing bugs.
async function render(route, awaitText, { shellRoute = { pathname: route }, ...shell } = {}) {
const opened = await openPage({ shellRoute, ...shell })
await opened.page.goto(`${origin}/`, { waitUntil: 'load' })
await waitForRoute(opened, route, awaitText)
const text = await opened.page.evaluate(() => document.body.innerText)
// Read page’s session identity to catch mounting without shell’s session or inventing one.
const session = await opened.page.evaluate(() => ({
sessionId: document.documentElement.dataset.orcaWebSessionId ?? null,
buildId: document.documentElement.dataset.orcaWebBuildId ?? null
}))
// Require rewrite from / before render or every host route resolves to Unmatched.
const url = await opened.page.evaluate(() => location.pathname + location.search)
await opened.page.close()
// Name CSP refusals within asserted console errors for useful diagnostics.
return {
errors: opened.errors,
cspErrors: opened.errors.filter((entry) => entry.includes('Content Security Policy')),
text,
session,
url
}
}
const paintReports = (page, name) =>
page.evaluate(
(paint) =>
@@ -223,58 +198,6 @@ const paintReports = (page, name) =>
)
describeRender('the Route A page in a real browser', () => {
it('fills the view, so what it mounted is painted and takes a tap', async () => {
const opened = await openPage({ shellRoute: { pathname: HOST_ROUTE } })
await opened.page.goto(`${origin}/`, { waitUntil: 'load' })
await waitForRoute(opened, HOST_ROUTE, SHELL_HOST.name)
const layout = await opened.page.evaluate(() => {
// No-RPC control at root bottom moves furthest if layout collapses.
const fab = [...document.querySelectorAll('[role="button"]')].find(
(element) => element.getAttribute('aria-label') === 'New workspace'
)
const box = fab?.getBoundingClientRect() ?? null
const hit =
box === null
? null
: document.elementFromPoint(box.x + box.width / 2, box.y + box.height / 2)
return {
rootHeight: document.getElementById('root').getBoundingClientRect().height,
viewportHeight: window.innerHeight,
fabTop: box?.top ?? null,
fabBottom: box?.bottom ?? null,
reachesTheControl: hit !== null && fab.contains(hit)
}
})
await opened.page.close()
expect(opened.errors).toEqual([])
// Measure height: mounted text/innerText can pass while collapsed root paints blank phone screen.
expect(layout.rootHeight).toBe(layout.viewportHeight)
expect(layout.fabTop).toBeGreaterThan(0)
expect(layout.fabBottom).toBeLessThanOrEqual(layout.viewportHeight)
// Require reachable tap: clipped scroller rows retain layout rects.
expect(layout.reachesTheControl).toBe(true)
}, 60_000)
// Native files routes throw requireNativeViewManager at import; deferred import hides this until actual route opens, requiring web siblings.
it('mounts the file preview, reading the file path out of a param and not a segment', async () => {
const previewRoute = `${HOST_ROUTE}/files/preview/worktree-a`
const { errors, cspErrors, text, url } = await render(previewRoute, 'readme.md', {
shellRoute: {
pathname: previewRoute,
params: { relativePath: 'docs/my notes/readme.md', source: 'worktree' }
}
})
expect(cspErrors).toEqual([])
// Require no unsupported RN-Web BackHandler registration; Android hardware Back pops native stack while page Back owns unsaved-draft prompt.
expect(errors).toEqual([])
// Title proves final path segment only; URL checks outbound encoding, not middle-segment decoding.
// Decode hazards are covered by mobile-file-path-route-encoding.test.ts and mobile-file-preview-route.test.ts.
expect(text).toContain('readme.md')
expect(url).toBe(`${previewRoute}?relativePath=docs%2Fmy+notes%2Freadme.md&source=worktree`)
expect(text).not.toContain(UNMATCHED)
}, 60_000)
it('tells the shell when a route chunk throws, rather than sitting on a blank page', async () => {
const chunk = routeChunks['./h/[hostId]/index.tsx']
expect(chunk, Object.keys(routeChunks).join(' ')).toBeTruthy()
@@ -345,128 +268,4 @@ describeRender('the Route A page in a real browser', () => {
heldChunks.delete(path)
}
}, 120_000)
it('says nothing for a redirect screen whose target is still behind its chunk', async () => {
// PR redirect remains mounted behind destination’s pending chunk; its own commit must not report screen paint.
const target = routeChunks['./h/[hostId]/source-control/[worktreeId].tsx']
expect(target, Object.keys(routeChunks).join(' ')).toBeTruthy()
const path = `/assets/${target}`
let arrive = () => {}
heldChunks.set(
path,
new Promise((resolve) => {
arrive = resolve
})
)
try {
const route = `${HOST_ROUTE}/pr/render-check-tree`
const opened = await openPage({
shellRoute: { pathname: route },
shellPageRoutes: [HOST_ROUTE_PATTERN, '/h/[hostId]/pr/[worktreeId]']
})
await opened.page.goto(`${origin}/`, { waitUntil: 'load' })
await opened.page.waitForFunction(
() => location.pathname.includes('/source-control/'),
undefined,
{ timeout: 30_000, polling: 250 }
)
// Router has moved but pending hub chunk still leaves document empty.
await waitForPageFrames(opened.page)
expect(await paintReports(opened.page, paintName)).toBe(0)
arrive()
await opened.page.waitForFunction(
(name) =>
(globalThis.__orcaRenderCheckNotifies ?? []).filter((frame) => frame.name === name)
.length > 0,
paintName,
{ timeout: 30_000, polling: 250 }
)
await opened.page.close()
} finally {
arrive()
heldChunks.delete(path)
}
}, 120_000)
it('refuses a target the shell will not take, rather than opening it in the page', async () => {
// Fault-only grant makes notifyNavigate refuse like disposed/older shell; local fallback once mounted Unmatched or native-only session route.
const opened = await openPage({ shellRoute: { pathname: HOST_ROUTE } })
const { page, errors } = opened
await page.goto(`${origin}/`, { waitUntil: 'load' })
await waitForRoute(opened, HOST_ROUTE, SHELL_HOST.name)
await page.getByLabel('Back to hosts').click()
// Settle handoff microtask before asserting no navigation.
await waitForPageFrames(page)
expect(await page.evaluate(() => location.pathname)).toBe(HOST_ROUTE)
const text = await page.evaluate(() => document.body.innerText)
expect(text).toContain(SHELL_HOST.name)
expect(text).not.toContain(UNMATCHED)
// Require no notify as well as unchanged page; successful shell handoff also leaves document in place.
const notifies = await page.evaluate(() => globalThis.__orcaRenderCheckNotifies ?? [])
expect(notifies.filter((frame) => frame.name === 'navigate')).toEqual([])
// Refused target declines navigation without faulting page.
expect(await page.evaluate(() => globalThis.__orcaRenderCheckFaults ?? [])).toEqual([])
expect(errors).toEqual([])
await page.close()
}, 60_000)
it("fetches the next route's chunks on a client-side navigation", async () => {
const opened = await openPage({ shellRoute: { pathname: HOST_ROUTE } })
const { page, errors, scripts } = opened
await page.goto(`${origin}/`, { waitUntil: 'load' })
await waitForRoute(opened, HOST_ROUTE, SHELL_HOST.name)
const loadedForFirstRoute = [...scripts]
// Shell fetches document once; later route must arrive as a chunk through in-page history navigation.
await page.evaluate((to) => {
history.pushState(null, '', to)
dispatchEvent(new PopStateEvent('popstate'))
}, `${HOST_ROUTE}/tasks`)
await waitForRoute(opened, `${HOST_ROUTE}/tasks`, 'Issues')
expect(new URL(page.url()).pathname).toBe(`${HOST_ROUTE}/tasks`)
const fetchedOnNavigation = scripts.filter((path) => !loadedForFirstRoute.includes(path))
// Require builder-identified tasks chunk, not any fetched script or code already loaded by entry.
const tasksChunk = routeChunks['./h/[hostId]/tasks.tsx']
expect(tasksChunk, Object.keys(routeChunks).join(' ')).toBeTruthy()
expect(fetchedOnNavigation, scripts.join(' ')).toContain(`/assets/${tasksChunk}`)
expect(loadedForFirstRoute).not.toContain(`/assets/${tasksChunk}`)
const text = await page.evaluate(() => document.body.innerText)
expect(text).toContain('Tasks')
expect(text).not.toContain(UNMATCHED)
expect(errors).toEqual([])
await page.close()
}, 60_000)
})
// Probe mounted React Navigation canGoBack through real route chevron/router.back; page exposes no direct test hook.
// First prove same-family tap reaches shell, since an inert handler and refused local Back both leave document unchanged.
describeRender('the stack the page Back button rests on', () => {
async function clickAndSettle(page, selector) {
await page.click(selector)
await waitForPageFrames(page)
return page.evaluate(() => location.pathname + location.search)
}
it('carries a handoff the shell granted across the bridge from a real tap', async () => {
// Grant navigate: this chevron proves handler/bridge path used by navigate-back before interpreting absent notifies.
const opened = await openPage({
shellRoute: { pathname: HOST_ROUTE },
shellGrants: [faultGrant, 'navigate'],
shellPageRoutes: [HOST_ROUTE_PATTERN]
})
await opened.page.goto(`${origin}/`, { waitUntil: 'load' })
await waitForRoute(opened, HOST_ROUTE, SHELL_HOST.name)
const url = await clickAndSettle(opened.page, '[aria-label="Back to hosts"]')
await expect
.poll(() =>
opened.page.evaluate(() =>
(globalThis.__orcaRenderCheckNotifies ?? []).filter((frame) => frame.name === 'navigate')
)
)
.toEqual([{ v: bridgeVersion, type: 'notify', name: 'navigate', href: '/' }])
// Require page stays on served route; local fallthrough would mount a screen document cannot serve.
expect(url).toBe(HOST_ROUTE)
expect(opened.errors).toEqual([])
await opened.page.close()
}, 60_000)
})
@@ -130,35 +130,6 @@ const fieldValue = (page) =>
describeRender(
'the terminal live input on the page',
() => {
it('clears the field when Enter submits, the way it does natively', async () => {
// Use real keydown to exercise RN-Web Enter/onSubmitEditing; command must clear previously sent live text.
const { errors, page } = await openProbe()
await page.focus(`#${LIVE_INPUT_FIELD_ID}`)
await page.keyboard.type('ls')
await page.waitForFunction(
(id) => document.getElementById(id)?.value === 'ls',
LIVE_INPUT_FIELD_ID,
{ timeout: 30_000, polling: 100 }
)
await page.keyboard.press('Enter')
await page.waitForFunction(
() => (globalThis.__orcaLiveInputProbe.sent() ?? []).includes('\r'),
undefined,
{ timeout: 30_000, polling: 100 }
)
// Require exact output once: RN-Web cancels submitted keydown, so page line-break binding must not send second CR.
expect(await page.evaluate(() => globalThis.__orcaLiveInputProbe.sent())).toEqual([
'l',
's',
'\r'
])
expect(await fieldValue(page)).toBe('')
expect(errors).toEqual([])
await page.close()
}, 300_000)
it('submits when Enter arrives with the keyboard composition still open', async () => {
// Android soft-keyboard Enter carries isComposing; RN-Web suppresses onSubmitEditing unlike native editor action.
const { errors, page } = await openProbe()
@@ -270,31 +241,6 @@ describeRender(
expect(errors).toEqual([])
await page.close()
}, 300_000)
it('erases and retypes a word the keyboard corrects when it commits', async () => {
const { errors, page } = await openProbe({ userAgent: ANDROID_WEBVIEW_USER_AGENT })
await page.focus(`#${LIVE_INPUT_FIELD_ID}`)
const input = await page.context().newCDPSession(page)
for (const text of ['t', 'te', 'teh']) {
await compose(input, text)
await waitForField(page, text)
}
await input.send('Input.insertText', { text: 'the' })
await waitForField(page, 'the')
await page.waitForFunction(
() => globalThis.__orcaLiveInputProbe.sent().length === 4,
undefined,
{
timeout: 30_000,
polling: 50
}
)
expect(await sent(page)).toEqual(['t', 'e', 'h', '\u007f\u007fhe'])
expect(errors).toEqual([])
await page.close()
}, 300_000)
})
},
900_000
@@ -27,7 +27,6 @@ const DESKTOP_SUITE_PREFIXES = [
'src/main/runtime/agent-session/agent-session-account-',
'src/main/runtime/agent-session/agent-session-acquisition-',
'src/main/runtime/agent-session/agent-session-conversation-',
'src/main/runtime/agent-session/agent-session-death-',
'src/main/runtime/agent-session/agent-session-launch-',
'src/main/runtime/agent-session/agent-session-operation-',
'src/main/runtime/agent-session/agent-session-rewind-',
@@ -1,10 +1,8 @@
import { mkdtempSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import { afterEach, expect, it } from 'vitest'
import { classifyNodeServerChanges, collectNodeServerInputs } from './node-server-change-scope.mjs'
import { runProcessSync } from '@orca/process-host'
import { NODE_SERVER_RUNNERS } from './node-server-qualification.mjs'
const temporaryDirs = []
afterEach(() => {
@@ -76,20 +74,6 @@ it('tracks workspace source and manifest closures without trusting dist or widen
).toBe(false)
})
it.each(['@orca/unknown', '@orca/process-host/private'])(
'retains qualification for an unresolved internal package export: %s',
async (specifier) => {
const root = workspaceTree(specifier)
const result = await classifyNodeServerChanges(
['src/packages/process-host/src/run-process.ts'],
() => collectNodeServerInputs({ root, entryPoints: ['entry.ts'] })
)
expect(result.shouldRun).toBe(true)
expect(result.graphUnavailable).toBe(true)
expect(result.reason).toContain('No public orca-source export')
}
)
it('checks ordinary source unit files against actual imports before skipping the matrix', async () => {
const reachable = 'src/main/persistence/example/used.test.ts'
const unrelated = 'src/main/persistence/example/unrelated.test.tsx'
@@ -118,90 +102,3 @@ it('retains qualification when a removed ordinary unit file breaks an actual imp
expect(result.reason).toContain('Dependency graph unavailable')
expect(result.reason).toContain('removed.test.ts')
})
it.each([
{ files: [], deferred: true, expected: 'should_run=true' },
{ files: ['package.json'], deferred: true, expected: 'should_run=true' },
{
files: ['src/main/persistence/profile-state/profile-state-windows.ts'],
deferred: true,
fullQualification: false,
qualification: false,
runners: ['ubuntu-22.04', 'windows-2022', 'windows-11-arm'],
expected: 'should_run=true'
},
{
files: ['src/main/persistence/profile-state/profile-state-windows.ts'],
deferred: true,
expected: 'should_run=true'
},
{
files: ['src/main/providers/provider-windows.ts'],
deferred: true,
fullQualification: false,
expected: 'should_run=true'
},
{
files: ['src/main/persistence/profile-state/profile-state-recovery-crash-boundaries.test.ts'],
deferred: true,
fullQualification: false,
pullRequest: true,
nativeGraph: true,
expected: 'should_run=true'
},
{ files: ['src/renderer/src/example.ts'], deferred: true, expected: 'graph_required=true' },
{ files: ['src/renderer/src/example.ts'], deferred: false, expected: 'should_run=true' }
])('fails closed or requests dependencies in an uninstalled checkout: %j', (scenario) => {
const root = moduleTree(
Object.fromEntries(
[
'node-server-change-scope',
'node-server-test-paths',
'node-server-qualification',
'node-server-native-compat-scope'
].map((name) => [
`config/scripts/node-server/qualification/${name}.mjs`,
readFileSync(new URL(`./${name}.mjs`, import.meta.url), 'utf8')
])
)
)
const changes = join(root, 'changes')
const stepOutput = join(root, 'step-output')
const statuses = join(root, 'native-diff')
writeFileSync(changes, scenario.files.map((file) => `${file}\0`).join(''))
writeFileSync(
statuses,
scenario.files
.map((file) => `:100644 100644 ${'1'.repeat(40)} ${'2'.repeat(40)} M\0${file}\0`)
.join('')
)
const result = runProcessSync({
program: process.execPath,
args: [
realpathSync(
join(root, 'config/scripts/node-server/qualification/node-server-change-scope.mjs')
),
changes,
...(scenario.fullQualification === false ? [] : ['--full-qualification']),
...(scenario.deferred ? ['--defer-graph'] : []),
...(scenario.pullRequest ? ['--pull-request', '--diff-paths', statuses] : [])
],
cwd: root,
env: { ...process.env, GITHUB_OUTPUT: stepOutput },
timeoutMs: 5_000
})
expect(result.code).toBe(0)
const output = readFileSync(stepOutput, 'utf8')
expect(output).toContain(scenario.expected)
if (scenario.nativeGraph) {
expect(output).toContain('graph_required=true')
expect(output).not.toContain('native_compatibility=')
}
if (scenario.expected === 'graph_required=true') {
expect(output).not.toContain('should_run=')
expect(output).not.toContain('runners=')
} else {
expect(output).toContain(`qualification=${scenario.qualification !== false}`)
expect(output).toContain(`runners=${JSON.stringify(scenario.runners ?? NODE_SERVER_RUNNERS)}`)
}
})
@@ -1,10 +1,7 @@
/** Mirrors ORCA_REQUIRED_TEST_INPUTS_ENV in src/main/orcad/orcad-node-slot-fixture.ts. */
export const REQUIRED_TEST_INPUTS_ENV = 'ORCA_REQUIRED_TEST_INPUTS'
// Need the pinned Bun and the last Bun orcad slot beside the built Node slot (design D7).
export const CROSS_RUNTIME_TEST_PATHS = [
'src/main/persistence/profile-state/profile-state-cross-runtime.integration.test.ts'
]
export const CROSS_RUNTIME_TEST_PATHS = []
// Need the built desktop server template; CI runs them by path after build-orcad-template.mjs.
export const TEMPLATE_TEST_PATHS = [
@@ -18,7 +15,7 @@ export function nodeServerTestPaths({
} = {}) {
return [
'src/main/persistence/profile-state',
'src/main/persistence/loading-store/profile-state',
'src/main/persistence/loading-store/profile-writing/profile-state',
'src/main/sqlite',
// The orcad server's identity and stop path, which Windows SSH hosts rely on (W2).
'src/main/orcad/orcad-instance-lock.test.ts',
@@ -18,9 +18,9 @@ const ORCAD_COMPAT_BUILD_TARGET = 'node18'
export const ORCAD_CHILD_ENTRY_POINTS = {
watcher: 'src/main/ipc/filesystem/watcher-process/parcel-watcher-process-entry.ts',
daemon: 'src/main/daemon/daemon-entry.ts',
writer: 'src/main/persistence/profile-state/profile-state-writer-worker-entry.ts',
backup: 'src/main/persistence/profile-state/profile-state-backup-worker-entry.ts',
sessionSearch: 'src/main/ai-vault-search/session-search-worker-entry.ts',
writer: 'src/main/persistence/profile-state/writer/profile-state-writer-worker-entry.ts',
backup: 'src/main/persistence/profile-state/backup/profile-state-backup-worker-entry.ts',
sessionSearch: 'src/main/ai-vault-search/worker/session-search-worker-entry.ts',
foreignSqliteReader: 'src/main/foreign-sqlite-readers/foreign-sqlite-reader-entry.ts',
portScanCommandWorker: 'src/main/ports/port-scan-command-worker-entry.ts',
commandPathDirectoryWorker: 'src/main/ipc/command-path/command-path-directory-worker-entry.ts',
@@ -19,7 +19,7 @@ async function initializeFixture(directory, databasePath, profileId) {
const fixture = join(directory, 'initialize.cjs')
await build({
stdin: {
contents: `import { openProfileStateDatabase } from './src/main/persistence/profile-state/profile-state-database';
contents: `import { openProfileStateDatabase } from './src/main/persistence/profile-state/database/profile-state-database';
export function initialize(path, profileId) { openProfileStateDatabase(path, profileId).db.close() }`,
resolveDir: resolve(import.meta.dirname, '../../../..'),
sourcefile: 'profile-state-build-fixture.ts'
@@ -1,63 +0,0 @@
import { build } from 'esbuild'
import { copyFileSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { smokeProfileStateWorkers } from './profile-state-worker-smoke.mjs'
const directories = []
const writerFilename = 'profile-state-writer-worker-entry.js'
const backupFilename = 'profile-state-backup-worker-entry.js'
let builtDirectory
function fixtureDirectory() {
const directory = mkdtempSync(join(tmpdir(), 'orca-profile-worker-build-test-'))
directories.push(directory)
return directory
}
beforeAll(async () => {
builtDirectory = fixtureDirectory()
await Promise.all(
['writer', 'backup'].map((role) =>
build({
entryPoints: [
resolve(`src/main/persistence/profile-state/profile-state-${role}-worker-entry.ts`)
],
outfile: join(builtDirectory, `profile-state-${role}-worker-entry.js`),
bundle: true,
platform: 'node',
target: 'node18',
format: 'cjs',
logLevel: 'silent'
})
)
)
})
afterAll(() => {
for (const directory of directories) {
rmSync(directory, { recursive: true, force: true })
}
})
describe('profile state build smoke', () => {
it('writes through the built writer and verifies the built backup after handle release', async () => {
await expect(smokeProfileStateWorkers(builtDirectory)).resolves.toBeUndefined()
})
it('does not accept a successful backup response without the copied database', async () => {
const directory = fixtureDirectory()
copyFileSync(join(builtDirectory, writerFilename), join(directory, writerFilename))
writeFileSync(
join(directory, backupFilename),
`const { parentPort } = require('node:worker_threads')
parentPort.postMessage({ ok: true })
parentPort.close()`
)
await expect(smokeProfileStateWorkers(directory)).rejects.toMatchObject({
code: 'ERR_SQLITE_ERROR',
errcode: 14
})
})
})
@@ -27,14 +27,40 @@ export function resolveClaudeBenchmarkCommit(ref) {
}
const SNAPSHOT_MODULE_PATHS = [
'src/main/usage/cache/usage-cache-snapshot-writer.ts',
'src/main/usage/usage-cache-snapshot-writer.ts',
'src/main/usage-cache-snapshot-writer.ts'
]
const PERSISTENCE_MODULE_PATHS = {
snapshot: SNAPSHOT_MODULE_PATHS,
lifecycle: [
'src/main/usage/provider-lifecycle/usage-provider-store-lifecycle.ts',
'src/main/usage/usage-provider-store-lifecycle.ts'
],
sourceCache: [
'src/main/usage/cache/usage-source-cache-file.ts',
'src/main/usage/usage-source-cache-file.ts'
]
}
function persistenceEntry(mode) {
function listClaudeBenchmarkModulePaths(commit, modulePaths) {
const listed = runProcessSync({
program: 'git',
args: ['ls-tree', '--name-only', commit, '--', ...modulePaths],
cwd: ROOT,
timeoutMs: 10_000,
maxOutputBytes: MIB,
env: { ...process.env, ORCA_BACKGROUND_LAUNCH: '1' }
})
assert.equal(listed.code, 0, listed.stderr)
assert.equal(listed.outputTruncated, false)
return new Set(listed.stdout.trim().split('\n'))
}
function persistenceEntry(mode, modulePaths) {
const exports = [
`export { UsageCacheSnapshotWriter } from './src/main/usage/usage-cache-snapshot-writer';`,
`export { UsageProviderStoreLifecycle } from './src/main/usage/usage-provider-store-lifecycle';`
`export { UsageCacheSnapshotWriter } from './${modulePaths.snapshot.slice(0, -3)}';`,
`export { UsageProviderStoreLifecycle } from './${modulePaths.lifecycle.slice(0, -3)}';`
]
if (mode === 'published') {
exports.push(`export { validatePersistedClaudeUsageProjections }
@@ -42,7 +68,7 @@ function persistenceEntry(mode) {
} else if (mode === 'main') {
exports.push(`export { readUsageSourceCache as readSourceCache,
writeUsageSourceCache as writeSourceCache, splitUsageCacheFile as splitCacheFile }
from './src/main/usage/usage-source-cache-file';`)
from './${modulePaths.sourceCache.slice(0, -3)}';`)
} else {
exports.push(`export { readClaudeUsageSourceCache as readSourceCache,
writeClaudeUsageSourceCache as writeSourceCache, persistClaudeUsageSourceCache as persistSourceCache,
@@ -75,24 +101,25 @@ const INACTIVE_LIFECYCLE_IMPORTS = new Map([
export async function loadClaudeUsageBenchmarkPersistence(mode, commit = null, frozen = new Map()) {
const sourceFingerprints = {}
const stubFingerprints = {}
let snapshotModulePath = SNAPSHOT_MODULE_PATHS[0]
const modulePaths = Object.fromEntries(
Object.entries(PERSISTENCE_MODULE_PATHS).map(([name, paths]) => [name, paths[0]])
)
const nativeModulePaths = new Map()
if (typeof commit === 'string') {
const listed = runProcessSync({
program: 'git',
args: ['ls-tree', '--name-only', commit, '--', ...SNAPSHOT_MODULE_PATHS],
cwd: ROOT,
timeoutMs: 10_000,
maxOutputBytes: MIB,
env: { ...process.env, ORCA_BACKGROUND_LAUNCH: '1' }
})
assert.equal(listed.code, 0, listed.stderr)
assert.equal(listed.outputTruncated, false)
const paths = new Set(listed.stdout.trim().split('\n'))
snapshotModulePath = SNAPSHOT_MODULE_PATHS.find((path) => paths.has(path))
assert(snapshotModulePath, 'Pinned usage snapshot writer is absent')
const paths = listClaudeBenchmarkModulePaths(
commit,
Object.values(PERSISTENCE_MODULE_PATHS).flat()
)
for (const [name, candidates] of Object.entries(PERSISTENCE_MODULE_PATHS)) {
if (name === 'sourceCache' && mode !== 'main') {
continue
}
modulePaths[name] = candidates.find((path) => paths.has(path))
assert(modulePaths[name], `Pinned usage ${name} is absent`)
}
}
const result = await build({
stdin: { contents: persistenceEntry(mode), loader: 'ts', resolveDir: ROOT },
stdin: { contents: persistenceEntry(mode, modulePaths), loader: 'ts', resolveDir: ROOT },
platform: 'node',
format: 'esm',
bundle: true,
@@ -107,7 +134,7 @@ export async function loadClaudeUsageBenchmarkPersistence(mode, commit = null, f
.join('/')
const modulePath = resolved.endsWith('.ts') ? resolved : `${resolved}.ts`
return SNAPSHOT_MODULE_PATHS.includes(modulePath)
? { path: resolve(ROOT, snapshotModulePath) }
? { path: resolve(ROOT, modulePaths.snapshot) }
: undefined
})
bundler.onResolve(
@@ -122,6 +149,29 @@ export async function loadClaudeUsageBenchmarkPersistence(mode, commit = null, f
return match ? { path: match, namespace: 'inactive-lifecycle' } : undefined
}
)
bundler.onResolve({ filter: /^\./ }, (args) => {
if (typeof commit !== 'string') {
return undefined
}
const target = relative(ROOT, resolve(args.resolveDir, args.path)).split(sep).join('/')
if (!target.startsWith('src/')) {
return undefined
}
if (!nativeModulePaths.has(target)) {
const extensions = ['.tsx', '.ts', '.jsx', '.js', '.css', '.json']
const candidates = extname(target)
? [target]
: [
...extensions.map((extension) => target + extension),
...extensions.map((extension) => `${target}/index${extension}`)
]
const paths = listClaudeBenchmarkModulePaths(commit, candidates)
const modulePath = candidates.find((path) => paths.has(path))
assert(modulePath, `Pinned usage source is absent: ${String(commit)}:${target}`)
nativeModulePaths.set(target, modulePath)
}
return { path: resolve(ROOT, nativeModulePaths.get(target)) }
})
bundler.onLoad({ filter: /.*/, namespace: 'inactive-lifecycle' }, (args) => {
const contents = INACTIVE_LIFECYCLE_IMPORTS.get(args.path)
stubFingerprints[args.path] = claudeBenchmarkSha256(contents)
@@ -205,7 +255,12 @@ export function createClaudeBenchmarkStore(arm, cacheFile, splitCacheFile, parse
class BenchmarkStore extends implementation.UsageProviderStoreLifecycle {
constructor() {
super(
{ getRepos: () => [], getAllWorktreeMeta: () => ({}) },
{
getRepos: () => [],
getAllWorktreeMeta: () => ({}),
getRememberedWorktreeDisplayNames: () => new Map(),
whenLoaded: async () => {}
},
{
logTag: '[claude-persistence-benchmark]',
resolveCacheFile: () => cacheFile,
@@ -1,9 +0,0 @@
import { describe, expect, it } from 'vitest'
import { summarizeBenchmarkSamples } from './benchmark-sample-summary.mjs'
describe('benchmark sample summary', () => {
it('averages the two middle samples for an even-sized median', () => {
expect(summarizeBenchmarkSamples([100, 1, 2, 99]).medianMs).toBe(50.5)
})
})
@@ -5,7 +5,7 @@ import { performance } from 'node:perf_hooks'
import { build } from 'esbuild'
// Pipe the baseline client module on stdin. Native process/filesystem operations are forbidden here.
const entry = path.resolve('src/main/computer/macos-native-provider-client.ts')
const entry = path.resolve('src/main/computer/macos-native/macos-native-provider-client.ts')
const sources = [readFileSync(0, 'utf8'), readFileSync(entry, 'utf8')]
assert(sources.every((source) => source.includes('export class MacOSNativeProviderClient')))
async function load(source) {
@@ -6,20 +6,20 @@ import {
} from '../../../../src/main/ai-vault/parse-cache/session-scanner-parse-cache'
import { resetSessionParseCacheForTests } from '../../../../src/main/ai-vault/parse-cache/session-parse-cache-store'
import { resetTranscriptConsumersForTests } from '../../../../src/main/ai-vault/transcripts/session-transcript-consumers'
import { SessionSearchEngine } from '../../../../src/main/ai-vault-search/session-search-engine'
import { SessionSearchEngine } from '../../../../src/main/ai-vault-search/query/session-search-engine'
import type {
SessionSearchRequest,
SessionSearchScope
} from '../../../../src/main/ai-vault-search/session-search-engine-types'
import { registerSessionSearchIndexConsumer } from '../../../../src/main/ai-vault-search/session-search-index-consumer'
import { SessionSearchStore } from '../../../../src/main/ai-vault-search/session-search-store'
} from '../../../../src/main/ai-vault-search/query/session-search-engine-types'
import { registerSessionSearchIndexConsumer } from '../../../../src/main/ai-vault-search/indexing/session-search-index-consumer'
import { SessionSearchStore } from '../../../../src/main/ai-vault-search/storage/session-search-store'
import type SyncDatabase from '../../../../src/main/sqlite/sync-database'
import {
writeSyntheticTranscriptCorpus,
type SyntheticCorpus,
type SyntheticCorpusOptions
} from '../../../../src/main/ai-vault-search/session-search-synthetic-corpus'
import { sessionCandidate } from '../../../../src/main/ai-vault-search/session-search-transcript-fixtures'
} from '../../../../src/main/ai-vault-search/indexing/session-search-synthetic-corpus'
import { sessionCandidate } from '../../../../src/main/ai-vault-search/indexing/session-search-transcript-fixtures'
// Measure real engine/store on synthetic corpus only; never use real transcripts.
@@ -6,14 +6,14 @@ import {
} from '../../../../src/main/ai-vault/parse-cache/session-scanner-parse-cache'
import { resetSessionParseCacheForTests } from '../../../../src/main/ai-vault/parse-cache/session-parse-cache-store'
import { resetTranscriptConsumersForTests } from '../../../../src/main/ai-vault/transcripts/session-transcript-consumers'
import { SessionSearchEngine } from '../../../../src/main/ai-vault-search/session-search-engine'
import { SessionSearchEngine } from '../../../../src/main/ai-vault-search/query/session-search-engine'
import type {
SessionSearchRequest,
SessionSearchScope
} from '../../../../src/main/ai-vault-search/session-search-engine-types'
import { registerSessionSearchIndexConsumer } from '../../../../src/main/ai-vault-search/session-search-index-consumer'
import { SessionSearchStore } from '../../../../src/main/ai-vault-search/session-search-store'
import { sessionCandidate } from '../../../../src/main/ai-vault-search/session-search-transcript-fixtures'
} from '../../../../src/main/ai-vault-search/query/session-search-engine-types'
import { registerSessionSearchIndexConsumer } from '../../../../src/main/ai-vault-search/indexing/session-search-index-consumer'
import { SessionSearchStore } from '../../../../src/main/ai-vault-search/storage/session-search-store'
import { sessionCandidate } from '../../../../src/main/ai-vault-search/indexing/session-search-transcript-fixtures'
import type SyncDatabase from '../../../../src/main/sqlite/sync-database'
import { writeToolHeavyCorpus, type ToolHeavyCorpus } from './session-search-tool-heavy-corpus'
@@ -9,10 +9,10 @@ import {
import { resetSessionParseCacheForTests } from '../../../../src/main/ai-vault/parse-cache/session-parse-cache-store'
import { resetTranscriptConsumersForTests } from '../../../../src/main/ai-vault/transcripts/session-transcript-consumers'
import { requestWholeTranscriptRead } from '../../../../src/main/ai-vault/transcripts/session-transcript-reader'
import { registerSessionSearchIndexConsumer } from '../../../../src/main/ai-vault-search/session-search-index-consumer'
import { SessionSearchStore } from '../../../../src/main/ai-vault-search/session-search-store'
import { writeSyntheticTranscriptCorpus } from '../../../../src/main/ai-vault-search/session-search-synthetic-corpus'
import { sessionCandidate } from '../../../../src/main/ai-vault-search/session-search-transcript-fixtures'
import { registerSessionSearchIndexConsumer } from '../../../../src/main/ai-vault-search/indexing/session-search-index-consumer'
import { SessionSearchStore } from '../../../../src/main/ai-vault-search/storage/session-search-store'
import { writeSyntheticTranscriptCorpus } from '../../../../src/main/ai-vault-search/indexing/session-search-synthetic-corpus'
import { sessionCandidate } from '../../../../src/main/ai-vault-search/indexing/session-search-transcript-fixtures'
import SyncDatabase from '../../../../src/main/sqlite/sync-database'
// Measures the real transcript reader and search store over a synthetic corpus.
@@ -63,6 +63,9 @@ await bundle(
OPENCODE_SQLITE_READER_FILENAME,
{ external: ['electron'] }
)
await bundle('src/main/opencode/opencode-wsl-text-task-entry.ts', OPENCODE_WSL_TEXT_TASK_FILENAME)
await bundle(
'src/main/opencode/text-tasks/wsl/opencode-wsl-text-task-entry.ts',
OPENCODE_WSL_TEXT_TASK_FILENAME
)
console.log('WSL guest build complete.')
@@ -90,7 +90,6 @@ async function collectPackageFiles(packageRoot) {
async function visit(directory) {
const entries = await readdir(directory, { withFileTypes: true })
// Build Node and packaged Electron may differ in ICU; use locale-independent identity ordering.
entries.sort((left, right) => compareCodeUnits(left.name, right.name))
for (const entry of entries) {
const absolutePath = path.join(directory, entry.name)
@@ -130,22 +129,9 @@ async function collectPackageFiles(packageRoot) {
return sortManifestFiles(files)
}
// Digest hashes array order; match runtime’s sorted depth-first filesystem walk.
function compareManifestPaths(left, right) {
const leftParts = left.split('/')
const rightParts = right.split('/')
const shared = Math.min(leftParts.length, rightParts.length)
for (let index = 0; index < shared; index += 1) {
const order = compareCodeUnits(leftParts[index], rightParts[index])
if (order !== 0) {
return order
}
}
return leftParts.length - rightParts.length
}
// Build Node and packaged Electron may differ in ICU; identity hashes complete paths in code-unit order.
function sortManifestFiles(files) {
return [...files].sort((left, right) => compareManifestPaths(left.path, right.path))
return [...files].sort((left, right) => compareCodeUnits(left.path, right.path))
}
function packageDigest(files) {
@@ -114,17 +114,6 @@ describe('skill bundle manifest generator', () => {
expect(digests).toHaveLength(2)
})
it('fails when a digest is missing or the pull request base cannot be read', async () => {
const sandbox = await createGeneratorSandbox()
sandbox.generate('--write')
expect(() => sandbox.generateOnPullRequest()).toThrow(/Cannot read the pull request base/)
await writeFile(
path.join(sandbox.root, 'resources', 'skills', 'released-digests.json'),
`${JSON.stringify({ schemaVersion: 1, skills: { demo: [] } }, null, 2)}\n`
)
expect(() => sandbox.generate()).toThrow(/stale/)
})
it.runIf(process.platform !== 'win32')(
'rejects executable files in shipped skill packages',
async () => {
@@ -1,48 +0,0 @@
import { describe, expect, it } from 'vitest'
import { assessProcessHostImports } from './check-process-host-imports.mjs'
const file = 'src/main/process-consumer.ts'
const manifest = { exports: { '.': './dist/index.js' } }
const assess = (source) => assessProcessHostImports(new Map([[file, source]]), manifest, new Set())
describe('process-host runtime import boundary', () => {
it.each([
"import type { ChildProcess } from 'node:child_process'",
"import type * as ChildProcess from 'child_process'",
"import type ChildProcess = require('node:child_process')",
"export type { ChildProcess } from 'node:child_process'",
"type Child = import('node:child_process').ChildProcess"
])('allows erased Node type ownership: %s', (source) => {
expect(assess(source)).toMatchObject({ direct: [], added: [], violations: [] })
})
it.each([
"import { spawn } from 'node:child_process'",
"import 'child_process'",
"import { type ChildProcess } from 'node:child_process'",
"export { spawn } from 'node:child_process'",
"const child = require('node:child_process')",
"const child = import('node:child_process')",
"import type { ChildProcess } from 'node:child_process'; require('node:child_process')",
"import { createRequire } from 'node:module'; const load = createRequire(import.meta.url); load('node:child_process')",
"process.getBuiltinModule('child_process')"
])('still rejects runtime access: %s', (source) => {
expect(assess(source)).toMatchObject({ direct: [file], added: [file] })
})
it('keeps package export restrictions for type-only imports', () => {
expect(assess("import type { Private } from '@orca/process-host/private'").violations).toEqual([
`${file}: @orca/process-host/private is not a public process-host export`
])
})
it('requires the WSL allowlist only for runtime child-process imports', () => {
const wsl = "const program = 'wsl.exe'"
expect(
assess(`import type { ChildProcess } from 'node:child_process'; ${wsl}`).violations
).toEqual([])
expect(assess(`import { spawn } from 'node:child_process'; ${wsl}`).violations).toEqual([
`${file}: direct wsl.exe exec must call assertWslDistroAllowed`
])
})
})
@@ -1,86 +0,0 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { runProcess, runProcessSync } from '@orca/process-host'
import { expect, it } from 'vitest'
import { resolvePinnedBunExecutable } from '../../tool-invocation/pinned-bun-executable.mjs'
const root = fileURLToPath(new URL('../../../..', import.meta.url))
it('restores environment stubs and finishes background imports before the next shared file', async () => {
const cache = join(root, 'node_modules/.cache')
mkdirSync(cache, { recursive: true })
const directory = mkdtempSync(join(cache, 'shared-worker-reset-'))
const write = (name, source) => writeFileSync(join(directory, name), source)
try {
write(
'vitest.config.mjs',
`import { defineConfig } from 'vitest/config'
import { BaseSequencer } from 'vitest/node'
class Ordered extends BaseSequencer {
async sort(specs) { return specs.sort((a, b) => a.moduleId.localeCompare(b.moduleId)) }
}
export default defineConfig({ test: {
root: ${JSON.stringify(directory)},
include: ['*.spec.mjs'], isolate: false, maxWorkers: 1,
setupFiles: ['./assert-import-finished.mjs', ${JSON.stringify(resolve(root, 'config/scripts/test-runtime/environment/vitest-shared-worker-file-reset.mjs'))}],
sequence: { sequencer: Ordered }
} })`
)
write(
'assert-import-finished.mjs',
`import { afterAll, expect } from 'vitest'
import { readFileSync } from 'node:fs'
afterAll(() => expect(readFileSync(new URL('./result', import.meta.url), 'utf8')).toBe('loaded'))`
)
write(
'import-started.mjs',
`export let started
export const ready = new Promise(resolve => { started = resolve })`
)
write(
'background.mjs',
`import { setImmediate } from 'node:timers/promises'
import { writeFileSync } from 'node:fs'
import { started } from './import-started.mjs'
started()
await setImmediate()
writeFileSync(new URL('./result', import.meta.url), 'loaded')`
)
write(
'01-replace-env.spec.mjs',
`import { it } from 'vitest'
import { ready } from './import-started.mjs'
it('replaces env and starts a background import', async () => {
process.env = { ...process.env }
void import('./background.mjs')
await ready
})`
)
write(
'02-stub-env.spec.mjs',
`import { expect, it, vi } from 'vitest'
it('removes an environment override after a previous file replaced env', () => {
vi.stubEnv('ORCA_SHARED_WORKER_OVERRIDE', 'asia-east2')
vi.unstubAllEnvs()
expect(process.env.ORCA_SHARED_WORKER_OVERRIDE).toBeUndefined()
})`
)
const result = await runProcess({
program: resolvePinnedBunExecutable(root, runProcessSync) ?? 'bun',
args: [
'--bun',
resolve(root, 'node_modules/vitest/vitest.mjs'),
'run',
'--config',
join(directory, 'vitest.config.mjs')
],
cwd: root,
env: { ...process.env, ORCA_BACKGROUND_LAUNCH: '1' },
timeoutMs: 30_000
})
expect(result.code, result.stdout + result.stderr).toBe(0)
} finally {
rmSync(directory, { recursive: true, force: true })
}
})
@@ -1,95 +1,12 @@
import { once } from 'node:events'
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { join } from 'node:path'
import { PassThrough } from 'node:stream'
import { afterAll, afterEach, beforeAll, expect, it, onTestFinished, vi } from 'vitest'
import { createVitest, type PoolOptions, type Vitest } from 'vitest/node'
import * as processes from '@orca/process-host'
import type { ChildProcess } from 'node:child_process'
import { expect, it, onTestFinished } from 'vitest'
import { createVitest } from 'vitest/node'
import { nodeRuntimePool } from './vitest-node-runtime-pool'
let context: Vitest
const children: ChildProcess[] = []
const spawn = processes.spawnProcess
beforeAll(async () => {
context = await createVitest('test', { config: false, watch: false, include: [] })
})
afterEach(async () => {
vi.useRealTimers()
vi.restoreAllMocks()
for (const child of children.splice(0)) {
if (child.pid && child.exitCode === null && child.signalCode === null) {
const exited = once(child, 'exit')
child.kill('SIGKILL')
await exited
}
}
})
afterAll(async () => {
await context.close()
})
function options(executable = process.execPath): PoolOptions {
return {
distPath: '',
project: context.getRootProject(),
method: 'run',
environment: { name: 'node', options: null },
execArgv: [],
env: { ...process.env, ORCA_TEST_NODE_EXECUTABLE: executable }
}
}
function captureChild(): void {
vi.spyOn(processes, 'spawnProcess').mockImplementation((spec) => {
const child = spawn(spec)
children.push(child)
return child
})
}
it('rejects an unavailable Node executable without an uncaught error or leaked pipes', async () => {
const output = context.logger.outputStream
const before = output.getMaxListeners()
const worker = nodeRuntimePool.createPoolWorker(options(resolve('missing-node-executable')))
await expect(worker.start()).rejects.toMatchObject({ code: 'ENOENT' })
await worker.stop()
expect(output.getMaxListeners()).toBe(before)
})
it('waits for a running Node worker to exit and restores its output listener budget', async () => {
captureChild()
const output = context.logger.outputStream
const before = output.getMaxListeners()
const worker = nodeRuntimePool.createPoolWorker(options())
await worker.start()
await worker.stop()
expect(children[0].signalCode).toBe('SIGTERM')
expect(output.getMaxListeners()).toBe(before)
})
it('reports a failed kill within its deadline rather than hanging teardown', async () => {
captureChild()
const worker = nodeRuntimePool.createPoolWorker(options())
const output = context.logger.outputStream
const before = output.getMaxListeners()
await worker.start()
const child = children[0]
vi.spyOn(child, 'kill').mockReturnValue(false)
vi.useFakeTimers()
const stopped = expect(worker.stop()).rejects.toThrow('did not exit after SIGKILL')
await vi.advanceTimersByTimeAsync(2_000)
await stopped
expect(child.kill).toHaveBeenCalledWith('SIGTERM')
expect(child.kill).toHaveBeenCalledWith('SIGKILL')
expect(child.listenerCount('exit')).toBe(0)
expect(output.getMaxListeners()).toBe(before)
})
it('reports a test file that fails to load as a failed file instead of crashing the run', async () => {
const dir = await mkdtemp(join(tmpdir(), 'orca-node-runtime-pool-'))
onTestFinished(() => rm(dir, { recursive: true, force: true }))
@@ -3,7 +3,6 @@ import { findSqliteRuntimeTests } from './vitest-sqlite-runtime-scan.mjs'
// SQLite publication, native bindings, worker IPC, socket liveness, and V8 retention use Node.
const NODE_RUNTIME_INCLUDE = [
// Exercise the native fetch error and abort contracts used by the Linear SDK in Electron.
'src/main/linear/linear-issue-detail-deadline.test.ts',
'tests/e2e/linear-cli-recovery.unit.test.ts',
'src/main/runtime/agent-session/lifecycle/structured-agent-cli-writers.test.ts',
'config/scripts/ci/workflow-contracts/cloud-security-history-workflow.test.mjs',
@@ -12,11 +11,10 @@ const NODE_RUNTIME_INCLUDE = [
'src/packages/process-host/src/run-process.test.ts',
'tests/e2e/cursor-quota-transport.unit.test.ts',
'tests/e2e/helpers/electron-process-shutdown.unit.test.ts',
'src/main/ai-vault-search/session-search-index-writer.test.ts',
'src/main/ai-vault-search/storage/session-search-index-writer.test.ts',
'src/main/ai-vault/session-scanner-unlimited-dedup.test.ts',
// The parse cache persists through node:sqlite.
'src/main/ai-vault/parse-cache/session-parse-cache-antigravity-upgrade.test.ts',
'src/main/ai-vault/parse-cache/session-parse-cache-large-scan.test.ts',
'src/main/ai-vault/parse-cache/session-parse-cache-persistence.test.ts',
'src/main/ai-vault/session-scanner-scope-cwd-facts.test.ts',
'src/main/ai-vault/session-scanner-scope-walk.test.ts',
@@ -39,8 +37,8 @@ const NODE_RUNTIME_INCLUDE = [
'src/main/claude/claude-transcript-duration.test.ts',
'tests/e2e/native-chat-startup-option-pickers.unit.test.ts',
'src/main/ai-vault/transcripts/session-document-consumer-replacement.test.ts',
'src/main/ai-vault-search/session-search-dependent-transcripts.test.ts',
'src/main/ai-vault-search/session-search-list-reparse.test.ts',
'src/main/ai-vault-search/indexing/session-search-dependent-transcripts.test.ts',
'src/main/ai-vault-search/indexing/session-search-list-reparse.test.ts',
'src/main/runtime/rpc/server/orchestration-cli-subprocess.test.ts',
'src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-mailbox-delivery.test.ts',
'src/main/runtime/orchestration/mailbox/routing/orchestration-mailbox-routing.test.ts',
@@ -50,13 +48,12 @@ const NODE_RUNTIME_INCLUDE = [
'tests/e2e/cross-version-wire/agent-session-clear-old-client.unit.test.ts',
'tests/e2e/cross-version-wire/agent-session-clear-old-tab-mirror.unit.test.ts',
'tests/e2e/cross-version-wire/host-model-catalog-released-phone.unit.test.ts',
'src/main/pi/rpc-session-adapter.test.ts',
'src/main/pi/rpc-session-startup.test.ts',
'src/main/pi/rpc/rpc-session-startup.test.ts',
'src/main/acp/session/acp-structured-omp-recordings.test.ts',
'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-clear-queued-command.test.ts',
'src/main/acp/session/acp-structured-session-adapter.test.ts',
'src/main/acp/session/acp-structured-session-adapter-resume.test.ts',
'src/main/pi/rpc-turn-races.test.ts',
'src/main/pi/rpc/rpc-turn-races.test.ts',
'src/main/acp/session/children/acp-structured-child-stop.test.ts',
'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-background-stop-unreadable.test.ts',
'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-exit-delivery.test.ts',
@@ -103,9 +100,7 @@ const NODE_RUNTIME_INCLUDE = [
'src/main/runtime/workspaces/removal/runtime-interrupted-local-worktree-removal.test.ts',
'src/main/workspaces/removal/local-worktree-removal-recovery-live.test.ts',
'src/main/rate-limits/providers/codex/codex-rpc-worker-backpressure.test.ts',
'src/main/computer/macos-native-provider-client.test.ts',
'src/main/ai-vault-search/session-search-schema.test.ts',
'src/main/ai-vault-search/session-search-fts5-contract.test.ts',
'src/main/computer/macos-native/macos-native-provider-client.test.ts',
'src/main/foreign-sqlite-readers/**/*.test.ts',
'src/main/browser/*cookie*.test.ts',
'src/main/browser/cookies/*cookie*.test.ts',
@@ -127,15 +122,13 @@ const NODE_RUNTIME_INCLUDE = [
'src/main/git/repo-detection.test.ts',
'src/renderer/src/components/browser-pane/annotate/browser-grab-toast-owner-cleanup.test.tsx',
'src/main/window/native-chat-paste-files.test.ts',
'src/main/computer/desktop-script-serve-channel.test.ts',
'src/main/computer/desktop-script/runtime-host/desktop-script-serve-channel.test.ts',
'src/main/providers/local-pty/local-pty-child-process-verdict.test.ts',
'src/main/providers/working-directory-validation.test.ts',
'src/main/pty/process-retirement/posix-pty-process-groups.integration.test.ts',
'src/shared/ephemeral-vm-recipe-output-capture.test.ts',
'src/main/gitlab/gitlab-known-host-retirement.test.ts',
'src/main/window/main-window-updater-deferred-setup.test.ts',
'src/renderer/src/components/terminal-pane/host-state/terminal-pane-host-state-memo.test.ts',
'src/renderer/src/components/automations/runs/use-automation-runs-dashboard-payload.test.tsx',
'src/main/native-chat/agent-session-journal/**/*.test.ts',
'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-terminal-writer-acquire.test.ts',
'src/main/runtime/agent-session/records/agent-session-conversation-name-store.test.ts',
@@ -149,7 +142,7 @@ const NODE_RUNTIME_INCLUDE = [
'src/shared/remote-runtime/requests/remote-runtime-request-websocket.test.ts',
'src/shared/remote-runtime/requests/remote-runtime-subscription-connect-bound.test.ts',
'src/main/codex/configuration/shared-server/codex-shared-server-probe.test.ts',
'src/main/opencode/opencode-launch-model-context-supervision.test.ts',
'src/main/opencode/model-launch/opencode-launch-model-context-supervision.test.ts',
'src/main/hermes/hermes-config-remote-adapter.test.ts',
'src/main/ipc/profiles/orca-profiles-switch-persistence.test.ts',
'src/main/ipc/settings-delayed-response.test.ts',
@@ -165,7 +158,6 @@ const NODE_RUNTIME_INCLUDE = [
'src/main/ipc/filesystem/watcher-process/parcel-watcher-shallow-file-subscription.test.ts',
'src/renderer/src/components/emulator-pane/emulator-device-frame-visibility.test.tsx',
'src/main/claude/claude-agent-sdk-contract-pins.test.ts',
'config/scripts/orcad-distribution/server-bundle/profile-state-worker-smoke.test.mjs',
'config/scripts/desktop-distribution/runtime-verification/process-host-dev-rebuild.test.ts',
'config/scripts/test-runtime/node-worker/vitest-node-runtime-pool.test.ts',
// Reopen WAL-backed row caches read-only, which Bun on macOS cannot.
@@ -28,8 +28,8 @@ const SQLITE_HARNESSES = new Set([
])
export const SQLITE_MODULES = [
'src/main/sqlite/sync-database',
'src/main/ai-vault-search/session-search-schema',
'src/main/ai-vault-search/session-search-store',
'src/main/ai-vault-search/storage/session-search-schema',
'src/main/ai-vault-search/storage/session-search-store',
'src/main/persistence/profile-state/profile-state-sqlite-authority',
'src/main/native-chat/agent-session-journal/database/journal-host-database',
'src/main/runtime/orchestration/db',
@@ -35,7 +35,7 @@ const MANAGED_SSH_HARNESS =
// An enabled SSH automation moves with its host and is re-enabled on the server (#29083).
const ENABLED_AUTOMATION_MOVE =
/^src\/(?:main\/(?:persistence\/(?:migrating-orcad-catalog\/orcad-(?:source-automation-state|source-dormant-state|source-dependency-census|destination-automation-state)|scheduling-automations\/automation-schedule-operations)|automations\/(?:run-target-resolution|automation-dispatch-request|orcad-fenced-automation)|ssh\/orcad-migration-(?:moved-automations|source-retention))|shared\/orcad-migration\/orcad-migration-(?:dormant-automation-validation|source-cutover))\.ts$/
/^src\/(?:main\/(?:persistence\/(?:migrating-orcad-catalog\/(?:source\/(?:automations\/orcad-source-automation-state|dormancy\/orcad-source-dormant-state|sessions\/orcad-source-dependency-census)|destination\/orcad-destination-automation-state)|scheduling-automations\/automation-schedule-operations)|automations\/(?:run-target-resolution|automation-dispatch-request|orcad-fenced-automation)|persistence\/migrating-orcad-catalog\/retained-source\/orcad-migration-(?:moved-automations|source-retention))|shared\/orcad-migration\/orcad-migration-(?:dormant-automation-validation|source-cutover))\.ts$/
export const PR_E2E_SOURCE_ROUTES = [
...PR_BROWSER_E2E_SOURCE_ROUTES,
@@ -153,16 +153,6 @@ export const PR_E2E_SOURCE_ROUTES = [
file
)
},
{
id: 'ssh.orcad-auto-convert',
specs: ['tests/e2e/ssh-orcad-auto-convert.spec.ts'],
matches: (file) =>
MANAGED_SSH_HARNESS.test(file) ||
(isProductSource(file) &&
/^src\/main\/(?:ipc\/(?:ssh\/)?ssh-host-server-|(?:ssh|managed-server\/[a-z-]+)\/(?:ssh-host-server-|orcad-runtime-conversion|orcad-migration-|orcad-retained-source|orcad-runtime-deployment))/.test(
file
))
},
{
id: 'ssh.orcad-connect-failure',
specs: [
@@ -174,7 +164,7 @@ export const PR_E2E_SOURCE_ROUTES = [
MANAGED_SSH_HARNESS.test(file) ||
ENABLED_AUTOMATION_MOVE.test(file) ||
(isProductSource(file) &&
/^src\/(?:main\/(?:ipc\/ssh\/(?:ssh-connect-flow|ssh-host-server-)|ssh\/(?:ssh-session-start-failure|ssh-host-server-|connection\/ssh-connection-manager|orcad-migration-refusal-reason|targets\/ssh-target-orcad-preflight)|managed-server\/lifecycle\/orcad-runtime-conversion|persistence\/migrating-orcad-catalog\/orcad-source-(?:automation-state|leave-behind-view))|renderer\/src\/(?:ssh\/(?:ssh-host-server-status-copy|ssh-connect-failure-toast)|components\/settings\/(?:SshTargetServerStatus|SshHostMoveAnywayAction|SshTargetCard)))/.test(
/^src\/(?:main\/(?:ipc\/ssh\/(?:ssh-connect-flow|ssh-host-server-)|ssh\/(?:ssh-session-start-failure|ssh-host-server-|connection\/ssh-connection-manager|orcad-migration-refusal-reason|targets\/ssh-target-orcad-preflight)|managed-server\/lifecycle\/orcad-runtime-conversion|persistence\/migrating-orcad-catalog\/source\/(?:automations\/orcad-source-automation-state|catalog\/orcad-source-leave-behind-view))|renderer\/src\/(?:ssh\/(?:ssh-host-server-status-copy|ssh-connect-failure-toast)|components\/settings\/(?:SshTargetServerStatus|SshHostMoveAnywayAction|SshTargetCard)))/.test(
file
))
},
@@ -352,7 +342,7 @@ export const PR_E2E_SOURCE_ROUTES = [
matches: (file) =>
MANAGED_SSH_HARNESS.test(file) ||
(isProductSource(file) &&
/^src\/main\/(?:persistence\/migrating-orcad-catalog\/orcad-source-(?:draft-rename|workspace-session|session-copy-resolution|export)|ssh\/orcad-migration-source-retention|ipc\/ssh\/ssh)\.ts$/.test(
/^src\/main\/(?:persistence\/migrating-orcad-catalog\/source\/(?:worktrees\/orcad-source-draft-rename|sessions\/orcad-source-(?:workspace-session|session-copy-resolution)|catalog\/orcad-source-export)|persistence\/migrating-orcad-catalog\/retained-source\/orcad-migration-source-retention|ipc\/ssh\/ssh)\.ts$/.test(
file
))
},
@@ -13,9 +13,9 @@ const LAYOUT_ORACLE_PREFIXES = [
'src/shared/workspace-layout/terminal-leaf-move.ts',
'src/main/persistence/terminal-topology/',
'src/main/persistence/restoring-sessions/',
'src/main/persistence/loading-store/pty-binding-',
'src/main/persistence/loading-store/session-host-partitions.ts',
'src/main/persistence/loading-store/workspace-session-snapshot-publication.ts',
'src/main/persistence/loading-store/terminal-bindings/pty-binding-',
'src/main/persistence/loading-store/workspace-sessions/session-host-partitions.ts',
'src/main/persistence/loading-store/workspace-sessions/workspace-session-snapshot-publication.ts',
'src/main/remote-layout-snapshot/',
'src/main/runtime/old-session-tabs-stream/',
'src/renderer/src/runtime/remote-workspace-frozen/',
@@ -129,7 +129,6 @@ export const LINUX_PACKAGE_TESTS = [
'src/main/browser/guest-lifecycle/popups/presentation/popup-origin-chrome.electron.test.ts',
'src/main/browser/guest-lifecycle/navigation/browser-link-materialization.electron.test.ts',
'src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts',
'src/main/persistence/profile-state/profile-state-writer-stall.electron.test.ts',
'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility.electron.test.ts',
'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-native-compatibility.electron.test.ts',
'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-background-compatibility.electron.test.ts',
@@ -162,7 +161,6 @@ export const WINDOWS_BOUNDARY_TESTS = [
'config/scripts/desktop-distribution/runtime-verification/package-electron-runtime-contract.test.mjs',
'config/scripts/desktop-distribution/runtime-verification/electron-builder-runtime-resources.test.mjs',
'src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts',
'src/main/persistence/profile-state/profile-state-writer-stall.electron.test.ts',
'src/main/providers/windows-conpty-wide-char-duplication.node-pty.test.ts',
'src/shared/__tests__/process-host/windows-command-line.win32.test.ts',
'src/shared/__tests__/process-host/windows-cmd-shim-resolution.test.ts',
@@ -191,14 +189,13 @@ export const WINDOWS_BOUNDARY_TESTS = [
'src/main/daemon/endpoint/identity/testing/daemon-pid-identity-native.win32.test.ts',
'src/main/daemon/pty-subprocess/testing/node-pty-conout-worker-errors.test.ts',
'src/main/daemon/pty-subprocess/testing/node-pty-windows-output-error.win32.test.ts',
'src/main/persistence/profile-state/profile-state-access-windows-native.win32.test.ts',
'src/main/persistence/profile-state/access/profile-state-access-windows-native.win32.test.ts',
'src/main/pty/process-retirement/windows-live-tree-kill.win32.test.ts',
'src/main/wsl/execution/wsl-guest-environment.test.ts',
'src/main/wsl/execution/wsl-executable-path.win32.test.ts',
'src/main/claude-accounts/claude-profile-history-windows.test.ts',
'src/shared/source-scan/source-tree-scan.test.ts',
'src/main/cli/wsl-cli-powershell-boundary.test.ts',
'src/main/computer/desktop-script-runtime-host.win32.test.ts',
'src/main/cli/wsl/wsl-cli-powershell-boundary.test.ts',
'src/main/cursor/hook-service.test.ts',
'src/main/orca-profiles/profile-index-store.test.ts',
'src/main/startup/windows-install-dir-acl-repair.win32.test.ts',
@@ -22,7 +22,7 @@ export const PR_WSL_E2E_SOURCE_ROUTES = [
id: 'wsl-move.fence',
specs: ['tests/e2e/wsl-move-fence.spec.ts'],
matches: (file) =>
/^src\/(?:main\/(?:persistence\/moving-wsl-projects\/wsl-move-(?:scope-guard|fence|reset|startup|startup-rewrite|cutover-journal)|ipc\/pty\/host-env\/spawn-cwd|wsl\/host-lifecycle\/wsl-host-gate(?:-startup)?)|shared\/wsl-move\/wsl-move-cutover)\.ts$/.test(
/^src\/(?:main\/(?:persistence\/moving-wsl-projects\/(?:quiescence\/wsl-move-(?:scope-guard|fence)|cutover-recovery\/wsl-move-(?:reset|cutover-journal)|startup\/wsl-move-(?:startup|startup-rewrite))|ipc\/pty\/host-env\/spawn-cwd|wsl\/host-lifecycle\/wsl-host-gate(?:-startup)?)|shared\/wsl-move\/wsl-move-cutover)\.ts$/.test(
file
)
},
+1 -1
View File
@@ -8,7 +8,7 @@
"../src/shared/editor-language/monaco-language-associations.json",
"../src/packages/process-host/src/__fixtures__/**/*",
// Loaded by path beside its launcher, so no import reaches it.
"../src/main/persistence/profile-state/profile-state-backup-worker-entry.ts"
"../src/main/persistence/profile-state/backup/profile-state-backup-worker-entry.ts"
],
"compilerOptions": {
// The CLI runs on Node 24; Node20 models synchronous ESM imports from CommonJS.
+1 -1
View File
@@ -39,7 +39,7 @@
],
"exclude": [
"../src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail.test.ts",
"../src/main/runtime/rpc/methods/orchestration/orchestration-check-ambiguous-caller.test.ts"
"../src/main/runtime/agent-session/structured-agent-session-chat-wait-work-state.test.ts"
],
"compilerOptions": {
"composite": true,
+3 -3
View File
@@ -25,12 +25,12 @@
"../src/preload/renderer-restart-wiring.ts",
"../src/preload/runtime-environment-subscriptions.ts",
"../src/preload/usage-provider-api.ts",
"../src/main/pi/rpc-model-schema.ts",
"../src/main/pi/rpc-model-options.ts",
"../src/main/pi/rpc/options/rpc-model-schema.ts",
"../src/main/pi/rpc/options/rpc-model-options.ts",
"../src/shared/**/*",
"../mobile/src/worktree/worktree-agent-child-rows.ts",
"../src/packages/process-host/src/__fixtures__/**/*",
"../src/main/gitlab/mappers.ts",
"../src/main/gitlab/requests/gitlab-response-mapping.ts",
"../src/main/source-control/hosted-review-branch-cache.ts",
"../src/main/source-control/hosted-review-branch-cache-types.ts",
"../src/main/source-control/hosted-review-active-branch-claims.ts",
+1 -1
View File
@@ -2,7 +2,7 @@
"extends": "./tsconfig.web.json",
"include": [
"../src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail.test.ts",
"../src/main/runtime/rpc/methods/orchestration/orchestration-check-ambiguous-caller.test.ts",
"../src/main/runtime/agent-session/structured-agent-session-chat-wait-work-state.test.ts",
"../src/renderer/src/components/task-page/linear/task-page-linear-detail-query.test.tsx",
"../src/renderer/src/runtime/observed-provider-accounts.test.tsx",
"../src/renderer/src/components/status-bar/ClaudeSwitcherMenu.observation.test.tsx",
+2 -2
View File
@@ -6,8 +6,8 @@
"../src/renderer/src/**/*.tsx",
"../src/preload/api-types.ts",
"../src/preload/api/**/*",
"../src/main/pi/rpc-model-schema.ts",
"../src/main/pi/rpc-model-options.ts",
"../src/main/pi/rpc/options/rpc-model-schema.ts",
"../src/main/pi/rpc/options/rpc-model-options.ts",
"../src/shared/**/*"
],
"exclude": [
+2 -6
View File
@@ -7,20 +7,16 @@ import { nodeRuntimePool } from './scripts/test-runtime/node-worker/vitest-node-
const contracts = [
'src/main/runtime/session-tabs/session-tabs-phone-layout-moves.test.ts',
'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-terminal-writer-acquire.test.ts',
'src/shared/agent-launch/permissions/tui-agent-permission-choice.test.ts',
'src/main/runtime/rpc/methods/projects/repo.test.ts',
'src/renderer/src/components/tab-bar/use-new-tab-agent-menu-host-preferences.test.tsx',
'src/main/sqlite/sync-database.test.ts',
'src/main/runtime/orchestration/db/row-column-lists.test.ts',
'src/shared/native-chat/tools/native-chat-tool-pairing.performance.test.ts',
'src/main/codex-usage/codex-rollout-file-lifetime.test.ts',
'src/main/codex-usage/scanner-incremental-append.test.ts',
'src/main/usage/jsonl-file-reader.test.ts',
'src/main/usage/jsonl-file-snapshot.test.ts',
'src/main/usage/source-input/jsonl/jsonl-file-reader.test.ts',
'config/scripts/static-analysis/oxlint-contracts/app-store-performance-plugin.test.mjs',
'config/scripts/static-analysis/oxlint-contracts/quadratic-buffer-concat-plugin.test.mjs',
'src/main/claude-usage/scanner-incremental-append.test.ts',
'src/main/claude-usage/store-checkpoint-persistence.test.ts'
'src/main/runtime/agent-session/structured-agent-session-chat-wait-work-state.test.ts'
]
for (const contract of contracts) {
if (!existsSync(resolve(contract))) {
+4 -4
View File
@@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="113" height="20" role="img" aria-label="downloads: 170m">
<title>downloads: 170m</title>
<svg xmlns="http://www.w3.org/2000/svg" width="113" height="20" role="img" aria-label="downloads: 171m">
<title>downloads: 171m</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
@@ -15,7 +15,7 @@
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="11">
<text x="37" y="15" fill="#010101" fill-opacity=".3">downloads</text>
<text x="37" y="14">downloads</text>
<text x="93.5" y="15" fill="#010101" fill-opacity=".3">170m</text>
<text x="93.5" y="14">170m</text>
<text x="93.5" y="15" fill="#010101" fill-opacity=".3">171m</text>
<text x="93.5" y="14">171m</text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 943 B

After

Width:  |  Height:  |  Size: 943 B

+1 -1
View File
@@ -52,7 +52,7 @@ If an agent's CLI is installed outside `PATH`, expand its row in **Settings →
| Freebuff | Auto-setup | [Freebuff](https://freebuff.com/cli) |
| Command Code | Auto-setup, status | [Command Code](https://commandcode.ai/docs/quickstart) |
| Muse | macOS/Linux; trusts the workspace at launch | [Meta](https://dev.meta.ai/docs/muse-code) |
| DeepSeek Harness | Launched through its `dsh-tui` profile; hooks, status, questions, resume | [DeepSeek](https://deepseek-harness.github.io/deepseek-harness/) |
| DeepSeek Harness | Needs `@deepseek-ai/dsh` plus the community `@deepseek-harness-tui/dsh-tui`; hooks, status, questions, resume | [dsh-TUI](https://github.com/ccch1mneyyy/dsh-TUI#quick-start) |
| ZCode | Deep integration; needs a `zcode` CLI that ships the TUI (see note below) | [Z.ai](https://zcode.z.ai/en/docs) |
| Continue | Auto-setup | [Continue](https://docs.continue.dev/cli/quickstart) |
| Cursor CLI | Deep integration | [Cursor](https://cursor.com/cli) |
@@ -86,6 +86,12 @@ orca orchestration worker-keep-open --dispatch <dispatchId>
orca orchestration worker-start --task <taskId> --retry-of <dispatchId> --worktree current --agent codex
```
When a worker stops at a permission prompt, the escalation names the prompt. Only a person can allow it, so carry on with other work until its closing message arrives; if it is holding up the task, deny it with a reason and the worker carries on another way:
```bash
orca orchestration deny --dispatch <dispatchId> --prompt <approvalId> --reason "<what to do instead>"
```
Do not leave completed worker terminals open just to re-read output — use `worker-read` after `worker-release`. Do not substitute a broad `terminal close` when release returns `release_pending` or `release_unknown`; follow the receipt's recovery action.
## Federated workers (optional)
+1
View File
@@ -125,6 +125,7 @@ For a direct LAN or Tailscale connection, allow the paired desktop's listening p
- **Pairing fails** — make sure your desktop and phone are signed into the same Orca account. Pairing codes expire after a few minutes; generate a fresh one if it's been sitting on the screen.
- **Authentication failed / pairing invalid** — the desktop no longer accepts this device token (for example after desktop cleared paired devices). Try **Retry** on the banner first (transient rejections can recover without re-pairing). If it keeps failing, use **Re-pair** from desktop, or **Remove** the host and pair again.
- **Update Orca Mobile / Update Orca on your computer** — the phone and desktop speak a versioned mobile protocol. If either side is too old, mobile blocks that host and points you at the App Store (iOS), [GitHub Releases](https://github.com/stablyai/orca/releases) (Android APK or desktop), then back to hosts. After updating, refresh the connection; if the message stays, remove the host and pair again.
- **A chat tab says Update mobile** — the session was started in desktop Chat UI, and this phone's app is too old to show it (the tab opens to an empty pane). Update the mobile app, then reconnect to the host so it sees the new app. If the app is already up to date and the tab still says Update mobile after reconnecting, report it with your mobile app version and desktop Orca version.
- **Quick Commands unavailable** — update the paired desktop so it advertises the quick-commands capability.
- **Can't reach desktop** — phone and desktop must share a network path (LAN, Tailscale, or the pairing path you used). Closing the desktop app drops the connection; reopen desktop and the phone reconnects automatically.
@@ -14,10 +14,4 @@ class IosReleaseVersionTest < Minitest::Test
assert_equal("0.0.36", version)
end
def test_max_version_compares_numerically_not_lexically
assert_equal("0.0.10", IosReleaseVersion.max_version(%w[0.0.9 0.0.10 0.0.2]))
assert_equal("0.2.0", IosReleaseVersion.max_version(%w[0.1.99 0.2.0]))
assert_equal("1.0.0", IosReleaseVersion.max_version(%w[0.9.9 1.0.0]))
end
end

Some files were not shown because too many files have changed in this diff Show More