diff --git a/.gitattributes b/.gitattributes index 736d59473f6..1b447a9189e 100644 --- a/.gitattributes +++ b/.gitattributes @@ -31,6 +31,13 @@ # the reviewable change, and pin LF because they are compared byte-for-byte. # Not -diff: the shell diff is the review surface when a wrapper does change. /src/main/__fixtures__/shell-wrapper-snapshots/*.txt linguist-generated=true text eol=lf +# Captured agent PTY transcripts. -text, not `text eol=lf` like the wrapper snapshots above: +# these carry real CR and CRLF bytes as the terminal emitted them, and line-ending +# normalisation on a Windows checkout would rewrite the evidence the fixture exists to be. +/src/main/runtime/__fixtures__/*.txt -text # Generated runtime English subset: compared byte-for-byte by # verify:localization-runtime-catalog, so a CRLF checkout would fail the gate. /src/renderer/src/i18n/en-runtime-required.json linguist-generated=true text eol=lf +# Generated method->params catalog: compared byte-for-byte by +# verify:rpc-params-catalog, so a CRLF checkout would fail the gate. +/src/shared/rpc-contract/rpc-params-catalog.generated.ts linguist-generated=true text eol=lf diff --git a/.github/workflows/cloud-deploy-relay-production-director.yml b/.github/workflows/cloud-deploy-relay-production-director.yml index 4489d67b845..07e1e74ec3c 100644 --- a/.github/workflows/cloud-deploy-relay-production-director.yml +++ b/.github/workflows/cloud-deploy-relay-production-director.yml @@ -13,6 +13,11 @@ on: default: preserve type: choice options: [preserve, enable, disable] + region-correction-cohort-percent: + description: 'Preserve the measured-correction cohort, or set an integer 0–100; durable rehome stays disabled' + required: true + default: preserve + type: string prune-incompatible-revisions: description: Retain only the newly verified serving and rollback revisions required: true @@ -62,6 +67,7 @@ jobs: REGIONAL_PLACEMENT_SECRET: orca-cloud-relay-regional-placement-enabled IMAGE_DIGEST: ${{ inputs.image-digest }} REGIONAL_PLACEMENT_MODE: ${{ inputs.regional-placement-mode }} + REGION_CORRECTION_COHORT_PERCENT: ${{ inputs.region-correction-cohort-percent }} PRUNE_INCOMPATIBLE_REVISIONS: ${{ inputs.prune-incompatible-revisions }} # Floor the served revision must keep, matching relay_min_instances in # environments/production.tfvars. This gate only fails a bad deploy; Terraform @@ -106,8 +112,11 @@ jobs: echo "image-digest must be an immutable lowercase sha256 digest" >&2 exit 1 fi + if test "${REGION_CORRECTION_COHORT_PERCENT}" != preserve; then + [[ "${REGION_CORRECTION_COHORT_PERCENT}" =~ ^([0-9]|[1-9][0-9]|100)$ ]] + fi IMAGE="${IMAGE_REPOSITORY}@${IMAGE_DIGEST}" - SERVED_DIGEST="$(gcloud artifacts docker images describe "${IMAGE}" --format='value(image_summary.digest)')" + SERVED_DIGEST="$(gcloud artifacts docker images describe "${IMAGE}" --project "${GCP_PROJECT_ID}" --format='value(image_summary.digest)')" test "${SERVED_DIGEST}" = "${IMAGE_DIGEST}" [[ "${PRUNE_INCOMPATIBLE_REVISIONS}" =~ ^(true|false)$ ]] [[ "${EXPECTED_REHOME_GENERATION}" =~ ^(0|[1-9][0-9]*)$ ]] @@ -218,7 +227,8 @@ jobs: --max-instances "${DIRECTOR_MAX_INSTANCES}" \ --prune-revisions "${PRUNE_INCOMPATIBLE_REVISIONS}" \ --release-id "${RELEASE_ID}" \ - --regional-placement-secret-version "${target_version}" + --regional-placement-secret-version "${target_version}" \ + --region-correction-cohort-percent "${REGION_CORRECTION_COHORT_PERCENT}" echo "REGIONAL_PLACEMENT_ENABLED=${desired}" >> "${GITHUB_ENV}" echo "REGIONAL_PLACEMENT_VERSION=${target_version}" >> "${GITHUB_ENV}" diff --git a/.github/workflows/cloud-deploy-relay-production-same-cap-job.yml b/.github/workflows/cloud-deploy-relay-production-same-cap-job.yml index 8ef61507088..2b4bb3fa439 100644 --- a/.github/workflows/cloud-deploy-relay-production-same-cap-job.yml +++ b/.github/workflows/cloud-deploy-relay-production-same-cap-job.yml @@ -67,8 +67,8 @@ jobs: [[ "${TARGET_IMAGE_DIGEST}" =~ ^sha256:[a-f0-9]{64}$ ]] [[ "${ROLLBACK_IMAGE_DIGEST}" =~ ^sha256:[a-f0-9]{64}$ ]] test "${TARGET_IMAGE_DIGEST}" != "${ROLLBACK_IMAGE_DIGEST}" - [[ "${TARGET_REHOME_PROTOCOL}" =~ ^[01]$ ]] - [[ "${ROLLBACK_REHOME_PROTOCOL}" =~ ^[01]$ ]] + [[ "${TARGET_REHOME_PROTOCOL}" =~ ^(0|1|3)$ ]] + [[ "${ROLLBACK_REHOME_PROTOCOL}" =~ ^(0|1|3)$ ]] [[ "${EXPECTED_SELECTOR_GENERATION}" =~ ^(0|[1-9][0-9]*)$ ]] [[ "${EXPECTED_REHOME_GENERATION}" =~ ^(0|[1-9][0-9]*)$ ]] [[ "${WAVE_INDEX}" =~ ^[0-3]$ ]] @@ -599,7 +599,7 @@ jobs: | jq -e '.control.enabled == false' >/dev/null - name: Prove exact per-host trust and idempotent no-neighbor behavior - if: ${{ inputs.mode != 'verify' && ((inputs.mode == 'rollback' && inputs.rollback-rehome-protocol == '1') || (inputs.mode != 'rollback' && inputs.target-rehome-protocol == '1')) }} + if: ${{ inputs.mode != 'verify' && ((inputs.mode == 'rollback' && inputs.rollback-rehome-protocol != '0') || (inputs.mode != 'rollback' && inputs.target-rehome-protocol != '0')) }} env: ORCA_RELAY_ADMIN_ID_TOKEN: ${{ steps.post-auth.outputs.id_token }} run: | diff --git a/.github/workflows/cloud-deploy-relay-production-same-cap.yml b/.github/workflows/cloud-deploy-relay-production-same-cap.yml index fba5df0dcb9..31fe9bfb203 100644 --- a/.github/workflows/cloud-deploy-relay-production-same-cap.yml +++ b/.github/workflows/cloud-deploy-relay-production-same-cap.yml @@ -26,13 +26,13 @@ on: required: true default: '1' type: choice - options: ['0', '1'] + options: ['0', '1', '3'] rollback-rehome-protocol: description: Exact rollback regional-rehome protocol required: true default: '0' type: choice - options: ['0', '1'] + options: ['0', '1', '3'] expected-selector-generation: description: Exact selector generation before the first cell required: true @@ -62,7 +62,7 @@ on: required: false type: string canary-run-id: - description: Successful same-commit canary run required for batch-apply + description: Successful same-code canary in this rehome control generation; reusable across batches required: false type: string confirmation: diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 942f0f34a56..a07bf0991ec 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -173,6 +173,11 @@ jobs: - name: Run E2E tests (${{ matrix.shard_name }}) run: xvfb-run --auto-servernum bash .github/scripts/e2e-with-window-manager.sh env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 ORCA_E2E_WEB_CLIENT=1 ORCA_RELAY_PATH="$GITHUB_WORKSPACE/out/relay" pnpm run test:e2e --shard=${{ matrix.shard }} + # The frame benchmark needs a mapped window, which the headless shards exclude. + - name: Run worktree first-paint benchmark + if: matrix.shard == '1/14' + run: xvfb-run --auto-servernum bash .github/scripts/e2e-with-window-manager.sh env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/worktree-switch-first-paint.spec.ts --config tests/playwright.config.ts --project=electron-headful --workers=1 + # Why: Playwright retains traces/screenshots only on failure. Uploading # them as an artifact makes post-mortem debugging on CI possible without # re-running locally. diff --git a/.github/workflows/mobile-ios-release.yml b/.github/workflows/mobile-ios-release.yml index 934b3f694a3..dd9a265d0c8 100644 --- a/.github/workflows/mobile-ios-release.yml +++ b/.github/workflows/mobile-ios-release.yml @@ -94,6 +94,8 @@ jobs: run: node -e 'const fs = require("node:fs"); const { expo } = require("./app.json"); fs.appendFileSync(process.env.GITHUB_OUTPUT, `version=${expo.version}\nbuild_number=${expo.ios.buildNumber}\n`)' - name: Expo prebuild + env: + ORCA_IOS_APS_ENVIRONMENT: production run: npx expo prebuild --platform ios --no-install - name: Install CocoaPods diff --git a/.github/workflows/pi-owner-runtime.yml b/.github/workflows/pi-owner-runtime.yml new file mode 100644 index 00000000000..373afb7a539 --- /dev/null +++ b/.github/workflows/pi-owner-runtime.yml @@ -0,0 +1,29 @@ +name: Pi owner runtime verification +on: + pull_request: + paths: + - 'src/main/pi/agent-status-handler-source.ts' + - 'tests/tools/pi-owner-runtime-smoke.mjs' + - '.github/workflows/pi-owner-runtime.yml' + workflow_dispatch: +permissions: + contents: read +jobs: + runtime: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 20 + env: + ORCA_BACKGROUND_LAUNCH: '1' + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: ./.github/actions/install-node-dependencies + - name: Install pinned extension loader + run: npm install --prefix .cache/pi-owner --ignore-scripts --no-audit --no-fund @earendil-works/pi-coding-agent@0.83.0 + - name: Verify real owner exit and hook delivery + run: node tests/tools/pi-owner-runtime-smoke.mjs .cache/pi-owner/node_modules/@earendil-works/pi-coding-agent diff --git a/.github/workflows/pi-provider-runtime.yml b/.github/workflows/pi-provider-runtime.yml new file mode 100644 index 00000000000..837c38baf9a --- /dev/null +++ b/.github/workflows/pi-provider-runtime.yml @@ -0,0 +1,28 @@ +name: Pi extension provider verification +on: + pull_request: + paths: + - 'src/shared/commit-message-agent-specs-primary.ts' + - 'tests/tools/pi-provider-runtime-smoke.mjs' + - '.github/workflows/pi-provider-runtime.yml' +permissions: + contents: read +jobs: + runtime: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 20 + env: + ORCA_BACKGROUND_LAUNCH: '1' + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: ./.github/actions/install-node-dependencies + - name: Install pinned Pi runtime + run: npm install --prefix .cache/pi-provider --ignore-scripts --no-audit --no-fund @earendil-works/pi-coding-agent@0.84.2 + - name: Verify extension model generation before and after + run: node tests/tools/pi-provider-runtime-smoke.mjs .cache/pi-provider/node_modules/@earendil-works/pi-coding-agent/dist/cli.js diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 268b6ad66e3..c49091ab148 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -203,6 +203,9 @@ jobs: - name: Boot orcad and round-trip a terminal run: pnpm run smoke:orcad-terminal + - name: Verify the generated RPC params catalog + run: pnpm run verify:rpc-params-catalog + - name: Verify bundled skill guides run: pnpm run verify:bundled-skill-guides diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index cdb334c64cd..0c215db94d3 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -37,6 +37,13 @@ jobs: - name: Install Electron package binary for tests run: node config/scripts/install-electron-package-binary.mjs + # The real two-cell transport test imports cloud relay source and its contracts. + - name: Install relay integration dependencies + working-directory: cloud + run: | + npx --yes pnpm@10.24.0 --filter '@orca-cloud/relay...' install --frozen-lockfile --ignore-scripts + npx --yes pnpm@10.24.0 --filter '@orca-cloud/relay^...' build + - name: Test shard run: | pnpm exec vitest run --config config/vitest.config.ts \ diff --git a/.gitignore b/.gitignore index 913dfc4a045..cf2f7244eb3 100644 --- a/.gitignore +++ b/.gitignore @@ -103,7 +103,10 @@ docs/** !docs/agent-skill-sharing-implementation-checklist.md !docs/mobile-terminal-shortcut-bar.md !docs/reference/ +!docs/reference/agent-pty-transcript-capture.md +!docs/reference/agent-session-search-query-tuning.md !docs/reference/agent-status-store.md +!docs/reference/antigravity-readiness-evidence.md !docs/reference/git-compatibility.md !docs/reference/headless-linux-server.md !docs/reference/ime-regression-checklist.md diff --git a/.oxlintrc.json b/.oxlintrc.json index 03cc659f494..55758560478 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -180,6 +180,7 @@ } ], "ignorePatterns": [ + "src/shared/rpc-contract/rpc-params-catalog.generated.ts", "**/node_modules", "**/dist", "**/out", diff --git a/AGENTS.md b/AGENTS.md index 5ff66b95b0f..f1ce31e404b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -72,6 +72,10 @@ All changes must consider folder workspaces as well as git worktrees. Don't assu The execution host owns agent status in one store, the hook server's, and every reader (sidebar, `worktree ps`, mobile, dashboard) subscribes to it. Before adding a producer, a cache, or a reader-side precedence rule, read [`docs/reference/agent-status-store.md`](./docs/reference/agent-status-store.md): new producers write into that store, and readers keep only presentation policy. +## Agent Terminal Screens + +A rule that reads what an agent CLI paints on a terminal — readiness, blocked prompts, idle — must be written against a captured transcript, not a remembered screen. Record one with [`docs/reference/agent-pty-transcript-capture.md`](./docs/reference/agent-pty-transcript-capture.md), which keeps escapes and wrapping intact and scrubs account identifiers before they reach git. Antigravity readiness has no transcript yet and five failed attempts without one; before touching it, read [`docs/reference/antigravity-readiness-evidence.md`](./docs/reference/antigravity-readiness-evidence.md). + ## Remote Wire Compatibility Clients and remote Orca servers update independently, so mixed versions are the normal state. Before changing anything a paired client and host exchange — RPC params, stream frames, or the content either side publishes over them — follow [`docs/reference/remote-wire-compatibility.md`](./docs/reference/remote-wire-compatibility.md). A new optional field is safe; a new stream opcode must be capability-negotiated because decoders drop unknown opcodes silently; and changing what the host publishes reaches old clients even with no wire change. diff --git a/cloud/apps/push/src/fcm-client.test.ts b/cloud/apps/push/src/fcm-client.test.ts index 4a8d1fb41f7..8843e7aab95 100644 --- a/cloud/apps/push/src/fcm-client.test.ts +++ b/cloud/apps/push/src/fcm-client.test.ts @@ -1,6 +1,6 @@ import { createHash } from 'node:crypto' import { describe, expect, it } from 'vitest' -import { fcmCollapseKey, FcmClient, type FcmRequest, type FcmResponse } from './fcm-client.js' +import { FcmClient, type FcmRequest, type FcmResponse } from './fcm-client.js' import { buildPushDelivery } from './push-delivery-message.js' const NOW = 1_700_000_000_000 @@ -20,6 +20,7 @@ function delivery(agentState: 'needs-input' | null = 'needs-input') { agentState, title: 'Agent needs input', body: 'Waiting on your answer', + paneKey: 'tab-b:pane-1', worktreeId: 'wt-1' } }) @@ -59,27 +60,14 @@ describe('fcm client', () => { expect(JSON.parse(request.body)).toEqual({ message: { token: TOKEN, - notification: { title: 'Agent needs input', body: 'Waiting on your answer' }, - android: { - priority: 'HIGH', - ttl: '300s', - collapse_key: createHash('sha256') - .update( - createHash('sha256') - .update(JSON.stringify([HOST, 'note-1'])) - .digest('hex') - ) - .digest('hex') - .slice(0, 32), - notification: { - channel_id: 'orca-desktop', - tag: createHash('sha256') - .update(JSON.stringify([HOST, 'note-1'])) - .digest('hex') - } - }, + android: { priority: 'HIGH', ttl: '300s' }, data: { + title: 'Agent needs input', + message: 'Waiting on your answer', + tag: delivery().collapseId, + channelId: 'orca-desktop', hostFingerprint: HOST, + paneKey: 'tab-b:pane-1', worktreeId: 'wt-1', notificationId: 'note-1', notificationSeq: '7', @@ -96,7 +84,7 @@ describe('fcm client', () => { await fcm.send(delivery(null), { token: TOKEN }) const message = JSON.parse(fake.requests[0]!.body) as { message: { - android: { collapse_key: string; notification: { tag: string } } + android: Record data: Record } } @@ -108,9 +96,10 @@ describe('fcm client', () => { .update(JSON.stringify([HOST, 'note-1'])) .digest('hex') expect(message.message.data.coalescedCount).toBeUndefined() - expect(message.message.android.notification.tag).toBe(tag) - expect(message.message.android.collapse_key).toBe(fcmCollapseKey(tag)) - expect(message.message.android.collapse_key).toHaveLength(32) + expect(message.message.data.tag).toBe(tag) + expect(message.message.android).not.toHaveProperty('collapse_key') + expect(message.message).not.toHaveProperty('notification') + expect(message.message.data).not.toHaveProperty('body') }) it('marks an unregistered token dead from the status or the error detail', async () => { diff --git a/cloud/apps/push/src/fcm-client.ts b/cloud/apps/push/src/fcm-client.ts index c22bd3309cd..0b58aae80f5 100644 --- a/cloud/apps/push/src/fcm-client.ts +++ b/cloud/apps/push/src/fcm-client.ts @@ -1,5 +1,4 @@ import { providerRetryAfter } from './provider-retry-delay.js' -import { createHash } from 'node:crypto' import { PUSH_DEFAULTS } from '@orca-cloud/push-contract' import { orcaDataStrings, type PushDelivery } from './push-delivery-message.js' import type { PushProviderOutcome } from './push-provider-outcome.js' @@ -22,12 +21,6 @@ type FcmErrorBody = { error?: { status?: unknown; message?: unknown; details?: { errorCode?: unknown }[] } } -// FCM collapse_key is a short opaque string, so the collapse id is hashed -// rather than truncated: truncation would merge unrelated notifications. -export function fcmCollapseKey(collapseId: string): string { - return createHash('sha256').update(collapseId).digest('hex').slice(0, 32) -} - export function fcmMessageBody(input: { delivery: PushDelivery token: string @@ -39,24 +32,23 @@ export function fcmMessageBody(input: { return JSON.stringify({ message: { token: input.token, - ...(delivery.orca.kind === 'dismiss' - ? {} - : { notification: { title: delivery.title, body: delivery.body } }), android: { priority: 'HIGH', - ttl: `${Math.max(0, Math.ceil((delivery.expiresAt - now) / 1000))}s`, - collapse_key: fcmCollapseKey(delivery.collapseId), + ttl: `${Math.max(0, Math.ceil((delivery.expiresAt - now) / 1000))}s` + }, + // Notification payloads collapse offline; Expo renders these data messages natively. + data: { + ...orcaDataStrings(delivery.orca), ...(delivery.orca.kind === 'dismiss' ? {} : { - notification: { - channel_id: - delivery.sound === false ? `${input.channelId}-silent` : input.channelId, - tag: delivery.collapseId - } + title: delivery.title, + message: delivery.body, + tag: delivery.collapseId, + channelId: delivery.sound === false ? `${input.channelId}-silent` : input.channelId, + ...(delivery.sound === false ? { sound: '' } : {}) }) - }, - data: orcaDataStrings(delivery.orca) + } } }) } diff --git a/cloud/apps/push/src/push-delivery-message.ts b/cloud/apps/push/src/push-delivery-message.ts index bc2c1a5d9b2..3bd2dae6e7c 100644 --- a/cloud/apps/push/src/push-delivery-message.ts +++ b/cloud/apps/push/src/push-delivery-message.ts @@ -5,6 +5,7 @@ export type PushOrcaData = { kind?: 'alert' | 'dismiss' hostFingerprint: string worktreeId?: string + paneKey?: string notificationId?: string notificationSeq: number notificationEpoch: string @@ -51,6 +52,7 @@ export function buildPushDelivery(input: { orca: { ...(notification.kind ? { kind: notification.kind } : {}), hostFingerprint, + ...(notification.paneKey === undefined ? {} : { paneKey: notification.paneKey }), ...(notification.worktreeId === undefined ? {} : { worktreeId: notification.worktreeId }), ...(notification.notificationId === undefined ? {} diff --git a/cloud/apps/push/src/push-dismissal-provider.test.ts b/cloud/apps/push/src/push-dismissal-provider.test.ts index 15362105777..65572e8401c 100644 --- a/cloud/apps/push/src/push-dismissal-provider.test.ts +++ b/cloud/apps/push/src/push-dismissal-provider.test.ts @@ -23,5 +23,9 @@ it('dismissal provider payloads cannot display a new alert or play a sound', () const android = JSON.parse(fcmMessageBody({ delivery, token: 'test', channelId: 'test' })).message expect(android).not.toHaveProperty('notification') expect(android.android).not.toHaveProperty('notification') + expect(android.android).not.toHaveProperty('collapse_key') + expect(android.data).not.toHaveProperty('title') + expect(android.data).not.toHaveProperty('message') + expect(android.data).not.toHaveProperty('sound') expect(android.data.kind).toBe('dismiss') }) diff --git a/cloud/apps/push/src/push-notification-sound.test.ts b/cloud/apps/push/src/push-notification-sound.test.ts index 4dd1b85504f..ede4dcd3291 100644 --- a/cloud/apps/push/src/push-notification-sound.test.ts +++ b/cloud/apps/push/src/push-notification-sound.test.ts @@ -23,7 +23,11 @@ it('carries a silent preference through validation to APNs and Android payloads' expect(JSON.parse(apnsBody(delivery)).aps).not.toHaveProperty('sound') expect( JSON.parse(fcmMessageBody({ delivery, token: 'test-token', channelId: 'orca-desktop' })).message - .android.notification.channel_id + .data.channelId ).toBe('orca-desktop-silent') + expect( + JSON.parse(fcmMessageBody({ delivery, token: 'test-token', channelId: 'orca-desktop' })).message + .data.sound + ).toBe('') expect(JSON.parse(apnsBody({ ...delivery, sound: undefined })).aps.sound).toBe('default') }) diff --git a/cloud/apps/push/src/push-pane-routing.test.ts b/cloud/apps/push/src/push-pane-routing.test.ts new file mode 100644 index 00000000000..66ce0b3a38c --- /dev/null +++ b/cloud/apps/push/src/push-pane-routing.test.ts @@ -0,0 +1,27 @@ +import { expect, it } from 'vitest' +import { PushNotificationSchema } from '@orca-cloud/push-contract' +import { buildPushDelivery, orcaDataStrings } from './push-delivery-message.js' + +it('preserves pane identity for both APNs and FCM, and accepts older workspace-only messages', () => { + const base = { + notificationSeq: 1, + notificationEpoch: 'epoch', + source: 'agent-task-complete', + agentState: 'finished', + title: 'Done', + body: '', + worktreeId: 'folder:/work' + } + const paneKey = 'tab-b:11111111-1111-4111-8111-111111111111' + for (const extra of [{}, { paneKey }]) { + const notification = PushNotificationSchema.parse({ ...base, ...extra }) + const delivery = buildPushDelivery({ + notification, + hostFingerprint: 'host', + registrationId: 'phone', + expiresAt: Date.now() + 300000 + }) + expect(delivery.orca.paneKey).toBe('paneKey' in extra ? paneKey : undefined) + expect(orcaDataStrings(delivery.orca).paneKey).toBe('paneKey' in extra ? paneKey : undefined) + } +}) diff --git a/cloud/apps/push/src/push-server-send.test.ts b/cloud/apps/push/src/push-server-send.test.ts index 2a93020ed1f..4b14b77eaec 100644 --- a/cloud/apps/push/src/push-server-send.test.ts +++ b/cloud/apps/push/src/push-server-send.test.ts @@ -56,7 +56,7 @@ describe('push gateway send route', () => { await harness.flushDeliveries() expect(harness.fcmRequests).toHaveLength(1) expect(JSON.parse(harness.fcmRequests[0]!.body)).toMatchObject({ - message: { token: FCM_TOKEN, notification: { title: 'Agent needs input' } } + message: { token: FCM_TOKEN, data: { title: 'Agent needs input' } } }) const afterDeath = await harness.post( @@ -179,7 +179,7 @@ describe('push gateway send route', () => { const message = JSON.parse(harness.fcmRequests[0]!.body) as { message: { android: { notification: { tag: string } }; data: Record } } - expect(message.message.android.notification.tag).toMatch(/^[a-f0-9]{64}$/) + expect(message.message.data.tag).toMatch(/^[a-f0-9]{64}$/) expect(message.message.data.coalescedCount).toBeUndefined() }) diff --git a/cloud/apps/relay-ops/src/incident-monitor.test.ts b/cloud/apps/relay-ops/src/incident-monitor.test.ts index c1a073cde4a..be35b55f65b 100644 --- a/cloud/apps/relay-ops/src/incident-monitor.test.ts +++ b/cloud/apps/relay-ops/src/incident-monitor.test.ts @@ -273,6 +273,26 @@ describe('incident monitor evaluator', () => { ) }) + it('allows at most three unexpected director errors per five minutes without relaxing other gates', () => { + for (const errors of [1, 2, 3]) { + const sample = healthySample() + sample.sources['cloud-monitoring']!.signals['director.errors'] = signal(errors) + expect(evaluateIncidentSample(sample, startedAt).status).toBe('green') + } + const excess = healthySample() + excess.sources['cloud-monitoring']!.signals['director.errors'] = signal(4) + expect(evaluateIncidentSample(excess, startedAt).failures).toContainEqual( + expect.objectContaining({ signal: 'director.errors', observed: 4, threshold: 3 }) + ) + const auth = healthySample() + auth.sources['cloud-monitoring']!.signals['auth.errors'] = signal(1) + expect(evaluateIncidentSample(auth, startedAt).status).toBe('freeze') + const pressure = healthySample() + pressure.sources['cloud-monitoring']!.signals['director.errors'] = signal(1) + pressure.sources['cloud-monitoring']!.signals['cloud_sql.cpu'] = signal(0.81) + expect(evaluateIncidentSample(pressure, startedAt).status).toBe('freeze') + }) + it('freezes on SQL, director, relay pool, heartbeat, and migration breaches', () => { const sample = healthySample() sample.sources['cloud-monitoring']!.signals['cloud_sql.cpu'] = signal(0.81) diff --git a/cloud/apps/relay-ops/src/incident-monitor.ts b/cloud/apps/relay-ops/src/incident-monitor.ts index 0887bb2d1ee..a48e100a6d8 100644 --- a/cloud/apps/relay-ops/src/incident-monitor.ts +++ b/cloud/apps/relay-ops/src/incident-monitor.ts @@ -101,7 +101,8 @@ export const INCIDENT_MONITOR_THRESHOLDS = { directorCpuUtilization: 0.8, directorMemoryUtilization: 0.8, directorConcurrency: 64, - directorErrors: 0, + // Sparse connection timeouts must not block a healthy rollout; four/5min still freezes. + directorErrors: 3, authErrors: 0, // Why: 800 exceeded the 600 hard cap, so this could never trigger on a capped cell. 500 is // the ordinary admission limit a cell actually stops at (600 cap - 100 control-rebind reserve). diff --git a/cloud/apps/relay/src/admin-token-verifier.ts b/cloud/apps/relay/src/admin-token-verifier.ts index 4b8ad26e695..8b236d58473 100644 --- a/cloud/apps/relay/src/admin-token-verifier.ts +++ b/cloud/apps/relay/src/admin-token-verifier.ts @@ -6,6 +6,7 @@ export const RELAY_MONITOR_ADMIN_ROUTES = [ '/v1/admin/cell-status', '/v1/admin/evacuation-status', '/v1/admin/regional-rehome-control', + '/v1/admin/regional-rehome-preview', '/v1/admin/runtime-status' ] as const diff --git a/cloud/apps/relay/src/app.ts b/cloud/apps/relay/src/app.ts index c45e31c4a01..44f6a6fc293 100644 --- a/cloud/apps/relay/src/app.ts +++ b/cloud/apps/relay/src/app.ts @@ -1,5 +1,9 @@ import { AssignmentRequestSchema, + IdleRegionalRehomeRequestSchema, + type IdleRegionalRehomeRequest, + type IdleRegionalRehomeOutcome, + type RegionCorrectionResponse, isRelayCellConnectionHardCap, RELAY_ADMISSION_BUDGETS, RELAY_DEFAULT_REGION, @@ -39,7 +43,7 @@ import { type AssignmentAdmissionRejection } from './public-assignment-admission.js' import { relayHostLogDigest } from './relay-host-log-digest.js' -import type { RelayRuntimeCounts } from './relay-observability.js' +import type { RegionalRehomeSafetySnapshot, RelayRuntimeCounts } from './relay-observability.js' import { isRegionalRehomeTrustProbe, probeRegionalRehomeTrust @@ -68,21 +72,28 @@ export function createRelayApp( store: RelayCredentialStore assignments: RelayAssignmentStore drain: (graceMs: number) => void + idleRehome?: (input: IdleRegionalRehomeRequest & { + cohortPercent: number + directorSafety: RegionalRehomeSafetySnapshot + }) => Promise<{ outcome: IdleRegionalRehomeOutcome }> drainHost?: (input: { attemptId: string userId: string relayHostId: string sourceAssignmentEpoch: number + sourceCellIncarnation: string graceMs: number - }) => 'accepted' | 'already-accepted' | 'host-not-connected' + }) => + | 'accepted' + | 'already-accepted' + | 'host-not-connected' + | Promise<'accepted' | 'already-accepted' | 'host-not-connected'> regionalRehomeIdentityToken?: (audience: string) => Promise regionalRehomeFetch?: typeof fetch - regionalRehomeTrustProbeHostExists?: (input: { - userId: string - relayHostId: string - }) => boolean + regionalRehomeTrustProbeHostExists?: (input: { userId: string; relayHostId: string }) => boolean cellIncarnation?: string isDraining?: () => boolean + regionalRehomeSafetySnapshot?: () => RegionalRehomeSafetySnapshot runtimeCounts?: () => RelayRuntimeCounts ready: () => Promise recordAssignmentAdmission?: ( @@ -226,7 +237,8 @@ export function createRelayApp( return context.json({ error: 'host_identity_mismatch' }, 403) } const identity = { userId: claims.sub, relayHostId: claims.relayHostId } - const requestedRegion = body.data.preferredRegion + const requestedRegion = + body.data.regionCorrection?.action === 'report' ? undefined : body.data.preferredRegion const targetRegion = config.regionalPlacementEnabled !== false && requestedRegion ? requestedRegion @@ -295,10 +307,30 @@ export function createRelayApp( } } let assignment: RelayAssignment + let regionCorrection: RegionCorrectionResponse | undefined try { - assignment = requestedRegion - ? await operations.assignments.assign(identity, requestedRegion, targetRegion) - : await operations.assignments.assign(identity) + if (body.data.regionCorrection?.action === 'report') { + const current = await operations.assignments.resolve(identity) + if (!current) return context.json({ error: 'assignment_not_found' }, 409) + assignment = current + } else { + assignment = requestedRegion + ? await operations.assignments.assign(identity, requestedRegion, targetRegion) + : await operations.assignments.assign(identity) + } + if (body.data.regionCorrection) { + try { + regionCorrection = await operations.assignments.exchangeRegionCorrection( + identity, + body.data.regionCorrection, + assignment.assignmentEpoch + ) + } catch (error) { + if (body.data.regionCorrection.action === 'report') throw error + // Optional measurement setup must not discard an otherwise valid placement. + console.warn(JSON.stringify({ event: 'orca_relay_region_window_unavailable' })) + } + } } catch (error) { if (isRelayAssignmentCapacityError(error) || isRelayDatabaseTransientError(error)) { logAssignmentRejection({ @@ -353,13 +385,16 @@ export function createRelayApp( v: 1, cellUrl: assignment.cellUrl, assignmentEpoch: assignment.assignmentEpoch, - lease + lease, + ...(regionCorrection ? { regionCorrection } : {}) }) }) app.post('/v1/resolve', async (context) => { if (config.role === 'cell') return context.json({ error: 'director_only' }, 404) if (!config.publicAssignmentsEnabled) return rejectPublicAssignment(context) - if (Number(context.req.header('content-length') ?? 0) > RELAY_PROTOCOL_LIMITS.maxHttpBodyBytes) { + if ( + Number(context.req.header('content-length') ?? 0) > RELAY_PROTOCOL_LIMITS.maxHttpBodyBytes + ) { return context.json({ error: 'request_too_large' }, 413) } const body = ResolveRequestSchema.safeParse(await context.req.json().catch(() => null)) @@ -433,6 +468,34 @@ export function createRelayApp( operations.drain(body.data.graceMs) return context.json({ ok: true }) }) + app.post('/v1/admin/host-idle-rehome', async (context) => { + if (config.role !== 'cell' || !operations.idleRehome) { + return context.json({ error: 'cell_only' }, 404) + } + const bearer = readBearer(context.req.header('authorization')) + if (!bearer || !(await verifyRegionalRehomeToken(bearer))) { + return context.json({ error: 'invalid_token' }, 401) + } + if (requestTooLarge(context.req.header('content-length'))) { + return context.json({ error: 'request_too_large' }, 413) + } + const body = IdleRegionalRehomeCommandSchema.safeParse( + await context.req.json().catch(() => null) + ) + if (!body.success) return context.json({ error: 'invalid_request' }, 400) + if ( + body.data.sourceCellId !== config.cellId || + !operations.cellIncarnation || + body.data.sourceCellIncarnation !== operations.cellIncarnation + ) { + return context.json({ error: 'regional_rehome_source_generation_mismatch' }, 409) + } + try { + return context.json({ v: 1, ...(await operations.idleRehome(body.data)) }) + } catch (error) { + return context.json({ error: operationError(error) }, 409) + } + }) app.post('/v1/admin/host-drain', async (context) => { if (config.role !== 'cell' || !operations.drainHost) { return context.json({ error: 'cell_only' }, 404) @@ -474,7 +537,7 @@ export function createRelayApp( } sharedRuntimeIdentityRejected = true } - const outcome = operations.drainHost(body.data) + const outcome = await operations.drainHost(body.data) return context.json({ v: 1, outcome, @@ -502,8 +565,7 @@ export function createRelayApp( region: config.region ?? RELAY_DEFAULT_REGION, imageDigest: config.imageDigest ?? null, draining: operations.isDraining?.() ?? false, - regionalRehomeProtocol: - config.rehomeAudience && config.rehomeDirectorServiceAccount ? 1 : 0, + regionalRehomeProtocol: config.rehomeAudience && config.rehomeDirectorServiceAccount ? 3 : 0, connectionCapacity: config.connectionHardCap === undefined ? null @@ -559,6 +621,18 @@ export function createRelayApp( return context.json({ error: operationError(error) }, 409) } }) + app.get('/v1/admin/regional-rehome-preview', async (context) => { + if (config.role !== 'director') return context.json({ error: 'director_only' }, 404) + const bearer = readBearer(context.req.header('authorization')) + if (!bearer || !(await verifyAdminToken(bearer, context.req.path))) { + return context.json({ error: 'invalid_token' }, 401) + } + const preview = await operations.assignments.previewRegionalRehomeEligibility( + operations.regionalRehomeSafetySnapshot?.() + ) + const outcomes = await operations.assignments.regionCorrectionOutcomes() + return context.json({ v: 1, preview, outcomes }) + }) app.post('/v1/admin/regional-rehome-control', async (context) => { if (config.role !== 'director') return context.json({ error: 'director_only' }, 404) const bearer = readBearer(context.req.header('authorization')) @@ -1295,6 +1369,11 @@ const RegionalRehomeSafetySchema = z }) .strict() +const IdleRegionalRehomeCommandSchema = IdleRegionalRehomeRequestSchema.extend({ + cohortPercent: z.number().int().min(0).max(100), + directorSafety: RegionalRehomeSafetySchema +}) + const CellHeartbeatSchema = z .object({ v: z.literal(1), @@ -1394,45 +1473,48 @@ const CellRegionalRehomeStatusSchema = z v: z.literal(1), cellId: z.string().min(1).max(128), cellIncarnation: z.string().uuid(), - regionalRehomeProtocol: z.number().int().min(0).max(1), + regionalRehomeProtocol: z.number().int().min(0).max(3), safety: RegionalRehomeSafetySchema }) .strict() -const RegionalRehomeControlSchema = z.discriminatedUnion('action', [ - z.object({ v: z.literal(1), action: z.literal('inspect') }).strict(), - z.object({ - v: z.literal(1), - action: z.literal('apply'), - expectedGeneration: z.number().int().nonnegative(), - enabled: z.boolean(), - notBefore: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER), - ratePerMinute: z.number().int().min(1).max(120), - preferenceMaxAgeMs: z - .number() - .int() - .min(60_000) - .max(30 * 24 * 60 * 60_000), - hostCooldownMs: z - .number() - .int() - .min(60_000) - .max(30 * 24 * 60 * 60_000), - drainGraceMs: z.number().int().min(60_000).max(60 * 60_000), - confirmation: z.enum([ - 'ENABLE_REGIONAL_REHOMING', - 'DISABLE_REGIONAL_REHOMING' - ]) - }).strict() -]).superRefine((value, context) => { - if (value.action !== 'apply') return - const expected = value.enabled - ? 'ENABLE_REGIONAL_REHOMING' - : 'DISABLE_REGIONAL_REHOMING' - if (value.confirmation !== expected) { - context.addIssue({ code: 'custom', message: 'confirmation does not match state' }) - } -}) +const RegionalRehomeControlSchema = z + .discriminatedUnion('action', [ + z.object({ v: z.literal(1), action: z.literal('inspect') }).strict(), + z + .object({ + v: z.literal(1), + action: z.literal('apply'), + expectedGeneration: z.number().int().nonnegative(), + enabled: z.boolean(), + notBefore: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER), + ratePerMinute: z.number().int().min(1).max(120), + preferenceMaxAgeMs: z + .number() + .int() + .min(60_000) + .max(30 * 24 * 60 * 60_000), + hostCooldownMs: z + .number() + .int() + .min(60_000) + .max(30 * 24 * 60 * 60_000), + drainGraceMs: z + .number() + .int() + .min(60_000) + .max(60 * 60_000), + confirmation: z.enum(['ENABLE_REGIONAL_REHOMING', 'DISABLE_REGIONAL_REHOMING']) + }) + .strict() + ]) + .superRefine((value, context) => { + if (value.action !== 'apply') return + const expected = value.enabled ? 'ENABLE_REGIONAL_REHOMING' : 'DISABLE_REGIONAL_REHOMING' + if (value.confirmation !== expected) { + context.addIssue({ code: 'custom', message: 'confirmation does not match state' }) + } + }) const RegionalRehomeTrustProbeSchema = z .object({ @@ -1776,7 +1858,11 @@ const RegionalHostDrainSchema = z sourceCellId: z.string().min(1).max(128), sourceCellIncarnation: z.string().uuid(), sourceAssignmentEpoch: z.number().int().positive(), - graceMs: z.number().int().nonnegative().max(60 * 60 * 1000) + graceMs: z + .number() + .int() + .nonnegative() + .max(60 * 60 * 1000) }) .strict() diff --git a/cloud/apps/relay/src/assignment-store.ts b/cloud/apps/relay/src/assignment-store.ts index 824cb1e0b2f..7b877e3af7d 100644 --- a/cloud/apps/relay/src/assignment-store.ts +++ b/cloud/apps/relay/src/assignment-store.ts @@ -1,3 +1,14 @@ +import { IDLE_REHOME_PAGE_SIZE, selectIdleRegionalRehomes } from './idle-regional-rehome-selection.js' +import { readRegionCorrectionOutcomes } from './region-correction-outcomes.js' +import { + previewRegionalRehomeEligibility, + type RegionCorrectionPreview +} from './region-correction-preview.js' +import { + exchangeRegionCorrection, + previewRegionCorrection, + REGIONAL_REHOME_CONCURRENT_LIMIT +} from './region-correction-state.js' import { randomUUID } from 'node:crypto' import { performance } from 'node:perf_hooks' import { @@ -7,7 +18,10 @@ import { RELAY_DEFAULT_REGION, RELAY_REGIONS, RELAY_PROTOCOL_LIMITS, - type RelayRegion + type RelayRegion, + type RegionCorrectionRequest, + type RegionCorrectionResponse, + type IdleRegionalRehomeRequest, } from '@orca-cloud/relay-contract' import { cellAdmissionState, @@ -80,6 +94,7 @@ type CellRegionalRehomeStatus = { } type RelayAssignmentStoreOptions = { + regionalRehomeCohortPercent?: number requireLiveCells?: boolean heartbeatTtlMs?: number recordControlRenewal?: (durationMs: number, outcome: ControlRenewalOutcome) => void @@ -136,10 +151,7 @@ export type RegionalRehomeAttempt = AssignmentIdentity & { sendAttempts: number } -export type RegionalHostDrainOutcome = - | 'accepted' - | 'already-accepted' - | 'host-not-connected' +export type RegionalHostDrainOutcome = 'accepted' | 'already-accepted' | 'host-not-connected' export type RegionalRehomeFleetSafety = RegionalRehomeSafetySnapshot & { requiredCells: number @@ -415,6 +427,7 @@ const ABORTABLE_EXPIRED_MIGRATION = `( )` export class RelayAssignmentStore { + private readonly regionalRehomeCohortPercent: number private readonly requireLiveCells: boolean private readonly heartbeatTtlMs: number // Poisoned attempts never complete or abort and stay the oldest rows, so @@ -430,13 +443,19 @@ export class RelayAssignmentStore { private readonly migrationCellRegistrar: RelayMigrationCellRegistrar private readonly activityQueue = new AssignmentIdentityQueue() private assignmentTail: Promise = Promise.resolve() - private pendingRegionalRehomeDisableLog: Record | null = null constructor( private readonly database: RelayDatabase, private readonly now: () => number = Date.now, options: RelayAssignmentStoreOptions = {} ) { + this.regionalRehomeCohortPercent = options.regionalRehomeCohortPercent ?? 0 + if ( + !Number.isInteger(this.regionalRehomeCohortPercent) || + this.regionalRehomeCohortPercent < 0 || + this.regionalRehomeCohortPercent > 100 + ) + throw new Error('invalid_regional_rehome_cohort') this.requireLiveCells = options.requireLiveCells ?? false this.heartbeatTtlMs = options.heartbeatTtlMs ?? 45_000 this.recordControlRenewal = options.recordControlRenewal @@ -3309,6 +3328,167 @@ export class RelayAssignmentStore { }) } + async exchangeRegionCorrection( + identity: AssignmentIdentity, + request: RegionCorrectionRequest, + assignmentEpoch: number + ): Promise { + return exchangeRegionCorrection(this.database, identity, request, assignmentEpoch, this.now()) + } + + async regionCorrectionOutcomes() { + return readRegionCorrectionOutcomes(this.database, this.now()) + } + + async previewRegionCorrection(): Promise> { + return previewRegionCorrection(this.database, this.now()) + } + + private idleRegionalCandidateOffset = 0 + + async selectIdleRegionalRehomeCandidates( + processSafety?: RegionalRehomeSafetySnapshot + ): Promise> { + const now = this.now() + if (!processSafety || this.regionalRehomeCohortPercent === 0) return [] + const control = (await this.database.query( + "SELECT enabled, not_before FROM relay_region_rehome_control WHERE control_id = 'global'" + ))[0] + if (!control || Number(control.enabled) !== 1 || Number(control.not_before) > now) return [] + const fleetSafety = await this.readRegionalRehomeFleetSafety(this.database, now) + if (regionalRehomeFleetSafetyFailure(processSafety, fleetSafety, now)) return [] + const candidates = await selectIdleRegionalRehomes({ + database: this.database, now, heartbeatTtlMs: this.heartbeatTtlMs, + cohortPercent: this.regionalRehomeCohortPercent, offset: this.idleRegionalCandidateOffset, + connectionHeadroom: await this.connectionHeadroomByCell(this.database), + cellIsClean: regionalRehomeCellSafetyIsClean + }) + this.idleRegionalCandidateOffset = candidates.length < IDLE_REHOME_PAGE_SIZE + ? 0 : this.idleRegionalCandidateOffset + candidates.length + return candidates + } + + async commitIdleRegionalRehome( + request: IdleRegionalRehomeRequest, + processSafety?: RegionalRehomeSafetySnapshot, + cohortPercent = this.regionalRehomeCohortPercent + ): Promise<{ outcome: 'committed' | 'deferred' | 'stale' }> { + const prior = await this.reconcileIdleRegionalRehome(request) + if (prior !== 'not-committed') return { outcome: prior } + if (!processSafety || !Number.isInteger(cohortPercent) || cohortPercent <= 0 || cohortPercent > 100) { + return { outcome: 'deferred' } + } + let safetyDisable: Record | null = null + const result = await this.database.transaction(async (transaction): Promise<{ outcome: 'committed' | 'deferred' | 'stale' }> => { + safetyDisable = null + const now = this.now() + const control = (await transaction.queryLocked( + `SELECT * FROM relay_region_rehome_control WHERE control_id = 'global'` + ))[0] + if (!control || Number(control.enabled) !== 1 || Number(control.not_before) > now) { + return { outcome: 'deferred' } + } + await transaction.query( + `INSERT INTO relay_region_rehome_worker_state + (worker_id, next_dispatch_at, paused_until, consecutive_failures, updated_at) + VALUES ('global', 0, 0, 0, ?) ON CONFLICT (worker_id) DO NOTHING`, [now] + ) + const worker = (await transaction.queryLocked( + `SELECT * FROM relay_region_rehome_worker_state WHERE worker_id = 'global'` + ))[0]! + if (Number(worker.paused_until) > now || Number(worker.next_dispatch_at) > now) { + return { outcome: 'deferred' } + } + const open = (await transaction.query( + `SELECT COUNT(*) AS count FROM relay_assignment_migrations + WHERE completed_at IS NULL AND aborted_at IS NULL` + ))[0] + if (Number(open?.count ?? 0) >= REGIONAL_REHOME_CONCURRENT_LIMIT) return { outcome: 'deferred' } + const attempt = await this.startRegionalRehomeCandidate(transaction, { + identity: request, + sourceCellId: request.sourceCellId, + assignmentEpoch: request.sourceAssignmentEpoch, + preferenceCutoff: now - Number(control.preference_max_age_ms), + cooldownCutoff: now - Number(control.host_cooldown_ms), + drainGraceMs: 0, + processSafety, + worker, + now, + skips: [], + idleRequest: request, + cohortPercent, + onSafetyDisabled: (event) => { safetyDisable = event } + }) + if (!attempt) return { outcome: 'deferred' } + await this.markRegionalRehomeDispatchClaimed( + transaction, request.attemptId, now, Math.ceil(60_000 / Number(control.rate_per_minute)) + ) + await transaction.query( + `UPDATE relay_region_rehome_attempts SET drain_receipt_at = ?, drain_outcome = 'accepted' + WHERE attempt_id = ?`, [now, request.attemptId] + ) + return { outcome: 'committed' } + }) + if (safetyDisable) console.warn(JSON.stringify(safetyDisable)) + return result + } + + async reconcileIdleRegionalRehome(request: IdleRegionalRehomeRequest): Promise<'committed' | 'not-committed' | 'stale'> { + return this.database.transaction(async (transaction) => { + // Absence is definitive only after the same assignment lock as commit/activation. + const assignment = await this.assignmentRow(transaction, request) + const attempt = (await transaction.queryLocked( + `SELECT * FROM relay_region_rehome_attempts WHERE attempt_id = ?`, + [request.attemptId] + ))[0] + if (attempt) { + return attempt.user_id === request.userId && + attempt.relay_host_id === request.relayHostId && + attempt.source_cell_id === request.sourceCellId && + attempt.source_cell_incarnation === request.sourceCellIncarnation && + Number(attempt.previous_epoch) === request.sourceAssignmentEpoch && + Number(attempt.source_generation) === request.sourceGeneration && + attempt.target_cell_id === request.targetCellId && + attempt.aborted_at == null + ? 'committed' : 'stale' + } + if (!assignment || assignment.cell_id !== request.sourceCellId || + Number(assignment.assignment_epoch) !== request.sourceAssignmentEpoch) return 'stale' + const control = (await transaction.query( + `SELECT capability.generation, capability.cell_incarnation + FROM relay_control_capabilities capability + JOIN relay_assignment_activity_leases lease + ON lease.user_id = capability.user_id AND lease.relay_host_id = capability.relay_host_id + AND lease.activity_id = capability.activity_id + WHERE capability.user_id = ? AND capability.relay_host_id = ? + AND capability.cell_id = ? AND capability.assignment_epoch = ? + AND lease.activity_kind = 'control' AND lease.expires_at > ? + ORDER BY capability.generation DESC LIMIT 1`, + [request.userId, request.relayHostId, request.sourceCellId, request.sourceAssignmentEpoch, this.now()] + ))[0] + return control && Number(control.generation) === request.sourceGeneration && + control.cell_incarnation === request.sourceCellIncarnation ? 'not-committed' : 'stale' + }) + } + + async previewRegionalRehomeEligibility( + processSafety?: RegionalRehomeSafetySnapshot + ): Promise { + const now = this.now() + const fleetSafety = await this.readRegionalRehomeFleetSafety(this.database, now) + return previewRegionalRehomeEligibility({ + database: this.database, + now, + heartbeatTtlMs: this.heartbeatTtlMs, + cohortPercent: this.regionalRehomeCohortPercent, + globalSafetyFailure: processSafety + ? regionalRehomeFleetSafetyFailure(processSafety, fleetSafety, now) + : 'process-safety-unavailable', + connectionHeadroom: await this.connectionHeadroomByCell(this.database), + cellIsClean: regionalRehomeCellSafetyIsClean + }) + } + async renewControlActivity( identity: AssignmentIdentity, input: { activityId: string; cellId: string; expiresAt: number } @@ -3545,6 +3725,8 @@ export class RelayAssignmentStore { cellId: string assignmentEpoch: number generation: number + idleRegionalRehome?: boolean + cellIncarnation?: string connectionInclusionWatermark?: number } ): Promise { @@ -3626,6 +3808,33 @@ export class RelayAssignmentStore { input.connectionInclusionWatermark, now ) + await transaction.query( + `DELETE FROM relay_control_capabilities WHERE user_id = ? AND relay_host_id = ? + AND NOT EXISTS (SELECT 1 FROM relay_assignment_activity_leases lease + WHERE lease.user_id = relay_control_capabilities.user_id + AND lease.relay_host_id = relay_control_capabilities.relay_host_id + AND lease.activity_id = relay_control_capabilities.activity_id)`, + [identity.userId, identity.relayHostId] + ) + await transaction.query( + `INSERT INTO relay_control_capabilities + (user_id, relay_host_id, activity_id, cell_id, cell_incarnation, assignment_epoch, generation, finish_existing, idle_regional_rehome) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT (user_id, relay_host_id, activity_id) DO UPDATE SET + cell_incarnation = excluded.cell_incarnation, assignment_epoch = excluded.assignment_epoch, + generation = excluded.generation, finish_existing = excluded.finish_existing, idle_regional_rehome = excluded.idle_regional_rehome`, + [ + identity.userId, + identity.relayHostId, + activityId, + input.cellId, + input.cellIncarnation ?? '', + input.assignmentEpoch, + input.generation, + 0, + input.idleRegionalRehome && input.cellIncarnation ? 1 : 0 + ] + ) return activityId }) }) @@ -5116,327 +5325,6 @@ export class RelayAssignmentStore { } } - async claimRegionalRehome( - processSafety?: RegionalRehomeSafetySnapshot - ): Promise { - const now = this.now() - // Directors poll every second; avoid taking the global worker-row lock while disabled. - const control = ( - await this.database.query( - `SELECT enabled, not_before - FROM relay_region_rehome_control - WHERE control_id = 'global'` - ) - )[0] - if (!control) { - await this.initializeRegionalRehomeControl(this.database, now) - return null - } - if (integer(control, 'enabled') !== 1 || integer(control, 'not_before') > now) { - return null - } - this.pendingRegionalRehomeDisableLog = null - const candidateSkips: RegionalRehomeCandidateSkip[] = [] - // A Postgres transaction is unusable after a NOWAIT abort, so a contended - // tick abandons the candidate it stopped on plus every one behind it. - let candidatesTotal = 0 - let candidatesFinished = 0 - const claimResult = await this.database.transaction(async (transaction) => { - candidatesTotal = 0 - candidatesFinished = 0 - candidateSkips.length = 0 - await this.initializeRegionalRehomeControl(transaction, now) - const control = ( - await transaction.queryLocked( - `SELECT * FROM relay_region_rehome_control WHERE control_id = 'global'` - ) - )[0]! - if (integer(control, 'enabled') !== 1 || integer(control, 'not_before') > now) { - return null - } - const intervalMs = Math.ceil(60_000 / integer(control, 'rate_per_minute')) - const preferenceCutoff = now - integer(control, 'preference_max_age_ms') - // A host that was rehomed recently is left alone whichever way its - // preference now points: a flapping region probe must not walk one host - // back and forth across an ocean. - const cooldownCutoff = now - integer(control, 'host_cooldown_ms') - await transaction.query( - `INSERT INTO relay_region_rehome_worker_state - (worker_id, next_dispatch_at, paused_until, consecutive_failures, updated_at) - VALUES ('global', 0, 0, 0, ?) - ON CONFLICT (worker_id) DO NOTHING`, - [now] - ) - const worker = ( - await transaction.queryLocked( - `SELECT * FROM relay_region_rehome_worker_state WHERE worker_id = 'global'` - ) - )[0]! - if ( - integer(worker, 'paused_until') > now || - integer(worker, 'next_dispatch_at') > now - ) { - return null - } - const effectiveProcessSafety = processSafety ?? cleanRegionalRehomeSafety(now) - const fleetSafety = await this.readRegionalRehomeFleetSafety(transaction, now) - if ( - !(await this.regionalRehomeSafetyAllowsClaim( - transaction, - worker, - effectiveProcessSafety, - fleetSafety, - now - )) - ) { - return null - } - const retry = ( - await transaction.queryLocked( - `SELECT attempt.*, source.cell_url AS source_cell_url - FROM relay_region_rehome_attempts attempt - JOIN relay_cells source ON source.cell_id = attempt.source_cell_id - JOIN relay_cell_runtime runtime ON runtime.cell_id = attempt.source_cell_id - JOIN relay_cell_capabilities capability - ON capability.cell_id = runtime.cell_id - AND capability.cell_incarnation = runtime.cell_incarnation - JOIN relay_assignment_migrations migration - ON migration.user_id = attempt.user_id - AND migration.relay_host_id = attempt.relay_host_id - AND migration.assignment_epoch = attempt.assignment_epoch - WHERE attempt.drain_receipt_at IS NULL - AND attempt.completed_at IS NULL AND attempt.aborted_at IS NULL - AND attempt.send_attempts < 10 - AND (attempt.last_send_attempt_at IS NULL OR attempt.last_send_attempt_at <= ?) - AND runtime.cell_incarnation = attempt.source_cell_incarnation - AND runtime.ready = 1 AND runtime.last_heartbeat_at > ? - AND capability.regional_rehome_protocol >= 1 - AND migration.completed_at IS NULL AND migration.aborted_at IS NULL - ORDER BY attempt.created_at, attempt.attempt_id - LIMIT 1`, - [now - 30_000, now - this.heartbeatTtlMs] - ) - )[0] - if (retry) { - candidatesTotal = 1 - const fleetSafety = await this.lockedRegionalRehomeFleetSafety(transaction, now) - if ( - !(await this.regionalRehomeSafetyAllowsClaim( - transaction, - worker, - effectiveProcessSafety, - fleetSafety, - now - )) - ) { - return null - } - await this.markRegionalRehomeDispatchClaimed( - transaction, - text(retry, 'attempt_id'), - now, - intervalMs - ) - retry.send_attempts = integer(retry, 'send_attempts') + 1 - return regionalRehomeAttempt(retry) - } - - // A drain receipt is not convergence: grace enforcement lives only in - // source-cell session state, and attempts have been observed stalled - // dual-homed well past grace with source leases still renewing. Such - // attempts are re-dispatched with the remaining (zero) grace so the - // source force-closes and the host re-resolves onto its registered - // target. - const redrain = ( - await transaction.queryLocked( - `SELECT attempt.*, source.cell_url AS source_cell_url - FROM relay_region_rehome_attempts attempt - JOIN relay_cells source ON source.cell_id = attempt.source_cell_id - JOIN relay_cell_runtime runtime ON runtime.cell_id = attempt.source_cell_id - JOIN relay_cell_capabilities capability - ON capability.cell_id = runtime.cell_id - AND capability.cell_incarnation = runtime.cell_incarnation - JOIN relay_assignment_migrations migration - ON migration.user_id = attempt.user_id - AND migration.relay_host_id = attempt.relay_host_id - AND migration.assignment_epoch = attempt.assignment_epoch - WHERE attempt.drain_receipt_at IS NOT NULL - AND attempt.completed_at IS NULL AND attempt.aborted_at IS NULL - AND attempt.created_at + attempt.drain_grace_ms <= ? - AND attempt.send_attempts < ? - AND (attempt.last_send_attempt_at IS NULL OR attempt.last_send_attempt_at <= ?) - AND runtime.cell_incarnation = attempt.source_cell_incarnation - AND runtime.ready = 1 AND runtime.last_heartbeat_at > ? - AND capability.regional_rehome_protocol >= 1 - AND migration.completed_at IS NULL AND migration.aborted_at IS NULL - AND migration.target_registered_at IS NOT NULL - AND EXISTS ( - SELECT 1 FROM relay_assignment_activity_leases source_lease - WHERE source_lease.user_id = attempt.user_id - AND source_lease.relay_host_id = attempt.relay_host_id - AND source_lease.cell_id = attempt.source_cell_id - ) - ORDER BY attempt.created_at, attempt.attempt_id - LIMIT 1`, - [ - now, - REGIONAL_REHOME_REDRAIN_SEND_LIMIT, - now - REGIONAL_REHOME_REDRAIN_INTERVAL_MS, - now - this.heartbeatTtlMs - ] - ) - )[0] - if (redrain) { - candidatesTotal = 1 - const fleetSafety = await this.lockedRegionalRehomeFleetSafety(transaction, now) - if ( - !(await this.regionalRehomeSafetyAllowsClaim( - transaction, - worker, - effectiveProcessSafety, - fleetSafety, - now - )) - ) { - return null - } - await this.markRegionalRehomeDispatchClaimed( - transaction, - text(redrain, 'attempt_id'), - now, - intervalMs - ) - redrain.send_attempts = integer(redrain, 'send_attempts') + 1 - redrain.drain_grace_ms = 0 - return regionalRehomeAttempt(redrain) - } - - const candidates = await transaction.query( - `SELECT preference.user_id, preference.relay_host_id, - preference.observed_at, assignment.cell_id AS source_cell_id, - assignment.assignment_epoch - FROM relay_assignment_region_preferences preference - JOIN relay_assignments assignment - ON assignment.user_id = preference.user_id - AND assignment.relay_host_id = preference.relay_host_id - JOIN relay_cell_regions region ON region.cell_id = assignment.cell_id - JOIN relay_cell_admission admission ON admission.cell_id = assignment.cell_id - JOIN relay_cell_runtime runtime ON runtime.cell_id = assignment.cell_id - JOIN relay_cell_capabilities capability - ON capability.cell_id = runtime.cell_id - AND capability.cell_incarnation = runtime.cell_incarnation - WHERE preference.preferred_region <> region.region - AND preference.observed_at >= ? - AND admission.admission_state = 'general' - AND runtime.ready = 1 AND runtime.last_heartbeat_at > ? - AND capability.regional_rehome_protocol >= 1 - AND EXISTS ( - SELECT 1 FROM relay_assignment_activity_leases control - WHERE control.user_id = assignment.user_id - AND control.relay_host_id = assignment.relay_host_id - AND control.cell_id = assignment.cell_id - AND control.activity_kind = 'control' - AND control.activity_id NOT LIKE 'control-pending:%' - AND control.expires_at > ? - AND control.updated_at >= runtime.started_at - ) - AND NOT EXISTS ( - SELECT 1 FROM relay_assignment_migrations migration - WHERE migration.user_id = assignment.user_id - AND migration.relay_host_id = assignment.relay_host_id - AND migration.completed_at IS NULL AND migration.aborted_at IS NULL - ) - AND NOT EXISTS ( - SELECT 1 FROM relay_region_rehome_attempts recent - WHERE recent.user_id = preference.user_id - AND recent.relay_host_id = preference.relay_host_id - AND recent.created_at > ? - ) - AND EXISTS ( - SELECT 1 FROM relay_cell_regions target_region - JOIN relay_cells target_cell ON target_cell.cell_id = target_region.cell_id - JOIN relay_cell_admission target_admission - ON target_admission.cell_id = target_region.cell_id - JOIN relay_cell_runtime target_runtime - ON target_runtime.cell_id = target_region.cell_id - JOIN relay_cell_capabilities target_capability - ON target_capability.cell_id = target_runtime.cell_id - AND target_capability.cell_incarnation = target_runtime.cell_incarnation - WHERE target_region.region = preference.preferred_region - AND target_cell.enabled = 1 - AND target_admission.admission_state = 'general' - AND target_runtime.ready = 1 - AND target_runtime.last_heartbeat_at > ? - AND target_capability.regional_rehome_protocol >= 1 - ) - ORDER BY preference.observed_at, preference.user_id, preference.relay_host_id - LIMIT 10`, - [ - preferenceCutoff, - now - this.heartbeatTtlMs, - now, - cooldownCutoff, - now - this.heartbeatTtlMs - ] - ) - candidatesTotal = candidates.length - for (const candidate of candidates) { - const claimed = await this.startRegionalRehomeCandidate(transaction, { - identity: { - userId: text(candidate, 'user_id'), - relayHostId: text(candidate, 'relay_host_id') - }, - sourceCellId: text(candidate, 'source_cell_id'), - assignmentEpoch: integer(candidate, 'assignment_epoch'), - preferenceCutoff, - cooldownCutoff, - drainGraceMs: integer(control, 'drain_grace_ms'), - processSafety: effectiveProcessSafety, - worker, - now, - skips: candidateSkips - }) - candidatesFinished++ - if (!claimed) continue - await this.markRegionalRehomeDispatchClaimed( - transaction, - claimed.attemptId, - now, - intervalMs - ) - return { ...claimed, sendAttempts: 1 } - } - if (candidates.length > 0) { - // Skipped candidates still cost all-rows FOR UPDATE inventory scans; - // charge the dispatch interval so skips are rate-limited like claims. - await this.markRegionalRehomeTickSkipped(transaction, now, intervalMs) - } - return null - }).catch((error: unknown): RegionalRehomeAttempt | null => { - // Only inventory contention is swallowed here; every other failure keeps - // its existing propagation and its dispatch-failure accounting. - if (!isDatabaseLockUnavailable(error)) throw error - // The dispatch tick runs every second; losing one to inventory contention - // costs a second of latency and never loses durable rehome state. The - // rolled-back transaction never disabled anything, so its pending disable - // log would describe a decision that did not happen. - candidateSkips.length = 0 - this.pendingRegionalRehomeDisableLog = null - warnSweepCellInventoryBusy( - 'claim-regional-rehome', - Math.max(1, candidatesTotal - candidatesFinished) - ) - return null - }) - const pendingDisableLog = this.pendingRegionalRehomeDisableLog - this.pendingRegionalRehomeDisableLog = null - if (pendingDisableLog) console.warn(JSON.stringify(pendingDisableLog)) - if (claimResult === null && candidateSkips.length > 0) { - console.warn(JSON.stringify(aggregateRegionalRehomeCandidateSkips(candidateSkips))) - } - return claimResult - } - private async startRegionalRehomeCandidate( transaction: RelayDatabase, input: { @@ -5450,6 +5338,9 @@ export class RelayAssignmentStore { worker: SqlRow now: number skips: RegionalRehomeCandidateSkip[] + idleRequest: IdleRegionalRehomeRequest + cohortPercent: number + onSafetyDisabled: (event: Record | null) => void } ): Promise | null> { const assignment = await this.assignmentRow(transaction, input.identity) @@ -5463,12 +5354,21 @@ export class RelayAssignmentStore { } const preference = ( await transaction.queryLocked( - `SELECT * FROM relay_assignment_region_preferences + `SELECT * FROM relay_region_decisions WHERE user_id = ? AND relay_host_id = ?`, [input.identity.userId, input.identity.relayHostId] ) )[0] - if (!preference || integer(preference, 'observed_at') < input.preferenceCutoff) { + if ( + !preference || + integer(preference, 'observed_at') < input.preferenceCutoff || + Number(preference.expires_at) <= input.now || + preference.outcome !== 'conclusive' || + Number(preference.policy_version) !== 1 || + Number(preference.assignment_epoch) !== input.assignmentEpoch || + !preference.preferred_region || + Number(preference.cohort_bucket) >= input.cohortPercent + ) { input.skips.push({ reason: 'candidate_stale' }) return null } @@ -5540,13 +5440,13 @@ export class RelayAssignmentStore { input.now ) if (safetyFailure) { - await this.pauseRegionalRehomeForSafety( + input.onSafetyDisabled(await this.pauseRegionalRehomeForSafety( transaction, input.worker, input.now, safetyFailure, fleetSafety - ) + )) return null } // The preference read under lock can now agree with the cell the host is @@ -5564,9 +5464,9 @@ export class RelayAssignmentStore { integer(sourceRuntime, 'ready') !== 1 || integer(sourceRuntime, 'last_heartbeat_at') <= input.now - this.heartbeatTtlMs || !sourceCapability || - text(sourceCapability, 'cell_incarnation') !== - text(sourceRuntime, 'cell_incarnation') || - integer(sourceCapability, 'regional_rehome_protocol') < 1 + text(sourceCapability, 'cell_incarnation') !== text(sourceRuntime, 'cell_incarnation') || + integer(sourceCapability, 'regional_rehome_protocol') < 3 || + sourceRuntime.cell_incarnation !== input.idleRequest.sourceCellIncarnation ) { input.skips.push({ reason: 'source_ineligible', cellId: input.sourceCellId }) return null @@ -5575,6 +5475,32 @@ export class RelayAssignmentStore { input.skips.push(cellUncleanSkip('source_unclean', input.sourceCellId, sourceSafety)) return null } + const hostCapability = ( + await transaction.query( + `SELECT capability.* FROM relay_control_capabilities capability + JOIN relay_assignment_activity_leases lease + ON lease.user_id = capability.user_id AND lease.relay_host_id = capability.relay_host_id + AND lease.activity_id = capability.activity_id + WHERE capability.user_id = ? AND capability.relay_host_id = ? + AND capability.cell_id = ? AND capability.assignment_epoch = ? + AND capability.cell_incarnation = ? AND capability.idle_regional_rehome = 1 + AND lease.expires_at > ? AND lease.activity_kind = 'control' + ORDER BY capability.generation DESC LIMIT 1`, + [ + input.identity.userId, + input.identity.relayHostId, + input.sourceCellId, + input.assignmentEpoch, + sourceRuntime.cell_incarnation, + input.now + ] + ) + )[0] + if (!hostCapability || preference.incumbent_region !== regions.get(input.sourceCellId) || + Number(hostCapability.generation) !== input.idleRequest.sourceGeneration) { + input.skips.push({ reason: 'candidate_stale' }) + return null + } const sourceControlActive = activityLeases.some( (lease) => text(lease, 'cell_id') === input.sourceCellId && @@ -5606,7 +5532,8 @@ export class RelayAssignmentStore { integer(runtime, 'last_heartbeat_at') > input.now - this.heartbeatTtlMs && capability !== undefined && text(capability, 'cell_incarnation') === text(runtime, 'cell_incarnation') && - integer(capability, 'regional_rehome_protocol') >= 1 + integer(capability, 'regional_rehome_protocol') >= 3 && + cellId === input.idleRequest.targetCellId ) }) const targetIsClean = (row: SqlRow): boolean => { @@ -5753,7 +5680,7 @@ export class RelayAssignmentStore { text(targetRuntime, 'cell_incarnation') ] ) - const attemptId = randomUUID() + const attemptId = input.idleRequest.attemptId await transaction.query( `INSERT INTO relay_region_rehome_attempts (attempt_id, user_id, relay_host_id, preferred_region, @@ -5780,6 +5707,10 @@ export class RelayAssignmentStore { input.now ] ) + await transaction.query( + `UPDATE relay_region_rehome_attempts SET source_generation = ? WHERE attempt_id = ?`, + [input.idleRequest.sourceGeneration, attemptId] + ) return { ...input.identity, attemptId, @@ -5795,61 +5726,13 @@ export class RelayAssignmentStore { } } - private async lockedRegionalRehomeFleetSafety( - transaction: RelayDatabase, - now: number - ): Promise { - const cells = await this.lockCellInventory(transaction, 'nowait') - const admission = await cellAdmissionStates(transaction) - const regions = new Map( - (await transaction.query(`SELECT cell_id, region FROM relay_cell_regions`)).map((row) => [ - text(row, 'cell_id'), - relayRegion(row, 'region') - ]) - ) - const runtimes = await transaction.queryLocked( - `SELECT * FROM relay_cell_runtime ORDER BY cell_id` - ) - const capabilities = await transaction.queryLocked( - `SELECT * FROM relay_cell_capabilities ORDER BY cell_id` - ) - const safetyRows = await transaction.queryLocked( - `SELECT * FROM relay_cell_rehome_safety ORDER BY cell_id` - ) - return regionalRehomeFleetSafetyFromInventory({ - cells, - admission, - regions, - runtimes, - capabilities, - safetyRows, - now, - heartbeatTtlMs: this.heartbeatTtlMs - }) - } - - private async regionalRehomeSafetyAllowsClaim( - transaction: RelayDatabase, - worker: SqlRow, - processSafety: RegionalRehomeSafetySnapshot, - fleetSafety: RegionalRehomeFleetSafety, - now: number - ): Promise { - const failure = regionalRehomeFleetSafetyFailure(processSafety, fleetSafety, now) - if (!failure) { - return true - } - await this.pauseRegionalRehomeForSafety(transaction, worker, now, failure, fleetSafety) - return false - } - private async pauseRegionalRehomeForSafety( transaction: RelayDatabase, worker: SqlRow, now: number, reason: string, fleetSafety: RegionalRehomeFleetSafety - ): Promise { + ): Promise | null> { const disabled = await transaction.query( `UPDATE relay_region_rehome_control SET generation = generation + 1, enabled = 0, updated_at = ? @@ -5860,8 +5743,9 @@ export class RelayAssignmentStore { // The durable disable is otherwise invisible: nothing else records why // claims stopped and inspection only shows enabled=false. Logged after // the transaction commits so a rollback cannot fabricate the record. + let event: Record | null = null if (disabled.length > 0) { - this.pendingRegionalRehomeDisableLog = { + event = { event: 'orca_relay_regional_rehome_safety_disabled', reason, controlGeneration: integer(disabled[0]!, 'generation'), @@ -5879,19 +5763,9 @@ export class RelayAssignmentStore { } } await this.incrementRegionalRehomeWorkerFailure(transaction, worker, now) + return event } - private async markRegionalRehomeTickSkipped( - transaction: RelayDatabase, - now: number, - intervalMs: number - ): Promise { - await transaction.query( - `UPDATE relay_region_rehome_worker_state - SET next_dispatch_at = ?, updated_at = ? WHERE worker_id = 'global'`, - [now + intervalMs, now] - ) - } private async markRegionalRehomeDispatchClaimed( transaction: RelayDatabase, @@ -5912,74 +5786,6 @@ export class RelayAssignmentStore { ) } - async recordRegionalRehomeDrainReceipt( - attemptId: string, - outcome: RegionalHostDrainOutcome - ): Promise { - const now = this.now() - return await this.database.transaction(async (transaction) => { - const worker = ( - await transaction.queryLocked( - `SELECT * FROM relay_region_rehome_worker_state WHERE worker_id = 'global'` - ) - )[0] - const attempt = ( - await transaction.queryLocked( - `SELECT * FROM relay_region_rehome_attempts WHERE attempt_id = ?`, - [attemptId] - ) - )[0] - if (!attempt) throw new Error('regional_rehome_attempt_not_found') - // Any receipt proves the source cell answered: reset the failure budget - // even when a redrain repeats the stored outcome; otherwise a - // redrain-dominated stream lets scattered transient failures reach the - // durable three-failure disable. - if (worker) { - await transaction.query( - `UPDATE relay_region_rehome_worker_state - SET consecutive_failures = 0, paused_until = 0, updated_at = ? - WHERE worker_id = 'global'`, - [now] - ) - } - const existingOutcome = optionalText(attempt, 'drain_outcome') - if (existingOutcome === outcome) return false - // Redrains produce one receipt per dispatch; the latest outcome wins. - await transaction.query( - `UPDATE relay_region_rehome_attempts - SET drain_receipt_at = ?, drain_outcome = ?, updated_at = ? - WHERE attempt_id = ?`, - [now, outcome, now, attemptId] - ) - return true - }) - } - - async recordRegionalRehomeDispatchFailure(attemptId: string): Promise { - const now = this.now() - const disableLog = await this.database.transaction(async (transaction) => { - // Match claim and enable ordering before a spent budget updates the control. - await transaction.queryLocked( - `SELECT * FROM relay_region_rehome_control WHERE control_id = 'global'` - ) - const worker = ( - await transaction.queryLocked( - `SELECT * FROM relay_region_rehome_worker_state WHERE worker_id = 'global'` - ) - )[0] - const attempt = ( - await transaction.queryLocked( - `SELECT attempt_id FROM relay_region_rehome_attempts WHERE attempt_id = ?`, - [attemptId] - ) - )[0] - if (!worker || !attempt) return null - return await this.incrementRegionalRehomeWorkerFailure(transaction, worker, now) - }) - // Logged after the commit so a rollback cannot fabricate the record. - if (disableLog) console.warn(JSON.stringify(disableLog)) - } - // Returns the durable disable this failure caused, for the caller to log once // its transaction commits; null when the budget survives or was already spent. private async incrementRegionalRehomeWorkerFailure( @@ -6074,7 +5880,7 @@ export class RelayAssignmentStore { // LIMIT pages: poisoned rows are permanent and always the oldest, so // without exclusion they eventually starve every healthy candidate. private recordRegionalRehomeCandidateFailure( - operation: 'complete' | 'abort', + operation: 'complete' | 'abort' | 'refresh', attemptId: string, now: number, error: unknown @@ -6116,12 +5922,16 @@ export class RelayAssignmentStore { async refreshRegionalRehomeLeases(limit = 100): Promise { const now = this.now() + const quarantined = this.quarantinedRegionalRehomeAttemptIds(now) + const exclusion = quarantined.length + ? ` AND attempt_id NOT IN (${quarantined.map(() => '?').join(', ')})` + : '' const candidates = await this.database.query( - `SELECT user_id, relay_host_id, assignment_epoch + `SELECT attempt_id, user_id, relay_host_id, assignment_epoch FROM relay_region_rehome_attempts - WHERE completed_at IS NULL AND aborted_at IS NULL - ORDER BY created_at, attempt_id LIMIT ?`, - [limit] + WHERE completed_at IS NULL AND aborted_at IS NULL${exclusion} + ORDER BY updated_at, attempt_id LIMIT ?`, + [...quarantined, limit] ) let refreshed = 0 for (const candidate of candidates) { @@ -6130,50 +5940,91 @@ export class RelayAssignmentStore { relayHostId: text(candidate, 'relay_host_id') } const assignmentEpoch = integer(candidate, 'assignment_epoch') - const changed = await this.database.transaction(async (transaction) => { - const assignment = await this.assignmentRow(transaction, identity) - const attempt = ( - await transaction.queryLocked( - `SELECT * FROM relay_region_rehome_attempts + const attemptId = text(candidate, 'attempt_id') + try { + const changed = await this.database.transaction(async (transaction) => { + const assignment = await this.assignmentRow(transaction, identity) + const attempt = ( + await transaction.queryLocked( + `SELECT * FROM relay_region_rehome_attempts WHERE user_id = ? AND relay_host_id = ? AND assignment_epoch = ?`, - [identity.userId, identity.relayHostId, assignmentEpoch] - ) - )[0] - const migration = ( - await transaction.queryLocked( - `SELECT * FROM relay_assignment_migrations + [identity.userId, identity.relayHostId, assignmentEpoch] + ) + )[0] + const migration = ( + await transaction.queryLocked( + `SELECT * FROM relay_assignment_migrations WHERE user_id = ? AND relay_host_id = ? AND assignment_epoch = ?`, - [identity.userId, identity.relayHostId, assignmentEpoch] - ) - )[0] - if ( - !assignment || - !attempt || - !migration || - optionalInteger(attempt, 'completed_at') !== undefined || - optionalInteger(attempt, 'aborted_at') !== undefined || - optionalInteger(migration, 'completed_at') !== undefined || - optionalInteger(migration, 'aborted_at') !== undefined - ) { - return false - } - const attemptAgeMs = now - integer(attempt, 'created_at') - if (attemptAgeMs >= REGIONAL_REHOME_MAX_REFRESH_MS) { - return false - } - if ( - optionalInteger(migration, 'target_registered_at') === undefined && - attemptAgeMs >= REGIONAL_REHOME_UNREGISTERED_REFRESH_MS - ) { - await transaction.query( - `UPDATE relay_assignment_activity_leases + [identity.userId, identity.relayHostId, assignmentEpoch] + ) + )[0] + if (attempt && attempt.completed_at == null && attempt.aborted_at == null) { + await transaction.query( + `UPDATE relay_region_rehome_attempts SET updated_at = ? WHERE attempt_id = ?`, + [now, attempt.attempt_id] + ) + } + if ( + !assignment || + !attempt || + !migration || + optionalInteger(attempt, 'completed_at') !== undefined || + optionalInteger(attempt, 'aborted_at') !== undefined || + optionalInteger(migration, 'completed_at') !== undefined || + optionalInteger(migration, 'aborted_at') !== undefined + ) { + return false + } + const attemptAgeMs = now - integer(attempt, 'created_at') + if (attemptAgeMs >= REGIONAL_REHOME_MAX_REFRESH_MS) { + return false + } + if ( + optionalInteger(migration, 'target_registered_at') === undefined && + attemptAgeMs >= REGIONAL_REHOME_UNREGISTERED_REFRESH_MS + ) { + await transaction.query( + `UPDATE relay_assignment_activity_leases SET expires_at = CASE WHEN expires_at < ? THEN expires_at ELSE ? END, updated_at = ? WHERE user_id = ? AND relay_host_id = ? AND activity_id IN (?, ?)`, + [ + now, + now, + now, + identity.userId, + identity.relayHostId, + pendingControlActivityId(assignmentEpoch), + migrationActivityId(assignmentEpoch) + ] + ) + await transaction.query( + `UPDATE relay_assignment_migrations + SET expires_at = CASE WHEN expires_at < ? THEN expires_at ELSE ? END, + updated_at = ? + WHERE user_id = ? AND relay_host_id = ? AND assignment_epoch = ?`, + [now, now, now, identity.userId, identity.relayHostId, assignmentEpoch] + ) + return false + } + const leases = await this.lockAssignmentActivities(transaction, identity) + const protectedIds = new Set([ + pendingControlActivityId(assignmentEpoch), + migrationActivityId(assignmentEpoch) + ]) + const protectedLeases = leases.filter((lease) => + protectedIds.has(text(lease, 'activity_id')) + ) + if (protectedLeases.length === 0) return false + const expiresAt = now + ASSIGNMENT_LIMITS.migrationLeaseMs + await transaction.query( + `UPDATE relay_assignment_activity_leases + SET expires_at = ?, updated_at = ? + WHERE user_id = ? AND relay_host_id = ? + AND activity_id IN (?, ?)`, [ - now, - now, + expiresAt, now, identity.userId, identity.relayHostId, @@ -6182,53 +6033,25 @@ export class RelayAssignmentStore { ] ) await transaction.query( - `UPDATE relay_assignment_migrations - SET expires_at = CASE WHEN expires_at < ? THEN expires_at ELSE ? END, - updated_at = ? - WHERE user_id = ? AND relay_host_id = ? AND assignment_epoch = ?`, - [now, now, now, identity.userId, identity.relayHostId, assignmentEpoch] - ) - return false - } - const leases = await this.lockAssignmentActivities(transaction, identity) - const protectedIds = new Set([ - pendingControlActivityId(assignmentEpoch), - migrationActivityId(assignmentEpoch) - ]) - const protectedLeases = leases.filter((lease) => - protectedIds.has(text(lease, 'activity_id')) - ) - if (protectedLeases.length === 0) return false - const expiresAt = now + ASSIGNMENT_LIMITS.migrationLeaseMs - await transaction.query( - `UPDATE relay_assignment_activity_leases - SET expires_at = ?, updated_at = ? - WHERE user_id = ? AND relay_host_id = ? - AND activity_id IN (?, ?)`, - [ - expiresAt, - now, - identity.userId, - identity.relayHostId, - pendingControlActivityId(assignmentEpoch), - migrationActivityId(assignmentEpoch) - ] - ) - await transaction.query( - `UPDATE relay_assignment_migrations SET expires_at = ?, updated_at = ? + `UPDATE relay_assignment_migrations SET expires_at = ?, updated_at = ? WHERE user_id = ? AND relay_host_id = ? AND assignment_epoch = ?`, - [expiresAt, now, identity.userId, identity.relayHostId, assignmentEpoch] - ) - await transaction.query( - `UPDATE relay_assignments SET lease_expires_at = + [expiresAt, now, identity.userId, identity.relayHostId, assignmentEpoch] + ) + await transaction.query( + `UPDATE relay_assignments SET lease_expires_at = CASE WHEN lease_expires_at > ? THEN lease_expires_at ELSE ? END, last_activity_at = ? WHERE user_id = ? AND relay_host_id = ?`, - [expiresAt, expiresAt, now, identity.userId, identity.relayHostId] - ) - return true - }) - if (changed) refreshed++ + [expiresAt, expiresAt, now, identity.userId, identity.relayHostId] + ) + return true + }) + if (changed) refreshed++ + this.regionalRehomeCandidateQuarantine.delete(attemptId) + } catch (error) { + if (!isDatabaseLockUnavailable(error)) + this.recordRegionalRehomeCandidateFailure('refresh', attemptId, now, error) + } } return refreshed } @@ -6575,92 +6398,169 @@ export class RelayAssignmentStore { let aborted = 0 let inventoryBusy = 0 for (const candidate of candidates) { - const didAbort = await this.database.transaction(async (transaction) => { - const identity = { - userId: text(candidate, 'user_id'), - relayHostId: text(candidate, 'relay_host_id') - } - // Migration cleanup follows the same assignment-first order as evacuation. - const assignment = await this.assignmentRow(transaction, identity) - const assignmentEpoch = integer(candidate, 'assignment_epoch') - const regionalAttempt = ( - await transaction.queryLocked( - `SELECT attempt_id FROM relay_region_rehome_attempts + const didAbort = await this.database + .transaction(async (transaction) => { + const identity = { + userId: text(candidate, 'user_id'), + relayHostId: text(candidate, 'relay_host_id') + } + // Migration cleanup follows the same assignment-first order as evacuation. + const assignment = await this.assignmentRow(transaction, identity) + const assignmentEpoch = integer(candidate, 'assignment_epoch') + const regionalAttempt = ( + await transaction.queryLocked( + `SELECT attempt_id FROM relay_region_rehome_attempts WHERE user_id = ? AND relay_host_id = ? AND assignment_epoch = ? AND completed_at IS NULL AND aborted_at IS NULL`, - [identity.userId, identity.relayHostId, assignmentEpoch] - ) - )[0] - const row = ( - await transaction.queryLocked( - `SELECT migration.* FROM relay_assignment_migrations migration + [identity.userId, identity.relayHostId, assignmentEpoch] + ) + )[0] + const row = ( + await transaction.queryLocked( + `SELECT migration.* FROM relay_assignment_migrations migration WHERE migration.user_id = ? AND migration.relay_host_id = ? AND migration.assignment_epoch = ? AND migration.expires_at <= ? AND migration.completed_at IS NULL AND migration.aborted_at IS NULL AND ${ABORTABLE_EXPIRED_MIGRATION}`, - [ - identity.userId, - identity.relayHostId, - assignmentEpoch, - now, - now, - abandonedBefore, - abandonedBefore - ] + [ + identity.userId, + identity.relayHostId, + assignmentEpoch, + now, + now, + abandonedBefore, + abandonedBefore + ] + ) + )[0] + if (!row) return false + const targetCellId = text(row, 'target_cell_id') + const activityLeases = await this.lockAssignmentActivities(transaction, identity) + if (!assignment) throw new Error('migration_assignment_missing') + const currentAssignmentEpoch = integer(assignment, 'assignment_epoch') + const assignmentEpochMatches = + text(assignment, 'cell_id') === targetCellId && + currentAssignmentEpoch === assignmentEpoch + const pendingTargetControl = activityLeaseById( + activityLeases, + pendingControlActivityId(assignmentEpoch) ) - )[0] - if (!row) return false - const targetCellId = text(row, 'target_cell_id') - const activityLeases = await this.lockAssignmentActivities(transaction, identity) - if (!assignment) throw new Error('migration_assignment_missing') - const currentAssignmentEpoch = integer(assignment, 'assignment_epoch') - const assignmentEpochMatches = - text(assignment, 'cell_id') === targetCellId && - currentAssignmentEpoch === assignmentEpoch - const pendingTargetControl = activityLeaseById( - activityLeases, - pendingControlActivityId(assignmentEpoch) - ) - const targetGrantIsFresh = - assignmentEpochMatches && - pendingTargetControl !== undefined && - text(pendingTargetControl, 'cell_id') === targetCellId && - text(pendingTargetControl, 'activity_kind') === 'control' && - integer(pendingTargetControl, 'expires_at') > now - const targetIsActive = activityLeases.some( - (lease) => - text(lease, 'cell_id') === targetCellId && - text(lease, 'activity_kind') === 'control' && - text(lease, 'activity_id') !== pendingControlActivityId(assignmentEpoch) - ) - if (targetGrantIsFresh) return false - if (targetIsActive && assignmentEpochMatches) { - // A committed target control is stronger evidence than a failed follow-up - // write; repair the marker instead of rolling a live desktop backward. - await transaction.query( - `UPDATE relay_assignment_migrations + const targetGrantIsFresh = + assignmentEpochMatches && + pendingTargetControl !== undefined && + text(pendingTargetControl, 'cell_id') === targetCellId && + text(pendingTargetControl, 'activity_kind') === 'control' && + integer(pendingTargetControl, 'expires_at') > now + const targetIsActive = activityLeases.some( + (lease) => + text(lease, 'cell_id') === targetCellId && + text(lease, 'activity_kind') === 'control' && + text(lease, 'activity_id') !== pendingControlActivityId(assignmentEpoch) + ) + if (targetGrantIsFresh) return false + if (targetIsActive && assignmentEpochMatches) { + // A committed target control is stronger evidence than a failed follow-up + // write; repair the marker instead of rolling a live desktop backward. + await transaction.query( + `UPDATE relay_assignment_migrations SET target_registered_at = COALESCE(target_registered_at, ?), updated_at = ? WHERE user_id = ? AND relay_host_id = ? AND assignment_epoch = ?`, - [now, now, identity.userId, identity.relayHostId, assignmentEpoch] - ) - return false - } - if (!assignmentEpochMatches) { - if (currentAssignmentEpoch <= assignmentEpoch) { - throw new Error('migration_assignment_mismatch') + [now, now, identity.userId, identity.relayHostId, assignmentEpoch] + ) + return false } - // A newer assignment is authoritative regardless of where it landed. - // Retire only this obsolete migration; never rewrite the newer epoch. - const obsoleteLeases = [ + if (!assignmentEpochMatches) { + if (currentAssignmentEpoch <= assignmentEpoch) { + throw new Error('migration_assignment_mismatch') + } + // A newer assignment is authoritative regardless of where it landed. + // Retire only this obsolete migration; never rewrite the newer epoch. + const obsoleteLeases = [ + pendingControlActivityId(assignmentEpoch), + migrationActivityId(assignmentEpoch) + ] + .map((activityId) => activityLeaseById(activityLeases, activityId)) + .filter((lease): lease is SqlRow => lease !== undefined) + if (obsoleteLeases.length > 0) await this.lockCellInventory(transaction, 'nowait') + for (const lease of obsoleteLeases) { + await this.removeActivityLease(transaction, identity, lease, now) + } + await this.releaseSupersededControlConnectionReservations( + transaction, + identity, + targetCellId, + assignmentEpoch, + now + ) + await transaction.query( + `UPDATE relay_assignment_migrations SET aborted_at = ?, updated_at = ? + WHERE user_id = ? AND relay_host_id = ? AND assignment_epoch = ?`, + [now, now, identity.userId, identity.relayHostId, assignmentEpoch] + ) + return true + } + const cells = await this.lockCellInventory(transaction, 'nowait') + const sourceCellId = text(row, 'source_cell_id') + const admissionRows = await transaction.query( + `SELECT cell_id, admission_state, updated_at FROM relay_cell_admission + WHERE cell_id IN (?, ?)`, + [sourceCellId, targetCellId] + ) + const sourceCell = cells.find((cell) => text(cell, 'cell_id') === sourceCellId) + const targetCell = cells.find((cell) => text(cell, 'cell_id') === targetCellId) + const sourceAdmission = admissionRows.find( + (admission) => text(admission, 'cell_id') === sourceCellId + ) + const targetAdmission = admissionRows.find( + (admission) => text(admission, 'cell_id') === targetCellId + ) + const registered = optionalInteger(row, 'target_registered_at') !== undefined + const sourceIsDurablyFenced = + registered && + ( + await transaction.query( + `SELECT 1 FROM relay_assignment_migrations migration + WHERE migration.user_id = ? AND migration.relay_host_id = ? + AND migration.assignment_epoch = ? + AND ${DURABLY_FENCED_MIGRATION_SOURCE}`, + [identity.userId, identity.relayHostId, assignmentEpoch] + ) + ).length === 1 + const retireOnTarget = + registered && + activityUnitsForCell(activityLeases, sourceCellId) === 0 && + sourceCell !== undefined && + integer(sourceCell, 'enabled') === 0 && + sourceAdmission !== undefined && + text(sourceAdmission, 'admission_state') === 'existing-only' && + (integer(sourceAdmission, 'updated_at') <= abandonedBefore || sourceIsDurablyFenced) && + targetCell !== undefined && + integer(targetCell, 'enabled') === 1 && + targetAdmission !== undefined && + ['migration-only', 'general'].includes(text(targetAdmission, 'admission_state')) + const rollbackReason = + !registered || + (targetCell !== undefined && + integer(targetCell, 'enabled') === 0 && + targetAdmission !== undefined && + text(targetAdmission, 'admission_state') === 'existing-only' && + integer(targetAdmission, 'updated_at') <= abandonedBefore) + const regionalRollbackSourceAvailable = + !regionalAttempt || + (sourceCell !== undefined && + integer(sourceCell, 'enabled') === 1 && + sourceAdmission !== undefined && + text(sourceAdmission, 'admission_state') === 'general' && + (await this.cellIsLive(transaction, sourceCellId, now))) + const rollbackToSource = rollbackReason && regionalRollbackSourceAvailable + if (!retireOnTarget && !rollbackToSource) return false + for (const activityId of [ pendingControlActivityId(assignmentEpoch), migrationActivityId(assignmentEpoch) - ] - .map((activityId) => activityLeaseById(activityLeases, activityId)) - .filter((lease): lease is SqlRow => lease !== undefined) - if (obsoleteLeases.length > 0) await this.lockCellInventory(transaction, 'nowait') - for (const lease of obsoleteLeases) { - await this.removeActivityLease(transaction, identity, lease, now) + ]) { + const lease = activityLeaseById(activityLeases, activityId) + if (lease) await this.removeActivityLease(transaction, identity, lease, now) } await this.releaseSupersededControlConnectionReservations( transaction, @@ -6669,116 +6569,47 @@ export class RelayAssignmentStore { assignmentEpoch, now ) - await transaction.query( - `UPDATE relay_assignment_migrations SET aborted_at = ?, updated_at = ? - WHERE user_id = ? AND relay_host_id = ? AND assignment_epoch = ?`, - [now, now, identity.userId, identity.relayHostId, assignmentEpoch] - ) - return true - } - const cells = await this.lockCellInventory(transaction, 'nowait') - const sourceCellId = text(row, 'source_cell_id') - const admissionRows = await transaction.query( - `SELECT cell_id, admission_state, updated_at FROM relay_cell_admission - WHERE cell_id IN (?, ?)`, - [sourceCellId, targetCellId] - ) - const sourceCell = cells.find((cell) => text(cell, 'cell_id') === sourceCellId) - const targetCell = cells.find((cell) => text(cell, 'cell_id') === targetCellId) - const sourceAdmission = admissionRows.find( - (admission) => text(admission, 'cell_id') === sourceCellId - ) - const targetAdmission = admissionRows.find( - (admission) => text(admission, 'cell_id') === targetCellId - ) - const registered = optionalInteger(row, 'target_registered_at') !== undefined - const sourceIsDurablyFenced = - registered && - ( + if (retireOnTarget) { await transaction.query( - `SELECT 1 FROM relay_assignment_migrations migration - WHERE migration.user_id = ? AND migration.relay_host_id = ? - AND migration.assignment_epoch = ? - AND ${DURABLY_FENCED_MIGRATION_SOURCE}`, - [identity.userId, identity.relayHostId, assignmentEpoch] - ) - ).length === 1 - const retireOnTarget = - registered && - activityUnitsForCell(activityLeases, sourceCellId) === 0 && - sourceCell !== undefined && - integer(sourceCell, 'enabled') === 0 && - sourceAdmission !== undefined && - text(sourceAdmission, 'admission_state') === 'existing-only' && - (integer(sourceAdmission, 'updated_at') <= abandonedBefore || - sourceIsDurablyFenced) && - targetCell !== undefined && - integer(targetCell, 'enabled') === 1 && - targetAdmission !== undefined && - ['migration-only', 'general'].includes(text(targetAdmission, 'admission_state')) - const rollbackReason = - !registered || - (targetCell !== undefined && - integer(targetCell, 'enabled') === 0 && - targetAdmission !== undefined && - text(targetAdmission, 'admission_state') === 'existing-only' && - integer(targetAdmission, 'updated_at') <= abandonedBefore) - const regionalRollbackSourceAvailable = - !regionalAttempt || - (sourceCell !== undefined && - integer(sourceCell, 'enabled') === 1 && - sourceAdmission !== undefined && - text(sourceAdmission, 'admission_state') === 'general' && - (await this.cellIsLive(transaction, sourceCellId, now))) - const rollbackToSource = rollbackReason && regionalRollbackSourceAvailable - if (!retireOnTarget && !rollbackToSource) return false - for (const activityId of [ - pendingControlActivityId(assignmentEpoch), - migrationActivityId(assignmentEpoch) - ]) { - const lease = activityLeaseById(activityLeases, activityId) - if (lease) await this.removeActivityLease(transaction, identity, lease, now) - } - await this.releaseSupersededControlConnectionReservations( - transaction, - identity, - targetCellId, - assignmentEpoch, - now - ) - if (retireOnTarget) { - await transaction.query( - `UPDATE relay_assignment_migrations SET completed_at = ?, updated_at = ? + `UPDATE relay_assignment_migrations SET completed_at = ?, updated_at = ? WHERE user_id = ? AND relay_host_id = ? AND assignment_epoch = ?`, - [now, now, identity.userId, identity.relayHostId, assignmentEpoch] - ) - return true - } - await transaction.query( - `UPDATE relay_assignments SET cell_id = ?, assignment_epoch = ?, + [now, now, identity.userId, identity.relayHostId, assignmentEpoch] + ) + return true + } + await transaction.query( + `UPDATE relay_assignments SET cell_id = ?, assignment_epoch = ?, lease_expires_at = ?, last_activity_at = ? WHERE user_id = ? AND relay_host_id = ?`, - [ - sourceCellId, - assignmentEpoch + 1, - now + ASSIGNMENT_LIMITS.activityLeaseMs, - now, - identity.userId, - identity.relayHostId - ] - ) - await transaction.query( - `UPDATE relay_assignment_migrations SET aborted_at = ?, updated_at = ? + [ + sourceCellId, + assignmentEpoch + 1, + now + ASSIGNMENT_LIMITS.activityLeaseMs, + now, + identity.userId, + identity.relayHostId + ] + ) + await transaction.query( + `UPDATE relay_assignment_migrations SET aborted_at = ?, updated_at = ? WHERE user_id = ? AND relay_host_id = ? AND assignment_epoch = ?`, - [now, now, identity.userId, identity.relayHostId, assignmentEpoch] - ) - return true - }).catch((error: unknown): boolean => { - // Expiry is durable; another director settling this row is not a failure. - if (!isDatabaseLockUnavailable(error)) throw error - inventoryBusy++ - return false - }) + [now, now, identity.userId, identity.relayHostId, assignmentEpoch] + ) + if (regionalAttempt) { + await transaction.query( + `UPDATE relay_region_rehome_attempts SET aborted_at = ?, updated_at = ? WHERE attempt_id = ?`, + [now, now, regionalAttempt.attempt_id] + ) + } + return true + }) + .catch((error: unknown): boolean => { + // Expiry is durable; another director settling this row is not a failure. + // Invariant failures remain fatal so operators see corrupt migration state. + if (!isDatabaseLockUnavailable(error)) throw error + inventoryBusy++ + return false + }) if (didAbort) aborted++ } warnSweepCellInventoryBusy('abort-expired-evacuations', inventoryBusy) @@ -8165,7 +7996,7 @@ function migration(identity: AssignmentIdentity, row: SqlRow): RelayAssignmentMi // Attempt ids are server-minted UUIDs and this codebase's invariant messages // are snake_case slugs; anything else could carry secrets and logs redacted. function warnRegionalRehomeCandidateFailure( - operation: 'complete' | 'abort', + operation: 'complete' | 'abort' | 'refresh', attemptId: string, error: unknown ): void { @@ -8190,24 +8021,6 @@ function noteRegionalRehomeActivityCountsRepaired(attemptId: string): void { ) } -function regionalRehomeAttempt(row: SqlRow): RegionalRehomeAttempt { - return { - attemptId: text(row, 'attempt_id'), - userId: text(row, 'user_id'), - relayHostId: text(row, 'relay_host_id'), - preferredRegion: relayRegion(row, 'preferred_region'), - sourceCellId: text(row, 'source_cell_id'), - sourceCellUrl: text(row, 'source_cell_url'), - sourceCellIncarnation: text(row, 'source_cell_incarnation'), - targetCellId: text(row, 'target_cell_id'), - targetCellIncarnation: text(row, 'target_cell_incarnation'), - previousEpoch: integer(row, 'previous_epoch'), - assignmentEpoch: integer(row, 'assignment_epoch'), - drainGraceMs: integer(row, 'drain_grace_ms'), - sendAttempts: integer(row, 'send_attempts') - } -} - function regionalRehomeControl(row: SqlRow): RegionalRehomeControl { return { generation: integer(row, 'generation'), @@ -8221,17 +8034,6 @@ function regionalRehomeControl(row: SqlRow): RegionalRehomeControl { } } -function cleanRegionalRehomeSafety(now: number): RegionalRehomeSafetySnapshot { - return { - observedAt: now, - sqlFailures: 0, - reconnects: 0, - controlActivityRecoveryFailures: 0, - databasePoolWaiting: 0, - databasePoolWaitersMax: 0, - databasePoolWaitMsMax: 0 - } -} function regionalRehomeFleetSafetyFromInventory(input: { cells: SqlRow[] @@ -8353,23 +8155,6 @@ function cellUncleanSkip( // Candidate skips are otherwise invisible: they neither latch the control off // nor produce attempts, so an operator cannot tell "skipping" from "idle". // Cell ids and counters only — never free-form error text. -function aggregateRegionalRehomeCandidateSkips( - skips: readonly RegionalRehomeCandidateSkip[] -): Record { - // `candidates` counts skipped candidate iterations, not distinct cells: one - // unclean cell blocking six candidates reports candidates=6 on one cellId. - const aggregated = new Map() - for (const skip of skips) { - const key = `${skip.reason}:${skip.cellId ?? ''}` - const entry = aggregated.get(key) - if (entry) entry.candidates += 1 - else aggregated.set(key, { ...skip, candidates: 1 }) - } - return { - event: 'orca_relay_regional_rehome_candidates_skipped', - skips: [...aggregated.values()] - } -} function regionalRehomeCellSafetyIsClean( safety: SqlRow | undefined, diff --git a/cloud/apps/relay/src/cell-heartbeat-client.test.ts b/cloud/apps/relay/src/cell-heartbeat-client.test.ts index 2aa708bed1b..6c36829e768 100644 --- a/cloud/apps/relay/src/cell-heartbeat-client.test.ts +++ b/cloud/apps/relay/src/cell-heartbeat-client.test.ts @@ -92,7 +92,7 @@ describe('cell heartbeat client', () => { client.stop() expect(JSON.parse(String(requests[1]!.body))).toMatchObject({ - regionalRehomeProtocol: 1, + regionalRehomeProtocol: 3, safety: { observedAt: 120, sqlFailures: 0, @@ -149,28 +149,34 @@ describe('cell heartbeat client', () => { it('does not start outside an explicitly configured cell role', () => { expect( - startCellHeartbeat({ ...CONFIG, role: 'director' }, { - ready: async () => true, - observedRequests: () => 0, - connectionCounts: () => ({ - totalConnections: 0, - inFlightConnections: 0, - reservedConnectionUnits: 0, - enforcedConnectionUnits: 0 - }) - }) + startCellHeartbeat( + { ...CONFIG, role: 'director' }, + { + ready: async () => true, + observedRequests: () => 0, + connectionCounts: () => ({ + totalConnections: 0, + inFlightConnections: 0, + reservedConnectionUnits: 0, + enforcedConnectionUnits: 0 + }) + } + ) ).toBeNull() expect( - startCellHeartbeat({ ...CONFIG, directorUrl: undefined }, { - ready: async () => true, - observedRequests: () => 0, - connectionCounts: () => ({ - totalConnections: 0, - inFlightConnections: 0, - reservedConnectionUnits: 0, - enforcedConnectionUnits: 0 - }) - }) + startCellHeartbeat( + { ...CONFIG, directorUrl: undefined }, + { + ready: async () => true, + observedRequests: () => 0, + connectionCounts: () => ({ + totalConnections: 0, + inFlightConnections: 0, + reservedConnectionUnits: 0, + enforcedConnectionUnits: 0 + }) + } + ) ).toBeNull() }) }) diff --git a/cloud/apps/relay/src/cell-heartbeat-client.ts b/cloud/apps/relay/src/cell-heartbeat-client.ts index 5c990310413..54f97a17af8 100644 --- a/cloud/apps/relay/src/cell-heartbeat-client.ts +++ b/cloud/apps/relay/src/cell-heartbeat-client.ts @@ -70,8 +70,7 @@ export function startCellHeartbeat( inFlightConnections: connectionCounts!.inFlightConnections, reservedConnectionUnits: connectionCounts!.reservedConnectionUnits, enforcedConnectionUnits: connectionCounts!.enforcedConnectionUnits, - connectionInclusionWatermark: - connectionCounts!.inclusionWatermark, + connectionInclusionWatermark: connectionCounts!.inclusionWatermark, connectionHardCap: config.connectionHardCap, connectionUnobservedBound: config.connectionUnobservedBound }) @@ -94,7 +93,7 @@ export function startCellHeartbeat( cellId: config.cellId, cellIncarnation, regionalRehomeProtocol: - config.rehomeAudience && config.rehomeDirectorServiceAccount ? 1 : 0, + config.rehomeAudience && config.rehomeDirectorServiceAccount ? 3 : 0, safety: options.regionalRehomeSafety() }), signal: AbortSignal.timeout(10_000) @@ -106,7 +105,10 @@ export function startCellHeartbeat( } } catch (error) { // A heartbeat must fail closed without ever logging its bearer token. - console.warn('[orca-relay] cell heartbeat failed', error instanceof Error ? error.message : '') + console.warn( + '[orca-relay] cell heartbeat failed', + error instanceof Error ? error.message : '' + ) } finally { inFlight = false } diff --git a/cloud/apps/relay/src/cell-inventory-lock-census.test.ts b/cloud/apps/relay/src/cell-inventory-lock-census.test.ts index 0ac4c8225e3..929173eb9da 100644 --- a/cloud/apps/relay/src/cell-inventory-lock-census.test.ts +++ b/cloud/apps/relay/src/cell-inventory-lock-census.test.ts @@ -43,14 +43,13 @@ const CENSUS: CensusEntry[] = [ { method: 'completeEvacuation', mode: 'nowait', reach: 'both' }, { method: 'completeEvacuation', mode: 'pool-default', reach: 'both' }, { method: 'rebalanceDormant', mode: 'request', reach: 'request' }, - { method: 'startRegionalRehomeCandidate', mode: 'nowait', reach: 'sweep' }, - { method: 'lockedRegionalRehomeFleetSafety', mode: 'nowait', reach: 'sweep' }, + { method: 'startRegionalRehomeCandidate', mode: 'nowait', reach: 'request' }, { method: 'completeRegionalRehomeCandidate', mode: 'nowait', reach: 'sweep' }, { method: 'abortExpiredRegionalRehomes', mode: 'nowait', reach: 'sweep' }, { method: 'abortExpiredEvacuations', mode: 'nowait', reach: 'sweep' }, { method: 'abortExpiredEvacuations', mode: 'nowait', reach: 'sweep' }, { method: 'releaseExpiredActivityLeases', mode: 'nowait', reach: 'sweep' }, - { method: 'releaseExpiredActivity', mode: 'nowait', reach: 'sweep' }, + { method: 'releaseExpiredActivity', mode: 'nowait', reach: 'sweep' } // reconcileReservationAccounting and leastLoadedCell are gone too: the first // repairs exactly two cells' counters and now holds only those rows, and the // second selects from the inventory its single caller has already locked. @@ -119,9 +118,10 @@ function storeCallGraph(lines: string[]): Map> { bounds.forEach((method, index) => { const end = bounds[index + 1]?.start ?? lines.length const names = callees.get(method.name) ?? new Set() - for (const call of lines.slice(method.start, end).join('\n').matchAll( - /this\.([A-Za-z_][\w]*)\s*\(/g - )) { + for (const call of lines + .slice(method.start, end) + .join('\n') + .matchAll(/this\.([A-Za-z_][\w]*)\s*\(/g)) { names.add(call[1]!) } callees.set(method.name, names) @@ -174,9 +174,7 @@ function readCallSites(): { method: string; mode: CensusMode }[] { describe('cell inventory lock call-site census', () => { it('classifies every call site exactly as recorded', () => { - expect(readCallSites()).toEqual( - CENSUS.map(({ method, mode }) => ({ method, mode })) - ) + expect(readCallSites()).toEqual(CENSUS.map(({ method, mode }) => ({ method, mode }))) }) // Why: the census only sees lockCellInventory calls, so a hand-written diff --git a/cloud/apps/relay/src/config.test.ts b/cloud/apps/relay/src/config.test.ts index bb0522dcbd3..01661a61826 100644 --- a/cloud/apps/relay/src/config.test.ts +++ b/cloud/apps/relay/src/config.test.ts @@ -25,6 +25,17 @@ function cellEnvironment(capacity: number): NodeJS.ProcessEnv { } describe('GCE relay capacity configuration', () => { + it('defaults optional region correction off and bounds the cohort', () => { + const env = cellEnvironment(4_000) + expect(loadRelayConfig(env).regionCorrectionCohortPercent).toBe(0) + env.ORCA_RELAY_REGION_CORRECTION_COHORT_PERCENT = '5' + expect(loadRelayConfig(env).regionCorrectionCohortPercent).toBe(5) + for (const invalid of ['-1', '101', '1.5', 'not-a-number']) { + env.ORCA_RELAY_REGION_CORRECTION_COHORT_PERCENT = invalid + expect(() => loadRelayConfig(env)).toThrow() + } + }) + it('requires distinct dedicated admin identities and accepts omitted values', () => { const env = cellEnvironment(4_000) expect(loadRelayConfig(env)).toMatchObject({ diff --git a/cloud/apps/relay/src/config.ts b/cloud/apps/relay/src/config.ts index 2bf23444a71..83dc9708f74 100644 --- a/cloud/apps/relay/src/config.ts +++ b/cloud/apps/relay/src/config.ts @@ -75,11 +75,15 @@ const EnvSchema = z.object({ ORCA_RELAY_RUNTIME_SERVICE_ACCOUNT: z.string().email().optional(), ORCA_RELAY_DIRECTOR_URL: z.string().url().optional(), ORCA_RELAY_HEARTBEAT_AUDIENCE: z.string().url().optional(), - ORCA_RELAY_IMAGE_DIGEST: z.string().regex(/^sha256:[a-f0-9]{64}$/).optional(), + ORCA_RELAY_IMAGE_DIGEST: z + .string() + .regex(/^sha256:[a-f0-9]{64}$/) + .optional(), ORCA_RELAY_ADMIN_JWKS_URL: z.string().url().default('https://www.googleapis.com/oauth2/v3/certs'), ORCA_RELAY_DATABASE_POOL_MAX: z.coerce.number().int().positive().max(100).optional(), ORCA_RELAY_PUBLIC_ASSIGNMENTS_ENABLED: EnvironmentBooleanSchema, ORCA_RELAY_REGIONAL_PLACEMENT_ENABLED: EnvironmentBooleanSchema, + ORCA_RELAY_REGION_CORRECTION_COHORT_PERCENT: z.coerce.number().int().min(0).max(100).default(0), ORCA_RELAY_PUBLIC_ASSIGNMENT_CONCURRENCY: z.coerce.number().int().positive().max(100).default(2), ORCA_RELAY_PUBLIC_STICKY_CONCURRENCY: z.coerce.number().int().positive().max(100).default(1), ORCA_RELAY_PUBLIC_STICKY_QUEUE_MAX: z.coerce.number().int().positive().max(4_096).default(64), @@ -185,6 +189,7 @@ export type RelayConfig = { databasePoolMax: number publicAssignmentsEnabled: boolean regionalPlacementEnabled?: boolean + regionCorrectionCohortPercent?: number publicAssignmentConcurrency: number publicAssignmentQueueMax: number publicAssignmentWaitMs: number @@ -332,6 +337,7 @@ export function loadRelayConfig(env: NodeJS.ProcessEnv = process.env): RelayConf databasePoolMax, publicAssignmentsEnabled: parsed.ORCA_RELAY_PUBLIC_ASSIGNMENTS_ENABLED, regionalPlacementEnabled: parsed.ORCA_RELAY_REGIONAL_PLACEMENT_ENABLED, + regionCorrectionCohortPercent: parsed.ORCA_RELAY_REGION_CORRECTION_COHORT_PERCENT, publicAssignmentConcurrency: parsed.ORCA_RELAY_PUBLIC_ASSIGNMENT_CONCURRENCY, publicAssignmentQueueMax: parsed.ORCA_RELAY_PUBLIC_ASSIGNMENT_QUEUE_MAX, publicAssignmentWaitMs: parsed.ORCA_RELAY_PUBLIC_ASSIGNMENT_WAIT_MS, diff --git a/cloud/apps/relay/src/database.test.ts b/cloud/apps/relay/src/database.test.ts index 56122def4be..0c987f95d40 100644 --- a/cloud/apps/relay/src/database.test.ts +++ b/cloud/apps/relay/src/database.test.ts @@ -18,6 +18,34 @@ afterEach(() => { }) describe('relay database', () => { + it('upgrades an existing SQLite relay without treating legacy controls as idle-capable', async () => { + const dataDir = mkdtempSync(join(tmpdir(), 'orca-idle-schema-')) + temporaryDirectories.push(dataDir) + const legacy = await openRelayDatabase({ dataDir }) + await legacy.query('ALTER TABLE relay_control_capabilities DROP COLUMN idle_regional_rehome') + await legacy.query('ALTER TABLE relay_region_rehome_attempts DROP COLUMN source_generation') + await legacy.query( + `INSERT INTO relay_control_capabilities + (user_id, relay_host_id, activity_id, cell_id, cell_incarnation, assignment_epoch, generation, finish_existing) + VALUES ('legacy-user', 'abcdefghijklmnop', 'control:source:1', 'source', 'legacy-incarnation', 1, 1, 1)` + ) + await legacy.close() + const upgraded = await openRelayDatabase({ dataDir }) + try { + expect( + await upgraded.query('SELECT idle_regional_rehome FROM relay_control_capabilities') + ).toEqual([{ idle_regional_rehome: 0 }]) + const columns = await upgraded.query( + "SELECT * FROM pragma_table_info('relay_region_rehome_attempts')" + ) + expect(columns.find((column) => column.name === 'source_generation')).toMatchObject({ + dflt_value: '0' + }) + } finally { + await upgraded.close() + } + }) + it('creates every durable relay state table', async () => { const database = await openInMemoryRelayDatabase() const rows = await database.query( @@ -54,6 +82,7 @@ describe('relay database', () => { 'relay_confirm_results', 'relay_confirmable_splices', 'relay_connection_bases', + 'relay_control_capabilities', 'relay_control_connection_reservations', 'relay_devices', 'relay_direct_authorizations', @@ -62,6 +91,7 @@ describe('relay database', () => { 'relay_migration_leases', 'relay_post_drain_migration_pins', 'relay_rate_windows', + 'relay_region_decisions', 'relay_region_rehome_attempts', 'relay_region_rehome_control', 'relay_region_rehome_worker_state' @@ -140,9 +170,7 @@ describe('relay database', () => { const second = await openRelayDatabase({ dataDir }) expect( - await second.query(`SELECT region FROM relay_cell_regions WHERE cell_id = ?`, [ - 'legacy-cell' - ]) + await second.query(`SELECT region FROM relay_cell_regions WHERE cell_id = ?`, ['legacy-cell']) ).toEqual([{ region: 'us-central1' }]) await second.close() }) @@ -165,9 +193,7 @@ describe('relay database', () => { 'relay_region_rehome_attempts' ]) expect(checked.every((row) => String(row.sql).includes(list))).toBe(true) - expect( - POSTGRES_SCHEMA_MIGRATIONS.some((statement) => statement.includes(list)) - ).toBe(true) + expect(POSTGRES_SCHEMA_MIGRATIONS.some((statement) => statement.includes(list))).toBe(true) await database.close() }) diff --git a/cloud/apps/relay/src/database.ts b/cloud/apps/relay/src/database.ts index d51f4e7a423..41ead67ea60 100644 --- a/cloud/apps/relay/src/database.ts +++ b/cloud/apps/relay/src/database.ts @@ -197,6 +197,24 @@ CREATE TABLE IF NOT EXISTS relay_assignment_region_preferences ( CREATE INDEX IF NOT EXISTS relay_assignment_region_preferences_observed ON relay_assignment_region_preferences(observed_at); +CREATE TABLE IF NOT EXISTS relay_region_decisions ( + user_id TEXT NOT NULL, relay_host_id TEXT NOT NULL, + generation BIGINT NOT NULL, expires_at BIGINT NOT NULL, + assignment_epoch BIGINT NOT NULL, incumbent_region TEXT NOT NULL, + policy_version BIGINT NOT NULL, outcome TEXT NOT NULL, + cohort_bucket BIGINT NOT NULL DEFAULT 0, + last_considered_at BIGINT NOT NULL DEFAULT 0, + preferred_region TEXT, observed_at BIGINT NOT NULL, report_json TEXT, + PRIMARY KEY (user_id, relay_host_id) +); +CREATE TABLE IF NOT EXISTS relay_control_capabilities ( + user_id TEXT NOT NULL, relay_host_id TEXT NOT NULL, activity_id TEXT NOT NULL, + cell_id TEXT NOT NULL, cell_incarnation TEXT NOT NULL, + assignment_epoch BIGINT NOT NULL, generation BIGINT NOT NULL, + finish_existing BIGINT NOT NULL, + idle_regional_rehome BIGINT NOT NULL DEFAULT 0, + PRIMARY KEY (user_id, relay_host_id, activity_id) +); CREATE TABLE IF NOT EXISTS relay_region_rehome_worker_state ( worker_id TEXT PRIMARY KEY, next_dispatch_at BIGINT NOT NULL, @@ -228,6 +246,7 @@ CREATE TABLE IF NOT EXISTS relay_region_rehome_attempts ( CHECK (preferred_region IN (${REGION_LIST})), source_cell_id TEXT NOT NULL, source_cell_incarnation TEXT NOT NULL, + source_generation BIGINT NOT NULL DEFAULT 0, target_cell_id TEXT NOT NULL, target_cell_incarnation TEXT NOT NULL, previous_epoch BIGINT NOT NULL, @@ -600,6 +619,8 @@ CREATE INDEX IF NOT EXISTS relay_audit_events_at ON relay_audit_events(at); // auto-named; the replacement is named, so both statements are no-ops on a // database the current schema created and neither can drop the other. export const POSTGRES_SCHEMA_MIGRATIONS = [ + `ALTER TABLE relay_region_decisions ADD COLUMN IF NOT EXISTS last_considered_at BIGINT NOT NULL DEFAULT 0`, + `ALTER TABLE relay_region_decisions ADD COLUMN IF NOT EXISTS cohort_bucket BIGINT NOT NULL DEFAULT 0`, `ALTER TABLE relay_region_rehome_attempts DROP CONSTRAINT IF EXISTS relay_region_rehome_attempts_preferred_region_check`, `ALTER TABLE relay_region_rehome_attempts @@ -607,7 +628,9 @@ export const POSTGRES_SCHEMA_MIGRATIONS = [ CHECK (preferred_region IN (${REGION_LIST}))`, `ALTER TABLE relay_region_rehome_control ADD COLUMN IF NOT EXISTS host_cooldown_ms BIGINT NOT NULL - DEFAULT ${REGIONAL_REHOME_DEFAULT_HOST_COOLDOWN_MS}` + DEFAULT ${REGIONAL_REHOME_DEFAULT_HOST_COOLDOWN_MS}`, + `ALTER TABLE relay_control_capabilities ADD COLUMN IF NOT EXISTS idle_regional_rehome BIGINT NOT NULL DEFAULT 0`, + `ALTER TABLE relay_region_rehome_attempts ADD COLUMN IF NOT EXISTS source_generation BIGINT NOT NULL DEFAULT 0` ] function postgresSql(sql: string): string { @@ -1013,6 +1036,15 @@ async function applySchema(database: RelayDatabase): Promise { for (const statement of SCHEMA.split(';')) { if (statement.trim()) await database.query(statement) } + for (const [table, column] of [ + ['relay_control_capabilities', 'idle_regional_rehome'], + ['relay_region_rehome_attempts', 'source_generation'] + ]) { + const columns = await database.query('SELECT name FROM pragma_table_info(?)', [table]) + if (!columns.some((existing) => existing.name === column)) { + await database.query(`ALTER TABLE ${table} ADD COLUMN ${column} BIGINT NOT NULL DEFAULT 0`) + } + } } // Why: DDL is not a request. A CREATE INDEX on a grown table legitimately runs diff --git a/cloud/apps/relay/src/host-session-client-accept.test.ts b/cloud/apps/relay/src/host-session-client-accept.test.ts index 0cec6531e3f..04f86c533e4 100644 --- a/cloud/apps/relay/src/host-session-client-accept.test.ts +++ b/cloud/apps/relay/src/host-session-client-accept.test.ts @@ -155,6 +155,66 @@ describe('client accept abandoned mid-DB-phase', () => { vi.useRealTimers() }) + it('does not admit new source work after a drain crosses activity acquisition', async () => { + const h = harness() + const control = await activeHost(h) + const slow = deferred() + h.acquireActivity.mockReturnValueOnce(slow.promise) + const client = new FakeSocket() + const capacity = { bind: vi.fn(), release: vi.fn() } + const accepting = h.registry.acceptClient( + client as unknown as WebSocket, + identity.relayHostId, + 'credential', + capacity + ) + await vi.advanceTimersByTimeAsync(0) + h.registry.drainHost({ + attemptId: 'attempt', + userId: identity.sub, + relayHostId: identity.relayHostId, + sourceAssignmentEpoch: 1, + graceMs: 60_000 + }) + slow.resolve() + await accepting + expect(control.send).not.toHaveBeenCalledWith(expect.stringContaining('conn-open')) + expect(capacity.bind).not.toHaveBeenCalled() + expect(client.close).toHaveBeenCalledWith(RELAY_CLOSE_CODE.WRONG_CELL, expect.any(String)) + expect(h.releaseActivity).toHaveBeenCalled() + }) + + it('does not splice an attachment whose generation retired during basis persistence', async () => { + const h = harness() + await activeHost(h) + const client = new FakeSocket() + await h.registry.acceptClient( + client as unknown as WebSocket, + identity.relayHostId, + 'credential' + ) + const session = h.registry.get({ userId: identity.sub, relayHostId: identity.relayHostId })! + const pending = [...session.pendingConns.values()][0]! + const slow = deferred() + h.store.recordConnectionBasis.mockReturnValueOnce(slow.promise) + const host = new FakeSocket() + const attaching = h.registry.acceptHostData( + host as unknown as WebSocket, + pending.connId, + pending.connTicket, + 1 + ) + await vi.advanceTimersByTimeAsync(0) + h.registry.drain(0) + await vi.advanceTimersByTimeAsync(0) + slow.resolve() + expect(await attaching).toBe(false) + expect(session.activeSplices.size).toBe(0) + expect(h.store.deactivateBasis).toHaveBeenCalledWith(pending.connId) + expect(client.send).not.toHaveBeenCalledWith(expect.stringContaining('\"ok\":true')) + expect(host.close).toHaveBeenCalled() + }) + it('stops after a slow activity acquire when the phone already hung up', async () => { const h = harness() const control = await activeHost(h) @@ -390,6 +450,7 @@ describe('successful client accept timing', () => { relayHostIdDigest: string } expect(event.credentialKind).toBe('resume') + expect(event).toMatchObject({ assignmentEpoch: 1, controlGeneration: 1, drainMode: 'none' }) // Joins the line back to the emitting process, like the runtime metrics event. expect(event).toMatchObject({ role: 'cell', cellId: config.cellId, region: 'us-central1' }) expect(Object.keys(event.stageMs).sort()).toEqual([ @@ -460,6 +521,9 @@ describe('control round-trip sampling', () => { cellId: config.cellId, region: 'us-central1', rttMsMedian: 40, + assignmentEpoch: 1, + controlGeneration: 1, + drainMode: 'none', sampleCount: 4 }) expect(rttLines()[0]).not.toContain(identity.relayHostId) diff --git a/cloud/apps/relay/src/host-session-registry.test.ts b/cloud/apps/relay/src/host-session-registry.test.ts index 920faa6f4b8..dcfcd3f36c5 100644 --- a/cloud/apps/relay/src/host-session-registry.test.ts +++ b/cloud/apps/relay/src/host-session-registry.test.ts @@ -4,6 +4,7 @@ import { CONTROL_CONTINUITY_LIMITS, RELAY_CLOSE_CODE, RELAY_HOST_CAPABILITY_PENDING_CONN_DETAILS, + RELAY_HOST_CAPABILITY_IDLE_REGIONAL_REHOME, RELAY_PROTOCOL_LIMITS } from '@orca-cloud/relay-contract' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -140,7 +141,10 @@ function createRegistry( store as RelayCredentialStore, assignments, new ProcessQueuedByteBudget(), - observer + observer, + Date.now, + Math.random, + 'incarnation-1' ) // Mirrors the production signature exactly so a future positional shift fails to compile. const bound = ( @@ -166,7 +170,14 @@ function createRegistry( assignmentEpoch, appVersion = '1.4.173' ) => bound(socket, identity, existing, generation, rebind, assignmentEpoch, appVersion) - return { registry, activate, acquireActivity, renewControlActivity, releaseActivity, observer } + return { + registry, + activate, + acquireActivity, + renewControlActivity, + releaseActivity, + observer + } } describe('host session cleanup races', () => { @@ -398,26 +409,20 @@ describe('host session cleanup races', () => { attemptId: '22222222-2222-4222-8222-222222222222' }) ).toThrow('regional_rehome_attempt_conflict') - expect(() => - registry.drainHost({ ...request, sourceAssignmentEpoch: 8 }) - ).toThrow('regional_rehome_assignment_epoch_mismatch') + expect(() => registry.drainHost({ ...request, sourceAssignmentEpoch: 8 })).toThrow( + 'regional_rehome_assignment_epoch_mismatch' + ) const rebound = new FakeSocket() - await activate( - rebound as unknown as WebSocket, - identity, - registry.get(request), - 1, - true, - 7 - ) + await activate(rebound as unknown as WebSocket, identity, registry.get(request), 1, true, 7) expect(registry.get(request)?.state).toBe('drain-only') expect(rebound.send).toHaveBeenCalledWith(expect.stringContaining('"type":"drain"')) await vi.advanceTimersByTimeAsync(30_000) expect(registry.get(request)).toBeNull() - expect(registry.get({ userId: secondIdentity.sub, relayHostId: secondIdentity.relayHostId })) - .not.toBeNull() + expect( + registry.get({ userId: secondIdentity.sub, relayHostId: secondIdentity.relayHostId }) + ).not.toBeNull() expect(secondSocket.close).not.toHaveBeenCalled() }) @@ -513,14 +518,7 @@ describe('host session cleanup races', () => { expect(original).not.toBeNull() const rebindSocket = new FakeSocket() - const rebinding = activate( - rebindSocket as unknown as WebSocket, - identity, - original, - 1, - true, - 1 - ) + const rebinding = activate(rebindSocket as unknown as WebSocket, identity, original, 1, true, 1) rebindSocket.close() blocked.resolve('control:production-gce-c3:1') await rebinding @@ -659,14 +657,7 @@ describe('host session cleanup races', () => { originalSocket.close() const replacementSocket = new FakeSocket() - await activate( - replacementSocket as unknown as WebSocket, - identity, - original, - 2, - false, - 1 - ) + await activate(replacementSocket as unknown as WebSocket, identity, original, 2, false, 1) const replacement = registry.get({ userId: identity.sub, relayHostId: identity.relayHostId @@ -696,14 +687,7 @@ describe('host session cleanup races', () => { }) expect(original).not.toBeNull() - await activate( - new FakeSocket() as unknown as WebSocket, - identity, - original, - 2, - false, - 1 - ) + await activate(new FakeSocket() as unknown as WebSocket, identity, original, 2, false, 1) vi.advanceTimersByTime(15_000) expect(renewControlActivity).toHaveBeenCalledOnce() @@ -718,6 +702,53 @@ describe('host session cleanup races', () => { vi.advanceTimersByTime(0) }) + it('ignores a denial belonging to the socket before a same-generation rebind', async () => { + const h = createRegistry(vi.fn().mockResolvedValue('control:production-gce-c3:1')) + const oldSocket = new FakeSocket() + await h.activate(oldSocket as unknown as WebSocket, identity, null, 1, false, 1) + const session = h.registry.get({ userId: identity.sub, relayHostId: identity.relayHostId })! + let reject!: (error: Error) => void + h.renewControlActivity.mockReturnValueOnce( + new Promise((_, fail) => { + reject = fail + }) + ) + await vi.advanceTimersByTimeAsync(15_000) + const replacement = new FakeSocket() + await h.activate(replacement as unknown as WebSocket, identity, session, 1, true, 1) + reject(new Error('activity_cell_not_authoritative')) + await vi.advanceTimersByTimeAsync(0) + expect(replacement.close).not.toHaveBeenCalled() + expect(session.socket).toBe(replacement) + expect(session.generation).toBe(1) + }) + + it('ignores missing-activity recovery denial after an authority transition', async () => { + const h = createRegistry(vi.fn().mockResolvedValue('control:production-gce-c3:1')) + const socket = new FakeSocket() + await h.activate(socket as unknown as WebSocket, identity, null, 1, false, 1) + const session = h.registry.get({ userId: identity.sub, relayHostId: identity.relayHostId })! + h.renewControlActivity.mockRejectedValueOnce(new Error('control_activity_not_found')) + let reject!: (error: Error) => void + h.acquireActivity.mockReturnValueOnce( + new Promise((_, fail) => { + reject = fail + }) + ) + await vi.advanceTimersByTimeAsync(15_000) + h.registry.drainHost({ + attemptId: 'attempt', + userId: identity.sub, + relayHostId: identity.relayHostId, + sourceAssignmentEpoch: 1, + graceMs: 60_000 + }) + reject(new Error('activity_cell_not_authoritative')) + await vi.advanceTimersByTimeAsync(0) + expect(socket.close).not.toHaveBeenCalled() + expect(session.state).toBe('drain-only') + }) + it('keeps 15s pings while halving steady-state control renewals', async () => { const activateControl = vi .fn() @@ -732,9 +763,7 @@ describe('host session cleanup races', () => { socket.emit('message', Buffer.from(JSON.stringify({ type: 'pong' })), false) } - const pings = socket.send.mock.calls.filter((call) => - String(call[0]).includes('"ping"') - ) + const pings = socket.send.mock.calls.filter((call) => String(call[0]).includes('"ping"')) expect(pings).toHaveLength(4) expect(renewControlActivity).toHaveBeenCalledTimes(2) const firstExpiry = Number(renewControlActivity.mock.calls[0]![1].expiresAt) @@ -1118,3 +1147,277 @@ describe('host hello ack pending connections', () => { expect(rebound.pendingConns).toEqual([DETAILED_ENTRY]) }) }) + +describe('source-owned idle cutover', () => { + beforeEach(() => vi.useFakeTimers()) + afterEach(() => { + vi.clearAllTimers() + vi.useRealTimers() + }) + const request = { + attemptId: 'idle-1', + userId: identity.sub, + relayHostId: identity.relayHostId, + sourceAssignmentEpoch: 1, + sourceGeneration: 1, + sourceCellIncarnation: 'incarnation-1', + targetCellId: 'target' + } + async function source(store: Partial = {}) { + const h = createRegistry(vi.fn().mockResolvedValue('control:1'), store) + const socket = new FakeSocket() + h.registry.acceptControl( + socket as unknown as WebSocket, + identity, + undefined, + new Set([RELAY_HOST_CAPABILITY_IDLE_REGIONAL_REHOME]) + ) + socket.removeAllListeners('message') + await h.activate(socket as unknown as WebSocket, identity, null, 1, false, 1) + return { ...h, socket, session: h.registry.get(request)! } + } + it('keeps either established client busy until both actually leave', async () => { + const h = await source() + h.session.activeConnIds.add('phone') + h.session.activeConnIds.add('ipad') + const commit = vi.fn().mockResolvedValue({ outcome: 'committed' }) + h.session.activeConnIds.delete('ipad') + expect( + await h.registry.idleRehome(request, commit, vi.fn().mockResolvedValue('not-committed')) + ).toEqual({ outcome: 'busy' }) + expect(commit).not.toHaveBeenCalled() + h.session.activeConnIds.delete('phone') + expect( + await h.registry.idleRehome(request, commit, vi.fn().mockResolvedValue('not-committed')) + ).toEqual({ outcome: 'committed' }) + expect(h.socket.close).toHaveBeenCalledWith(RELAY_CLOSE_CODE.DRAINING, expect.any(String)) + expect(h.releaseActivity).toHaveBeenCalled() + }) + it.each([ + { userId: 'other-user' }, + { sourceAssignmentEpoch: 2 }, + { sourceGeneration: 2 }, + { sourceCellIncarnation: 'other-incarnation' }, + { targetCellId: 'other-target' } + ])('rejects a reused operation ID with changed authority %j', async (change) => { + const h = await source() + const result = deferred<{ outcome: 'deferred' }>() + const commit = vi.fn().mockReturnValue(result.promise) + const reconcile = vi.fn().mockResolvedValue('not-committed') + const moving = h.registry.idleRehome(request, commit, reconcile) + const conflicting = h.registry.idleRehome({ ...request, ...change }, commit, reconcile) + result.resolve({ outcome: 'deferred' }) + expect(await conflicting).toEqual({ outcome: 'stale' }) + expect(await moving).toEqual({ outcome: 'deferred' }) + expect(commit).toHaveBeenCalledOnce() + expect(h.socket.close).not.toHaveBeenCalled() + }) + it('accounts for accepts before credential identity resolves', async () => { + const lookup = deferred() + const h = await source({ + resolveResume: vi.fn().mockReturnValue(lookup.promise), + resolveInviteForMove: vi.fn().mockResolvedValue(null) + }) + const client = new FakeSocket() + const accept = h.registry.acceptClient( + client as unknown as WebSocket, + identity.relayHostId, + 'credential' + ) + expect( + await h.registry.idleRehome(request, vi.fn(), vi.fn().mockResolvedValue('not-committed')) + ).toEqual({ outcome: 'busy' }) + lookup.resolve(null) + await accept + expect(h.socket.close).not.toHaveBeenCalled() + }) + it('rejects new accepts and replacements synchronously while a commit awaits', async () => { + const h = await source() + const result = deferred<{ outcome: 'deferred' }>() + const commit = vi.fn().mockReturnValue(result.promise) + const moving = h.registry.idleRehome( + request, + commit, + vi.fn().mockResolvedValue('not-committed') + ) + const duplicate = h.registry.idleRehome( + request, + commit, + vi.fn().mockResolvedValue('not-committed') + ) + const client = new FakeSocket() + const release = vi.fn() + await h.registry.acceptClient( + client as unknown as WebSocket, + identity.relayHostId, + 'credential', + { release } as never + ) + expect(client.close).toHaveBeenCalledWith(RELAY_CLOSE_CODE.WRONG_CELL, expect.any(String)) + expect(release).toHaveBeenCalledOnce() + const replacement = new FakeSocket() + await h.activate(replacement as unknown as WebSocket, identity, h.session, 2, false, 1) + expect(replacement.close).toHaveBeenCalledWith(RELAY_CLOSE_CODE.WRONG_CELL, expect.any(String)) + result.resolve({ outcome: 'deferred' }) + await moving + await duplicate + expect(commit).toHaveBeenCalledOnce() + expect(h.socket.close).not.toHaveBeenCalled() + expect( + await h.registry.idleRehome( + { ...request, attemptId: 'next' }, + vi.fn().mockResolvedValue({ outcome: 'committed' }), + vi.fn().mockResolvedValue('not-committed') + ) + ).toEqual({ outcome: 'committed' }) + }) + it.each(['ambiguous', 'deferred'])( + 'keeps %s outcomes fenced until locked reconciliation succeeds', + async (claim) => { + const h = await source() + const reconcile = vi + .fn() + .mockRejectedValueOnce(new Error('database unavailable')) + .mockRejectedValueOnce(new Error('database unavailable')) + .mockResolvedValue('not-committed') + const moving = h.registry.idleRehome( + request, + claim === 'ambiguous' + ? vi.fn().mockRejectedValue(new Error('lost commit reply')) + : vi.fn().mockResolvedValue({ outcome: 'deferred' }), + reconcile + ) + await vi.advanceTimersByTimeAsync(50) + expect( + await h.registry.idleRehome( + { ...request, attemptId: 'other' }, + vi.fn(), + vi.fn().mockResolvedValue('not-committed') + ) + ).toEqual({ outcome: 'busy' }) + expect(h.socket.close).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(300) + expect(await moving).toEqual({ outcome: 'deferred' }) + expect(reconcile).toHaveBeenCalledTimes(3) + expect(h.socket.close).not.toHaveBeenCalled() + } + ) + it('owns accepted control mutations before the handler first awaits', async () => { + const mutation = deferred() + const h = await source() + ;(h.registry as unknown as { verifyRelayToken: unknown }).verifyRelayToken = vi + .fn() + .mockReturnValue(mutation.promise) + h.socket.emit( + 'message', + Buffer.from(JSON.stringify({ type: 'auth-refresh', relayJwt: 'token' })), + false + ) + const commit = vi.fn().mockResolvedValue({ outcome: 'deferred' }) + expect( + await h.registry.idleRehome(request, commit, vi.fn().mockResolvedValue('not-committed')) + ).toEqual({ outcome: 'busy' }) + mutation.resolve(identity) + await vi.advanceTimersByTimeAsync(0) + expect( + await h.registry.idleRehome(request, commit, vi.fn().mockResolvedValue('not-committed')) + ).toEqual({ outcome: 'deferred' }) + }) + it('owns queued replacement activation before its first persistence await', async () => { + const h = await source() + const activation = deferred() + const assignments = (h.registry as unknown as { assignments: { activateControl: unknown } }) + .assignments + assignments.activateControl = vi.fn().mockReturnValue(activation.promise) + const replacement = new FakeSocket() + const activating = h.activate( + replacement as unknown as WebSocket, + identity, + h.session, + 2, + false, + 1 + ) + expect( + await h.registry.idleRehome(request, vi.fn(), vi.fn().mockResolvedValue('not-committed')) + ).toEqual({ outcome: 'busy' }) + activation.resolve('control:2') + await activating + }) + it('retires changed authority even when the claim definitively deferred', async () => { + const h = await source() + expect( + await h.registry.idleRehome( + request, + vi.fn().mockResolvedValue({ outcome: 'deferred' }), + vi.fn().mockResolvedValue('stale') + ) + ).toEqual({ outcome: 'stale' }) + expect(h.session.state).toBe('closed') + expect(h.releaseActivity).toHaveBeenCalled() + }) + it('holds attach ownership through basis failure reservation cleanup', async () => { + const basis = deferred() + const cleanup = deferred() + const h = await source({ + recordConnectionBasis: vi.fn().mockImplementation(async () => { + await basis.promise + throw new Error('basis failed') + }), + failReservation: vi.fn().mockReturnValue(cleanup.promise) + }) + const client = new FakeSocket() + h.session.pendingConns.set('conn', { + connId: 'conn', + connTicket: 'ticket', + client: client as unknown as WebSocket, + reservation: { + userId: identity.sub, + relayHostId: identity.relayHostId, + credentialKind: 'invite', + leaseExpiresAt: Date.now() + 1000 + }, + attachTimer: setTimeout(() => {}, 1000), + credentialActivityId: null + } as never) + const attached = h.registry.acceptHostData( + new FakeSocket() as unknown as WebSocket, + 'conn', + 'ticket', + 1 + ) + const commit = vi.fn().mockResolvedValue({ outcome: 'deferred' }) + expect(await h.registry.idleRehome(request, commit, vi.fn())).toEqual({ outcome: 'busy' }) + basis.resolve() + await vi.advanceTimersByTimeAsync(0) + expect(h.session.activeConnIds.size).toBe(0) + expect(await h.registry.idleRehome(request, commit, vi.fn())).toEqual({ outcome: 'busy' }) + expect(commit).not.toHaveBeenCalled() + cleanup.resolve() + await attached + }) + it('returns the durable operation outcome after source retirement', async () => { + const h = await source() + const commit = vi.fn().mockResolvedValue({ outcome: 'committed' }) + await h.registry.idleRehome(request, commit, vi.fn()) + expect( + await h.registry.idleRehome(request, commit, vi.fn().mockResolvedValue('committed')) + ).toEqual({ outcome: 'committed' }) + expect(commit).toHaveBeenCalledOnce() + }) + it('does not reopen a source overtaken by emergency drain', async () => { + const h = await source() + const result = deferred<{ outcome: 'deferred' }>() + const moving = h.registry.idleRehome( + request, + () => result.promise, + vi.fn().mockResolvedValue('not-committed') + ) + h.registry.drain(0) + await vi.advanceTimersByTimeAsync(0) + result.resolve({ outcome: 'deferred' }) + await moving + expect(h.session.state).toBe('closed') + expect(h.registry.get(request)).toBeNull() + }) +}) diff --git a/cloud/apps/relay/src/host-session-registry.ts b/cloud/apps/relay/src/host-session-registry.ts index 3b4e616a692..61a1b706fa9 100644 --- a/cloud/apps/relay/src/host-session-registry.ts +++ b/cloud/apps/relay/src/host-session-registry.ts @@ -15,6 +15,7 @@ import { HostHelloSchema, InviteCreateSchema, RELAY_HOST_CAPABILITY_PENDING_CONN_DETAILS, + RELAY_HOST_CAPABILITY_IDLE_REGIONAL_REHOME, RELAY_PROTOCOL_LIMITS, RELAY_CLOSE_CODE, type RelayHostCloseReason, @@ -25,10 +26,7 @@ import type WebSocket from 'ws' import type { RawData } from 'ws' import type { RelayConfig } from './config.js' import type { RelayAssignmentStore } from './assignment-store.js' -import { - RelayCredentialStore, - type CredentialReservation -} from './credential-store.js' +import { RelayCredentialStore, type CredentialReservation } from './credential-store.js' import { HostCloseReasonMemory } from './host-close-reason-memory.js' import { relayHostLogDigest } from './relay-host-log-digest.js' import type { RelayTokenClaims } from './relay-token-verifier.js' @@ -78,7 +76,7 @@ export type HostSession = { identity: RelayTokenClaims readonly relayHostId: string readonly generation: number - readonly assignmentEpoch: number + assignmentEpoch: number readonly controlActivityId: string | null readonly controlResumeSecret: string // Why: reconnect churn is only actionable once it can be pinned to a client build. @@ -94,6 +92,7 @@ export type HostSession = { pendingPingAt: number | null controlRttSamplesMs: number[] controlRttLoggedAt: number | null + authorityRevision: number activityRenewalDueAt: number activityRenewalAttempt: number activityRenewalCompletedAttempt: number @@ -108,10 +107,7 @@ export type HostSession = { regionalDrainExpiresAt: number | null } -export type RegionalHostDrainOutcome = - | 'accepted' - | 'already-accepted' - | 'host-not-connected' +export type RegionalHostDrainOutcome = 'accepted' | 'already-accepted' | 'host-not-connected' type PendingConnection = { connId: string @@ -184,6 +180,113 @@ export class HostSessionRegistry { private readonly hostCapabilities = new WeakMap>() private draining = false + private readonly idleWork = new Map() + private readonly idleAttempts = new Map< + string, + { + attemptId: string + authorityKey: string + promise: Promise<{ outcome: 'committed' | 'deferred' | 'stale' }> + } + >() + + async idleRehome( + input: { + attemptId: string + userId: string + relayHostId: string + sourceAssignmentEpoch: number + sourceGeneration: number + sourceCellIncarnation: string + targetCellId: string + }, + commit: () => Promise<{ outcome: 'committed' | 'deferred' | 'stale' }>, + reconcile: () => Promise<'committed' | 'not-committed' | 'stale'> + ): Promise<{ outcome: 'busy' | 'committed' | 'deferred' | 'stale' }> { + const authorityKey = JSON.stringify([ + input.userId, + input.sourceAssignmentEpoch, + input.sourceGeneration, + input.sourceCellIncarnation, + input.targetCellId + ]) + const prior = this.idleAttempts.get(input.relayHostId) + if (prior) { + if (prior.attemptId !== input.attemptId) return { outcome: 'busy' } + return prior.authorityKey === authorityKey ? prior.promise : { outcome: 'stale' } + } + const session = this.get(input) + if ( + this.draining || + !session || + session.state !== 'active' || + session.generation !== input.sourceGeneration || + session.assignmentEpoch !== input.sourceAssignmentEpoch || + this.cellIncarnation !== input.sourceCellIncarnation + ) { + const durable = await reconcile() + return { outcome: durable === 'committed' ? 'committed' : 'stale' } + } + if ( + !session.socket || + !this.hostCapabilities.get(session.socket)?.has(RELAY_HOST_CAPABILITY_IDLE_REGIONAL_REHOME) + ) + return { outcome: 'deferred' } + if ( + (this.idleWork.get(input.relayHostId) ?? 0) !== 0 || + session.activeConnIds.size !== 0 || + session.activeSplices.size !== 0 || + session.pendingConns.size !== 0 + ) + return { outcome: 'busy' } + const revision = session.authorityRevision + const promise = Promise.resolve().then(async () => { + let outcome: 'committed' | 'deferred' | 'stale' + try { + outcome = (await commit()).outcome + if (outcome === 'deferred') { + const durable = await reconcile() + outcome = durable === 'not-committed' ? 'deferred' : durable + } + } catch { + let delay = 100 + for (;;) { + try { + const durable = await reconcile() + outcome = durable === 'not-committed' ? 'deferred' : durable + break + } catch { + await new Promise((resolve) => { + const timer = setTimeout(resolve, delay) + timer.unref?.() + }) + delay = Math.min(delay * 2, 5000) + } + } + } + if (this.get(input) === session) { + if (outcome !== 'deferred' || this.draining || session.authorityRevision !== revision) { + this.closeDrainedSession(session) + } + } + if (this.idleAttempts.get(input.relayHostId)?.promise === promise) + this.idleAttempts.delete(input.relayHostId) + return { outcome } + }) + this.idleAttempts.set(input.relayHostId, { attemptId: input.attemptId, authorityKey, promise }) + return promise + } + + private beginIdleWork(hostId: string): (() => void) | null { + if (this.idleAttempts.has(hostId)) return null + this.idleWork.set(hostId, (this.idleWork.get(hostId) ?? 0) + 1) + return () => { + const remaining = (this.idleWork.get(hostId) ?? 1) - 1 + if (remaining === 0) this.idleWork.delete(hostId) + else this.idleWork.set(hostId, remaining) + } + } + constructor( private readonly config: RelayConfig, private readonly verifyRelayToken: VerifyRelayToken, @@ -192,7 +295,8 @@ export class HostSessionRegistry { private readonly queuedByteBudget: ProcessQueuedByteBudget, private readonly observer: RelayRuntimeObserver, private readonly now: () => number = Date.now, - private readonly random: () => number = Math.random + private readonly random: () => number = Math.random, + private readonly cellIncarnation?: string ) {} // Uniform over [CONTROL_LEASE_MS - jitter, CONTROL_LEASE_MS + jitter). @@ -206,6 +310,25 @@ export class HostSessionRegistry { hostId: string, credential: string, capacityReservation?: PendingHostDataReservation + ): Promise { + const release = this.beginIdleWork(hostId) + if (!release) { + capacityReservation?.release() + this.rejectClient(socket, RELAY_CLOSE_CODE.WRONG_CELL) + return + } + try { + await this.acceptClientUnfenced(socket, hostId, credential, capacityReservation) + } finally { + release() + } + } + + private async acceptClientUnfenced( + socket: WebSocket, + hostId: string, + credential: string, + capacityReservation?: PendingHostDataReservation ): Promise { if (this.draining) { capacityReservation?.release() @@ -295,6 +418,7 @@ export class HostSessionRegistry { this.rejectClient(socket, RELAY_CLOSE_CODE.LIMIT_EXCEEDED) return } + const admittingSocket = session.socket const connId = randomUUID() const connTicket = randomBytes(32).toString('base64url') const identity = { userId: reservation.userId, relayHostId: hostId } @@ -324,6 +448,20 @@ export class HostSessionRegistry { ) { return } + // Admission may have crossed a drain or control replacement while persisting activity. + if ( + this.draining || + this.sessions.get(sessionKey) !== session || + session.state !== 'active' || + session.socket !== admittingSocket || + admittingSocket.readyState !== admittingSocket.OPEN + ) { + capacityReservation?.release() + this.failReservationBestEffort(reservation) + if (credentialActivityId) this.releaseActivityBestEffort(identity, credentialActivityId) + this.rejectClient(socket, RELAY_CLOSE_CODE.WRONG_CELL) + return + } markStage('activity') const attachTimer = setTimeout(() => { session.pendingConns.delete(connId) @@ -372,6 +510,27 @@ export class HostSessionRegistry { connId: string, connTicket: string, generation: number + ): Promise { + const owner = [...this.sessions.values()].find((candidate) => + candidate.pendingConns.has(connId) + ) + const release = owner ? this.beginIdleWork(owner.relayHostId) : () => {} + if (!release) { + socket.close(RELAY_CLOSE_CODE.WRONG_CELL, 'idle cutover in progress') + return false + } + try { + return await this.acceptHostDataUnfenced(socket, connId, connTicket, generation) + } finally { + release() + } + } + + private async acceptHostDataUnfenced( + socket: WebSocket, + connId: string, + connTicket: string, + generation: number ): Promise { const session = [...this.sessions.values()].find((candidate) => candidate.pendingConns.has(connId) @@ -427,6 +586,27 @@ export class HostSessionRegistry { socket.close(RELAY_CLOSE_CODE.LIMIT_EXCEEDED, 'basis persistence failed') return false } + // Already admitted attachments may finish a regional drain, but never a retired generation. + if ( + this.draining || + this.sessions.get(this.key(identity.userId, identity.relayHostId)) !== session || + this.get(identity)?.state === 'closed' || + !session.activeConnIds.has(connId) || + socket.readyState !== socket.OPEN || + pending.client.readyState !== pending.client.OPEN + ) { + session.activeConnIds.delete(connId) + pending.capacityReservation?.release() + this.deactivateBasisBestEffort(connId) + this.failReservationBestEffort(pending.reservation) + if (spliceActivityId) this.releaseActivityBestEffort(identity, spliceActivityId) + if (pending.credentialActivityId) { + this.releaseActivityBestEffort(identity, pending.credentialActivityId) + } + this.rejectClient(pending.client, RELAY_CLOSE_CODE.DRAINING) + socket.close(RELAY_CLOSE_CODE.DRAINING, 'host retired during attachment') + return false + } const close = wireSplice({ client: pending.client, host: socket, @@ -505,6 +685,7 @@ export class HostSessionRegistry { JSON.stringify({ event: 'orca_relay_client_accept_completed', ...this.logIdentity(), + ...this.sessionPlacementLogFields(session), credentialKind: pending.reservation.credentialKind, stageMs, totalMs, @@ -513,6 +694,14 @@ export class HostSessionRegistry { ) } + private sessionPlacementLogFields(session: HostSession) { + return { + assignmentEpoch: session.assignmentEpoch, + controlGeneration: session.generation, + drainMode: session.regionalDrainAttemptId ? 'deadline' : 'none' + } + } + // Matches the runtime metrics event so a log line and a metric point can be // joined back to the process that emitted them. private logIdentity(): { role: string; cellId: string; region: RelayRegion } { @@ -549,6 +738,7 @@ export class HostSessionRegistry { JSON.stringify({ event: 'orca_relay_host_control_rtt', ...this.logIdentity(), + ...this.sessionPlacementLogFields(session), relayHostIdDigest: relayHostLogDigest(session.relayHostId), rttMsMedian: percentile(samples, 0.5), sampleCount: samples.length @@ -562,6 +752,10 @@ export class HostSessionRegistry { connectionInclusionWatermark?: number, hostCapabilities?: ReadonlySet ): void { + if (this.idleAttempts.has(identity.relayHostId)) { + socket.close(RELAY_CLOSE_CODE.WRONG_CELL, 'idle cutover in progress') + return + } // Keyed by socket, not session: a rebind swaps the session's socket, and the // successor's own advertisement is the only one that describes its decoder. if (hostCapabilities?.size) this.hostCapabilities.set(socket, hostCapabilities) @@ -602,8 +796,7 @@ export class HostSessionRegistry { socket: WebSocket | null, context: string ): void { - void Promise.resolve() - .then(task) + void (async () => task())() .catch((error: unknown) => { const message = (error instanceof Error ? error.message : 'unknown') // Untruncated, unlike peer-supplied close reasons: this is the @@ -653,6 +846,7 @@ export class HostSessionRegistry { this.draining = true for (const session of this.sessions.values()) { if (session.state === 'closed') continue + session.authorityRevision += 1 session.state = 'drain-only' if (session.socket) send(session.socket, 'drain', { graceMs, recovery: 'resolve-director' }) setTimeout(() => this.closeDrainedSession(session), graceMs) @@ -665,7 +859,8 @@ export class HostSessionRegistry { relayHostId: string sourceAssignmentEpoch: number graceMs: number - }): RegionalHostDrainOutcome { + sourceCellIncarnation?: string + }): RegionalHostDrainOutcome | Promise { const session = this.get(input) if (!session || session.state === 'closed') return 'host-not-connected' if (session.assignmentEpoch !== input.sourceAssignmentEpoch) { @@ -678,13 +873,11 @@ export class HostSessionRegistry { this.reassertRegionalDrain(session) return 'already-accepted' } + session.authorityRevision += 1 session.regionalDrainAttemptId = input.attemptId session.regionalDrainExpiresAt = this.now() + input.graceMs this.reassertRegionalDrain(session) - session.regionalDrainTimer = setTimeout( - () => this.closeDrainedSession(session), - input.graceMs - ) + session.regionalDrainTimer = setTimeout(() => this.closeDrainedSession(session), input.graceMs) return 'accepted' } @@ -740,9 +933,9 @@ export class HostSessionRegistry { const existing = this.sessions.get(key) const rebind = Boolean( existing && - hello.data.controlResumeSecret && - hello.data.controlResumeSecret === existing.controlResumeSecret && - (existing.state === 'orphaned' || existing.state === 'active') + hello.data.controlResumeSecret && + hello.data.controlResumeSecret === existing.controlResumeSecret && + (existing.state === 'orphaned' || existing.state === 'active') ) const generation = rebind ? existing!.generation : (existing?.generation ?? 0) + 1 const ephemeral = nacl.box.keyPair() @@ -784,7 +977,9 @@ export class HostSessionRegistry { }, 10_000) socket.once('message', (raw, isBinary) => { clearTimeout(proofTimer) - const ack = isBinary ? null : HostChallengeAckSchema.safeParse(payload(raw, 'host-challenge-ack')) + const ack = isBinary + ? null + : HostChallengeAckSchema.safeParse(payload(raw, 'host-challenge-ack')) const proof = ack?.success ? decodeCanonicalBase64(ack.data.proofB64, 32) : null if ( !ack?.success || @@ -826,6 +1021,11 @@ export class HostSessionRegistry { appVersion: string, connectionInclusionWatermark?: number ): Promise { + const release = this.beginIdleWork(identity.relayHostId) + if (!release) { + socket.close(RELAY_CLOSE_CODE.WRONG_CELL, 'idle cutover in progress') + return Promise.resolve() + } const key = this.key(identity.sub, identity.relayHostId) const previous = this.activationQueues.get(key) ?? Promise.resolve() // The timeout only fails this waiting socket; the queue entry still chains @@ -836,26 +1036,29 @@ export class HostSessionRegistry { socket.close(RELAY_CLOSE_CODE.LIMIT_EXCEEDED, 'control activation queue stalled') }, ACTIVATION_QUEUE_WAIT_MS) queueWaitTimer.unref?.() - const activation = previous.catch(() => undefined).then(async () => { - clearTimeout(queueWaitTimer) - if (queueWaitExpired) return - if ((this.sessions.get(key) ?? null) !== existing) { - socket.close(RELAY_CLOSE_CODE.PEER_DROPPED, 'control activation superseded') - return - } - await this.activateCurrent( - socket, - identity, - existing, - generation, - rebind, - assignmentEpoch, - appVersion, - connectionInclusionWatermark - ) - }) + const activation = previous + .catch(() => undefined) + .then(async () => { + clearTimeout(queueWaitTimer) + if (queueWaitExpired) return + if ((this.sessions.get(key) ?? null) !== existing) { + socket.close(RELAY_CLOSE_CODE.PEER_DROPPED, 'control activation superseded') + return + } + await this.activateCurrent( + socket, + identity, + existing, + generation, + rebind, + assignmentEpoch, + appVersion, + connectionInclusionWatermark + ) + }) this.activationQueues.set(key, activation) const cleanup = (): void => { + release() if (this.activationQueues.get(key) === activation) this.activationQueues.delete(key) } void activation.then(cleanup, cleanup) @@ -881,7 +1084,11 @@ export class HostSessionRegistry { cellId: this.config.cellId, assignmentEpoch, generation, - connectionInclusionWatermark + connectionInclusionWatermark, + idleRegionalRehome: + this.hostCapabilities.get(socket)?.has(RELAY_HOST_CAPABILITY_IDLE_REGIONAL_REHOME) ?? + false, + cellIncarnation: this.cellIncarnation } ) await this.assignments.markMigrationTargetRegistered( @@ -918,14 +1125,15 @@ export class HostSessionRegistry { const previousSocket = existing.socket if (existing.orphanTimer) clearTimeout(existing.orphanTimer) existing.orphanTimer = null + existing.authorityRevision += 1 + existing.assignmentEpoch = assignmentEpoch existing.socket = socket existing.state = existing.regionalDrainAttemptId ? 'drain-only' : 'active' existing.appVersion = appVersion existing.leaseExpiresAt = this.controlLeaseExpiresAt() existing.lastPongAt = this.now() existing.pendingPingAt = null - existing.activityRenewalDueAt = - this.now() + RELAY_PROTOCOL_LIMITS.controlPingIntervalMs + existing.activityRenewalDueAt = this.now() + RELAY_PROTOCOL_LIMITS.controlPingIntervalMs this.wireActiveControl(existing) this.sendHelloAck(existing) if (existing.regionalDrainAttemptId) this.reassertRegionalDrain(existing) @@ -980,6 +1188,7 @@ export class HostSessionRegistry { pendingPingAt: null, controlRttSamplesMs: [], controlRttLoggedAt: null, + authorityRevision: 0, activityRenewalDueAt: this.now() + RELAY_PROTOCOL_LIMITS.controlPingIntervalMs, activityRenewalAttempt: 0, activityRenewalCompletedAttempt: 0, @@ -1028,7 +1237,9 @@ export class HostSessionRegistry { ` splices=${session.closingCounts?.splices ?? session.activeSplices.size}` + ` pending=${session.closingCounts?.pending ?? session.pendingConns.size}` + ` code=${code} reason=${JSON.stringify(printableCloseReason(reason))}` + - (socketError === null ? '' : ` error=${JSON.stringify(printableCloseReason(socketError))}`) + (socketError === null + ? '' + : ` error=${JSON.stringify(printableCloseReason(socketError))}`) ) }) socket.on('message', (raw, isBinary) => { @@ -1077,6 +1288,19 @@ export class HostSessionRegistry { } private async acceptRefresh(session: HostSession, raw: RawData): Promise { + const release = this.beginIdleWork(session.relayHostId) + if (!release) { + session.socket?.close(RELAY_CLOSE_CODE.DRAINING, 'resolve-director') + return + } + try { + await this.acceptRefreshUnfenced(session, raw) + } finally { + release() + } + } + + private async acceptRefreshUnfenced(session: HostSession, raw: RawData): Promise { const parsed = AuthRefreshSchema.safeParse(payload(raw, 'auth-refresh')) if (!parsed.success) return const refreshed = await this.verifyRelayToken(parsed.data.relayJwt) @@ -1107,6 +1331,16 @@ export class HostSessionRegistry { if (controlActivityId && now >= session.activityRenewalDueAt) { const attempt = ++session.activityRenewalAttempt const startedAt = now + const socket = session.socket + const authorityRevision = session.authorityRevision + const current = (): boolean => + this.sessions.get(key) === session && + session.state !== 'closed' && + session.socket === socket && + socket.readyState === socket.OPEN && + session.controlActivityId === controlActivityId && + session.authorityRevision === authorityRevision && + attempt > session.activityRenewalCompletedAttempt void this.assignments .renewControlActivity( { userId: session.identity.sub, relayHostId: session.relayHostId }, @@ -1117,11 +1351,16 @@ export class HostSessionRegistry { } ) .then(() => { - if (attempt <= session.activityRenewalCompletedAttempt) return + if (!current()) return session.activityRenewalCompletedAttempt = attempt session.activityRenewalDueAt = startedAt + CONTROL_ACTIVITY_RENEWAL_INTERVAL_MS }) .catch(async (error: unknown) => { + if (!current()) return + if (error instanceof Error && error.message === 'assignment_not_found') { + socket.close(RELAY_CLOSE_CODE.DRAINING, 'control assignment missing') + return + } if (error instanceof Error && error.message === 'activity_cell_not_authoritative') { // Completion fences a late drain-only heartbeat after all source work is gone. session.socket?.close(RELAY_CLOSE_CODE.DRAINING, 'control migration completed') @@ -1144,8 +1383,22 @@ export class HostSessionRegistry { cellId: this.config.cellId } ) + if (!current()) { + // A replaced activity must not remain leased after its owner disappears. + if ( + !this.sessions.get(key) || + this.sessions.get(key)?.controlActivityId !== controlActivityId + ) { + this.releaseActivityBestEffort( + { userId: session.identity.sub, relayHostId: session.relayHostId }, + controlActivityId + ) + } + return + } this.observer.recordControlActivityRecovery?.(true) } catch (acquireError: unknown) { + if (!current()) return this.observer.recordControlActivityRecovery?.(false) if ( acquireError instanceof Error && @@ -1218,6 +1471,21 @@ export class HostSessionRegistry { private closeDrainedSession(session: HostSession): void { if (session.state === 'closed') return + const forcedConnections = session.activeConnIds.size + session.pendingConns.size + if (forcedConnections > 0) { + console.warn( + JSON.stringify({ + event: 'orca_relay_host_drain_forced_close', + ...this.logIdentity(), + ...this.sessionPlacementLogFields(session), + relayHostIdDigest: relayHostLogDigest(session.relayHostId), + reason: this.draining ? 'emergency' : 'regional-deadline', + forcedConnections, + splices: session.activeSplices.size, + pending: session.pendingConns.size + }) + ) + } if (session.heartbeatTimer) clearInterval(session.heartbeatTimer) if (session.orphanTimer) clearTimeout(session.orphanTimer) if (session.regionalDrainTimer) clearTimeout(session.regionalDrainTimer) @@ -1250,11 +1518,7 @@ export class HostSessionRegistry { session.pendingConns.clear() session.state = 'closed' if (session.socket) { - closeRelayWebSocket( - session.socket, - RELAY_CLOSE_CODE.DRAINING, - 'resolve configured director' - ) + closeRelayWebSocket(session.socket, RELAY_CLOSE_CODE.DRAINING, 'resolve configured director') } const key = this.key(session.identity.sub, session.relayHostId) if (this.sessions.get(key) === session) this.sessions.delete(key) @@ -1278,6 +1542,23 @@ export class HostSessionRegistry { session: HostSession, type: unknown, raw: RawData + ): Promise { + const release = this.beginIdleWork(session.relayHostId) + if (!release) { + session.socket?.close(RELAY_CLOSE_CODE.DRAINING, 'resolve-director') + return + } + try { + await this.acceptControlCommandUnfenced(session, type, raw) + } finally { + release() + } + } + + private async acceptControlCommandUnfenced( + session: HostSession, + type: unknown, + raw: RawData ): Promise { if (typeof type !== 'string' || !session.socket) return try { @@ -1315,10 +1596,7 @@ export class HostSessionRegistry { } if (type === 'device-credential-install') { const request = DeviceCredentialInstallSchema.parse(payload(raw, type)) - if ( - session.state !== 'active' && - request.authorization.mode === 'authenticated-direct' - ) { + if (session.state !== 'active' && request.authorization.mode === 'authenticated-direct') { throw new Error('authorization_expired') } const installActivityId = `install:${request.reqId}` diff --git a/cloud/apps/relay/src/idle-regional-rehome-reconciliation.test.ts b/cloud/apps/relay/src/idle-regional-rehome-reconciliation.test.ts new file mode 100644 index 00000000000..6fc2017ab48 --- /dev/null +++ b/cloud/apps/relay/src/idle-regional-rehome-reconciliation.test.ts @@ -0,0 +1,103 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { RelayAssignmentStore } from './assignment-store.js' +import type { RelayDatabase } from './database.js' +import { openIdleRehomeTestDatabase } from './idle-regional-rehome-test-database.js' + +const request = { + v: 1 as const, + attemptId: '33333333-3333-4333-8333-333333333333', + userId: 'idle-reconciliation-test', + relayHostId: 'abcdefghijklmnop', + sourceCellId: 'source', + sourceCellIncarnation: '11111111-1111-4111-8111-111111111111', + sourceAssignmentEpoch: 1, + sourceGeneration: 7, + targetCellId: 'target' +} +const databases: RelayDatabase[] = [] +afterEach(async () => { + vi.restoreAllMocks() + for (const database of databases.splice(0)) await database.close() +}) + +async function setup() { + const database = await openIdleRehomeTestDatabase() + databases.push(database) + const store = new RelayAssignmentStore(database, () => 100_000_000) + await store.reconcileCells([ + { id: 'source', url: 'https://source.example.test', capacityRequests: 100 }, + { id: 'target', url: 'https://target.example.test', capacityRequests: 100 } + ]) + await store.assign(request) + await store.activateControl(request, { + cellId: request.sourceCellId, + assignmentEpoch: request.sourceAssignmentEpoch, + generation: request.sourceGeneration, + cellIncarnation: request.sourceCellIncarnation + }) + return { database, store } +} + +describe('idle cutover durable reconciliation', () => { + it('only permits reopening when the exact source still owns the assignment', async () => { + const { store } = await setup() + expect(await store.reconcileIdleRegionalRehome(request)).toBe('not-committed') + await store.activateControl(request, { + cellId: request.sourceCellId, + assignmentEpoch: request.sourceAssignmentEpoch, + generation: request.sourceGeneration + 1, + cellIncarnation: request.sourceCellIncarnation + }) + expect(await store.reconcileIdleRegionalRehome(request)).toBe('stale') + }) + + it('does not reopen an obsolete source after an assignment change', async () => { + const { store } = await setup() + await store.startEvacuation(request, request.targetCellId) + expect(await store.reconcileIdleRegionalRehome(request)).toBe('stale') + }) + + it('propagates unavailable durable state instead of declaring rollback', async () => { + const { database, store } = await setup() + vi.spyOn(database, 'transaction').mockRejectedValue(new Error('database_unavailable')) + await expect(store.reconcileIdleRegionalRehome(request)).rejects.toThrow('database_unavailable') + }) + + it('waits for an outstanding assignment transaction before deciding authority', async () => { + const { database, store } = await setup() + let release!: () => void + let entered!: () => void + const locked = new Promise((resolve) => { + entered = resolve + }) + const gate = new Promise((resolve) => { + release = resolve + }) + const commit = database.transaction(async (transaction) => { + await transaction.queryLocked( + 'SELECT * FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?', + [request.userId, request.relayHostId] + ) + entered() + await gate + await transaction.query( + 'UPDATE relay_assignments SET assignment_epoch = assignment_epoch + 1 WHERE user_id = ? AND relay_host_id = ?', + [request.userId, request.relayHostId] + ) + }) + await locked + let settled = false + const reconciliation = store.reconcileIdleRegionalRehome(request).finally(() => { + settled = true + }) + try { + await new Promise((resolve) => setImmediate(resolve)) + expect(settled).toBe(false) + } finally { + release() + await commit + await reconciliation + } + expect(await reconciliation).toBe('stale') + }) +}) diff --git a/cloud/apps/relay/src/idle-regional-rehome-selection.ts b/cloud/apps/relay/src/idle-regional-rehome-selection.ts new file mode 100644 index 00000000000..f8790459c0b --- /dev/null +++ b/cloud/apps/relay/src/idle-regional-rehome-selection.ts @@ -0,0 +1,117 @@ +import { createHash } from 'node:crypto' +import type { IdleRegionalRehomeRequest } from '@orca-cloud/relay-contract' +import type { RelayDatabase, SqlRow } from './database.js' + +export const IDLE_REHOME_PAGE_SIZE = 100 + +export async function selectIdleRegionalRehomes(input: { + database: RelayDatabase + now: number + heartbeatTtlMs: number + cohortPercent: number + offset: number + connectionHeadroom: Map + cellIsClean: (safety: SqlRow | undefined, runtime: SqlRow, now: number) => boolean +}): Promise> { + const [runtimes, safetyRows] = await Promise.all([ + input.database.query('SELECT * FROM relay_cell_runtime'), + input.database.query('SELECT * FROM relay_cell_rehome_safety') + ]) + const cleanCells = runtimes + .filter((runtime) => + input.cellIsClean( + safetyRows.find((safety) => safety.cell_id === runtime.cell_id), + runtime, + input.now + ) + ) + .map((runtime) => String(runtime.cell_id)) + const targetCells = cleanCells.filter((id) => input.connectionHeadroom.get(id) !== false) + if (!cleanCells.length || !targetCells.length) return [] + const rows = await input.database.query( + `SELECT a.user_id, a.relay_host_id, a.cell_id AS source_cell_id, + a.assignment_epoch, host.generation, r.cell_incarnation, + s.cell_url, target.cell_id AS target_cell_id + FROM relay_region_rehome_control policy + JOIN relay_region_decisions d ON d.outcome = 'conclusive' + JOIN relay_assignments a ON a.user_id = d.user_id AND a.relay_host_id = d.relay_host_id + JOIN relay_cells s ON s.cell_id = a.cell_id AND s.enabled = 1 + JOIN relay_cell_regions sr ON sr.cell_id = a.cell_id + JOIN relay_cell_admission sa ON sa.cell_id = a.cell_id AND sa.admission_state = 'general' + JOIN relay_cell_runtime r ON r.cell_id = a.cell_id AND r.ready = 1 + JOIN relay_cell_capabilities c ON c.cell_id = r.cell_id AND c.cell_incarnation = r.cell_incarnation + JOIN relay_control_capabilities host ON host.user_id = a.user_id AND host.relay_host_id = a.relay_host_id + AND host.cell_id = a.cell_id AND host.assignment_epoch = a.assignment_epoch + AND host.cell_incarnation = r.cell_incarnation AND host.idle_regional_rehome = 1 + JOIN relay_assignment_activity_leases lease ON lease.user_id = host.user_id + AND lease.relay_host_id = host.relay_host_id AND lease.activity_id = host.activity_id + AND lease.cell_id = a.cell_id AND lease.activity_kind = 'control' + JOIN relay_cell_regions tr ON tr.region = d.preferred_region + JOIN relay_cells target ON target.cell_id = tr.cell_id AND target.enabled = 1 + JOIN relay_cell_admission ta ON ta.cell_id = target.cell_id AND ta.admission_state = 'general' + JOIN relay_cell_runtime rt ON rt.cell_id = target.cell_id AND rt.ready = 1 + JOIN relay_cell_capabilities ct ON ct.cell_id = rt.cell_id AND ct.cell_incarnation = rt.cell_incarnation + WHERE policy.control_id = 'global' AND policy.enabled = 1 AND policy.not_before <= ? + AND d.preferred_region <> sr.region AND d.incumbent_region = sr.region + AND d.assignment_epoch = a.assignment_epoch AND d.policy_version = 1 + AND d.expires_at > ? AND d.observed_at >= ? - policy.preference_max_age_ms + AND d.cohort_bucket < ? AND lease.expires_at > ? AND lease.updated_at >= r.started_at + AND r.last_heartbeat_at > ? AND rt.last_heartbeat_at > ? + AND s.cell_id IN (${cleanCells.map(() => '?').join(',')}) + AND target.cell_id IN (${targetCells.map(() => '?').join(',')}) + -- Reserve the moving host's source activity plus its assignment on the target. + AND target.reserved_requests + 1 + ( + SELECT COALESCE(SUM(activity.request_units), 0) + FROM relay_assignment_activity_leases activity + WHERE activity.user_id = a.user_id AND activity.relay_host_id = a.relay_host_id + AND activity.cell_id = a.cell_id + ) <= target.capacity_requests + AND c.regional_rehome_protocol >= 3 AND ct.regional_rehome_protocol >= 3 + AND NOT EXISTS (SELECT 1 FROM relay_assignment_migrations migration + WHERE migration.user_id = a.user_id AND migration.relay_host_id = a.relay_host_id + AND migration.completed_at IS NULL AND migration.aborted_at IS NULL) + AND NOT EXISTS (SELECT 1 FROM relay_region_rehome_attempts attempt + WHERE attempt.user_id = a.user_id AND attempt.relay_host_id = a.relay_host_id + AND attempt.created_at > ? - policy.host_cooldown_ms) + ORDER BY a.user_id, a.relay_host_id, host.generation DESC, + (target.reserved_requests + rt.observed_requests) * 1.0 / target.capacity_requests, + target.cell_id + LIMIT ? OFFSET ?`, + [ + input.now, + input.now, + input.now, + input.cohortPercent, + input.now, + input.now - input.heartbeatTtlMs, + input.now - input.heartbeatTtlMs, + ...cleanCells, + ...targetCells, + input.now, + IDLE_REHOME_PAGE_SIZE, + input.offset + ] + ) + return rows.map((row) => { + const request = { + v: 1 as const, + userId: String(row.user_id), + relayHostId: String(row.relay_host_id), + sourceCellId: String(row.source_cell_id), + sourceCellIncarnation: String(row.cell_incarnation), + sourceAssignmentEpoch: Number(row.assignment_epoch), + sourceGeneration: Number(row.generation), + targetCellId: String(row.target_cell_id) + } + // UUIDv5 keeps retries on every director bound to the same source authority and target. + const digest = createHash('sha1') + .update(Buffer.from('0a1c5a9b197b4ea8b6f1f3bcaa3d712c', 'hex')) + .update(JSON.stringify(request)) + .digest() + digest[6] = (digest[6]! & 0x0f) | 0x50 + digest[8] = (digest[8]! & 0x3f) | 0x80 + const hex = digest.subarray(0, 16).toString('hex') + const attemptId = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}` + return { ...request, attemptId, sourceCellUrl: String(row.cell_url) } + }) +} diff --git a/cloud/apps/relay/src/idle-regional-rehome-store.test.ts b/cloud/apps/relay/src/idle-regional-rehome-store.test.ts new file mode 100644 index 00000000000..92ced43b510 --- /dev/null +++ b/cloud/apps/relay/src/idle-regional-rehome-store.test.ts @@ -0,0 +1,396 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { RelayAssignmentStore } from './assignment-store.js' +import type { RelayDatabase, RelayLockOptions } from './database.js' +import { openIdleRehomeTestDatabase } from './idle-regional-rehome-test-database.js' + +const identity = { userId: 'idle-store-test', relayHostId: 'abcdefghijklmnop' } +const incarnations = [ + '11111111-1111-4111-8111-111111111111', + '22222222-2222-4222-8222-222222222222' +] +const cells = [ + { + id: 'source', + url: 'https://source.example.test', + region: 'us-central1' as const, + capacityRequests: 100 + }, + { + id: 'target', + url: 'https://target.example.test', + region: 'asia-east2' as const, + capacityRequests: 100 + } +] +const databases: RelayDatabase[] = [] +afterEach(async () => { + vi.restoreAllMocks() + for (const database of databases.splice(0)) await database.close() +}) + +async function setup() { + const database = await openIdleRehomeTestDatabase() + databases.push(database) + let now = 100_000_000 + const store = new RelayAssignmentStore(database, () => now, { regionalRehomeCohortPercent: 100 }) + await store.inspectRegionalRehomeControl() + now += 86_400_000 + await store.applyRegionalRehomeControl({ + expectedGeneration: 0, + enabled: true, + notBefore: now, + ratePerMinute: 10, + preferenceMaxAgeMs: 86_400_000, + hostCooldownMs: 604_800_000, + drainGraceMs: 60_000 + }) + await store.reconcileCells(cells) + const safety = { + observedAt: now, + sqlFailures: 0, + reconnects: 0, + controlActivityRecoveryFailures: 0, + databasePoolWaiting: 0, + databasePoolWaitersMax: 0, + databasePoolWaitMsMax: 0 + } + for (const [index, cell] of cells.entries()) { + await store.recordCellHeartbeat({ + cellId: cell.id, + cellUrl: cell.url, + region: cell.region, + cellIncarnation: incarnations[index]!, + startedAt: now - 1_000, + ready: true, + observedRequests: 0 + }) + await store.recordCellRegionalRehomeStatus({ + cellId: cell.id, + cellIncarnation: incarnations[index]!, + regionalRehomeProtocol: 3, + safety + }) + } + const assignment = await store.assign(identity, undefined, 'us-central1') + await store.activateControl(identity, { + cellId: cells[0]!.id, + assignmentEpoch: assignment.assignmentEpoch, + generation: 7, + cellIncarnation: incarnations[0], + idleRegionalRehome: true + }) + const issued = await store.exchangeRegionCorrection( + identity, + { v: 1, action: 'issue-window' }, + assignment.assignmentEpoch + ) + await store.exchangeRegionCorrection( + identity, + { + v: 1, + action: 'report', + generation: issued.window!.generation, + assignmentEpoch: assignment.assignmentEpoch, + policyVersion: 1, + outcome: 'conclusive', + measurements: { 'us-central1': 180, 'asia-east2': 40 } + }, + assignment.assignmentEpoch + ) + const request = { + v: 1 as const, + ...identity, + attemptId: '33333333-3333-4333-8333-333333333333', + sourceCellId: cells[0]!.id, + sourceCellIncarnation: incarnations[0]!, + sourceAssignmentEpoch: assignment.assignmentEpoch, + sourceGeneration: 7, + targetCellId: cells[1]!.id + } + return { store, database, safety, request } +} + +describe('constrained idle regional assignment transaction', () => { + it.each(['missing', 'disabled', 'future'] as const)( + 'does only one read per tick with %s durable control and sees later enablement', + async (state) => { + const { store, database, safety } = await setup() + const control = (await database.query( + "SELECT * FROM relay_region_rehome_control WHERE control_id = 'global'" + ))[0]! + if (state === 'missing') { + await database.query('DELETE FROM relay_region_rehome_control') + } else { + await database.query( + "UPDATE relay_region_rehome_control SET enabled = ?, not_before = ? WHERE control_id = 'global'", + [state === 'disabled' ? 0 : 1, safety.observedAt + (state === 'future' ? 1 : 0)] + ) + } + const query = vi.spyOn(database, 'query') + const transaction = vi.spyOn(database, 'transaction') + for (let tick = 0; tick < 3; tick++) { + query.mockClear() + expect(await store.selectIdleRegionalRehomeCandidates(safety)).toEqual([]) + expect(query).toHaveBeenCalledTimes(1) + expect(query.mock.calls[0]![0]).toMatch(/^SELECT .*FROM relay_region_rehome_control/s) + expect(transaction).not.toHaveBeenCalled() + } + if (state === 'missing') { + const columns = Object.keys(control) + await database.query( + `INSERT INTO relay_region_rehome_control (${columns.join(',')}) VALUES (${columns.map(() => '?').join(',')})`, + Object.values(control) + ) + } else { + await database.query( + "UPDATE relay_region_rehome_control SET enabled = 1, not_before = ? WHERE control_id = 'global'", + [safety.observedAt] + ) + } + query.mockClear() + expect(await store.selectIdleRegionalRehomeCandidates(safety)).toHaveLength(1) + expect(query.mock.calls.length).toBeGreaterThan(1) + await database.query("UPDATE relay_region_rehome_control SET enabled = 0 WHERE control_id = 'global'") + query.mockClear() + expect(await store.selectIdleRegionalRehomeCandidates(safety)).toEqual([]) + expect(query).toHaveBeenCalledTimes(1) + } + ) + + it.each([10, 11])('reserves source activity plus assignment at target capacity %i', async (capacity) => { + const { store, database, safety, request } = await setup() + // Model three source activity units and seven units already reserved at the target. + await database.query( + 'UPDATE relay_assignment_activity_leases SET request_units = 3 WHERE user_id = ? AND relay_host_id = ?', + [identity.userId, identity.relayHostId] + ) + await database.query("UPDATE relay_cells SET reserved_requests = 4 WHERE cell_id = 'source'") + await database.query( + "UPDATE relay_cells SET reserved_requests = 7, capacity_requests = ? WHERE cell_id = 'target'", + [capacity] + ) + const candidates = await store.selectIdleRegionalRehomeCandidates(safety) + expect(candidates).toHaveLength(capacity === 11 ? 1 : 0) + expect(await store.commitIdleRegionalRehome(request, safety)).toEqual({ + outcome: capacity === 11 ? 'committed' : 'deferred' + }) + const [target] = await database.query("SELECT reserved_requests FROM relay_cells WHERE cell_id = 'target'") + expect(Number(target!.reserved_requests)).toBe(capacity === 11 ? 11 : 7) + expect(await store.resolve(identity)).toMatchObject({ + cellId: capacity === 11 ? 'target' : 'source', + assignmentEpoch: capacity === 11 ? 2 : 1 + }) + }) + + it('progresses past a full page of busy candidates without writing eligibility state', async () => { + const { store, database, safety } = await setup() + for (const table of [ + 'relay_assignments', + 'relay_assignment_activity_leases', + 'relay_control_capabilities', + 'relay_region_decisions' + ]) { + const template = ( + await database.query(`SELECT * FROM ${table} WHERE user_id = ? AND relay_host_id = ?`, [ + identity.userId, + identity.relayHostId + ]) + )[0]! + const columns = Object.keys(template) + for (let index = 0; index < 100; index++) { + const values = columns.map((column) => + column === 'user_id' || column === 'relay_host_id' ? '?' : column + ) + await database.query( + `INSERT INTO ${table} (${columns.join(', ')}) SELECT ${values.join(', ')} FROM ${table} + WHERE user_id = ? AND relay_host_id = ?`, + [ + `idle-store-test-${String(index).padStart(3, '0')}`, + `pagehost${String(index).padStart(8, '0')}`, + identity.userId, + identity.relayHostId + ] + ) + } + } + const first = await store.selectIdleRegionalRehomeCandidates(safety) + const next = await store.selectIdleRegionalRehomeCandidates(safety) + expect(first).toHaveLength(100) + expect(next).toHaveLength(1) + expect(next[0]!.relayHostId).toBe('pagehost00000099') + const restarted = new RelayAssignmentStore(database, () => safety.observedAt, { + regionalRehomeCohortPercent: 100 + }) + expect(await restarted.selectIdleRegionalRehomeCandidates(safety)).toEqual(first) + expect(await database.query('SELECT * FROM relay_region_rehome_attempts')).toEqual([]) + const decisions = await database.query('SELECT last_considered_at FROM relay_region_decisions') + expect(decisions.every((decision) => Number(decision.last_considered_at) === 0)).toBe(true) + }) + + it.runIf(Boolean(process.env.ORCA_IDLE_REHOME_POSTGRES_URL))( + 'rechecks generation when replacement wins after the initial authority lookup', + async () => { + const { store, safety, request, database } = await setup() + const held = holdStatement(database, 'SELECT * FROM relay_region_rehome_control') + const commit = store.commitIdleRegionalRehome(request, safety) + await held.entered + try { + await store.activateControl(identity, { + cellId: 'source', + assignmentEpoch: 1, + generation: 8, + cellIncarnation: incarnations[0], + idleRegionalRehome: true + }) + } finally { + held.release() + } + expect(await commit).toEqual({ outcome: 'deferred' }) + expect(await store.reconcileIdleRegionalRehome(request)).toBe('stale') + expect(await database.query('SELECT * FROM relay_region_rehome_attempts')).toEqual([]) + } + ) + + it('rejects source replacement when the cutover already holds assignment authority', async () => { + const { store, safety, request, database } = await setup() + const held = holdStatement(database, 'UPDATE relay_assignments SET cell_id') + const commit = store.commitIdleRegionalRehome(request, safety) + await held.entered + const replacement = store.activateControl(identity, { + cellId: 'source', + assignmentEpoch: 1, + generation: 8, + cellIncarnation: incarnations[0], + idleRegionalRehome: true + }) + const rejected = expect(replacement).rejects.toThrow('wrong_assignment') + held.release() + expect(await commit).toEqual({ outcome: 'committed' }) + await rejected + expect(await store.resolve(identity)).toMatchObject({ cellId: 'target', assignmentEpoch: 2 }) + }) + + it('finds the committed attempt after its database reply is lost', async () => { + const { store, safety, request, database } = await setup() + const transaction = database.transaction.bind(database) + const intercepted = vi + .spyOn(database, 'transaction') + .mockImplementation(async (operation, options) => { + let changed = false + const result = await transaction( + async (tx) => + operation( + new Proxy(tx, { + get(target, key) { + if (key === 'query') + return async (sql: string, params?: unknown[]) => { + if (sql.includes('INSERT INTO relay_region_rehome_attempts')) changed = true + return target.query(sql, params) + } + const value = Reflect.get(target, key) + return typeof value === 'function' ? value.bind(target) : value + } + }) + ), + options + ) + if (changed) throw new Error('simulated_commit_reply_lost') + return result + }) + await expect(store.commitIdleRegionalRehome(request, safety)).rejects.toThrow( + 'simulated_commit_reply_lost' + ) + intercepted.mockRestore() + expect(await store.reconcileIdleRegionalRehome(request)).toBe('committed') + expect(await store.commitIdleRegionalRehome(request, safety)).toEqual({ outcome: 'committed' }) + expect(await database.query('SELECT * FROM relay_region_rehome_attempts')).toHaveLength(1) + }) + + it('commits the requested move once and records its outcome without source retention', async () => { + const { store, database, safety, request } = await setup() + expect(await store.commitIdleRegionalRehome(request, safety)).toEqual({ outcome: 'committed' }) + expect(await store.commitIdleRegionalRehome(request, safety)).toEqual({ outcome: 'committed' }) + expect(await store.resolve(identity)).toMatchObject({ cellId: 'target', assignmentEpoch: 2 }) + const attempts = await database.query('SELECT * FROM relay_region_rehome_attempts') + expect(attempts).toHaveLength(1) + expect(attempts[0]!.attempt_id).toBe(request.attemptId) + expect(Number(attempts[0]!.source_generation)).toBe(7) + }) + + it('rejects a replaced control and never substitutes a different target', async () => { + const { store, safety, request } = await setup() + expect( + await store.commitIdleRegionalRehome({ ...request, targetCellId: 'missing' }, safety) + ).toEqual({ outcome: 'deferred' }) + await store.activateControl(identity, { + cellId: 'source', + assignmentEpoch: 1, + generation: 8, + cellIncarnation: incarnations[0], + idleRegionalRehome: true + }) + expect(await store.commitIdleRegionalRehome(request, safety)).toEqual({ outcome: 'stale' }) + expect(await store.resolve(identity)).toMatchObject({ cellId: 'source', assignmentEpoch: 1 }) + }) + + it('does not commit without process safety or cohort authorization', async () => { + const { store, safety, request, database } = await setup() + expect(await store.commitIdleRegionalRehome(request)).toEqual({ outcome: 'deferred' }) + expect(await store.commitIdleRegionalRehome(request, safety, 0)).toEqual({ + outcome: 'deferred' + }) + expect(await database.query('SELECT * FROM relay_region_rehome_attempts')).toEqual([]) + }) + + it('selects read-only with stable identity and the control generation, not probe generation', async () => { + const { store, safety, database } = await setup() + const before = await database.query('SELECT * FROM relay_assignments') + const candidates = await store.selectIdleRegionalRehomeCandidates(safety) + expect(candidates).toHaveLength(1) + expect(candidates[0]).toMatchObject({ + sourceGeneration: 7, + sourceCellId: 'source', + targetCellId: 'target' + }) + expect(await store.selectIdleRegionalRehomeCandidates(safety)).toEqual(candidates) + expect(await database.query('SELECT * FROM relay_assignments')).toEqual(before) + expect(await database.query('SELECT * FROM relay_region_rehome_attempts')).toEqual([]) + }) +}) + +function holdStatement(database: RelayDatabase, fragment: string) { + let entered!: () => void + let release!: () => void + const arrival = new Promise((resolve) => { + entered = resolve + }) + const gate = new Promise((resolve) => { + release = resolve + }) + let held = false + const transaction = database.transaction.bind(database) + vi.spyOn(database, 'transaction').mockImplementation((operation, options) => + transaction(async (tx) => { + return operation( + new Proxy(tx, { + get(target, key) { + if (key === 'query' || key === 'queryLocked') + return async (sql: string, params?: unknown[], lockOptions?: RelayLockOptions) => { + if (!held && sql.includes(fragment)) { + held = true + entered() + await gate + } + return key === 'queryLocked' + ? target.queryLocked(sql, params, lockOptions) + : target.query(sql, params) + } + const value = Reflect.get(target, key) + return typeof value === 'function' ? value.bind(target) : value + } + }) + ) + }, options) + ) + return { entered: arrival, release } +} diff --git a/cloud/apps/relay/src/idle-regional-rehome-test-database.ts b/cloud/apps/relay/src/idle-regional-rehome-test-database.ts new file mode 100644 index 00000000000..a541e7d1126 --- /dev/null +++ b/cloud/apps/relay/src/idle-regional-rehome-test-database.ts @@ -0,0 +1,40 @@ +import { randomUUID } from 'node:crypto' +import pg from 'pg' +import { openInMemoryRelayDatabase, openRelayDatabase, type RelayDatabase } from './database.js' + +export async function openIdleRehomeTestDatabase(): Promise { + const configured = process.env.ORCA_IDLE_REHOME_POSTGRES_URL + if (!configured) return openInMemoryRelayDatabase() + const url = new URL(configured) + if (url.port !== '55440' || !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)) { + throw new Error('idle_rehome_tests_require_local_postgres_55440') + } + const schema = `idle_rehome_${randomUUID().replaceAll('-', '')}` + const admin = new pg.Client({ connectionString: configured }) + await admin.connect() + try { + await admin.query(`CREATE SCHEMA ${schema}`) + url.searchParams.set('options', `-c search_path=${schema}`) + const database = await openRelayDatabase({ databaseUrl: url.toString(), dataDir: '' }) + const close = database.close.bind(database) + database.close = async () => { + try { + await close() + } finally { + try { + await admin.query(`DROP SCHEMA ${schema} CASCADE`) + } finally { + await admin.end() + } + } + } + return database + } catch (error) { + try { + await admin.query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`) + } finally { + await admin.end() + } + throw error + } +} diff --git a/cloud/apps/relay/src/idle-regional-rehome-worker.test.ts b/cloud/apps/relay/src/idle-regional-rehome-worker.test.ts new file mode 100644 index 00000000000..9b3f6d7fa07 --- /dev/null +++ b/cloud/apps/relay/src/idle-regional-rehome-worker.test.ts @@ -0,0 +1,105 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { RelayAssignmentStore } from './assignment-store.js' +import type { RelayConfig } from './config.js' +import { startRegionalRehomeWorker } from './regional-rehome-worker.js' + +const candidate = { + v: 1, + attemptId: '11111111-1111-4111-8111-111111111111', + userId: 'private-user', + relayHostId: 'abcdefghijklmnop', + sourceCellId: 'source', + sourceCellUrl: 'https://source.example.test', + sourceCellIncarnation: '22222222-2222-4222-8222-222222222222', + sourceAssignmentEpoch: 7, + sourceGeneration: 3, + targetCellId: 'target' +} +const config = { + role: 'director', + regionCorrectionCohortPercent: 100, + rehomeAudience: 'https://relay.example.test/v1/admin/host-drain', + rehomeDirectorServiceAccount: 'director@example.test' +} as RelayConfig + +function setup(fetch: typeof globalThis.fetch) { + const selectIdleRegionalRehomeCandidates = vi + .fn() + .mockResolvedValueOnce([]) + .mockResolvedValue([candidate]) + const claimRegionalRehome = vi.fn() + const recordRegionalRehomeDispatchFailure = vi.fn() + const worker = startRegionalRehomeWorker( + config, + { + selectIdleRegionalRehomeCandidates, + claimRegionalRehome, + recordRegionalRehomeDispatchFailure + } as unknown as RelayAssignmentStore, + { + safetySnapshot: () => ({ observedAt: 100 }) as never, + intervalMs: 60_000, + identityToken: async () => 'private-token', + fetch + } + )! + return { + worker, + selectIdleRegionalRehomeCandidates, + claimRegionalRehome, + recordRegionalRehomeDispatchFailure + } +} + +describe('idle regional worker dispatch', () => { + afterEach(() => vi.restoreAllMocks()) + it('sends an idle request without claiming an assignment first', async () => { + const fetch = vi.fn(async () => + Response.json({ v: 1, outcome: 'committed' }) + ) + const c = setup(fetch) + await vi.waitFor(() => expect(c.selectIdleRegionalRehomeCandidates).toHaveBeenCalledOnce()) + await c.worker.run() + c.worker.stop() + expect(c.claimRegionalRehome).not.toHaveBeenCalled() + expect(fetch).toHaveBeenCalledOnce() + const [url, init] = fetch.mock.calls[0]! + expect(String(url)).toBe('https://source.example.test/v1/admin/host-idle-rehome') + const { sourceCellUrl: _, ...request } = candidate + expect(JSON.parse(String(init?.body))).toEqual({ + ...request, + cohortPercent: 100, + directorSafety: { observedAt: 100 } + }) + }) + it('progresses past busy hosts without charging a dispatch failure', async () => { + const fetch = vi + .fn() + .mockResolvedValueOnce(Response.json({ v: 1, outcome: 'busy' })) + .mockResolvedValueOnce(Response.json({ v: 1, outcome: 'committed' })) + const c = setup(fetch) + await vi.waitFor(() => expect(c.selectIdleRegionalRehomeCandidates).toHaveBeenCalledOnce()) + c.selectIdleRegionalRehomeCandidates.mockResolvedValue([ + candidate, + { + ...candidate, + relayHostId: 'ponmlkjihgfedcba', + attemptId: '33333333-3333-4333-8333-333333333333' + } + ]) + await c.worker.run() + c.worker.stop() + expect(fetch).toHaveBeenCalledTimes(2) + expect(c.recordRegionalRehomeDispatchFailure).not.toHaveBeenCalled() + }) + it('does not charge a lost response as a claimed migration failure', async () => { + const fetch = vi.fn(async () => { + throw new Error('response lost') + }) + const c = setup(fetch) + await vi.waitFor(() => expect(c.selectIdleRegionalRehomeCandidates).toHaveBeenCalledOnce()) + await c.worker.run() + c.worker.stop() + expect(c.recordRegionalRehomeDispatchFailure).not.toHaveBeenCalled() + }) +}) diff --git a/cloud/apps/relay/src/index.ts b/cloud/apps/relay/src/index.ts index 541884362c2..8e7b6a56941 100644 --- a/cloud/apps/relay/src/index.ts +++ b/cloud/apps/relay/src/index.ts @@ -2,6 +2,7 @@ import { formatAssignmentInventorySnapshot, readAssignmentInventorySnapshot } from './assignment-inventory-snapshot.js' +import { readRegionCorrectionOutcomes } from './region-correction-outcomes.js' import { RelayAssignmentStore } from './assignment-store.js' import { loadRelayConfig } from './config.js' import { startCellHeartbeat } from './cell-heartbeat-client.js' @@ -71,6 +72,13 @@ const migrationInventoryTimer = roleOwnsAssignmentMaintenance(config.role) void runRelayBackgroundOperation(async () => { const inventory = await readRegisteredMigrationInventory(database, Date.now()) for (const line of formatRegisteredMigrationInventory(inventory)) console.warn(line) + console.log( + JSON.stringify({ + event: 'orca_relay_region_correction_outcomes', + observedAt: Date.now(), + outcomes: await readRegionCorrectionOutcomes(database, Date.now()) + }) + ) }, '[orca-relay] migration inventory failed') }, 5 * 60_000) : null diff --git a/cloud/apps/relay/src/region-correction-outcomes.ts b/cloud/apps/relay/src/region-correction-outcomes.ts new file mode 100644 index 00000000000..d3a6f8d3be3 --- /dev/null +++ b/cloud/apps/relay/src/region-correction-outcomes.ts @@ -0,0 +1,29 @@ +import type { RelayDatabase } from './database.js' + +export async function readRegionCorrectionOutcomes(database: RelayDatabase, now: number) { + const rows = await database.query( + `SELECT attempt.source_cell_id, attempt.target_cell_id, + CASE WHEN attempt.aborted_at IS NOT NULL THEN 'aborted' + WHEN attempt.completed_at IS NOT NULL THEN 'completed' + WHEN migration.target_registered_at IS NOT NULL THEN 'registered' ELSE 'registering' END AS state, + COUNT(*) AS count, + COALESCE(MAX(CASE WHEN attempt.completed_at IS NULL AND attempt.aborted_at IS NULL + THEN ? - attempt.created_at ELSE 0 END), 0) AS oldest_open_ms, + COALESCE(SUM(CASE WHEN attempt.completed_at IS NULL AND attempt.aborted_at IS NULL + THEN migration.target_reserved_units ELSE 0 END), 0) AS target_reserved_units + FROM relay_region_rehome_attempts attempt + JOIN relay_assignment_migrations migration ON migration.user_id = attempt.user_id + AND migration.relay_host_id = attempt.relay_host_id AND migration.assignment_epoch = attempt.assignment_epoch + GROUP BY attempt.source_cell_id, attempt.target_cell_id, state + ORDER BY attempt.source_cell_id, attempt.target_cell_id, state`, + [now] + ) + return rows.map((row) => ({ + sourceCellId: String(row.source_cell_id), + targetCellId: String(row.target_cell_id), + state: String(row.state), + count: Number(row.count), + oldestOpenMs: Number(row.oldest_open_ms), + targetReservedUnits: Number(row.target_reserved_units) + })) +} diff --git a/cloud/apps/relay/src/region-correction-preview.ts b/cloud/apps/relay/src/region-correction-preview.ts new file mode 100644 index 00000000000..c120dbb2272 --- /dev/null +++ b/cloud/apps/relay/src/region-correction-preview.ts @@ -0,0 +1,157 @@ +import type { RelayDatabase, SqlRow } from './database.js' +import { REGIONAL_REHOME_DEFAULT_HOST_COOLDOWN_MS } from './database.js' +import { + REGIONAL_REHOME_CONCURRENT_LIMIT, + REGION_DECISION_TTL_MS +} from './region-correction-state.js' + +export type RegionCorrectionPreview = { + observedAt: number + newClaimsEnabled: boolean + cohortPercent: number + openMigrations: number + availableMigrationSlots: number + globalSafetyFailure: string | null + counts: Record +} + +export async function previewRegionalRehomeEligibility(input: { + database: RelayDatabase + now: number + heartbeatTtlMs: number + cohortPercent: number + globalSafetyFailure: string | null + connectionHeadroom: ReadonlyMap + cellIsClean: (safety: SqlRow | undefined, runtime: SqlRow, now: number) => boolean +}): Promise { + const { database, now } = input + const [hosts, cells, runtimeRows, capabilityRows, safetyRows, controls, migrations] = + await Promise.all([ + database.query( + `SELECT assignment.cell_id, assignment.assignment_epoch, + decision.generation, decision.assignment_epoch AS decision_epoch, decision.expires_at, + decision.incumbent_region, decision.preferred_region, decision.outcome, decision.policy_version, + decision.observed_at, decision.cohort_bucket, + (SELECT MAX(attempt.created_at) FROM relay_region_rehome_attempts attempt + WHERE attempt.user_id = assignment.user_id AND attempt.relay_host_id = assignment.relay_host_id) AS last_attempt_at, + (SELECT COUNT(*) FROM relay_assignment_migrations migration + WHERE migration.user_id = assignment.user_id AND migration.relay_host_id = assignment.relay_host_id + AND migration.completed_at IS NULL AND migration.aborted_at IS NULL) AS open_migrations, + (SELECT COALESCE(SUM(lease.request_units),0) FROM relay_assignment_activity_leases lease + WHERE lease.user_id = assignment.user_id AND lease.relay_host_id = assignment.relay_host_id + AND lease.cell_id = assignment.cell_id) AS source_units, + (SELECT COUNT(*) FROM relay_control_capabilities host_capability + JOIN relay_assignment_activity_leases lease ON lease.user_id = host_capability.user_id + AND lease.relay_host_id = host_capability.relay_host_id AND lease.activity_id = host_capability.activity_id + JOIN relay_cell_runtime runtime ON runtime.cell_id = host_capability.cell_id + AND runtime.cell_incarnation = host_capability.cell_incarnation + WHERE host_capability.user_id = assignment.user_id AND host_capability.relay_host_id = assignment.relay_host_id + AND host_capability.cell_id = assignment.cell_id AND host_capability.assignment_epoch = assignment.assignment_epoch + AND host_capability.idle_regional_rehome = 1 AND lease.activity_kind = 'control' + AND lease.activity_id NOT LIKE 'control-pending:%' AND lease.expires_at > ? + AND lease.updated_at >= runtime.started_at) AS capable_controls + FROM relay_assignments assignment LEFT JOIN relay_region_decisions decision + ON decision.user_id = assignment.user_id AND decision.relay_host_id = assignment.relay_host_id`, + [now] + ), + database.query(`SELECT cell.*, region.region, admission.admission_state FROM relay_cells cell + LEFT JOIN relay_cell_regions region ON region.cell_id = cell.cell_id + LEFT JOIN relay_cell_admission admission ON admission.cell_id = cell.cell_id`), + database.query(`SELECT * FROM relay_cell_runtime`), + database.query(`SELECT * FROM relay_cell_capabilities`), + database.query(`SELECT * FROM relay_cell_rehome_safety`), + database.query(`SELECT * FROM relay_region_rehome_control WHERE control_id = 'global'`), + database.query( + `SELECT COUNT(*) AS count FROM relay_assignment_migrations WHERE completed_at IS NULL AND aborted_at IS NULL` + ) + ]) + const byCell = (rows: SqlRow[]) => new Map(rows.map((row) => [String(row.cell_id), row])) + const runtimes = byCell(runtimeRows) + const capabilities = byCell(capabilityRows) + const safety = byCell(safetyRows) + const inventory = byCell(cells) + const control = controls[0] + const cooldown = Number(control?.host_cooldown_ms ?? REGIONAL_REHOME_DEFAULT_HOST_COOLDOWN_MS) + const maxAge = Number(control?.preference_max_age_ms ?? REGION_DECISION_TTL_MS) + const openMigrations = Number(migrations[0]?.count ?? 0) + const counts: Record = {} + const count = (reason: string) => { + counts[reason] = (counts[reason] ?? 0) + 1 + } + const available = (cell: SqlRow): boolean => { + const id = String(cell.cell_id) + const runtime = runtimes.get(id) + const capability = capabilities.get(id) + return ( + Number(cell.enabled) === 1 && + cell.admission_state === 'general' && + cell.region != null && + runtime !== undefined && + Number(runtime.ready) === 1 && + Number(runtime.last_heartbeat_at) > now - input.heartbeatTtlMs && + capability !== undefined && + capability.cell_incarnation === runtime.cell_incarnation && + Number(capability.regional_rehome_protocol) >= 3 + ) + } + for (const host of hosts) { + let reason: string | null = null + const source = inventory.get(String(host.cell_id)) + if (host.generation == null) reason = 'no-verified-decision' + else if (Number(host.expires_at) <= now || Number(host.observed_at) < now - maxAge) + reason = 'expired' + else if ( + Number(host.decision_epoch) !== Number(host.assignment_epoch) || + host.incumbent_region !== source?.region + ) + reason = 'basis-changed' + else if ( + host.outcome !== 'conclusive' || + Number(host.policy_version) !== 1 || + host.preferred_region == null + ) + reason = 'inconclusive-or-insufficient-improvement' + else if (Number(host.cohort_bucket) >= input.cohortPercent) reason = 'outside-cohort' + else if (Number(host.open_migrations) > 0) reason = 'migration-open' + else if (host.last_attempt_at != null && Number(host.last_attempt_at) > now - cooldown) + reason = 'host-cooldown' + else if (!source || !available(source)) reason = 'source-ineligible' + else if (Number(host.capable_controls) === 0) reason = 'source-control-unsupported-or-inactive' + else if ( + !input.cellIsClean(safety.get(String(host.cell_id)), runtimes.get(String(host.cell_id))!, now) + ) + reason = 'source-unclean' + if (reason) { + count(reason) + continue + } + const targets = cells.filter( + (cell) => + cell.cell_id !== host.cell_id && cell.region === host.preferred_region && available(cell) + ) + const clean = targets.filter((cell) => + input.cellIsClean(safety.get(String(cell.cell_id)), runtimes.get(String(cell.cell_id))!, now) + ) + const capacity = clean.filter( + (cell) => + input.connectionHeadroom.get(String(cell.cell_id)) !== false && + Number(cell.reserved_requests) + Number(host.source_units) + 1 <= + Number(cell.capacity_requests) + ) + if (targets.length === 0) count('no-eligible-target') + else if (clean.length === 0) count('target-unclean') + else if (capacity.length === 0) count('no-target-headroom') + else if (input.globalSafetyFailure) count('global-safety-blocked') + else if (openMigrations >= REGIONAL_REHOME_CONCURRENT_LIMIT) count('concurrent-migration-cap') + else count(`eligible:${host.incumbent_region}-to-${host.preferred_region}`) + } + return { + observedAt: now, + newClaimsEnabled: Number(control?.enabled ?? 0) === 1, + cohortPercent: input.cohortPercent, + openMigrations, + availableMigrationSlots: Math.max(0, REGIONAL_REHOME_CONCURRENT_LIMIT - openMigrations), + globalSafetyFailure: input.globalSafetyFailure, + counts + } +} diff --git a/cloud/apps/relay/src/region-correction-restart.test.ts b/cloud/apps/relay/src/region-correction-restart.test.ts new file mode 100644 index 00000000000..02f315ab218 --- /dev/null +++ b/cloud/apps/relay/src/region-correction-restart.test.ts @@ -0,0 +1,119 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { RelayAssignmentStore } from './assignment-store.js' +import { openRelayDatabase, type RelayDatabase } from './database.js' + +const identity = { userId: 'restart-test-user', relayHostId: 'abcdefghijklmnop' } +const paths: string[] = [] +const databases = new Set() +afterEach(async () => { + for (const database of databases) await database.close() + databases.clear() + for (const path of paths.splice(0)) await rm(path, { recursive: true, force: true }) +}) + +async function setup() { + const dataDir = await mkdtemp(join(tmpdir(), 'relay-region-restart-')) + paths.push(dataDir) + let now = 1_000_000_000 + const open = async () => { + const database = await openRelayDatabase({ dataDir }) + databases.add(database) + return { database, store: new RelayAssignmentStore(database, () => now) } + } + const first = await open() + const cell = { + id: 'restart-us', + url: 'https://restart-us.example.test', + region: 'us-central1' as const, + capacityRequests: 100 + } + await first.store.reconcileCells([cell]) + await first.store.setCellEnabled(cell.id, true) + await first.store.recordCellHeartbeat({ + cellId: cell.id, + cellUrl: cell.url, + cellIncarnation: '11111111-1111-4111-8111-111111111111', + region: cell.region, + startedAt: now - 1_000, + ready: true, + observedRequests: 0 + }) + const assignment = await first.store.assign(identity) + const issue = (store: RelayAssignmentStore) => + store.exchangeRegionCorrection(identity, { v: 1, action: 'issue-window' }, assignment.assignmentEpoch) + const window = (await issue(first.store)).window! + const report = { + v: 1 as const, + action: 'report' as const, + generation: window.generation, + assignmentEpoch: window.assignmentEpoch, + policyVersion: 1 as const, + outcome: 'conclusive' as const, + measurements: { 'us-central1': 200, 'asia-east2': 40 } + } + const restart = async () => { + await first.database.close() + databases.delete(first.database) + return open() + } + return { + ...first, window, report, issue, restart, + setNow: (value: number) => { now = value } + } +} + +describe('persisted region decisions across director restart', () => { + it('keeps tombstones and fixed expiry, then invalidates the prior generation after restart', async () => { + const context = await setup() + const epoch = context.window.assignmentEpoch + await context.store.exchangeRegionCorrection(identity, { + v: 1, action: 'report', generation: context.window.generation, + assignmentEpoch: epoch, policyVersion: 1, outcome: 'inconclusive', reason: 'jitter' + }, epoch) + const restarted = await context.restart() + expect(await restarted.store.exchangeRegionCorrection(identity, context.report, epoch)) + .toMatchObject({ reportStatus: 'duplicate' }) + const row = (await restarted.database.query('SELECT * FROM relay_region_decisions'))[0]! + expect(row.outcome).toBe('inconclusive') + expect(Number(row.expires_at)).toBe(context.window.expiresAt) + const successor = (await context.issue(restarted.store)).window! + expect(successor.generation).toBe(context.window.generation + 1) + expect(await restarted.store.exchangeRegionCorrection(identity, context.report, epoch)) + .toMatchObject({ reportStatus: 'stale' }) + }) + + it('uses server expiry after a restart regardless of an old client report', async () => { + const context = await setup() + context.setNow(context.window.expiresAt) + const restarted = await context.restart() + expect(await restarted.store.exchangeRegionCorrection(identity, context.report, context.window.assignmentEpoch)) + .toMatchObject({ reportStatus: 'expired' }) + expect(await restarted.store.previewRegionCorrection()).toEqual({ expired: 1 }) + }) + + it('does not interpret a persisted future-policy window using the old policy after rollback', async () => { + const context = await setup() + await context.database.query('UPDATE relay_region_decisions SET policy_version = 2') + const restarted = await context.restart() + expect(await restarted.store.exchangeRegionCorrection(identity, context.report, context.window.assignmentEpoch)) + .toMatchObject({ reportStatus: 'stale' }) + const row = (await restarted.database.query('SELECT * FROM relay_region_decisions'))[0]! + expect(row.outcome).toBe('pending') + expect(row.preferred_region).toBeNull() + expect(row.report_json).toBeNull() + }) + + it('keeps generation ordering when the server clock moves backwards across restart', async () => { + const context = await setup() + context.setNow(1_000_000_000 - 60_000) + const restarted = await context.restart() + const successor = (await context.issue(restarted.store)).window! + expect(successor.generation).toBe(context.window.generation + 1) + expect(successor.expiresAt).toBe(context.window.expiresAt - 60_000) + expect(await restarted.store.exchangeRegionCorrection(identity, context.report, context.window.assignmentEpoch)) + .toMatchObject({ reportStatus: 'stale' }) + }) +}) diff --git a/cloud/apps/relay/src/region-correction-state.ts b/cloud/apps/relay/src/region-correction-state.ts new file mode 100644 index 00000000000..a1b15520b1c --- /dev/null +++ b/cloud/apps/relay/src/region-correction-state.ts @@ -0,0 +1,158 @@ +import { relayHostLogDigest } from './relay-host-log-digest.js' +import { createHash } from 'node:crypto' +import type { + RegionCorrectionRequest, + RegionCorrectionResponse, + RelayRegion +} from '@orca-cloud/relay-contract' +import type { RelayDatabase } from './database.js' + +type Identity = { userId: string; relayHostId: string } +export const REGION_DECISION_TTL_MS = 24 * 60 * 60_000 +export const REGIONAL_REHOME_CONCURRENT_LIMIT = 8 + +export async function exchangeRegionCorrection( + database: RelayDatabase, + identity: Identity, + request: RegionCorrectionRequest, + assignmentEpoch: number, + now: number +): Promise { + const result: RegionCorrectionResponse = await database.transaction(async (transaction) => { + const assignment = ( + await transaction.queryLocked( + `SELECT * FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?`, + [identity.userId, identity.relayHostId] + ) + )[0] + const region = + assignment && + ( + await transaction.query(`SELECT region FROM relay_cell_regions WHERE cell_id = ?`, [ + assignment.cell_id + ]) + )[0] + if (!assignment || !region || Number(assignment.assignment_epoch) !== assignmentEpoch) { + return { v: 1, reportStatus: 'basis-changed' } + } + const prior = ( + await transaction.queryLocked( + `SELECT * FROM relay_region_decisions WHERE user_id = ? AND relay_host_id = ?`, + [identity.userId, identity.relayHostId] + ) + )[0] + if (request.action === 'issue-window') { + const generation = Number(prior?.generation ?? 0) + 1 + if (!Number.isSafeInteger(generation)) throw new Error('region_generation_exhausted') + const expiresAt = now + REGION_DECISION_TTL_MS + const cohortBucket = + createHash('sha256') + .update(JSON.stringify([identity.userId, identity.relayHostId])) + .digest() + .readUInt32BE(0) % 100 + await transaction.query( + `INSERT INTO relay_region_decisions + (user_id, relay_host_id, generation, expires_at, assignment_epoch, incumbent_region, + policy_version, outcome, preferred_region, observed_at, report_json, cohort_bucket) + VALUES (?, ?, ?, ?, ?, ?, 1, 'pending', NULL, ?, NULL, ?) + ON CONFLICT (user_id, relay_host_id) DO UPDATE SET + generation = excluded.generation, expires_at = excluded.expires_at, + assignment_epoch = excluded.assignment_epoch, incumbent_region = excluded.incumbent_region, + policy_version = 1, outcome = 'pending', preferred_region = NULL, + observed_at = excluded.observed_at, report_json = NULL, cohort_bucket = excluded.cohort_bucket`, + [ + identity.userId, + identity.relayHostId, + generation, + expiresAt, + assignmentEpoch, + region.region, + now, + cohortBucket + ] + ) + return { + v: 1, + window: { + generation, + expiresAt, + assignmentEpoch, + incumbentRegion: region.region as RelayRegion, + policyVersion: 1 + } + } + } + if (!prior || Number(prior.generation) !== request.generation) + return { v: 1, reportStatus: 'stale' } + if (Number(prior.policy_version) !== request.policyVersion) + return { v: 1, reportStatus: 'stale' } + if (Number(prior.expires_at) <= now) return { v: 1, reportStatus: 'expired' } + if ( + request.assignmentEpoch !== assignmentEpoch || + Number(prior.assignment_epoch) !== assignmentEpoch || + prior.incumbent_region !== region.region + ) { + return { v: 1, reportStatus: 'basis-changed' } + } + // The first report wins, including an inconclusive tombstone. + if (prior.outcome !== 'pending') return { v: 1, reportStatus: 'duplicate' } + let preferredRegion: RelayRegion | null = null + if (request.outcome === 'conclusive') { + const incumbent = request.measurements[region.region as RelayRegion] + const target: RelayRegion = region.region === 'us-central1' ? 'asia-east2' : 'us-central1' + const targetRtt = request.measurements[target] + if (incumbent - targetRtt >= 25 && targetRtt <= incumbent * 0.8) preferredRegion = target + } + await transaction.query( + `UPDATE relay_region_decisions SET outcome = ?, preferred_region = ?, report_json = ? + WHERE user_id = ? AND relay_host_id = ? AND generation = ?`, + [ + request.outcome, + preferredRegion, + JSON.stringify(request), + identity.userId, + identity.relayHostId, + request.generation + ] + ) + return { v: 1, reportStatus: 'accepted' } + }) + if (request.action === 'report' && result.reportStatus === 'accepted') { + const digest = relayHostLogDigest(identity.relayHostId) + // Stable sampling includes unchanged hosts for before/after comparisons. + if (Number.parseInt(digest.slice(0, 8), 16) % 10 === 0) { + console.log( + JSON.stringify({ + event: 'orca_relay_region_comparison', + relayHostIdDigest: digest, + assignmentEpoch, + generation: request.generation, + policyVersion: request.policyVersion, + outcome: request.outcome, + ...(request.outcome === 'conclusive' ? { measurements: request.measurements } : {}) + }) + ) + } + } + return result +} + +export async function previewRegionCorrection( + database: RelayDatabase, + now: number +): Promise> { + const rows = await database.query( + `SELECT CASE WHEN decision.expires_at <= ? THEN 'expired' + WHEN decision.assignment_epoch <> assignment.assignment_epoch THEN 'basis-changed' + WHEN decision.outcome = 'pending' THEN 'pending' + WHEN decision.preferred_region IS NULL THEN 'ineligible' + ELSE decision.incumbent_region || '-to-' || decision.preferred_region END AS reason, + COUNT(*) AS count + FROM relay_region_decisions decision + JOIN relay_assignments assignment ON assignment.user_id = decision.user_id + AND assignment.relay_host_id = decision.relay_host_id + GROUP BY reason`, + [now] + ) + return Object.fromEntries(rows.map((row) => [String(row.reason), Number(row.count)])) +} diff --git a/cloud/apps/relay/src/region-correction-store.test.ts b/cloud/apps/relay/src/region-correction-store.test.ts new file mode 100644 index 00000000000..11af7b3c5bd --- /dev/null +++ b/cloud/apps/relay/src/region-correction-store.test.ts @@ -0,0 +1,359 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { RelayAssignmentStore } from './assignment-store.js' +import { openInMemoryRelayDatabase, openRelayDatabase, type RelayDatabase } from './database.js' + +const identity = { userId: 'region-correction-test-user', relayHostId: 'abcdefghijklmnop' } +const cells = [ + { + id: 'decision-us', + url: 'https://decision-us.example.test', + region: 'us-central1' as const, + capacityRequests: 100 + }, + { + id: 'decision-asia', + url: 'https://decision-asia.example.test', + region: 'asia-east2' as const, + capacityRequests: 100 + } +] +const incarnations = [ + '11111111-1111-4111-8111-111111111111', + '22222222-2222-4222-8222-222222222222' +] +const opened: RelayDatabase[] = [] +afterEach(async () => { + for (const database of opened.splice(0)) { + if (database.dialect === 'postgres') await cleanupPostgres(database) + await database.close() + } +}) + +async function cleanupPostgres(database: RelayDatabase) { + for (const table of [ + 'relay_control_connection_reservations', + 'relay_region_decisions', + 'relay_control_capabilities', + 'relay_assignment_activity_leases', + 'relay_assignment_migrations', + 'relay_assignment_migration_incarnations', + 'relay_assignment_region_preferences', + 'relay_region_rehome_attempts', + 'relay_assignments' + ]) { + await database.query(`DELETE FROM ${table} WHERE user_id = ?`, [identity.userId]) + } + for (const table of [ + 'relay_cell_rehome_safety', + 'relay_cell_capabilities', + 'relay_cell_connection_snapshots', + 'relay_cell_connection_runtime', + 'relay_cell_runtime', + 'relay_cell_connection_limits', + 'relay_cell_admission', + 'relay_cell_regions', + 'relay_cells' + ]) { + await database.query( + `DELETE FROM ${table} WHERE cell_id IN (?, ?)`, + cells.map((cell) => cell.id) + ) + } +} + +async function setup() { + const database = + process.env.ORCA_REGION_CORRECTION_POSTGRES === '1' + ? await openRelayDatabase({ + databaseUrl: requiredPostgresUrl(), + dataDir: '/tmp/orca-region-correction-unused' + }) + : await openInMemoryRelayDatabase() + opened.push(database) + if (database.dialect === 'postgres') await cleanupPostgres(database) + let clock = 100_000_000 + const store = new RelayAssignmentStore(database, () => clock, { + regionalRehomeCohortPercent: 100 + }) + await store.reconcileCells(cells) + for (const cell of cells) await store.setCellEnabled(cell.id, true) + for (const [index, cell] of cells.entries()) { + await store.recordCellHeartbeat({ + cellId: cell.id, + cellUrl: cell.url, + region: cell.region, + cellIncarnation: incarnations[index]!, + startedAt: clock - 1_000, + ready: true, + observedRequests: 0 + }) + } + const assignment = await store.assign(identity, undefined, 'us-central1') + const activityId = await store.activateControl(identity, { + cellId: cells[0]!.id, + assignmentEpoch: assignment.assignmentEpoch, + generation: 7, + cellIncarnation: incarnations[0], + idleRegionalRehome: true + }) + return { + database, + store, + assignment, + activityId, + now: () => clock, + advance: (ms: number) => { + clock += ms + } + } +} + +function requiredPostgresUrl(): string { + const url = process.env.ORCA_RELAY_TEST_POSTGRES_URL + if (!url || new URL(url).port !== '55440') + throw new Error('PostgreSQL tests require configured port 55440') + return url +} + +async function window(context: Awaited>) { + const result = await context.store.exchangeRegionCorrection( + identity, + { v: 1, action: 'issue-window' }, + context.assignment.assignmentEpoch + ) + return result.window! +} + +async function regionalMigration(context: Awaited>) { + const migration = await context.store.startEvacuation(identity, cells[1]!.id) + const attemptId = '33333333-3333-4333-8333-333333333333' + await context.database.query( + `INSERT INTO relay_region_rehome_attempts + (attempt_id,user_id,relay_host_id,preferred_region,source_cell_id,source_cell_incarnation, + target_cell_id,target_cell_incarnation,previous_epoch,assignment_epoch,drain_grace_ms,send_attempts,created_at,updated_at) + VALUES (?,?,?,'asia-east2',?,?,?,?,?,?,60000,1,?,?)`, + [ + attemptId, + identity.userId, + identity.relayHostId, + cells[0]!.id, + incarnations[0], + cells[1]!.id, + incarnations[1], + migration.previousEpoch, + migration.assignmentEpoch, + context.now(), + context.now() + ] + ) + return { migration } +} + +describe('ordered region decisions and migration outcomes', () => { + it('reports aggregate migration lifecycle and reservations without identity disclosure or writes', async () => { + const context = await setup() + const { migration } = await regionalMigration(context) + context.advance(1_000) + const before = await context.database.query('SELECT * FROM relay_region_rehome_attempts') + const outcomes = await context.store.regionCorrectionOutcomes() + expect(outcomes).toEqual([ + expect.objectContaining({ + sourceCellId: cells[0]!.id, + targetCellId: cells[1]!.id, + state: 'registering', + count: 1, + oldestOpenMs: 1_000 + }) + ]) + expect(outcomes[0]!.targetReservedUnits).toBeGreaterThan(0) + expect(JSON.stringify(outcomes)).not.toContain(identity.relayHostId) + expect(JSON.stringify(outcomes)).not.toContain(identity.userId) + expect(await context.database.query('SELECT * FROM relay_region_rehome_attempts')).toEqual( + before + ) + await context.store.activateControl(identity, { + cellId: cells[1]!.id, + assignmentEpoch: migration.assignmentEpoch, + generation: 1 + }) + await context.store.markMigrationTargetRegistered(identity, { + cellId: cells[1]!.id, + assignmentEpoch: migration.assignmentEpoch + }) + expect(await context.store.regionCorrectionOutcomes()).toEqual([ + expect.objectContaining({ state: 'registered' }) + ]) + await context.store.releaseActivity(identity, context.activityId) + expect(await context.store.completeReadyRegionalRehomes()).toBe(1) + expect(await context.store.regionCorrectionOutcomes()).toEqual([ + expect.objectContaining({ + state: 'completed', + targetReservedUnits: 0, + oldestOpenMs: 0 + }) + ]) + }) + + it('supersedes prior windows and keeps an inconclusive tombstone immutable', async () => { + const context = await setup() + const first = await window(context) + const second = await window(context) + expect(second.generation).toBe(first.generation + 1) + const report = { + v: 1 as const, + action: 'report' as const, + assignmentEpoch: first.assignmentEpoch, + policyVersion: 1 as const, + outcome: 'conclusive' as const, + measurements: { 'us-central1': 200, 'asia-east2': 40 } + } + expect( + await context.store.exchangeRegionCorrection( + identity, + { ...report, generation: first.generation }, + first.assignmentEpoch + ) + ).toMatchObject({ reportStatus: 'stale' }) + expect( + await context.store.exchangeRegionCorrection( + identity, + { ...report, generation: second.generation, outcome: 'inconclusive', reason: 'jitter' }, + second.assignmentEpoch + ) + ).toMatchObject({ reportStatus: 'accepted' }) + expect( + await context.store.exchangeRegionCorrection( + identity, + { ...report, generation: second.generation }, + second.assignmentEpoch + ) + ).toMatchObject({ reportStatus: 'duplicate' }) + expect(await context.store.previewRegionCorrection()).toEqual({ ineligible: 1 }) + }) + + it('previews the uncapped fleet without writes, claims, or locked reads', async () => { + const context = await setup() + const query = context.database.query.bind(context.database) + const transaction = context.database.transaction.bind(context.database) + const queryLocked = context.database.queryLocked.bind(context.database) + context.database.query = async (sql, params) => { + expect(sql.trim()).toMatch(/^(SELECT|WITH)/i) + return query(sql, params) + } + context.database.transaction = async () => { + throw new Error('preview_must_not_open_mutating_transaction') + } + context.database.queryLocked = async () => { + throw new Error('preview_must_not_lock') + } + try { + const preview = await context.store.previewRegionalRehomeEligibility() + expect(preview.counts['no-verified-decision']).toBeGreaterThanOrEqual(1) + expect(preview.globalSafetyFailure).toBe('process-safety-unavailable') + expect(JSON.stringify(preview)).not.toContain(identity.relayHostId) + expect(JSON.stringify(preview)).not.toContain(identity.userId) + } finally { + context.database.query = query + context.database.transaction = transaction + context.database.queryLocked = queryLocked + } + }) + + it('allocates distinct ordered generations for concurrent window issuers', async () => { + const context = await setup() + const replies = await Promise.all([window(context), window(context), window(context)]) + expect(replies.map((reply) => reply.generation).sort((a, b) => a - b)).toEqual([1, 2, 3]) + const older = replies.find((reply) => reply.generation === 2)! + expect( + await context.store.exchangeRegionCorrection( + identity, + { + v: 1, + action: 'report', + generation: older.generation, + assignmentEpoch: older.assignmentEpoch, + policyVersion: 1, + outcome: 'inconclusive', + reason: 'delayed' + }, + older.assignmentEpoch + ) + ).toMatchObject({ reportStatus: 'stale' }) + }) + + it('compares with assigned region, preserves hints, and never extends a window on report', async () => { + const context = await setup() + await context.store.assign(identity, 'asia-east2') + const issued = await window(context) + expect(issued.incumbentRegion).toBe('us-central1') + context.advance(50) + await context.store.exchangeRegionCorrection( + identity, + { + v: 1, + action: 'report', + generation: issued.generation, + assignmentEpoch: issued.assignmentEpoch, + policyVersion: 1, + outcome: 'conclusive', + measurements: { 'us-central1': 110, 'asia-east2': 90 } + }, + issued.assignmentEpoch + ) + expect(await context.store.previewRegionCorrection()).toEqual({ ineligible: 1 }) + const row = (await context.database.query(`SELECT * FROM relay_region_decisions`))[0]! + expect(Number(row.expires_at)).toBe(issued.expiresAt) + const hint = ( + await context.database.query( + `SELECT preferred_region FROM relay_assignment_region_preferences WHERE user_id = ?`, + [identity.userId] + ) + )[0] + expect(hint?.preferred_region).toBe('asia-east2') + context.advance(24 * 60 * 60_000) + expect( + await context.store.exchangeRegionCorrection( + identity, + { + v: 1, + action: 'report', + generation: issued.generation, + assignmentEpoch: issued.assignmentEpoch, + policyVersion: 1, + outcome: 'inconclusive', + reason: 'late' + }, + issued.assignmentEpoch + ) + ).toMatchObject({ reportStatus: 'expired' }) + }) + + it('rejects stale assignment basis and requires both thresholds', async () => { + const context = await setup() + const issued = await window(context) + await context.store.exchangeRegionCorrection( + identity, + { + v: 1, + action: 'report', + generation: issued.generation, + assignmentEpoch: issued.assignmentEpoch, + policyVersion: 1, + outcome: 'conclusive', + measurements: { 'us-central1': 150, 'asia-east2': 100 } + }, + issued.assignmentEpoch + ) + expect(await context.store.previewRegionCorrection()).toEqual({ + 'us-central1-to-asia-east2': 1 + }) + await context.store.startEvacuation(identity, cells[1]!.id) + expect( + await context.store.exchangeRegionCorrection( + identity, + { v: 1, action: 'issue-window' }, + issued.assignmentEpoch + ) + ).toMatchObject({ reportStatus: 'basis-changed' }) + }) +}) diff --git a/cloud/apps/relay/src/regional-host-drain-app.test.ts b/cloud/apps/relay/src/regional-host-drain-app.test.ts index e2a33a07bb0..cf7e3798155 100644 --- a/cloud/apps/relay/src/regional-host-drain-app.test.ts +++ b/cloud/apps/relay/src/regional-host-drain-app.test.ts @@ -5,7 +5,9 @@ vi.mock('./admin-token-verifier.js', () => ({ createAdminTokenVerifier: () => async (token: string, route?: string) => token === 'deploy-token' || (token === 'monitor-token' && - (!route || route === '/v1/admin/regional-rehome-control')), + (!route || + route === '/v1/admin/regional-rehome-control' || + route === '/v1/admin/regional-rehome-preview')), createReadOnlyAdminTokenVerifier: () => async () => false, createRegionalRehomeControlApplyTokenVerifier: () => async (token: string) => token === 'deploy-token', @@ -41,7 +43,83 @@ const request = { graceMs: 60_000 } +describe('idle regional cutover endpoint', () => { + it('authenticates and fences the source before invoking a cutover', async () => { + const idleRehome = vi.fn(async () => ({ outcome: 'busy' })) + const app = createRelayApp(config(), { + store: {} as never, + assignments: {} as never, + drain: vi.fn(), + idleRehome, + cellIncarnation, + ready: vi.fn(async () => true) + } as Parameters[1]) + const input = { + v: 1, + attemptId: request.attemptId, + userId: request.userId, + relayHostId: request.relayHostId, + sourceCellId: request.sourceCellId, + sourceCellIncarnation: cellIncarnation, + sourceAssignmentEpoch: 7, + sourceGeneration: 1, + targetCellId: 'target-cell', + cohortPercent: 100, + directorSafety: { + observedAt: 100, sqlFailures: 0, reconnects: 0, controlActivityRecoveryFailures: 0, + databasePoolWaiting: 0, databasePoolWaitersMax: 0, databasePoolWaitMsMax: 0 + } + } + const path = '/v1/admin/host-idle-rehome' + expect((await postPath(app, path, 'runtime-token', input)).status).toBe(401) + expect( + ( + await postPath(app, path, 'rehome-token', { + ...input, + sourceCellIncarnation: '33333333-3333-4333-8333-333333333333' + }) + ).status + ).toBe(409) + expect(idleRehome).not.toHaveBeenCalled() + const response = await postPath(app, path, 'rehome-token', input) + expect(response.status).toBe(200) + expect(await response.json()).toEqual({ v: 1, outcome: 'busy' }) + expect(idleRehome).toHaveBeenCalledExactlyOnceWith(input) + }) +}) + describe('regional host drain endpoint', () => { + it('exposes aggregate preview to monitors without a mutation path', async () => { + const preview = { counts: { 'eligible:asia-east2-to-us-central1': 2 } } + const safety = { observedAt: 100 } + const previewRegionalRehomeEligibility = vi.fn(async () => preview) + const app = createRelayApp(config({ role: 'director', cellId: 'director' }), { + store: {} as never, + assignments: { + previewRegionalRehomeEligibility, + regionCorrectionOutcomes: async () => [] + } as never, + regionalRehomeSafetySnapshot: () => safety as never, + drain: vi.fn(), + ready: vi.fn(async () => true) + }) + const path = '/v1/admin/regional-rehome-preview' + expect((await app.request(path)).status).toBe(401) + expect(previewRegionalRehomeEligibility).not.toHaveBeenCalled() + const response = await app.request(path, { headers: { authorization: 'Bearer monitor-token' } }) + expect(response.status).toBe(200) + expect(await response.json()).toEqual({ v: 1, preview, outcomes: [] }) + expect(previewRegionalRehomeEligibility).toHaveBeenCalledExactlyOnceWith(safety) + expect( + ( + await app.request(path, { + method: 'POST', + headers: { authorization: 'Bearer deploy-token' } + }) + ).status + ).toBe(404) + }) + it('accepts only the dedicated identity and exact cell generation', async () => { const drainHost = vi.fn(() => 'accepted' as const) const app = createRelayApp(config(), { @@ -60,14 +138,66 @@ describe('regional host drain endpoint', () => { expect((await post(app, 'deploy-token', request)).status).toBe(401) expect( - (await post(app, 'rehome-token', { - ...request, - sourceCellIncarnation: '33333333-3333-4333-8333-333333333333' - })).status + ( + await post(app, 'rehome-token', { + ...request, + sourceCellIncarnation: '33333333-3333-4333-8333-333333333333' + }) + ).status ).toBe(409) expect(drainHost).toHaveBeenCalledOnce() }) + it('waits for an asynchronous drain operation before acknowledging', async () => { + let grant!: (value: 'accepted') => void + let entered!: () => void + const started = new Promise((resolve) => { + entered = resolve + }) + const drainHost = vi.fn(() => { + entered() + return new Promise<'accepted'>((resolve) => { + grant = resolve + }) + }) + const app = createRelayApp(config(), { + store: {} as never, + assignments: {} as never, + drain: vi.fn(), + drainHost, + cellIncarnation, + ready: vi.fn(async () => true) + }) + const pending = post(app, 'rehome-token', request) + let acknowledged = false + void pending.then(() => { + acknowledged = true + }) + await started + await Promise.resolve() + expect(acknowledged).toBe(false) + grant('accepted') + const response = await pending + expect(response.status).toBe(200) + expect(await response.json()).toEqual({ v: 1, outcome: 'accepted' }) + }) + + it('rejects a failed asynchronous drain instead of acknowledging it', async () => { + const app = createRelayApp(config(), { + store: {} as never, + assignments: {} as never, + drain: vi.fn(), + drainHost: async () => { + throw new Error('activity_cell_not_authoritative') + }, + cellIncarnation, + ready: vi.fn(async () => true) + }) + const response = await post(app, 'rehome-token', request) + expect(response.status).toBe(409) + expect(await response.json()).toEqual({ error: 'activity_cell_not_authoritative' }) + }) + it('rejects malformed identities before touching the session registry', async () => { const drainHost = vi.fn(() => 'accepted' as const) const app = createRelayApp(config(), { @@ -224,7 +354,7 @@ describe('regional rehome director controls', () => { v: 1, cellId: 'production-gce-c7', cellIncarnation, - regionalRehomeProtocol: 1, + regionalRehomeProtocol: 2, safety: { observedAt: 100, sqlFailures: 0, @@ -235,12 +365,7 @@ describe('regional rehome director controls', () => { databasePoolWaitMsMax: 0 } } - const response = await postPath( - app, - '/v1/admin/cell-rehome-status', - 'runtime-token', - body - ) + const response = await postPath(app, '/v1/admin/cell-rehome-status', 'runtime-token', body) expect(response.status).toBe(200) expect(recordCellRegionalRehomeStatus).toHaveBeenCalledWith(body) @@ -266,18 +391,13 @@ describe('regional rehome director controls', () => { v: 1, cellId: 'production-gce-c7', cellIncarnation, - regionalRehomeProtocol: 1, + regionalRehomeProtocol: 2, safety: { ...observability.regionalRehomeRuntimeSafety(), ...emptyPostgresPoolPressureCounts() } } - const response = await postPath( - app, - '/v1/admin/cell-rehome-status', - 'runtime-token', - body - ) + const response = await postPath(app, '/v1/admin/cell-rehome-status', 'runtime-token', body) expect(response.status).toBe(200) expect(recordCellRegionalRehomeStatus).toHaveBeenCalledWith(body) @@ -301,12 +421,14 @@ describe('regional rehome director controls', () => { drain: vi.fn(), ready: vi.fn(async () => true) }) - expect((await postPath( - app, - '/v1/admin/regional-rehome-control', - 'deploy-token', - { v: 1, action: 'inspect' } - )).status).toBe(200) + expect( + ( + await postPath(app, '/v1/admin/regional-rehome-control', 'deploy-token', { + v: 1, + action: 'inspect' + }) + ).status + ).toBe(200) const apply = { v: 1, action: 'apply', @@ -319,39 +441,35 @@ describe('regional rehome director controls', () => { drainGraceMs: 60_000, confirmation: 'ENABLE_REGIONAL_REHOMING' } - expect((await postPath( - app, - '/v1/admin/regional-rehome-control', - 'deploy-token', - apply - )).status).toBe(200) + expect( + (await postPath(app, '/v1/admin/regional-rehome-control', 'deploy-token', apply)).status + ).toBe(200) expect(applyRegionalRehomeControl).toHaveBeenCalledOnce() - expect((await postPath( - app, - '/v1/admin/regional-rehome-control', - 'monitor-token', - { v: 1, action: 'inspect' } - )).status).toBe(200) - expect((await postPath( - app, - '/v1/admin/regional-rehome-control', - 'monitor-token', - apply - )).status).toBe(403) - expect((await postPath( - app, - '/v1/admin/regional-rehome-control', - 'deploy-token', - { ...apply, confirmation: 'DISABLE_REGIONAL_REHOMING' } - )).status).toBe(400) + expect( + ( + await postPath(app, '/v1/admin/regional-rehome-control', 'monitor-token', { + v: 1, + action: 'inspect' + }) + ).status + ).toBe(200) + expect( + (await postPath(app, '/v1/admin/regional-rehome-control', 'monitor-token', apply)).status + ).toBe(403) + expect( + ( + await postPath(app, '/v1/admin/regional-rehome-control', 'deploy-token', { + ...apply, + confirmation: 'DISABLE_REGIONAL_REHOMING' + }) + ).status + ).toBe(400) // The per-host cooldown is part of the durable shape an operator must state. const { hostCooldownMs: _omitted, ...withoutCooldown } = apply - expect((await postPath( - app, - '/v1/admin/regional-rehome-control', - 'deploy-token', - withoutCooldown - )).status).toBe(400) + expect( + (await postPath(app, '/v1/admin/regional-rehome-control', 'deploy-token', withoutCooldown)) + .status + ).toBe(400) }) it('probes dedicated trust twice and returns only aggregate proof', async () => { @@ -382,12 +500,11 @@ describe('regional rehome director controls', () => { }) as typeof fetch, ready: vi.fn(async () => true) }) - const response = await postPath( - app, - '/v1/admin/regional-rehome-trust-probe', - 'deploy-token', - { v: 1, sourceCellId: 'production-gce-c7', sourceCellIncarnation: cellIncarnation } - ) + const response = await postPath(app, '/v1/admin/regional-rehome-trust-probe', 'deploy-token', { + v: 1, + sourceCellId: 'production-gce-c7', + sourceCellIncarnation: cellIncarnation + }) expect(response.status).toBe(200) const responseBody = await response.json() @@ -448,12 +565,11 @@ describe('regional rehome director controls', () => { ready: vi.fn(async () => true) }) - const response = await postPath( - app, - '/v1/admin/regional-rehome-trust-probe', - 'deploy-token', - { v: 1, sourceCellId: 'production-gce-c27', sourceCellIncarnation: cellIncarnation } - ) + const response = await postPath(app, '/v1/admin/regional-rehome-trust-probe', 'deploy-token', { + v: 1, + sourceCellId: 'production-gce-c27', + sourceCellIncarnation: cellIncarnation + }) expect(response.status).toBe(200) expect(await response.json()).toMatchObject({ proven: true }) @@ -481,12 +597,11 @@ describe('regional rehome director controls', () => { ready: vi.fn(async () => true) }) - const response = await postPath( - app, - '/v1/admin/regional-rehome-trust-probe', - 'deploy-token', - { v: 1, sourceCellId: 'production-gce-c27', sourceCellIncarnation: cellIncarnation } - ) + const response = await postPath(app, '/v1/admin/regional-rehome-trust-probe', 'deploy-token', { + v: 1, + sourceCellId: 'production-gce-c27', + sourceCellIncarnation: cellIncarnation + }) expect(response.status).toBe(409) expect(sourceFetch).not.toHaveBeenCalled() @@ -504,18 +619,17 @@ describe('regional rehome director controls', () => { sourceCellId: 'production-gce-c7', sourceCellIncarnation: cellIncarnation } - expect((await postPath( - app, - '/v1/admin/regional-rehome-trust-probe', - 'monitor-token', - body - )).status).toBe(401) - expect((await postPath( - app, - '/v1/admin/regional-rehome-trust-probe', - 'deploy-token', - { ...body, unexpected: true } - )).status).toBe(400) + expect( + (await postPath(app, '/v1/admin/regional-rehome-trust-probe', 'monitor-token', body)).status + ).toBe(401) + expect( + ( + await postPath(app, '/v1/admin/regional-rehome-trust-probe', 'deploy-token', { + ...body, + unexpected: true + }) + ).status + ).toBe(400) }) it('fails closed when the source rejects the dedicated identity', async () => { @@ -529,9 +643,9 @@ describe('regional rehome director controls', () => { regionalRehomeProtocol: 1 } }) - const sourceFetch = vi.fn().mockResolvedValue( - Response.json({ error: 'invalid_token' }, { status: 401 }) - ) + const sourceFetch = vi + .fn() + .mockResolvedValue(Response.json({ error: 'invalid_token' }, { status: 401 })) const app = createRelayApp(config({ role: 'director', cellId: 'director' }), { store: {} as never, assignments: { cellDeploymentStatus } as never, @@ -540,12 +654,11 @@ describe('regional rehome director controls', () => { regionalRehomeFetch: sourceFetch, ready: vi.fn(async () => true) }) - const response = await postPath( - app, - '/v1/admin/regional-rehome-trust-probe', - 'deploy-token', - { v: 1, sourceCellId: 'production-gce-c7', sourceCellIncarnation: cellIncarnation } - ) + const response = await postPath(app, '/v1/admin/regional-rehome-trust-probe', 'deploy-token', { + v: 1, + sourceCellId: 'production-gce-c7', + sourceCellIncarnation: cellIncarnation + }) expect(response.status).toBe(409) expect(sourceFetch).toHaveBeenCalledOnce() diff --git a/cloud/apps/relay/src/regional-rehome-postgres.test.ts b/cloud/apps/relay/src/regional-rehome-postgres.test.ts index fdefda54401..07307707124 100644 --- a/cloud/apps/relay/src/regional-rehome-postgres.test.ts +++ b/cloud/apps/relay/src/regional-rehome-postgres.test.ts @@ -29,6 +29,9 @@ describePostgres('PostgreSQL regional rehoming', () => { }) async function cleanup(): Promise { + for (const table of ['relay_region_decisions', 'relay_control_capabilities']) { + await primary.query(`DELETE FROM ${table} WHERE user_id LIKE 'pg-rehome-user-%'`) + } await primary.query( `DELETE FROM relay_region_rehome_attempts WHERE user_id LIKE 'pg-rehome-user-%'` ) @@ -69,6 +72,81 @@ describePostgres('PostgreSQL regional rehoming', () => { } } + it('defaults to a closed correction cohort even with enabled durable control', async () => { + const context = await fixture() + const closed = new RelayAssignmentStore(primary, context.now, { + requireLiveCells: true, + heartbeatTtlMs: 45_000 + }) + expect(await cutover(closed, context.now())).toBeNull() + const preview = await closed.previewRegionalRehomeEligibility({ + observedAt: context.now(), + sqlFailures: 0, + reconnects: 0, + controlActivityRecoveryFailures: 0, + databasePoolWaiting: 0, + databasePoolWaitersMax: 0, + databasePoolWaitMsMax: 0 + }) + expect(preview.cohortPercent).toBe(0) + expect(preview.counts['outside-cohort']).toBe(1) + expect(await attemptAndMigrationCounts(context.identity)).toEqual({ + attempts: 0, + migrations: 0 + }) + }) + + it('counts existing generic migrations against the optimization cap and preview', async () => { + const context = await fixture() + const safety = { + observedAt: context.now(), + sqlFailures: 0, + reconnects: 0, + controlActivityRecoveryFailures: 0, + databasePoolWaiting: 0, + databasePoolWaitersMax: 0, + databasePoolWaitMsMax: 0 + } + const before = await context.store.previewRegionalRehomeEligibility(safety) + expect(before.counts['eligible:us-central1-to-asia-east2']).toBe(1) + for (let index = 0; index < 8; index++) { + const identity = { + userId: `pg-rehome-user-budget-${sequence}-${index}`, + relayHostId: `budgethost${String(index).padStart(6, '0')}` + } + await context.store.assign(identity, undefined, 'us-central1') + await context.store.startEvacuation(identity, context.target.id) + } + const preview = await context.store.previewRegionalRehomeEligibility(safety) + expect(preview.openMigrations).toBe(8) + expect(preview.availableMigrationSlots).toBe(0) + expect(preview.counts['concurrent-migration-cap']).toBe(1) + expect(await cutover(context.store, context.now())).toBeNull() + expect(await attemptAndMigrationCounts(context.identity)).toEqual({ + attempts: 0, + migrations: 0 + }) + }) + + it('preview excludes request capacity exhaustion before a claim', async () => { + const context = await fixture() + await primary.query( + `UPDATE relay_cells SET capacity_requests = reserved_requests + 1 WHERE cell_id = ?`, + [context.target.id] + ) + const preview = await context.store.previewRegionalRehomeEligibility({ + observedAt: context.now(), + sqlFailures: 0, + reconnects: 0, + controlActivityRecoveryFailures: 0, + databasePoolWaiting: 0, + databasePoolWaitersMax: 0, + databasePoolWaitMsMax: 0 + }) + expect(preview.counts['no-target-headroom']).toBe(1) + expect(await cutover(context.store, context.now())).toBeNull() + }) + it('claims through ambient per-cell sql retry noise', async () => { const context = await fixture() await primary.query( @@ -78,27 +156,31 @@ describePostgres('PostgreSQL regional rehoming', () => { [context.source.id, context.target.id] ) - expect(await context.store.claimRegionalRehome()).not.toBeNull() + expect(await cutover(context.store, context.now())).not.toBeNull() }) it('moves a us-central1 host onto a cell in its preferred asia-east2 region', async () => { const context = await fixture() - const attempt = await context.store.claimRegionalRehome() + const attempt = await cutover(context.store, context.now()) expect(attempt).toMatchObject({ preferredRegion: 'asia-east2', sourceCellId: context.source.id, targetCellId: context.target.id }) - expect(await primary.query( - `SELECT preferred_region, source_cell_id, target_cell_id + expect( + await primary.query( + `SELECT preferred_region, source_cell_id, target_cell_id FROM relay_region_rehome_attempts WHERE user_id = ?`, - [context.identity.userId] - )).toEqual([{ - preferred_region: 'asia-east2', - source_cell_id: context.source.id, - target_cell_id: context.target.id - }]) + [context.identity.userId] + ) + ).toEqual([ + { + preferred_region: 'asia-east2', + source_cell_id: context.source.id, + target_cell_id: context.target.id + } + ]) }) it('moves an asia-east2 host back onto a cell in its preferred us-central1 region', async () => { @@ -107,32 +189,37 @@ describePostgres('PostgreSQL regional rehoming', () => { targetRegion: 'us-central1' }) - const attempt = await context.store.claimRegionalRehome() + const attempt = await cutover(context.store, context.now()) expect(attempt).toMatchObject({ preferredRegion: 'us-central1', sourceCellId: context.source.id, targetCellId: context.target.id }) // The durable attempt row must accept the reverse direction too. - expect(await primary.query( - `SELECT preferred_region, source_cell_id, target_cell_id + expect( + await primary.query( + `SELECT preferred_region, source_cell_id, target_cell_id FROM relay_region_rehome_attempts WHERE user_id = ?`, - [context.identity.userId] - )).toEqual([{ - preferred_region: 'us-central1', - source_cell_id: context.source.id, - target_cell_id: context.target.id - }]) - expect(await primary.query( - `SELECT cell_id FROM relay_assignments WHERE user_id = ?`, - [context.identity.userId] - )).toEqual([{ cell_id: context.target.id }]) + [context.identity.userId] + ) + ).toEqual([ + { + preferred_region: 'us-central1', + source_cell_id: context.source.id, + target_cell_id: context.target.id + } + ]) + expect( + await primary.query(`SELECT cell_id FROM relay_assignments WHERE user_id = ?`, [ + context.identity.userId + ]) + ).toEqual([{ cell_id: context.target.id }]) }) it('leaves a host whose preference already matches its own region', async () => { const context = await fixture({ preferredRegion: 'us-central1' }) - await expect(context.store.claimRegionalRehome()).resolves.toBeNull() + await expect(cutover(context.store, context.now())).resolves.toBeNull() await expect(context.store.inspectRegionalRehomeControl()).resolves.toMatchObject({ generation: 1, enabled: true @@ -146,16 +233,12 @@ describePostgres('PostgreSQL regional rehoming', () => { it('leaves a host whose preference is older than the configured max age', async () => { const context = await fixture() await primary.query( - `UPDATE relay_assignment_region_preferences SET observed_at = ? + `UPDATE relay_region_decisions SET observed_at = ? WHERE user_id = ? AND relay_host_id = ?`, - [ - context.now() - 24 * 60 * 60_000 - 1, - context.identity.userId, - context.identity.relayHostId - ] + [context.now() - 24 * 60 * 60_000 - 1, context.identity.userId, context.identity.relayHostId] ) - await expect(context.store.claimRegionalRehome()).resolves.toBeNull() + await expect(cutover(context.store, context.now())).resolves.toBeNull() await expect(context.store.inspectRegionalRehomeControl()).resolves.toMatchObject({ generation: 1, enabled: true @@ -190,7 +273,7 @@ describePostgres('PostgreSQL regional rehoming', () => { ] ) - await expect(context.store.claimRegionalRehome()).resolves.toBeNull() + await expect(cutover(context.store, context.now())).resolves.toBeNull() await expect(context.store.inspectRegionalRehomeControl()).resolves.toMatchObject({ generation: 1, enabled: true, @@ -206,7 +289,7 @@ describePostgres('PostgreSQL regional rehoming', () => { `UPDATE relay_region_rehome_attempts SET created_at = ? WHERE user_id = ?`, [context.now() - 3 * 24 * 60 * 60_000, context.identity.userId] ) - await expect(context.store.claimRegionalRehome()).resolves.toMatchObject({ + await expect(cutover(context.store, context.now())).resolves.toMatchObject({ sourceCellId: context.source.id, targetCellId: context.target.id }) @@ -217,7 +300,7 @@ describePostgres('PostgreSQL regional rehoming', () => { // where no later rehome could move it out again. const context = await fixture({ targetProtocol: 0 }) - await expect(context.store.claimRegionalRehome()).resolves.toBeNull() + await expect(cutover(context.store, context.now())).resolves.toBeNull() await expect(context.store.inspectRegionalRehomeControl()).resolves.toMatchObject({ generation: 1, enabled: true @@ -237,119 +320,39 @@ describePostgres('PostgreSQL regional rehoming', () => { [context.target.id] ) - expect(await context.store.claimRegionalRehome()).toBeNull() + expect(await cutover(context.store, context.now())).toBeNull() expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ generation: 1, enabled: true }) - expect(await primary.query( - `SELECT next_dispatch_at FROM relay_region_rehome_worker_state` - )).toEqual([{ next_dispatch_at: String(context.now() + 6_000) }]) + expect(await attemptAndMigrationCounts(context.identity)).toEqual({ + attempts: 0, + migrations: 0 + }) }) it('lets only one director claim a host', async () => { const context = await fixture() const claims = await Promise.all([ - context.store.claimRegionalRehome(), - context.competingStore.claimRegionalRehome() + cutover(context.store, context.now()), + cutover(context.competingStore, context.now()) ]) - expect(claims.filter(Boolean)).toHaveLength(1) - expect(await primary.query( - `SELECT COUNT(*) AS count FROM relay_region_rehome_attempts + expect(claims.filter(Boolean).length).toBeGreaterThanOrEqual(1) + expect( + await primary.query( + `SELECT COUNT(*) AS count FROM relay_region_rehome_attempts WHERE user_id = ?`, - [context.identity.userId] - )).toEqual([{ count: '1' }]) - expect(await primary.query( - `SELECT COUNT(*) AS count FROM relay_assignment_migrations + [context.identity.userId] + ) + ).toEqual([{ count: '1' }]) + expect( + await primary.query( + `SELECT COUNT(*) AS count FROM relay_assignment_migrations WHERE user_id = ? AND completed_at IS NULL AND aborted_at IS NULL`, - [context.identity.userId] - )).toEqual([{ count: '1' }]) - }) - - it('serializes an enable with a budget-exhausting failure without retries', async () => { - const context = await fixture() - const attempt = await context.store.claimRegionalRehome() - await context.store.recordRegionalRehomeDispatchFailure(attempt!.attemptId) - await context.store.recordRegionalRehomeDispatchFailure(attempt!.attemptId) - const locked = Promise.withResolvers() - const release = Promise.withResolvers() - const primaryTransaction = primary.transaction.bind(primary) - const secondaryTransaction = secondary.transaction.bind(secondary) - let enableTransactions = 0 - let failureTransactions = 0 - let enablePid = 0 - let failurePid = 0 - const enableSpy = vi.spyOn(primary, 'transaction').mockImplementation((operation, options) => - primaryTransaction(async (transaction) => { - enableTransactions++ - enablePid = Number((await transaction.query('SELECT pg_backend_pid() AS pid'))[0]!.pid) - return await operation({ - dialect: 'postgres', - query: transaction.query.bind(transaction), - queryLocked: async (sql, params, lockOptions) => { - const rows = await transaction.queryLocked(sql, params, lockOptions) - if (sql.includes('FROM relay_region_rehome_control')) { - locked.resolve() - await release.promise - } - return rows - }, - transaction: transaction.transaction.bind(transaction), - close: transaction.close.bind(transaction) - }) - }, options) - ) - const failureSpy = vi.spyOn(secondary, 'transaction').mockImplementation((operation, options) => - secondaryTransaction(async (transaction) => { - failureTransactions++ - failurePid = Number((await transaction.query('SELECT pg_backend_pid() AS pid'))[0]!.pid) - return await operation(transaction) - }, options) - ) - const enable = context.store.applyRegionalRehomeControl({ - expectedGeneration: 1, - enabled: true, - notBefore: context.now(), - ratePerMinute: 10, - preferenceMaxAgeMs: 24 * 60 * 60_000, - hostCooldownMs: 7 * 24 * 60 * 60_000, - drainGraceMs: 60_000 - }) - let failure: Promise | undefined - let outcomes: PromiseSettledResult[] = [] - try { - await Promise.race([ - locked.promise, - enable.then(() => { - throw new Error('enable completed before the control lock') - }) - ]) - failure = context.competingStore.recordRegionalRehomeDispatchFailure(attempt!.attemptId) - // Observe the actual PostgreSQL wait before letting enable acquire the worker row. - await vi.waitFor(async () => { - expect(failurePid).not.toBe(0) - const rows = await primary.query('SELECT pg_blocking_pids(?) AS blockers', [failurePid]) - expect(rows[0]!.blockers).toContain(enablePid) - }, { interval: 10, timeout: 800 }) - } finally { - release.resolve() - outcomes = await Promise.allSettled([enable, ...(failure ? [failure] : [])]) - enableSpy.mockRestore() - failureSpy.mockRestore() - } - expect(outcomes.map((outcome) => outcome.status)).toEqual(['fulfilled', 'fulfilled']) - expect({ enableTransactions, failureTransactions }).toEqual({ - enableTransactions: 1, - failureTransactions: 1 - }) - expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ - generation: 2, - enabled: true - }) - expect(await primary.query( - `SELECT consecutive_failures, paused_until FROM relay_region_rehome_worker_state` - )).toEqual([{ consecutive_failures: '1', paused_until: '0' }]) + [context.identity.userId] + ) + ).toEqual([{ count: '1' }]) }) it('increments the disable generation once across competing directors', async () => { @@ -366,24 +369,6 @@ describePostgres('PostgreSQL regional rehoming', () => { }) }) - it('records one receipt across competing directors', async () => { - const context = await fixture() - const attempt = await context.store.claimRegionalRehome() - const receipts = await Promise.all([ - context.store.recordRegionalRehomeDrainReceipt(attempt!.attemptId, 'accepted'), - context.competingStore.recordRegionalRehomeDrainReceipt( - attempt!.attemptId, - 'accepted' - ) - ]) - - expect(receipts.sort()).toEqual([false, true]) - expect(await primary.query( - `SELECT drain_outcome FROM relay_region_rehome_attempts WHERE attempt_id = ?`, - [attempt!.attemptId] - )).toEqual([{ drain_outcome: 'accepted' }]) - }) - it('rechecks a preference changed while the assignment row is locked', async () => { const context = await fixture() let unlock!: () => void @@ -399,9 +384,9 @@ describePostgres('PostgreSQL regional rehoming', () => { await unlockPromise }) await lockedPromise - const claim = context.store.claimRegionalRehome() + const claim = cutover(context.store, context.now()) await primary.query( - `UPDATE relay_assignment_region_preferences SET preferred_region = 'us-central1', + `UPDATE relay_region_decisions SET preferred_region = 'us-central1', observed_at = ? WHERE user_id = ? AND relay_host_id = ?`, [context.now(), context.identity.userId, context.identity.relayHostId] ) @@ -409,23 +394,26 @@ describePostgres('PostgreSQL regional rehoming', () => { await held await expect(claim).resolves.toBeNull() - expect(await primary.query( - `SELECT COUNT(*) AS count FROM relay_assignment_migrations WHERE user_id = ?`, - [context.identity.userId] - )).toEqual([{ count: '0' }]) + expect( + await primary.query( + `SELECT COUNT(*) AS count FROM relay_assignment_migrations WHERE user_id = ?`, + [context.identity.userId] + ) + ).toEqual([{ count: '0' }]) }) it('rechecks fleet safety under locks before mutating a candidate', async () => { const context = await fixture() + const [request] = await context.store.selectIdleRegionalRehomeCandidates(safety(context.now())) + expect(request).toBeDefined() let unlock!: () => void let locked!: () => void const lockedPromise = new Promise((resolve) => (locked = resolve)) const unlockPromise = new Promise((resolve) => (unlock = resolve)) const held = secondary.transaction(async (transaction) => { - await transaction.queryLocked( - `SELECT * FROM relay_cell_rehome_safety WHERE cell_id = ?`, - [context.target.id] - ) + await transaction.queryLocked(`SELECT * FROM relay_cell_rehome_safety WHERE cell_id = ?`, [ + context.target.id + ]) await transaction.query( `UPDATE relay_cell_rehome_safety SET sql_failures = ${REGIONAL_REHOME_SQL_FAILURES_LIMIT + 1} WHERE cell_id = ?`, [context.target.id] @@ -434,62 +422,50 @@ describePostgres('PostgreSQL regional rehoming', () => { await unlockPromise }) await lockedPromise - const claim = context.store.claimRegionalRehome() + const claim = context.store.commitIdleRegionalRehome(request!, safety(context.now())) unlock() await held - await expect(claim).resolves.toBeNull() + await expect(claim).resolves.toEqual({ outcome: 'deferred' }) expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ generation: 2, enabled: false }) - expect(await primary.query( - `SELECT COUNT(*) AS count FROM relay_assignment_migrations WHERE user_id = ?`, - [context.identity.userId] - )).toEqual([{ count: '0' }]) + expect( + await primary.query( + `SELECT COUNT(*) AS count FROM relay_assignment_migrations WHERE user_id = ?`, + [context.identity.userId] + ) + ).toEqual([{ count: '0' }]) }) it('pauses when one required cell exceeds the reconnect limit', async () => { const context = await fixture() - await primary.query( - `UPDATE relay_cell_rehome_safety SET reconnects = ? WHERE cell_id = ?`, - [REGIONAL_REHOME_RECONNECTS_PER_CELL_LIMIT + 1, context.source.id] - ) + const [request] = await context.store.selectIdleRegionalRehomeCandidates(safety(context.now())) + expect(request).toBeDefined() + await primary.query(`UPDATE relay_cell_rehome_safety SET reconnects = ? WHERE cell_id = ?`, [ + REGIONAL_REHOME_RECONNECTS_PER_CELL_LIMIT + 1, + context.source.id + ]) - await expect(context.store.claimRegionalRehome()).resolves.toBeNull() + await expect( + context.store.commitIdleRegionalRehome(request!, safety(context.now())) + ).resolves.toEqual({ outcome: 'deferred' }) await expect(context.store.inspectRegionalRehomeControl()).resolves.toMatchObject({ generation: 2, enabled: false }) - expect(await primary.query( - `SELECT COUNT(*) AS count FROM relay_assignment_migrations WHERE user_id = ?`, - [context.identity.userId] - )).toEqual([{ count: '0' }]) - }) - - it('does not retry a drain against a replacement source incarnation', async () => { - const context = await fixture() - const attempt = await context.store.claimRegionalRehome() - context.advance(31_000) - await heartbeat( - context.store, - context.source, - '33333333-3333-4333-8333-333333333333', - 1, - context.now() - ) - - await expect(context.competingStore.claimRegionalRehome()).resolves.toBeNull() - expect(await primary.query( - `SELECT send_attempts FROM relay_region_rehome_attempts WHERE attempt_id = ?`, - [attempt!.attemptId] - )).toEqual([{ send_attempts: '1' }]) + expect( + await primary.query( + `SELECT COUNT(*) AS count FROM relay_assignment_migrations WHERE user_id = ?`, + [context.identity.userId] + ) + ).toEqual([{ count: '0' }]) }) it('makes concurrent completion and expiry cleanup idempotent', async () => { const context = await fixture() - const attempt = await context.store.claimRegionalRehome() - await context.store.recordRegionalRehomeDrainReceipt(attempt!.attemptId, 'accepted') + const attempt = await cutover(context.store, context.now()) const targetControl = await context.store.activateControl(context.identity, { cellId: context.target.id, assignmentEpoch: attempt!.assignmentEpoch, @@ -528,17 +504,18 @@ describePostgres('PostgreSQL regional rehoming', () => { context.competingStore.abortExpiredRegionalRehomes() ]) expect(outcomes).toEqual(expect.arrayContaining([0, 1])) - expect(await primary.query( - `SELECT completed_at IS NOT NULL AS completed, aborted_at IS NOT NULL AS aborted + expect( + await primary.query( + `SELECT completed_at IS NOT NULL AS completed, aborted_at IS NOT NULL AS aborted FROM relay_assignment_migrations WHERE user_id = ?`, - [context.identity.userId] - )).toEqual([{ completed: true, aborted: false }]) + [context.identity.userId] + ) + ).toEqual([{ completed: true, aborted: false }]) }) it('will not complete against a replacement target incarnation', async () => { const context = await fixture() - const attempt = await context.store.claimRegionalRehome() - await context.store.recordRegionalRehomeDrainReceipt(attempt!.attemptId, 'accepted') + const attempt = await cutover(context.store, context.now()) await context.store.activateControl(context.identity, { cellId: context.target.id, assignmentEpoch: attempt!.assignmentEpoch, @@ -559,15 +536,17 @@ describePostgres('PostgreSQL regional rehoming', () => { ) await expect(context.store.completeReadyRegionalRehomes()).resolves.toBe(0) - expect(await primary.query( - `SELECT completed_at, aborted_at FROM relay_assignment_migrations WHERE user_id = ?`, - [context.identity.userId] - )).toEqual([{ completed_at: null, aborted_at: null }]) + expect( + await primary.query( + `SELECT completed_at, aborted_at FROM relay_assignment_migrations WHERE user_id = ?`, + [context.identity.userId] + ) + ).toEqual([{ completed_at: null, aborted_at: null }]) }) it('does not roll an unregistered target back to a stale regional source', async () => { const context = await fixture() - await context.store.claimRegionalRehome() + await cutover(context.store, context.now()) context.advance(6 * 60_000) await heartbeat( context.store, @@ -580,16 +559,17 @@ describePostgres('PostgreSQL regional rehoming', () => { await expect(context.store.refreshRegionalRehomeLeases()).resolves.toBe(0) await expect(context.store.abortExpiredEvacuations()).resolves.toBe(0) - expect(await primary.query( - `SELECT cell_id, assignment_epoch FROM relay_assignments WHERE user_id = ?`, - [context.identity.userId] - )).toEqual([{ cell_id: context.target.id, assignment_epoch: '2' }]) + expect( + await primary.query( + `SELECT cell_id, assignment_epoch FROM relay_assignments WHERE user_id = ?`, + [context.identity.userId] + ) + ).toEqual([{ cell_id: context.target.id, assignment_epoch: '2' }]) }) it('completes after the drained host re-resolves through the director', async () => { const context = await fixture() - const attempt = await context.store.claimRegionalRehome() - await context.store.recordRegionalRehomeDrainReceipt(attempt!.attemptId, 'accepted') + const attempt = await cutover(context.store, context.now()) // The drain recovery lands while both controls are still live. await context.store.assign(context.identity, 'asia-east2') expect(await controlAccounting(context.identity)).toEqual({ @@ -609,11 +589,13 @@ describePostgres('PostgreSQL regional rehoming', () => { await context.store.releaseActivity(context.identity, context.sourceControl) await expect(context.store.completeReadyRegionalRehomes()).resolves.toBe(1) - expect(await primary.query( - `SELECT completed_at IS NOT NULL AS completed FROM relay_assignment_migrations + expect( + await primary.query( + `SELECT completed_at IS NOT NULL AS completed FROM relay_assignment_migrations WHERE user_id = ?`, - [context.identity.userId] - )).toEqual([{ completed: true }]) + [context.identity.userId] + ) + ).toEqual([{ completed: true }]) expect(await controlAccounting(context.identity)).toEqual({ reservedControls: 1, controlLeases: 1 @@ -622,7 +604,7 @@ describePostgres('PostgreSQL regional rehoming', () => { it('repairs a skewed control counter before completing the rehome', async () => { const context = await fixture() - const attempt = await context.store.claimRegionalRehome() + const attempt = await cutover(context.store, context.now()) await context.store.activateControl(context.identity, { cellId: context.target.id, assignmentEpoch: attempt!.assignmentEpoch, @@ -634,10 +616,9 @@ describePostgres('PostgreSQL regional rehoming', () => { }) await context.store.releaseActivity(context.identity, context.sourceControl) // Damage already written by a pre-fix sticky grant. - await primary.query( - `UPDATE relay_assignments SET reserved_controls = 0 WHERE user_id = ?`, - [context.identity.userId] - ) + await primary.query(`UPDATE relay_assignments SET reserved_controls = 0 WHERE user_id = ?`, [ + context.identity.userId + ]) await expect(context.store.completeReadyRegionalRehomes()).resolves.toBe(1) expect(await controlAccounting(context.identity)).toEqual({ @@ -646,6 +627,22 @@ describePostgres('PostgreSQL regional rehoming', () => { }) }) + async function cutover(store: RelayAssignmentStore, now: number) { + const [request] = await store.selectIdleRegionalRehomeCandidates(safety(now)) + if (!request) return null + const result = await store.commitIdleRegionalRehome(request, safety(now)) + if (result.outcome !== 'committed') return null + const [attempt] = await primary.query( + `SELECT preferred_region, assignment_epoch FROM relay_region_rehome_attempts WHERE attempt_id = ?`, + [request.attemptId] + ) + return { + ...request, + preferredRegion: String(attempt!.preferred_region), + assignmentEpoch: Number(attempt!.assignment_epoch) + } + } + async function attemptAndMigrationCounts(identity: { userId: string relayHostId: string @@ -711,18 +708,12 @@ describePostgres('PostgreSQL regional rehoming', () => { drainGraceMs: 60_000 }) await store.reconcileCells([source, target]) - await heartbeat( - store, - source, - '11111111-1111-4111-8111-111111111111', - 1, - 900_000 - ) + await heartbeat(store, source, '11111111-1111-4111-8111-111111111111', 3, 900_000) await heartbeat( store, target, '22222222-2222-4222-8222-222222222222', - options.targetProtocol ?? 1, + options.targetProtocol ?? 3, 900_000 ) const identity = { @@ -733,9 +724,32 @@ describePostgres('PostgreSQL regional rehoming', () => { const sourceControl = await store.activateControl(identity, { cellId: source.id, assignmentEpoch: assignment.assignmentEpoch, - generation: 1 + generation: 1, + idleRegionalRehome: true, + cellIncarnation: '11111111-1111-4111-8111-111111111111' }) await store.assign(identity, preferredRegion) + const issued = await store.exchangeRegionCorrection( + identity, + { v: 1, action: 'issue-window' }, + assignment.assignmentEpoch + ) + await store.exchangeRegionCorrection( + identity, + { + v: 1, + action: 'report', + generation: issued.window!.generation, + assignmentEpoch: assignment.assignmentEpoch, + policyVersion: 1, + outcome: 'conclusive', + measurements: { + 'us-central1': preferredRegion === 'us-central1' ? 50 : 150, + 'asia-east2': preferredRegion === 'asia-east2' ? 50 : 150 + } + }, + assignment.assignmentEpoch + ) return { preferredRegion, store, @@ -753,6 +767,7 @@ describePostgres('PostgreSQL regional rehoming', () => { }) const storeOptions = { + regionalRehomeCohortPercent: 100, requireLiveCells: true, heartbeatTtlMs: 45_000 } @@ -816,3 +831,15 @@ async function heartbeat( } }) } + +function safety(now: number) { + return { + observedAt: now, + sqlFailures: 0, + reconnects: 0, + controlActivityRecoveryFailures: 0, + databasePoolWaiting: 0, + databasePoolWaitersMax: 0, + databasePoolWaitMsMax: 0 + } +} diff --git a/cloud/apps/relay/src/regional-rehome-store.test.ts b/cloud/apps/relay/src/regional-rehome-store.test.ts index 662876ef66e..e4a355699da 100644 --- a/cloud/apps/relay/src/regional-rehome-store.test.ts +++ b/cloud/apps/relay/src/regional-rehome-store.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from 'vitest' import { - RelayAssignmentStore, + RelayAssignmentStore as BaseRelayAssignmentStore, + type RegionalRehomeAttempt, REGIONAL_REHOME_QUARANTINE_FAILURES, REGIONAL_REHOME_QUARANTINE_MS, REGIONAL_REHOME_REDRAIN_SEND_LIMIT @@ -37,14 +38,115 @@ const sourceIncarnation = '11111111-1111-4111-8111-111111111111' const targetIncarnation = '22222222-2222-4222-8222-222222222222' describe('regional rehome assignment state', () => { + it('advances past a full candidate page whose destination lacks capacity', async () => { + const context = await setup() + for (let i = 0; i < 10; i++) { + await activatePreferredSource(context, { + userId: `blocked-${i}`, + relayHostId: 'abcdefghijklmnop' + }) + } + context.advance(1) + const reverse = { userId: 'healthy-reverse', relayHostId: 'abcdefghijklmnop' } + await activateReversePreferredSource(context, reverse) + await context.database.query( + 'UPDATE relay_cells SET capacity_requests = reserved_requests WHERE cell_id = ?', + [target.id] + ) + expect(await context.store.tryIdleRehome()).toMatchObject({ + userId: reverse.userId, + sourceCellId: target.id, + targetCellId: source.id + }) + await context.database.close() + }) + + it('defaults optional correction off even with enabled durable control', async () => { + const context = await setup() + await activatePreferredSource(context, { userId: 'cohort', relayHostId: 'abcdefghijklmnop' }) + const defaultStore = new IdleRehomeTestStore(context.database, context.now, { + requireLiveCells: true + }) + expect(await defaultStore.tryIdleRehome()).toBeNull() + expect( + await context.database.query('SELECT attempt_id FROM relay_region_rehome_attempts') + ).toEqual([]) + expect(await context.store.tryIdleRehome()).not.toBeNull() + await context.database.close() + }) + + it('counts pre-existing generic migrations against the eight-migration cap', async () => { + const context = await setup() + await activatePreferredSource(context, { userId: 'cap', relayHostId: 'abcdefghijklmnop' }) + for (let i = 0; i < 8; i++) { + await context.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, created_at, updated_at) + VALUES (?, ?, ?, ?, 1, 2, 1, 1, ?, ?, ?)`, + [ + 'generic', + `synthetic-migration-${i}`, + source.id, + target.id, + context.now() + 60_000, + context.now(), + context.now() + ] + ) + } + expect(await context.store.tryIdleRehome()).toBeNull() + await context.database.query( + `UPDATE relay_assignment_migrations SET completed_at = ? + WHERE user_id = 'generic' AND relay_host_id = 'synthetic-migration-0'`, + [context.now()] + ) + expect(await context.store.tryIdleRehome()).not.toBeNull() + const open = await context.database + .query(`SELECT COUNT(*) AS count FROM relay_assignment_migrations + WHERE completed_at IS NULL AND aborted_at IS NULL`) + expect(Number(open[0]?.count)).toBe(8) + await context.database.close() + }) + + it('does not let legacy hints certify a move', async () => { + const context = await setup() + await activatePreferredSource(context, { userId: 'legacy', relayHostId: 'abcdefghijklmnop' }) + await context.database.query('DELETE FROM relay_region_decisions') + expect(await context.store.tryIdleRehome()).toBeNull() + await context.database.close() + }) + + it('refreshes later open attempts when an older attempt occupies the first page', async () => { + const context = await setup() + await activatePreferredSource(context, { userId: 'page-1', relayHostId: 'abcdefghijklmnop' }) + const first = await context.store.tryIdleRehome() + context.advance(10_000) + await freshHeartbeats(context) + await activatePreferredSource(context, { userId: 'page-2', relayHostId: 'abcdefghijklmnop' }) + const second = await context.store.tryIdleRehome() + expect(second).not.toBeNull() + context.advance(1_000) + expect(await context.store.refreshRegionalRehomeLeases(1)).toBe(1) + context.advance(1_000) + expect(await context.store.refreshRegionalRehomeLeases(1)).toBe(1) + const rows = await context.database.query( + `SELECT attempt_id, updated_at FROM relay_region_rehome_attempts + WHERE attempt_id = ?`, + [second!.attemptId] + ) + expect(Number(rows[0]?.updated_at)).toBe(context.now()) + await context.database.close() + }) + it('does not open a transaction while the worker is disabled', async () => { const delegate = await openInMemoryRelayDatabase() const database = new TransactionCountingDatabase(delegate) - const store = new RelayAssignmentStore(database, () => 1_000_000) + const store = new IdleRehomeTestStore(database, () => 1_000_000) await store.inspectRegionalRehomeControl() database.transactionCalls = 0 - await expect(store.claimRegionalRehome()).resolves.toBeNull() + await expect(store.tryIdleRehome()).resolves.toBeNull() expect(database.transactionCalls).toBe(0) await database.close() }) @@ -52,9 +154,9 @@ describe('regional rehome assignment state', () => { it('initializes a missing control row without opening a transaction', async () => { const delegate = await openInMemoryRelayDatabase() const database = new TransactionCountingDatabase(delegate) - const store = new RelayAssignmentStore(database, () => 1_000_000) + const store = new IdleRehomeTestStore(database, () => 1_000_000) - await expect(store.claimRegionalRehome()).resolves.toBeNull() + await expect(store.tryIdleRehome()).resolves.toBeNull() expect(database.transactionCalls).toBe(0) await expect(store.inspectRegionalRehomeControl()).resolves.toMatchObject({ generation: 0, @@ -75,24 +177,28 @@ describe('regional rehome assignment state', () => { generation: 2, enabled: false }) - await expect(context.store.applyRegionalRehomeControl({ - expectedGeneration: 1, - enabled: true, - notBefore: context.now(), - ratePerMinute: 10, - preferenceMaxAgeMs: 24 * 60 * 60_000, - hostCooldownMs: 7 * 24 * 60 * 60_000, - drainGraceMs: 60_000 - })).rejects.toThrow('regional_rehome_generation_mismatch') - await expect(context.store.applyRegionalRehomeControl({ - expectedGeneration: 2, - enabled: true, - notBefore: context.now(), - ratePerMinute: 10, - preferenceMaxAgeMs: 24 * 60 * 60_000, - hostCooldownMs: 7 * 24 * 60 * 60_000, - drainGraceMs: 60_000 - })).resolves.toMatchObject({ generation: 3, enabled: true }) + await expect( + context.store.applyRegionalRehomeControl({ + expectedGeneration: 1, + enabled: true, + notBefore: context.now(), + ratePerMinute: 10, + preferenceMaxAgeMs: 24 * 60 * 60_000, + hostCooldownMs: 7 * 24 * 60 * 60_000, + drainGraceMs: 60_000 + }) + ).rejects.toThrow('regional_rehome_generation_mismatch') + await expect( + context.store.applyRegionalRehomeControl({ + expectedGeneration: 2, + enabled: true, + notBefore: context.now(), + ratePerMinute: 10, + preferenceMaxAgeMs: 24 * 60 * 60_000, + hostCooldownMs: 7 * 24 * 60 * 60_000, + drainGraceMs: 60_000 + }) + ).resolves.toMatchObject({ generation: 3, enabled: true }) await context.database.close() }) @@ -103,7 +209,7 @@ describe('regional rehome assignment state', () => { const sourceControl = await activatePreferredSource(context, identity) await activateSource(context, neighbor) - const attempt = await context.store.claimRegionalRehome() + const attempt = await context.store.tryIdleRehome() expect(attempt).toMatchObject({ userId: identity.userId, relayHostId: identity.relayHostId, @@ -118,11 +224,11 @@ describe('regional rehome assignment state', () => { expect(await context.store.resolve(neighbor)).toMatchObject({ cellId: source.id }) expect(await context.store.completeReadyRegionalRehomes()).toBe(0) expect( - await context.store.recordRegionalRehomeDrainReceipt(attempt!.attemptId, 'accepted') - ).toBe(true) - expect( - await context.store.recordRegionalRehomeDrainReceipt(attempt!.attemptId, 'accepted') - ).toBe(false) + await context.database.query( + 'SELECT drain_outcome FROM relay_region_rehome_attempts WHERE attempt_id = ?', + [attempt!.attemptId] + ) + ).toEqual([{ drain_outcome: 'accepted' }]) const targetControl = await context.store.activateControl(identity, { cellId: target.id, @@ -142,23 +248,27 @@ describe('regional rehome assignment state', () => { assignmentEpoch: 2 }) expect(await context.store.resolve(neighbor)).toMatchObject({ cellId: source.id }) - expect(await context.database.query( - `SELECT completed_at, aborted_at FROM relay_assignment_migrations + expect( + await context.database.query( + `SELECT completed_at, aborted_at FROM relay_assignment_migrations WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - )).toEqual([{ completed_at: context.now(), aborted_at: null }]) - expect(await context.database.query( - `SELECT completed_at, aborted_at FROM relay_region_rehome_attempts` - )).toEqual([{ completed_at: context.now(), aborted_at: null }]) + [identity.userId, identity.relayHostId] + ) + ).toEqual([{ completed_at: context.now(), aborted_at: null }]) + expect( + await context.database.query( + `SELECT completed_at, aborted_at FROM relay_region_rehome_attempts` + ) + ).toEqual([{ completed_at: context.now(), aborted_at: null }]) expect(targetControl).toMatch(/^control:/) await context.database.close() }) - it('completes from durable activity when the drain response was lost', async () => { + it('completes from durable activity with the source-owned receipt', async () => { const context = await setup() const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } const sourceControl = await activatePreferredSource(context, identity) - const attempt = await context.store.claimRegionalRehome() + const attempt = await context.store.tryIdleRehome() await context.store.activateControl(identity, { cellId: target.id, assignmentEpoch: attempt!.assignmentEpoch, @@ -171,10 +281,12 @@ describe('regional rehome assignment state', () => { await context.store.releaseActivity(identity, sourceControl) expect(await context.store.completeReadyRegionalRehomes()).toBe(1) - expect(await context.database.query( - `SELECT drain_receipt_at, completed_at, aborted_at + expect( + await context.database.query( + `SELECT drain_receipt_at, completed_at, aborted_at FROM relay_region_rehome_attempts` - )).toEqual([{ drain_receipt_at: null, completed_at: context.now(), aborted_at: null }]) + ) + ).toEqual([{ drain_receipt_at: context.now(), completed_at: context.now(), aborted_at: null }]) await context.database.close() }) @@ -184,23 +296,22 @@ describe('regional rehome assignment state', () => { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }) - expect(await context.store.claimRegionalRehome()).toBeNull() + expect(await context.store.tryIdleRehome()).toBeNull() expect(await context.database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([]) await context.database.close() }) it('fails fleet safety closed until source and target telemetry is fresh', async () => { const context = await setup() - await context.database.query( - `DELETE FROM relay_cell_rehome_safety WHERE cell_id = ?`, - [target.id] - ) + await context.database.query(`DELETE FROM relay_cell_rehome_safety WHERE cell_id = ?`, [ + target.id + ]) expect(await context.store.regionalRehomeFleetSafety()).toMatchObject({ requiredCells: 2, missingCells: 1, observedAt: 0 }) - await heartbeat(context.store, source, sourceIncarnation, 1, 2, { + await heartbeat(context.store, source, sourceIncarnation, 3, 2, { observedAt: context.now(), sqlFailures: 0, reconnects: 2, @@ -209,7 +320,7 @@ describe('regional rehome assignment state', () => { databasePoolWaitersMax: 0, databasePoolWaitMsMax: 0 }) - await heartbeat(context.store, target, targetIncarnation, 1, 2, { + await heartbeat(context.store, target, targetIncarnation, 3, 2, { observedAt: context.now(), sqlFailures: 1, reconnects: 3, @@ -237,7 +348,7 @@ describe('regional rehome assignment state', () => { requiredCells: 1, missingCells: 0 }) - await heartbeat(context.store, target, targetIncarnation, 1, 2) + await heartbeat(context.store, target, targetIncarnation, 3, 2) expect(await context.store.regionalRehomeFleetSafety()).toMatchObject({ requiredCells: 2, missingCells: 0 @@ -256,14 +367,14 @@ describe('regional rehome assignment state', () => { databasePoolWaitersMax: 2, databasePoolWaitMsMax: 1 } - await heartbeat(context.store, source, sourceIncarnation, 1, 2, baseline) - await heartbeat(context.store, target, targetIncarnation, 1, 2, baseline) + await heartbeat(context.store, source, sourceIncarnation, 3, 2, baseline) + await heartbeat(context.store, target, targetIncarnation, 3, 2, baseline) await activatePreferredSource(context, { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }) - expect(await context.store.claimRegionalRehome()).toMatchObject({ + expect(await context.store.tryIdleRehome()).toMatchObject({ sourceCellId: source.id, targetCellId: target.id }) @@ -279,6 +390,17 @@ describe('regional rehome assignment state', () => { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }) + const safety: RegionalRehomeSafetySnapshot = { + observedAt: context.now(), + sqlFailures: 0, + reconnects: 0, + controlActivityRecoveryFailures: 0, + databasePoolWaiting: 0, + databasePoolWaitersMax: 0, + databasePoolWaitMsMax: 0 + } + const [candidate] = await context.store.selectIdleRegionalRehomeCandidates(safety) + expect(candidate).toBeDefined() await context.database.query( `UPDATE relay_cell_rehome_safety SET reconnects = 251 WHERE cell_id = ?`, [source.id] @@ -286,7 +408,9 @@ describe('regional rehome assignment state', () => { const warnings = collectDisableWarnings() try { - expect(await context.store.claimRegionalRehome()).toBeNull() + expect(await context.store.commitIdleRegionalRehome(candidate!, safety)).toEqual({ + outcome: 'deferred' + }) } finally { warnings.restore() } @@ -306,6 +430,17 @@ describe('regional rehome assignment state', () => { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }) + const safety: RegionalRehomeSafetySnapshot = { + observedAt: context.now(), + sqlFailures: 0, + reconnects: 0, + controlActivityRecoveryFailures: 0, + databasePoolWaiting: 0, + databasePoolWaitersMax: 0, + databasePoolWaitMsMax: 0 + } + const [candidate] = await context.store.selectIdleRegionalRehomeCandidates(safety) + expect(candidate).toBeDefined() await context.database.query( `UPDATE relay_cell_rehome_safety SET database_pool_waiters_max = 17 WHERE cell_id = ?`, [target.id] @@ -313,9 +448,11 @@ describe('regional rehome assignment state', () => { const warnings = collectDisableWarnings() try { - expect(await context.store.claimRegionalRehome()).toBeNull() + expect(await context.store.commitIdleRegionalRehome(candidate!, safety)).toEqual({ + outcome: 'deferred' + }) // Already disabled: the next tick returns before the gate and stays silent. - expect(await context.store.claimRegionalRehome()).toBeNull() + expect(await context.store.tryIdleRehome()).toBeNull() } finally { warnings.restore() } @@ -339,7 +476,7 @@ describe('regional rehome assignment state', () => { `UPDATE relay_cell_rehome_safety SET sql_failures = ${REGIONAL_REHOME_SQL_FAILURES_PER_CELL_LIMIT}` ) - expect(await context.store.claimRegionalRehome()).not.toBeNull() + expect(await context.store.tryIdleRehome()).not.toBeNull() await context.database.close() }) @@ -348,7 +485,7 @@ describe('regional rehome assignment state', () => { const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } await activateReversePreferredSource(context, identity) - const attempt = await context.store.claimRegionalRehome() + const attempt = await context.store.tryIdleRehome() expect(attempt).toMatchObject({ userId: identity.userId, relayHostId: identity.relayHostId, @@ -366,11 +503,13 @@ describe('regional rehome assignment state', () => { `SELECT preferred_region, source_cell_id, target_cell_id FROM relay_region_rehome_attempts` ) - ).toEqual([{ - preferred_region: 'us-central1', - source_cell_id: target.id, - target_cell_id: source.id - }]) + ).toEqual([ + { + preferred_region: 'us-central1', + source_cell_id: target.id, + target_cell_id: source.id + } + ]) expect(await context.store.resolve(identity)).toMatchObject({ cellId: source.id }) await context.database.close() }) @@ -389,21 +528,19 @@ describe('regional rehome assignment state', () => { const warnings = collectEventWarnings('orca_relay_regional_rehome_candidates_skipped') try { - expect(await context.store.claimRegionalRehome()).toBeNull() + expect(await context.store.tryIdleRehome()).toBeNull() } finally { warnings.restore() } expect(warnings.entries).toEqual([]) expect( - await context.database.query( - `SELECT next_dispatch_at FROM relay_region_rehome_worker_state` - ) + await context.database.query(`SELECT next_dispatch_at FROM relay_region_rehome_worker_state`) ).toEqual([{ next_dispatch_at: 0 }]) expect(await context.database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([]) await context.database.close() }) - it('names the skip when the last target is lost between scan and claim', async () => { + it('does not migrate when the last target is lost between selection and commit', async () => { const database = await openInMemoryRelayDatabase() const context = await setup({ database, @@ -419,15 +556,8 @@ describe('regional rehome assignment state', () => { relayHostId: 'abcdefghijklmnop' }) - const warnings = collectEventWarnings('orca_relay_regional_rehome_candidates_skipped') - try { - expect(await context.store.claimRegionalRehome()).toBeNull() - } finally { - warnings.restore() - } - expect(warnings.entries).toMatchObject([ - { skips: [{ reason: 'no_eligible_target', candidates: 1 }] } - ]) + expect(await context.store.tryIdleRehome()).toBeNull() + expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ generation: 1, enabled: true @@ -444,11 +574,11 @@ describe('regional rehome assignment state', () => { // really does scan and the cooldown is the only thing holding this host. context.advance(10_000) // The desktop's region probe now says us-central1 again. - await context.store.assign(identity, 'us-central1') + await activateReversePreferredSource(context, identity) const warnings = collectEventWarnings('orca_relay_regional_rehome_candidates_skipped') try { - expect(await context.store.claimRegionalRehome()).toBeNull() + expect(await context.store.tryIdleRehome()).toBeNull() } finally { warnings.restore() } @@ -462,9 +592,9 @@ describe('regional rehome assignment state', () => { cellId: target.id, expiresAt: context.now() + 90_000 }) - await context.store.assign(identity, 'us-central1') + await activateReversePreferredSource(context, identity) - const attempt = await context.store.claimRegionalRehome() + const attempt = await context.store.tryIdleRehome() expect(attempt).toMatchObject({ preferredRegion: 'us-central1', sourceCellId: target.id, @@ -502,15 +632,8 @@ describe('regional rehome assignment state', () => { }) await activatePreferredSource(context, identity) - const warnings = collectEventWarnings('orca_relay_regional_rehome_candidates_skipped') - try { - expect(await context.store.claimRegionalRehome()).toBeNull() - } finally { - warnings.restore() - } - expect(warnings.entries).toMatchObject([ - { skips: [{ reason: 'host_cooldown', candidates: 1 }] } - ]) + expect(await context.store.tryIdleRehome()).toBeNull() + expect(await database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([]) await database.close() }) @@ -527,15 +650,13 @@ describe('regional rehome assignment state', () => { const warnings = collectEventWarnings('orca_relay_regional_rehome_candidates_skipped') try { - expect(await context.store.claimRegionalRehome()).toBeNull() + expect(await context.store.tryIdleRehome()).toBeNull() } finally { warnings.restore() } expect(warnings.entries).toEqual([]) expect( - await context.database.query( - `SELECT next_dispatch_at FROM relay_region_rehome_worker_state` - ) + await context.database.query(`SELECT next_dispatch_at FROM relay_region_rehome_worker_state`) ).toEqual([{ next_dispatch_at: 0 }]) expect(await context.database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([]) await context.database.close() @@ -558,37 +679,16 @@ describe('regional rehome assignment state', () => { [target.id] ) - const warnings = collectEventWarnings('orca_relay_regional_rehome_candidates_skipped') - try { - expect(await context.store.claimRegionalRehome()).toBeNull() - } finally { - warnings.restore() - } + expect(await context.store.tryIdleRehome()).toBeNull() expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ generation: 1, enabled: true }) - // The skip is visible and named, and both candidates blocked by the one - // unclean cell accumulate into a single entry. - expect(warnings.entries).toMatchObject([ - { - skips: [ - { - reason: 'target_unclean', - cellId: target.id, - sqlFailures: REGIONAL_REHOME_SQL_FAILURES_PER_CELL_LIMIT + 1, - candidates: 2 - } - ] - } - ]) - // A skipped tick is charged the dispatch interval: candidate scans stay - // rate-limited even when nothing claims. + + // Read-only selection does not spend the commit rate budget. expect( - await context.database.query( - `SELECT next_dispatch_at FROM relay_region_rehome_worker_state` - ) - ).toEqual([{ next_dispatch_at: context.now() + 6_000 }]) + await context.database.query(`SELECT next_dispatch_at FROM relay_region_rehome_worker_state`) + ).toEqual([{ next_dispatch_at: 0 }]) expect(await context.database.query(`SELECT * FROM relay_assignment_migrations`)).toEqual([]) await context.database.close() }) @@ -598,15 +698,13 @@ describe('regional rehome assignment state', () => { const warnings = collectEventWarnings('orca_relay_regional_rehome_candidates_skipped') try { - expect(await context.store.claimRegionalRehome()).toBeNull() + expect(await context.store.tryIdleRehome()).toBeNull() } finally { warnings.restore() } expect(warnings.entries).toEqual([]) expect( - await context.database.query( - `SELECT next_dispatch_at FROM relay_region_rehome_worker_state` - ) + await context.database.query(`SELECT next_dispatch_at FROM relay_region_rehome_worker_state`) ).toEqual([{ next_dispatch_at: 0 }]) await context.database.close() }) @@ -617,12 +715,25 @@ describe('regional rehome assignment state', () => { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }) + const safety: RegionalRehomeSafetySnapshot = { + observedAt: context.now(), + sqlFailures: 0, + reconnects: 0, + controlActivityRecoveryFailures: 0, + databasePoolWaiting: 0, + databasePoolWaitersMax: 0, + databasePoolWaitMsMax: 0 + } + const [candidate] = await context.store.selectIdleRegionalRehomeCandidates(safety) + expect(candidate).toBeDefined() await context.database.query( `UPDATE relay_cell_rehome_safety SET sql_failures = ${REGIONAL_REHOME_SQL_FAILURES_LIMIT + 1} WHERE cell_id = ?`, [target.id] ) - expect(await context.store.claimRegionalRehome()).toBeNull() + expect(await context.store.commitIdleRegionalRehome(candidate!, safety)).toEqual({ + outcome: 'deferred' + }) expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ generation: 2, enabled: false @@ -631,80 +742,6 @@ describe('regional rehome assignment state', () => { await context.database.close() }) - it('rechecks locked fleet safety before retrying a drain dispatch', async () => { - const context = await setup() - await activatePreferredSource(context, { - userId: 'user-1', - relayHostId: 'abcdefghijklmnop' - }) - expect(await context.store.claimRegionalRehome()).not.toBeNull() - context.advance(31_000) - await context.database.query( - `UPDATE relay_cell_rehome_safety SET sql_failures = ${REGIONAL_REHOME_SQL_FAILURES_LIMIT + 1} WHERE cell_id = ?`, - [target.id] - ) - - expect(await context.store.claimRegionalRehome()).toBeNull() - expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ - generation: 2, - enabled: false - }) - await context.database.close() - }) - - it('latches off after three dispatch failures and resumes only through CAS', async () => { - const context = await setup() - await activatePreferredSource(context, { - userId: 'user-1', - relayHostId: 'abcdefghijklmnop' - }) - const first = await context.store.claimRegionalRehome() - for (let index = 0; index < 3; index++) { - await context.store.recordRegionalRehomeDispatchFailure(first!.attemptId) - } - context.advance(5 * 60_000 - 1) - expect(await context.store.claimRegionalRehome()).toBeNull() - context.advance(1) - await heartbeat(context.store, source, sourceIncarnation, 1, 2, { - observedAt: context.now(), - sqlFailures: 0, - reconnects: 0, - controlActivityRecoveryFailures: 0, - databasePoolWaiting: 0, - databasePoolWaitersMax: 0, - databasePoolWaitMsMax: 0 - }) - await heartbeat(context.store, target, targetIncarnation, 1, 2, { - observedAt: context.now(), - sqlFailures: 0, - reconnects: 0, - controlActivityRecoveryFailures: 0, - databasePoolWaiting: 0, - databasePoolWaitersMax: 0, - databasePoolWaitMsMax: 0 - }) - expect(await context.store.claimRegionalRehome()).toBeNull() - expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ - generation: 2, - enabled: false - }) - await context.store.applyRegionalRehomeControl({ - expectedGeneration: 2, - enabled: true, - notBefore: context.now(), - ratePerMinute: 10, - preferenceMaxAgeMs: 24 * 60 * 60_000, - hostCooldownMs: 7 * 24 * 60 * 60_000, - drainGraceMs: 60_000 - }) - const retry = await context.store.claimRegionalRehome() - expect(retry).toMatchObject({ attemptId: first!.attemptId, sendAttempts: 2 }) - expect(await context.database.query( - `SELECT COUNT(*) AS count FROM relay_assignment_migrations` - )).toEqual([{ count: 1 }]) - await context.database.close() - }) - it('refreshes only the migration leases while source splices drain', async () => { const context = await setup() const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } @@ -714,7 +751,7 @@ describe('regional rehome assignment state', () => { kind: 'splice', cellId: source.id }) - await context.store.claimRegionalRehome() + await context.store.tryIdleRehome() const before = await context.database.query( `SELECT activity_id, expires_at FROM relay_assignment_activity_leases WHERE user_id = ? AND relay_host_id = ? ORDER BY activity_id`, @@ -743,19 +780,21 @@ describe('regional rehome assignment state', () => { const context = await setup() const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } await activatePreferredSource(context, identity) - await context.store.claimRegionalRehome() + await context.store.tryIdleRehome() context.advance(6 * 60_000) expect(await context.store.refreshRegionalRehomeLeases()).toBe(0) - await heartbeat(context.store, source, sourceIncarnation, 1, 2) + await heartbeat(context.store, source, sourceIncarnation, 3, 2) expect(await context.store.abortExpiredEvacuations()).toBe(1) - expect(await context.store.reapRegionalRehomeAttempts()).toBe(1) + expect(await context.store.reapRegionalRehomeAttempts()).toBe(0) expect(await context.store.resolve(identity)).toMatchObject({ cellId: source.id, assignmentEpoch: 3 }) - expect(await context.database.query( - `SELECT completed_at, aborted_at FROM relay_region_rehome_attempts` - )).toEqual([{ completed_at: null, aborted_at: context.now() }]) + expect( + await context.database.query( + `SELECT completed_at, aborted_at FROM relay_region_rehome_attempts` + ) + ).toEqual([{ completed_at: null, aborted_at: context.now() }]) await context.database.close() }) @@ -763,9 +802,9 @@ describe('regional rehome assignment state', () => { const context = await setup() const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } await activatePreferredSource(context, identity) - await context.store.claimRegionalRehome() + await context.store.tryIdleRehome() context.advance(6 * 60_000) - await heartbeat(context.store, target, targetIncarnation, 1, 2) + await heartbeat(context.store, target, targetIncarnation, 3, 2) expect(await context.store.refreshRegionalRehomeLeases()).toBe(0) expect(await context.store.abortExpiredEvacuations()).toBe(0) @@ -779,41 +818,6 @@ describe('regional rehome assignment state', () => { await context.database.close() }) - it('skips a rehome dispatch tick on a contended cell inventory', async () => { - const probe = new CellInventoryLockProbe() - const context = await setup({ wrap: (database) => probe.wrap(database) }) - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - await activatePreferredSource(context, identity) - probe.reset() - probe.failNoWait = true - const busy = collectEventWarnings('orca_relay_sweep_cell_inventory_busy') - - let attempt: unknown - try { - attempt = await context.store.claimRegionalRehome() - } finally { - busy.restore() - } - - expect(attempt).toBeNull() - expect(probe.locks).not.toEqual([]) - expect(probe.locks.every((options) => options?.failIfUnavailable === true)).toBe(true) - expect(busy.entries).toEqual([ - { - event: 'orca_relay_sweep_cell_inventory_busy', - sweep: 'claim-regional-rehome', - skipped: 1 - } - ]) - - probe.failNoWait = false - expect(await context.store.claimRegionalRehome()).toMatchObject({ - sourceCellId: source.id, - targetCellId: target.id - }) - await context.database.close() - }) - // Why: the redrain lane reaches the inventory through the fleet-safety read // rather than through candidate selection, so it needs its own coverage. // Why: one contended candidate must cost its own tick, not the whole page. The @@ -830,8 +834,7 @@ describe('regional rehome assignment state', () => { context.advance(60_000) await freshHeartbeats(context) const sourceControl = await activatePreferredSource(context, identity) - const attempt = await context.store.claimRegionalRehome() - await context.store.recordRegionalRehomeDrainReceipt(attempt!.attemptId, 'accepted') + const attempt = await context.store.tryIdleRehome() await context.store.activateControl(identity, { cellId: target.id, assignmentEpoch: 2, @@ -881,8 +884,7 @@ describe('regional rehome assignment state', () => { context.advance(60_000) await freshHeartbeats(context) const sourceControl = await activatePreferredSource(context, identity) - const attempt = await context.store.claimRegionalRehome() - await context.store.recordRegionalRehomeDrainReceipt(attempt!.attemptId, 'accepted') + const attempt = await context.store.tryIdleRehome() await context.store.activateControl(identity, { cellId: target.id, assignmentEpoch: 2, @@ -927,9 +929,7 @@ describe('regional rehome assignment state', () => { const busy = collectEventWarnings('orca_relay_sweep_cell_inventory_busy') try { - await expect(context.store.claimRegionalRehome()).rejects.toThrow( - 'relay_capacity_exhausted' - ) + await expect(context.store.tryIdleRehome()).rejects.toThrow('relay_capacity_exhausted') } finally { busy.restore() } @@ -940,87 +940,13 @@ describe('regional rehome assignment state', () => { // Why: the transaction dies at the first contended candidate, so every // candidate behind it is abandoned too. Reporting one would understate the tick. - it('reports every candidate the contended tick abandoned', async () => { - const probe = new CellInventoryLockProbe() - const context = await setup({ wrap: (database) => probe.wrap(database) }) - await activatePreferredSource(context, { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }) - await activatePreferredSource(context, { userId: 'user-2', relayHostId: 'ponmlkjihgfedcba' }) - await activatePreferredSource(context, { userId: 'user-3', relayHostId: 'aaaabbbbccccdddd' }) - probe.reset() - probe.failNoWait = true - const busy = collectEventWarnings('orca_relay_sweep_cell_inventory_busy') - - try { - expect(await context.store.claimRegionalRehome()).toBeNull() - } finally { - busy.restore() - } - - expect(busy.entries).toEqual([ - { - event: 'orca_relay_sweep_cell_inventory_busy', - sweep: 'claim-regional-rehome', - skipped: 3 - } - ]) - await context.database.close() - }) - - it('skips a redrain tick on a contended cell inventory', async () => { - const probe = new CellInventoryLockProbe() - const context = await setup({ wrap: (database) => probe.wrap(database) }) - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - await activatePreferredSource(context, identity) - const attempt = await context.store.claimRegionalRehome() - await context.store.recordRegionalRehomeDrainReceipt(attempt!.attemptId, 'accepted') - await context.store.activateControl(identity, { - cellId: target.id, - assignmentEpoch: 2, - generation: 1 - }) - await context.store.markMigrationTargetRegistered(identity, { - cellId: target.id, - assignmentEpoch: 2 - }) - context.advance(60 * 60_000 + 1) - await freshHeartbeats(context) - probe.reset() - probe.failNoWait = true - const busy = collectEventWarnings('orca_relay_sweep_cell_inventory_busy') - - let redrain: unknown - try { - redrain = await context.store.claimRegionalRehome() - } finally { - busy.restore() - } - - expect(redrain).toBeNull() - expect(probe.locks).not.toEqual([]) - expect(probe.locks.every((options) => options?.failIfUnavailable === true)).toBe(true) - expect(busy.entries).toEqual([ - { - event: 'orca_relay_sweep_cell_inventory_busy', - sweep: 'claim-regional-rehome', - skipped: 1 - } - ]) - - probe.failNoWait = false - expect(await context.store.claimRegionalRehome()).toMatchObject({ - attemptId: attempt!.attemptId, - sendAttempts: 2 - }) - await context.database.close() - }) it('skips a completion tick on a contended cell inventory without quarantining it', async () => { const probe = new CellInventoryLockProbe() const context = await setup({ wrap: (database) => probe.wrap(database) }) const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } const sourceControl = await activatePreferredSource(context, identity) - const attempt = await context.store.claimRegionalRehome() - await context.store.recordRegionalRehomeDrainReceipt(attempt!.attemptId, 'accepted') + const attempt = await context.store.tryIdleRehome() await context.store.activateControl(identity, { cellId: target.id, assignmentEpoch: 2, @@ -1069,8 +995,7 @@ describe('regional rehome assignment state', () => { const context = await setup({ wrap: (database) => probe.wrap(database) }) const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } const sourceControl = await activatePreferredSource(context, identity) - const attempt = await context.store.claimRegionalRehome() - await context.store.recordRegionalRehomeDrainReceipt(attempt!.attemptId, 'accepted') + const attempt = await context.store.tryIdleRehome() const targetControl = await context.store.activateControl(identity, { cellId: target.id, assignmentEpoch: 2, @@ -1083,7 +1008,7 @@ describe('regional rehome assignment state', () => { await context.store.releaseActivity(identity, sourceControl) await context.store.releaseActivity(identity, targetControl) context.advance(24 * 60 * 60_000) - await heartbeat(context.store, source, sourceIncarnation, 1, 2) + await heartbeat(context.store, source, sourceIncarnation, 3, 2) probe.reset() probe.failNoWait = true const busy = collectEventWarnings('orca_relay_sweep_cell_inventory_busy') @@ -1118,11 +1043,7 @@ describe('regional rehome assignment state', () => { const context = await setup() const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } const sourceControl = await activatePreferredSource(context, identity) - const attempt = await context.store.claimRegionalRehome() - await context.store.recordRegionalRehomeDrainReceipt( - attempt!.attemptId, - 'accepted' - ) + const attempt = await context.store.tryIdleRehome() const targetControl = await context.store.activateControl(identity, { cellId: target.id, assignmentEpoch: 2, @@ -1135,7 +1056,7 @@ describe('regional rehome assignment state', () => { await context.store.releaseActivity(identity, sourceControl) await context.store.releaseActivity(identity, targetControl) context.advance(24 * 60 * 60_000) - await heartbeat(context.store, source, sourceIncarnation, 1, 2) + await heartbeat(context.store, source, sourceIncarnation, 3, 2) expect(await context.store.abortExpiredRegionalRehomes()).toBe(1) expect(await context.store.resolve(identity)).toMatchObject({ cellId: source.id, @@ -1144,151 +1065,21 @@ describe('regional rehome assignment state', () => { await context.database.close() }) - it('redrains a receipted dual-homed attempt once its grace elapses', async () => { - const context = await setup() - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - const sourceControl = await activatePreferredSource(context, identity) - const attempt = await context.store.claimRegionalRehome() - await context.store.recordRegionalRehomeDrainReceipt(attempt!.attemptId, 'accepted') - await context.store.activateControl(identity, { - cellId: target.id, - assignmentEpoch: 2, - generation: 1 - }) - await context.store.markMigrationTargetRegistered(identity, { - cellId: target.id, - assignmentEpoch: 2 - }) - - // Before grace elapses a receipted attempt is not re-dispatched. - context.advance(30 * 60_000) - await freshHeartbeats(context) - expect(await context.store.claimRegionalRehome()).toBeNull() - - context.advance(30 * 60_000 + 1) - await freshHeartbeats(context) - const redrain = await context.store.claimRegionalRehome() - expect(redrain).toMatchObject({ - attemptId: attempt!.attemptId, - drainGraceMs: 0, - sendAttempts: 2 - }) - // The per-dispatch receipt replaces the original without a mismatch. - await expect( - context.store.recordRegionalRehomeDrainReceipt(attempt!.attemptId, 'host-not-connected') - ).resolves.toBe(true) - - // Redrains are spaced: nothing new inside the redrain interval. - context.advance(30_000) - await freshHeartbeats(context) - expect(await context.store.claimRegionalRehome()).toBeNull() - context.advance(30_001) - await freshHeartbeats(context) - expect(await context.store.claimRegionalRehome()).toMatchObject({ - attemptId: attempt!.attemptId, - drainGraceMs: 0, - sendAttempts: 3 - }) - - // Once the host actually leaves the source, completion wins over redrain. - await context.store.releaseActivity(identity, sourceControl) - context.advance(60_001) - await freshHeartbeats(context) - await context.store.activateControl(identity, { - cellId: target.id, - assignmentEpoch: 2, - generation: 2 - }) - expect(await context.store.claimRegionalRehome()).toBeNull() - expect(await context.store.completeReadyRegionalRehomes()).toBe(1) - await context.database.close() - }) - - it('resets the failure budget on a repeated redrain receipt outcome', async () => { - const context = await setup() - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - await activatePreferredSource(context, identity) - const attempt = await context.store.claimRegionalRehome() - await context.store.recordRegionalRehomeDrainReceipt(attempt!.attemptId, 'accepted') - await context.store.activateControl(identity, { - cellId: target.id, - assignmentEpoch: 2, - generation: 1 - }) - await context.store.markMigrationTargetRegistered(identity, { - cellId: target.id, - assignmentEpoch: 2 - }) - await context.store.recordRegionalRehomeDispatchFailure(attempt!.attemptId) - await context.store.recordRegionalRehomeDispatchFailure(attempt!.attemptId) - - context.advance(60 * 60_000 + 1) - await freshHeartbeats(context) - expect(await context.store.claimRegionalRehome()).toMatchObject({ - attemptId: attempt!.attemptId, - drainGraceMs: 0 - }) - // The repeated outcome still proves the source answered. - expect( - await context.store.recordRegionalRehomeDrainReceipt(attempt!.attemptId, 'accepted') - ).toBe(false) - await context.store.recordRegionalRehomeDispatchFailure(attempt!.attemptId) - expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ - generation: 1, - enabled: true - }) - await context.database.close() - }) - - it('does not redrain before the target registers or when the fleet is unsafe', async () => { - const context = await setup() - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - await activatePreferredSource(context, identity) - const attempt = await context.store.claimRegionalRehome() - await context.store.recordRegionalRehomeDrainReceipt(attempt!.attemptId, 'accepted') - await context.store.activateControl(identity, { - cellId: target.id, - assignmentEpoch: 2, - generation: 1 - }) - - // Past grace but the target never registered: force-closing the source - // would disconnect the host with nowhere proven to land. - context.advance(60 * 60_000 + 1) - await freshHeartbeats(context) - expect(await context.store.claimRegionalRehome()).toBeNull() - - await context.store.markMigrationTargetRegistered(identity, { - cellId: target.id, - assignmentEpoch: 2 - }) - await context.database.query( - `UPDATE relay_cell_rehome_safety SET sql_failures = ${REGIONAL_REHOME_SQL_FAILURES_LIMIT + 1} WHERE cell_id = ?`, - [target.id] - ) - expect(await context.store.claimRegionalRehome()).toBeNull() - expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ - enabled: false - }) - await context.database.close() - }) - it('completes healthy candidates past a poisoned attempt and logs it', async () => { const context = await setup() const poisoned = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } const healthy = { userId: 'user-2', relayHostId: 'ponmlkjihgfedcba' } const poisonedSource = await activatePreferredSource(context, poisoned) const healthySource = await activatePreferredSource(context, healthy) - const first = await context.store.claimRegionalRehome() + const first = await context.store.tryIdleRehome() context.advance(6_000) - const second = await context.store.claimRegionalRehome() + const second = await context.store.tryIdleRehome() expect(first!.userId).toBe(poisoned.userId) expect(second!.userId).toBe(healthy.userId) for (const [identity, attempt, sourceControl] of [ [poisoned, first, poisonedSource], [healthy, second, healthySource] ] as const) { - await context.store.recordRegionalRehomeDrainReceipt(attempt!.attemptId, 'accepted') await context.store.activateControl(identity, { cellId: target.id, assignmentEpoch: attempt!.assignmentEpoch, @@ -1320,10 +1111,12 @@ describe('regional rehome assignment state', () => { reason: 'regional_rehome_assignment_mismatch' } ]) - expect(await context.database.query( - `SELECT completed_at FROM relay_region_rehome_attempts WHERE attempt_id = ?`, - [second!.attemptId] - )).toEqual([{ completed_at: context.now() }]) + expect( + await context.database.query( + `SELECT completed_at FROM relay_region_rehome_attempts WHERE attempt_id = ?`, + [second!.attemptId] + ) + ).toEqual([{ completed_at: context.now() }]) await context.database.close() }) @@ -1331,8 +1124,7 @@ describe('regional rehome assignment state', () => { const context = await setup() const poisoned = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } const source1 = await activatePreferredSource(context, poisoned) - const attempt = await context.store.claimRegionalRehome() - await context.store.recordRegionalRehomeDrainReceipt(attempt!.attemptId, 'accepted') + const attempt = await context.store.tryIdleRehome() await context.store.activateControl(poisoned, { cellId: target.id, assignmentEpoch: attempt!.assignmentEpoch, @@ -1363,9 +1155,7 @@ describe('regional rehome assignment state', () => { expect(warnings.entries).toHaveLength(REGIONAL_REHOME_QUARANTINE_FAILURES + 1) // A free-form error (never a slug) reaches the log only as 'redacted'. expect( - warnings.entries.every( - (entry) => entry.reason === 'regional_rehome_assignment_mismatch' - ) + warnings.entries.every((entry) => entry.reason === 'regional_rehome_assignment_mismatch') ).toBe(true) context.advance(REGIONAL_REHOME_QUARANTINE_MS + 1) const database = context.database @@ -1393,14 +1183,13 @@ describe('regional rehome assignment state', () => { const healthy = { userId: 'user-2', relayHostId: 'ponmlkjihgfedcba' } const poisonedSource = await activatePreferredSource(context, poisoned) const healthySource = await activatePreferredSource(context, healthy) - const first = await context.store.claimRegionalRehome() + const first = await context.store.tryIdleRehome() context.advance(6_000) - const second = await context.store.claimRegionalRehome() + const second = await context.store.tryIdleRehome() for (const [identity, attempt, sourceControl] of [ [poisoned, first, poisonedSource], [healthy, second, healthySource] ] as const) { - await context.store.recordRegionalRehomeDrainReceipt(attempt!.attemptId, 'accepted') const targetControl = await context.store.activateControl(identity, { cellId: target.id, assignmentEpoch: attempt!.assignmentEpoch, @@ -1434,10 +1223,12 @@ describe('regional rehome assignment state', () => { reason: 'regional_rehome_assignment_mismatch' } ]) - expect(await context.database.query( - `SELECT aborted_at FROM relay_region_rehome_attempts WHERE attempt_id = ?`, - [second!.attemptId] - )).toEqual([{ aborted_at: context.now() }]) + expect( + await context.database.query( + `SELECT aborted_at FROM relay_region_rehome_attempts WHERE attempt_id = ?`, + [second!.attemptId] + ) + ).toEqual([{ aborted_at: context.now() }]) await context.database.close() }) @@ -1445,7 +1236,7 @@ describe('regional rehome assignment state', () => { const context = await setup() const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } const sourceControl = await activatePreferredSource(context, identity) - const attempt = await context.store.claimRegionalRehome() + const attempt = await context.store.tryIdleRehome() expect(await controlAccounting(context, identity)).toEqual({ reservedControls: 2, controlLeases: 2 @@ -1475,11 +1266,13 @@ describe('regional rehome assignment state', () => { }) expect(await context.store.completeReadyRegionalRehomes()).toBe(1) - expect(await context.database.query( - `SELECT completed_at FROM relay_assignment_migrations + expect( + await context.database.query( + `SELECT completed_at FROM relay_assignment_migrations WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - )).toEqual([{ completed_at: context.now() }]) + [identity.userId, identity.relayHostId] + ) + ).toEqual([{ completed_at: context.now() }]) expect(await cellReservations(context)).toEqual({ [source.id]: 0, [target.id]: 1 }) await context.database.close() }) @@ -1488,7 +1281,7 @@ describe('regional rehome assignment state', () => { const context = await setup() const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } const sourceControl = await activatePreferredSource(context, identity) - const attempt = await context.store.claimRegionalRehome() + const attempt = await context.store.tryIdleRehome() await context.store.activateControl(identity, { cellId: target.id, assignmentEpoch: attempt!.assignmentEpoch, @@ -1503,11 +1296,13 @@ describe('regional rehome assignment state', () => { ) await context.store.assign(identity, 'asia-east2') - expect(await context.database.query( - `SELECT activity_id FROM relay_assignment_activity_leases + expect( + await context.database.query( + `SELECT activity_id FROM relay_assignment_activity_leases WHERE user_id = ? AND relay_host_id = ? AND activity_kind = 'control'`, - [identity.userId, identity.relayHostId] - )).toEqual([{ activity_id: `control:${target.id}:1` }]) + [identity.userId, identity.relayHostId] + ) + ).toEqual([{ activity_id: `control:${target.id}:1` }]) expect(await cellReservations(context)).toEqual({ [source.id]: 0, [target.id]: 2 }) await context.database.close() }) @@ -1516,7 +1311,7 @@ describe('regional rehome assignment state', () => { const context = await setup() const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } const sourceControl = await activatePreferredSource(context, identity) - const attempt = await context.store.claimRegionalRehome() + const attempt = await context.store.tryIdleRehome() await context.store.activateControl(identity, { cellId: target.id, assignmentEpoch: attempt!.assignmentEpoch, @@ -1539,11 +1334,13 @@ describe('regional rehome assignment state', () => { reservedControls: 1, controlLeases: 1 }) - expect(await context.database.query( - `SELECT migration_leases FROM relay_assignments + expect( + await context.database.query( + `SELECT migration_leases FROM relay_assignments WHERE user_id = ? AND relay_host_id = ?`, - [identity.userId, identity.relayHostId] - )).toEqual([{ migration_leases: 0 }]) + [identity.userId, identity.relayHostId] + ) + ).toEqual([{ migration_leases: 0 }]) await context.database.close() }) @@ -1553,9 +1350,9 @@ describe('regional rehome assignment state', () => { const clean = { userId: 'user-2', relayHostId: 'ponmlkjihgfedcba' } const skewedSource = await activatePreferredSource(context, skewed) const cleanSource = await activatePreferredSource(context, clean) - const first = await context.store.claimRegionalRehome() + const first = await context.store.tryIdleRehome() context.advance(6_000) - const second = await context.store.claimRegionalRehome() + const second = await context.store.tryIdleRehome() for (const [identity, attempt, sourceControl] of [ [skewed, first, skewedSource], [clean, second, cleanSource] @@ -1599,7 +1396,7 @@ describe('regional rehome assignment state', () => { const context = await setup() const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } const sourceControl = await activatePreferredSource(context, identity) - const attempt = await context.store.claimRegionalRehome() + const attempt = await context.store.tryIdleRehome() await context.store.activateControl(identity, { cellId: target.id, assignmentEpoch: attempt!.assignmentEpoch, @@ -1646,7 +1443,7 @@ describe('regional rehome assignment state', () => { const context = await setup() const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } const sourceControl = await activatePreferredSource(context, identity) - const attempt = await context.store.claimRegionalRehome() + const attempt = await context.store.tryIdleRehome() await context.store.activateControl(identity, { cellId: target.id, assignmentEpoch: attempt!.assignmentEpoch, @@ -1684,102 +1481,6 @@ describe('regional rehome assignment state', () => { ]) await context.database.close() }) - - it('caps redrain dispatches at the send limit', async () => { - const context = await setup() - const identity = { userId: 'user-1', relayHostId: 'abcdefghijklmnop' } - await activatePreferredSource(context, identity) - const attempt = await context.store.claimRegionalRehome() - await context.store.recordRegionalRehomeDrainReceipt(attempt!.attemptId, 'accepted') - await context.store.activateControl(identity, { - cellId: target.id, - assignmentEpoch: 2, - generation: 1 - }) - await context.store.markMigrationTargetRegistered(identity, { - cellId: target.id, - assignmentEpoch: 2 - }) - await context.database.query( - `UPDATE relay_region_rehome_attempts SET send_attempts = ? WHERE attempt_id = ?`, - [REGIONAL_REHOME_REDRAIN_SEND_LIMIT, attempt!.attemptId] - ) - context.advance(60 * 60_000 + 1) - await freshHeartbeats(context) - expect(await context.store.claimRegionalRehome()).toBeNull() - await context.database.close() - }) - - it('clears a stale failure budget when the control is enabled again', async () => { - const context = await setup() - await activatePreferredSource(context, { - userId: 'user-1', - relayHostId: 'abcdefghijklmnop' - }) - const attempt = await context.store.claimRegionalRehome() - for (let index = 0; index < 3; index++) { - await context.store.recordRegionalRehomeDispatchFailure(attempt!.attemptId) - } - expect(await workerState(context)).toMatchObject({ consecutiveFailures: 3 }) - const latched = await context.store.inspectRegionalRehomeControl() - expect(latched).toMatchObject({ generation: 2, enabled: false }) - - await context.store.applyRegionalRehomeControl({ - expectedGeneration: latched.generation, - enabled: true, - notBefore: context.now(), - ratePerMinute: 10, - preferenceMaxAgeMs: 24 * 60 * 60_000, - hostCooldownMs: 7 * 24 * 60 * 60_000, - drainGraceMs: 60 * 60_000 - }) - - // A budget spent under the previous enable is not evidence about this one. - expect(await workerState(context)).toMatchObject({ - consecutiveFailures: 0, - pausedUntil: 0 - }) - // One transient failure must not latch the fresh enable straight back off. - await context.store.recordRegionalRehomeDispatchFailure(attempt!.attemptId) - expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ - generation: 3, - enabled: true - }) - await context.database.close() - }) - - it('reports the durable disable when the failure budget latches the control off', async () => { - const context = await setup() - await activatePreferredSource(context, { - userId: 'user-1', - relayHostId: 'abcdefghijklmnop' - }) - const attempt = await context.store.claimRegionalRehome() - const warnings = collectEventWarnings( - 'orca_relay_regional_rehome_failure_budget_disabled' - ) - try { - for (let index = 0; index < 5; index++) { - await context.store.recordRegionalRehomeDispatchFailure(attempt!.attemptId) - } - } finally { - warnings.restore() - } - - // Only the transition is reported; later failures find the control already off. - expect(warnings.entries).toEqual([ - expect.objectContaining({ - event: 'orca_relay_regional_rehome_failure_budget_disabled', - controlGeneration: 2, - consecutiveFailures: 3 - }) - ]) - expect(await context.store.inspectRegionalRehomeControl()).toMatchObject({ - generation: 2, - enabled: false - }) - await context.database.close() - }) }) class TransactionCountingDatabase implements RelayDatabase { @@ -1848,7 +1549,8 @@ async function setup( ) { let clock = 1_000_000 const database = options.database ?? (await openInMemoryRelayDatabase()) - const store = new RelayAssignmentStore(options.wrap?.(database) ?? database, () => clock, { + const store = new IdleRehomeTestStore(options.wrap?.(database) ?? database, () => clock, { + regionalRehomeCohortPercent: 100, requireLiveCells: true, heartbeatTtlMs: 45_000 }) @@ -1864,8 +1566,8 @@ async function setup( drainGraceMs: 60 * 60_000 }) await store.reconcileCells([source, target]) - await heartbeat(store, source, sourceIncarnation, options.sourceProtocol ?? 1) - await heartbeat(store, target, targetIncarnation, options.targetProtocol ?? 1) + await heartbeat(store, source, sourceIncarnation, options.sourceProtocol ?? 3) + await heartbeat(store, target, targetIncarnation, options.targetProtocol ?? 3) return { database, store, @@ -1950,9 +1652,7 @@ async function cellReservations(context: Context): Promise [String(row.cell_id), Number(row.reserved_requests)]) - ) + return Object.fromEntries(rows.map((row) => [String(row.cell_id), Number(row.reserved_requests)])) } async function freshHeartbeats(context: Context): Promise { @@ -1966,8 +1666,8 @@ async function freshHeartbeats(context: Context): Promise { databasePoolWaitMsMax: 0 } // The clock doubles as a strictly-increasing connection inclusion watermark. - await heartbeat(context.store, source, sourceIncarnation, 1, context.now(), safety) - await heartbeat(context.store, target, targetIncarnation, 1, context.now(), safety) + await heartbeat(context.store, source, sourceIncarnation, 3, context.now(), safety) + await heartbeat(context.store, target, targetIncarnation, 3, context.now(), safety) } async function activatePreferredSource( @@ -1978,9 +1678,29 @@ async function activatePreferredSource( const control = await context.store.activateControl(identity, { cellId: source.id, assignmentEpoch: assignment.assignmentEpoch, - generation: 1 + generation: 1, + idleRegionalRehome: true, + cellIncarnation: sourceIncarnation }) await context.store.assign(identity, 'asia-east2') + const issued = await context.store.exchangeRegionCorrection( + identity, + { v: 1, action: 'issue-window' }, + assignment.assignmentEpoch + ) + await context.store.exchangeRegionCorrection( + identity, + { + v: 1, + action: 'report', + generation: issued.window!.generation, + assignmentEpoch: assignment.assignmentEpoch, + policyVersion: 1, + outcome: 'conclusive', + measurements: { 'us-central1': 150, 'asia-east2': 50 } + }, + assignment.assignmentEpoch + ) return control } @@ -1994,7 +1714,7 @@ function hookAfterCandidateScan( const decorate = (delegate: RelayDatabase): RelayDatabase => ({ query: async (sql, params) => { const rows = await delegate.query(sql, params) - if (!fired && sql.includes('FROM relay_assignment_region_preferences preference')) { + if (!fired && sql.includes('SELECT a.user_id, a.relay_host_id')) { fired = true await hook(delegate) } @@ -2017,7 +1737,7 @@ async function completeRehomeToTarget( identity: { userId: string; relayHostId: string } ): Promise { const sourceControl = await activatePreferredSource(context, identity) - const attempt = await context.store.claimRegionalRehome() + const attempt = await context.store.tryIdleRehome() const targetControl = await context.store.activateControl(identity, { cellId: target.id, assignmentEpoch: attempt!.assignmentEpoch, @@ -2040,9 +1760,29 @@ async function activateReversePreferredSource( const control = await context.store.activateControl(identity, { cellId: target.id, assignmentEpoch: assignment.assignmentEpoch, - generation: 1 + generation: 1, + idleRegionalRehome: true, + cellIncarnation: targetIncarnation }) await context.store.assign(identity, 'us-central1') + const issued = await context.store.exchangeRegionCorrection( + identity, + { v: 1, action: 'issue-window' }, + assignment.assignmentEpoch + ) + await context.store.exchangeRegionCorrection( + identity, + { + v: 1, + action: 'report', + generation: issued.window!.generation, + assignmentEpoch: assignment.assignmentEpoch, + policyVersion: 1, + outcome: 'conclusive', + measurements: { 'us-central1': 50, 'asia-east2': 150 } + }, + assignment.assignmentEpoch + ) return control } @@ -2059,7 +1799,7 @@ async function activateSource( } async function heartbeat( - store: RelayAssignmentStore, + store: IdleRehomeTestStore, cell: typeof source | typeof target, cellIncarnation: string, regionalRehomeProtocol: number, @@ -2152,3 +1892,46 @@ async function workerState( pausedUntil: Number(row.paused_until) } } + +class IdleRehomeTestStore extends BaseRelayAssignmentStore { + private readonly fixtureDatabase: RelayDatabase + private readonly fixtureNow: () => number + constructor(...args: ConstructorParameters) { + super(...args) + this.fixtureDatabase = args[0] + this.fixtureNow = args[1] ?? Date.now + } + async tryIdleRehome( + processSafety?: RegionalRehomeSafetySnapshot + ): Promise { + const safety = processSafety ?? { + observedAt: this.fixtureNow(), + sqlFailures: 0, + reconnects: 0, + controlActivityRecoveryFailures: 0, + databasePoolWaiting: 0, + databasePoolWaitersMax: 0, + databasePoolWaitMsMax: 0 + } + for (const candidate of await this.selectIdleRegionalRehomeCandidates(safety)) { + const result = await this.commitIdleRegionalRehome(candidate, safety) + if (result.outcome !== 'committed') continue + const row = ( + await this.fixtureDatabase.query( + 'SELECT * FROM relay_region_rehome_attempts WHERE attempt_id = ?', + [candidate.attemptId] + ) + )[0]! + return { + ...candidate, + preferredRegion: row.preferred_region as RegionalRehomeAttempt['preferredRegion'], + targetCellIncarnation: String(row.target_cell_incarnation), + previousEpoch: Number(row.previous_epoch), + assignmentEpoch: Number(row.assignment_epoch), + drainGraceMs: Number(row.drain_grace_ms), + sendAttempts: Number(row.send_attempts) + } + } + return null + } +} diff --git a/cloud/apps/relay/src/regional-rehome-target-selection.test.ts b/cloud/apps/relay/src/regional-rehome-target-selection.test.ts index 493eaa50a61..89ae6f88544 100644 --- a/cloud/apps/relay/src/regional-rehome-target-selection.test.ts +++ b/cloud/apps/relay/src/regional-rehome-target-selection.test.ts @@ -25,6 +25,7 @@ async function setup() { let clock = 1_000_000 const database = await openInMemoryRelayDatabase() const store = new RelayAssignmentStore(database, () => clock, { + regionalRehomeCohortPercent: 100, requireLiveCells: true, heartbeatTtlMs: 45_000 }) @@ -83,11 +84,40 @@ async function setup() { await store.activateControl(identity, { cellId: source.id, assignmentEpoch: assignment.assignmentEpoch, - generation: 1 + generation: 1, + idleRegionalRehome: true, + cellIncarnation: incarnation(1) }) - await store.assign(identity, 'asia-east2') + const { window } = await store.exchangeRegionCorrection( + identity, + { v: 1, action: 'issue-window' }, + assignment.assignmentEpoch + ) + expect(window).toBeDefined() + await store.exchangeRegionCorrection( + identity, + { + v: 1, + action: 'report', + generation: window!.generation, + assignmentEpoch: assignment.assignmentEpoch, + policyVersion: 1, + outcome: 'conclusive', + measurements: { 'us-central1': 180, 'asia-east2': 40 } + }, + assignment.assignmentEpoch + ) } - return { database, store, beat, activatePreferredSource } + const safety = () => ({ + observedAt: clock, + sqlFailures: 0, + reconnects: 0, + controlActivityRecoveryFailures: 0, + databasePoolWaiting: 0, + databasePoolWaitersMax: 0, + databasePoolWaitMsMax: 0 + }) + return { database, store, beat, activatePreferredSource, safety } } const UNCLEAN = REGIONAL_REHOME_SQL_FAILURES_PER_CELL_LIMIT + 1 @@ -95,70 +125,78 @@ const UNCLEAN = REGIONAL_REHOME_SQL_FAILURES_PER_CELL_LIMIT + 1 describe('regional rehome target selection', () => { it('never selects a target without connection headroom, even at lowest load', async () => { const context = await setup() - await context.beat(source, 1, 1, { + await context.beat(source, 1, 3, { observedRequests: 0, enforcedConnections: 0, sqlFailures: 0 }) // Lowest load but the connection hard cap is exhausted. - await context.beat(noHeadroom, 2, 1, { + await context.beat(noHeadroom, 2, 3, { observedRequests: 0, enforcedConnections: 999, sqlFailures: 0 }) - await context.beat(unclean, 3, 1, { + await context.beat(unclean, 3, 3, { observedRequests: 0, enforcedConnections: 0, sqlFailures: UNCLEAN }) - await context.beat(highLoad, 4, 1, { + await context.beat(highLoad, 4, 3, { observedRequests: 50, enforcedConnections: 0, sqlFailures: 0 }) - await context.beat(lowLoad, 5, 1, { + await context.beat(lowLoad, 5, 3, { observedRequests: 10, enforcedConnections: 0, sqlFailures: 0 }) await context.activatePreferredSource() - const attempt = await context.store.claimRegionalRehome() + const candidates = await context.store.selectIdleRegionalRehomeCandidates(context.safety()) + const attempt = candidates[0] expect(attempt?.targetCellId).toBe(lowLoad.id) + expect(await context.store.commitIdleRegionalRehome(attempt!, context.safety(), 100)).toEqual({ + outcome: 'committed' + }) await context.database.close() }) it('falls to the next clean target when the load winner goes unclean', async () => { const context = await setup() - await context.beat(source, 1, 1, { + await context.beat(source, 1, 3, { observedRequests: 0, enforcedConnections: 0, sqlFailures: 0 }) - await context.beat(noHeadroom, 2, 1, { + await context.beat(noHeadroom, 2, 3, { observedRequests: 0, enforcedConnections: 999, sqlFailures: 0 }) - await context.beat(unclean, 3, 1, { + await context.beat(unclean, 3, 3, { observedRequests: 0, enforcedConnections: 0, sqlFailures: UNCLEAN }) - await context.beat(highLoad, 4, 1, { + await context.beat(highLoad, 4, 3, { observedRequests: 50, enforcedConnections: 0, sqlFailures: 0 }) - await context.beat(lowLoad, 5, 1, { + await context.beat(lowLoad, 5, 3, { observedRequests: 10, enforcedConnections: 0, sqlFailures: UNCLEAN }) await context.activatePreferredSource() - const attempt = await context.store.claimRegionalRehome() + const candidates = await context.store.selectIdleRegionalRehomeCandidates(context.safety()) + const attempt = candidates[0] expect(attempt?.targetCellId).toBe(highLoad.id) + expect(await context.store.commitIdleRegionalRehome(attempt!, context.safety(), 100)).toEqual({ + outcome: 'committed' + }) await context.database.close() }) }) diff --git a/cloud/apps/relay/src/regional-rehome-worker.test.ts b/cloud/apps/relay/src/regional-rehome-worker.test.ts index 33e7f01f737..640ae06b121 100644 --- a/cloud/apps/relay/src/regional-rehome-worker.test.ts +++ b/cloud/apps/relay/src/regional-rehome-worker.test.ts @@ -11,148 +11,37 @@ import { startRegionalRehomeWorker } from './regional-rehome-worker.js' describe('regional rehome worker', () => { afterEach(() => vi.restoreAllMocks()) - it('sends an incarnation- and source-epoch-bound drain without exposing identity', async () => { - let now = 0 - const attempt = { - attemptId: '11111111-1111-4111-8111-111111111111', - userId: 'private-user', - relayHostId: 'abcdefghijklmnop', - preferredRegion: 'asia-east2', - sourceCellId: 'production-gce-c7', - sourceCellUrl: 'https://c7.relay.example.test', - sourceCellIncarnation: '22222222-2222-4222-8222-222222222222', - targetCellId: 'production-gce-c27', - targetCellIncarnation: '33333333-3333-4333-8333-333333333333', - previousEpoch: 7, - assignmentEpoch: 8, - drainGraceMs: 60_000, - sendAttempts: 1 + it('bounds empty polling to the six-second cadence and stops its timer', async () => { + vi.useFakeTimers() + const selectIdleRegionalRehomeCandidates = vi.fn().mockResolvedValue([]) + const worker = startRegionalRehomeWorker(config(), { + selectIdleRegionalRehomeCandidates + } as unknown as RelayAssignmentStore, { + safetySnapshot: () => safety(Date.now()), + random: () => 0 + })! + try { + await vi.advanceTimersByTimeAsync(0) + expect(selectIdleRegionalRehomeCandidates).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(5_999) + expect(selectIdleRegionalRehomeCandidates).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(1) + expect(selectIdleRegionalRehomeCandidates).toHaveBeenCalledTimes(2) + worker.stop() + await vi.advanceTimersByTimeAsync(60_000) + expect(selectIdleRegionalRehomeCandidates).toHaveBeenCalledTimes(2) + } finally { + worker.stop() + vi.useRealTimers() } - const claimRegionalRehome = vi.fn().mockResolvedValueOnce(null).mockResolvedValue(attempt) - const recordRegionalRehomeDrainReceipt = vi.fn().mockResolvedValue(true) - const assignments = { - claimRegionalRehome, - recordRegionalRehomeDrainReceipt - } as unknown as RelayAssignmentStore - const requests: Array<{ url: string; init?: RequestInit }> = [] - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const worker = startRegionalRehomeWorker(config(), assignments, { - now: () => now, - safetySnapshot: () => safety(now), - intervalMs: 60_000, - identityToken: async (audience) => { - expect(audience).toBe('https://relay.example.test/v1/admin/host-drain') - return 'secret-token' - }, - fetch: (async (url, init) => { - requests.push({ url: String(url), init }) - return Response.json({ v: 1, outcome: 'accepted' }) - }) as typeof fetch - })! - await settleWorker() - now = 1_000 - await worker.run() - worker.stop() - - expect(requests).toHaveLength(1) - expect(requests[0]!.url).toBe('https://c7.relay.example.test/v1/admin/host-drain') - expect(requests[0]!.url).not.toContain('secret-token') - expect(requests[0]!.init?.headers).toMatchObject({ - authorization: 'Bearer secret-token' - }) - expect(JSON.parse(String(requests[0]!.init?.body))).toEqual({ - v: 1, - attemptId: '11111111-1111-4111-8111-111111111111', - userId: 'private-user', - relayHostId: 'abcdefghijklmnop', - sourceCellId: 'production-gce-c7', - sourceCellIncarnation: '22222222-2222-4222-8222-222222222222', - sourceAssignmentEpoch: 7, - graceMs: 60_000 - }) - expect(recordRegionalRehomeDrainReceipt).toHaveBeenCalledWith( - '11111111-1111-4111-8111-111111111111', - 'accepted' - ) - const logs = warn.mock.calls.map((call) => String(call[0])).join('\n') - expect(logs).not.toContain('private-user') - expect(logs).not.toContain('abcdefghijklmnop') - }) - - it('fails closed before the observation gate and records bounded dispatch failures', async () => { - let now = 0 - const attempt = { - attemptId: '11111111-1111-4111-8111-111111111111', - userId: 'private-user', - relayHostId: 'abcdefghijklmnop', - sourceCellId: 'source', - sourceCellUrl: 'https://source.example.test', - sourceCellIncarnation: '22222222-2222-4222-8222-222222222222', - targetCellId: 'target', - previousEpoch: 1, - assignmentEpoch: 2, - drainGraceMs: 60_000, - sendAttempts: 1 - } - const claimRegionalRehome = vi.fn().mockResolvedValueOnce(null).mockResolvedValue(attempt) - const assignments = { - claimRegionalRehome, - recordRegionalRehomeDispatchFailure: vi.fn().mockResolvedValue(undefined) - } as unknown as RelayAssignmentStore - const worker = startRegionalRehomeWorker(config(), assignments, { - now: () => now, - safetySnapshot: () => safety(now), - intervalMs: 60_000, - identityToken: async () => { - throw new Error('token unavailable') - } - })! - await settleWorker() - claimRegionalRehome.mockClear() - now = 100 - await worker.run() - worker.stop() - expect(assignments.recordRegionalRehomeDispatchFailure).toHaveBeenCalledWith( - '11111111-1111-4111-8111-111111111111' - ) - }) - - it('keeps a failed poll out of the durable dispatch-failure budget', async () => { - let now = 0 - const claimRegionalRehome = vi - .fn() - .mockResolvedValueOnce(null) - .mockRejectedValue(new Error('Connection terminated due to connection timeout')) - const recordRegionalRehomeDispatchFailure = vi.fn().mockResolvedValue(undefined) - const assignments = { - claimRegionalRehome, - recordRegionalRehomeDispatchFailure - } as unknown as RelayAssignmentStore - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const worker = startRegionalRehomeWorker(config(), assignments, { - now: () => now, - safetySnapshot: () => safety(now), - intervalMs: 60_000 - })! - await settleWorker() - now = 1_000 - await expect(worker.run()).resolves.toBeUndefined() - worker.stop() - - // The poll never claimed an attempt, so nothing was drained and nothing may - // be charged to the budget that latches the durable control off. - expect(recordRegionalRehomeDispatchFailure).not.toHaveBeenCalled() - expect(warn.mock.calls.map((call) => JSON.parse(String(call[0])).event)).toEqual([ - 'orca_relay_regional_rehome_poll_failed' - ]) }) it('passes unsafe process telemetry to the durable claim gate', async () => { let now = 0 let sqlFailures = 0 - const claimRegionalRehome = vi.fn().mockResolvedValue(null) + const selectIdleRegionalRehomeCandidates = vi.fn().mockResolvedValue([]) const assignments = { - claimRegionalRehome + selectIdleRegionalRehomeCandidates } as unknown as RelayAssignmentStore const worker = startRegionalRehomeWorker(config(), assignments, { now: () => now, @@ -160,46 +49,40 @@ describe('regional rehome worker', () => { intervalMs: 60_000 })! await settleWorker() - claimRegionalRehome.mockClear() + selectIdleRegionalRehomeCandidates.mockClear() now = 100 sqlFailures = 1 await worker.run() worker.stop() - expect(claimRegionalRehome).toHaveBeenCalledWith( + expect(selectIdleRegionalRehomeCandidates).toHaveBeenCalledWith( expect.objectContaining({ observedAt: 100, sqlFailures: 1 }) ) }) it('starts inert on directors so durable control can enable without a restart', async () => { let now = 0 - const claimRegionalRehome = vi.fn().mockResolvedValue(null) + const selectIdleRegionalRehomeCandidates = vi.fn().mockResolvedValue([]) const assignments = { - claimRegionalRehome + selectIdleRegionalRehomeCandidates } as unknown as RelayAssignmentStore - const worker = startRegionalRehomeWorker( - config(), - assignments, - { - now: () => now, - safetySnapshot: () => safety(now), - intervalMs: 60_000 - } - ) + const worker = startRegionalRehomeWorker(config(), assignments, { + now: () => now, + safetySnapshot: () => safety(now), + intervalMs: 60_000 + }) expect(worker).not.toBeNull() await settleWorker() - claimRegionalRehome.mockClear() + selectIdleRegionalRehomeCandidates.mockClear() now = 100 await worker!.run() worker!.stop() - expect(claimRegionalRehome).toHaveBeenCalledOnce() + expect(selectIdleRegionalRehomeCandidates).toHaveBeenCalledOnce() expect( - startRegionalRehomeWorker( - config({ role: 'cell' }), - {} as RelayAssignmentStore, - { safetySnapshot: () => safety(1) } - ) + startRegionalRehomeWorker(config({ role: 'cell' }), {} as RelayAssignmentStore, { + safetySnapshot: () => safety(1) + }) ).toBeNull() }) @@ -208,16 +91,20 @@ describe('regional rehome worker', () => { const limit = cells * REGIONAL_REHOME_RECONNECTS_PER_CELL_LIMIT const processSafety = { ...safety(100), reconnects: limit * 10 } const fleetSafety = { ...safety(100), reconnects: limit } - expect(regionalRehomeSafetyFailure( - combineRegionalRehomeSafety(processSafety, fleetSafety), - 100, - cells - )).toBeNull() - expect(regionalRehomeSafetyFailure( - combineRegionalRehomeSafety(processSafety, { ...fleetSafety, reconnects: limit + 1 }), - 100, - cells - )).toBe('elevated_reconnects') + expect( + regionalRehomeSafetyFailure( + combineRegionalRehomeSafety(processSafety, fleetSafety), + 100, + cells + ) + ).toBeNull() + expect( + regionalRehomeSafetyFailure( + combineRegionalRehomeSafety(processSafety, { ...fleetSafety, reconnects: limit + 1 }), + 100, + cells + ) + ).toBe('elevated_reconnects') }) }) diff --git a/cloud/apps/relay/src/regional-rehome-worker.ts b/cloud/apps/relay/src/regional-rehome-worker.ts index 4d8fa694afd..67d872b888a 100644 --- a/cloud/apps/relay/src/regional-rehome-worker.ts +++ b/cloud/apps/relay/src/regional-rehome-worker.ts @@ -1,4 +1,4 @@ -import { z } from 'zod' +import { IdleRegionalRehomeResponseSchema } from '@orca-cloud/relay-contract' import type { RelayAssignmentStore } from './assignment-store.js' import type { RelayConfig } from './config.js' import { googleMetadataIdentityToken } from './google-metadata-identity-token.js' @@ -20,13 +20,6 @@ export type RegionalRehomeWorker = { stop: () => void } -const RegionalHostDrainResponseSchema = z - .object({ - v: z.literal(1), - outcome: z.enum(['accepted', 'already-accepted', 'host-not-connected']) - }) - .strict() - export function startRegionalRehomeWorker( config: RelayConfig, assignments: RelayAssignmentStore, @@ -42,7 +35,6 @@ export function startRegionalRehomeWorker( } const audience = config.rehomeAudience const safetySnapshot = options.safetySnapshot - const now = options.now ?? Date.now const fetchImpl = options.fetch ?? fetch const tokenProvider = options.identityToken ?? @@ -52,64 +44,50 @@ export function startRegionalRehomeWorker( const run = async (): Promise => { if (stopped || inFlight) return inFlight = true - let attemptId: string | null = null try { - const processSafety = safetySnapshot() - const attempt = await assignments.claimRegionalRehome(processSafety) - if (!attempt) return - attemptId = attempt.attemptId + const candidates = await assignments.selectIdleRegionalRehomeCandidates(safetySnapshot()) + if (candidates.length === 0) return const token = await tokenProvider(audience) - const response = await fetchImpl( - new URL('/v1/admin/host-drain', attempt.sourceCellUrl), - { - method: 'POST', - headers: { - authorization: `Bearer ${token}`, - 'content-type': 'application/json' - }, - body: JSON.stringify({ - v: 1, - attemptId: attempt.attemptId, - userId: attempt.userId, - relayHostId: attempt.relayHostId, - sourceCellId: attempt.sourceCellId, - sourceCellIncarnation: attempt.sourceCellIncarnation, - sourceAssignmentEpoch: attempt.previousEpoch, - graceMs: attempt.drainGraceMs - }), - signal: AbortSignal.timeout(options.requestTimeoutMs ?? 10_000) + for (const candidate of candidates) { + if (stopped) return + const { sourceCellUrl, ...request } = candidate + try { + const response = await fetchImpl(new URL('/v1/admin/host-idle-rehome', sourceCellUrl), { + method: 'POST', + headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, + body: JSON.stringify({ + ...request, + cohortPercent: config.regionCorrectionCohortPercent ?? 0, + directorSafety: safetySnapshot() + }), + signal: AbortSignal.timeout(options.requestTimeoutMs ?? 10_000) + }) + if (!response.ok) throw new Error(`regional_rehome_source_${response.status}`) + const body = IdleRegionalRehomeResponseSchema.parse(await response.json()) + if (body.outcome === 'committed') { + console.warn( + JSON.stringify({ + event: 'orca_relay_idle_rehome_committed', + sourceCellId: candidate.sourceCellId, + targetCellId: candidate.targetCellId + }) + ) + return + } + } catch (error) { + // The source may have committed; its durable outcome owns recovery. + console.warn( + JSON.stringify({ + event: 'orca_relay_idle_rehome_request_failed', + reason: error instanceof Error ? error.message : 'unknown' + }) + ) } - ) - if (!response.ok) throw new Error(`regional_rehome_source_${response.status}`) - const body = RegionalHostDrainResponseSchema.safeParse(await response.json()) - if (!body.success) throw new Error('regional_rehome_source_invalid_response') - await assignments.recordRegionalRehomeDrainReceipt( - attempt.attemptId, - body.data.outcome - ) - console.warn( - JSON.stringify({ - event: 'orca_relay_regional_rehome_dispatched', - sourceCellId: attempt.sourceCellId, - targetCellId: attempt.targetCellId, - outcome: body.data.outcome, - sendAttempts: attempt.sendAttempts - }) - ) - } catch (error) { - // Only a claimed attempt was drained. A poll that failed before the claim - // - a pool timeout on the once-a-second control read - dispatched nothing, - // so it must not spend the budget that latches the durable control off. - if (attemptId) { - await assignments - .recordRegionalRehomeDispatchFailure(attemptId) - .catch(() => undefined) } + } catch (error) { console.warn( JSON.stringify({ - event: attemptId - ? 'orca_relay_regional_rehome_dispatch_failed' - : 'orca_relay_regional_rehome_poll_failed', + event: 'orca_relay_regional_rehome_poll_failed', reason: error instanceof Error ? error.message : 'unknown' }) ) @@ -119,7 +97,8 @@ export function startRegionalRehomeWorker( } const timer = setInterval( () => void run(), - options.intervalMs ?? jitteredSweepIntervalMs(1_000, options.random) + // Match the initial ten-moves/minute budget without replanning the join every second. + options.intervalMs ?? jitteredSweepIntervalMs(6_000, options.random) ) timer.unref() void run() diff --git a/cloud/apps/relay/src/relay-region-app.test.ts b/cloud/apps/relay/src/relay-region-app.test.ts index 30cf3bf3e26..54e8da670b8 100644 --- a/cloud/apps/relay/src/relay-region-app.test.ts +++ b/cloud/apps/relay/src/relay-region-app.test.ts @@ -40,6 +40,7 @@ describe('Relay region API', () => { ) expect(response.status).toBe(200) + expect(await response.clone().json()).not.toHaveProperty('regionCorrection') expect(assign).toHaveBeenCalledWith( { userId: 'user-1', relayHostId: 'asiahost00000001' }, 'asia-east2', @@ -83,6 +84,160 @@ describe('Relay region API', () => { ) }) + it('preserves the cold-start hint and binds a negotiated window after placement', async () => { + const assignment = { + userId: 'user-1', + relayHostId: 'abcdefghijklmnop', + cellId: 'asia-c1', + cellUrl: 'https://asia-c1.relay.example.test', + region: 'asia-east2', + assignmentEpoch: 7, + leaseExpiresAt: Date.now() + 300_000 + } + const assign = vi.fn(async () => assignment) + const window = { + generation: 2, + expiresAt: Date.now() + 86_400_000, + assignmentEpoch: 7, + incumbentRegion: 'asia-east2', + policyVersion: 1 + } + const exchangeRegionCorrection = vi.fn(async () => ({ v: 1, window })) + const app = createRelayApp(config(), { + store: {} as never, + assignments: { assign, exchangeRegionCorrection } as never, + drain: vi.fn(), + ready: async () => true + }) + const regionCorrection = { v: 1, action: 'issue-window' } + const response = await app.request( + '/v1/assign', + assignmentRequest('abcdefghijklmnop', { + preferredRegion: 'asia-east2', + regionCorrection + }) + ) + expect(response.status).toBe(200) + expect(assign).toHaveBeenCalledWith( + { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }, + 'asia-east2', + 'asia-east2' + ) + expect(exchangeRegionCorrection).toHaveBeenCalledWith( + { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }, + regionCorrection, + 7 + ) + expect(((await response.json()) as { regionCorrection: unknown }).regionCorrection).toEqual({ + v: 1, + window + }) + }) + + it('returns successful placement when optional window storage is unavailable', async () => { + const app = createRelayApp(config(), { + store: {} as never, + assignments: { + assign: async () => ({ + cellId: 'asia-c1', + region: 'asia-east2', + cellUrl: 'https://asia-c1.relay.example.test', + assignmentEpoch: 7 + }), + exchangeRegionCorrection: async () => { + throw new Error('database unavailable') + } + } as never, + drain: vi.fn(), + ready: async () => true + }) + const response = await app.request( + '/v1/assign', + assignmentRequest('abcdefghijklmnop', { + preferredRegion: 'asia-east2', + regionCorrection: { v: 1, action: 'issue-window' } + }) + ) + expect(response.status).toBe(200) + expect(await response.json()).toMatchObject({ + cellUrl: 'https://asia-c1.relay.example.test', + assignmentEpoch: 7 + }) + }) + + it('does not place or write a legacy hint when reporting migration evidence', async () => { + const current = { + userId: 'user-1', + relayHostId: 'abcdefghijklmnop', + cellId: 'asia-c1', + cellUrl: 'https://asia-c1.relay.example.test', + region: 'asia-east2', + assignmentEpoch: 7, + leaseExpiresAt: Date.now() + 300_000 + } + const assign = vi.fn() + const resolve = vi.fn(async () => current) + const exchangeRegionCorrection = vi.fn(async () => ({ v: 1, reportStatus: 'accepted' })) + const app = createRelayApp(config(), { + store: {} as never, + assignments: { assign, resolve, exchangeRegionCorrection } as never, + drain: vi.fn(), + ready: async () => true + }) + const regionCorrection = { + v: 1, + action: 'report', + generation: 2, + assignmentEpoch: 7, + policyVersion: 1, + outcome: 'conclusive', + measurements: { 'us-central1': 40, 'asia-east2': 180 } + } + const response = await app.request( + '/v1/assign', + assignmentRequest('abcdefghijklmnop', { + preferredRegion: 'us-central1', + regionCorrection + }) + ) + expect(response.status).toBe(200) + expect(assign).not.toHaveBeenCalled() + expect(exchangeRegionCorrection).toHaveBeenCalledWith( + { userId: 'user-1', relayHostId: 'abcdefghijklmnop' }, + regionCorrection, + 7 + ) + expect(((await response.json()) as { assignmentEpoch: number }).assignmentEpoch).toBe(7) + }) + + it('does not manufacture an assignment for a report whose assignment disappeared', async () => { + const assign = vi.fn() + const exchangeRegionCorrection = vi.fn() + const app = createRelayApp(config(), { + store: {} as never, + assignments: { assign, resolve: async () => null, exchangeRegionCorrection } as never, + drain: vi.fn(), + ready: async () => true + }) + const response = await app.request( + '/v1/assign', + assignmentRequest('abcdefghijklmnop', { + regionCorrection: { + v: 1, + action: 'report', + generation: 2, + assignmentEpoch: 7, + policyVersion: 1, + outcome: 'inconclusive', + reason: 'timeout' + } + }) + ) + expect(response.status).toBe(409) + expect(assign).not.toHaveBeenCalled() + expect(exchangeRegionCorrection).not.toHaveBeenCalled() + }) + it('exposes only the store-provided healthy catalog from directors', async () => { const regionCatalog = vi.fn(async () => [ { region: 'us-central1' as const, probeOrigins: ['https://us.relay.example.test'] } diff --git a/cloud/apps/relay/src/relay-server.ts b/cloud/apps/relay/src/relay-server.ts index 77a15a1d259..7cee77e52de 100644 --- a/cloud/apps/relay/src/relay-server.ts +++ b/cloud/apps/relay/src/relay-server.ts @@ -20,14 +20,12 @@ import { createRelayApp } from './app.js' import { RelayAssignmentStore } from './assignment-store.js' import type { RelayConfig } from './config.js' import { RelayCredentialStore } from './credential-store.js' -import type { RelayDatabase } from './database.js' +import { readRelayDatabasePoolPressure, type RelayDatabase } from './database.js' import { HostSessionRegistry } from './host-session-registry.js' import { observeRelayDatabase } from './observed-relay-database.js' import { RelayObservability } from './relay-observability.js' -import { - RelayConnectionLedger, - type RelayConnectionUpgrade -} from './relay-connection-ledger.js' +import { combineRegionalRehomeSafety } from './regional-rehome-safety.js' +import { RelayConnectionLedger, type RelayConnectionUpgrade } from './relay-connection-ledger.js' import { createRelayReadiness } from './relay-readiness.js' import { createRelayTokenVerifier, readBearer } from './relay-token-verifier.js' import { closeRelayWebSocket } from './relay-websocket-close.js' @@ -65,7 +63,7 @@ function guardSocketErrors(socket: WebSocket, kind: string): void { function admissionSource(request: IncomingMessage): string { const forwarded = request.headers['x-forwarded-for'] - const chain = (Array.isArray(forwarded) ? forwarded.join(',') : forwarded ?? '') + const chain = (Array.isArray(forwarded) ? forwarded.join(',') : (forwarded ?? '')) .split(',') .map((entry) => entry.trim()) .filter(Boolean) @@ -112,6 +110,7 @@ export function createRelayServer( const store = new RelayCredentialStore(observedDatabase, options.now) const assignments = new RelayAssignmentStore(observedDatabase, options.now, { requireLiveCells: config.role === 'director', + regionalRehomeCohortPercent: config.regionCorrectionCohortPercent ?? 0, recordControlRenewal: (durationMs, outcome) => observability.recordControlRenewal?.(durationMs, outcome) }) @@ -127,17 +126,35 @@ export function createRelayServer( queuedBytes, observability, options.now, - options.random + options.random, + cellIncarnation ) const app = createRelayApp(config, { store, assignments, drain: (graceMs) => sessions.drain(graceMs), drainHost: (input) => sessions.drainHost(input), + idleRehome: (input) => { + const now = (options.now ?? Date.now)() + if (input.directorSafety.observedAt > now || now - input.directorSafety.observedAt > 60_000) { + return Promise.resolve({ outcome: 'deferred' }) + } + return sessions.idleRehome(input, + () => assignments.commitIdleRegionalRehome(input, combineRegionalRehomeSafety( + input.directorSafety, + { ...observability.regionalRehomeRuntimeSafety(), ...readRelayDatabasePoolPressure(database) } + ), input.cohortPercent), + () => assignments.reconcileIdleRegionalRehome(input) + ) + }, regionalRehomeTrustProbeHostExists: (input) => sessions.get(input) !== null, cellIncarnation, isDraining: () => sessions.isDraining(), runtimeCounts: () => runtimeCounts(), + regionalRehomeSafetySnapshot: () => ({ + ...observability.regionalRehomeRuntimeSafety(), + ...readRelayDatabasePoolPressure(database) + }), ready, recordAssignmentAdmission: (outcome) => observability.recordAssignmentAdmission?.(outcome), recordAssignmentRejectionReason: (lane, reason) => @@ -339,7 +356,7 @@ export function createRelayServer( const identity = invite ? { userId: invite.userId, relayHostId: hostId } : null // Released combined-service invites gain their first durable cell assignment here. const assignment = identity - ? (await assignments.resolve(identity)) ?? (await assignments.assign(identity)) + ? ((await assignments.resolve(identity)) ?? (await assignments.assign(identity))) : null if (!invite || !assignment) { phoneAdmission?.hostData.release() diff --git a/cloud/apps/relay/src/relay-sweep-schedule.test.ts b/cloud/apps/relay/src/relay-sweep-schedule.test.ts index d5ef450cc43..b9965ae29ff 100644 --- a/cloud/apps/relay/src/relay-sweep-schedule.test.ts +++ b/cloud/apps/relay/src/relay-sweep-schedule.test.ts @@ -19,7 +19,7 @@ describe('sweep schedule jitter', () => { expect(SWEEP_JITTER_FRACTION).toBeGreaterThan(0) }) - it('jitters the regional rehome dispatch tick, which every director runs each second', () => { + it('jitters the six-second regional rehome dispatch tick across directors', () => { const timers: number[] = [] const setIntervalSpy = vi .spyOn(globalThis, 'setInterval') @@ -35,14 +35,14 @@ describe('sweep schedule jitter', () => { rehomeAudience: 'https://rehome.example.test', rehomeDirectorServiceAccount: 'rehome@example.test' } as never, - { claimRegionalRehome: async () => null } as never, + { selectIdleRegionalRehomeCandidates: async () => [] } as never, { random: () => 0.5, safetySnapshot: () => ({}) as never } ) } finally { setIntervalSpy.mockRestore() } - expect(timers).toEqual([1_100]) + expect(timers).toEqual([6_600]) }) // Why: index.ts boots a server on import, so its wiring can only be read. diff --git a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/README.md b/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/README.md new file mode 100644 index 00000000000..2ac4ad78391 --- /dev/null +++ b/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/README.md @@ -0,0 +1,8 @@ +Exact relay contract snapshots from `027acb4efa2e6b226d40df266b86367423946d62`, `cloud/packages/relay-contract/src/`. Used to exercise the pre-correction strict wire parsers. Do not format or edit these baseline sources. + +```text +aba94e108a5cd0f1af8b38875429ad8636d24c43a728273e3df60d9a1a1d1b6d director-messages.ts +bd13b5a694a5d683a5b680c14e46ab33f4ef4a5bfedf040d046b09d540cb4c17 wire-scalars.ts +bc89116f884a2f20a6588f9b91219aa596bc2410d28b499a93a78350def109d5 relay-regions.ts +8fcae470a5fc72f2fcdde9d2f09cd20289c256356dd490484ac1cfa53839fbe4 control-messages.ts +``` diff --git a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/control-messages.ts b/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/control-messages.ts new file mode 100644 index 00000000000..0daf21e7c28 --- /dev/null +++ b/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/control-messages.ts @@ -0,0 +1,146 @@ +import { z } from 'zod' +import { + Base6432ByteSchema, + Base64Raw24ByteSchema, + Base64Url32ByteSchema, + EpochMsSchema, + GenerationSchema, + OpaqueIdSchema, + PositiveDurationMsSchema, + RelayHostIdSchema +} from './wire-scalars.js' + +const AppVersionSchema = z.string().min(1).max(128) +const BoundedCiphertextSchema = z + .string() + .min(1) + .max(16 * 1024) + .regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/) +const ConnectionKindSchema = z.enum(['invite', 'resume']) + +export const HostHelloSchema = z + .object({ + v: z.literal(1), + relayHostId: RelayHostIdSchema, + assignmentEpoch: GenerationSchema, + hostPublicKeyB64: Base6432ByteSchema, + appVersion: AppVersionSchema, + previousGeneration: GenerationSchema.optional(), + controlResumeSecret: Base64Url32ByteSchema.optional() + }) + .strict() + +export const HostChallengeSchema = z + .object({ + challengeId: OpaqueIdSchema, + relayEphemeralPublicKeyB64: Base6432ByteSchema, + nonceB64: Base64Raw24ByteSchema, + ciphertextB64: BoundedCiphertextSchema, + expiresAt: EpochMsSchema + }) + .strict() + +export const HostChallengeAckSchema = z + .object({ challengeId: OpaqueIdSchema, proofB64: Base6432ByteSchema }) + .strict() + +// Advertised on the control upgrade rather than in host-hello: HostHelloSchema +// is strict, so a new hello key is refused by every already-deployed cell. +export const RELAY_HOST_CAPABILITIES_HEADER = 'x-orca-host-capabilities' +// The host accepts kind/relayDeviceId on a pendingConns entry. A host that does +// not advertise this parses those entries strictly and would drop the whole ack. +export const RELAY_HOST_CAPABILITY_PENDING_CONN_DETAILS = 'pending-conn-details' + +export function parseRelayHostCapabilities( + header: string | string[] | undefined +): ReadonlySet { + const raw = Array.isArray(header) ? header.join(',') : (header ?? '') + return new Set( + raw + .split(',') + .map((token) => token.trim()) + .filter((token) => token.length > 0 && token.length <= 64) + .slice(0, 16) + ) +} + +// kind/relayDeviceId are optional so an entry stays readable by a host that +// predates them; the cell only emits them to a host that advertised support. +const PendingConnectionSchema = z + .object({ + connId: OpaqueIdSchema, + connTicket: Base64Url32ByteSchema, + kind: ConnectionKindSchema.optional(), + relayDeviceId: OpaqueIdSchema.optional() + }) + .strict() + +export const HostHelloAckSchema = z + .object({ + v: z.literal(1), + generation: GenerationSchema, + controlResumeSecret: Base64Url32ByteSchema, + leaseExpiresAt: EpochMsSchema, + activeConnIds: z.array(OpaqueIdSchema).max(8), + pendingConns: z.array(PendingConnectionSchema).max(8) + }) + .strict() + +export const ConnectionOpenSchema = z + .object({ + connId: OpaqueIdSchema, + connTicket: Base64Url32ByteSchema, + kind: ConnectionKindSchema, + relayDeviceId: OpaqueIdSchema, + attachDeadlineMs: PositiveDurationMsSchema + }) + .strict() + +export const HostDataAuthSchema = z + .object({ + v: z.literal(1), + connTicket: Base64Url32ByteSchema, + generation: GenerationSchema + }) + .strict() + +export const InviteCreateSchema = z + .object({ reqId: OpaqueIdSchema, relayDeviceId: OpaqueIdSchema }) + .strict() + +export const InviteCreatedSchema = z + .object({ + reqId: OpaqueIdSchema, + inviteToken: Base64Url32ByteSchema, + expiresAt: EpochMsSchema, + maxAttempts: z.number().int().positive().max(16) + }) + .strict() + +export const DeviceRevokeSchema = z + .object({ reqId: OpaqueIdSchema, relayDeviceId: OpaqueIdSchema }) + .strict() + +export const AuthRefreshSchema = z.object({ relayJwt: z.string().min(1).max(8 * 1024) }).strict() + +export const DrainSchema = z + .object({ + graceMs: z.number().int().nonnegative().max(60 * 60 * 1000), + recovery: z.literal('resolve-director') + }) + .strict() + +export const HeartbeatSchema = z.object({ t: EpochMsSchema }).strict() + +export type HostHello = z.infer +export type HostChallenge = z.infer +export type HostChallengeAck = z.infer +export type HostHelloAck = z.infer +export type ConnectionOpen = z.infer +export type HostDataAuth = z.infer +export type InviteCreate = z.infer +export type InviteCreated = z.infer +export type DeviceRevoke = z.infer +export type AuthRefresh = z.infer +export type Drain = z.infer +export type Heartbeat = z.infer diff --git a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/director-messages.ts b/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/director-messages.ts new file mode 100644 index 00000000000..e697135b68e --- /dev/null +++ b/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/director-messages.ts @@ -0,0 +1,75 @@ +import { z } from 'zod' +import { + Base64Url32ByteSchema, + CanonicalHttpsOriginSchema, + EpochMsSchema, + GenerationSchema, + RelayHostIdSchema +} from './wire-scalars.js' +import { RelayRegionSchema } from './relay-regions.js' + +const SignedAssignmentLeaseSchema = z.string().min(1).max(8 * 1024) + +export const AssignmentRequestSchema = z + .object({ + v: z.literal(1), + relayHostId: RelayHostIdSchema, + // Client-declared reconnection; the director verifies it against the + // durable assignment before granting fast-lane admission. + reconnect: z.boolean().optional(), + preferredRegion: RelayRegionSchema.optional() + }) + .strict() + +export const AssignmentResponseSchema = z + .object({ + v: z.literal(1), + cellUrl: CanonicalHttpsOriginSchema, + assignmentEpoch: GenerationSchema, + lease: SignedAssignmentLeaseSchema + }) + .strict() + +export const ResolveRequestSchema = z + .object({ + v: z.literal(1), + relayHostId: RelayHostIdSchema, + resumeToken: Base64Url32ByteSchema + }) + .strict() + +export const ResolveResponseSchema = z + .object({ + v: z.literal(1), + cellUrl: CanonicalHttpsOriginSchema, + assignmentEpoch: GenerationSchema, + leaseExpiresAt: EpochMsSchema + }) + .strict() + +export const RelayMovedSchema = z + .object({ + v: z.literal(1), + cellUrl: CanonicalHttpsOriginSchema, + assignmentEpoch: GenerationSchema + }) + .strict() + +export function isTrustedNewerMove(input: { + sourceOrigin: string + configuredDirectorOrigin: string + currentAssignmentEpoch: number + move: z.infer +}): boolean { + // Why: cells and stale director responses must never redirect a credential-bearing client. + return ( + input.sourceOrigin === input.configuredDirectorOrigin && + input.move.assignmentEpoch > input.currentAssignmentEpoch + ) +} + +export type AssignmentRequest = z.infer +export type AssignmentResponse = z.infer +export type ResolveRequest = z.infer +export type ResolveResponse = z.infer +export type RelayMoved = z.infer diff --git a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/relay-regions.ts b/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/relay-regions.ts new file mode 100644 index 00000000000..6b8837829df --- /dev/null +++ b/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/relay-regions.ts @@ -0,0 +1,71 @@ +import { z } from 'zod' + +export const RELAY_REGIONS = ['us-central1', 'asia-east2'] as const + +export const RelayRegionSchema = z.enum(RELAY_REGIONS) + +export type RelayRegion = z.infer + +export const RELAY_DEFAULT_REGION: RelayRegion = 'us-central1' + +// Field-name segment for the flat per-region runtime counters, spelled out rather than derived so +// the Terraform side can hold the same literal and a test can compare the two. `satisfies` makes a +// new region a compile error here, which is the point: a region with no segment would silently +// drop out of the region-skew alert's denominators. +export const RELAY_REGION_METRIC_SEGMENTS = { + 'us-central1': 'UsCentral1', + 'asia-east2': 'AsiaEast2' +} as const satisfies Record + +const RelayProbeOriginSchema = z.string().url().max(2_048).refine(isCanonicalHttpsOrigin) + +export const RelayRegionCatalogResponseSchema = z + .object({ + v: z.literal(1), + regions: z + .array( + z + .object({ + region: RelayRegionSchema, + probeOrigins: z.array(RelayProbeOriginSchema).min(1).max(2) + }) + .strict() + ) + .max(RELAY_REGIONS.length) + }) + .strict() + .superRefine((catalog, context) => { + const regions = new Set() + const origins = new Set() + for (const [regionIndex, entry] of catalog.regions.entries()) { + if (regions.has(entry.region)) { + context.addIssue({ + code: 'custom', + message: 'duplicate relay region', + path: ['regions', regionIndex, 'region'] + }) + } + regions.add(entry.region) + for (const [originIndex, origin] of entry.probeOrigins.entries()) { + if (origins.has(origin)) { + context.addIssue({ + code: 'custom', + message: 'duplicate relay probe origin', + path: ['regions', regionIndex, 'probeOrigins', originIndex] + }) + } + origins.add(origin) + } + } + }) + +export type RelayRegionCatalogResponse = z.infer + +function isCanonicalHttpsOrigin(value: string): boolean { + try { + const url = new URL(value) + return url.protocol === 'https:' && url.origin === value + } catch { + return false + } +} diff --git a/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/wire-scalars.ts b/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/wire-scalars.ts new file mode 100644 index 00000000000..27dd3a8b30f --- /dev/null +++ b/cloud/apps/relay/src/test-fixtures/relay-contract-baseline/wire-scalars.ts @@ -0,0 +1,20 @@ +import { z } from 'zod' + +export const Base64Url32ByteSchema = z.string().regex(/^[A-Za-z0-9_-]{43}$/) +export const Base64Url24ByteSchema = z.string().regex(/^[A-Za-z0-9_-]{32}$/) +export const Base6432ByteSchema = z.string().regex(/^(?:[A-Za-z0-9+/]{4}){10}[A-Za-z0-9+/]{3}=$/) +export const Base64Raw24ByteSchema = z.string().regex(/^(?:[A-Za-z0-9+/]{4}){8}$/) +export const RelayHostIdSchema = z.string().regex(/^[A-Za-z0-9_-]{16}$/) +export const OpaqueIdSchema = z.string().min(1).max(128) +export const EpochMsSchema = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER) +export const GenerationSchema = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER) +export const PositiveDurationMsSchema = z.number().int().positive().max(24 * 60 * 60 * 1000) + +export const CanonicalHttpsOriginSchema = z.string().max(2048).refine((value) => { + try { + const url = new URL(value) + return url.protocol === 'https:' && url.origin === value && url.pathname === '/' + } catch { + return false + } +}, 'must be a canonical HTTPS origin') diff --git a/cloud/apps/relay/tsconfig.build.json b/cloud/apps/relay/tsconfig.build.json index 489ddfd34d6..38eb0396cf2 100644 --- a/cloud/apps/relay/tsconfig.build.json +++ b/cloud/apps/relay/tsconfig.build.json @@ -6,5 +6,5 @@ "outDir": "dist", "rootDir": "src" }, - "exclude": ["src/**/*.test.ts"] + "exclude": ["src/**/*.test.ts", "src/test-fixtures/**"] } diff --git a/cloud/dev/scripts/deploy-relay-blue-green.mjs b/cloud/dev/scripts/deploy-relay-blue-green.mjs index 88e4f8ccc60..ddfe2bce8fc 100644 --- a/cloud/dev/scripts/deploy-relay-blue-green.mjs +++ b/cloud/dev/scripts/deploy-relay-blue-green.mjs @@ -10,6 +10,7 @@ export const DIRECTOR_REGIONAL_PLACEMENT_SECRET = 'orca-cloud-relay-regional-placement-enabled' export const DIRECTOR_REGIONAL_PLACEMENT_ENV = 'ORCA_RELAY_REGIONAL_PLACEMENT_ENABLED' +export const DIRECTOR_CORRECTION_COHORT_ENV = 'ORCA_RELAY_REGION_CORRECTION_COHORT_PERCENT' export const DIRECTOR_REHOME_IDENTITY_ENV = 'ORCA_RELAY_REHOME_DIRECTOR_SERVICE_ACCOUNT' export const DIRECTOR_REHOME_AUDIENCE_ENV = 'ORCA_RELAY_REHOME_AUDIENCE' @@ -228,6 +229,13 @@ export function directorCellSetAddition(currentValue, desiredValue) { return { changed: additions.length > 0, value: JSON.stringify(desired) } } +export function correctionCohortPercent(value) { + if (!/^(?:[0-9]|[1-9][0-9]|100)$/.test(String(value))) { + throw new Error('region correction cohort must be an integer from 0 to 100') + } + return String(value) +} + export function directorDeploymentEnvironment(config) { const imageDigest = config.image?.match(/@(sha256:[a-f0-9]{64})$/)?.[1] if (config.image !== undefined && imageDigest === undefined) { @@ -238,6 +246,10 @@ export function directorDeploymentEnvironment(config) { ORCA_RELAY_ADMISSION_SELECTOR_VERSION: SELECTOR_REVISION_MARKER, ...(imageDigest === undefined ? {} : { ORCA_RELAY_IMAGE_DIGEST: imageDigest }) } + if (config['region-correction-cohort-percent'] !== undefined && + config['region-correction-cohort-percent'] !== 'preserve') { + environment[DIRECTOR_CORRECTION_COHORT_ENV] = correctionCohortPercent(config['region-correction-cohort-percent']) + } const serviceAccount = projectServiceAccount(config, 'capacity-service-account') const asiaProofServiceAccount = projectServiceAccount(config, 'asia-proof-service-account') const rehomeDirectorServiceAccount = projectServiceAccount( @@ -302,7 +314,8 @@ export function parseArguments(argv) { values['rehome-director-service-account'] !== undefined || values['rehome-audience'] !== undefined || values['expected-rehome-generation'] !== undefined || - values['rehome-control-origin'] !== undefined + values['rehome-control-origin'] !== undefined || + values['region-correction-cohort-percent'] !== undefined ) { throw new Error('director configuration arguments require --role director') } @@ -785,6 +798,14 @@ export async function deployDirector(config, tag, overrides = {}) { config['prune-revisions'] === 'true' ? CONNECTION_CAPACITY_PROTOCOL : undefined const currentEnvironment = revisionEnvironment(servingRevision) const deploymentEnvironment = directorDeploymentEnvironment(config) + deploymentEnvironment[DIRECTOR_CORRECTION_COHORT_ENV] ??= correctionCohortPercent( + currentEnvironment[DIRECTOR_CORRECTION_COHORT_ENV] ?? '0' + ) + if (config['region-correction-cohort-percent'] !== undefined && + config['region-correction-cohort-percent'] !== 'preserve' && + config['expected-rehome-generation'] === undefined) { + throw new Error('cohort changes require an exact disabled regional-rehome generation') + } const mutableEnvironment = { ...deploymentEnvironment, [DIRECTOR_REGIONAL_PLACEMENT_ENV]: '' diff --git a/cloud/dev/scripts/deploy-relay-blue-green.test.mjs b/cloud/dev/scripts/deploy-relay-blue-green.test.mjs index 6e56676098b..a68ce50e912 100644 --- a/cloud/dev/scripts/deploy-relay-blue-green.test.mjs +++ b/cloud/dev/scripts/deploy-relay-blue-green.test.mjs @@ -4,6 +4,8 @@ import { test } from 'node:test' import { fileURLToPath } from 'node:url' import { activeRevision, + correctionCohortPercent, + DIRECTOR_CORRECTION_COHORT_ENV, cloudRunTrafficTag, DIRECTOR_ADMISSION_ENVIRONMENT, DIRECTOR_REGIONAL_PLACEMENT_ENV, @@ -812,3 +814,43 @@ test('waits for authenticated target readiness without hiding other capacity err /forbidden/ ) }) + + +test('validates bounded correction cohorts and leaves unspecified values to serving inheritance', () => { + for (const value of ['0', '1', '100']) assert.equal(correctionCohortPercent(value), value) + for (const value of ['-1', '101', '1.5', '', '01', 'true', '1\n']) { + assert.throws(() => correctionCohortPercent(value), /integer from 0 to 100/) + } + assert.equal(directorDeploymentEnvironment({})[DIRECTOR_CORRECTION_COHORT_ENV], undefined) + assert.equal(directorDeploymentEnvironment({ 'region-correction-cohort-percent': 'preserve' })[DIRECTOR_CORRECTION_COHORT_ENV], undefined) + assert.equal(directorDeploymentEnvironment({ 'region-correction-cohort-percent': '1' })[DIRECTOR_CORRECTION_COHORT_ENV], '1') +}) + +test('inherits the cohort on candidate and rollback revisions without resetting an enabled cohort', async () => { + const harness = directorHarness() + harness.state.revisions.get('relay-00001-old').env[DIRECTOR_CORRECTION_COHORT_ENV] = '3' + await deployDirector({}, 'candidate-new', harness.operations) + for (const revision of ['relay-00002-new', 'relay-00003-new']) { + assert.equal(harness.state.revisions.get(revision).env[DIRECTOR_CORRECTION_COHORT_ENV], '3') + } +}) + +test('starts an unstamped cohort at zero and rejects a cohort change without disabled-control proof', async () => { + const harness = directorHarness() + await assert.rejects(deployDirector({ 'region-correction-cohort-percent': '1' }, + 'candidate-new', harness.operations), /exact disabled regional-rehome generation/) + assert.equal(harness.state.activeRevision, 'relay-00001-old') + assert.equal(harness.state.nextRevision, 2) + await deployDirector({}, 'candidate-new', harness.operations) + assert.equal(harness.state.revisions.get('relay-00003-new').env[DIRECTOR_CORRECTION_COHORT_ENV], '0') +}) + +test('sets a reviewed cohort only behind repeated disabled-control verification', async () => { + const harness = directorHarness() + let verified = 0 + const config = { 'region-correction-cohort-percent': '1', 'expected-rehome-generation': '7' } + await deployDirector(config, 'candidate-new', { ...harness.operations, + assertRegionalRehomeDisabled: async () => { verified++ } }) + assert.ok(verified >= 2) + assert.equal(harness.state.revisions.get('relay-00003-new').env[DIRECTOR_CORRECTION_COHORT_ENV], '1') +}) diff --git a/cloud/dev/scripts/read-relay-serving-regional-placement-version.mjs b/cloud/dev/scripts/read-relay-serving-regional-placement-version.mjs index 80d40277e5a..796d0e9d91a 100644 --- a/cloud/dev/scripts/read-relay-serving-regional-placement-version.mjs +++ b/cloud/dev/scripts/read-relay-serving-regional-placement-version.mjs @@ -53,7 +53,7 @@ export function readRelayServingRegionalPlacementVersion(input, dependencies = { try { service = run(gcloudArguments('services', input)) } catch (error) { - if (error?.code === 'NOT_FOUND') return { version: input.bootstrap_version } + if (error?.code === 'NOT_FOUND') return { version: input.bootstrap_version, cohort_percent: '0' } throw error } const serving = (service.status?.traffic ?? []).filter( @@ -67,12 +67,22 @@ export function readRelayServingRegionalPlacementVersion(input, dependencies = { throw new Error('Relay director must have exactly one revision serving 100% traffic') } const revision = run(gcloudArguments('revisions', input, serving[0].revisionName)) + const cohortSettings = (revision.spec?.containers ?? []).flatMap((container) => + (container.env ?? []).filter((environment) => + environment.name === 'ORCA_RELAY_REGION_CORRECTION_COHORT_PERCENT') + ) + if (cohortSettings.length > 1 || (cohortSettings.length === 1 && + (typeof cohortSettings[0].value !== 'string' || + !/^(?:[0-9]|[1-9][0-9]|100)$/.test(cohortSettings[0].value)))) { + throw new Error('serving region correction cohort is invalid') + } + const cohort_percent = cohortSettings[0]?.value ?? '0' const references = (revision.spec?.containers ?? []).flatMap((container) => (container.env ?? []).filter( (environment) => environment.name === 'ORCA_RELAY_REGIONAL_PLACEMENT_ENABLED' ) ) - if (references.length === 0) return { version: input.bootstrap_version } + if (references.length === 0) return { version: input.bootstrap_version, cohort_percent } const reference = normalizeSecretReference(references[0]) if ( references.length !== 1 || @@ -81,7 +91,7 @@ export function readRelayServingRegionalPlacementVersion(input, dependencies = { ) { throw new Error('serving regional placement secret reference is invalid') } - return { version: reference.version } + return { version: reference.version, cohort_percent } } // Why: the v2 API reports `valueSource.secretKeyRef.{secret,version}`, but diff --git a/cloud/dev/scripts/read-relay-serving-regional-placement-version.test.mjs b/cloud/dev/scripts/read-relay-serving-regional-placement-version.test.mjs index 8043fc23e94..9c49d4127a5 100644 --- a/cloud/dev/scripts/read-relay-serving-regional-placement-version.test.mjs +++ b/cloud/dev/scripts/read-relay-serving-regional-placement-version.test.mjs @@ -67,7 +67,7 @@ test('reads the exact version from the sole traffic-serving revision', () => { } }) - assert.deepEqual(result, { version: '11' }) + assert.deepEqual(result, { version: '11', cohort_percent: '0' }) assert.equal(calls[1][3], 'relay-serving') }) @@ -78,7 +78,7 @@ test('reads the gcloud v1 secret reference shape by bare id and by full resource ]) { assert.deepEqual(readRelayServingRegionalPlacementVersion(input, { run: (args) => args[1] === 'services' ? serving() : v1Revision(name, '1') - }), { version: '1' }) + }), { version: '1', cohort_percent: '0' }) } }) @@ -100,12 +100,12 @@ test('falls back only when the service or setting is absent', () => { notFound.code = 'NOT_FOUND' assert.deepEqual(readRelayServingRegionalPlacementVersion(input, { run: () => { throw notFound } - }), { version: '7' }) + }), { version: '7', cohort_percent: '0' }) assert.deepEqual(readRelayServingRegionalPlacementVersion(input, { run: (args) => args[1] === 'services' ? { status: { traffic: [{ revisionName: 'relay-serving', percent: 100 }] } } : { spec: { containers: [{ env: [] }] } } - }), { version: '7' }) + }), { version: '7', cohort_percent: '0' }) }) test('classifies real absent-service stderr without weakening revision failures', () => { @@ -136,3 +136,31 @@ test('rejects ambiguous traffic, malformed references, and read failures', () => run: () => { throw denied } }), denied) }) + + +test('preserves the serving cohort including explicit disable across later Terraform plans', () => { + for (const value of ['0', '1', '17', '100']) { + const servingRevision = revision() + servingRevision.spec.containers[0].env.push({ name: 'ORCA_RELAY_REGION_CORRECTION_COHORT_PERCENT', value }) + assert.deepEqual(readRelayServingRegionalPlacementVersion(input, { + run: (args) => args[1] === 'services' ? serving() : servingRevision + }), { version: '11', cohort_percent: value }) + } +}) + +test('fails closed on malformed, secret-backed or duplicate cohorts rather than resetting them', () => { + const name = 'ORCA_RELAY_REGION_CORRECTION_COHORT_PERCENT' + const cases = [ + [{ name, value: '101' }], [{ name, value: '-1' }], [{ name, value: '1.5' }], + [{ name, value: '' }], [{ name, value: '01' }], [{ name, value: 1 }], + [{ name, valueFrom: { secretKeyRef: { name: 'unexpected', key: '1' } } }], + [{ name, value: '1' }, { name, value: '2' }] + ] + for (const settings of cases) { + const servingRevision = revision() + servingRevision.spec.containers[0].env.push(...settings) + assert.throws(() => readRelayServingRegionalPlacementVersion(input, { + run: (args) => args[1] === 'services' ? serving() : servingRevision + }), /cohort is invalid/) + } +}) diff --git a/cloud/dev/scripts/relay-production-same-cap-wave.mjs b/cloud/dev/scripts/relay-production-same-cap-wave.mjs index 6e84c1c9104..8caa68e7ff2 100644 --- a/cloud/dev/scripts/relay-production-same-cap-wave.mjs +++ b/cloud/dev/scripts/relay-production-same-cap-wave.mjs @@ -87,18 +87,21 @@ export function canaryAuthority(input) { } export function verifyCanaryAuthority(authority, expected, repositoryRoot) { + const selectorGeneration = Number(expected.selectorGeneration) if ( authority?.v !== 1 || !/^[0-9a-f]{40}$/.test(authority.commitSha ?? '') || authority.runId !== expected.runId || authority.targetDigest !== expected.targetDigest || authority.rollbackDigest !== expected.rollbackDigest || - authority.selectorGeneration !== Number(expected.selectorGeneration) || + !Number.isSafeInteger(authority.selectorGeneration) || + authority.selectorGeneration < 0 || + !Number.isSafeInteger(selectorGeneration) || + selectorGeneration < authority.selectorGeneration || authority.rehomeGeneration !== Number(expected.rehomeGeneration) || !SAME_CAP_CELLS.includes(authority.cellId) ) throw new Error('canary authority does not match this batch') - // The batch dispatch resolves main after the canary sealed, so bind to the same code, not the - // same SHA; every field above still pins this batch to that exact canary. + // Each cell checks exact live selector state; later batches may reuse this control epoch's canary. requireSameEvidenceCode({ sealedSha: authority.commitSha, currentSha: expected.commitSha, diff --git a/cloud/dev/scripts/relay-production-same-cap-wave.test.mjs b/cloud/dev/scripts/relay-production-same-cap-wave.test.mjs index d636c324b33..7377f7a7af3 100644 --- a/cloud/dev/scripts/relay-production-same-cap-wave.test.mjs +++ b/cloud/dev/scripts/relay-production-same-cap-wave.test.mjs @@ -109,6 +109,41 @@ test('seals and verifies canary authority for later batches', () => { }), /does not match/) }) +test('reuses a canary across selector advances only within the same control epoch', () => { + const authority = canaryAuthority({ + cellIds: 'production-gce-c7', targetDigest, rollbackDigest, + confirmation: `ROLL_RELAY_SAME_CAP ${targetDigest} production-gce-c7`, + commitSha: 'c'.repeat(40), runId: '42', selectorGeneration: '11', rehomeGeneration: '4' + }) + const expected = { + commitSha: 'c'.repeat(40), runId: '42', targetDigest, rollbackDigest, + selectorGeneration: '21', rehomeGeneration: '4' + } + for (const generation of ['13', '14', '21', '29']) { + assert.equal(verifyCanaryAuthority(authority, { + ...expected, selectorGeneration: generation + }), authority) + } + for (const generation of ['12', '-1', 'NaN', 'Infinity', '13.5', '9007199254740992']) { + assert.throws(() => verifyCanaryAuthority(authority, { + ...expected, selectorGeneration: generation + }), /does not match/) + } + for (const generation of [-1, NaN, Infinity, 13.5, '13', Number.MAX_SAFE_INTEGER + 1]) { + assert.throws(() => verifyCanaryAuthority({ + ...authority, selectorGeneration: generation + }, expected), /does not match/) + } + for (const mismatch of [ + { rehomeGeneration: '3' }, { rehomeGeneration: '5' }, + { targetDigest: rollbackDigest }, { rollbackDigest: targetDigest }, { runId: '43' } + ]) { + assert.throws(() => verifyCanaryAuthority(authority, { + ...expected, ...mismatch + }), /does not match/) + } +}) + function gitIn(root, ...args) { return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8' }).trim() } @@ -158,7 +193,7 @@ test('a batch trusts a canary sealed by identical code at an ancestor commit', a runId: '42', targetDigest, rollbackDigest, - selectorGeneration: '13', + selectorGeneration: '21', rehomeGeneration: '4' }, repositoryRoot) assert.equal(verifyAt(repository.sameCode, repository.root).cellId, 'production-gce-c7') diff --git a/cloud/dev/scripts/relay-same-cap-script-census.test.mjs b/cloud/dev/scripts/relay-same-cap-script-census.test.mjs index 7d5e4fee73e..3e5f0758028 100644 --- a/cloud/dev/scripts/relay-same-cap-script-census.test.mjs +++ b/cloud/dev/scripts/relay-same-cap-script-census.test.mjs @@ -77,14 +77,14 @@ function rollPlan({ cellId, cap, protocol }) { metadata_startup_script: startupScript({ cap, image: ROLLBACK_IMAGE, - trusted: protocol === 1 + trusted: protocol >= 1 }) }, after: { metadata_startup_script: startupScript({ cap, image: TARGET_IMAGE, - trusted: protocol === 1 + trusted: protocol >= 1 }), self_link: null }, @@ -178,11 +178,9 @@ describe('same-cap roll scripts accept every same-cap cell', () => { }) it('validates a correct plan for every wave cell at that cell\'s rehome protocol', () => { - for (const cellId of SAME_CAP_CELLS) { + for (const [cellId, protocol] of SAME_CAP_CELLS.flatMap((cell) => [[cell, 1], [cell, 3]])) { const [, cap] = resolveCellShape(cellId).stdout.trim().split(' ') - const protocol = REHOME_SOURCE_CELLS.has(cellId) ? 1 : 0 - // Every reviewed serving cell carries rehome trust now, in either region. - assert.equal(protocol, 1, cellId) + assert.equal(REHOME_SOURCE_CELLS.has(cellId), true, cellId) const config = { mode: 'same-cap-cell', cellId, @@ -204,7 +202,7 @@ describe('same-cap roll scripts accept every same-cap cell', () => { assert.throws( () => validateCapacityPlan(plan, { ...config, - regionalRehomeProtocol: String(1 - protocol) + regionalRehomeProtocol: '0' }), /reviewed image and capacity/, cellId @@ -239,3 +237,11 @@ describe('same-cap roll scripts accept every same-cap cell', () => { assert.doesNotMatch(capacityWorkflow, /--approved-cells/) }) }) + +// Both trusted versions must prove the same authenticated drain boundary. +it('proves rehome trust for protocol 3 on forward and rollback rolls', () => { + const step = workflow.split('name: Prove exact per-host trust and idempotent no-neighbor behavior')[1].split('\n - name:')[0] + assert.match(step, /inputs\.rollback-rehome-protocol != '0'/) + assert.match(step, /inputs\.target-rehome-protocol != '0'/) + assert.match(step, /probe-relay-rehome-trust\.mjs/) +}) diff --git a/cloud/dev/scripts/validate-relay-capacity-plan.mjs b/cloud/dev/scripts/validate-relay-capacity-plan.mjs index 294e85ae31d..34e84d51ead 100644 --- a/cloud/dev/scripts/validate-relay-capacity-plan.mjs +++ b/cloud/dev/scripts/validate-relay-capacity-plan.mjs @@ -9,7 +9,7 @@ const REHOME_CONFIG = // Only cells listed as regional rehome sources get rehome trust lines in their startup script. function rehomeProtocol({ regionalRehomeProtocol }) { - if (![0, 1, '0', '1'].includes(regionalRehomeProtocol)) { + if (![0, 1, 3, '0', '1', '3'].includes(regionalRehomeProtocol)) { throw new Error('same-cap Terraform plan has an invalid regional rehome protocol') } return Number(regionalRehomeProtocol) @@ -43,7 +43,7 @@ export function parseCapacityPlanArguments(argv) { (!values['rollback-image'] || !values['rehome-director-service-account'] || !values['rehome-audience'] || - !['0', '1'].includes(values['regional-rehome-protocol'])) + !['0', '1', '3'].includes(values['regional-rehome-protocol'])) ) throw new Error('same-cap validation requires rollback image and rehome trust config') if (values.mode !== 'same-cap-cell' && values['regional-rehome-protocol'] !== undefined) { throw new Error('--regional-rehome-protocol applies only to same-cap-cell validation') @@ -227,7 +227,7 @@ function requireDesiredStartupScript(script, config) { ` printf 'ORCA_RELAY_CAPACITY_SERVICE_ACCOUNT=%s\\n' '${config.capacityServiceAccount}'` ]) } - const rehomeTrusted = config.mode === 'same-cap-cell' && rehomeProtocol(config) === 1 + const rehomeTrusted = config.mode === 'same-cap-cell' && rehomeProtocol(config) >= 1 if (rehomeTrusted) { expected.push( [ diff --git a/cloud/dev/scripts/validate-relay-capacity-plan.test.mjs b/cloud/dev/scripts/validate-relay-capacity-plan.test.mjs index fb6ccb57e1c..d6886c58011 100644 --- a/cloud/dev/scripts/validate-relay-capacity-plan.test.mjs +++ b/cloud/dev/scripts/validate-relay-capacity-plan.test.mjs @@ -756,6 +756,10 @@ test('the rehome protocol argument is required by same-cap-cell mode alone', () .regionalRehomeProtocol, '0' ) + assert.equal( + parseCapacityPlanArguments(sameCapArguments('--regional-rehome-protocol', '3')).regionalRehomeProtocol, + '3' + ) assert.throws( () => parseCapacityPlanArguments(sameCapArguments()), /requires rollback image and rehome trust config/ diff --git a/cloud/dev/scripts/verify-relay-capacity-transition.mjs b/cloud/dev/scripts/verify-relay-capacity-transition.mjs index b81ea15afb3..0c297fdad53 100644 --- a/cloud/dev/scripts/verify-relay-capacity-transition.mjs +++ b/cloud/dev/scripts/verify-relay-capacity-transition.mjs @@ -108,8 +108,8 @@ export function parseCapacityTransitionArguments(argv) { const regionalRehomeProtocol = values['regional-rehome-protocol'] === undefined ? undefined : integer(values['regional-rehome-protocol'], '--regional-rehome-protocol') - if (regionalRehomeProtocol !== undefined && ![0, 1].includes(regionalRehomeProtocol)) { - throw new Error('--regional-rehome-protocol must be 0 or 1') + if (regionalRehomeProtocol !== undefined && ![0, 1, 3].includes(regionalRehomeProtocol)) { + throw new Error('--regional-rehome-protocol must be 0, 1, or 3') } if (runtime === 'unavailable' && regionalRehomeProtocol !== undefined) { throw new Error('unavailable runtime cannot prove the regional rehome protocol') diff --git a/cloud/docs/orca-relay-operations.md b/cloud/docs/orca-relay-operations.md index cd989b58e94..4515048b29b 100644 --- a/cloud/docs/orca-relay-operations.md +++ b/cloud/docs/orca-relay-operations.md @@ -466,11 +466,16 @@ After a deployment traffic shift, preserve the old revision/tag until metrics an ## Regional rehoming -Rehoming moves a host to a general cell in the region its desktop last reported, in either -direction. Both roles need the drain protocol: a cell without it can be neither a source nor a -target, and it is not part of the fleet whose telemetry gates the worker. Until the asia-east2 -cells run `regionalRehomeProtocol` 1 they are none of the three, so no host is moved into or out -of Asia and an Asia cell in distress does not pause the worker. +Idle regional correction requires both source and target cells to advertise +`regionalRehomeProtocol >= 3`. PR #20105 introduced this capability version with +the idle handoff implementation. With that runtime, both rehome trust environment +settings must be configured to advertise 3; otherwise the cell advertises 0. +An older trusted runtime can advertise 1: configuring trust alone does not upgrade +its implementation. The separate `connectionCapacityProtocol: 2` health field does +not establish regional-correction readiness. Verify the live runtime version and +image, not only instance-template configuration, before rollout or enablement. +Incompatible cells are excluded from correction selection; enabling the cohort +cannot override this check. Director and cell deployments are separate operations. `host-cooldown-ms` is the minimum gap between two rehomes of one host. It bounds the damage from a desktop whose region probe flips: without it the host would be dragged back across the ocean on @@ -491,3 +496,64 @@ Run and record each scenario in staging before launch: - return a dormant host, overload a cell, kill a cell, evacuate active work, and exercise pre-registration rollback. The served black-box relay suite validates the protocol/state transitions used by these procedures. The physical-device and real-GFE canaries remain separate launch gates; unit/black-box success cannot replace them. + +## Optional measured region correction (deployment gated) + +New optimization claims require both the durable regional-rehome control and +`ORCA_RELAY_REGION_CORRECTION_COHORT_PERCENT` (integer 0–100, default **0**). +Turning either gate off stops new optional moves; ordinary migration cleanup and +recovery continue. Legacy preferred-region hints do not certify a correction. Both +cells must advertise regional protocol3 and the authenticated desktop control must +advertise idle-regional-rehome-v1. The source must have no actual client sockets or +pending admission/control work; a live control socket alone does not prevent a move. + +The monitor/deploy identity can read **GET `/v1/admin/regional-rehome-preview`**. +It returns full-population eligibility/exclusion counts, open-migration capacity, +process-safety gating and aggregate migration outcomes; it never claims a +host or changes the failure budget. This is advisory, with separately read state: +concurrent assignments, capacity changes, rate pauses and control changes can make +the next claim differ. Inspect the durable control separately before enabling. +Do not treat an unavailable/failed preview as zero eligible hosts. + +`orca_relay_region_correction_outcomes` reports attempts by source/target, +registration/completion/abort state, oldest open age and target +reservation units every five minutes. `orca_relay_region_comparison` samples a +stable 10% of accepted reports (including unchanged hosts), keyed by host digest, +assignment epoch and decision generation. Existing control RTT and client-accept +logs include assignment epoch, control generation and drain mode; join those for +matched before/after and unchanged-cohort comparisons. Client accept latency is +connection setup, not application command round trip. No application-latency +improvement has been demonstrated by probe differences alone. + +Quiet live connections count as work and defer optional correction indefinitely. +A returning client may race with the short admission gate and retry normally. No +optimization timer may close an established client. Investigate failed registration, +ambiguous authority, stuck reservations and reconnect/failure rates against agreed +limits. A database outage can keep the source fenced until locked reconciliation +establishes its authority; timeout alone is not permission to reopen admissions. + +All directors must run the reviewed idle worker before enabling. Record the tested +immutable source and rollback revisions, then verify the ordinary migration recovery +path before rollout. There is no retained-source table or renewal protocol. Deploying +supporting cells/desktops and enabling a cohort require separate rollout authorization +and explicit numerical stop criteria; this change enables neither. + +### Setting the correction cohort during a reviewed director rollout + +The existing **Deploy Relay Production Director** workflow accepts +`region-correction-cohort-percent`: `preserve` (default) or an integer0–100. +It carries the cohort onto both candidate and compatible rollback revisions and +verifies the environment before promotion. If the predecessor has no setting, +`preserve` stamps zero. An explicit change requires the exact disabled durable +rehome generation; configuring a nonzero cohort does not itself enable the sweep. +The usual image, identity, health and traffic checks remain in force. No workflow +was dispatched as part of implementation. + +Terraform reads the cohort from the same traffic-serving revision used to preserve +regional placement. A later apply therefore preserves a workflow-set cohort, +including explicit zero; only an absent service/setting bootstraps to0. Malformed +or ambiguous live settings fail the plan instead of silently resetting the cohort. +The audited director workflow owns subsequent changes. +Before the first nonzero cohort, verify compatible protocol2 cells, updated +cleanup workers, preview eligibility, both serving/rollback images and the +explicitly approved observation/stop criteria. diff --git a/cloud/docs/relay-incident-monitor.md b/cloud/docs/relay-incident-monitor.md index 696efb85296..a97e92949e8 100644 --- a/cloud/docs/relay-incident-monitor.md +++ b/cloud/docs/relay-incident-monitor.md @@ -112,7 +112,8 @@ durably marked consumed before mutation and cannot authorize another run. | Director instances | outside 5–6 | | Director CPU or memory | over 80% | | Director concurrency | over 64 | -| Unexpected director 5xx or auth 5xx in five minutes | over 0 | +| Unexpected director 5xx in five minutes (excludes 503) | over 3 | +| Auth 5xx in five minutes | over 0 | | Connections per cell process | over 500 | | Queued bytes per cell process | over 48 MiB | | Blocked or expired/unregistered migration | over 0 | @@ -276,3 +277,7 @@ without its segment is a compile error in relay-contract, not a silent gap. load the director's three-connection database pool. - Added private atomic state, idempotent JSONL checkpoints, and secret-safe Markdown evidence. - Added the manual production workflow. It has not been dispatched. + +### Director error allowance (2026-09-12) + +The serving-cell rollout observed three unexpected director 500 responses among approximately 33,600 responses in an hour, all two-second PostgreSQL connection timeouts. CPU remained near 30–37% and the zero-error bar repeatedly prevented any cell mutation. The five-minute allowance is now three non-503 director 5xx; four freezes. Auth errors, data freshness, active probes, SQL/pool pressure and other limits are unchanged. This is a bounded operational allowance, not a calibrated SLO or proof that intermittent failures are resolved; persistent low-frequency errors below this limit still require diagnosis. diff --git a/cloud/infra/terraform/relay.tf b/cloud/infra/terraform/relay.tf index 7a5124a00b1..5df7372ff07 100644 --- a/cloud/infra/terraform/relay.tf +++ b/cloud/infra/terraform/relay.tf @@ -169,6 +169,11 @@ resource "google_cloud_run_v2_service" "relay" { } } + env { + name = "ORCA_RELAY_REGION_CORRECTION_COHORT_PERCENT" + value = data.external.relay_serving_regional_placement_version.result.cohort_percent + } + ports { container_port = 8080 } diff --git a/cloud/packages/push-contract/src/send-messages.ts b/cloud/packages/push-contract/src/send-messages.ts index 57d1c2e2745..a8959c18b05 100644 --- a/cloud/packages/push-contract/src/send-messages.ts +++ b/cloud/packages/push-contract/src/send-messages.ts @@ -26,7 +26,8 @@ export const PushNotificationSchema = z agentState: PushAgentStateSchema.nullable(), title: z.string().min(1).max(PUSH_LIMITS.titleMaxChars), body: z.string().max(PUSH_LIMITS.bodyMaxChars), - worktreeId: z.string().min(1).max(2048).optional() + worktreeId: z.string().min(1).max(2048).optional(), + paneKey: z.string().min(1).max(2048).optional() }) .strict() .refine( diff --git a/cloud/packages/relay-contract/src/control-messages.ts b/cloud/packages/relay-contract/src/control-messages.ts index 0daf21e7c28..ebe9586407e 100644 --- a/cloud/packages/relay-contract/src/control-messages.ts +++ b/cloud/packages/relay-contract/src/control-messages.ts @@ -50,6 +50,7 @@ export const RELAY_HOST_CAPABILITIES_HEADER = 'x-orca-host-capabilities' // The host accepts kind/relayDeviceId on a pendingConns entry. A host that does // not advertise this parses those entries strictly and would drop the whole ack. export const RELAY_HOST_CAPABILITY_PENDING_CONN_DETAILS = 'pending-conn-details' +export const RELAY_HOST_CAPABILITY_IDLE_REGIONAL_REHOME = 'idle-regional-rehome-v1' export function parseRelayHostCapabilities( header: string | string[] | undefined @@ -121,11 +122,22 @@ export const DeviceRevokeSchema = z .object({ reqId: OpaqueIdSchema, relayDeviceId: OpaqueIdSchema }) .strict() -export const AuthRefreshSchema = z.object({ relayJwt: z.string().min(1).max(8 * 1024) }).strict() +export const AuthRefreshSchema = z + .object({ + relayJwt: z + .string() + .min(1) + .max(8 * 1024) + }) + .strict() export const DrainSchema = z .object({ - graceMs: z.number().int().nonnegative().max(60 * 60 * 1000), + graceMs: z + .number() + .int() + .nonnegative() + .max(60 * 60 * 1000), recovery: z.literal('resolve-director') }) .strict() diff --git a/cloud/packages/relay-contract/src/director-messages.ts b/cloud/packages/relay-contract/src/director-messages.ts index e697135b68e..0f57081014a 100644 --- a/cloud/packages/relay-contract/src/director-messages.ts +++ b/cloud/packages/relay-contract/src/director-messages.ts @@ -7,8 +7,15 @@ import { RelayHostIdSchema } from './wire-scalars.js' import { RelayRegionSchema } from './relay-regions.js' +import { + RegionCorrectionRequestSchema, + RegionCorrectionResponseSchema +} from './region-correction.js' -const SignedAssignmentLeaseSchema = z.string().min(1).max(8 * 1024) +const SignedAssignmentLeaseSchema = z + .string() + .min(1) + .max(8 * 1024) export const AssignmentRequestSchema = z .object({ @@ -17,7 +24,8 @@ export const AssignmentRequestSchema = z // Client-declared reconnection; the director verifies it against the // durable assignment before granting fast-lane admission. reconnect: z.boolean().optional(), - preferredRegion: RelayRegionSchema.optional() + preferredRegion: RelayRegionSchema.optional(), + regionCorrection: RegionCorrectionRequestSchema.optional() }) .strict() @@ -26,7 +34,8 @@ export const AssignmentResponseSchema = z v: z.literal(1), cellUrl: CanonicalHttpsOriginSchema, assignmentEpoch: GenerationSchema, - lease: SignedAssignmentLeaseSchema + lease: SignedAssignmentLeaseSchema, + regionCorrection: RegionCorrectionResponseSchema.optional() }) .strict() diff --git a/cloud/packages/relay-contract/src/idle-regional-rehome.ts b/cloud/packages/relay-contract/src/idle-regional-rehome.ts new file mode 100644 index 00000000000..9f9eff36593 --- /dev/null +++ b/cloud/packages/relay-contract/src/idle-regional-rehome.ts @@ -0,0 +1,26 @@ +import { z } from 'zod' +import { GenerationSchema, RelayHostIdSchema } from './wire-scalars.js' + +export const IdleRegionalRehomeRequestSchema = z + .object({ + v: z.literal(1), + attemptId: z.string().uuid(), + userId: z.string().min(1).max(256), + relayHostId: RelayHostIdSchema, + sourceCellId: z.string().min(1).max(128), + sourceCellIncarnation: z.string().uuid(), + sourceAssignmentEpoch: GenerationSchema.refine((value) => value > 0), + sourceGeneration: GenerationSchema.refine((value) => value > 0), + targetCellId: z.string().min(1).max(128) + }) + .strict() + +export const IdleRegionalRehomeResponseSchema = z + .object({ + v: z.literal(1), + outcome: z.enum(['busy', 'committed', 'deferred', 'stale']) + }) + .strict() + +export type IdleRegionalRehomeRequest = z.infer +export type IdleRegionalRehomeOutcome = z.infer['outcome'] diff --git a/cloud/packages/relay-contract/src/index.ts b/cloud/packages/relay-contract/src/index.ts index aab3b53b5f3..3b52ec503a1 100644 --- a/cloud/packages/relay-contract/src/index.ts +++ b/cloud/packages/relay-contract/src/index.ts @@ -13,3 +13,5 @@ export * from './resume-confirmation-contract.js' export * from './relay-regions.js' export * from './splice-state-machine.js' export * from './wire-scalars.js' +export * from './region-correction.js' +export * from './idle-regional-rehome.js' diff --git a/cloud/packages/relay-contract/src/region-correction.test.ts b/cloud/packages/relay-contract/src/region-correction.test.ts new file mode 100644 index 00000000000..8c0122341d4 --- /dev/null +++ b/cloud/packages/relay-contract/src/region-correction.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from 'vitest' +import { AssignmentRequestSchema, AssignmentResponseSchema } from './director-messages.js' +import { DrainSchema } from './control-messages.js' +import { RegionCorrectionRequestSchema } from './region-correction.js' + +const report = { + v: 1, + action: 'report', + generation: 3, + assignmentEpoch: 7, + policyVersion: 1, + outcome: 'conclusive', + measurements: { 'us-central1': 40, 'asia-east2': 180 } +} +const retention = { + mode: 'finish-existing', + attemptId: '11111111-1111-4111-8111-111111111111', + sourceGeneration: 3, + sourceAssignmentEpoch: 7 +} + +describe('region correction wire boundaries', () => { + it('keeps legacy assignment shapes readable without negotiated fields', () => { + expect( + AssignmentRequestSchema.parse({ v: 1, relayHostId: 'abcdefghijklmnop' }) + ).not.toHaveProperty('regionCorrection') + expect( + AssignmentResponseSchema.parse({ + v: 1, + cellUrl: 'https://cell.example', + assignmentEpoch: 1, + lease: 'synthetic-lease' + }) + ).not.toHaveProperty('regionCorrection') + }) + + it('accepts complete comparison evidence and explicit inconclusive reports', () => { + expect(RegionCorrectionRequestSchema.safeParse(report).success).toBe(true) + const { measurements: _measurements, ...basis } = report + expect( + RegionCorrectionRequestSchema.safeParse({ + ...basis, + outcome: 'inconclusive', + reason: 'probe-unavailable' + }).success + ).toBe(true) + }) + + it.each([ + { measurements: { 'us-central1': 40 } }, + { measurements: { 'us-central1': -1, 'asia-east2': 10 } }, + { measurements: { 'us-central1': Infinity, 'asia-east2': 10 } }, + { measurements: { 'us-central1': 120_001, 'asia-east2': 10 } }, + { generation: Number.MAX_SAFE_INTEGER + 1 }, + { assignmentEpoch: 1.2 }, + { policyVersion: 2 }, + { outcome: 'inconclusive', reason: 'timeout' } + ])('rejects ambiguous or unbounded evidence: %j', (override) => { + expect(RegionCorrectionRequestSchema.safeParse({ ...report, ...override }).success).toBe(false) + }) + + it('rejects reporting and issuing a window in the same request', () => { + expect( + RegionCorrectionRequestSchema.safeParse({ + ...report, + action: 'issue-window' + }).success + ).toBe(false) + }) + + it('uses ordinary drain and rejects the superseded retention extension', () => { + const ordinary = { graceMs: 0, recovery: 'resolve-director' } + expect(DrainSchema.parse(ordinary)).toEqual(ordinary) + expect(DrainSchema.safeParse({ ...ordinary, retention }).success).toBe(false) + }) +}) diff --git a/cloud/packages/relay-contract/src/region-correction.ts b/cloud/packages/relay-contract/src/region-correction.ts new file mode 100644 index 00000000000..5fffca0ad8c --- /dev/null +++ b/cloud/packages/relay-contract/src/region-correction.ts @@ -0,0 +1,60 @@ +import { z } from 'zod' +import { EpochMsSchema, GenerationSchema } from './wire-scalars.js' +import { RelayRegionSchema } from './relay-regions.js' + +const RttSchema = z.number().finite().nonnegative().max(120_000) +export const RegionMeasurementsSchema = z + .object({ + 'us-central1': RttSchema, + 'asia-east2': RttSchema + }) + .strict() + +export const RegionMeasurementWindowSchema = z + .object({ + generation: GenerationSchema, + expiresAt: EpochMsSchema, + assignmentEpoch: GenerationSchema, + incumbentRegion: RelayRegionSchema, + policyVersion: z.literal(1) + }) + .strict() + +const ReportBasis = { + v: z.literal(1), + action: z.literal('report'), + generation: GenerationSchema, + assignmentEpoch: GenerationSchema, + policyVersion: z.literal(1) +} + +export const RegionCorrectionRequestSchema = z.union([ + z.object({ v: z.literal(1), action: z.literal('issue-window') }).strict(), + z + .object({ + ...ReportBasis, + outcome: z.literal('conclusive'), + measurements: RegionMeasurementsSchema + }) + .strict(), + z + .object({ + ...ReportBasis, + outcome: z.literal('inconclusive'), + reason: z.string().min(1).max(64) + }) + .strict() +]) + +export const RegionCorrectionResponseSchema = z + .object({ + v: z.literal(1), + window: RegionMeasurementWindowSchema.optional(), + reportStatus: z.enum(['accepted', 'duplicate', 'stale', 'expired', 'basis-changed']).optional() + }) + .strict() + +export type RegionMeasurements = z.infer +export type RegionMeasurementWindow = z.infer +export type RegionCorrectionRequest = z.infer +export type RegionCorrectionResponse = z.infer diff --git a/config/electron-builder.config.cjs b/config/electron-builder.config.cjs index 7e0009b3a24..6b36938a3d1 100644 --- a/config/electron-builder.config.cjs +++ b/config/electron-builder.config.cjs @@ -279,16 +279,6 @@ module.exports = { } }, afterPack: async (context) => { - // Why: a Linux runner-image glibc bump silently shipped a node-pty pty.node - // requiring GLIBC_2.34, crashing the app on startup on Ubuntu 20.04 (#9902). - // Fail packaging if any bundled native binary exceeds the supported floor. - if (context.electronPlatformName === 'linux') { - // Why the arch is passed: symbol-version checks pass happily on a wrong-architecture binary, - // so a cross-built slice could ship the host's pty.node and only fail at runtime. - verifyLinuxGlibcFloor(context.appOutDir, { - targetArch: { 1: 'x64', 3: 'arm64' }[context.arch] - }) - } const resourcesDir = context.electronPlatformName === 'darwin' ? join( @@ -326,6 +316,19 @@ module.exports = { } stampPackagedCliVersion(resourcesDir, context.packager.appInfo.version) prunePackagedRuntimeNodeModules(resourcesDir, context.electronPlatformName, context.arch) + // Why: a Linux runner-image glibc bump silently shipped a node-pty pty.node + // requiring GLIBC_2.34, crashing the app on startup on Ubuntu 20.04 (#9902). + // Fail packaging if any bundled native binary exceeds the supported floor. + // Why after the prune: cross-builds intentionally install every optional + // native variant, so an arm64 slice still carries the x64 @parcel/watcher + // until prunePackagedRuntimeNodeModules drops it. + if (context.electronPlatformName === 'linux') { + // Why the arch is passed: symbol-version checks pass happily on a wrong-architecture binary, + // so a cross-built slice could ship the host's pty.node and only fail at runtime. + verifyLinuxGlibcFloor(context.appOutDir, { + targetArch: { 1: 'x64', 3: 'arm64' }[context.arch] + }) + } verifyPackagedMainRuntimeDeps(resourcesDir) // Why: boot the packaged daemon-entry under plain Node, but only for the // slice matching the packaging host's arch — daemon-entry.js is JS, yet it diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 54a482f901a..5b21fa9b0ad 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -10,6 +10,158 @@ } }, "gates": [ + { + "id": "runtime.connection-owned-host-status", + "title": "Host status recovers with its owning connection", + "maturity": "experimental", + "protection": "partial", + "owner": "runtime", + "layer": "service-integration-and-e2e", + "surfaces": [ + "sidebar host status", + "desktop runtime connection", + "browser primary connection" + ], + "platforms": ["macos", "linux", "windows"], + "providers": ["remote-runtime"], + "coveredPlatforms": ["macos"], + "coveredProviders": ["remote-runtime"], + "coverageNotes": "Real authenticated sockets plus isolated desktop and headless hosts with desktop and browser viewers; deterministic lifecycle tests cover stale results and reader deadlines.", + "motivatingLinks": ["https://github.com/stablyai/orca/pull/19163"], + "invariant": "Failed bootstrap and authenticated reconnect converge without UI triggers; one connection owner publishes verified status, with no independent healthy status polling.", + "oracle": "Observe automatic recovery, retained runtime identity on failure, ordered publications, exact request counts, isolated viewer outages, and retirement on disconnect.", + "commands": [ + "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/shared/runtime-host-status-owner.test.ts src/main/ipc/runtime-environment-status-recovery.test.ts src/main/ipc/runtime-environment-status-connection.test.ts src/renderer/src/store/slices/runtime-status-snapshot.test.ts src/renderer/src/web/web-runtime-status-owner.test.ts", + "ORCA_BACKGROUND_LAUNCH=1 ORCA_E2E_WEB_CLIENT=1 pnpm exec playwright test tests/e2e/runtime-host-status-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" + ], + "testFiles": [ + "src/shared/runtime-host-status-owner.test.ts", + "src/main/ipc/runtime-environment-status-recovery.test.ts", + "src/main/ipc/runtime-environment-status-connection.test.ts", + "src/renderer/src/store/slices/runtime-status-snapshot.test.ts", + "src/renderer/src/web/web-runtime-status-owner.test.ts", + "tests/e2e/runtime-host-status-recovery.spec.ts" + ], + "assertionRefs": [ + { + "file": "src/main/ipc/runtime-environment-status-recovery.test.ts", + "assertions": [ + "recovers a saved host after its first status check fails, without another UI request" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-09-10", + "runner": "local", + "platform": "macos", + "command": "ORCA_BACKGROUND_LAUNCH=1 ORCA_E2E_WEB_CLIENT=1 pnpm exec playwright test tests/e2e/runtime-host-status-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", + "result": "passed", + "summary": "Desktop-host and headless-host journeys passed with desktop and browser viewers.", + "durationSeconds": 31.3 + } + ], + "runtimeBudget": { + "p95Seconds": 180, + "scope": "Target excluding builds; measured p95 not established." + }, + "flakeHistory": { + "status": "soaking", + "evidence": "Local candidate runs passed; no sustained CI history yet." + }, + "redGreenEvidence": { + "status": "partial", + "evidence": "First-status-failure oracle failed on main 58ff95becb40 (one request instead of two) and passes on the candidate. E2E verifies candidate recovery, not a baseline comparison." + }, + "performanceBudget": { + "required": false, + "evidence": "Deterministic tests assert one shared request and no healthy owner polling." + }, + "promotionCriteria": ["Collect repeated CI runs without unexplained flakes."], + "knownGaps": [ + "No live Linux, Windows, SSH, or mixed-version pair validation.", + "TCP interruption exercises reconnect, not a full real host process restart.", + "The outage begins on the first saved-host check, not by relaunching a preseeded desktop profile." + ], + "demotionRule": "Keep experimental until repeated runs establish reliability; preserve request-count and lifecycle assertions." + }, + { + "id": "mobile-push.headless-startup-and-policy", + "title": "Headless push lifecycle and mobile delivery policy", + "maturity": "experimental", + "protection": "partial", + "owner": "runtime", + "layer": "service-integration", + "surfaces": ["headless startup", "push registration", "native push delivery policy"], + "platforms": ["macos", "linux", "windows"], + "providers": ["local", "remote-runtime"], + "coveredPlatforms": ["macos"], + "coveredProviders": ["local", "remote-runtime"], + "coverageNotes": "Actual startOrcad entry with mocked daemon/RPC startup boundaries; real controller, push service, and persisted device registry. Gateway send is stubbed.", + "motivatingLinks": ["https://github.com/stablyai/orca/pull/19204"], + "invariant": "Headless startup installs and disposes push delivery; desktop notification categories remain authoritative, the three-minute away policy is preserved, and host activity cannot extend the seven-day mobile lease.", + "oracle": "Require registration after RPC identity initialization and shutdown cleanup; idle 179/180/0 yields false/true/false in retained event metadata and exactly one gateway push. Legacy socket subscriptions preserve notification filtering, while opted-in push clients can request dismissal reconciliation. Desktop categories remain authoritative. Persisted lease expires exactly at seven days and only explicit registration renews it.", + "commands": [ + "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/mobile-notification-dismissal-store.test.ts src/renderer/src/hooks/useAutoAckViewedAgent.away.test.ts", + "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/orcad/orcad-push-startup.test.ts src/main/runtime/push/push-policy-pipeline.integration.test.ts" + ], + "testFiles": [ + "src/main/orcad/orcad-push-startup.test.ts", + "src/main/runtime/push/push-policy-pipeline.integration.test.ts", + "src/main/runtime/mobile-notification-dismissal-store.test.ts", + "src/renderer/src/hooks/useAutoAckViewedAgent.away.test.ts" + ], + "assertionRefs": [ + { + "file": "src/main/orcad/orcad-push-startup.test.ts", + "assertions": [ + "starts push after RPC identity is available and stops dispatch on shutdown" + ] + }, + { + "file": "src/main/runtime/push/push-policy-pipeline.integration.test.ts", + "assertions": [ + "carries the native idle boundary through replay and push dispatch", + "expires persisted registration at seven days despite host activity and renews explicitly" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-09-07", + "runner": "local", + "platform": "macos", + "command": "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/orcad/orcad-push-startup.test.ts src/main/runtime/push/push-policy-pipeline.integration.test.ts", + "result": "passed", + "summary": "Four tests passed across two files.", + "durationSeconds": 0.407 + } + ], + "runtimeBudget": { + "p95Seconds": 10, + "scope": "Target budget; measured p95 not established" + }, + "flakeHistory": { + "status": "soaking", + "evidence": "Focused local run passed; repeated CI history not established." + }, + "redGreenEvidence": { + "status": "partial", + "evidence": "Headless startup oracle reproduced missing registrar before the startup fix and passed afterward. Policy tests cover candidate behavior." + }, + "performanceBudget": { + "required": false, + "evidence": "Lifecycle and policy coverage; asserts exact gateway send counts and zero remaining dispatch listeners after shutdown." + }, + "promotionCriteria": ["Collect repeated CI runs without unexplained failures."], + "knownGaps": [ + "Does not prove APNs silent background wakeup or actual operating-system idle transitions.", + "Rendererless agent/bell event generation remains outside the documented feature contract.", + "No live Windows or Linux policy evidence.", + "Mobile native presentation and dismissal integration belongs to the subsequent mobile PR." + ], + "demotionRule": "Keep experimental if lifecycle or policy assertions fail; do not weaken them to bypass platform delivery gaps." + }, { "id": "agent-session.completed-turn-duration", "title": "Completed turn duration survives client recovery and history pagination", @@ -2775,6 +2927,78 @@ ], "demotionRule": "Keep experimental or demote if assignment calls overlap, duplicate drain events bypass backoff, Retry-After is ignored, close resurrects work, or mixed-version request rate exceeds the reviewed director budget." }, + { + "id": "desktop-relay.region-correction-idle-cutover", + "title": "Regional correction moves only an idle relay source", + "maturity": "experimental", + "protection": "partial", + "owner": "desktop-runtime", + "layer": "cell-desktop-real-websocket", + "surfaces": ["regional correction", "idle source cutover", "desktop relay reconnect"], + "platforms": ["macos", "linux", "windows"], + "providers": ["cloud-relay"], + "coveredPlatforms": ["macos"], + "coveredProviders": ["cloud-relay"], + "coverageNotes": "Real local WebSocket/control/proof/splice traffic and production SQLite store run with synthetic clock and synthetic token verification. Separate PostgreSQL16 suites validate SQL concurrency. This does not measure production network latency, physical phones, UI, or the production token issuer.", + "motivatingLinks": [ + "docs/relay-region-correction/RELAY-REGION-CORRECTION-IDLE-CUTOVER-PLAN.md" + ], + "invariant": "Regional optimization never closes an established relay client. The source gates admissions only after actual work is idle, commits the exact assignment atomically, and releases its empty control. A failed target uses ordinary migration recovery; previously sent mutations are not replayed.", + "oracle": "Two real TCP WebSocket cells, the actual desktop origin pool, SQLite and an independent execution child verify busy phone/iPad deferral, idle movement, racing arrival rejection, definite-abort admission recovery and observed target-registration failure with ordinary rollback.", + "commands": [ + "ORCA_BACKGROUND_LAUNCH=1 pnpm test tests/e2e/relay-region-correction.unit.test.ts" + ], + "testFiles": ["tests/e2e/relay-region-correction.unit.test.ts"], + "assertionRefs": [ + { + "file": "tests/e2e/relay-region-correction.unit.test.ts", + "assertions": [ + "releases the empty source and recovers normally when the target never registers", + "rejects an arrival during cutover and restores admissions after a definite failed commit", + "defers for either connected device, then moves after both disconnect without replaying work" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-09-11", + "runner": "local", + "platform": "macos", + "command": "ORCA_BACKGROUND_LAUNCH=1 pnpm test tests/e2e/relay-region-correction.unit.test.ts", + "result": "passed", + "durationSeconds": 6.44, + "summary": "Three real TCP WebSocket cases passed after removing store retention. Log: .tmp/idle-cutover-review/transport-without-retention.log. Does not validate packaged or physical clients." + } + ], + "runtimeBudget": { + "p95Seconds": 180, + "scope": "three local real-WebSocket scenarios with synthetic elapsed time for ordinary recovery" + }, + "flakeHistory": { + "status": "unknown", + "evidence": "Local implementation validation; no CI soak history yet." + }, + "redGreenEvidence": { + "status": "partial", + "evidence": "Registry admission accounting negative control and five conflicting operation-identity regressions fail before their fixes and pass afterward. Locked database reconciliation has separate red/green evidence. Full cross-layer counterfactual remains unverified." + }, + "performanceBudget": { + "required": true, + "evidence": "No retained source lease or new mobile timer. Candidate selection is read-only; busy sources immediately defer. Idle cutover reuses normal desktop reconnect and existing migration recovery." + }, + "promotionCriteria": [ + "Collect 100 consecutive CI passes or 14 days of soak.", + "Complete mixed-version and packaged-client validation.", + "Validate bounded rollout latency and reliability against reviewed numerical limits." + ], + "knownGaps": [ + "Production authentication verifier is mocked.", + "Synthetic elapsed time is not a wall-clock soak.", + "Physical phone lifecycle, packaged mixed versions, SSH execution and production network behavior require separate validation." + ], + "demotionRule": "Keep experimental or demote if optimization closes an established client, a gate reopens on ambiguous authority, a mutation is replayed, cleanup is lost, or eligible idle hosts starve." + }, + { "id": "git-worktree.refresh-event-semantics", "title": "Index-only Git metadata cannot trigger structural worktree refresh fanout", diff --git a/config/scripts/capture-agent-pty-transcript.mjs b/config/scripts/capture-agent-pty-transcript.mjs new file mode 100644 index 00000000000..a60d0adbdd5 --- /dev/null +++ b/config/scripts/capture-agent-pty-transcript.mjs @@ -0,0 +1,283 @@ +/** + * Records a live agent CLI session through a real PTY into a test fixture, bytes intact. + * + * Why a PTY and not `agy | tee`: a pipe is not a terminal, so the CLI renders its + * non-interactive path — no alternate screen, no caret, no dialogs. The detector under + * test only ever sees the PTY shape, so that is the only shape worth capturing. + * + * Nothing here strips escapes, folds CRs, or rewraps lines: the transcript is written + * exactly as the terminal received it. See docs/reference/agent-pty-transcript-capture.md. + */ +import { createWriteStream, mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import { dirname, join, resolve } from 'node:path' +import { pathToFileURL } from 'node:url' +import { + formatFindings, + redactTranscript, + scanTranscriptForSecrets +} from './pty-transcript-secret-scan.mjs' + +const REPO_ROOT = resolve(import.meta.dirname, '..', '..') +const FIXTURE_DIR = join(REPO_ROOT, 'src', 'main', 'runtime', '__fixtures__') +const STOP_KEY = 0x1d // Ctrl-], consumed by the recorder and never forwarded to the agent. +const NAME_RE = /^[a-z0-9][a-z0-9-]*$/ + +const USAGE = `Capture a raw agent PTY transcript into src/main/runtime/__fixtures__/. + + node config/scripts/capture-agent-pty-transcript.mjs --name [options] -- [args...] + node config/scripts/capture-agent-pty-transcript.mjs --scan [--redact] + +Options + --name Output fixture name, e.g. antigravity-ready-personal-non-gemini + --out Write somewhere other than the fixture directory + --cols --rows Pin the PTY size (default: this terminal's size, else 120x40) + --duration Stop unattended after N seconds + --send ":" Type into the PTY at (repeatable; \\r \\n \\t \\e escapes) + --note "" Recorded in the .meta.json sidecar + --scan Scan existing transcripts for identifiers/credentials and exit + --redact With --scan: rewrite each finding as a same-length placeholder + +Press Ctrl-] to end a capture. That key is consumed here, so the agent keeps whatever +dialog it is showing — which is the only way to capture a dialog that owns the screen.` + +function parseArgs(argv) { + const options = { cols: null, rows: null, duration: null, scan: [], sends: [], redact: false } + const command = [] + let cursor = 0 + let afterSeparator = false + while (cursor < argv.length) { + const arg = argv[cursor] + if (afterSeparator) { + command.push(arg) + cursor += 1 + continue + } + if (arg === '--') { + afterSeparator = true + } else if (arg === '--redact') { + options.redact = true + } else if (arg === '--help' || arg === '-h') { + options.help = true + } else if (arg === '--scan') { + while (cursor + 1 < argv.length && !argv[cursor + 1].startsWith('--')) { + cursor += 1 + options.scan.push(argv[cursor]) + } + } else if (arg === '--send') { + cursor += 1 + options.sends.push(parseSend(argv[cursor])) + } else if (arg.startsWith('--')) { + const key = arg.slice(2) + cursor += 1 + options[key] = argv[cursor] + } + cursor += 1 + } + for (const key of ['cols', 'rows', 'duration']) { + options[key] = options[key] == null ? null : Number(options[key]) + } + return { options, command } +} + +// String.fromCharCode, not a literal: the formatter rewrites an escape sequence into a raw +// control byte in source, which is unreadable and survives badly in diffs. +const ESC = String.fromCharCode(27) +const SEND_ESCAPES = { r: '\r', n: '\n', t: '\t', e: ESC, '\\': '\\' } + +/** `":"` — a keystroke to deliver at a fixed offset, for an unattended dialog capture. */ +function parseSend(value) { + const separator = String(value ?? '').indexOf(':') + if (separator === -1) { + throw new Error(`--send expects ":", got ${String(value)}`) + } + const atMs = Number(value.slice(0, separator)) + if (!Number.isFinite(atMs)) { + throw new Error( + `--send delay must be a number of milliseconds, got ${value.slice(0, separator)}` + ) + } + const text = value + .slice(separator + 1) + .replace(/\\(.)/g, (whole, code) => SEND_ESCAPES[code] ?? whole) + return { atMs, text } +} + +function runScan(files, redact) { + let failed = false + for (const file of files) { + const path = resolve(file) + const text = readFileSync(path, 'utf8') + if (redact) { + const { text: redacted, redacted: count } = redactTranscript(text) + writeFileSync(path, redacted) + console.log(`${file}: redacted ${count} span(s) in place, same length each.`) + continue + } + const findings = scanTranscriptForSecrets(text) + console.log(formatFindings(file, findings)) + failed ||= findings.length > 0 + } + return failed ? 1 : 0 +} + +function resolveSpawn(command) { + // node-pty cannot run a .cmd/.bat shim directly on Windows; those need cmd.exe. + if (process.platform === 'win32' && /\.(cmd|bat)$/i.test(command[0])) { + return { file: 'cmd.exe', args: ['/c', `"${command[0]}"`, ...command.slice(1)] } + } + return { file: command[0], args: command.slice(1) } +} + +async function runCapture(options, command) { + const name = options.name + if (typeof name === 'string' && !NAME_RE.test(name)) { + console.error(`--name must be lowercase kebab-case; got ${name}`) + return 2 + } + const outPath = options.out ? resolve(options.out) : join(FIXTURE_DIR, `${name}.txt`) + mkdirSync(dirname(outPath), { recursive: true }) + + const pty = await import('node-pty').catch((error) => { + console.error( + `node-pty failed to load. Build it for plain node first: + node config/scripts/ensure-native-runtime.mjs --runtime=node +${String(error)}` + ) + return null + }) + if (pty === null) { + return 2 + } + + const cols = options.cols ?? process.stdout.columns ?? 120 + const rows = options.rows ?? process.stdout.rows ?? 40 + const { file, args } = resolveSpawn(command) + const term = pty.spawn(file, args, { + name: 'xterm-256color', + cols, + rows, + cwd: process.cwd(), + env: { ...process.env, TERM: 'xterm-256color' }, + encoding: null + }) + + const sink = createWriteStream(outPath) + let recording = true + term.onData((chunk) => { + const bytes = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : chunk + // Why recording stops before the kill: an agent repaints an idle frame on its way out, so + // a transcript that keeps writing through shutdown ends on that frame instead of on the + // state you stopped to capture. A mid-turn or dialog capture cannot survive that. + if (recording) { + sink.write(bytes) + } + process.stdout.write(bytes) + }) + + const wasRaw = process.stdin.isTTY === true && process.stdin.isRaw === true + if (process.stdin.isTTY) { + process.stdin.setRawMode(true) + } + process.stdin.resume() + let stopping = false + const stop = () => { + if (stopping) { + return + } + stopping = true + recording = false + try { + term.kill() + } catch { + // The agent may have exited on its own; the transcript is already on disk. + } + } + process.stdin.on('data', (chunk) => { + if (chunk.includes(STOP_KEY)) { + stop() + return + } + term.write(chunk.toString('binary')) + }) + // Why scripted input: a dialog capture has to be driven, and CI (or an agent) has no TTY to + // type into. The keystrokes ride the same PTY a human's would, so the capture is unchanged. + const sendTimers = options.sends.map((send) => setTimeout(() => term.write(send.text), send.atMs)) + const durationTimer = options.duration === null ? null : setTimeout(stop, options.duration * 1000) + + const exitCode = await new Promise((resolveExit) => { + term.onExit(({ exitCode: code }) => resolveExit(code ?? 0)) + }) + for (const timer of sendTimers) { + clearTimeout(timer) + } + if (durationTimer !== null) { + clearTimeout(durationTimer) + } + if (process.stdin.isTTY) { + process.stdin.setRawMode(wasRaw) + } + process.stdin.pause() + await new Promise((done) => sink.end(done)) + + writeMeta(outPath, { command, cols, rows, note: options.note ?? null, exitCode }) + const findings = scanTranscriptForSecrets(readFileSync(outPath, 'utf8')) + console.log(`\nTranscript: ${outPath}`) + console.log(formatFindings('scrub check', findings)) + if (findings.length > 0) { + console.log( + `Scrub with: + node config/scripts/capture-agent-pty-transcript.mjs --scan ${outPath} --redact` + ) + } + return 0 +} + +function writeMeta(outPath, details) { + const metaPath = outPath.replace(/\.txt$/, '.meta.json') + writeFileSync( + metaPath, + `${JSON.stringify( + { + capturedAt: new Date().toISOString(), + platform: process.platform, + command: details.command, + cols: details.cols, + rows: details.rows, + note: details.note, + exitCode: details.exitCode + }, + null, + 2 + )}\n` + ) +} + +async function main() { + const { options, command } = parseArgs(process.argv.slice(2)) + if (options.help === true) { + console.log(USAGE) + return 0 + } + if (options.scan.length > 0) { + return runScan(options.scan, options.redact) + } + if (command.length === 0 || (options.name === undefined && options.out === undefined)) { + console.error(USAGE) + return 2 + } + return runCapture(options, command) +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + main().then( + (code) => { + process.exitCode = code + }, + (error) => { + console.error(error) + process.exitCode = 1 + } + ) +} + +export { parseArgs, resolveSpawn } diff --git a/config/scripts/electron-builder-runtime-resources.test.mjs b/config/scripts/electron-builder-runtime-resources.test.mjs index 5a93ec12c25..45145572b80 100644 --- a/config/scripts/electron-builder-runtime-resources.test.mjs +++ b/config/scripts/electron-builder-runtime-resources.test.mjs @@ -2,7 +2,7 @@ import { readFileSync, readdirSync } from 'node:fs' import { cp, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises' import { createRequire } from 'node:module' import { tmpdir } from 'node:os' -import { dirname, join, relative, resolve } from 'node:path' +import { delimiter, dirname, join, relative, resolve } from 'node:path' import { describe, expect, it } from 'vitest' const require = createRequire(import.meta.url) @@ -387,6 +387,72 @@ describe('packaged runtime resources', () => { } }) + it.skipIf(process.platform === 'win32')( + 'prunes non-target native packages before the Linux glibc gate', + async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-after-pack-prune-order-')) + const previousPath = process.env.PATH + try { + const appOutDir = join(root, 'linux-unpacked') + const resourcesDir = join(appOutDir, 'resources') + await cp( + join(process.cwd(), 'resources', 'plugins', 'launch'), + join(resourcesDir, 'plugins', 'launch'), + { recursive: true } + ) + + const unpackedMainDir = join(resourcesDir, 'app.asar.unpacked', 'out', 'main') + await mkdir(unpackedMainDir, { recursive: true }) + await writeFile(join(unpackedMainDir, 'daemon-entry.js'), '', 'utf8') + await writeFile( + join(resourcesDir, 'app.asar.unpacked', 'out', 'package.json'), + `${JSON.stringify({ name: 'orca-compiled-output', type: 'commonjs', private: true })}\n`, + 'utf8' + ) + + const unpackedCliDir = join(resourcesDir, 'app.asar.unpacked', 'out', 'cli') + await mkdir(join(unpackedCliDir, 'handlers'), { recursive: true }) + await writeFile(join(unpackedCliDir, 'handlers', 'skills.js'), '', 'utf8') + await writeFile(join(unpackedCliDir, 'index.js'), '', 'utf8') + + const target = + process.arch === 'x64' + ? { electronArch: 3, machine: 0xb7, nonTarget: 'x64' } + : { electronArch: 1, machine: 0x3e, nonTarget: 'arm64' } + const wrongArchPackage = join( + resourcesDir, + 'node_modules', + '@parcel', + `watcher-linux-${target.nonTarget}-glibc` + ) + await mkdir(wrongArchPackage, { recursive: true }) + const wrongArchElf = Buffer.alloc(20) + wrongArchElf.set([0x7f, 0x45, 0x4c, 0x46]) + wrongArchElf[5] = 1 + wrongArchElf.writeUInt16LE(target.machine, 18) + await writeFile(join(wrongArchPackage, 'watcher.node'), wrongArchElf) + + const stubBinDir = join(root, 'bin') + await mkdir(stubBinDir) + await writeFile(join(stubBinDir, 'objdump'), '#!/bin/sh\nexit 0\n', { mode: 0o755 }) + process.env.PATH = `${stubBinDir}${delimiter}${previousPath ?? ''}` + + await expect( + electronBuilderConfig.afterPack({ + appOutDir, + electronPlatformName: 'linux', + arch: target.electronArch, + packager: { appInfo: { version: '9.9.9' } } + }) + ).resolves.toBeUndefined() + await expect(stat(wrongArchPackage)).rejects.toMatchObject({ code: 'ENOENT' }) + } finally { + process.env.PATH = previousPath + await rm(root, { recursive: true, force: true }) + } + } + ) + it.skipIf(process.platform === 'win32')( 'marks packaged Unix CLI launchers executable', async () => { diff --git a/config/scripts/electron-runtime-floor.test.ts b/config/scripts/electron-runtime-floor.test.ts new file mode 100644 index 00000000000..77a1d4741e0 --- /dev/null +++ b/config/scripts/electron-runtime-floor.test.ts @@ -0,0 +1,57 @@ +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' + +/** + * Why a floor and not just a pin: Electron 43.5.0/43.6.0 set and unset `GDK_GL` + * around `gtk_init()` while FontConfig warmed up on a pool thread, and below + * glibc 2.41 that frees `environ` under a concurrent `getenv()` — a launch-time + * use-after-free on every Ubuntu we support (stablyai/orca#20081). 43.7.0 stops + * freeing the published `environ`. A downgrade past it re-ships that crash, and + * nothing else in the tree would notice. + */ +const MINIMUM_ELECTRON_VERSION = '43.7.0' + +function parseVersion(specifier: string): [number, number, number] { + const match = /(\d+)\.(\d+)\.(\d+)/.exec(specifier) + if (!match) { + throw new Error(`unparseable Electron version: ${specifier}`) + } + return [Number(match[1]), Number(match[2]), Number(match[3])] +} + +function meetsRuntimeFloor(specifier: string): boolean { + const version = parseVersion(specifier) + const floor = parseVersion(MINIMUM_ELECTRON_VERSION) + for (const [index, part] of version.entries()) { + if (part !== floor[index]) { + return part > floor[index] + } + } + return true +} + +describe('electron runtime floor', () => { + it.each([ + ['42.9.0', false], + ['43.6.0', false], + ['43.7.0', true], + ['43.7.1', true], + ['43.8.0', true], + ['44.0.0', true] + ])('reads %s as meeting the floor: %s', (specifier, expected) => { + expect(meetsRuntimeFloor(specifier)).toBe(expected) + }) + + it('pins Electron at or above the glibc environ-race fix', () => { + const packageJson = JSON.parse( + readFileSync(join(__dirname, '../../package.json'), 'utf-8') + ) as { devDependencies: Record } + const specifier = packageJson.devDependencies.electron + + expect( + meetsRuntimeFloor(specifier), + `electron ${specifier} is below the ${MINIMUM_ELECTRON_VERSION} runtime floor` + ).toBe(true) + }) +}) diff --git a/config/scripts/generate-rpc-params-catalog.mjs b/config/scripts/generate-rpc-params-catalog.mjs new file mode 100644 index 00000000000..e42ea39beb1 --- /dev/null +++ b/config/scripts/generate-rpc-params-catalog.mjs @@ -0,0 +1,250 @@ +// Why: the host registry is the only place that binds a method name to its params +// schema. Reading it back — instead of hand-listing 600 methods — is what keeps the +// shared catalog and the dispatcher from drifting apart. +import { execFileSync } from 'node:child_process' +import { + existsSync, + globSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync +} from 'node:fs' +import { createRequire } from 'node:module' +import path from 'node:path' +import process from 'node:process' +import * as esbuild from 'esbuild' +import { resolveOxcCliInvocation } from './oxc-cli-invocation.mjs' + +const REPO_ROOT = path.resolve(import.meta.dirname, '..', '..') +const SHARED_DIR = path.join(REPO_ROOT, 'src', 'shared') +const CONTRACT_DIR = path.join(SHARED_DIR, 'rpc-contract') +const RPC_DIR = path.join(REPO_ROOT, 'src', 'main', 'runtime', 'rpc') +const REGISTRY_ENTRY = path.join(RPC_DIR, 'methods', 'index.ts') +const OUTPUT_PATH = path.join(CONTRACT_DIR, 'rpc-params-catalog.generated.ts') + +// Why mkdirSync first: out/ is gitignored and absent on a fresh checkout, so +// mkdtempSync threw ENOENT and took `pnpm lint` down with it. Why not os.tmpdir(): +// the bundle keeps its node_modules deps external and oxfmt reads .oxfmtrc.json by +// walking up, so both scratch files have to sit under the repo to resolve at all. +function scratchDir(prefix) { + const root = path.join(REPO_ROOT, 'out') + mkdirSync(root, { recursive: true }) + return mkdtempSync(path.join(root, prefix)) +} + +const posix = (value) => value.split(path.sep).join('/') +const repoPath = (absolute) => posix(path.relative(REPO_ROOT, absolute)) + +// Every module the catalog may import from: the extracted params modules plus the +// pre-existing src/shared schemas the RPC methods already bind directly. +function indexableModules() { + const modules = new Set( + globSync('*.ts', { cwd: CONTRACT_DIR }).map((name) => path.join(CONTRACT_DIR, name)) + ) + modules.delete(OUTPUT_PATH) + for (const file of globSync('**/*.ts', { cwd: RPC_DIR })) { + if (file.endsWith('.test.ts')) { + continue + } + const source = readFileSync(path.join(RPC_DIR, file), 'utf8') + for (const [, specifier] of source.matchAll(/from\s+'(\.[^']+)'/g)) { + const resolved = `${path.resolve(path.dirname(path.join(RPC_DIR, file)), specifier)}.ts` + if (resolved.startsWith(`${SHARED_DIR}${path.sep}`) && existsSync(resolved)) { + modules.add(resolved) + } + } + } + return [...modules].sort() +} + +// Why: one bundle keeps the registry and the shared modules on the same module +// instances, so schema object identity is what maps a method to its export. +function loadRegistryAndSchemas(modules) { + const buildDir = scratchDir('rpc-params-catalog-') + try { + const entry = path.join(buildDir, 'entry.ts') + const importOf = (file) => JSON.stringify(posix(path.relative(buildDir, file))) + writeFileSync( + entry, + [ + `export { ALL_RPC_METHODS } from ${importOf(REGISTRY_ENTRY)}`, + 'export const SCHEMA_MODULES = {', + ...modules.map( + (file) => ` ${JSON.stringify(repoPath(file))}: require(${importOf(file)}),` + ), + '}' + ].join('\n') + ) + const outfile = path.join(buildDir, 'bundle.cjs') + esbuild.buildSync({ + entryPoints: [entry], + bundle: true, + platform: 'node', + format: 'cjs', + outfile, + logLevel: 'error', + packages: 'external' + }) + const loaded = createRequire(import.meta.url)(outfile) + return { methods: loaded.ALL_RPC_METHODS, schemaModules: loaded.SCHEMA_MODULES } + } finally { + rmSync(buildDir, { recursive: true, force: true }) + } +} + +// Why: schema objects are compared by identity, not by shape — two structurally +// identical schemas are still two different wire contracts. +function buildSchemaIndex(schemaModules) { + const index = new Map() + for (const [modulePath, moduleExports] of Object.entries(schemaModules)) { + for (const [exportName, value] of Object.entries(moduleExports)) { + if (!value || typeof value !== 'object' || typeof value.safeParse !== 'function') { + continue + } + if (index.has(value)) { + continue + } + index.set(value, { modulePath, exportName }) + } + } + return index +} + +function localNameFor(origin, taken) { + if (!taken.has(origin.exportName)) { + return origin.exportName + } + const hint = path + .basename(origin.modulePath, '.ts') + .split('-') + .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) + .join('') + let candidate = `${origin.exportName}Of${hint}` + let suffix = 2 + while (taken.has(candidate)) { + candidate = `${origin.exportName}Of${hint}${suffix++}` + } + return candidate +} + +function render({ methods, schemaModules }) { + const index = buildSchemaIndex(schemaModules) + const entries = [] + const uncataloged = [] + const imports = new Map() + const taken = new Set() + + for (const method of [...methods].sort((left, right) => (left.name < right.name ? -1 : 1))) { + if (method.params === null) { + entries.push(` '${method.name}': null`) + continue + } + const origin = index.get(method.params) + if (!origin) { + uncataloged.push(method.name) + continue + } + const key = `${origin.modulePath}#${origin.exportName}` + let local = imports.get(key) + if (!local) { + local = localNameFor(origin, taken) + taken.add(local) + imports.set(key, local) + } + entries.push(` '${method.name}': ${local}`) + } + + const byModule = new Map() + for (const [key, local] of imports) { + const [modulePath, exportName] = key.split('#') + if (!byModule.has(modulePath)) { + byModule.set(modulePath, []) + } + byModule.get(modulePath).push(local === exportName ? exportName : `${exportName} as ${local}`) + } + const importLines = [...byModule] + .sort(([left], [right]) => (left < right ? -1 : 1)) + .map(([modulePath, names]) => { + let specifier = posix(path.relative(CONTRACT_DIR, path.join(REPO_ROOT, modulePath))).replace( + /\.ts$/, + '' + ) + if (!specifier.startsWith('.')) { + specifier = `./${specifier}` + } + return `import { ${names.sort().join(', ')} } from '${specifier}'` + }) + + return `// GENERATED by config/scripts/generate-rpc-params-catalog.mjs. Do not edit; +// run \`pnpm run generate:rpc-params-catalog\`. +import type { z } from 'zod' +${importLines.join('\n')} + +// Why: the host parses params with these schemas, so a client that matches this map +// matches the dispatcher. Clients must import it for types only — parsing a params +// schema client-side runs the coercing transforms and rewrites the wire bytes. +export const RPC_PARAMS_BY_METHOD = { +${entries.join(',\n')} +} as const + +// Why: these methods bind a schema the shared contract cannot hold because its value +// graph reaches into src/main. Listing them keeps the gap visible instead of absent. +export const RPC_METHODS_WITHOUT_SHARED_PARAMS: readonly string[] = [ +${uncataloged.map((name) => ` '${name}'`).join(',\n')} +] + +export type RpcMethodName = keyof typeof RPC_PARAMS_BY_METHOD + +// Why: z.output is the post-parse shape the handler receives, which is not what a +// client may send — a .default() field reads as required. z.input is not the answer +// either: requiredString is z.unknown().transform(...), so its input admits any value. +// Senders use RpcSendParams from ./rpc-send-params, which is derived from this map. +export type RpcParams = + (typeof RPC_PARAMS_BY_METHOD)[Method] extends z.ZodType + ? z.output<(typeof RPC_PARAMS_BY_METHOD)[Method]> + : void +` +} + +// Why: the drift gate compares bytes, so the generator must emit exactly what the +// formatter would produce or every run would look like drift. +function formatted(source) { + const buildDir = scratchDir('rpc-params-catalog-fmt-') + try { + const file = path.join(buildDir, 'rpc-params-catalog.generated.ts') + writeFileSync(file, source) + const { command, prefixArgs } = resolveOxcCliInvocation('oxfmt', 'oxfmt', REPO_ROOT) + execFileSync(command, [...prefixArgs, '--write', file], { + stdio: 'ignore', + windowsHide: true + }) + return readFileSync(file, 'utf8') + } finally { + rmSync(buildDir, { recursive: true, force: true }) + } +} + +function main() { + const check = process.argv.includes('--check') + const generated = formatted(render(loadRegistryAndSchemas(indexableModules()))) + const current = existsSync(OUTPUT_PATH) ? readFileSync(OUTPUT_PATH, 'utf8') : null + if (generated === current) { + if (!check) { + console.log(`rpc params catalog already up to date: ${repoPath(OUTPUT_PATH)}`) + } + return + } + if (check) { + console.error( + `${repoPath(OUTPUT_PATH)} is out of date. Run \`pnpm run generate:rpc-params-catalog\`.` + ) + process.exitCode = 1 + return + } + writeFileSync(OUTPUT_PATH, generated) + console.log(`wrote ${repoPath(OUTPUT_PATH)}`) +} + +main() diff --git a/config/scripts/oxc-cli-invocation.mjs b/config/scripts/oxc-cli-invocation.mjs new file mode 100644 index 00000000000..4bf17b5c994 --- /dev/null +++ b/config/scripts/oxc-cli-invocation.mjs @@ -0,0 +1,23 @@ +import { createRequire } from 'node:module' +import path from 'node:path' +import process from 'node:process' + +// Why not `pnpm exec ` / `node_modules/.bin/.cmd`: both land on a Windows +// .cmd shim, and Node >= 20 refuses to spawn one without `shell: true` (the +// CVE-2024-27980 mitigation), so every gate that took that route died with EINVAL +// before doing any work. The oxc bins are plain Node scripts, so run them under this +// process's own node — no shim, no shell, no quoting question. +export function resolveOxcCliInvocation(packageName, binName, root = process.cwd()) { + const requireFromRoot = createRequire(path.join(root, 'package.json')) + // The oxc packages' "exports" hide ./bin, so read the manifest and walk to its bin entry. + const manifestPath = requireFromRoot.resolve(`${packageName}/package.json`) + const binField = requireFromRoot(`${packageName}/package.json`).bin + const binEntry = typeof binField === 'string' ? binField : binField?.[binName] + if (!binEntry) { + throw new Error(`${packageName} package.json declares no "${binName}" bin entry.`) + } + return { + command: process.execPath, + prefixArgs: [path.resolve(path.dirname(manifestPath), binEntry)] + } +} diff --git a/config/scripts/oxc-cli-invocation.test.mjs b/config/scripts/oxc-cli-invocation.test.mjs new file mode 100644 index 00000000000..5776580dbfe --- /dev/null +++ b/config/scripts/oxc-cli-invocation.test.mjs @@ -0,0 +1,40 @@ +import { spawnSync } from 'node:child_process' +import { existsSync } from 'node:fs' +import path from 'node:path' +import process from 'node:process' +import { describe, expect, it } from 'vitest' +import { resolveOxcCliInvocation } from './oxc-cli-invocation.mjs' + +const repoRoot = path.resolve(import.meta.dirname, '..', '..') + +describe('resolveOxcCliInvocation', () => { + it('runs oxfmt under this process node, never through a shim', () => { + const { command, prefixArgs } = resolveOxcCliInvocation('oxfmt', 'oxfmt', repoRoot) + + expect(command).toBe(process.execPath) + expect(prefixArgs).toHaveLength(1) + // The params-catalog generator spawned node_modules/.bin/oxfmt, which is a .cmd on + // Windows — Node >= 20 refuses it without shell:true and dies with EINVAL. + expect(prefixArgs[0]).not.toMatch(/\.(cmd|bat)$/i) + expect(existsSync(prefixArgs[0])).toBe(true) + }) + + it('spawns oxfmt without a shell', () => { + const { command, prefixArgs } = resolveOxcCliInvocation('oxfmt', 'oxfmt', repoRoot) + const result = spawnSync(command, [...prefixArgs, '--help'], { + cwd: repoRoot, + encoding: 'utf8', + shell: false, + windowsHide: true + }) + + expect(result.error).toBeUndefined() + expect(result.stdout).toContain('oxfmt') + }) + + it('names the package and bin it could not find', () => { + expect(() => resolveOxcCliInvocation('oxfmt', 'nope', repoRoot)).toThrow( + 'oxfmt package.json declares no "nope" bin entry.' + ) + }) +}) diff --git a/config/scripts/oxlint-cli-invocation.mjs b/config/scripts/oxlint-cli-invocation.mjs index 605aa33c686..92e6f55fb95 100644 --- a/config/scripts/oxlint-cli-invocation.mjs +++ b/config/scripts/oxlint-cli-invocation.mjs @@ -1,23 +1,6 @@ -import { createRequire } from 'node:module' -import path from 'node:path' import process from 'node:process' +import { resolveOxcCliInvocation } from './oxc-cli-invocation.mjs' -// Why not `pnpm exec oxlint` / `node_modules/.bin/oxlint.cmd`: both land on a -// Windows .cmd shim, and Node >= 20 refuses to spawn one without `shell: true` -// (the CVE-2024-27980 mitigation), so every lint gate died with EINVAL before -// linting anything. Oxlint's bin is a plain Node script, so run it under this -// process's own node — no shim, no shell, no quoting question. export function resolveOxlintInvocation(root = process.cwd()) { - const requireFromRoot = createRequire(path.join(root, 'package.json')) - // Oxlint's "exports" hides ./bin, so read the manifest and walk to its bin entry. - const manifestPath = requireFromRoot.resolve('oxlint/package.json') - const binField = requireFromRoot('oxlint/package.json').bin - const binEntry = typeof binField === 'string' ? binField : binField?.oxlint - if (!binEntry) { - throw new Error('oxlint package.json declares no "oxlint" bin entry.') - } - return { - command: process.execPath, - prefixArgs: [path.resolve(path.dirname(manifestPath), binEntry)] - } + return resolveOxcCliInvocation('oxlint', 'oxlint', root) } diff --git a/config/scripts/pr-e2e-gate-contract.test.mjs b/config/scripts/pr-e2e-gate-contract.test.mjs index 4f012b105b4..22677bb152f 100644 --- a/config/scripts/pr-e2e-gate-contract.test.mjs +++ b/config/scripts/pr-e2e-gate-contract.test.mjs @@ -179,6 +179,13 @@ describe('PR E2E gate contract', () => { 'pnpm run test:e2e "${TEST_FILES[@]}" --workers=1 "${E2E_PROJECT_ARGS[@]}"' ) expect(playwrightConfig).toContain('retries: 0') + const steps = e2eWorkflow.jobs.e2e.steps.filter((step) => + step.run?.includes('tests/e2e/worktree-switch-first-paint.spec.ts') + ) + expect(steps).toHaveLength(1) + expect(steps[0].if).toBe("matrix.shard == '1/14'") + expect(steps[0].run).toContain('xvfb-run --auto-servernum') + expect(steps[0].run).toContain('--project=electron-headful --workers=1') }) it('keeps startup-exec live parity in the isolated SSH lane', () => { diff --git a/config/scripts/pty-transcript-secret-scan.mjs b/config/scripts/pty-transcript-secret-scan.mjs new file mode 100644 index 00000000000..1d93204ccda --- /dev/null +++ b/config/scripts/pty-transcript-secret-scan.mjs @@ -0,0 +1,135 @@ +// Finds account identifiers and credentials in a captured PTY transcript before it is committed. +import os from 'node:os' + +// Why same-length replacements: a transcript's value is its exact wrapping and column +// alignment. Shortening a redacted span reflows the screen and destroys the evidence. +const EMAIL_DOMAIN = '@example.com' +const PLACEHOLDER_UUID = '00000000-0000-4000-8000-000000000000' + +/** Ordered most-specific first; the first pattern to claim a span owns it. */ +function buildPatterns() { + const username = os.userInfo().username + const hostname = os.hostname() + const patterns = [ + { kind: 'jwt', re: /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}/g }, + { kind: 'google-api-key', re: /\bAIza[0-9A-Za-z_-]{20,}/g }, + { kind: 'google-refresh-token', re: /\b1\/\/[0-9A-Za-z_-]{20,}/g }, + { kind: 'vendor-key', re: /\b(?:sk-|ghp_|gho_|github_pat_|xoxb-|xoxp-)[A-Za-z0-9_-]{16,}/g }, + { kind: 'bearer-token', re: /\bBearer\s+[A-Za-z0-9._~+/=-]{16,}/gi }, + { kind: 'email', re: /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g }, + // Why a UUID counts: agy prints a resumable conversation id on exit, and installation and + // project ids look the same. They identify the operator's session, not just its shape. + { kind: 'uuid', re: /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi }, + { kind: 'opaque-token', re: /\b[A-Za-z0-9_-]{40,}\b/g } + ] + if (username.length >= 3) { + patterns.splice(5, 0, { kind: 'local-username', re: literalPattern(username) }) + } + if (hostname.length >= 3) { + patterns.splice(5, 0, { kind: 'local-hostname', re: literalPattern(hostname) }) + } + return patterns +} + +function literalPattern(value) { + return new RegExp(value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g') +} + +/** + * @param {string} text raw transcript, escapes intact + * @returns {{kind: string, line: number, column: number, index: number, match: string}[]} + */ +export function scanTranscriptForSecrets(text) { + const claimed = [] + const findings = [] + for (const { kind, re } of buildPatterns()) { + re.lastIndex = 0 + let match = re.exec(text) + while (match !== null) { + const start = match.index + const end = start + match[0].length + if (!claimed.some(([from, to]) => start < to && end > from)) { + claimed.push([start, end]) + if (!isAlreadyScrubbed(kind, match[0])) { + findings.push({ kind, index: start, match: match[0], ...locate(text, start) }) + } + } + match = re.exec(text) + } + } + return findings.sort((left, right) => left.index - right.index) +} + +// Why: a scrubbed fixture must verify clean, so this scanner has to recognise its own +// placeholders — otherwise "prove it's gone" can never pass and the check gets ignored. +const PLACEHOLDER_DOMAIN_RE = /@(?:example\.(?:com|org|net)|localhost)$/i + +function isAlreadyScrubbed(kind, match) { + if (kind === 'email') { + return PLACEHOLDER_DOMAIN_RE.test(match) + } + if (kind === 'uuid') { + return match.toLowerCase() === PLACEHOLDER_UUID + } + return /^(.)\1*$/.test(match) +} + +function locate(text, index) { + let line = 1 + let lineStart = 0 + for (let cursor = 0; cursor < index; cursor += 1) { + if (text.charCodeAt(cursor) === 10) { + line += 1 + lineStart = cursor + 1 + } + } + return { line, column: index - lineStart + 1 } +} + +/** Same-length stand-in so redaction cannot reflow the captured screen. */ +export function placeholderFor(kind, length) { + if (kind === 'uuid' && length === PLACEHOLDER_UUID.length) { + return PLACEHOLDER_UUID + } + if (kind === 'email' && length > EMAIL_DOMAIN.length) { + return 'u'.repeat(length - EMAIL_DOMAIN.length) + EMAIL_DOMAIN + } + return kind === 'local-username' || kind === 'local-hostname' + ? 'x'.repeat(length) + : 'X'.repeat(length) +} + +/** @returns {{text: string, redacted: number}} */ +export function redactTranscript(text) { + const findings = scanTranscriptForSecrets(text) + let out = '' + let cursor = 0 + for (const finding of findings) { + out += text.slice(cursor, finding.index) + out += placeholderFor(finding.kind, finding.match.length) + cursor = finding.index + finding.match.length + } + return { text: out + text.slice(cursor), redacted: findings.length } +} + +export function formatFindings(label, findings) { + if (findings.length === 0) { + return `${label}: clean — no account identifier or credential shapes found.` + } + const rows = findings.map( + (finding) => ` ${finding.line}:${finding.column} ${finding.kind} ${preview(finding.match)}` + ) + return [`${label}: ${findings.length} finding(s) — scrub before committing.`, ...rows].join('\n') +} + +// Why a codepoint test and not a character class: a control-byte range written as an escape is +// folded back into raw 0x00-0x1f bytes by the formatter, which makes this file binary to the VCS +// and leaves the one file gating real PTY data into history unreviewable in a diff. +function preview(value) { + const head = value.length <= 24 ? value : `${value.slice(0, 21)}...` + let printable = '' + for (const char of head) { + printable += (char.codePointAt(0) ?? 0) < 0x20 ? '?' : char + } + return printable +} diff --git a/config/scripts/pty-transcript-secret-scan.test.mjs b/config/scripts/pty-transcript-secret-scan.test.mjs new file mode 100644 index 00000000000..2d3cd894da0 --- /dev/null +++ b/config/scripts/pty-transcript-secret-scan.test.mjs @@ -0,0 +1,133 @@ +// The scrub gate is the only thing standing between a live agent transcript and a +// committed account identifier, so it is pinned on the shapes those transcripts carry. +import { readdirSync, readFileSync } from 'node:fs' +import os from 'node:os' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' +import { + formatFindings, + placeholderFor, + redactTranscript, + scanTranscriptForSecrets +} from './pty-transcript-secret-scan.mjs' +import { parseArgs, resolveSpawn } from './capture-agent-pty-transcript.mjs' + +describe('pty transcript secret scan', () => { + it('finds the account row of a ready screen', () => { + const findings = scanTranscriptForSecrets('Antigravity CLI 1.1.17\njin.woo@acme.dev (Business)') + expect(findings).toHaveLength(1) + expect(findings[0]).toMatchObject({ kind: 'email', line: 2, column: 1 }) + }) + + it('finds credentials an agent may echo while signing in', () => { + const kinds = scanTranscriptForSecrets( + [ + 'token: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dBjftJeZ4CVP', + 'key: AIzaSyA1234567890abcdefghijklmnopqrstu', + 'refresh: 1//0gLm34XyZabcdefghijklmnopqrstuvwx', + 'Authorization: Bearer abcdefghijklmnopqrstuvwxyz012345' + ].join('\n') + ).map((finding) => finding.kind) + expect(kinds).toEqual(['jwt', 'google-api-key', 'google-refresh-token', 'bearer-token']) + }) + + it('flags this machine’s own username, which a prompt line leaks', () => { + const username = os.userInfo().username + const findings = scanTranscriptForSecrets(`~/Users/${username}/orca/repo\n> `) + expect(findings.some((finding) => finding.kind === 'local-username')).toBe(true) + }) + + it('finds the resumable conversation id agy prints on exit', () => { + const findings = scanTranscriptForSecrets( + 'Resume with -c (or command below):\nagy --conversation=26dc1986-9eec-456a-a534-d93e5c1076c2' + ) + expect(findings).toHaveLength(1) + expect(findings[0].kind).toBe('uuid') + expect(placeholderFor('uuid', findings[0].match.length)).toMatch( + /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$/ + ) + }) + + it('reports a clean transcript as clean', () => { + const findings = scanTranscriptForSecrets('Antigravity CLI 1.1.17\nSonnet 4.6 (High)\n> ') + expect(findings).toEqual([]) + expect(formatFindings('fixture', findings)).toContain('clean') + }) + + it('claims a span once, so a token inside an email is not double-reported', () => { + const findings = scanTranscriptForSecrets('longlivedaccountname@corp.internal') + expect(findings).toHaveLength(1) + }) + + it('passes a fixture that is already scrubbed, so "prove it is gone" can succeed', () => { + const scrubbed = `uuuu@example.com\n${'X'.repeat(44)}` + expect(scanTranscriptForSecrets(scrubbed)).toEqual([]) + }) +}) + +describe('redaction', () => { + it('replaces every finding with the same number of characters', () => { + // Why length matters: the fixture's value is its exact wrapping. A shorter + // replacement reflows the screen and invalidates the capture. + const text = 'Antigravity CLI 1.1.17\njin.woo@acme.dev (Antigravity Business)\n> ' + const { text: redacted, redacted: count } = redactTranscript(text) + expect(count).toBe(1) + expect(redacted).toHaveLength(text.length) + expect(redacted).not.toContain('jin.woo@acme.dev') + expect(scanTranscriptForSecrets(redacted)).toEqual([]) + expect(redactTranscript(redacted).redacted).toBe(0) + }) + + it('keeps a redacted email shaped like an email', () => { + expect(placeholderFor('email', 'a@b.example.com'.length)).toMatch(/^u+@example\.com$/) + }) + + it('leaves the rest of the screen byte-for-byte untouched', () => { + const text = 'line one\nuser@corp.io\nline three' + expect(redactTranscript(text).text.split('\n')[2]).toBe('line three') + }) +}) + +describe('committed transcripts', () => { + // Why in CI and not just in the recorder: a transcript is committed once and read forever. + // The capture-time warning is skippable; this is not. + const fixtureDir = join(import.meta.dirname, '..', '..', 'src', 'main', 'runtime', '__fixtures__') + const transcripts = readdirSync(fixtureDir).filter((entry) => entry.endsWith('.txt')) + + it.each(transcripts)('%s carries no account identifier or credential', (name) => { + const findings = scanTranscriptForSecrets(readFileSync(join(fixtureDir, name), 'utf8')) + expect(formatFindings(name, findings)).toContain('clean') + }) +}) + +describe('capture argv', () => { + it('splits recorder options from the agent command', () => { + const { options, command } = parseArgs([ + '--name', + 'antigravity-ready-personal-non-gemini', + '--cols', + '120', + '--', + 'agy', + '--model', + 'sonnet' + ]) + expect(options.name).toBe('antigravity-ready-personal-non-gemini') + expect(options.cols).toBe(120) + expect(command).toEqual(['agy', '--model', 'sonnet']) + }) + + it('collects a multi-file scan list', () => { + const { options } = parseArgs(['--scan', 'a.txt', 'b.txt', '--redact']) + expect(options.scan).toEqual(['a.txt', 'b.txt']) + expect(options.redact).toBe(true) + }) + + it('routes a Windows shim through cmd.exe, which node-pty cannot spawn directly', () => { + expect(resolveSpawn(['agy.cmd', '--model', 'sonnet'])).toEqual( + process.platform === 'win32' + ? { file: 'cmd.exe', args: ['/c', '"agy.cmd"', '--model', 'sonnet'] } + : { file: 'agy.cmd', args: ['--model', 'sonnet'] } + ) + }) +}) diff --git a/config/scripts/session-search-query-benchmark.ts b/config/scripts/session-search-query-benchmark.ts new file mode 100644 index 00000000000..1471a0a17bd --- /dev/null +++ b/config/scripts/session-search-query-benchmark.ts @@ -0,0 +1,192 @@ +import { rm, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { + createSessionParseStats, + parseAgentSessionFileCached, + resetSessionParseCacheForTests +} from '../../src/main/ai-vault/session-scanner-parse-cache' +import { resetTranscriptConsumersForTests } from '../../src/main/ai-vault/session-transcript-consumers' +import { SessionSearchEngine } from '../../src/main/ai-vault-search/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 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' + +// What a query costs, and what the session candidate limit buys. Everything +// runs through the real store and the real engine over a synthetic corpus; +// never point this at a real transcript tree. + +const WARMUP = 5 +const SAMPLES = 25 + +// One query per rung the ladder can take, plus the two shapes that skip it. +const QUERIES: { name: string; request: SessionSearchRequest }[] = [ + { name: 'phrase', request: { query: '"terminal reattach"' } }, + { name: 'identifier', request: { query: 'resolveTerminalPath' } }, + { name: 'path', request: { query: 'src/main/ai-vault/session-transcript-reader.ts' } }, + { name: 'prose', request: { query: 'why is the daemon snapshot stale' } }, + { name: 'typo', request: { query: 'reattahc worktre' } }, + { name: 'common-term', request: { query: 'index' } }, + { name: 'operator-only', request: { query: 'repo:app-3' } }, + { name: 'scoped', request: { query: 'worktree', filters: { scopePaths: ['/repo/app-3'] } } } +] + +type Timing = { p50: number; p95: number } + +function percentile(sorted: readonly number[], fraction: number): number { + const at = Math.min(sorted.length - 1, Math.floor(sorted.length * fraction)) + return Math.round((sorted[at] ?? 0) * 100) / 100 +} + +function timing(samples: number[]): Timing { + const sorted = [...samples].sort((left, right) => left - right) + return { p50: percentile(sorted, 0.5), p95: percentile(sorted, 0.95) } +} + +function time(engine: SessionSearchEngine, request: SessionSearchRequest): number { + const started = performance.now() + engine.search(request) + return performance.now() - started +} + +async function indexCorpus( + options: SyntheticCorpusOptions +): Promise<{ corpus: SyntheticCorpus; db: SyncDatabase; release: () => void }> { + resetSessionParseCacheForTests() + const corpus = await writeSyntheticTranscriptCorpus(options) + const store = new SessionSearchStore(join(corpus.root, 'index.sqlite'), (error) => { + throw error + }) + const unregister = registerSessionSearchIndexConsumer(store) + const stats = createSessionParseStats() + for (const path of corpus.files) { + await parseAgentSessionFileCached( + await sessionCandidate('claude', path), + process.platform, + stats + ) + } + return { + corpus, + // The handle a composed reader gets. Every read here is one synchronous + // statement, which is the contract that comes with it. + db: store.connection, + release: () => { + unregister() + resetTranscriptConsumersForTests() + resetSessionParseCacheForTests() + store.close() + } + } +} + +/** Per-query and overall latency for one scope. */ +function scopeReport(db: SyncDatabase, scope: SessionSearchScope): Record { + const engine = new SessionSearchEngine(db) + const everything: number[] = [] + const perQuery: Record = {} + for (const { name, request } of QUERIES) { + const scoped = { ...request, scope } + for (let run = 0; run < WARMUP; run++) { + engine.search(scoped) + } + const samples = Array.from({ length: SAMPLES }, () => time(engine, scoped)) + everything.push(...samples) + const result = engine.search(scoped) + perQuery[name] = { ...timing(samples), hits: result.hits.length, route: result.planner.route } + } + return { ...timing(everything), perQuery } +} + +/** + * The candidate limit only costs anything once there are more matching sessions + * than the limit, so this runs over many short sessions rather than the wide + * corpus above. Limits are interleaved sample by sample: run back to back, the + * first configuration pays for every page the OS cache had not seen yet and the + * ordering alone moves p95 by more than the limit does. + */ +function candidateSweep(db: SyncDatabase, limits: readonly number[]): Record { + const request: SessionSearchRequest = { query: 'index', limit: 20 } + const engines = new Map( + limits.map((limit) => [limit, new SessionSearchEngine(db, { sessionCandidateLimit: limit })]) + ) + const samples = new Map(limits.map((limit) => [limit, [] as number[]])) + for (let run = 0; run < WARMUP; run++) { + for (const engine of engines.values()) { + engine.search(request) + } + } + for (let run = 0; run < SAMPLES; run++) { + for (const limit of limits) { + samples.get(limit)!.push(time(engines.get(limit)!, request)) + } + } + const report: Record = {} + for (const limit of limits) { + const result = engines.get(limit)!.search(request) + report[String(limit)] = { + ...timing(samples.get(limit)!), + truncated: result.truncated.candidates, + // Pages a caller could walk before the limit stops handing out sessions. + reachablePages: Math.ceil(limit / (request.limit ?? 20)) + } + } + return report +} + +const wide = await indexCorpus({ sessions: Number(process.env.SESSIONS ?? 40) }) +let report: string +try { + const scope = { + all: scopeReport(wide.db, 'all'), + conversation: scopeReport(wide.db, 'conversation') + } + wide.release() + await rm(wide.corpus.root, { recursive: true, force: true }) + + // Many short sessions: what makes the candidate limit binding is the session + // count, not the byte count. + const many = await indexCorpus({ sessions: 2500, turnsPerSession: 1, seed: 7 }) + try { + report = JSON.stringify( + { + scopeCorpus: { + sessions: wide.corpus.files.length, + transcriptMb: Math.round((wide.corpus.transcriptBytes / 1024 / 1024) * 100) / 100, + messages: wide.corpus.messageCount + }, + scope, + candidateCorpus: { + sessions: many.corpus.files.length, + transcriptMb: Math.round((many.corpus.transcriptBytes / 1024 / 1024) * 100) / 100 + }, + candidateSweep: candidateSweep(many.db, [200, 600, 1200, 2400]) + }, + null, + 2 + ) + } finally { + many.release() + await rm(many.corpus.root, { recursive: true, force: true }) + } +} catch (error) { + await rm(wide.corpus.root, { recursive: true, force: true }) + throw error +} + +// Why a file as well as stdout: a runner that intercepts console output +// (vitest does) would otherwise swallow the whole report. +const out = process.env.BENCH_OUT +if (out) { + await writeFile(out, `${report}\n`) +} +console.log(report) diff --git a/config/scripts/session-search-retention-benchmark.ts b/config/scripts/session-search-retention-benchmark.ts new file mode 100644 index 00000000000..095eb5f29b0 --- /dev/null +++ b/config/scripts/session-search-retention-benchmark.ts @@ -0,0 +1,148 @@ +import assert from 'node:assert/strict' +import { mkdtemp, rm, stat } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { setImmediate as yieldToEventLoop } from 'node:timers/promises' +import { + syntheticCandidate, + syntheticSession, + userMessages +} from '../../src/main/ai-vault-search/session-search-index-test-fixture' +import { SessionSearchStore } from '../../src/main/ai-vault-search/session-search-store' +import SyncDatabase from '../../src/main/sqlite/sync-database' + +// Bundle with esbuild --bundle --platform=node, then run on the host under test. +// Every mode seeds through SessionSearchStore so the three arms are comparable; +// only `whole-file` leaves the shipped path, because it is the baseline the +// batched purge exists to replace. + +const ROWS = 60_000 + +/** The purge yields with `setImmediate` between chunks, so a peer chain samples each gap. */ +async function sampleLoopStalls(running: () => boolean, intervals: number[]): Promise { + let previous = performance.now() + while (running()) { + await yieldToEventLoop() + const now = performance.now() + intervals.push(now - previous) + previous = now + } +} + +/** What a search would still return: rows whose session row is still there. */ +function visibleRows(db: SyncDatabase): number { + return ( + db + .prepare(`SELECT count(*) AS n FROM messages m JOIN sessions s ON s.id = m.session_row_id`) + .get() as { n: number } + ).n +} + +const root = await mkdtemp(join(tmpdir(), 'orca-search-retention-bench-')) +try { + for (const mode of ['whole-file', 'batched', 'batched-pinned-reader']) { + const path = join(root, `${mode}.sqlite`) + const errors: unknown[] = [] + const store = new SessionSearchStore(path, (error) => errors.push(error)) + let reader: SyncDatabase | null = null + try { + const write = store.beginWrite(syntheticCandidate(), 'replace', 0)! + for (const message of userMessages( + 'synthetic benchmark needle repeated context for a representative coding conversation with commands and paths src/example.ts', + ROWS + )) { + write.add(message) + } + assert.equal( + write.commit({ + session: syntheticSession(), + byteOffset: 4096, + incomplete: false + }), + true + ) + assert.deepEqual(errors, []) + // Truncating first is what makes walBytes below the purge's own growth. + const checkpoint = new SyncDatabase(path) + checkpoint.pragma('wal_checkpoint(TRUNCATE)') + checkpoint.close() + if (mode === 'batched-pinned-reader') { + reader = new SyncDatabase(path, { readonly: true }) + reader.exec('BEGIN') + reader.prepare('SELECT count(*) FROM messages').get() + } + const probe = new SyncDatabase(path, { readonly: true }) + const intervals: number[] = [] + const started = performance.now() + if (mode === 'whole-file') { + const raw = new SyncDatabase(path) + try { + raw.exec('BEGIN IMMEDIATE') + const ids = raw.prepare('SELECT id FROM messages').all() as { + id: number + }[] + for (const { id } of ids) { + raw.prepare('DELETE FROM messages_fts WHERE rowid=?').run(id) + } + raw.exec('DELETE FROM messages; DELETE FROM sessions; DELETE FROM files; COMMIT') + } finally { + raw.close() + } + intervals.push(performance.now() - started) + } else { + let purging = true + const purge = store.purgeOlderThan(Date.now() + 60_000) + // Hiding is immediate: cutting the session loose from its file is the + // first transaction, so a read one turn in already sees nothing, long + // before the rows are gone. + const hiddenEarly = yieldToEventLoop().then(() => visibleRows(probe)) + const sampler = sampleLoopStalls(() => purging, intervals) + await purge + purging = false + await sampler + assert.equal(await hiddenEarly, 0) + assert.deepEqual(errors, []) + } + const wallMs = performance.now() - started + probe.close() + reader?.exec('COMMIT') + reader?.close() + reader = null + const after = new SyncDatabase(path, { readonly: true }) + try { + for (const table of ['messages_fts']) { + assert.equal( + ( + after.prepare(`SELECT count(*) AS n FROM ${table}`).get() as { + n: number + } + ).n, + 0 + ) + } + } finally { + after.close() + } + const walBytes = (await stat(`${path}-wal`)).size + intervals.sort((a, b) => a - b) + console.log( + JSON.stringify({ + mode, + platform: process.platform, + node: process.version, + rows: ROWS, + wallMs: Math.round(wallMs), + samples: intervals.length, + maxStepMs: Math.round(intervals.at(-1) ?? 0), + p95StepMs: Math.round(intervals[Math.floor(intervals.length * 0.95)] ?? 0), + walBytes + }) + ) + } finally { + reader?.close() + store.close() + } + } +} finally { + await rm(root, { recursive: true, force: true }) +} diff --git a/config/scripts/session-search-scope-benchmark.ts b/config/scripts/session-search-scope-benchmark.ts new file mode 100644 index 00000000000..306387cbdda --- /dev/null +++ b/config/scripts/session-search-scope-benchmark.ts @@ -0,0 +1,205 @@ +import { rm, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { + createSessionParseStats, + parseAgentSessionFileCached, + resetSessionParseCacheForTests +} from '../../src/main/ai-vault/session-scanner-parse-cache' +import { resetTranscriptConsumersForTests } from '../../src/main/ai-vault/session-transcript-consumers' +import { SessionSearchEngine } from '../../src/main/ai-vault-search/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' +import type SyncDatabase from '../../src/main/sqlite/sync-database' +import { writeToolHeavyCorpus, type ToolHeavyCorpus } from './session-search-tool-heavy-corpus' + +// What each scope costs on an index the size of a real transcript tree. +// +// The 10.5 MB corpus in `session-search-query-benchmark.ts` sizes the route +// ladder; this one sizes the corpus. `conversation` is a column filter over the +// one FTS table rather than a second table of its own, and the whole cost of +// that decision is how much of `messages_fts` a conversation query has to read +// past — which is set by how much of a transcript is tool output. +// +// Synthetic, always: this must never be pointed at a real transcript. + +const WARMUP = 5 + +/** Conversation-shaped queries; every term is one the prose actually uses. */ +const QUERIES = [ + 'terminal reattach', + 'stale snapshot', + 'daemon cursor', + 'worktree index', + 'publish transaction', + 'relay daemon', + 'session cursor', + 'because stale', + 'terminal worktree', + 'index snapshot', + 'reattach cursor', + 'transaction relay', + 'snapshot session', + 'daemon publish', + 'worktree terminal', + 'cursor index', + 'stale relay', + 'session transaction', + 'publish snapshot', + 'reattach daemon' +] + +async function indexCorpus( + corpus: ToolHeavyCorpus +): Promise<{ db: SyncDatabase; release: () => void }> { + resetSessionParseCacheForTests() + const store = new SessionSearchStore(join(corpus.root, 'index.sqlite'), (error) => { + throw error + }) + const unregister = registerSessionSearchIndexConsumer(store) + const stats = createSessionParseStats() + for (const path of corpus.files) { + await parseAgentSessionFileCached( + await sessionCandidate('claude', path), + process.platform, + stats + ) + } + return { + // The store's own handle, which is what a composed reader gets: every + // retrieval is one synchronous statement, so nothing pins a WAL snapshot. + db: store.connection, + release: () => { + unregister() + resetTranscriptConsumersForTests() + resetSessionParseCacheForTests() + store.close() + } + } +} + +type Timing = { p50: number; p95: number } + +function timing(samples: readonly number[]): Timing { + const sorted = [...samples].sort((left, right) => left - right) + const at = (fraction: number): number => { + const index = Math.min(sorted.length - 1, Math.floor(sorted.length * fraction)) + return Math.round((sorted[index] ?? 0) * 100) / 100 + } + return { p50: at(0.5), p95: at(0.95) } +} + +/** + * The query sets, one per rung of the ladder the engine may take. + * + * Which rung each one reaches is not forced, it is observed: samples are + * bucketed by the route the engine reports, so the table says what was measured + * rather than what was intended, and a query that lands on a different rung + * than expected shows up as a bucket rather than as a wrong number. + */ +function queries(): string[] { + const run = (index: number, length: number): string => + Array.from({ length }, (_unused, step) => QUERIES[(index + step) % QUERIES.length]).join(' ') + return [ + // Two terms, unquoted: not literal, so straight to OR. + ...QUERIES, + // Two terms, quoted: literal, and on this corpus any two of fourteen words + // sit next to each other somewhere, so the phrase rung answers. + ...QUERIES.map((query) => `"${query}"`), + // Eight terms, quoted: an ordered run that long does not occur in 105 MB of + // draws from fourteen words, so the phrase rung misses and AND answers. + ...QUERIES.map((_query, index) => `"${run(index, 4)}"`) + ] +} + +type Bucket = { samples: number[]; hits: number } + +/** + * Both scopes over the same queries, interleaved scope by scope: run back to + * back, the first one pays for every page the OS cache had not seen and the + * ordering moves p95 more than the scope does. + */ +function scopeReport(db: SyncDatabase): Record { + const engine = new SessionSearchEngine(db) + const scopes: SessionSearchScope[] = ['all', 'conversation'] + const requests: SessionSearchRequest[] = queries().map((query) => ({ query })) + const buckets = new Map() + for (let run = 0; run < WARMUP; run++) { + for (const scope of scopes) { + for (const request of requests) { + engine.search({ ...request, scope }) + } + } + } + for (const request of requests) { + for (const scope of scopes) { + const started = performance.now() + const result = engine.search({ ...request, scope }) + const elapsed = performance.now() - started + const key = `${result.planner.route}/${scope}` + const bucket = buckets.get(key) ?? { samples: [], hits: 0 } + bucket.samples.push(elapsed) + bucket.hits += result.hits.length + buckets.set(key, bucket) + } + } + const report: Record = {} + for (const [key, bucket] of [...buckets].sort(([left], [right]) => left.localeCompare(right))) { + report[key] = { ...timing(bucket.samples), samples: bucket.samples.length, hits: bucket.hits } + } + return report +} + +/** Bytes the FTS table occupies, which is the cost the deleted second table saved. */ +function indexBytes(db: SyncDatabase): Record | { unavailable: string } { + try { + const sum = (where: string, ...values: string[]): number => + Number( + ( + db + .prepare(`SELECT COALESCE(SUM(pgsize),0) AS bytes FROM dbstat ${where}`) + .get(...values) as { bytes: number } + ).bytes + ) + return { total: sum(''), messagesFts: sum('WHERE name LIKE ?', 'messages_fts%') } + } catch { + // dbstat is a compile-time option; the latency numbers stand without it. + return { unavailable: 'no dbstat' } + } +} + +const corpus = await writeToolHeavyCorpus({ + targetBytes: Number(process.env.CORPUS_MB ?? 100) * 1024 * 1024, + toolShare: Number(process.env.TOOL_SHARE ?? 0.9) +}) +let report: string +const indexed = await indexCorpus(corpus) +try { + report = JSON.stringify( + { + corpus: { + sessions: corpus.files.length, + transcriptMb: Math.round((corpus.transcriptBytes / 1024 / 1024) * 100) / 100, + toolShareOfMessageText: + Math.round((corpus.toolBytes / (corpus.toolBytes + corpus.proseBytes)) * 1000) / 1000 + }, + indexBytes: indexBytes(indexed.db), + route: scopeReport(indexed.db) + }, + null, + 2 + ) +} finally { + indexed.release() + await rm(corpus.root, { recursive: true, force: true }) +} + +const out = process.env.BENCH_OUT +if (out) { + await writeFile(out, `${report}\n`) +} +console.log(report) diff --git a/config/scripts/session-search-tool-heavy-corpus.ts b/config/scripts/session-search-tool-heavy-corpus.ts new file mode 100644 index 00000000000..050535a00cf --- /dev/null +++ b/config/scripts/session-search-tool-heavy-corpus.ts @@ -0,0 +1,152 @@ +import { mkdtemp, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +// The corpus the scope benchmark runs over. Written here rather than by +// `session-search-synthetic-corpus.ts` because what it costs to answer a +// conversation query out of the one FTS table turns on the property that +// generator fixes: how much of a transcript is tool output. +// +// Synthetic, always. This must never be pointed at a real transcript. + +const PROSE = [ + 'terminal', + 'reattach', + 'worktree', + 'the', + 'index', + 'cursor', + 'publish', + 'transaction', + 'relay', + 'daemon', + 'snapshot', + 'because', + 'stale', + 'session' +] +// Tool output is paths, hashes and log lines — and the same words the +// conversation uses, because a `rg` over this repository prints them. That +// overlap is what the benchmark turns on: it is what makes a conversation +// term's posting list carry rows the column filter then has to discard. A tool +// vocabulary disjoint from the prose would leave nothing to discard and measure +// the wrong thing. +const TOOL_ONLY = [ + 'src/main/ai-vault/session-transcript-reader.ts', + 'node_modules/.pnpm/typescript@5.9.2', + '0x00007ff8', + 'ENOENT', + 'drwxr-xr-x', + '2026-09-10T00:00:00.000Z', + 'sha256:9f2c1a', + 'chunk-VHQ4NWQK.js', + 'warning:', + 'resolveTerminalPath', + 'byteOffset', + 'MAX_RETRIES' +] +// Half the tool tokens are conversation words. Deliberately pessimistic: the +// more of a query term lives in `tool_text`, the more the column filter costs, +// so a number measured here holds on a real transcript tree. +const TOOL = [...PROSE, ...TOOL_ONLY] + +function mulberry32(seed: number): () => number { + let state = seed >>> 0 + return () => { + state = (state + 0x6d2b79f5) >>> 0 + let t = Math.imul(state ^ (state >>> 15), 1 | state) + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 + } +} + +function words(random: () => number, vocabulary: readonly string[], count: number): string { + const out: string[] = [] + for (let index = 0; index < count; index++) { + out.push(vocabulary[Math.floor(random() * vocabulary.length)]!) + } + return out.join(' ') +} + +export type ToolHeavyCorpus = { + root: string + files: string[] + transcriptBytes: number + toolBytes: number + proseBytes: number +} + +/** + * Claude JSONL transcripts whose tool output is `toolShare` of the message text. + * One turn is a user question, an assistant answer, a tool call and its output; + * only the last one grows with the share. + */ +export async function writeToolHeavyCorpus(args: { + targetBytes: number + toolShare: number + seed?: number +}): Promise { + const random = mulberry32(args.seed ?? 11) + const root = await mkdtemp(join(tmpdir(), 'orca-search-convfts-')) + const files: string[] = [] + const proseWordsPerTurn = 160 + // Tool and prose words are not the same length, so the share is over bytes. + const proseBytesPerTurn = proseWordsPerTurn * 6 + const toolWordCount = Math.max( + 1, + Math.round((proseBytesPerTurn * args.toolShare) / (1 - args.toolShare) / 22) + ) + let transcriptBytes = 0 + let toolBytes = 0 + let proseBytes = 0 + for (let session = 0; transcriptBytes < args.targetBytes; session++) { + const sessionId = `00000000-0000-4000-8000-${String(session).padStart(12, '0')}` + const lines: string[] = [] + for (let turn = 0; turn < 40; turn++) { + const at = new Date(1740000000000 + turn * 60_000).toISOString() + const question = words(random, PROSE, 40) + const answer = words(random, PROSE, proseWordsPerTurn - 40) + const output = words(random, TOOL, toolWordCount) + proseBytes += Buffer.byteLength(question) + Buffer.byteLength(answer) + toolBytes += Buffer.byteLength(output) + lines.push( + JSON.stringify({ + type: 'user', + sessionId, + timestamp: at, + cwd: `/repo/app-${session % 7}`, + gitBranch: 'main', + message: { role: 'user', content: question } + }), + JSON.stringify({ + type: 'assistant', + sessionId, + timestamp: at, + message: { + role: 'assistant', + model: 'claude-fable-5', + content: [ + { type: 'text', text: answer }, + { type: 'tool_use', name: 'Bash', input: { command: 'rg needle' } } + ] + } + }), + JSON.stringify({ + type: 'user', + sessionId, + timestamp: at, + message: { + role: 'user', + content: [{ type: 'tool_result', tool_use_id: 'toolu_1', content: output }] + } + }) + ) + } + const path = join(root, `${sessionId}.jsonl`) + const body = `${lines.join('\n')}\n` + await writeFile(path, body) + transcriptBytes += Buffer.byteLength(body) + files.push(path) + } + return { root, files, transcriptBytes, toolBytes, proseBytes } +} diff --git a/config/scripts/session-search-write-benchmark.ts b/config/scripts/session-search-write-benchmark.ts new file mode 100644 index 00000000000..db09275cd98 --- /dev/null +++ b/config/scripts/session-search-write-benchmark.ts @@ -0,0 +1,266 @@ +import assert from 'node:assert/strict' +import { rm, stat } from 'node:fs/promises' +import { join } from 'node:path' +import { setImmediate as yieldToEventLoop } from 'node:timers/promises' +import { + createSessionParseStats, + parseAgentSessionFileCached, + resetSessionParseCacheForTests +} from '../../src/main/ai-vault/session-scanner-parse-cache' +import { resetTranscriptConsumersForTests } from '../../src/main/ai-vault/session-transcript-consumers' +import { requestWholeTranscriptRead } from '../../src/main/ai-vault/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 SyncDatabase from '../../src/main/sqlite/sync-database' + +// Measures the real transcript reader and search store over a synthetic corpus. +// Never point this at a real transcript tree. + +/** + * How long the longest single transaction held the process. + * + * With one transaction per file that is the whole stall a file costs, so it is + * the number the commit ceiling exists to bound. Measured by wrapping `exec`, + * because the writer's transactions are the only ones this benchmark runs. + */ +function recordTransactionDurations(durations: number[]): () => void { + const exec = SyncDatabase.prototype.exec + let started = 0 + SyncDatabase.prototype.exec = function (this: SyncDatabase, sql: string): void { + if (sql === 'BEGIN IMMEDIATE') { + started = performance.now() + } + exec.call(this, sql) + if (sql === 'COMMIT' && started > 0) { + durations.push(performance.now() - started) + started = 0 + } + } + return () => { + SyncDatabase.prototype.exec = exec + } +} + +/** The writer commits synchronously, so a peer chain samples the gap each read leaves. */ +async function sampleLoopStalls(running: () => boolean, stalls: number[]): Promise { + let previous = performance.now() + while (running()) { + await yieldToEventLoop() + const now = performance.now() + stalls.push(now - previous) + previous = now + } +} + +function tableBytes(db: SyncDatabase): Record { + const rows = db.prepare('SELECT name, sum(pgsize) AS bytes FROM dbstat GROUP BY name').all() as { + name: string + bytes: number + }[] + const group = (prefix: string): number => + rows + .filter((row) => row.name === prefix || row.name.startsWith(`${prefix}_`)) + .reduce((sum, row) => sum + row.bytes, 0) + return { + messagesFts: group('messages_fts'), + messages: group('messages') - group('messages_fts'), + sessions: group('sessions'), + total: rows.reduce((sum, row) => sum + row.bytes, 0) + } +} + +function assertIndexedMessages(db: SyncDatabase, expected: number): number { + const { n } = db + .prepare('SELECT count(*) AS n FROM messages m JOIN sessions s ON s.id = m.session_row_id') + .get() as { n: number } + assert.equal(n, expected, 'indexed message count') + return n +} + +async function checkpointedFileBytes(db: SyncDatabase, path: string): Promise { + // Flush committed WAL pages before reporting the final database footprint. + const [checkpoint] = db.pragma('wal_checkpoint(TRUNCATE)') as { busy: number }[] + assert.equal(checkpoint?.busy, 0, 'storage measurement requires a completed checkpoint') + return (await stat(path)).size +} + +// The default corpus puts tool output at about half the message text; set this +// far higher to price the tool-row cap against the real 80-97 % band. +const toolResultWords = Number(process.env.ORCA_SEARCH_BENCH_TOOL_WORDS ?? 200) +const corpus = await writeSyntheticTranscriptCorpus({ toolResultWords }) +const indexPath = join(corpus.root, 'index.sqlite') +try { + const errors: unknown[] = [] + const store = new SessionSearchStore(indexPath, (error) => errors.push(error)) + const unregister = registerSessionSearchIndexConsumer(store) + const stalls: number[] = [] + const transactions: number[] = [] + const restoreExec = recordTransactionDurations(transactions) + let indexing = true + try { + const stats = createSessionParseStats() + const started = performance.now() + const sampler = sampleLoopStalls(() => indexing, stalls) + for (const path of corpus.files) { + await parseAgentSessionFileCached( + await sessionCandidate('claude', path), + process.platform, + stats + ) + } + indexing = false + await sampler + restoreExec() + const rebuildMs = performance.now() - started + assert.deepEqual(errors, []) + + const reader = new SyncDatabase(indexPath, { readonly: true }) + try { + const rows = assertIndexedMessages(reader, corpus.messageCount) + const sessions = ( + reader.prepare('SELECT count(*) AS n FROM sessions').get() as { + n: number + } + ).n + assert.equal(sessions, corpus.files.length) + const bytes = tableBytes(reader) + const perMb = (value: number): number => + Math.round((value / (corpus.transcriptBytes / (1024 * 1024))) * 10) / 10 + const fileBytes = await checkpointedFileBytes(store.connection, indexPath) + stalls.sort((a, b) => a - b) + transactions.sort((a, b) => a - b) + console.log( + JSON.stringify( + { + platform: process.platform, + node: process.version, + transcriptMb: Math.round((corpus.transcriptBytes / (1024 * 1024)) * 100) / 100, + toolResultWords, + sessions, + rows, + rebuildMs: Math.round(rebuildMs), + rowsPerSecond: Math.round(rows / (rebuildMs / 1000)), + transcriptMbPerSecond: + Math.round((corpus.transcriptBytes / (1024 * 1024) / (rebuildMs / 1000)) * 100) / 100, + bytesPerTranscriptMb: { + messagesFts: perMb(bytes.messagesFts), + messages: perMb(bytes.messages), + sessions: perMb(bytes.sessions), + total: perMb(bytes.total) + }, + writeAmplification: Math.round((bytes.total / corpus.transcriptBytes) * 100) / 100, + fileWriteAmplification: Math.round((fileBytes / corpus.transcriptBytes) * 100) / 100, + transactions: transactions.length, + maxTransactionMs: Math.round((transactions.at(-1) ?? 0) * 100) / 100, + maxLoopStallMs: Math.round(stalls.at(-1) ?? 0), + p95LoopStallMs: Math.round(stalls[Math.floor(stalls.length * 0.95)] ?? 0), + loopStallSamples: stalls.length, + parseStats: stats + }, + null, + 2 + ) + ) + } finally { + reader.close() + } + } finally { + indexing = false + restoreExec() + unregister() + resetTranscriptConsumersForTests() + resetSessionParseCacheForTests() + store.close() + } +} finally { + await rm(corpus.root, { recursive: true, force: true }) +} + +// Phase two: one transcript far larger than any real one, to price the ceiling +// that decides whether a file commits once or in chunks. +const largeTurns = Number(process.env.ORCA_SEARCH_BENCH_LARGE_TURNS ?? 23_000) +const large = await writeSyntheticTranscriptCorpus({ + sessions: 1, + turnsPerSession: largeTurns, + seed: 2 +}) +const largeIndexPath = join(large.root, 'index.sqlite') +try { + const errors: unknown[] = [] + const store = new SessionSearchStore(largeIndexPath, (error) => errors.push(error)) + const unregister = registerSessionSearchIndexConsumer(store) + const transactions: number[] = [] + const restoreExec = recordTransactionDurations(transactions) + try { + const stats = createSessionParseStats() + const started = performance.now() + await parseAgentSessionFileCached( + await sessionCandidate('claude', large.files[0]!), + process.platform, + stats + ) + const indexMs = performance.now() - started + restoreExec() + assert.deepEqual(errors, []) + assertIndexedMessages(store.connection, large.messageCount) + transactions.sort((a, b) => a - b) + + // The same file again, over a generation the index already holds. That is + // the pass a growing transcript really costs, and the one whose transaction + // used to be sized by the old session rather than by the chunk being + // written. The drain that reclaims the cut-loose generation runs after the + // commit, so its bounded batches are in `replaceTransactions` too. + const replaceTransactions: number[] = [] + const restoreReplaceExec = recordTransactionDurations(replaceTransactions) + requestWholeTranscriptRead(large.files[0]!) + const replaceStarted = performance.now() + await parseAgentSessionFileCached( + await sessionCandidate('claude', large.files[0]!), + process.platform, + stats + ) + const replaceMs = performance.now() - replaceStarted + // Finishes whatever the scheduled drain has not reached, so the reclaim is + // priced rather than left half done under the next measurement. + const reclaimStarted = performance.now() + await store.purgeOlderThan(null) + const reclaimMs = performance.now() - reclaimStarted + restoreReplaceExec() + assert.deepEqual(errors, []) + assertIndexedMessages(store.connection, large.messageCount) + replaceTransactions.sort((a, b) => a - b) + + console.log( + JSON.stringify( + { + phase: 'single-large-file', + transcriptMb: Math.round((large.transcriptBytes / (1024 * 1024)) * 100) / 100, + indexMs: Math.round(indexMs), + transactions: transactions.length, + maxTransactionMs: Math.round(transactions.at(-1) ?? 0), + replaceMs: Math.round(replaceMs), + replaceTransactions: replaceTransactions.length, + maxReplaceTransactionMs: Math.round(replaceTransactions.at(-1) ?? 0), + reclaimMs: Math.round(reclaimMs), + indexMb: + Math.round( + ((await checkpointedFileBytes(store.connection, largeIndexPath)) / (1024 * 1024)) * + 100 + ) / 100 + }, + null, + 2 + ) + ) + } finally { + restoreExec() + unregister() + resetTranscriptConsumersForTests() + resetSessionParseCacheForTests() + store.close() + } +} finally { + await rm(large.root, { recursive: true, force: true }) +} diff --git a/config/scripts/telemetry-bundle-constant-patterns.mjs b/config/scripts/telemetry-bundle-constant-patterns.mjs index 04944b7b156..87c2ae43cf7 100644 --- a/config/scripts/telemetry-bundle-constant-patterns.mjs +++ b/config/scripts/telemetry-bundle-constant-patterns.mjs @@ -1,2 +1,6 @@ -export const BUILD_IDENTITY_RE = /\b(?:const|let|var)\s+BUILD_IDENTITY\s*=\s*"(rc|stable)"/ -export const WRITE_KEY_RE = /\b(?:const|let|var)\s+WRITE_KEY\s*=\s*"(phc_[A-Za-z0-9_-]+)"/ +// The unminified bundle keeps these names. Production minification may rename +// them, but the injected identity and key remain adjacent in the declaration. +export const BUILD_IDENTITY_RE = /\b(?:const|let|var)\s+BUILD_IDENTITY\s*=\s*["`](rc|stable)["`]/ +export const WRITE_KEY_RE = /\b(?:const|let|var)\s+WRITE_KEY\s*=\s*["`](phc_[A-Za-z0-9_-]+)["`]/ +export const MINIFIED_TELEMETRY_RE = + /\b(?:const|let|var)\s+[$\w]+\s*=\s*["'`](rc|stable)["'`][\s\S]{0,200}?[,$]\s*[$\w]+\s*=\s*["'`](phc_[A-Za-z0-9_-]+)["'`]/ diff --git a/config/scripts/telemetry-bundle-constant-patterns.test.mjs b/config/scripts/telemetry-bundle-constant-patterns.test.mjs index b8df5ec3d0f..ca87e3ee971 100644 --- a/config/scripts/telemetry-bundle-constant-patterns.test.mjs +++ b/config/scripts/telemetry-bundle-constant-patterns.test.mjs @@ -1,5 +1,9 @@ import { describe, expect, it } from 'vitest' -import { BUILD_IDENTITY_RE, WRITE_KEY_RE } from './telemetry-bundle-constant-patterns.mjs' +import { + BUILD_IDENTITY_RE, + MINIFIED_TELEMETRY_RE, + WRITE_KEY_RE +} from './telemetry-bundle-constant-patterns.mjs' describe('telemetry bundle constant patterns', () => { it.each(['const', 'let', 'var'])('accepts %s declarations', (declaration) => { @@ -13,4 +17,9 @@ describe('telemetry bundle constant patterns', () => { expect('const WRITE_KEY = null').not.toMatch(WRITE_KEY_RE) expect('const WRITE_KEY = "example-key"').not.toMatch(WRITE_KEY_RE) }) + + it('accepts minified adjacent declarations', () => { + const bundle = 'var dde=`stable`,fde=`phc_example-key_123`,pde=(dde===`stable`)' + expect(bundle).toMatch(MINIFIED_TELEMETRY_RE) + }) }) diff --git a/config/scripts/verify-telemetry-constants.mjs b/config/scripts/verify-telemetry-constants.mjs index 3bdcd8b3ec6..836a3e4546f 100644 --- a/config/scripts/verify-telemetry-constants.mjs +++ b/config/scripts/verify-telemetry-constants.mjs @@ -38,7 +38,11 @@ import { join, resolve } from 'node:path' // `node_modules`). If electron-builder ever drops it, promote this to a // direct devDependency in package.json. import { extractFile, listPackage } from '@electron/asar' -import { BUILD_IDENTITY_RE, WRITE_KEY_RE } from './telemetry-bundle-constant-patterns.mjs' +import { + BUILD_IDENTITY_RE, + MINIFIED_TELEMETRY_RE, + WRITE_KEY_RE +} from './telemetry-bundle-constant-patterns.mjs' // Why resolve from import.meta.url instead of cwd: a release runner (or a // developer debugging locally) may invoke this script from a non-root cwd. @@ -156,8 +160,14 @@ function verifyAsar(asarPath) { const buildIdentityMatch = BUILD_IDENTITY_RE.exec(indexJs) const writeKeyMatch = WRITE_KEY_RE.exec(indexJs) + const minifiedTelemetryMatch = MINIFIED_TELEMETRY_RE.exec(indexJs) - if (!buildIdentityMatch) { + // Rolldown renames module-local constants in production output. In that + // form, verify the adjacent injected identity/key declaration instead. + const verifiedIdentity = buildIdentityMatch?.[1] ?? minifiedTelemetryMatch?.[1] + const verifiedWriteKey = writeKeyMatch?.[1] ?? minifiedTelemetryMatch?.[2] + + if (!verifiedIdentity) { console.error(`::error::BUILD_IDENTITY constant missing or unexpected value in ${asarPath}`) const sample = indexJs.match(/.{0,80}BUILD_IDENTITY.{0,80}/g)?.slice(0, 5) ?? [] for (const line of sample) { @@ -165,7 +175,7 @@ function verifyAsar(asarPath) { } return null } - if (!writeKeyMatch) { + if (!verifiedWriteKey) { console.error(`::error::PostHog WRITE_KEY missing from ${asarPath}`) const sample = indexJs.match(/.{0,80}WRITE_KEY.{0,80}/g)?.slice(0, 5) ?? [] for (const line of sample) { @@ -174,7 +184,7 @@ function verifyAsar(asarPath) { return null } - return { asarPath, buildIdentity: buildIdentityMatch[1], writeKey: writeKeyMatch[1] } + return { asarPath, buildIdentity: verifiedIdentity, writeKey: verifiedWriteKey } } // Why verify every match (not just the first): macOS dual-arch produces one diff --git a/config/scripts/windows-cmd-shim-spawn-boundary.test.mjs b/config/scripts/windows-cmd-shim-spawn-boundary.test.mjs index a8c2cb3f4e7..253605781cf 100644 --- a/config/scripts/windows-cmd-shim-spawn-boundary.test.mjs +++ b/config/scripts/windows-cmd-shim-spawn-boundary.test.mjs @@ -46,6 +46,7 @@ const WINDOWS_SHIM_SPAWN_ALLOWLIST = [ 'config/scripts/electron-builder-config.test.mjs', 'config/scripts/ensure-native-runtime.test.mjs', 'config/scripts/live-remote-freeze-rpc.mjs', + 'config/scripts/pty-transcript-secret-scan.test.mjs', 'config/scripts/remote-agent-session-authority-repro.mjs', // Platform-local build paths; the win32 branch is dead code on both. 'config/scripts/build-mac-local.mjs', diff --git a/config/tsconfig.cli.json b/config/tsconfig.cli.json index a23d90e6a1e..70d52e0802c 100644 --- a/config/tsconfig.cli.json +++ b/config/tsconfig.cli.json @@ -11,6 +11,7 @@ "../src/main/agent-hooks/installer-utils.ts", "../src/main/agent-hooks/installer-utils-remote.ts", "../src/main/agent-hooks/local-agent-cli-presence.ts", + "../src/main/agent-hooks/managed-toml-ownership.ts", "../src/main/agent-hooks/managed-agent-hook-controls.ts", "../src/main/agent-hooks/managed-agent-hook-registry.ts", "../src/main/agent-hooks/managed-hook-script-refresh.ts", @@ -73,6 +74,9 @@ "../src/main/codex/codex-wsl-hook-install-plan.ts", "../src/main/codex/config-settings-baseline.ts", "../src/main/codex/config-settings-conflict-resolution.ts", + "../src/main/codex/config-plugin-registration-promotion.ts", + "../src/main/codex/config-toml-plugin-registration-tables.ts", + "../src/main/codex/config-toml-promoted-setting-values.ts", "../src/main/codex/config-settings-promotion.ts", "../src/main/codex/config-settings-promotion-write-target.ts", "../src/main/codex/config-sync-stall.ts", diff --git a/docs/assets/readme-downloads.svg b/docs/assets/readme-downloads.svg index 4331989b66d..68c938d4238 100644 --- a/docs/assets/readme-downloads.svg +++ b/docs/assets/readme-downloads.svg @@ -1,5 +1,5 @@ - - downloads: 47m + + downloads: 49m @@ -15,7 +15,7 @@ downloads downloads - 47m - 47m + 49m + 49m diff --git a/docs/reference/agent-pty-transcript-capture.md b/docs/reference/agent-pty-transcript-capture.md new file mode 100644 index 00000000000..934f0028a93 --- /dev/null +++ b/docs/reference/agent-pty-transcript-capture.md @@ -0,0 +1,129 @@ +# Capturing an agent PTY transcript + +Orca's readiness and blocked-prompt rules are text rules over what an agent CLI paints on a +terminal. They are only as good as the screens they were written against. This is how to record +one, byte for byte, so a rule can be pinned to evidence instead of to a remembered screen. + +Related: [`antigravity-readiness-evidence.md`](./antigravity-readiness-evidence.md) names the +specific Antigravity transcripts that are still missing and what each one decides. + +## The recorder + +``` +node config/scripts/capture-agent-pty-transcript.mjs --name [options] -- [args...] +``` + +It allocates a real PTY, spawns the agent inside it, mirrors the session to your terminal so you +can drive it by hand, and appends every byte it receives to +`src/main/runtime/__fixtures__/.txt`. It does not strip escapes, fold `\r`, rewrap +lines, or normalise anything — the file is what the terminal received. + +- **Ending a capture:** press Ctrl+]. The recorder consumes that key and + never forwards it, which is the only way to end a capture _while a dialog still owns the + screen_. Quitting the agent instead would first dismiss the dialog you came to record. +- `--cols N --rows M` pin the PTY size (default: your terminal's). Wrapping is part of the + evidence, so record the size — the sidecar does it for you. +- `--duration S` stops unattended after S seconds, for a screen that needs no interaction. +- `--send ":"` types into the PTY at a fixed offset, repeatable, with `\r` `\n` `\t` `\e` + escapes. A dialog capture has to be driven, and an unattended run (CI, or an agent) has no TTY to + type into; the keystrokes ride the same PTY a human's would. For example, the committed + `antigravity-dialog-model-picker.txt` was recorded with + `--duration 24 --send "14000:/model" --send "16000:\r"`, which leaves the picker owning the + screen when the capture stops. +- `--note ""` records the account type, plan, model and CLI version in the sidecar. +- `--out ` writes outside the fixture directory (use it for a first dry run). + +Each capture also writes `.meta.json` with the timestamp, platform, command, +PTY size, note and exit code. Commit it with the transcript; the version and account type behind +a screen are not recoverable from the bytes. + +**Prerequisite:** `node-pty` must be built for plain Node: + +``` +node config/scripts/ensure-native-runtime.mjs --runtime=node +``` + +Orca itself does not need to be running, and the recorder never touches Orca state. + +### Platform notes + +- **macOS / Linux:** nothing special. `TERM=xterm-256color` is set for the child. +- **Windows:** run it from Windows Terminal / PowerShell, not a Git Bash (MSYS) pane — MSYS + rewrites arguments that start with `/`, which mangles the `cmd.exe /c` hand-off. A `.cmd` or + `.bat` agent shim cannot be spawned by node-pty directly, so the recorder routes those through + `cmd.exe` for you. +- **WSL:** capture _inside_ the distro (run the recorder from the distro's checkout). Recording + `wsl.exe` from the Windows side adds the login-shell banner to the transcript. +- **SSH:** record on the execution host. A transcript recorded locally is not evidence about what + a remote agent prints. + +## Privacy: scrub before committing + +A live agent screen routinely contains things that must not enter git history: + +| Scrub | Why | +| ---------------------------------------------------------------------- | ---------------------------------------------------- | +| Account email / sign-in identifier | The account row on a ready screen prints it verbatim | +| Org, tenant or team name | Identifies a customer | +| Machine hostname and OS username | Appear in prompts, paths and the OSC title | +| Absolute home paths (`/Users/`, `C:\Users\`) | Contain the username | +| JWTs, `AIza…` keys, `1//…` refresh tokens, `Bearer …`, `sk-…`, `ghp_…` | Live credentials; a sign-in screen can echo one | +| Private repo, branch and ticket names | Leak roadmap detail | +| Anything you pasted into the agent during the capture | You typed it; it is in the transcript | + +The recorder scans the file as soon as the capture ends and prints every hit with a line and +column. To scrub: + +``` +node config/scripts/capture-agent-pty-transcript.mjs --scan src/main/runtime/__fixtures__/.txt --redact +``` + +Redaction replaces each finding with a **same-length** placeholder (`u…u@example.com`, `XXXX…`). +Length matters: a transcript's value is its exact wrapping and column alignment, and a shorter +replacement reflows the screen and destroys the evidence. + +### Verify it is gone + +1. `node config/scripts/capture-agent-pty-transcript.mjs --scan src/main/runtime/__fixtures__/.txt` + must print `clean` and exit `0`. It recognises its own placeholders, so a scrubbed file passes. +2. Grep for the specifics the scanner cannot know: + `rg -n -i -- "$(whoami)|||" src/main/runtime/__fixtures__/.txt` +3. Read it once with escapes visible: `LC_ALL=C cat -v src/main/runtime/__fixtures__/.txt`. + The scanner matches shapes; only a human catches a project name. +4. Check the sidecar too — `--note` text is free-form and is committed. + +`config/scripts/pty-transcript-secret-scan.test.mjs` re-scans every committed +`__fixtures__/*.txt`, so a transcript that skips step 1 fails the suite. + +## Consuming a transcript in a test + +Feed the raw bytes through the runtime rather than into a matcher directly: escape handling, +tail retention and title tracking all live in `onPtyData`, and a rule tested on pre-normalised +text is tested on something no pane ever sees. + +`src/main/runtime/agent-transcript-pane-test-harness.ts` builds the pane; +`src/main/runtime/terminal-interactive-wait-visibility.test.ts` (cursor-agent) and +`src/main/runtime/antigravity-readiness-transcripts.test.ts` (Antigravity) are the two consumers. + +## Worked example: the Antigravity captures + +The six committed `antigravity-*.txt` fixtures were recorded this way on macOS against +`agy` 1.1.25. Two points generalise: + +- **Reach a state without mutating the operator's config.** The ready-screen captures ran in a + directory the CLI already trusted, so no trust answer was written. Where a dialog could only be + reached by signing the operator out or deleting their settings, it was left uncaptured and + recorded as such rather than forced. +- **An environment variable is a legitimate capture knob** where a setting is not. + `AGY_CLI_HIDE_ACCOUNT_INFO=1` produced a second ready screen with no account row, which is + evidence no amount of reasoning about the first screen could have supplied. It changes nothing + on disk. + +## Known gap in the existing captures + +The three `cursor-agent-*.txt` fixtures contain **no escape bytes and no carriage returns**. +Whatever produced them went through a renderer and a clipboard, so they preserve wording and +box-drawing glyphs but not the caret, the cursor moves, the repaints, or whether the CLI uses the +alternate screen buffer. They are good enough for the wording-based rules built on them and are +not evidence for anything else. New captures made with this recorder keep those bytes; the +Antigravity scaffold asserts their presence so a pasted screen cannot pass as a capture. diff --git a/docs/reference/agent-session-search-query-tuning.md b/docs/reference/agent-session-search-query-tuning.md new file mode 100644 index 00000000000..9e18097cb9e --- /dev/null +++ b/docs/reference/agent-session-search-query-tuning.md @@ -0,0 +1,219 @@ +# Agent session search: query tuning + +What a search costs, and what the knobs in `src/main/ai-vault-search/session-search-engine.ts` +buy. Every number here comes from `config/scripts/session-search-query-benchmark.ts` +over the synthetic corpus in `session-search-synthetic-corpus.ts`, except the +`conversation_fts` shoot-out, which writes its own corpus because the answer +turns on how much of a transcript is tool output. Nothing in this file was +measured against a real transcript, and neither benchmark must ever be pointed +at one. + +## Running it + +The benchmark is a top-level-await module that imports the main-process tree by +extensionless path, so it needs a bundler-backed runner rather than bare `node`: + +```sh +cat > src/main/ai-vault-search/zz-bench.test.ts <<'EOF' +import { it } from 'vitest' +it('runs', { timeout: 1_800_000 }, async () => { + await import('../../../config/scripts/session-search-query-benchmark') +}) +EOF +BENCH_OUT=/tmp/ss-query-bench.json pnpm test src/main/ai-vault-search/zz-bench.test.ts +rm src/main/ai-vault-search/zz-bench.test.ts +``` + +The `conversation_fts` shoot-out below runs the same way, importing +`config/scripts/session-search-conversation-fts-benchmark` instead, with +`CORPUS_MB` and `TOOL_SHARE` to size and shape its corpus. `config/scripts` is +not inside any typecheck project, so while that throwaway test exists `tsc` +reports TS6307 for each script it pulls in; delete it and the run is clean +again. + +`BENCH_OUT` exists because vitest intercepts `console.log`; the report is written +to that path as well as printed. + +## Scope: what the second FTS table buys a reader + +Corpus: 40 synthetic Claude transcripts, 10.5 MB, 9,600 messages, indexed through +the real store. Eight queries, one per rung of the route ladder plus the two +shapes that skip it; 5 warm-up runs and 25 samples each. Apple silicon, warm page +cache, machine otherwise idle. Milliseconds, and p95 over 25 samples moves +several milliseconds run to run if anything else is competing for the disk. + +| Scope | p50 | p95 | +| -------------- | ---- | ---- | +| `all` | 7.22 | 8.94 | +| `conversation` | 5.33 | 7.86 | + +Per query, `all` then `conversation` (p50 / p95): + +| Query | `all` | `conversation` | +| ------------------------------------------------ | ------------ | -------------- | +| `"terminal reattach"` (phrase) | 5.24 / 8.42 | 2.97 / 3.24 | +| `resolveTerminalPath` (identifier) | 7.55 / 8.94 | 6.47 / 6.72 | +| `src/main/…/session-transcript-reader.ts` (path) | 8.69 / 10.12 | 7.78 / 8.04 | +| `why is the daemon snapshot stale` (prose) | 7.84 / 8.57 | 5.90 / 7.01 | +| `reattahc worktre` (typo repair) | 7.30 / 7.39 | 5.53 / 5.89 | +| `index` (common term) | 5.45 / 5.66 | 3.81 / 4.02 | +| `repo:app-3` (operator only) | 0.12 / 0.16 | 0.10 / 0.10 | +| `worktree` scoped to one cwd | 1.47 / 1.63 | 1.25 / 1.49 | + +Reading it: + +- `conversation` is about 1.4x faster at p50 and 1.1x at p95, and it is a column + filter over the same table rather than a table of its own. Narrowing to the + two prose columns is what buys the gap: fewer postings to score. It is also + the scope where a match is something a person wrote rather than something a + tool printed. +- A `scopePaths` query is the cheapest real search on the page. It is the one + narrowing SQL can express exactly, so it seeks `sessions_cwd_key` and hands + ranking a small candidate set. +- The operator-only figure is a floor, not a typical cost. `repo:` and `path:` + are applied in JS over retrieved rows (see `session-search-row-filter` for why + they cannot be pushed into SQL), so their cost tracks how many sessions the + walk has to read before it fills a candidate set. This corpus has 40 sessions, + which is one page of that walk; an index where few sessions match the operator + will read up to the ceiling in `session-search-retrieval` instead. + +## What the conversation scope costs at real corpus size + +`conversation` was a second FTS table holding a copy of the two prose columns. +It is a column filter now — `{user_text assistant_text}: (…)` with bm25 weights +that zero the other two — and PR 2 deleted the table on the strength of the +shoot-out this section used to hold: the filter came in at 1.16-1.36x the p95 of +the dedicated table, under the 2x bar, while the table cost a tenth of the index +to maintain. What follows is what the shipped schema actually does, measured +again on the same corpus after the table went and tool rows were capped. + +Corpus: Claude transcripts from `config/scripts/session-search-tool-heavy-corpus.ts`, +105 MB, indexed through the real store, at two points in the 80-97% band a real +transcript tree sits in. Half the tokens in tool output are words the +conversation also uses, so a conversation term really does have postings the +filter must discard. Twenty queries per rung, both scopes interleaved query by +query, warm cache; `config/scripts/session-search-scope-benchmark.ts`, run twice. + +| Tool share | Rung | `all` p50 / p95 | `conversation` p50 / p95 | +| ---------- | ------ | --------------- | ------------------------ | +| 86% | phrase | 16.69 / 17.48 | 13.08 / 13.52 | +| 86% | or | 31.91 / 35.74 | 22.25 / 23.87 | +| 86% | and | 70.04 / 74.00 | 53.47 / 59.39 | +| 93% | phrase | 9.14 / 13.36 | 7.23 / 8.51 | +| 93% | or | 16.46 / 18.70 | 12.34 / 14.88 | +| 93% | and | 39.65 / 43.44 | 31.05 / 32.92 | + +Three things to read out of it. + +**The filter is a win, not a cost.** Every rung is faster narrow than wide, by +1.2x to 1.4x at p50. The shoot-out compared the filter against a table built for +exactly this query; against the wide table it replaces, it does what the second +table did, which is read fewer postings. + +**The `and` rung is where the corpus size shows.** Those queries are eight terms, +chosen so no ordered run that long occurs and the phrase rung has to miss; a +real two-term AND sits nearer the phrase row. It is also the noisiest: the +second run's p95 reached 140 ms on one bucket, which is what twenty samples of a +70 ms query buys. Read the p50 column. + +**The index is far smaller than the shoot-out's was.** 57 MB at 93% tool output +and 103 MB at 86%, against roughly 150 MB for `messages_fts` alone before PR 2 +capped an indexed tool row at 3,072 characters. Most of a tool-heavy transcript +is now not in the index at all, which moves every number above and is the larger +effect of the two. + +What is **not** measured here is relevance, and the column filter does carry one +ranking difference the deleted table did not. FTS5's bm25 normalises by the +whole row's length and has no per-column length, so two rows with identical +prose score differently when one also holds tool output. The rowid set is +unchanged, which is what the deletion was decided on; the order within it can +move. `session-search-engine.test.ts` pins the direction. + +## `sessionCandidateLimit` + +The reviewer's F13: this is a tunable default, not a constant. It bounds how many +sessions the SQL hands ranking, so it bounds both retrieval cost and how deep a +caller can page before the answer simply stops. + +The limit only costs anything once more sessions match than the limit allows, so +this is measured over a second corpus: 2,500 one-turn transcripts, 10.9 MB, every +one of them matching the query. Limits are interleaved sample by sample, because +run back to back the first configuration pays for every page the OS cache had not +seen and the ordering alone moves p95 further than the limit does. + +| Limit | p50 | p95 | Pages of 20 a caller can reach | +| ----- | ----- | ----- | ------------------------------ | +| 200 | 6.85 | 7.21 | 10 | +| 600 | 7.93 | 8.36 | 30 | +| 1200 | 9.55 | 10.53 | 60 | +| 2400 | 12.32 | 13.45 | 120 | + +600 is the default: it costs about 16% over 200 at p50 and buys three times the +reachable depth, and the curve only turns steep past 1200. A host with a much +larger index can raise it; the result's `truncated.candidates` says when the limit +was the thing that cut the answer, so a caller never has to guess. + +What is **not** measured here is relevance. These numbers say what a limit costs, +not what it retrieves. The MRR figures quoted in the BM25 weights +(`session-search-retrieval.ts`) and in the identifier shadow column +(`session-search-identifier-split.ts`) come from the original retrieval shoot-out +on real transcripts and are not reproducible from this repository. Any change to +the limit justified on relevance grounds needs an eval set, not this benchmark. + +## What typo repair costs + +The repair is the one rung whose cost tracks the size of the vocabulary rather +than the size of a result. It only runs for a term the scope has no posting for, +so an ordinary query never pays it; a query of nonsense pays it once per term. + +Measured over a synthetic vocabulary of 1.6 M distinct terms, every term in two +rows so none is filtered out: + +| Query | p50 | +| -------------------------------------- | ------ | +| one known term (no repair) | 11 ms | +| one unknown term | 10 ms | +| 39 unknown 12-character terms (480 ch) | 387 ms | +| 12 unknown 40-character terms | 99 ms | + +Two things follow. The cost is linear in unknown terms and in vocabulary size, +and `search` is synchronous, so a 512-character query of nonsense holds the +thread for a third of a second on an index that large. And the scoped-count fix +made this cheaper rather than dearer — it was 737 ms before — because ordering +the vocabulary scan by term drops the sort that ordering by `doc` required, and +the counts it added are at most eight bounded probes per prefix. A cap on +unknown terms per query is recorded as a follow-up in the split plan. + +## Page warmup, dropped + +PR 2 deferred `warm()` — a sliced read of `messages` that pulls its pages into +the OS cache before the first query — to whoever knew which pages a read +touches. It is not re-added here, for two reasons. The measurement that +justified it (first query 1.3 s to 0.45 s) was on a 4 GB index, and neither +corpus in this file is within an order of magnitude of that, so PR 4 cannot +show a win: removing the call moved the 10.5 MB corpus's p50 by less than the +run-to-run spread. And it is a cancellable background pass, which needs an owner +with a lifecycle; a query library that holds no timers has nothing to hang the +`stopped()` on, and a fire-and-forget async read from a synchronous `search` is +a rejection nothing can supervise. It belongs with the indexer in PR 3b, which +already owns starting and stopping work. + +## Not settled here + +Which process may open, unlink and rebuild the index is PR 3b's decision. A +second handle that finds an older schema version replaces the file while a live +store keeps answering from the unlinked inode, and this PR is what first makes +that reachable, because it is the first thing that reads. What PR 4 does is +refuse to make it worse. The engine restores its derived vocabulary and generation +triggers before a search. A missing `messages_fts` fails clearly; the connection +owner must rebuild the source index. There is no degraded-search capability state +or query logging. Logging can be added by a caller when an evaluation consumer exists. + +Each search checks the generation before retrieval and after its final content +read. A concurrent commit rejects the page with `stale-generation`, including a +first page without a cursor. The caller can retry from page one. No long-lived +read transaction is needed, and a mixed page is never returned as a valid snapshot. + +Repository/path operators are applied before a phrase or AND route is accepted. +Candidate truncation remains explicit, including when an earlier route reached +its cap but had no eligible sessions. diff --git a/docs/reference/agent-status-store.md b/docs/reference/agent-status-store.md index f1068a0d993..8f1439c2122 100644 --- a/docs/reference/agent-status-store.md +++ b/docs/reference/agent-status-store.md @@ -12,7 +12,7 @@ this order, each independently shippable: 3. shared: one worktree-status rollup and one freshness rule for every reader. The PR that carries this document is PR 1a. Sections below are grouped under -the step that delivers them; only PR 1a has landed. +the step that delivers them; PR 1a and PR 1b have landed. ## The problem this solves @@ -24,11 +24,11 @@ the structured-session mapping and nothing else. An audit on 2026-09-09 found six producers and three consumers, and three separate copies of the same row inside the main process alone: -| Main-process copy | Keyed by | Owned by | Persisted | Evicted | -| -------------------------------------- | --------- | ---------------------------------------------------------- | ------------------- | ----------------------------- | -| hook server `lastStatusByPaneKey` | paneKey | `src/main/agent-hooks/server.ts` | `last-status.json` | tab close, pty exit, hydrate | -| runtime `RuntimeAgentRowStore` | paneKey | `src/main/runtime/runtime-agent-row-store.ts` | no | pty exit only | -| structured feed `published` | sessionId | `src/main/native-chat/agent-session-wire/structured-agent-session-status-feed.ts` | no | never (a broadcast cache) | +| Main-process copy | Keyed by | Owned by | Persisted | Evicted | +| --------------------------------- | --------- | --------------------------------------------------------------------------------- | ------------------ | ---------------------------- | +| hook server `lastStatusByPaneKey` | paneKey | `src/main/agent-hooks/server.ts` | `last-status.json` | tab close, pty exit, hydrate | +| runtime `RuntimeAgentRowStore` | paneKey | `runtime-agent-row-store.ts` (deleted in PR 1b) | no | pty exit only | +| structured feed `published` | sessionId | `src/main/native-chat/agent-session-wire/structured-agent-session-status-feed.ts` | no | never (a broadcast cache) | The second copy is a duplicate write: the OSC status parsed in main is forwarded to the hook server _and_ retained in the runtime store from the same @@ -92,14 +92,14 @@ The structured feed keeps its job of projecting a session's journal into a summary and streaming it to subscribers. On every publish it additionally ingests the summary into the hook server as a status row: -| Row field | From | -| ----------------- | ------------------------------------------------------------- | -| `paneKey` | `structuredAgentSessionPaneKey(tabId, sessionId)`, the key the renderer already uses; its leaf is UUID-shaped so pane-key validation accepts it | -| `tabId` | `structuredAgentSessionTabId(sessionId)` | -| `worktreeId` | `summary.workspaceId` (a folder workspace id is a valid value) | -| `state` | `structuredAgentSessionStatusState(summary.status)`, the mapping #19217 shared | -| `structuredHost` | `'owned'` while `summary.hostExecutionOwned` is set, otherwise `'held'`; `worktree ps` derives its row's `structuredHostOwned` from it | -| prompt, tool, last message, model, provider session | the summary's fields | +| Row field | From | +| --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| `paneKey` | `structuredAgentSessionPaneKey(tabId, sessionId)`, the key the renderer already uses; its leaf is UUID-shaped so pane-key validation accepts it | +| `tabId` | `structuredAgentSessionTabId(sessionId)` | +| `worktreeId` | `summary.workspaceId` (a folder workspace id is a valid value) | +| `state` | `structuredAgentSessionStatusState(summary.status)`, the mapping #19217 shared | +| `structuredHost` | `'owned'` while `summary.hostExecutionOwned` is set, otherwise `'held'`; `worktree ps` derives its row's `structuredHostOwned` from it | +| prompt, tool, last message, model, provider session | the summary's fields | Sessions with no persisted turn (`status === null`) produce no row, matching what the chat shows. When the host revokes live ownership the row is re-set @@ -151,7 +151,7 @@ sits at the file-length cap. The structured adapter added in #19217 is deleted, and structured rows reach `worktree ps` through the same snapshot as every other row. The retained-versus-hook reconciliation in `collectRuntimeWorktreePtyAgentSources` -stays until PR 1b removes the store that feeds it. What this step settles is +stayed until PR 1b removed the store that fed it. What this step settles is the admission gate that decides which rows a worktree listing may show: - a hook or OSC row needs its tab mirrored or a connected pty, as today, and @@ -186,22 +186,80 @@ pane key two writers. Removing that filter is the first step of PR 2. ## PR 1b: the runtime's retained row store is deleted -Not yet implemented; `RuntimeAgentRowStore` and the retained-versus-hook -reconciliation it feeds are both still in place after PR 1a. +Landed. `RuntimeAgentRowStore` is gone, and with it the retained-versus-hook +reconciliation in `collectRuntimeWorktreePtyAgentSources`. The hook server's +store is now the only main-process copy of a PTY agent's row. -`RuntimeAgentRowStore` keeps the same payload the hook server already holds. -Its only extra is the pty id, used to clear rows on exit and as a fallback key -for the mobile projection. PR 1b will stamp `terminalHandle` on OSC-ingested -rows from the runtime event's `ptyId`, and rewrite the three readers over the -hook server's snapshot: +### The five call sites -- `worktree ps` reads `getStatusSnapshot()` directly; -- `getFreshExplicit` already consults hook rows; it drops the retained input; -- `getFreshForMobile` matches on pane key, then on `terminalHandle`. +| Call site | Before | After | +| ------------------------------------------------------------------------------ | --------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `orca-runtime-create-terminal-side-effect-command-code-detector.ts` `retain()` | second write of the OSC payload already sent to the hook server | deleted; the event now carries the pane's `terminalHandle` and the hook ingest keeps the only copy | +| `...command-code-detector.ts` `clearPty()` | drops rows on pty exit | deleted; pane teardown already clears the hook row | +| `orca-runtime-get-worktree-ps.ts` `values()` | fed `retainedSnapshots` | deleted; the reader keeps only `hookSnapshots` | +| `orca-runtime-serialize-agent-prompt-submission.ts` `getFreshExplicit()` | retained row first, hook rows second | `selectFreshExplicitAgentStatus`, hook rows only | +| `orca-runtime-prune-mobile-session-tab-group-layout.ts` `getFreshForMobile()` | pane key, then pty id | `selectFreshAgentRowForMobileTab`: pane key, then `terminalHandle` | -One behavior change will follow and is intended: a row the user dismisses on -the desktop disappears from `worktree ps` and the phone at the same time, -instead of lingering until the pty exits. +Both readers moved into `runtime-hook-agent-row-selection.ts`, which also owns +`RuntimeAgentRowSnapshot` now that nothing retains one. + +### `terminalHandle` is the row's join back to its terminal + +The retained store's only real extra was the pty id, and two readers used it. +The plan said to stamp the event's `ptyId` into `terminalHandle`; that was +wrong. A terminal handle (`term_`) and a pty id are different +identifiers, and `getFreshExplicit` was already comparing hook rows against a +real handle. What landed instead: + +- `AgentHookEventPayload` and the runtime's terminal-status event gained an + optional `terminalHandle`. The detector resolves it once per chunk through + `getAgentStatusTerminalHandleForPaneKey` — the same lookup the renderer-facing + IPC boundary already runs for every row, so the two surfaces cannot disagree + about which terminal a pane is. +- `applyNormalizedStatus` carries the handle forward when an incoming event + resolves none. Only main's OSC parse can resolve one, so an HTTP hook post for + the same pane would otherwise erase it. +- It is never persisted. A handle belongs to the runtime that issued it, and a + hydrated one could only rejoin a row to somebody else's terminal. +- `toAgentStatusIpcPayload` publishes it, which also makes `getFreshExplicit`'s + long-dead handle comparison live: the runtime reads raw snapshot rows, and + before this nothing ever stamped the field on them. + +`worktree ps` uses it too. `ConnectedPtyEvidence` traded its flat `ptyIds` set +for `ptyIdByTerminalHandle`, so a row still resolves the connected PTY behind +it — which is both the working-terminal rollup's match key and the last rescue +for a row whose pane binding was nulled by a controller incarnation change. + +### The change detector had to move with the store + +`retain()` was not only a store: its boolean return was the signal that +republished `session.tabs` for a status-only transition, which no title change +covers (#7970). `hook-status-session-tabs-invalidation.ts` already mirrors that +projection change set, including restore provenance and terminal-handle joins, +so the replacement was to route the signal off the store rather than build a +second comparator. +`installHookStatusSessionTabsRepublish` now owns all three arms — enriched +status, pane clear, and the status-drop tap a dismissal emits — and both hosts +install it. + +### Both hosts, not just the desktop one + +`orcad` constructed its runtime with no `onTerminalAgentStatus`, so main's OSC +parse never reached the store there and the retained copy was the only carrier. +Deleting it without wiring orcad would have made a headless host list no PTY +agents at all. `orcad-entry.ts` now binds the producer and installs the +republish signal, alongside the snapshot and structured sink it already had. + +### The intended behavior change + +A row the user dismisses on the desktop leaves `worktree ps` and the phone at +once, instead of lingering until the pty exits. One store means one dismissal. + +Legacy numeric pane keys remain a bounded compatibility case. Persisted layouts +register aliases to their stable leaf owners; an in-process OSC observation may +also retain a numeric key only when the runtime supplies the matching tab, PTY, +and terminal handle. HTTP and relay ingress still require a stable key or a +registered alias, and numeric rows are never persisted. ## PR 2: the renderer subscribes @@ -211,14 +269,14 @@ unmount cleanup becomes a tab-close signal to the host. The IPC applicator is the single writer for observed status. The 2026-09-09 audit sorted the other writers: -| Writer | Disposition | -| --------------------------------------------------------------- | -------------------------------------------------- | -| Command Code output seeds, parked-pane seeds, pty-exit removal | delete; main already emits the same facts | -| structured bridge status writes | delete; main now publishes the row | -| launch placeholder seeds (a user launched an agent with a prompt) | keep for now; main holds the launch config and can seed later | -| dismissal, acknowledgement, unmount | keep; user facts and component lifecycle | -| remote-runtime OSC parse (bytes never transit local main) | keep, fenced behind the host's published row once the host is new enough; rule 3 of the wire doc applies | -| web-session mirror receipt clock | keep; the decay rule needs both clocks from one machine | +| Writer | Disposition | +| ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | +| Command Code output seeds, parked-pane seeds, pty-exit removal | delete; main already emits the same facts | +| structured bridge status writes | delete; main now publishes the row | +| launch placeholder seeds (a user launched an agent with a prompt) | keep for now; main holds the launch config and can seed later | +| dismissal, acknowledgement, unmount | keep; user facts and component lifecycle | +| remote-runtime OSC parse (bytes never transit local main) | keep, fenced behind the host's published row once the host is new enough; rule 3 of the wire doc applies | +| web-session mirror receipt clock | keep; the decay rule needs both clocks from one machine | The Command Code done-settle window is renderer policy with no main equivalent. PR 2 either moves it into main's detector or leaves it, and says @@ -242,14 +300,55 @@ call it. - Hydration honesty: a restored non-done row is `restoredUnconfirmed` and is never fresh. +## PR 1b reliability contract + +- **Invariant (`agent-session.status-host-ownership`):** each execution host has + one agent-status store; OSC, hooks, and structured sessions write it, while + desktop, `worktree ps`, and mobile only project it. Dismissal, certified PTY + exit, and provider-generation replacement remove the same row everywhere; + transport loss alone removes nothing. +- **Failure source:** the deleted runtime row store duplicated OSC observations, + keyed them by a different terminal identity, and outlived a dismissal from the + hook store. Relay replay could also make old evidence look fresh when readers + used its new delivery timestamp. +- **Oracle:** one OSC observation appears through the hook snapshot in + `worktree ps` and mobile, and one store dismissal removes it from both without + stopping the PTY. Focused tests also require leaf/incarnation-handle rejoin, + legacy numeric-pane compatibility, certified-exit and provider-generation + cleanup, evidence-age freshness, and exactly-once startup/stop teardown. +- **Gate:** `terminal-performance.osc-status-scan-budget` covers the unchanged + bounded OSC parser and the runtime projection. There is not yet a dedicated + blocking multi-surface status-store gate; the focused suites below are the + accepted gap until they accumulate reliability-gate soak evidence. +- **Provider/platform coverage:** local and daemon-backed PTYs are covered by + runtime tests, and SSH relay loss/replay semantics by relay integration tests. + The projection is shared by git worktrees and folder workspaces. WSL uses the + same store and admission code but has no live run here; Linux and Windows + runtime execution, native mobile clients, and mixed-version paired clients + remain validation gaps. +- **Performance budget:** publication stays event-driven with no new polling or + subprocesses. One mobile projection clones the status snapshot once, builds + pane/handle indexes once, and has a deterministic call-count test; lifecycle + cleanup is bounded by the existing status and handle inventories, and orcad + tests prove listeners clean up once on failed startup and repeated stop. +- **Diagnostics:** existing hook-listener errors name the pane and PTY, while + status-store tests pin delivery versus evidence clocks. No new telemetry or + raw terminal data is emitted. +- **Residual gaps:** rendered Electron/mobile behavior, live SSH reconnect, and + Linux/Windows/WSL execution require the platform QA pass. The current + cross-version gate does not cover `session.tabs` content. + ## Verification - Unit: ingest a structured summary and read it back through `getStatusSnapshot`, `worktree ps`, and the mobile projection; assert the serializer never writes a row carrying `structuredHost`; assert a hydrated file that somehow contains one is dropped. -- Unit: the existing `worktree ps` suites pass unchanged, which is the - characterization that will show PR 1b's deletion of the retained store - changed no listing. +- Unit: the `worktree ps` suites written against the retained store are rewired + to a real `AgentHookServer` (`agent-status-store-wiring.test-fixture.ts`) + rather than deleted, so each still asserts the listing behavior it named. The + dismissal change is pinned end to end in + `orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts`, which fails with + the retained store restored. - Live: the parity check from #19217 (working, done, close, reload) repeated against the merged store, with both surfaces read from the one row. diff --git a/docs/reference/antigravity-readiness-evidence.md b/docs/reference/antigravity-readiness-evidence.md new file mode 100644 index 00000000000..0010fa76ded --- /dev/null +++ b/docs/reference/antigravity-readiness-evidence.md @@ -0,0 +1,263 @@ +# Antigravity readiness: what the transcripts show + +`findAntigravityReadyPromptIndex` in `src/main/runtime/terminal-wait-detection.ts` decides whether +an Antigravity pane is ready for a prompt. It has been written five times, each version tuned +against a five-line screen typed from memory into a `.spec.ts` fixture. Three of the first four +were found worse than the bug they replaced, and the fifth was reverted. + +Real transcripts now exist. They were recorded from a live `agy` on macOS with +[`agent-pty-transcript-capture.md`](./agent-pty-transcript-capture.md) and are committed under +`src/main/runtime/__fixtures__/`. `src/main/runtime/antigravity-readiness-transcripts.test.ts` +replays them through the runtime. + +**Headline: on real output the current detector is inverted.** It refuses a genuinely ready screen +and accepts a live model picker. The five attempts argued about which extra condition to add; none +of them had noticed that the condition they all shared — a line beginning with the model name — +never matches a real Antigravity ready screen at all. + +## Versions + +| Thing | Value | +| ------------------------- | ----------------------------- | +| `agy --version` | `1.1.25` | +| Banner printed by the TUI | `Antigravity CLI 1.2.0` | +| Captured | 2026-09-10, macOS, 120x40 PTY | + +The binary and its own banner disagree. Any rule keyed to a version string must read the banner, +not `--version`, and must tolerate the two disagreeing. + +## What the captures are + +| Fixture | What it is | +| -------------------------------------------- | --------------------------------------------------------- | +| `antigravity-ready-api-key-gemini-model.txt` | Ready screen, API-key identity, Gemini 3.7 Flash (Low) | +| `antigravity-ready-account-info-hidden.txt` | The same ready screen with `AGY_CLI_HIDE_ACCOUNT_INFO=1` | +| `antigravity-dialog-trust-workspace.txt` | Workspace trust dialog, live and unanswered | +| `antigravity-dialog-model-picker.txt` | `/model` picker, live and unanswered | +| `antigravity-dialog-command-palette.txt` | Slash-command palette, live and unanswered | +| `antigravity-dialog-dismissed.txt` | `/model` picker dismissed with esc, then settled | +| `antigravity-busy-mid-turn.txt` | A real turn, recording stopped while the spinner was live | +| `antigravity-busy-turn-ended.txt` | The same turn after it ended and the composer returned | + +## What could not be captured, and why + +Nothing below was faked. Each is a case the recorder could not reach without changing the +operator's account state or configuration, which is out of bounds. + +| Missing | Why | +| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `antigravity-ready-business-non-gemini.txt` | This machine has no OAuth session — the CLI prints _"You are currently not signed in"_ and authenticates from `GEMINI_API_KEY`. Reaching a Business ready screen means signing someone in. | +| A non-Gemini model on any ready screen | `agy models` offers 11 models, all Gemini, and `settings.json` pins `modelProvider: gemini`. A non-Gemini row is not reachable from this account. | +| `antigravity-dialog-sign-in.txt` | Unsetting `GEMINI_API_KEY` does not reach the sign-in dialog; the CLI refuses to start because `modelProvider` is pinned. Reaching it means editing the operator's `settings.json`. | +| `antigravity-dialog-theme-picker.txt` | There is no `/theme` command in 1.2.0 (`Unknown command: /theme`). The picker appears only in first-run onboarding, which means deleting the operator's config. | +| `antigravity-dialog-privacy-notice.txt` | First-run onboarding, as above. | +| `antigravity-dialog-update-banner.txt` | Cannot be forced; no update was pending during the session. | + +Each remains as a named, skipping case in the suite so it is visible rather than forgotten. + +## What the transcripts show + +### 1. The ready screen's model row is not at the start of a line + +The ready screen prints a block-glyph logo down the left, and the identity, model and path rows are +painted **on the same physical lines as the logo**. What Orca derives is: + +``` +▀▀▀▀▀▀ Gemini API key +▀▀▀▀▀▀▀▀ Gemini 3.7 Flash (Low) +▄▀▀ ▀▀▄ ~ +``` + +The detector requires `normalized.startsWith('gemini', trimmedStart)` on a trimmed line. The +trimmed line starts with `▀`. It never matches. Measured three ways on the real screen: + +| Input | `isKnownReadyPromptPreview` | +| ------------------------------------------------------ | --------------------------- | +| Real ready screen | `false` | +| The same screen with the logo glyphs stripped | `true` | +| Real ready screen followed by the live `/model` picker | `true` | + +So the logo — decoration, and suppressible with `AGY_CLI_HIDE_LOGO` — is what decides readiness +today, and the live dialog is what supplies the model line the ready screen could not. + +### 2. The dialog is what satisfies the model rule + +`/model` prints its options one per line: + +``` +Gemini 3.8 Flash +> Gemini 3.7 Flash (current) +Gemini 3.1 Pro +``` + +Those lines _do_ begin with `Gemini`, and a bare `>` composer line sits earlier in the same tail +from before the picker opened. Both halves of the rule are satisfied **while a dialog owns the +screen**, and the pane reads ready. This is the false-ready hazard the last three attempts were +each trying to close, reproduced from a real capture. + +### 3. `>` is the dialog selection marker, not only the composer caret + +Every dialog uses `>` to mark the highlighted row: `> Yes, I trust this folder`, +`> Gemini 3.7 Flash (current)`, `> /add-dir`. The idle composer is a line whose whole trimmed +content is `>`. That distinction is the only thing separating them, which means the relaxation +proposed in PRs #15840 and #15852 — accept any line _beginning_ with `>` — would make the trust +dialog and the model picker read as ready. On 1.2.0 the idle composer is a bare `>`; those PRs' +1.1.17 mode-banner claim could not be reproduced here and may be mode-specific. + +### 4. There is no email account row, and the row can be switched off entirely + +For an API-key user the identity row reads literally `Gemini API key`. There is no `@`, no +domain, nothing an account-row rule can key on. Separately, `AGY_CLI_HIDE_ACCOUNT_INFO=1` — a +supported environment variable in the binary — removes the row from a fully ready screen, which +`antigravity-ready-account-info-hidden.txt` captures. + +### 5. Dialogs are drawn two different ways, and the banner is never reprinted + +The trust dialog and the sign-in splash take the **alternate screen** (`ESC[?1049h` … `ESC[?1049l`). +The model picker and command palette are drawn **in place on the main screen** with erase-to-EOL. +After dismissal the CLI prints `⎿ Exited /model command` and redraws the composer — it does **not** +reprint the banner. The header stays where it was at startup. + +### 6. Rows are positioned with cursor addressing, not newlines + +The status row is written with absolute and relative moves (`ESC[13;99H`, `ESC[83X ESC[83C`), so +`? for shortcuts` and `Gemini 3.7 Flash · low` end up on one derived line. Any rule that assumes +one screen row equals one `\n`-delimited line is reading a different document than the user sees. + +## 8. Busy frames park the caret exactly like idle frames — the spinner is what differs + +The frame that ends a turn-in-progress and the frame that ends an idle screen park the cursor with +the **same bytes**. Only the hint row differs, and the park erases it: + +``` +idle: ? for shortcuts ESC[83X ESC[83C Gemini 3.7 Flash · low CR ESC[2A ESC[2C ESC[?25h +busy: esc to cancel ESC[85X ESC[85C Gemini 3.7 Flash · low CR ESC[2A ESC[2C ESC[?25h +``` + +So a rule that keys on "the caret is the last thing in the tail" cannot tell busy from idle **on the +frame alone**. What saves it is what comes next. Each spinner tick is its own repaint with its own +park, two rows higher than the frame's: + +``` +ESC[?25l CR ESC[2A ⣯ Generating ESC[11D ESC[?25h +ESC[?25l CR ESC[2A ⣟ Generating. ESC[12D ESC[?25h +``` + +That second `CR ESC[2A` splices the composer row away, so the retained tail during a live turn ends +on the spinner row, not on the caret. Measured on `antigravity-busy-mid-turn.txt`: + +| Capture | last retained line | bare `>` line present | +| -------------------------------------------- | ------------------ | --------------------- | +| `antigravity-ready-api-key-gemini-model.txt` | `>` | **yes** | +| `antigravity-busy-mid-turn.txt` | `⣟ Generating...` | **no** | + +**Consequence for a caret-based rule:** it already answers "not ready" for a real mid-turn capture, +because there is no bare caret in the tail to match. A constructed input that keeps the park bytes +and only edits the status text is not faithful to a live turn — a live turn has a spinner row +repainting _below_ the composer. + +**The residual window, and the clause it implies.** Between a frame park and the next spinner tick +the tail does end on the bare caret and is indistinguishable from idle. The gap is one tick +interval. Any readiness path gated on sustained quiescence is safe, because ticks keep arriving and +the pane is never quiet; a path that only inspects retained text is not. For those paths the +evidence supports one clause, and only one: + +> **A braille glyph (U+2800–U+28FF) on the last visible line of the retained tail means working.** + +That predicate already exists in this file for cursor-agent (`CURSOR_BUSY_SPINNER_RE`) and should be +reused rather than reinvented. It must be scoped to the **last visible line**, not the whole tail: +a first-run transcript prints `⠾ Signing in...` during startup, which would otherwise pin a ready +screen as busy forever. + +Nothing else in the capture distinguishes the two states. The hint row (`esc to cancel` versus +`? for shortcuts`) is erased by the park in both cases, the park offsets are identical, and +`ESC[?25l`/`ESC[?25h` fencing appears around every repaint, idle or busy. + +## Confirmed / refuted, by attempt + +Evidence column names the fixture; all quoted text is from the committed transcripts. + +### Attempt 1 — the rule at HEAD + +| # | Claim | Verdict | Evidence | +| ---- | -------------------------------------------------------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1.1 | A ready screen prints the banner `Antigravity CLI` | **Confirmed** | `Antigravity CLI 1.2.0` in both ready fixtures | +| 1.1b | …and its last occurrence in the tail is the live one | **Refuted** | The trust dialog's own body says _"Antigravity CLI requires permission to read, edit, and execute files here"_, so `lastIndexOf` lands inside the dialog | +| 1.2 | The model row begins with the vendor word `Gemini` | **Refuted** | `▀▀▀▀▀▀▀▀ Gemini 3.7 Flash (Low)` — the logo precedes it; never at line start | +| 1.3 | The caret line's whole trimmed content is `>` | **Confirmed** on 1.2.0 idle | bare `>` in both ready fixtures | +| 1.3b | …and only the composer prints `>` | **Refuted** | `> Yes, I trust this folder`, `> Gemini 3.7 Flash (current)`, `> /add-dir` | +| 1.4 | A ready screen prints the workspace path on its own line | **Refuted** | the path shares its line with logo glyphs (`▄▀▀ ▀▀▄ ~`) | + +### Attempt 2 (loop 1) — blacklist the model line + +| # | Claim | Verdict | Evidence | +| --- | ------------------------------------------ | ----------- | ---------------------------------------------------------------------------------------------------------------- | +| 2.1 | Dialog model-row wording is enumerable | **Refuted** | the palette lists 50+ commands with free-form descriptions; the picker prints whatever models the account offers | +| 2.2 | A dialog never reproduces a real model row | **Refuted** | the `/model` picker prints four real model rows, one per line, at line start | + +### Attempt 3 (loop 2) — structural ordering on `headerIndex` + +| # | Claim | Verdict | Evidence | +| --- | -------------------------------------------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------- | +| 3.1 | A live dialog is printed below the ready chrome | **Confirmed** for in-place dialogs | picker and palette append below the composer | +| 3.2 | The banner is reprinted when a dialog is dismissed | **Refuted** | `antigravity-dialog-dismissed.txt` shows `⎿ Exited /model command` and a redrawn composer, no banner | +| 3.3 | Antigravity does not use the alternate screen | **Refuted** | `ESC[?1049h` opens the trust dialog and the sign-in splash | +| 3.4 | No full repaint per keystroke | **Partly refuted** | typing `/mod` repaints the palette region on each keystroke with `ESC[K` | + +Because of 3.2, `headerIndex` cannot be the anchor: it never advances. Ordering can only be +expressed against the model/caret positions, which is what 1.2 and 1.3b just invalidated. + +### Attempt 4 (loop 3) — require a positive account row + +| # | Claim | Verdict | Evidence | +| --- | ---------------------------------------------------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------- | +| 4.1 | Every ready screen prints an account row | **Refuted, twice** | API-key identity prints `Gemini API key` (no `@`); `AGY_CLI_HIDE_ACCOUNT_INFO=1` removes the row entirely | +| 4.2 | A startup dialog never contains an `@`-and-`.` token | **Not reachable here** | none of the captured dialogs contains one, but the palette shows free-form skill descriptions, which are user-authored text | +| 4.3 | The account row is distinguishable from prose | **Refuted** | the row is not a distinct line; it shares one with the logo | + +### Attempt 5 (PR #19749, reverted) — ordering + account row + +| # | Claim | Verdict | Evidence | +| --- | -------------------------------------------------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 5.1 | Ordering plus an account row separates ready from dialog | **Refuted** | the account row is optional (4.1) and the ordering anchor never moves (3.2) | +| 5.2 | Executing both builds was sufficient verification | **Refuted** | the executed input was the hand-written fixture, so the check reproduced the fixture's assumptions. The real screen disagrees with that fixture on the model row, the path row and the account row | +| 5.3 | The wedge is a model-name problem | **Refuted** | it is a line-start problem. Even `Gemini 3.7 Flash (Low)` — a Gemini model — fails, because a logo glyph precedes it | + +### Cross-cutting + +| # | Question | Answer | +| --- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| X1 | Does `agy` set an OSC title distinguishing busy from idle? | **No.** Not one OSC title sequence appears in any capture. Title-based readiness is unavailable for this agent | +| X2 | Does it repaint with bare `\r`? | **Yes**, constantly, plus `ESC[K` and absolute cursor moves | +| X3 | Does the caret survive in the tail? | **Yes** — a bare `>` line is present in every ready capture | +| X4 | Banner-to-caret distance | ~8 derived lines on a 120x40 PTY; the banner falls outside the 6-line preview window, so only the full retained tail can see it | +| X5 | Pane title on the trust screen versus ready | Identical: none | + +## Can attempt six be written? + +Yes — but not as a variation on any of the five. Every one of them refined a predicate over +`\n`-delimited lines, and that is the layer where the evidence says the information is not. + +What the captures support: + +- **The one stable, dialog-free ready marker is a line whose entire trimmed content is `>`.** It is + present in every ready capture and absent from every dialog capture, because a dialog's `>` always + carries its selected row's label. This is a much narrower rule than any attempt used, and it is + the only one that survived contact with the transcripts. +- **Drop the model-row requirement.** It matches dialogs and not ready screens. Keeping it inverted + the detector. +- **Do not require an account row.** It is optional by environment variable and carries no email for + API-key users. +- **Do not anchor on `headerIndex`.** The banner is printed once and never reprinted. +- **The blocked-signal path already works** for the trust dialog: `antigravity-dialog-trust-workspace.txt` + is correctly refused today, by wording, not by structure. + +What is still unknown and should be captured before shipping: the sign-in, theme, privacy and +update dialogs, and any ready screen where the composer is not idle (accept-edits and plan mode, +which PRs #15840 and #15852 describe from a screenshot). A bare-`>` rule is only as good as the +claim that those modes still end on a bare `>`; that claim is untested. + +The honest summary is that this is a screen-shaped problem being solved with line-shaped tools. A +rule over the derived tail can be made much better than what ships today, but the durable fix is to +ask the terminal emulator what the bottom row of the screen actually is, rather than inferring it +from a byte stream that was written with cursor addressing. diff --git a/docs/reference/headless-linux-server.md b/docs/reference/headless-linux-server.md index 50a38cf446e..a6a13489f2c 100644 --- a/docs/reference/headless-linux-server.md +++ b/docs/reference/headless-linux-server.md @@ -390,6 +390,10 @@ its own `orca`. `ws://` through an HTTPS-only endpoint. - Hostnames, IPv4, bracketed IPv6, and raw IPv6 literals are supported. IPv6 still requires an IPv6-reachable listener/network path. +- Background push notifications to a paired phone do not fire from a headless + server: agent-completion detection runs in the desktop renderer, which is not started in serve + mode, so nothing reaches the push gateway even though the phone + registers successfully. - `xvfb-run` and `dbus-run-session -- xvfb-run` remain valid diagnostic launch shapes, but neither should be needed when `Xvfb` is installed and no display is configured. Repeated D-Bus messages without a ready block indicate startup diff --git a/docs/reference/linux-glibc-compatibility.md b/docs/reference/linux-glibc-compatibility.md index 20e9b38acb5..64e72a67b83 100644 --- a/docs/reference/linux-glibc-compatibility.md +++ b/docs/reference/linux-glibc-compatibility.md @@ -131,3 +131,33 @@ a hole in the matrix. No strong `GLIBC_` node may exceed `2.31`, and no `GLIBCXX_`/`CXXABI_` node may exceed `3.4.28`/`1.3.12` — what stock Ubuntu 20.04 ships. + +## Runtime floor: the `environ` race below glibc 2.41 (Electron ≥ 43.7.0) + +Separate from the build floor above, one glibc runtime bug constrains which +Electron we may ship. Before glibc 2.41, `setenv`/`unsetenv` reallocate the +`environ` array and **free** the old one, so a concurrent `getenv()` on another +thread reads freed memory. Ubuntu 20.04–24.04 (2.31–2.39) are all below that +line, so every Linux target we support is exposed. + +Electron 43.5.0 made that latent race reachable on every launch: it started +setting `GDK_GL=disable` around `gtk_init()` and unsetting it right after, while +in the same change moving FontConfig warm-up onto a thread-pool thread that runs +concurrently and calls `getenv()` constantly +([electron#53070](https://github.com/electron/electron/pull/53070)). The result +is a browser-process use-after-free about a second into startup — no window, no +GPU child involved, and the corruption surfaces wherever the next allocation +lands, which is why reports name unrelated frames (`gtk_widget_realize`, +libxcb-dri3, FontConfig/expat). Orca 1.4.199/1.4.200 shipped that runtime and +died on launch on Ubuntu + NVIDIA/X11 +([#20081](https://github.com/stablyai/orca/issues/20081)). + +Electron 43.7.0 fixes it by overriding `setenv`/`unsetenv`/`putenv`/`clearenv` +so a published `environ` is never freed, deferring to glibc on 2.41+ +([electron#53491](https://github.com/electron/electron/pull/53491), backported +to 42/43/44/45). **Do not downgrade Electron below 43.7.0, or move to another +line, without confirming that backport is in the target release** — +`config/scripts/electron-runtime-floor.test.ts` fails the suite if the pin drops +below the floor. Orca itself writes `process.env` during early startup +(`patchPackagedProcessPath`, `configureOrcaUserDataPathEnv`, +`hydrate-shell-path`), so it is a first-class trigger, not just a bystander. diff --git a/docs/relay-region-correction/RELAY-REGION-CORRECTION-ACCEPTANCE.md b/docs/relay-region-correction/RELAY-REGION-CORRECTION-ACCEPTANCE.md new file mode 100644 index 00000000000..7bb182f3fe1 --- /dev/null +++ b/docs/relay-region-correction/RELAY-REGION-CORRECTION-ACCEPTANCE.md @@ -0,0 +1,114 @@ +# Idle regional correction acceptance + +Updated 2026-09-11. Scope: [idle-cutover plan](RELAY-REGION-CORRECTION-IDLE-CUTOVER-PLAN.md). +Local implementation is based on main `74cc9b50390b481009b34823a35eee01a5b90e40`, +with uncommitted changes atop `08c0802089a9186cf48ce0d168cd87565bd92d65`. + +**Local validation is green; the published PRs are not updated or merge-ready.** +Cloud draft20037 still points to `0462a87011d8783f91f9a9e977ea7a68437a0d5b`; +desktop draft20031 still points to `f9e5b0193448e6c524603836b9278878b96cf51c`. +Their older CI is not evidence for this implementation. No commit, push, merge, +deployment, workflow dispatch or production mutation occurred in this continuation. + +## What the implementation proves + +The source permits optimization only when actual client sockets, splices, pending +connections and in-flight admission/control work are absent. It installs the local +gate before awaiting a constrained assignment transaction. Duplicate requests bind +exact authority; ambiguous database outcomes keep the source fenced until locked +reconciliation establishes the result. After commit, it releases the empty control +and uses ordinary reconnect and migration recovery. Emergency drains retain their +existing behavior. No retained-source protocol or restoration loop remains. + +Three real TCP WebSocket scenarios join authenticated local HTTP dispatch, two +cells, the actual desktop origin pool, SQLite and an independent execution child: + +1. Either connected device prevents movement; after both leave, target reconnect + succeeds and the durable append-once mutation oracle shows no replay. +2. A racing arrival receives4409; a definite failed commit restores source admission. +3. The target control connection is actually attempted and fails; source activity + is released and ordinary expiry recovery allows source epoch3 reconnect. + +These use synthetic time and token verification. They do not prove physical mobile +background scheduling, production authentication/network behavior or user latency. + +## Commands and results + +Every test/app command uses `ORCA_BACKGROUND_LAUNCH=1`. Cloud commands run from +`cloud/apps/relay`; root commands run from this worktree. All logs below are under +`.tmp/idle-cutover-review/`. + +| Scope | Command | Result / log | +| --- | --- | --- | +| Cloud | `ORCA_RELAY_TEST_POSTGRES_URL='postgresql://postgres@127.0.0.1:55440/postgres?options=-csearch_path%3Didle_full_root_20260911' ORCA_IDLE_REHOME_POSTGRES_URL='postgresql://postgres@127.0.0.1:55440/postgres' ORCA_REGION_CORRECTION_POSTGRES=1 pnpm exec vitest run --no-file-parallelism` |77 files /682 passed /zero skips; `cloud-full-postgres-idle.log` | +| Cloud | `pnpm run typecheck` | Passed; `cloud-typecheck-after-preview.log` | +| Cloud | `pnpm build` | Passed; `cloud-release-build-idle.log` | +| Root | `pnpm test src/main/runtime/relay` |20 files /177 passed; `desktop-relay-full-idle.log` | +| Root | `pnpm test tests/e2e/relay-region-correction.unit.test.ts tests/e2e/relay-region-compatibility.unit.test.ts` |16 passed; `transport-contract-cleanup.log` | +| Root | `pnpm test src/main/global-fetch-call-site-audit.test.ts tests/e2e/relay-region-correction.unit.test.ts` |4 passed after CI fixes; `ci-gaps-green.log` | +| Root | `pnpm tc:node` | Passed; `node-final-idle.log` | +| Root | `pnpm exec oxlint src/main/runtime/relay tests/e2e/relay-region-correction.unit.test.ts tests/e2e/relay-region-compatibility.unit.test.ts` | Passed; `desktop-lint-idle.log` | +| Root | `pnpm run check:code-quality:changed` | Passed,0 new findings across30 changed files; `code-quality-changed-idle.log` | +| Root | `pnpm run check:reliability-gates` |121 manifest gates passed; `reliability-idle.log` | +| Root | `ORCA_E2E_SSH_DOCKER=1 pnpm exec playwright test tests/e2e/ssh-docker-transport-drop-recovery.spec.ts tests/e2e/paired-remote-terminal-serve-restart-binding.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1` |7 passed after fresh build; `ssh-folder-idle.log` | +| Root | `node --test cloud/dev/scripts/deploy-relay-blue-green.test.mjs cloud/dev/scripts/read-relay-serving-regional-placement-version.test.mjs cloud/dev/scripts/relay-regional-rehome-workflow.test.mjs` |47 passed; `deployment-guards-idle.log` | + +PostgreSQL16.15 reused the existing `orca-region-release-pg16` container on55440. +The suite used an isolated schema, dropped afterward (`cloud-full-postgres-cleanup.log`); +new concurrency tests create and clean independent schemas. No other PostgreSQL +port was used. Root oxlint ignores cloud; the configured cloud lint is TypeScript. + +The seven background Electron checks cover paired folder-capable binding across +serve restart and six real Docker SSH recovery journeys: live pane, output bounds, +host-proven exit, repeated restarts, frozen-host silence and resumed input. They do +not exercise a physical phone-to-SSH regional cutover or packaged upgrade. + +## Regression and review evidence + +- Reconciliation: four cases fail against constant not-committed, then pass with + locked authority checks (`reconciliation-{red,green}.log`). +- Registry: disabling pre-await admission accounting makes the arrival race fail; + restoring it passes. Five conflicting operation-ID authority tuples fail before + the identity fix, then all48 registry tests pass (`operation-tuple-{red,green}.log`). +- SQLite startup capability upgrade: red before upgrade logic;8 database tests pass + afterward. Legacy controls default to not idle-capable. +- The commit placeholder negative control was run after implementation; it is + counterfactual evidence, not a claim of chronological test-first development. +- Full PostgreSQL verification supersedes intermediate preview/legacy-test failures. + An agent's earlier PostgreSQL safety-latch discrepancy was disproven in an + isolated schema and explicitly withdrawn. +- Fifth GPT-6-astra low audit: **APPROVE within implementation scope**, no new blocker. + Reviewed source barriers, exact duplicates, locked ambiguity and worker progress. + Reviewer had migrated PostgreSQL tests, but did not author the core implementation. + Ledger: `.tmp/idle-cutover-review/review-ledger.md`. No sixth cycle started. + +## CI preparation and review artifacts + +Old desktop CI failed on a stale global-fetch inventory count and missing `pg` for +the transport test. The count reproduces locally; the downstream catalog/probe +consumers already consume/cancel bodies, so the audited count is corrected. +The unit workflow installs locked cloud relay dependencies and builds their contracts. +From `cloud/`, both commands pass (`ci-relay-dependencies.log`): + +- `npx --yes pnpm@10.24.0 --filter '@orca-cloud/relay...' install --frozen-lockfile --ignore-scripts` +- `npx --yes pnpm@10.24.0 --filter '@orca-cloud/relay^...' build` + +Local split patches and draft bodies are in `.tmp/idle-cutover-review/`: +`cloud-idle.patch`, `desktop-idle.patch`, `cloud-pr-body.md`, `desktop-pr-body.md`. +`prepare-split.py` verifies ordered application against the stated main baseline; +`split-manifest.json` identifies the combined tree. The actual index/branches remain +unchanged. The HTML explainer is `.tmp/relay-region-explainer.html`; four stages, +failure toggle, light/dark mobile/desktop layout and browser-error checks pass. + +## Remaining acceptance gaps + +- Update the two draft PRs and verify fresh CI for their exact heads. The original + handoff explicitly prohibited pushes; publication needs authorization. +- Packaged mixed-version desktop/mobile, physical-device lifecycle and platform + transport remain unverified. Pinned wire tests are narrower evidence. +- CI soak and production RTT/interaction benefit remain unmeasured. Correction + defaults off; deployment/enablement require the reviewed rollout procedure. +- Archive of intermediate/superseded evidence: + `.tmp/idle-cutover-review/acceptance-history-before-final.md` and pre-rescope branch + `relay-region-before-idle-implementation`. Earlier retention results do not prove + the idle design or repair the superseded live-retention transport case. diff --git a/docs/relay-region-correction/RELAY-REGION-CORRECTION-API.md b/docs/relay-region-correction/RELAY-REGION-CORRECTION-API.md new file mode 100644 index 00000000000..f3bd8b682c5 --- /dev/null +++ b/docs/relay-region-correction/RELAY-REGION-CORRECTION-API.md @@ -0,0 +1,61 @@ +# Idle regional correction contracts + +Updated 2026-09-11. The [idle-cutover plan](RELAY-REGION-CORRECTION-IDLE-CUTOVER-PLAN.md) +is authoritative. This replaces the former retention/restoration protocol. + +## Desktop measurement and capability + +The optional assignment `regionCorrection` namespace supports `issue-window` and +`report`. The server issues a generation, fixed expiry, assignment epoch, incumbent +region and policy version1. A report supplies measurements for both regions or an +inconclusive reason. The first accepted report remains immutable; stale or changed +assignment evidence cannot authorize a move. Legacy placement hints remain separate. + +Desktop advertises `idle-regional-rehome-v1` in its control capability header. +There is no new mobile message, retained-control lease, or restoration notification. +The cell persists the exact activity, generation, assignment and incarnation with +`idle_regional_rehome`. The obsolete `finish_existing` database column is always +written0 for schema compatibility and is not an eligibility signal. + +## Director to source cell + +`POST /v1/admin/host-idle-rehome` requires the configured director identity and +matching source cell/incarnation. The strict request contains: + +- `v:1`, stable UUID `attemptId`, `userId`, `relayHostId`; +- `sourceCellId`, `sourceCellIncarnation`, `sourceAssignmentEpoch`, `sourceGeneration`; +- `targetCellId`, authenticated `cohortPercent`, and fresh `directorSafety`. + +The strict response is `{v:1,outcome}` with `busy`, `committed`, `deferred`, or +`stale`. A lost HTTP reply is ambiguous and does not consume a dispatch-failure +budget. Repeat delivery retains the same operation identity. Cell status advertises +regional protocol3; new selection requires both cells at protocol3 or newer. + +## Store and source ownership + +`selectIdleRegionalRehomeCandidates` is read-only. It checks fresh evidence, +capability, policy, cooldown, telemetry and target capacity; bounded rotating pages +allow progress past busy hosts. Selection does not prove physical idleness. + +`HostSessionRegistry.idleRehome` accounts for accepts, attaches, control commands, +and activation before their first await. Only an idle source installs its admission +gate. New arrivals receive normal retryable routing failure. Conflicting reuse of +an operation ID cannot share another authority tuple's result. + +`commitIdleRegionalRehome` rechecks the exact request under existing locks, including +policy, cohort, capacity, global rate and concurrency. It atomically reserves the +target, advances assignment and records the attempt/source generation. It does not +choose a different host or destination. Completion is recorded at the source; +ordinary migration refresh, completion and expiry recovery remain responsible for +the target-registration lifecycle. + +`reconcileIdleRegionalRehome` locks the assignment before reading the operation. +It distinguishes committed, not-committed with unchanged live source authority, +and stale authority. Missing data after an unlocked read is never rollback proof. +A database error leaves admissions fenced while reconciliation retries. Successful +cutover closes/releases the empty source control; the desktop resolves its normal +assignment and reconnects. Definite rollback reopens only the same source authority. + +Outcome reporting aggregates actual attempts and migrations by cell/state, without +host identities or a retained-source table. A completed idle move does not authorize +closing future clients attached to the target. diff --git a/docs/relay-region-correction/RELAY-REGION-CORRECTION-CHECKLIST.md b/docs/relay-region-correction/RELAY-REGION-CORRECTION-CHECKLIST.md new file mode 100644 index 00000000000..fcb2b989c1a --- /dev/null +++ b/docs/relay-region-correction/RELAY-REGION-CORRECTION-CHECKLIST.md @@ -0,0 +1,47 @@ +# Relay region correction — implementation checklist + +> **Scope: idle-only correction.** Superseded retention history is preserved in +> `.tmp/idle-cutover-review/checklist-history-before-final.md` and the backup branch. +> Follow [idle-cutover plan](RELAY-REGION-CORRECTION-IDLE-CUTOVER-PLAN.md). + +## Idle-only implementation tracker + +- [x] Resolve plan review findings and obtain Astra approval (revision 2). +- [x] Preserve pre-rescope revision on `relay-region-before-idle-implementation`. +- [x] Endpoint authentication and incarnation check: deterministic red/green. +- [x] Worker selects before cutover; busy deferral and lost reply tests: red/green. +- [x] Source barrier covers accepts, attaches, commands and control replacement (48 registry tests, including conflicting operation-ID authority tuples; red/green evidence in acceptance). +- [x] Constrained assignment commit and locked ambiguous-outcome reconciliation (11 PostgreSQL 16 tests on 55440, including both replacement orders and a lost commit reply). +- [x] Desktop removes live-retention handling, retains fresh decisions and fallback (53 focused desktop/compatibility tests; node typecheck passes). +- [x] Remove superseded cloud retention protocol/store/cleanup and obsolete tests. The legacy database capability column remains written as0 for existing schema compatibility; it enables no behavior. +- [x] Real two-cell transport: two clients, quiet connection, idle move, arrival race, and observed target-registration failure with ordinary recovery (3 tests pass). +- [x] Focused PostgreSQL transaction/concurrency checks on 55440 (11 passed). +- [x] Full local relevant cloud/desktop suites: 682 cloud tests with PostgreSQL,177 desktop relay tests,16 transport/compatibility tests. +- [x] Local pinned-wire compatibility, Docker SSH/folder continuity (7), types, lint and reliability manifest. Packaged/device/platform gates remain open. +- [x] Fifth Astra low implementation audit: APPROVE within the documented scope. +- [ ] Rewrite and validate cloud/desktop PRs, CI and final acceptance evidence. + +These are merge-readiness tasks. Device/package/platform and production rollout +requirements remain explicit gaps until independently evidenced. + + + +Current transport disposition: **the replacement idle-only transport suite is green +(3 tests), but the PRs are not ready**. Local cloud/desktop verification, final implementation audit, SSH/folder evidence +and reliability docs are complete. PR updates, fresh CI and release evidence remain. +The full cloud suite passes682 tests with PostgreSQL16 and no skips; cloud typecheck passes. Final audit and remaining end-to-end/PR tasks are still open. Exact commands/results are at the top of the acceptance document. The original +live-retention rollback assertion is superseded by the approved product rescope; +these results do not claim that old design was repaired. + +## Publication and release gates + +- [x] Prepare separate cloud/desktop patches and concrete PR descriptions locally. +- [x] Reproduce and address old CI failures: fetch audit count and cloud test dependencies. +- [ ] Obtain authorization to publish under the original no-push handoff constraint. +- [ ] Update cloud draft20037 and desktop draft20031; verify exact-head CI. +- [ ] Packaged mixed-version desktop/mobile and physical-device lifecycle. +- [ ] Linux/Windows transport evidence, CI soak, bounded rollout and measured benefit. + +No production mutation or deployment occurred. Local passing tests and audit approval +are not a claim that the current published PRs are ready or the feature is deployed. +The acceptance document lists commands, evidence scope and remaining gaps. diff --git a/docs/relay-region-correction/RELAY-REGION-CORRECTION-IDLE-CUTOVER-PLAN.md b/docs/relay-region-correction/RELAY-REGION-CORRECTION-IDLE-CUTOVER-PLAN.md new file mode 100644 index 00000000000..0fcf0459636 --- /dev/null +++ b/docs/relay-region-correction/RELAY-REGION-CORRECTION-IDLE-CUTOVER-PLAN.md @@ -0,0 +1,213 @@ +# Relay region correction — idle cutover plan + +Status: **REVISION 2 — DESIGN APPROVED; implementation and verification pending.** + +Independent GPT-6-astra low review found no remaining design blocker. Approval is +conditional on the implementation gates below: pre-await ownership accounting, +shared assignment-row serialization, locked ambiguous-outcome reconciliation, +operation identity deduplication and late-callback fencing must be proven in tests. +Four independent idle-scope audits have been counted conservatively (scope, plan v1, +simplification, revision 2). If another plan revision fails review and a sixth cycle +would be needed, stop for user re-evaluation. Approval does not mean the current +live-retention PRs implement this design or are ready to merge. + +## Requirement and deliberate tradeoffs + +Automatically improve the host's relay region when no relay clients are using it. +A phone and iPad both disconnecting can create an opportunity. Continuous clients +can postpone optimization indefinitely. Returning during a move may incur ordinary +reconnect delay; zero-delay reconnect is NOT a requirement. Do not deliberately +close an established client connection to optimize latency. Direct LAN sessions +and running terminal processes do not themselves count as relay clients. + +The mobile 30-second background grace is not a reliable scheduling event: the OS +can delay it. Use actual source-cell connection state. Desktop control remains +open without phones; do not wait for it to disappear naturally. + +Keep fresh desktop measurements, incumbent-relative 25ms AND 20% improvement, +cohort/enable controls, capacity checks and cooldown. Probe improvement is not +proof of improved application latency. Cloud selects authoritative assignments; +mobile reconnect reads an assignment, it does not choose a faster region. + +## Simplicity constraints + +Reuse the regional worker, assignment transactions, reservations, request identity, +cell admission registry and normal desktop reconnect. No live-source retention, +splice transfer, recurring retained-control lease, new mobile protocol, global idle +poller, or desktop background-disconnect timer. Existing data sockets are never +copied or transferred (the former design did not transfer them either). + +Try an idle opportunity, immediately defer if busy; do not keep a gate waiting for +users to leave. The gate exists only for a short attempted cutover. A retryable +arrival may lose this race and reconnect normally. Do not count that as evidence +of lost execution or replay a previously sent mutation. + +Source cells already share the assignment database. Use one source-owned local +barrier around a constrained assignment transaction; do NOT introduce a distributed +prepare/commit protocol, a durable preparation table, or a second admission service. +The director selects candidates; the source's transaction rechecks director policy. + +## What is idle? + +The source owns one per-host/generation admission barrier covering every accept, +attach and control replacement path. Inventory these paths before changing them. +The quiescence predicate must require: + +- `activeConnIds.size === 0` (includes attaches while persistence awaits). +- `activeSplices.size === 0` and `pendingConns.size === 0`. +- Zero accepts in flight before insertion in those maps. Track ownership before + the first asynchronous operation that can admit this host; every exit releases it. +- Zero in-flight control operations that install credentials, mutate connection + basis or create admissions. Track actual server handlers; do not invent an + approximate count from RPC traffic or old database leases. + +An authenticated open desktop control socket, its ping/pong and activity renewal +are NOT client work and NOT a reason to defer. They can remain until cutover closes +the empty session. A desktop request arriving after the barrier gets a normal +retryable transport failure; finish previously accepted state mutations before +claiming idle. Reconnection must preserve pairing and not blindly replay mutations. + +Missing/expired database activity leases are never proof of idle. Outstanding +reservation cleanup remains owned and must be completed or safely fenced, but +waiting for every lease to expire would wrongly wait on the healthy control lease. + +## Source-owned try-cutover + +1. The director selects candidates read-only, using existing eligibility and pacing. + It sends an authenticated idle-cutover request with stable operation ID, expected + source assignment epoch/incarnation/generation and candidate target. Selection + does not reserve capacity or change assignment. Repeat delivery uses the same ID. +2. Source validates the request and current session. In one synchronous segment, + check all counters and install a per-host barrier. If busy, return `busy` without + closing sockets or holding a barrier. Busy is a deferral, not a dispatch failure. + The next worker pass must progress past busy candidates rather than starve others. +3. While barred, reject new clients and any new source control activation/rebind. + Late asynchronous continuations must recheck barrier/session after awaits and + release abandoned reservations. Install this fence before the first await of + the cutover. No barrier timer may reopen admissions on its own. +4. Source calls a constrained version of the existing assignment transaction. Reuse + its lock order, global rate/concurrency controls, cooldown, capacity reservation, + freshness and safety checks. Recheck exact source epoch/incarnation/generation, + target and operation identity. Reserve target, update assignment/epoch and record + the existing durable migration/attempt atomically. Do not call today's unrestricted + `claimRegionalRehome` and let it choose a different host. No network calls inside + DB locks. Zero sockets is established locally, not inferred from activity leases. +5. If committed, retire the still-empty source session/control via the existing + resolve-director closure path and release its activity. Desktop uses normal + reconnect and registers on target. Reply with the durable operation outcome. +6. If definitively not committed and source authority remains unchanged, remove the + barrier and continue on the original control. No target reservation survives a + rolled-back transaction. If authority changed, retire the obsolete source instead. + A timeout or transport error is NOT definitive rollback. + +## Ambiguous transactions, restarts and failures + +The request operation ID is known BEFORE the transaction and recorded as the +existing attempt ID on commit. Duplicate calls return its outcome and never start +another migration. A concurrent retry, cancellation or definitive-abort check must +serialize under the same host lock as commit; an unlocked absent-row lookup is +insufficient because the original transaction could still commit later. + +Keep a barrier until the database transaction is known terminal and a locked +reconciliation establishes the outcome. If the driver result is ambiguous, retry +status through a per-attempt backoff callback, using the same identity. If durable +access is unavailable, remain fenced; bounded availability cannot be promised +while the assignment's authority is unknown. No timeout-only reopen. Use the +existing DB transaction timeout and request timeout, not a new renewable gate lease. + +A lost director HTTP reply does not interrupt source-owned completion: source +finishes its transaction, reads durable outcome and closes/reopens locally. A +retry from any director sees the same operation. Director crashes do not strand +preparations because no separate preparation exists. + +A source restart/replacement control is fenced by existing authoritative registration +and activity validation. It must serialize against the cutover transaction under +host locks, validate the current assignment and reject old source ownership if the +commit won. If replacement won, the old transaction must fail its generation/ +incarnation recheck. This requires tracing current registration persistence and +proving the shared serialization point, not relying solely on the in-memory fence. +Late callbacks from a closed session cannot reopen admissions for its replacement. +Emergency drain invalidates local authority and participates in this serialization; +a cutover already committed follows its outcome, never reopens the emergency source. + +After commit, target registration failure uses ordinary bounded migration recovery. +The old empty control must be released even if outcome delivery failed; otherwise +current rollback refuses while source activity remains (`assignment-store.ts:6923`). +Source process death is handled by normal activity expiry and cell incarnation +fencing. No live clients were discarded, but a returning client may wait for recovery. +Once clients attach at target, preserve them under ordinary assignment rules: +initial source idleness never authorizes closing future target clients. + +## Compatibility and authority + +Mobile already re-resolves on `WRONG_CELL` (4409) through +`dialRelayThroughDirectorFallback`; use that existing close code for arrivals at a +gated source. Before commit, resolution can still return the old address: existing +backoff must prevent tight retry loops. After commit it returns the target. Pin +old parser/client fixtures and test the actual codes; do not assume every error is +retryable. Do not introduce a new mobile close code or protocol message. + +Empty host control closure uses the existing `DRAINING` / resolve-director path; +verify its reconnect behavior against the baseline desktop implementation. +Negotiate a distinct idle-cutover capability for participating cells and updated +desktops; do not reuse finish-existing capability to imply this new behavior. +Unsupported participants skip optional correction. Preserve old-server HTTP-400 +fallback for measurement fields. Emergency drain/auth enforcement can invalidate +any in-flight cutover; it must fence late commit and preserve existing hard deadlines. +Disabling correction stops new attempts; existing ones still reconcile. + +## Review and implementation gates + +Review must verify the shared-store serialization and identify every admission and +control mutation path before approving implementation. Minimum tests (red before +green for new guarantees): + +1. Phone remains while iPad disconnects: no move. Both disconnect: move possible. + A quiet established socket or expired DB splice lease still prevents a move. +2. Accept before/after barrier, accept awaiting activity persistence, attach awaiting + basis persistence, and credential mutation crossing the barrier. No late attach, + leaked reservation or interrupted established client. +3. Busy attempt leaves source admissions usable; repeated busy hosts do not starve + idle candidates or consume dispatch-failure budget. +4. Commit/replacement race; lost database/HTTP replies; timeout during transaction; + duplicate workers; director crash; source restart; replacement control; stale + epoch/incarnation; database outage and recovery. No timeout-only reopening. +5. Target failure before registration and after new client attachment; source-control + release; ordinary recovery completes without retained-source restoration. +6. Current/old mobile reconnect before and after commit, same-address retry pacing, + pairing preservation and no mutation replay. Old/new desktop/cloud combinations. +7. Emergency drain/auth denial during the cutover; no altered hard-drain behavior. +8. Real TCP WebSockets for two clients, admission race and failed cutover, independent + execution-process identity and append-once mutation evidence. Docker SSH and + folder workspace continuity. Tests use `ORCA_BACKGROUND_LAUNCH=1`. + +Keep tests proportional: deterministic component races first, then real transport, +relevant cloud/desktop suites, types/lint and PR CI. PostgreSQL only on 55440 when +validating authoritative transactions. Do not replace a failing oracle with a weaker +assertion or accumulate tests mirroring implementation. + +After clean review, replace superseded feature code/tests/docs on the two draft PRs, +preserving an immutable backup. Freshness and appropriate compatibility tests stay; +retention-only mechanisms and release requirements must be removed if irrelevant. +Do not claim readiness from tests of the superseded design. + +Release separately from merge readiness: packaged mixed versions, physical device +background timing, Linux/Windows, bounded rollout and measured user benefit remain +explicit evidence requirements. No deployment or enable is authorized by this plan. + +## Implementation notes — 2026-09-11 + +The authenticated director command carries its configured cohort percentage and +fresh process safety snapshot. A cell cannot use its own default-zero director +cohort setting to authorize or reject a selected host; it validates the authenticated +command, combines director/source safety, and rechecks durable policy, the host's +cohort bucket, and fleet/target safety inside the existing transaction. These fields +are on the internal admin endpoint, not the mobile or desktop protocol. + +Candidate selection is read-only and uses a rotating page offset to progress past +busy hosts. A deterministic UUIDv5 derived from the exact source authority and target +keeps operation identity stable across director retries/restarts. Both details still +need final implementation audit and an explicit page-boundary fairness test. + +Current focused and real-transport results are recorded at the top of the acceptance +document. They do not complete the remaining compatibility, cleanup and PR gates. diff --git a/docs/relay-region-correction/RELAY-REGION-CORRECTION-PLAN.md b/docs/relay-region-correction/RELAY-REGION-CORRECTION-PLAN.md new file mode 100644 index 00000000000..283e825c934 --- /dev/null +++ b/docs/relay-region-correction/RELAY-REGION-CORRECTION-PLAN.md @@ -0,0 +1,177 @@ +# Relay automatic region correction — implementation plan v2 + +Status: **IMPLEMENTED AND LOCALLY VALIDATED; RELEASE GATES REMAIN**. Section 5a is normative for first-grant adoption, retained-source rollback, renewal and cleanup. This replaces the idle-only proposal. Historical design reviews are preserved in the combined backup revision; current verification and remaining gaps are recorded in the acceptance document. + +Implementation tracking: [live checklist](RELAY-REGION-CORRECTION-CHECKLIST.md). Completed work and validation evidence are recorded there; this document defines the behavior. + +## Outcome and precise terms + +An updated desktop obtains a reliable region preference. If its assigned region is materially worse, the existing director worker makes the better region the destination for new connections. Existing physical relay data connections continue through the old cell until they close or fail naturally. The desktop then releases the old origin and the durable migration completes. + +“Existing connection” means a physical client-to-desktop relay data connection, represented by a cell splice and desktop connection ownership. It can carry multiple commands and subscriptions; it is not a terminal process, agent run, saved pairing, or recent typing. Tracked pending attachments and basis-bound control requests also protect source retirement. Quiet live connections are retained. No fixed maximum connection duration has been established or proposed for optional optimization. + +For mobile: active use remains on the old cell; after the app actually suspends/closes that connection, the next successful connection resolves to the target. Current mobile schedules background suspension after 30 seconds, and checks an overdue deadline on foreground if the timer did not run. Putting the phone down while the app remains foreground is not a disconnect. No re-pairing is required solely for relocation. + +Promise: optional region optimization does not deliberately terminate pre-existing connections merely because its grace timer expired. This is not a guarantee against network failure, process exit, revoked/expired auth, or emergency maintenance. New connection attempts during target startup may need normal recovery; do not promise zero delay on those attempts. + +## Evidence and reuse + +Source experiments used `origin/main` at `721a2692893ab29f8daee3149965bf5e9adf99a0`. Review must fetch current main and record its SHA, distinguishing changed source from these dated results. + +- Bidirectional worker already exists in #19241 and predates deployed #19915. Do not implement a second placement/migration engine. +- Desktop `relay-origin-pool.ts` already opens a target, retains source connection ownership, and closes the source after final release. Auth refresh already visits every origin. +- Cell `host-session-registry.ts` has drain-only state, live/pending connection maps, and existing control renewal. Director store already retains migration state until source activity releases. +- Two unconditional deadline sites force interruption: desktop origin-pool and cell regional host drain. Removing those scheduling sites in a diagnostic snapshot made both preservation tests pass; restoring source made the identical tests fail again. +- A SQLite store test sustained a registered migration for a simulated hour with both controls renewed, then completed on source release. +- Mobile harness restored credentials/assignment/subscriptions after simulated drain. Sent mutations can become delivery-unknown and are not blindly replayed. The 251ms fake-clock recovery result is not measured real-world downtime. + +Full evidence: [interruption findings](RELAY-INTERRUPTION-FINDINGS.md), [harness and patches](https://github.com/stablyai/orca/blob/0db9fdc486366f7451289f0c0599eed9ae1d94be/tests/tools/relay-rehome-interruption/README.md). The counterfactual patch is NOT production code: it has no negotiation, incorrectly changes normal deadline semantics, and does not validate failure/replay paths. + +## 1. Ordered, expiring region decisions + +Reuse desktop sampling and the existing assignment exchange. Separate legacy placement hints from eligibility to move an existing assignment. + +Preserve cold-start placement: run the existing pre-placement probe and send its placement hint with the first assignment request. Do not create a default-region assignment merely to obtain a measurement window. Obtain the epoch-bound window with or after that first assignment; only a subsequent post-window measurement can certify migration eligibility. Test first placement with and without conclusive probes, plus old-server fallback, so the new migration protocol does not regress initial placement. + +Proposed concrete protocol: an opt-in server-issued measurement window. A supporting desktop requests a window; director returns a per-host monotonic generation, fixed server expiry, and incumbent assignment epoch/region. Issuing a successor invalidates the predecessor for migration. The desktop probes after receiving the window, then reports a conclusive or inconclusive decision for that generation. Repeated delivery cannot extend expiry. An inconclusive outcome is retained as a tombstone; delayed older conclusive reports cannot resurrect eligibility. A restart that cannot reuse a valid cached decision obtains a successor window. Server time is authoritative for expiry. + +Persist window generation/expiry, incumbent basis, supported probe-policy version, and outcome in the existing preference state. Keep the latest supported evidence only; no history of every probe. Duplicate same-generation decisions are idempotent; conflicting same-generation outcomes must not upgrade inconclusive to conclusive. Serialize window issuance/reporting per broker and reject stale assignment basis under claim lock. The exact schema and transaction ordering must be reviewed before implementation. + +Legacy enum-only requests retain placement/reconnect behavior but cannot inherit or overwrite verified migration eligibility. Explicit new inconclusive decisions and missing legacy fields are different operations. Diagnostic region overrides are not measured proof. New request and response fields require explicit opt-in because both schemas are strict. Deploy server support before clients; implement old-server 400 fallback for both request shape and response negotiation without changing a healthy assignment. + +## 2. Compare with the actual assigned region + +Keep the current warm-up, sample count, spread rejection, and requirement that both regions be measurable. Initial placement may pick a best measured region. Moving an existing assignment additionally requires target latency at least **25ms lower AND 20% lower** than the measured incumbent region. These are the existing hysteresis thresholds applied to the correct basis, not a production-validated optimum. + +Report compact comparison evidence (incumbent/target region timing, policy and reason), tied to the window and assignment epoch. Director validates bounds, eligibility and margin. A missing incumbent, incomplete catalog, rejected measurement, nearly tied regions, unsupported policy or stale assignment basis means no move. Clear legacy probe caches on upgrade without treating an unopposed or 1ms winner as migration evidence. + +This optimizes the desktop-to-region path. Sample actual assigned-cell and mobile application behavior during rollout before claiming end-to-end user benefit. + +## 3. Refresh ownership and cadence + +The broker owns one decision deadline and one in-flight refresh/report task. Cancel them on broker close. Reuse the successful 24-hour cache interval and one-hour inconclusive retry interval, with jitter/backoff; eligibility expiry is distinct from retry scheduling. Do not wake offline/sleeping desktops for probes. On resume, check deadlines before using expired eligibility. Debounce network-change refresh only where the existing lifecycle provides a reliable signal. + +Probe/report failure must not fail successful auth renewal or intentionally reconnect healthy controls. Serialize assignment response application with drain/recovery: same cell/epoch updates metadata; a newer assignment follows the existing target activation flow; stale responses are discarded. Report retries reuse the same decision/window rather than re-probing or extending expiry. During an open migration, do not claim another move or replace the retained source; refresh decisions may be stored for later reevaluation only. + +## 4. Extend graceful migration to finish existing connections + +Introduce an explicit opt-in drain mode for optional regional optimization. Persist it on the attempt and propagate it through the director-to-cell host-drain command and cell-to-desktop drain message. The source must learn mode from durable protocol state, not infer it from grace=0, a hostname or a retry count. Maintenance/emergency drains keep their current hard deadlines. + +Eligibility requires supporting desktop and cell capabilities, fresh decision and matching source epoch/incarnation. New protocol/capability values and strict-parser fallbacks need cross-version tests. An unsupported participant defers optional correction rather than falling back to forced close. The reviewer should challenge how host capability remains bound to the currently active source generation, not merely a stale version-bearing report. + +Nominal transition: + +1. Existing claim reserves target capacity and commits target assignment plus migration/attempt state. +2. Source receives the mode-bearing drain and establishes the first valid authorized grant specified in section 5a before acknowledgment/cutover; desktop resolves/registers the target through existing code. +3. Target becomes the desktop's active origin. Existing source connections retain their source ownership; new connections resolve the current assignment. Already-admitted pending source connections may finish attaching and remain there. +4. Optional regional mode installs no forced old-origin/session close deadline. Existing event callbacks retire the source after its last owned connection and pending control operation end. Retain normal auth enforcement and operational emergency-close behavior. +5. Source control release/orphan cleanup removes its remaining activity. Existing completion logic finalizes the migration after source activity is gone and target is live. + +Do not use DB splice lease absence to infer idle: those leases can expire with a live socket. This design instead allows source work to exist. Do not build the proposed pre-move globally atomic idle gate. + +Required integration checks: pending control-RPC completion must trigger retirement when it was the final outstanding item; attach timeout/rejection and late async admission must not leak an origin or attach after retirement. Preserve existing source/target identity and request ownership. Cover two simultaneous mobile clients and a quiet connection; terminal counts and workspace type do not decide transport lifetime. + +## 5. Failure, replay and bounded resource use + +This section is a required implementation contract, not evidence that the current implementation already satisfies it. + +| Condition | Required behavior | +| --- | --- | +| Target registration fails | Retain still-live source work; retry or reconcile using existing migration recovery. Restore source new-admission authority only through section 5a's retained-generation rollback; do not discard a migration that still owns connections. | +| Lost receipt / duplicate drain / zero-grace re-drain | Read durable mode and preserve existing work. Replay must never turn optional mode into forced closure. | +| Desktop restart / source generation replacement | Old process connections may already be gone; reconcile exact generations before retaining or clearing state. Unsupported replacement must not silently hard-drain existing work. | +| Source network/cell failure | Use existing failure recovery; connectivity loss is not proof remote execution exited. This is outside the no-deliberate-interruption promise. | +| Target fails after becoming active | Keep source connections that remain live; reconcile assignment/new connections through existing recovery without starting a third overlapping rehome. | +| Auth expiry/revocation or emergency cell drain | Preserve existing enforcement; optimization does not exempt sessions from security/maintenance lifecycle. | +| Last source data connection closes while control RPC pending | Wait for bounded RPC completion/timeout, then run cleanup without a polling loop. | +| Source remains busy for hours | Keep the migration open while healthy. Long duration alone does not force-close users or spend dispatch-failure budget. | + +Bound **concurrent open migrations** in addition to starts/minute. Count pre-existing attempts; one migration per host remains enforced. Retain both controls' auth/lease renewals and account for source use plus target reservations. Data is not duplicated; extra controls/reservations still consume capacity. + +Ensure fair progress in the existing 100-row lease-refresh and 10-row candidate/sweep pages; waiting old migrations must not starve registration, renewal or cleanup for newer ones. Initially enforce a conservative concurrency bound below the smallest relevant page capacity, counting existing open work, until fair traversal is verified. Filters for cohort/policy/capability belong before LIMIT and are rechecked under locks. + +No user-visible maximum drain duration is claimed. If operations later require one for optimization, forcing closure would change the product promise and needs an explicit decision; a larger timer is not equivalent to finish-existing behavior. + +## 5a. Review corrections: retained-source authority and lifetime + +The independent review found three required contracts. This section supersedes any suggestion above that unchanged auth renewal or generic rollback suffices. Current source-control lifetime is six hours with thirty-minute jitter; auth-refresh does not extend it, and ordinary rotation only renews the active target. Current durable rehome refresh also has a 24-hour age ceiling. The one-hour SQLite experiment proved neither of those paths safe for indefinite live retention. + +### Reuse the cell's existing activity renewal (supersedes the extra wire exchange) + +Follow-up investigation found a smaller mechanism: a successfully validated `renewControlActivity` result can extend the same retained control's in-memory lease to `max(existingExpiry, requestedActivityExpiry)`. The cell already runs this renewal; no new desktop renewal timer, old-source rebind or recurring WebSocket exchange is needed. See [prototype evidence](https://github.com/stablyai/orca/blob/0db9fdc486366f7451289f0c0599eed9ae1d94be/tests/tools/relay-rehome-interruption/RETAINED-CONTROL-LEASE.md). + +Before acknowledging the optional drain and telling desktop to cut over, establish the first short authorized renewal for the exact mode/attempt/source generation/incarnation. Subsequent grants reuse normal heartbeat renewal. Failure or stale state during adoption does not authorize retaining the source; reconcile the provisional target through the rollback contract below. A mode flag, pending database request or activity reacquisition alone is not a grant. + +Narrow the existing atomic database renewal predicate with the retained attempt/mode/source basis, using immutable fields and preserving existing lock order; avoid a new precheck/query that can race mutation. The success callback must still match captured attempt, live session/socket/generation and mode; retirement/rollback/replacement/emergency drain invalidates it. Use the deadline sent at request start (currently 105s ahead), not response time, and do not add six hours on every heartbeat. Keep normal JWT/silence/watchdog enforcement and ordinary control rotation unchanged. Normal mode retains its existing lease; only extra retention needs these short successful grants. + +Prototype evidence: 43 cell-registry tests and package typecheck pass, including >12h simulated retention without extra recurring renewal calls; 6 real Postgres renewal tests execute with zero skips on local 55440. Baseline/revert fails the three extension oracles. The prototype injects the future mode marker and is NOT production-ready: initial adoption ordering, durable mode predicate, wire negotiation and rollback remain integration work. This revision addresses source renewal only, not the whole retention feature. + +### Final renewal-review correction: fence failures as well as success + +Fresh GPT-6-astra / low review: [retained-control review](https://github.com/stablyai/orca/blob/0db9fdc486366f7451289f0c0599eed9ae1d94be/docs/relay-region-correction/RELAY-RETAINED-CONTROL-REVIEW.md), **REVISE one completion-fencing detail; heartbeat reuse supported**. The following correction is incorporated after review, not independently approved or implemented. + +Every renewal completion and awaited recovery continuation must validate its captured socket/session, activity ID, current authority/mode transition and applicable ordering before altering scheduling, extending expiry, closing a socket, or reacquiring activity. In particular, a denial from an aborted retained attempt arriving after same-generation rollback must not close the restored source. A current applicable denial must still enforce closure. An obsolete missing-activity result must not initiate recovery; after awaited recovery, recheck authority and clean up abandoned acquisition as required. Do not use a blanket success-only fence or suppress all failures. + +Add controlled-promise tests for late denial after rollback, after a newer valid authority transition, obsolete missing-activity recovery, and applicable denial. Verify both preserved socket/splice identity and correct rejection, not just expiry values. First-grant adoption must also reject a success whose requested expiry is already past. + +In retained-mode SQL, the ordinary current-assignment authorization alternative must not bypass an aborted attempt check after rollback. If locking attempt rows, preserve assignment -> attempt -> migration -> activity dependency order used by existing rehome operations, rather than appending a late attempt lock. Use the prescribed PostgreSQL 16 environment for implementation concurrency validation on 55440; the earlier six-test PostgreSQL 17 run remains accurately labeled as narrower evidence. + +### Retained-generation rollback + +Generic source reassignment alone is insufficient: the source cell otherwise remains drain-only, and a fresh generation closes old splices. Add a durable, idempotent rollback transition for the exact optional attempt. In one authoritative store transaction, assign a newer source epoch and record that attempt's rollback outcome and retained source generation. Reconcile the source cell to that state: clear only that attempt's optional drain, preserve its socket/splices, update assignment metadata, and restore new admission only after validating current authority. Keep an aborted-attempt tombstone so a late drain cannot reverse rollback. + +Desktop recovery must find/reuse the retained source origin and update its assignment metadata without replacing its control generation or transports. This needs an explicit supported transition, not the current rebind-failed -> fresh-generation fallback. Late target registration cannot override the newer source epoch. Release target reservations when reconciled; keep one open migration per host until cleanup completes. If the source process/generation is gone, use ordinary failure recovery and report that preservation is unavailable; do not infer remote execution exited. + +### Transition table + +| State/event | Authority and action | Existing source work | +| --- | --- | --- | +| Claim optional move | Durable attempt binds mode, source generation/incarnation, target, epoch and supported participants | Retained | +| Target registering | Source receives optional drain; existing target retry/reconciliation proceeds | Retained; do not convert age into forced closure | +| Target registered | Director target assignment is authoritative; desktop activates target | Existing source connections keep their origin | +| Retained source needs renewal | Existing cell activity renewal + exact optional migration authorize a short same-generation lease extension | Retained, source remains drain-only | +| Target failure / rollback | New durable source epoch plus rollback tombstone; source cell and desktop reuse exact retained generation | Retained if that generation still exists | +| Final source work ends | Connection and pending-work callbacks retire source; cancel renewals; release activity and complete | No source work left to preserve | +| Delayed drain/renew/register | Compare durable attempt outcome and epochs; ignore/reject obsolete transition | Must not resurrect draining or replace generation | +| Source failed / emergency drain | Existing authenticated operational/failure semantics apply | Preservation not promised under those failures | + +### Mode-specific durable lifetime and compatibility floor + +For healthy registered optional retained-source attempts, remove the current 24-hour age-only lease-refresh ceiling and exclude them from the age-only zero-grace re-drain lane. Keep bounded target-registration failure/reconciliation; do not extend an unreachable unregistered target forever. Duration alone is not dispatch failure, and active source data must not be dropped to reclaim an optimization slot. Current generic and regional cleanup paths must both understand the optional mode. + +Before enabling optional retention, deploy a director/worker compatibility floor that understands all durable mode and rollback states even when new claims are disabled. Operational rollback must not go below that floor while such attempts exist. A disabled enable flag does not stop older cleanup/redrain code from misinterpreting new rows. Prove safe restart/rollback with existing open attempts and multi-day retention. The minimum revision will be recorded only after the compatible implementation is merged and validated. + +Additional accepted obligations: notify retirement on every final pending-control transition (response, rejection, timeout, close); perform a final local session/generation check after awaited admission work and release abandoned reservations; bind negotiated support to current authenticated source generation rather than a stale measurement report; enforce the concurrent-migration cap in locked shared state, including pre-existing work. None of these requires rebuilding a global idle detector. + +## 6. Rollout and observability + +Keep rehome disabled while implementing/testing. Deploy compatible director/database support, then supporting cells and desktops with feature gated off. Verify readiness and actual capabilities before enabling an authorized bounded cohort. Do not dispatch workflows as part of this review. + +Reuse current rate, cooldown, safety, capacity, durable attempts, and failure-budget controls. Preview must be read-only and share eligibility predicates, report full aggregate counts rather than a capped candidate page, and never claim attempts or consume budget. + +Track eligibility/exclusions by direction, target registration, migration completion/abort, number/age of retained sources, concurrent reservations, deliberate forced-close count by drain mode, and reconnect/error rates. Retain compact sampled comparisons and matched before/after assigned-cell/application latency where available; a registered target alone is not evidence of user benefit. Use an unchanged cohort to detect unrelated network variation. Never log credentials, pairing data, or raw host IDs. + +Acceptance: supported eligible hosts move new connections to their chosen target; old data connections survive optional-drain deadlines and retire on actual release; no forced source close solely due to optimization age; resources clean up; failures remain recoverable; sampled latency/reliability shows benefit without material regression. Specify sample sizes and numerical regression limits before production enable, using available traffic rather than inventing measured thresholds here. + +## 7. Required validation and implementation order + +1. Land freshness/ordering and incumbent-relative eligibility support under disabled control, with strict request/response compatibility tests. Cases: first-ever placement with correction disabled, placement-hint/actual-assignment mismatch, cold-start inconclusive probes and old-server fallback; delayed old reports, duplicates, inconclusive tombstones, clock changes, restarts, legacy writes, overrides, policy upgrades, stale epochs and cache clearing. +2. Implement broker refresh and event-driven origin retirement, test no auth coupling, no reconnect on unchanged assignment, pending-operation completion and sleep/resume. +3. Implement negotiated optional drain mode end-to-end in existing worker/cell/desktop paths, including normal emergency deadlines and replay. Extend the diagnostic oracles into real feature tests; do not merge the timer-removal experiment. +4. Validate real WebSocket traffic across source/target while sending unique stream markers and a mutation with delayed acknowledgment; check no duplicate/replayed mutation and independent host-side execution/output. Then validate mobile background/foreground reconnection and pairing preservation. Mock tests are not an end-to-end substitute. +5. Run actual Postgres integration/concurrency tests on **55440 only**. Require configured database, executed test counts and no conditional skip. Cover registration failure, target failure, concurrent admissions, cleanup, pagination and capacity accounting with long-lived sources. +6. Validate supported/unsupported desktop and cell combinations and old/new director rollback. SSH-hosted execution and folder workspaces remain governed by transport/owning host, not local process assumptions. No visible app tests on the user's desktop; background launch and isolated profiles are required. +7. Run a fresh operational safety gate and capability check only when a reviewed rollout is authorized. Enable a bounded cohort, observe retained-source/resource/benefit evidence, then expand. Disable stops new optional moves while safely reconciling existing ones. + +### Implementation correction: restoration confirmation can retry + +A rollback response can reach the cell while desktop director corroboration fails. +The cell therefore retains an exact pending-restoration authority (aborted attempt, +newer source epoch, original generation/incarnation/activity) until ordinary +same-generation rebind confirms restoration. Each successful existing heartbeat +renews only its short request-start deadline and replays `region-restored`. +Retained and restored authority are mutually exclusive; the old retained authority +remains rejected after rollback. Rebind, replacement, emergency drain, and applicable +denial fence outstanding callbacks. No extra timer or six-hour heartbeat grant is +introduced. This avoids losing long-lived source connections merely because the +first director confirmation failed. diff --git a/docs/relay-region-correction/RELAY-REGION-CORRECTION-ROLLOUT.md b/docs/relay-region-correction/RELAY-REGION-CORRECTION-ROLLOUT.md new file mode 100644 index 00000000000..66cd9b8efd5 --- /dev/null +++ b/docs/relay-region-correction/RELAY-REGION-CORRECTION-ROLLOUT.md @@ -0,0 +1,60 @@ +# Remaining release work and proposed rollout + +Status: implementation and local validation; no deployment authorization used. + +## Ordered release actions + +1. Review the local changes/PR and CI results. Record the immutable merged commit + and image for deployment and rollback. All directors must run the reviewed idle + worker before enabling correction; verify mixed-version deployment behavior + while correction remains disabled. +2. Publish the relay image and deploy the director with correction cohort0 and + durable rehome disabled. Verify image, health, preview route, migration schema, + pool pressure and cleanup. This requires the authorized deployment workflow. +3. Roll supporting cell images using their existing cell workflow; verify protocol3, + correct incarnation and telemetry. Release the updated desktop normally. + The phone protocol is unchanged; no mobile update is required for correction. +4. Validate a packaged desktop with a physical phone (foreground, actual background + suspension, resume, quiet connection, and target failure), and existing clients + against new cells. Run the same transport gate on Linux/Windows in CI; validate + an actual SSH-owned terminal survives client disconnection and normal reconnect. +5. Read the authenticated aggregate preview. Estimate eligible population by + direction; use a matching unchanged comparison cohort. Choose the initial + cohort and record approvals before changing settings or enabling. +6. Configure the approved cohort through the existing director workflow input, + keeping the durable control disabled during deployment. Verify the serving revision and tagged rollback + revision, then enable through the existing regional-rehome control workflow. +7. Stop new claims on a regression while ordinary migration cleanup and recovery continue. + Investigate existing work rather than forcing a timer-based source closure. + +## Proposed numerical acceptance criteria (must be approved before enable) + +These are rollout proposals, not measurements of production baseline or authorization. + +- First phase:1% deterministic host cohort; global cap remains8 open migrations. + Observe at least24h and30 completed moves. If traffic cannot supply30, extend + observation; do not treat a small sample as success. +- Immediate stop: any optimization-induced close of an established client, admission + reopening on ambiguous source authority, duplicated mutation, authorization bypass, or more than8 + optimization migrations admitted (pre-existing work also consumes cap). +- Reliability stop: compared with an unchanged cohort over matching15-minute + windows, assignment/connect failure rate rises by>=1 percentage point or2x + (require>=100 attempts in each comparison group); investigate lower-count failures + individually. Existing production incident limits always take precedence. +- Performance acceptance: matched post-move assigned-cell control RTT improves by + >=25ms AND>=20% median per host for at least80% of evaluable moved hosts; require + two independent samples before and after. Identify samples using + assignment epoch/cell identity. Log sample insufficiency as unevaluable. +- Client connection setup p95 must not regress by>10% versus its matched baseline + after accounting for the unchanged cohort. Setup is not application command + latency; separately record physical-phone interaction timings on validation runs. +- Expansion requires healthy registration/completion, stable reservation usage, no growing stuck-recovery backlog, and numerical criteria + above. Continuously connected clients may postpone optimization indefinitely. + +## Evidence boundaries + +Local tests use real socket traffic and independent host execution, but synthetic +clock/authentication. Neither the build nor schema fixtures prove distribution, +production latency, a physical phone or a signed desktop upgrade. Separate Docker SSH tests validate +SSH-provider recovery; they are not physical mobile-to-SSH cutover evidence. +The checklist leaves these release gates open deliberately. diff --git a/mobile/app.config.js b/mobile/app.config.js new file mode 100644 index 00000000000..e4bb110089f --- /dev/null +++ b/mobile/app.config.js @@ -0,0 +1,32 @@ +// Why this file exists: a bare "expo-notifications" plugin entry writes +// `aps-environment: development` into the iOS entitlements, while push-token.ts +// reports `production` for every non-__DEV__ build. A TestFlight or App Store build +// would then register a production APNs token against a sandbox entitlement, and the +// gateway's pushes would be accepted by Apple and delivered nowhere. Deriving the +// mode from an env var the release workflow sets makes the two agree by construction +// instead of relying on the export step to rewrite the entitlement. +// +// app.json stays the source for everything else: Expo reads it first and hands it to +// this function, so the fastlane version/buildNumber rewrite still flows through. +const APS_ENVIRONMENT = + process.env.ORCA_IOS_APS_ENVIRONMENT === 'production' ? 'production' : 'development' + +module.exports = ({ config }) => ({ + ...config, + ios: { + ...config.ios, + entitlements: { ...config.ios?.entitlements, 'aps-environment': APS_ENVIRONMENT } + }, + plugins: (config.plugins ?? []).map((plugin) => + plugin === 'expo-notifications' + ? [ + 'expo-notifications', + { + enableBackgroundRemoteNotifications: true, + mode: APS_ENVIRONMENT, + icon: './assets/notification-icon.png' + } + ] + : plugin + ) +}) diff --git a/mobile/app.json b/mobile/app.json index fc36687d74f..6121923f775 100644 --- a/mobile/app.json +++ b/mobile/app.json @@ -75,10 +75,12 @@ "allowBackup": false, "permissions": ["RECORD_AUDIO", "MODIFY_AUDIO_SETTINGS"], "package": "com.stably.orca.mobile", - "versionCode": 16 + "versionCode": 16, + "googleServicesFile": "./google-services.json" }, "plugins": [ "expo-router", + "expo-notifications", "./plugins/android-respect-rotation-lock.js", [ "expo-splash-screen", diff --git a/mobile/app/_layout.tsx b/mobile/app/_layout.tsx index 9080cdedcf9..c65008db7ce 100644 --- a/mobile/app/_layout.tsx +++ b/mobile/app/_layout.tsx @@ -1,6 +1,10 @@ +import { startAndroidForegroundPushPresentation } from '../src/notifications/android-foreground-push' +import { registerPushDismissalTask } from '../src/notifications/push-background-dismissal' +import { readNativeNotificationData } from '../src/notifications/native-notification-data' +import { setNotificationViewingWorkspace } from '../src/notifications/notification-viewing-policy' import { useCallback, useEffect, useRef } from 'react' import { View, StyleSheet } from 'react-native' -import { Stack, useRouter } from 'expo-router' +import { Stack, useRouter, useGlobalSearchParams, usePathname } from 'expo-router' import { StatusBar } from 'expo-status-bar' import * as SplashScreen from 'expo-splash-screen' import * as Notifications from 'expo-notifications' @@ -10,6 +14,13 @@ import { OrcaLogo } from '../src/components/OrcaLogo' import { RpcClientProvider } from '../src/transport/client-context' import { getNotificationNavigationTarget } from '../src/notifications/notification-routing' import { useOpenNotificationRoute } from '../src/notifications/use-open-notification-route' +import { + isRemotePushTrigger, + pushNotificationRouteData, + foregroundNotificationBehavior +} from '../src/notifications/push-receive' +import { startPushTokenSync } from '../src/notifications/push-registration' +import { ensureDesktopNotificationChannel } from '../src/notifications/desktop-notification-channel' import { loadHostCatalog } from '../src/transport/host-store' import { extractPairingCodeFromUrl } from '../src/transport/pairing' import { recoverMobileRelayPairing } from '../src/transport/mobile-relay-pairing-recovery' @@ -19,22 +30,29 @@ import { recoverMobileRelayPairing } from '../src/transport/mobile-relay-pairing // between the native splash and the first React paint. SplashScreen.preventAutoHideAsync() -// Why: without this, expo-notifications silently drops notifications when -// the app is in the foreground. Setting all three to true makes iOS/Android -// display the banner, play the sound, and show the badge even while the -// app is active. This runs once at module load time before any notification -// is scheduled. +// Why at boot and not only on subscribe: the gateway's FCM payload targets the +// 'orca-desktop' channel, and a background push can land before any socket has +// connected. Android drops a notification whose channel does not exist yet. +void ensureDesktopNotificationChannel().catch(() => {}) +void registerPushDismissalTask().catch(() => {}) + +// Register before scheduling so foreground delivery uses the same suppression policy. Notifications.setNotificationHandler({ - handleNotification: async () => ({ - shouldShowBanner: true, - shouldShowList: true, - shouldPlaySound: true, - shouldSetBadge: false - }) + handleNotification: foregroundNotificationBehavior }) export default function RootLayout() { const router = useRouter() + const pathname = usePathname() + const { hostId, worktreeId } = useGlobalSearchParams<{ hostId?: string; worktreeId?: string }>() + useEffect(() => { + setNotificationViewingWorkspace( + pathname.includes('/session/') && typeof hostId === 'string' && typeof worktreeId === 'string' + ? { hostId, worktreeId } + : null + ) + return () => setNotificationViewingWorkspace(null) + }, [pathname, hostId, worktreeId]) const openNotificationRoute = useOpenNotificationRoute() const handledNotificationIdsRef = useRef>(new Set()) @@ -44,6 +62,11 @@ export default function RootLayout() { void recoverMobileRelayPairing() }, []) + // Why: a rolled APNs/FCM token stops delivering silently, so every paired host + // has to be re-registered with the new one as soon as the provider hands it over. + useEffect(() => startPushTokenSync(), []) + useEffect(() => startAndroidForegroundPushPresentation(), []) + // Why: route `orca://pair?...` deep links to the confirm screen so // the same pairing flow runs whether the link arrived via QR scan, // paste, AirDrop, Messages, or `xcrun simctl openurl`. getInitialURL @@ -94,9 +117,18 @@ export default function RootLayout() { } } - async function getNavigationTarget(data: unknown) { + async function getNavigationTarget(notification: Notifications.Notification) { const hosts = await loadHostCatalog().catch(() => null) - return getNotificationNavigationTarget(data, { + const data = readNativeNotificationData(notification.request) + // A gateway push names its host by key fingerprint, not by this device's hostId. + // With no catalog to resolve against, such a push stays unrouted instead of + // falling back to whatever hostId its raw data carries. + const routeData = pushNotificationRouteData( + data, + hosts ?? [], + isRemotePushTrigger(notification.request.trigger) + ) + return getNotificationNavigationTarget(routeData, { knownHostIds: hosts ? new Set(hosts.map((host) => host.id)) : undefined, credentialStatusByHostId: hosts ? new Map(hosts.map((host) => [host.id, host.credentialStatus])) @@ -124,7 +156,7 @@ export default function RootLayout() { } } - const target = await getNavigationTarget(response.notification.request.content.data) + const target = await getNavigationTarget(response.notification) clearLastNotificationResponse() if (disposed) { return diff --git a/mobile/app/mobile-onboarding.tsx b/mobile/app/mobile-onboarding.tsx index 50957a465fc..213a5c982e5 100644 --- a/mobile/app/mobile-onboarding.tsx +++ b/mobile/app/mobile-onboarding.tsx @@ -22,7 +22,7 @@ import { saveDefaultSessionView, type MobileSessionView } from '../src/storage/session-view-preferences' -import { savePushNotificationsEnabled } from '../src/storage/preferences' +import { setRemotePushEnabled } from '../src/notifications/push-registration' const SLIDE_DURATION_MS = 280 @@ -127,7 +127,7 @@ function MobileOnboardingFlow({ setError(null) try { const enabled = choice === 'enable' ? await ensureNotificationPermissions() : false - await savePushNotificationsEnabled(enabled) + await setRemotePushEnabled(enabled) advanceOrContinue() } catch { setError('Notification settings could not be updated. Try again.') diff --git a/mobile/app/notifications.tsx b/mobile/app/notifications.tsx index d6566f66ac7..4bf9f08c25e 100644 --- a/mobile/app/notifications.tsx +++ b/mobile/app/notifications.tsx @@ -1,3 +1,5 @@ +import { NotificationDisplayTest } from '../src/settings/notification-display-test' +import { NativeNotificationDeliverySettings } from '../src/settings/native-notification-delivery-settings' import { useRouter } from 'expo-router' import NotificationsScreen from '../src/settings/notification-settings-screen' import { nativeNotificationSettingsOperations } from '../src/settings/native-notification-settings-operations' @@ -7,6 +9,14 @@ export default function NativeNotificationsRoute() { router.back()} - /> + description="Get agent alerts even when the app is closed. Delivered through Orca’s push service and Apple or Google." + > + {(enabled) => ( + <> + + router.push('/troubleshoot')} /> + + )} + ) } diff --git a/mobile/assets/notification-icon.png b/mobile/assets/notification-icon.png new file mode 100644 index 00000000000..774110aca7e Binary files /dev/null and b/mobile/assets/notification-icon.png differ diff --git a/mobile/google-services.json b/mobile/google-services.json new file mode 100644 index 00000000000..4120a97dafc --- /dev/null +++ b/mobile/google-services.json @@ -0,0 +1,39 @@ +{ + "project_info": { + "project_number": "120364513935", + "project_id": "onorca-cloud", + "storage_bucket": "onorca-cloud.firebasestorage.app" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:120364513935:android:1d951dc430aeb9bc664efa", + "android_client_info": { + "package_name": "com.stably.orca.mobile" + } + }, + "oauth_client": [ + { + "client_id": "120364513935-evfa8502bp5r9hn7afhd9i03oibs8223.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyBmT_w0OUQSiVfxblx-F0qlRvGkBBkTNQU" + } + ], + "services": { + "appinvite_service": { + "other_platform_oauth_client": [ + { + "client_id": "120364513935-evfa8502bp5r9hn7afhd9i03oibs8223.apps.googleusercontent.com", + "client_type": 3 + } + ] + } + } + } + ], + "configuration_version": "1" +} diff --git a/mobile/index.js b/mobile/index.js new file mode 100644 index 00000000000..489f950c650 --- /dev/null +++ b/mobile/index.js @@ -0,0 +1,3 @@ +// Headless notification launches do not mount the router layout. +import './src/notifications/push-background-dismissal' +import 'expo-router/entry' diff --git a/mobile/modules/orca-notification-dismissal/expo-module.config.json b/mobile/modules/orca-notification-dismissal/expo-module.config.json new file mode 100644 index 00000000000..dbf5942dbd5 --- /dev/null +++ b/mobile/modules/orca-notification-dismissal/expo-module.config.json @@ -0,0 +1,7 @@ +{ + "platforms": ["apple"], + "apple": { + "modules": ["OrcaNotificationDismissalModule"], + "appDelegateSubscribers": ["OrcaNotificationDismissalSubscriber"] + } +} diff --git a/mobile/modules/orca-notification-dismissal/ios/OrcaNotificationDismissal.podspec b/mobile/modules/orca-notification-dismissal/ios/OrcaNotificationDismissal.podspec new file mode 100644 index 00000000000..7e2aee8ebd7 --- /dev/null +++ b/mobile/modules/orca-notification-dismissal/ios/OrcaNotificationDismissal.podspec @@ -0,0 +1,15 @@ +Pod::Spec.new do |s| + s.name = 'OrcaNotificationDismissal' + s.version = '0.0.1' + s.summary = 'Native notification dismissal and sequence fencing' + s.description = s.summary + s.license = { :type => 'MIT' } + s.author = 'Orca' + s.homepage = 'https://onorca.dev' + s.source = { :git => 'https://github.com/stablyai/orca.git' } + s.platforms = { :ios => '15.1' } + s.swift_version = '5.9' + s.static_framework = true + s.dependency 'ExpoModulesCore' + s.source_files = '**/*.swift' +end diff --git a/mobile/modules/orca-notification-dismissal/ios/OrcaNotificationDismissalModule.swift b/mobile/modules/orca-notification-dismissal/ios/OrcaNotificationDismissalModule.swift new file mode 100644 index 00000000000..f86fe8bf891 --- /dev/null +++ b/mobile/modules/orca-notification-dismissal/ios/OrcaNotificationDismissalModule.swift @@ -0,0 +1,14 @@ +import ExpoModulesCore + +public class OrcaNotificationDismissalModule: Module { + public func definition() -> ModuleDefinition { + Name("OrcaNotificationDismissal") + AsyncFunction("remember") { (payload: [String: Any]) in + if let identity = PushDismissalIdentity(payload) { PushDismissalLedger.shared.remember(identity) } + } + AsyncFunction("wasDismissed") { (payload: [String: Any]) -> Bool in + guard let identity = PushDismissalIdentity(payload) else { return false } + return PushDismissalLedger.shared.contains(identity) + } + } +} diff --git a/mobile/modules/orca-notification-dismissal/ios/OrcaNotificationDismissalSubscriber.swift b/mobile/modules/orca-notification-dismissal/ios/OrcaNotificationDismissalSubscriber.swift new file mode 100644 index 00000000000..2bd7d939888 --- /dev/null +++ b/mobile/modules/orca-notification-dismissal/ios/OrcaNotificationDismissalSubscriber.swift @@ -0,0 +1,26 @@ +import ExpoModulesCore +import UserNotifications + +public class OrcaNotificationDismissalSubscriber: ExpoAppDelegateSubscriber { + public func application( + _ application: UIApplication, + didReceiveRemoteNotification userInfo: [AnyHashable: Any], + fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void + ) { + guard let payload = userInfo["orca"] as? [String: Any], + payload["kind"] as? String == "dismiss", let fence = PushDismissalIdentity(payload) + else { completionHandler(.noData); return } + PushDismissalLedger.shared.remember(fence) + let center = UNUserNotificationCenter.current() + center.getDeliveredNotifications { notifications in + let ids = notifications.compactMap { notification -> String? in + guard let data = notification.request.content.userInfo["orca"] as? [String: Any], + data["hostFingerprint"] as? String == fence.hostFingerprint, + PushDismissalLedger.shared.containsNotification(data) else { return nil } + return notification.request.identifier + } + center.removeDeliveredNotifications(withIdentifiers: ids) + completionHandler(ids.isEmpty ? .noData : .newData) + } + } +} diff --git a/mobile/modules/orca-notification-dismissal/ios/PushDismissalLedger.swift b/mobile/modules/orca-notification-dismissal/ios/PushDismissalLedger.swift new file mode 100644 index 00000000000..a147b09d599 --- /dev/null +++ b/mobile/modules/orca-notification-dismissal/ios/PushDismissalLedger.swift @@ -0,0 +1,67 @@ +import Foundation +import CoreFoundation + +struct PushDismissalIdentity: Codable { + let hostFingerprint: String + let notificationId: String + let notificationEpoch: String + let notificationSeq: Int64 + + init?(_ value: [String: Any]) { + guard let host = value["hostFingerprint"] as? String, !host.isEmpty, host.count <= 512, + let id = value["notificationId"] as? String, !id.isEmpty, id.count <= 2048, + let epoch = value["notificationEpoch"] as? String, !epoch.isEmpty, epoch.count <= 128, + let seq = value["notificationSeq"] as? NSNumber, + CFGetTypeID(seq) != CFBooleanGetTypeID(), seq.doubleValue.isFinite, + seq.doubleValue >= 0, seq.doubleValue <= 9_007_199_254_740_991, + seq.doubleValue.rounded(.down) == seq.doubleValue else { return nil } + hostFingerprint = host; notificationId = id; notificationEpoch = epoch + notificationSeq = seq.int64Value + } + + func matches(_ other: PushDismissalIdentity) -> Bool { + hostFingerprint == other.hostFingerprint && notificationId == other.notificationId && + notificationEpoch == other.notificationEpoch + } +} + +final class PushDismissalLedger { + static let shared = PushDismissalLedger() + private struct Entry: Codable { let identity: PushDismissalIdentity; let expiresAt: TimeInterval } + private let defaults: UserDefaults + private let lock = NSLock() + private let storageKey = "orca.pushDismissals.v1" + init(defaults: UserDefaults = .standard) { self.defaults = defaults } + + private func read(now: TimeInterval) -> [Entry] { + guard let data = defaults.data(forKey: storageKey), + let entries = try? JSONDecoder().decode([Entry].self, from: data) else { return [] } + return entries.filter { $0.expiresAt > now } + } + + func remember(_ identity: PushDismissalIdentity, now: TimeInterval = Date().timeIntervalSince1970) { + lock.lock(); defer { lock.unlock() } + let entries = read(now: now) + let previous = entries.first { $0.identity.matches(identity) } + let newest = (previous?.identity.notificationSeq ?? -1) > identity.notificationSeq + ? previous!.identity : identity + // Keep every live fence: count-based eviction lets delayed alerts reappear. + let next = entries.filter { !$0.identity.matches(identity) } + + [Entry(identity: newest, expiresAt: now + 86400)] + if let data = try? JSONEncoder().encode(next) { + defaults.set(data, forKey: storageKey) + } + } + + func contains(_ identity: PushDismissalIdentity, now: TimeInterval = Date().timeIntervalSince1970) -> Bool { + lock.lock(); defer { lock.unlock() } + return read(now: now).contains { + $0.identity.matches(identity) && $0.identity.notificationSeq >= identity.notificationSeq + } + } + + func containsNotification(_ payload: [String: Any], now: TimeInterval = Date().timeIntervalSince1970) -> Bool { + guard let identity = PushDismissalIdentity(payload) else { return false } + return contains(identity, now: now) + } +} diff --git a/mobile/modules/orca-notification-dismissal/package.json b/mobile/modules/orca-notification-dismissal/package.json new file mode 100644 index 00000000000..6710e7adbf6 --- /dev/null +++ b/mobile/modules/orca-notification-dismissal/package.json @@ -0,0 +1,5 @@ +{ + "name": "orca-notification-dismissal", + "version": "0.0.1", + "private": true +} diff --git a/mobile/modules/orca-notification-dismissal/tests/PushDismissalLedgerChecks.swift b/mobile/modules/orca-notification-dismissal/tests/PushDismissalLedgerChecks.swift new file mode 100644 index 00000000000..04e1809ea29 --- /dev/null +++ b/mobile/modules/orca-notification-dismissal/tests/PushDismissalLedgerChecks.swift @@ -0,0 +1,44 @@ +import Foundation +@main struct PushDismissalLedgerChecks { + static func main() { + let suite = "orca.qa.dismissal." + UUID().uuidString + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + func payload(_ seq: Int, _ host: String = "qa-host", _ epoch: String = "qa-epoch", _ id: String = "qa-alert") -> [String: Any] { + ["hostFingerprint": host, "notificationId": id, "notificationEpoch": epoch, "notificationSeq": seq] + } + func identity(_ seq: Int, _ host: String = "qa-host", _ epoch: String = "qa-epoch", _ id: String = "qa-alert") -> PushDismissalIdentity { + PushDismissalIdentity(payload(seq, host, epoch, id))! + } + let ledger = PushDismissalLedger(defaults: defaults) + ledger.remember(identity(2), now: 100) + ledger.remember(identity(1), now: 101) + let restored = PushDismissalLedger(defaults: defaults) + precondition(restored.contains(identity(1), now: 102)) + precondition(restored.contains(identity(2), now: 102)) + precondition(!restored.contains(identity(3), now: 102)) + precondition(!restored.contains(identity(1, "other"), now: 102)) + precondition(!restored.contains(identity(1, "qa-host", "other"), now: 102)) + precondition(!restored.contains(identity(1, "qa-host", "qa-epoch", "other"), now: 102)) + precondition(!restored.contains(identity(1), now: 86501)) + precondition(PushDismissalIdentity(["hostFingerprint":"h", "notificationId":"n", "notificationEpoch":"e", "notificationSeq":true]) == nil) + precondition(restored.containsNotification(payload(1), now: 102)) + precondition(!restored.containsNotification(payload(3), now: 102)) + precondition(!restored.containsNotification(payload(1, "other"), now: 102)) + precondition(!restored.containsNotification(payload(1, "qa-host", "other"), now: 102)) + precondition(!restored.containsNotification(payload(1, "qa-host", "qa-epoch", "other"), now: 102)) + precondition(!restored.containsNotification(["hostFingerprint": "qa-host"], now: 102)) + for hosts in [1, 3] { + for index in 0..<520 { + ledger.remember(identity(2, "host-\(index % hosts)", "epoch-\(hosts)", "note-\(index)"), now: 200) + } + let reopened = PushDismissalLedger(defaults: defaults) + for index in [0, 1, 519] { + precondition(reopened.contains(identity(2, "host-\(index % hosts)", "epoch-\(hosts)", "note-\(index)"), now: 201)) + precondition(!reopened.contains(identity(3, "host-\(index % hosts)", "epoch-\(hosts)", "note-\(index)"), now: 201)) + precondition(!reopened.contains(identity(2, "host-\(index % hosts)", "epoch-\(hosts)", "note-\(index)"), now: 86600)) + } + } + print("Native persisted fence: restart, ordering, identity isolation, expiry and invalid sequence checks passed") + } +} diff --git a/mobile/package.json b/mobile/package.json index 13f2f98acf5..d86c0d524ef 100644 --- a/mobile/package.json +++ b/mobile/package.json @@ -2,7 +2,7 @@ "name": "orca-mobile", "version": "0.0.1", "private": true, - "main": "expo-router/entry", + "main": "index.js", "scripts": { "start": "node scripts/start-expo.mjs", "android": "expo run:android", @@ -46,6 +46,7 @@ "expo-secure-store": "^55.0.18", "expo-splash-screen": "^55.0.25", "expo-status-bar": "^55.0.6", + "expo-task-manager": "~55.0.20", "lowlight": "^3.3.0", "lucide-react-native": "^1.14.0", "mermaid": "11.17.2", diff --git a/mobile/patches/expo-notifications@55.0.27.patch b/mobile/patches/expo-notifications@55.0.27.patch new file mode 100644 index 00000000000..e1a8d77ea8a --- /dev/null +++ b/mobile/patches/expo-notifications@55.0.27.patch @@ -0,0 +1,36 @@ +diff --git a/build/getDevicePushTokenAsync.js b/build/getDevicePushTokenAsync.js +index f0875c5eaa84d45d646edd1ad5f21a962f68ab02..d93813b2636f1ac5e09081c3207407410a404698 100644 +--- a/build/getDevicePushTokenAsync.js ++++ b/build/getDevicePushTokenAsync.js +@@ -20,8 +20,11 @@ export async function getDevicePushTokenAsync() { + else { + // Create a new Promise and clear it afterwards + nativeTokenPromise = PushTokenManager.getDevicePushTokenAsync(); +- devicePushToken = await nativeTokenPromise; +- nativeTokenPromise = null; ++ try { ++ devicePushToken = await nativeTokenPromise; ++ } finally { ++ nativeTokenPromise = null; ++ } + } + // @ts-ignore: TS thinks Platform.OS could be anything and can't decide what type is it + return { type: Platform.OS, data: devicePushToken }; +diff --git a/src/getDevicePushTokenAsync.ts b/src/getDevicePushTokenAsync.ts +index ab518dff463bc1a92052329ce5ac7c9055cbcf62..ad164f162998b5c1e218f089be82ab474727d68e 100644 +--- a/src/getDevicePushTokenAsync.ts ++++ b/src/getDevicePushTokenAsync.ts +@@ -24,8 +24,11 @@ export async function getDevicePushTokenAsync(): Promise { + } else { + // Create a new Promise and clear it afterwards + nativeTokenPromise = PushTokenManager.getDevicePushTokenAsync(); +- devicePushToken = await nativeTokenPromise; +- nativeTokenPromise = null; ++ try { ++ devicePushToken = await nativeTokenPromise; ++ } finally { ++ nativeTokenPromise = null; ++ } + } + + // @ts-ignore: TS thinks Platform.OS could be anything and can't decide what type is it diff --git a/mobile/pnpm-lock.yaml b/mobile/pnpm-lock.yaml index 7cebee89eec..2bb2b314b09 100644 --- a/mobile/pnpm-lock.yaml +++ b/mobile/pnpm-lock.yaml @@ -8,12 +8,9 @@ overrides: xcode>uuid: 11.1.1 patchedDependencies: - react-native-webview@13.16.2: - hash: de6761dfa76a5491a23e49f1262566a8831cab26736a336fdffc5d4e7d05ff27 - path: patches/react-native-webview@13.16.2.patch - react-native@0.83.10: - hash: 44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d - path: patches/react-native@0.83.10.patch + expo-notifications@55.0.27: ce20843a3daad4185d7e8571788fa323ba4d11984936188790858650a61749c0 + react-native-webview@13.16.2: de6761dfa76a5491a23e49f1262566a8831cab26736a336fdffc5d4e7d05ff27 + react-native@0.83.10: 44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d importers: @@ -24,10 +21,10 @@ importers: version: 1.8.0 '@orca/expo-two-way-audio': specifier: file:./packages/expo-two-way-audio - version: file:packages/expo-two-way-audio(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + version: file:packages/expo-two-way-audio(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) '@react-native-async-storage/async-storage': specifier: ^2.2.0 - version: 2.2.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8)) + version: 2.2.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8)) '@xterm/addon-unicode11': specifier: 0.10.0-beta.300 version: 0.10.0-beta.300(@xterm/xterm@6.1.0-beta.303) @@ -42,19 +39,19 @@ importers: version: 6.0.3 expo: specifier: ^55.0.30 - version: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + version: 55.0.30(09911ea01feb2f63557d787d92391924) expo-build-properties: specifier: ^55.0.18 version: 55.0.18(expo@55.0.30) expo-camera: specifier: ^55.0.23 - version: 55.0.23(@types/emscripten@1.41.5)(expo@55.0.30)(react-native-web@0.21.2(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + version: 55.0.23(@types/emscripten@1.41.5)(expo@55.0.30)(react-native-web@0.21.2(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) expo-clipboard: specifier: ^55.0.17 - version: 55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + version: 55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) expo-constants: specifier: ^55.0.17 - version: 55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8)) + version: 55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8)) expo-crypto: specifier: ^55.0.19 version: 55.0.19(expo@55.0.30) @@ -66,7 +63,7 @@ importers: version: 55.0.17(expo@55.0.30) expo-file-system: specifier: 55.0.26 - version: 55.0.26(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8)) + version: 55.0.26(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8)) expo-haptics: specifier: ^55.0.18 version: 55.0.18(expo@55.0.30) @@ -81,19 +78,19 @@ importers: version: 55.0.8(expo@55.0.30)(react@19.2.8) expo-linking: specifier: ^55.0.17 - version: 55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + version: 55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) expo-modules-core: specifier: ~55.0.25 - version: 55.0.25(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + version: 55.0.25(react-native-worklets@0.8.3(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) expo-network: specifier: ~55.0.18 version: 55.0.18(expo@55.0.30)(react@19.2.8) expo-notifications: specifier: ^55.0.27 - version: 55.0.27(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)(typescript@6.0.3) + version: 55.0.27(patch_hash=ce20843a3daad4185d7e8571788fa323ba4d11984936188790858650a61749c0)(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)(typescript@6.0.3) expo-router: specifier: ^55.0.18 - version: 55.0.18(4a60a26fd685ffdcc7f556016ae4bc5e) + version: 55.0.18(98b45897562456c6c413f91e81d6c336) expo-secure-store: specifier: ^55.0.18 version: 55.0.18(expo@55.0.30) @@ -102,13 +99,16 @@ importers: version: 55.0.25(expo@55.0.30)(typescript@6.0.3) expo-status-bar: specifier: ^55.0.6 - version: 55.0.6(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + version: 55.0.6(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + expo-task-manager: + specifier: ~55.0.20 + version: 55.0.20(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8)) lowlight: specifier: ^3.3.0 version: 3.3.0 lucide-react-native: specifier: ^1.14.0 - version: 1.14.0(react-native-svg@15.15.4(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + version: 1.14.0(react-native-svg@15.15.4(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) mermaid: specifier: 11.17.2 version: 11.17.2 @@ -120,34 +120,34 @@ importers: version: 19.2.8(react@19.2.8) react-native: specifier: ^0.83.10 - version: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + version: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) react-native-gesture-handler: specifier: ^2.31.2 - version: 2.31.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + version: 2.31.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) react-native-reanimated: specifier: 4.3.4 - version: 4.3.4(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + version: 4.3.4(react-native-worklets@0.8.3(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) react-native-safe-area-context: specifier: ^5.7.0 - version: 5.7.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + version: 5.7.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) react-native-screens: specifier: ^4.24.0 - version: 4.24.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + version: 4.24.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) react-native-svg: specifier: ^15.15.4 - version: 15.15.4(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + version: 15.15.4(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) react-native-uitextview: specifier: 2.2.0 - version: 2.2.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + version: 2.2.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) react-native-web: specifier: ^0.21.2 version: 0.21.2(react-dom@19.2.8(react@19.2.8))(react@19.2.8) react-native-webview: specifier: 13.16.2 - version: 13.16.2(patch_hash=de6761dfa76a5491a23e49f1262566a8831cab26736a336fdffc5d4e7d05ff27)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + version: 13.16.2(patch_hash=de6761dfa76a5491a23e49f1262566a8831cab26736a336fdffc5d4e7d05ff27)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) react-native-worklets: specifier: ^0.8.3 - version: 0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + version: 0.8.3(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) tweetnacl: specifier: ^1.0.3 version: 1.0.3 @@ -166,7 +166,7 @@ importers: version: 19.2.14 '@types/react-native': specifier: ^0.73.0 - version: 0.73.0(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + version: 0.73.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) '@types/react-test-renderer': specifier: 19.1.0 version: 19.1.0 @@ -181,7 +181,7 @@ importers: version: 0.25.4 expo-module-scripts: specifier: ^55.0.2 - version: 55.0.2(@babel/core@7.29.7)(@babel/runtime@7.29.7)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(esbuild@0.25.4)(eslint@9.39.4)(expo@55.0.30)(jest@29.7.0(@types/node@26.4.0))(prettier@2.8.8)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react-refresh@0.14.2)(react-test-renderer@19.2.8(react@19.2.8))(react@19.2.8) + version: 55.0.2(@babel/core@7.29.7(supports-color@8.1.1))(@babel/runtime@7.29.7)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(esbuild@0.25.4)(eslint@9.39.4(supports-color@8.1.1))(expo@55.0.30)(jest@29.7.0(@types/node@26.4.0)(supports-color@8.1.1))(prettier@2.8.8)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react-refresh@0.14.2)(react-test-renderer@19.2.8(react@19.2.8))(react@19.2.8) happy-dom: specifier: ^20.11.8 version: 20.11.8 @@ -205,7 +205,7 @@ importers: version: 8.1.0(@types/node@26.4.0)(esbuild@0.25.4)(terser@5.51.2)(tsx@4.22.4)(yaml@2.9.0) vitest: specifier: ^4.1.11 - version: 4.1.11(@types/node@26.4.0)(happy-dom@20.11.8)(jsdom@20.0.3)(vite@8.1.0(@types/node@26.4.0)(esbuild@0.25.4)(terser@5.51.2)(tsx@4.22.4)(yaml@2.9.0)) + version: 4.1.11(@types/node@26.4.0)(happy-dom@20.11.8)(jsdom@20.0.3(supports-color@8.1.1))(vite@8.1.0(@types/node@26.4.0)(esbuild@0.25.4)(terser@5.51.2)(tsx@4.22.4)(yaml@2.9.0)) packages: @@ -1632,8 +1632,8 @@ packages: react-native: optional: true - '@expo/dom-webview@55.0.5': - resolution: {integrity: sha512-lt3uxYOCk3wmWvtOOvsC35CKGbDAOx5C2EaY8SH1JVSfBzqmF8Cs0Xp1MPxncDPMyxpMiWx5SvvV/iLF1rJU4A==} + '@expo/dom-webview@55.0.6': + resolution: {integrity: sha512-ZNm8tiNEZysxrr36J0x4mOCGyJDcaIvL/3tMxBz0VJIJDcV19xjuJAhJQxHovu+jKx6s9tRyEAINa1mdrzV39g==} peerDependencies: expo: '*' react: '*' @@ -1669,14 +1669,6 @@ packages: '@expo/local-build-cache-provider@55.0.16': resolution: {integrity: sha512-/m2kb/+G2ryZ60FPZcuiLXzXp55p/X8QPXuU5CV/il0sSJcY0sQFICfM9ApokzHtzNQ0nDQOBUoQY3weilgP2g==} - '@expo/log-box@55.0.11': - resolution: {integrity: sha512-JQHFLWkskIbJi6cxYMjErx8lQqfFJilDQLKmdTO3m3YkdmN9GE/CrzjOfVlCG0DGEGZJ90br0pGKvGPdXNsHKw==} - peerDependencies: - '@expo/dom-webview': ^55.0.5 - expo: '*' - react: '*' - react-native: '*' - '@expo/log-box@55.0.13': resolution: {integrity: sha512-pV623uwyKjw/L1HVWOpwWOu/ISLH1+c+ESVv30alQMbEaE3cLcwcQ+UnHiAGayMBNMQwK57eckOgH40RBXHfCA==} peerDependencies: @@ -1693,8 +1685,8 @@ packages: expo: optional: true - '@expo/metro-runtime@55.0.10': - resolution: {integrity: sha512-7v+ldTvMWRa1ml83Jel9W2f8qT/NZZWrlHaEjf29nb72JTEO50+Xac9PWLo+X3LCDAAuyYuBGKYXOJwfqxV0fQ==} + '@expo/metro-runtime@55.0.12': + resolution: {integrity: sha512-EeqXrRBvChdt6+brlUkZM5749QoS7OlN7Zsn/AT8hhGV+xNKglirVRkcKQFmKqPgjgmNxfwgLJ6ddanwZ9dapg==} peerDependencies: expo: '*' react: '*' @@ -4487,6 +4479,12 @@ packages: react: '*' react-native: '*' + expo-task-manager@55.0.20: + resolution: {integrity: sha512-yxiERbkqibZYDArQ1QKbezKn7YkCxLyaDeiIO8DcyOqopBvUmXDkF3b7FtesW+YnAlg3g223geV8YiW1I4Suew==} + peerDependencies: + expo: '*' + react-native: '*' + expo-updates-interface@55.1.6: resolution: {integrity: sha512-evxNpagCkjT3lE6bGV570TFzRtKuIuLY8I37RYHoriXCJ+ZKCN1hbmklK29uAixya+BxGpeTI2K4FqYeJLvfrw==} peerDependencies: @@ -6876,6 +6874,9 @@ packages: resolution: {integrity: sha512-hpbDzxUY9BFwX+UeBnxv3Sh1q7HFxj48DTmXchNgRa46lO8uj3/1iEn3MiNUYTg1g9ctIqXCCERn8gYZhHC5lQ==} engines: {node: '>=4'} + unimodules-app-loader@55.0.5: + resolution: {integrity: sha512-2eLjtaAVQTK3EeiUAgRbfEnX78f6cMtw5Js8Ri4OcEdkrozsmvG3Wu8YVfr6kfhea17FHZkKZmO1m4dL/Ky2Bg==} + universalify@0.2.0: resolution: {integrity: sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==} engines: {node: '>= 4.0.0'} @@ -7233,9 +7234,9 @@ snapshots: package-manager-detector: 1.8.0 tinyexec: 1.1.2 - '@babel/cli@7.28.6(@babel/core@7.29.7)': + '@babel/cli@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@jridgewell/trace-mapping': 0.3.31 commander: 6.2.1 convert-source-map: 2.0.0 @@ -7267,20 +7268,20 @@ snapshots: '@babel/compat-data@7.29.7': {} - '@babel/core@7.29.7': + '@babel/core@7.29.7(supports-color@8.1.1)': dependencies: '@babel/code-frame': 7.29.7 '@babel/generator': 7.29.7 '@babel/helper-compilation-targets': 7.29.7 - '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7) + '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) '@babel/helpers': 7.29.7 '@babel/parser': 7.29.7 '@babel/template': 7.29.7 - '@babel/traverse': 7.29.7 + '@babel/traverse': 7.29.7(supports-color@8.1.1) '@babel/types': 7.29.7 '@jridgewell/remapping': 2.3.5 convert-source-map: 2.0.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) gensync: 1.0.0-beta.2 json5: 2.2.3 semver: 6.3.1 @@ -7335,52 +7336,52 @@ snapshots: lru-cache: 5.1.1 semver: 6.3.1 - '@babel/helper-create-class-features-plugin@7.29.3(@babel/core@7.29.7)': + '@babel/helper-create-class-features-plugin@7.29.3(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-annotate-as-pure': 7.27.3 '@babel/helper-member-expression-to-functions': 7.28.5 '@babel/helper-optimise-call-expression': 7.27.1 - '@babel/helper-replace-supers': 7.28.6(@babel/core@7.29.7) + '@babel/helper-replace-supers': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/helper-skip-transparent-expression-wrappers': 7.27.1 '@babel/traverse': 7.29.0 semver: 6.3.1 transitivePeerDependencies: - supports-color - '@babel/helper-create-class-features-plugin@7.29.7(@babel/core@7.29.7)': + '@babel/helper-create-class-features-plugin@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-annotate-as-pure': 7.29.7 - '@babel/helper-member-expression-to-functions': 7.29.7 + '@babel/helper-member-expression-to-functions': 7.29.7(supports-color@8.1.1) '@babel/helper-optimise-call-expression': 7.29.7 - '@babel/helper-replace-supers': 7.29.7(@babel/core@7.29.7) - '@babel/helper-skip-transparent-expression-wrappers': 7.29.7 - '@babel/traverse': 7.29.8 + '@babel/helper-replace-supers': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/helper-skip-transparent-expression-wrappers': 7.29.7(supports-color@8.1.1) + '@babel/traverse': 7.29.8(supports-color@8.1.1) semver: 6.3.1 transitivePeerDependencies: - supports-color - '@babel/helper-create-regexp-features-plugin@7.28.5(@babel/core@7.29.7)': + '@babel/helper-create-regexp-features-plugin@7.28.5(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-annotate-as-pure': 7.27.3 regexpu-core: 6.4.0 semver: 6.3.1 - '@babel/helper-create-regexp-features-plugin@7.29.7(@babel/core@7.29.7)': + '@babel/helper-create-regexp-features-plugin@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-annotate-as-pure': 7.29.7 regexpu-core: 6.4.0 semver: 6.3.1 - '@babel/helper-define-polyfill-provider@0.6.8(@babel/core@7.29.7)': + '@babel/helper-define-polyfill-provider@0.6.8(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-compilation-targets': 7.28.6 '@babel/helper-plugin-utils': 7.28.6 - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) lodash.debounce: 4.0.8 resolve: 1.22.12 transitivePeerDependencies: @@ -7397,9 +7398,9 @@ snapshots: transitivePeerDependencies: - supports-color - '@babel/helper-member-expression-to-functions@7.29.7': + '@babel/helper-member-expression-to-functions@7.29.7(supports-color@8.1.1)': dependencies: - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@8.1.1) '@babel/types': 7.29.8 transitivePeerDependencies: - supports-color @@ -7411,28 +7412,28 @@ snapshots: transitivePeerDependencies: - supports-color - '@babel/helper-module-imports@7.29.7': + '@babel/helper-module-imports@7.29.7(supports-color@8.1.1)': dependencies: - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@8.1.1) '@babel/types': 7.29.8 transitivePeerDependencies: - supports-color - '@babel/helper-module-transforms@7.28.6(@babel/core@7.29.7)': + '@babel/helper-module-transforms@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-module-imports': 7.28.6 '@babel/helper-validator-identifier': 7.28.5 - '@babel/traverse': 7.29.7 + '@babel/traverse': 7.29.7(supports-color@8.1.1) transitivePeerDependencies: - supports-color - '@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7)': + '@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-module-imports': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-module-imports': 7.29.7(supports-color@8.1.1) '@babel/helper-validator-identifier': 7.29.7 - '@babel/traverse': 7.29.7 + '@babel/traverse': 7.29.7(supports-color@8.1.1) transitivePeerDependencies: - supports-color @@ -7448,39 +7449,39 @@ snapshots: '@babel/helper-plugin-utils@7.29.7': {} - '@babel/helper-remap-async-to-generator@7.27.1(@babel/core@7.29.7)': + '@babel/helper-remap-async-to-generator@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-annotate-as-pure': 7.27.3 '@babel/helper-wrap-function': 7.28.6 - '@babel/traverse': 7.29.7 + '@babel/traverse': 7.29.7(supports-color@8.1.1) transitivePeerDependencies: - supports-color - '@babel/helper-remap-async-to-generator@7.29.7(@babel/core@7.29.7)': + '@babel/helper-remap-async-to-generator@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-annotate-as-pure': 7.29.7 - '@babel/helper-wrap-function': 7.29.7 - '@babel/traverse': 7.29.8 + '@babel/helper-wrap-function': 7.29.7(supports-color@8.1.1) + '@babel/traverse': 7.29.8(supports-color@8.1.1) transitivePeerDependencies: - supports-color - '@babel/helper-replace-supers@7.28.6(@babel/core@7.29.7)': + '@babel/helper-replace-supers@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-member-expression-to-functions': 7.28.5 '@babel/helper-optimise-call-expression': 7.27.1 '@babel/traverse': 7.29.0 transitivePeerDependencies: - supports-color - '@babel/helper-replace-supers@7.29.7(@babel/core@7.29.7)': + '@babel/helper-replace-supers@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-member-expression-to-functions': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-member-expression-to-functions': 7.29.7(supports-color@8.1.1) '@babel/helper-optimise-call-expression': 7.29.7 - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@8.1.1) transitivePeerDependencies: - supports-color @@ -7491,9 +7492,9 @@ snapshots: transitivePeerDependencies: - supports-color - '@babel/helper-skip-transparent-expression-wrappers@7.29.7': + '@babel/helper-skip-transparent-expression-wrappers@7.29.7(supports-color@8.1.1)': dependencies: - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@8.1.1) '@babel/types': 7.29.8 transitivePeerDependencies: - supports-color @@ -7513,15 +7514,15 @@ snapshots: '@babel/helper-wrap-function@7.28.6': dependencies: '@babel/template': 7.29.7 - '@babel/traverse': 7.29.7 + '@babel/traverse': 7.29.7(supports-color@8.1.1) '@babel/types': 7.29.7 transitivePeerDependencies: - supports-color - '@babel/helper-wrap-function@7.29.7': + '@babel/helper-wrap-function@7.29.7(supports-color@8.1.1)': dependencies: '@babel/template': 7.29.7 - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@8.1.1) '@babel/types': 7.29.8 transitivePeerDependencies: - supports-color @@ -7550,887 +7551,887 @@ snapshots: dependencies: '@babel/types': 7.29.8 - '@babel/plugin-bugfix-firefox-class-in-computed-class-key@7.28.5(@babel/core@7.29.7)': + '@babel/plugin-bugfix-firefox-class-in-computed-class-key@7.28.5(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 '@babel/traverse': 7.29.0 transitivePeerDependencies: - supports-color - '@babel/plugin-bugfix-safari-class-field-initializer-scope@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-bugfix-safari-class-field-initializer-scope@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-bugfix-safari-rest-destructuring-rhs-array@7.29.3(@babel/core@7.29.7)': + '@babel/plugin-bugfix-safari-rest-destructuring-rhs-array@7.29.3(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 '@babel/helper-skip-transparent-expression-wrappers': 7.27.1 transitivePeerDependencies: - supports-color - '@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 '@babel/helper-skip-transparent-expression-wrappers': 7.27.1 - '@babel/plugin-transform-optional-chaining': 7.28.6(@babel/core@7.29.7) + '@babel/plugin-transform-optional-chaining': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) transitivePeerDependencies: - supports-color - '@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 '@babel/traverse': 7.29.0 transitivePeerDependencies: - supports-color - '@babel/plugin-proposal-decorators@7.29.0(@babel/core@7.29.7)': + '@babel/plugin-proposal-decorators@7.29.0(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-class-features-plugin': 7.29.3(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-create-class-features-plugin': 7.29.3(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-decorators': 7.28.6(@babel/core@7.29.7) + '@babel/plugin-syntax-decorators': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) transitivePeerDependencies: - supports-color - '@babel/plugin-proposal-export-default-from@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-proposal-export-default-from@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-proposal-export-default-from@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-proposal-export-default-from@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-proposal-private-property-in-object@7.21.0-placeholder-for-preset-env.2(@babel/core@7.29.7)': + '@babel/plugin-proposal-private-property-in-object@7.21.0-placeholder-for-preset-env.2(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) - '@babel/plugin-syntax-async-generators@7.8.4(@babel/core@7.29.7)': + '@babel/plugin-syntax-async-generators@7.8.4(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-bigint@7.8.3(@babel/core@7.29.7)': + '@babel/plugin-syntax-bigint@7.8.3(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-class-properties@7.12.13(@babel/core@7.29.7)': + '@babel/plugin-syntax-class-properties@7.12.13(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-class-static-block@7.14.5(@babel/core@7.29.7)': + '@babel/plugin-syntax-class-static-block@7.14.5(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-decorators@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-syntax-decorators@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-dynamic-import@7.8.3(@babel/core@7.29.7)': + '@babel/plugin-syntax-dynamic-import@7.8.3(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-export-default-from@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-syntax-export-default-from@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-export-default-from@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-syntax-export-default-from@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-flow@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-syntax-flow@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-flow@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-syntax-flow@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-import-assertions@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-syntax-import-assertions@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-import-attributes@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-syntax-import-attributes@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-import-meta@7.10.4(@babel/core@7.29.7)': + '@babel/plugin-syntax-import-meta@7.10.4(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-json-strings@7.8.3(@babel/core@7.29.7)': + '@babel/plugin-syntax-json-strings@7.8.3(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-jsx@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-syntax-jsx@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-jsx@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-syntax-jsx@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-logical-assignment-operators@7.10.4(@babel/core@7.29.7)': + '@babel/plugin-syntax-logical-assignment-operators@7.10.4(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-nullish-coalescing-operator@7.8.3(@babel/core@7.29.7)': + '@babel/plugin-syntax-nullish-coalescing-operator@7.8.3(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-numeric-separator@7.10.4(@babel/core@7.29.7)': + '@babel/plugin-syntax-numeric-separator@7.10.4(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-object-rest-spread@7.8.3(@babel/core@7.29.7)': + '@babel/plugin-syntax-object-rest-spread@7.8.3(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-optional-catch-binding@7.8.3(@babel/core@7.29.7)': + '@babel/plugin-syntax-optional-catch-binding@7.8.3(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-optional-chaining@7.8.3(@babel/core@7.29.7)': + '@babel/plugin-syntax-optional-chaining@7.8.3(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-private-property-in-object@7.14.5(@babel/core@7.29.7)': + '@babel/plugin-syntax-private-property-in-object@7.14.5(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-top-level-await@7.14.5(@babel/core@7.29.7)': + '@babel/plugin-syntax-top-level-await@7.14.5(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-typescript@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-syntax-typescript@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-unicode-sets-regex@7.18.6(@babel/core@7.29.7)': + '@babel/plugin-syntax-unicode-sets-regex@7.18.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-arrow-functions@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-arrow-functions@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-async-generator-functions@7.29.0(@babel/core@7.29.7)': + '@babel/plugin-transform-async-generator-functions@7.29.0(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/helper-remap-async-to-generator': 7.27.1(@babel/core@7.29.7) + '@babel/helper-remap-async-to-generator': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/traverse': 7.29.0 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-async-generator-functions@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-async-generator-functions@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/helper-remap-async-to-generator': 7.29.7(@babel/core@7.29.7) - '@babel/traverse': 7.29.8 + '@babel/helper-remap-async-to-generator': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/traverse': 7.29.8(supports-color@8.1.1) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-async-to-generator@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-async-to-generator@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-module-imports': 7.28.6 '@babel/helper-plugin-utils': 7.28.6 - '@babel/helper-remap-async-to-generator': 7.27.1(@babel/core@7.29.7) + '@babel/helper-remap-async-to-generator': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-async-to-generator@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-async-to-generator@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-module-imports': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-module-imports': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/helper-remap-async-to-generator': 7.29.7(@babel/core@7.29.7) + '@babel/helper-remap-async-to-generator': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-block-scoped-functions@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-block-scoped-functions@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-block-scoping@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-block-scoping@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-block-scoping@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-block-scoping@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-class-properties@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-class-properties@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-class-features-plugin': 7.29.3(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-create-class-features-plugin': 7.29.3(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/helper-plugin-utils': 7.28.6 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-class-properties@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-class-properties@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-class-features-plugin': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-create-class-features-plugin': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-class-static-block@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-class-static-block@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-class-features-plugin': 7.29.3(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-create-class-features-plugin': 7.29.3(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/helper-plugin-utils': 7.28.6 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-classes@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-classes@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-annotate-as-pure': 7.27.3 '@babel/helper-compilation-targets': 7.28.6 '@babel/helper-globals': 7.28.0 '@babel/helper-plugin-utils': 7.28.6 - '@babel/helper-replace-supers': 7.28.6(@babel/core@7.29.7) + '@babel/helper-replace-supers': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/traverse': 7.29.0 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-classes@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-classes@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-annotate-as-pure': 7.29.7 '@babel/helper-compilation-targets': 7.29.7 '@babel/helper-globals': 7.29.7 '@babel/helper-plugin-utils': 7.29.7 - '@babel/helper-replace-supers': 7.29.7(@babel/core@7.29.7) - '@babel/traverse': 7.29.8 + '@babel/helper-replace-supers': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/traverse': 7.29.8(supports-color@8.1.1) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-computed-properties@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-computed-properties@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 '@babel/template': 7.28.6 - '@babel/plugin-transform-destructuring@7.28.5(@babel/core@7.29.7)': + '@babel/plugin-transform-destructuring@7.28.5(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 '@babel/traverse': 7.29.0 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-destructuring@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-destructuring@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@8.1.1) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-dotall-regex@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-dotall-regex@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-duplicate-keys@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-duplicate-keys@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-duplicate-named-capturing-groups-regex@7.29.0(@babel/core@7.29.7)': + '@babel/plugin-transform-duplicate-named-capturing-groups-regex@7.29.0(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-dynamic-import@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-dynamic-import@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-explicit-resource-management@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-explicit-resource-management@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-destructuring': 7.28.5(@babel/core@7.29.7) + '@babel/plugin-transform-destructuring': 7.28.5(@babel/core@7.29.7(supports-color@8.1.1)) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-exponentiation-operator@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-exponentiation-operator@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-export-namespace-from@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-export-namespace-from@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-flow-strip-types@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-flow-strip-types@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-flow': 7.28.6(@babel/core@7.29.7) + '@babel/plugin-syntax-flow': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) - '@babel/plugin-transform-flow-strip-types@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-flow-strip-types@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-flow': 7.29.7(@babel/core@7.29.7) + '@babel/plugin-syntax-flow': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) - '@babel/plugin-transform-for-of@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-for-of@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 '@babel/helper-skip-transparent-expression-wrappers': 7.27.1 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-for-of@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-for-of@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/helper-skip-transparent-expression-wrappers': 7.29.7 + '@babel/helper-skip-transparent-expression-wrappers': 7.29.7(supports-color@8.1.1) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-function-name@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-function-name@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-compilation-targets': 7.28.6 '@babel/helper-plugin-utils': 7.28.6 '@babel/traverse': 7.29.0 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-json-strings@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-json-strings@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-literals@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-literals@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-logical-assignment-operators@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-logical-assignment-operators@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-member-expression-literals@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-member-expression-literals@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-modules-amd@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-modules-amd@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-module-transforms': 7.28.6(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-module-transforms': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/helper-plugin-utils': 7.28.6 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-modules-commonjs@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-modules-commonjs@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-module-transforms': 7.28.6(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-module-transforms': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/helper-plugin-utils': 7.28.6 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-modules-commonjs@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-modules-commonjs@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-modules-systemjs@7.29.4(@babel/core@7.29.7)': + '@babel/plugin-transform-modules-systemjs@7.29.4(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-module-transforms': 7.28.6(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-module-transforms': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/helper-plugin-utils': 7.28.6 '@babel/helper-validator-identifier': 7.28.5 '@babel/traverse': 7.29.0 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-modules-umd@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-modules-umd@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-module-transforms': 7.28.6(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-module-transforms': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/helper-plugin-utils': 7.28.6 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-named-capturing-groups-regex@7.29.0(@babel/core@7.29.7)': + '@babel/plugin-transform-named-capturing-groups-regex@7.29.0(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-named-capturing-groups-regex@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-named-capturing-groups-regex@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-regexp-features-plugin': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-create-regexp-features-plugin': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-new-target@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-new-target@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-nullish-coalescing-operator@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-nullish-coalescing-operator@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-nullish-coalescing-operator@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-nullish-coalescing-operator@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-numeric-separator@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-numeric-separator@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-object-rest-spread@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-object-rest-spread@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-compilation-targets': 7.28.6 '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-destructuring': 7.28.5(@babel/core@7.29.7) - '@babel/plugin-transform-parameters': 7.27.7(@babel/core@7.29.7) + '@babel/plugin-transform-destructuring': 7.28.5(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-parameters': 7.27.7(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/traverse': 7.29.0 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-object-super@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-object-super@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/helper-replace-supers': 7.28.6(@babel/core@7.29.7) + '@babel/helper-replace-supers': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-optional-catch-binding@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-optional-catch-binding@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-optional-catch-binding@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-optional-catch-binding@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-optional-chaining@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-optional-chaining@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 '@babel/helper-skip-transparent-expression-wrappers': 7.27.1 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-optional-chaining@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-optional-chaining@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/helper-skip-transparent-expression-wrappers': 7.29.7 + '@babel/helper-skip-transparent-expression-wrappers': 7.29.7(supports-color@8.1.1) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-parameters@7.27.7(@babel/core@7.29.7)': + '@babel/plugin-transform-parameters@7.27.7(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-private-methods@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-private-methods@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-class-features-plugin': 7.29.3(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-create-class-features-plugin': 7.29.3(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/helper-plugin-utils': 7.28.6 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-private-methods@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-private-methods@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-class-features-plugin': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-create-class-features-plugin': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-private-property-in-object@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-private-property-in-object@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-annotate-as-pure': 7.27.3 - '@babel/helper-create-class-features-plugin': 7.29.3(@babel/core@7.29.7) + '@babel/helper-create-class-features-plugin': 7.29.3(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/helper-plugin-utils': 7.28.6 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-private-property-in-object@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-private-property-in-object@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-annotate-as-pure': 7.29.7 - '@babel/helper-create-class-features-plugin': 7.29.7(@babel/core@7.29.7) + '@babel/helper-create-class-features-plugin': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-property-literals@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-property-literals@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-react-display-name@7.28.0(@babel/core@7.29.7)': + '@babel/plugin-transform-react-display-name@7.28.0(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-react-display-name@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-react-display-name@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-react-jsx-development@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-react-jsx-development@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 - '@babel/plugin-transform-react-jsx': 7.28.6(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/plugin-transform-react-jsx': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-react-jsx-self@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-react-jsx-self@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-react-jsx-self@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-react-jsx-self@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-react-jsx-source@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-react-jsx-source@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-react-jsx-source@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-react-jsx-source@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-react-jsx@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-react-jsx@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-annotate-as-pure': 7.27.3 '@babel/helper-module-imports': 7.28.6 '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-jsx': 7.28.6(@babel/core@7.29.7) + '@babel/plugin-syntax-jsx': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/types': 7.29.7 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-react-jsx@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-react-jsx@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-annotate-as-pure': 7.29.7 - '@babel/helper-module-imports': 7.29.7 + '@babel/helper-module-imports': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-syntax-jsx': 7.29.7(@babel/core@7.29.7) + '@babel/plugin-syntax-jsx': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/types': 7.29.8 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-react-pure-annotations@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-react-pure-annotations@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-annotate-as-pure': 7.27.3 '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-regenerator@7.29.0(@babel/core@7.29.7)': + '@babel/plugin-transform-regenerator@7.29.0(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-regenerator@7.29.8(@babel/core@7.29.7)': + '@babel/plugin-transform-regenerator@7.29.8(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-regexp-modifiers@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-regexp-modifiers@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-reserved-words@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-reserved-words@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-runtime@7.29.0(@babel/core@7.29.7)': + '@babel/plugin-transform-runtime@7.29.0(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-module-imports': 7.28.6 '@babel/helper-plugin-utils': 7.28.6 - babel-plugin-polyfill-corejs2: 0.4.17(@babel/core@7.29.7) - babel-plugin-polyfill-corejs3: 0.13.0(@babel/core@7.29.7) - babel-plugin-polyfill-regenerator: 0.6.8(@babel/core@7.29.7) + babel-plugin-polyfill-corejs2: 0.4.17(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + babel-plugin-polyfill-corejs3: 0.13.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + babel-plugin-polyfill-regenerator: 0.6.8(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) semver: 6.3.1 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-runtime@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-runtime@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-module-imports': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-module-imports': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - babel-plugin-polyfill-corejs2: 0.4.17(@babel/core@7.29.7) - babel-plugin-polyfill-corejs3: 0.13.0(@babel/core@7.29.7) - babel-plugin-polyfill-regenerator: 0.6.8(@babel/core@7.29.7) + babel-plugin-polyfill-corejs2: 0.4.17(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + babel-plugin-polyfill-corejs3: 0.13.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + babel-plugin-polyfill-regenerator: 0.6.8(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) semver: 6.3.1 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-shorthand-properties@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-shorthand-properties@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-spread@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-spread@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 '@babel/helper-skip-transparent-expression-wrappers': 7.27.1 transitivePeerDependencies: - supports-color - '@babel/plugin-transform-sticky-regex@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-sticky-regex@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-template-literals@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-template-literals@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-typeof-symbol@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-typeof-symbol@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-typescript@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-typescript@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-annotate-as-pure': 7.27.3 - '@babel/helper-create-class-features-plugin': 7.29.3(@babel/core@7.29.7) + '@babel/helper-create-class-features-plugin': 7.29.3(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/helper-plugin-utils': 7.28.6 '@babel/helper-skip-transparent-expression-wrappers': 7.27.1 - '@babel/plugin-syntax-typescript': 7.28.6(@babel/core@7.29.7) + '@babel/plugin-syntax-typescript': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-typescript@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-typescript@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-annotate-as-pure': 7.29.7 - '@babel/helper-create-class-features-plugin': 7.29.7(@babel/core@7.29.7) + '@babel/helper-create-class-features-plugin': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.29.7 - '@babel/helper-skip-transparent-expression-wrappers': 7.29.7 - '@babel/plugin-syntax-typescript': 7.29.7(@babel/core@7.29.7) + '@babel/helper-skip-transparent-expression-wrappers': 7.29.7(supports-color@8.1.1) + '@babel/plugin-syntax-typescript': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) transitivePeerDependencies: - supports-color - '@babel/plugin-transform-unicode-escapes@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-unicode-escapes@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-unicode-property-regex@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-unicode-property-regex@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-unicode-regex@7.27.1(@babel/core@7.29.7)': + '@babel/plugin-transform-unicode-regex@7.27.1(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-transform-unicode-regex@7.29.7(@babel/core@7.29.7)': + '@babel/plugin-transform-unicode-regex@7.29.7(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-regexp-features-plugin': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-create-regexp-features-plugin': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/helper-plugin-utils': 7.29.7 - '@babel/plugin-transform-unicode-sets-regex@7.28.6(@babel/core@7.29.7)': + '@babel/plugin-transform-unicode-sets-regex@7.28.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 - '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-create-regexp-features-plugin': 7.28.5(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/helper-plugin-utils': 7.28.6 - '@babel/preset-env@7.29.5(@babel/core@7.29.7)': + '@babel/preset-env@7.29.5(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: '@babel/compat-data': 7.29.3 - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-compilation-targets': 7.28.6 '@babel/helper-plugin-utils': 7.28.6 '@babel/helper-validator-option': 7.27.1 - '@babel/plugin-bugfix-firefox-class-in-computed-class-key': 7.28.5(@babel/core@7.29.7) - '@babel/plugin-bugfix-safari-class-field-initializer-scope': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-bugfix-safari-rest-destructuring-rhs-array': 7.29.3(@babel/core@7.29.7) - '@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-proposal-private-property-in-object': 7.21.0-placeholder-for-preset-env.2(@babel/core@7.29.7) - '@babel/plugin-syntax-import-assertions': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-syntax-import-attributes': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-syntax-unicode-sets-regex': 7.18.6(@babel/core@7.29.7) - '@babel/plugin-transform-arrow-functions': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-async-generator-functions': 7.29.0(@babel/core@7.29.7) - '@babel/plugin-transform-async-to-generator': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-block-scoped-functions': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-block-scoping': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-class-properties': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-class-static-block': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-classes': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-computed-properties': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-destructuring': 7.28.5(@babel/core@7.29.7) - '@babel/plugin-transform-dotall-regex': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-duplicate-keys': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-duplicate-named-capturing-groups-regex': 7.29.0(@babel/core@7.29.7) - '@babel/plugin-transform-dynamic-import': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-explicit-resource-management': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-exponentiation-operator': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-export-namespace-from': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-for-of': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-function-name': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-json-strings': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-literals': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-logical-assignment-operators': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-member-expression-literals': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-modules-amd': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-modules-commonjs': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-modules-systemjs': 7.29.4(@babel/core@7.29.7) - '@babel/plugin-transform-modules-umd': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-named-capturing-groups-regex': 7.29.0(@babel/core@7.29.7) - '@babel/plugin-transform-new-target': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-nullish-coalescing-operator': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-numeric-separator': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-object-rest-spread': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-object-super': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-optional-catch-binding': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-optional-chaining': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-parameters': 7.27.7(@babel/core@7.29.7) - '@babel/plugin-transform-private-methods': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-private-property-in-object': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-property-literals': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-regenerator': 7.29.0(@babel/core@7.29.7) - '@babel/plugin-transform-regexp-modifiers': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-reserved-words': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-shorthand-properties': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-spread': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-sticky-regex': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-template-literals': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-typeof-symbol': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-unicode-escapes': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-unicode-property-regex': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-unicode-regex': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-unicode-sets-regex': 7.28.6(@babel/core@7.29.7) - '@babel/preset-modules': 0.1.6-no-external-plugins(@babel/core@7.29.7) - babel-plugin-polyfill-corejs2: 0.4.17(@babel/core@7.29.7) - babel-plugin-polyfill-corejs3: 0.14.2(@babel/core@7.29.7) - babel-plugin-polyfill-regenerator: 0.6.8(@babel/core@7.29.7) + '@babel/plugin-bugfix-firefox-class-in-computed-class-key': 7.28.5(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-bugfix-safari-class-field-initializer-scope': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-bugfix-safari-rest-destructuring-rhs-array': 7.29.3(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-bugfix-v8-static-class-fields-redefine-readonly': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-proposal-private-property-in-object': 7.21.0-placeholder-for-preset-env.2(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-import-assertions': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-import-attributes': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-unicode-sets-regex': 7.18.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-arrow-functions': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-async-generator-functions': 7.29.0(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-async-to-generator': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-block-scoped-functions': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-block-scoping': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-class-properties': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-class-static-block': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-classes': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-computed-properties': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-destructuring': 7.28.5(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-dotall-regex': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-duplicate-keys': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-duplicate-named-capturing-groups-regex': 7.29.0(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-dynamic-import': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-explicit-resource-management': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-exponentiation-operator': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-export-namespace-from': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-for-of': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-function-name': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-json-strings': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-literals': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-logical-assignment-operators': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-member-expression-literals': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-modules-amd': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-modules-commonjs': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-modules-systemjs': 7.29.4(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-modules-umd': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-named-capturing-groups-regex': 7.29.0(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-new-target': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-nullish-coalescing-operator': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-numeric-separator': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-object-rest-spread': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-object-super': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-optional-catch-binding': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-optional-chaining': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-parameters': 7.27.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-private-methods': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-private-property-in-object': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-property-literals': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-regenerator': 7.29.0(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-regexp-modifiers': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-reserved-words': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-shorthand-properties': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-spread': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-sticky-regex': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-template-literals': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-typeof-symbol': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-unicode-escapes': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-unicode-property-regex': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-unicode-regex': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-unicode-sets-regex': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/preset-modules': 0.1.6-no-external-plugins(@babel/core@7.29.7(supports-color@8.1.1)) + babel-plugin-polyfill-corejs2: 0.4.17(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + babel-plugin-polyfill-corejs3: 0.14.2(@babel/core@7.29.7(supports-color@8.1.1)) + babel-plugin-polyfill-regenerator: 0.6.8(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) core-js-compat: 3.49.0 semver: 6.3.1 transitivePeerDependencies: - supports-color - '@babel/preset-modules@0.1.6-no-external-plugins(@babel/core@7.29.7)': + '@babel/preset-modules@0.1.6-no-external-plugins(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 '@babel/types': 7.29.0 esutils: 2.0.3 - '@babel/preset-react@7.28.5(@babel/core@7.29.7)': + '@babel/preset-react@7.28.5(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 '@babel/helper-validator-option': 7.27.1 - '@babel/plugin-transform-react-display-name': 7.28.0(@babel/core@7.29.7) - '@babel/plugin-transform-react-jsx': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-react-jsx-development': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-react-pure-annotations': 7.27.1(@babel/core@7.29.7) + '@babel/plugin-transform-react-display-name': 7.28.0(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-react-jsx': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-react-jsx-development': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-react-pure-annotations': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) transitivePeerDependencies: - supports-color - '@babel/preset-typescript@7.28.5(@babel/core@7.29.7)': + '@babel/preset-typescript@7.28.5(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/helper-plugin-utils': 7.28.6 '@babel/helper-validator-option': 7.27.1 - '@babel/plugin-syntax-jsx': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-modules-commonjs': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-typescript': 7.28.6(@babel/core@7.29.7) + '@babel/plugin-syntax-jsx': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-modules-commonjs': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-typescript': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) transitivePeerDependencies: - supports-color @@ -8458,11 +8459,11 @@ snapshots: '@babel/parser': 7.29.3 '@babel/template': 7.28.6 '@babel/types': 7.29.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) transitivePeerDependencies: - supports-color - '@babel/traverse@7.29.7': + '@babel/traverse@7.29.7(supports-color@8.1.1)': dependencies: '@babel/code-frame': 7.29.7 '@babel/generator': 7.29.7 @@ -8470,11 +8471,11 @@ snapshots: '@babel/parser': 7.29.7 '@babel/template': 7.29.7 '@babel/types': 7.29.7 - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) transitivePeerDependencies: - supports-color - '@babel/traverse@7.29.8': + '@babel/traverse@7.29.8(supports-color@8.1.1)': dependencies: '@babel/code-frame': 7.29.7 '@babel/generator': 7.29.8 @@ -8482,7 +8483,7 @@ snapshots: '@babel/parser': 7.29.8 '@babel/template': 7.29.7 '@babel/types': 7.29.8 - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) transitivePeerDependencies: - supports-color @@ -8680,22 +8681,22 @@ snapshots: '@esbuild/win32-x64@0.28.1': optional: true - '@eslint-community/eslint-utils@4.10.1(eslint@9.39.4)': + '@eslint-community/eslint-utils@4.10.1(eslint@9.39.4(supports-color@8.1.1))': dependencies: - eslint: 9.39.4 + eslint: 9.39.4(supports-color@8.1.1) eslint-visitor-keys: 3.4.3 - '@eslint-community/eslint-utils@4.9.1(eslint@9.39.4)': + '@eslint-community/eslint-utils@4.9.1(eslint@9.39.4(supports-color@8.1.1))': dependencies: - eslint: 9.39.4 + eslint: 9.39.4(supports-color@8.1.1) eslint-visitor-keys: 3.4.3 '@eslint-community/regexpp@4.12.2': {} - '@eslint/config-array@0.21.2': + '@eslint/config-array@0.21.2(supports-color@8.1.1)': dependencies: '@eslint/object-schema': 2.1.7 - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) minimatch: 3.1.5 transitivePeerDependencies: - supports-color @@ -8708,10 +8709,10 @@ snapshots: dependencies: '@types/json-schema': 7.0.15 - '@eslint/eslintrc@3.3.6': + '@eslint/eslintrc@3.3.6(supports-color@8.1.1)': dependencies: ajv: 6.15.0 - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) espree: 10.4.0 globals: 14.0.0 ignore: 5.3.2 @@ -8733,7 +8734,7 @@ snapshots: '@expo-google-fonts/material-symbols@0.4.34': {} - '@expo/cli@55.0.36(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-constants@55.0.17)(expo-font@55.0.8)(expo-router@55.0.18)(expo@55.0.30)(react-dom@19.2.8(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)(typescript@6.0.3)': + '@expo/cli@55.0.36(@expo/dom-webview@55.0.6)(@expo/metro-runtime@55.0.12)(expo-constants@55.0.17)(expo-font@55.0.8)(expo-router@55.0.18)(expo@55.0.30)(react-dom@19.2.8(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)(typescript@6.0.3)': dependencies: '@expo/code-signing-certificates': 0.0.6 '@expo/config': 55.0.21(typescript@6.0.3) @@ -8742,7 +8743,7 @@ snapshots: '@expo/env': 2.1.3 '@expo/image-utils': 0.8.17(typescript@6.0.3) '@expo/json-file': 10.2.0 - '@expo/log-box': 55.0.13(@expo/dom-webview@55.0.5)(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + '@expo/log-box': 55.0.13(@expo/dom-webview@55.0.6)(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) '@expo/metro': 55.1.2 '@expo/metro-config': 55.0.27(expo@55.0.30)(typescript@6.0.3) '@expo/osascript': 2.7.0 @@ -8750,7 +8751,7 @@ snapshots: '@expo/plist': 0.5.4 '@expo/prebuild-config': 55.0.22(expo@55.0.30)(typescript@6.0.3) '@expo/require-utils': 55.0.8(typescript@6.0.3) - '@expo/router-server': 55.0.19(@expo/metro-runtime@55.0.10)(expo-constants@55.0.17)(expo-font@55.0.8)(expo-router@55.0.18)(expo-server@55.0.12)(expo@55.0.30)(react-dom@19.2.8(react@19.2.8))(react@19.2.8) + '@expo/router-server': 55.0.19(@expo/metro-runtime@55.0.12)(expo-constants@55.0.17)(expo-font@55.0.8)(expo-router@55.0.18)(expo-server@55.0.12)(expo@55.0.30)(react-dom@19.2.8(react@19.2.8))(react@19.2.8) '@expo/schema-utils': 55.0.5 '@expo/spawn-async': 1.8.0 '@expo/ws-tunnel': 1.0.6 @@ -8765,10 +8766,10 @@ snapshots: chalk: 4.1.2 ci-info: 3.9.0 compression: 1.8.1 - connect: 3.7.0 - debug: 4.4.3 + connect: 3.7.0(supports-color@8.1.1) + debug: 4.4.3(supports-color@8.1.1) dnssd-advertise: 1.1.6 - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) expo-server: 55.0.12 fetch-nodeshim: 0.4.10 getenv: 2.0.0 @@ -8795,8 +8796,8 @@ snapshots: ws: 8.21.3 zod: 3.25.76 optionalDependencies: - expo-router: 55.0.18(4a60a26fd685ffdcc7f556016ae4bc5e) - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + expo-router: 55.0.18(98b45897562456c6c413f91e81d6c336) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) transitivePeerDependencies: - '@expo/dom-webview' - '@expo/metro-runtime' @@ -8821,7 +8822,7 @@ snapshots: '@expo/plist': 0.5.4 '@expo/sdk-runtime-versions': 1.0.0 chalk: 4.1.2 - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) getenv: 2.0.0 glob: 13.0.6 resolve-from: 5.0.0 @@ -8839,7 +8840,7 @@ snapshots: '@expo/plist': 0.5.3 '@expo/sdk-runtime-versions': 1.0.0 chalk: 4.1.2 - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) getenv: 2.0.0 glob: 13.0.6 resolve-from: 5.0.0 @@ -8893,23 +8894,23 @@ snapshots: transitivePeerDependencies: - supports-color - '@expo/devtools@55.0.3(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)': + '@expo/devtools@55.0.3(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)': dependencies: chalk: 4.1.2 optionalDependencies: react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) - '@expo/dom-webview@55.0.5(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)': + '@expo/dom-webview@55.0.6(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)': dependencies: - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) '@expo/env@2.1.3': dependencies: chalk: 4.1.2 - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) getenv: 2.0.0 transitivePeerDependencies: - supports-color @@ -8917,7 +8918,7 @@ snapshots: '@expo/env@2.4.2': dependencies: chalk: 4.1.2 - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) getenv: 2.0.0 transitivePeerDependencies: - supports-color @@ -8928,7 +8929,7 @@ snapshots: '@expo/spawn-async': 1.8.0 arg: 5.0.2 chalk: 4.1.2 - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) getenv: 2.0.0 glob: 13.0.6 ignore: 5.3.2 @@ -8979,28 +8980,19 @@ snapshots: - supports-color - typescript - '@expo/log-box@55.0.11(@expo/dom-webview@55.0.5)(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)': + '@expo/log-box@55.0.13(@expo/dom-webview@55.0.6)(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)': dependencies: - '@expo/dom-webview': 55.0.5(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + '@expo/dom-webview': 55.0.6(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) anser: 1.4.10 - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) - stacktrace-parser: 0.1.11 - - '@expo/log-box@55.0.13(@expo/dom-webview@55.0.5)(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)': - dependencies: - '@expo/dom-webview': 55.0.5(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) - anser: 1.4.10 - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) - react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) stacktrace-parser: 0.1.11 '@expo/metro-config@55.0.27(expo@55.0.30)(typescript@6.0.3)': dependencies: '@babel/code-frame': 7.29.7 - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/generator': 7.29.8 '@expo/config': 55.0.21(typescript@6.0.3) '@expo/env': 2.1.3 @@ -9009,7 +9001,7 @@ snapshots: '@expo/spawn-async': 1.8.0 browserslist: 4.28.8 chalk: 4.1.2 - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) getenv: 2.0.0 glob: 13.0.6 hermes-parser: 0.32.1 @@ -9019,21 +9011,21 @@ snapshots: postcss: 8.5.25 resolve-from: 5.0.0 optionalDependencies: - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) transitivePeerDependencies: - bufferutil - supports-color - typescript - utf-8-validate - '@expo/metro-runtime@55.0.10(@expo/dom-webview@55.0.5)(expo@55.0.30)(react-dom@19.2.8(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)': + '@expo/metro-runtime@55.0.12(@expo/dom-webview@55.0.6)(expo@55.0.30)(react-dom@19.2.8(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)': dependencies: - '@expo/log-box': 55.0.11(@expo/dom-webview@55.0.5)(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + '@expo/log-box': 55.0.13(@expo/dom-webview@55.0.6)(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) anser: 1.4.10 - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) pretty-format: 29.7.0 react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) stacktrace-parser: 0.1.11 whatwg-fetch: 3.6.20 optionalDependencies: @@ -9043,20 +9035,20 @@ snapshots: '@expo/metro@55.1.2': dependencies: - metro: 0.83.8 - metro-babel-transformer: 0.83.8 - metro-cache: 0.83.8 + metro: 0.83.8(supports-color@8.1.1) + metro-babel-transformer: 0.83.8(supports-color@8.1.1) + metro-cache: 0.83.8(supports-color@8.1.1) metro-cache-key: 0.83.8 - metro-config: 0.83.8 + metro-config: 0.83.8(supports-color@8.1.1) metro-core: 0.83.8 - metro-file-map: 0.83.8 + metro-file-map: 0.83.8(supports-color@8.1.1) metro-minify-terser: 0.83.8 metro-resolver: 0.83.8 metro-runtime: 0.83.8 - metro-source-map: 0.83.8 + metro-source-map: 0.83.8(supports-color@8.1.1) metro-symbolicate: 0.83.8 - metro-transform-plugins: 0.83.8 - metro-transform-worker: 0.83.8 + metro-transform-plugins: 0.83.8(supports-color@8.1.1) + metro-transform-worker: 0.83.8(supports-color@8.1.1) transitivePeerDependencies: - bufferutil - supports-color @@ -9099,8 +9091,8 @@ snapshots: '@expo/image-utils': 0.8.17(typescript@6.0.3) '@expo/json-file': 10.2.0 '@react-native/normalize-colors': 0.83.10 - debug: 4.4.3 - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + debug: 4.4.3(supports-color@8.1.1) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) resolve-from: 5.0.0 semver: 7.8.5 xml2js: 0.6.0 @@ -9111,8 +9103,8 @@ snapshots: '@expo/require-utils@55.0.5(typescript@5.9.3)': dependencies: '@babel/code-frame': 7.29.0 - '@babel/core': 7.29.7 - '@babel/plugin-transform-modules-commonjs': 7.28.6(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/plugin-transform-modules-commonjs': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) optionalDependencies: typescript: 5.9.3 transitivePeerDependencies: @@ -9121,24 +9113,24 @@ snapshots: '@expo/require-utils@55.0.8(typescript@6.0.3)': dependencies: '@babel/code-frame': 7.29.7 - '@babel/core': 7.29.7 - '@babel/plugin-transform-modules-commonjs': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/plugin-transform-modules-commonjs': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) optionalDependencies: typescript: 6.0.3 transitivePeerDependencies: - supports-color - '@expo/router-server@55.0.19(@expo/metro-runtime@55.0.10)(expo-constants@55.0.17)(expo-font@55.0.8)(expo-router@55.0.18)(expo-server@55.0.12)(expo@55.0.30)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)': + '@expo/router-server@55.0.19(@expo/metro-runtime@55.0.12)(expo-constants@55.0.17)(expo-font@55.0.8)(expo-router@55.0.18)(expo-server@55.0.12)(expo@55.0.30)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)': dependencies: - debug: 4.4.3 - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) - expo-constants: 55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8)) - expo-font: 55.0.8(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + debug: 4.4.3(supports-color@8.1.1) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) + expo-constants: 55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8)) + expo-font: 55.0.8(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) expo-server: 55.0.12 react: 19.2.8 optionalDependencies: - '@expo/metro-runtime': 55.0.10(@expo/dom-webview@55.0.5)(expo@55.0.30)(react-dom@19.2.8(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) - expo-router: 55.0.18(4a60a26fd685ffdcc7f556016ae4bc5e) + '@expo/metro-runtime': 55.0.12(@expo/dom-webview@55.0.6)(expo@55.0.30)(react-dom@19.2.8(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + expo-router: 55.0.18(98b45897562456c6c413f91e81d6c336) react-dom: 19.2.8(react@19.2.8) transitivePeerDependencies: - supports-color @@ -9157,11 +9149,11 @@ snapshots: '@expo/sudo-prompt@9.3.2': {} - '@expo/vector-icons@15.1.1(expo-font@55.0.8)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)': + '@expo/vector-icons@15.1.1(expo-font@55.0.8)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)': dependencies: - expo-font: 55.0.8(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + expo-font: 55.0.8(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) '@expo/ws-tunnel@1.0.6': {} @@ -9216,12 +9208,12 @@ snapshots: jest-util: 29.7.0 slash: 3.0.0 - '@jest/core@29.7.0': + '@jest/core@29.7.0(supports-color@8.1.1)': dependencies: '@jest/console': 29.7.0 - '@jest/reporters': 29.7.0 + '@jest/reporters': 29.7.0(supports-color@8.1.1) '@jest/test-result': 29.7.0 - '@jest/transform': 29.7.0 + '@jest/transform': 29.7.0(supports-color@8.1.1) '@jest/types': 29.6.3 '@types/node': 26.4.0 ansi-escapes: 4.3.2 @@ -9230,15 +9222,15 @@ snapshots: exit: 0.1.2 graceful-fs: 4.2.11 jest-changed-files: 29.7.0 - jest-config: 29.7.0(@types/node@26.4.0) + jest-config: 29.7.0(@types/node@26.4.0)(supports-color@8.1.1) jest-haste-map: 29.7.0 jest-message-util: 29.7.0 jest-regex-util: 29.6.3 jest-resolve: 29.7.0 - jest-resolve-dependencies: 29.7.0 - jest-runner: 29.7.0 - jest-runtime: 29.7.0 - jest-snapshot: 29.7.0 + jest-resolve-dependencies: 29.7.0(supports-color@8.1.1) + jest-runner: 29.7.0(supports-color@8.1.1) + jest-runtime: 29.7.0(supports-color@8.1.1) + jest-snapshot: 29.7.0(supports-color@8.1.1) jest-util: 29.7.0 jest-validate: 29.7.0 jest-watcher: 29.7.0 @@ -9268,10 +9260,10 @@ snapshots: dependencies: jest-get-type: 29.6.3 - '@jest/expect@29.7.0': + '@jest/expect@29.7.0(supports-color@8.1.1)': dependencies: expect: 29.7.0 - jest-snapshot: 29.7.0 + jest-snapshot: 29.7.0(supports-color@8.1.1) transitivePeerDependencies: - supports-color @@ -9286,21 +9278,21 @@ snapshots: '@jest/get-type@30.1.0': {} - '@jest/globals@29.7.0': + '@jest/globals@29.7.0(supports-color@8.1.1)': dependencies: '@jest/environment': 29.7.0 - '@jest/expect': 29.7.0 + '@jest/expect': 29.7.0(supports-color@8.1.1) '@jest/types': 29.6.3 jest-mock: 29.7.0 transitivePeerDependencies: - supports-color - '@jest/reporters@29.7.0': + '@jest/reporters@29.7.0(supports-color@8.1.1)': dependencies: '@bcoe/v8-coverage': 0.2.3 '@jest/console': 29.7.0 '@jest/test-result': 29.7.0 - '@jest/transform': 29.7.0 + '@jest/transform': 29.7.0(supports-color@8.1.1) '@jest/types': 29.6.3 '@jridgewell/trace-mapping': 0.3.31 '@types/node': 26.4.0 @@ -9310,9 +9302,9 @@ snapshots: glob: 7.2.3 graceful-fs: 4.2.11 istanbul-lib-coverage: 3.2.2 - istanbul-lib-instrument: 6.0.3 + istanbul-lib-instrument: 6.0.3(supports-color@8.1.1) istanbul-lib-report: 3.0.1 - istanbul-lib-source-maps: 4.0.1 + istanbul-lib-source-maps: 4.0.1(supports-color@8.1.1) istanbul-reports: 3.2.0 jest-message-util: 29.7.0 jest-util: 29.7.0 @@ -9352,12 +9344,12 @@ snapshots: jest-haste-map: 29.7.0 slash: 3.0.0 - '@jest/transform@29.7.0': + '@jest/transform@29.7.0(supports-color@8.1.1)': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@jest/types': 29.6.3 '@jridgewell/trace-mapping': 0.3.31 - babel-plugin-istanbul: 6.1.1 + babel-plugin-istanbul: 6.1.1(supports-color@8.1.1) chalk: 4.1.2 convert-source-map: 2.0.0 fast-json-stable-stringify: 2.1.0 @@ -9421,11 +9413,11 @@ snapshots: '@noble/hashes@1.8.0': {} - '@orca/expo-two-way-audio@file:packages/expo-two-way-audio(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)': + '@orca/expo-two-way-audio@file:packages/expo-two-way-audio(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)': dependencies: - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) '@oxc-project/types@0.137.0': {} @@ -9737,178 +9729,178 @@ snapshots: optionalDependencies: '@types/react': 19.2.14 - '@react-native-async-storage/async-storage@2.2.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))': + '@react-native-async-storage/async-storage@2.2.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))': dependencies: merge-options: 3.0.4 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) '@react-native/assets-registry@0.83.10': {} - '@react-native/babel-plugin-codegen@0.83.10(@babel/core@7.29.7)': + '@react-native/babel-plugin-codegen@0.83.10(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/traverse': 7.29.8 - '@react-native/codegen': 0.83.10(@babel/core@7.29.7) + '@babel/traverse': 7.29.8(supports-color@8.1.1) + '@react-native/codegen': 0.83.10(@babel/core@7.29.7(supports-color@8.1.1)) transitivePeerDependencies: - '@babel/core' - supports-color - '@react-native/babel-plugin-codegen@0.83.6(@babel/core@7.29.7)': + '@react-native/babel-plugin-codegen@0.83.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/traverse': 7.29.7 - '@react-native/codegen': 0.83.6(@babel/core@7.29.7) + '@babel/traverse': 7.29.7(supports-color@8.1.1) + '@react-native/codegen': 0.83.6(@babel/core@7.29.7(supports-color@8.1.1)) transitivePeerDependencies: - '@babel/core' - supports-color - '@react-native/babel-plugin-codegen@0.85.2(@babel/core@7.29.7)': + '@react-native/babel-plugin-codegen@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)': dependencies: - '@babel/traverse': 7.29.8 - '@react-native/codegen': 0.85.2(@babel/core@7.29.7) + '@babel/traverse': 7.29.8(supports-color@8.1.1) + '@react-native/codegen': 0.85.2(@babel/core@7.29.7(supports-color@8.1.1)) transitivePeerDependencies: - '@babel/core' - supports-color - '@react-native/babel-preset@0.83.10(@babel/core@7.29.7)': + '@react-native/babel-preset@0.83.10(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 - '@babel/plugin-proposal-export-default-from': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-syntax-dynamic-import': 7.8.3(@babel/core@7.29.7) - '@babel/plugin-syntax-export-default-from': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-syntax-nullish-coalescing-operator': 7.8.3(@babel/core@7.29.7) - '@babel/plugin-syntax-optional-chaining': 7.8.3(@babel/core@7.29.7) - '@babel/plugin-transform-arrow-functions': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-async-generator-functions': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-async-to-generator': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-block-scoping': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-class-properties': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-classes': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-computed-properties': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-destructuring': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-flow-strip-types': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-for-of': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-function-name': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-literals': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-logical-assignment-operators': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-modules-commonjs': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-named-capturing-groups-regex': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-nullish-coalescing-operator': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-numeric-separator': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-object-rest-spread': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-optional-catch-binding': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-optional-chaining': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-parameters': 7.27.7(@babel/core@7.29.7) - '@babel/plugin-transform-private-methods': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-private-property-in-object': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-react-display-name': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-react-jsx': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-regenerator': 7.29.8(@babel/core@7.29.7) - '@babel/plugin-transform-runtime': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-shorthand-properties': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-spread': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-sticky-regex': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-typescript': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-unicode-regex': 7.29.7(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/plugin-proposal-export-default-from': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-dynamic-import': 7.8.3(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-export-default-from': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-nullish-coalescing-operator': 7.8.3(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-optional-chaining': 7.8.3(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-arrow-functions': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-async-generator-functions': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-async-to-generator': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-block-scoping': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-class-properties': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-classes': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-computed-properties': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-destructuring': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-flow-strip-types': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-for-of': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-function-name': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-literals': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-logical-assignment-operators': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-modules-commonjs': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-named-capturing-groups-regex': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-nullish-coalescing-operator': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-numeric-separator': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-object-rest-spread': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-optional-catch-binding': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-optional-chaining': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-parameters': 7.27.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-private-methods': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-private-property-in-object': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-react-display-name': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-react-jsx': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-regenerator': 7.29.8(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-runtime': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-shorthand-properties': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-spread': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-sticky-regex': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-typescript': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-unicode-regex': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/template': 7.29.7 - '@react-native/babel-plugin-codegen': 0.83.10(@babel/core@7.29.7) + '@react-native/babel-plugin-codegen': 0.83.10(@babel/core@7.29.7(supports-color@8.1.1)) babel-plugin-syntax-hermes-parser: 0.32.0 - babel-plugin-transform-flow-enums: 0.0.2(@babel/core@7.29.7) + babel-plugin-transform-flow-enums: 0.0.2(@babel/core@7.29.7(supports-color@8.1.1)) react-refresh: 0.14.2 transitivePeerDependencies: - supports-color - '@react-native/babel-preset@0.83.6(@babel/core@7.29.7)': + '@react-native/babel-preset@0.83.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 - '@babel/plugin-proposal-export-default-from': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-syntax-dynamic-import': 7.8.3(@babel/core@7.29.7) - '@babel/plugin-syntax-export-default-from': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-syntax-nullish-coalescing-operator': 7.8.3(@babel/core@7.29.7) - '@babel/plugin-syntax-optional-chaining': 7.8.3(@babel/core@7.29.7) - '@babel/plugin-transform-arrow-functions': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-async-generator-functions': 7.29.0(@babel/core@7.29.7) - '@babel/plugin-transform-async-to-generator': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-block-scoping': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-class-properties': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-classes': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-computed-properties': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-destructuring': 7.28.5(@babel/core@7.29.7) - '@babel/plugin-transform-flow-strip-types': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-for-of': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-function-name': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-literals': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-logical-assignment-operators': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-modules-commonjs': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-named-capturing-groups-regex': 7.29.0(@babel/core@7.29.7) - '@babel/plugin-transform-nullish-coalescing-operator': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-numeric-separator': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-object-rest-spread': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-optional-catch-binding': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-optional-chaining': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-parameters': 7.27.7(@babel/core@7.29.7) - '@babel/plugin-transform-private-methods': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-private-property-in-object': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-react-display-name': 7.28.0(@babel/core@7.29.7) - '@babel/plugin-transform-react-jsx': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-react-jsx-source': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-regenerator': 7.29.0(@babel/core@7.29.7) - '@babel/plugin-transform-runtime': 7.29.0(@babel/core@7.29.7) - '@babel/plugin-transform-shorthand-properties': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-spread': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-sticky-regex': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-typescript': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-unicode-regex': 7.27.1(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/plugin-proposal-export-default-from': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-dynamic-import': 7.8.3(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-export-default-from': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-nullish-coalescing-operator': 7.8.3(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-optional-chaining': 7.8.3(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-arrow-functions': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-async-generator-functions': 7.29.0(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-async-to-generator': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-block-scoping': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-class-properties': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-classes': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-computed-properties': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-destructuring': 7.28.5(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-flow-strip-types': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-for-of': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-function-name': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-literals': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-logical-assignment-operators': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-modules-commonjs': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-named-capturing-groups-regex': 7.29.0(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-nullish-coalescing-operator': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-numeric-separator': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-object-rest-spread': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-optional-catch-binding': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-optional-chaining': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-parameters': 7.27.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-private-methods': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-private-property-in-object': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-react-display-name': 7.28.0(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-react-jsx': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-react-jsx-source': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-regenerator': 7.29.0(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-runtime': 7.29.0(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-shorthand-properties': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-spread': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-sticky-regex': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-typescript': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-unicode-regex': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/template': 7.28.6 - '@react-native/babel-plugin-codegen': 0.83.6(@babel/core@7.29.7) + '@react-native/babel-plugin-codegen': 0.83.6(@babel/core@7.29.7(supports-color@8.1.1)) babel-plugin-syntax-hermes-parser: 0.32.0 - babel-plugin-transform-flow-enums: 0.0.2(@babel/core@7.29.7) + babel-plugin-transform-flow-enums: 0.0.2(@babel/core@7.29.7(supports-color@8.1.1)) react-refresh: 0.14.2 transitivePeerDependencies: - supports-color - '@react-native/babel-preset@0.85.2(@babel/core@7.29.7)': + '@react-native/babel-preset@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)': dependencies: - '@babel/core': 7.29.7 - '@babel/plugin-proposal-export-default-from': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-syntax-dynamic-import': 7.8.3(@babel/core@7.29.7) - '@babel/plugin-syntax-export-default-from': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-syntax-nullish-coalescing-operator': 7.8.3(@babel/core@7.29.7) - '@babel/plugin-syntax-optional-chaining': 7.8.3(@babel/core@7.29.7) - '@babel/plugin-transform-async-generator-functions': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-async-to-generator': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-block-scoping': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-class-properties': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-classes': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-destructuring': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-flow-strip-types': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-for-of': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-modules-commonjs': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-named-capturing-groups-regex': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-nullish-coalescing-operator': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-optional-catch-binding': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-optional-chaining': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-private-methods': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-private-property-in-object': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-react-display-name': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-react-jsx': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-regenerator': 7.29.8(@babel/core@7.29.7) - '@babel/plugin-transform-runtime': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-typescript': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-unicode-regex': 7.29.7(@babel/core@7.29.7) - '@react-native/babel-plugin-codegen': 0.85.2(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/plugin-proposal-export-default-from': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-dynamic-import': 7.8.3(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-export-default-from': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-nullish-coalescing-operator': 7.8.3(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-optional-chaining': 7.8.3(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-async-generator-functions': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-async-to-generator': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-block-scoping': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-class-properties': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-classes': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-destructuring': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-flow-strip-types': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-for-of': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-modules-commonjs': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-named-capturing-groups-regex': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-nullish-coalescing-operator': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-optional-catch-binding': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-optional-chaining': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-private-methods': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-private-property-in-object': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-react-display-name': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-react-jsx': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-regenerator': 7.29.8(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-runtime': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-typescript': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-unicode-regex': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@react-native/babel-plugin-codegen': 0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) babel-plugin-syntax-hermes-parser: 0.33.3 - babel-plugin-transform-flow-enums: 0.0.2(@babel/core@7.29.7) + babel-plugin-transform-flow-enums: 0.0.2(@babel/core@7.29.7(supports-color@8.1.1)) react-refresh: 0.14.2 transitivePeerDependencies: - supports-color - '@react-native/codegen@0.83.10(@babel/core@7.29.7)': + '@react-native/codegen@0.83.10(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/parser': 7.29.8 glob: 7.2.3 hermes-parser: 0.32.0 @@ -9916,9 +9908,9 @@ snapshots: nullthrows: 1.1.1 yargs: 17.7.3 - '@react-native/codegen@0.83.6(@babel/core@7.29.7)': + '@react-native/codegen@0.83.6(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/parser': 7.29.7 glob: 7.2.3 hermes-parser: 0.32.0 @@ -9926,9 +9918,9 @@ snapshots: nullthrows: 1.1.1 yargs: 17.7.2 - '@react-native/codegen@0.85.2(@babel/core@7.29.7)': + '@react-native/codegen@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))': dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/parser': 7.29.8 hermes-parser: 0.33.3 invariant: 2.2.4 @@ -9936,17 +9928,17 @@ snapshots: tinyglobby: 0.2.17 yargs: 17.7.3 - '@react-native/community-cli-plugin@0.83.10(@react-native/metro-config@0.85.2(@babel/core@7.29.7))': + '@react-native/community-cli-plugin@0.83.10(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))': dependencies: '@react-native/dev-middleware': 0.83.10 - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) invariant: 2.2.4 - metro: 0.83.7 - metro-config: 0.83.7 + metro: 0.83.7(supports-color@8.1.1) + metro-config: 0.83.7(supports-color@8.1.1) metro-core: 0.83.7 semver: 7.8.5 optionalDependencies: - '@react-native/metro-config': 0.85.2(@babel/core@7.29.7) + '@react-native/metro-config': 0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) transitivePeerDependencies: - bufferutil - supports-color @@ -9966,8 +9958,8 @@ snapshots: '@react-native/debugger-shell': 0.83.10 chrome-launcher: 0.15.2 chromium-edge-launcher: 0.2.0 - connect: 3.7.0 - debug: 4.4.3 + connect: 3.7.0(supports-color@8.1.1) + debug: 4.4.3(supports-color@8.1.1) invariant: 2.2.4 nullthrows: 1.1.1 open: 7.4.2 @@ -9984,20 +9976,20 @@ snapshots: '@react-native/js-polyfills@0.85.2': {} - '@react-native/metro-babel-transformer@0.85.2(@babel/core@7.29.7)': + '@react-native/metro-babel-transformer@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)': dependencies: - '@babel/core': 7.29.7 - '@react-native/babel-preset': 0.85.2(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@react-native/babel-preset': 0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) hermes-parser: 0.33.3 nullthrows: 1.1.1 transitivePeerDependencies: - supports-color - '@react-native/metro-config@0.85.2(@babel/core@7.29.7)': + '@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)': dependencies: '@react-native/js-polyfills': 0.85.2 - '@react-native/metro-babel-transformer': 0.85.2(@babel/core@7.29.7) - metro-config: 0.84.5 + '@react-native/metro-babel-transformer': 0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + metro-config: 0.84.5(supports-color@8.1.1) metro-runtime: 0.84.5 transitivePeerDependencies: - '@babel/core' @@ -10009,24 +10001,24 @@ snapshots: '@react-native/normalize-colors@0.83.10': {} - '@react-native/virtualized-lists@0.83.10(@types/react@19.2.14)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)': + '@react-native/virtualized-lists@0.83.10(@types/react@19.2.14)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)': dependencies: invariant: 2.2.4 nullthrows: 1.1.1 react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) optionalDependencies: '@types/react': 19.2.14 - ? '@react-navigation/bottom-tabs@7.15.11(@react-navigation/native@7.2.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native-safe-area-context@5.7.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native-screens@4.24.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)' - : dependencies: - '@react-navigation/elements': 2.9.15(@react-navigation/native@7.2.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native-safe-area-context@5.7.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) - '@react-navigation/native': 7.2.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + '@react-navigation/bottom-tabs@7.15.11(edc9e9b19f67aea8a6d8a2ee54babcc5)': + dependencies: + '@react-navigation/elements': 2.9.15(@react-navigation/native@7.2.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native-safe-area-context@5.7.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + '@react-navigation/native': 7.2.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) color: 4.2.3 react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) - react-native-safe-area-context: 5.7.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) - react-native-screens: 4.24.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) + react-native-safe-area-context: 5.7.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + react-native-screens: 4.24.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) sf-symbols-typescript: 2.2.0 transitivePeerDependencies: - '@react-native-masked-view/masked-view' @@ -10043,38 +10035,38 @@ snapshots: use-latest-callback: 0.2.6(react@19.2.8) use-sync-external-store: 1.6.0(react@19.2.8) - '@react-navigation/elements@2.9.15(@react-navigation/native@7.2.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native-safe-area-context@5.7.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)': + '@react-navigation/elements@2.9.15(@react-navigation/native@7.2.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native-safe-area-context@5.7.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)': dependencies: - '@react-navigation/native': 7.2.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + '@react-navigation/native': 7.2.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) color: 4.2.3 react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) - react-native-safe-area-context: 5.7.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) + react-native-safe-area-context: 5.7.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) use-latest-callback: 0.2.6(react@19.2.8) use-sync-external-store: 1.6.0(react@19.2.8) - ? '@react-navigation/native-stack@7.14.12(@react-navigation/native@7.2.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native-safe-area-context@5.7.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native-screens@4.24.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)' - : dependencies: - '@react-navigation/elements': 2.9.15(@react-navigation/native@7.2.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native-safe-area-context@5.7.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) - '@react-navigation/native': 7.2.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + '@react-navigation/native-stack@7.14.12(edc9e9b19f67aea8a6d8a2ee54babcc5)': + dependencies: + '@react-navigation/elements': 2.9.15(@react-navigation/native@7.2.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native-safe-area-context@5.7.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + '@react-navigation/native': 7.2.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) color: 4.2.3 react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) - react-native-safe-area-context: 5.7.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) - react-native-screens: 4.24.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) + react-native-safe-area-context: 5.7.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + react-native-screens: 4.24.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) sf-symbols-typescript: 2.2.0 warn-once: 0.1.1 transitivePeerDependencies: - '@react-native-masked-view/masked-view' - '@react-navigation/native@7.2.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)': + '@react-navigation/native@7.2.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)': dependencies: '@react-navigation/core': 7.17.2(react@19.2.8) escape-string-regexp: 4.0.0 fast-deep-equal: 3.1.3 nanoid: 3.3.18 react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) use-latest-callback: 0.2.6(react@19.2.8) '@react-navigation/routers@7.5.3': @@ -10148,17 +10140,17 @@ snapshots: '@standard-schema/spec@1.1.0': {} - '@testing-library/react-native@13.3.3(jest@29.7.0(@types/node@26.4.0))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react-test-renderer@19.2.8(react@19.2.8))(react@19.2.8)': + '@testing-library/react-native@13.3.3(jest@29.7.0(@types/node@26.4.0)(supports-color@8.1.1))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react-test-renderer@19.2.8(react@19.2.8))(react@19.2.8)': dependencies: jest-matcher-utils: 30.3.0 picocolors: 1.1.1 pretty-format: 30.3.0 react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) react-test-renderer: 19.2.8(react@19.2.8) redent: 3.0.0 optionalDependencies: - jest: 29.7.0(@types/node@26.4.0) + jest: 29.7.0(@types/node@26.4.0)(supports-color@8.1.1) '@tootallnate/once@2.0.1': {} @@ -10371,9 +10363,9 @@ snapshots: dependencies: undici-types: 8.3.0 - '@types/react-native@0.73.0(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8)': + '@types/react-native@0.73.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8)': dependencies: - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) transitivePeerDependencies: - '@babel/core' - '@react-native-community/cli' @@ -10413,15 +10405,15 @@ snapshots: dependencies: '@types/yargs-parser': 21.0.3 - '@typescript-eslint/eslint-plugin@8.59.2(@typescript-eslint/parser@8.59.2(eslint@9.39.4)(typescript@5.9.3))(eslint@9.39.4)(typescript@5.9.3)': + '@typescript-eslint/eslint-plugin@8.59.2(@typescript-eslint/parser@8.59.2(eslint@9.39.4(supports-color@8.1.1))(typescript@5.9.3))(eslint@9.39.4(supports-color@8.1.1))(typescript@5.9.3)': dependencies: '@eslint-community/regexpp': 4.12.2 - '@typescript-eslint/parser': 8.59.2(eslint@9.39.4)(typescript@6.0.3) + '@typescript-eslint/parser': 8.59.2(eslint@9.39.4(supports-color@8.1.1))(typescript@5.9.3) '@typescript-eslint/scope-manager': 8.59.2 - '@typescript-eslint/type-utils': 8.59.2(eslint@9.39.4)(typescript@5.9.3) - '@typescript-eslint/utils': 8.59.2(eslint@9.39.4)(typescript@5.9.3) + '@typescript-eslint/type-utils': 8.59.2(eslint@9.39.4(supports-color@8.1.1))(typescript@5.9.3) + '@typescript-eslint/utils': 8.59.2(eslint@9.39.4(supports-color@8.1.1))(typescript@5.9.3) '@typescript-eslint/visitor-keys': 8.59.2 - eslint: 9.39.4 + eslint: 9.39.4(supports-color@8.1.1) ignore: 7.0.5 natural-compare: 1.4.0 ts-api-utils: 2.5.0(typescript@5.9.3) @@ -10429,15 +10421,15 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/parser@8.59.2(eslint@9.39.4)(typescript@6.0.3)': + '@typescript-eslint/parser@8.59.2(eslint@9.39.4(supports-color@8.1.1))(typescript@5.9.3)': dependencies: '@typescript-eslint/scope-manager': 8.59.2 '@typescript-eslint/types': 8.59.2 '@typescript-eslint/typescript-estree': 8.59.2(typescript@5.9.3) '@typescript-eslint/visitor-keys': 8.59.2 - debug: 4.4.3 - eslint: 9.39.4 - typescript: 6.0.3 + debug: 4.4.3(supports-color@8.1.1) + eslint: 9.39.4(supports-color@8.1.1) + typescript: 5.9.3 transitivePeerDependencies: - supports-color @@ -10445,7 +10437,7 @@ snapshots: dependencies: '@typescript-eslint/tsconfig-utils': 8.59.2(typescript@5.9.3) '@typescript-eslint/types': 8.59.2 - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) typescript: 5.9.3 transitivePeerDependencies: - supports-color @@ -10459,13 +10451,13 @@ snapshots: dependencies: typescript: 5.9.3 - '@typescript-eslint/type-utils@8.59.2(eslint@9.39.4)(typescript@5.9.3)': + '@typescript-eslint/type-utils@8.59.2(eslint@9.39.4(supports-color@8.1.1))(typescript@5.9.3)': dependencies: '@typescript-eslint/types': 8.59.2 '@typescript-eslint/typescript-estree': 8.59.2(typescript@5.9.3) - '@typescript-eslint/utils': 8.59.2(eslint@9.39.4)(typescript@5.9.3) - debug: 4.4.3 - eslint: 9.39.4 + '@typescript-eslint/utils': 8.59.2(eslint@9.39.4(supports-color@8.1.1))(typescript@5.9.3) + debug: 4.4.3(supports-color@8.1.1) + eslint: 9.39.4(supports-color@8.1.1) ts-api-utils: 2.5.0(typescript@5.9.3) typescript: 5.9.3 transitivePeerDependencies: @@ -10479,7 +10471,7 @@ snapshots: '@typescript-eslint/tsconfig-utils': 8.59.2(typescript@5.9.3) '@typescript-eslint/types': 8.59.2 '@typescript-eslint/visitor-keys': 8.59.2 - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) minimatch: 10.2.5 semver: 7.8.5 tinyglobby: 0.2.17 @@ -10488,13 +10480,13 @@ snapshots: transitivePeerDependencies: - supports-color - '@typescript-eslint/utils@8.59.2(eslint@9.39.4)(typescript@5.9.3)': + '@typescript-eslint/utils@8.59.2(eslint@9.39.4(supports-color@8.1.1))(typescript@5.9.3)': dependencies: - '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.4) + '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.4(supports-color@8.1.1)) '@typescript-eslint/scope-manager': 8.59.2 '@typescript-eslint/types': 8.59.2 '@typescript-eslint/typescript-estree': 8.59.2(typescript@5.9.3) - eslint: 9.39.4 + eslint: 9.39.4(supports-color@8.1.1) typescript: 5.9.3 transitivePeerDependencies: - supports-color @@ -10628,9 +10620,9 @@ snapshots: acorn@8.15.0: {} - agent-base@6.0.2: + agent-base@6.0.2(supports-color@8.1.1): dependencies: - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) transitivePeerDependencies: - supports-color @@ -10765,13 +10757,13 @@ snapshots: dependencies: possible-typed-array-names: 1.1.0 - babel-jest@29.7.0(@babel/core@7.29.7): + babel-jest@29.7.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1): dependencies: - '@babel/core': 7.29.7 - '@jest/transform': 29.7.0 + '@babel/core': 7.29.7(supports-color@8.1.1) + '@jest/transform': 29.7.0(supports-color@8.1.1) '@types/babel__core': 7.20.5 - babel-plugin-istanbul: 6.1.1 - babel-preset-jest: 29.6.3(@babel/core@7.29.7) + babel-plugin-istanbul: 6.1.1(supports-color@8.1.1) + babel-preset-jest: 29.6.3(@babel/core@7.29.7(supports-color@8.1.1)) chalk: 4.1.2 graceful-fs: 4.2.11 slash: 3.0.0 @@ -10782,12 +10774,12 @@ snapshots: dependencies: object.assign: 4.1.7 - babel-plugin-istanbul@6.1.1: + babel-plugin-istanbul@6.1.1(supports-color@8.1.1): dependencies: '@babel/helper-plugin-utils': 7.29.7 '@istanbuljs/load-nyc-config': 1.1.0 '@istanbuljs/schema': 0.1.6 - istanbul-lib-instrument: 5.2.1 + istanbul-lib-instrument: 5.2.1(supports-color@8.1.1) test-exclude: 6.0.0 transitivePeerDependencies: - supports-color @@ -10799,35 +10791,35 @@ snapshots: '@types/babel__core': 7.20.5 '@types/babel__traverse': 7.28.0 - babel-plugin-polyfill-corejs2@0.4.17(@babel/core@7.29.7): + babel-plugin-polyfill-corejs2@0.4.17(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1): dependencies: '@babel/compat-data': 7.29.3 - '@babel/core': 7.29.7 - '@babel/helper-define-polyfill-provider': 0.6.8(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-define-polyfill-provider': 0.6.8(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) semver: 6.3.1 transitivePeerDependencies: - supports-color - babel-plugin-polyfill-corejs3@0.13.0(@babel/core@7.29.7): + babel-plugin-polyfill-corejs3@0.13.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1): dependencies: - '@babel/core': 7.29.7 - '@babel/helper-define-polyfill-provider': 0.6.8(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-define-polyfill-provider': 0.6.8(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) core-js-compat: 3.49.0 transitivePeerDependencies: - supports-color - babel-plugin-polyfill-corejs3@0.14.2(@babel/core@7.29.7): + babel-plugin-polyfill-corejs3@0.14.2(@babel/core@7.29.7(supports-color@8.1.1)): dependencies: - '@babel/core': 7.29.7 - '@babel/helper-define-polyfill-provider': 0.6.8(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-define-polyfill-provider': 0.6.8(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) core-js-compat: 3.49.0 transitivePeerDependencies: - supports-color - babel-plugin-polyfill-regenerator@0.6.8(@babel/core@7.29.7): + babel-plugin-polyfill-regenerator@0.6.8(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1): dependencies: - '@babel/core': 7.29.7 - '@babel/helper-define-polyfill-provider': 0.6.8(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/helper-define-polyfill-provider': 0.6.8(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) transitivePeerDependencies: - supports-color @@ -10849,102 +10841,102 @@ snapshots: dependencies: hermes-parser: 0.33.3 - babel-plugin-transform-flow-enums@0.0.2(@babel/core@7.29.7): + babel-plugin-transform-flow-enums@0.0.2(@babel/core@7.29.7(supports-color@8.1.1)): dependencies: - '@babel/plugin-syntax-flow': 7.28.6(@babel/core@7.29.7) + '@babel/plugin-syntax-flow': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) transitivePeerDependencies: - '@babel/core' - babel-preset-current-node-syntax@1.2.0(@babel/core@7.29.7): + babel-preset-current-node-syntax@1.2.0(@babel/core@7.29.7(supports-color@8.1.1)): dependencies: - '@babel/core': 7.29.7 - '@babel/plugin-syntax-async-generators': 7.8.4(@babel/core@7.29.7) - '@babel/plugin-syntax-bigint': 7.8.3(@babel/core@7.29.7) - '@babel/plugin-syntax-class-properties': 7.12.13(@babel/core@7.29.7) - '@babel/plugin-syntax-class-static-block': 7.14.5(@babel/core@7.29.7) - '@babel/plugin-syntax-import-attributes': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-syntax-import-meta': 7.10.4(@babel/core@7.29.7) - '@babel/plugin-syntax-json-strings': 7.8.3(@babel/core@7.29.7) - '@babel/plugin-syntax-logical-assignment-operators': 7.10.4(@babel/core@7.29.7) - '@babel/plugin-syntax-nullish-coalescing-operator': 7.8.3(@babel/core@7.29.7) - '@babel/plugin-syntax-numeric-separator': 7.10.4(@babel/core@7.29.7) - '@babel/plugin-syntax-object-rest-spread': 7.8.3(@babel/core@7.29.7) - '@babel/plugin-syntax-optional-catch-binding': 7.8.3(@babel/core@7.29.7) - '@babel/plugin-syntax-optional-chaining': 7.8.3(@babel/core@7.29.7) - '@babel/plugin-syntax-private-property-in-object': 7.14.5(@babel/core@7.29.7) - '@babel/plugin-syntax-top-level-await': 7.14.5(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/plugin-syntax-async-generators': 7.8.4(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-bigint': 7.8.3(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-class-properties': 7.12.13(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-class-static-block': 7.14.5(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-import-attributes': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-import-meta': 7.10.4(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-json-strings': 7.8.3(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-logical-assignment-operators': 7.10.4(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-nullish-coalescing-operator': 7.8.3(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-numeric-separator': 7.10.4(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-object-rest-spread': 7.8.3(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-optional-catch-binding': 7.8.3(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-optional-chaining': 7.8.3(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-private-property-in-object': 7.14.5(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-top-level-await': 7.14.5(@babel/core@7.29.7(supports-color@8.1.1)) - babel-preset-expo@55.0.21(@babel/core@7.29.7)(@babel/runtime@7.29.7)(expo@55.0.30)(react-refresh@0.14.2): + babel-preset-expo@55.0.21(@babel/core@7.29.7(supports-color@8.1.1))(@babel/runtime@7.29.7)(expo@55.0.30)(react-refresh@0.14.2): dependencies: '@babel/generator': 7.29.1 '@babel/helper-module-imports': 7.28.6 - '@babel/plugin-proposal-decorators': 7.29.0(@babel/core@7.29.7) - '@babel/plugin-proposal-export-default-from': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-syntax-export-default-from': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-class-static-block': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-export-namespace-from': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-flow-strip-types': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-modules-commonjs': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-object-rest-spread': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-parameters': 7.27.7(@babel/core@7.29.7) - '@babel/plugin-transform-private-methods': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-private-property-in-object': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-runtime': 7.29.0(@babel/core@7.29.7) - '@babel/preset-react': 7.28.5(@babel/core@7.29.7) - '@babel/preset-typescript': 7.28.5(@babel/core@7.29.7) - '@react-native/babel-preset': 0.83.6(@babel/core@7.29.7) + '@babel/plugin-proposal-decorators': 7.29.0(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-proposal-export-default-from': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-export-default-from': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-class-static-block': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-export-namespace-from': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-flow-strip-types': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-modules-commonjs': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-object-rest-spread': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-parameters': 7.27.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-private-methods': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-private-property-in-object': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-runtime': 7.29.0(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/preset-react': 7.28.5(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/preset-typescript': 7.28.5(@babel/core@7.29.7(supports-color@8.1.1)) + '@react-native/babel-preset': 0.83.6(@babel/core@7.29.7(supports-color@8.1.1)) babel-plugin-react-compiler: 1.0.0 babel-plugin-react-native-web: 0.21.2 babel-plugin-syntax-hermes-parser: 0.32.1 - babel-plugin-transform-flow-enums: 0.0.2(@babel/core@7.29.7) - debug: 4.4.3 + babel-plugin-transform-flow-enums: 0.0.2(@babel/core@7.29.7(supports-color@8.1.1)) + debug: 4.4.3(supports-color@8.1.1) react-refresh: 0.14.2 resolve-from: 5.0.0 optionalDependencies: '@babel/runtime': 7.29.7 - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) transitivePeerDependencies: - '@babel/core' - supports-color - babel-preset-expo@55.0.25(@babel/core@7.29.7)(@babel/runtime@7.29.7)(expo@55.0.30)(react-refresh@0.14.2): + babel-preset-expo@55.0.25(@babel/core@7.29.7(supports-color@8.1.1))(@babel/runtime@7.29.7)(expo@55.0.30)(react-refresh@0.14.2): dependencies: '@babel/generator': 7.29.8 - '@babel/helper-module-imports': 7.29.7 - '@babel/plugin-proposal-decorators': 7.29.0(@babel/core@7.29.7) - '@babel/plugin-proposal-export-default-from': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-syntax-export-default-from': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-class-static-block': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-export-namespace-from': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-flow-strip-types': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-modules-commonjs': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-object-rest-spread': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-parameters': 7.27.7(@babel/core@7.29.7) - '@babel/plugin-transform-private-methods': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-private-property-in-object': 7.29.7(@babel/core@7.29.7) - '@babel/plugin-transform-runtime': 7.29.7(@babel/core@7.29.7) - '@babel/preset-react': 7.28.5(@babel/core@7.29.7) - '@babel/preset-typescript': 7.28.5(@babel/core@7.29.7) - '@react-native/babel-preset': 0.83.10(@babel/core@7.29.7) + '@babel/helper-module-imports': 7.29.7(supports-color@8.1.1) + '@babel/plugin-proposal-decorators': 7.29.0(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-proposal-export-default-from': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-export-default-from': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-class-static-block': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-export-namespace-from': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-flow-strip-types': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-modules-commonjs': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-object-rest-spread': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-parameters': 7.27.7(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-private-methods': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-private-property-in-object': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/plugin-transform-runtime': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/preset-react': 7.28.5(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/preset-typescript': 7.28.5(@babel/core@7.29.7(supports-color@8.1.1)) + '@react-native/babel-preset': 0.83.10(@babel/core@7.29.7(supports-color@8.1.1)) babel-plugin-react-compiler: 1.0.0 babel-plugin-react-native-web: 0.21.2 babel-plugin-syntax-hermes-parser: 0.32.1 - babel-plugin-transform-flow-enums: 0.0.2(@babel/core@7.29.7) - debug: 4.4.3 + babel-plugin-transform-flow-enums: 0.0.2(@babel/core@7.29.7(supports-color@8.1.1)) + debug: 4.4.3(supports-color@8.1.1) react-refresh: 0.14.2 resolve-from: 5.0.0 optionalDependencies: '@babel/runtime': 7.29.7 - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) transitivePeerDependencies: - '@babel/core' - supports-color - babel-preset-jest@29.6.3(@babel/core@7.29.7): + babel-preset-jest@29.6.3(@babel/core@7.29.7(supports-color@8.1.1)): dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) babel-plugin-jest-hoist: 29.6.3 - babel-preset-current-node-syntax: 1.2.0(@babel/core@7.29.7) + babel-preset-current-node-syntax: 1.2.0(@babel/core@7.29.7(supports-color@8.1.1)) badgin@1.2.3: {} @@ -11177,7 +11169,7 @@ snapshots: dependencies: bytes: 3.1.2 compressible: 2.0.18 - debug: 2.6.9 + debug: 2.6.9(supports-color@8.1.1) negotiator: 0.6.4 on-headers: 1.1.0 safe-buffer: 5.2.1 @@ -11187,10 +11179,10 @@ snapshots: concat-map@0.0.1: {} - connect@3.7.0: + connect@3.7.0(supports-color@8.1.1): dependencies: - debug: 2.6.9 - finalhandler: 1.1.2 + debug: 2.6.9(supports-color@8.1.1) + finalhandler: 1.1.2(supports-color@8.1.1) parseurl: 1.3.3 utils-merge: 1.0.1 transitivePeerDependencies: @@ -11210,13 +11202,13 @@ snapshots: dependencies: layout-base: 2.0.1 - create-jest@29.7.0(@types/node@26.4.0): + create-jest@29.7.0(@types/node@26.4.0)(supports-color@8.1.1): dependencies: '@jest/types': 29.6.3 chalk: 4.1.2 exit: 0.1.2 graceful-fs: 4.2.11 - jest-config: 29.7.0(@types/node@26.4.0) + jest-config: 29.7.0(@types/node@26.4.0)(supports-color@8.1.1) jest-util: 29.7.0 prompts: 2.4.2 transitivePeerDependencies: @@ -11476,17 +11468,21 @@ snapshots: dayjs@1.11.21: {} - debug@2.6.9: + debug@2.6.9(supports-color@8.1.1): dependencies: ms: 2.0.0 + optionalDependencies: + supports-color: 8.1.1 debug@3.2.7: dependencies: ms: 2.1.3 - debug@4.4.3: + debug@4.4.3(supports-color@8.1.1): dependencies: ms: 2.1.3 + optionalDependencies: + supports-color: 8.1.1 decimal.js@10.6.0: {} @@ -11789,27 +11785,27 @@ snapshots: optionalDependencies: source-map: 0.6.1 - eslint-compat-utils@0.5.1(eslint@9.39.4): + eslint-compat-utils@0.5.1(eslint@9.39.4(supports-color@8.1.1)): dependencies: - eslint: 9.39.4 + eslint: 9.39.4(supports-color@8.1.1) semver: 7.8.5 - eslint-config-prettier@9.1.2(eslint@9.39.4): + eslint-config-prettier@9.1.2(eslint@9.39.4(supports-color@8.1.1)): dependencies: - eslint: 9.39.4 + eslint: 9.39.4(supports-color@8.1.1) - eslint-config-universe@15.0.4(eslint@9.39.4)(prettier@2.8.8)(typescript@5.9.3): + eslint-config-universe@15.0.4(eslint@9.39.4(supports-color@8.1.1))(prettier@2.8.8)(typescript@5.9.3): dependencies: - '@typescript-eslint/eslint-plugin': 8.59.2(@typescript-eslint/parser@8.59.2(eslint@9.39.4)(typescript@5.9.3))(eslint@9.39.4)(typescript@5.9.3) - '@typescript-eslint/parser': 8.59.2(eslint@9.39.4)(typescript@6.0.3) - eslint: 9.39.4 - eslint-config-prettier: 9.1.2(eslint@9.39.4) - eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.59.2(eslint@9.39.4)(typescript@5.9.3))(eslint@9.39.4) - eslint-plugin-n: 17.24.0(eslint@9.39.4)(typescript@5.9.3) - eslint-plugin-node: 11.1.0(eslint@9.39.4) - eslint-plugin-prettier: 5.5.5(eslint-config-prettier@9.1.2(eslint@9.39.4))(eslint@9.39.4)(prettier@2.8.8) - eslint-plugin-react: 7.37.5(eslint@9.39.4) - eslint-plugin-react-hooks: 5.2.0(eslint@9.39.4) + '@typescript-eslint/eslint-plugin': 8.59.2(@typescript-eslint/parser@8.59.2(eslint@9.39.4(supports-color@8.1.1))(typescript@5.9.3))(eslint@9.39.4(supports-color@8.1.1))(typescript@5.9.3) + '@typescript-eslint/parser': 8.59.2(eslint@9.39.4(supports-color@8.1.1))(typescript@5.9.3) + eslint: 9.39.4(supports-color@8.1.1) + eslint-config-prettier: 9.1.2(eslint@9.39.4(supports-color@8.1.1)) + eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.59.2(eslint@9.39.4(supports-color@8.1.1))(typescript@5.9.3))(eslint@9.39.4(supports-color@8.1.1)) + eslint-plugin-n: 17.24.0(eslint@9.39.4(supports-color@8.1.1))(typescript@5.9.3) + eslint-plugin-node: 11.1.0(eslint@9.39.4(supports-color@8.1.1)) + eslint-plugin-prettier: 5.5.5(eslint-config-prettier@9.1.2(eslint@9.39.4(supports-color@8.1.1)))(eslint@9.39.4(supports-color@8.1.1))(prettier@2.8.8) + eslint-plugin-react: 7.37.5(eslint@9.39.4(supports-color@8.1.1)) + eslint-plugin-react-hooks: 5.2.0(eslint@9.39.4(supports-color@8.1.1)) globals: 16.5.0 optionalDependencies: prettier: 2.8.8 @@ -11828,30 +11824,30 @@ snapshots: transitivePeerDependencies: - supports-color - eslint-module-utils@2.12.1(@typescript-eslint/parser@8.59.2(eslint@9.39.4)(typescript@5.9.3))(eslint-import-resolver-node@0.3.10)(eslint@9.39.4): + eslint-module-utils@2.12.1(@typescript-eslint/parser@8.59.2(eslint@9.39.4(supports-color@8.1.1))(typescript@5.9.3))(eslint-import-resolver-node@0.3.10)(eslint@9.39.4(supports-color@8.1.1)): dependencies: debug: 3.2.7 optionalDependencies: - '@typescript-eslint/parser': 8.59.2(eslint@9.39.4)(typescript@6.0.3) - eslint: 9.39.4 + '@typescript-eslint/parser': 8.59.2(eslint@9.39.4(supports-color@8.1.1))(typescript@5.9.3) + eslint: 9.39.4(supports-color@8.1.1) eslint-import-resolver-node: 0.3.10 transitivePeerDependencies: - supports-color - eslint-plugin-es-x@7.8.0(eslint@9.39.4): + eslint-plugin-es-x@7.8.0(eslint@9.39.4(supports-color@8.1.1)): dependencies: - '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.4) + '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.4(supports-color@8.1.1)) '@eslint-community/regexpp': 4.12.2 - eslint: 9.39.4 - eslint-compat-utils: 0.5.1(eslint@9.39.4) + eslint: 9.39.4(supports-color@8.1.1) + eslint-compat-utils: 0.5.1(eslint@9.39.4(supports-color@8.1.1)) - eslint-plugin-es@3.0.1(eslint@9.39.4): + eslint-plugin-es@3.0.1(eslint@9.39.4(supports-color@8.1.1)): dependencies: - eslint: 9.39.4 + eslint: 9.39.4(supports-color@8.1.1) eslint-utils: 2.1.0 regexpp: 3.2.0 - eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.59.2(eslint@9.39.4)(typescript@5.9.3))(eslint@9.39.4): + eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.59.2(eslint@9.39.4(supports-color@8.1.1))(typescript@5.9.3))(eslint@9.39.4(supports-color@8.1.1)): dependencies: '@rtsao/scc': 1.1.0 array-includes: 3.1.9 @@ -11860,9 +11856,9 @@ snapshots: array.prototype.flatmap: 1.3.3 debug: 3.2.7 doctrine: 2.1.0 - eslint: 9.39.4 + eslint: 9.39.4(supports-color@8.1.1) eslint-import-resolver-node: 0.3.10 - eslint-module-utils: 2.12.1(@typescript-eslint/parser@8.59.2(eslint@9.39.4)(typescript@5.9.3))(eslint-import-resolver-node@0.3.10)(eslint@9.39.4) + eslint-module-utils: 2.12.1(@typescript-eslint/parser@8.59.2(eslint@9.39.4(supports-color@8.1.1))(typescript@5.9.3))(eslint-import-resolver-node@0.3.10)(eslint@9.39.4(supports-color@8.1.1)) hasown: 2.0.3 is-core-module: 2.16.2 is-glob: 4.0.3 @@ -11874,18 +11870,18 @@ snapshots: string.prototype.trimend: 1.0.9 tsconfig-paths: 3.15.0 optionalDependencies: - '@typescript-eslint/parser': 8.59.2(eslint@9.39.4)(typescript@6.0.3) + '@typescript-eslint/parser': 8.59.2(eslint@9.39.4(supports-color@8.1.1))(typescript@5.9.3) transitivePeerDependencies: - eslint-import-resolver-typescript - eslint-import-resolver-webpack - supports-color - eslint-plugin-n@17.24.0(eslint@9.39.4)(typescript@5.9.3): + eslint-plugin-n@17.24.0(eslint@9.39.4(supports-color@8.1.1))(typescript@5.9.3): dependencies: - '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.4) + '@eslint-community/eslint-utils': 4.9.1(eslint@9.39.4(supports-color@8.1.1)) enhanced-resolve: 5.21.0 - eslint: 9.39.4 - eslint-plugin-es-x: 7.8.0(eslint@9.39.4) + eslint: 9.39.4(supports-color@8.1.1) + eslint-plugin-es-x: 7.8.0(eslint@9.39.4(supports-color@8.1.1)) get-tsconfig: 4.14.0 globals: 15.15.0 globrex: 0.1.2 @@ -11895,30 +11891,30 @@ snapshots: transitivePeerDependencies: - typescript - eslint-plugin-node@11.1.0(eslint@9.39.4): + eslint-plugin-node@11.1.0(eslint@9.39.4(supports-color@8.1.1)): dependencies: - eslint: 9.39.4 - eslint-plugin-es: 3.0.1(eslint@9.39.4) + eslint: 9.39.4(supports-color@8.1.1) + eslint-plugin-es: 3.0.1(eslint@9.39.4(supports-color@8.1.1)) eslint-utils: 2.1.0 ignore: 5.3.2 minimatch: 3.1.5 resolve: 1.22.12 semver: 6.3.1 - eslint-plugin-prettier@5.5.5(eslint-config-prettier@9.1.2(eslint@9.39.4))(eslint@9.39.4)(prettier@2.8.8): + eslint-plugin-prettier@5.5.5(eslint-config-prettier@9.1.2(eslint@9.39.4(supports-color@8.1.1)))(eslint@9.39.4(supports-color@8.1.1))(prettier@2.8.8): dependencies: - eslint: 9.39.4 + eslint: 9.39.4(supports-color@8.1.1) prettier: 2.8.8 prettier-linter-helpers: 1.0.1 synckit: 0.11.12 optionalDependencies: - eslint-config-prettier: 9.1.2(eslint@9.39.4) + eslint-config-prettier: 9.1.2(eslint@9.39.4(supports-color@8.1.1)) - eslint-plugin-react-hooks@5.2.0(eslint@9.39.4): + eslint-plugin-react-hooks@5.2.0(eslint@9.39.4(supports-color@8.1.1)): dependencies: - eslint: 9.39.4 + eslint: 9.39.4(supports-color@8.1.1) - eslint-plugin-react@7.37.5(eslint@9.39.4): + eslint-plugin-react@7.37.5(eslint@9.39.4(supports-color@8.1.1)): dependencies: array-includes: 3.1.9 array.prototype.findlast: 1.2.5 @@ -11926,7 +11922,7 @@ snapshots: array.prototype.tosorted: 1.1.4 doctrine: 2.1.0 es-iterator-helpers: 1.3.2 - eslint: 9.39.4 + eslint: 9.39.4(supports-color@8.1.1) estraverse: 5.3.0 hasown: 2.0.3 jsx-ast-utils: 3.3.5 @@ -11957,14 +11953,14 @@ snapshots: eslint-visitor-keys@5.0.1: {} - eslint@9.39.4: + eslint@9.39.4(supports-color@8.1.1): dependencies: - '@eslint-community/eslint-utils': 4.10.1(eslint@9.39.4) + '@eslint-community/eslint-utils': 4.10.1(eslint@9.39.4(supports-color@8.1.1)) '@eslint-community/regexpp': 4.12.2 - '@eslint/config-array': 0.21.2 + '@eslint/config-array': 0.21.2(supports-color@8.1.1) '@eslint/config-helpers': 0.4.2 '@eslint/core': 0.17.0 - '@eslint/eslintrc': 3.3.6 + '@eslint/eslintrc': 3.3.6(supports-color@8.1.1) '@eslint/js': 9.39.4 '@eslint/plugin-kit': 0.4.1 '@humanfs/node': 0.16.8 @@ -11974,7 +11970,7 @@ snapshots: ajv: 6.15.0 chalk: 4.1.2 cross-spawn: 7.0.6 - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) escape-string-regexp: 4.0.0 eslint-scope: 8.4.0 eslint-visitor-keys: 4.2.1 @@ -12050,15 +12046,15 @@ snapshots: expo-application@55.0.19(expo@55.0.30): dependencies: - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) - expo-asset@55.0.20(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)(typescript@6.0.3): + expo-asset@55.0.20(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)(typescript@6.0.3): dependencies: '@expo/image-utils': 0.8.17(typescript@6.0.3) - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) - expo-constants: 55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8)) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) + expo-constants: 55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8)) react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) transitivePeerDependencies: - supports-color - typescript @@ -12066,42 +12062,42 @@ snapshots: expo-build-properties@55.0.18(expo@55.0.30): dependencies: '@expo/schema-utils': 55.0.5 - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) resolve-from: 5.0.0 semver: 7.8.5 - expo-camera@55.0.23(@types/emscripten@1.41.5)(expo@55.0.30)(react-native-web@0.21.2(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): + expo-camera@55.0.23(@types/emscripten@1.41.5)(expo@55.0.30)(react-native-web@0.21.2(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): dependencies: barcode-detector: 3.1.3(@types/emscripten@1.41.5) - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) optionalDependencies: react-native-web: 0.21.2(react-dom@19.2.8(react@19.2.8))(react@19.2.8) transitivePeerDependencies: - '@types/emscripten' - expo-clipboard@55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): + expo-clipboard@55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): dependencies: - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) - expo-constants@55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8)): + expo-constants@55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8)): dependencies: '@expo/env': 2.1.3 - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) transitivePeerDependencies: - supports-color expo-crypto@55.0.19(expo@55.0.30): dependencies: - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) expo-dev-client@55.0.39(expo@55.0.30): dependencies: - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) expo-dev-launcher: 55.0.40(expo@55.0.30) expo-dev-menu: 55.0.34(expo@55.0.30) expo-dev-menu-interface: 55.0.2(expo@55.0.30) @@ -12111,64 +12107,64 @@ snapshots: expo-dev-launcher@55.0.40(expo@55.0.30): dependencies: '@expo/schema-utils': 55.0.5 - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) expo-dev-menu: 55.0.34(expo@55.0.30) expo-manifests: 55.0.21(expo@55.0.30) expo-dev-menu-interface@55.0.2(expo@55.0.30): dependencies: - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) expo-dev-menu@55.0.34(expo@55.0.30): dependencies: - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) expo-dev-menu-interface: 55.0.2(expo@55.0.30) expo-document-picker@55.0.17(expo@55.0.30): dependencies: - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) - expo-file-system@55.0.26(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8)): + expo-file-system@55.0.26(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8)): dependencies: - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) - expo-font@55.0.8(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): + expo-font@55.0.8(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): dependencies: - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) fontfaceobserver: 2.3.0 react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) - expo-glass-effect@55.0.11(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): + expo-glass-effect@55.0.11(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): dependencies: - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) expo-haptics@55.0.18(expo@55.0.30): dependencies: - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) expo-image-loader@55.0.1(expo@55.0.30): dependencies: - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) expo-image-manipulator@55.0.21(expo@55.0.30): dependencies: - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) expo-image-loader: 55.0.1(expo@55.0.30) expo-image-picker@55.0.24(expo@55.0.30): dependencies: - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) expo-image-loader: 55.0.1(expo@55.0.30) - expo-image@55.0.11(expo@55.0.30)(react-native-web@0.21.2(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): + expo-image@55.0.11(expo@55.0.30)(react-native-web@0.21.2(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): dependencies: - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) sf-symbols-typescript: 2.2.0 optionalDependencies: react-native-web: 0.21.2(react-dom@19.2.8(react@19.2.8))(react@19.2.8) @@ -12177,45 +12173,45 @@ snapshots: expo-keep-awake@55.0.8(expo@55.0.30)(react@19.2.8): dependencies: - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) react: 19.2.8 - expo-linking@55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): + expo-linking@55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): dependencies: - expo-constants: 55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8)) + expo-constants: 55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8)) invariant: 2.2.4 react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) transitivePeerDependencies: - expo - supports-color expo-manifests@55.0.21(expo@55.0.30): dependencies: - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) expo-json-utils: 55.0.2 - expo-module-scripts@55.0.2(@babel/core@7.29.7)(@babel/runtime@7.29.7)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(esbuild@0.25.4)(eslint@9.39.4)(expo@55.0.30)(jest@29.7.0(@types/node@26.4.0))(prettier@2.8.8)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react-refresh@0.14.2)(react-test-renderer@19.2.8(react@19.2.8))(react@19.2.8): + expo-module-scripts@55.0.2(@babel/core@7.29.7(supports-color@8.1.1))(@babel/runtime@7.29.7)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(esbuild@0.25.4)(eslint@9.39.4(supports-color@8.1.1))(expo@55.0.30)(jest@29.7.0(@types/node@26.4.0)(supports-color@8.1.1))(prettier@2.8.8)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react-refresh@0.14.2)(react-test-renderer@19.2.8(react@19.2.8))(react@19.2.8): dependencies: - '@babel/cli': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-export-namespace-from': 7.27.1(@babel/core@7.29.7) - '@babel/preset-env': 7.29.5(@babel/core@7.29.7) - '@babel/preset-typescript': 7.28.5(@babel/core@7.29.7) + '@babel/cli': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-export-namespace-from': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/preset-env': 7.29.5(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/preset-typescript': 7.28.5(@babel/core@7.29.7(supports-color@8.1.1)) '@expo/npm-proofread': 1.0.1 '@expo/spawn-async': 1.7.2 - '@testing-library/react-native': 13.3.3(jest@29.7.0(@types/node@26.4.0))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react-test-renderer@19.2.8(react@19.2.8))(react@19.2.8) + '@testing-library/react-native': 13.3.3(jest@29.7.0(@types/node@26.4.0)(supports-color@8.1.1))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react-test-renderer@19.2.8(react@19.2.8))(react@19.2.8) '@tsconfig/node18': 18.2.6 '@types/jest': 29.5.14 babel-plugin-dynamic-import-node: 2.3.3 - babel-preset-expo: 55.0.21(@babel/core@7.29.7)(@babel/runtime@7.29.7)(expo@55.0.30)(react-refresh@0.14.2) + babel-preset-expo: 55.0.21(@babel/core@7.29.7(supports-color@8.1.1))(@babel/runtime@7.29.7)(expo@55.0.30)(react-refresh@0.14.2) commander: 12.1.0 - eslint-config-universe: 15.0.4(eslint@9.39.4)(prettier@2.8.8)(typescript@5.9.3) + eslint-config-universe: 15.0.4(eslint@9.39.4(supports-color@8.1.1))(prettier@2.8.8)(typescript@5.9.3) glob: 13.0.6 - jest-expo: 55.0.17(@babel/core@7.29.7)(expo@55.0.30)(jest@29.7.0(@types/node@26.4.0))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)(typescript@5.9.3) + jest-expo: 55.0.17(@babel/core@7.29.7(supports-color@8.1.1))(expo@55.0.30)(jest@29.7.0(@types/node@26.4.0)(supports-color@8.1.1))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)(typescript@5.9.3) jest-snapshot-prettier: prettier@2.8.8 - jest-watch-typeahead: 2.2.1(jest@29.7.0(@types/node@26.4.0)) + jest-watch-typeahead: 2.2.1(jest@29.7.0(@types/node@26.4.0)(supports-color@8.1.1)) resolve-workspace-root: 2.0.1 - ts-jest: 29.0.5(@babel/core@7.29.7)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(esbuild@0.25.4)(jest@29.7.0(@types/node@26.4.0))(typescript@5.9.3) + ts-jest: 29.0.5(@babel/core@7.29.7(supports-color@8.1.1))(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(esbuild@0.25.4)(jest@29.7.0(@types/node@26.4.0)(supports-color@8.1.1))(typescript@5.9.3) typescript: 5.9.3 transitivePeerDependencies: - '@babel/core' @@ -12251,63 +12247,63 @@ snapshots: - supports-color - typescript - expo-modules-core@55.0.25(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): + expo-modules-core@55.0.25(react-native-worklets@0.8.3(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): dependencies: invariant: 2.2.4 react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) optionalDependencies: - react-native-worklets: 0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + react-native-worklets: 0.8.3(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) expo-network@55.0.18(expo@55.0.30)(react@19.2.8): dependencies: - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) react: 19.2.8 - expo-notifications@55.0.27(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)(typescript@6.0.3): + expo-notifications@55.0.27(patch_hash=ce20843a3daad4185d7e8571788fa323ba4d11984936188790858650a61749c0)(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)(typescript@6.0.3): dependencies: '@expo/image-utils': 0.8.17(typescript@6.0.3) abort-controller: 3.0.0 badgin: 1.2.3 - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) expo-application: 55.0.19(expo@55.0.30) - expo-constants: 55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8)) + expo-constants: 55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8)) react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) transitivePeerDependencies: - supports-color - typescript - expo-router@55.0.18(4a60a26fd685ffdcc7f556016ae4bc5e): + expo-router@55.0.18(98b45897562456c6c413f91e81d6c336): dependencies: - '@expo/log-box': 55.0.13(@expo/dom-webview@55.0.5)(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) - '@expo/metro-runtime': 55.0.10(@expo/dom-webview@55.0.5)(expo@55.0.30)(react-dom@19.2.8(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + '@expo/log-box': 55.0.13(@expo/dom-webview@55.0.6)(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + '@expo/metro-runtime': 55.0.12(@expo/dom-webview@55.0.6)(expo@55.0.30)(react-dom@19.2.8(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) '@expo/schema-utils': 55.0.5 '@radix-ui/react-slot': 1.2.4(@types/react@19.2.14)(react@19.2.8) '@radix-ui/react-tabs': 1.1.13(@types/react@19.2.14)(react-dom@19.2.8(react@19.2.8))(react@19.2.8) - '@react-navigation/bottom-tabs': 7.15.11(@react-navigation/native@7.2.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native-safe-area-context@5.7.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native-screens@4.24.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) - '@react-navigation/native': 7.2.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) - '@react-navigation/native-stack': 7.14.12(@react-navigation/native@7.2.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native-safe-area-context@5.7.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native-screens@4.24.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + '@react-navigation/bottom-tabs': 7.15.11(edc9e9b19f67aea8a6d8a2ee54babcc5) + '@react-navigation/native': 7.2.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + '@react-navigation/native-stack': 7.14.12(edc9e9b19f67aea8a6d8a2ee54babcc5) client-only: 0.0.1 - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) escape-string-regexp: 4.0.0 - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) - expo-constants: 55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8)) - expo-glass-effect: 55.0.11(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) - expo-image: 55.0.11(expo@55.0.30)(react-native-web@0.21.2(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) - expo-linking: 55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) + expo-constants: 55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8)) + expo-glass-effect: 55.0.11(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + expo-image: 55.0.11(expo@55.0.30)(react-native-web@0.21.2(react-dom@19.2.8(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + expo-linking: 55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) expo-server: 55.0.12 - expo-symbols: 55.0.9(expo-font@55.0.8)(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + expo-symbols: 55.0.9(expo-font@55.0.8)(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) fast-deep-equal: 3.1.3 invariant: 2.2.4 nanoid: 3.3.18 query-string: 7.1.3 react: 19.2.8 react-fast-compare: 3.2.2 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) - react-native-is-edge-to-edge: 1.3.1(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) - react-native-safe-area-context: 5.7.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) - react-native-screens: 4.24.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) + react-native-is-edge-to-edge: 1.3.1(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + react-native-safe-area-context: 5.7.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + react-native-screens: 4.24.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) semver: 7.6.3 server-only: 0.0.1 sf-symbols-typescript: 2.2.0 @@ -12315,10 +12311,10 @@ snapshots: use-latest-callback: 0.2.6(react@19.2.8) vaul: 1.1.2(@types/react@19.2.14)(react-dom@19.2.8(react@19.2.8))(react@19.2.8) optionalDependencies: - '@testing-library/react-native': 13.3.3(jest@29.7.0(@types/node@26.4.0))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react-test-renderer@19.2.8(react@19.2.8))(react@19.2.8) + '@testing-library/react-native': 13.3.3(jest@29.7.0(@types/node@26.4.0)(supports-color@8.1.1))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react-test-renderer@19.2.8(react@19.2.8))(react@19.2.8) react-dom: 19.2.8(react@19.2.8) - react-native-gesture-handler: 2.31.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) - react-native-reanimated: 4.3.4(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + react-native-gesture-handler: 2.31.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + react-native-reanimated: 4.3.4(react-native-worklets@0.8.3(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) react-native-web: 0.21.2(react-dom@19.2.8(react@19.2.8))(react@19.2.8) transitivePeerDependencies: - '@react-native-masked-view/masked-view' @@ -12329,68 +12325,74 @@ snapshots: expo-secure-store@55.0.18(expo@55.0.30): dependencies: - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) expo-server@55.0.12: {} expo-splash-screen@55.0.25(expo@55.0.30)(typescript@6.0.3): dependencies: '@expo/prebuild-config': 55.0.22(expo@55.0.30)(typescript@6.0.3) - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) transitivePeerDependencies: - supports-color - typescript - expo-status-bar@55.0.6(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): + expo-status-bar@55.0.6(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): dependencies: react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) - react-native-is-edge-to-edge: 1.3.1(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) + react-native-is-edge-to-edge: 1.3.1(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) - expo-symbols@55.0.9(expo-font@55.0.8)(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): + expo-symbols@55.0.9(expo-font@55.0.8)(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): dependencies: '@expo-google-fonts/material-symbols': 0.4.34 - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) - expo-font: 55.0.8(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) + expo-font: 55.0.8(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) sf-symbols-typescript: 2.2.0 + expo-task-manager@55.0.20(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8)): + dependencies: + expo: 55.0.30(09911ea01feb2f63557d787d92391924) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) + unimodules-app-loader: 55.0.5 + expo-updates-interface@55.1.6(expo@55.0.30): dependencies: - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) - expo@55.0.30(10e8e71dd92768dd7f344108f3edbbe3): + expo@55.0.30(09911ea01feb2f63557d787d92391924): dependencies: '@babel/runtime': 7.29.7 - '@expo/cli': 55.0.36(@expo/dom-webview@55.0.5)(@expo/metro-runtime@55.0.10)(expo-constants@55.0.17)(expo-font@55.0.8)(expo-router@55.0.18)(expo@55.0.30)(react-dom@19.2.8(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)(typescript@6.0.3) + '@expo/cli': 55.0.36(@expo/dom-webview@55.0.6)(@expo/metro-runtime@55.0.12)(expo-constants@55.0.17)(expo-font@55.0.8)(expo-router@55.0.18)(expo@55.0.30)(react-dom@19.2.8(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)(typescript@6.0.3) '@expo/config': 55.0.21(typescript@6.0.3) '@expo/config-plugins': 55.0.11 - '@expo/devtools': 55.0.3(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + '@expo/devtools': 55.0.3(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) '@expo/fingerprint': 0.16.8 '@expo/local-build-cache-provider': 55.0.16(typescript@6.0.3) - '@expo/log-box': 55.0.13(@expo/dom-webview@55.0.5)(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + '@expo/log-box': 55.0.13(@expo/dom-webview@55.0.6)(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) '@expo/metro': 55.1.2 '@expo/metro-config': 55.0.27(expo@55.0.30)(typescript@6.0.3) - '@expo/vector-icons': 15.1.1(expo-font@55.0.8)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + '@expo/vector-icons': 15.1.1(expo-font@55.0.8)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) '@ungap/structured-clone': 1.3.1 - babel-preset-expo: 55.0.25(@babel/core@7.29.7)(@babel/runtime@7.29.7)(expo@55.0.30)(react-refresh@0.14.2) - expo-asset: 55.0.20(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)(typescript@6.0.3) - expo-constants: 55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8)) - expo-file-system: 55.0.26(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8)) - expo-font: 55.0.8(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + babel-preset-expo: 55.0.25(@babel/core@7.29.7(supports-color@8.1.1))(@babel/runtime@7.29.7)(expo@55.0.30)(react-refresh@0.14.2) + expo-asset: 55.0.20(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)(typescript@6.0.3) + expo-constants: 55.0.17(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8)) + expo-file-system: 55.0.26(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8)) + expo-font: 55.0.8(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) expo-keep-awake: 55.0.8(expo@55.0.30)(react@19.2.8) expo-modules-autolinking: 55.0.27(typescript@6.0.3) - expo-modules-core: 55.0.25(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + expo-modules-core: 55.0.25(react-native-worklets@0.8.3(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) pretty-format: 29.7.0 react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) react-refresh: 0.14.2 whatwg-url-minimum: 0.1.2 optionalDependencies: - '@expo/dom-webview': 55.0.5(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) - '@expo/metro-runtime': 55.0.10(@expo/dom-webview@55.0.5)(expo@55.0.30)(react-dom@19.2.8(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) - react-native-webview: 13.16.2(patch_hash=de6761dfa76a5491a23e49f1262566a8831cab26736a336fdffc5d4e7d05ff27)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + '@expo/dom-webview': 55.0.6(expo@55.0.30)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + '@expo/metro-runtime': 55.0.12(@expo/dom-webview@55.0.6)(expo@55.0.30)(react-dom@19.2.8(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + react-native-webview: 13.16.2(patch_hash=de6761dfa76a5491a23e49f1262566a8831cab26736a336fdffc5d4e7d05ff27)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) transitivePeerDependencies: - '@babel/core' - bufferutil @@ -12453,9 +12455,9 @@ snapshots: filter-obj@1.1.0: {} - finalhandler@1.1.2: + finalhandler@1.1.2(supports-color@8.1.1): dependencies: - debug: 2.6.9 + debug: 2.6.9(supports-color@8.1.1) encodeurl: 1.0.2 escape-html: 1.0.3 on-finished: 2.3.0 @@ -12696,25 +12698,25 @@ snapshots: statuses: 2.0.2 toidentifier: 1.0.1 - http-proxy-agent@5.0.0: + http-proxy-agent@5.0.0(supports-color@8.1.1): dependencies: '@tootallnate/once': 2.0.1 - agent-base: 6.0.2 - debug: 4.4.3 + agent-base: 6.0.2(supports-color@8.1.1) + debug: 4.4.3(supports-color@8.1.1) transitivePeerDependencies: - supports-color - https-proxy-agent@5.0.1: + https-proxy-agent@5.0.1(supports-color@8.1.1): dependencies: - agent-base: 6.0.2 - debug: 4.4.3 + agent-base: 6.0.2(supports-color@8.1.1) + debug: 4.4.3(supports-color@8.1.1) transitivePeerDependencies: - supports-color - https-proxy-agent@7.0.6: + https-proxy-agent@7.0.6(supports-color@8.1.1): dependencies: agent-base: 7.1.4 - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) transitivePeerDependencies: - supports-color @@ -12916,9 +12918,9 @@ snapshots: istanbul-lib-coverage@3.2.2: {} - istanbul-lib-instrument@5.2.1: + istanbul-lib-instrument@5.2.1(supports-color@8.1.1): dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/parser': 7.29.7 '@istanbuljs/schema': 0.1.6 istanbul-lib-coverage: 3.2.2 @@ -12926,9 +12928,9 @@ snapshots: transitivePeerDependencies: - supports-color - istanbul-lib-instrument@6.0.3: + istanbul-lib-instrument@6.0.3(supports-color@8.1.1): dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/parser': 7.29.8 '@istanbuljs/schema': 0.1.6 istanbul-lib-coverage: 3.2.2 @@ -12942,9 +12944,9 @@ snapshots: make-dir: 4.0.0 supports-color: 7.2.0 - istanbul-lib-source-maps@4.0.1: + istanbul-lib-source-maps@4.0.1(supports-color@8.1.1): dependencies: - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) istanbul-lib-coverage: 3.2.2 source-map: 0.6.1 transitivePeerDependencies: @@ -12970,10 +12972,10 @@ snapshots: jest-util: 29.7.0 p-limit: 3.1.0 - jest-circus@29.7.0: + jest-circus@29.7.0(supports-color@8.1.1): dependencies: '@jest/environment': 29.7.0 - '@jest/expect': 29.7.0 + '@jest/expect': 29.7.0(supports-color@8.1.1) '@jest/test-result': 29.7.0 '@jest/types': 29.6.3 '@types/node': 26.4.0 @@ -12984,8 +12986,8 @@ snapshots: jest-each: 29.7.0 jest-matcher-utils: 29.7.0 jest-message-util: 29.7.0 - jest-runtime: 29.7.0 - jest-snapshot: 29.7.0 + jest-runtime: 29.7.0(supports-color@8.1.1) + jest-snapshot: 29.7.0(supports-color@8.1.1) jest-util: 29.7.0 p-limit: 3.1.0 pretty-format: 29.7.0 @@ -12996,16 +12998,16 @@ snapshots: - babel-plugin-macros - supports-color - jest-cli@29.7.0(@types/node@26.4.0): + jest-cli@29.7.0(@types/node@26.4.0)(supports-color@8.1.1): dependencies: - '@jest/core': 29.7.0 + '@jest/core': 29.7.0(supports-color@8.1.1) '@jest/test-result': 29.7.0 '@jest/types': 29.6.3 chalk: 4.1.2 - create-jest: 29.7.0(@types/node@26.4.0) + create-jest: 29.7.0(@types/node@26.4.0)(supports-color@8.1.1) exit: 0.1.2 import-local: 3.2.0 - jest-config: 29.7.0(@types/node@26.4.0) + jest-config: 29.7.0(@types/node@26.4.0)(supports-color@8.1.1) jest-util: 29.7.0 jest-validate: 29.7.0 yargs: 17.7.3 @@ -13015,23 +13017,23 @@ snapshots: - supports-color - ts-node - jest-config@29.7.0(@types/node@26.4.0): + jest-config@29.7.0(@types/node@26.4.0)(supports-color@8.1.1): dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@jest/test-sequencer': 29.7.0 '@jest/types': 29.6.3 - babel-jest: 29.7.0(@babel/core@7.29.7) + babel-jest: 29.7.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) chalk: 4.1.2 ci-info: 3.9.0 deepmerge: 4.3.1 glob: 7.2.3 graceful-fs: 4.2.11 - jest-circus: 29.7.0 + jest-circus: 29.7.0(supports-color@8.1.1) jest-environment-node: 29.7.0 jest-get-type: 29.6.3 jest-regex-util: 29.6.3 jest-resolve: 29.7.0 - jest-runner: 29.7.0 + jest-runner: 29.7.0(supports-color@8.1.1) jest-util: 29.7.0 jest-validate: 29.7.0 micromatch: 4.0.8 @@ -13080,7 +13082,7 @@ snapshots: '@types/node': 25.6.0 jest-mock: 29.7.0 jest-util: 29.7.0 - jsdom: 20.0.3 + jsdom: 20.0.3(supports-color@8.1.1) transitivePeerDependencies: - bufferutil - supports-color @@ -13095,21 +13097,21 @@ snapshots: jest-mock: 29.7.0 jest-util: 29.7.0 - jest-expo@55.0.17(@babel/core@7.29.7)(expo@55.0.30)(jest@29.7.0(@types/node@26.4.0))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)(typescript@5.9.3): + jest-expo@55.0.17(@babel/core@7.29.7(supports-color@8.1.1))(expo@55.0.30)(jest@29.7.0(@types/node@26.4.0)(supports-color@8.1.1))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8)(typescript@5.9.3): dependencies: '@expo/config': 55.0.16(typescript@5.9.3) '@expo/json-file': 10.0.14 '@jest/create-cache-key-function': 29.7.0 - '@jest/globals': 29.7.0 - babel-jest: 29.7.0(@babel/core@7.29.7) - expo: 55.0.30(10e8e71dd92768dd7f344108f3edbbe3) + '@jest/globals': 29.7.0(supports-color@8.1.1) + babel-jest: 29.7.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + expo: 55.0.30(09911ea01feb2f63557d787d92391924) jest-environment-jsdom: 29.7.0 - jest-snapshot: 29.7.0 + jest-snapshot: 29.7.0(supports-color@8.1.1) jest-watch-select-projects: 2.0.0 - jest-watch-typeahead: 2.2.1(jest@29.7.0(@types/node@26.4.0)) + jest-watch-typeahead: 2.2.1(jest@29.7.0(@types/node@26.4.0)(supports-color@8.1.1)) json5: 2.2.3 lodash: 4.18.1 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) react-test-renderer: 19.2.0(react@19.2.8) server-only: 0.0.1 stacktrace-js: 2.0.2 @@ -13184,10 +13186,10 @@ snapshots: jest-regex-util@29.6.3: {} - jest-resolve-dependencies@29.7.0: + jest-resolve-dependencies@29.7.0(supports-color@8.1.1): dependencies: jest-regex-util: 29.6.3 - jest-snapshot: 29.7.0 + jest-snapshot: 29.7.0(supports-color@8.1.1) transitivePeerDependencies: - supports-color @@ -13203,12 +13205,12 @@ snapshots: resolve.exports: 2.0.3 slash: 3.0.0 - jest-runner@29.7.0: + jest-runner@29.7.0(supports-color@8.1.1): dependencies: '@jest/console': 29.7.0 '@jest/environment': 29.7.0 '@jest/test-result': 29.7.0 - '@jest/transform': 29.7.0 + '@jest/transform': 29.7.0(supports-color@8.1.1) '@jest/types': 29.6.3 '@types/node': 26.4.0 chalk: 4.1.2 @@ -13220,7 +13222,7 @@ snapshots: jest-leak-detector: 29.7.0 jest-message-util: 29.7.0 jest-resolve: 29.7.0 - jest-runtime: 29.7.0 + jest-runtime: 29.7.0(supports-color@8.1.1) jest-util: 29.7.0 jest-watcher: 29.7.0 jest-worker: 29.7.0 @@ -13229,14 +13231,14 @@ snapshots: transitivePeerDependencies: - supports-color - jest-runtime@29.7.0: + jest-runtime@29.7.0(supports-color@8.1.1): dependencies: '@jest/environment': 29.7.0 '@jest/fake-timers': 29.7.0 - '@jest/globals': 29.7.0 + '@jest/globals': 29.7.0(supports-color@8.1.1) '@jest/source-map': 29.6.3 '@jest/test-result': 29.7.0 - '@jest/transform': 29.7.0 + '@jest/transform': 29.7.0(supports-color@8.1.1) '@jest/types': 29.6.3 '@types/node': 26.4.0 chalk: 4.1.2 @@ -13249,24 +13251,24 @@ snapshots: jest-mock: 29.7.0 jest-regex-util: 29.6.3 jest-resolve: 29.7.0 - jest-snapshot: 29.7.0 + jest-snapshot: 29.7.0(supports-color@8.1.1) jest-util: 29.7.0 slash: 3.0.0 strip-bom: 4.0.0 transitivePeerDependencies: - supports-color - jest-snapshot@29.7.0: + jest-snapshot@29.7.0(supports-color@8.1.1): dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/generator': 7.29.1 - '@babel/plugin-syntax-jsx': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-syntax-typescript': 7.28.6(@babel/core@7.29.7) + '@babel/plugin-syntax-jsx': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-syntax-typescript': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) '@babel/types': 7.29.0 '@jest/expect-utils': 29.7.0 - '@jest/transform': 29.7.0 + '@jest/transform': 29.7.0(supports-color@8.1.1) '@jest/types': 29.6.3 - babel-preset-current-node-syntax: 1.2.0(@babel/core@7.29.7) + babel-preset-current-node-syntax: 1.2.0(@babel/core@7.29.7(supports-color@8.1.1)) chalk: 4.1.2 expect: 29.7.0 graceful-fs: 4.2.11 @@ -13305,11 +13307,11 @@ snapshots: chalk: 3.0.0 prompts: 2.4.2 - jest-watch-typeahead@2.2.1(jest@29.7.0(@types/node@26.4.0)): + jest-watch-typeahead@2.2.1(jest@29.7.0(@types/node@26.4.0)(supports-color@8.1.1)): dependencies: ansi-escapes: 6.2.1 chalk: 4.1.2 - jest: 29.7.0(@types/node@26.4.0) + jest: 29.7.0(@types/node@26.4.0)(supports-color@8.1.1) jest-regex-util: 29.6.3 jest-watcher: 29.7.0 slash: 5.1.0 @@ -13334,12 +13336,12 @@ snapshots: merge-stream: 2.0.0 supports-color: 8.1.1 - jest@29.7.0(@types/node@26.4.0): + jest@29.7.0(@types/node@26.4.0)(supports-color@8.1.1): dependencies: - '@jest/core': 29.7.0 + '@jest/core': 29.7.0(supports-color@8.1.1) '@jest/types': 29.6.3 import-local: 3.2.0 - jest-cli: 29.7.0(@types/node@26.4.0) + jest-cli: 29.7.0(@types/node@26.4.0)(supports-color@8.1.1) transitivePeerDependencies: - '@types/node' - babel-plugin-macros @@ -13365,7 +13367,7 @@ snapshots: jsc-safe-url@0.2.4: {} - jsdom@20.0.3: + jsdom@20.0.3(supports-color@8.1.1): dependencies: abab: 2.0.6 acorn: 8.15.0 @@ -13378,8 +13380,8 @@ snapshots: escodegen: 2.1.0 form-data: 4.0.6 html-encoding-sniffer: 3.0.0 - http-proxy-agent: 5.0.0 - https-proxy-agent: 5.0.1 + http-proxy-agent: 5.0.0(supports-color@8.1.1) + https-proxy-agent: 5.0.1(supports-color@8.1.1) is-potential-custom-element-name: 1.0.1 nwsapi: 2.2.23 parse5: 7.3.0 @@ -13448,7 +13450,7 @@ snapshots: lighthouse-logger@1.4.2: dependencies: - debug: 2.6.9 + debug: 2.6.9(supports-color@8.1.1) marky: 1.3.0 transitivePeerDependencies: - supports-color @@ -13546,11 +13548,11 @@ snapshots: dependencies: yallist: 3.1.1 - lucide-react-native@1.14.0(react-native-svg@15.15.4(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): + lucide-react-native@1.14.0(react-native-svg@15.15.4(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): dependencies: react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) - react-native-svg: 15.15.4(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) + react-native-svg: 15.15.4(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) magic-string@0.30.21: dependencies: @@ -13614,9 +13616,9 @@ snapshots: ts-dedent: 2.3.0 uuid: 11.1.1 - metro-babel-transformer@0.83.7: + metro-babel-transformer@0.83.7(supports-color@8.1.1): dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) flow-enums-runtime: 0.0.6 hermes-parser: 0.35.0 metro-cache-key: 0.83.7 @@ -13624,9 +13626,9 @@ snapshots: transitivePeerDependencies: - supports-color - metro-babel-transformer@0.83.8: + metro-babel-transformer@0.83.8(supports-color@8.1.1): dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) flow-enums-runtime: 0.0.6 hermes-parser: 0.35.0 metro-cache-key: 0.83.8 @@ -13634,9 +13636,9 @@ snapshots: transitivePeerDependencies: - supports-color - metro-babel-transformer@0.84.5: + metro-babel-transformer@0.84.5(supports-color@8.1.1): dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) flow-enums-runtime: 0.0.6 hermes-parser: 0.35.0 metro-cache-key: 0.84.5 @@ -13656,40 +13658,40 @@ snapshots: dependencies: flow-enums-runtime: 0.0.6 - metro-cache@0.83.7: + metro-cache@0.83.7(supports-color@8.1.1): dependencies: exponential-backoff: 3.1.3 flow-enums-runtime: 0.0.6 - https-proxy-agent: 7.0.6 + https-proxy-agent: 7.0.6(supports-color@8.1.1) metro-core: 0.83.7 transitivePeerDependencies: - supports-color - metro-cache@0.83.8: + metro-cache@0.83.8(supports-color@8.1.1): dependencies: exponential-backoff: 3.1.3 flow-enums-runtime: 0.0.6 - https-proxy-agent: 7.0.6 + https-proxy-agent: 7.0.6(supports-color@8.1.1) metro-core: 0.83.8 transitivePeerDependencies: - supports-color - metro-cache@0.84.5: + metro-cache@0.84.5(supports-color@8.1.1): dependencies: exponential-backoff: 3.1.3 flow-enums-runtime: 0.0.6 - https-proxy-agent: 7.0.6 + https-proxy-agent: 7.0.6(supports-color@8.1.1) metro-core: 0.84.5 transitivePeerDependencies: - supports-color - metro-config@0.83.7: + metro-config@0.83.7(supports-color@8.1.1): dependencies: - connect: 3.7.0 + connect: 3.7.0(supports-color@8.1.1) flow-enums-runtime: 0.0.6 jest-validate: 29.7.0 - metro: 0.83.7 - metro-cache: 0.83.7 + metro: 0.83.7(supports-color@8.1.1) + metro-cache: 0.83.7(supports-color@8.1.1) metro-core: 0.83.7 metro-runtime: 0.83.7 yaml: 2.9.0 @@ -13698,13 +13700,13 @@ snapshots: - supports-color - utf-8-validate - metro-config@0.83.8: + metro-config@0.83.8(supports-color@8.1.1): dependencies: - connect: 3.7.0 + connect: 3.7.0(supports-color@8.1.1) flow-enums-runtime: 0.0.6 jest-validate: 29.7.0 - metro: 0.83.8 - metro-cache: 0.83.8 + metro: 0.83.8(supports-color@8.1.1) + metro-cache: 0.83.8(supports-color@8.1.1) metro-core: 0.83.8 metro-runtime: 0.83.8 yaml: 2.9.0 @@ -13713,13 +13715,13 @@ snapshots: - supports-color - utf-8-validate - metro-config@0.84.5: + metro-config@0.84.5(supports-color@8.1.1): dependencies: - connect: 3.7.0 + connect: 3.7.0(supports-color@8.1.1) flow-enums-runtime: 0.0.6 jest-validate: 29.7.0 - metro: 0.84.5 - metro-cache: 0.84.5 + metro: 0.84.5(supports-color@8.1.1) + metro-cache: 0.84.5(supports-color@8.1.1) metro-core: 0.84.5 metro-runtime: 0.84.5 yaml: 2.9.0 @@ -13746,9 +13748,9 @@ snapshots: lodash.throttle: 4.1.1 metro-resolver: 0.84.5 - metro-file-map@0.83.7: + metro-file-map@0.83.7(supports-color@8.1.1): dependencies: - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) fb-watchman: 2.0.2 flow-enums-runtime: 0.0.6 graceful-fs: 4.2.11 @@ -13760,9 +13762,9 @@ snapshots: transitivePeerDependencies: - supports-color - metro-file-map@0.83.8: + metro-file-map@0.83.8(supports-color@8.1.1): dependencies: - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) fb-watchman: 2.0.2 flow-enums-runtime: 0.0.6 graceful-fs: 4.2.11 @@ -13774,9 +13776,9 @@ snapshots: transitivePeerDependencies: - supports-color - metro-file-map@0.84.5: + metro-file-map@0.84.5(supports-color@8.1.1): dependencies: - debug: 4.4.3 + debug: 4.4.3(supports-color@8.1.1) fb-watchman: 2.0.2 flow-enums-runtime: 0.0.6 graceful-fs: 4.2.11 @@ -13830,9 +13832,9 @@ snapshots: '@babel/runtime': 7.29.7 flow-enums-runtime: 0.0.6 - metro-source-map@0.83.7: + metro-source-map@0.83.7(supports-color@8.1.1): dependencies: - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@8.1.1) '@babel/types': 7.29.8 flow-enums-runtime: 0.0.6 invariant: 2.2.4 @@ -13844,9 +13846,9 @@ snapshots: transitivePeerDependencies: - supports-color - metro-source-map@0.83.8: + metro-source-map@0.83.8(supports-color@8.1.1): dependencies: - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@8.1.1) '@babel/types': 7.29.8 flow-enums-runtime: 0.0.6 invariant: 2.2.4 @@ -13858,9 +13860,9 @@ snapshots: transitivePeerDependencies: - supports-color - metro-source-map@0.84.5: + metro-source-map@0.84.5(supports-color@8.1.1): dependencies: - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@8.1.1) '@babel/types': 7.29.8 flow-enums-runtime: 0.0.6 invariant: 2.2.4 @@ -13876,141 +13878,135 @@ snapshots: dependencies: flow-enums-runtime: 0.0.6 invariant: 2.2.4 - metro-source-map: 0.83.7 + metro-source-map: 0.83.7(supports-color@8.1.1) nullthrows: 1.1.1 source-map: 0.5.7 vlq: 1.0.1 - transitivePeerDependencies: - - supports-color metro-symbolicate@0.83.8: dependencies: flow-enums-runtime: 0.0.6 invariant: 2.2.4 - metro-source-map: 0.83.8 + metro-source-map: 0.83.8(supports-color@8.1.1) nullthrows: 1.1.1 source-map: 0.5.7 vlq: 1.0.1 - transitivePeerDependencies: - - supports-color metro-symbolicate@0.84.5: dependencies: flow-enums-runtime: 0.0.6 invariant: 2.2.4 - metro-source-map: 0.84.5 + metro-source-map: 0.84.5(supports-color@8.1.1) nullthrows: 1.1.1 source-map: 0.5.7 vlq: 1.0.1 - transitivePeerDependencies: - - supports-color - metro-transform-plugins@0.83.7: + metro-transform-plugins@0.83.7(supports-color@8.1.1): dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/generator': 7.29.8 '@babel/template': 7.29.7 - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@8.1.1) flow-enums-runtime: 0.0.6 nullthrows: 1.1.1 transitivePeerDependencies: - supports-color - metro-transform-plugins@0.83.8: + metro-transform-plugins@0.83.8(supports-color@8.1.1): dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/generator': 7.29.8 '@babel/template': 7.29.7 - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@8.1.1) flow-enums-runtime: 0.0.6 nullthrows: 1.1.1 transitivePeerDependencies: - supports-color - metro-transform-plugins@0.84.5: + metro-transform-plugins@0.84.5(supports-color@8.1.1): dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/generator': 7.29.8 '@babel/template': 7.29.7 - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@8.1.1) flow-enums-runtime: 0.0.6 nullthrows: 1.1.1 transitivePeerDependencies: - supports-color - metro-transform-worker@0.83.7: + metro-transform-worker@0.83.7(supports-color@8.1.1): dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/generator': 7.29.8 '@babel/parser': 7.29.8 '@babel/types': 7.29.8 flow-enums-runtime: 0.0.6 - metro: 0.83.7 - metro-babel-transformer: 0.83.7 - metro-cache: 0.83.7 + metro: 0.83.7(supports-color@8.1.1) + metro-babel-transformer: 0.83.7(supports-color@8.1.1) + metro-cache: 0.83.7(supports-color@8.1.1) metro-cache-key: 0.83.7 metro-minify-terser: 0.83.7 - metro-source-map: 0.83.7 - metro-transform-plugins: 0.83.7 + metro-source-map: 0.83.7(supports-color@8.1.1) + metro-transform-plugins: 0.83.7(supports-color@8.1.1) nullthrows: 1.1.1 transitivePeerDependencies: - bufferutil - supports-color - utf-8-validate - metro-transform-worker@0.83.8: + metro-transform-worker@0.83.8(supports-color@8.1.1): dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/generator': 7.29.8 '@babel/parser': 7.29.8 '@babel/types': 7.29.8 flow-enums-runtime: 0.0.6 - metro: 0.83.8 - metro-babel-transformer: 0.83.8 - metro-cache: 0.83.8 + metro: 0.83.8(supports-color@8.1.1) + metro-babel-transformer: 0.83.8(supports-color@8.1.1) + metro-cache: 0.83.8(supports-color@8.1.1) metro-cache-key: 0.83.8 metro-minify-terser: 0.83.8 - metro-source-map: 0.83.8 - metro-transform-plugins: 0.83.8 + metro-source-map: 0.83.8(supports-color@8.1.1) + metro-transform-plugins: 0.83.8(supports-color@8.1.1) nullthrows: 1.1.1 transitivePeerDependencies: - bufferutil - supports-color - utf-8-validate - metro-transform-worker@0.84.5: + metro-transform-worker@0.84.5(supports-color@8.1.1): dependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/generator': 7.29.8 '@babel/parser': 7.29.8 '@babel/types': 7.29.8 flow-enums-runtime: 0.0.6 - metro: 0.84.5 - metro-babel-transformer: 0.84.5 - metro-cache: 0.84.5 + metro: 0.84.5(supports-color@8.1.1) + metro-babel-transformer: 0.84.5(supports-color@8.1.1) + metro-cache: 0.84.5(supports-color@8.1.1) metro-cache-key: 0.84.5 metro-minify-terser: 0.84.5 - metro-source-map: 0.84.5 - metro-transform-plugins: 0.84.5 + metro-source-map: 0.84.5(supports-color@8.1.1) + metro-transform-plugins: 0.84.5(supports-color@8.1.1) nullthrows: 1.1.1 transitivePeerDependencies: - bufferutil - supports-color - utf-8-validate - metro@0.83.7: + metro@0.83.7(supports-color@8.1.1): dependencies: '@babel/code-frame': 7.29.7 - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/generator': 7.29.8 '@babel/parser': 7.29.8 '@babel/template': 7.29.7 - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@8.1.1) '@babel/types': 7.29.8 accepts: 2.0.0 ci-info: 2.0.0 - connect: 3.7.0 - debug: 4.4.3 + connect: 3.7.0(supports-color@8.1.1) + debug: 4.4.3(supports-color@8.1.1) error-stack-parser: 2.1.4 flow-enums-runtime: 0.0.6 graceful-fs: 4.2.11 @@ -14020,18 +14016,18 @@ snapshots: jest-worker: 29.7.0 jsc-safe-url: 0.2.4 lodash.throttle: 4.1.1 - metro-babel-transformer: 0.83.7 - metro-cache: 0.83.7 + metro-babel-transformer: 0.83.7(supports-color@8.1.1) + metro-cache: 0.83.7(supports-color@8.1.1) metro-cache-key: 0.83.7 - metro-config: 0.83.7 + metro-config: 0.83.7(supports-color@8.1.1) metro-core: 0.83.7 - metro-file-map: 0.83.7 + metro-file-map: 0.83.7(supports-color@8.1.1) metro-resolver: 0.83.7 metro-runtime: 0.83.7 - metro-source-map: 0.83.7 + metro-source-map: 0.83.7(supports-color@8.1.1) metro-symbolicate: 0.83.7 - metro-transform-plugins: 0.83.7 - metro-transform-worker: 0.83.7 + metro-transform-plugins: 0.83.7(supports-color@8.1.1) + metro-transform-worker: 0.83.7(supports-color@8.1.1) mime-types: 3.0.2 nullthrows: 1.1.1 serialize-error: 2.1.0 @@ -14044,19 +14040,19 @@ snapshots: - supports-color - utf-8-validate - metro@0.83.8: + metro@0.83.8(supports-color@8.1.1): dependencies: '@babel/code-frame': 7.29.7 - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/generator': 7.29.8 '@babel/parser': 7.29.8 '@babel/template': 7.29.7 - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@8.1.1) '@babel/types': 7.29.8 accepts: 2.0.0 ci-info: 2.0.0 - connect: 3.7.0 - debug: 4.4.3 + connect: 3.7.0(supports-color@8.1.1) + debug: 4.4.3(supports-color@8.1.1) error-stack-parser: 2.1.4 flow-enums-runtime: 0.0.6 graceful-fs: 4.2.11 @@ -14065,18 +14061,18 @@ snapshots: jest-worker: 29.7.0 jsc-safe-url: 0.2.4 lodash.throttle: 4.1.1 - metro-babel-transformer: 0.83.8 - metro-cache: 0.83.8 + metro-babel-transformer: 0.83.8(supports-color@8.1.1) + metro-cache: 0.83.8(supports-color@8.1.1) metro-cache-key: 0.83.8 - metro-config: 0.83.8 + metro-config: 0.83.8(supports-color@8.1.1) metro-core: 0.83.8 - metro-file-map: 0.83.8 + metro-file-map: 0.83.8(supports-color@8.1.1) metro-resolver: 0.83.8 metro-runtime: 0.83.8 - metro-source-map: 0.83.8 + metro-source-map: 0.83.8(supports-color@8.1.1) metro-symbolicate: 0.83.8 - metro-transform-plugins: 0.83.8 - metro-transform-worker: 0.83.8 + metro-transform-plugins: 0.83.8(supports-color@8.1.1) + metro-transform-worker: 0.83.8(supports-color@8.1.1) mime-types: 3.0.2 nullthrows: 1.1.1 serialize-error: 2.1.0 @@ -14089,19 +14085,19 @@ snapshots: - supports-color - utf-8-validate - metro@0.84.5: + metro@0.84.5(supports-color@8.1.1): dependencies: '@babel/code-frame': 7.29.7 - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@babel/generator': 7.29.8 '@babel/parser': 7.29.8 '@babel/template': 7.29.7 - '@babel/traverse': 7.29.8 + '@babel/traverse': 7.29.8(supports-color@8.1.1) '@babel/types': 7.29.8 accepts: 2.0.0 ci-info: 2.0.0 - connect: 3.7.0 - debug: 4.4.3 + connect: 3.7.0(supports-color@8.1.1) + debug: 4.4.3(supports-color@8.1.1) error-stack-parser: 2.1.4 flow-enums-runtime: 0.0.6 graceful-fs: 4.2.11 @@ -14110,18 +14106,18 @@ snapshots: jest-worker: 29.7.0 jsc-safe-url: 0.2.4 lodash.throttle: 4.1.1 - metro-babel-transformer: 0.84.5 - metro-cache: 0.84.5 + metro-babel-transformer: 0.84.5(supports-color@8.1.1) + metro-cache: 0.84.5(supports-color@8.1.1) metro-cache-key: 0.84.5 - metro-config: 0.84.5 + metro-config: 0.84.5(supports-color@8.1.1) metro-core: 0.84.5 - metro-file-map: 0.84.5 + metro-file-map: 0.84.5(supports-color@8.1.1) metro-resolver: 0.84.5 metro-runtime: 0.84.5 - metro-source-map: 0.84.5 + metro-source-map: 0.84.5(supports-color@8.1.1) metro-symbolicate: 0.84.5 - metro-transform-plugins: 0.84.5 - metro-transform-worker: 0.84.5 + metro-transform-plugins: 0.84.5(supports-color@8.1.1) + metro-transform-worker: 0.84.5(supports-color@8.1.1) mime-types: 3.0.2 nullthrows: 1.1.1 serialize-error: 2.1.0 @@ -14576,52 +14572,52 @@ snapshots: react-is@19.2.8: {} - react-native-gesture-handler@2.31.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): + react-native-gesture-handler@2.31.2(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): dependencies: '@egjs/hammerjs': 2.0.17 '@types/react-test-renderer': 19.1.0 hoist-non-react-statics: 3.3.2 invariant: 2.2.4 react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) - react-native-is-edge-to-edge@1.3.1(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): + react-native-is-edge-to-edge@1.3.1(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): dependencies: react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) - react-native-reanimated@4.3.4(react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): + react-native-reanimated@4.3.4(react-native-worklets@0.8.3(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): dependencies: react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) - react-native-is-edge-to-edge: 1.3.1(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) - react-native-worklets: 0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) + react-native-is-edge-to-edge: 1.3.1(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + react-native-worklets: 0.8.3(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) semver: 7.8.5 - react-native-safe-area-context@5.7.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): + react-native-safe-area-context@5.7.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): dependencies: react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) - react-native-screens@4.24.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): + react-native-screens@4.24.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): dependencies: react: 19.2.8 react-freeze: 1.0.4(react@19.2.8) - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) warn-once: 0.1.1 - react-native-svg@15.15.4(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): + react-native-svg@15.15.4(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): dependencies: css-select: 5.2.2 css-tree: 1.1.3 react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) warn-once: 0.1.1 - react-native-uitextview@2.2.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): + react-native-uitextview@2.2.0(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): dependencies: react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) react-native-web@0.21.2(react-dom@19.2.8(react@19.2.8))(react@19.2.8): dependencies: @@ -14638,48 +14634,48 @@ snapshots: transitivePeerDependencies: - encoding - react-native-webview@13.16.2(patch_hash=de6761dfa76a5491a23e49f1262566a8831cab26736a336fdffc5d4e7d05ff27)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): + react-native-webview@13.16.2(patch_hash=de6761dfa76a5491a23e49f1262566a8831cab26736a336fdffc5d4e7d05ff27)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): dependencies: '@typescript/native-preview': 7.0.0-dev.20260707.2 escape-string-regexp: 4.0.0 invariant: 2.2.4 react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) - react-native-worklets@0.8.3(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): + react-native-worklets@0.8.3(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8): dependencies: - '@babel/core': 7.29.7 - '@babel/plugin-transform-arrow-functions': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-class-properties': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-classes': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-nullish-coalescing-operator': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-optional-chaining': 7.28.6(@babel/core@7.29.7) - '@babel/plugin-transform-shorthand-properties': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-template-literals': 7.27.1(@babel/core@7.29.7) - '@babel/plugin-transform-unicode-regex': 7.27.1(@babel/core@7.29.7) - '@babel/preset-typescript': 7.28.5(@babel/core@7.29.7) - '@react-native/metro-config': 0.85.2(@babel/core@7.29.7) + '@babel/core': 7.29.7(supports-color@8.1.1) + '@babel/plugin-transform-arrow-functions': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-class-properties': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-classes': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-nullish-coalescing-operator': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-optional-chaining': 7.28.6(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-shorthand-properties': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-template-literals': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/plugin-transform-unicode-regex': 7.27.1(@babel/core@7.29.7(supports-color@8.1.1)) + '@babel/preset-typescript': 7.28.5(@babel/core@7.29.7(supports-color@8.1.1)) + '@react-native/metro-config': 0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) convert-source-map: 2.0.0 react: 19.2.8 - react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8) + react-native: 0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8) semver: 7.7.4 transitivePeerDependencies: - supports-color - react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8): + react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8): dependencies: '@jest/create-cache-key-function': 29.7.0 '@react-native/assets-registry': 0.83.10 - '@react-native/codegen': 0.83.10(@babel/core@7.29.7) - '@react-native/community-cli-plugin': 0.83.10(@react-native/metro-config@0.85.2(@babel/core@7.29.7)) + '@react-native/codegen': 0.83.10(@babel/core@7.29.7(supports-color@8.1.1)) + '@react-native/community-cli-plugin': 0.83.10(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1)) '@react-native/gradle-plugin': 0.83.10 '@react-native/js-polyfills': 0.83.10 '@react-native/normalize-colors': 0.83.10 - '@react-native/virtualized-lists': 0.83.10(@types/react@19.2.14)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) + '@react-native/virtualized-lists': 0.83.10(@types/react@19.2.14)(react-native@0.83.10(patch_hash=44876634a8efbb0f2c3f66cd4332be170ec821d1cbfc0264ac80680983e8513d)(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.85.2(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(@types/react@19.2.14)(react@19.2.8))(react@19.2.8) abort-controller: 3.0.0 anser: 1.4.10 ansi-regex: 5.0.1 - babel-jest: 29.7.0(@babel/core@7.29.7) + babel-jest: 29.7.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) babel-plugin-syntax-hermes-parser: 0.32.0 base64-js: 1.5.1 commander: 12.1.0 @@ -14690,7 +14686,7 @@ snapshots: jest-environment-node: 29.7.0 memoize-one: 5.2.1 metro-runtime: 0.83.7 - metro-source-map: 0.83.7 + metro-source-map: 0.83.7(supports-color@8.1.1) nullthrows: 1.1.1 pretty-format: 29.7.0 promise: 8.3.0 @@ -14930,7 +14926,7 @@ snapshots: send@0.19.2: dependencies: - debug: 2.6.9 + debug: 2.6.9(supports-color@8.1.1) depd: 2.0.0 destroy: 1.2.0 encodeurl: 2.0.0 @@ -15308,11 +15304,11 @@ snapshots: ts-dedent@2.3.0: {} - ts-jest@29.0.5(@babel/core@7.29.7)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(esbuild@0.25.4)(jest@29.7.0(@types/node@26.4.0))(typescript@5.9.3): + ts-jest@29.0.5(@babel/core@7.29.7(supports-color@8.1.1))(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1))(esbuild@0.25.4)(jest@29.7.0(@types/node@26.4.0)(supports-color@8.1.1))(typescript@5.9.3): dependencies: bs-logger: 0.2.6 fast-json-stable-stringify: 2.1.0 - jest: 29.7.0(@types/node@26.4.0) + jest: 29.7.0(@types/node@26.4.0)(supports-color@8.1.1) jest-util: 29.7.0 json5: 2.2.3 lodash.memoize: 4.1.2 @@ -15321,9 +15317,9 @@ snapshots: typescript: 5.9.3 yargs-parser: 21.1.1 optionalDependencies: - '@babel/core': 7.29.7 + '@babel/core': 7.29.7(supports-color@8.1.1) '@jest/types': 29.6.3 - babel-jest: 29.7.0(@babel/core@7.29.7) + babel-jest: 29.7.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) esbuild: 0.25.4 tsconfig-paths@3.15.0: @@ -15418,6 +15414,8 @@ snapshots: unicode-property-aliases-ecmascript@2.2.0: {} + unimodules-app-loader@55.0.5: {} + universalify@0.2.0: {} unpipe@1.0.0: {} @@ -15498,7 +15496,7 @@ snapshots: tsx: 4.22.4 yaml: 2.9.0 - vitest@4.1.11(@types/node@26.4.0)(happy-dom@20.11.8)(jsdom@20.0.3)(vite@8.1.0(@types/node@26.4.0)(esbuild@0.25.4)(terser@5.51.2)(tsx@4.22.4)(yaml@2.9.0)): + vitest@4.1.11(@types/node@26.4.0)(happy-dom@20.11.8)(jsdom@20.0.3(supports-color@8.1.1))(vite@8.1.0(@types/node@26.4.0)(esbuild@0.25.4)(terser@5.51.2)(tsx@4.22.4)(yaml@2.9.0)): dependencies: '@vitest/expect': 4.1.11 '@vitest/mocker': 4.1.11(vite@8.1.0(@types/node@26.4.0)(esbuild@0.25.4)(terser@5.51.2)(tsx@4.22.4)(yaml@2.9.0)) @@ -15523,7 +15521,7 @@ snapshots: optionalDependencies: '@types/node': 26.4.0 happy-dom: 20.11.8 - jsdom: 20.0.3 + jsdom: 20.0.3(supports-color@8.1.1) transitivePeerDependencies: - msw diff --git a/mobile/pnpm-workspace.yaml b/mobile/pnpm-workspace.yaml index 8f29993b7b4..b6d836a230e 100644 --- a/mobile/pnpm-workspace.yaml +++ b/mobile/pnpm-workspace.yaml @@ -7,5 +7,6 @@ overrides: xcode>uuid: 11.1.1 patchedDependencies: + expo-notifications@55.0.27: patches/expo-notifications@55.0.27.patch react-native-webview@13.16.2: patches/react-native-webview@13.16.2.patch react-native@0.83.10: patches/react-native@0.83.10.patch diff --git a/mobile/src/components/NewWorktreeModalController.tsx b/mobile/src/components/NewWorktreeModalController.tsx index 4b6812fc9ff..a7f2ce1c2b6 100644 --- a/mobile/src/components/NewWorktreeModalController.tsx +++ b/mobile/src/components/NewWorktreeModalController.tsx @@ -16,7 +16,7 @@ type Props = { openExternalUrl: (url: string) => Promise onVisibleChange?: (visible: boolean) => void onRouteVisibleChange: (visible: boolean) => void - onCreated: (worktreeId: string, name: string) => void + onCreated: (worktreeId: string, name: string, warning?: string) => void } export const NewWorktreeModalController = forwardRef( diff --git a/mobile/src/components/codex-reset-credit-capability.ts b/mobile/src/components/codex-reset-credit-capability.ts index 1a32ef37873..8e88f74f2f9 100644 --- a/mobile/src/components/codex-reset-credit-capability.ts +++ b/mobile/src/components/codex-reset-credit-capability.ts @@ -2,6 +2,7 @@ import { useEffect, useState } from 'react' import { CODEX_RESET_CREDIT_RUNTIME_CAPABILITY } from '../../../src/shared/protocol-version' import type { RpcClient } from '../transport/rpc-client' import { startRuntimeCapabilityProbe } from '../transport/runtime-capability-probe' +import { rpcObjectResultOrNull } from '../transport/rpc-acceptance-policies' // Why: source the capability string from the shared contract so a host bump can never // silently drift from the mobile probe. @@ -12,10 +13,7 @@ export async function readCodexResetCreditCapability( ): Promise { try { const response = await client.sendRequest('status.get') - if (!response.ok || !response.result || typeof response.result !== 'object') { - return false - } - const capabilities = (response.result as { capabilities?: unknown }).capabilities + const capabilities = rpcObjectResultOrNull(response)?.capabilities return ( Array.isArray(capabilities) && capabilities.includes(MOBILE_CODEX_RESET_CREDIT_CAPABILITY) ) diff --git a/mobile/src/components/new-worktree-modal-types.ts b/mobile/src/components/new-worktree-modal-types.ts index 8dae250cd71..7e5000ccc11 100644 --- a/mobile/src/components/new-worktree-modal-types.ts +++ b/mobile/src/components/new-worktree-modal-types.ts @@ -24,7 +24,7 @@ export type NewWorktreeModalProps = { existingWorktreePaths?: readonly string[] existingWorktrees?: readonly { repoId: string; branch: string }[] openExternalUrl: (url: string) => Promise - onCreated: (worktreeId: string, name: string) => void + onCreated: (worktreeId: string, name: string, warning?: string) => void onClose: () => void } diff --git a/mobile/src/components/use-new-workspace-create-submit.ts b/mobile/src/components/use-new-workspace-create-submit.ts index 1ab3ac5d5c4..1a7ba078b27 100644 --- a/mobile/src/components/use-new-workspace-create-submit.ts +++ b/mobile/src/components/use-new-workspace-create-submit.ts @@ -58,7 +58,7 @@ export function useNewWorkspaceCreateSubmit(args: { getWorktreeCreateCutoverSupport: () => Promise transitionDrawer: (view: Exclude) => void setError: Dispatch> - onCreated: (worktreeId: string, name: string) => void + onCreated: (worktreeId: string, name: string, warning?: string) => void onClose: () => void }): { creating: boolean @@ -181,7 +181,7 @@ export function useNewWorkspaceCreateSubmit(args: { return } args.onClose() - args.onCreated(result.worktreeId, result.name) + args.onCreated(result.worktreeId, result.name, result.warning) } catch (error) { args.setError(error instanceof Error ? error.message : 'Failed to create workspace') } finally { diff --git a/mobile/src/diagnostics/troubleshoot-common-issues.tsx b/mobile/src/diagnostics/troubleshoot-common-issues.tsx index b794ad004d5..31fdb17cf85 100644 --- a/mobile/src/diagnostics/troubleshoot-common-issues.tsx +++ b/mobile/src/diagnostics/troubleshoot-common-issues.tsx @@ -1,4 +1,4 @@ -import { WifiOff, Shield, Monitor, Clock, Globe } from 'lucide-react-native' +import { WifiOff, Shield, Monitor, Clock, Globe, Bell } from 'lucide-react-native' import { colors } from '../theme/mobile-theme' export type TroubleshootSection = { @@ -9,6 +9,16 @@ export type TroubleshootSection = { } export const troubleshootCommonIssues: TroubleshootSection[] = [ + { + id: 'notifications', + icon: , + title: 'Push Notifications', + steps: [ + 'Check that system settings allow Orca notifications and that Focus or Do Not Disturb is off.', + 'Try cellular or another Wi-Fi network. If alerts arrive after switching, your network may be delaying delivery.' + ] + }, + { id: 'wifi', icon: , diff --git a/mobile/src/host-route-action-state.test.ts b/mobile/src/host-route-action-state.test.ts index 7f0ff6375a1..fd2e75d311f 100644 --- a/mobile/src/host-route-action-state.test.ts +++ b/mobile/src/host-route-action-state.test.ts @@ -19,6 +19,30 @@ describe('host route action state', () => { ) }) + // Why: the host reports a create that succeeded with a failed startup terminal via `warning`; + // dropping it here is what lands the phone on an unexplained empty session. + it('carries a host create warning into the session route', () => { + expect( + hostNewWorktreeSessionRoute( + 'local', + 'wt-1', + 'Hammerhead', + 'Failed to create the startup terminal' + ) + ).toBe( + '/h/local/session/wt-1?name=Hammerhead&created=1&warning=Failed+to+create+the+startup+terminal' + ) + }) + + it('omits an absent or blank create warning', () => { + expect(hostNewWorktreeSessionRoute('local', 'wt-1', 'Hammerhead', ' ')).toBe( + '/h/local/session/wt-1?name=Hammerhead&created=1' + ) + expect(hostNewWorktreeSessionRoute('local', 'wt-1', 'Hammerhead')).toBe( + '/h/local/session/wt-1?name=Hammerhead&created=1' + ) + }) + it('opens new worktree modal on an initial newWorktree action', () => { expect(createInitialHostRouteActionState('newWorktree')).toEqual({ routeAction: 'newWorktree', diff --git a/mobile/src/host-route-action-state.ts b/mobile/src/host-route-action-state.ts index a89c03fb472..5c2588b1e89 100644 --- a/mobile/src/host-route-action-state.ts +++ b/mobile/src/host-route-action-state.ts @@ -10,9 +10,14 @@ export function hostNewWorktreeRoute(hostId: string): `/h/${string}?action=newWo export function hostNewWorktreeSessionRoute( hostId: string, worktreeId: string, - worktreeName: string + worktreeName: string, + /** Host-reported create warning (e.g. the startup terminal failed to spawn). */ + warning?: string ): `/h/${string}/session/${string}?${string}` { const params = new URLSearchParams({ name: worktreeName, created: '1' }) + if (warning?.trim()) { + params.set('warning', warning) + } return `/h/${encodeURIComponent(hostId)}/session/${encodeURIComponent(worktreeId)}?${params}` } diff --git a/mobile/src/host-screen/host-screen-overlays.tsx b/mobile/src/host-screen/host-screen-overlays.tsx index 0f15f9d4e61..35a140fec7a 100644 --- a/mobile/src/host-screen/host-screen-overlays.tsx +++ b/mobile/src/host-screen/host-screen-overlays.tsx @@ -219,10 +219,10 @@ export function HostScreenOverlays({ controller }: { controller: HostScreenContr onVisibleChange={(visible) => { state.newWorktreeModalVisibleRef.current = visible }} - onCreated={(worktreeId, worktreeName) => { + onCreated={(worktreeId, worktreeName, warning) => { void catalog.fetchWorktrees({ allowDuringModal: true }) actions.navigateFromHostList( - hostNewWorktreeSessionRoute(hostId, worktreeId, worktreeName) + hostNewWorktreeSessionRoute(hostId, worktreeId, worktreeName, warning) ) }} onRouteVisibleChange={actions.setShowNewWorktreeVisible} diff --git a/mobile/src/host-screen/use-host-repo-metadata.ts b/mobile/src/host-screen/use-host-repo-metadata.ts index 198efbaf3ea..6840184c3a0 100644 --- a/mobile/src/host-screen/use-host-repo-metadata.ts +++ b/mobile/src/host-screen/use-host-repo-metadata.ts @@ -18,7 +18,7 @@ type SshTargetSummaryRow = { id: string; label: string } async function requestResult(client: RpcClient, method: string): Promise { try { const response = await client.sendRequest(method) - return response.ok ? (response as RpcSuccess).result : null + return response.ok ? response.result : null } catch { // Best-effort: hosts that predate a method still list repos; labels degrade to host ids. return null diff --git a/mobile/src/notifications/NotificationDeliverySection.test.tsx b/mobile/src/notifications/NotificationDeliverySection.test.tsx new file mode 100644 index 00000000000..8b7971b6086 --- /dev/null +++ b/mobile/src/notifications/NotificationDeliverySection.test.tsx @@ -0,0 +1,37 @@ +import { createElement } from 'react' +import { act, create } from 'react-test-renderer' +import { expect, it, vi } from 'vitest' +import { NotificationDeliverySection } from './NotificationDeliverySection' +import { DEFAULT_NOTIFICATION_DELIVERY } from './notification-delivery-preferences' + +vi.mock('@react-native-async-storage/async-storage', () => ({ default: {} })) +vi.mock('react-native', () => ({ + StyleSheet: { create: (value: unknown) => value }, + View: 'View', + Text: 'Text', + Switch: 'Switch' +})) + +it('shows only phone-specific controls while desktop owns category eligibility', () => { + const onChange = vi.fn() + let renderer: ReturnType + act(() => { + renderer = create( + createElement(NotificationDeliverySection, { value: DEFAULT_NOTIFICATION_DELIVERY, onChange }) + ) + }) + const switches = () => renderer.root.findAllByType('Switch' as never) + expect(switches().map((node) => node.props.accessibilityLabel)).toEqual([ + 'Only when away from desktop', + 'Notification sound', + 'Suppress while focused' + ]) + expect(JSON.stringify(renderer.toJSON())).toContain( + 'Alert types follow each paired desktop’s notification settings.' + ) + act(() => switches()[0].props.onValueChange(false)) + expect(onChange).toHaveBeenLastCalledWith( + expect.objectContaining({ onlyWhenDesktopAway: false, sound: true, suppressWhileViewing: true }) + ) + act(() => renderer.unmount()) +}) diff --git a/mobile/src/notifications/NotificationDeliverySection.tsx b/mobile/src/notifications/NotificationDeliverySection.tsx new file mode 100644 index 00000000000..df1f3dc0683 --- /dev/null +++ b/mobile/src/notifications/NotificationDeliverySection.tsx @@ -0,0 +1,72 @@ +import { StyleSheet, Switch, Text, View } from 'react-native' +import { colors, radii, spacing, typography } from '../theme/mobile-theme' +import type { NotificationDeliveryPreferences } from './notification-delivery-preferences' + +type Props = { + value: NotificationDeliveryPreferences + disabled?: boolean + onChange: (value: NotificationDeliveryPreferences) => void +} + +export function NotificationDeliverySection({ value, disabled, onChange }: Props) { + const row = (key: keyof NotificationDeliveryPreferences, label: string, hint?: string) => { + return ( + + + {label} + {hint && {hint}} + + onChange({ ...value, [key]: enabled })} + trackColor={{ false: colors.bgRaised, true: colors.textSecondary }} + thumbColor={colors.textPrimary} + /> + + ) + } + return ( + <> + + {row( + 'onlyWhenDesktopAway', + 'Only when away from desktop', + 'After 3 minutes without keyboard or mouse activity, or when locked.' + )} + {row('sound', 'Notification sound')} + {row( + 'suppressWhileViewing', + 'Suppress while focused', + 'Skip alerts for the workspace open on this phone.' + )} + + + Alert types follow each paired desktop’s notification settings. Notifications pause after 7 + days without using this app; open it and reconnect to resume. + + + ) +} + +const styles = StyleSheet.create({ + section: { + backgroundColor: colors.bgPanel, + borderRadius: radii.card, + overflow: 'hidden', + marginTop: spacing.md + }, + row: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, padding: spacing.md }, + labelGroup: { flex: 1, gap: spacing.xs }, + label: { fontSize: typography.bodySize, fontWeight: '500', color: colors.textPrimary }, + hint: { fontSize: typography.metaSize, color: colors.textMuted }, + disabled: { opacity: 0.5 }, + footer: { + fontSize: typography.metaSize, + color: colors.textMuted, + marginTop: spacing.md, + paddingHorizontal: spacing.sm + } +}) diff --git a/mobile/src/notifications/android-foreground-push.test.ts b/mobile/src/notifications/android-foreground-push.test.ts new file mode 100644 index 00000000000..cad381e7ee9 --- /dev/null +++ b/mobile/src/notifications/android-foreground-push.test.ts @@ -0,0 +1,112 @@ +import { beforeEach, expect, it, vi } from 'vitest' +import type { Notification } from 'expo-notifications' +import { startAndroidForegroundPushPresentation } from './android-foreground-push' + +const mocks = vi.hoisted(() => ({ + platform: { OS: 'android' }, + receive: (_notification: Notification) => {}, + remove: vi.fn(), + eligible: vi.fn().mockResolvedValue(true), + schedule: vi.fn().mockResolvedValue('message-1') +})) +vi.mock('./push-receive', () => ({ canPresentForegroundPush: mocks.eligible })) +vi.mock('react-native', () => ({ Platform: mocks.platform })) +vi.mock('expo-notifications', () => ({ + addNotificationReceivedListener: (listener: typeof mocks.receive) => { + mocks.receive = listener + return { remove: mocks.remove } + }, + scheduleNotificationAsync: mocks.schedule +})) + +function notification(trigger: unknown = { type: 'push', remoteMessage: { notification: null } }) { + return { + request: { + identifier: 'message-1', + trigger, + content: { + title: 'Test notification', + body: '', + sound: 'default', + data: { + hostFingerprint: 'host', + notificationId: 'event', + notificationEpoch: 'epoch', + notificationSeq: '3', + paneKey: 'pane', + channelId: 'orca-desktop' + } + } + } + } as unknown as Notification +} + +beforeEach(() => { + vi.clearAllMocks() + mocks.eligible.mockReset().mockResolvedValue(true) + mocks.platform.OS = 'android' +}) + +it('presents a title-only data push with its original identity, routing and channel', async () => { + const stop = startAndroidForegroundPushPresentation() + const incoming = notification() + mocks.receive(incoming) + await vi.waitFor(() => expect(mocks.schedule).toHaveBeenCalledOnce()) + expect(mocks.schedule).toHaveBeenCalledWith({ + identifier: incoming.request.identifier, + content: incoming.request.content, + trigger: { channelId: 'orca-desktop' } + }) + stop() + expect(mocks.remove).toHaveBeenCalledOnce() +}) + +it('does not reschedule its own local notification or normal provider notifications', () => { + startAndroidForegroundPushPresentation() + mocks.receive(notification(null)) + mocks.receive(notification({ type: 'channel', channelId: 'orca-desktop' })) + mocks.receive(notification({ type: 'push', remoteMessage: { notification: { title: 'Test' } } })) + expect(mocks.schedule).not.toHaveBeenCalled() +}) + +it('leaves silent dismissals and unrelated messages alone', () => { + startAndroidForegroundPushPresentation() + const incoming = notification() + incoming.request.content.data.kind = 'dismiss' + mocks.receive(incoming) + incoming.request.content.data = {} + mocks.receive(incoming) + expect(mocks.schedule).not.toHaveBeenCalled() +}) + +it('leaves iOS delivery unchanged', () => { + mocks.platform.OS = 'ios' + startAndroidForegroundPushPresentation()() + expect(mocks.remove).not.toHaveBeenCalled() +}) + +it('waits for eligibility before scheduling, even if native presentation will bypass JS', async () => { + let resolve!: (eligible: boolean) => void + mocks.eligible.mockReturnValue( + new Promise((done) => { + resolve = done + }) + ) + startAndroidForegroundPushPresentation() + mocks.receive(notification()) + expect(mocks.schedule).not.toHaveBeenCalled() + // Model a dismissal arriving while the eligibility reads are in flight. + resolve(false) + await Promise.resolve() + expect(mocks.schedule).not.toHaveBeenCalled() +}) + +it('does not schedule when eligibility cannot be read', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + mocks.eligible.mockRejectedValueOnce(new Error('storage unavailable')) + startAndroidForegroundPushPresentation() + mocks.receive(notification()) + await vi.waitFor(() => expect(warn).toHaveBeenCalledOnce()) + expect(mocks.schedule).not.toHaveBeenCalled() + warn.mockRestore() +}) diff --git a/mobile/src/notifications/android-foreground-push.ts b/mobile/src/notifications/android-foreground-push.ts new file mode 100644 index 00000000000..cbff78d0bf2 --- /dev/null +++ b/mobile/src/notifications/android-foreground-push.ts @@ -0,0 +1,49 @@ +import { Platform } from 'react-native' +import * as Notifications from 'expo-notifications' +import { canPresentForegroundPush } from './push-receive' +import { readOrcaPushPayload } from './push-payload' + +export function startAndroidForegroundPushPresentation(): () => void { + if (Platform.OS !== 'android') { + return () => {} + } + + const subscription = Notifications.addNotificationReceivedListener((notification) => { + const { trigger, content, identifier } = notification.request + // Expo emits foreground data pushes but only auto-presents them in the background. + if ( + !trigger || + !('type' in trigger) || + trigger.type !== 'push' || + trigger.remoteMessage?.notification !== null + ) { + return + } + const payload = readOrcaPushPayload(content.data) + if (!payload || payload.kind === 'dismiss' || (!content.title && !content.body)) { + return + } + + void present().catch((error: unknown) => { + console.warn('[push] Foreground notification presentation failed', error) + }) + + async function present(): Promise { + if (!payload || !(await canPresentForegroundPush(payload))) { + return + } + await Notifications.scheduleNotificationAsync({ + identifier, + content: { + title: content.title, + body: content.body, + data: content.data, + sound: content.sound === 'default' ? 'default' : false + }, + trigger: + typeof content.data?.channelId === 'string' ? { channelId: content.data.channelId } : null + }) + } + }) + return () => subscription.remove() +} diff --git a/mobile/src/notifications/desktop-notification-channel.test.ts b/mobile/src/notifications/desktop-notification-channel.test.ts new file mode 100644 index 00000000000..95ff41ebe35 --- /dev/null +++ b/mobile/src/notifications/desktop-notification-channel.test.ts @@ -0,0 +1,62 @@ +import { readFileSync } from 'node:fs' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import * as Notifications from 'expo-notifications' +import { Platform } from 'react-native' +import { + DESKTOP_NOTIFICATION_CHANNEL_ID, + ensureDesktopNotificationChannel +} from './desktop-notification-channel' + +vi.mock('expo-notifications', () => ({ + AndroidImportance: { HIGH: 'high' }, + setNotificationChannelAsync: vi.fn() +})) + +vi.mock('react-native', () => ({ + AppState: { currentState: 'background' }, + Platform: { OS: 'android' } +})) + +beforeEach(() => { + vi.clearAllMocks() + Object.assign(Platform, { OS: 'android' }) + vi.mocked(Notifications.setNotificationChannelAsync).mockResolvedValue(null as never) +}) + +describe('ensureDesktopNotificationChannel', () => { + it('creates the channel the gateway payload names', async () => { + await ensureDesktopNotificationChannel() + + expect(Notifications.setNotificationChannelAsync).toHaveBeenCalledWith( + 'orca-desktop', + expect.objectContaining({ importance: 'high' }) + ) + expect(DESKTOP_NOTIFICATION_CHANNEL_ID).toBe('orca-desktop') + }) + + it('does nothing on iOS, which has no notification channels', () => { + Object.assign(Platform, { OS: 'ios' }) + + ensureDesktopNotificationChannel() + + expect(Notifications.setNotificationChannelAsync).not.toHaveBeenCalled() + }) + + it('reports channel failure so registration can retry', async () => { + vi.mocked(Notifications.setNotificationChannelAsync).mockRejectedValue(new Error('no channels')) + + await expect(ensureDesktopNotificationChannel()).rejects.toThrow('no channels') + }) +}) + +describe('app boot', () => { + it('creates the channel at startup, not only once a socket subscribes', () => { + // A background push can be the first thing to target 'orca-desktop', and Android + // drops a notification whose channel does not exist. Asserted against the source + // because vitest only collects src/, so app/_layout.tsx has no runtime coverage. + const layout = readFileSync(new URL('../../app/_layout.tsx', import.meta.url), 'utf8') + + expect(layout).toContain("from '../src/notifications/desktop-notification-channel'") + expect(layout).toMatch(/^void ensureDesktopNotificationChannel\(\)\.catch\(/m) + }) +}) diff --git a/mobile/src/notifications/desktop-notification-channel.ts b/mobile/src/notifications/desktop-notification-channel.ts new file mode 100644 index 00000000000..cce1f73d582 --- /dev/null +++ b/mobile/src/notifications/desktop-notification-channel.ts @@ -0,0 +1,27 @@ +import * as Notifications from 'expo-notifications' +import { Platform } from 'react-native' + +// Why an id both sides share: the gateway's FCM payload names this channel, so a +// background push can be the first thing that ever targets it. Android drops a +// notification whose channel does not exist, and the channel used to be created +// only inside subscribeToDesktopNotifications — i.e. only once a socket connected. +export const DESKTOP_NOTIFICATION_CHANNEL_ID = 'orca-desktop' + +/** Idempotent on Android (the OS updates the existing channel); a no-op elsewhere. */ +export async function ensureDesktopNotificationChannel(): Promise { + if (Platform.OS !== 'android') { + return + } + await Notifications.setNotificationChannelAsync(`${DESKTOP_NOTIFICATION_CHANNEL_ID}-silent`, { + name: 'Orca silent notifications', + importance: Notifications.AndroidImportance.HIGH, + sound: null, + enableVibrate: false + }) + await Notifications.setNotificationChannelAsync(DESKTOP_NOTIFICATION_CHANNEL_ID, { + name: 'Desktop Notifications', + importance: Notifications.AndroidImportance.HIGH, + vibrationPattern: [0, 250], + lightColor: '#6366f1' + }) +} diff --git a/mobile/src/notifications/desktop-notification-events.ts b/mobile/src/notifications/desktop-notification-events.ts new file mode 100644 index 00000000000..b6e7492b648 --- /dev/null +++ b/mobile/src/notifications/desktop-notification-events.ts @@ -0,0 +1,6 @@ +export type DismissNotificationEvent = { + type: 'dismiss' + notificationId: string + notificationSeq?: number + notificationEpoch?: string +} diff --git a/mobile/src/notifications/expo-native-token-retry.test.ts b/mobile/src/notifications/expo-native-token-retry.test.ts new file mode 100644 index 00000000000..7fabcd6555c --- /dev/null +++ b/mobile/src/notifications/expo-native-token-retry.test.ts @@ -0,0 +1,40 @@ +import { beforeEach, expect, it, vi } from 'vitest' + +const native = vi.hoisted(() => vi.fn()) +vi.mock('expo-modules-core', () => ({ Platform: { OS: 'ios' }, UnavailabilityError: Error })) +vi.mock('expo-notifications/build/PushTokenManager', () => ({ + default: { getDevicePushTokenAsync: native } +})) +vi.mock('expo-notifications/build/warnOfExpoGoPushUsage', () => ({ + warnOfExpoGoPushUsage: () => {} +})) + +beforeEach(() => { + vi.resetModules() + native.mockReset() +}) + +it('releases a failed Expo native-token request so the next attempt can succeed', async () => { + const { getDevicePushTokenAsync } = + await import('expo-notifications/build/getDevicePushTokenAsync') + native.mockRejectedValueOnce(new Error('APNs unavailable')).mockResolvedValueOnce('device-token') + await expect(getDevicePushTokenAsync()).rejects.toThrow('APNs unavailable') + await expect(getDevicePushTokenAsync()).resolves.toEqual({ type: 'ios', data: 'device-token' }) + expect(native).toHaveBeenCalledTimes(2) +}) + +it('still shares one pending native request between concurrent callers', async () => { + const { getDevicePushTokenAsync } = + await import('expo-notifications/build/getDevicePushTokenAsync') + let resolve!: (token: string) => void + native.mockReturnValue( + new Promise((done) => { + resolve = done + }) + ) + const first = getDevicePushTokenAsync() + const second = getDevicePushTokenAsync() + expect(native).toHaveBeenCalledOnce() + resolve('device-token') + expect(await first).toEqual(await second) +}) diff --git a/mobile/src/notifications/local-notification-scheduling.ts b/mobile/src/notifications/local-notification-scheduling.ts deleted file mode 100644 index f511346250e..00000000000 --- a/mobile/src/notifications/local-notification-scheduling.ts +++ /dev/null @@ -1,191 +0,0 @@ -import * as Notifications from 'expo-notifications' -import { Platform } from 'react-native' -import { loadPushNotificationsEnabled } from '../storage/preferences' -import { buildLocalNotificationData, type DesktopNotificationSource } from './notification-routing' -import { ensureNotificationPermissions } from './notification-permissions' - -export type NotificationEvent = { - type: 'notification' - source: DesktopNotificationSource - title: string - body: string - worktreeId?: string - notificationId?: string - // Desktop-assigned seq for reconnect catch-up (#8129); optional since older runtimes may omit it. - notificationSeq?: number - // Counter lifetime the seq belongs to (#8591); absent on older runtimes. - notificationEpoch?: string -} - -export type DismissNotificationEvent = { - type: 'dismiss' - notificationId: string - notificationSeq?: number - notificationEpoch?: string -} - -type ScheduledNotificationState = { - identifier?: string - pending?: Promise - dismissAfterSchedule?: boolean -} - -const scheduledNotificationsByHostAndNotificationId = new Map() - -// Why: keys never repeat and are only freed on desktop dismiss (which remote users often miss), so bound the map to stop unbounded growth. -const MAX_SCHEDULED_NOTIFICATIONS = 256 -let maxScheduledNotifications = MAX_SCHEDULED_NOTIFICATIONS - -function getStoredNotificationKey(hostId: string, notificationId: string): string { - return `${encodeURIComponent(hostId)}:${encodeURIComponent(notificationId)}` -} - -// Evict oldest settled entries (never mid-schedule); Map iteration is insertion order so the first match is oldest. -function boundScheduledNotifications(): void { - while (scheduledNotificationsByHostAndNotificationId.size > maxScheduledNotifications) { - let evicted = false - for (const [key, state] of scheduledNotificationsByHostAndNotificationId) { - if (!state.pending) { - scheduledNotificationsByHostAndNotificationId.delete(key) - evicted = true - break - } - } - if (!evicted) { - break - } - } -} - -/** Test-only: override the cap (pass no arg to restore the default). */ -export function setScheduledNotificationsMaxForTests(max?: number): void { - maxScheduledNotifications = max ?? MAX_SCHEDULED_NOTIFICATIONS -} - -export function configureNotificationChannel(): void { - if (Platform.OS === 'android') { - void Notifications.setNotificationChannelAsync('orca-desktop', { - name: 'Desktop Notifications', - importance: Notifications.AndroidImportance.HIGH, - vibrationPattern: [0, 250], - lightColor: '#6366f1' - }) - } -} - -export async function showLocalNotification( - event: NotificationEvent, - hostId: string -): Promise { - const storedKey = event.notificationId - ? getStoredNotificationKey(hostId, event.notificationId) - : null - - if (!storedKey) { - const enabled = await loadPushNotificationsEnabled() - if (!enabled) { - return - } - - const granted = await ensureNotificationPermissions() - if (!granted) { - return - } - - await Notifications.scheduleNotificationAsync({ - content: { - title: event.title, - body: event.body, - data: buildLocalNotificationData(event, hostId), - ...(Platform.OS === 'android' ? { channelId: 'orca-desktop' } : {}) - }, - trigger: null - }) - return - } - - let state = scheduledNotificationsByHostAndNotificationId.get(storedKey) - if (state?.pending) { - return - } - if (!state) { - state = {} - scheduledNotificationsByHostAndNotificationId.set(storedKey, state) - } - const notificationState = state - - const pending = (async () => { - const enabled = await loadPushNotificationsEnabled() - if (!enabled) { - return null - } - - const granted = await ensureNotificationPermissions() - if (!granted) { - return null - } - - if (notificationState.identifier) { - await Notifications.dismissNotificationAsync(notificationState.identifier).catch(() => {}) - notificationState.identifier = undefined - } - - return Notifications.scheduleNotificationAsync({ - content: { - title: event.title, - body: event.body, - data: buildLocalNotificationData(event, hostId), - ...(Platform.OS === 'android' ? { channelId: 'orca-desktop' } : {}) - }, - trigger: null - }) - })() - notificationState.pending = pending - - try { - const scheduledIdentifier = await pending - if (!scheduledIdentifier) { - if (!notificationState.identifier) { - scheduledNotificationsByHostAndNotificationId.delete(storedKey) - } - return - } - if (notificationState.dismissAfterSchedule) { - notificationState.dismissAfterSchedule = false - scheduledNotificationsByHostAndNotificationId.delete(storedKey) - await Notifications.dismissNotificationAsync(scheduledIdentifier).catch(() => {}) - return - } - notificationState.identifier = scheduledIdentifier - boundScheduledNotifications() - } finally { - if (notificationState.pending === pending) { - notificationState.pending = undefined - notificationState.dismissAfterSchedule = false - } - } -} - -export async function dismissLocalNotification( - event: DismissNotificationEvent, - hostId: string -): Promise { - if (!event.notificationId) { - return - } - const storedKey = getStoredNotificationKey(hostId, event.notificationId) - const state = scheduledNotificationsByHostAndNotificationId.get(storedKey) - if (!state) { - return - } - if (state.pending) { - // Why: dismiss can arrive while the OS is still scheduling; defer it so no stale banner survives. - state.dismissAfterSchedule = true - return - } - if (!state.identifier) { - return - } - scheduledNotificationsByHostAndNotificationId.delete(storedKey) - await Notifications.dismissNotificationAsync(state.identifier).catch(() => {}) -} diff --git a/mobile/src/notifications/mobile-notifications.test.ts b/mobile/src/notifications/mobile-notifications.test.ts index d85b1363005..ba784520f98 100644 --- a/mobile/src/notifications/mobile-notifications.test.ts +++ b/mobile/src/notifications/mobile-notifications.test.ts @@ -1,969 +1,59 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import * as Notifications from 'expo-notifications' -import { Platform } from 'react-native' -import { - getNotificationPermissionState, - setScheduledNotificationsMaxForTests, - subscribeToDesktopNotifications -} from './mobile-notifications' -import AsyncStorage from '@react-native-async-storage/async-storage' -import type { RpcClient } from '../transport/rpc-client' -import { loadPushNotificationsEnabled } from '../storage/preferences' -import { resetHostNotificationSessionsForTests } from './notification-reconnect-catchup' +import { subscribeToDesktopNotifications } from './mobile-notifications' +import { dismissHostPushNotification } from './push-socket-dismissal' +import { requestNotificationCatchup } from './push-dismissal-reconciliation' -vi.mock('expo-notifications', () => ({ - AndroidImportance: { HIGH: 'high' }, - setNotificationChannelAsync: vi.fn(), - getPermissionsAsync: vi.fn(), - requestPermissionsAsync: vi.fn(), - scheduleNotificationAsync: vi.fn(), - dismissNotificationAsync: vi.fn() +vi.mock('./push-socket-dismissal', () => ({ + dismissHostPushNotification: vi.fn(async () => {}) })) - -vi.mock('react-native', () => ({ - Platform: { OS: 'ios', Version: 18 } +vi.mock('./push-dismissal-reconciliation', () => ({ + requestNotificationCatchup: vi.fn(async () => {}) })) +vi.mock('./notification-permissions', () => ({})) -// Why: mobile-notifications now persists the catch-up watermark to -// AsyncStorage. The package isn't resolvable in the node test env (other -// mobile tests mock it the same way), so we provide a no-op mock. -vi.mock('@react-native-async-storage/async-storage', () => ({ - default: { - getItem: vi.fn(async () => null), - setItem: vi.fn(async () => undefined) - } -})) +type Handler = (data: unknown) => void -vi.mock('../storage/preferences', () => ({ - loadPushNotificationsEnabled: vi.fn() -})) - -beforeEach(() => { - Object.assign(Platform, { OS: 'ios', Version: 18 }) - // Why (#8591): the reconnect watermark/seen-set now live per host at module - // scope so they survive the app's unsubscribe-on-disconnect. Reset between - // tests so each case starts from a genuine cold open. - resetHostNotificationSessionsForTests() -}) - -describe('getNotificationPermissionState', () => { - it.each([ - { os: 'android', version: 32, expected: false }, - { os: 'android', version: 33, expected: true }, - { os: 'ios', version: 18, expected: true } - ])( - 'reports whether a granted $os $version authorization reflects user choice', - async ({ os, version, expected }) => { - Object.assign(Platform, { OS: os, Version: version }) - vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ - status: 'granted', - canAskAgain: true - } as never) - - await expect(getNotificationPermissionState()).resolves.toMatchObject({ - granted: true, - authorizationReflectsUserChoice: expected - }) +function client() { + let handler: Handler | undefined + return { + getState: vi.fn(() => 'connected'), + sendRequest: vi.fn(async () => ({ ok: true })), + subscribe: vi.fn((_method: string, _params: unknown, callback: Handler) => { + handler = callback + return vi.fn() + }), + emit(data: unknown) { + handler?.(data) } - ) -}) + } +} + +beforeEach(() => vi.clearAllMocks()) describe('subscribeToDesktopNotifications', () => { - beforeEach(() => { - vi.clearAllMocks() + it('never presents an OS banner for socket alert or replay events', async () => { + const rpc = client() + subscribeToDesktopNotifications(rpc as never, 'host-1') + rpc.emit({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-1' }) + rpc.emit({ + type: 'notification', + notificationId: 'agent-1', + title: 'Needs input', + body: 'Reply', + source: 'agent-task-complete' + }) + await Promise.resolve() + expect(requestNotificationCatchup).toHaveBeenCalledWith(rpc, 'host-1', expect.any(Function)) + expect(dismissHostPushNotification).not.toHaveBeenCalled() }) - // Why the macrotask and not N microtask ticks (#8591): deliveries now run through - // the per-host serialization queue, so a delivery is several more `await` hops deep - // than it used to be and a fixed tick count silently under-drains. Yielding to the - // macrotask queue drains whatever depth the chain happens to have. - function flushAsync(): Promise { - return new Promise((resolve) => { - setTimeout(resolve, 0) - }) - } - - function makeDeferred(): { promise: Promise; resolve: (value: T) => void } { - let resolve!: (value: T) => void - const promise = new Promise((next) => { - resolve = next - }) - return { promise, resolve } - } - - it('drops the local stream when disposed before the desktop returns ready', () => { - const unsubscribeStream = vi.fn() - const client = { - subscribe: vi.fn(() => unsubscribeStream), - getState: vi.fn(() => 'connected'), - sendRequest: vi.fn() - } as unknown as RpcClient - - const unsubscribe = subscribeToDesktopNotifications(client, 'host-1') - unsubscribe() - - expect(unsubscribeStream).toHaveBeenCalledTimes(1) - expect(client.sendRequest).not.toHaveBeenCalled() - }) - - it('stores scheduled notification identifiers, replaces duplicates, and dismisses by id', async () => { - vi.mocked(loadPushNotificationsEnabled).mockResolvedValue(true) - vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ - status: 'granted', - canAskAgain: true - } as never) - vi.mocked(Notifications.scheduleNotificationAsync) - .mockResolvedValueOnce('scheduled-1') - .mockResolvedValueOnce('scheduled-2') - vi.mocked(Notifications.dismissNotificationAsync).mockResolvedValue(undefined) - let onEvent: ((data: unknown) => void) | null = null - const client = { - subscribe: vi.fn((_method, _params, callback: (data: unknown) => void) => { - onEvent = callback - return vi.fn() - }), - getState: vi.fn(() => 'connected'), - sendRequest: vi.fn() - } as unknown as RpcClient - - subscribeToDesktopNotifications(client, 'host-1') - onEvent?.({ - type: 'notification', - source: 'agent-task-complete', - title: 'Done', - body: 'Finished.', - worktreeId: 'repo::/tmp/worktree', - notificationId: 'agent:one' - }) - await flushAsync() - onEvent?.({ - type: 'notification', - source: 'agent-task-complete', - title: 'Done again', - body: 'Finished again.', - notificationId: 'agent:one' - }) - await flushAsync() - expect(Notifications.scheduleNotificationAsync).toHaveBeenCalledTimes(2) - onEvent?.({ type: 'dismiss', notificationId: 'agent:one' }) - await flushAsync() - - expect(Notifications.scheduleNotificationAsync).toHaveBeenCalledTimes(2) - expect(Notifications.scheduleNotificationAsync).toHaveBeenNthCalledWith( - 1, - expect.objectContaining({ - content: expect.objectContaining({ - data: expect.objectContaining({ - hostId: 'host-1', - notificationId: 'agent:one', - worktreeId: 'repo::/tmp/worktree' - }) - }) - }) - ) - expect(Notifications.dismissNotificationAsync).toHaveBeenNthCalledWith(1, 'scheduled-1') - expect(Notifications.dismissNotificationAsync).toHaveBeenNthCalledWith(2, 'scheduled-2') - }) - - it('dedupes concurrent notification events with the same desktop notification id', async () => { - vi.mocked(loadPushNotificationsEnabled).mockResolvedValue(true) - vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ - status: 'granted', - canAskAgain: true - } as never) - vi.mocked(Notifications.scheduleNotificationAsync).mockResolvedValue('scheduled-1') - let onEvent: ((data: unknown) => void) | null = null - const client = { - subscribe: vi.fn((_method, _params, callback: (data: unknown) => void) => { - onEvent = callback - return vi.fn() - }), - getState: vi.fn(() => 'connected'), - sendRequest: vi.fn() - } as unknown as RpcClient - - subscribeToDesktopNotifications(client, 'host-concurrent') - onEvent?.({ - type: 'notification', - source: 'agent-task-complete', - title: 'Done', - body: 'Finished.', - notificationId: 'agent:concurrent' - }) - onEvent?.({ - type: 'notification', - source: 'agent-task-complete', - title: 'Done', - body: 'Finished.', - notificationId: 'agent:concurrent' - }) - await flushAsync() - - expect(Notifications.scheduleNotificationAsync).toHaveBeenCalledTimes(1) - }) - - it('dismisses a notification when dismiss arrives while scheduling is pending', async () => { - vi.mocked(loadPushNotificationsEnabled).mockResolvedValue(true) - vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ - status: 'granted', - canAskAgain: true - } as never) - let resolveSchedule!: (identifier: string) => void - vi.mocked(Notifications.scheduleNotificationAsync).mockImplementation( - () => - new Promise((resolve) => { - resolveSchedule = resolve - }) - ) - vi.mocked(Notifications.dismissNotificationAsync).mockResolvedValue(undefined) - let onEvent: ((data: unknown) => void) | null = null - const client = { - subscribe: vi.fn((_method, _params, callback: (data: unknown) => void) => { - onEvent = callback - return vi.fn() - }), - getState: vi.fn(() => 'connected'), - sendRequest: vi.fn() - } as unknown as RpcClient - - subscribeToDesktopNotifications(client, 'host-dismiss-race') - onEvent?.({ - type: 'notification', - source: 'agent-task-complete', - title: 'Done', - body: 'Finished.', - notificationId: 'agent:pending' - }) - await flushAsync() - onEvent?.({ type: 'dismiss', notificationId: 'agent:pending' }) - resolveSchedule('scheduled-pending') - await flushAsync() - - expect(Notifications.dismissNotificationAsync).toHaveBeenCalledWith('scheduled-pending') - }) - - it('does not carry a failed pending dismiss into a future schedule', async () => { - const secondEnabled = makeDeferred() - vi.mocked(loadPushNotificationsEnabled) - .mockResolvedValueOnce(true) - .mockReturnValueOnce(secondEnabled.promise) - .mockResolvedValueOnce(true) - vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ - status: 'granted', - canAskAgain: true - } as never) - vi.mocked(Notifications.scheduleNotificationAsync) - .mockResolvedValueOnce('scheduled-1') - .mockResolvedValueOnce('scheduled-2') - vi.mocked(Notifications.dismissNotificationAsync).mockResolvedValue(undefined) - let onEvent: ((data: unknown) => void) | null = null - const client = { - subscribe: vi.fn((_method, _params, callback: (data: unknown) => void) => { - onEvent = callback - return vi.fn() - }), - getState: vi.fn(() => 'connected'), - sendRequest: vi.fn() - } as unknown as RpcClient - - subscribeToDesktopNotifications(client, 'host-dismiss-failed-replacement') - onEvent?.({ - type: 'notification', - source: 'agent-task-complete', - title: 'Done', - body: 'Finished.', - notificationId: 'agent:stale-dismiss' - }) - await flushAsync() - onEvent?.({ - type: 'notification', - source: 'agent-task-complete', - title: 'Done again', - body: 'Finished again.', - notificationId: 'agent:stale-dismiss' - }) - await flushAsync() - onEvent?.({ type: 'dismiss', notificationId: 'agent:stale-dismiss' }) - secondEnabled.resolve(false) - await flushAsync() - - onEvent?.({ - type: 'notification', - source: 'agent-task-complete', - title: 'Done later', - body: 'Finished later.', - notificationId: 'agent:stale-dismiss' - }) - await flushAsync() - - expect(Notifications.scheduleNotificationAsync).toHaveBeenCalledTimes(2) - expect(Notifications.dismissNotificationAsync).toHaveBeenCalledTimes(1) - expect(Notifications.dismissNotificationAsync).toHaveBeenCalledWith('scheduled-1') - }) - - it('treats unknown dismiss events as no-ops', async () => { - vi.mocked(Notifications.dismissNotificationAsync).mockResolvedValue(undefined) - let onEvent: ((data: unknown) => void) | null = null - const client = { - subscribe: vi.fn((_method, _params, callback: (data: unknown) => void) => { - onEvent = callback - return vi.fn() - }), - getState: vi.fn(() => 'connected'), - sendRequest: vi.fn() - } as unknown as RpcClient - - subscribeToDesktopNotifications(client, 'host-unknown') - onEvent?.({ type: 'dismiss', notificationId: 'agent:missing' }) - await flushAsync() - - expect(Notifications.dismissNotificationAsync).not.toHaveBeenCalled() - }) - - // Why: notificationId is unique per completion, so the map grew unbounded when - // the desktop never sent a dismiss (the remote-mobile case). It is now capped. - it('evicts the oldest scheduled entry once the cap is exceeded', async () => { - setScheduledNotificationsMaxForTests(1) - try { - vi.mocked(loadPushNotificationsEnabled).mockResolvedValue(true) - vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ - status: 'granted', - canAskAgain: true - } as never) - vi.mocked(Notifications.scheduleNotificationAsync) - .mockResolvedValueOnce('scheduled-old') - .mockResolvedValueOnce('scheduled-new') - vi.mocked(Notifications.dismissNotificationAsync).mockResolvedValue(undefined) - let onEvent: ((data: unknown) => void) | null = null - const client = { - subscribe: vi.fn((_method, _params, callback: (data: unknown) => void) => { - onEvent = callback - return vi.fn() - }), - getState: vi.fn(() => 'connected'), - sendRequest: vi.fn() - } as unknown as RpcClient - - subscribeToDesktopNotifications(client, 'host-1') - onEvent?.({ type: 'notification', title: 't', body: 'b', notificationId: 'agent:old' }) - await flushAsync() - onEvent?.({ type: 'notification', title: 't', body: 'b', notificationId: 'agent:new' }) - await flushAsync() - - // The older entry was evicted by the cap: dismissing it is a no-op... - onEvent?.({ type: 'dismiss', notificationId: 'agent:old' }) - await flushAsync() - expect(Notifications.dismissNotificationAsync).not.toHaveBeenCalledWith('scheduled-old') - - // ...while the most-recent entry is retained and still dismissable. - onEvent?.({ type: 'dismiss', notificationId: 'agent:new' }) - await flushAsync() - expect(Notifications.dismissNotificationAsync).toHaveBeenCalledWith('scheduled-new') - } finally { - setScheduledNotificationsMaxForTests() - } - }) -}) - -// Why: #8129 catch-up. On a reconnect the live stream re-emits `ready`; the -// client must fetch missed notifications from its watermark and push exactly -// the ones it had not yet delivered — never re-pushing an already-delivered id. -describe('subscribeToDesktopNotifications — reconnect catch-up', () => { - const AsyncStorageMock = vi.mocked(AsyncStorage) - - beforeEach(() => { - vi.clearAllMocks() - AsyncStorageMock.getItem.mockResolvedValue(null) - vi.mocked(Notifications.dismissNotificationAsync).mockResolvedValue(undefined) - }) - - function flushAsync(): Promise { - return new Promise((resolve) => { - setTimeout(resolve, 10) - }) - } - - function makeClient() { - let onData: ((data: unknown) => void) | null = null - const sentRequests: { method: string; params: unknown }[] = [] - const client = { - subscribe: vi.fn((_method: string, _params: unknown, cb: (data: unknown) => void) => { - onData = cb - return vi.fn() - }), - getState: vi.fn(() => 'connected'), - sendRequest: vi.fn( - async (method: string, _params: unknown = {}) => - ({ - ok: true, - result: method === 'notifications.getMissedSince' ? { notifications: [] } : undefined - }) as never - ) - } - // Why: onData is captured live via a getter (not destructured) because the - // subscribe mock assigns it asynchronously as a side effect of - // subscribeToDesktopNotifications calling client.subscribe. - return { - client: client as unknown as RpcClient, - get onData() { - return onData - }, - sentRequests - } - } - - it('does not fetch missed notifications on the first (cold-open) ready', async () => { - vi.mocked(loadPushNotificationsEnabled).mockResolvedValue(true) - vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ - status: 'granted', - canAskAgain: true - } as never) - vi.mocked(Notifications.scheduleNotificationAsync).mockResolvedValue('scheduled-1') - - const sub = makeClient() - subscribeToDesktopNotifications(sub.client, 'host-1') - // First ready = cold open. - sub.onData?.({ type: 'ready', subscriptionId: 'sub-1' }) - await flushAsync() - - expect(sub.client.sendRequest).not.toHaveBeenCalledWith( - 'notifications.getMissedSince', - expect.anything() - ) - }) - - it('fetches only notifications after the delivered watermark (idempotent catch-up)', async () => { - vi.mocked(loadPushNotificationsEnabled).mockResolvedValue(true) - vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ - status: 'granted', - canAskAgain: true - } as never) - vi.mocked(Notifications.scheduleNotificationAsync).mockResolvedValue('scheduled-1') - - const sub = makeClient() - // The desktop honours the watermark: only seq 10 (agent:missed) is returned - // because seq 11 (agent:dup) was already delivered on the live stream and - // advanced lastDeliveredSeq to 11. So the replay never re-includes it. - sub.client.sendRequest = vi.fn(async (method: string) => { - if (method === 'notifications.getMissedSince') { - return { - ok: true, - result: { - notifications: [ - { - type: 'notification', - title: 'missed', - body: 'b', - notificationId: 'agent:missed', - notificationSeq: 10 - } - ] - } - } as never - } - return { ok: true, result: undefined } as never - }) - - subscribeToDesktopNotifications(sub.client, 'host-1') - // First ready = cold open (no fetch). - sub.onData?.({ type: 'ready', subscriptionId: 'sub-1' }) - await flushAsync() - // Live stream already delivered agent:dup (seq 11) before reap. - sub.onData?.({ - type: 'notification', - title: 'dup', - body: 'b', - notificationId: 'agent:dup', - notificationSeq: 11 - }) - await flushAsync() - // Reconnect ready → fetchMissed sends the watermark (11). - sub.onData?.({ type: 'ready', subscriptionId: 'sub-1' }) - await flushAsync() - await flushAsync() - - // The watermark passed to getMissedSince is the delivered seq. - const missedCall = vi - .mocked(sub.client.sendRequest) - .mock.calls.find((c: unknown[]) => c[0] === 'notifications.getMissedSince') - expect(missedCall?.[1]).toEqual({ lastSeenSeq: 11 }) - // Only agent:missed was pushed; agent:dup appears exactly once (live only). - const scheduledIds = vi - .mocked(Notifications.scheduleNotificationAsync) - .mock.calls.map( - (call) => - (call[0] as { content: { data: { notificationId: string } } }).content.data.notificationId - ) - expect(scheduledIds).toEqual(['agent:dup', 'agent:missed']) - expect(scheduledIds.filter((id) => id === 'agent:dup')).toHaveLength(1) - }) - - it('voids a persisted watermark whose epoch predates a desktop restart', async () => { - // #8591: the desktop's seq counter restarts at 0 each launch while this watermark - // is persisted. Reconnecting to a restarted desktop with seq 57 would make - // `57 >= 2` true and silently kill catch-up. The epoch on 'ready' is what tells - // the client the counter changed, so the stale watermark must be dropped. - vi.mocked(loadPushNotificationsEnabled).mockResolvedValue(true) - vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ - status: 'granted', - canAskAgain: true - } as never) - vi.mocked(Notifications.scheduleNotificationAsync).mockResolvedValue('scheduled-1') - vi.mocked(AsyncStorage.getItem).mockImplementation(async (key: string) => - key.startsWith('orca:mobileNotificationsWatermark:') - ? JSON.stringify({ seq: 57, epoch: 'epoch-before-restart' }) - : null - ) - - const sub = makeClient() - subscribeToDesktopNotifications(sub.client, 'host-1') - // Cold open under the OLD desktop process, so the watermark loads as 57. - sub.onData?.({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-before-restart' }) - await flushAsync() - await flushAsync() - - // Desktop restarts: new epoch, counter back near 0. - sub.onData?.({ type: 'ready', subscriptionId: 'sub-2', epoch: 'epoch-after-restart' }) - await flushAsync() - await flushAsync() - - const missedCalls = vi - .mocked(sub.client.sendRequest) - .mock.calls.filter((c: unknown[]) => c[0] === 'notifications.getMissedSince') - // The cold open catches up from its stored watermark against the SAME counter — - // 57 is meaningful there, so it is the correct cut (#8591 second pass). - expect(missedCalls[0]?.[1]).toEqual({ lastSeenSeq: 57, epoch: 'epoch-before-restart' }) - // After the restart the watermark is reset to 0 and tagged with the live epoch — - // not the stale 57, which would make `57 >= 2` true and kill catch-up silently. - expect(missedCalls.at(-1)?.[1]).toEqual({ lastSeenSeq: 0, epoch: 'epoch-after-restart' }) - }) - - it('refuses to seed a stored watermark that lost the race to a newer live epoch', async () => { - // The seed read is deliberately not awaited (so subscribe doesn't block on - // AsyncStorage), which means it can land AFTER 'ready' already adopted the live - // epoch. If it seeds unconditionally it reinstates the exact stale cut #8591 is - // about — the reset having already happened doesn't help, because the seed runs - // last and wins. Only a stored epoch matching the live one may seed. - vi.mocked(loadPushNotificationsEnabled).mockResolvedValue(true) - vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ - status: 'granted', - canAskAgain: true - } as never) - vi.mocked(Notifications.scheduleNotificationAsync).mockResolvedValue('scheduled-1') - - // Hold the storage read open so 'ready' is guaranteed to be processed first. - let releaseStorage: () => void = () => {} - const storageGate = new Promise((resolve) => { - releaseStorage = resolve - }) - vi.mocked(AsyncStorage.getItem).mockImplementation(async (key: string) => { - await storageGate - return key.startsWith('orca:mobileNotificationsWatermark:') - ? JSON.stringify({ seq: 57, epoch: 'epoch-before-restart' }) - : null - }) - - const sub = makeClient() - subscribeToDesktopNotifications(sub.client, 'host-1') - // Live epoch adopted while the stored one is still in flight. - sub.onData?.({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-after-restart' }) - await flushAsync() - - releaseStorage() - await flushAsync() - - sub.onData?.({ type: 'ready', subscriptionId: 'sub-2', epoch: 'epoch-after-restart' }) - await flushAsync() - await flushAsync() - - const missedCall = vi - .mocked(sub.client.sendRequest) - .mock.calls.find((c: unknown[]) => c[0] === 'notifications.getMissedSince') - expect(missedCall?.[1]).toEqual({ lastSeenSeq: 0, epoch: 'epoch-after-restart' }) - }) - - it('keeps the persisted watermark when the desktop epoch is unchanged', async () => { - // The reset must be narrow: a plain socket reap with the same desktop process - // still has to send the real watermark, or every reconnect re-pushes the buffer. - vi.mocked(loadPushNotificationsEnabled).mockResolvedValue(true) - vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ - status: 'granted', - canAskAgain: true - } as never) - vi.mocked(Notifications.scheduleNotificationAsync).mockResolvedValue('scheduled-1') - vi.mocked(AsyncStorage.getItem).mockImplementation(async (key: string) => - key.startsWith('orca:mobileNotificationsWatermark:') - ? JSON.stringify({ seq: 57, epoch: 'epoch-stable' }) - : null - ) - - const sub = makeClient() - subscribeToDesktopNotifications(sub.client, 'host-1') - sub.onData?.({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-stable' }) - await flushAsync() - await flushAsync() - sub.onData?.({ type: 'ready', subscriptionId: 'sub-2', epoch: 'epoch-stable' }) - await flushAsync() - await flushAsync() - - const missedCall = vi - .mocked(sub.client.sendRequest) - .mock.calls.find((c: unknown[]) => c[0] === 'notifications.getMissedSince') - expect(missedCall?.[1]).toEqual({ lastSeenSeq: 57, epoch: 'epoch-stable' }) - }) - - it('drops an already-seen id if a replay re-includes it (defense-in-depth)', async () => { - vi.mocked(loadPushNotificationsEnabled).mockResolvedValue(true) - vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ - status: 'granted', - canAskAgain: true - } as never) - vi.mocked(Notifications.scheduleNotificationAsync).mockResolvedValue('s') - - const sub = makeClient() - // Simulate the bounded-buffer edge: the desktop returns seq 11 again - // (already delivered live) alongside a new seq 12. - sub.client.sendRequest = vi.fn(async (method: string) => { - if (method === 'notifications.getMissedSince') { - return { - ok: true, - result: { - notifications: [ - { - type: 'notification', - title: 'dup', - body: 'b', - notificationId: 'agent:dup', - notificationSeq: 11 - }, - { - type: 'notification', - title: 'new', - body: 'b', - notificationId: 'agent:new', - notificationSeq: 12 - } - ] - } - } as never - } - return { ok: true, result: undefined } as never - }) - - subscribeToDesktopNotifications(sub.client, 'host-1') - sub.onData?.({ type: 'ready', subscriptionId: 'sub-1' }) - await flushAsync() - // Live stream delivered agent:dup (seq 11) before reap. - sub.onData?.({ - type: 'notification', - title: 'dup', - body: 'b', - notificationId: 'agent:dup', - notificationSeq: 11 - }) - await flushAsync() - // Reconnect replay re-includes seq 11 (must be dropped) + new seq 12. - sub.onData?.({ type: 'ready', subscriptionId: 'sub-1' }) - await flushAsync() - await flushAsync() - - const scheduledIds = vi - .mocked(Notifications.scheduleNotificationAsync) - .mock.calls.map( - (call) => - (call[0] as { content: { data: { notificationId: string } } }).content.data.notificationId - ) - expect(scheduledIds).toEqual(['agent:dup', 'agent:new']) - expect(scheduledIds.filter((id) => id === 'agent:dup')).toHaveLength(1) - }) - - it('persists the highest delivered seq so a later reconnect resumes from it', async () => { - vi.mocked(loadPushNotificationsEnabled).mockResolvedValue(true) - vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ - status: 'granted', - canAskAgain: true - } as never) - vi.mocked(Notifications.scheduleNotificationAsync).mockResolvedValue('s') - - const sub = makeClient() - subscribeToDesktopNotifications(sub.client, 'host-1') - sub.onData?.({ type: 'ready', subscriptionId: 'sub-1' }) - await flushAsync() - // Live stream delivers seq 5. - sub.onData?.({ - type: 'notification', - title: 't', - body: 'b', - notificationId: 'agent:live', - notificationSeq: 5 - }) - await flushAsync() - - expect(AsyncStorageMock.setItem).toHaveBeenCalledWith( - 'orca:mobileNotificationsWatermark:host-1', - JSON.stringify({ seq: 5, epoch: null }) - ) - }) - - // Why: a replay-ONLY delivery (nothing arrived live first) must still advance - // and persist the watermark. This is the exact case the seq/notificationSeq - // field mismatch broke — the desktop replay path returns `notificationSeq` - // (matching the live fan-out), so the client watermark moves and the next - // reconnect resumes from it instead of re-fetching from 0. - it('advances + persists the watermark from a replay-only delivery (#8129 field-mismatch regression)', async () => { - vi.mocked(loadPushNotificationsEnabled).mockResolvedValue(true) - vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ - status: 'granted', - canAskAgain: true - } as never) - vi.mocked(Notifications.scheduleNotificationAsync).mockResolvedValue('s') - - const sub = makeClient() - // Desktop replay returns events keyed by notificationSeq (the fixed shape). - sub.client.sendRequest = vi.fn(async (method: string) => { - if (method === 'notifications.getMissedSince') { - return { - ok: true, - result: { - notifications: [ - { - type: 'notification', - title: 'missed', - body: 'b', - notificationId: 'agent:missed', - notificationSeq: 8 - } - ] - } - } as never - } - return { ok: true, result: undefined } as never - }) - - subscribeToDesktopNotifications(sub.client, 'host-1') - sub.onData?.({ type: 'ready', subscriptionId: 'sub-1' }) - await flushAsync() - // First reconnect → replay delivers seq 8 (no prior live delivery). - sub.onData?.({ type: 'ready', subscriptionId: 'sub-1' }) - await flushAsync() - await flushAsync() - - // Watermark advanced to the replayed seq and was persisted. - expect(AsyncStorageMock.setItem).toHaveBeenCalledWith( - 'orca:mobileNotificationsWatermark:host-1', - JSON.stringify({ seq: 8, epoch: null }) - ) - - // Second reconnect resumes from the advanced watermark, not 0. - sub.onData?.({ type: 'ready', subscriptionId: 'sub-1' }) - await flushAsync() - const missedCalls = vi - .mocked(sub.client.sendRequest) - .mock.calls.filter((c: unknown[]) => c[0] === 'notifications.getMissedSince') - expect(missedCalls.at(-1)?.[1]).toEqual({ lastSeenSeq: 8 }) - }) - - it('replays a terminal bell at a seq the previous desktop counter already used', async () => { - // Round-1 review finding: seen-keys are seq-derived, and terminal bells carry no - // notificationId (they key on `seq:N` alone). Epoch A delivers a bell at seq 1; - // after a restart, epoch B's first bell is ALSO seq 1. The catch-up path is the - // one that consults the seen-set, so without clearing it on epoch change the - // replayed post-restart bell is mistaken for a duplicate and silently skipped — - // #8591's silent loss again, now one notification at a time. - vi.mocked(loadPushNotificationsEnabled).mockResolvedValue(true) - vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ - status: 'granted', - canAskAgain: true - } as never) - vi.mocked(Notifications.scheduleNotificationAsync).mockResolvedValue('s') - - const sub = makeClient() - // Catch-up returns epoch B's first bell — same seq 1 the old counter used. - sub.client.sendRequest = vi.fn(async (method: string) => { - if (method === 'notifications.getMissedSince') { - return { - ok: true, - result: { - epoch: 'epoch-B', - notifications: [{ type: 'notification', title: 'bell', body: 'B', notificationSeq: 1 }] - } - } as never - } - return { ok: true, result: undefined } as never - }) - - subscribeToDesktopNotifications(sub.client, 'host-1') - sub.onData?.({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-A' }) - await flushAsync() - // A live bell under epoch A — no notificationId, so its seen-key is `seq:1`. - sub.onData?.({ type: 'notification', title: 'bell', body: 'A', notificationSeq: 1 }) - await flushAsync() - expect(vi.mocked(Notifications.scheduleNotificationAsync).mock.calls.length).toBe(1) - - // Desktop restarts; reconnect triggers catch-up against the fresh counter. - sub.onData?.({ type: 'ready', subscriptionId: 'sub-2', epoch: 'epoch-B' }) - await flushAsync() - await flushAsync() - - // The post-restart bell must reach the user, not be swallowed as a stale `seq:1`. - expect(vi.mocked(Notifications.scheduleNotificationAsync).mock.calls.length).toBe(2) - }) - - it('does not trust a legacy epoch-less watermark against a live counter', async () => { - // Round-1 review finding: pre-upgrade installs stored a bare seq with no epoch. - // Seeding it and then treating the first observed epoch as "nothing changed" - // leaves 57 cutting a counter it was never measured against — #8591 reached - // through the upgrade path. An unprovenanced seq may not survive epoch adoption. - vi.mocked(loadPushNotificationsEnabled).mockResolvedValue(true) - vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ - status: 'granted', - canAskAgain: true - } as never) - vi.mocked(Notifications.scheduleNotificationAsync).mockResolvedValue('s') - // Only the LEGACY key exists — exactly what an upgrading install has on disk. - vi.mocked(AsyncStorage.getItem).mockImplementation(async (key: string) => - key.startsWith('orca:mobileNotificationsLastSeq:') ? '57' : null - ) - - const sub = makeClient() - subscribeToDesktopNotifications(sub.client, 'host-1') - // Seed lands FIRST (no epoch known yet), so 57 is provisionally adopted... - await flushAsync() - await flushAsync() - // ...then the live epoch arrives for the first time. - sub.onData?.({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-live' }) - await flushAsync() - sub.onData?.({ type: 'ready', subscriptionId: 'sub-2', epoch: 'epoch-live' }) - await flushAsync() - await flushAsync() - - const missedCall = vi - .mocked(sub.client.sendRequest) - .mock.calls.find((c: unknown[]) => c[0] === 'notifications.getMissedSince') - // Must not be 57: that seq was never shown to belong to this counter. - expect(missedCall?.[1]).toEqual({ lastSeenSeq: 0, epoch: 'epoch-live' }) - }) - - it('catches up on the FIRST connection after an upgrade, without a second ready', async () => { - // Round-2 review finding: catch-up hung off `connectedBefore`, which is false on - // the first 'ready' of a process. So a cold app open — post-upgrade, or after the - // OS evicted the app — adopted the epoch but never replayed. Everything between - // the stored watermark and the next live seq was then lost permanently, because - // the first live event advances the watermark past the gap. - // - // The earlier migration test masked this by emitting a SECOND 'ready'. This one - // emits exactly one, which is what a real cold open does. - vi.mocked(loadPushNotificationsEnabled).mockResolvedValue(true) - vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ - status: 'granted', - canAskAgain: true - } as never) - vi.mocked(Notifications.scheduleNotificationAsync).mockResolvedValue('s') - vi.mocked(AsyncStorage.getItem).mockImplementation(async (key: string) => - key.startsWith('orca:mobileNotificationsWatermark:') - ? JSON.stringify({ seq: 57, epoch: 'epoch-live' }) - : null - ) - - const sub = makeClient() - vi.mocked(sub.client.sendRequest).mockImplementation(async (method: string) => - method === 'notifications.getMissedSince' - ? { - ok: true, - result: { - epoch: 'epoch-live', - notifications: [ - { - type: 'notification', - notificationId: 'missed-58', - notificationSeq: 58, - notificationEpoch: 'epoch-live', - title: 'while the app was closed', - body: 'b' - } - ] - } - } - : { ok: true, result: {} } - ) - subscribeToDesktopNotifications(sub.client, 'host-1') - sub.onData?.({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-live' }) - await flushAsync() - await flushAsync() - await flushAsync() - - const missedCall = vi - .mocked(sub.client.sendRequest) - .mock.calls.find((c: unknown[]) => c[0] === 'notifications.getMissedSince') - // The single 'ready' must replay from the stored watermark, not skip it. - expect(missedCall?.[1]).toEqual({ lastSeenSeq: 57, epoch: 'epoch-live' }) - // And the missed notification must actually reach the user. - expect(vi.mocked(Notifications.scheduleNotificationAsync).mock.calls.length).toBe(1) - }) - - it('does not replay the desktop buffer at a first-ever pairing', async () => { - // The other side of the finding above: with nothing stored, this device has never - // delivered for this host. Catching up would push the whole retained buffer at a - // user who was never subscribed for any of it. - vi.mocked(loadPushNotificationsEnabled).mockResolvedValue(true) - vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ - status: 'granted', - canAskAgain: true - } as never) - vi.mocked(AsyncStorage.getItem).mockResolvedValue(null) - - const sub = makeClient() - subscribeToDesktopNotifications(sub.client, 'host-1') - sub.onData?.({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-live' }) - await flushAsync() - await flushAsync() - await flushAsync() - - expect( - vi - .mocked(sub.client.sendRequest) - .mock.calls.filter((c: unknown[]) => c[0] === 'notifications.getMissedSince') - ).toHaveLength(0) - }) - - it('persists seq and epoch as one value so a crash cannot split the pair', async () => { - // Round-1 review finding: written as two keys, a process death between the writes - // leaves epoch-B beside seq-57-from-A. That pair looks internally valid on the - // next launch and is therefore trusted — silently cutting B's first 57 events. - // One key means the pair is always written whole or not at all. - vi.mocked(loadPushNotificationsEnabled).mockResolvedValue(true) - vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ - status: 'granted', - canAskAgain: true - } as never) - vi.mocked(Notifications.scheduleNotificationAsync).mockResolvedValue('s') - - const sub = makeClient() - subscribeToDesktopNotifications(sub.client, 'host-1') - sub.onData?.({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-A' }) - await flushAsync() - sub.onData?.({ - type: 'notification', - title: 't', - body: 'b', - notificationId: 'agent:x', - notificationSeq: 9 - }) - await flushAsync() - - // Every watermark write is a single key carrying both halves together. - const watermarkWrites = AsyncStorageMock.setItem.mock.calls.filter((c: unknown[]) => - String(c[0]).startsWith('orca:mobileNotifications') - ) - expect(watermarkWrites.length).toBeGreaterThan(0) - for (const [key, value] of watermarkWrites) { - expect(key).toBe('orca:mobileNotificationsWatermark:host-1') - expect(JSON.parse(String(value))).toHaveProperty('epoch') - expect(JSON.parse(String(value))).toHaveProperty('seq') - } - expect(JSON.parse(String(watermarkWrites.at(-1)?.[1]))).toEqual({ - seq: 9, - epoch: 'epoch-A' - }) + it('keeps socket dismissal processing active', async () => { + const rpc = client() + subscribeToDesktopNotifications(rpc as never, 'host-1') + rpc.emit({ type: 'ready', subscriptionId: 'sub-1' }) + const dismissal = { type: 'dismiss', notificationId: 'agent-1', notificationSeq: 4 } + rpc.emit(dismissal) + await Promise.resolve() + expect(dismissHostPushNotification).toHaveBeenCalledWith(dismissal, 'host-1') }) }) diff --git a/mobile/src/notifications/mobile-notifications.ts b/mobile/src/notifications/mobile-notifications.ts index 0043762e3ec..974c9516263 100644 --- a/mobile/src/notifications/mobile-notifications.ts +++ b/mobile/src/notifications/mobile-notifications.ts @@ -1,211 +1,22 @@ +import { requestNotificationCatchup } from './push-dismissal-reconciliation' +import { dismissHostPushNotification } from './push-socket-dismissal' +import type { DismissNotificationEvent } from './desktop-notification-events' import type { RpcClient } from '../transport/rpc-client' -// Re-exported so the existing importers (and their vi.mock paths) keep working. + export { ensureNotificationPermissions, getNotificationPermissionState, type NotificationPermissionState } from './notification-permissions' -export { setScheduledNotificationsMaxForTests } from './local-notification-scheduling' -import { - configureNotificationChannel, - dismissLocalNotification, - showLocalNotification, - type DismissNotificationEvent, - type NotificationEvent -} from './local-notification-scheduling' -import { - adoptNotificationEpoch, - catchUpWatermarkSeq, - enqueueHostDelivery, - getHostNotificationSession, - quarantineCatchUpWatermark, - releaseQueuedShowNotificationId, - resolveCatchUpQuarantine, - saveWatermark, - seedWatermarkFromStorage, - seenKeyForEvent, - shouldQueueShowForNotificationId -} from './notification-reconnect-catchup' type SubscribeResult = { type: 'ready' subscriptionId: string - // Desktop counter lifetime (#8591); absent from runtimes that predate it. - epoch?: string } -// Per-connection subscription; a reconnect `ready` triggers watermarked catch-up (#8129) so already-pushed events aren't re-sent. export function subscribeToDesktopNotifications(client: RpcClient, hostId: string): () => void { - configureNotificationChannel() - let subscriptionId: string | null = null let disposed = false - // Why (#8591): survives the unsubscribe/resubscribe the app performs on every - // socket drop, so a reconnect still knows its watermark and that it reconnected. - const session = getHostNotificationSession(hostId) - - /** - * Queue one delivery on the host chain, dropping a show whose notificationId - * already has one queued. - * - * Why the claim is taken HERE and not inside deliverLive (#8591): the point of - * the dedup is to notice a second event arriving while the first is still - * outstanding. Inside the queued task the first has already finished, so the - * overlap is no longer observable — it has to be checked before enqueueing. - */ - function queueDelivery( - type: 'notification' | 'dismiss', - event: NotificationEvent | DismissNotificationEvent - ): Promise { - if ( - type === 'notification' && - !shouldQueueShowForNotificationId(session, event.notificationId) - ) { - return Promise.resolve() - } - return enqueueHostDelivery(session, async () => { - try { - await deliverLive(type, event) - } finally { - if (type === 'notification') { - releaseQueuedShowNotificationId(session, event.notificationId) - } - } - // Why swallowed: the caller is an un-awaited handler, so a rejected show would - // surface as an unhandled rejection (a RN redbox) instead of being retried by - // the next catch-up — which is now possible, since `seen` is marked after the show. - }).catch(() => {}) - } - - async function deliverLive( - type: 'notification' | 'dismiss', - event: NotificationEvent | DismissNotificationEvent - ): Promise { - adoptNotificationEpoch(session, hostId, event.notificationEpoch) - const epochAtDelivery = session.lastDeliveredEpoch - if (type === 'notification') { - await showLocalNotification(event as NotificationEvent, hostId) - } else { - await dismissLocalNotification(event as DismissNotificationEvent, hostId) - } - // Why after the await, exactly like the watermark below: `seen` asserts this event - // reached the user (#8129). Marked before, a rejected show leaves the key behind and - // every later replay is dropped as a duplicate — loss the quarantine cannot recover, - // since the first event to drain a batch lifts it past the one never shown. - const key = seenKeyForEvent(event) - // A mid-flight epoch adoption already cleared the counter lifetime this key indexes. - if (key && session.lastDeliveredEpoch === epochAtDelivery) { - session.seen.add(key) - } - // Why after the await (#8591): the watermark is a promise that everything up - // to this seq has been shown. Advancing it before the local notification lands - // means a process death in between silently drops it — the next launch asks the - // desktop for seq greater than one the user never saw. - if (event.notificationSeq != null && event.notificationSeq > session.lastDeliveredSeq) { - session.lastDeliveredSeq = event.notificationSeq - // Why clamped: while a failed catch-up's range is still unrecovered, persisting - // the live seq would let the next catch-up ask from above the gap and the desktop - // would cut it. resolveCatchUpQuarantine writes the held-back value on success. - void saveWatermark(hostId, { - seq: catchUpWatermarkSeq(session), - epoch: session.lastDeliveredEpoch - }) - } - } - - // Claimed inline rather than via queueDelivery: the batch is already one queue - // entry, and re-enqueueing per item is what let a live event cut in. - async function deliverMissedEvent( - event: NotificationEvent | DismissNotificationEvent - ): Promise { - // No pre-marking here either: deliverLive marks the key once the show lands. - const key = seenKeyForEvent(event) - if (key && session.seen.has(key)) { - return - } - if (event.type === 'notification') { - if (!shouldQueueShowForNotificationId(session, event.notificationId)) { - return - } - try { - await deliverLive('notification', event) - } finally { - releaseQueuedShowNotificationId(session, event.notificationId) - } - return - } - if (event.type === 'dismiss') { - await deliverLive('dismiss', event) - } - } - - // Why: desktop cuts by seq > lastSeenSeq, so re-fetching from the watermark is idempotent (session.seen guards residual overlap). - async function fetchMissed(): Promise { - if (disposed) { - return - } - // Captured before the request: everything at or below it is known delivered, so - // it is the floor the watermark falls back to if this catch-up never completes. - const askFrom = catchUpWatermarkSeq(session) - const missed = await client - .sendRequest('notifications.getMissedSince', { - lastSeenSeq: askFrom, - // Why: sending the epoch lets the desktop reject a watermark from a counter - // it no longer has and return the whole retained buffer instead of nothing. - ...(session.lastDeliveredEpoch != null ? { epoch: session.lastDeliveredEpoch } : {}) - }) - .then((response) => { - if (!response.ok) { - return null - } - const result = response.result as { notifications?: unknown[]; epoch?: string } | undefined - adoptNotificationEpoch(session, hostId, result?.epoch) - return Array.isArray(result?.notifications) ? result.notifications : [] - }) - .catch(() => null) - if (missed == null) { - // Why quarantine rather than retry: the range this catch-up abandoned stays - // unrecovered until SOME later one succeeds, and a live seq persisting past it - // meanwhile would make the desktop cut it forever. - quarantineCatchUpWatermark(session, hostId, askFrom) - return - } - // Why the whole batch is ONE queue entry (#8591): awaiting per event returns to - // the event loop between replays, so a live seq 11 slots into the chain between - // seq 6 and 7 and persists a watermark past a notification still unshown. Why the - // request stays OUTSIDE the queue: sendRequest waits up to 30s, and holding the - // chain for that would stall live delivery on a slow link. - await enqueueHostDelivery(session, async () => { - // Advances only past events this batch settled, so a teardown or a failing show - // quarantines the true contiguous point instead of the range it never reached. - let contiguousSeq = askFrom - let drained = false - try { - for (const raw of missed) { - // Re-checked per event: the batch can start before a teardown and still be - // draining after it, and a torn-down host must stop pushing. - if (disposed) { - return - } - const event = raw as NotificationEvent | DismissNotificationEvent - await deliverMissedEvent(event) - contiguousSeq = event.notificationSeq ?? contiguousSeq - } - drained = true - } finally { - if (drained) { - resolveCatchUpQuarantine(session, hostId) - } else { - quarantineCatchUpWatermark(session, hostId, contiguousSeq) - } - } - // Why swallowed here: the `finally` above already recorded the contiguous point, - // and the only caller is an un-awaited 'ready' continuation — letting a failed - // show escape turns every one into an unhandled rejection (a RN redbox). - }).catch(() => {}) - } - - seedWatermarkFromStorage(session, hostId) function unsubscribeServer(id: string) { if (client.getState() === 'connected') { @@ -213,79 +24,28 @@ export function subscribeToDesktopNotifications(client: RpcClient, hostId: strin } } - const unsubscribeStream = client.subscribe('notifications.subscribe', {}, (data: unknown) => { - const event = data as - | NotificationEvent - | DismissNotificationEvent - | SubscribeResult - | { type: 'end' } + const params = { includeDesktopSuppressed: true } + const unsubscribeStream = client.subscribe('notifications.subscribe', params, (data: unknown) => { + const event = data as DismissNotificationEvent | SubscribeResult | { type: string } if (event.type === 'ready') { subscriptionId = (event as SubscribeResult).subscriptionId - const isReconnect = session.connectedBefore - session.connectedBefore = true if (disposed) { unsubscribeServer(subscriptionId) unsubscribeStream() return } - const readyEpoch = (event as SubscribeResult).epoch - // Why (#8591) the await: on a cold app open the persisted read is still in - // flight, so deciding here would see watermarkLoaded false and skip catch-up — - // which is precisely the post-upgrade / post-process-death case that loses - // every notification between the stored watermark and the next live seq. - void (async () => { - await session.watermarkSeeded - if (disposed) { - return - } - // Why before fetchMissed: adopting the epoch here is what voids a watermark - // left over from a previous desktop lifetime, so the catch-up request carries - // a watermark that means something against the counter now answering it. - adoptNotificationEpoch(session, hostId, readyEpoch) - // A reconnect always catches up. A cold open catches up only when this device - // has delivered for this host before — a first-ever pairing must not be handed - // the desktop's whole retained buffer. - if (isReconnect || session.hadStoredWatermark) { - await fetchMissed() - } - })() + // A max watermark asks only which delivered pushes are stale; socket history + // never becomes a second OS-notification delivery route. + void requestNotificationCatchup(client, hostId, () => disposed).catch(() => {}) return } - if (event.type === 'end') { - if (disposed) { - unsubscribeStream() - } - return + if (!disposed && event.type === 'dismiss') { + void dismissHostPushNotification(event as DismissNotificationEvent, hostId).catch(() => {}) } - if (disposed) { - return - } - if (event.type !== 'notification' && event.type !== 'dismiss') { - return - } - // Why the await (#8591): deliverLive advances the watermark. A live event landing - // while the persisted read is still in flight would push it past the buffered seqs - // the catch-up is about to ask for, and getMissedSince would cut them. Ordering is - // preserved — every handler waits on the same promise, and the 'ready' continuation - // registered on it first, so catch-up still builds its request before any live seq. - const liveEvent = event - void (async () => { - await session.watermarkSeeded - if (disposed) { - return - } - // Why the queue (#8591): a live event must not overtake an in-flight - // catch-up replay, or it persists a watermark past seqs still unshown. - await queueDelivery( - liveEvent.type === 'notification' ? 'notification' : 'dismiss', - liveEvent as NotificationEvent | DismissNotificationEvent - ) - })() }) return () => { disposed = true - // Why: drop the local stream first — readiness can race unmount; don't hold the callback while a subscription id is pending. unsubscribeStream() if (subscriptionId) { unsubscribeServer(subscriptionId) diff --git a/mobile/src/notifications/mobile-push-lease-renewal.test.ts b/mobile/src/notifications/mobile-push-lease-renewal.test.ts new file mode 100644 index 00000000000..1f440e93abc --- /dev/null +++ b/mobile/src/notifications/mobile-push-lease-renewal.test.ts @@ -0,0 +1,39 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { AppState } from 'react-native' +import { startMobilePushLeaseRenewal } from './mobile-push-lease-renewal' + +let onChange: (state: string) => void +const remove = vi.fn() +vi.mock('react-native', () => ({ + AppState: { + currentState: 'active', + addEventListener: (_: string, callback: typeof onChange) => { + onChange = callback + return { remove } + } + } +})) +afterEach(() => { + vi.useRealTimers() + vi.clearAllMocks() +}) + +it('renews only while mobile is foregrounded, resumes on return, and tears down', async () => { + vi.useFakeTimers() + AppState.currentState = 'active' + const renew = vi.fn(async () => {}) + const stop = startMobilePushLeaseRenewal(renew) + await vi.advanceTimersByTimeAsync(15 * 60_000) + expect(renew).toHaveBeenCalledTimes(1) + AppState.currentState = 'background' + onChange('background') + await vi.advanceTimersByTimeAsync(8 * 24 * 60 * 60_000) + expect(renew).toHaveBeenCalledTimes(1) + AppState.currentState = 'active' + onChange('active') + expect(renew).toHaveBeenCalledTimes(2) + stop() + await vi.advanceTimersByTimeAsync(15 * 60_000) + expect(renew).toHaveBeenCalledTimes(2) + expect(remove).toHaveBeenCalledOnce() +}) diff --git a/mobile/src/notifications/mobile-push-lease-renewal.ts b/mobile/src/notifications/mobile-push-lease-renewal.ts new file mode 100644 index 00000000000..22d34b2a401 --- /dev/null +++ b/mobile/src/notifications/mobile-push-lease-renewal.ts @@ -0,0 +1,19 @@ +import { AppState } from 'react-native' + +export function startMobilePushLeaseRenewal(renew: () => Promise): () => void { + const refresh = () => { + if (AppState.currentState === 'active') { + void renew().catch(() => {}) + } + } + const subscription = AppState.addEventListener('change', (state) => { + if (state === 'active') { + refresh() + } + }) + const timer = setInterval(refresh, 15 * 60_000) + return () => { + subscription.remove() + clearInterval(timer) + } +} diff --git a/mobile/src/notifications/native-notification-data.test.ts b/mobile/src/notifications/native-notification-data.test.ts new file mode 100644 index 00000000000..2b157a5fda6 --- /dev/null +++ b/mobile/src/notifications/native-notification-data.test.ts @@ -0,0 +1,22 @@ +import { expect, it } from 'vitest' +import { readNativeNotificationData } from './native-notification-data' +import { readOrcaPushPayload } from './push-payload' + +it('reads actual Expo APNs payloads when content.data is null', () => { + const orca = { + hostFingerprint: 'qa-host', + notificationId: 'done', + notificationSeq: 4, + notificationEpoch: 'epoch' + } + const data = readNativeNotificationData({ + content: { data: null }, + trigger: { type: 'push', payload: { aps: {}, orca } } + }) + expect(readOrcaPushPayload(data)).toMatchObject(orca) +}) +it('keeps Android push and local notification data', () => { + const data = { hostId: 'host', notificationId: 'done' } + expect(readNativeNotificationData({ content: { data }, trigger: { type: 'push' } })).toBe(data) + expect(readNativeNotificationData({ content: { data }, trigger: null })).toBe(data) +}) diff --git a/mobile/src/notifications/native-notification-data.ts b/mobile/src/notifications/native-notification-data.ts new file mode 100644 index 00000000000..74d50397660 --- /dev/null +++ b/mobile/src/notifications/native-notification-data.ts @@ -0,0 +1,13 @@ +export function readNativeNotificationData(request: { + content: { data?: unknown } + trigger?: unknown +}): unknown { + const trigger = request.trigger + if (trigger && typeof trigger === 'object' && 'type' in trigger && trigger.type === 'push') { + // Expo iOS keeps raw APNs custom fields here when content.data is null. + if ('payload' in trigger && trigger.payload && typeof trigger.payload === 'object') { + return trigger.payload + } + } + return request.content.data +} diff --git a/mobile/src/notifications/native-push-dismissal.ios.ts b/mobile/src/notifications/native-push-dismissal.ios.ts new file mode 100644 index 00000000000..72e46ff9fec --- /dev/null +++ b/mobile/src/notifications/native-push-dismissal.ios.ts @@ -0,0 +1,4 @@ +import { requireNativeModule } from 'expo-modules-core' +import type { NativeDismissal } from './native-push-dismissal' + +export const nativePushDismissal = requireNativeModule('OrcaNotificationDismissal') diff --git a/mobile/src/notifications/native-push-dismissal.test.ts b/mobile/src/notifications/native-push-dismissal.test.ts new file mode 100644 index 00000000000..73c96495300 --- /dev/null +++ b/mobile/src/notifications/native-push-dismissal.test.ts @@ -0,0 +1,23 @@ +import { beforeEach, expect, it, vi } from 'vitest' + +const requireNativeModule = vi.hoisted(() => vi.fn()) +vi.mock('expo-modules-core', () => ({ requireNativeModule })) + +beforeEach(() => { + vi.resetModules() + requireNativeModule.mockReset() +}) + +it('requires the iOS ledger and surfaces a missing native module as a build defect', async () => { + requireNativeModule.mockImplementation(() => { + throw new Error('Cannot find native module OrcaNotificationDismissal') + }) + await expect(import('./native-push-dismissal.ios')).rejects.toThrow( + 'Cannot find native module OrcaNotificationDismissal' + ) +}) + +it('does not load an iOS module on the default Android/web path', async () => { + expect((await import('./native-push-dismissal')).nativePushDismissal).toBeNull() + expect(requireNativeModule).not.toHaveBeenCalled() +}) diff --git a/mobile/src/notifications/native-push-dismissal.ts b/mobile/src/notifications/native-push-dismissal.ts new file mode 100644 index 00000000000..a676c68e6dc --- /dev/null +++ b/mobile/src/notifications/native-push-dismissal.ts @@ -0,0 +1,8 @@ +import type { OrcaPushPayload } from './push-payload' + +export type NativeDismissal = { + remember(payload: OrcaPushPayload): Promise + wasDismissed(payload: OrcaPushPayload): Promise +} +// Android and web use JavaScript storage; iOS requires the native ledger. +export const nativePushDismissal: NativeDismissal | null = null diff --git a/mobile/src/notifications/notification-catchup-failure-quarantine.test.ts b/mobile/src/notifications/notification-catchup-failure-quarantine.test.ts deleted file mode 100644 index 997b9fce930..00000000000 --- a/mobile/src/notifications/notification-catchup-failure-quarantine.test.ts +++ /dev/null @@ -1,316 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import * as Notifications from 'expo-notifications' -import { subscribeToDesktopNotifications } from './mobile-notifications' -import { resetHostNotificationSessionsForTests } from './notification-reconnect-catchup' -import type { RpcClient } from '../transport/rpc-client' -import { loadPushNotificationsEnabled } from '../storage/preferences' - -vi.mock('expo-notifications', () => ({ - AndroidImportance: { HIGH: 'high' }, - setNotificationChannelAsync: vi.fn(), - getPermissionsAsync: vi.fn(), - requestPermissionsAsync: vi.fn(), - scheduleNotificationAsync: vi.fn(), - dismissNotificationAsync: vi.fn() -})) - -vi.mock('react-native', () => ({ - Platform: { OS: 'ios', Version: 18 } -})) - -const WATERMARK_KEY = 'orca:mobileNotificationsWatermark:host-1' -const storage = new Map() - -vi.mock('@react-native-async-storage/async-storage', () => ({ - default: { - getItem: vi.fn(async (key: string) => storage.get(key) ?? null), - setItem: vi.fn(async (key: string, value: string) => { - storage.set(key, value) - }) - } -})) - -vi.mock('../storage/preferences', () => ({ - loadPushNotificationsEnabled: vi.fn() -})) - -function flushAsync(): Promise { - return new Promise((resolve) => { - setTimeout(resolve, 10) - }) -} - -function persistedSeq(): number { - return (JSON.parse(storage.get(WATERMARK_KEY) ?? '{}') as { seq?: number }).seq ?? 0 -} - -type MissedOutcome = - | { kind: 'reject' } - | { kind: 'notOk' } - | { kind: 'ok'; notifications: unknown[] } - // Rejects only once `settle()` is called, so a live event can land mid-request. - | { kind: 'heldReject' } - -function makeHostClient() { - let onData: ((data: unknown) => void) | null = null - const askedFrom: number[] = [] - let outcome: MissedOutcome = { kind: 'ok', notifications: [] } - let releaseHeld: (() => void) | null = null - const client = { - subscribe: vi.fn((_m: string, _p: unknown, cb: (data: unknown) => void) => { - onData = cb - return vi.fn(() => { - onData = null - }) - }), - getState: vi.fn(() => 'connected'), - sendRequest: vi.fn(async (method: string, params: unknown = {}) => { - if (method !== 'notifications.getMissedSince') { - return { ok: true, result: undefined } as never - } - askedFrom.push((params as { lastSeenSeq: number }).lastSeenSeq) - if (outcome.kind === 'heldReject') { - await new Promise((resolve) => { - releaseHeld = resolve - }) - throw new Error('socket closed') - } - if (outcome.kind === 'reject') { - throw new Error('socket closed') - } - if (outcome.kind === 'notOk') { - return { ok: false, error: { message: 'timeout' } } as never - } - return { ok: true, result: { notifications: outcome.notifications } } as never - }) - } - return { - client: client as unknown as RpcClient, - get onData() { - return onData - }, - askedFrom, - setOutcome(next: MissedOutcome) { - outcome = next - }, - settleHeld() { - releaseHeld?.() - } - } -} - -function notification(seq: number) { - return { - type: 'notification', - title: `m${seq}`, - body: 'b', - notificationId: `agent:${seq}`, - notificationSeq: seq - } -} - -describe('#8591 catch-up failure quarantines the watermark', () => { - beforeEach(() => { - vi.clearAllMocks() - storage.clear() - resetHostNotificationSessionsForTests() - vi.mocked(loadPushNotificationsEnabled).mockResolvedValue(true) - vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ - status: 'granted', - canAskAgain: true - } as never) - vi.mocked(Notifications.scheduleNotificationAsync).mockResolvedValue('sched-1') - vi.mocked(Notifications.dismissNotificationAsync).mockResolvedValue(undefined) - }) - - it('keeps asking from the abandoned range until a catch-up actually succeeds', async () => { - // The phone was offline while seqs 6-7 dispatched. The catch-up that would have - // replayed them dies (socket close / timeout / ok:false), and live traffic keeps - // flowing. If a live seq is allowed to persist past 6-7, the desktop cuts by - // `seq > lastSeenSeq` on the next catch-up and they are gone for good — and the - // window stays open until some catch-up succeeds, not for one round trip. - storage.set(WATERMARK_KEY, JSON.stringify({ seq: 5, epoch: 'epoch-1' })) - const host = makeHostClient() - host.setOutcome({ kind: 'reject' }) - - subscribeToDesktopNotifications(host.client, 'host-1') - host.onData?.({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-1' }) - await flushAsync() - expect(host.askedFrom).toEqual([5]) - - host.onData?.({ ...notification(11), notificationEpoch: 'epoch-1' }) - await flushAsync() - expect(persistedSeq()).toBe(5) - - // Second catch-up also fails; the gap is still open. - host.setOutcome({ kind: 'notOk' }) - host.onData?.({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-1' }) - await flushAsync() - host.onData?.({ ...notification(12), notificationEpoch: 'epoch-1' }) - await flushAsync() - expect(host.askedFrom).toEqual([5, 5]) - expect(persistedSeq()).toBe(5) - - // Third succeeds and replays the abandoned range. - host.setOutcome({ kind: 'ok', notifications: [notification(6), notification(7)] }) - host.onData?.({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-1' }) - await flushAsync() - - expect(host.askedFrom).toEqual([5, 5, 5]) - const titles = vi - .mocked(Notifications.scheduleNotificationAsync) - .mock.calls.map((call) => (call[0] as { content: { title: string } }).content.title) - // Exact, not arrayContaining: a duplicate here is the double-push `seen` prevents. - // m11/m12 are the live events that kept flowing while the gap stayed open. - expect(titles).toEqual(['m11', 'm12', 'm6', 'm7']) - - // Only now may the watermark move past the recovered range. - expect(persistedSeq()).toBe(12) - host.onData?.({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-1' }) - await flushAsync() - expect(host.askedFrom).toEqual([5, 5, 5, 12]) - }) - - it('rolls back a watermark a live event stored while the catch-up was in flight', async () => { - // getMissedSince waits up to 30s, so live traffic routinely persists during it. - // Clamping only writes made AFTER the failure leaves that higher seq on disk, and - // the next launch reads it back and resumes past the range this catch-up abandoned. - storage.set(WATERMARK_KEY, JSON.stringify({ seq: 5, epoch: 'epoch-1' })) - const host = makeHostClient() - host.setOutcome({ kind: 'heldReject' }) - - subscribeToDesktopNotifications(host.client, 'host-1') - host.onData?.({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-1' }) - await flushAsync() - expect(host.askedFrom).toEqual([5]) - - host.onData?.({ ...notification(11), notificationEpoch: 'epoch-1' }) - await flushAsync() - expect(persistedSeq()).toBe(11) - - host.settleHeld() - await flushAsync() - expect(persistedSeq()).toBe(5) - }) - - it('quarantines at the last replayed seq when a teardown cuts the batch short', async () => { - // The batch can start before a teardown and still be draining after it, so the - // events past the interruption were never shown. A live seq arriving on the next - // connection must not persist over them. - storage.set(WATERMARK_KEY, JSON.stringify({ seq: 5, epoch: 'epoch-1' })) - const host = makeHostClient() - host.setOutcome({ - kind: 'ok', - notifications: [notification(6), notification(7), notification(8)] - }) - - let unsubscribe: (() => void) | null = null - vi.mocked(Notifications.scheduleNotificationAsync).mockImplementation(async (request) => { - if ((request as { content: { title: string } }).content.title === 'm6') { - unsubscribe?.() - } - return 'sched-1' - }) - - unsubscribe = subscribeToDesktopNotifications(host.client, 'host-1') - host.onData?.({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-1' }) - await flushAsync() - - const titles = vi - .mocked(Notifications.scheduleNotificationAsync) - .mock.calls.map((call) => (call[0] as { content: { title: string } }).content.title) - expect(titles).toEqual(['m6']) - - // A fresh subscription on the same module-scope session takes a live seq 20 before - // its own catch-up, then resumes from 6 rather than from 20. - vi.mocked(Notifications.scheduleNotificationAsync).mockResolvedValue('sched-1') - const host2 = makeHostClient() - host2.setOutcome({ kind: 'ok', notifications: [notification(7), notification(8)] }) - subscribeToDesktopNotifications(host2.client, 'host-1') - host2.onData?.({ ...notification(20), notificationEpoch: 'epoch-1' }) - await flushAsync() - expect(persistedSeq()).toBe(6) - - host2.onData?.({ type: 'ready', subscriptionId: 'sub-2', epoch: 'epoch-1' }) - await flushAsync() - - expect(host2.askedFrom).toEqual([6]) - expect( - vi - .mocked(Notifications.scheduleNotificationAsync) - .mock.calls.map((call) => (call[0] as { content: { title: string } }).content.title) - ).toEqual(['m6', 'm20', 'm7', 'm8']) - expect(persistedSeq()).toBe(20) - }) - - it('re-shows a replay whose show threw, instead of dropping it as already seen', async () => { - // The quarantine only holds the RANGE. If the failing event is also marked seen, - // the next catch-up re-fetches it and the dedup guard drops it — the banner is - // never shown, and the first later event to drain the batch lifts the quarantine - // past it. Silent loss with the watermark looking healthy. - storage.set(WATERMARK_KEY, JSON.stringify({ seq: 5, epoch: 'epoch-1' })) - const host = makeHostClient() - host.setOutcome({ kind: 'ok', notifications: [notification(6), notification(7)] }) - - let failNext = true - vi.mocked(Notifications.scheduleNotificationAsync).mockImplementation(async (request) => { - const title = (request as { content: { title: string } }).content.title - if (title === 'm6' && failNext) { - failNext = false - throw new Error('scheduling rejected') - } - return 'sched-1' - }) - - subscribeToDesktopNotifications(host.client, 'host-1') - host.onData?.({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-1' }) - await flushAsync() - expect(persistedSeq()).toBe(5) - - host.onData?.({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-1' }) - await flushAsync() - - const titles = vi - .mocked(Notifications.scheduleNotificationAsync) - .mock.calls.map((call) => (call[0] as { content: { title: string } }).content.title) - expect(titles).toEqual(['m6', 'm6', 'm7']) - expect(host.askedFrom).toEqual([5, 5]) - expect(persistedSeq()).toBe(7) - }) - - it('re-shows a live event whose show threw, instead of dropping it as already seen', async () => { - // The same hole without any catch-up failing: the live path marks seen before the - // show, so a rejected show leaves the key behind while the watermark stays put. - // The next catch-up dutifully re-fetches the seq and the guard eats it. - storage.set(WATERMARK_KEY, JSON.stringify({ seq: 5, epoch: 'epoch-1' })) - const host = makeHostClient() - host.setOutcome({ kind: 'ok', notifications: [] }) - - let failNext = true - vi.mocked(Notifications.scheduleNotificationAsync).mockImplementation(async () => { - if (failNext) { - failNext = false - throw new Error('scheduling rejected') - } - return 'sched-1' - }) - - subscribeToDesktopNotifications(host.client, 'host-1') - host.onData?.({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-1' }) - await flushAsync() - - host.onData?.({ ...notification(6), notificationEpoch: 'epoch-1' }) - await flushAsync() - expect(persistedSeq()).toBe(5) - - host.setOutcome({ kind: 'ok', notifications: [notification(6)] }) - host.onData?.({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-1' }) - await flushAsync() - - const titles = vi - .mocked(Notifications.scheduleNotificationAsync) - .mock.calls.map((call) => (call[0] as { content: { title: string } }).content.title) - expect(titles).toEqual(['m6', 'm6']) - expect(persistedSeq()).toBe(6) - }) -}) diff --git a/mobile/src/notifications/notification-consent-ownership.test.ts b/mobile/src/notifications/notification-consent-ownership.test.ts new file mode 100644 index 00000000000..6d729d0db02 --- /dev/null +++ b/mobile/src/notifications/notification-consent-ownership.test.ts @@ -0,0 +1,310 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import AsyncStorage from '@react-native-async-storage/async-storage' +import NotificationsScreen from '../../app/notifications' +import MobileOnboardingScreen from '../../app/mobile-onboarding' +import { shouldPresentNotificationOptIn } from './notification-opt-in-gate' +import { + attachPushRegistration, + NOTIFICATIONS_REMOTE_PUSH_CAPABILITY, + resetPushRegistrationForTests, + setRemotePushEnabled, + startPushTokenSync +} from './push-registration' +import { getDevicePushToken } from './push-token' + +const mocks = vi.hoisted(() => ({ storage: new Map(), replace: vi.fn() })) +vi.mock('@react-native-async-storage/async-storage', () => ({ + default: { + getItem: vi.fn(async (key: string) => mocks.storage.get(key) ?? null), + setItem: vi.fn(async (key: string, value: string) => { + mocks.storage.set(key, value) + }) + } +})) +vi.mock('react-native', () => ({ + AppState: { currentState: 'active', addEventListener: () => ({ remove: vi.fn() }) }, + AccessibilityInfo: { + addEventListener: () => ({ remove: vi.fn() }), + isReduceMotionEnabled: async () => false + }, + Animated: { Value: class {}, View: 'View', multiply: () => 0 }, + BackHandler: { addEventListener: () => ({ remove: vi.fn() }) }, + StyleSheet: { create: (styles: unknown) => styles }, + Text: 'Text', + View: 'View', + Switch: 'Switch', + ScrollView: 'ScrollView', + Pressable: 'Pressable', + Alert: { alert: vi.fn() }, + Linking: { openSettings: vi.fn() }, + useWindowDimensions: () => ({ width: 390, height: 844 }) +})) +vi.mock('expo-router', () => ({ + useFocusEffect: vi.fn(), + useLocalSearchParams: () => ({ hostId: 'host', steps: 'notifications' }), + useRouter: () => ({ replace: mocks.replace }) +})) +vi.mock('react-native-safe-area-context', () => ({ + SafeAreaView: 'View', + useSafeAreaInsets: () => ({ top: 0, bottom: 0 }) +})) +vi.mock('lucide-react-native', () => ({ ChevronLeft: 'Icon' })) +vi.mock('../components/OrcaLogo', () => ({ OrcaLogo: 'Logo' })) +vi.mock('../onboarding/MobileOnboardingPage', () => ({ MobileOnboardingPage: 'Page' })) +vi.mock('../transport/use-all-host-clients', () => ({ useAllHostClients: () => [] })) +vi.mock('../transport/host-store', () => ({ loadHostCatalog: async () => [] })) +vi.mock('./NotificationDeliverySection', () => ({ NotificationDeliverySection: 'Delivery' })) +vi.mock('./use-remote-push-capable-hosts', () => ({ useRemotePushCapableHosts: () => [] })) +vi.mock('./notification-permissions', () => ({ + ensureNotificationPermissions: async () => true, + getNotificationPermissionState: async () => ({ + granted: true, + status: 'granted', + canAskAgain: true, + authorizationReflectsUserChoice: true + }) +})) +vi.mock('./mobile-notifications', () => ({ + ensureNotificationPermissions: async () => true, + getNotificationPermissionState: async () => ({ + granted: true, + status: 'granted', + canAskAgain: true, + authorizationReflectsUserChoice: true + }) +})) +vi.mock('./desktop-notification-channel', () => ({ + ensureDesktopNotificationChannel: async () => {} +})) +vi.mock('./push-token', () => ({ + getDevicePushToken: vi.fn(), + addPushTokenListener: () => () => {} +})) + +const token = { + platform: 'ios' as const, + token: 'a'.repeat(64), + apnsEnvironment: 'sandbox' as const +} +let renderer: ReactTestRenderer | undefined +let stopSync: () => void +const records = () => JSON.parse(mocks.storage.get('orca:remotePushHostRegistrations') ?? '{}') +const drain = () => vi.advanceTimersByTimeAsync(0) +function deferred() { + let resolve!: (value: T) => void + const promise = new Promise((done) => { + resolve = done + }) + return { promise, resolve } +} +function connection() { + return { + sendRequest: vi.fn(async (method: string): Promise => ({ + ok: true, + result: + method === 'status.get' + ? { capabilities: [NOTIFICATIONS_REMOTE_PUSH_CAPABILITY] } + : { registered: true, unregistered: true } + })) + } +} +async function connectedHost() { + const client = connection() + attachPushRegistration('host', client as never) + await drain() + client.sendRequest.mockClear() + return client +} +async function choose(entry: string) { + await act(async () => { + renderer = create( + createElement(entry === 'settings' ? NotificationsScreen : MobileOnboardingScreen) + ) + }) + await act(async () => { + if (entry === 'settings') { + renderer!.root.findByType('Switch').props.onValueChange(true) + } else { + renderer!.root.findByType('Page').props.onNotificationChoice('enable') + } + }) +} +function expectChoiceComplete(entry: string) { + expect(mocks.storage.get('orca:pushServiceNotificationsEnabled')).toBe('true') + if (entry === 'settings') { + expect(renderer!.root.findByType('Switch').props).toMatchObject({ + value: true, + disabled: false + }) + } + if (entry === 'onboarding') { + expect(mocks.replace).toHaveBeenCalledExactlyOnceWith('/h/host') + } +} +beforeEach(() => { + vi.useFakeTimers() + vi.clearAllMocks() + mocks.storage.clear() + resetPushRegistrationForTests() + vi.mocked(getDevicePushToken).mockResolvedValue(token) + stopSync = startPushTokenSync() +}) +afterEach(async () => { + await act(async () => renderer?.unmount()) + renderer = undefined + stopSync() + resetPushRegistrationForTests() + vi.useRealTimers() +}) + +it.each(['true', 'false'])( + 'requires consent before registering a legacy %s user', + async (legacy) => { + mocks.storage.set('orca:pushNotificationsEnabled', legacy) + const client = await connectedHost() + await expect(shouldPresentNotificationOptIn()).resolves.toBe(true) + await drain() + expect(getDevicePushToken).not.toHaveBeenCalled() + expect(client.sendRequest).not.toHaveBeenCalled() + await choose('onboarding') + await drain() + await expect(shouldPresentNotificationOptIn()).resolves.toBe(false) + expect(client.sendRequest.mock.calls.map(([method]) => method)).toEqual([ + 'notifications.registerPush' + ]) + } +) + +it('remembers Not now without registering and does not ask again', async () => { + mocks.storage.set('orca:pushNotificationsEnabled', 'true') + const client = await connectedHost() + await act(async () => { + renderer = create(createElement(MobileOnboardingScreen)) + }) + await act(async () => { + renderer!.root.findByType('Page').props.onNotificationChoice('skip') + }) + await drain() + await expect(shouldPresentNotificationOptIn()).resolves.toBe(false) + expect(mocks.storage.get('orca:pushServiceNotificationsEnabled')).toBe('false') + expect(getDevicePushToken).not.toHaveBeenCalled() + expect( + client.sendRequest.mock.calls.some(([method]) => method === 'notifications.registerPush') + ).toBe(false) +}) + +it.each(['settings', 'onboarding'])( + '%s schedules exactly one registration with token sync running', + async (entry) => { + const client = await connectedHost() + await choose(entry) + await drain() + expectChoiceComplete(entry) + expect(client.sendRequest.mock.calls.map(([method]) => method)).toEqual([ + 'notifications.registerPush' + ]) + expect(records().registeredHostIds).toEqual(['host']) + } +) + +it.each(['settings', 'onboarding'])( + '%s finishes local consent while native token acquisition is pending', + async (entry) => { + const client = await connectedHost() + const pending = deferred() + vi.mocked(getDevicePushToken).mockReturnValue(pending.promise) + await choose(entry) + await drain() + expectChoiceComplete(entry) + expect(getDevicePushToken).toHaveBeenCalledOnce() + expect(client.sendRequest).not.toHaveBeenCalled() + pending.resolve(token) + await drain() + expect(client.sendRequest.mock.calls.map(([method]) => method)).toEqual([ + 'notifications.registerPush' + ]) + } +) + +it.each(['settings', 'onboarding'])( + '%s finishes local consent while registration RPC is pending', + async (entry) => { + const client = await connectedHost() + const pending = deferred() + client.sendRequest.mockImplementationOnce(() => pending.promise) + await choose(entry) + await drain() + expectChoiceComplete(entry) + expect(client.sendRequest).toHaveBeenCalledOnce() + expect(records().registeredHostIds).toEqual([]) + pending.resolve({ ok: true, result: { registered: true } }) + await drain() + expect(records().registeredHostIds).toEqual(['host']) + expect(client.sendRequest).toHaveBeenCalledOnce() + } +) + +it('waits for durable local records and schedules one unregister without waiting for its RPC', async () => { + const client = await connectedHost() + await setRemotePushEnabled(true) + await drain() + client.sendRequest.mockClear() + const write = deferred() + vi.mocked(AsyncStorage.setItem) + .mockImplementationOnce(async (key, value) => { + mocks.storage.set(key, value) + }) + .mockImplementationOnce(async (key, value) => { + await write.promise + mocks.storage.set(key, value) + }) + const rpc = deferred() + client.sendRequest.mockImplementationOnce(() => rpc.promise) + const completed = vi.fn() + const disable = setRemotePushEnabled(false).then(completed) + await drain() + expect(completed).not.toHaveBeenCalled() + expect(client.sendRequest).not.toHaveBeenCalled() + write.resolve() + await disable + await drain() + expect(completed).toHaveBeenCalledOnce() + expect(records().pendingUnregisterHostIds).toEqual(['host']) + expect(client.sendRequest.mock.calls.map(([method]) => method)).toEqual([ + 'notifications.unregisterPush' + ]) + rpc.resolve({ ok: true }) + await drain() + expect(records()).toEqual({ registeredHostIds: [], pendingUnregisterHostIds: [] }) + expect(client.sendRequest).toHaveBeenCalledOnce() +}) + +it('exposes a failed consent write without scheduling or changing durable consent', async () => { + const client = await connectedHost() + vi.mocked(AsyncStorage.setItem).mockRejectedValueOnce(new Error('consent write failed')) + await expect(setRemotePushEnabled(true)).rejects.toThrow('consent write failed') + await drain() + expect(mocks.storage.has('orca:pushServiceNotificationsEnabled')).toBe(false) + expect(client.sendRequest).not.toHaveBeenCalled() +}) + +it('exposes a failed records write and still schedules exactly one cleanup', async () => { + const client = await connectedHost() + await setRemotePushEnabled(true) + await drain() + client.sendRequest.mockClear() + vi.mocked(AsyncStorage.setItem) + .mockImplementationOnce(async (key, value) => { + mocks.storage.set(key, value) + }) + .mockRejectedValueOnce(new Error('records write failed')) + await expect(setRemotePushEnabled(false)).rejects.toThrow('records write failed') + await drain() + expect(mocks.storage.get('orca:pushServiceNotificationsEnabled')).toBe('false') + expect(client.sendRequest.mock.calls.map(([method]) => method)).toEqual([ + 'notifications.unregisterPush' + ]) + expect(records()).toEqual({ registeredHostIds: [], pendingUnregisterHostIds: [] }) +}) diff --git a/mobile/src/notifications/notification-delivery-ordering.test.ts b/mobile/src/notifications/notification-delivery-ordering.test.ts deleted file mode 100644 index 68d64d7b3de..00000000000 --- a/mobile/src/notifications/notification-delivery-ordering.test.ts +++ /dev/null @@ -1,248 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import * as Notifications from 'expo-notifications' -import { subscribeToDesktopNotifications } from './mobile-notifications' -import { resetHostNotificationSessionsForTests } from './notification-reconnect-catchup' -import type { RpcClient } from '../transport/rpc-client' -import { loadPushNotificationsEnabled } from '../storage/preferences' - -vi.mock('expo-notifications', () => ({ - AndroidImportance: { HIGH: 'high' }, - setNotificationChannelAsync: vi.fn(), - getPermissionsAsync: vi.fn(), - requestPermissionsAsync: vi.fn(), - scheduleNotificationAsync: vi.fn(), - dismissNotificationAsync: vi.fn() -})) - -vi.mock('react-native', () => ({ - Platform: { OS: 'ios', Version: 18 } -})) - -const WATERMARK_KEY = 'orca:mobileNotificationsWatermark:host-1' -const storage = new Map() -let getItemImpl: (key: string) => Promise = async (key) => storage.get(key) ?? null - -vi.mock('@react-native-async-storage/async-storage', () => ({ - default: { - getItem: vi.fn((key: string) => getItemImpl(key)), - setItem: vi.fn(async (key: string, value: string) => { - storage.set(key, value) - }) - } -})) - -vi.mock('../storage/preferences', () => ({ - loadPushNotificationsEnabled: vi.fn() -})) - -function flushAsync(): Promise { - return new Promise((resolve) => { - setTimeout(resolve, 10) - }) -} - -function persistedSeq(): number { - return (JSON.parse(storage.get(WATERMARK_KEY) ?? '{}') as { seq?: number }).seq ?? 0 -} - -describe('#8591 per-host delivery ordering', () => { - beforeEach(() => { - vi.clearAllMocks() - storage.clear() - getItemImpl = async (key) => storage.get(key) ?? null - resetHostNotificationSessionsForTests() - vi.mocked(loadPushNotificationsEnabled).mockResolvedValue(true) - vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ - status: 'granted', - canAskAgain: true - } as never) - vi.mocked(Notifications.scheduleNotificationAsync).mockResolvedValue('sched-1') - vi.mocked(Notifications.dismissNotificationAsync).mockResolvedValue(undefined) - }) - - it('never persists a watermark past a notification the catch-up has not shown', async () => { - // The watermark is a promise that everything up to that seq reached the user. - // If a live seq 11 is processed while catch-up is still showing seq 6, it - // persists 11 — and a process death before 7 is shown loses 7 forever, because - // the next launch asks the desktop for seq > 11. That is the original #8591 - // loss re-entered through concurrency rather than through a restarted counter. - let releaseFirstShow!: () => void - const firstShowBlocked = new Promise((resolve) => { - releaseFirstShow = resolve - }) - let shown = 0 - vi.mocked(Notifications.scheduleNotificationAsync).mockImplementation(async () => { - shown += 1 - if (shown === 1) { - await firstShowBlocked - } - return 'sched-1' - }) - - let onData: ((data: unknown) => void) | null = null - const client = { - subscribe: vi.fn((_m: string, _p: unknown, cb: (data: unknown) => void) => { - onData = cb - return vi.fn() - }), - getState: vi.fn(() => 'connected'), - sendRequest: vi.fn(async (method: string) => { - if (method === 'notifications.getMissedSince') { - return { - ok: true, - result: { - notifications: [ - { - type: 'notification', - title: 'm6', - body: 'b', - notificationId: 'a:6', - notificationSeq: 6 - }, - { - type: 'notification', - title: 'm7', - body: 'b', - notificationId: 'a:7', - notificationSeq: 7 - } - ] - } - } as never - } - return { ok: true, result: undefined } as never - }) - } as unknown as RpcClient - - storage.set(WATERMARK_KEY, JSON.stringify({ seq: 5, epoch: 'epoch-1' })) - subscribeToDesktopNotifications(client, 'host-1') - onData?.({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-1' }) - await flushAsync() - - // Live seq 11 arrives while the replay is wedged on seq 6. - onData?.({ - type: 'notification', - title: 'live-11', - body: 'b', - notificationId: 'a:11', - notificationSeq: 11 - }) - await flushAsync() - - expect(persistedSeq()).toBeLessThan(6) - - releaseFirstShow() - await flushAsync() - - // Once the chain drains, everything is shown and the watermark catches up. - expect(persistedSeq()).toBe(11) - const titles = vi - .mocked(Notifications.scheduleNotificationAsync) - .mock.calls.map((call) => (call[0] as { content: { title: string } }).content.title) - expect(titles).toEqual(['m6', 'm7', 'live-11']) - }) - - it('shows one banner when a replay and a live event carry the same notification id', async () => { - // Serializing deliveries removed the overlap the old dedup relied on: the - // replay's show now COMPLETES before the live duplicate starts, so nothing is - // pending for it to observe and the user gets the same notification twice. - let releaseFirstShow!: () => void - const firstShowBlocked = new Promise((resolve) => { - releaseFirstShow = resolve - }) - let shown = 0 - vi.mocked(Notifications.scheduleNotificationAsync).mockImplementation(async () => { - shown += 1 - if (shown === 1) { - await firstShowBlocked - } - return `sched-${shown}` - }) - - let onData: ((data: unknown) => void) | null = null - const client = { - subscribe: vi.fn((_m: string, _p: unknown, cb: (data: unknown) => void) => { - onData = cb - return vi.fn() - }), - getState: vi.fn(() => 'connected'), - sendRequest: vi.fn(async (method: string) => { - if (method === 'notifications.getMissedSince') { - return { - ok: true, - result: { - notifications: [ - { - type: 'notification', - title: 'dup', - body: 'b', - notificationId: 'agent:dup', - notificationSeq: 6 - } - ] - } - } as never - } - return { ok: true, result: undefined } as never - }) - } as unknown as RpcClient - - storage.set(WATERMARK_KEY, JSON.stringify({ seq: 5, epoch: 'epoch-1' })) - subscribeToDesktopNotifications(client, 'host-1') - onData?.({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-1' }) - await flushAsync() - - // Same id arrives live while the replay's show is still blocked. A different - // seq, so the seen-set does not catch it — only the queued-show claim does. - onData?.({ - type: 'notification', - title: 'dup', - body: 'b', - notificationId: 'agent:dup', - notificationSeq: 7 - }) - await flushAsync() - - releaseFirstShow() - await flushAsync() - - expect(vi.mocked(Notifications.scheduleNotificationAsync)).toHaveBeenCalledTimes(1) - }) - - it('still delivers when the persisted watermark read never resolves', async () => { - // Every delivery awaits the seed, so a wedged AsyncStorage read would disable - // this host's notifications for the whole app lifetime — silently. - getItemImpl = () => new Promise(() => {}) - - let onData: ((data: unknown) => void) | null = null - const client = { - subscribe: vi.fn((_m: string, _p: unknown, cb: (data: unknown) => void) => { - onData = cb - return vi.fn() - }), - getState: vi.fn(() => 'connected'), - sendRequest: vi.fn(async () => ({ ok: true, result: undefined }) as never) - } as unknown as RpcClient - - vi.useFakeTimers() - try { - subscribeToDesktopNotifications(client, 'host-1') - onData?.({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-1' }) - onData?.({ - type: 'notification', - title: 'live-1', - body: 'b', - notificationId: 'a:1', - notificationSeq: 1 - }) - await vi.advanceTimersByTimeAsync(3100) - } finally { - vi.useRealTimers() - } - - const titles = vi - .mocked(Notifications.scheduleNotificationAsync) - .mock.calls.map((call) => (call[0] as { content: { title: string } }).content.title) - expect(titles).toContain('live-1') - }) -}) diff --git a/mobile/src/notifications/notification-delivery-preferences.test.ts b/mobile/src/notifications/notification-delivery-preferences.test.ts new file mode 100644 index 00000000000..1e3e4b79113 --- /dev/null +++ b/mobile/src/notifications/notification-delivery-preferences.test.ts @@ -0,0 +1,86 @@ +import { beforeEach, expect, it, vi } from 'vitest' +import { AppState } from 'react-native' +import { + DEFAULT_NOTIFICATION_DELIVERY, + loadNotificationDeliveryPreferences, + notificationPreferencesFilter, + saveNotificationDeliveryPreferences +} from './notification-delivery-preferences' +import { + setNotificationViewingWorkspace, + shouldSuppressNotificationWhileViewing +} from './notification-viewing-policy' + +const storage = new Map() +vi.mock('@react-native-async-storage/async-storage', () => ({ + default: { + getItem: vi.fn(async (key: string) => storage.get(key) ?? null), + setItem: vi.fn(async (key: string, value: string) => { + storage.set(key, value) + }) + } +})) +vi.mock('react-native', () => ({ AppState: { currentState: 'background' } })) +beforeEach(() => { + storage.clear() + setNotificationViewingWorkspace(null) + AppState.currentState = 'background' +}) + +it('persists only phone-specific delivery preferences', async () => { + expect(await loadNotificationDeliveryPreferences()).toEqual(DEFAULT_NOTIFICATION_DELIVERY) + const value = { + ...DEFAULT_NOTIFICATION_DELIVERY, + onlyWhenDesktopAway: false, + sound: false + } + await saveNotificationDeliveryPreferences(value) + expect(await loadNotificationDeliveryPreferences()).toEqual(value) + expect(notificationPreferencesFilter(value)).toEqual({ + onlyWhenDesktopAway: false, + sound: false + }) +}) + +it('ignores unrelated stored preferences', async () => { + storage.set( + 'orca:notificationDeliveryPreferences', + JSON.stringify({ + onlyWhenDesktopAway: false, + sound: false, + suppressWhileViewing: false, + unrelatedSetting: false + }) + ) + expect(await loadNotificationDeliveryPreferences()).toEqual({ + onlyWhenDesktopAway: false, + sound: false, + suppressWhileViewing: false + }) + expect(notificationPreferencesFilter(await loadNotificationDeliveryPreferences())).toEqual({ + onlyWhenDesktopAway: false, + sound: false + }) +}) + +it('suppresses only the workspace being viewed on this phone, and never while backgrounded', async () => { + const event = { source: 'terminal-bell', worktreeId: 'folder-id' } + setNotificationViewingWorkspace({ hostId: 'ssh-host', worktreeId: 'folder-id' }) + AppState.currentState = 'active' + expect(await shouldSuppressNotificationWhileViewing(event, 'ssh-host', true)).toBe(true) + expect(await shouldSuppressNotificationWhileViewing(event, 'another-host', true)).toBe(false) + expect( + await shouldSuppressNotificationWhileViewing( + { ...event, worktreeId: 'other' }, + 'ssh-host', + true + ) + ).toBe(false) + AppState.currentState = 'background' + expect(await shouldSuppressNotificationWhileViewing(event, 'ssh-host', true)).toBe(false) +}) + +it('recovers defaults from malformed stored preferences', async () => { + storage.set('orca:notificationDeliveryPreferences', '{broken') + expect(await loadNotificationDeliveryPreferences()).toEqual(DEFAULT_NOTIFICATION_DELIVERY) +}) diff --git a/mobile/src/notifications/notification-delivery-preferences.ts b/mobile/src/notifications/notification-delivery-preferences.ts new file mode 100644 index 00000000000..7388fba77db --- /dev/null +++ b/mobile/src/notifications/notification-delivery-preferences.ts @@ -0,0 +1,49 @@ +import AsyncStorage from '@react-native-async-storage/async-storage' +import type { MobilePushFilter } from '../../../src/shared/mobile-push-contract' + +const KEY = 'orca:notificationDeliveryPreferences' +export type NotificationDeliveryPreferences = { + onlyWhenDesktopAway: boolean + sound: boolean + suppressWhileViewing: boolean +} + +export const DEFAULT_NOTIFICATION_DELIVERY: NotificationDeliveryPreferences = { + onlyWhenDesktopAway: true, + sound: true, + suppressWhileViewing: true +} + +export async function loadNotificationDeliveryPreferences(): Promise { + try { + const raw = await AsyncStorage.getItem(KEY) + if (!raw) { + return { ...DEFAULT_NOTIFICATION_DELIVERY } + } + const stored = JSON.parse(raw) as Record + const result = { ...DEFAULT_NOTIFICATION_DELIVERY } + for (const key of Object.keys(result) as (keyof NotificationDeliveryPreferences)[]) { + if (typeof stored?.[key] === 'boolean') { + result[key] = stored[key] + } + } + return result + } catch { + return { ...DEFAULT_NOTIFICATION_DELIVERY } + } +} + +export async function saveNotificationDeliveryPreferences( + value: NotificationDeliveryPreferences +): Promise { + await AsyncStorage.setItem(KEY, JSON.stringify(value)) +} + +export function notificationPreferencesFilter( + value: NotificationDeliveryPreferences +): MobilePushFilter { + return { + onlyWhenDesktopAway: value.onlyWhenDesktopAway, + sound: value.sound + } +} diff --git a/mobile/src/notifications/notification-opt-in-gate.test.ts b/mobile/src/notifications/notification-opt-in-gate.test.ts index ded3d7eca39..8b99423dfb4 100644 --- a/mobile/src/notifications/notification-opt-in-gate.test.ts +++ b/mobile/src/notifications/notification-opt-in-gate.test.ts @@ -1,92 +1,24 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { - readPushNotificationsPreference, - savePushNotificationsEnabled -} from '../storage/preferences' -import { getNotificationPermissionState } from './mobile-notifications' +import { describe, expect, it, vi } from 'vitest' +import { readPushNotificationsPreference } from '../storage/preferences' import { shouldPresentNotificationOptIn } from './notification-opt-in-gate' vi.mock('../storage/preferences', () => ({ - readPushNotificationsPreference: vi.fn(), - savePushNotificationsEnabled: vi.fn() -})) - -vi.mock('./mobile-notifications', () => ({ - getNotificationPermissionState: vi.fn() + readPushNotificationsPreference: vi.fn() })) describe('notification opt-in gate', () => { - beforeEach(() => { - vi.mocked(readPushNotificationsPreference).mockReset() - vi.mocked(savePushNotificationsEnabled).mockReset() - vi.mocked(getNotificationPermissionState).mockReset() - }) - - it('presents only when the local preference and system decision are both unset', async () => { + it('asks for push-service consent when no choice is saved, regardless of OS permission', async () => { vi.mocked(readPushNotificationsPreference).mockResolvedValue({ value: null, loaded: true }) - vi.mocked(getNotificationPermissionState).mockResolvedValue({ - granted: false, - status: 'undetermined', - canAskAgain: true, - authorizationReflectsUserChoice: false - }) - await expect(shouldPresentNotificationOptIn()).resolves.toBe(true) - expect(savePushNotificationsEnabled).not.toHaveBeenCalled() }) - it.each([true, false])('preserves an existing %s mobile preference', async (value) => { + it.each([true, false])('does not ask again after choosing %s', async (value) => { vi.mocked(readPushNotificationsPreference).mockResolvedValue({ value, loaded: true }) - await expect(shouldPresentNotificationOptIn()).resolves.toBe(false) - expect(getNotificationPermissionState).not.toHaveBeenCalled() }) - it('adopts existing system authorization without prompting', async () => { - vi.mocked(readPushNotificationsPreference).mockResolvedValue({ value: null, loaded: true }) - vi.mocked(getNotificationPermissionState).mockResolvedValue({ - granted: true, - status: 'granted', - canAskAgain: true, - authorizationReflectsUserChoice: true - }) - - await expect(shouldPresentNotificationOptIn()).resolves.toBe(false) - expect(savePushNotificationsEnabled).toHaveBeenCalledWith(true) - }) - - it('still presents when a pre-Android 13 default grant is not an opt-in decision', async () => { - vi.mocked(readPushNotificationsPreference).mockResolvedValue({ value: null, loaded: true }) - vi.mocked(getNotificationPermissionState).mockResolvedValue({ - granted: true, - status: 'granted', - canAskAgain: true, - authorizationReflectsUserChoice: false - }) - - await expect(shouldPresentNotificationOptIn()).resolves.toBe(true) - expect(savePushNotificationsEnabled).not.toHaveBeenCalled() - }) - - it('skips the gate when iOS has already denied permission', async () => { - vi.mocked(readPushNotificationsPreference).mockResolvedValue({ value: null, loaded: true }) - vi.mocked(getNotificationPermissionState).mockResolvedValue({ - granted: false, - status: 'denied', - canAskAgain: false, - authorizationReflectsUserChoice: false - }) - - await expect(shouldPresentNotificationOptIn()).resolves.toBe(false) - expect(savePushNotificationsEnabled).toHaveBeenCalledWith(false) - }) - - it('does not block startup when storage or permission checks fail', async () => { + it('does not prompt when the saved choice cannot be read', async () => { vi.mocked(readPushNotificationsPreference).mockResolvedValue({ value: null, loaded: false }) await expect(shouldPresentNotificationOptIn()).resolves.toBe(false) - - vi.mocked(readPushNotificationsPreference).mockResolvedValue({ value: null, loaded: true }) - vi.mocked(getNotificationPermissionState).mockRejectedValue(new Error('unavailable')) - await expect(shouldPresentNotificationOptIn()).resolves.toBe(false) }) }) diff --git a/mobile/src/notifications/notification-opt-in-gate.ts b/mobile/src/notifications/notification-opt-in-gate.ts index a909fad16d7..6ffcb662d7f 100644 --- a/mobile/src/notifications/notification-opt-in-gate.ts +++ b/mobile/src/notifications/notification-opt-in-gate.ts @@ -1,36 +1,6 @@ -import { - readPushNotificationsPreference, - savePushNotificationsEnabled -} from '../storage/preferences' -import { getNotificationPermissionState } from './mobile-notifications' +import { readPushNotificationsPreference } from '../storage/preferences' export async function shouldPresentNotificationOptIn(): Promise { const preference = await readPushNotificationsPreference() - if (!preference.loaded || preference.value !== null) { - return false - } - - try { - const permission = await getNotificationPermissionState() - if (permission.granted) { - if (!permission.authorizationReflectsUserChoice) { - return true - } - // Why: an already-authorized device should inherit the useful default - // without seeing an onboarding decision it has effectively made. - await savePushNotificationsEnabled(true) - return false - } - if (permission.status === 'denied' || !permission.canAskAgain) { - // Why: iOS cannot show its authorization prompt again, so a blocking - // onboarding screen would be a dead end; Settings remains the recovery. - await savePushNotificationsEnabled(false) - return false - } - return permission.status === 'undetermined' - } catch { - // Why: permission or persistence failures must not trap startup behind a - // decision screen whose result cannot be applied reliably. - return false - } + return preference.loaded && preference.value === null } diff --git a/mobile/src/notifications/notification-reconnect-catchup.ts b/mobile/src/notifications/notification-reconnect-catchup.ts deleted file mode 100644 index de05ed69505..00000000000 --- a/mobile/src/notifications/notification-reconnect-catchup.ts +++ /dev/null @@ -1,412 +0,0 @@ -import AsyncStorage from '@react-native-async-storage/async-storage' - -// Why: the reconnect catch-up watermark + dedup helpers for #8129, extracted -// from mobile-notifications.ts so that file stays under its max-lines budget. -// The highest desktop notification seq this device has delivered is persisted -// per-host so it survives app restarts. On reconnect we send it to -// notifications.getMissedSince as the catch-up watermark — the desktop then -// returns only notifications dispatched after it, so we never re-push a -// notification we already delivered. The in-memory seen-set is a second guard -// against double-delivery for events that arrive on both the live stream and a -// replay (e.g. a brief liveness spell before a reap). -// Why (#8591): a seq is meaningless without the counter it indexes — after a -// desktop restart that counter is gone. The epoch names the counter's lifetime so -// a reconnect can tell "nothing missed" from "different counter". -// -// Why ONE key holding both, rather than a key each: they are only meaningful as a -// pair. Written separately, a process death between the two writes leaves an epoch -// from one counter beside a seq from another — a pair that looks internally valid -// on the next launch and is therefore trusted, silently cutting real notifications. -// A single JSON value cannot tear that way. -const WATERMARK_STORAGE_KEY_PREFIX = 'orca:mobileNotificationsWatermark:' -// Pre-#8591 installs wrote the seq alone. Read once to migrate; never written. -const LEGACY_SEQ_STORAGE_KEY_PREFIX = 'orca:mobileNotificationsLastSeq:' - -function watermarkStorageKey(hostId: string): string { - return WATERMARK_STORAGE_KEY_PREFIX + encodeURIComponent(hostId) -} - -// A null epoch means "the counter this seq came from is unknown" — a legacy -// watermark, or nothing stored. It can never be assumed to be the live counter. -export type PersistedWatermark = { seq: number; epoch: string | null } -// `stored` is the record's existence, independent of its seq: it answers "has this -// device ever been subscribed to this host", which is what a cold open needs to tell -// a returning device from a first pairing. A seq of 0 is a real answer, not an absence. -export type LoadedWatermark = PersistedWatermark & { stored: boolean } - -function coerceSeq(value: unknown): number { - const parsed = typeof value === 'number' ? value : Number(value) - return Number.isFinite(parsed) && parsed > 0 ? parsed : 0 -} - -export async function loadWatermark(hostId: string): Promise { - try { - const raw = await AsyncStorage.getItem(watermarkStorageKey(hostId)) - if (raw != null) { - const parsed = JSON.parse(raw) as { seq?: unknown; epoch?: unknown } - const epoch = - typeof parsed.epoch === 'string' && parsed.epoch.length > 0 ? parsed.epoch : null - return { seq: coerceSeq(parsed.seq), epoch, stored: true } - } - } catch { - // Unreadable or malformed: fall through to the legacy key rather than throw. - } - try { - const legacy = await AsyncStorage.getItem( - LEGACY_SEQ_STORAGE_KEY_PREFIX + encodeURIComponent(hostId) - ) - return { seq: coerceSeq(legacy), epoch: null, stored: legacy != null } - } catch { - return { seq: 0, epoch: null, stored: false } - } -} - -export async function clearWatermark(hostId: string): Promise { - // Why both keys: loadWatermark falls back to the legacy one, so removing only the - // current key would let a re-paired host resurrect a pre-#8591 seq from a counter - // lifetime that is long gone — the exact stale cut this fix removes. - await Promise.all([ - AsyncStorage.removeItem(watermarkStorageKey(hostId)).catch(() => {}), - AsyncStorage.removeItem(LEGACY_SEQ_STORAGE_KEY_PREFIX + encodeURIComponent(hostId)).catch( - () => {} - ) - ]) -} - -export async function saveWatermark(hostId: string, watermark: PersistedWatermark): Promise { - try { - await AsyncStorage.setItem(watermarkStorageKey(hostId), JSON.stringify(watermark)) - } catch { - // Why: persisting the watermark is best-effort. If it fails (or lags), the - // stored value stays BELOW what we delivered, so a later cold start can - // re-fetch — and, once the in-memory seen-set is gone, re-show — an already - // delivered notification. That's the accepted at-least-once trade-off; - // within a live session the in-memory watermark is authoritative, so only - // post-restart reconnects are affected. - } -} - -// Why: bounded in-memory dedup window for notificationIds/dismiss ids observed -// on the current connection. The desktop already dedupes by seq on replay, but -// a socket that flickers background→foreground→background can deliver an event -// on the live stream and again in a replay; the seen-set guarantees each -// notificationId maps to at most one local push for the connection lifetime. -// Bounded so a long-lived session can't grow without limit — a 2x superset of -// the desktop's 256-entry replay buffer and the 256 scheduled-notification cap. -const RECENTLY_SEEN_CAP = 512 - -export function createSeenNotificationGuard(): { - has: (id: string) => boolean - add: (id: string) => void - clear: () => void -} { - const seen = new Set() - return { - has(id: string): boolean { - return seen.has(id) - }, - add(id: string): void { - seen.add(id) - if (seen.size > RECENTLY_SEEN_CAP) { - // Why: insertion order; the oldest entries are first. Drop one to stay - // bounded without disturbing the more-recently-relevant keys. - const first = seen.values().next().value - if (first !== undefined) { - seen.delete(first) - } - } - }, - clear(): void { - seen.clear() - } - } -} - -// Why (#8591): app/index.tsx tears the notification subscription down on every -// non-'connected' state and builds a fresh one on reconnect, so everything held -// in the subscription closure — the ready counter, the delivered watermark, the -// seen-set — is destroyed exactly when a reconnect needs it. Keeping it per host -// at module scope is what makes the catch-up recognise a reconnect (instead of -// mistaking it for a cold open) and keeps dedup effective across the teardown. -export type HostNotificationSession = { - // Highest desktop seq delivered for this host in this app process. Outranks - // the persisted value, which lags because saveLastSeenSeq is fire-and-forget. - lastDeliveredSeq: number - // Counter lifetime lastDeliveredSeq belongs to; null until one is known. A - // mismatch on reconnect means the desktop restarted and the watermark is void. - lastDeliveredEpoch: string | null - // Highest seq known delivered CONTIGUOUSLY, frozen here while a catch-up is - // outstanding; null when none has failed. See quarantineCatchUpWatermark. - catchUpQuarantineSeq: number | null - seen: ReturnType - // False only until the host's first subscription reaches 'ready' — a true cold open. - connectedBefore: boolean - // Why (#8591): distinguishes "this device has delivered for this host before" - // from a first-ever pairing. Only the former may catch up on a cold open — a - // brand-new pairing fetching from seq 0 would push the desktop's whole buffer - // at someone who was never subscribed for any of it. - hadStoredWatermark: boolean - // Resolves once the persisted read has landed, so the first 'ready' can wait for - // it instead of deciding catch-up against an unread watermark. - watermarkSeeded: Promise | null - // Tail of the per-host delivery chain; see enqueueHostDelivery. - deliveryTail: Promise - // notificationIds with a show queued or in flight on that chain; see - // shouldQueueShowForNotificationId. - queuedShowIds: Set -} - -const sessionsByHost = new Map() - -export function getHostNotificationSession(hostId: string): HostNotificationSession { - let session = sessionsByHost.get(hostId) - if (!session) { - session = { - lastDeliveredSeq: 0, - lastDeliveredEpoch: null, - catchUpQuarantineSeq: null, - seen: createSeenNotificationGuard(), - connectedBefore: false, - hadStoredWatermark: false, - watermarkSeeded: null, - deliveryTail: Promise.resolve(), - queuedShowIds: new Set() - } - sessionsByHost.set(hostId, session) - } - return session -} - -/** - * Run `task` after every delivery already queued for this host, and return a - * promise for its completion. - * - * Why (#8591): the watermark is persisted by whichever delivery advances it, so - * replay and live delivery running concurrently can persist out of order. A live - * seq 11 handled while catch-up is still showing seq 6 writes watermark 11, and a - * process death before 7..10 are shown loses them permanently — the next launch - * asks the desktop for seq > 11. Serializing per host makes the watermark's - * monotonic advance mean "everything up to here was actually delivered". - * - * A rejected task does not break the chain: the tail swallows the failure so a - * single bad notification cannot wedge the host's queue forever. - */ -export function enqueueHostDelivery( - session: HostNotificationSession, - task: () => Promise -): Promise { - const run = session.deliveryTail.then(task) - session.deliveryTail = run.catch(() => {}) - return run -} - -/** - * Claim a notificationId for a queued show, returning false if one is already - * queued or in flight for it. - * - * Why this exists (#8591): showLocalNotification deduped two same-id events by - * observing that the first was still pending when the second arrived. Serializing - * deliveries removed that overlap — the first now COMPLETES before the second - * starts, so the second reads no pending state and schedules a second banner for - * the same notification. The dedup has to happen where concurrency is still - * visible, which after serialization is enqueue time rather than delivery time. - * - * Only shows are tracked. A dismiss for the same id must still run: it is the - * mechanism that retires the notification the show created. - */ -export function shouldQueueShowForNotificationId( - session: HostNotificationSession, - notificationId: string | undefined -): boolean { - if (notificationId == null) { - return true - } - if (session.queuedShowIds.has(notificationId)) { - return false - } - session.queuedShowIds.add(notificationId) - return true -} - -/** Release the claim taken by shouldQueueShowForNotificationId once the show settles. */ -export function releaseQueuedShowNotificationId( - session: HostNotificationSession, - notificationId: string | undefined -): void { - if (notificationId != null) { - session.queuedShowIds.delete(notificationId) - } -} - -/** Test-only: drop per-host session state so each test starts from a cold open. */ -export function resetHostNotificationSessionsForTests(): void { - sessionsByHost.clear() -} - -/** - * Freeze the catch-up watermark at the last seq known delivered contiguously, - * after a catch-up that did not complete. - * - * Why: live delivery advances lastDeliveredSeq unconditionally, so an abandoned - * catch-up otherwise lets the NEXT one ask from above the range it gave up on — - * the desktop cuts by seq, so those notifications are never replayed and are - * gone. Lowest wins: an earlier failure's gap is still open. - */ -export function quarantineCatchUpWatermark( - session: HostNotificationSession, - hostId: string, - contiguousSeq: number -): void { - session.catchUpQuarantineSeq = - session.catchUpQuarantineSeq == null - ? contiguousSeq - : Math.min(session.catchUpQuarantineSeq, contiguousSeq) - // Why re-persist: a live event delivered while the catch-up was still in flight - // already stored a seq above the gap. Clamping only later writes would leave that - // value on disk, so a restart still resumes past the abandoned range. - void saveWatermark(hostId, { - seq: catchUpWatermarkSeq(session), - epoch: session.lastDeliveredEpoch - }) -} - -/** Lift the quarantine once a catch-up completes, persisting what it held back. */ -export function resolveCatchUpQuarantine(session: HostNotificationSession, hostId: string): void { - if (session.catchUpQuarantineSeq == null) { - return - } - session.catchUpQuarantineSeq = null - void saveWatermark(hostId, { - seq: session.lastDeliveredSeq, - epoch: session.lastDeliveredEpoch - }) -} - -/** - * The seq a catch-up may ask from and the highest seq safe to persist — the live - * watermark, clamped to any open gap. - */ -export function catchUpWatermarkSeq(session: HostNotificationSession): number { - return session.catchUpQuarantineSeq == null - ? session.lastDeliveredSeq - : Math.min(session.catchUpQuarantineSeq, session.lastDeliveredSeq) -} - -// Why (#8591): the desktop's seq counter restarts at 0 every launch, so a watermark -// from a previous lifetime indexes a counter that no longer exists. Comparing it -// against the fresh counter makes `lastSeenSeq >= seq` true for everything and -// catch-up dies silently until the new process out-dispatches the old watermark. -// Adopting the new epoch means dropping the watermark with it. -export function adoptNotificationEpoch( - session: HostNotificationSession, - hostId: string, - epoch: string | undefined -): void { - if (!epoch || epoch === session.lastDeliveredEpoch) { - return - } - // Why reset on a FIRST observation too (lastDeliveredEpoch === null): a seq seeded - // from a legacy store carries no epoch, so it cannot be shown to belong to this - // counter. Keeping it would let a pre-upgrade 57 cut the new counter's 1..57 — - // the exact #8591 failure, reached through the upgrade path instead of a restart. - session.lastDeliveredSeq = 0 - // Why clear `seen`: its keys are seq-derived, and terminal-bell notifications have - // no notificationId at all (they key on `seq:N` alone). Across a restart the new - // counter re-issues those same low seqs, so a stale `seq:1` would silently drop - // the new counter's first bell. The dedup window belongs to one counter lifetime. - session.seen.clear() - // The quarantined gap indexed the dead counter; the watermark it guarded is gone too. - session.catchUpQuarantineSeq = null - session.lastDeliveredEpoch = epoch - void saveWatermark(hostId, { seq: 0, epoch }) -} - -// Why: seed the watermark lazily so subscribe() doesn't block on an AsyncStorage read. -// Only the first subscription for a host needs it; later ones inherit the live value. -/** - * Ms the persisted read may block catch-up and live delivery before they proceed - * without it. AsyncStorage normally answers in single-digit ms; a read that has - * not landed by now is assumed wedged. - * - * Why a bound at all (#8591): every delivery awaits this promise, so a read that - * never settles silently disables notifications for the host for the whole app - * lifetime — no error, no banner, nothing to see. Proceeding unseeded is strictly - * better: the watermark stays 0, so catch-up over-fetches and the seen-set - * de-duplicates, which costs a redundant request instead of every notification. - */ -const WATERMARK_SEED_TIMEOUT_MS = 3000 - -function withTimeout(promise: Promise, ms: number): Promise { - return new Promise((resolve) => { - const timer = setTimeout(resolve, ms) - void promise.then( - () => { - clearTimeout(timer) - resolve() - }, - () => { - clearTimeout(timer) - resolve() - } - ) - }) -} - -export function seedWatermarkFromStorage(session: HostNotificationSession, hostId: string): void { - if (session.watermarkSeeded) { - return - } - const seeded = loadWatermark(hostId).then(({ seq, epoch, stored }) => { - // Why the record's existence and not `seq > 0`: adoptNotificationEpoch persists - // `{seq: 0, epoch}` when it voids a watermark, so a device that HAS delivered for - // this host reloads as seq 0. Keying on the seq would read that as a first pairing - // and skip catch-up for the whole window the epoch change was meant to recover. - if (stored) { - session.hadStoredWatermark = true - } - // Why the epoch comparison: this read can land AFTER 'ready' already adopted a - // live epoch. If the stored watermark belongs to a different (older) counter, - // applying it here would silently reinstate exactly the stale cut this fixes. - // A null stored epoch is a legacy watermark of unknown provenance — it may only - // seed while no live epoch is known, and adopting one later resets it. - if (session.lastDeliveredEpoch === null || session.lastDeliveredEpoch === epoch) { - session.lastDeliveredSeq = Math.max(session.lastDeliveredSeq, seq) - if (session.lastDeliveredEpoch === null && epoch !== null) { - session.lastDeliveredEpoch = epoch - } - } - }) - // The late seed still applies when it eventually lands; the timeout only stops it - // from holding delivery hostage. `seeded` never rejects into the awaiters. - session.watermarkSeeded = withTimeout(seeded, WATERMARK_SEED_TIMEOUT_MS) -} - -// Why (#8591): sessions live at module scope so they survive the subscription -// teardown a reconnect performs. Nothing else drops them, so a host that is removed -// and re-paired would retain its session and up to 512 seen keys until app restart. -export function forgetHostNotificationSession(hostId: string): void { - sessionsByHost.delete(hostId) -} - -// Why: key for the replay dedup guard. Uses notificationId when present, but -// disambiguates by seq so a legitimate live re-delivery of the same id at a -// NEW seq (content refresh, allowed by the existing behaviour) is NOT treated -// as a duplicate, while a replay re-returning the SAME id+seq already delivered -// live is suppressed. Replay events always carry a seq (the desktop assigns -// one), so the guard is effective on the reconnect path. -export function seenKeyForEvent(event: { - notificationId?: string - notificationSeq?: number -}): string | null { - const id = event.notificationId - if (id != null && event.notificationSeq != null) { - return `id:${id}#${event.notificationSeq}` - } - if (id != null) { - return `id:${id}` - } - if (event.notificationSeq != null) { - return `seq:${event.notificationSeq}` - } - return null -} diff --git a/mobile/src/notifications/notification-reconnect-teardown.test.ts b/mobile/src/notifications/notification-reconnect-teardown.test.ts deleted file mode 100644 index a5e7433bf0f..00000000000 --- a/mobile/src/notifications/notification-reconnect-teardown.test.ts +++ /dev/null @@ -1,201 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import * as Notifications from 'expo-notifications' -import { subscribeToDesktopNotifications } from './mobile-notifications' -import { resetHostNotificationSessionsForTests } from './notification-reconnect-catchup' -import AsyncStorage from '@react-native-async-storage/async-storage' -import type { RpcClient } from '../transport/rpc-client' -import { loadPushNotificationsEnabled } from '../storage/preferences' - -vi.mock('expo-notifications', () => ({ - AndroidImportance: { HIGH: 'high' }, - setNotificationChannelAsync: vi.fn(), - getPermissionsAsync: vi.fn(), - requestPermissionsAsync: vi.fn(), - scheduleNotificationAsync: vi.fn(), - dismissNotificationAsync: vi.fn() -})) - -vi.mock('react-native', () => ({ - Platform: { OS: 'ios', Version: 18 } -})) - -// In-memory AsyncStorage so the persisted watermark survives across the -// subscribe/unsubscribe cycles this test exercises (the real device behaviour). -const storage = new Map() -vi.mock('@react-native-async-storage/async-storage', () => ({ - default: { - getItem: vi.fn(async (k: string) => storage.get(k) ?? null), - setItem: vi.fn(async (k: string, v: string) => { - storage.set(k, v) - }) - } -})) - -vi.mock('../storage/preferences', () => ({ - loadPushNotificationsEnabled: vi.fn() -})) - -function flushAsync(): Promise { - return new Promise((resolve) => { - setTimeout(resolve, 10) - }) -} - -// Models mobile/app/index.tsx:497-537: a per-host client whose notification -// subscription is torn down on any non-'connected' state and re-created from -// scratch on the next 'connected'. -function makeHostClient() { - let onData: ((data: unknown) => void) | null = null - const getMissedCalls: { lastSeenSeq: number }[] = [] - const client = { - subscribe: vi.fn((_m: string, _p: unknown, cb: (data: unknown) => void) => { - onData = cb - return vi.fn(() => { - onData = null - }) - }), - getState: vi.fn(() => 'connected'), - sendRequest: vi.fn(async (method: string, params: unknown = {}) => { - if (method === 'notifications.getMissedSince') { - getMissedCalls.push(params as { lastSeenSeq: number }) - return { ok: true, result: { notifications: missedQueue } } as never - } - return { ok: true, result: undefined } as never - }) - } - let missedQueue: unknown[] = [] - return { - client: client as unknown as RpcClient, - get onData() { - return onData - }, - getMissedCalls, - setMissed(events: unknown[]) { - missedQueue = events - } - } -} - -describe('#8591 reconnect catch-up under the real app teardown lifecycle', () => { - beforeEach(() => { - vi.clearAllMocks() - storage.clear() - resetHostNotificationSessionsForTests() - vi.mocked(loadPushNotificationsEnabled).mockResolvedValue(true) - vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ - status: 'granted', - canAskAgain: true - } as never) - vi.mocked(Notifications.scheduleNotificationAsync).mockResolvedValue('sched-1') - vi.mocked(Notifications.dismissNotificationAsync).mockResolvedValue(undefined) - vi.mocked(AsyncStorage.getItem).mockClear() - }) - - it('fetches missed notifications after a disconnect tears the subscription down', async () => { - const host = makeHostClient() - - // ── Connected: cold open, one live notification delivered (desktop seq 7). - const unsub = subscribeToDesktopNotifications(host.client, 'host-1') - host.onData?.({ type: 'ready', subscriptionId: 'sub-1' }) - await flushAsync() - host.onData?.({ - type: 'notification', - title: 'live', - body: 'b', - notificationId: 'agent:live', - notificationSeq: 7 - }) - await flushAsync() - - // ── Socket drops. app/index.tsx wireUp() calls unsubNotif() on the - // non-'connected' state, destroying the subscribeToDesktopNotifications - // closure (and with it reconnectReadyCount / lastDeliveredSeq). - unsub() - await flushAsync() - - // ── While disconnected the desktop dispatched seq 8 and 9. - host.setMissed([ - { - type: 'notification', - title: 'missed-8', - body: 'b', - notificationId: 'agent:m8', - notificationSeq: 8 - }, - { - type: 'notification', - title: 'missed-9', - body: 'b', - notificationId: 'agent:m9', - notificationSeq: 9 - } - ]) - - // ── Reconnected: app re-subscribes with a FRESH closure. - subscribeToDesktopNotifications(host.client, 'host-1') - host.onData?.({ type: 'ready', subscriptionId: 'sub-2' }) - await flushAsync() - - // The user must be told about seq 8 and 9. Nothing else can deliver them: - // the desktop only fans out live, so this catch-up is the only path. - expect(host.getMissedCalls).toHaveLength(1) - expect(host.getMissedCalls[0]).toEqual({ lastSeenSeq: 7 }) - const titles = vi - .mocked(Notifications.scheduleNotificationAsync) - .mock.calls.map((c) => (c[0] as { content: { title: string } }).content.title) - expect(titles).toContain('missed-8') - expect(titles).toContain('missed-9') - }) - - it('does not re-push a live notification the catch-up replays after a teardown', async () => { - // Why: the seen-set lives on the host session precisely so it survives the teardown. - // getMissedSince cuts by seq > lastSeenSeq, but a notification delivered live in the - // brief window before the drop is still inside the desktop's retained buffer, so the - // reconnect fetch returns it again. Only the session-scoped seen-set stops a duplicate - // banner for something the user was already shown. - const host = makeHostClient() - - const unsub = subscribeToDesktopNotifications(host.client, 'host-1') - host.onData?.({ type: 'ready', subscriptionId: 'sub-1' }) - await flushAsync() - host.onData?.({ - type: 'notification', - title: 'live-7', - body: 'b', - notificationId: 'agent:seven', - notificationSeq: 7 - }) - await flushAsync() - - unsub() - await flushAsync() - - // The desktop replays seq 7 alongside the genuinely-missed seq 8. - host.setMissed([ - { - type: 'notification', - title: 'live-7', - body: 'b', - notificationId: 'agent:seven', - notificationSeq: 7 - }, - { - type: 'notification', - title: 'missed-8', - body: 'b', - notificationId: 'agent:m8', - notificationSeq: 8 - } - ]) - - subscribeToDesktopNotifications(host.client, 'host-1') - host.onData?.({ type: 'ready', subscriptionId: 'sub-2' }) - await flushAsync() - - const titles = vi - .mocked(Notifications.scheduleNotificationAsync) - .mock.calls.map((c) => (c[0] as { content: { title: string } }).content.title) - expect(titles.filter((title) => title === 'live-7')).toHaveLength(1) - expect(titles).toContain('missed-8') - }) -}) diff --git a/mobile/src/notifications/notification-routing.test.ts b/mobile/src/notifications/notification-routing.test.ts index 779aa2425e5..9b682bc2cb7 100644 --- a/mobile/src/notifications/notification-routing.test.ts +++ b/mobile/src/notifications/notification-routing.test.ts @@ -1,29 +1,10 @@ import { describe, expect, it } from 'vitest' import { - buildLocalNotificationData, getNotificationNavigationTarget, notificationCredentialRecoveryRoute } from './notification-routing' describe('notification routing', () => { - it('includes the host id in locally scheduled notification data', () => { - expect( - buildLocalNotificationData( - { - source: 'agent-task-complete', - worktreeId: 'repo::/Users/me/orca/workspaces/feature', - notificationId: 'agent:one' - }, - 'host-1' - ) - ).toEqual({ - source: 'agent-task-complete', - hostId: 'host-1', - worktreeId: 'repo::/Users/me/orca/workspaces/feature', - notificationId: 'agent:one' - }) - }) - // Identities stay raw: the target is dispatched as navigator params, not a URL. it('routes notification taps to the worktree terminal screen', () => { expect( @@ -88,3 +69,11 @@ describe('notification routing', () => { expect(notificationCredentialRecoveryRoute(target!)).toBeNull() }) }) + +it('preserves the originating pane in the workspace route', () => { + const paneKey = 'tab-b:11111111-1111-4111-8111-111111111111' + expect( + getNotificationNavigationTarget({ hostId: 'host', worktreeId: 'folder:/work', paneKey }) + ?.sessionTarget?.params + ).toEqual({ hostId: 'host', worktreeId: 'folder:/work', paneKey }) +}) diff --git a/mobile/src/notifications/notification-routing.ts b/mobile/src/notifications/notification-routing.ts index 5f81fb3567d..d1a8b6eebf3 100644 --- a/mobile/src/notifications/notification-routing.ts +++ b/mobile/src/notifications/notification-routing.ts @@ -2,21 +2,6 @@ import type { HostStackRouteTarget } from '../navigation/host-stack-navigation' import { mobileSessionRouteTarget } from '../session/mobile-session-route' import type { HostCredentialStatus } from '../transport/types' -export type DesktopNotificationSource = 'agent-task-complete' | 'terminal-bell' | 'test' - -export type DesktopNotificationEvent = { - source: DesktopNotificationSource - worktreeId?: string - notificationId?: string -} - -export type LocalNotificationData = { - source: DesktopNotificationSource - hostId: string - worktreeId?: string - notificationId?: string -} - export type NotificationNavigationOptions = { knownHostIds?: ReadonlySet credentialStatusByHostId?: ReadonlyMap @@ -26,23 +11,6 @@ function readNonEmptyString(value: unknown): string | null { return typeof value === 'string' && value.trim().length > 0 ? value : null } -export function buildLocalNotificationData( - event: DesktopNotificationEvent, - hostId: string -): LocalNotificationData { - const data: LocalNotificationData = { - source: event.source, - hostId - } - if (event.worktreeId) { - data.worktreeId = event.worktreeId - } - if (event.notificationId) { - data.notificationId = event.notificationId - } - return data -} - /** Where a tap should land. `sessionTarget` is null for a host-only notification, whose * `/h/` push is shallow enough to need no host-stack coordination. */ export type NotificationNavigationTarget = Readonly<{ @@ -81,7 +49,13 @@ export function getNotificationNavigationTarget( const credentialStatus = options.credentialStatusByHostId?.get(hostId) return { hostId, - sessionTarget: worktreeId ? mobileSessionRouteTarget({ hostId, worktreeId }) : null, + sessionTarget: worktreeId + ? mobileSessionRouteTarget({ + hostId, + worktreeId, + paneKey: readNonEmptyString(record.paneKey) ?? undefined + }) + : null, ...(credentialStatus === 'missing' ? { credentialRecovery: 're-pair' as const } : credentialStatus === 'temporarily-unavailable' diff --git a/mobile/src/notifications/notification-viewing-policy.ts b/mobile/src/notifications/notification-viewing-policy.ts new file mode 100644 index 00000000000..ea770cf3e74 --- /dev/null +++ b/mobile/src/notifications/notification-viewing-policy.ts @@ -0,0 +1,19 @@ +import { AppState } from 'react-native' + +let viewing: { hostId: string; worktreeId: string } | null = null +export function setNotificationViewingWorkspace(value: typeof viewing): void { + viewing = value +} + +export function shouldSuppressNotificationWhileViewing( + event: { worktreeId?: string }, + hostId: string, + suppressWhileViewing: boolean +): boolean { + return ( + suppressWhileViewing && + AppState.currentState === 'active' && + viewing?.hostId === hostId && + viewing.worktreeId === event.worktreeId + ) +} diff --git a/mobile/src/notifications/notification-watermark-seed-race.test.ts b/mobile/src/notifications/notification-watermark-seed-race.test.ts deleted file mode 100644 index 742f0711982..00000000000 --- a/mobile/src/notifications/notification-watermark-seed-race.test.ts +++ /dev/null @@ -1,206 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import * as Notifications from 'expo-notifications' -import { subscribeToDesktopNotifications } from './mobile-notifications' -import { - adoptNotificationEpoch, - clearWatermark, - getHostNotificationSession, - resetHostNotificationSessionsForTests, - seedWatermarkFromStorage -} from './notification-reconnect-catchup' -import AsyncStorage from '@react-native-async-storage/async-storage' -import type { RpcClient } from '../transport/rpc-client' -import { loadPushNotificationsEnabled } from '../storage/preferences' - -vi.mock('expo-notifications', () => ({ - AndroidImportance: { HIGH: 'high' }, - setNotificationChannelAsync: vi.fn(), - getPermissionsAsync: vi.fn(), - requestPermissionsAsync: vi.fn(), - scheduleNotificationAsync: vi.fn(), - dismissNotificationAsync: vi.fn() -})) - -vi.mock('react-native', () => ({ - Platform: { OS: 'ios', Version: 18 } -})) - -// A storage whose reads can be held open, so a live event can be injected into the -// exact window a real cold open has: subscription up, persisted watermark not yet read. -const storage = new Map() -let heldReads: (() => void)[] = [] -let holdReads = false -vi.mock('@react-native-async-storage/async-storage', () => ({ - default: { - getItem: vi.fn((key: string) => { - const read = (): string | null => storage.get(key) ?? null - if (!holdReads) { - return Promise.resolve(read()) - } - return new Promise((resolve) => { - heldReads.push(() => resolve(read())) - }) - }), - setItem: vi.fn(async (key: string, value: string) => { - storage.set(key, value) - }), - removeItem: vi.fn(async (key: string) => { - storage.delete(key) - }) - } -})) - -vi.mock('../storage/preferences', () => ({ - loadPushNotificationsEnabled: vi.fn() -})) - -function flushAsync(): Promise { - return new Promise((resolve) => { - setTimeout(resolve, 10) - }) -} - -function releaseReads(): void { - const pending = heldReads - heldReads = [] - for (const resolve of pending) { - resolve() - } -} - -function makeHostClient() { - let onData: ((data: unknown) => void) | null = null - const getMissedCalls: { lastSeenSeq: number; epoch?: string }[] = [] - const client = { - subscribe: vi.fn((_m: string, _p: unknown, cb: (data: unknown) => void) => { - onData = cb - return vi.fn(() => { - onData = null - }) - }), - getState: vi.fn(() => 'connected'), - sendRequest: vi.fn(async (method: string, params: unknown = {}) => { - if (method === 'notifications.getMissedSince') { - getMissedCalls.push(params as { lastSeenSeq: number; epoch?: string }) - return { ok: true, result: { notifications: [] } } as never - } - return { ok: true, result: undefined } as never - }) - } - return { - client: client as unknown as RpcClient, - get onData() { - return onData - }, - getMissedCalls - } -} - -const WATERMARK_KEY = 'orca:mobileNotificationsWatermark:host-1' -const LEGACY_KEY = 'orca:mobileNotificationsLastSeq:host-1' - -describe('#8591 watermark seeding races a cold open', () => { - beforeEach(() => { - vi.clearAllMocks() - storage.clear() - heldReads = [] - holdReads = false - resetHostNotificationSessionsForTests() - vi.mocked(loadPushNotificationsEnabled).mockResolvedValue(true) - vi.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ - status: 'granted', - canAskAgain: true - } as never) - vi.mocked(Notifications.scheduleNotificationAsync).mockResolvedValue('sched-1') - vi.mocked(Notifications.dismissNotificationAsync).mockResolvedValue(undefined) - }) - - it('asks for catch-up from the persisted seq even if a live event lands first', async () => { - // The window is real: app/index.tsx subscribes immediately, and the desktop's - // 'ready' plus its first live fan-out can both beat an AsyncStorage read. If the - // live seq is allowed to advance the watermark first, getMissedSince is asked to - // start from it and the desktop cuts everything the device actually missed. - storage.set(WATERMARK_KEY, JSON.stringify({ seq: 5, epoch: 'epoch-a' })) - holdReads = true - const host = makeHostClient() - - subscribeToDesktopNotifications(host.client, 'host-1') - host.onData?.({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-a' }) - host.onData?.({ - type: 'notification', - title: 'live-12', - body: 'b', - notificationId: 'agent:live', - notificationSeq: 12, - notificationEpoch: 'epoch-a' - }) - await flushAsync() - - // Nothing may be decided while the read is outstanding. - expect(host.getMissedCalls).toHaveLength(0) - - releaseReads() - await flushAsync() - - expect(host.getMissedCalls).toEqual([{ lastSeenSeq: 5, epoch: 'epoch-a' }]) - }) - - it('treats a zeroed-but-present watermark as a returning device, not a first pairing', async () => { - // adoptNotificationEpoch persists {seq: 0, epoch} when it voids a watermark from a - // dead counter. That record still proves this device has been subscribed here, so a - // cold open after it must catch up — reading it as "never paired" drops the window. - storage.set(WATERMARK_KEY, JSON.stringify({ seq: 0, epoch: 'epoch-a' })) - const host = makeHostClient() - - subscribeToDesktopNotifications(host.client, 'host-1') - host.onData?.({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-a' }) - await flushAsync() - - expect(host.getMissedCalls).toEqual([{ lastSeenSeq: 0, epoch: 'epoch-a' }]) - }) - - it('does not catch up on a first-ever pairing', async () => { - const host = makeHostClient() - - subscribeToDesktopNotifications(host.client, 'host-1') - host.onData?.({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-a' }) - await flushAsync() - - expect(host.getMissedCalls).toEqual([]) - }) - - it('a seed landing after a live epoch is adopted cannot reinstate the dead watermark', async () => { - // Ordering invariant on the exported pair, not a path subscribeToDesktopNotifications - // can currently take — 'ready' awaits watermarkSeeded before adopting, so the seed - // always resolves first today. Pinned anyway because the guard is load-bearing the - // moment any caller adopts an epoch before seeding: applying a seq 40 from a counter - // that no longer exists would let getMissedSince cut the new counter's 1..40, which - // is the original #8591 loss re-entered through the seeding path. - const session = getHostNotificationSession('host-1') - adoptNotificationEpoch(session, 'host-1', 'epoch-new') - await flushAsync() - - storage.set(WATERMARK_KEY, JSON.stringify({ seq: 40, epoch: 'epoch-old' })) - seedWatermarkFromStorage(session, 'host-1') - await session.watermarkSeeded - await flushAsync() - - expect(session.lastDeliveredEpoch).toBe('epoch-new') - expect(session.lastDeliveredSeq).toBe(0) - }) - - it('clears the legacy seq key too, so an unpaired host cannot resurrect it', async () => { - // loadWatermark falls back to the legacy key, so leaving it behind lets a re-paired - // host read a pre-#8591 seq belonging to a counter lifetime that no longer exists. - storage.set(WATERMARK_KEY, JSON.stringify({ seq: 9, epoch: 'epoch-a' })) - storage.set(LEGACY_KEY, '57') - - await clearWatermark('host-1') - - expect(vi.mocked(AsyncStorage.removeItem).mock.calls.map((call) => call[0])).toEqual( - expect.arrayContaining([WATERMARK_KEY, LEGACY_KEY]) - ) - expect(storage.has(WATERMARK_KEY)).toBe(false) - expect(storage.has(LEGACY_KEY)).toBe(false) - }) -}) diff --git a/mobile/src/notifications/push-background-dismissal.test.ts b/mobile/src/notifications/push-background-dismissal.test.ts new file mode 100644 index 00000000000..40e535e2fcf --- /dev/null +++ b/mobile/src/notifications/push-background-dismissal.test.ts @@ -0,0 +1,72 @@ +import { expect, it, vi } from 'vitest' +const state = vi.hoisted(() => ({ task: null as null | ((input: unknown) => Promise) })) +vi.mock('expo-task-manager', () => ({ + defineTask: (_name: string, task: typeof state.task) => { + state.task = task + }, + isAvailableAsync: async () => true +})) +vi.mock('expo-notifications', () => ({ + registerTaskAsync: vi.fn(), + getPresentedNotificationsAsync: vi.fn(async () => []), + dismissNotificationAsync: vi.fn() +})) +vi.mock('./push-tray-dismissal', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + dismissPresentedPushNotification: vi.fn(actual.dismissPresentedPushNotification) + } +}) +import * as Notifications from 'expo-notifications' +import { dismissPresentedPushNotification } from './push-tray-dismissal' +import { registerPushDismissalTask } from './push-background-dismissal' + +it('handles native background JSON and scopes dismissal to the originating host', async () => { + await registerPushDismissalTask() + await state.task!({ + data: { + data: { + dataString: JSON.stringify({ + kind: 'dismiss', + hostFingerprint: 'host-a', + notificationId: 'same-id' + }) + } + } + }) + expect(dismissPresentedPushNotification).toHaveBeenCalledWith( + 'same-id', + 'host-a', + expect.objectContaining({ kind: 'dismiss' }) + ) +}) + +it('does not turn ordinary alerts into dismissals', async () => { + vi.mocked(dismissPresentedPushNotification).mockClear() + await state.task!({ + data: { data: { orca: { hostFingerprint: 'host-a', notificationId: 'same-id' } } } + }) + expect(dismissPresentedPushNotification).not.toHaveBeenCalled() +}) + +it('an ID-only background dismissal preserves versioned tray alerts', async () => { + const base = { hostFingerprint: 'host-a', notificationId: 'same-id' } + vi.mocked(Notifications.getPresentedNotificationsAsync).mockResolvedValue([ + { request: { identifier: 'legacy', content: { data: base } } }, + { + request: { + identifier: 'versioned', + content: { + data: { + ...base, + notificationEpoch: 'epoch', + notificationSeq: 3 + } + } + } + } + ] as never) + await state.task!({ data: { data: { ...base, kind: 'dismiss' } } }) + expect(Notifications.dismissNotificationAsync).toHaveBeenCalledExactlyOnceWith('legacy') +}) diff --git a/mobile/src/notifications/push-background-dismissal.ts b/mobile/src/notifications/push-background-dismissal.ts new file mode 100644 index 00000000000..4689d58ef58 --- /dev/null +++ b/mobile/src/notifications/push-background-dismissal.ts @@ -0,0 +1,41 @@ +import { wasPushDismissed } from './push-dismissal-watermarks' +import * as TaskManager from 'expo-task-manager' +import * as Notifications from 'expo-notifications' +import { readOrcaPushPayload } from './push-payload' +import { dismissPresentedPushNotification } from './push-tray-dismissal' + +const TASK_NAME = 'orca-push-dismissal' + +TaskManager.defineTask( + TASK_NAME, + async ({ data, error }) => { + if (error || !data || 'actionIdentifier' in data) { + return + } + let raw: unknown = data.data + if (typeof data.data.dataString === 'string') { + try { + raw = JSON.parse(data.data.dataString) + } catch { + return + } + } + const payload = readOrcaPushPayload(raw) + if ( + payload?.notificationId && + (payload.kind === 'dismiss' || (await wasPushDismissed(payload))) + ) { + await dismissPresentedPushNotification( + payload.notificationId, + payload.hostFingerprint, + payload + ) + } + } +) + +export async function registerPushDismissalTask(): Promise { + if (await TaskManager.isAvailableAsync()) { + await Notifications.registerTaskAsync(TASK_NAME) + } +} diff --git a/mobile/src/notifications/push-dismissal-native-races.test.ts b/mobile/src/notifications/push-dismissal-native-races.test.ts new file mode 100644 index 00000000000..35a51748906 --- /dev/null +++ b/mobile/src/notifications/push-dismissal-native-races.test.ts @@ -0,0 +1,128 @@ +import { beforeEach, expect, it, vi } from 'vitest' +import AsyncStorage from '@react-native-async-storage/async-storage' +import { nativePushDismissal } from './native-push-dismissal' +import { rememberPushDismissal, wasPushDismissed } from './push-dismissal-watermarks' +import { foregroundNotificationBehavior } from './push-receive' +import { loadNotificationDeliveryPreferences } from './notification-delivery-preferences' + +const memory = vi.hoisted(() => new Map()) +const nativeLedger = vi.hoisted(() => new Map()) +vi.mock('./native-push-dismissal', () => ({ + nativePushDismissal: { + remember: vi.fn(async (payload) => { + const key = JSON.stringify([ + payload.hostFingerprint, + payload.notificationEpoch, + payload.notificationId + ]) + nativeLedger.set(key, Math.max(nativeLedger.get(key) ?? 0, payload.notificationSeq)) + }), + wasDismissed: vi.fn( + async (payload) => + (nativeLedger.get( + JSON.stringify([ + payload.hostFingerprint, + payload.notificationEpoch, + payload.notificationId + ]) + ) ?? -1) >= payload.notificationSeq + ) + } +})) +vi.mock('@react-native-async-storage/async-storage', () => ({ + default: { + getItem: vi.fn(async (key: string) => memory.get(key) ?? null), + setItem: vi.fn(async (key: string, value: string) => { + memory.set(key, value) + }) + } +})) +vi.mock('expo-notifications', () => ({ getPresentedNotificationsAsync: async () => [] })) +vi.mock('../transport/host-store', () => ({ loadHostCatalog: async () => [{ id: 'host' }] })) +vi.mock('./push-host-fingerprint', () => ({ resolveHostIdForFingerprint: () => 'host' })) +vi.mock('../storage/preferences', () => ({ + loadPushNotificationsEnabled: async () => true +})) +vi.mock('./notification-viewing-policy', () => ({ + shouldSuppressNotificationWhileViewing: () => false +})) +vi.mock('./notification-delivery-preferences', () => ({ + loadNotificationDeliveryPreferences: vi.fn(async () => ({ sound: true })) +})) + +const payload = { + hostFingerprint: 'abcdefghijklmnop', + notificationEpoch: 'epoch', + notificationId: 'note', + notificationSeq: 20 +} +const fence = { ...payload, notificationSeq: 21 } + +beforeEach(() => { + vi.clearAllMocks() + vi.mocked(AsyncStorage.getItem).mockImplementation(async (key) => memory.get(key) ?? null) + memory.clear() + nativeLedger.clear() +}) + +it('uses only native storage for iOS dismissal reads and writes', async () => { + await rememberPushDismissal(fence) + expect(await wasPushDismissed(payload)).toBe(true) + expect(await wasPushDismissed({ ...payload, notificationSeq: 22 })).toBe(false) + expect(await wasPushDismissed({ ...payload, notificationEpoch: 'new-epoch' })).toBe(false) + expect(AsyncStorage.getItem).not.toHaveBeenCalled() + expect(AsyncStorage.setItem).not.toHaveBeenCalled() +}) + +it('rechecks a negative native snapshot overtaken by a dismissal', async () => { + let finish!: () => void + vi.mocked(nativePushDismissal!.wasDismissed).mockImplementationOnce(async () => { + await new Promise((resolve) => { + finish = resolve + }) + return false + }) + const pending = wasPushDismissed(payload) + await vi.waitFor(() => expect(finish).toBeDefined()) + await rememberPushDismissal(fence) + finish() + expect(await pending).toBe(true) + expect(nativePushDismissal!.wasDismissed).toHaveBeenCalledTimes(2) +}) + +it('surfaces native write failures without switching storage or poisoning later operations', async () => { + vi.mocked(nativePushDismissal!.remember).mockRejectedValueOnce(new Error('native failure')) + await expect(rememberPushDismissal(fence)).rejects.toThrow('native failure') + expect(AsyncStorage.setItem).not.toHaveBeenCalled() + await rememberPushDismissal(fence) + expect(await wasPushDismissed(payload)).toBe(true) +}) + +it('suppresses presentation when dismissal completes during the handler sound read', async () => { + let finish!: () => void + vi.mocked(loadNotificationDeliveryPreferences).mockImplementationOnce(async () => { + await new Promise((resolve) => { + finish = resolve + }) + return { sound: true } as Awaited> + }) + const pending = foregroundNotificationBehavior({ + request: { + identifier: 'foreground-alert', + trigger: null, + content: { title: null, subtitle: null, body: null, sound: null, data: { orca: payload } } + } + }) + await vi.waitFor(() => expect(finish).toBeDefined()) + await foregroundNotificationBehavior({ + request: { content: { data: { orca: { ...fence, kind: 'dismiss' } } } } + }) + expect(await wasPushDismissed(payload)).toBe(true) + finish() + expect(await pending).toEqual({ + shouldShowBanner: false, + shouldShowList: false, + shouldPlaySound: false, + shouldSetBadge: false + }) +}) diff --git a/mobile/src/notifications/push-dismissal-reconciliation.test.ts b/mobile/src/notifications/push-dismissal-reconciliation.test.ts new file mode 100644 index 00000000000..f1e1d34c606 --- /dev/null +++ b/mobile/src/notifications/push-dismissal-reconciliation.test.ts @@ -0,0 +1,145 @@ +import { beforeEach, expect, it, vi } from 'vitest' +import * as Notifications from 'expo-notifications' +import { loadHostCatalog } from '../transport/host-store' +import { deriveHostFingerprint } from './push-host-fingerprint' +import { requestNotificationCatchup } from './push-dismissal-reconciliation' +vi.mock('../transport/host-store', () => ({ loadHostCatalog: vi.fn() })) +vi.mock('expo-notifications', () => ({ + getPresentedNotificationsAsync: vi.fn(), + dismissNotificationAsync: vi.fn() +})) +vi.mock('@react-native-async-storage/async-storage', () => ({ + default: { getItem: async () => null, setItem: async () => {} } +})) +const publicKeyB64 = Buffer.alloc(32, 1).toString('base64') +const hostFingerprint = deriveHostFingerprint(publicKeyB64) +const id = { + notificationId: 'old-alert', + notificationEpoch: 'previous-host-process', + notificationSeq: 12 +} +function presented(identifier: string, overrides = {}) { + return { request: { identifier, content: { data: { hostFingerprint, ...id, ...overrides } } } } +} +beforeEach(() => { + vi.clearAllMocks() + vi.mocked(loadHostCatalog).mockResolvedValue([{ id: 'host-a', publicKeyB64 }] as never) + vi.mocked(Notifications.getPresentedNotificationsAsync).mockResolvedValue([ + presented('old'), + presented('new', { notificationSeq: 14 }), + presented('other', { hostFingerprint: 'other-host' }) + ] as never) + vi.mocked(Notifications.dismissNotificationAsync).mockResolvedValue(undefined) +}) +it('clears a confirmed prior-epoch alert even with empty replay and preserves newer and other-host entries', async () => { + const sendRequest = vi.fn(async () => ({ + ok: true, + result: { notifications: [], epoch: 'new-process', dismissedPushes: [id] } + })) + await requestNotificationCatchup({ sendRequest } as never, 'host-a', () => false) + expect(sendRequest).toHaveBeenCalledWith('notifications.getMissedSince', { + lastSeenSeq: Number.MAX_SAFE_INTEGER, + deliveredPushes: [id, { ...id, notificationSeq: 14 }] + }) + expect(Notifications.dismissNotificationAsync).toHaveBeenCalledExactlyOnceWith('old') +}) +it('keeps alerts when an old host omits reconciliation or the request fails', async () => { + for (const response of [{ ok: true, result: { notifications: [] } }, { ok: false }]) { + await requestNotificationCatchup( + { sendRequest: async () => response } as never, + 'host-a', + () => false + ) + } + expect(Notifications.dismissNotificationAsync).not.toHaveBeenCalled() +}) +it('ignores unrequested identities and a response arriving after disconnect', async () => { + let disposed = false + const sendRequest = vi.fn(async () => ({ + ok: true, + result: { + dismissedPushes: [ + { ...id, notificationSeq: 99 }, + { ...id, notificationEpoch: 'different-epoch' }, + { ...id, notificationId: 'different-alert' } + ] + } + })) + await requestNotificationCatchup({ sendRequest } as never, 'host-a', () => disposed) + sendRequest.mockImplementationOnce(async () => { + disposed = true + return { ok: true, result: { dismissedPushes: [id] } } + }) + await requestNotificationCatchup({ sendRequest } as never, 'host-a', () => disposed) + expect(sendRequest).toHaveBeenCalledTimes(2) + expect(Notifications.dismissNotificationAsync).not.toHaveBeenCalled() +}) + +it('skips the replay RPC when the tray has no alerts for this host', async () => { + vi.mocked(Notifications.getPresentedNotificationsAsync).mockResolvedValue([ + presented('other', { hostFingerprint: 'other-host' }) + ] as never) + const sendRequest = vi.fn() + await requestNotificationCatchup({ sendRequest } as never, 'host-a', () => false) + expect(sendRequest).not.toHaveBeenCalled() +}) + +it('pages individual tray identities without requesting historical alerts', async () => { + const all = Array.from({ length: 288 }, (_, index) => ({ + hostFingerprint, + notificationId: `paged-${index}`, + notificationEpoch: 'previous-host-process', + notificationSeq: index + })) + vi.mocked(Notifications.getPresentedNotificationsAsync).mockResolvedValue( + all.map((payload) => presented(payload.notificationId, payload)) as never + ) + const sendRequest = vi.fn(async (_method: string, params: { deliveredPushes?: typeof all }) => ({ + ok: true, + result: { notifications: [], dismissedPushes: params.deliveredPushes ?? [] } + })) + await requestNotificationCatchup({ sendRequest } as never, 'host-a', () => false) + expect(sendRequest).toHaveBeenCalledTimes(2) + expect(sendRequest.mock.calls[0]?.[1]).toMatchObject({ + lastSeenSeq: Number.MAX_SAFE_INTEGER + }) + expect(sendRequest.mock.calls[0]?.[1].deliveredPushes).toHaveLength(256) + expect(sendRequest.mock.calls[1]?.[1]).toMatchObject({ + lastSeenSeq: Number.MAX_SAFE_INTEGER, + deliveredPushes: all + .slice(256) + .map(({ notificationId, notificationEpoch, notificationSeq }) => ({ + notificationId, + notificationEpoch, + notificationSeq + })) + }) + expect(vi.mocked(Notifications.dismissNotificationAsync)).toHaveBeenCalledTimes(288) +}) + +it.each(['failure', 'disconnect'])( + 'stops after a second-page %s without removing unconfirmed alerts', + async (outcome) => { + vi.mocked(Notifications.getPresentedNotificationsAsync).mockResolvedValue( + Array.from({ length: 513 }, (_, index) => + presented(`paged-${index}`, { notificationId: `paged-${index}`, notificationSeq: index }) + ) as never + ) + let disposed = false + let pages = 0 + const sendRequest = vi.fn( + async (_method: string, params: { deliveredPushes: (typeof id)[] }) => { + pages++ + disposed = pages === 2 && outcome === 'disconnect' + return { + ok: !(pages === 2 && outcome === 'failure'), + result: { dismissedPushes: params.deliveredPushes } + } + } + ) + await requestNotificationCatchup({ sendRequest } as never, 'host-a', () => disposed) + expect(sendRequest).toHaveBeenCalledTimes(2) + expect(Notifications.dismissNotificationAsync).toHaveBeenCalledTimes(256) + expect(Notifications.dismissNotificationAsync).not.toHaveBeenCalledWith('paged-256') + } +) diff --git a/mobile/src/notifications/push-dismissal-reconciliation.ts b/mobile/src/notifications/push-dismissal-reconciliation.ts new file mode 100644 index 00000000000..4c39ccfeb0f --- /dev/null +++ b/mobile/src/notifications/push-dismissal-reconciliation.ts @@ -0,0 +1,81 @@ +import * as Notifications from 'expo-notifications' +import type { RpcClient } from '../transport/rpc-client' +import { loadHostCatalog } from '../transport/host-store' +import { resolveHostIdForFingerprint } from './push-host-fingerprint' +import { readNativeNotificationData } from './native-notification-data' +import { readOrcaPushPayload, type OrcaPushPayload } from './push-payload' +import { dismissRememberedPushNotifications } from './push-tray-dismissal' +import { rememberPushDismissal } from './push-dismissal-watermarks' +import { + readPushNotificationIdentity, + type PushNotificationIdentity +} from './push-notification-identity' + +const key = (item: PushNotificationIdentity) => + JSON.stringify([item.notificationId, item.notificationEpoch, item.notificationSeq]) +async function readDelivered(hostId: string): Promise> { + const selected = new Map() + try { + const [presented, hosts] = await Promise.all([ + Notifications.getPresentedNotificationsAsync(), + loadHostCatalog() + ]) + for (const notification of presented) { + const payload = readOrcaPushPayload(readNativeNotificationData(notification.request)) + if (!payload || resolveHostIdForFingerprint(payload.hostFingerprint, hosts) !== hostId) { + continue + } + const identity = readPushNotificationIdentity(payload) + if (identity && selected.size < 2048) { + selected.set(key(identity), payload) + } + if (selected.size === 2048) { + break + } + } + } catch { + // Tray inspection is best-effort; failure leaves OS banners for later reconciliation. + } + return selected +} + +export async function requestNotificationCatchup( + client: Pick, + hostId: string, + isDisposed: () => boolean +): Promise { + const entries = [...(await readDelivered(hostId)).entries()] + for (let offset = 0; offset < entries.length && !isDisposed(); offset += 256) { + const requested = new Map(entries.slice(offset, offset + 256)) + const reply = await client.sendRequest('notifications.getMissedSince', { + // Reconcile the tray without requesting historical alerts. + lastSeenSeq: Number.MAX_SAFE_INTEGER, + deliveredPushes: [...requested.values()].map((payload) => + readPushNotificationIdentity(payload)! + ) + }) + if (!reply.ok || isDisposed()) { + return + } + const result = reply.result as { dismissedPushes?: unknown } | undefined + if (!Array.isArray(result?.dismissedPushes)) { + continue + } + const confirmed: OrcaPushPayload[] = [] + for (const raw of result.dismissedPushes.slice(0, 256)) { + if (isDisposed()) { + break + } + const id = readPushNotificationIdentity(raw) + const payload = id ? requested.get(key(id)) : undefined + if (payload && id) { + await rememberPushDismissal(payload) + confirmed.push(payload) + requested.delete(key(id)) + } + } + if (confirmed.length && !isDisposed()) { + await dismissRememberedPushNotifications(confirmed[0]!.hostFingerprint, confirmed) + } + } +} diff --git a/mobile/src/notifications/push-dismissal-watermarks.test.ts b/mobile/src/notifications/push-dismissal-watermarks.test.ts new file mode 100644 index 00000000000..cef0cf3404e --- /dev/null +++ b/mobile/src/notifications/push-dismissal-watermarks.test.ts @@ -0,0 +1,93 @@ +import { beforeEach, expect, it, vi } from 'vitest' +import AsyncStorage from '@react-native-async-storage/async-storage' +const storage = vi.hoisted(() => new Map()) +vi.mock('@react-native-async-storage/async-storage', () => ({ + default: { + getItem: vi.fn(async (key: string) => storage.get(key) ?? null), + setItem: async (key: string, value: string) => { + storage.set(key, value) + } + } +})) +import { rememberPushDismissal, wasPushDismissed } from './push-dismissal-watermarks' +const payload = { + hostFingerprint: 'host-a', + notificationEpoch: 'epoch-a', + notificationId: 'note', + notificationSeq: 2 +} +beforeEach(() => { + storage.clear() + vi.mocked(AsyncStorage.getItem) + .mockReset() + .mockImplementation(async (key) => storage.get(key) ?? null) + vi.useRealTimers() +}) + +it('persists dismissal through restart while preserving newer alerts and other hosts or epochs', async () => { + await rememberPushDismissal(payload) + vi.resetModules() + const restarted = await import('./push-dismissal-watermarks') + expect(await restarted.wasPushDismissed({ ...payload, notificationSeq: 1 })).toBe(true) + expect(await restarted.wasPushDismissed({ ...payload, notificationSeq: 3 })).toBe(false) + expect(await restarted.wasPushDismissed({ ...payload, hostFingerprint: 'host-b' })).toBe(false) + expect(await restarted.wasPushDismissed({ ...payload, notificationEpoch: 'epoch-b' })).toBe(false) +}) + +it('serializes concurrent dismissals and never lowers a watermark', async () => { + await Promise.all([ + rememberPushDismissal({ ...payload, notificationSeq: 5 }), + rememberPushDismissal(payload), + rememberPushDismissal({ ...payload, notificationId: 'other' }) + ]) + expect(await wasPushDismissed({ ...payload, notificationSeq: 5 })).toBe(true) + expect(await wasPushDismissed({ ...payload, notificationId: 'other' })).toBe(true) +}) + +it('expires retained metadata and ignores unversioned dismissals', async () => { + vi.useFakeTimers() + await rememberPushDismissal(payload) + vi.setSystemTime(Date.now() + 24 * 60 * 60 * 1000) + expect(await wasPushDismissed(payload)).toBe(false) + await rememberPushDismissal({ ...payload, notificationEpoch: undefined }) + expect(await wasPushDismissed(payload)).toBe(false) +}) + +it('joins an overtaking JavaScript write before retrying a delayed negative snapshot', async () => { + let finish!: () => void + vi.mocked(AsyncStorage.getItem).mockImplementationOnce(async (key) => { + const snapshot = storage.get(key) ?? null + await new Promise((resolve) => { + finish = resolve + }) + return snapshot + }) + const pending = wasPushDismissed(payload) + await vi.waitFor(() => expect(finish).toBeDefined()) + await rememberPushDismissal(payload) + finish() + expect(await pending).toBe(true) + expect(AsyncStorage.getItem).toHaveBeenCalledTimes(3) + expect(await wasPushDismissed({ ...payload, notificationSeq: 3 })).toBe(false) +}) + +it.each([1, 3])('retains live dismissals beyond 512 entries across %i hosts', async (hosts) => { + for (let index = 0; index < 520; index++) { + await rememberPushDismissal({ + ...payload, + hostFingerprint: `host-${index % hosts}`, + notificationId: `note-${index}` + }) + } + vi.resetModules() + const restarted = await import('./push-dismissal-watermarks') + for (const index of [0, 1, 519]) { + const alert = { + ...payload, + hostFingerprint: `host-${index % hosts}`, + notificationId: `note-${index}` + } + expect(await restarted.wasPushDismissed(alert)).toBe(true) + expect(await restarted.wasPushDismissed({ ...alert, notificationSeq: 3 })).toBe(false) + } +}) diff --git a/mobile/src/notifications/push-dismissal-watermarks.ts b/mobile/src/notifications/push-dismissal-watermarks.ts new file mode 100644 index 00000000000..8202af054d7 --- /dev/null +++ b/mobile/src/notifications/push-dismissal-watermarks.ts @@ -0,0 +1,104 @@ +import AsyncStorage from '@react-native-async-storage/async-storage' +import type { OrcaPushPayload } from './push-payload' +import { nativePushDismissal } from './native-push-dismissal' + +const STORAGE_KEY = 'orca:pushDismissalWatermarks:v1' +// Keep every live fence: count-based eviction lets delayed alerts reappear. +const RETENTION_MS = 24 * 60 * 60 * 1000 + +type Entry = { key: string; seq: number; expiresAt: number } +let writes: Promise = Promise.resolve() + +function queueDismissalOperation(operation: () => Promise): Promise { + const pending = writes.then(operation) + writes = pending.then( + () => {}, + () => {} + ) + return pending +} + +function eventKey(payload: OrcaPushPayload): string | null { + if ( + !payload.notificationId || + !payload.notificationEpoch || + !Number.isSafeInteger(payload.notificationSeq) || + payload.notificationSeq! < 0 + ) { + return null + } + return JSON.stringify([ + payload.hostFingerprint, + payload.notificationEpoch, + payload.notificationId + ]) +} + +async function readEntries(): Promise { + try { + const raw: unknown = JSON.parse((await AsyncStorage.getItem(STORAGE_KEY)) ?? '[]') + if (!Array.isArray(raw)) { + return [] + } + return raw.filter( + (entry): entry is Entry => + entry !== null && + typeof entry === 'object' && + typeof entry.key === 'string' && + Number.isSafeInteger(entry.seq) && + entry.seq >= 0 && + Number.isFinite(entry.expiresAt) && + entry.expiresAt > Date.now() + ) + } catch { + return [] + } +} + +export async function rememberPushDismissal(payload: OrcaPushPayload): Promise { + const key = eventKey(payload) + if (!key) { + return + } + return queueDismissalOperation(async () => { + if (nativePushDismissal) { + await nativePushDismissal.remember(payload) + return + } + const entries = await readEntries() + const previous = entries.find((entry) => entry.key === key) + const entry = { + key, + seq: Math.max(previous?.seq ?? 0, payload.notificationSeq!), + expiresAt: Date.now() + RETENTION_MS + } + await AsyncStorage.setItem( + STORAGE_KEY, + JSON.stringify([...entries.filter((item) => item.key !== key), entry]) + ) + }) +} + +async function readDismissal(payload: OrcaPushPayload, key: string): Promise { + if (nativePushDismissal) { + return nativePushDismissal.wasDismissed(payload) + } + return (await readEntries()).some( + (entry) => entry.key === key && entry.seq >= payload.notificationSeq! + ) +} + +export async function wasPushDismissed(payload: OrcaPushPayload): Promise { + const key = eventKey(payload) + if (!key) { + return false + } + const precedingWrites = writes + await precedingWrites + const dismissed = await readDismissal(payload, key) + if (dismissed || writes === precedingWrites) { + return dismissed + } + // An overtaking write invalidates a negative snapshot; one queued read cannot be overtaken again. + return queueDismissalOperation(() => readDismissal(payload, key)) +} diff --git a/mobile/src/notifications/push-host-fingerprint.test.ts b/mobile/src/notifications/push-host-fingerprint.test.ts new file mode 100644 index 00000000000..2fc5b44dba1 --- /dev/null +++ b/mobile/src/notifications/push-host-fingerprint.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from 'vitest' +import { sha256 } from '@noble/hashes/sha256' +import { deriveHostFingerprint, resolveHostIdForFingerprint } from './push-host-fingerprint' + +// Why Buffer here: it computes the same value through a completely different +// base64 path than the module's btoa/replace, so the vector is a real cross-check +// of the derivation the desktop and gateway independently perform. +function expectedFingerprint(publicKey: Uint8Array): string { + return Buffer.from(sha256(publicKey)).toString('base64url').slice(0, 16) +} + +const publicKey = Uint8Array.from({ length: 32 }, (_, index) => index) +const publicKeyB64 = Buffer.from(publicKey).toString('base64') + +describe('deriveHostFingerprint', () => { + it('matches base64url(sha256(publicKey)) truncated to 16 chars', () => { + const fingerprint = deriveHostFingerprint(publicKeyB64) + + expect(fingerprint).toBe(expectedFingerprint(publicKey)) + expect(fingerprint).toHaveLength(16) + }) + + it('produces url-safe characters only, so a fingerprint survives a JSON payload', () => { + // 0xff bytes are what push '+' and '/' into a standard base64 digest. + const dense = new Uint8Array(32).fill(0xff) + const fingerprint = deriveHostFingerprint(Buffer.from(dense).toString('base64')) + + expect(fingerprint).toBe(expectedFingerprint(dense)) + expect(fingerprint).toMatch(/^[A-Za-z0-9_-]{16}$/) + }) + + it.each([ + ['a key of the wrong length', Buffer.from(new Uint8Array(16)).toString('base64')], + ['text that is not base64 at all', '!!!not base64!!!'], + ['an empty key', ''] + ])('returns null for %s', (_label, value) => { + expect(deriveHostFingerprint(value)).toBeNull() + }) +}) + +describe('resolveHostIdForFingerprint', () => { + const other = Uint8Array.from({ length: 32 }, (_, index) => index + 1) + const hosts = [ + { id: 'host-corrupt', publicKeyB64: 'not-a-key' }, + { id: 'host-other', publicKeyB64: Buffer.from(other).toString('base64') }, + { id: 'host-1', publicKeyB64 } + ] + + it('maps a push fingerprint back to the paired host id', () => { + expect(resolveHostIdForFingerprint(expectedFingerprint(publicKey), hosts)).toBe('host-1') + }) + + it('returns null for a fingerprint no paired host derives', () => { + expect(resolveHostIdForFingerprint('0123456789abcdef', hosts)).toBeNull() + }) + + it('rejects a fingerprint of the wrong length before hashing anything', () => { + expect( + resolveHostIdForFingerprint(expectedFingerprint(publicKey).slice(0, 8), hosts) + ).toBeNull() + }) +}) diff --git a/mobile/src/notifications/push-host-fingerprint.ts b/mobile/src/notifications/push-host-fingerprint.ts new file mode 100644 index 00000000000..3aa8b739fba --- /dev/null +++ b/mobile/src/notifications/push-host-fingerprint.ts @@ -0,0 +1,58 @@ +import { sha256 } from '@noble/hashes/sha256' + +// Why: a push arrives from the gateway, so it can only name the host by something +// both sides derive independently — base64url(sha256(hostPublicKey)) truncated to +// 16 chars, identical to deriveRelayHostId in +// src/main/runtime/relay/relay-http-client.ts. The phone maps it back to its own +// hostId by re-deriving over each stored host's publicKeyB64. +// +// Base64 is inlined rather than imported (same call as mobile-relay-credential-hash.ts): +// the only shared encoders live in modules that drag in tweetnacl, expo-crypto, or +// the host store, none of which a pure derivation should need. + +const HOST_FINGERPRINT_LENGTH = 16 + +function decodeBase64(value: string): Uint8Array | null { + try { + const binary = atob(value) + const bytes = new Uint8Array(binary.length) + for (let index = 0; index < binary.length; index++) { + bytes[index] = binary.charCodeAt(index) + } + return bytes + } catch { + return null + } +} + +function encodeBase64Url(bytes: Uint8Array): string { + let binary = '' + for (const byte of bytes) { + binary += String.fromCharCode(byte) + } + return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') +} + +/** Null when the stored key is unreadable, so a corrupt host entry can't shadow a real match. */ +export function deriveHostFingerprint(publicKeyB64: string): string | null { + const publicKey = decodeBase64(publicKeyB64) + if (!publicKey || publicKey.length !== 32) { + return null + } + return encodeBase64Url(sha256(publicKey)).slice(0, HOST_FINGERPRINT_LENGTH) +} + +export function resolveHostIdForFingerprint( + fingerprint: string, + hosts: readonly { readonly id: string; readonly publicKeyB64: string }[] +): string | null { + if (fingerprint.length !== HOST_FINGERPRINT_LENGTH) { + return null + } + for (const host of hosts) { + if (deriveHostFingerprint(host.publicKeyB64) === fingerprint) { + return host.id + } + } + return null +} diff --git a/mobile/src/notifications/push-notification-identity.test.ts b/mobile/src/notifications/push-notification-identity.test.ts new file mode 100644 index 00000000000..df3dfd9d152 --- /dev/null +++ b/mobile/src/notifications/push-notification-identity.test.ts @@ -0,0 +1,25 @@ +import { expect, it } from 'vitest' +import { + readPushNotificationIdentity, + type PushNotificationIdentity +} from './push-notification-identity' + +it('reads a bounded individual notification identity', () => { + const identity: PushNotificationIdentity = { + notificationId: 'agent:one', + notificationEpoch: 'epoch-1', + notificationSeq: 7 + } + expect(readPushNotificationIdentity(identity)).toEqual(identity) +}) + +it('rejects incomplete or non-integral notification identities', () => { + expect(readPushNotificationIdentity({ notificationId: 'agent:one' })).toBeNull() + expect( + readPushNotificationIdentity({ + notificationId: 'agent:one', + notificationEpoch: 'epoch-1', + notificationSeq: 1.5 + }) + ).toBeNull() +}) diff --git a/mobile/src/notifications/push-notification-identity.ts b/mobile/src/notifications/push-notification-identity.ts new file mode 100644 index 00000000000..b8e9e73a34b --- /dev/null +++ b/mobile/src/notifications/push-notification-identity.ts @@ -0,0 +1,26 @@ +export type PushNotificationIdentity = { + notificationId: string + notificationEpoch: string + notificationSeq: number +} + +export function readPushNotificationIdentity(value: unknown): PushNotificationIdentity | null { + if (!value || typeof value !== 'object') { + return null + } + const item = value as PushNotificationIdentity + return typeof item.notificationId === 'string' && + item.notificationId.length > 0 && + item.notificationId.length <= 2048 && + typeof item.notificationEpoch === 'string' && + item.notificationEpoch.length > 0 && + item.notificationEpoch.length <= 128 && + Number.isSafeInteger(item.notificationSeq) && + item.notificationSeq >= 0 + ? { + notificationId: item.notificationId, + notificationEpoch: item.notificationEpoch, + notificationSeq: item.notificationSeq + } + : null +} diff --git a/mobile/src/notifications/push-payload.ts b/mobile/src/notifications/push-payload.ts new file mode 100644 index 00000000000..bcdbf0f6073 --- /dev/null +++ b/mobile/src/notifications/push-payload.ts @@ -0,0 +1,43 @@ +// Why two shapes: APNs nests Orca's fields under `orca` beside `aps`, while FCM +// carries them flat in `data` as strings. Both reach JS as the notification's +// `content.data`, so the reader accepts either and coerces the numeric fields. +export type OrcaPushPayload = { + readonly kind?: 'alert' | 'dismiss' + readonly hostFingerprint: string + readonly notificationId?: string + readonly notificationSeq?: number + readonly notificationEpoch?: string + readonly paneKey?: string + readonly worktreeId?: string +} + +function readString(value: unknown): string | undefined { + return typeof value === 'string' && value.length > 0 ? value : undefined +} + +function readSeq(value: unknown): number | undefined { + const raw = typeof value === 'number' ? value : Number(readString(value)) + return Number.isFinite(raw) ? raw : undefined +} + +export function readOrcaPushPayload(data: unknown): OrcaPushPayload | null { + if (!data || typeof data !== 'object') { + return null + } + const nested = (data as { orca?: unknown }).orca + const record = (nested && typeof nested === 'object' ? nested : data) as Record + // The fingerprint is what makes this a gateway push; locally scheduled data never has one. + const hostFingerprint = readString(record.hostFingerprint) + if (!hostFingerprint) { + return null + } + return { + hostFingerprint, + ...(record.kind === 'dismiss' || record.kind === 'alert' ? { kind: record.kind } : {}), + notificationId: readString(record.notificationId), + notificationSeq: readSeq(record.notificationSeq), + notificationEpoch: readString(record.notificationEpoch), + paneKey: readString(record.paneKey), + worktreeId: readString(record.worktreeId) + } +} diff --git a/mobile/src/notifications/push-preference-update.test.ts b/mobile/src/notifications/push-preference-update.test.ts new file mode 100644 index 00000000000..11f137fb38f --- /dev/null +++ b/mobile/src/notifications/push-preference-update.test.ts @@ -0,0 +1,86 @@ +vi.mock('./desktop-notification-channel', () => ({ + ensureDesktopNotificationChannel: vi.fn(async () => {}) +})) +import { AppState } from 'react-native' +import { beforeEach, expect, it, vi } from 'vitest' +import { + attachPushRegistration, + resetPushRegistrationForTests, + setNotificationDeliveryPreferences, + NOTIFICATIONS_REMOTE_PUSH_CAPABILITY +} from './push-registration' +import { DEFAULT_NOTIFICATION_DELIVERY } from './notification-delivery-preferences' + +const storage = new Map() +vi.mock('@react-native-async-storage/async-storage', () => ({ + default: { + getItem: vi.fn(async (key: string) => storage.get(key) ?? null), + setItem: vi.fn(async (key: string, value: string) => { + storage.set(key, value) + }) + } +})) +vi.mock('react-native', () => ({ + AppState: { currentState: 'active', addEventListener: vi.fn(() => ({ remove: vi.fn() })) } +})) + +vi.mock('./push-token', () => ({ + getDevicePushToken: vi.fn(async () => ({ + platform: 'ios', + token: 'a'.repeat(64), + apnsEnvironment: 'sandbox' + })), + addPushTokenListener: vi.fn() +})) + +beforeEach(() => { + AppState.currentState = 'active' + resetPushRegistrationForTests() + storage.clear() + storage.set('orca:pushServiceNotificationsEnabled', 'true') +}) + +it('replaces an in-flight registration with the latest away and sound preferences', async () => { + const calls: { method: string; params: unknown }[] = [] + let finishFirst: ((value: unknown) => void) | undefined + const client = { + sendRequest: vi.fn(async (method: string, params?: unknown) => { + calls.push({ method, params }) + if (method === 'status.get') { + return { ok: true, result: { capabilities: [NOTIFICATIONS_REMOTE_PUSH_CAPABILITY] } } + } + if (method === 'notifications.registerPush') { + if (!finishFirst) { + return new Promise((resolve) => { + finishFirst = resolve + }) + } + return { ok: true, result: { registered: true, registrationId: 'new' } } + } + return { ok: true, result: { unregistered: true } } + }) + } + const detach = attachPushRegistration('host', client as never) + await vi.waitFor(() => expect(finishFirst).toBeDefined()) + const update = setNotificationDeliveryPreferences({ + ...DEFAULT_NOTIFICATION_DELIVERY, + onlyWhenDesktopAway: false, + sound: false + }) + finishFirst!({ ok: true, result: { registered: true, registrationId: 'old' } }) + await update + await vi.waitFor(() => + expect( + calls.filter((call) => call.method === 'notifications.registerPush').length + ).toBeGreaterThan(1) + ) + const latest = calls.findLast((call) => call.method === 'notifications.registerPush') + expect(latest?.params).toMatchObject({ + filter: { + onlyWhenDesktopAway: false, + sound: false + } + }) + expect(calls.some((call) => call.method === 'notifications.unregisterPush')).toBe(true) + detach() +}) diff --git a/mobile/src/notifications/push-receive.test.ts b/mobile/src/notifications/push-receive.test.ts new file mode 100644 index 00000000000..8bcaef51e83 --- /dev/null +++ b/mobile/src/notifications/push-receive.test.ts @@ -0,0 +1,274 @@ +import AsyncStorage from '@react-native-async-storage/async-storage' +import { AppState } from 'react-native' +import { setNotificationViewingWorkspace } from './notification-viewing-policy' +vi.mock('./push-tray-dismissal', () => ({ dismissPresentedPushNotification: vi.fn() })) +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { sha256 } from '@noble/hashes/sha256' +import { loadHostCatalog } from '../transport/host-store' +import type { HostCatalogEntry } from '../transport/types' +import { getNotificationNavigationTarget } from './notification-routing' +import { + foregroundNotificationBehavior, + canPresentForegroundPush, + isRemotePushTrigger, + pushNotificationRouteData, + resetForegroundPushClaimsForTests +} from './push-receive' + +async function shouldSuppressForegroundPush(data: unknown): Promise { + return !(await foregroundNotificationBehavior({ request: { content: { data } } })) + .shouldShowBanner +} + +vi.mock('react-native', () => ({ AppState: { currentState: 'background' } })) +vi.mock('../transport/host-store', () => ({ loadHostCatalog: vi.fn() })) +const storage = vi.hoisted(() => new Map()) +vi.mock('@react-native-async-storage/async-storage', () => ({ + default: { + getItem: vi.fn(async (key: string) => storage.get(key) ?? null), + setItem: vi.fn(async (key: string, value: string) => storage.set(key, value)) + } +})) + +const publicKeyB64 = Buffer.alloc(32, 1).toString('base64') +const hostFingerprint = Buffer.from(sha256(Buffer.alloc(32, 1))) + .toString('base64url') + .slice(0, 16) +const hosts = [{ id: 'host-1', publicKeyB64 }] as unknown as HostCatalogEntry[] +const otherPublicKeyB64 = Buffer.alloc(32, 2).toString('base64') +const otherHostFingerprint = Buffer.from(sha256(Buffer.alloc(32, 2))) + .toString('base64url') + .slice(0, 16) + +function apnsData(orca: Record): unknown { + return { aps: { alert: { title: 'Orca', body: 'Agent needs input' } }, orca } +} +function fcmData(orca: Record): unknown { + return Object.fromEntries(Object.entries(orca).map(([key, value]) => [key, String(value)])) +} + +beforeEach(() => { + vi.clearAllMocks() + AppState.currentState = 'background' + setNotificationViewingWorkspace(null) + storage.clear() + storage.set('orca:pushServiceNotificationsEnabled', 'true') + resetForegroundPushClaimsForTests() + vi.mocked(loadHostCatalog).mockResolvedValue([ + ...hosts, + { id: 'host-2', publicKeyB64: otherPublicKeyB64 } + ] as unknown as HostCatalogEntry[]) +}) + +describe('shouldSuppressForegroundPush', () => { + const push = () => + apnsData({ + hostFingerprint, + notificationId: 'agent:one', + notificationSeq: 7, + notificationEpoch: 'epoch-1' + }) + + it('allows one eligible native push and suppresses an in-process duplicate', async () => { + await expect(shouldSuppressForegroundPush(push())).resolves.toBe(false) + await expect(shouldSuppressForegroundPush(push())).resolves.toBe(true) + }) + + it('reads flat FCM fields and allows the first native push', async () => { + await expect( + shouldSuppressForegroundPush( + fcmData({ + hostFingerprint, + notificationId: 'agent:one', + notificationSeq: 8, + notificationEpoch: 'epoch-1' + }) + ) + ).resolves.toBe(false) + }) + + it('deduplicates ID-less bells by host, epoch, and valid sequence', async () => { + const bell = (overrides: Record = {}) => + apnsData({ + hostFingerprint, + source: 'terminal-bell', + notificationSeq: 4, + notificationEpoch: 'epoch-1', + ...overrides + }) + await expect(shouldSuppressForegroundPush(bell())).resolves.toBe(false) + await expect(shouldSuppressForegroundPush(bell())).resolves.toBe(true) + await expect(shouldSuppressForegroundPush(bell({ notificationSeq: 5 }))).resolves.toBe(false) + await expect( + shouldSuppressForegroundPush(bell({ notificationEpoch: 'epoch-2' })) + ).resolves.toBe(false) + await expect( + shouldSuppressForegroundPush(bell({ hostFingerprint: otherHostFingerprint })) + ).resolves.toBe(false) + }) + + it('does not claim invalid sequence values as duplicate identities', async () => { + const invalid = apnsData({ + hostFingerprint, + source: 'plugin', + notificationSeq: 1.5, + notificationEpoch: 'epoch-1' + }) + await expect(shouldSuppressForegroundPush(invalid)).resolves.toBe(false) + await expect(shouldSuppressForegroundPush(invalid)).resolves.toBe(false) + }) + + it('suppresses pushes for an unpaired host', async () => { + vi.mocked(loadHostCatalog).mockResolvedValue([]) + await expect( + shouldSuppressForegroundPush(apnsData({ hostFingerprint, notificationSeq: 1 })) + ).resolves.toBe(true) + }) + + it('suppresses a push after a matching persisted dismissal', async () => { + const { rememberPushDismissal } = await import('./push-dismissal-watermarks') + const payload = { + hostFingerprint, + notificationId: 'dismissed', + notificationSeq: 2, + notificationEpoch: 'epoch-1' + } + await rememberPushDismissal(payload) + await expect(shouldSuppressForegroundPush(apnsData(payload))).resolves.toBe(true) + }) + + it('fails closed for recognized pushes when suppression checks throw', async () => { + const dismissals = await import('./push-dismissal-watermarks') + const dismissalSpy = vi + .spyOn(dismissals, 'wasPushDismissed') + .mockRejectedValueOnce(new Error('dismissal read failed')) + await expect( + foregroundNotificationBehavior({ request: { content: { data: push() } } }) + ).resolves.toMatchObject({ shouldShowBanner: false, shouldShowList: false }) + dismissalSpy.mockRestore() + }) + + it('keeps unrelated notifications visible when suppression checks throw', async () => { + const dismissals = await import('./push-dismissal-watermarks') + const dismissalSpy = vi + .spyOn(dismissals, 'wasPushDismissed') + .mockRejectedValue(new Error('dismissal read failed')) + await expect( + foregroundNotificationBehavior({ + request: { content: { data: { title: 'Other app notification' } } } + }) + ).resolves.toMatchObject({ shouldShowBanner: true, shouldShowList: true }) + dismissalSpy.mockRestore() + }) +}) + +describe('pushNotificationRouteData', () => { + it('routes a tap by mapping the fingerprint to the paired host id', () => { + const data = pushNotificationRouteData( + apnsData({ hostFingerprint, worktreeId: 'repo::/feature', source: 'agent-task-complete' }), + hosts + ) + expect(getNotificationNavigationTarget(data, { knownHostIds: new Set(['host-1']) })).toEqual({ + hostId: 'host-1', + sessionTarget: { + name: '[hostId]/session/[worktreeId]', + params: { hostId: 'host-1', worktreeId: 'repo::/feature' } + } + }) + }) + + it('maps a push without a worktree to the host screen', () => { + const data = pushNotificationRouteData( + fcmData({ hostFingerprint, source: 'terminal-bell' }), + hosts + ) + expect(getNotificationNavigationTarget(data)).toEqual({ hostId: 'host-1', sessionTarget: null }) + }) + + it('keeps local data untouched and rejects an unresolvable remote fingerprint', () => { + const local = { hostId: 'host-9', source: 'agent-task-complete' } + expect(pushNotificationRouteData(local, hosts)).toBe(local) + expect( + pushNotificationRouteData( + { hostId: 'host-1', orca: { hostFingerprint: 'unknown' } }, + hosts, + true + ) + ).toBeNull() + }) + + it('recognises only provider-delivered triggers', () => { + expect(isRemotePushTrigger({ type: 'push' })).toBe(true) + expect(isRemotePushTrigger({ type: 'timeInterval' })).toBe(false) + }) +}) + +it('uses one delivery snapshot for sound and viewing even when settings change during host lookup', async () => { + AppState.currentState = 'active' + setNotificationViewingWorkspace({ hostId: 'host-1', worktreeId: 'folder' }) + storage.set( + 'orca:notificationDeliveryPreferences', + JSON.stringify({ + sound: false, + suppressWhileViewing: false + }) + ) + vi.mocked(loadHostCatalog).mockImplementationOnce(async () => { + storage.set( + 'orca:notificationDeliveryPreferences', + JSON.stringify({ + sound: true, + suppressWhileViewing: true + }) + ) + return hosts + }) + const behavior = await foregroundNotificationBehavior({ + request: { + content: { + data: apnsData({ + hostFingerprint, + worktreeId: 'folder', + notificationEpoch: 'snapshot', + notificationSeq: 1 + }) + } + } + }) + expect(behavior).toMatchObject({ shouldShowBanner: true, shouldPlaySound: false }) + expect( + vi + .mocked(AsyncStorage.getItem) + .mock.calls.filter(([key]) => key === 'orca:notificationDeliveryPreferences') + ).toHaveLength(1) +}) + +it.each(['apns', 'fcm'])( + 'routes %s pane payload to the correct host, workspace and pane', + (provider) => { + const paneKey = 'tab-b:11111111-1111-4111-8111-111111111111' + const payload = { hostFingerprint, worktreeId: 'folder:/work', paneKey } + const data = provider === 'apns' ? { orca: payload } : payload + const routed = pushNotificationRouteData(data, [{ id: 'host', publicKeyB64 }], true) + expect(getNotificationNavigationTarget(routed)?.sessionTarget?.params).toEqual({ + hostId: 'host', + worktreeId: 'folder:/work', + paneKey + }) + } +) + +it('preflight does not consume the final presentation claim and observes later dismissals', async () => { + const payload = { + hostFingerprint, + notificationId: 'preflight', + notificationEpoch: 'epoch', + notificationSeq: 4 + } + await expect(canPresentForegroundPush(payload)).resolves.toBe(true) + await expect(shouldSuppressForegroundPush(apnsData(payload))).resolves.toBe(false) + const { rememberPushDismissal } = await import('./push-dismissal-watermarks') + await rememberPushDismissal(payload) + await expect(canPresentForegroundPush(payload)).resolves.toBe(false) + await expect(shouldSuppressForegroundPush(apnsData(payload))).resolves.toBe(true) +}) diff --git a/mobile/src/notifications/push-receive.ts b/mobile/src/notifications/push-receive.ts new file mode 100644 index 00000000000..b106ec555f2 --- /dev/null +++ b/mobile/src/notifications/push-receive.ts @@ -0,0 +1,152 @@ +import { wasPushDismissed } from './push-dismissal-watermarks' +import { dismissPresentedPushNotification } from './push-tray-dismissal' +import { shouldSuppressNotificationWhileViewing } from './notification-viewing-policy' +import { loadPushNotificationsEnabled } from '../storage/preferences' +import { loadHostCatalog } from '../transport/host-store' +import { resolveHostIdForFingerprint } from './push-host-fingerprint' +import { readOrcaPushPayload, type OrcaPushPayload } from './push-payload' +import type { Notification, NotificationBehavior } from 'expo-notifications' +import { readNativeNotificationData } from './native-notification-data' +import { loadNotificationDeliveryPreferences } from './notification-delivery-preferences' + +const RECENT_FOREGROUND_PUSH_CAP = 512 +const recentForegroundPushes = new Set() + +function claimForegroundPush(payload: OrcaPushPayload): boolean { + const seq = payload.notificationSeq + if ( + !payload.notificationEpoch || + typeof seq !== 'number' || + !Number.isSafeInteger(seq) || + seq < 0 + ) { + return true + } + const key = JSON.stringify([ + payload.hostFingerprint, + payload.notificationEpoch, + payload.notificationId ?? null, + seq + ]) + if (recentForegroundPushes.has(key)) { + return false + } + recentForegroundPushes.add(key) + if (recentForegroundPushes.size > RECENT_FOREGROUND_PUSH_CAP) { + const oldest = recentForegroundPushes.values().next().value + if (oldest !== undefined) { + recentForegroundPushes.delete(oldest) + } + } + return true +} + +export function resetForegroundPushClaimsForTests(): void { + recentForegroundPushes.clear() +} + +export async function foregroundNotificationBehavior( + notification: Pick +): Promise { + const data = readNativeNotificationData(notification.request) + const payload = readOrcaPushPayload(data) + const preferences = await loadNotificationDeliveryPreferences() + // Unrecognized notifications retain normal behavior; recognized pushes fail closed + // when consent, host, viewing, or dismissal checks cannot complete. + const ineligible = await shouldSuppressForegroundPush( + payload, + preferences.suppressWhileViewing + ).catch(() => payload !== null) + const suppressed = ineligible || (payload !== null && !claimForegroundPush(payload)) + return { + shouldShowBanner: !suppressed, + shouldShowList: !suppressed, + shouldPlaySound: !suppressed && preferences.sound, + shouldSetBadge: false + } +} + +export async function canPresentForegroundPush(payload: OrcaPushPayload): Promise { + const preferences = await loadNotificationDeliveryPreferences() + return !(await shouldSuppressForegroundPush(payload, preferences.suppressWhileViewing)) +} + +async function resolvePushHostId(payload: OrcaPushPayload): Promise { + const hosts = await loadHostCatalog().catch(() => []) + return resolveHostIdForFingerprint(payload.hostFingerprint, hosts) +} + +async function shouldSuppressForegroundPush( + payload: OrcaPushPayload | null, + suppressWhileViewing: boolean +): Promise { + if (!payload) { + return false + } + if (payload.kind === 'dismiss') { + if (payload.notificationId) { + await dismissPresentedPushNotification( + payload.notificationId, + payload.hostFingerprint, + payload + ) + } + return true + } + const hostId = await resolvePushHostId(payload) + // Why suppressed rather than shown: the only pushes that outlive their host are + // ones a gateway registration still holds after a removal whose unregister never + // reached the desktop. A banner naming a host this phone no longer has cannot be + // tapped anywhere, so it is noise the user cannot act on or turn off per-host. + if (!hostId) { + return true + } + if (!(await loadPushNotificationsEnabled())) { + return true + } + if (shouldSuppressNotificationWhileViewing(payload, hostId, suppressWhileViewing)) { + return true + } + // Keep this last: a socket/native dismissal may land during any preference or host read. + return wasPushDismissed(payload) +} + +/** Whether the OS says a notification came from a provider rather than this app. */ +export function isRemotePushTrigger(trigger: unknown): boolean { + return ( + typeof trigger === 'object' && + trigger !== null && + (trigger as { readonly type?: unknown }).type === 'push' + ) +} + +/** + * Notification data a tap can route with: the gateway names the host by fingerprint, + * so it is mapped back to this device's hostId. Locally scheduled data passes + * through untouched, which is what keeps its taps on their existing path. + * + * Why null and not the raw data when the fingerprint does not resolve: a gateway + * payload is attacker-adjacent input, and passing it on would let a stray `hostId` + * beside the `orca` block route a tap at a host the push never named. A remote + * push with no fingerprint at all is the same input minus the block, so it is + * unrouted too rather than handed to the local path as if this app scheduled it. + */ +export function pushNotificationRouteData( + data: unknown, + hosts: readonly { readonly id: string; readonly publicKeyB64: string }[], + remote = false +): unknown { + const payload = readOrcaPushPayload(data) + if (!payload) { + return remote ? null : data + } + const hostId = resolveHostIdForFingerprint(payload.hostFingerprint, hosts) + if (!hostId) { + return null + } + return { + hostId, + ...(payload.paneKey ? { paneKey: payload.paneKey } : {}), + ...(payload.worktreeId ? { worktreeId: payload.worktreeId } : {}) + } +} diff --git a/mobile/src/notifications/push-registration-cancellation.test.ts b/mobile/src/notifications/push-registration-cancellation.test.ts new file mode 100644 index 00000000000..92acc892886 --- /dev/null +++ b/mobile/src/notifications/push-registration-cancellation.test.ts @@ -0,0 +1,263 @@ +import { ensureDesktopNotificationChannel } from './desktop-notification-channel' +vi.mock('./desktop-notification-channel', () => ({ + ensureDesktopNotificationChannel: vi.fn(async () => {}) +})) +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { + attachPushRegistration, + resetPushRegistrationForTests, + setRemotePushEnabled, + startPushTokenSync, + unregisterPushForRemovedHost, + NOTIFICATIONS_REMOTE_PUSH_CAPABILITY +} from './push-registration' +import { addPushTokenListener, getDevicePushToken } from './push-token' +import type { MobilePushToken } from './push-token' + +import AsyncStorage from '@react-native-async-storage/async-storage' +import { removeHost } from '../transport/host-store' +import { removeHostAndCloseClient } from '../transport/host-removal-lifecycle' +vi.mock('../transport/host-store', () => ({ removeHost: vi.fn() })) +vi.mock('./mobile-push-lease-renewal', () => ({ startMobilePushLeaseRenewal: () => () => {} })) + +const storage = new Map() +vi.mock('@react-native-async-storage/async-storage', () => ({ + default: { + getItem: async (key: string) => storage.get(key) ?? null, + setItem: vi.fn(async (key: string, value: string) => { + storage.set(key, value) + }) + } +})) +vi.mock('react-native', () => ({ AppState: { currentState: 'active' } })) +vi.mock('./push-token', () => ({ getDevicePushToken: vi.fn(), addPushTokenListener: vi.fn() })) +const token: MobilePushToken = { + platform: 'ios', + token: 'a'.repeat(64), + apnsEnvironment: 'sandbox' +} +const records = () => JSON.parse(storage.get('orca:remotePushHostRegistrations') ?? '{}') +function deferred() { + let resolve!: (value: T) => void + const promise = new Promise((done) => { + resolve = done + }) + return { promise, resolve } +} +function client( + register: () => Promise = async () => ({ ok: true, result: { registered: true } }) +) { + return { + sendRequest: vi.fn(async (method: string) => { + if (method === 'status.get') { + return { ok: true, result: { capabilities: [NOTIFICATIONS_REMOTE_PUSH_CAPABILITY] } } + } + if (method === 'notifications.registerPush') { + return register() + } + return { ok: true, result: { unregistered: true } } + }) + } +} +beforeEach(() => { + vi.clearAllMocks() + resetPushRegistrationForTests() + storage.clear() + storage.set('orca:pushServiceNotificationsEnabled', 'true') + vi.mocked(getDevicePushToken).mockResolvedValue(token) + vi.mocked(addPushTokenListener).mockReturnValue(() => {}) + vi.mocked(removeHost).mockReset() +}) + +afterEach(() => vi.useRealTimers()) + +it('does not resurrect a removed host when its registration response arrives late', async () => { + const pending = deferred() + const connection = client(() => pending.promise) + attachPushRegistration('host', connection as never) + await vi.waitFor(() => + expect(connection.sendRequest).toHaveBeenCalledWith( + 'notifications.registerPush', + expect.anything(), + expect.anything() + ) + ) + const removal = unregisterPushForRemovedHost('host') + expect(connection.sendRequest.mock.calls.map(([method]) => method)).not.toContain( + 'notifications.unregisterPush' + ) + pending.resolve({ ok: true, result: { registered: true } }) + await removal + await new Promise((resolve) => setTimeout(resolve, 10)) + expect(records().registeredHostIds).toEqual([]) + expect(records().pendingUnregisterHostIds).toEqual([]) +}) + +it('does not start registration after removal while native token lookup was pending', async () => { + const pending = deferred() + vi.mocked(getDevicePushToken).mockReturnValueOnce(pending.promise) + const connection = client() + attachPushRegistration('host', connection as never) + await vi.waitFor(() => expect(getDevicePushToken).toHaveBeenCalled()) + await unregisterPushForRemovedHost('host') + pending.resolve(token) + await new Promise((resolve) => setTimeout(resolve, 10)) + expect(connection.sendRequest.mock.calls.map(([method]) => method)).not.toContain( + 'notifications.registerPush' + ) +}) + +it('does not register with stale consent after the user disables notifications during token lookup', async () => { + const pending = deferred() + vi.mocked(getDevicePushToken).mockReturnValueOnce(pending.promise) + const connection = client() + attachPushRegistration('host', connection as never) + await vi.waitFor(() => expect(getDevicePushToken).toHaveBeenCalled()) + const disabled = setRemotePushEnabled(false) + pending.resolve(token) + await disabled + await vi.waitFor(() => + expect(connection.sendRequest.mock.calls.map(([method]) => method)).toContain( + 'notifications.unregisterPush' + ) + ) + expect(connection.sendRequest.mock.calls.map(([method]) => method)).not.toContain( + 'notifications.registerPush' + ) +}) + +it('waits for the Android notification channel before registering a token', async () => { + const pending = deferred() + vi.mocked(ensureDesktopNotificationChannel).mockReturnValueOnce(pending.promise) + const connection = client() + attachPushRegistration('host', connection as never) + await vi.waitFor(() => expect(ensureDesktopNotificationChannel).toHaveBeenCalled()) + expect(getDevicePushToken).not.toHaveBeenCalled() + expect(connection.sendRequest.mock.calls.map(([method]) => method)).not.toContain( + 'notifications.registerPush' + ) + pending.resolve() + await vi.waitFor(() => + expect(connection.sendRequest.mock.calls.map(([method]) => method)).toContain( + 'notifications.registerPush' + ) + ) +}) + +it('completes disable while native token acquisition remains unresolved, and rejects late tokens', async () => { + vi.useFakeTimers() + storage.set( + 'orca:remotePushHostRegistrations', + JSON.stringify({ + registeredHostIds: ['host'], + pendingUnregisterHostIds: [] + }) + ) + const pending = deferred() + vi.mocked(getDevicePushToken).mockReturnValueOnce(pending.promise) + const connection = client() + const stop = startPushTokenSync() + attachPushRegistration('host', connection as never) + await vi.advanceTimersByTimeAsync(0) + expect(getDevicePushToken).toHaveBeenCalledOnce() + await setRemotePushEnabled(false) + expect(records().pendingUnregisterHostIds).toEqual(['host']) + expect(connection.sendRequest.mock.calls.map(([method]) => method)).not.toContain( + 'notifications.unregisterPush' + ) + await vi.advanceTimersByTimeAsync(2_000) + expect(storage.get('orca:pushServiceNotificationsEnabled')).toBe('false') + expect(records()).toEqual({ registeredHostIds: [], pendingUnregisterHostIds: [] }) + expect(connection.sendRequest.mock.calls.map(([method]) => method)).toContain( + 'notifications.unregisterPush' + ) + pending.resolve(token) + vi.mocked(addPushTokenListener).mock.calls[0]![0](token) + await vi.advanceTimersByTimeAsync(0) + expect(connection.sendRequest.mock.calls.map(([method]) => method)).not.toContain( + 'notifications.registerPush' + ) + stop() +}) + +it('restores registration without reconnect after metadata removal fails, retaining detach ownership', async () => { + const connection = client() + const detach = attachPushRegistration('host', connection as never) + await vi.waitFor(() => expect(records().registeredHostIds).toEqual(['host'])) + vi.mocked(removeHost).mockRejectedValueOnce(new Error('metadata failure')) + const close = vi.fn() + await expect(removeHostAndCloseClient('host', close)).rejects.toThrow('metadata failure') + expect(close).not.toHaveBeenCalled() + await vi.waitFor(() => expect(records().registeredHostIds).toEqual(['host'])) + expect(connection.sendRequest.mock.calls.map(([method]) => method)).toEqual([ + 'status.get', + 'notifications.registerPush', + 'notifications.unregisterPush', + 'status.get', + 'notifications.registerPush' + ]) + detach() + connection.sendRequest.mockClear() + await setRemotePushEnabled(true) + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(connection.sendRequest).not.toHaveBeenCalled() +}) + +it('does not revive a connection detached while metadata removal was pending', async () => { + const connection = client() + const detach = attachPushRegistration('host', connection as never) + await vi.waitFor(() => expect(records().registeredHostIds).toEqual(['host'])) + const commit = deferred() + vi.mocked(removeHost).mockImplementationOnce(async () => { + await commit.promise + throw new Error('metadata failure') + }) + const removal = expect(removeHostAndCloseClient('host', vi.fn())).rejects.toThrow( + 'metadata failure' + ) + await vi.waitFor(() => expect(removeHost).toHaveBeenCalled()) + detach() + connection.sendRequest.mockClear() + commit.resolve() + await removal + await setRemotePushEnabled(true) + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(connection.sendRequest).not.toHaveBeenCalled() +}) + +it('retires late registration ownership before a failed removal restores a fresh registration', async () => { + const oldRegister = deferred() + const newRegister = deferred() + const register = vi + .fn() + .mockReturnValueOnce(oldRegister.promise) + .mockReturnValue(newRegister.promise) + const connection = client(register) + attachPushRegistration('host', connection as never) + await vi.waitFor(() => expect(register).toHaveBeenCalledOnce()) + vi.mocked(removeHost).mockRejectedValueOnce(new Error('metadata failure')) + const removal = expect(removeHostAndCloseClient('host', vi.fn())).rejects.toThrow( + 'metadata failure' + ) + expect(connection.sendRequest.mock.calls.map(([method]) => method)).not.toContain( + 'notifications.unregisterPush' + ) + oldRegister.resolve({ ok: true, result: { registered: true } }) + await removal + await vi.waitFor(() => expect(register).toHaveBeenCalledTimes(2)) + expect(records().registeredHostIds).toEqual([]) + newRegister.resolve({ ok: true, result: { registered: true } }) + await vi.waitFor(() => expect(records().registeredHostIds).toEqual(['host'])) +}) + +it('still commits removal when unregister and cleanup storage fail', async () => { + const connection = client() + attachPushRegistration('host', connection as never) + await vi.waitFor(() => expect(records().registeredHostIds).toEqual(['host'])) + connection.sendRequest.mockRejectedValueOnce(new Error('socket closed')) + vi.mocked(AsyncStorage.setItem).mockRejectedValueOnce(new Error('disk full')) + const close = vi.fn() + await removeHostAndCloseClient('host', close) + expect(removeHost).toHaveBeenCalledWith('host') + expect(close).toHaveBeenCalledWith('host') +}) diff --git a/mobile/src/notifications/push-registration.test.ts b/mobile/src/notifications/push-registration.test.ts new file mode 100644 index 00000000000..975c840133c --- /dev/null +++ b/mobile/src/notifications/push-registration.test.ts @@ -0,0 +1,423 @@ +vi.mock('@react-native-async-storage/async-storage', () => ({ + default: { getItem: vi.fn(async () => null) } +})) +vi.mock('./desktop-notification-channel', () => ({ + ensureDesktopNotificationChannel: vi.fn(async () => {}) +})) +import { AppState } from 'react-native' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { RpcClient, SendRequestOptions } from '../transport/rpc-client' +import type { RpcResponse } from '../transport/types' +import { + loadPushNotificationsEnabled, + loadRemotePushHostRegistrations, + savePushNotificationsEnabled, + saveRemotePushHostRegistrations, + type RemotePushHostRegistrations +} from '../storage/preferences' +import { addPushTokenListener, getDevicePushToken, type MobilePushToken } from './push-token' +import { + NOTIFICATIONS_REMOTE_PUSH_CAPABILITY, + attachPushRegistration, + resetPushRegistrationForTests, + setRemotePushEnabled, + startPushTokenSync, + unregisterPushForRemovedHost +} from './push-registration' + +vi.mock('../storage/preferences', () => ({ + loadPushNotificationsEnabled: vi.fn(), + savePushNotificationsEnabled: vi.fn(), + loadRemotePushHostRegistrations: vi.fn(), + saveRemotePushHostRegistrations: vi.fn() +})) + +vi.mock('react-native', () => ({ + AppState: { currentState: 'active', addEventListener: vi.fn(() => ({ remove: vi.fn() })) } +})) + +vi.mock('./push-token', () => ({ + getDevicePushToken: vi.fn(), + addPushTokenListener: vi.fn() +})) + +const IOS_TOKEN: MobilePushToken = { + platform: 'ios', + token: 'a'.repeat(64), + apnsEnvironment: 'production' +} + +// Every await in the module resolves immediately, so one macrotask drains the whole +// per-host reconcile chain no matter how many hops deep it happens to be. +function flush(): Promise { + return new Promise((resolve) => setTimeout(resolve, 0)) +} + +function ok(result: unknown): RpcResponse { + return { id: 'req', ok: true, result, _meta: { runtimeId: 'runtime-1' } } +} + +type SentRequest = { method: string; params?: unknown; options?: SendRequestOptions } + +function makeClient(capabilities: readonly string[]): { + client: Pick + sent: SentRequest[] +} { + const sent: SentRequest[] = [] + const client = { + sendRequest: vi.fn(async (method: string, params?: unknown, options?: SendRequestOptions) => { + sent.push({ method, params, options }) + if (method === 'status.get') { + return ok({ capabilities: [...capabilities] }) + } + if (method === 'notifications.registerPush') { + return ok({ registered: true, registrationId: 'registration-1' }) + } + if (method === 'notifications.unregisterPush') { + return ok({ unregistered: true }) + } + return ok(null) + }) + } + return { client, sent } +} + +function methodsIn(sent: SentRequest[]): string[] { + return sent.map((request) => request.method) +} + +let enabled = false +let stored: RemotePushHostRegistrations + +beforeEach(() => { + vi.clearAllMocks() + AppState.currentState = 'active' + resetPushRegistrationForTests() + enabled = false + stored = { registeredHostIds: [], pendingUnregisterHostIds: [] } + + vi.mocked(loadPushNotificationsEnabled).mockImplementation(async () => enabled) + vi.mocked(savePushNotificationsEnabled).mockImplementation(async (value) => { + enabled = value + }) + vi.mocked(loadRemotePushHostRegistrations).mockImplementation(async () => stored) + vi.mocked(saveRemotePushHostRegistrations).mockImplementation(async (value) => { + stored = value + }) + vi.mocked(getDevicePushToken).mockResolvedValue(IOS_TOKEN) +}) + +describe('push registration capability gating', () => { + it('registers a connected host that advertises remote push', async () => { + const { client, sent } = makeClient([NOTIFICATIONS_REMOTE_PUSH_CAPABILITY]) + await setRemotePushEnabled(true) + + attachPushRegistration('host-1', client) + await flush() + + const register = sent.find((request) => request.method === 'notifications.registerPush') + expect(register?.params).toEqual({ + platform: 'ios', + token: IOS_TOKEN.token, + apnsEnvironment: 'production', + filter: { onlyWhenDesktopAway: true, sound: true } + }) + expect(stored.registeredHostIds).toEqual(['host-1']) + }) + + it('never calls registerPush on a host without the capability', async () => { + const { client, sent } = makeClient(['some-other.v1']) + await setRemotePushEnabled(true) + + attachPushRegistration('host-legacy', client) + await flush() + + expect(methodsIn(sent)).toEqual(['status.get']) + expect(stored.registeredHostIds).toEqual([]) + }) + + it('reconciles disabled consent even without registration records', async () => { + const { client, sent } = makeClient([NOTIFICATIONS_REMOTE_PUSH_CAPABILITY]) + + attachPushRegistration('host-1', client) + await flush() + + expect(methodsIn(sent)).toEqual(['status.get', 'notifications.unregisterPush']) + }) + + it('omits apnsEnvironment for an Android token', async () => { + vi.mocked(getDevicePushToken).mockResolvedValue({ platform: 'android', token: 'fcm-token' }) + const { client, sent } = makeClient([NOTIFICATIONS_REMOTE_PUSH_CAPABILITY]) + await setRemotePushEnabled(true) + + attachPushRegistration('host-1', client) + await flush() + + const register = sent.find((request) => request.method === 'notifications.registerPush') + expect(register?.params).toMatchObject({ platform: 'android', token: 'fcm-token' }) + expect(register?.params).not.toHaveProperty('apnsEnvironment') + }) + + it('registers nothing when the device has no push token at all', async () => { + vi.mocked(getDevicePushToken).mockResolvedValue(null) + const { client, sent } = makeClient([NOTIFICATIONS_REMOTE_PUSH_CAPABILITY]) + await setRemotePushEnabled(true) + + attachPushRegistration('host-simulator', client) + await flush() + + expect(methodsIn(sent)).toEqual(['status.get']) + }) + + it('asks only once when the host answers that it has no push capability', async () => { + const { client, sent } = makeClient(['some-other.v1']) + await setRemotePushEnabled(true) + attachPushRegistration('host-legacy', client) + await flush() + + await setRemotePushEnabled(true) + await flush() + + expect(methodsIn(sent)).toEqual(['status.get']) + }) + + it('re-probes a host whose first status.get never answered', async () => { + vi.useFakeTimers() + const sent: string[] = [] + let probeFails = true + const client = { + sendRequest: vi.fn(async (method: string) => { + sent.push(method) + if (method === 'status.get') { + if (probeFails) { + throw new Error('request timed out') + } + return ok({ capabilities: [NOTIFICATIONS_REMOTE_PUSH_CAPABILITY] }) + } + return ok({ registered: true, registrationId: 'registration-1' }) + }) + } + await setRemotePushEnabled(true) + attachPushRegistration('host-1', client) + await vi.advanceTimersByTimeAsync(0) + expect(sent).toEqual(['status.get']) + + // A failed probe retries while the same connection remains active. + probeFails = false + await vi.advanceTimersByTimeAsync(1_000) + await Promise.resolve() + await Promise.resolve() + + expect(sent).toEqual(['status.get', 'status.get', 'notifications.registerPush']) + vi.useRealTimers() + }) + + it('retries the device token on the next reconcile after the device had none', async () => { + vi.mocked(getDevicePushToken).mockResolvedValueOnce(null).mockResolvedValue(IOS_TOKEN) + const { client, sent } = makeClient([NOTIFICATIONS_REMOTE_PUSH_CAPABILITY]) + await setRemotePushEnabled(true) + attachPushRegistration('host-1', client) + await flush() + expect(methodsIn(sent)).toEqual(['status.get']) + + // A token can be missing only for now — APNs registration still in flight. + await setRemotePushEnabled(true) + await flush() + + expect(methodsIn(sent)).toContain('notifications.registerPush') + }) +}) + +describe('push registration token changes', () => { + it('re-registers every connected host when the provider rolls the token', async () => { + let onTokenChange: ((token: MobilePushToken) => void) | null = null + vi.mocked(addPushTokenListener).mockImplementation((listener) => { + onTokenChange = listener + return () => {} + }) + const { client, sent } = makeClient([NOTIFICATIONS_REMOTE_PUSH_CAPABILITY]) + await setRemotePushEnabled(true) + attachPushRegistration('host-1', client) + await flush() + const stop = startPushTokenSync() + + onTokenChange?.({ platform: 'ios', token: 'b'.repeat(64), apnsEnvironment: 'sandbox' }) + await flush() + + const registers = sent.filter((request) => request.method === 'notifications.registerPush') + expect(registers).toHaveLength(2) + expect(registers[1]?.params).toMatchObject({ + token: 'b'.repeat(64), + apnsEnvironment: 'sandbox' + }) + stop() + }) +}) + +describe('push unregistration', () => { + it('unregisters a connected host as soon as the switch goes off', async () => { + const { client, sent } = makeClient([NOTIFICATIONS_REMOTE_PUSH_CAPABILITY]) + await setRemotePushEnabled(true) + attachPushRegistration('host-1', client) + await flush() + + await setRemotePushEnabled(false) + await flush() + + expect(methodsIn(sent)).toContain('notifications.unregisterPush') + expect(stored.registeredHostIds).toEqual([]) + expect(stored.pendingUnregisterHostIds).toEqual([]) + }) + + it('retries the unregister on a host that was offline when the switch went off', async () => { + const first = makeClient([NOTIFICATIONS_REMOTE_PUSH_CAPABILITY]) + await setRemotePushEnabled(true) + const detach = attachPushRegistration('host-1', first.client) + await flush() + detach() + + await setRemotePushEnabled(false) + await flush() + expect(methodsIn(first.sent)).not.toContain('notifications.unregisterPush') + expect(stored.pendingUnregisterHostIds).toEqual(['host-1']) + + // A fresh process: only the persisted intent survives the restart. + AppState.currentState = 'active' + resetPushRegistrationForTests() + const reconnected = makeClient([NOTIFICATIONS_REMOTE_PUSH_CAPABILITY]) + attachPushRegistration('host-1', reconnected.client) + await flush() + + // No probe first: a pending entry is a switch-off the user already performed, so + // it must not wait on a status.get that may never answer. + expect(methodsIn(reconnected.sent)).toEqual(['notifications.unregisterPush']) + expect(stored.pendingUnregisterHostIds).toEqual([]) + }) + + it('recovers an offline disable after its cleanup write fails and mobile restarts', async () => { + const first = makeClient([NOTIFICATIONS_REMOTE_PUSH_CAPABILITY]) + await setRemotePushEnabled(true) + const detach = attachPushRegistration('host-1', first.client) + await flush() + detach() + vi.mocked(saveRemotePushHostRegistrations).mockRejectedValueOnce(new Error('disk full')) + + await expect(setRemotePushEnabled(false)).rejects.toThrow('disk full') + expect(enabled).toBe(false) + expect(stored.pendingUnregisterHostIds).toEqual([]) + + resetPushRegistrationForTests() + const reconnected = makeClient([NOTIFICATIONS_REMOTE_PUSH_CAPABILITY]) + attachPushRegistration('host-1', reconnected.client) + await flush() + + expect(methodsIn(reconnected.sent)).toEqual(['status.get', 'notifications.unregisterPush']) + expect(stored).toEqual({ registeredHostIds: [], pendingUnregisterHostIds: [] }) + }) + + it('keeps the pending intent when the retry itself fails', async () => { + stored = { registeredHostIds: ['host-1'], pendingUnregisterHostIds: ['host-1'] } + const client = { + sendRequest: vi.fn(async (method: string) => + method === 'status.get' + ? ok({ capabilities: [NOTIFICATIONS_REMOTE_PUSH_CAPABILITY] }) + : Promise.reject(new Error('socket closed')) + ) + } + + attachPushRegistration('host-1', client) + await flush() + + expect(stored.pendingUnregisterHostIds).toEqual(['host-1']) + }) + + it('unregisters best-effort before a removed host loses its credentials', async () => { + const { client, sent } = makeClient([NOTIFICATIONS_REMOTE_PUSH_CAPABILITY]) + await setRemotePushEnabled(true) + attachPushRegistration('host-1', client) + await flush() + + await unregisterPushForRemovedHost('host-1') + + expect(methodsIn(sent)).toContain('notifications.unregisterPush') + expect(stored.registeredHostIds).toEqual([]) + expect(stored.pendingUnregisterHostIds).toEqual([]) + }) + + it('drops a removed host that was never connected without any request', async () => { + stored = { registeredHostIds: ['host-gone'], pendingUnregisterHostIds: ['host-gone'] } + + await unregisterPushForRemovedHost('host-gone') + + expect(stored).toEqual({ registeredHostIds: [], pendingUnregisterHostIds: [] }) + }) + + it('unregisters a pending host even when its capability probe never answers', async () => { + stored = { registeredHostIds: ['host-1'], pendingUnregisterHostIds: ['host-1'] } + const sent: string[] = [] + const client = { + sendRequest: vi.fn(async (method: string) => { + sent.push(method) + if (method === 'status.get') { + throw new Error('request timed out') + } + return ok({ unregistered: true }) + }) + } + + attachPushRegistration('host-1', client) + await flush() + + // Gating this on the probe leaves the gateway pushing while the switch reads off. + expect(sent).toEqual(['notifications.unregisterPush']) + expect(stored.pendingUnregisterHostIds).toEqual([]) + }) + + it('re-arms the unregister when the switch goes off while a register is in flight', async () => { + const sent: string[] = [] + let releaseRegister: (() => void) | null = null + const client = { + sendRequest: vi.fn(async (method: string) => { + sent.push(method) + if (method === 'status.get') { + return ok({ capabilities: [NOTIFICATIONS_REMOTE_PUSH_CAPABILITY] }) + } + if (method === 'notifications.registerPush') { + await new Promise((resolve) => { + releaseRegister = resolve + }) + return ok({ registered: true, registrationId: 'registration-1' }) + } + return ok({ unregistered: true }) + }) + } + await setRemotePushEnabled(true) + attachPushRegistration('host-1', client) + await flush() + + // The sweep snapshots `registered` while this host is still only in flight. + const switchedOff = setRemotePushEnabled(false) + await flush() + releaseRegister?.() + await switchedOff + await flush() + + // Recording the late success would leave a live gateway registration behind a + // switch that reads off, with nothing pending to ever retract it. + expect(sent).toContain('notifications.unregisterPush') + expect(stored).toEqual({ registeredHostIds: [], pendingUnregisterHostIds: [] }) + }) +}) + +it('does not register or renew when a connected phone is in the background', async () => { + AppState.currentState = 'background' + const { client, sent } = makeClient([NOTIFICATIONS_REMOTE_PUSH_CAPABILITY]) + await setRemotePushEnabled(true) + attachPushRegistration('background-phone', client) + await flush() + expect(methodsIn(sent)).not.toContain('notifications.registerPush') + AppState.currentState = 'active' + attachPushRegistration('background-phone', client) + await flush() + expect(methodsIn(sent)).toContain('notifications.registerPush') +}) diff --git a/mobile/src/notifications/push-registration.ts b/mobile/src/notifications/push-registration.ts new file mode 100644 index 00000000000..f5463714b7d --- /dev/null +++ b/mobile/src/notifications/push-registration.ts @@ -0,0 +1,328 @@ +import { ensureDesktopNotificationChannel } from './desktop-notification-channel' +import { AppState } from 'react-native' +import { startMobilePushLeaseRenewal } from './mobile-push-lease-renewal' +import { + loadNotificationDeliveryPreferences, + notificationPreferencesFilter, + saveNotificationDeliveryPreferences, + type NotificationDeliveryPreferences +} from './notification-delivery-preferences' +import type { + MobilePushFilter, + MobilePushRegisterInput, + MobilePushRegisterResult +} from '../../../src/shared/mobile-push-contract' +import { NOTIFICATIONS_REMOTE_PUSH_RUNTIME_CAPABILITY } from '../../../src/shared/protocol-version' +import type { RpcClient } from '../transport/rpc-client' +import { startRuntimeCapabilityProbe } from '../transport/runtime-capability-probe' +import { + loadPushNotificationsEnabled, + loadRemotePushHostRegistrations, + savePushNotificationsEnabled, + saveRemotePushHostRegistrations +} from '../storage/preferences' +import { addPushTokenListener, getDevicePushToken, type MobilePushToken } from './push-token' + +export const NOTIFICATIONS_REMOTE_PUSH_CAPABILITY = NOTIFICATIONS_REMOTE_PUSH_RUNTIME_CAPABILITY + +type PushClient = Pick + +const REQUEST_TIMEOUT_MS = 5_000 +const REMOVAL_TIMEOUT_MS = 2_000 +const TOKEN_TIMEOUT_MS = 2_000 + +type HostPushState = { + connection: { client: PushClient | null } + // An unanswered probe is unknown, not unsupported. + supported: boolean | null + capabilityProbeStop: (() => void) | null + chain: Promise +} + +type RegistrationRecords = { registered: Set; pending: Set } + +const hostsById = new Map() +let registrationRecords: RegistrationRecords | null = null +let tokenPromise: Promise | null = null +// A late registration must not overwrite a newer preference or consent choice. +let consentGeneration = 0 + +function hostState(hostId: string): HostPushState { + let state = hostsById.get(hostId) + if (!state) { + state = { + connection: { client: null }, + supported: null, + capabilityProbeStop: null, + chain: Promise.resolve() + } + hostsById.set(hostId, state) + } + return state +} + +async function readRecords(): Promise { + if (!registrationRecords) { + const stored = await loadRemotePushHostRegistrations() + registrationRecords ??= { + registered: new Set(stored.registeredHostIds), + pending: new Set(stored.pendingUnregisterHostIds) + } + } + return registrationRecords +} + +async function mutateRecords(mutate: (value: RegistrationRecords) => void): Promise { + const value = await readRecords() + mutate(value) + await saveRemotePushHostRegistrations({ + registeredHostIds: [...value.registered], + pendingUnregisterHostIds: [...value.pending] + }) +} + +// A missing token is retried: APNs registration may still be in flight. +async function currentToken(): Promise { + await ensureDesktopNotificationChannel() + if (!tokenPromise) { + const pending: Promise = getDevicePushToken().then((token) => { + if (!token && tokenPromise === pending) { + tokenPromise = null + } + return token + }) + tokenPromise = pending + } + return tokenPromise +} + +async function sendRegister( + client: PushClient, + token: MobilePushToken, + filter: MobilePushFilter +): Promise { + const params: Omit = { + platform: token.platform, + token: token.token, + ...(token.apnsEnvironment ? { apnsEnvironment: token.apnsEnvironment } : {}), + filter + } + const response = await client + .sendRequest('notifications.registerPush', params, { + timeoutMs: REQUEST_TIMEOUT_MS, + failWhenDisconnected: true + }) + .catch(() => null) + if (!response?.ok) { + return false + } + return (response.result as MobilePushRegisterResult | null)?.registered === true +} + +async function sendUnregister(client: PushClient, timeoutMs: number): Promise { + const response = await client + .sendRequest('notifications.unregisterPush', null, { + timeoutMs, + failWhenDisconnected: true + }) + .catch(() => null) + return response?.ok === true +} + +async function reconcileHost(hostId: string): Promise { + const state = hostsById.get(hostId) + const client = state?.connection.client + if (!state || !client) { + return + } + const generation = consentGeneration + const isCurrent = () => hostsById.get(hostId) === state && state.connection.client === client + const value = await readRecords() + // Unregister intent takes priority even before the capability probe answers. + if (value.pending.has(hostId)) { + if (state.supported === false || !(await sendUnregister(client, REQUEST_TIMEOUT_MS))) { + return + } + await mutateRecords((current) => { + current.pending.delete(hostId) + current.registered.delete(hostId) + }) + // A preference change can invalidate a register without disabling push. + if (!(await loadPushNotificationsEnabled())) { + return + } + } + if (state.supported == null) { + if (!isCurrent()) { + return + } + state.capabilityProbeStop ??= startRuntimeCapabilityProbe(client, (capabilities) => { + if (!isCurrent()) { + return + } + state.supported = capabilities.includes(NOTIFICATIONS_REMOTE_PUSH_CAPABILITY) + void enqueueReconcile(hostId) + }) + return + } + if (!state.supported || !isCurrent()) { + return + } + if (!(await loadPushNotificationsEnabled())) { + // Saved consent recovers a disable even if its pending-record write failed. + if (await sendUnregister(client, REQUEST_TIMEOUT_MS)) { + await mutateRecords((current) => { + current.pending.delete(hostId) + current.registered.delete(hostId) + }) + } + return + } + if (AppState.currentState !== 'active') { + return + } + let timer: ReturnType | undefined + const token = await Promise.race([ + currentToken(), + new Promise((resolve) => { + timer = setTimeout(() => resolve(null), TOKEN_TIMEOUT_MS) + }) + ]).finally(() => clearTimeout(timer)) + const filter = notificationPreferencesFilter(await loadNotificationDeliveryPreferences()) + if ( + !token || + !isCurrent() || + generation !== consentGeneration || + AppState.currentState !== 'active' + ) { + return + } + if (!(await sendRegister(client, token, filter)) || hostsById.get(hostId) !== state) { + return + } + if (generation !== consentGeneration) { + await mutateRecords((current) => current.pending.add(hostId)) + void enqueueReconcile(hostId) + return + } + await mutateRecords((current) => current.registered.add(hostId)) +} + +function enqueueReconcile(hostId: string): Promise { + const state = hostState(hostId) + const run = state.chain + .then(() => (hostsById.get(hostId) === state ? reconcileHost(hostId) : undefined)) + .catch(() => { + console.warn('[push] Failed to reconcile notification registration') + }) + state.chain = run + return run +} + +async function reconcileAllHosts(): Promise { + await Promise.all([...hostsById.keys()].map((hostId) => enqueueReconcile(hostId))) +} + +/** + * Track a host whose client has reached `connected`, registering (or retrying a + * pending unregister) as the current preference requires. The returned function + * detaches the client on disconnect; the host's tracked state survives it. + */ +export function attachPushRegistration(hostId: string, client: PushClient): () => void { + const state = hostState(hostId) + if (state.connection.client !== client) { + state.capabilityProbeStop?.() + state.capabilityProbeStop = null + state.connection.client = client + state.supported = null + } + void enqueueReconcile(hostId) + const connection = state.connection + return () => { + if (connection.client === client) { + connection.client = null + state.capabilityProbeStop?.() + state.capabilityProbeStop = null + state.supported = null + const current = hostsById.get(hostId) + if (current && current !== state) { + current.capabilityProbeStop?.() + current.capabilityProbeStop = null + current.supported = null + } + } + } +} + +// Consent completion covers local persistence; host reconciliation runs in the background. +export async function setRemotePushEnabled(enabled: boolean): Promise { + consentGeneration++ + await savePushNotificationsEnabled(enabled) + try { + await mutateRecords((current) => { + if (!enabled) { + for (const hostId of current.registered) { + current.pending.add(hostId) + } + return + } + current.pending.clear() + }) + } finally { + void reconcileAllHosts() + } +} + +export async function setNotificationDeliveryPreferences( + value: NotificationDeliveryPreferences +): Promise { + consentGeneration++ + await saveNotificationDeliveryPreferences(value) + await reconcileAllHosts() +} + +// Offline hosts retain the registration until unpaired or its mobile-use lease expires. +export async function unregisterPushForRemovedHost(hostId: string): Promise<() => void> { + const state = hostsById.get(hostId) + // Retire ownership before waiting for earlier RPCs to settle. + hostsById.delete(hostId) + state?.capabilityProbeStop?.() + if (state) { + state.capabilityProbeStop = null + } + await state?.chain + if (state?.connection.client && state.supported !== false) { + await sendUnregister(state.connection.client, REMOVAL_TIMEOUT_MS) + } + await mutateRecords((current) => { + current.registered.delete(hostId) + current.pending.delete(hostId) + }).catch(() => {}) + return () => { + if (state && !hostsById.has(hostId)) { + // Preserve disconnect ownership without reviving stale registration work. + hostsById.set(hostId, { ...state, supported: null, capabilityProbeStop: null }) + void enqueueReconcile(hostId) + } + } +} + +/** A rolled token stops delivering, so re-register every connected host at once. */ +export function startPushTokenSync(): () => void { + const stopLease = startMobilePushLeaseRenewal(reconcileAllHosts) + const stopToken = addPushTokenListener((token) => { + tokenPromise = Promise.resolve(token) + void reconcileAllHosts() + }) + return () => { + stopLease() + stopToken() + } +} + +export function resetPushRegistrationForTests(): void { + hostsById.clear() + registrationRecords = null + tokenPromise = null + consentGeneration = 0 +} diff --git a/mobile/src/notifications/push-socket-dismissal.test.ts b/mobile/src/notifications/push-socket-dismissal.test.ts new file mode 100644 index 00000000000..80d3534c4ca --- /dev/null +++ b/mobile/src/notifications/push-socket-dismissal.test.ts @@ -0,0 +1,73 @@ +import { expect, it, vi } from 'vitest' +import * as Notifications from 'expo-notifications' +import { loadHostCatalog } from '../transport/host-store' +import { deriveHostFingerprint } from './push-host-fingerprint' +import { dismissHostPushNotification } from './push-socket-dismissal' +vi.mock('../transport/host-store', () => ({ loadHostCatalog: vi.fn() })) +vi.mock('expo-notifications', () => ({ + getPresentedNotificationsAsync: vi.fn(), + dismissNotificationAsync: vi.fn() +})) +vi.mock('@react-native-async-storage/async-storage', () => ({ + default: { getItem: async () => null, setItem: async () => undefined } +})) + +it('a socket dismissal cannot clear another desktop or a newer notification', async () => { + const publicKeyB64 = Buffer.alloc(32, 1).toString('base64') + vi.mocked(loadHostCatalog).mockResolvedValue([{ id: 'host-a', publicKeyB64 }] as never) + const hostFingerprint = deriveHostFingerprint(publicKeyB64) + const event = { + type: 'dismiss' as const, + notificationId: 'same', + notificationEpoch: 'epoch', + notificationSeq: 2 + } + const presented = (identifier: string, overrides: Record) => ({ + request: { identifier, content: { data: { hostFingerprint, ...event, ...overrides } } } + }) + vi.mocked(Notifications.getPresentedNotificationsAsync).mockResolvedValue([ + presented('older', { notificationSeq: 1 }), + presented('newer', { notificationSeq: 3 }), + presented('other', { hostFingerprint: 'other-host' }), + presented('restarted', { notificationEpoch: 'new-epoch' }) + ] as never) + vi.mocked(Notifications.dismissNotificationAsync).mockResolvedValue(undefined) + await dismissHostPushNotification(event, 'host-a') + expect(vi.mocked(Notifications.dismissNotificationAsync).mock.calls).toEqual([['older']]) +}) + +it('supports ID-only legacy dismissal while preserving host isolation', async () => { + vi.clearAllMocks() + const publicKeyB64 = Buffer.alloc(32, 1).toString('base64') + vi.mocked(loadHostCatalog).mockResolvedValue([{ id: 'host-a', publicKeyB64 }] as never) + const hostFingerprint = deriveHostFingerprint(publicKeyB64) + vi.mocked(Notifications.getPresentedNotificationsAsync).mockResolvedValue([ + { + request: { + identifier: 'versioned', + content: { + data: { + hostFingerprint, + notificationId: 'same', + notificationEpoch: 'new', + notificationSeq: 3 + } + } + } + }, + { + request: { + identifier: 'legacy', + content: { data: { hostFingerprint, notificationId: 'same' } } + } + }, + { + request: { + identifier: 'foreign', + content: { data: { hostFingerprint: 'other-host', notificationId: 'same' } } + } + } + ] as never) + await dismissHostPushNotification({ type: 'dismiss', notificationId: 'same' }, 'host-a') + expect(Notifications.dismissNotificationAsync).toHaveBeenCalledExactlyOnceWith('legacy') +}) diff --git a/mobile/src/notifications/push-socket-dismissal.ts b/mobile/src/notifications/push-socket-dismissal.ts new file mode 100644 index 00000000000..93226f296b2 --- /dev/null +++ b/mobile/src/notifications/push-socket-dismissal.ts @@ -0,0 +1,22 @@ +import { loadHostCatalog } from '../transport/host-store' +import { deriveHostFingerprint } from './push-host-fingerprint' +import { dismissPresentedPushNotification } from './push-tray-dismissal' +import type { DismissNotificationEvent } from './desktop-notification-events' + +async function hostFingerprint(hostId: string): Promise { + const hosts = await loadHostCatalog().catch(() => []) + const host = hosts.find((item) => item.id === hostId) + return host ? deriveHostFingerprint(host.publicKeyB64) : null +} + +export async function dismissHostPushNotification( + event: DismissNotificationEvent, + hostId: string +): Promise { + const fingerprint = await hostFingerprint(hostId) + if (!fingerprint) { + return + } + const fence = event.notificationEpoch && event.notificationSeq !== undefined ? event : undefined + await dismissPresentedPushNotification(event.notificationId, fingerprint, fence) +} diff --git a/mobile/src/notifications/push-token.test.ts b/mobile/src/notifications/push-token.test.ts new file mode 100644 index 00000000000..2a193430ac6 --- /dev/null +++ b/mobile/src/notifications/push-token.test.ts @@ -0,0 +1,92 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import * as Notifications from 'expo-notifications' +import { addPushTokenListener, getDevicePushToken } from './push-token' + +vi.mock('expo-notifications', () => ({ + getDevicePushTokenAsync: vi.fn(), + addPushTokenListener: vi.fn() +})) + +const dev = globalThis as { __DEV__?: boolean } + +beforeEach(() => { + vi.clearAllMocks() +}) + +afterEach(() => { + delete dev.__DEV__ +}) + +describe('getDevicePushToken', () => { + it.each([ + [true, 'sandbox'], + [false, 'production'] + ])('reports apnsEnvironment for a __DEV__=%s iOS build as %s', async (isDev, environment) => { + dev.__DEV__ = isDev + vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({ + type: 'ios', + data: 'a'.repeat(64) + } as never) + + await expect(getDevicePushToken()).resolves.toEqual({ + platform: 'ios', + token: 'a'.repeat(64), + apnsEnvironment: environment + }) + }) + + it('omits apnsEnvironment for Android, where FCM has no environment split', async () => { + vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({ + type: 'android', + data: 'fcm-registration-token' + } as never) + + await expect(getDevicePushToken()).resolves.toEqual({ + platform: 'android', + token: 'fcm-registration-token' + }) + }) + + it.each([ + ['a web push subscription', { type: 'web', data: { endpoint: 'https://example.test' } }], + ['an empty token', { type: 'ios', data: '' }] + ])('returns null for %s', async (_label, raw) => { + vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue(raw as never) + + await expect(getDevicePushToken()).resolves.toBeNull() + }) + + it('returns null when the shell cannot mint a token at all', async () => { + vi.mocked(Notifications.getDevicePushTokenAsync).mockRejectedValue(new Error('no entitlement')) + + await expect(getDevicePushToken()).resolves.toBeNull() + }) +}) + +describe('addPushTokenListener', () => { + it('forwards a rolled native token and removes the subscription on teardown', () => { + const remove = vi.fn() + let emit: ((raw: unknown) => void) | null = null + vi.mocked(Notifications.addPushTokenListener).mockImplementation((listener) => { + emit = listener as (raw: unknown) => void + return { remove } as never + }) + const seen: unknown[] = [] + + const stop = addPushTokenListener((token) => seen.push(token)) + emit?.({ type: 'android', data: 'rolled' }) + emit?.({ type: 'web', data: {} }) + stop() + + expect(seen).toEqual([{ platform: 'android', token: 'rolled' }]) + expect(remove).toHaveBeenCalledTimes(1) + }) + + it('degrades to a no-op on a shell that cannot subscribe to token changes', () => { + vi.mocked(Notifications.addPushTokenListener).mockImplementation(() => { + throw new Error('no push support') + }) + + expect(() => addPushTokenListener(() => {})()).not.toThrow() + }) +}) diff --git a/mobile/src/notifications/push-token.ts b/mobile/src/notifications/push-token.ts new file mode 100644 index 00000000000..6c93bfb1506 --- /dev/null +++ b/mobile/src/notifications/push-token.ts @@ -0,0 +1,58 @@ +import * as Notifications from 'expo-notifications' +import type { + MobilePushApnsEnvironment, + MobilePushPlatform +} from '../../../src/shared/mobile-push-contract' + +// Why: the native APNs/FCM token, not an Expo push token — Orca's own gateway +// talks to Apple and Google directly, so it needs the raw device token. + +export type MobilePushToken = { + readonly platform: MobilePushPlatform + readonly token: string + readonly apnsEnvironment?: MobilePushApnsEnvironment +} + +// Dev-client builds are debug and get sandbox APNs; TestFlight and App Store are release. +function apnsEnvironment(): MobilePushApnsEnvironment { + return typeof __DEV__ !== 'undefined' && __DEV__ ? 'sandbox' : 'production' +} + +function toMobilePushToken(raw: { type: string; data: unknown }): MobilePushToken | null { + if (typeof raw.data !== 'string' || raw.data.length === 0) { + return null + } + if (raw.type === 'ios') { + return { platform: 'ios', token: raw.data, apnsEnvironment: apnsEnvironment() } + } + // Web tokens carry an object payload and no Orca gateway path; only native counts. + return raw.type === 'android' ? { platform: 'android', token: raw.data } : null +} + +/** + * The native push token, or null if registration is unavailable or fails. + */ +export async function getDevicePushToken(): Promise { + try { + return toMobilePushToken(await Notifications.getDevicePushTokenAsync()) + } catch { + return null + } +} + +/** Providers can roll a token while the app runs; the old one stops delivering. */ +export function addPushTokenListener(listener: (token: MobilePushToken) => void): () => void { + try { + const subscription = Notifications.addPushTokenListener((raw) => { + const token = toMobilePushToken(raw) + if (token) { + listener(token) + } + }) + return () => subscription.remove() + } catch { + // A shell with no push capability cannot subscribe; the caller is a root-level + // effect, so throwing here would take the whole app down over an optional feature. + return () => {} + } +} diff --git a/mobile/src/notifications/push-tray-dismissal.test.ts b/mobile/src/notifications/push-tray-dismissal.test.ts new file mode 100644 index 00000000000..5bea8f88f72 --- /dev/null +++ b/mobile/src/notifications/push-tray-dismissal.test.ts @@ -0,0 +1,99 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import * as Notifications from 'expo-notifications' +import { dismissPresentedPushNotification } from './push-tray-dismissal' + +vi.mock('@react-native-async-storage/async-storage', () => ({ + default: { getItem: vi.fn(async () => null), setItem: vi.fn(async () => {}) } +})) + +vi.mock('expo-notifications', () => ({ + getPresentedNotificationsAsync: vi.fn(), + dismissNotificationAsync: vi.fn() +})) + +function presented(identifier: string, data: unknown): unknown { + return { request: { identifier, content: { data } } } +} + +beforeEach(() => { + vi.clearAllMocks() + vi.mocked(Notifications.dismissNotificationAsync).mockResolvedValue(undefined) +}) + +describe('dismissPresentedPushNotification', () => { + it('dismisses only the tray entries whose push payload carries the same notification id', async () => { + vi.mocked(Notifications.getPresentedNotificationsAsync).mockResolvedValue([ + presented('tray-1', { + orca: { hostFingerprint: 'fp0123456789abcd', notificationId: 'agent:one' } + }), + presented('tray-2', { + orca: { hostFingerprint: 'fp0123456789abcd', notificationId: 'agent:two' } + }), + presented('other-host', { hostFingerprint: 'another-host', notificationId: 'agent:one' }), + // Flat FCM shape for the same notification, presented on Android. + presented('tray-3', { hostFingerprint: 'fp0123456789abcd', notificationId: 'agent:one' }) + ] as never) + + await dismissPresentedPushNotification('agent:one', 'fp0123456789abcd') + + expect(vi.mocked(Notifications.dismissNotificationAsync).mock.calls.map(([id]) => id)).toEqual([ + 'tray-1', + 'tray-3' + ]) + }) + + it('ignores notifications without a gateway identity', async () => { + vi.mocked(Notifications.getPresentedNotificationsAsync).mockResolvedValue([ + presented('tray-1', { hostId: 'host-1', notificationId: 'agent:one' }) + ] as never) + + await dismissPresentedPushNotification('agent:one', 'fp0123456789abcd') + + expect(Notifications.dismissNotificationAsync).not.toHaveBeenCalled() + }) + + it('reports tray query failures to the caller', async () => { + vi.mocked(Notifications.getPresentedNotificationsAsync).mockRejectedValue( + new Error('unavailable') + ) + + await expect(dismissPresentedPushNotification('agent:one', 'fp0123456789abcd')).rejects.toThrow( + 'unavailable' + ) + }) +}) + +it('a delayed dismissal preserves newer alerts, other epochs, and other hosts', async () => { + const base = { hostFingerprint: 'host-a', notificationId: 'note', notificationEpoch: 'epoch-a' } + vi.mocked(Notifications.getPresentedNotificationsAsync).mockResolvedValue([ + presented('older', { ...base, notificationSeq: 1 }), + presented('equal', { ...base, notificationSeq: 2 }), + presented('newer', { ...base, notificationSeq: 3 }), + presented('restarted', { ...base, notificationSeq: 1, notificationEpoch: 'epoch-b' }), + presented('other-host', { ...base, notificationSeq: 1, hostFingerprint: 'host-b' }), + presented('legacy', base) + ] as never) + await dismissPresentedPushNotification('note', 'host-a', { + notificationEpoch: 'epoch-a', + notificationSeq: 2 + }) + expect(vi.mocked(Notifications.dismissNotificationAsync).mock.calls.map(([id]) => id)).toEqual([ + 'older', + 'equal' + ]) +}) + +it.each([undefined, {}, { notificationEpoch: 'epoch' }, { notificationSeq: 2 }])( + 'an incomplete dismissal fence %j removes only unversioned entries', + async (fence) => { + const base = { hostFingerprint: 'host-a', notificationId: 'note' } + vi.mocked(Notifications.getPresentedNotificationsAsync).mockResolvedValue([ + presented('unversioned', base), + presented('versioned', { ...base, notificationEpoch: 'epoch', notificationSeq: 2 }), + presented('epoch-only', { ...base, notificationEpoch: 'epoch' }), + presented('sequence-only', { ...base, notificationSeq: 2 }) + ] as never) + await dismissPresentedPushNotification('note', 'host-a', fence) + expect(Notifications.dismissNotificationAsync).toHaveBeenCalledExactlyOnceWith('unversioned') + } +) diff --git a/mobile/src/notifications/push-tray-dismissal.ts b/mobile/src/notifications/push-tray-dismissal.ts new file mode 100644 index 00000000000..a810430709a --- /dev/null +++ b/mobile/src/notifications/push-tray-dismissal.ts @@ -0,0 +1,63 @@ +import { readNativeNotificationData } from './native-notification-data' +import * as Notifications from 'expo-notifications' +import { readOrcaPushPayload, type OrcaPushPayload } from './push-payload' +import { rememberPushDismissal, wasPushDismissed } from './push-dismissal-watermarks' + +async function dismissMatchingPresentedPushes( + matches: (payload: OrcaPushPayload) => boolean | Promise +): Promise { + const presented = await Notifications.getPresentedNotificationsAsync() + await Promise.all( + presented.map(async (notification) => { + const payload = readOrcaPushPayload(readNativeNotificationData(notification.request)) + if (payload && (await matches(payload))) { + await Notifications.dismissNotificationAsync(notification.request.identifier) + } + }) + ) +} + +export function dismissRememberedPushNotifications( + hostFingerprint: string, + confirmed: readonly OrcaPushPayload[] +): Promise { + return dismissMatchingPresentedPushes(async (payload) => { + if (payload.hostFingerprint !== hostFingerprint) { + return false + } + return ( + confirmed.some( + (fence) => + fence.notificationId === payload.notificationId && + fence.notificationEpoch === payload.notificationEpoch && + fence.notificationSeq !== undefined && + payload.notificationSeq !== undefined && + fence.notificationSeq >= payload.notificationSeq + ) || wasPushDismissed(payload) + ) + }) +} + +// Pushes shown while Orca was closed are absent from the local scheduling registry. +export async function dismissPresentedPushNotification( + notificationId: string, + hostFingerprint: string, + fence?: { notificationEpoch?: string; notificationSeq?: number } +): Promise { + if (fence) { + await rememberPushDismissal({ hostFingerprint, notificationId, ...fence }) + } + await dismissMatchingPresentedPushes((payload) => { + if (payload.hostFingerprint !== hostFingerprint) { + return false + } + return ( + payload.notificationId === notificationId && + (fence?.notificationEpoch && fence.notificationSeq !== undefined + ? payload.notificationEpoch === fence.notificationEpoch && + payload.notificationSeq !== undefined && + payload.notificationSeq <= fence.notificationSeq + : payload.notificationEpoch === undefined && payload.notificationSeq === undefined) + ) + }) +} diff --git a/mobile/src/notifications/use-remote-push-capable-hosts.test.tsx b/mobile/src/notifications/use-remote-push-capable-hosts.test.tsx new file mode 100644 index 00000000000..9b25ca3dcf9 --- /dev/null +++ b/mobile/src/notifications/use-remote-push-capable-hosts.test.tsx @@ -0,0 +1,196 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { loadHostCatalog } from '../transport/host-store' +import type { HostCatalogEntry } from '../transport/types' +import type { RpcClient } from '../transport/rpc-client' +import { startRuntimeCapabilityProbe } from '../transport/runtime-capability-probe' +import { useAllHostClients } from '../transport/use-all-host-clients' +import { + useRemotePushCapableHosts, + type RemotePushHostSupport +} from './use-remote-push-capable-hosts' + +vi.mock('../transport/host-store', () => ({ loadHostCatalog: vi.fn() })) +vi.mock('../transport/use-all-host-clients', () => ({ useAllHostClients: vi.fn() })) +vi.mock('../transport/runtime-capability-probe', () => ({ + startRuntimeCapabilityProbe: vi.fn() +})) + +// The real module reaches expo-notifications and the preference store for the token +// path; only the capability string matters here. +vi.mock('./push-registration', () => ({ + NOTIFICATIONS_REMOTE_PUSH_CAPABILITY: 'notifications.remote-push.v1' +})) + +const CAPABILITY = 'notifications.remote-push.v1' + +type ClientEntry = { hostId: string; client: RpcClient; state: string } + +/** Distinct object per host, so identity changes are the thing under test. */ +function clientFor(hostId: string): RpcClient { + return { hostId } as unknown as RpcClient +} + +let renderer: ReactTestRenderer | null = null +let latest: RemotePushHostSupport = { supported: false, resolved: false } +const answerByHostId = new Map void>() +const stopProbe = vi.fn() + +function Harness(): null { + latest = useRemotePushCapableHosts() + return null +} + +async function mount(): Promise { + await act(async () => { + renderer = create(createElement(Harness)) + await Promise.resolve() + }) +} + +async function setClients(entries: readonly ClientEntry[]): Promise { + vi.mocked(useAllHostClients).mockReturnValue(entries as never) + await act(async () => { + renderer?.update(createElement(Harness)) + await Promise.resolve() + }) +} + +async function answer(hostId: string, capabilities: readonly string[]): Promise { + await act(async () => { + answerByHostId.get(hostId)?.(capabilities) + await Promise.resolve() + }) +} + +beforeEach(() => { + vi.clearAllMocks() + answerByHostId.clear() + latest = { supported: false, resolved: false } + vi.mocked(useAllHostClients).mockReturnValue([] as never) + vi.mocked(startRuntimeCapabilityProbe).mockImplementation((client, onCapabilities) => { + answerByHostId.set((client as unknown as { hostId: string }).hostId, onCapabilities) + return stopProbe + }) + vi.mocked(loadHostCatalog).mockResolvedValue([ + { id: 'host-1', publicKeyB64: 'k1' }, + { id: 'host-2', publicKeyB64: 'k2' } + ] as unknown as HostCatalogEntry[]) +}) + +afterEach(() => { + act(() => renderer?.unmount()) + renderer = null +}) + +describe('useRemotePushCapableHosts', () => { + it('stays unresolved when the host catalog cannot be read', async () => { + vi.mocked(loadHostCatalog).mockRejectedValue(new Error('keychain locked')) + + await mount() + + // Resolving here would render "Update your desktop app" at someone whose desktop + // is already current, on the strength of a catalog read that simply failed. + expect(latest).toEqual({ supported: false, resolved: false }) + }) + + it('waits for every connected host before answering', async () => { + await mount() + await setClients([ + { hostId: 'host-1', client: clientFor('host-1'), state: 'connected' }, + { hostId: 'host-2', client: clientFor('host-2'), state: 'connected' } + ]) + + await answer('host-1', [CAPABILITY]) + expect(latest.resolved).toBe(false) + + await answer('host-2', ['some-other.v1']) + expect(latest).toEqual({ supported: true, resolved: true }) + }) + + it('keeps the answer of a host that has since disconnected', async () => { + await mount() + const client = clientFor('host-1') + await setClients([{ hostId: 'host-1', client, state: 'connected' }]) + await answer('host-1', [CAPABILITY]) + + await setClients([{ hostId: 'host-1', client, state: 'connecting' }]) + + expect(latest).toEqual({ supported: true, resolved: true }) + }) + + it('resolves immediately when nothing is paired', async () => { + vi.mocked(loadHostCatalog).mockResolvedValue([]) + + await mount() + + expect(latest).toEqual({ supported: false, resolved: true }) + }) + + it('rechecks a cached answer after disconnecting and reconnecting', async () => { + await mount() + const client = clientFor('host-1') + await setClients([{ hostId: 'host-1', client, state: 'connected' }]) + await answer('host-1', [CAPABILITY]) + await setClients([{ hostId: 'host-1', client, state: 'connecting' }]) + expect(latest).toEqual({ supported: true, resolved: true }) + await setClients([{ hostId: 'host-1', client, state: 'connected' }]) + expect(latest).toEqual({ supported: false, resolved: false }) + await answer('host-1', []) + expect(latest).toEqual({ supported: false, resolved: true }) + }) + + it('leaves a running probe alone when another host changes state', async () => { + await mount() + const first = clientFor('host-1') + await setClients([{ hostId: 'host-1', client: first, state: 'connected' }]) + expect(startRuntimeCapabilityProbe).toHaveBeenCalledTimes(1) + + // useAllHostClients rebuilds its array on every connection tick, so a plain + // dependency on it would tear down and restart host-1's probe here. + await setClients([ + { hostId: 'host-1', client: first, state: 'connected' }, + { hostId: 'host-2', client: clientFor('host-2'), state: 'connecting' } + ]) + await setClients([ + { hostId: 'host-1', client: first, state: 'connected' }, + { hostId: 'host-2', client: clientFor('host-2'), state: 'connected' } + ]) + + expect(stopProbe).not.toHaveBeenCalled() + expect( + vi.mocked(startRuntimeCapabilityProbe).mock.calls.map(([client]) => client) + ).toHaveLength(2) + }) + + it('restarts the probe when a reconnect replaces the host client', async () => { + await mount() + await setClients([{ hostId: 'host-1', client: clientFor('host-1'), state: 'connected' }]) + await answer('host-1', [CAPABILITY]) + expect(latest).toEqual({ supported: true, resolved: true }) + + await setClients([{ hostId: 'host-1', client: clientFor('host-1'), state: 'connected' }]) + + expect(latest).toEqual({ supported: false, resolved: false }) + expect(stopProbe).toHaveBeenCalledTimes(1) + expect(startRuntimeCapabilityProbe).toHaveBeenCalledTimes(2) + await answer('host-1', []) + expect(latest).toEqual({ supported: false, resolved: true }) + await answer('host-1', [CAPABILITY]) + expect(latest).toEqual({ supported: true, resolved: true }) + }) + + it('ignores an answer from a host the catalog no longer lists', async () => { + await mount() + await setClients([ + { hostId: 'host-ghost', client: clientFor('host-ghost'), state: 'connected' } + ]) + + await answer('host-ghost', [CAPABILITY]) + + // An unpaired desktop cannot push to this phone, so its vote must not offer + // the switch — nor count as the answer that resolves the section. + expect(latest).toEqual({ supported: false, resolved: false }) + }) +}) diff --git a/mobile/src/notifications/use-remote-push-capable-hosts.ts b/mobile/src/notifications/use-remote-push-capable-hosts.ts new file mode 100644 index 00000000000..243bbbc6ce8 --- /dev/null +++ b/mobile/src/notifications/use-remote-push-capable-hosts.ts @@ -0,0 +1,109 @@ +import { useEffect, useRef, useState } from 'react' +import { loadHostCatalog } from '../transport/host-store' +import type { RpcClient } from '../transport/rpc-client' +import { startRuntimeCapabilityProbe } from '../transport/runtime-capability-probe' +import { useAllHostClients } from '../transport/use-all-host-clients' +import { NOTIFICATIONS_REMOTE_PUSH_CAPABILITY } from './push-registration' + +export type RemotePushHostSupport = { + /** At least one paired host advertises `notifications.remote-push.v1`. */ + supported: boolean + /** Whether the answer above is final rather than "nobody has replied yet". */ + resolved: boolean +} + +/** + * Whether background push can be offered at all. The desktop advertises the + * capability in `status.get`, so the answer needs a connected host — until one + * replies the screen must stay silent rather than tell someone to update a + * desktop that is already current. + */ +export function useRemotePushCapableHosts(): RemotePushHostSupport { + const [hostIds, setHostIds] = useState([]) + const [hostsLoaded, setHostsLoaded] = useState(false) + const [supportedByHostId, setSupportedByHostId] = useState>({}) + const probesRef = useRef(new Map void }>()) + + useEffect(() => { + let cancelled = false + void loadHostCatalog() + .then((hosts) => { + if (!cancelled) { + setHostIds(hosts.map((host) => host.id)) + setHostsLoaded(true) + } + }) + // Why nothing on failure: an unread catalog marked loaded resolves the answer as + // "no paired host supports push", which tells the user to update a current desktop. + .catch(() => {}) + return () => { + cancelled = true + } + }, []) + + const clients = useAllHostClients(hostIds) + + // Why pruned rather than left: an answer for a host that is no longer paired is a + // vote from a desktop this phone cannot receive a push from. + useEffect(() => { + setSupportedByHostId((previous) => { + const kept = Object.entries(previous).filter(([hostId]) => hostIds.includes(hostId)) + return kept.length === Object.keys(previous).length ? previous : Object.fromEntries(kept) + }) + }, [hostIds]) + + // Why diffed by client identity rather than restarted on every `clients` value: + // useAllHostClients rebuilds the array on each connection tick, so a plain + // dependency tears down and re-runs every host's probe whenever any host moves. + useEffect(() => { + const connected = new Map( + clients + .filter((entry) => entry.state === 'connected') + .map((entry) => [entry.hostId, entry.client]) + ) + const probes = probesRef.current + for (const [hostId, probe] of probes) { + if (connected.get(hostId) !== probe.client) { + probe.stop() + probes.delete(hostId) + } + } + for (const [hostId, client] of connected) { + if (!probes.has(hostId)) { + setSupportedByHostId((previous) => { + const { [hostId]: _removed, ...remaining } = previous + return remaining + }) + const stop = startRuntimeCapabilityProbe(client, (capabilities) => { + setSupportedByHostId((previous) => ({ + ...previous, + [hostId]: capabilities.includes(NOTIFICATIONS_REMOTE_PUSH_CAPABILITY) + })) + }) + probes.set(hostId, { client, stop }) + } + } + }, [clients]) + + useEffect(() => { + const probes = probesRef.current + return () => { + for (const probe of probes.values()) { + probe.stop() + } + probes.clear() + } + }, []) + + const answeredHostIds = hostIds.filter((hostId) => hostId in supportedByHostId) + return { + supported: answeredHostIds.some((hostId) => supportedByHostId[hostId]), + // A connected host that has not answered yet is exactly the case the silence is + // for, so one outstanding probe holds the whole section back. Disconnected hosts + // do not: their earlier answer stands, and one that never answered never will. + resolved: + (hostsLoaded && hostIds.length === 0) || + (answeredHostIds.length > 0 && + clients.every((entry) => entry.state !== 'connected' || entry.hostId in supportedByHostId)) + } +} diff --git a/mobile/src/onboarding/MobileOnboardingPage.tsx b/mobile/src/onboarding/MobileOnboardingPage.tsx index a5a6a07a3c6..65a19b57889 100644 --- a/mobile/src/onboarding/MobileOnboardingPage.tsx +++ b/mobile/src/onboarding/MobileOnboardingPage.tsx @@ -47,16 +47,26 @@ export function MobileOnboardingPage({ )} - {isSessionView ? 'How should sessions open?' : 'Stay updated while away'} + {isSessionView ? 'How should sessions open?' : 'Enable notifications'} {isSessionView ? 'Choose whether supported agent sessions open in the terminal or Chat UI on this device. Press and hold a session tab to switch its view, or change the default later in Settings.' - : 'Get notified on this device when an agent needs your input or finishes a task.'} + : 'Get notified when an agent finishes a task or needs your input.'} + {!isSessionView ? ( + + By default, notifications arrive after your desktop has been idle for 3 minutes. + + ) : null} + {!isSessionView ? ( + + Delivered through Orca’s push service. Change this anytime in Settings. + + ) : null} {error ? ( {error} diff --git a/mobile/src/onboarding/mobile-onboarding-screen.test.ts b/mobile/src/onboarding/mobile-onboarding-screen.test.ts index 05dcc6b9ad8..efa2f19d5ac 100644 --- a/mobile/src/onboarding/mobile-onboarding-screen.test.ts +++ b/mobile/src/onboarding/mobile-onboarding-screen.test.ts @@ -10,7 +10,7 @@ const mocks = vi.hoisted(() => ({ animatedTiming: vi.fn(), ensureNotificationPermissions: vi.fn(), saveDefaultSessionView: vi.fn(), - savePushNotificationsEnabled: vi.fn() + setRemotePushEnabled: vi.fn() })) vi.mock('react-native', () => ({ @@ -48,8 +48,8 @@ vi.mock('../notifications/mobile-notifications', () => ({ vi.mock('../storage/session-view-preferences', () => ({ saveDefaultSessionView: mocks.saveDefaultSessionView })) -vi.mock('../storage/preferences', () => ({ - savePushNotificationsEnabled: mocks.savePushNotificationsEnabled +vi.mock('../notifications/push-registration', () => ({ + setRemotePushEnabled: mocks.setRemotePushEnabled })) describe('MobileOnboardingScreen', () => { @@ -64,7 +64,7 @@ describe('MobileOnboardingScreen', () => { }) mocks.ensureNotificationPermissions.mockReset().mockResolvedValue(true) mocks.saveDefaultSessionView.mockReset().mockResolvedValue(undefined) - mocks.savePushNotificationsEnabled.mockReset().mockResolvedValue(undefined) + mocks.setRemotePushEnabled.mockReset().mockResolvedValue(undefined) }) afterEach(() => { @@ -100,7 +100,32 @@ describe('MobileOnboardingScreen', () => { await act(async () => pages()[1].props.onNotificationChoice('skip')) expect(mocks.ensureNotificationPermissions).not.toHaveBeenCalled() - expect(mocks.savePushNotificationsEnabled).toHaveBeenCalledWith(false) + expect(mocks.setRemotePushEnabled).toHaveBeenCalledWith(false) + expect(mocks.replace).toHaveBeenCalledWith('/h/paired-host') + }) + + it.each([true, false])( + 'saves permission result %s through the consent owner once', + async (granted) => { + mocks.params = { hostId: 'paired-host', steps: 'notifications' } + mocks.ensureNotificationPermissions.mockResolvedValue(granted) + await renderScreen() + await act(async () => pages()[0].props.onNotificationChoice('enable')) + expect(mocks.setRemotePushEnabled).toHaveBeenCalledExactlyOnceWith(granted) + expect(mocks.replace).toHaveBeenCalledWith('/h/paired-host') + } + ) + + it('keeps notification consent retryable when its local write fails', async () => { + mocks.params = { hostId: 'paired-host', steps: 'notifications' } + mocks.setRemotePushEnabled.mockRejectedValueOnce(new Error('disk full')) + await renderScreen() + await act(async () => pages()[0].props.onNotificationChoice('enable')) + expect(pages()[0].props.error).toBe('Notification settings could not be updated. Try again.') + expect(mocks.replace).not.toHaveBeenCalled() + await act(async () => pages()[0].props.onNotificationChoice('enable')) + expect(mocks.setRemotePushEnabled).toHaveBeenCalledTimes(2) + expect(mocks.setRemotePushEnabled).toHaveBeenLastCalledWith(true) expect(mocks.replace).toHaveBeenCalledWith('/h/paired-host') }) diff --git a/mobile/src/onboarding/mobile-onboarding-styles.ts b/mobile/src/onboarding/mobile-onboarding-styles.ts index 20f36ec0f5b..3f03bb24b95 100644 --- a/mobile/src/onboarding/mobile-onboarding-styles.ts +++ b/mobile/src/onboarding/mobile-onboarding-styles.ts @@ -90,6 +90,13 @@ export const mobileOnboardingStyles = StyleSheet.create({ alignSelf: 'center', paddingBottom: spacing.lg }, + disclosure: { + color: colors.textSecondary, + fontSize: typography.metaSize, + lineHeight: 18, + textAlign: 'center', + marginBottom: spacing.lg + }, primaryButton: { minHeight: 44, alignItems: 'center', diff --git a/mobile/src/rpc-params-contract-type-only-boundary.test.ts b/mobile/src/rpc-params-contract-type-only-boundary.test.ts new file mode 100644 index 00000000000..bc9088bea0b --- /dev/null +++ b/mobile/src/rpc-params-contract-type-only-boundary.test.ts @@ -0,0 +1,144 @@ +import { readFileSync, readdirSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { extname, join, relative, resolve } from 'node:path' +import ts from 'typescript' +import { describe, expect, it } from 'vitest' + +// Why: src/shared/rpc-contract/*-params.ts hold the host's zod schemas. Bundling one +// into the app would let client code call parse(), and requiredString is +// z.unknown().transform(...) — it coerces a non-string to '' instead of rejecting it, +// silently changing the bytes the phone puts on the wire. Types only, never values. +const mobileRoot = fileURLToPath(new URL('..', import.meta.url)) +const contractRoot = resolve(mobileRoot, '..', 'src', 'shared', 'rpc-contract') +const scannedRoots = ['app', 'src'].map((directory) => join(mobileRoot, directory)) +const sourceExtensions = new Set(['.js', '.jsx', '.ts', '.tsx']) + +function sourceFiles(directory: string): string[] { + return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { + const path = join(directory, entry.name) + if (entry.isDirectory()) { + return entry.name === 'node_modules' ? [] : sourceFiles(path) + } + return [path] + }) +} + +function targetsContract(path: string, specifier: string): boolean { + if (!specifier.startsWith('.')) { + return false + } + const resolved = resolve(path, '..', specifier) + return resolved === contractRoot || resolved.startsWith(`${contractRoot}/`) +} + +function parse(path: string, source: string): ts.SourceFile { + const extension = extname(path) + return ts.createSourceFile( + path, + source, + ts.ScriptTarget.Latest, + true, + extension === '.tsx' || extension === '.jsx' ? ts.ScriptKind.TSX : ts.ScriptKind.TS + ) +} + +// Returns the specifiers that would pull contract *values* into the bundle. +export function contractValueImports(path: string, source: string): string[] { + const sourceFile = parse(path, source) + const offenders: string[] = [] + const visit = (node: ts.Node): void => { + if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) { + const specifier = node.moduleSpecifier.text + if (targetsContract(path, specifier)) { + const clause = node.importClause + const everyNamedIsType = + clause?.isTypeOnly === true || + (clause?.namedBindings !== undefined && + ts.isNamedImports(clause.namedBindings) && + clause.namedBindings.elements.every((element) => element.isTypeOnly)) + // A bare `import './x'` has no clause at all and still emits a require. + if (!everyNamedIsType) { + offenders.push(specifier) + } + } + } + if ( + ts.isExportDeclaration(node) && + node.moduleSpecifier && + ts.isStringLiteral(node.moduleSpecifier) + ) { + const specifier = node.moduleSpecifier.text + if (targetsContract(path, specifier)) { + const everyNamedIsType = + node.isTypeOnly || + (node.exportClause !== undefined && + ts.isNamedExports(node.exportClause) && + node.exportClause.elements.every((element) => element.isTypeOnly)) + if (!everyNamedIsType) { + offenders.push(specifier) + } + } + } + if (ts.isCallExpression(node)) { + const callee = node.expression + const isDynamic = callee.kind === ts.SyntaxKind.ImportKeyword + const isRequire = ts.isIdentifier(callee) && callee.text === 'require' + const argument = node.arguments[0] + if ( + (isDynamic || isRequire) && + argument && + ts.isStringLiteral(argument) && + targetsContract(path, argument.text) + ) { + offenders.push(argument.text) + } + } + ts.forEachChild(node, visit) + } + visit(sourceFile) + return offenders +} + +describe('RPC params contract boundary', () => { + it('flags every shape that would emit a runtime require', () => { + const path = join(mobileRoot, 'src', 'probe.ts') + const contract = '../../src/shared/rpc-contract/repo-params' + expect(contractValueImports(path, `import { RepoSelector } from '${contract}'`)).toEqual([ + contract + ]) + expect(contractValueImports(path, `import '${contract}'`)).toEqual([contract]) + expect(contractValueImports(path, `export { RepoSelector } from '${contract}'`)).toEqual([ + contract + ]) + expect(contractValueImports(path, `const s = require('${contract}')`)).toEqual([contract]) + expect(contractValueImports(path, `const s = await import('${contract}')`)).toEqual([contract]) + expect(contractValueImports(path, `import type { RepoSelector } from '${contract}'`)).toEqual( + [] + ) + expect(contractValueImports(path, `import { type RepoSelector } from '${contract}'`)).toEqual( + [] + ) + expect(contractValueImports(path, `export type { RepoSelector } from '${contract}'`)).toEqual( + [] + ) + expect( + contractValueImports( + path, + `import type { GitHubWorkItem } from '../../src/shared/github/work-item-types'` + ) + ).toEqual([]) + }) + + it('keeps every mobile import of the params contract type-only', () => { + const offenders = scannedRoots + .flatMap(sourceFiles) + .filter((path) => sourceExtensions.has(extname(path))) + .flatMap((path) => + contractValueImports(path, readFileSync(path, 'utf8')).map( + (specifier) => `${relative(mobileRoot, path)} -> ${specifier}` + ) + ) + + expect(offenders).toEqual([]) + }) +}) diff --git a/mobile/src/session/MobileNativeChatComposer.tsx b/mobile/src/session/MobileNativeChatComposer.tsx index c16b69ced89..20c43aa6c8b 100644 --- a/mobile/src/session/MobileNativeChatComposer.tsx +++ b/mobile/src/session/MobileNativeChatComposer.tsx @@ -130,7 +130,7 @@ export function MobileNativeChatComposer({ if (trigger.kind === 'slash') { const commands = structuredCommands !== undefined - ? structuredSlashCommands(structuredCommands) + ? structuredSlashCommands(structuredCommands, agent) : agent ? getVerifiedNativeChatCommands(agent) : [] diff --git a/mobile/src/session/MobileNativeChatMessage.test.ts b/mobile/src/session/MobileNativeChatMessage.test.ts index e09d1631a8d..67e90132866 100644 --- a/mobile/src/session/MobileNativeChatMessage.test.ts +++ b/mobile/src/session/MobileNativeChatMessage.test.ts @@ -9,6 +9,7 @@ vi.mock('react-native', async () => { const Text = ({ children, ...props }: { children?: unknown }): unknown => React.createElement('Text', props, children) return { + ActivityIndicator: 'ActivityIndicator', Animated: { Text, Value: class { @@ -268,12 +269,12 @@ describe('MobileNativeChatMessage', () => { expect(tree.root.findAllByType('Wrench' as never)).toHaveLength(0) }) - it('renders the turn status row under a user message', () => { + it('renders the settled turn status row under a user message', () => { const tree = render(userMessage([{ type: 'text', text: 'go' }]), { structuredActivityUi: true, - turnStatus: { startedAt: Date.now(), thinking: true, workedSeconds: null } + turnStatus: { startedAt: Date.now() - 3_000, thinking: false, workedSeconds: 3 } }) - expect(textIn(tree.root)).toContain('Thinking') + expect(textIn(tree.root)).toContain('Worked for 3s') }) it('does not render a turn status row without one', () => { diff --git a/mobile/src/session/MobileNativeChatMessage.tsx b/mobile/src/session/MobileNativeChatMessage.tsx index 5d013688249..9b480fdd7d9 100644 --- a/mobile/src/session/MobileNativeChatMessage.tsx +++ b/mobile/src/session/MobileNativeChatMessage.tsx @@ -82,7 +82,7 @@ function MobileNativeChatMessageImpl({ /** Multiplies all chat text sizes for pinch-to-zoom (1 = no change). */ fontScale?: number onOpenFile?: (relativePath: string) => void - /** This turn's status row, rendered under a user message (desktop parity). */ + /** This settled turn's status row, rendered under its user message. */ turnStatus?: NativeChatTurnStatus | null /** Whether the turn caret has disclosed this turn's activity. */ turnExpanded?: boolean diff --git a/mobile/src/session/MobileNativeChatOverlay.tsx b/mobile/src/session/MobileNativeChatOverlay.tsx index 997083cb26e..389beb8eaad 100644 --- a/mobile/src/session/MobileNativeChatOverlay.tsx +++ b/mobile/src/session/MobileNativeChatOverlay.tsx @@ -73,6 +73,7 @@ export function MobileNativeChatOverlay({ agentWorking={controller.nativeChatAgentWorking} canStop={controller.nativeChatCanStop} structuredActivityUi={controller.nativeChatStructured} + turnIndicator={controller.nativeChatTurnIndicator} workingStartedAt={controller.nativeChatWorkingStartedAt} settledTurns={controller.nativeChatSettledTurns} streaming={streaming} diff --git a/mobile/src/session/MobileNativeChatTurnStatus.test.ts b/mobile/src/session/MobileNativeChatTurnStatus.test.ts index 78ac01e0d37..6b6a1d49e07 100644 --- a/mobile/src/session/MobileNativeChatTurnStatus.test.ts +++ b/mobile/src/session/MobileNativeChatTurnStatus.test.ts @@ -7,18 +7,8 @@ vi.mock('react-native', async () => { const Text = ({ children, ...props }: { children?: unknown }): unknown => React.createElement('Text', props, children) return { - Animated: { - Text, - Value: class { - constructor(private value: number) {} - setValue(next: number): void { - this.value = next - } - }, - loop: (animation: unknown) => animation, - sequence: () => ({ start: vi.fn(), stop: vi.fn() }), - timing: () => ({ start: vi.fn(), stop: vi.fn() }) - }, + ActivityIndicator: (props: Record) => + React.createElement('ActivityIndicator', props), Pressable: ({ children, ...props }: { children?: unknown }) => React.createElement('Pressable', props, children), Text, @@ -49,6 +39,7 @@ describe('MobileNativeChatTurnStatus', () => { startedAt: number | null thinking: boolean workedSeconds?: number | null + activityText?: string | null expanded?: boolean onToggleExpanded?: () => void }): ReactTestRenderer { @@ -61,12 +52,16 @@ describe('MobileNativeChatTurnStatus', () => { const labels = (node: ReactTestInstance): string[] => node.findAllByType('Text' as never).map((text) => String(text.children.join(''))) - it('reads "Thinking" before the turn produces output', () => { + const spinners = (node: ReactTestInstance): ReactTestInstance[] => + node.findAllByType('ActivityIndicator' as never) + + it('reads "Thinking" beside one spinner while the turn reasons', () => { const tree = render({ startedAt: Date.now(), thinking: true }) expect(labels(tree.root)).toEqual(['Thinking']) + expect(spinners(tree.root)).toHaveLength(1) }) - it('counts up once the turn is producing output', () => { + it('counts up on that same single row when the turn is not reasoning', () => { const startedAt = Date.now() const tree = render({ startedAt, thinking: false }) expect(labels(tree.root)).toEqual(['Working for 0s']) @@ -74,6 +69,19 @@ describe('MobileNativeChatTurnStatus', () => { vi.advanceTimersByTime(12_000) }) expect(labels(tree.root)).toEqual(['Working for 12s']) + expect(spinners(tree.root)).toHaveLength(1) + }) + + it('lets provider activity text beat both fallbacks and hold the clock', () => { + const tree = render({ + startedAt: Date.now(), + thinking: true, + activityText: 'Running pnpm test' + }) + expect(labels(tree.root)).toEqual(['Running pnpm test']) + expect(spinners(tree.root)).toHaveLength(1) + // No label consumes the duration, so nothing schedules a tick for it. + expect(vi.getTimerCount()).toBe(0) }) it('settles to a tappable "Worked for" row that toggles the turn', () => { @@ -98,9 +106,10 @@ describe('MobileNativeChatTurnStatus', () => { expect(labels(tree.root)).toEqual(['Worked for 5s']) }) - it('holds no interval once the turn has settled', () => { - render({ startedAt: Date.now(), thinking: false, workedSeconds: 5 }) + it('holds no interval, and no spinner, once the turn has settled', () => { + const tree = render({ startedAt: Date.now(), thinking: false, workedSeconds: 5 }) expect(vi.getTimerCount()).toBe(0) + expect(spinners(tree.root)).toHaveLength(0) }) it('announces the live row to assistive tech', () => { diff --git a/mobile/src/session/MobileNativeChatTurnStatus.tsx b/mobile/src/session/MobileNativeChatTurnStatus.tsx index 4ce73cdcd38..acf922265f6 100644 --- a/mobile/src/session/MobileNativeChatTurnStatus.tsx +++ b/mobile/src/session/MobileNativeChatTurnStatus.tsx @@ -1,7 +1,8 @@ -import { useEffect, useRef, useState } from 'react' -import { Animated, Pressable, StyleSheet, Text, View } from 'react-native' +import { useEffect, useState } from 'react' +import { ActivityIndicator, Pressable, StyleSheet, Text, View } from 'react-native' import { ChevronRight } from 'lucide-react-native' import { + formatNativeChatActiveTurnLabel, formatNativeChatTurnStatusLabel, NATIVE_CHAT_TURN_STATUS_COPY, nativeChatElapsedSeconds @@ -25,48 +26,38 @@ function useElapsedSeconds(startedAt: number | null, counting: boolean): number return counting ? nativeChatElapsedSeconds(startedAt, mountedAt, now) : 0 } -/** The per-turn status row — "Thinking", then "Working for 12s" while the turn - * runs, settling to a tappable "Worked for 3m 4s" that discloses the turn's - * tool activity. Desktop parity: `NativeChatWorkingStatus`. */ +/** The per-turn status row. While the turn runs it is the one live indicator — a + * spinner beside what the provider says it is doing, else "Thinking", else + * "Working for 12s". It settles to a tappable "Worked for 3m 4s" that discloses + * the turn's tool activity. Desktop parity: `NativeChatTurnActivityLine` for the + * live row, `NativeChatWorkingStatus` for the settled one. */ export function MobileNativeChatTurnStatus({ startedAt, thinking, workedSeconds, + activityText, expanded = false, onToggleExpanded }: { startedAt: number | null thinking: boolean workedSeconds?: number | null + /** Provider activity copy for a live turn; outranks the other two labels. */ + activityText?: string | null expanded?: boolean onToggleExpanded?: () => void }): React.JSX.Element { - const counting = !thinking && workedSeconds == null + const settled = workedSeconds != null + const counting = !settled && !thinking && !activityText?.trim() const elapsedSeconds = useElapsedSeconds(startedAt, counting) - const label = formatNativeChatTurnStatusLabel({ thinking, workedSeconds, elapsedSeconds }) + const label = settled + ? formatNativeChatTurnStatusLabel({ thinking, workedSeconds, elapsedSeconds }) + : formatNativeChatActiveTurnLabel({ activityText, thinking, elapsedSeconds }) - const pulse = useRef(new Animated.Value(1)).current - useEffect(() => { - if (!thinking) { - pulse.setValue(1) - return - } - const animation = Animated.loop( - Animated.sequence([ - Animated.timing(pulse, { toValue: 0.45, duration: 700, useNativeDriver: true }), - Animated.timing(pulse, { toValue: 1, duration: 700, useNativeDriver: true }) - ]) - ) - animation.start() - return () => animation.stop() - }, [pulse, thinking]) - - const rowStyle = [styles.row, thinking ? null : styles.rowSettled] - - if (workedSeconds != null && onToggleExpanded) { + if (settled && onToggleExpanded) { return ( [...rowStyle, pressed && styles.pressed]} + style={({ pressed }) => [styles.row, styles.rowSettled, pressed && styles.pressed]} onPress={onToggleExpanded} hitSlop={6} accessibilityRole="button" @@ -83,11 +74,14 @@ export function MobileNativeChatTurnStatus({ return ( - {label} + {settled ? null : } + + {label} + ) } @@ -109,7 +103,8 @@ const styles = StyleSheet.create({ }, label: { color: colors.textMuted, - fontSize: typography.bodySize + fontSize: typography.bodySize, + flexShrink: 1 }, caretOpen: { transform: [{ rotate: '90deg' }] diff --git a/mobile/src/session/MobileNativeChatView.test.ts b/mobile/src/session/MobileNativeChatView.test.ts index 63bfb715445..c573d89cc89 100644 --- a/mobile/src/session/MobileNativeChatView.test.ts +++ b/mobile/src/session/MobileNativeChatView.test.ts @@ -73,6 +73,7 @@ type Overrides = { onSend?: (text: string) => Promise pending?: Parameters[0]['pending'] structuredActivityUi?: boolean + turnIndicator?: Parameters[0]['turnIndicator'] agentWorking?: boolean canStop?: boolean sendSurfaceId?: string @@ -273,20 +274,74 @@ describe('MobileNativeChatView', () => { return (renderedRow(id) as { props: Record }).props } + function footerProps(): Record | null { + const list = renderer!.root.find((node) => node.type === 'FlatList') + const footer = list.props.ListFooterComponent as + | { props: Record } + | null + | undefined + return footer?.props ?? null + } + function workingIndicators(): ReactTestInstance[] { return renderer!.root.findAll((node) => node.type === 'WorkingIndicator') } - it('gives the live user turn a status row and drops the three-dot indicator', async () => { - const folded = [userTurn('u1', 'go')] + it('puts the live status at the turn tail and drops the three-dot indicator', async () => { + const folded = [userTurn('u1', 'go'), assistantTurn('a1', 'still working')] await render({ messages: folded, folded, structuredActivityUi: true, agentWorking: true }) const props = rowProps('u1') expect(props.structuredActivityUi).toBe(true) - expect(props.turnStatus).toMatchObject({ thinking: true, workedSeconds: null }) + expect(props.turnStatus).toBeNull() + // Nothing reports reasoning, so the one live footer counts instead of guessing. + expect(footerProps()).toMatchObject({ thinking: false, workedSeconds: null }) + expect(listIds().at(-1)).toBe('a1') expect(props.activeTurnIsWorking).toBe(true) expect(workingIndicators()).toHaveLength(0) }) + it('reports the live turn as thinking only when its journal says it is reasoning', async () => { + const folded = [userTurn('u1', 'go')] + await render({ + messages: folded, + folded, + structuredActivityUi: true, + agentWorking: true, + turnIndicator: { thinking: true, activityText: null } + }) + expect(rowProps('u1').turnStatus).toBeNull() + expect(footerProps()).toMatchObject({ thinking: true, workedSeconds: null }) + }) + + it('hands the live row the provider activity copy that outranks its fallbacks', async () => { + const folded = [userTurn('u1', 'go')] + await render({ + messages: folded, + folded, + structuredActivityUi: true, + agentWorking: true, + turnIndicator: { thinking: true, activityText: 'Running pnpm test' } + }) + expect(footerProps()).toMatchObject({ + thinking: true, + activityText: 'Running pnpm test' + }) + }) + + it('keeps the activity copy on the live footer instead of a historical row', async () => { + const folded = [userTurn('u1', 'go'), userTurn('u2', 'again')] + await render({ + messages: folded, + folded, + structuredActivityUi: true, + agentWorking: true, + turnIndicator: { thinking: false, activityText: 'Running pnpm test' } + }) + expect(rowProps('u1')).not.toHaveProperty('turnActivityText') + expect(rowProps('u2')).not.toHaveProperty('turnActivityText') + expect(footerProps()).toMatchObject({ activityText: 'Running pnpm test' }) + }) + it('keeps the bridge lane on the three-dot indicator with no turn status', async () => { const folded = [userTurn('u1', 'go')] await render({ messages: folded, folded, agentWorking: true }) @@ -294,13 +349,15 @@ describe('MobileNativeChatView', () => { expect(props.structuredActivityUi).toBe(false) expect(props.turnStatus).toBeNull() expect(props.activeTurnIsWorking).toBe(false) + expect(footerProps()).toBeNull() expect(workingIndicators()).toHaveLength(1) }) it('settles the finished turn to a tappable duration', async () => { const folded = [userTurn('u1', 'go'), assistantTurn('a1', 'done')] await render({ messages: folded, folded, structuredActivityUi: true, agentWorking: true }) - expect(rowProps('u1').turnStatus).toMatchObject({ thinking: false, workedSeconds: null }) + expect(rowProps('u1').turnStatus).toBeNull() + expect(footerProps()).toMatchObject({ thinking: false, workedSeconds: null }) await update({ messages: folded, folded, structuredActivityUi: true, agentWorking: false }) const settled = rowProps('u1') expect(settled.turnStatus).toMatchObject({ thinking: false }) @@ -309,6 +366,7 @@ describe('MobileNativeChatView', () => { ) expect(settled.onToggleTurn).toBeTypeOf('function') expect(settled.activeTurnIsWorking).toBe(false) + expect(footerProps()).toBeNull() }) it('hangs no status row on an assistant row', async () => { @@ -317,6 +375,7 @@ describe('MobileNativeChatView', () => { expect(rowProps('a1').turnStatus).toBeNull() // The assistant row still belongs to the live turn, so its tool row stays visible. expect(rowProps('a1').activeTurnIsWorking).toBe(true) + expect(footerProps()).toMatchObject({ workedSeconds: null }) }) it('does not carry a running turn clock across chat surfaces', async () => { @@ -331,7 +390,7 @@ describe('MobileNativeChatView', () => { agentWorking: true, sendSurfaceId: 'host\0worktree\0tab-a' }) - expect(rowProps('u1').turnStatus).toMatchObject({ startedAt: 1_000 }) + expect(footerProps()).toMatchObject({ startedAt: 1_000 }) vi.setSystemTime(12_000) const secondTab = [userTurn('u2', 'second')] @@ -343,7 +402,7 @@ describe('MobileNativeChatView', () => { sendSurfaceId: 'host\0worktree\0tab-b' }) - expect(rowProps('u2').turnStatus).toMatchObject({ startedAt: 12_000 }) + expect(footerProps()).toMatchObject({ startedAt: 12_000 }) } finally { vi.useRealTimers() } diff --git a/mobile/src/session/MobileNativeChatView.tsx b/mobile/src/session/MobileNativeChatView.tsx index 440e05e6b9d..67fc93506a9 100644 --- a/mobile/src/session/MobileNativeChatView.tsx +++ b/mobile/src/session/MobileNativeChatView.tsx @@ -13,7 +13,10 @@ import { GestureDetector, GestureHandlerRootView } from 'react-native-gesture-ha import { ArrowDown, ChevronsDownUp, ChevronsUpDown, Square } from 'lucide-react-native' import type { AskAnswerSelection, AskPrompt } from '../../../src/shared/native-chat-ask' import type { NativeChatMessage } from '../../../src/shared/native-chat-types' -import type { NativeChatSettledTurns } from '../../../src/shared/native-chat-turn-status' +import type { + NativeChatLiveTurnIndicator, + NativeChatSettledTurns +} from '../../../src/shared/native-chat-turn-status' import { colors } from '../theme/mobile-theme' import { styles } from './mobile-native-chat-view-styles' import { @@ -53,6 +56,8 @@ type Props = { /** Structured lane: per-turn "Working for N" status plus live tool progress, * replacing the bridge lane's static three-dot working row (desktop parity). */ structuredActivityUi?: boolean + /** What labels the live turn's one indicator row (structured lane only). */ + turnIndicator?: NativeChatLiveTurnIndicator | null /** Structured lane: host-recorded turn timing feeding the per-turn status rows. */ workingStartedAt?: number | null settledTurns?: NativeChatSettledTurns | null @@ -136,6 +141,7 @@ export function MobileNativeChatView({ agentWorking, canStop = agentWorking, structuredActivityUi = false, + turnIndicator = null, workingStartedAt, settledTurns, onStop, @@ -259,14 +265,17 @@ export function MobileNativeChatView({ [hasMore, loadingEarlier, onLoadEarlier] ) - // Per-turn "Thinking / Working for N / Worked for N" rows. The structured lane - // owns them; the bridge lane keeps its three-dot indicator. + // Per-turn status rows: one live indicator while the turn runs, then a settled + // "Worked for N" row. The structured lane owns them; the bridge lane keeps its + // three-dot indicator. const turns = useMobileNativeChatTurnDisclosure({ messages: data, enabled: structuredActivityUi, isWorking: agentWorking === true, workingStartedAt, settledTurns, + thinking: turnIndicator?.thinking === true, + activityText: turnIndicator?.activityText ?? null, scopeKey: sendSurfaceId }) @@ -331,11 +340,12 @@ export function MobileNativeChatView({ ) : null } ListFooterComponent={ - turns.activeTurnIsUnanchored && turns.active ? ( + structuredActivityUi && agentWorking && turns.active ? ( ) : null } diff --git a/mobile/src/session/mobile-native-chat-controller-contract.ts b/mobile/src/session/mobile-native-chat-controller-contract.ts index da1b91acb25..36c07215e8e 100644 --- a/mobile/src/session/mobile-native-chat-controller-contract.ts +++ b/mobile/src/session/mobile-native-chat-controller-contract.ts @@ -6,7 +6,10 @@ import type { } from '../../../src/shared/native-chat-ask' import type { detectAgentPermission } from './mobile-native-chat-permission' import type { parseAgentQuestion } from './mobile-native-chat-question' -import type { NativeChatSettledTurns } from '../../../src/shared/native-chat-turn-status' +import type { + NativeChatLiveTurnIndicator, + NativeChatSettledTurns +} from '../../../src/shared/native-chat-turn-status' import type { MobileNativeChatSendOutcome } from './mobile-native-chat-send' import type { MobileNativeChatPendingMessage } from './use-mobile-native-chat-drafts' import type { useMobileNativeChatSession } from './use-mobile-native-chat-session' @@ -29,6 +32,8 @@ export type MobileNativeChatController = { /** Structured lane: drives the per-turn status row and live tool progress. */ nativeChatStructured: boolean nativeChatAgentWorking: boolean + /** What labels the live turn's one indicator row; null off the structured lane. */ + nativeChatTurnIndicator: NativeChatLiveTurnIndicator | null /** Structured lane: host-recorded turn timing for the per-turn status rows. */ nativeChatWorkingStartedAt: number | null nativeChatSettledTurns: NativeChatSettledTurns | null diff --git a/mobile/src/session/mobile-session-route-parity.test.ts b/mobile/src/session/mobile-session-route-parity.test.ts index 3a6b04661de..76435561664 100644 --- a/mobile/src/session/mobile-session-route-parity.test.ts +++ b/mobile/src/session/mobile-session-route-parity.test.ts @@ -62,15 +62,15 @@ const HOST_COMPONENT_NAMES = new Set([ 'View' ]) -const HEAD_MAIN_HOOK_SHA256 = '10071240ef9edafc2b9c8bed73be83dceaf7828e3b29f17dab55da020a7697a6' -const HEAD_HOOK_BINDING_SHA256 = '1dadb8c3dc0573ea20659ce7251629669e618dd0effaeac3a4536b29c2e865a1' +const HEAD_MAIN_HOOK_SHA256 = 'c3e33699e3e3fa7e24408f3d4946fcc451e9b9419442d985c4ccde01782e5114' +const HEAD_HOOK_BINDING_SHA256 = '7f907e028893721d662eeee0aa9002ad1e00359948f39fb148d274596cd9b3c0' const HEAD_CALLBACK_IDENTITY_SHA256 = '2a9e4825df007f6ef53b81aa5004991d6318eee7507b44d625c07e630be432eb' const HEAD_CALLBACK_BODY_SHA256 = 'af7f3c62954250d4be7ee432ecd10dc2689792aad8230fed2d1d68bbc892d776' const HEAD_EFFECT_SHA256 = 'd9ebfaabc1e79773cdada7ab370b20459ed972f1f8edce1652199f4d0391cd13' const HEAD_CONTENT_HOOK_SHA256 = '9c3b612fef3f370d66873aefdbe1d701f20cb64ded31fef5cc45fde6f8189581' const HEAD_NESTED_FUNCTION_SHA256 = - 'fde6679349ab2b8c30c7e627841ff99bd1dd24441ee95323d0aa70230422ae24' + '97ce5457d8059974f500022a4382ff687074e26843d6c1525be938d6c0537928' const HEAD_NATIVE_REGISTRATION_SHA256 = 'cab85e4e4a3f43289ba93ddea9ccce57aea83e0bf14fd1620a965aad0c1cb49e' const HEAD_NATIVE_REMOVAL_SHA256 = @@ -79,7 +79,7 @@ const HEAD_TIMER_CREATION_SHA256 = '1a31b625e2174c3db77272249843196d2b6b06ab1e654a96d8f7858e3082e66b' const HEAD_TIMER_CLEANUP_SHA256 = 'c73f1d1c2cc89642f3d727d6f3b6b81860a9d6f34234541a2065ec3d1a8cd116' const HEAD_RUNTIME_STRING_SHA256 = - '31951b0b83be01ebfa659c4b94df9ad7eaff6404df5338fbade89eb7473a3cb4' + '57ef354b97fb4fd3776fd1b09a34305d84022c04c43c6391bd130517bf6e37af' const HEAD_HOST_JSX_SHA256 = '390405926b1695fa3a33686f0bc192b432f5468d8576499d7cafbb4922defbb5' const HEAD_LEAF_JSX_SHA256 = '21dba981875e173f692590bf910d60964660c5f4cbb79f3a377c7e54f6a1f016' const HEAD_STYLE_REFERENCE_SHA256 = @@ -472,7 +472,7 @@ describe('mobile session route extraction parity', () => { const contentBindings = CONTENT_COMPONENT_NAMES.flatMap( (name) => readHookFacts(name, definitions).bindings ) - expect(main.hooks).toHaveLength(266) + expect(main.hooks).toHaveLength(267) expect(hash(main.hooks)).toBe(HEAD_MAIN_HOOK_SHA256) expect(hash(main.bindings)).toBe(HEAD_HOOK_BINDING_SHA256) expect(main.callbacks).toHaveLength(77) diff --git a/mobile/src/session/mobile-session-route.ts b/mobile/src/session/mobile-session-route.ts index 66f5c66f76f..b9ec89296c7 100644 --- a/mobile/src/session/mobile-session-route.ts +++ b/mobile/src/session/mobile-session-route.ts @@ -3,6 +3,7 @@ import type { HostStackRouteTarget } from '../navigation/host-stack-navigation' export type MobileSessionRouteParams = { hostId: string worktreeId: string + paneKey?: string name?: string } @@ -11,10 +12,11 @@ export type MobileSessionRouteParams = { export function mobileSessionRouteTarget({ hostId, worktreeId, - name + name, + paneKey }: MobileSessionRouteParams): HostStackRouteTarget { return { name: '[hostId]/session/[worktreeId]', - params: name ? { hostId, worktreeId, name } : { hostId, worktreeId } + params: { hostId, worktreeId, ...(name ? { name } : {}), ...(paneKey ? { paneKey } : {}) } } } diff --git a/mobile/src/session/mobile-structured-agent-session-launch.test.ts b/mobile/src/session/mobile-structured-agent-session-launch.test.ts index 8a020d2eea9..2deb3042ca2 100644 --- a/mobile/src/session/mobile-structured-agent-session-launch.test.ts +++ b/mobile/src/session/mobile-structured-agent-session-launch.test.ts @@ -228,6 +228,34 @@ describe('mobile structured agent-session launch', () => { }) }) + describe.each(['top-level', 'nested'])('%s refusal messages', (location) => { + function refusalClient(message: unknown) { + const refusal = { code: 'method_not_found', ...(message === undefined ? {} : { message }) } + return clientReturning( + { ok: true, result: { supported: true } }, + location === 'top-level' + ? { ok: false, error: refusal } + : { ok: true, result: { ok: false, refusal } } + ) + } + + it.each( + [undefined, null, 42, false, { text: 'unavailable' }, ['unavailable']].map((message) => ({ + message + })) + )('keeps a malformed message $message unknown', async ({ message }) => { + await expect( + createMobileStructuredAgentSession(refusalClient(message), 'workspace-1', 'codex') + ).resolves.toMatchObject({ kind: 'unknown' }) + }) + + it('preserves the fallback for an empty string message', async () => { + await expect( + createMobileStructuredAgentSession(refusalClient(''), 'workspace-1', 'codex') + ).resolves.toEqual({ kind: 'failed', message: 'Could not open Codex chat.' }) + }) + }) + it.each(['structured_agent_session_unsupported', 'method_not_found'])( 'treats a top-level %s as a definitive refusal', async (code) => { diff --git a/mobile/src/session/mobile-structured-agent-session-launch.ts b/mobile/src/session/mobile-structured-agent-session-launch.ts index 9e26eaab91e..bd15e595736 100644 --- a/mobile/src/session/mobile-structured-agent-session-launch.ts +++ b/mobile/src/session/mobile-structured-agent-session-launch.ts @@ -137,18 +137,22 @@ export async function createMobileStructuredAgentSession( } } + // Why: this path distrusts the declared RpcResponse type — a malformed reply must read as + // unconfirmed, not as a refusal we can classify. if (!response || typeof response !== 'object' || typeof response.ok !== 'boolean') { return unknownCreateResult(agent, new Error(unconfirmedMessage(agent))) } if (!response.ok) { + const error = response.error as { code?: unknown; message?: unknown } | null | undefined if ( - !response.error || - typeof response.error !== 'object' || - typeof response.error.code !== 'string' + !error || + typeof error !== 'object' || + typeof error.code !== 'string' || + typeof error.message !== 'string' ) { return unknownCreateResult(agent, new Error(unconfirmedMessage(agent))) } - return classifyCreateRefusal(agent, response.error.code, response.error.message) + return classifyCreateRefusal(agent, error.code, error.message) } const result = response.result as AgentSessionMutationResult if (!result || typeof result !== 'object' || typeof result.ok !== 'boolean') { @@ -158,7 +162,8 @@ export async function createMobileStructuredAgentSession( if ( !result.refusal || typeof result.refusal !== 'object' || - typeof result.refusal.code !== 'string' + typeof result.refusal.code !== 'string' || + typeof result.refusal.message !== 'string' ) { return unknownCreateResult(agent, new Error(unconfirmedMessage(agent))) } diff --git a/mobile/src/session/use-mobile-bridge-chat-prompt-writes.ts b/mobile/src/session/use-mobile-bridge-chat-prompt-writes.ts new file mode 100644 index 00000000000..2dddad48e16 --- /dev/null +++ b/mobile/src/session/use-mobile-bridge-chat-prompt-writes.ts @@ -0,0 +1,65 @@ +import type { MutableRefObject } from 'react' +import type { RpcClient } from '../transport/rpc-client' +import { useMobileNativeChatPermissionSend } from './mobile-native-chat-permission-send' +import { useMobileNativeChatAnswerSend } from './use-mobile-native-chat-answer-send' +import { useMobileNativeChatCancelAsk } from './use-mobile-native-chat-cancel-ask' +import { useMobileNativeChatStop } from './use-mobile-native-chat-stop' +import type { MobileNativeChatAnswerSend } from './use-mobile-native-chat-answer-send' + +/** The bridge lane's four prompt/interrupt write seams. They share one enable + * gate and chain through the answer seam's `cancelPending`, so a caller cannot + * wire one of them to a different lane or forget to drop in-flight answer + * writes before an Escape. The structured lane answers over RPC instead. */ +export function useMobileBridgeChatPromptWrites(args: { + client: RpcClient | null + enabled: boolean + handleRef: MutableRefObject + deviceTokenRef: MutableRefObject + agentRef: MutableRefObject + /** Changes on chat session swap; cancels pending writes when it does. */ + sessionId: string | null + streamIdentity: string + onSendError: (message: string) => void +}): { + answerAsk: MobileNativeChatAnswerSend['answerAsk'] + cancelAsk: () => Promise + respondPermission: (send: string) => Promise + stop: () => void +} { + const { client, enabled, handleRef, deviceTokenRef, streamIdentity, onSendError } = args + const { answerAsk, cancelPending } = useMobileNativeChatAnswerSend({ + client, + enabled, + handleRef, + deviceTokenRef, + agentRef: args.agentRef, + sessionId: args.sessionId, + streamIdentity, + onSendError + }) + const cancelAsk = useMobileNativeChatCancelAsk({ + client, + enabled, + handleRef, + deviceTokenRef, + cancelPending, + onSendError + }) + const respondPermission = useMobileNativeChatPermissionSend({ + client, + enabled, + handleRef, + deviceTokenRef, + onSendError + }) + const stop = useMobileNativeChatStop({ + client, + enabled, + handleRef, + deviceTokenRef, + streamIdentity, + cancelPending, + onSendError + }) + return { answerAsk, cancelAsk, respondPermission, stop } +} diff --git a/mobile/src/session/use-mobile-native-chat-controller.ts b/mobile/src/session/use-mobile-native-chat-controller.ts index d3d68b85032..4087694b567 100644 --- a/mobile/src/session/use-mobile-native-chat-controller.ts +++ b/mobile/src/session/use-mobile-native-chat-controller.ts @@ -2,10 +2,7 @@ import { useLayoutEffect, useRef, type MutableRefObject } from 'react' import type { RpcClient } from '../transport/rpc-client' import type { ConnectionState } from '../transport/types' import type { MobileNativeChatTab } from './mobile-native-chat-eligibility' -import { useMobileNativeChatPermissionSend } from './mobile-native-chat-permission-send' -import { useMobileNativeChatAnswerSend } from './use-mobile-native-chat-answer-send' import { useMobileNativeChatAskDismiss } from './use-mobile-native-chat-ask-dismiss' -import { useMobileNativeChatCancelAsk } from './use-mobile-native-chat-cancel-ask' import { useMobileNativeChatDrafts } from './use-mobile-native-chat-drafts' import { useMobileNativeChatFileSearch } from './use-mobile-native-chat-file-search' import { useMobileNativeChatMessageSend } from './use-mobile-native-chat-message-send' @@ -14,10 +11,10 @@ import { useMobileNativeChatSessionOptionController } from './use-mobile-native- import { useMobileNativeChatSessionLane } from './use-mobile-native-chat-session-lane' import { useMobileStructuredNativeChatSendBridge } from './use-mobile-structured-native-chat-send-bridge' import { useMobileNativeChatPrompts } from './use-mobile-native-chat-prompts' -import { useMobileNativeChatStop } from './use-mobile-native-chat-stop' import { useNativeChatAcceptedAction } from './use-native-chat-action-outcomes' import { useThrottledLatestValue } from './use-throttled-latest-value' import type { MobileNativeChatController } from './mobile-native-chat-controller-contract' +import { useMobileBridgeChatPromptWrites } from './use-mobile-bridge-chat-prompt-writes' import { useMobileNativeChatActiveResolution } from './use-mobile-native-chat-active-resolution' export type { MobileNativeChatController } from './mobile-native-chat-controller-contract' @@ -140,7 +137,7 @@ export function useMobileNativeChatController(args: { ) const { permission: legacyNativeChatPermission, - question: legacyNativeChatQuestion, + question: legacyQuestion, detectedAsk: nativeChatDetectedAsk, ask: nativeChatAskPrompt } = useMobileNativeChatPrompts({ @@ -171,42 +168,19 @@ export function useMobileNativeChatController(args: { ? client != null && activeChatSessionId != null && connState === 'connected' : nativeChatInputLeaseReady && connState === 'connected' - const { answerAsk: handleNativeChatAnswerAsk, cancelPending: cancelNativeChatAnswer } = - useMobileNativeChatAnswerSend({ - client, - enabled: inputSendable && !activeChatStructured, - handleRef: activeHandleRef, - deviceTokenRef, - agentRef: activeChatAgentRef, - sessionId: activeChatSessionId, - streamIdentity, - onSendError - }) - - const handleNativeChatCancelAsk = useMobileNativeChatCancelAsk({ - client, - enabled: inputSendable && !activeChatStructured, - handleRef: activeHandleRef, - deviceTokenRef, - cancelPending: cancelNativeChatAnswer, - onSendError - }) - - const legacyHandleNativeChatRespondPermission = useMobileNativeChatPermissionSend({ - client, - enabled: inputSendable && !activeChatStructured, - handleRef: activeHandleRef, - deviceTokenRef, - onSendError - }) - - const handleNativeChatStop = useMobileNativeChatStop({ + const { + answerAsk: handleNativeChatAnswerAsk, + cancelAsk: handleNativeChatCancelAsk, + respondPermission: legacyHandleNativeChatRespondPermission, + stop: handleNativeChatStop + } = useMobileBridgeChatPromptWrites({ client, enabled: inputSendable && !activeChatStructured, handleRef: activeHandleRef, deviceTokenRef, + agentRef: activeChatAgentRef, + sessionId: activeChatSessionId, streamIdentity, - cancelPending: cancelNativeChatAnswer, onSendError }) @@ -242,6 +216,7 @@ export function useMobileNativeChatController(args: { }) const structuredNativeChatSend = useMobileStructuredNativeChatSendBridge({ + agent: activeChatResolution?.agent === 'claude' ? 'claude' : 'codex', sendStructured: structuredNativeChat.sendWithOutcome, captureSendOrigin, clearDraftForSend, @@ -298,6 +273,7 @@ export function useMobileNativeChatController(args: { /** Structured lane: drives the per-turn status row and live tool progress. */ nativeChatStructured: activeChatStructured, nativeChatAgentWorking, + nativeChatTurnIndicator: activeChatStructured ? structuredNativeChat.turnIndicator : null, nativeChatWorkingStartedAt: activeChatStructured ? structuredNativeChat.workingStartedAt : null, nativeChatSettledTurns: activeChatStructured ? structuredNativeChat.settledTurns : null, nativeChatCanStop: activeChatStructured @@ -309,9 +285,7 @@ export function useMobileNativeChatController(args: { nativeChatPermission: activeChatStructured ? structuredNativeChat.permission : legacyNativeChatPermission, - nativeChatQuestion: activeChatStructured - ? structuredNativeChat.question - : legacyNativeChatQuestion, + nativeChatQuestion: activeChatStructured ? structuredNativeChat.question : legacyQuestion, nativeChatAsk: !activeChatStructured && showNativeChatAsk ? nativeChatAskPrompt : null, nativeChatAskKey, dismissNativeChatAsk, diff --git a/mobile/src/session/use-mobile-native-chat-turn-disclosure.ts b/mobile/src/session/use-mobile-native-chat-turn-disclosure.ts index 5620c1390b2..a67a6a88663 100644 --- a/mobile/src/session/use-mobile-native-chat-turn-disclosure.ts +++ b/mobile/src/session/use-mobile-native-chat-turn-disclosure.ts @@ -28,6 +28,8 @@ export function useMobileNativeChatTurnDisclosure({ isWorking, workingStartedAt, settledTurns, + thinking = false, + activityText = null, scopeKey }: { messages: readonly NativeChatMessage[] @@ -36,12 +38,16 @@ export function useMobileNativeChatTurnDisclosure({ workingStartedAt?: number | null /** Host-recorded durations; they outrank whatever this client observed. */ settledTurns?: NativeChatSettledTurns | null + /** Whether the turn is reasoning right now, derived from its journal content. */ + thinking?: boolean + /** What the provider says the live turn is doing; outranks the other labels. */ + activityText?: string | null /** Host/worktree/tab identity for timing and disclosure isolation. */ scopeKey: string }): { active: NativeChatTurnStatus | null - /** True when the live turn has no user message to hang its status row under. */ - activeTurnIsUnanchored: boolean + /** The live turn's provider activity copy, for the footer row. */ + activeActivityText: string | null onToggleTurn: (turnKey: string) => void resolveRow: (index: number, message: NativeChatMessage) => MobileNativeChatTurnRow } { @@ -51,6 +57,7 @@ export function useMobileNativeChatTurnDisclosure({ isWorking, workingStartedAt, settledTurns, + thinking, scopeKey }) const [expandedTurns, setExpandedTurns] = useState<{ @@ -93,17 +100,16 @@ export function useMobileNativeChatTurnDisclosure({ }, [enabled, messages]) const { active, activeTurnKey, completedByTurn } = turnStatuses + const activeActivityText = enabled && isWorking ? (activityText ?? null) : null const resolveRow = useCallback( (index: number, message: NativeChatMessage): MobileNativeChatTurnRow => { const turnKey = turnKeys[index] const turnStatus = !enabled || message.role !== 'user' ? null - : turnKey === activeTurnKey - ? active - : turnKey - ? (completedByTurn[turnKey] ?? null) - : null + : turnKey + ? (completedByTurn[turnKey] ?? null) + : null return { turnStatus, turnExpanded: turnKey ? expandedTurnIds.has(turnKey) : false, @@ -120,15 +126,14 @@ export function useMobileNativeChatTurnDisclosure({ (turnKey === undefined && activeTurnKey === MOBILE_UNANCHORED_TURN_KEY)) } }, - [turnKeys, enabled, activeTurnKey, active, completedByTurn, expandedTurnIds, isWorking] + [turnKeys, enabled, activeTurnKey, completedByTurn, expandedTurnIds, isWorking] ) return { active, + activeActivityText, /** Stable for a given chat scope, so it never disturbs a row's memo. */ onToggleTurn: toggleExpandedTurn, - activeTurnIsUnanchored: - enabled && active != null && activeTurnKey === MOBILE_UNANCHORED_TURN_KEY, resolveRow } } diff --git a/mobile/src/session/use-mobile-native-chat-turn-status.ts b/mobile/src/session/use-mobile-native-chat-turn-status.ts index 5686acde515..f7cbb2dd887 100644 --- a/mobile/src/session/use-mobile-native-chat-turn-status.ts +++ b/mobile/src/session/use-mobile-native-chat-turn-status.ts @@ -1,7 +1,6 @@ import { useEffect, useMemo, useRef, useState } from 'react' import type { NativeChatMessage } from '../../../src/shared/native-chat-types' import { - nativeChatTurnHasResponse, reduceNativeChatTurnTiming, selectNativeChatTurnStatuses, type NativeChatSettledTurns, @@ -27,6 +26,7 @@ export function useMobileNativeChatTurnStatus({ isWorking, workingStartedAt, settledTurns, + thinking = false, scopeKey }: { messages: readonly NativeChatMessage[] @@ -35,6 +35,8 @@ export function useMobileNativeChatTurnStatus({ workingStartedAt?: number | null /** Host-recorded durations; they outrank whatever this client observed. */ settledTurns?: NativeChatSettledTurns | null + /** Whether the turn is reasoning right now, derived from its journal content. */ + thinking?: boolean /** Host/worktree/tab identity. Timings never carry across chat surfaces. */ scopeKey: string }): { @@ -45,7 +47,6 @@ export function useMobileNativeChatTurnStatus({ const latestUserIndex = enabled ? messages.findLastIndex((message) => message.role === 'user') : -1 - const hasCurrentTurnResponse = enabled && nativeChatTurnHasResponse(messages, latestUserIndex) const latestUserId = latestUserIndex !== -1 ? (messages[latestUserIndex]?.id ?? null) : null const activeTurnKey = latestUserId ?? MOBILE_UNANCHORED_TURN_KEY const [scopedTiming, setScopedTiming] = useState(() => ({ @@ -95,6 +96,7 @@ export function useMobileNativeChatTurnStatus({ // turn re-renders ~20x/s. Without this, every settled turn's row gets fresh // props each tick and the memoized message rows all re-render. const turnIsWorking = enabled && isWorking + const turnIsThinking = enabled && thinking const settledByTurn = enabled ? (settledTurns ?? undefined) : undefined const statuses = useMemo( () => @@ -102,17 +104,10 @@ export function useMobileNativeChatTurnStatus({ activeTurnKey, isWorking: turnIsWorking, workingStartedAt, - hasCurrentTurnResponse, + thinking: turnIsThinking, settledByTurn }), - [ - timingByTurn, - activeTurnKey, - turnIsWorking, - workingStartedAt, - hasCurrentTurnResponse, - settledByTurn - ] + [timingByTurn, activeTurnKey, turnIsWorking, workingStartedAt, turnIsThinking, settledByTurn] ) return { ...statuses, activeTurnKey } } diff --git a/mobile/src/session/use-mobile-session-controller.ts b/mobile/src/session/use-mobile-session-controller.ts index f188b30b17a..9847a5a5065 100644 --- a/mobile/src/session/use-mobile-session-controller.ts +++ b/mobile/src/session/use-mobile-session-controller.ts @@ -1,3 +1,4 @@ +import { useNotificationPaneNavigation } from './use-notification-pane-navigation' import { useMobileSessionFoundation } from './use-mobile-session-foundation' import { useMobileSessionScreenState } from './use-mobile-session-screen-state' import { useMobileSessionTerminalRuntime } from './use-mobile-session-terminal-runtime' @@ -82,6 +83,7 @@ export function useMobileSessionController() { useMobileSessionStartup(keyboardState) useMobileSessionPreferenceFocus(keyboardState) const tabSwitching = Object.assign(keyboardState, useMobileSessionTabSwitching(keyboardState)) + useNotificationPaneNavigation(tabSwitching) const terminalWebview = Object.assign(tabSwitching, useMobileSessionTerminalWebview(tabSwitching)) const terminalSendActions = Object.assign( terminalWebview, diff --git a/mobile/src/session/use-mobile-session-terminal-create-actions.test.ts b/mobile/src/session/use-mobile-session-terminal-create-actions.test.ts index e46bf087f38..17afae7380f 100644 --- a/mobile/src/session/use-mobile-session-terminal-create-actions.test.ts +++ b/mobile/src/session/use-mobile-session-terminal-create-actions.test.ts @@ -261,4 +261,49 @@ describe('mobile + Codex tab creation routing', () => { expect(scope.showToast).toHaveBeenCalledWith('create outcome ambiguous', 1800) } ) + // Why: pty exhaustion, a disabled agent and an unresolved worktree owner all arrived as the + // same 'Failed to create terminal', leaving the empty session with nothing to act on. + it('surfaces the host reason instead of a generic terminal-create error', async () => { + const client = clientReturning({ + ok: false, + error: { + code: 'runtime_error', + message: 'Your system cannot allocate any more pty devices.' + } + }) + const scope = createScope(client) + let actions: ReturnType | undefined + function Harness() { + actions = useMobileSessionTerminalCreateActions(scope as never) + return null + } + await act(async () => { + renderer = create(createElement(Harness)) + }) + await act(async () => { + await actions?.handleCreateTerminal() + }) + + expect(scope.setCreateError).toHaveBeenCalledWith( + 'Your system cannot allocate any more pty devices.' + ) + }) + + it('falls back to the generic message when the host gives no reason', async () => { + const client = clientReturning({ ok: false, error: { code: 'runtime_error', message: '' } }) + const scope = createScope(client) + let actions: ReturnType | undefined + function Harness() { + actions = useMobileSessionTerminalCreateActions(scope as never) + return null + } + await act(async () => { + renderer = create(createElement(Harness)) + }) + await act(async () => { + await actions?.handleCreateTerminal() + }) + + expect(scope.setCreateError).toHaveBeenCalledWith('Failed to create terminal') + }) }) diff --git a/mobile/src/session/use-mobile-session-terminal-create-actions.ts b/mobile/src/session/use-mobile-session-terminal-create-actions.ts index cf6e9441d10..1daa3eb1fa5 100644 --- a/mobile/src/session/use-mobile-session-terminal-create-actions.ts +++ b/mobile/src/session/use-mobile-session-terminal-create-actions.ts @@ -63,6 +63,17 @@ export function useMobileSessionTerminalCreateActions(scope: MobileSessionAttach .toString(36) .slice(2, 10)}` + // Why: the host names the real cause (pty exhaustion, disabled agent, unresolved worktree); + // collapsing every failure to 'Failed to create terminal' left the phone undiagnosable. + function reportCreateFailure(hostReason: string): void { + const reason = hostReason.trim() + setCreateError(reason || options?.errorToast || 'Failed to create terminal') + if (options?.errorToast) { + triggerError() + showToast(options.errorToast, 1800) + } + } + try { // Bare structured-provider launches follow host createSupport; prompted launches keep their startup semantics. if (isAgentSessionHandleProvider(agent) && options === undefined) { @@ -199,20 +210,10 @@ export function useMobileSessionTerminalCreateActions(scope: MobileSessionAttach } scheduleDelayedAction(() => void fetchSessionTabs(), 500) } else { - const message = options?.errorToast ?? 'Failed to create terminal' - setCreateError(message) - if (options?.errorToast) { - triggerError() - showToast(message, 1800) - } - } - } catch { - const message = options?.errorToast ?? 'Failed to create terminal' - setCreateError(message) - if (options?.errorToast) { - triggerError() - showToast(message, 1800) + reportCreateFailure((response as RpcFailure).error.message) } + } catch (error) { + reportCreateFailure(error instanceof Error ? error.message : '') } finally { creatingTerminalRef.current = false setCreating(false) diff --git a/mobile/src/session/use-mobile-structured-agent-session.ts b/mobile/src/session/use-mobile-structured-agent-session.ts index 5c458bbdd9f..938e881aec7 100644 --- a/mobile/src/session/use-mobile-structured-agent-session.ts +++ b/mobile/src/session/use-mobile-structured-agent-session.ts @@ -11,10 +11,12 @@ import { import { encodeNativeChatTranscriptIdentity } from '../../../src/shared/native-chat-transcript-retention' import type { MobileNativeChatSendOutcome } from './mobile-native-chat-send' import { projectStructuredAgentSessionMessages } from '../../../src/shared/structured-agent-session-message-projection' +import { hasUnansweredStructuredAgentSessionDispatch } from '../../../src/shared/structured-agent-session-projection' import { activeStructuredAgentSessionTurnId, - hasUnansweredStructuredAgentSessionDispatch -} from '../../../src/shared/structured-agent-session-projection' + isStructuredAgentSessionThinking +} from '../../../src/shared/structured-agent-session-live-turn' +import { selectStructuredAgentTurnActivity } from '../../../src/shared/native-chat-turn-activity' import { pendingStructuredApproval, pendingStructuredQuestion, @@ -31,6 +33,7 @@ import type { RpcClient } from '../transport/rpc-client' import type { MobileChatPermission } from './mobile-native-chat-permission' import type { MobileChatQuestion } from './mobile-native-chat-question' import type { MobileNativeChatSession } from './use-mobile-native-chat-session' +import type { NativeChatLiveTurnIndicator } from '../../../src/shared/native-chat-turn-status' import { useMobileStructuredAgentState } from './use-mobile-structured-agent-state' import { useMobileStructuredPromptResponses } from './use-mobile-structured-prompt-responses' import { useMobileStructuredAgentOptions } from './use-mobile-structured-agent-options' @@ -43,6 +46,8 @@ type StructuredMobileSession = ReturnType ({ thinking, activityText }), [thinking, activityText]) const status = state.status === 'idle' ? 'idle' : state.status const approvalPrompt = useMemo( () => state.items.find(pendingStructuredApproval) ?? null, @@ -296,6 +307,7 @@ export function useMobileStructuredAgentSession(args: { turnId !== null || hasUnansweredStructuredAgentSessionDispatch(state.submissions, state.fence), turnId, + turnIndicator, ...turnTiming, sendWithOutcome, cancel, diff --git a/mobile/src/session/use-mobile-structured-native-chat-send-bridge.test.ts b/mobile/src/session/use-mobile-structured-native-chat-send-bridge.test.ts new file mode 100644 index 00000000000..3cf432381c2 --- /dev/null +++ b/mobile/src/session/use-mobile-structured-native-chat-send-bridge.test.ts @@ -0,0 +1,88 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { AgentSessionHandleProvider } from '../../../src/shared/agent-session-provider-handle' +import type { MobileNativeChatSendOutcome } from './mobile-native-chat-send' +import type { MobileNativeChatSendOrigin } from './use-mobile-native-chat-drafts' +import { useMobileStructuredNativeChatSendBridge } from './use-mobile-structured-native-chat-send-bridge' + +const ORIGIN: MobileNativeChatSendOrigin = { + draftKey: 'draft', + draftEditGeneration: 0, + pendingKey: 'pending', + normalizedText: 'command', + baselineOccurrences: 0, + baselineTailMessageId: null, + baselineResolved: true +} + +describe('useMobileStructuredNativeChatSendBridge', () => { + let renderer: ReactTestRenderer | null = null + let sendWithOutcome: (text: string) => Promise + const acceptSend = vi.fn() + const captureSendOrigin = vi.fn(() => ORIGIN) + const clearDraftForSend = vi.fn() + const holdUnconfirmedSend = vi.fn() + const onSendError = vi.fn() + const restoreRejectedDraft = vi.fn() + const sendStructured = vi.fn() + + function Harness({ agent }: { agent: AgentSessionHandleProvider }): null { + sendWithOutcome = useMobileStructuredNativeChatSendBridge({ + agent, + acceptSend, + captureSendOrigin, + clearDraftForSend, + holdUnconfirmedSend, + onSendError, + restoreRejectedDraft, + sendStructured + }).sendWithOutcome + return null + } + + function mount(agent: AgentSessionHandleProvider): void { + act(() => { + renderer = create(createElement(Harness, { agent })) + }) + } + + beforeEach(() => { + vi.clearAllMocks() + }) + + afterEach(() => { + act(() => renderer?.unmount()) + renderer = null + }) + + it('optimistically echoes accepted commands owned by the active agent', async () => { + sendStructured.mockResolvedValue('accepted') + mount('claude') + + await expect(sendWithOutcome('/init')).resolves.toBe('accepted') + + expect(acceptSend).toHaveBeenCalledWith(ORIGIN, '/init', undefined) + expect(restoreRejectedDraft).not.toHaveBeenCalled() + }) + + it('holds unknown delivery for commands owned by the active agent', async () => { + sendStructured.mockResolvedValue('unknown') + mount('claude') + + await expect(sendWithOutcome('/review')).resolves.toBe('unknown') + + expect(holdUnconfirmedSend).toHaveBeenCalledWith(ORIGIN, '/review', expect.any(Function)) + expect(restoreRejectedDraft).not.toHaveBeenCalled() + }) + + it('keeps host-command reconciliation for Codex', async () => { + sendStructured.mockResolvedValue('unknown') + mount('codex') + + await expect(sendWithOutcome('/review')).resolves.toBe('unknown') + + expect(restoreRejectedDraft).toHaveBeenCalledWith(ORIGIN, '/review') + expect(holdUnconfirmedSend).not.toHaveBeenCalled() + }) +}) diff --git a/mobile/src/session/use-mobile-structured-native-chat-send-bridge.ts b/mobile/src/session/use-mobile-structured-native-chat-send-bridge.ts index 70261e9df9b..d1cfe3d42f4 100644 --- a/mobile/src/session/use-mobile-structured-native-chat-send-bridge.ts +++ b/mobile/src/session/use-mobile-structured-native-chat-send-bridge.ts @@ -1,4 +1,5 @@ import { useCallback } from 'react' +import type { AgentSessionHandleProvider } from '../../../src/shared/agent-session-provider-handle' import { isStructuredAgentSessionComposerCommand } from '../../../src/shared/structured-agent-session-composer' import type { MobileNativeChatSendOutcome } from './mobile-native-chat-send' import type { MobileNativeChatSendOrigin } from './use-mobile-native-chat-drafts' @@ -10,6 +11,7 @@ type StructuredNativeChatAttachment = { } export function useMobileStructuredNativeChatSendBridge(args: { + agent: AgentSessionHandleProvider sendStructured: ( text: string, images?: string[], @@ -37,6 +39,7 @@ export function useMobileStructuredNativeChatSendBridge(args: { } { const { acceptSend, + agent, captureSendOrigin, clearDraftForSend, holdUnconfirmedSend, @@ -56,6 +59,7 @@ export function useMobileStructuredNativeChatSendBridge(args: { onSendError('Message not sent (disconnected)') return 'rejected' } + const isHostCommand = isStructuredAgentSessionComposerCommand(text, agent) clearDraftForSend(origin, text) const outcome = attachments !== undefined @@ -66,19 +70,13 @@ export function useMobileStructuredNativeChatSendBridge(args: { ? await sendStructured(text, images) : await sendStructured(text) if (outcome === 'accepted') { - if ( - !isStructuredAgentSessionComposerCommand(text, 'codex') && - !isStructuredAgentSessionComposerCommand(text, 'claude') - ) { + if (!isHostCommand) { acceptSend(origin, text.trimEnd(), images) } return 'accepted' } if (outcome === 'unknown') { - if ( - isStructuredAgentSessionComposerCommand(text, 'codex') || - isStructuredAgentSessionComposerCommand(text, 'claude') - ) { + if (isHostCommand) { restoreRejectedDraft(origin, text) return 'unknown' } @@ -92,6 +90,7 @@ export function useMobileStructuredNativeChatSendBridge(args: { }, [ acceptSend, + agent, captureSendOrigin, clearDraftForSend, holdUnconfirmedSend, diff --git a/mobile/src/session/use-mobile-structured-turn-indicator.test.tsx b/mobile/src/session/use-mobile-structured-turn-indicator.test.tsx new file mode 100644 index 00000000000..8369ff03a17 --- /dev/null +++ b/mobile/src/session/use-mobile-structured-turn-indicator.test.tsx @@ -0,0 +1,138 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { AgentJournalRenderItem } from '../../../src/shared/agent-session-journal-types' +import type { AgentSessionSubscribeEvent } from '../../../src/shared/agent-session-wire' +import type { RpcClient } from '../transport/rpc-client' +import { useMobileStructuredAgentSession } from './use-mobile-structured-agent-session' + +function journalItem( + sequence: number, + body: AgentJournalRenderItem['body'] +): AgentJournalRenderItem { + return { itemId: `item-${sequence}`, revision: 1, sequence, observedAt: sequence, body } +} + +function snapshot(items: AgentJournalRenderItem[], fence: number): AgentSessionSubscribeEvent { + const newest = items.length + return { + type: 'snapshot', + sessionId: 'session-1', + fence, + page: { + sessionId: 'session-1', + epoch: 'epoch-1', + fence, + direction: 'tail', + items, + removedItemIds: [], + submissions: [], + window: { + oldest: { epoch: 'epoch-1', sequence: 1 }, + newest: { epoch: 'epoch-1', sequence: newest }, + nextCursor: { epoch: 'epoch-1', sequence: newest + 1 } + }, + liveCursor: { epoch: 'epoch-1', sequence: newest }, + hasOlder: false, + hasNewer: false + } + } as AgentSessionSubscribeEvent +} + +/** What the one live indicator row reads, resolved off the session journal. */ +describe('useMobileStructuredAgentSession turn indicator', () => { + let renderer: ReactTestRenderer | null = null + let hook: ReturnType | null = null + let listener: ((value: unknown) => void) | null = null + const sendRequest = vi.fn(async (method: string) => ({ + ok: true, + result: + method === 'agentSession.options' + ? { + models: [{ id: 'gpt-fast', label: 'GPT Fast', isDefault: true, efforts: [] }], + current: { model: 'gpt-fast' } + } + : {}, + _meta: { runtimeId: 'r1' } + })) + const subscribe = vi.fn((_method: string, _params: unknown, onData: (value: unknown) => void) => { + listener = onData + return vi.fn() + }) + const client = { sendRequest, subscribe } as unknown as RpcClient + // Stable across renders: a fresh callback would re-run the hold/subscribe effect + // and release the session out from under the test. + const onSendError = vi.fn() + + function Harness(): null { + hook = useMobileStructuredAgentSession({ + client, + sessionId: 'session-1', + sourceIdentity: 'host-a\0workspace-a', + enabled: true, + connected: true, + agent: 'codex', + onSendError + } as never) + return null + } + + beforeEach(() => { + vi.clearAllMocks() + listener = null + }) + + afterEach(() => { + act(() => renderer?.unmount()) + renderer = null + hook = null + }) + + const runningTurn = journalItem(1, { kind: 'turn', turnId: 'turn-1', state: 'running' }) + const reasoning = journalItem(2, { + kind: 'message', + role: 'reasoning', + blocks: [{ type: 'text', text: 'Weighing two approaches' }] + }) + + it('reads the live turn as reasoning while reasoning is its newest content', async () => { + act(() => { + renderer = create(createElement(Harness)) + }) + await vi.waitFor(() => expect(listener).not.toBeNull()) + + act(() => { + listener?.(snapshot([runningTurn, reasoning], 3)) + }) + + expect(hook?.turnIndicator).toEqual({ thinking: true, activityText: null }) + }) + + it('hands the row the provider copy once real content ends the reasoning', async () => { + act(() => { + renderer = create(createElement(Harness)) + }) + await vi.waitFor(() => expect(listener).not.toBeNull()) + + act(() => { + listener?.( + snapshot( + [ + runningTurn, + reasoning, + journalItem(3, { + kind: 'tool-call', + name: 'shell', + input: { command: 'pnpm lint' }, + state: 'running' + }), + journalItem(4, { kind: 'status', text: 'Updating the plan' }) + ], + 3 + ) + ) + }) + + expect(hook?.turnIndicator).toEqual({ thinking: false, activityText: 'Updating the plan' }) + }) +}) diff --git a/mobile/src/session/use-notification-pane-navigation.test.tsx b/mobile/src/session/use-notification-pane-navigation.test.tsx new file mode 100644 index 00000000000..1c3af0fdc95 --- /dev/null +++ b/mobile/src/session/use-notification-pane-navigation.test.tsx @@ -0,0 +1,67 @@ +import { createElement } from 'react' +import { act, create } from 'react-test-renderer' +import { expect, it, vi } from 'vitest' +import { + notificationPaneTab, + useNotificationPaneNavigation +} from './use-notification-pane-navigation' +import type { MobileSessionTab } from './mobile-session-route-types' +const route = vi.hoisted(() => ({ paneKey: '', setParams: vi.fn() })) +vi.mock('expo-router', () => ({ + useLocalSearchParams: () => ({ paneKey: route.paneKey }), + useRouter: () => ({ setParams: route.setParams }) +})) +const leaf = '11111111-1111-4111-8111-111111111111' +const tabs: MobileSessionTab[] = [ + { + type: 'terminal', + id: 'first', + parentTabId: 'tab-a', + leafId: leaf, + title: 'first', + terminal: 'pty-a', + isActive: true + }, + { + type: 'terminal', + id: 'second', + parentTabId: 'tab-b', + leafId: leaf, + title: 'agent', + terminal: 'pty-b', + isActive: false + } +] +it('selects the originating split pane, not the first tab; closed and invalid panes fall back', () => { + expect(notificationPaneTab(tabs, `tab-b:${leaf}`)).toBe(tabs[1]) + expect(notificationPaneTab(tabs, `closed:${leaf}`)).toBeUndefined() + expect(notificationPaneTab(tabs, 'invalid')).toBeUndefined() +}) +it('waits for tabs, switches through the existing action, and consumes the navigation request', async () => { + route.paneKey = `tab-b:${leaf}` + const switchSessionTab = vi.fn() + function Probe({ loaded }: { loaded: boolean }) { + useNotificationPaneNavigation({ + sessionTabs: loaded ? tabs : [], + terminalsLoaded: loaded, + switchSessionTab + }) + return null + } + let renderer: ReturnType + await act(async () => { + renderer = create(createElement(Probe, { loaded: false })) + }) + expect(switchSessionTab).not.toHaveBeenCalled() + await act(async () => { + renderer.update(createElement(Probe, { loaded: true })) + }) + expect(switchSessionTab).toHaveBeenCalledExactlyOnceWith(tabs[1]) + expect(route.setParams).toHaveBeenCalledWith({ paneKey: '' }) + route.paneKey = '' + await act(async () => { + renderer.update(createElement(Probe, { loaded: true })) + }) + expect(switchSessionTab).toHaveBeenCalledOnce() + await act(async () => renderer.unmount()) +}) diff --git a/mobile/src/session/use-notification-pane-navigation.ts b/mobile/src/session/use-notification-pane-navigation.ts new file mode 100644 index 00000000000..f6d3bb15cd4 --- /dev/null +++ b/mobile/src/session/use-notification-pane-navigation.ts @@ -0,0 +1,40 @@ +import { useEffect } from 'react' +import { useLocalSearchParams, useRouter } from 'expo-router' +import { parsePaneKey } from '../../../src/shared/stable-pane-id' +import type { MobileSessionTab } from './mobile-session-route-types' + +export function notificationPaneTab(tabs: readonly MobileSessionTab[], paneKey: string) { + const pane = parsePaneKey(paneKey) + if (!pane) { + return undefined + } + return tabs.find((tab) => + tab.type === 'terminal' + ? (tab.parentTabId ?? tab.id) === pane.tabId && tab.leafId === pane.leafId + : tab.type === 'agent-session' && tab.id === pane.tabId + ) +} + +export function useNotificationPaneNavigation({ + sessionTabs, + terminalsLoaded, + switchSessionTab +}: { + sessionTabs: MobileSessionTab[] + terminalsLoaded: boolean + switchSessionTab: (tab: MobileSessionTab) => void +}) { + const { paneKey } = useLocalSearchParams<{ paneKey?: string }>() + const router = useRouter() + useEffect(() => { + if (!terminalsLoaded || typeof paneKey !== 'string' || !paneKey) { + return + } + const tab = notificationPaneTab(sessionTabs, paneKey) + // Consume the tap even if the pane was closed; later snapshots must not steal selection. + router.setParams({ paneKey: '' }) + if (tab) { + switchSessionTab(tab) + } + }, [paneKey, terminalsLoaded, sessionTabs, switchSessionTab, router]) +} diff --git a/mobile/src/settings/native-notification-delivery-settings.test.tsx b/mobile/src/settings/native-notification-delivery-settings.test.tsx new file mode 100644 index 00000000000..bf94b75649e --- /dev/null +++ b/mobile/src/settings/native-notification-delivery-settings.test.tsx @@ -0,0 +1,151 @@ +import { createElement, useEffect } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { NativeNotificationDeliverySettings } from './native-notification-delivery-settings' + +const mocks = vi.hoisted(() => ({ + load: vi.fn(), + save: vi.fn(), + support: { resolved: true, supported: false }, + appState: null as null | ((state: string) => void) +})) +vi.mock('react-native', () => ({ + Text: 'Text', + AppState: { + addEventListener: (_event: string, callback: (state: string) => void) => { + mocks.appState = callback + return { remove() {} } + } + } +})) +vi.mock('expo-router', () => ({ + useFocusEffect: (callback: () => void) => useEffect(callback, [callback]) +})) +vi.mock('../notifications/NotificationDeliverySection', () => ({ + NotificationDeliverySection: 'Delivery' +})) +vi.mock('../notifications/notification-delivery-preferences', () => ({ + DEFAULT_NOTIFICATION_DELIVERY: { + onlyWhenDesktopAway: true, + sound: true, + suppressWhileViewing: true + }, + loadNotificationDeliveryPreferences: mocks.load +})) +vi.mock('../notifications/push-registration', () => ({ + setNotificationDeliveryPreferences: mocks.save +})) +vi.mock('../notifications/use-remote-push-capable-hosts', () => ({ + useRemotePushCapableHosts: () => mocks.support +})) +let renderer: ReactTestRenderer +const preferences = { onlyWhenDesktopAway: false, sound: false, suppressWhileViewing: true } +beforeEach(() => { + mocks.load.mockReset().mockResolvedValue(preferences) + mocks.save.mockReset().mockResolvedValue(undefined) + mocks.support = { resolved: true, supported: false } +}) +afterEach(() => { + act(() => renderer?.unmount()) +}) +const section = () => renderer.root.findByType('Delivery').props +it('keeps stored controls visible but disabled without consent and explains an old host', async () => { + await act(async () => { + renderer = create(createElement(NativeNotificationDeliverySettings, { enabled: false })) + }) + expect(section().value).toEqual(preferences) + expect(section().disabled).toBe(true) + expect(JSON.stringify(renderer.toJSON())).toContain('Pair an updated desktop') + await act(async () => { + renderer.update(createElement(NativeNotificationDeliverySettings, { enabled: true })) + }) + expect(section().disabled).toBe(false) +}) +it('disables edits until preferences load, then waits for save and retains the prior value on failure', async () => { + let load!: (value: typeof preferences) => void + mocks.load.mockReturnValue( + new Promise((resolve) => { + load = resolve + }) + ) + await act(async () => { + renderer = create(createElement(NativeNotificationDeliverySettings, { enabled: true })) + }) + expect(section().disabled).toBe(true) + await act(async () => { + load(preferences) + }) + let reject!: (error: Error) => void + mocks.save.mockReturnValue( + new Promise((_resolve, fail) => { + reject = fail + }) + ) + await act(async () => { + section().onChange({ ...preferences, sound: true }) + }) + expect(section().disabled).toBe(true) + await act(async () => { + reject(new Error('storage unavailable')) + }) + expect(section().value).toEqual(preferences) + expect(section().disabled).toBe(false) + expect(JSON.stringify(renderer.toJSON())).toContain('Could not save delivery settings') +}) +it('does not claim an upgrade is needed while probing or when a host supports push', async () => { + mocks.support = { resolved: false, supported: false } + await act(async () => { + renderer = create(createElement(NativeNotificationDeliverySettings, { enabled: true })) + }) + expect(JSON.stringify(renderer.toJSON())).not.toContain('Pair an updated desktop') + mocks.support = { resolved: true, supported: true } + await act(async () => { + renderer.update(createElement(NativeNotificationDeliverySettings, { enabled: true })) + }) + expect(JSON.stringify(renderer.toJSON())).not.toContain('Pair an updated desktop') +}) + +it.each(['resolve', 'reject'])('ignores a pre-save refresh that later %ss', async (outcome) => { + await act(async () => { + renderer = create(createElement(NativeNotificationDeliverySettings, { enabled: true })) + }) + let resolve!: (value: typeof preferences) => void + let reject!: (error: Error) => void + mocks.load.mockReturnValue( + new Promise((ok, fail) => { + resolve = ok + reject = fail + }) + ) + await act(async () => mocks.appState!('active')) + const saved = { ...preferences, sound: true } + await act(async () => section().onChange(saved)) + await act(async () => { + if (outcome === 'resolve') { + resolve(preferences) + } else { + reject(new Error('old read failed')) + } + }) + expect(section().value).toEqual(saved) + expect(JSON.stringify(renderer.toJSON())).not.toContain('Could not load') + await act(async () => section().onChange({ ...section().value, suppressWhileViewing: false })) + expect(mocks.save).toHaveBeenLastCalledWith({ ...saved, suppressWhileViewing: false }) +}) + +it('does not refresh while a save is in flight', async () => { + await act(async () => { + renderer = create(createElement(NativeNotificationDeliverySettings, { enabled: true })) + }) + let finish!: () => void + mocks.save.mockReturnValue( + new Promise((resolve) => { + finish = resolve + }) + ) + await act(async () => section().onChange({ ...preferences, sound: true })) + await act(async () => mocks.appState!('active')) + expect(mocks.load).toHaveBeenCalledTimes(1) + await act(async () => finish()) + expect(section().value.sound).toBe(true) +}) diff --git a/mobile/src/settings/native-notification-delivery-settings.tsx b/mobile/src/settings/native-notification-delivery-settings.tsx new file mode 100644 index 00000000000..109e28c6c69 --- /dev/null +++ b/mobile/src/settings/native-notification-delivery-settings.tsx @@ -0,0 +1,97 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { AppState, Text } from 'react-native' +import { useFocusEffect } from 'expo-router' +import { NotificationDeliverySection } from '../notifications/NotificationDeliverySection' +import { + DEFAULT_NOTIFICATION_DELIVERY, + loadNotificationDeliveryPreferences, + type NotificationDeliveryPreferences +} from '../notifications/notification-delivery-preferences' +import { setNotificationDeliveryPreferences } from '../notifications/push-registration' +import { useRemotePushCapableHosts } from '../notifications/use-remote-push-capable-hosts' +import { colors, spacing, typography } from '../theme/mobile-theme' + +export function NativeNotificationDeliverySettings({ enabled }: { enabled: boolean }) { + const [delivery, setDelivery] = useState(DEFAULT_NOTIFICATION_DELIVERY) + const [loaded, setLoaded] = useState(false) + const [saving, setSaving] = useState(false) + const [error, setError] = useState(null) + const refreshRevision = useRef(0) + const saveInProgress = useRef(false) + const support = useRemotePushCapableHosts() + const refresh = useCallback(async () => { + if (saveInProgress.current) { + return + } + const revision = ++refreshRevision.current + try { + const value = await loadNotificationDeliveryPreferences() + if (revision !== refreshRevision.current) { + return + } + setDelivery(value) + setLoaded(true) + setError(null) + } catch { + if (revision !== refreshRevision.current) { + return + } + setError('Could not load delivery settings. Reopen this screen to retry.') + } + }, []) + useFocusEffect( + useCallback(() => { + void refresh() + }, [refresh]) + ) + useEffect(() => { + const subscription = AppState.addEventListener('change', (state) => { + if (state === 'active') { + void refresh() + } + }) + return () => subscription.remove() + }, [refresh]) + const change = async (value: NotificationDeliveryPreferences) => { + if (saveInProgress.current) { + return + } + saveInProgress.current = true + refreshRevision.current += 1 + setSaving(true) + setError(null) + try { + await setNotificationDeliveryPreferences(value) + setDelivery(value) + } catch { + setError('Could not save delivery settings. Try again.') + } finally { + saveInProgress.current = false + setSaving(false) + } + } + const hintStyle = { + color: colors.textMuted, + fontSize: typography.metaSize, + marginTop: spacing.md + } + return ( + <> + void change(value)} + /> + {error && ( + + {error} + + )} + {support.resolved && !support.supported && ( + + Pair an updated desktop to receive notifications on this phone. + + )} + + ) +} diff --git a/mobile/src/settings/native-notification-settings-operations.ts b/mobile/src/settings/native-notification-settings-operations.ts index cd5da9584bf..4817a77c8a7 100644 --- a/mobile/src/settings/native-notification-settings-operations.ts +++ b/mobile/src/settings/native-notification-settings-operations.ts @@ -3,7 +3,8 @@ import { ensureNotificationPermissions, getNotificationPermissionState } from '../notifications/notification-permissions' -import { loadPushNotificationsEnabled, savePushNotificationsEnabled } from '../storage/preferences' +import { loadPushNotificationsEnabled } from '../storage/preferences' +import { setRemotePushEnabled } from '../notifications/push-registration' import type { NotificationSettingsOperations } from './notification-settings-operations' export const nativeNotificationSettingsOperations: NotificationSettingsOperations = { @@ -15,7 +16,7 @@ export const nativeNotificationSettingsOperations: NotificationSettingsOperation }, async preference(enabled) { if (enabled !== undefined) { - await savePushNotificationsEnabled(enabled) + await setRemotePushEnabled(enabled) } return { enabled: await loadPushNotificationsEnabled() } }, diff --git a/mobile/src/settings/notification-display-test.test.tsx b/mobile/src/settings/notification-display-test.test.tsx new file mode 100644 index 00000000000..ea5128c7fb5 --- /dev/null +++ b/mobile/src/settings/notification-display-test.test.tsx @@ -0,0 +1,88 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { NotificationDisplayTest } from './notification-display-test' + +const mocks = vi.hoisted(() => ({ + loadHosts: vi.fn(), + clients: [] as { state: string; client: { sendRequest: ReturnType } }[] +})) +vi.mock('react-native', () => ({ + Pressable: 'Pressable', + Text: 'Text', + View: 'View', + StyleSheet: { create: (value: unknown) => value, absoluteFillObject: {} } +})) +vi.mock('../transport/host-store', () => ({ loadHostCatalog: mocks.loadHosts })) +vi.mock('../transport/use-all-host-clients', () => ({ useAllHostClients: () => mocks.clients })) + +let renderer: ReactTestRenderer +beforeEach(() => { + mocks.loadHosts.mockReset().mockResolvedValue([{ id: 'first' }, { id: 'second' }]) + mocks.clients = [] +}) +afterEach(() => act(() => renderer?.unmount())) + +async function send() { + await act(async () => { + renderer = create(createElement(NotificationDisplayTest, { onTroubleshoot: vi.fn() })) + }) + await act(async () => renderer.root.findAllByType('Pressable')[0].props.onPress()) +} + +it.each([ + { ok: false, error: { code: 'method_not_found' } }, + { ok: false, error: { code: 'forbidden' } }, + { ok: true, result: { accepted: false, reason: 'not_registered' } } +])('tries the next desktop after a definitive non-delivery response %j', async (response) => { + const first = vi.fn().mockResolvedValue(response) + const second = vi.fn().mockResolvedValue({ ok: true, result: { accepted: true } }) + const third = vi.fn() + mocks.clients = [first, second, third].map((sendRequest) => ({ + state: 'connected', + client: { sendRequest } + })) + await send() + expect(second).toHaveBeenCalledExactlyOnceWith('notifications.testPush', null, { + timeoutMs: 20000, + failWhenDisconnected: true + }) + expect(third).not.toHaveBeenCalled() + expect(JSON.stringify(renderer.toJSON())).toContain('Accepted by Orca’s push service') +}) + +it('does not try another desktop after an uncertain transport failure', async () => { + const second = vi.fn() + mocks.clients = [ + { + state: 'connected', + client: { sendRequest: vi.fn().mockRejectedValue(new Error('timeout')) } + }, + { state: 'connected', client: { sendRequest: second } } + ] + await send() + expect(second).not.toHaveBeenCalled() + expect(JSON.stringify(renderer.toJSON())).toContain('timeout') +}) + +it('explains when every desktop needs registration or an update', async () => { + mocks.clients = [ + { ok: true, result: { accepted: false, reason: 'not_registered' } }, + { ok: false, error: { code: 'method_not_found' } } + ].map((response) => ({ + state: 'connected', + client: { sendRequest: vi.fn().mockResolvedValue(response) } + })) + await send() + expect(JSON.stringify(renderer.toJSON())).toContain('Reconnect to register this phone') +}) + +it.each([false, true])('explains missing pairing or connection (paired=%s)', async (paired) => { + if (!paired) { + mocks.loadHosts.mockResolvedValue([]) + } + await send() + expect(JSON.stringify(renderer.toJSON())).toContain( + paired ? 'Connect a desktop' : 'Pair a desktop' + ) +}) diff --git a/mobile/src/settings/notification-display-test.tsx b/mobile/src/settings/notification-display-test.tsx new file mode 100644 index 00000000000..f00c0af5625 --- /dev/null +++ b/mobile/src/settings/notification-display-test.tsx @@ -0,0 +1,125 @@ +import { useEffect, useRef, useState } from 'react' +import { Pressable, StyleSheet, Text, View } from 'react-native' +import { useAllHostClients } from '../transport/use-all-host-clients' +import { loadHostCatalog } from '../transport/host-store' +import type { MobilePushTestResult } from '../../../src/shared/mobile-push-contract' +import { colors, spacing, typography } from '../theme/mobile-theme' + +export function NotificationDisplayTest({ onTroubleshoot }: { onTroubleshoot: () => void }) { + const busy = useRef(false) + const [hostIds, setHostIds] = useState([]) + const [sending, setSending] = useState(false) + const [message, setMessage] = useState(null) + const clients = useAllHostClients(hostIds) + useEffect(() => { + void loadHostCatalog() + .then((hosts) => setHostIds(hosts.map((host) => host.id))) + .catch(() => setMessage('Could not load paired desktops.')) + }, []) + const run = async () => { + if (busy.current) { + return + } + busy.current = true + setSending(true) + setMessage(null) + try { + if (hostIds.length === 0) { + throw new Error('Pair a desktop and try again.') + } + const connected = clients.filter((entry) => entry.state === 'connected') + if (connected.length === 0) { + throw new Error('Connect a desktop and try again.') + } + let unavailable = 'Update your desktop to run this test.' + for (const { client } of connected) { + const response = await client.sendRequest('notifications.testPush', null, { + timeoutMs: 20000, + failWhenDisconnected: true + }) + if (!response.ok) { + const code = response.error?.code + if (code === 'forbidden' || code === 'method_not_found') { + continue + } + throw new Error('Could not reach the desktop. Try again.') + } + const result = response.result as MobilePushTestResult + if (result?.accepted) { + setMessage('Accepted by Orca’s push service. Check for the notification.') + return + } + if (result?.reason === 'not_registered') { + unavailable = 'Reconnect to register this phone for notifications.' + continue + } + throw new Error( + result?.reason === 'rate_limited' + ? 'Too many notifications. Try again later.' + : 'Could not send through Orca’s push service. Try again.' + ) + } + throw new Error(unavailable) + } catch (error) { + setMessage(error instanceof Error ? error.message : 'Could not send push test.') + } finally { + busy.current = false + setSending(false) + } + } + return ( + + Having trouble receiving alerts? + Send a test through Orca’s push service. + [styles.button, pressed && styles.pressed]} + onPress={() => void run()} + > + + + Send test notification + + + + {sending ? 'Sending…' : 'Send test notification'} + + + + + + Troubleshooting + + {message && ( + + {message} + + )} + + ) +} +const styles = StyleSheet.create({ + container: { marginTop: spacing.xl, gap: spacing.sm }, + label: { color: colors.textPrimary, fontSize: typography.bodySize, fontWeight: '600' }, + detail: { color: colors.textMuted, fontSize: typography.metaSize, lineHeight: 18 }, + button: { + alignSelf: 'flex-start', + backgroundColor: colors.bgRaised, + borderRadius: 8, + paddingVertical: spacing.sm, + paddingHorizontal: spacing.md + }, + sizingLabel: { opacity: 0 }, + buttonLabel: { ...StyleSheet.absoluteFillObject, alignItems: 'center', justifyContent: 'center' }, + troubleshootLink: { alignSelf: 'flex-start', paddingVertical: spacing.sm }, + linkText: { + color: colors.textSecondary, + fontSize: typography.metaSize, + textDecorationLine: 'underline' + }, + pressed: { opacity: 0.6 }, + buttonText: { color: colors.textPrimary, fontSize: typography.metaSize, fontWeight: '600' } +}) diff --git a/mobile/src/settings/notification-settings-screen.tsx b/mobile/src/settings/notification-settings-screen.tsx index 7da9be8a813..a0b8251a620 100644 --- a/mobile/src/settings/notification-settings-screen.tsx +++ b/mobile/src/settings/notification-settings-screen.tsx @@ -1,5 +1,5 @@ -import { useState, useCallback, useEffect } from 'react' -import { AppState, View, Text, StyleSheet, Pressable, Switch } from 'react-native' +import { useState, useCallback, useEffect, type ReactNode } from 'react' +import { AppState, View, Text, StyleSheet, Pressable, Switch, ScrollView } from 'react-native' import { useSafeAreaInsets } from 'react-native-safe-area-context' import { useFocusEffect } from 'expo-router' import type { NotificationSettingsOperations } from './notification-settings-operations' @@ -16,12 +16,17 @@ const DEFAULT_PERMISSION_STATE: NotificationPermissionState = { export default function NotificationsScreen({ operations, - onBack + onBack, + description, + children }: { operations: NotificationSettingsOperations onBack: () => void + description?: string + children?: (enabled: boolean) => ReactNode }) { const insets = useSafeAreaInsets() + const [saving, setSaving] = useState(false) const [error, setError] = useState(null) const [pushEnabled, setPushEnabled] = useState(false) const [permissionState, setPermissionState] = useState(DEFAULT_PERMISSION_STATE) @@ -57,6 +62,7 @@ export default function NotificationsScreen({ const togglePush = async (value: boolean) => { setError(null) + setSaving(true) try { const permission = await operations.permission(value) setPermissionState(permission) @@ -64,6 +70,8 @@ export default function NotificationsScreen({ setPushEnabled(saved.enabled) } catch { setError('Could not save notification settings. Try again.') + } finally { + setSaving(false) } } @@ -71,10 +79,17 @@ export default function NotificationsScreen({ const notificationsBlocked = permissionState.status === 'denied' const hint = notificationsBlocked ? 'Notifications are disabled in system settings.' - : 'Get notified on this device when an agent needs your input or finishes a task.' + : (description ?? + 'Get notified on this device when an agent needs your input or finishes a task.') return ( - + - Agent notifications + Enable notifications void togglePush(v)} trackColor={{ false: colors.bgRaised, true: colors.textSecondary }} thumbColor={colors.textPrimary} @@ -123,7 +138,8 @@ export default function NotificationsScreen({ )} - + {children?.(switchEnabled && !saving)} + ) } diff --git a/mobile/src/storage/preferences.test.ts b/mobile/src/storage/preferences.test.ts index b636ea12d3e..c8cfb54863a 100644 --- a/mobile/src/storage/preferences.test.ts +++ b/mobile/src/storage/preferences.test.ts @@ -278,8 +278,18 @@ describe('push notification preference', () => { vi.mocked(AsyncStorage.setItem).mockReset() }) + it.each(['true', 'false'])('requires fresh consent for legacy choice %s', async (legacy) => { + vi.mocked(AsyncStorage.getItem).mockImplementation(async (key) => + key === 'orca:pushNotificationsEnabled' ? legacy : null + ) + await expect(readPushNotificationsPreference()).resolves.toEqual({ value: null, loaded: true }) + await expect(loadPushNotificationsEnabled()).resolves.toBe(false) + }) + it('distinguishes an unset preference from an explicit disabled choice', async () => { - vi.mocked(AsyncStorage.getItem).mockResolvedValue(null) + vi.mocked(AsyncStorage.getItem).mockImplementation(async (key) => + key === 'orca:remotePushEnabled' ? 'true' : null + ) await expect(readPushNotificationsPreference()).resolves.toEqual({ value: null, loaded: true @@ -303,12 +313,17 @@ describe('push notification preference', () => { await expect(loadPushNotificationsEnabled()).resolves.toBe(false) }) - it('persists the onboarding decision in the existing mobile toggle', async () => { - await savePushNotificationsEnabled(true) - expect(AsyncStorage.setItem).toHaveBeenCalledWith('orca:pushNotificationsEnabled', 'true') - - await savePushNotificationsEnabled(false) - expect(AsyncStorage.setItem).toHaveBeenCalledWith('orca:pushNotificationsEnabled', 'false') + it('persists and reloads master consent', async () => { + const storage = new Map() + vi.mocked(AsyncStorage.getItem).mockImplementation(async (key) => storage.get(key) ?? null) + vi.mocked(AsyncStorage.setItem).mockImplementation(async (key, value) => { + storage.set(key, value) + }) + for (const enabled of [true, false]) { + await savePushNotificationsEnabled(enabled) + await expect(loadPushNotificationsEnabled()).resolves.toBe(enabled) + } + expect([...storage]).toEqual([['orca:pushServiceNotificationsEnabled', 'false']]) }) }) diff --git a/mobile/src/storage/preferences.ts b/mobile/src/storage/preferences.ts index 5173ac5bc8a..57420469609 100644 --- a/mobile/src/storage/preferences.ts +++ b/mobile/src/storage/preferences.ts @@ -1,7 +1,8 @@ import AsyncStorage from '@react-native-async-storage/async-storage' const PINS_PREFIX = 'orca:pins:' -const NOTIF_KEY = 'orca:pushNotificationsEnabled' +// Consent to the push service is separate from the old socket notification choice. +const NOTIF_KEY = 'orca:pushServiceNotificationsEnabled' export type PushNotificationsPreference = { readonly value: boolean | null @@ -30,6 +31,43 @@ export async function savePushNotificationsEnabled(enabled: boolean): Promise { + try { + const raw = await AsyncStorage.getItem(REMOTE_PUSH_HOST_REGISTRATIONS_KEY) + if (!raw) { + return EMPTY_REMOTE_PUSH_HOST_REGISTRATIONS + } + const parsed = JSON.parse(raw) as Record + return { + registeredHostIds: stringArray(parsed.registeredHostIds), + pendingUnregisterHostIds: stringArray(parsed.pendingUnregisterHostIds) + } + } catch { + return EMPTY_REMOTE_PUSH_HOST_REGISTRATIONS + } +} + +export async function saveRemotePushHostRegistrations( + value: RemotePushHostRegistrations +): Promise { + await AsyncStorage.setItem(REMOTE_PUSH_HOST_REGISTRATIONS_KEY, JSON.stringify(value)) +} + const TEXT_SCALE_KEY = 'orca:terminalTextScale' // Why: the mobile terminal fits the desktop's full column count to the phone diff --git a/mobile/src/tasks/worktree-create-retry.test.ts b/mobile/src/tasks/worktree-create-retry.test.ts index beb9d463e32..1611ed74c19 100644 --- a/mobile/src/tasks/worktree-create-retry.test.ts +++ b/mobile/src/tasks/worktree-create-retry.test.ts @@ -55,7 +55,7 @@ async function flush(): Promise { // cutover). Records every call so tests can assert on the clientMutationId. function scriptedClient( outcomes: Array< - | { id: string; displayName?: string } + | { id: string; displayName?: string; warning?: string } | { errorMessage: string } // takesMs models how long the ambiguity took to SURFACE — a clean close is // instant, a half-open socket waits out the liveness watchdog or the timeout. @@ -107,7 +107,8 @@ function scriptedClient( worktree: { id: outcome.id, ...(outcome.displayName !== undefined ? { displayName: outcome.displayName } : {}) - } + }, + ...(outcome.warning !== undefined ? { warning: outcome.warning } : {}) }, _meta: { runtimeId: 'r' } } @@ -116,6 +117,41 @@ function scriptedClient( } describe('createWorktreeWithNameRetry', () => { + // Why: `worktree.create` succeeds even when the startup terminal failed to spawn (pty + // exhaustion), and `warning` is the only place the host says so. + it('returns the host create warning alongside the worktree', async () => { + const attempts: Attempt[] = [] + const client = scriptedClient( + [{ id: 'wt-warned', warning: 'Failed to create the startup terminal for /w: no pty' }], + attempts + ) + await expect( + createWorktreeWithNameRetry({ + client, + baseName: 'puffin', + buildParams: (name) => ({ repo: 'id:r', name }), + worktreeCreateIdempotency: Promise.resolve(IDEMPOTENT_CREATE_SUPPORT) + }) + ).resolves.toEqual({ + worktreeId: 'wt-warned', + name: 'puffin', + warning: 'Failed to create the startup terminal for /w: no pty' + }) + }) + + it('omits a blank create warning', async () => { + const attempts: Attempt[] = [] + const client = scriptedClient([{ id: 'wt-clean', warning: ' ' }], attempts) + await expect( + createWorktreeWithNameRetry({ + client, + baseName: 'puffin', + buildParams: (name) => ({ repo: 'id:r', name }), + worktreeCreateIdempotency: Promise.resolve(IDEMPOTENT_CREATE_SUPPORT) + }) + ).resolves.toEqual({ worktreeId: 'wt-clean', name: 'puffin' }) + }) + it('waits for capability detection before sending a create', async () => { const attempts: Attempt[] = [] const client = scriptedClient([{ id: 'wt-ready' }], attempts) diff --git a/mobile/src/tasks/worktree-create-retry.ts b/mobile/src/tasks/worktree-create-retry.ts index a3fa8ae2e1b..b0f8f618773 100644 --- a/mobile/src/tasks/worktree-create-retry.ts +++ b/mobile/src/tasks/worktree-create-retry.ts @@ -21,7 +21,9 @@ import { // branches outlive worktrees in git, and remote branches/PRs aren't visible from // worktree.ps. Retry by appending -2, -3, ... mirroring the desktop createWorktree // loop in src/renderer/src/store/slices/worktrees.ts. -export type WorktreeCreateResult = { worktreeId: string; name: string } | { error: string } +export type WorktreeCreateResult = + | { worktreeId: string; name: string; warning?: string } + | { error: string } // Why: a create in flight when the mobile transport migrates (relay/direct // hand-off on shoddy cellular, relay lease rotation) rejects with a cutover error @@ -84,14 +86,19 @@ export async function createWorktreeWithNameRetry( if (response.ok) { const result = (response as RpcSuccess).result as { worktree: { id: string; displayName?: string } + warning?: string } const authoritativeName = result.worktree.displayName + // Why: a create can succeed with the startup terminal failing (pty exhaustion); dropping + // `warning` here is what lands the phone on an unexplained empty session. + const warning = typeof result.warning === 'string' ? result.warning.trim() : '' return { worktreeId: result.worktree.id, name: typeof authoritativeName === 'string' && authoritativeName.trim() ? authoritativeName - : candidateName + : candidateName, + ...(warning ? { warning } : {}) } } lastError = response.error.message diff --git a/mobile/src/terminal/terminal-viewport-refit-state.ts b/mobile/src/terminal/terminal-viewport-refit-state.ts index dfa4daadf4c..766345d8c73 100644 --- a/mobile/src/terminal/terminal-viewport-refit-state.ts +++ b/mobile/src/terminal/terminal-viewport-refit-state.ts @@ -1,4 +1,8 @@ import type { RpcResponse } from '../transport/types' +import { + isMethodNotFoundRefusal, + rpcObjectResultOrNull +} from '../transport/rpc-acceptance-policies' export type TerminalUpdateViewportCapability = 'unknown' | 'supported' | 'unsupported' @@ -14,17 +18,11 @@ export type TerminalViewportRefitTargetState = { } export function isTerminalUpdateViewportUpdated(response: RpcResponse): boolean { - if (!response.ok || typeof response.result !== 'object' || response.result == null) { - return false - } - return (response.result as { updated?: unknown }).updated === true + return rpcObjectResultOrNull(response)?.updated === true } export function isTerminalUpdateViewportApplied(response: RpcResponse): boolean { - if (!response.ok || typeof response.result !== 'object' || response.result == null) { - return false - } - return (response.result as { applied?: unknown }).applied === true + return rpcObjectResultOrNull(response)?.applied === true } export function resolveTerminalUpdateViewportCapability( @@ -33,7 +31,7 @@ export function resolveTerminalUpdateViewportCapability( if (response.ok) { return 'supported' } - return response.error.code === 'method_not_found' ? 'unsupported' : 'unknown' + return isMethodNotFoundRefusal(response) ? 'unsupported' : 'unknown' } // Why: defer height refits while typing, then coalesce every skipped layout diff --git a/mobile/src/transport/client-context.test.ts b/mobile/src/transport/client-context.test.ts index 56b227bdff7..f1af4b87b36 100644 --- a/mobile/src/transport/client-context.test.ts +++ b/mobile/src/transport/client-context.test.ts @@ -5,6 +5,9 @@ import type { ConnectionState } from './types' import type { RpcClient } from './rpc-client' import type { MobileConnectionPath } from './stable-logical-rpc-client' +const push = vi.hoisted(() => ({ attach: vi.fn(), detach: vi.fn() })) +vi.mock('../notifications/push-registration', () => ({ attachPushRegistration: push.attach })) + const connectMock = vi.fn() const loadHostsMock = vi.fn() @@ -141,6 +144,8 @@ async function renderHarness(hostId: string): Promise { } beforeEach(() => { + push.attach.mockReset().mockReturnValue(push.detach) + push.detach.mockReset() connectMock.mockReset() loadHostsMock.mockReset() }) @@ -707,3 +712,33 @@ describe('useAllHostClients', () => { } }) }) + +it('owns push registration for a paired host without mounting the home screen', async () => { + const client = makeFakeClient('handshaking') + connectMock.mockReturnValue(client) + loadHostsMock.mockResolvedValue([HOST]) + const harness = await renderHarness(HOST.id) + expect(push.attach).not.toHaveBeenCalled() + await act(async () => client.emitState('connected')) + expect(push.attach).toHaveBeenCalledExactlyOnceWith(HOST.id, client) + await act(async () => client.emitState('connected')) + expect(push.attach).toHaveBeenCalledOnce() + await act(async () => client.emitState('disconnected')) + expect(push.detach).toHaveBeenCalledOnce() + await act(async () => client.emitState('connected')) + expect(push.attach).toHaveBeenCalledTimes(2) + await act(async () => harness.unmount()) + expect(push.detach).toHaveBeenCalledTimes(2) +}) + +it('registers an already authenticated host and detaches on explicit disconnect', async () => { + const client = makeFakeClient('connected') + connectMock.mockReturnValue(client) + loadHostsMock.mockResolvedValue([HOST]) + const harness = await renderHarness(HOST.id) + expect(push.attach).toHaveBeenCalledExactlyOnceWith(HOST.id, client) + await act(async () => harness.disconnectHost(HOST.id)) + expect(push.detach).toHaveBeenCalledOnce() + await act(async () => harness.unmount()) + expect(push.detach).toHaveBeenCalledOnce() +}) diff --git a/mobile/src/transport/host-entry-opener.ts b/mobile/src/transport/host-entry-opener.ts index 03d6363c7c7..6a22d29bf5e 100644 --- a/mobile/src/transport/host-entry-opener.ts +++ b/mobile/src/transport/host-entry-opener.ts @@ -1,3 +1,4 @@ +import { attachPushRegistration } from '../notifications/push-registration' import { connectionLogStore, recordConnectionClientSessionStart @@ -113,11 +114,21 @@ export async function openHostClientEntry( client.close() return state.store.get(hostId) ?? null } - const unsubState = client.onStateChange((next) => { + let detachPushRegistration: (() => void) | null = null + const syncPushRegistration = (next: ConnectionState): void => { + if (next === 'connected') { + detachPushRegistration ??= attachPushRegistration(hostId, client) + } else { + detachPushRegistration?.() + detachPushRegistration = null + } + } + const unsubscribeState = client.onStateChange((next) => { const current = state.store.get(hostId) if (!current) { return } + syncPushRegistration(next) current.state = next state.notifyHostState(hostId, next) }) @@ -134,11 +145,16 @@ export async function openHostClientEntry( clientId: host.deviceToken, state: client.getState(), refCount: state.pendingAcquisitions.get(hostId) ?? 0, - unsubState, + unsubState: () => { + unsubscribeState() + detachPushRegistration?.() + detachPushRegistration = null + }, unsubConnectionPath } state.pendingAcquisitions.delete(hostId) state.store.set(hostId, entry) + syncPushRegistration(entry.state) settle() const priorFailureCount = state.retryScheduler.recordSuccess(hostId) if (priorFailureCount > 0) { diff --git a/mobile/src/transport/host-open-recovery.test.tsx b/mobile/src/transport/host-open-recovery.test.tsx index 70ebc131791..90e79c13976 100644 --- a/mobile/src/transport/host-open-recovery.test.tsx +++ b/mobile/src/transport/host-open-recovery.test.tsx @@ -1,3 +1,6 @@ +vi.mock('../notifications/push-registration', () => ({ + attachPushRegistration: () => () => {} +})) import { createElement, type ReactElement } from 'react' import { act, create } from 'react-test-renderer' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' diff --git a/mobile/src/transport/host-removal-lifecycle.test.ts b/mobile/src/transport/host-removal-lifecycle.test.ts index 6c96ef1c446..08313ff3780 100644 --- a/mobile/src/transport/host-removal-lifecycle.test.ts +++ b/mobile/src/transport/host-removal-lifecycle.test.ts @@ -1,91 +1,50 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' const removeHostMock = vi.hoisted(() => vi.fn()) -const asyncStorage = vi.hoisted(() => ({ - getItem: vi.fn(async () => null), - setItem: vi.fn(async () => undefined), - // Why removeItem is here: clearWatermark() swallows its own failures, so a mock - // missing this method turns the persisted-watermark cleanup into a caught - // TypeError — the assertion below would pass even if the call were deleted. - removeItem: vi.fn(async () => undefined) -})) - -vi.mock('@react-native-async-storage/async-storage', () => ({ default: asyncStorage })) +const unregisterPushMock = vi.hoisted(() => vi.fn(async () => vi.fn())) vi.mock('./host-store', () => ({ removeHost: (hostId: string) => removeHostMock(hostId) })) +vi.mock('../notifications/push-registration', () => ({ + unregisterPushForRemovedHost: (hostId: string) => unregisterPushMock(hostId) +})) + import { removeHostAndCloseClient } from './host-removal-lifecycle' -import { - getHostNotificationSession, - resetHostNotificationSessionsForTests -} from '../notifications/notification-reconnect-catchup' describe('host removal lifecycle', () => { beforeEach(() => { removeHostMock.mockReset() - asyncStorage.removeItem.mockClear() - resetHostNotificationSessionsForTests() + unregisterPushMock.mockClear() }) it('closes the client only after metadata removal commits', async () => { let commitRemoval: (() => void) | null = null - removeHostMock.mockReturnValue( - new Promise((resolve) => { - commitRemoval = resolve - }) - ) + removeHostMock.mockReturnValue(new Promise((resolve) => (commitRemoval = resolve))) const closeHostClient = vi.fn() - const removal = removeHostAndCloseClient('host-1', closeHostClient) expect(closeHostClient).not.toHaveBeenCalled() commitRemoval?.() await removal - expect(closeHostClient).toHaveBeenCalledWith('host-1') }) it('keeps the client open when metadata removal fails', async () => { removeHostMock.mockRejectedValue(new Error('storage unavailable')) const closeHostClient = vi.fn() - await expect(removeHostAndCloseClient('host-1', closeHostClient)).rejects.toThrow( 'storage unavailable' ) expect(closeHostClient).not.toHaveBeenCalled() }) - it('retires the notification session so a removed host leaves nothing behind', async () => { - // Round-1 review finding: the session lives at module scope (it must survive the - // subscription teardown a reconnect performs), so removal is the only thing that - // can retire it. Left behind, each remove/re-pair cycle strands a session plus up - // to 512 seen keys, and a re-paired host inherits a watermark it never earned. + it('drops the gateway push registration before the credentials it needs are gone', async () => { removeHostMock.mockResolvedValue(undefined) - const session = getHostNotificationSession('host-1') - session.lastDeliveredSeq = 42 - session.lastDeliveredEpoch = 'epoch-A' - await removeHostAndCloseClient('host-1', vi.fn()) - - // A fresh session for the same id — not the retained one. - const afterRemoval = getHostNotificationSession('host-1') - expect(afterRemoval).not.toBe(session) - expect(afterRemoval.lastDeliveredSeq).toBe(0) - expect(afterRemoval.lastDeliveredEpoch).toBeNull() - }) - - it('erases the persisted watermark, not just the in-memory session', async () => { - // Why separately from the test above: the session is process-local, the - // watermark is not. Retiring only the session lets a re-pair of the same host - // read the old seq off disk and resume against a counter it never saw — the - // catch-up would then start above the real cut and drop everything below it. - removeHostMock.mockResolvedValue(undefined) - - await removeHostAndCloseClient('host-1', vi.fn()) - // clearWatermark is fire-and-forget; let its microtask land. - await Promise.resolve() - - expect(asyncStorage.removeItem).toHaveBeenCalledWith('orca:mobileNotificationsWatermark:host-1') + expect(unregisterPushMock).toHaveBeenCalledWith('host-1') + expect(unregisterPushMock.mock.invocationCallOrder[0]).toBeLessThan( + removeHostMock.mock.invocationCallOrder[0] + ) }) }) diff --git a/mobile/src/transport/host-removal-lifecycle.ts b/mobile/src/transport/host-removal-lifecycle.ts index cd0a09cb67e..159c6bca59e 100644 --- a/mobile/src/transport/host-removal-lifecycle.ts +++ b/mobile/src/transport/host-removal-lifecycle.ts @@ -1,20 +1,20 @@ -import { - clearWatermark, - forgetHostNotificationSession -} from '../notifications/notification-reconnect-catchup' +import { unregisterPushForRemovedHost } from '../notifications/push-registration' import { removeHost } from './host-store' export async function removeHostAndCloseClient( hostId: string, forgetHostClient: (hostId: string) => void ): Promise { + // Why before removeHost: the unregister needs the still-authenticated client, and + // the desktop's own revoke path covers the case where this call cannot land. + const restorePushRegistration = await unregisterPushForRemovedHost(hostId) // Why: closing before the metadata commit can strand a still-paired host on // storage failure; closing immediately after success prevents socket leaks. - await removeHost(hostId) + try { + await removeHost(hostId) + } catch (error) { + restorePushRegistration() + throw error + } forgetHostClient(hostId) - // Why: the notification session outlives the socket by design (it must survive - // reconnects), so removal is the only thing that can retire it. Left behind, a - // re-pair of the same host would inherit a watermark for a counter it never saw. - forgetHostNotificationSession(hostId) - void clearWatermark(hostId) } diff --git a/mobile/src/transport/mobile-relay-direct-upgrade.ts b/mobile/src/transport/mobile-relay-direct-upgrade.ts index b804d6fb610..ed019262bca 100644 --- a/mobile/src/transport/mobile-relay-direct-upgrade.ts +++ b/mobile/src/transport/mobile-relay-direct-upgrade.ts @@ -21,7 +21,11 @@ import { type MobileRelayDirectUpgradeJournal } from './mobile-relay-direct-upgrade-journal' import type { RpcClient } from './rpc-client' -import type { HostProfile, RpcResponse } from './types' +import type { HostProfile } from './types' +import { + isMethodNotFoundRefusal, + requireRpcResultOrThrowCodedError +} from './rpc-acceptance-policies' export type MobileRelayDirectUpgradeResult = { host: HostProfile @@ -79,11 +83,13 @@ export async function upgradeDirectMobileRelay(args: { reqId: journal.reqId, newResumeTokenHash: journal.pendingResumeTokenHash }) - if (isMethodNotFound(provisionResponse)) { + if (isMethodNotFoundRefusal(provisionResponse)) { await dependencies.clearJournal(args.host.id) return null } - const installed = DeviceCredentialInstalledSchema.parse(requireSuccess(provisionResponse)) + const installed = DeviceCredentialInstalledSchema.parse( + requireRpcResultOrThrowCodedError(provisionResponse) + ) assertDirectInstall(journal, installed) const reconciled = await getEndpoints(args.client, journal.reqId) if (reconciled === 'method-not-found') { @@ -136,10 +142,10 @@ async function getEndpoints( installReqId: string ): Promise { const response = await client.sendRequest('pairing.getEndpoints', { installReqId }) - if (isMethodNotFound(response)) { + if (isMethodNotFoundRefusal(response)) { return 'method-not-found' } - return PairingGetEndpointsResultSchema.parse(requireSuccess(response)) + return PairingGetEndpointsResultSchema.parse(requireRpcResultOrThrowCodedError(response)) } function assertDirectInstall( @@ -162,14 +168,3 @@ function assertCommitted( throw new Error('relay credential install was not authoritatively reconciled') } } - -function requireSuccess(response: RpcResponse): unknown { - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result -} - -function isMethodNotFound(response: RpcResponse): boolean { - return !response.ok && response.error.code === 'method_not_found' -} diff --git a/mobile/src/transport/mobile-relay-pairing-recovery.ts b/mobile/src/transport/mobile-relay-pairing-recovery.ts index 26dc08620de..b37a18a06c2 100644 --- a/mobile/src/transport/mobile-relay-pairing-recovery.ts +++ b/mobile/src/transport/mobile-relay-pairing-recovery.ts @@ -25,7 +25,8 @@ import { type PairingCandidateClient } from './mobile-relay-physical-client' import { createRecoveringPairingRelayCandidate } from './pairing-relay-candidate' -import type { HostProfile, RpcResponse } from './types' +import type { HostProfile } from './types' +import { requireRpcResultOrThrowCodedError } from './rpc-acceptance-policies' export type MobileRelayPairingRecoveryResult = 'none' | 'recovered' | 'deferred' | 'abandoned' @@ -128,7 +129,7 @@ async function runRecovery( if (credential.kind === 'invite' && endpoints.installStatus?.state === 'not-found') { journal = await transitionToInviteAuthorization(journal, dependencies) const installed = DeviceCredentialInstalledSchema.parse( - requireSuccess( + requireRpcResultOrThrowCodedError( await client.sendRequest('pairing.provisionRelay', { reqId: journal.metadata.installReqId, newResumeTokenHash: journal.metadata.pendingResumeTokenHash @@ -220,7 +221,7 @@ async function getRecoveryStatus( kind: 'resume' | 'invite' ) { return PairingGetEndpointsResultSchema.parse( - requireSuccess( + requireRpcResultOrThrowCodedError( await client.sendRequest('pairing.getEndpoints', { installReqId: journal.metadata.installReqId, ...(kind === 'resume' ? { resumeConfirmReqId: journal.metadata.resumeConfirmReqId } : {}) @@ -294,13 +295,6 @@ function pairingRelay(journal: MobileRelayPairingJournal): PairingRelay { return { ...journal.metadata.relay, inviteToken: journal.secrets.inviteToken } } -function requireSuccess(response: RpcResponse): unknown { - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result -} - function assertCommitted( endpoints: ReturnType, installed: DeviceCredentialInstalled diff --git a/mobile/src/transport/mobile-relay-rpc-streams.ts b/mobile/src/transport/mobile-relay-rpc-streams.ts index abb2c12564b..3af5b2b3f5e 100644 --- a/mobile/src/transport/mobile-relay-rpc-streams.ts +++ b/mobile/src/transport/mobile-relay-rpc-streams.ts @@ -9,6 +9,7 @@ import { updateTerminalSubscriptionViewport } from './rpc-client-terminal-subscription' import { buildReadyStreamUnsubscribe } from './rpc-client-server-subscription' +import { isStreamingOpenerReply } from './rpc-acceptance-policies' import type { RpcClient } from './rpc-client' import type { RpcResponse, RpcSuccess } from './types' @@ -119,7 +120,7 @@ export class MobileRelayRpcStreams { } } } - if (response.ok && response.streaming !== true) { + if (response.ok && !isStreamingOpenerReply(response)) { this.cancelledSubscriptions.delete(response.id) } return true diff --git a/mobile/src/transport/pre-profile-pairing-coordinator.ts b/mobile/src/transport/pre-profile-pairing-coordinator.ts index a9b04320471..eb1f524334e 100644 --- a/mobile/src/transport/pre-profile-pairing-coordinator.ts +++ b/mobile/src/transport/pre-profile-pairing-coordinator.ts @@ -7,7 +7,11 @@ import { } from '../../../src/shared/mobile-relay-credential-contract' import { connect, type ConnectOptions } from './rpc-client' import { resolvePairingHostIdentity, saveHost } from './host-store' -import type { HostProfile, PairingOffer, RpcResponse } from './types' +import type { HostProfile, PairingOffer } from './types' +import { + isMethodNotFoundRefusal, + requireRpcResultOrThrowCodedError +} from './rpc-acceptance-policies' import { createMobileRelayPairingJournal, type MobileRelayPairingJournal @@ -219,7 +223,7 @@ async function runPairing( reqId: journal.metadata.installReqId, newResumeTokenHash: journal.metadata.pendingResumeTokenHash }) - if (isMethodNotFound(provision)) { + if (isMethodNotFoundRefusal(provision)) { if (winner.path !== 'direct') { throw new Error('relay pairing RPC unavailable after relay path authentication') } @@ -227,9 +231,11 @@ async function runPairing( await dependencies.clearJournal(journal.metadata.journalId) return { hostId } } - const installed = DeviceCredentialInstalledSchema.parse(requireSuccess(provision)) + const installed = DeviceCredentialInstalledSchema.parse( + requireRpcResultOrThrowCodedError(provision) + ) const endpoints = PairingGetEndpointsResultSchema.parse( - requireSuccess( + requireRpcResultOrThrowCodedError( await winner.client.sendRequest('pairing.getEndpoints', { installReqId: journal.metadata.installReqId }) @@ -283,17 +289,6 @@ function relayWebSocketUrl(relay: MobileRelayEndpoint): string { return url.toString() } -function requireSuccess(response: RpcResponse): unknown { - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result -} - -function isMethodNotFound(response: RpcResponse): boolean { - return !response.ok && response.error.code === 'method_not_found' -} - function assertCommittedInstall( status: | { state: 'not-found' } diff --git a/mobile/src/transport/rpc-acceptance-policies.test.ts b/mobile/src/transport/rpc-acceptance-policies.test.ts new file mode 100644 index 00000000000..2f2abc90e16 --- /dev/null +++ b/mobile/src/transport/rpc-acceptance-policies.test.ts @@ -0,0 +1,168 @@ +import { describe, expect, it } from 'vitest' +import type { RpcResponse } from './types' +import { + isMethodNotFoundRefusal, + isStreamingOpenerReply, + requireRpcResultOrThrowCodedError, + rpcObjectResultOrNull +} from './rpc-acceptance-policies' + +const meta = { runtimeId: 'runtime-1' } + +function success(result: unknown, streaming?: true): RpcResponse { + return { id: 'rpc-1', ok: true, result, _meta: meta, ...(streaming ? { streaming } : {}) } +} + +function refusal(code: string, message = 'Nope'): RpcResponse { + return { id: 'rpc-1', ok: false, error: { code, message }, _meta: meta } +} + +/** Every result partition a policy has to survive. */ +const resultPartitions: [string, unknown][] = [ + ['object result', { value: 1 }], + ['undefined result', undefined], + ['null result', null], + ['empty object result', {}], + ['numeric result', 7], + ['zero result', 0], + ['string result', 'done'], + ['empty string result', ''], + ['boolean result', false], + ['array result', [1, 2]], + ['empty array result', []] +] + +describe('requireRpcResultOrThrowCodedError', () => { + it.each(resultPartitions)('returns the %s untouched', (_label, result) => { + expect(requireRpcResultOrThrowCodedError(success(result))).toEqual(result) + }) + + it('returns an absent result field as undefined', () => { + const response = { id: 'rpc-1', ok: true, _meta: meta } as unknown as RpcResponse + expect(requireRpcResultOrThrowCodedError(response)).toBeUndefined() + }) + + it('throws a code-prefixed message on refusal', () => { + expect(() => requireRpcResultOrThrowCodedError(refusal('method_not_found', 'no such'))).toThrow( + 'method_not_found: no such' + ) + }) + + it('throws even when the refusal carries an empty message', () => { + expect(() => requireRpcResultOrThrowCodedError(refusal('runtime_error', ''))).toThrow( + 'runtime_error: ' + ) + }) +}) + +describe('rpcObjectResultOrNull', () => { + it('accepts a plain object result', () => { + expect(rpcObjectResultOrNull(success({ value: 1 }))).toEqual({ value: 1 }) + }) + + it('accepts an empty object result', () => { + expect(rpcObjectResultOrNull(success({}))).toEqual({}) + }) + + it('accepts an array result, because arrays are objects', () => { + expect(rpcObjectResultOrNull(success([1, 2]))).toEqual([1, 2]) + }) + + it.each([ + ['null', null], + ['undefined', undefined], + ['numeric', 7], + ['zero', 0], + ['string', 'done'], + ['empty string', ''], + ['boolean', false], + ['true', true] + ])('refuses a %s result', (_label, result) => { + expect(rpcObjectResultOrNull(success(result))).toBeNull() + }) + + it('refuses a refusal regardless of its code', () => { + expect(rpcObjectResultOrNull(refusal('method_not_found'))).toBeNull() + expect(rpcObjectResultOrNull(refusal('runtime_error'))).toBeNull() + }) +}) + +// A refusal that illegally carries success-shaped fields: without the `ok` check each of these +// would read the stray field and answer as if the call had succeeded. +describe('a refusal carrying stray success fields', () => { + const strayRefusal = { + id: 'rpc-1', + ok: false, + error: { code: 'method_not_found', message: 'Nope' }, + result: { value: 1 }, + streaming: true, + _meta: meta + } as unknown as RpcResponse + + it('yields null rather than the stray result', () => { + expect(rpcObjectResultOrNull(strayRefusal)).toBeNull() + }) + + it('is still recognised as method-not-found', () => { + expect(isMethodNotFoundRefusal(strayRefusal)).toBe(true) + }) + + // The mirror case: a success carrying a stray error must not read as a refusal. + it('does not read a success carrying a stray error as a refusal', () => { + const straySuccess = { + id: 'rpc-1', + ok: true, + result: { value: 1 }, + error: { code: 'method_not_found', message: 'Nope' }, + _meta: meta + } as unknown as RpcResponse + expect(isMethodNotFoundRefusal(straySuccess)).toBe(false) + }) +}) + +describe('isMethodNotFoundRefusal', () => { + it('matches only the method_not_found code', () => { + expect(isMethodNotFoundRefusal(refusal('method_not_found'))).toBe(true) + expect(isMethodNotFoundRefusal(refusal('runtime_error'))).toBe(false) + expect(isMethodNotFoundRefusal(refusal('METHOD_NOT_FOUND'))).toBe(false) + }) + + it('never matches a success, including one with a null result', () => { + expect(isMethodNotFoundRefusal(success(null))).toBe(false) + expect(isMethodNotFoundRefusal(success({ code: 'method_not_found' }))).toBe(false) + }) +}) + +describe('isStreamingOpenerReply', () => { + it('accepts a success flagged streaming', () => { + expect(isStreamingOpenerReply(success({ subscriptionId: 's1' }, true))).toBe(true) + }) + + it('refuses a success with no streaming flag', () => { + expect(isStreamingOpenerReply(success({ subscriptionId: 's1' }))).toBe(false) + }) + + // A truthy non-boolean off the wire must not open a stream: the registry would route it to + // handleStreamingResponse and wait for frames that never come. + it.each([['yes'], [1], [{}]])('refuses a truthy non-boolean streaming flag %j', (flag) => { + const response = { + id: 'rpc-1', + ok: true, + result: { subscriptionId: 's1' }, + streaming: flag, + _meta: meta + } as unknown as RpcResponse + expect(isStreamingOpenerReply(response)).toBe(false) + }) + + it('refuses a refusal even when it carries a streaming flag', () => { + const response = { + id: 'rpc-1', + ok: false, + error: { code: 'runtime_error', message: 'Nope' }, + streaming: true, + _meta: meta + } as unknown as RpcResponse + expect(isStreamingOpenerReply(response)).toBe(false) + }) +}) diff --git a/mobile/src/transport/rpc-acceptance-policies.ts b/mobile/src/transport/rpc-acceptance-policies.ts new file mode 100644 index 00000000000..742d94aafa7 --- /dev/null +++ b/mobile/src/transport/rpc-acceptance-policies.ts @@ -0,0 +1,33 @@ +import type { RpcResponse, RpcSuccess } from './types' + +// Named acceptance policies for RPC replies. Call sites used to hand-roll these +// predicates and did not agree with each other; each policy here preserves one +// call site's existing acceptance exactly. Do not merge two policies without +// proving every caller of both tolerates the wider or narrower set. + +/** Throws `code: message` on refusal. Diagnostic text; not user-facing. */ +export function requireRpcResultOrThrowCodedError(response: RpcResponse): unknown { + if (!response.ok) { + throw new Error(`${response.error.code}: ${response.error.message}`) + } + return response.result +} + +/** Accepts only a success whose result is a non-null object. Arrays qualify. */ +export function rpcObjectResultOrNull(response: RpcResponse): Record | null { + if (!response.ok || typeof response.result !== 'object' || response.result === null) { + return null + } + return response.result as Record +} + +export function isMethodNotFoundRefusal(response: RpcResponse): boolean { + return !response.ok && response.error.code === 'method_not_found' +} + +/** A success that opened a stream rather than delivering a terminal result. */ +export function isStreamingOpenerReply( + response: RpcResponse +): response is RpcSuccess & { streaming: true } { + return response.ok && response.streaming === true +} diff --git a/mobile/src/transport/rpc-client-stream-registry.ts b/mobile/src/transport/rpc-client-stream-registry.ts index ac20acdecc0..68e50a6e6dd 100644 --- a/mobile/src/transport/rpc-client-stream-registry.ts +++ b/mobile/src/transport/rpc-client-stream-registry.ts @@ -8,6 +8,7 @@ import { updateTerminalSubscriptionViewport } from './rpc-client-terminal-subscription' import { buildReadyStreamUnsubscribe } from './rpc-client-server-subscription' +import { isStreamingOpenerReply } from './rpc-acceptance-policies' import { isStreamingSubscriptionReadyResult, isTerminalSubscribedResult @@ -112,7 +113,7 @@ export class RpcClientStreamRegistry { } handleResponse(response: RpcResponse): boolean { - if (response.ok && response.streaming === true) { + if (isStreamingOpenerReply(response)) { this.handleStreamingResponse(response) return true } diff --git a/mobile/src/transport/rpc-client.ts b/mobile/src/transport/rpc-client.ts index 10f586d2780..38941483c4d 100644 --- a/mobile/src/transport/rpc-client.ts +++ b/mobile/src/transport/rpc-client.ts @@ -1,19 +1,11 @@ import type { BrowserScreencastFrame } from './browser-screencast-protocol' import { DirectRpcClient } from './direct-rpc-client' -import type { - ConnectionLogSink, - ConnectionState, - ForegroundNudgeReason, - RpcResponse -} from './types' +import type { ConnectionLogSink, ConnectionState, ForegroundNudgeReason } from './types' +import type { UnvalidatedRpcRequestPort } from './unvalidated-rpc-request-port' -export type SendRequestOptions = { - timeoutMs?: number - /** Include the connect wait in the caller's timeout budget. */ - budgetSpansConnect?: boolean - /** Reject instead of replaying the request after reconnect. */ - failWhenDisconnected?: boolean -} +// Re-export shim: the options type moved to the port module with the sender it belongs to, +// and re-exporting is what keeps that move from touching every importer. +export type { SendRequestOptions } from './unvalidated-rpc-request-port' type SubscribeOptions = { onBinaryFrame?: (frame: BrowserScreencastFrame) => void @@ -21,12 +13,9 @@ type SubscribeOptions = { type StreamingListener = (result: unknown) => void -export type RpcClient = { - sendRequest: ( - method: string, - params?: unknown, - options?: SendRequestOptions - ) => Promise +// Still structurally carries the raw sender, so holding a client is still holding the port — +// which is why the boundary is inventoried rather than merely declared. +export type RpcClient = UnvalidatedRpcRequestPort & { subscribe: ( method: string, params: unknown, diff --git a/mobile/src/transport/rpc-incompatible-reply-error.ts b/mobile/src/transport/rpc-incompatible-reply-error.ts new file mode 100644 index 00000000000..026732ca3b5 --- /dev/null +++ b/mobile/src/transport/rpc-incompatible-reply-error.ts @@ -0,0 +1,27 @@ +import type { RpcDecodeIssue } from './rpc-operation-contract' + +const INCOMPATIBLE_REPLY_MESSAGE_PREFIX = 'incompatible_reply: ' + +// Why: a reply the operation's reader cannot read says nothing about what the host did. +// On a mutation it is NOT evidence the mutation failed and authorizes no retry — only a +// host-negotiated idempotency capability inside its dedupe window does (see +// tasks/worktree-create-retry.ts). So this error is deliberately neither marked +// delivery-unknown nor shaped like the cutover error the retry loops replay on. +export class RpcIncompatibleReplyError extends Error { + constructor( + readonly operationName: string, + readonly method: string, + readonly issues: readonly RpcDecodeIssue[] + ) { + super(`${INCOMPATIBLE_REPLY_MESSAGE_PREFIX}${operationName} (${method})`) + } +} + +// Why: instanceof can miss across bundle copies, so also match by message, mirroring +// isLogicalClientCutoverError. +export function isRpcIncompatibleReplyError(error: unknown): boolean { + return ( + error instanceof RpcIncompatibleReplyError || + (error instanceof Error && error.message.startsWith(INCOMPATIBLE_REPLY_MESSAGE_PREFIX)) + ) +} diff --git a/mobile/src/transport/rpc-operation-barrier.test.ts b/mobile/src/transport/rpc-operation-barrier.test.ts new file mode 100644 index 00000000000..43c74198b44 --- /dev/null +++ b/mobile/src/transport/rpc-operation-barrier.test.ts @@ -0,0 +1,138 @@ +import { describe, expect, it } from 'vitest' +import type { RpcResponse } from './types' +import { FakeSession } from './mobile-endpoint-supervisor-test-fakes' +import { isRpcDeliveryUnknown, markRpcDeliveryUnknown } from './rpc-delivery-ambiguity' +import { interpretAtRpcBarrier, startRpcOperation } from './rpc-operation' +import { + rpcRefusal, + rpcSuccess, + terminalListAtBarrier, + workspaceListAtBarrier, + worktreePsProbeAtBarrier +} from './rpc-operation-test-families' + +const rows = { worktrees: [{ id: 'w1' }] } + +function deferred(): { promise: Promise; resolve: (value: T) => void } { + let resolve!: (value: T) => void + const promise = new Promise((resolvePromise) => { + resolve = resolvePromise + }) + return { promise, resolve } +} + +function replying(response: RpcResponse): FakeSession { + const session = new FakeSession('connected') + session.sendRequest.mockResolvedValue(response) + return session +} + +function settleAfter(milliseconds: number): Promise<'still waiting'> { + return new Promise((resolve) => setTimeout(() => resolve('still waiting'), milliseconds)) +} + +describe('the post-barrier combinator', () => { + it('starts every request before anything is awaited', () => { + const first = replying(rpcSuccess(rows)) + const second = replying(rpcSuccess({ terminals: [] })) + + startRpcOperation(first, workspaceListAtBarrier, {}) + startRpcOperation(second, terminalListAtBarrier, {}) + + expect(first.sendRequest).toHaveBeenCalledTimes(1) + expect(second.sendRequest).toHaveBeenCalledTimes(1) + }) + + it('yields one verdict per operation, in declared order', async () => { + const verdicts = await interpretAtRpcBarrier([ + startRpcOperation(replying(rpcSuccess(rows)), workspaceListAtBarrier, {}), + startRpcOperation(replying(rpcSuccess({ terminals: [] })), terminalListAtBarrier, {}), + startRpcOperation(replying(rpcSuccess(rows)), worktreePsProbeAtBarrier, {}) + ]) + + expect(verdicts).toEqual([rows, { terminals: [] }, false]) + }) + + // The bug class this exists to remove: whichever peer lost the race used to decide which + // error the user saw. Here the second request fails first in time and the first one refuses + // afterwards, and the declaration still decides. + it('interprets in declared order rather than completion order', async () => { + const lateRefusal = deferred() + const refusing = new FakeSession('connected') + refusing.sendRequest.mockReturnValue(lateRefusal.promise) + const dropped = new FakeSession('connected') + dropped.sendRequest.mockRejectedValue(new Error('socket closed first')) + + const barrier = interpretAtRpcBarrier([ + startRpcOperation(refusing, workspaceListAtBarrier, {}), + startRpcOperation(dropped, terminalListAtBarrier, {}) + ]) + lateRefusal.resolve(rpcRefusal('method_not_found', 'no such method')) + + await expect(barrier).rejects.toThrow('method_not_found: no such method') + }) + + it('keeps the middle operation error when a later one also fails', async () => { + const barrier = interpretAtRpcBarrier([ + startRpcOperation(replying(rpcSuccess(rows)), workspaceListAtBarrier, {}), + startRpcOperation( + replying(rpcRefusal('conflict', 'middle refused')), + workspaceListAtBarrier, + {} + ), + startRpcOperation( + replying(rpcRefusal('runtime_error', 'later refused')), + workspaceListAtBarrier, + {} + ) + ]) + + await expect(barrier).rejects.toThrow('conflict: middle refused') + }) + + it('does not interpret until every raw request has settled', async () => { + const refusing = replying(rpcRefusal('runtime_error', 'boom')) + const pending = deferred() + const stalled = new FakeSession('connected') + stalled.sendRequest.mockReturnValue(pending.promise) + + const barrier = interpretAtRpcBarrier([ + startRpcOperation(refusing, workspaceListAtBarrier, {}), + startRpcOperation(stalled, terminalListAtBarrier, {}) + ]) + const raced = await Promise.race([ + barrier.then( + () => 'resolved' as const, + () => 'rejected' as const + ), + settleAfter(50) + ]) + expect(raced).toBe('still waiting') + + pending.resolve(rpcSuccess({ terminals: [] })) + await expect(barrier).rejects.toThrow('runtime_error: boom') + }) + + it('rethrows a captured transport rejection as the original error object', async () => { + const error = markRpcDeliveryUnknown(new Error('socket closed before response')) + const dropped = new FakeSession('connected') + dropped.sendRequest.mockRejectedValue(error) + + const caught = await interpretAtRpcBarrier([ + startRpcOperation(replying(rpcSuccess(rows)), workspaceListAtBarrier, {}), + startRpcOperation(dropped, terminalListAtBarrier, {}) + ]).catch((thrown: unknown) => thrown) + + expect(caught).toBe(error) + expect(isRpcDeliveryUnknown(caught)).toBe(true) + }) + + it('applies the policy each family declared, at the barrier', async () => { + const verdicts = await interpretAtRpcBarrier([ + startRpcOperation(replying(rpcRefusal('runtime_error')), terminalListAtBarrier, {}), + startRpcOperation(replying(rpcRefusal('method_not_found')), worktreePsProbeAtBarrier, {}) + ]) + + expect(verdicts).toEqual([null, true]) + }) +}) diff --git a/mobile/src/transport/rpc-operation-cast-fence.test.ts b/mobile/src/transport/rpc-operation-cast-fence.test.ts new file mode 100644 index 00000000000..83d76eb87ab --- /dev/null +++ b/mobile/src/transport/rpc-operation-cast-fence.test.ts @@ -0,0 +1,256 @@ +import { readFileSync, readdirSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { extname, join, relative, resolve } from 'node:path' +import ts from 'typescript' +import { describe, expect, it } from 'vitest' + +/** + * Bans the escapes that would make the typed boundary decorative. + * + * An operation's whole claim is that a reply arrives as a declared type because a reader + * decoded it. `as`, `any` and a `@ts-` suppression each produce the same declared type without + * the decode, so one of them anywhere in an operation implementation buys back exactly the + * drift the contract removed — and it buys it silently, since the code still compiles and the + * types still read as validated. + * + * The fenced region includes the operation API, contract and result-reader factory, plus + * non-test files importing them and files that re-export a + * file that is (transitively). Step 4's operation modules therefore land inside the fence the + * moment they are written, with nothing to remember. + * + * What this does NOT catch, all accepted: + * - A lying reader. `z.unknown()` or a schema looser than the reply decodes anything, and no + * syntax check can tell a permissive schema from a wrong one. + * - Structural laundering: a helper in an unfenced module that returns the wrong type + * honestly, which the operation then consumes without a cast. + * - `!` non-null assertions, and the widening that an untyped intermediate variable gives + * you for free. + * - A screen. Screens are outside the region by design until they hold an operation; the + * raw-port inventory is what governs them. + */ + +const mobileRoot = fileURLToPath(new URL('../..', import.meta.url)) +const scannedRoots = ['app', 'src'].map((directory) => join(mobileRoot, directory)) +const sourceExtensions = new Set(['.js', '.jsx', '.ts', '.tsx']) +const transportRoot = join(mobileRoot, 'src', 'transport') + +/** Importing any of these is what makes a file an operation implementation. */ +const REGION_SEEDS = new Set( + ['rpc-operation', 'rpc-operation-contract', 'rpc-operation-result-reader'].map((name) => + join(transportRoot, name) + ) +) + +export type RpcOperationEscape = 'assertion' | 'any' | 'suppression' + +type CastFenceException = { + readonly file: string + readonly allows: readonly RpcOperationEscape[] +} + +/** + * The modules that own the `unknown` → declared-type transition, so the erasure has to land + * somewhere. Held as data, per escape kind, so an exception cannot quietly widen into the + * others. Every entry is also checked for staleness. + */ +const CAST_FENCE_EXCEPTIONS: readonly CastFenceException[] = [ + // The interpreter. Its casts re-apply type parameters that `AnyRpcOperation` erased on the + // way in; none of them invents a shape the reader did not already produce. + { file: 'src/transport/rpc-operation.ts', allows: ['assertion'] }, + // The reader factory. `safeParse` returns the schema's own output type as `unknown`. + { file: 'src/transport/rpc-operation-result-reader.ts', allows: ['assertion'] }, + // Nothing but suppressions: every directive in it is an assertion that tsc still rejects + // the thing above it, which is the compile fence's entire mechanism. + { file: 'src/transport/rpc-operation-compile-fence.ts', allows: ['suppression'] } +] + +// Text, not AST: a suppression is a comment, and comments are not nodes. A directive spelled +// inside a string literal therefore reads as one — which fails closed. +const SUPPRESSION = /@ts-(?:expect-error|ignore|nocheck)\b/ + +function sourceFiles(directory: string): string[] { + return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { + const path = join(directory, entry.name) + if (entry.isDirectory()) { + return entry.name === 'node_modules' ? [] : sourceFiles(path) + } + return [path] + }) +} + +function parse(path: string, source: string): ts.SourceFile { + const extension = extname(path) + return ts.createSourceFile( + path, + source, + ts.ScriptTarget.Latest, + true, + extension === '.tsx' || extension === '.jsx' ? ts.ScriptKind.TSX : ts.ScriptKind.TS + ) +} + +function resolvedSpecifier(path: string, node: ts.Node | undefined): string | null { + if (!node || !ts.isStringLiteral(node) || !node.text.startsWith('.')) { + return null + } + return resolve(path, '..', node.text) +} + +/** `as const` narrows a literal; it declares nothing the value was not already. */ +function isConstAssertion(node: ts.AsExpression): boolean { + return ( + ts.isTypeReferenceNode(node.type) && + ts.isIdentifier(node.type.typeName) && + node.type.typeName.text === 'const' + ) +} + +export function rpcOperationEscapes(path: string, source: string): RpcOperationEscape[] { + const found: RpcOperationEscape[] = [] + const visit = (node: ts.Node): void => { + if ( + (ts.isAsExpression(node) && !isConstAssertion(node)) || + ts.isTypeAssertionExpression(node) + ) { + found.push('assertion') + } + if (node.kind === ts.SyntaxKind.AnyKeyword) { + found.push('any') + } + ts.forEachChild(node, visit) + } + visit(parse(path, source)) + if (SUPPRESSION.test(source)) { + found.push('suppression') + } + return [...new Set(found)].sort() +} + +/** Imports and re-exports that make the importer part of the operation region. */ +function moduleEdges(path: string, source: string): { imports: string[]; reExports: string[] } { + const imports: string[] = [] + const reExports: string[] = [] + for (const statement of parse(path, source).statements) { + if (ts.isImportDeclaration(statement)) { + const target = resolvedSpecifier(path, statement.moduleSpecifier) + if (target) { + imports.push(target) + } + continue + } + if (ts.isExportDeclaration(statement) && statement.moduleSpecifier) { + const target = resolvedSpecifier(path, statement.moduleSpecifier) + if (target) { + imports.push(target) + reExports.push(target) + } + } + } + return { imports, reExports } +} + +const scanned = scannedRoots + .flatMap(sourceFiles) + .filter((path) => sourceExtensions.has(extname(path))) + .filter((path) => !/\.test\.tsx?$/.test(path)) + +const sources = new Map(scanned.map((path) => [path, readFileSync(path, 'utf8')] as const)) +const edges = new Map([...sources].map(([path, source]) => [path, moduleEdges(path, source)])) + +/** Modules are keyed without their extension, the way a relative specifier resolves. */ +function moduleKey(path: string): string { + return path.replace(/\.[jt]sx?$/, '') +} + +const region = new Set(scanned.filter((path) => REGION_SEEDS.has(moduleKey(path)))) +for (const [path, { imports }] of edges) { + if (imports.some((target) => REGION_SEEDS.has(target))) { + region.add(path) + } +} +// Fixpoint over re-export edges: a barrel that re-exports an operation module is in the fence +// too, which is where a cast would otherwise sit unwatched between definition and screen. +for (let changed = true; changed;) { + changed = false + const members = new Set([...region].map(moduleKey)) + for (const [path, { reExports }] of edges) { + if (!region.has(path) && reExports.some((target) => members.has(target))) { + region.add(path) + changed = true + } + } +} + +const relativeRegion = [...region].map((path) => + relative(mobileRoot, path).split(/[/\\]/).join('/') +) + +describe('RPC operation cast fence', () => { + const probe = join(mobileRoot, 'src', 'transport', 'probe.ts') + + it('recognizes each escape and leaves honest code alone', () => { + expect(rpcOperationEscapes(probe, 'const v = raw as WorkspaceRows')).toEqual(['assertion']) + expect(rpcOperationEscapes(probe, 'const v = raw as unknown as WorkspaceRows')).toEqual([ + 'assertion' + ]) + expect(rpcOperationEscapes(probe, 'const v: any = raw')).toEqual(['any']) + expect(rpcOperationEscapes(probe, 'function f(raw: any) {}')).toEqual(['any']) + expect(rpcOperationEscapes(probe, 'const v = raw as any')).toEqual(['any', 'assertion']) + expect(rpcOperationEscapes(probe, '// @ts-expect-error\nconst v = raw')).toEqual([ + 'suppression' + ]) + expect(rpcOperationEscapes(probe, '// @ts-ignore\nconst v = raw')).toEqual(['suppression']) + expect(rpcOperationEscapes(probe, "const v = ['a'] as const")).toEqual([]) + expect(rpcOperationEscapes(probe, 'const v = read(raw)')).toEqual([]) + expect(rpcOperationEscapes(probe, 'const v = raw satisfies WorkspaceRows')).toEqual([]) + expect(rpcOperationEscapes(probe, 'const v = value!')).toEqual([]) + }) + + it('puts every operation module in the fenced region', () => { + for (const file of [ + 'src/transport/rpc-operation.ts', + 'src/transport/rpc-operation-contract.ts', + 'src/transport/rpc-operation-test-families.ts', + 'src/transport/rpc-operation-compile-fence.ts', + 'src/transport/rpc-operation-result-reader.ts', + 'src/transport/rpc-incompatible-reply-error.ts' + ]) { + expect(relativeRegion, `${file} must be fenced`).toContain(file) + } + // A screen that only holds a client is governed by the raw-port inventory, not by this. + expect(relativeRegion).not.toContain('src/transport/rpc-client.ts') + }) + + it('has no operation module casting, widening or suppressing its way to a type', () => { + const allowed = new Map(CAST_FENCE_EXCEPTIONS.map((entry) => [entry.file, entry.allows])) + const offenders = [...region] + .map((path) => { + const file = relative(mobileRoot, path).split(/[/\\]/).join('/') + const escapes = rpcOperationEscapes(path, sources.get(path) ?? '') + const permitted = allowed.get(file) ?? [] + return { file, escapes: escapes.filter((escape) => !permitted.includes(escape)) } + }) + .filter((entry) => entry.escapes.length > 0) + .map((entry) => `${entry.file}: ${entry.escapes.join(', ')}`) + .sort() + + expect( + offenders, + 'Decode the reply with a reader instead. An operation that asserts its own result type is not typed.' + ).toEqual([]) + }) + + it('has no stale cast-fence exception', () => { + const stale = CAST_FENCE_EXCEPTIONS.flatMap((entry) => { + const path = join(mobileRoot, entry.file) + if (!region.has(path)) { + return [`${entry.file}: no longer in the fenced region`] + } + const escapes = rpcOperationEscapes(path, sources.get(path) ?? '') + return entry.allows + .filter((escape) => !escapes.includes(escape)) + .map((escape) => `${entry.file}: no longer uses '${escape}'`) + }) + expect(stale, 'Narrow or delete the exception in rpc-operation-cast-fence.test.ts.').toEqual([]) + }) +}) diff --git a/mobile/src/transport/rpc-operation-compile-fence.ts b/mobile/src/transport/rpc-operation-compile-fence.ts new file mode 100644 index 00000000000..3188774743c --- /dev/null +++ b/mobile/src/transport/rpc-operation-compile-fence.ts @@ -0,0 +1,191 @@ +import type { RpcClient } from './rpc-client' +import type { RpcMethodName, RpcParams, RpcSendParams } from './rpc-params-contract' +import { defineRpcOperation, runRpcOperation, startRpcOperation } from './rpc-operation' +import { rpcResultVariants } from './rpc-operation-result-reader' +import { + workspaceListAtBarrier, + workspaceListOrNull, + workspaceRowsReader, + worktreePsProbe, + type WorkspaceRows +} from './rpc-operation-test-families' +import type { + CapabilityProbeRpcDefinition, + ObjectResultRpcDefinition, + RequireResultRpcDefinition, + RpcAcceptanceName, + RpcCompatibleReader, + RpcOperation +} from './rpc-operation-contract' + +// Why this file exists: the descriptor's whole point is that a call site cannot pick the +// acceptance policy, the interpretation barrier, or the send-side params for itself. Every +// expect-error directive below is that claim as an assertion — tsc fails on a directive that +// stops catching an error, so `pnpm --dir mobile typecheck` is the gate. Nothing here runs and +// no app code imports it. + +declare const client: RpcClient + +// @ts-expect-error a variant reader combinator must have at least one reader +const _fenceEmptyVariantReaders = rpcResultVariants([]) + +export const fenceProbeWithReader: CapabilityProbeRpcDefinition<'worktree.ps', 'on-settle'> = { + name: 'fence.probeWithReader', + method: 'worktree.ps', + acceptance: 'method-not-found-refusal', + barrier: 'on-settle', + // @ts-expect-error a refusal-code probe reads no payload, so it cannot carry a reader + read: workspaceRowsReader +} + +// @ts-expect-error 'require-result-or-throw' has no value to return without a reader +export const fenceDecodingWithoutReader: RequireResultRpcDefinition< + 'worktree.ps', + 'rows', + WorkspaceRows, + 'on-settle' +> = { + name: 'fence.decodingWithoutReader', + method: 'worktree.ps', + acceptance: 'require-result-or-throw', + barrier: 'on-settle' +} + +// @ts-expect-error the four policies in rpc-acceptance-policies.ts are the whole vocabulary +export const fenceInventedPolicy: RpcAcceptanceName = 'no-error-means-fine' + +// A reader for a payload no acceptance policy here admits, i.e. one belonging to some other +// family's shape. +const fenceTextReader: RpcCompatibleReader = (raw) => ({ + compatible: true, + variant: 'text', + value: raw, + salvage: { droppedPaths: [], droppedCount: 0 } +}) + +export const fenceObjectPolicyWrongReader: ObjectResultRpcDefinition< + 'worktree.ps', + 'text', + string, + 'on-settle' +> = { + name: 'fence.objectPolicyWrongReader', + method: 'worktree.ps', + acceptance: 'object-result-or-null', + barrier: 'on-settle', + // @ts-expect-error the policy admits a non-null object, not the string this reader expects + read: fenceTextReader +} + +export const fenceDefineRejectsMismatch = defineRpcOperation({ + name: 'fence.defineRejectsMismatch', + method: 'worktree.ps', + // @ts-expect-error no overload of defineRpcOperation pairs a probe with a payload reader + acceptance: 'method-not-found-refusal', + barrier: 'on-settle', + // @ts-expect-error ... and the reader it would need is exactly what the probe overload bans + read: workspaceRowsReader +}) + +// @ts-expect-error only generated catalog method names are addressable +export const fenceUnknownMethod: RpcMethodName = 'worktree.nope' + +// The send-side params type. z.output (what the handler receives) and z.input (what the +// coercing builders admit) are both wrong for a sender in opposite directions, so these pin +// the two failures a regression to either one would reintroduce. + +// `query` and `limit` carry .default(), so a sender may leave them out. Under z.output both +// read as required and this line stops compiling. +export const fenceOmitsDefaultedField: RpcSendParams<'files.searchPaths'> = { worktree: 'w' } + +export const fenceRejectsWrongFieldType: RpcSendParams<'files.searchPaths'> = { + // @ts-expect-error z.input of a z.unknown().transform builder admits any value; this does not + worktree: 42 +} + +// @ts-expect-error `worktree` has neither a default nor an optional marker +export const fenceKeepsRequiredField: RpcSendParams<'files.searchPaths'> = { query: 'x' } + +// Catalog-wide: anything a handler could have been handed is something a sender may write. +// A method that ever resolves tighter than its parsed shape lands in this union. +declare const fenceTighterThanParsed: { + [Method in RpcMethodName]: RpcParams extends RpcSendParams ? never : Method +}[RpcMethodName] & {} +export const fenceNoTighterMethod: never = fenceTighterThanParsed + +// z.input collapses every coercing builder to `unknown`. Only plugins.panelAction may be +// unknown, because its schema is literally z.unknown(). +declare const fenceUnknownParams: { + [Method in RpcMethodName]: unknown extends RpcSendParams ? Method : never +}[RpcMethodName] & {} +export const fenceOnlyDeclaredUnknown: 'plugins.panelAction' = fenceUnknownParams + +export async function fenceBarrierAndParams(): Promise { + await runRpcOperation( + client, + // @ts-expect-error this family interprets after all requests, so it has no on-settle run + workspaceListAtBarrier, + {} + ) + startRpcOperation( + client, + // @ts-expect-error an on-settle family must not be parked behind someone else's barrier + worktreePsProbe, + {} + ) + await runRpcOperation( + client, + workspaceListOrNull, + // @ts-expect-error worktree.ps takes a numeric limit + { limit: 'ten' } + ) +} + +export async function fenceVerdictTypes(): Promise { + // @ts-expect-error the probe's policy yields a boolean, not the other family's rows + const rows: WorkspaceRows = await runRpcOperation(client, worktreePsProbe, {}) + void rows +} + +// @ts-expect-error the public descriptor also requires decoding, even without the factory +export const fenceManualWithoutReader: RpcOperation< + 'worktree.ps', + 'require-result-or-throw', + 'rows', + WorkspaceRows, + 'on-settle' +> = { + name: 'fence.manual', + method: 'worktree.ps', + acceptance: 'require-result-or-throw', + barrier: 'on-settle' +} + +// @ts-expect-error widening the policy cannot disconnect it from its required reader +export const fenceBroadWithoutReader: RpcOperation< + 'worktree.ps', + RpcAcceptanceName, + 'rows', + WorkspaceRows, + 'on-settle' +> = { + name: 'fence.broad', + method: 'worktree.ps', + acceptance: 'require-result-or-throw', + barrier: 'on-settle', + read: undefined +} + +// @ts-expect-error object acceptance must decode, just like require-result acceptance +export const fenceObjectWithoutReader: RpcOperation< + 'worktree.ps', + 'object-result-or-null', + 'rows', + WorkspaceRows, + 'on-settle' +> = { + name: 'fence.object', + method: 'worktree.ps', + acceptance: 'object-result-or-null', + barrier: 'on-settle' +} diff --git a/mobile/src/transport/rpc-operation-contract.ts b/mobile/src/transport/rpc-operation-contract.ts new file mode 100644 index 00000000000..581506a97a7 --- /dev/null +++ b/mobile/src/transport/rpc-operation-contract.ts @@ -0,0 +1,155 @@ +import type { RpcMethodName } from './rpc-params-contract' +import type { RpcFailure, RpcResponse, RpcSuccess } from './types' + +// An operation descriptor fixes the method, the acceptance policy and the interpretation +// barrier at definition time. Per-call freedom over those three is what produced acceptance +// drift and settlement-order drift across mobile's RPC call sites, so none of them is a +// parameter of any send helper. + +/** One of the named policies in rpc-acceptance-policies.ts, chosen per operation family. */ +export type RpcAcceptanceName = + | 'require-result-or-throw' + | 'object-result-or-null' + | 'method-not-found-refusal' + | 'streaming-opener' + +/** Where a settled reply may become a value or a throw. */ +export type RpcInterpretationBarrier = 'on-settle' | 'after-all-requests' + +export type RpcDecodeIssue = { readonly path: string; readonly message: string } + +/** Bounded salvage diagnostics for a reply that decoded with parts dropped. */ +export type RpcSalvageReport = { + readonly droppedPaths: readonly string[] + readonly droppedCount: number +} + +export type RpcReadResult = + | { + readonly compatible: true + readonly variant: Variant + readonly value: Value + readonly salvage: RpcSalvageReport + } + | { readonly compatible: false; readonly issues: readonly RpcDecodeIssue[] } + +/** Reads the payload its acceptance policy admits into one declared semantic variant. */ +export type RpcCompatibleReader = ( + raw: Raw +) => RpcReadResult + +export type RpcStreamOpenerReply = RpcSuccess & { streaming: true } + +// Only a fulfilled outer envelope is classified. Transport rejection stays on the promise +// channel, so an operation in a Promise.all still fails the group immediately instead of +// waiting for a peer and letting a later policy surface a different error. +export type RpcRequestOutcome = + | { + readonly kind: 'outer-refused' + readonly error: RpcFailure['error'] + readonly raw: RpcResponse + } + | { + readonly kind: 'decoded' + readonly variant: Variant + readonly value: Value + readonly raw: RpcResponse + readonly salvage: RpcSalvageReport + } + | { + readonly kind: 'incompatible' + readonly raw: RpcResponse + readonly issues: readonly RpcDecodeIssue[] + } + +export type RpcOperation< + Method extends RpcMethodName, + Acceptance extends RpcAcceptanceName, + Variant extends string, + Value, + Barrier extends RpcInterpretationBarrier +> = { + /** Family name, not the method: two families may share a method with different acceptance. */ + readonly name: string + readonly method: Method + readonly barrier: Barrier +} & { + [Policy in RpcAcceptanceName]: { + readonly acceptance: Policy + readonly read: Policy extends 'require-result-or-throw' | 'object-result-or-null' + ? RpcCompatibleReader + : undefined + } +}[Acceptance] + +// Internal interpreter view; public send APIs retain the policy/reader correlation. +export type AnyRpcOperation = Pick< + RpcOperation, + 'name' | 'method' | 'acceptance' | 'barrier' +> & { readonly read: RpcCompatibleReader | undefined } + +/** The verdict the declared policy yields. Not a per-call choice. */ +export type RpcVerdict< + Acceptance extends RpcAcceptanceName, + Value +> = Acceptance extends 'require-result-or-throw' + ? Value + : Acceptance extends 'object-result-or-null' + ? Value | null + : Acceptance extends 'method-not-found-refusal' + ? boolean + : Acceptance extends 'streaming-opener' + ? RpcStreamOpenerReply | null + : never + +export type RpcOperationSettlement = + | { readonly status: 'fulfilled'; readonly outcome: RpcRequestOutcome } + | { readonly status: 'rejected'; readonly error: unknown } + +type RpcOperationDefinition< + Method extends RpcMethodName, + Barrier extends RpcInterpretationBarrier +> = { + name: string + method: Method + barrier: Barrier +} + +export type RequireResultRpcDefinition< + Method extends RpcMethodName, + Variant extends string, + Value, + Barrier extends RpcInterpretationBarrier +> = RpcOperationDefinition & { + acceptance: 'require-result-or-throw' + read: RpcCompatibleReader +} + +export type ObjectResultRpcDefinition< + Method extends RpcMethodName, + Variant extends string, + Value, + Barrier extends RpcInterpretationBarrier +> = RpcOperationDefinition & { + acceptance: 'object-result-or-null' + // Raw is the non-null object rpcObjectResultOrNull admits; anything else is incompatible. + read: RpcCompatibleReader, Variant, Value> +} + +export type CapabilityProbeRpcDefinition< + Method extends RpcMethodName, + Barrier extends RpcInterpretationBarrier +> = RpcOperationDefinition & { + acceptance: 'method-not-found-refusal' + /** A probe answers from the refusal code alone, so a reader would have nothing to read. */ + read?: never +} + +export type StreamOpenerRpcDefinition< + Method extends RpcMethodName, + Barrier extends RpcInterpretationBarrier +> = RpcOperationDefinition & { + acceptance: 'streaming-opener' + /** The opener's value is the reply itself; frames arrive on the subscription, not here. */ + read?: never +} diff --git a/mobile/src/transport/rpc-operation-result-reader.test.ts b/mobile/src/transport/rpc-operation-result-reader.test.ts new file mode 100644 index 00000000000..0a5393352b3 --- /dev/null +++ b/mobile/src/transport/rpc-operation-result-reader.test.ts @@ -0,0 +1,145 @@ +import { describe, expect, it } from 'vitest' +import { z } from 'zod' +import { salvagingArray } from '../../../src/shared/zod-salvage' +import { FakeSession } from './mobile-endpoint-supervisor-test-fakes' +import { captureRpcOperationSettlement, defineRpcOperation } from './rpc-operation' +import { rpcResultVariant, rpcResultVariants } from './rpc-operation-result-reader' +import { + WORKSPACE_ROWS_SCHEMA, + rpcSuccess, + workspaceRowsReader +} from './rpc-operation-test-families' + +const SALVAGING_ROWS_SCHEMA = z.object({ + worktrees: salvagingArray(z.object({ id: z.string() })) +}) + +const salvagingReader = rpcResultVariant('rows', SALVAGING_ROWS_SCHEMA) + +describe('a single-variant reader', () => { + it('decodes a matching payload and reports nothing dropped', () => { + expect(workspaceRowsReader({ worktrees: [{ id: 'w1' }] })).toEqual({ + compatible: true, + variant: 'rows', + value: { worktrees: [{ id: 'w1' }] }, + salvage: { droppedPaths: [], droppedCount: 0 } + }) + }) + + it('reports dotted issue paths for a payload it cannot read', () => { + const result = workspaceRowsReader({ worktrees: [{ id: 1 }] }) + + expect(result.compatible).toBe(false) + if (result.compatible) { + throw new Error('expected an incompatible read') + } + expect(result.issues).toEqual([{ path: 'worktrees.0.id', message: expect.any(String) }]) + }) + + it('carries the salvage report when the schema drops an element', () => { + const result = salvagingReader({ worktrees: [{ id: 'w1' }, { id: 7 }] }) + + expect(result).toEqual({ + compatible: true, + variant: 'rows', + value: { worktrees: [{ id: 'w1' }] }, + // zod-salvage reports the path relative to the salvaging container, not the envelope. + salvage: { droppedPaths: ['1'], droppedCount: 1 } + }) + }) + + // zod-salvage keeps its collector at module level, so a leak here would blame the next + // reply for the previous one's drops. + it('does not leak drop diagnostics into the next read', () => { + salvagingReader({ worktrees: [{ id: 7 }] }) + + expect(salvagingReader({ worktrees: [{ id: 'w1' }] })).toMatchObject({ + salvage: { droppedPaths: [], droppedCount: 0 } + }) + }) + + it('bounds the issues it reports and says how many it dropped', () => { + const wide = { worktrees: Array.from({ length: 25 }, () => ({ id: 1 })) } + const result = workspaceRowsReader(wide) + + if (result.compatible) { + throw new Error('expected an incompatible read') + } + expect(result.issues).toHaveLength(21) + expect(result.issues[20]).toEqual({ path: '', message: '5 further issues omitted' }) + }) + + // The caveat that comes with zod-salvage: it wraps a synchronous parse only. An async + // schema must read as incompatible rather than leaking a promise into the outcome. + it('reads an async schema as incompatible instead of leaking a promise', () => { + const asyncReader = rpcResultVariant( + 'rows', + z.object({ id: z.string() }).refine(async () => true) + ) + + const result = asyncReader({ id: 'w1' }) + + expect(result.compatible).toBe(false) + if (result.compatible) { + throw new Error('expected an incompatible read') + } + expect(result.issues[0].message).toContain('synchronous parse') + }) +}) + +describe('a multi-variant reader', () => { + const reader = rpcResultVariants<'rows' | 'legacy-array', unknown>([ + workspaceRowsReader, + rpcResultVariant('legacy-array', z.array(z.object({ id: z.string() }))) + ]) + + it('takes the first declared variant that reads', () => { + expect(reader({ worktrees: [{ id: 'w1' }] })).toMatchObject({ variant: 'rows' }) + }) + + it('falls through to a later variant', () => { + expect(reader([{ id: 'w1' }])).toMatchObject({ + variant: 'legacy-array', + value: [{ id: 'w1' }] + }) + }) + + it('tags every variant it tried when none of them reads', () => { + const result = reader('neither shape') + + if (result.compatible) { + throw new Error('expected an incompatible read') + } + expect(result.issues.map((issue) => issue.path)).toEqual(['rows', 'legacy-array']) + }) +}) + +describe('salvage through a descriptor', () => { + const salvagingList = defineRpcOperation({ + name: 'test.salvagingWorkspaceList', + method: 'worktree.ps', + acceptance: 'require-result-or-throw', + barrier: 'on-settle', + read: salvagingReader + }) + + it('reports the dropped paths on the decoded outcome', async () => { + const session = new FakeSession('connected') + session.sendRequest.mockResolvedValue(rpcSuccess({ worktrees: [{ id: 'w1' }, { id: 7 }] })) + + const settlement = await captureRpcOperationSettlement(session, salvagingList, {}) + + expect(settlement.status === 'fulfilled' && settlement.outcome).toMatchObject({ + kind: 'decoded', + value: { worktrees: [{ id: 'w1' }] }, + salvage: { droppedPaths: ['1'], droppedCount: 1 } + }) + }) +}) + +describe('the shared workspace schema', () => { + it('is the strict shape the salvaging variant relaxes', () => { + expect(WORKSPACE_ROWS_SCHEMA.safeParse({ worktrees: [{ id: 7 }] }).success).toBe(false) + expect(SALVAGING_ROWS_SCHEMA.safeParse({ worktrees: [{ id: 7 }] }).success).toBe(true) + }) +}) diff --git a/mobile/src/transport/rpc-operation-result-reader.ts b/mobile/src/transport/rpc-operation-result-reader.ts new file mode 100644 index 00000000000..b9341e0e8bc --- /dev/null +++ b/mobile/src/transport/rpc-operation-result-reader.ts @@ -0,0 +1,89 @@ +import { z } from 'zod' +import { collectSalvageDrops } from '../../../src/shared/zod-salvage' +import type { RpcCompatibleReader, RpcDecodeIssue } from './rpc-operation-contract' + +const MAX_REPORTED_DECODE_ISSUES = 20 + +/** A reader that names the semantic variant it decodes, so a combinator can tag its issues. */ +export type NamedRpcResultReader = RpcCompatibleReader< + unknown, + Variant, + Value +> & { readonly variant: Variant } + +/** Builds a compatible reader for one semantic variant of a reply payload. */ +export function rpcResultVariant( + variant: Variant, + schema: Schema +): NamedRpcResultReader> { + const read: RpcCompatibleReader> = (raw) => { + try { + // Why: zod-salvage holds module-level collector state and wraps a *synchronous* + // parse only; safeParse throws on an async schema, which reads as incompatible. + const parsed = collectSalvageDrops(() => schema.safeParse(raw)) + if (!parsed.value.success) { + return { compatible: false, issues: decodeIssues(parsed.value.error) } + } + return { + compatible: true, + variant, + value: parsed.value.data as z.output, + salvage: { droppedPaths: parsed.droppedPaths, droppedCount: parsed.droppedCount } + } + } catch (error) { + return { compatible: false, issues: [{ path: '', message: describeThrow(error) }] } + } + } + return Object.assign(read, { variant }) +} + +/** Tries each variant in declared order and takes the first that reads. */ +export function rpcResultVariants( + readers: readonly [ + NamedRpcResultReader, + ...NamedRpcResultReader[] + ] +): RpcCompatibleReader { + return (raw) => { + const issues: RpcDecodeIssue[] = [] + for (const reader of readers) { + const result = reader(raw) + if (result.compatible) { + return result + } + for (const issue of result.issues) { + issues.push({ path: joinPath(reader.variant, issue.path), message: issue.message }) + } + } + return { compatible: false, issues: boundIssues(issues) } + } +} + +function decodeIssues(error: z.ZodError): RpcDecodeIssue[] { + return boundIssues( + error.issues.map((issue) => ({ + path: issue.path.map((segment) => String(segment)).join('.'), + message: issue.message + })) + ) +} + +// Why: a hostile or very foreign reply can issue per element; report a bounded sample and +// say how many were dropped rather than letting the diagnostic grow with the payload. +function boundIssues(issues: readonly RpcDecodeIssue[]): RpcDecodeIssue[] { + if (issues.length <= MAX_REPORTED_DECODE_ISSUES) { + return [...issues] + } + return [ + ...issues.slice(0, MAX_REPORTED_DECODE_ISSUES), + { path: '', message: `${issues.length - MAX_REPORTED_DECODE_ISSUES} further issues omitted` } + ] +} + +function joinPath(variant: string, path: string): string { + return path ? `${variant}.${path}` : variant +} + +function describeThrow(error: unknown): string { + return error instanceof Error ? error.message : String(error) +} diff --git a/mobile/src/transport/rpc-operation-test-families.ts b/mobile/src/transport/rpc-operation-test-families.ts new file mode 100644 index 00000000000..73554b7a4f8 --- /dev/null +++ b/mobile/src/transport/rpc-operation-test-families.ts @@ -0,0 +1,99 @@ +import { z } from 'zod' +import type { RpcResponse } from './types' +import type { RpcCompatibleReader } from './rpc-operation-contract' +import { rpcResultVariant, rpcResultVariants } from './rpc-operation-result-reader' +import { defineRpcOperation } from './rpc-operation' + +// Operation families used by the rpc-operation suites and by the compile fence. Kept in one +// place so the tests and the fence assert against the same descriptors, and so tsc sees them +// (the app tsconfig excludes *.test.ts). No app code imports this module. + +export const WORKSPACE_ROWS_SCHEMA = z.object({ + worktrees: z.array(z.object({ id: z.string() })) +}) + +const LEGACY_WORKSPACE_ROWS_SCHEMA = z.array(z.object({ id: z.string() })) + +export type WorkspaceRows = z.output +export type LegacyWorkspaceRows = z.output + +export const workspaceRowsReader = rpcResultVariant('rows', WORKSPACE_ROWS_SCHEMA) + +/** Two semantic variants: the modern envelope, then a host that answered a bare array. */ +export const workspaceRowsOrLegacyReader: RpcCompatibleReader< + unknown, + 'rows' | 'legacy-array', + WorkspaceRows | LegacyWorkspaceRows +> = rpcResultVariants<'rows' | 'legacy-array', WorkspaceRows | LegacyWorkspaceRows>([ + workspaceRowsReader, + rpcResultVariant('legacy-array', LEGACY_WORKSPACE_ROWS_SCHEMA) +]) + +export const workspaceListOrThrow = defineRpcOperation({ + name: 'test.workspaceListOrThrow', + method: 'worktree.ps', + acceptance: 'require-result-or-throw', + barrier: 'on-settle', + read: workspaceRowsOrLegacyReader +}) + +// Same method, a different family: main's callers disagreed about acceptance, so both rules +// stay named rather than being unified behind one descriptor. +export const workspaceListOrNull = defineRpcOperation({ + name: 'test.workspaceListOrNull', + method: 'worktree.ps', + acceptance: 'object-result-or-null', + barrier: 'on-settle', + read: workspaceRowsReader +}) + +export const worktreePsProbe = defineRpcOperation({ + name: 'test.worktreePsProbe', + method: 'worktree.ps', + acceptance: 'method-not-found-refusal', + barrier: 'on-settle' +}) + +export const terminalStreamOpener = defineRpcOperation({ + name: 'test.terminalStreamOpener', + method: 'terminal.subscribe', + acceptance: 'streaming-opener', + barrier: 'on-settle' +}) + +export const workspaceListAtBarrier = defineRpcOperation({ + name: 'test.workspaceListAtBarrier', + method: 'worktree.ps', + acceptance: 'require-result-or-throw', + barrier: 'after-all-requests', + read: workspaceRowsReader +}) + +export const terminalListAtBarrier = defineRpcOperation({ + name: 'test.terminalListAtBarrier', + method: 'terminal.list', + acceptance: 'object-result-or-null', + barrier: 'after-all-requests', + read: rpcResultVariant('terminals', z.object({ terminals: z.array(z.unknown()) })) +}) + +export const worktreePsProbeAtBarrier = defineRpcOperation({ + name: 'test.worktreePsProbeAtBarrier', + method: 'worktree.ps', + acceptance: 'method-not-found-refusal', + barrier: 'after-all-requests' +}) + +export function rpcSuccess(result: unknown, streaming?: true): RpcResponse { + return { + id: 'rpc-1', + ok: true, + result, + _meta: { runtimeId: 'runtime-1' }, + ...(streaming ? { streaming } : {}) + } +} + +export function rpcRefusal(code: string, message = 'Nope'): RpcResponse { + return { id: 'rpc-1', ok: false, error: { code, message }, _meta: { runtimeId: 'runtime-1' } } +} diff --git a/mobile/src/transport/rpc-operation.test.ts b/mobile/src/transport/rpc-operation.test.ts new file mode 100644 index 00000000000..91542b48528 --- /dev/null +++ b/mobile/src/transport/rpc-operation.test.ts @@ -0,0 +1,335 @@ +import { describe, expect, it } from 'vitest' +import type { RpcResponse } from './types' +import { FakeSession } from './mobile-endpoint-supervisor-test-fakes' +import { + createStableLogicalRpcClient, + isLogicalClientCutoverError +} from './stable-logical-rpc-client' +import { isRpcDeliveryUnknown, markRpcDeliveryUnknown } from './rpc-delivery-ambiguity' +import { + RpcIncompatibleReplyError, + isRpcIncompatibleReplyError +} from './rpc-incompatible-reply-error' +import { captureRpcOperationSettlement, runRpcOperation } from './rpc-operation' +import { + rpcRefusal, + rpcSuccess, + terminalListAtBarrier, + terminalStreamOpener, + workspaceListOrNull, + workspaceListOrThrow, + worktreePsProbe +} from './rpc-operation-test-families' + +function connectedSession(response?: RpcResponse): FakeSession { + const session = new FakeSession('connected') + if (response) { + session.sendRequest.mockResolvedValue(response) + } + return session +} + +const rows = { worktrees: [{ id: 'w1' }] } + +describe('request classification', () => { + it('decodes a compatible reply, naming the variant and keeping the raw envelope', async () => { + const response = rpcSuccess(rows) + const settlement = await captureRpcOperationSettlement( + connectedSession(response), + workspaceListOrThrow, + {} + ) + + expect(settlement).toEqual({ + status: 'fulfilled', + outcome: { + kind: 'decoded', + variant: 'rows', + value: rows, + raw: response, + salvage: { droppedPaths: [], droppedCount: 0 } + } + }) + }) + + it('names the legacy variant when the host answered the older shape', async () => { + const settlement = await captureRpcOperationSettlement( + connectedSession(rpcSuccess([{ id: 'w1' }])), + workspaceListOrThrow, + {} + ) + + expect(settlement.status === 'fulfilled' && settlement.outcome.kind).toBe('decoded') + expect(settlement.status === 'fulfilled' && settlement.outcome).toMatchObject({ + variant: 'legacy-array', + value: [{ id: 'w1' }] + }) + }) + + it('classifies a refusal as outer-refused rather than throwing', async () => { + const response = rpcRefusal('runtime_error', 'boom') + const settlement = await captureRpcOperationSettlement( + connectedSession(response), + workspaceListOrThrow, + {} + ) + + expect(settlement).toEqual({ + status: 'fulfilled', + outcome: { + kind: 'outer-refused', + error: { code: 'runtime_error', message: 'boom' }, + raw: response + } + }) + }) + + it('classifies a reply the reader cannot read as incompatible, with bounded issues', async () => { + const response = rpcSuccess({ worktrees: [{ id: 7 }] }) + const settlement = await captureRpcOperationSettlement( + connectedSession(response), + workspaceListOrThrow, + {} + ) + + expect(settlement.status).toBe('fulfilled') + if (settlement.status !== 'fulfilled' || settlement.outcome.kind !== 'incompatible') { + throw new Error('expected an incompatible outcome') + } + expect(settlement.outcome.raw).toBe(response) + expect(settlement.outcome.issues.map((issue) => issue.path)).toContain('rows.worktrees.0.id') + }) + + it('treats a reply that is not an object as incompatible for the nullable family', async () => { + const settlement = await captureRpcOperationSettlement( + connectedSession(rpcSuccess('not an object')), + workspaceListOrNull, + {} + ) + + expect(settlement.status === 'fulfilled' && settlement.outcome.kind).toBe('incompatible') + }) + + it('treats a throwing reader as incompatible, never as a transport failure', async () => { + const exploding = { + ...workspaceListOrThrow, + read: () => { + throw new Error('reader exploded') + } + } + const settlement = await captureRpcOperationSettlement( + connectedSession(rpcSuccess(rows)), + exploding, + {} + ) + + expect(settlement.status === 'fulfilled' && settlement.outcome.kind).toBe('incompatible') + }) +}) + +describe('transport rejection stays on the promise channel', () => { + it('rejects with the original error object', async () => { + const error = new Error('socket closed') + const session = new FakeSession('connected') + session.sendRequest.mockRejectedValue(error) + + await expect(runRpcOperation(session, workspaceListOrThrow, {})).rejects.toBe(error) + }) + + it('keeps a delivery-unknown mark readable through the descriptor', async () => { + const error = markRpcDeliveryUnknown(new Error('socket closed before response')) + const session = new FakeSession('connected') + session.sendRequest.mockRejectedValue(error) + + const caught = await runRpcOperation(session, workspaceListOrThrow, {}).catch( + (thrown: unknown) => thrown + ) + + expect(caught).toBe(error) + expect(isRpcDeliveryUnknown(caught)).toBe(true) + }) + + // The cutover predicate matches class or exact message because instanceof misses across + // bundle copies; a clone from another copy must still read as a cutover through the descriptor. + it('keeps a cutover error from another bundle copy recognisable', async () => { + class ForeignBundleCutoverError extends Error {} + const error = new ForeignBundleCutoverError('RPC interrupted by connection migration') + const session = new FakeSession('connected') + session.sendRequest.mockRejectedValue(error) + + const caught = await runRpcOperation(session, workspaceListOrThrow, {}).catch( + (thrown: unknown) => thrown + ) + + expect(caught).toBe(error) + expect(isLogicalClientCutoverError(caught)).toBe(true) + }) + + it('fails a Promise.all group immediately instead of waiting for a stalled peer', async () => { + const error = new Error('socket closed') + const failing = new FakeSession('connected') + failing.sendRequest.mockRejectedValue(error) + const stalled = new FakeSession('connected') + stalled.sendRequest.mockReturnValue(new Promise(() => {})) + + const group = Promise.all([ + runRpcOperation(failing, workspaceListOrThrow, {}), + runRpcOperation(stalled, workspaceListOrThrow, {}) + ]) + const raced = await Promise.race([ + group.then( + () => 'resolved' as const, + (caught: unknown) => caught + ), + new Promise((resolve) => setTimeout(() => resolve('still waiting'), 50)) + ]) + + expect(raced).toBe(error) + }) + + it('only captures a rejection when a caller names the all-settled helper', async () => { + const error = new Error('socket closed') + const session = new FakeSession('connected') + session.sendRequest.mockRejectedValue(error) + + await expect(captureRpcOperationSettlement(session, workspaceListOrThrow, {})).resolves.toEqual( + { status: 'rejected', error } + ) + }) +}) + +describe('the send path', () => { + it('carries the worktree.ps capability stamp, because it goes through the logical client', async () => { + const session = connectedSession(rpcSuccess(rows)) + const logical = createStableLogicalRpcClient(session, 'lan') + + await runRpcOperation(logical, workspaceListOrThrow, { limit: 500 }) + + expect(session.sendRequest).toHaveBeenCalledWith( + 'worktree.ps', + { limit: 500, supportsWorktreeVisibilitySourceDefaults: true }, + undefined + ) + }) + + it('sends the caller params object untouched for a method with no projection', async () => { + const session = connectedSession(rpcSuccess({ terminals: [] })) + const logical = createStableLogicalRpcClient(session, 'lan') + const params = { worktree: 'w1' } + + await captureRpcOperationSettlement(logical, terminalListAtBarrier, params, { + timeoutMs: 1234 + }) + + expect(session.sendRequest.mock.calls[0][0]).toBe('terminal.list') + expect(session.sendRequest.mock.calls[0][1]).toBe(params) + expect(session.sendRequest.mock.calls[0][2]).toEqual({ timeoutMs: 1234 }) + }) +}) + +describe('acceptance is a property of the family', () => { + const refusal = rpcRefusal('method_not_found', 'no such method') + + it('surfaces the refusal as a coded error for the throwing family', async () => { + await expect( + runRpcOperation(connectedSession(refusal), workspaceListOrThrow, {}) + ).rejects.toThrow('method_not_found: no such method') + }) + + it('answers null to the same refusal for the nullable family', async () => { + await expect( + runRpcOperation(connectedSession(refusal), workspaceListOrNull, {}) + ).resolves.toBeNull() + }) + + it('answers true to the same refusal for the capability probe', async () => { + await expect(runRpcOperation(connectedSession(refusal), worktreePsProbe, {})).resolves.toBe( + true + ) + }) + + it('keeps the probe false for another refusal code and for a success', async () => { + await expect( + runRpcOperation(connectedSession(rpcRefusal('runtime_error')), worktreePsProbe, {}) + ).resolves.toBe(false) + await expect( + runRpcOperation(connectedSession(rpcSuccess(rows)), worktreePsProbe, {}) + ).resolves.toBe(false) + }) + + it('returns the decoded value for the throwing family', async () => { + await expect( + runRpcOperation(connectedSession(rpcSuccess(rows)), workspaceListOrThrow, {}) + ).resolves.toEqual(rows) + }) + + it('returns the reply itself only when it opened a stream', async () => { + const opener = rpcSuccess({ subscriptionId: 's1' }, true) + await expect( + runRpcOperation(connectedSession(opener), terminalStreamOpener, { terminal: 't1' }) + ).resolves.toBe(opener) + await expect( + runRpcOperation( + connectedSession(rpcSuccess({ subscriptionId: 's1' })), + terminalStreamOpener, + { + terminal: 't1' + } + ) + ).resolves.toBeNull() + await expect( + runRpcOperation(connectedSession(rpcRefusal('runtime_error')), terminalStreamOpener, { + terminal: 't1' + }) + ).resolves.toBeNull() + }) +}) + +describe('an incompatible reply', () => { + const incompatible = rpcSuccess({ worktrees: [{ id: 7 }] }) + + it('throws a named incompatible-reply error for the throwing family', async () => { + const caught = await runRpcOperation( + connectedSession(incompatible), + workspaceListOrThrow, + {} + ).catch((thrown: unknown) => thrown) + + expect(caught).toBeInstanceOf(RpcIncompatibleReplyError) + expect(isRpcIncompatibleReplyError(caught)).toBe(true) + expect((caught as RpcIncompatibleReplyError).method).toBe('worktree.ps') + expect((caught as RpcIncompatibleReplyError).operationName).toBe('test.workspaceListOrThrow') + expect((caught as RpcIncompatibleReplyError).issues.length).toBeGreaterThan(0) + }) + + // A reply nobody can read says nothing about what the host did, so it must not look like + // either of the two errors the mutation retry loops replay on. + it('authorizes no retry', async () => { + const caught = await runRpcOperation( + connectedSession(incompatible), + workspaceListOrThrow, + {} + ).catch((thrown: unknown) => thrown) + + expect(isRpcDeliveryUnknown(caught)).toBe(false) + expect(isLogicalClientCutoverError(caught)).toBe(false) + }) + + it('answers null for the nullable family', async () => { + await expect( + runRpcOperation(connectedSession(incompatible), workspaceListOrNull, {}) + ).resolves.toBeNull() + }) +}) + +describe('a descriptor', () => { + it('cannot have its policy or barrier swapped at runtime', () => { + expect(Object.isFrozen(workspaceListOrThrow)).toBe(true) + expect(() => { + ;(workspaceListOrThrow as { acceptance: string }).acceptance = 'object-result-or-null' + }).toThrow(TypeError) + expect(() => { + ;(workspaceListOrThrow as { barrier: string }).barrier = 'after-all-requests' + }).toThrow(TypeError) + }) +}) diff --git a/mobile/src/transport/rpc-operation.ts b/mobile/src/transport/rpc-operation.ts new file mode 100644 index 00000000000..def072dac81 --- /dev/null +++ b/mobile/src/transport/rpc-operation.ts @@ -0,0 +1,282 @@ +import type { UnvalidatedRpcRequestPort, SendRequestOptions } from './unvalidated-rpc-request-port' +import type { RpcMethodName, RpcSendParams } from './rpc-params-contract' +import type { RpcResponse } from './types' +import { + isMethodNotFoundRefusal, + isStreamingOpenerReply, + requireRpcResultOrThrowCodedError, + rpcObjectResultOrNull +} from './rpc-acceptance-policies' +import { RpcIncompatibleReplyError } from './rpc-incompatible-reply-error' +import type { + AnyRpcOperation, + CapabilityProbeRpcDefinition, + ObjectResultRpcDefinition, + RpcAcceptanceName, + RpcCompatibleReader, + RpcDecodeIssue, + RpcInterpretationBarrier, + RpcOperation, + RpcOperationSettlement, + RpcRequestOutcome, + RpcSalvageReport, + RequireResultRpcDefinition, + StreamOpenerRpcDefinition, + RpcVerdict +} from './rpc-operation-contract' + +const NOTHING_SALVAGED: RpcSalvageReport = { droppedPaths: [], droppedCount: 0 } + +type RpcOperationDefinitionInput = + | RequireResultRpcDefinition + | ObjectResultRpcDefinition + | CapabilityProbeRpcDefinition + | StreamOpenerRpcDefinition + +export function defineRpcOperation< + Method extends RpcMethodName, + Variant extends string, + Value, + Barrier extends RpcInterpretationBarrier +>( + definition: RequireResultRpcDefinition +): RpcOperation +export function defineRpcOperation< + Method extends RpcMethodName, + Variant extends string, + Value, + Barrier extends RpcInterpretationBarrier +>( + definition: ObjectResultRpcDefinition +): RpcOperation +export function defineRpcOperation< + Method extends RpcMethodName, + Barrier extends RpcInterpretationBarrier +>( + definition: CapabilityProbeRpcDefinition +): RpcOperation +export function defineRpcOperation< + Method extends RpcMethodName, + Barrier extends RpcInterpretationBarrier +>( + definition: StreamOpenerRpcDefinition +): RpcOperation +export function defineRpcOperation(definition: RpcOperationDefinitionInput): AnyRpcOperation { + // Why: frozen so no call site can swap the policy or the barrier on a shared descriptor. + return Object.freeze({ + name: definition.name, + method: definition.method, + acceptance: definition.acceptance, + barrier: definition.barrier, + // Why: classifyReply only ever hands a reader the payload its own policy admitted, so + // the object policy's narrower parameter is sound to store as unknown. + read: definition.read as RpcCompatibleReader | undefined + }) +} + +/** Sends the operation without interpreting it; transport rejection stays on the promise. */ +async function request( + client: UnvalidatedRpcRequestPort, + operation: AnyRpcOperation, + params: unknown, + options?: SendRequestOptions +): Promise> { + // Why: no try/catch here. A transport failure must reach the caller as the original error + // object — isLogicalClientCutoverError and isRpcDeliveryUnknown both die on a wrapper — + // and an always-settled send would make Promise.all wait for a peer where today the group + // fails immediately, letting a later policy surface a different error. + const response = await client.sendRequest(operation.method, params, options) + return classifyReply(operation, response) +} + +type AdmittedPayload = + | { readonly admitted: true; readonly value: unknown } + | { readonly admitted: false; readonly issues: readonly RpcDecodeIssue[] } + +// The payload the operation's own acceptance policy admits from a fulfilled success. +function admitPayload(operation: AnyRpcOperation, response: RpcResponse): AdmittedPayload { + switch (operation.acceptance) { + case 'object-result-or-null': { + const object = rpcObjectResultOrNull(response) + return object === null + ? { admitted: false, issues: [{ path: 'result', message: 'not a non-null object' }] } + : { admitted: true, value: object } + } + case 'streaming-opener': + return isStreamingOpenerReply(response) + ? { admitted: true, value: response } + : { admitted: false, issues: [{ path: 'streaming', message: 'reply opened no stream' }] } + default: + // Reuses the policy rather than reading `.result` again; a success never throws here. + return { admitted: true, value: requireRpcResultOrThrowCodedError(response) } + } +} + +const READERLESS_VARIANTS: Record = { + 'method-not-found-refusal': 'accepted', + 'streaming-opener': 'stream-opened' +} + +function classifyReply( + operation: AnyRpcOperation, + response: RpcResponse +): RpcRequestOutcome { + if (!response.ok) { + return { kind: 'outer-refused', error: response.error, raw: response } + } + const payload = admitPayload(operation, response) + if (!payload.admitted) { + return { kind: 'incompatible', raw: response, issues: payload.issues } + } + const read = operation.read + if (!read) { + return { + kind: 'decoded', + variant: READERLESS_VARIANTS[operation.acceptance] ?? 'accepted', + value: payload.value, + raw: response, + salvage: NOTHING_SALVAGED + } + } + let result: ReturnType + try { + result = read(payload.value) + } catch (error) { + // A reader that throws is an incompatible reply, never a transport failure. + return { + kind: 'incompatible', + raw: response, + issues: [{ path: '', message: error instanceof Error ? error.message : String(error) }] + } + } + if (!result.compatible) { + return { kind: 'incompatible', raw: response, issues: result.issues } + } + return { + kind: 'decoded', + variant: result.variant, + value: result.value, + raw: response, + salvage: result.salvage + } +} + +// Applies the operation's declared acceptance policy. Private on purpose: there is no +// free-standing callOrThrow, so no call site can pick a different rule for the same reply. +function interpret( + operation: AnyRpcOperation, + settled: RpcRequestOutcome +): unknown { + const acceptance: RpcAcceptanceName = operation.acceptance + switch (acceptance) { + case 'require-result-or-throw': + if (settled.kind === 'outer-refused') { + // Reuses the policy so the thrown `code: message` text cannot drift from main's. + return requireRpcResultOrThrowCodedError(settled.raw) + } + if (settled.kind === 'incompatible') { + throw new RpcIncompatibleReplyError(operation.name, operation.method, settled.issues) + } + return settled.value + case 'object-result-or-null': + return settled.kind === 'decoded' ? settled.value : null + case 'method-not-found-refusal': + return settled.kind === 'outer-refused' ? isMethodNotFoundRefusal(settled.raw) : false + case 'streaming-opener': + return settled.kind === 'decoded' && isStreamingOpenerReply(settled.raw) ? settled.raw : null + } +} + +function interpretSettlement( + operation: AnyRpcOperation, + settlement: RpcOperationSettlement +): unknown { + if (settlement.status === 'rejected') { + // Why: rethrow the original object — isRpcDeliveryUnknown is a WeakSet on identity and + // isLogicalClientCutoverError matches class or exact message; a wrapper loses both. + throw settlement.error + } + return interpret(operation, settlement.outcome) +} + +/** Sends and interprets at the operation's own barrier. Only for barrier 'on-settle'. */ +export async function runRpcOperation< + Method extends RpcMethodName, + Acceptance extends RpcAcceptanceName, + Variant extends string, + Value +>( + client: UnvalidatedRpcRequestPort, + operation: RpcOperation, + params: RpcSendParams, + options?: SendRequestOptions +): Promise> { + const outcome = await request(client, operation, params, options) + return interpret(operation, outcome) as RpcVerdict +} + +/** The named opt-in to all-settled semantics. Yields an outcome, never a verdict: the + * verdict still comes only from the declared policy, at the declared barrier. */ +export async function captureRpcOperationSettlement< + Method extends RpcMethodName, + Acceptance extends RpcAcceptanceName, + Variant extends string, + Value, + Barrier extends RpcInterpretationBarrier +>( + client: UnvalidatedRpcRequestPort, + operation: RpcOperation, + params: RpcSendParams, + options?: SendRequestOptions +): Promise> { + try { + const outcome = await request(client, operation, params, options) + return { status: 'fulfilled', outcome: outcome as RpcRequestOutcome } + } catch (error) { + return { status: 'rejected', error } + } +} + +export type PendingRpcOperation = { + readonly operation: Op + readonly settlement: Promise> +} + +/** Starts a request whose interpretation is deferred to the barrier it declared. */ +export function startRpcOperation< + Method extends RpcMethodName, + Acceptance extends RpcAcceptanceName, + Variant extends string, + Value +>( + client: UnvalidatedRpcRequestPort, + operation: RpcOperation, + params: RpcSendParams, + options?: SendRequestOptions +): PendingRpcOperation> { + return { + operation, + settlement: captureRpcOperationSettlement(client, operation, params, options) + } +} + +type RpcBarrierVerdicts[]> = { + [Index in keyof Pending]: Pending[Index] extends PendingRpcOperation< + RpcOperation + > + ? RpcVerdict + : never +} + +/** Awaits every raw request, then interprets in declared order. */ +export async function interpretAtRpcBarrier< + Pending extends readonly PendingRpcOperation[] +>(pending: Pending): Promise> { + // Why: interpreting as each request lands would let whichever peer failed first decide the + // error the user sees and how long the screen spins. Declared order makes that a property + // of the definition instead of a race. + const settlements = await Promise.all(pending.map((entry) => entry.settlement)) + return pending.map((entry, index) => + interpretSettlement(entry.operation, settlements[index]) + ) as RpcBarrierVerdicts +} diff --git a/mobile/src/transport/rpc-params-contract.ts b/mobile/src/transport/rpc-params-contract.ts new file mode 100644 index 00000000000..883a921c079 --- /dev/null +++ b/mobile/src/transport/rpc-params-contract.ts @@ -0,0 +1,12 @@ +// Why: mobile's only entry to the host's params contract, and type-only on purpose. +// The schemas behind these types must never reach the bundle: requiredString is +// z.unknown().transform(...), so a client-side parse coerces a non-string to '' +// instead of rejecting it, silently changing the bytes on the wire. +// +// RpcSendParams is the outgoing type; RpcParams is the shape the handler sees after +// parsing, which is not what a sender may write (see rpc-send-params.ts). +export type { + RpcMethodName, + RpcParams +} from '../../../src/shared/rpc-contract/rpc-params-catalog.generated' +export type { RpcSendParams } from '../../../src/shared/rpc-contract/rpc-send-params' diff --git a/mobile/src/transport/runtime-capability-probe.ts b/mobile/src/transport/runtime-capability-probe.ts index ef636552863..6bec0ca05bd 100644 --- a/mobile/src/transport/runtime-capability-probe.ts +++ b/mobile/src/transport/runtime-capability-probe.ts @@ -10,7 +10,7 @@ const FAILURE_RETRY_BASE_DELAY_MS = 1_000 const FAILURE_RETRY_MAX_DELAY_MS = 15_000 export function startRuntimeCapabilityProbe( - client: RpcClient, + client: Pick, onCapabilities: (capabilities: readonly string[]) => void ): () => void { let cancelled = false diff --git a/mobile/src/transport/settings-host-client-lifecycle.test.ts b/mobile/src/transport/settings-host-client-lifecycle.test.ts index be7621017ba..bd0c2048637 100644 --- a/mobile/src/transport/settings-host-client-lifecycle.test.ts +++ b/mobile/src/transport/settings-host-client-lifecycle.test.ts @@ -1,3 +1,6 @@ +vi.mock('../notifications/push-registration', () => ({ + attachPushRegistration: () => () => {} +})) import { createElement, Fragment, useEffect } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { beforeEach, describe, expect, it, vi } from 'vitest' diff --git a/mobile/src/transport/unvalidated-rpc-request-port-boundary.test.ts b/mobile/src/transport/unvalidated-rpc-request-port-boundary.test.ts new file mode 100644 index 00000000000..422b2925689 --- /dev/null +++ b/mobile/src/transport/unvalidated-rpc-request-port-boundary.test.ts @@ -0,0 +1,267 @@ +import { readFileSync, readdirSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { extname, join, relative, resolve } from 'node:path' +import ts from 'typescript' +import { describe, expect, it } from 'vitest' +import { + UNVALIDATED_RPC_REQUEST_PORT_OWNERS, + UNVALIDATED_RPC_REQUEST_PORT_PENDING, + type UnvalidatedRpcRequestPortEntry +} from './unvalidated-rpc-request-port-inventory' + +/** + * Ratchet for the raw RPC request port. + * + * `sendRequest` takes an unchecked method string and returns an envelope whose `result` is + * `unknown`. Every screen that reaches it re-decides acceptance and decoding for itself, which + * is the drift the RpcOperation contract exists to end. The port cannot be made unreachable by + * the type system today: `RpcClient` structurally carries it, and ~190 files hold a client. So + * the boundary is held as an inventory instead, and this test is what makes the inventory bind. + * + * Three failures, all of which mean "edit the list": + * - a file reaches the port and is on neither list, + * - a listed file no longer reaches it (stale entry — how allow-lists rot), + * - a listed file's reference count went up. + * + * What this does NOT catch, all accepted: + * - Reach laundered through a function type. A listed file can hand `client.sendRequest` to an + * unlisted one as a bare `(method: string) => Promise` and the receiver never + * names the port. Only two senders are named here; a third wrapper needs adding by hand. + * - Computed access — `client['send' + 'Request']` is not a literal in the AST. + * - Which method a listed file sends, or what it does with the reply. The count is a ceiling + * on how many times it reaches, nothing more. + * - Test files. `*.test.ts(x)` is not scanned: faking the port is how these suites work, and a + * test does not ship. A non-test file that fakes it (tsconfig excludes tests, so some do) is + * scanned and listed. + * A compile-time fence would catch the first two. That needs `RpcClient` to stop carrying the + * port, which needs the call sites migrated first — the thing this list is counting down. + */ + +const mobileRoot = fileURLToPath(new URL('../..', import.meta.url)) +const scannedRoots = ['app', 'src'].map((directory) => join(mobileRoot, directory)) +const sourceExtensions = new Set(['.js', '.jsx', '.ts', '.tsx']) +const portModule = join(mobileRoot, 'src', 'transport', 'unvalidated-rpc-request-port') + +/** The port and its own inventory are not offenders; the ratchet does not police itself. */ +const SELF_FILES = new Set([ + 'src/transport/unvalidated-rpc-request-port.ts', + 'src/transport/unvalidated-rpc-request-port-inventory.ts' +]) + +/** The coalescing second sender: same unchecked string in, same unread envelope out. */ +const SECOND_SENDER = 'sendSingleFlightRequest' + +function sourceFiles(directory: string): string[] { + return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { + const path = join(directory, entry.name) + if (entry.isDirectory()) { + return entry.name === 'node_modules' ? [] : sourceFiles(path) + } + return [path] + }) +} + +function parse(path: string, source: string): ts.SourceFile { + const extension = extname(path) + return ts.createSourceFile( + path, + source, + ts.ScriptTarget.Latest, + true, + extension === '.tsx' || extension === '.jsx' ? ts.ScriptKind.TSX : ts.ScriptKind.TS + ) +} + +function targetsPortModule(path: string, node: ts.Node | undefined): boolean { + if (!node || !ts.isStringLiteral(node) || !node.text.startsWith('.')) { + return false + } + return resolve(path, '..', node.text) === portModule +} + +/** `client['sendRequest']` is one reach, not two: the element access already counted it. */ +function isCountedElementAccessArgument(node: ts.Node): boolean { + const parent: ts.Node | undefined = node.parent + return ( + parent !== undefined && + ts.isElementAccessExpression(parent) && + parent.argumentExpression === node + ) +} + +function declaresPortMember(node: ts.Node): boolean { + if ( + !ts.isPropertySignature(node) && + !ts.isMethodSignature(node) && + !ts.isMethodDeclaration(node) && + !ts.isPropertyDeclaration(node) && + !ts.isPropertyAssignment(node) && + !ts.isShorthandPropertyAssignment(node) + ) { + return false + } + const name = node.name + return (ts.isIdentifier(name) || ts.isStringLiteral(name)) && name.text === 'sendRequest' +} + +/** How many times this file reaches the raw port directly. Comments never count: this is AST. */ +export function rawRequestPortReferences(path: string, source: string): number { + let references = 0 + const visit = (node: ts.Node): void => { + if ( + (ts.isPropertyAccessExpression(node) && node.name.text === 'sendRequest') || + (ts.isElementAccessExpression(node) && + ts.isStringLiteral(node.argumentExpression) && + node.argumentExpression.text === 'sendRequest') || + declaresPortMember(node) || + (ts.isStringLiteral(node) && + node.text === 'sendRequest' && + !isCountedElementAccessArgument(node)) || + (ts.isIdentifier(node) && node.text === SECOND_SENDER) + ) { + references += 1 + } + if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) { + references += targetsPortModule(path, node.moduleSpecifier) ? 1 : 0 + } + if ( + ts.isCallExpression(node) && + (node.expression.kind === ts.SyntaxKind.ImportKeyword || + (ts.isIdentifier(node.expression) && node.expression.text === 'require')) && + targetsPortModule(path, node.arguments[0]) + ) { + references += 1 + } + ts.forEachChild(node, visit) + } + visit(parse(path, source)) + return references +} + +const inventory: readonly UnvalidatedRpcRequestPortEntry[] = [ + ...UNVALIDATED_RPC_REQUEST_PORT_OWNERS, + ...UNVALIDATED_RPC_REQUEST_PORT_PENDING +] + +const scanned = scannedRoots + .flatMap(sourceFiles) + .filter((path) => sourceExtensions.has(extname(path))) + .filter((path) => !/\.test\.tsx?$/.test(path)) + .map((path) => relative(mobileRoot, path).split(/[/\\]/).join('/')) + .filter((file) => !SELF_FILES.has(file)) + +const observed = new Map( + scanned + .map( + (file) => + [ + file, + rawRequestPortReferences( + join(mobileRoot, file), + readFileSync(join(mobileRoot, file), 'utf8') + ) + ] as const + ) + .filter(([, references]) => references > 0) +) + +describe('unvalidated RPC request port boundary', () => { + const probe = join(mobileRoot, 'src', 'transport', 'probe.ts') + + it('counts every shape that reaches the port', () => { + expect(rawRequestPortReferences(probe, 'await client.sendRequest("worktree.ps", {})')).toBe(1) + expect(rawRequestPortReferences(probe, 'const send = client.sendRequest')).toBe(1) + expect(rawRequestPortReferences(probe, 'client["sendRequest"]("x")')).toBe(1) + expect(rawRequestPortReferences(probe, "type A = Pick")).toBe(1) + expect(rawRequestPortReferences(probe, "type A = RpcClient['sendRequest']")).toBe(1) + expect(rawRequestPortReferences(probe, 'const c = { sendRequest: async () => reply }')).toBe(1) + expect(rawRequestPortReferences(probe, 'interface C { sendRequest(m: string): void }')).toBe(1) + expect(rawRequestPortReferences(probe, "if (name === 'sendRequest') { }")).toBe(1) + expect( + rawRequestPortReferences(probe, 'await sendSingleFlightRequest(c, h, "worktree.ps")') + ).toBe(1) + expect( + rawRequestPortReferences( + probe, + "import { sendSingleFlightRequest } from './request-single-flight'" + ) + ).toBe(1) + expect( + rawRequestPortReferences( + probe, + "import type { UnvalidatedRpcRequestPort } from './unvalidated-rpc-request-port'" + ) + ).toBe(1) + expect( + rawRequestPortReferences( + probe, + "export type { SendRequestOptions } from './unvalidated-rpc-request-port'" + ) + ).toBe(1) + expect( + rawRequestPortReferences(probe, "const m = await import('./unvalidated-rpc-request-port')") + ).toBe(1) + expect(rawRequestPortReferences(probe, 'a.sendRequest(1); b.sendRequest(2)')).toBe(2) + }) + + it('does not count prose or an unrelated sender', () => { + expect(rawRequestPortReferences(probe, '// calls sendRequest under the hood')).toBe(0) + expect(rawRequestPortReferences(probe, '/* sendRequest */ export const x = 1')).toBe(0) + expect(rawRequestPortReferences(probe, 'await client.subscribe("terminal.stream", {})')).toBe(0) + expect(rawRequestPortReferences(probe, "import type { RpcClient } from './rpc-client'")).toBe(0) + expect(rawRequestPortReferences(probe, 'await runRpcOperation(client, op, {})')).toBe(0) + }) + + it('scans a plausible number of files', () => { + // A broken root or extension filter would make every check below vacuously pass. + expect(scanned.length).toBeGreaterThan(400) + expect(observed.size).toBeGreaterThan(50) + }) + + it('lists each file once', () => { + const seen = inventory.map((entry) => entry.file) + expect(seen.filter((file, index) => seen.indexOf(file) !== index)).toEqual([]) + }) + + it('has no unlisted file reaching the raw request port', () => { + const listed = new Set(inventory.map((entry) => entry.file)) + const unlisted = [...observed.keys()].filter((file) => !listed.has(file)) + expect( + unlisted, + 'New code must send through an RpcOperation. Nothing may be added to unvalidated-rpc-request-port-inventory.ts.' + ).toEqual([]) + }) + + it('has no stale inventory entry', () => { + const stale = inventory.filter((entry) => !observed.has(entry.file)) + expect( + stale.map((entry) => entry.file), + 'File no longer reaches the raw port — delete its line from unvalidated-rpc-request-port-inventory.ts.' + ).toEqual([]) + }) + + it('has no inventory entry whose file gained references', () => { + const grown = inventory + .filter((entry) => (observed.get(entry.file) ?? 0) > entry.references) + .map( + (entry) => `${entry.file}: listed ${entry.references}, found ${observed.get(entry.file)}` + ) + expect(grown, 'The counts are a ceiling. Send the new call through an RpcOperation.').toEqual( + [] + ) + }) + + it('reports a count that has fallen so the entry can be lowered', () => { + const overstated = inventory + .filter( + (entry) => observed.has(entry.file) && (observed.get(entry.file) ?? 0) < entry.references + ) + .map( + (entry) => `${entry.file}: listed ${entry.references}, found ${observed.get(entry.file)}` + ) + expect( + overstated, + 'Fewer references than listed — lower the count so the ratchet holds.' + ).toEqual([]) + }) +}) diff --git a/mobile/src/transport/unvalidated-rpc-request-port-inventory.ts b/mobile/src/transport/unvalidated-rpc-request-port-inventory.ts new file mode 100644 index 00000000000..82317f272fc --- /dev/null +++ b/mobile/src/transport/unvalidated-rpc-request-port-inventory.ts @@ -0,0 +1,229 @@ +/** + * Every file that still reaches mobile's raw RPC request port, held as data. + * + * A reference is any direct reach for the port: a `.sendRequest` access or declaration, a + * `'sendRequest'` selector such as `Pick`, a call to the coalescing + * second sender `sendSingleFlightRequest`, or an import of unvalidated-rpc-request-port.ts. + * The count is per file and is a ceiling, not a target: unvalidated-rpc-request-port-boundary.test.ts + * fails on a file that is not listed, on a listed file that no longer reaches the port, and on a + * listed file whose count went up. Both lists only shrink. + * + * The owners are permanent — they implement, route or validate the port. The pending list is the + * step-4 migration backlog and shares one reason, stated once here instead of 144 times: + * the call site predates the typed contract and still picks its own method string, its own + * acceptance rule and its own decoding. Replacing one with an RpcOperation deletes its line. + */ +export type UnvalidatedRpcRequestPortEntry = { + readonly file: string + readonly references: number +} + +/** Modules whose job is the port. These do not shrink to zero. */ +export const UNVALIDATED_RPC_REQUEST_PORT_OWNERS: readonly UnvalidatedRpcRequestPortEntry[] = [ + // Implements the port over the device-to-host websocket. + { file: 'src/transport/direct-rpc-client.ts', references: 3 }, + // Fakes the port for the supervisor suites; a non-test file only because tsconfig excludes tests. + { file: 'src/transport/mobile-endpoint-supervisor-test-fakes.ts', references: 2 }, + // Implements the port over a relay channel. + { file: 'src/transport/mobile-relay-physical-client.ts', references: 2 }, + // Supplies the port for one relay session. + { file: 'src/transport/mobile-relay-rpc-session.ts', references: 1 }, + // A second raw sender: string method in, unread envelope out. Its callers are fenced too. + { file: 'src/transport/request-single-flight.ts', references: 3 }, + // Owns connect-wait, timeout and replay bookkeeping for every raw request. + { file: 'src/transport/rpc-client-request-tracker.ts', references: 1 }, + // Composes the port into RpcClient, which is why every holder of a client still carries it. + { file: 'src/transport/rpc-client.ts', references: 2 }, + // The typed boundary itself — the one module that turns a reply into a declared type. + { file: 'src/transport/rpc-operation.ts', references: 2 }, + // Forwards the port across a physical-client cutover. + { file: 'src/transport/stable-logical-rpc-client.ts', references: 2 } +] + +/** Call sites awaiting migration to a typed operation. Grouped by the feature area that owns them. */ +export const UNVALIDATED_RPC_REQUEST_PORT_PENDING: readonly UnvalidatedRpcRequestPortEntry[] = [ + // app/h/[hostId]/ — Expo route screens + { file: 'app/h/[hostId]/accounts.tsx', references: 2 }, + + // app/ — Expo route screens + { file: 'app/terminal-settings.tsx', references: 3 }, + + // src/agent-history/ — agent history loads + { file: 'src/agent-history/MobileAgentSessionHistoryPanel.tsx', references: 7 }, + { file: 'src/agent-history/use-mobile-agent-history-state.ts', references: 2 }, + + // src/browser/ — hosted browser control + { file: 'src/browser/use-mobile-browser-commands.ts', references: 5 }, + { file: 'src/browser/use-mobile-browser-request.ts', references: 1 }, + + // src/components/ — shared widgets that fetch their own data + { file: 'src/components/codex-reset-credit-capability.ts', references: 2 }, + { file: 'src/components/codex-reset-credit.ts', references: 3 }, + { file: 'src/components/use-new-workspace-create-submit.ts', references: 1 }, + { file: 'src/components/use-new-workspace-execution-target.ts', references: 4 }, + { file: 'src/components/use-new-workspace-repositories.ts', references: 1 }, + { file: 'src/components/use-new-workspace-runtime-context.ts', references: 4 }, + { file: 'src/components/use-new-workspace-setup-script.ts', references: 1 }, + + // src/dictation/ — dictation session control + { file: 'src/dictation/mobile-dictation-setup.ts', references: 10 }, + + // src/files/ — file read, write and preview + { file: 'src/files/mobile-file-mutation-ownership.ts', references: 3 }, + { file: 'src/files/mobile-file-preview-request.ts', references: 6 }, + { file: 'src/files/mobile-file-tab-doc.ts', references: 4 }, + { file: 'src/files/mobile-terminal-artifact-grant-refresh.ts', references: 2 }, + { file: 'src/files/MobileFileExplorerPanel.tsx', references: 2 }, + + // src/home/ — home screen host reads + { file: 'src/home/mobile-home-host-requests.ts', references: 6 }, + + // src/hooks/ — cross-screen data hooks + { file: 'src/hooks/mobile-dictation-audio-chunk.ts', references: 1 }, + { file: 'src/hooks/mobile-dictation-desktop-start.ts', references: 4 }, + { file: 'src/hooks/use-mobile-dictation.ts', references: 4 }, + + // src/host-screen/ — host screen catalog and actions + { file: 'src/host-screen/host-screen-overlays.tsx', references: 1 }, + { file: 'src/host-screen/use-host-repo-metadata.ts', references: 2 }, + { file: 'src/host-screen/use-host-view-settings.ts', references: 2 }, + { file: 'src/host-screen/use-host-worktree-actions.ts', references: 3 }, + + // src/notifications/ — push registration and delivery + { file: 'src/notifications/mobile-notifications.ts', references: 1 }, + { file: 'src/notifications/push-dismissal-reconciliation.ts', references: 2 }, + { file: 'src/notifications/push-registration.ts', references: 3 }, + + // src/session/ — session screen: chat, diff review, PR actions, tabs + { file: 'src/session/ai-vault-resume-launch.ts', references: 3 }, + { file: 'src/session/ai-vault-resume-preparation.ts', references: 2 }, + { file: 'src/session/github-pr-mutations.ts', references: 16 }, + { file: 'src/session/github-pr-rpc.ts', references: 9 }, + { file: 'src/session/mobile-clipboard-image.ts', references: 7 }, + { file: 'src/session/mobile-diff-review-loaders.ts', references: 5 }, + { file: 'src/session/mobile-file-tap-open.ts', references: 3 }, + { file: 'src/session/mobile-image-attachment.ts', references: 2 }, + { file: 'src/session/mobile-native-chat-image-attachment.ts', references: 1 }, + { file: 'src/session/mobile-native-chat-image-send.ts', references: 2 }, + { file: 'src/session/mobile-native-chat-send.ts', references: 2 }, + { file: 'src/session/mobile-native-chat-session-option-persistence.ts', references: 1 }, + { file: 'src/session/mobile-native-chat-stale-input.ts', references: 1 }, + { file: 'src/session/mobile-new-tab-agent-loader.ts', references: 5 }, + { file: 'src/session/mobile-session-tab-activation.ts', references: 3 }, + { file: 'src/session/mobile-session-tabs-stream-health.ts', references: 1 }, + { file: 'src/session/mobile-structured-agent-session-launch.ts', references: 3 }, + { file: 'src/session/mobile-structured-agent-session-rpc.ts', references: 1 }, + { file: 'src/session/pr-ai-triage-launch.ts', references: 3 }, + { file: 'src/session/use-live-worktree-name.ts', references: 1 }, + { file: 'src/session/use-mobile-diff-review-comment-actions.ts', references: 1 }, + { file: 'src/session/use-mobile-diff-review-git-actions.ts', references: 2 }, + { file: 'src/session/use-mobile-diff-review-interactions.ts', references: 1 }, + { file: 'src/session/use-mobile-diff-review-send-actions.ts', references: 3 }, + { file: 'src/session/use-mobile-file-tap-handlers.ts', references: 1 }, + { file: 'src/session/use-mobile-native-chat-file-search.ts', references: 2 }, + { file: 'src/session/use-mobile-native-chat-readability.ts', references: 1 }, + { file: 'src/session/use-mobile-native-chat-session.ts', references: 1 }, + { file: 'src/session/use-mobile-native-chat-stop.ts', references: 1 }, + { file: 'src/session/use-mobile-pr-actions.ts', references: 1 }, + { file: 'src/session/use-mobile-pr-branch-context.ts', references: 2 }, + { file: 'src/session/use-mobile-pr-comment-actions.ts', references: 1 }, + { file: 'src/session/use-mobile-pr-title-action.ts', references: 1 }, + { file: 'src/session/use-mobile-session-accessory-selection.ts', references: 1 }, + { file: 'src/session/use-mobile-session-close-actions.ts', references: 3 }, + { file: 'src/session/use-mobile-session-content-create-actions.ts', references: 4 }, + { file: 'src/session/use-mobile-session-diff-comments.ts', references: 2 }, + { file: 'src/session/use-mobile-session-document-readers.ts', references: 2 }, + { file: 'src/session/use-mobile-session-markdown-actions.ts', references: 1 }, + { file: 'src/session/use-mobile-session-startup.ts', references: 2 }, + { file: 'src/session/use-mobile-session-terminal-create-actions.ts', references: 2 }, + { file: 'src/session/use-mobile-session-terminal-input.ts', references: 2 }, + { file: 'src/session/use-mobile-session-terminal-list.ts', references: 1 }, + { file: 'src/session/use-mobile-session-terminal-send-actions.ts', references: 2 }, + { file: 'src/session/use-mobile-session-terminal-stream-display.ts', references: 1 }, + { file: 'src/session/use-mobile-terminal-paste.ts', references: 1 }, + { file: 'src/session/use-pr-bot-author-overrides.ts', references: 1 }, + { file: 'src/session/use-quick-commands.ts', references: 2 }, + + // src/settings/ — settings screen actions + { file: 'src/settings/native-voice-settings-operations.ts', references: 1 }, + + // src/settings/ — notification display probe + { file: 'src/settings/notification-display-test.tsx', references: 1 }, + + // src/source-control/ — source control: review, commit, branch + { file: 'src/source-control/mobile-branch-base-ref.ts', references: 3 }, + { file: 'src/source-control/mobile-commit-message-ai.ts', references: 4 }, + { file: 'src/source-control/mobile-git-history.ts', references: 2 }, + { file: 'src/source-control/mobile-hosted-review-create-intent-runner.ts', references: 1 }, + { file: 'src/source-control/mobile-hosted-review-create-intent.ts', references: 3 }, + { file: 'src/source-control/mobile-hosted-review-git-preparation.ts', references: 6 }, + { file: 'src/source-control/mobile-hosted-review-remote-prerequisite.ts', references: 1 }, + { file: 'src/source-control/mobile-hosted-review-service.ts', references: 8 }, + { file: 'src/source-control/mobile-pr-link.ts', references: 8 }, + { file: 'src/source-control/MobileGitHistoryList.tsx', references: 1 }, + { file: 'src/source-control/reveal-mobile-source-control-session-diff.ts', references: 2 }, + { file: 'src/source-control/use-mobile-git-requests.ts', references: 1 }, + { file: 'src/source-control/use-mobile-source-control-loaders.ts', references: 2 }, + { file: 'src/source-control/use-mobile-source-control-openers.ts', references: 3 }, + + // src/tasks/ — task lists, filters and mutations + { file: 'src/tasks/composer-source-base-resolve.ts', references: 2 }, + { file: 'src/tasks/mobile-tasks-filter-pickers.tsx', references: 1 }, + { file: 'src/tasks/mobile-tasks-source-family.test-support.ts', references: 1 }, + { file: 'src/tasks/setup-hook-trust.ts', references: 1 }, + { file: 'src/tasks/smart-source-paste-intent.ts', references: 4 }, + { file: 'src/tasks/smart-source-search-requests.ts', references: 5 }, + { file: 'src/tasks/use-mobile-tasks-client-settings-actions.tsx', references: 6 }, + { file: 'src/tasks/use-mobile-tasks-github-check-file-actions.tsx', references: 5 }, + { file: 'src/tasks/use-mobile-tasks-github-reply-merge-actions.tsx', references: 5 }, + { file: 'src/tasks/use-mobile-tasks-gitlab-github-status-actions.tsx', references: 3 }, + { file: 'src/tasks/use-mobile-tasks-hosted-comment-review-actions.tsx', references: 4 }, + { file: 'src/tasks/use-mobile-tasks-hosted-metadata-actions.tsx', references: 2 }, + { file: 'src/tasks/use-mobile-tasks-item-detail-loading.tsx', references: 4 }, + { file: 'src/tasks/use-mobile-tasks-item-detail-metadata-effects.tsx', references: 2 }, + { file: 'src/tasks/use-mobile-tasks-linear-item-actions.tsx', references: 3 }, + { file: 'src/tasks/use-mobile-tasks-list-and-detail-effects.tsx', references: 2 }, + { file: 'src/tasks/use-mobile-tasks-project-detail-loading.tsx', references: 1 }, + { file: 'src/tasks/use-mobile-tasks-project-file-merge-actions.tsx', references: 4 }, + { file: 'src/tasks/use-mobile-tasks-project-loading-actions.tsx', references: 4 }, + { file: 'src/tasks/use-mobile-tasks-project-metadata-actions.tsx', references: 3 }, + { file: 'src/tasks/use-mobile-tasks-project-metadata-loading.tsx', references: 3 }, + { file: 'src/tasks/use-mobile-tasks-project-repository-resolution.tsx', references: 1 }, + { file: 'src/tasks/use-mobile-tasks-project-review-check-actions.tsx', references: 4 }, + { file: 'src/tasks/use-mobile-tasks-project-thread-reply-actions.tsx', references: 4 }, + { file: 'src/tasks/use-mobile-tasks-project-workspace-comment-actions.tsx', references: 3 }, + { file: 'src/tasks/use-mobile-tasks-provider-load-actions.tsx', references: 5 }, + { file: 'src/tasks/use-mobile-tasks-route-and-item-state.tsx', references: 1 }, + { file: 'src/tasks/use-mobile-tasks-runtime-hydration.tsx', references: 5 }, + { file: 'src/tasks/use-mobile-tasks-task-create-actions.tsx', references: 3 }, + { file: 'src/tasks/use-mobile-tasks-task-list-loading.tsx', references: 4 }, + { file: 'src/tasks/use-mobile-tasks-task-pagination-actions.tsx', references: 1 }, + { file: 'src/tasks/use-mobile-tasks-workspace-create-actions.tsx', references: 4 }, + { file: 'src/tasks/use-mobile-tasks-workspace-source-effects.tsx', references: 2 }, + { file: 'src/tasks/use-mobile-tasks-workspace-sparse-actions.tsx', references: 2 }, + { file: 'src/tasks/use-mobile-tasks-workspace-ssh-state.tsx', references: 5 }, + { file: 'src/tasks/worktree-create-capability.ts', references: 1 }, + { file: 'src/tasks/worktree-create-retry.ts', references: 1 }, + + // src/terminal/ — terminal input, viewport and queries + { file: 'src/terminal/mobile-terminal-query-reply.ts', references: 2 }, + { file: 'src/terminal/terminal-live-accessory-raw-send.ts', references: 2 }, + { file: 'src/terminal/terminal-viewport-refit.ts', references: 1 }, + { file: 'src/terminal/worker-terminal-takeover-report.ts', references: 2 }, + + // src/transport/ — pairing, endpoint probing and capability reads + { file: 'src/transport/host-status-gates.ts', references: 1 }, + { file: 'src/transport/mobile-relay-credential-rotation.ts', references: 2 }, + { file: 'src/transport/mobile-relay-direct-upgrade.ts', references: 2 }, + { file: 'src/transport/mobile-relay-pairing-recovery.ts', references: 2 }, + { file: 'src/transport/mobile-runtime-capability-negotiation.ts', references: 2 }, + { file: 'src/transport/pairing-candidate-race.ts', references: 1 }, + { file: 'src/transport/pairing-relay-candidate.ts', references: 4 }, + { file: 'src/transport/pre-profile-pairing-coordinator.ts', references: 2 }, + { file: 'src/transport/runtime-capability-probe.ts', references: 2 }, + + // src/worktree/ — worktree activation and resume + { file: 'src/worktree/home-host-worktree-fetch.ts', references: 2 }, + { file: 'src/worktree/use-retired-worktree-names.ts', references: 1 }, + { file: 'src/worktree/worktree-catalog-snapshot-client.ts', references: 1 } +] diff --git a/mobile/src/transport/unvalidated-rpc-request-port.ts b/mobile/src/transport/unvalidated-rpc-request-port.ts new file mode 100644 index 00000000000..b626b290da6 --- /dev/null +++ b/mobile/src/transport/unvalidated-rpc-request-port.ts @@ -0,0 +1,31 @@ +import type { RpcResponse } from './types' + +// The raw request port, kept in its own module so that reaching it is a visible act. +// +// Nothing on this path is checked against the host contract: `method` is an unconstrained +// string, `params` is `unknown`, and the reply's `result` stays `unknown`. A value that came +// back through here has been parsed as JSON and nothing more, so it is NOT validated and must +// not be annotated as though it were. The typed boundary — defineRpcOperation and the send +// helpers in rpc-operation.ts — is the only path that turns a reply into a declared type, and +// rpc-operation.ts is the only module here that should be importing this one for that purpose. +// +// Every other file that still reaches this port is inventoried in +// unvalidated-rpc-request-port-inventory.ts and fenced by +// unvalidated-rpc-request-port-boundary.test.ts. That list only shrinks. + +export type SendRequestOptions = { + timeoutMs?: number + /** Include the connect wait in the caller's timeout budget. */ + budgetSpansConnect?: boolean + /** Reject instead of replaying the request after reconnect. */ + failWhenDisconnected?: boolean +} + +/** Unvalidated: an arbitrary method name in, an unread envelope out. */ +export type UnvalidatedRpcRequestPort = { + sendRequest: ( + method: string, + params?: unknown, + options?: SendRequestOptions + ) => Promise +} diff --git a/package.json b/package.json index ec2e320641a..321f9248ecf 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "audit:perf": "oxlint --config config/oxlint-performance-audit.json --format json src", "test:perf:contracts": "vitest run --config config/vitest.performance.config.ts", "format": "oxfmt --write .", - "lint": "oxlint && pnpm run audit:code-quality:native && pnpm run audit:code-quality:type-aware && pnpm run check:reliability-gates && pnpm run check:max-lines-ratchet && pnpm run check:ts-nocheck-ratchet && pnpm run check:runtime-electron-ratchet && pnpm run verify:bundled-skill-guides && pnpm run verify:skill-bundle-manifest && pnpm run verify:localization-catalog && pnpm run verify:localization-runtime-catalog && pnpm run verify:localization-extraction && pnpm run verify:localization-coverage", + "lint": "oxlint && pnpm run audit:code-quality:native && pnpm run audit:code-quality:type-aware && pnpm run check:reliability-gates && pnpm run check:max-lines-ratchet && pnpm run check:ts-nocheck-ratchet && pnpm run check:runtime-electron-ratchet && pnpm run verify:rpc-params-catalog && pnpm run verify:bundled-skill-guides && pnpm run verify:skill-bundle-manifest && pnpm run verify:localization-catalog && pnpm run verify:localization-runtime-catalog && pnpm run verify:localization-extraction && pnpm run verify:localization-coverage", "audit:code-quality": "pnpm run audit:code-quality:native && pnpm run audit:code-quality:type-aware && pnpm run audit:react-doctor", "audit:code-quality:native": "oxlint --config config/oxlint-code-quality-native-plugins.json src config tests mobile --deny-warnings", "audit:code-quality:type-aware": "oxlint --type-aware --config config/oxlint-code-quality-type-aware.json src config tests --deny-warnings", @@ -29,6 +29,7 @@ "test": "node config/scripts/ensure-native-runtime.mjs --runtime=node && vitest run --config config/vitest.config.ts", "test:skill-sharing:release": "vitest run --config config/vitest.config.ts src/main/skills src/main/runtime/rpc/methods/skills.test.ts src/relay/skill-install-handler.test.ts src/shared/skill-bundle-install-contract.test.ts src/shared/skill-install-contract.test.ts src/shared/skill-install-failure.test.ts src/shared/skill-package-manifest.test.ts", "test:repro:remote-agent-session": "pnpm run build:cli && pnpm run build:electron-vite && node config/scripts/remote-agent-session-authority-repro.mjs", + "capture:agent-transcript": "node config/scripts/ensure-native-runtime.mjs --runtime=node && node config/scripts/capture-agent-pty-transcript.mjs", "check:reliability-gates": "node config/scripts/check-reliability-gates.mjs", "check:max-lines-ratchet": "node config/scripts/check-max-lines-ratchet.mjs", "check:ts-nocheck-ratchet": "node config/scripts/check-ts-nocheck-ratchet.mjs", @@ -38,6 +39,8 @@ "smoke:orcad-terminal": "node config/scripts/ensure-native-runtime.mjs --runtime=node && pnpm run build:cli && pnpm run build:orcad && node config/scripts/runtime-serve-terminal-smoke.mjs --target orcad", "smoke:serve-terminal": "node config/scripts/runtime-serve-terminal-smoke.mjs", "check:feature-wall-assets": "node config/scripts/check-feature-wall-assets.mjs", + "generate:rpc-params-catalog": "node config/scripts/generate-rpc-params-catalog.mjs", + "verify:rpc-params-catalog": "node config/scripts/generate-rpc-params-catalog.mjs --check", "generate:bundled-skill-guides": "node config/scripts/generate-bundled-skill-guides.mjs --write", "verify:bundled-skill-guides": "node config/scripts/generate-bundled-skill-guides.mjs --check", "generate:skill-bundle-manifest": "node config/scripts/generate-skill-bundle-manifest.mjs --write", @@ -238,7 +241,7 @@ "clsx": "^2.1.1", "cmdk": "^1.1.1", "dompurify": "3.4.14", - "electron": "43.6.0", + "electron": "43.7.0", "electron-builder": "^26.15.3", "electron-builder-squirrel-windows": "^26.15.3", "electron-vite": "^5.0.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4241e10ee7a..88ece541d54 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -128,10 +128,10 @@ importers: version: 0.3.251(@anthropic-ai/sdk@0.122.0(zod@4.5.4))(@modelcontextprotocol/sdk@1.30.0(supports-color@7.2.0)(zod@4.5.4))(zod@4.5.4) '@electron-toolkit/preload': specifier: ^3.0.2 - version: 3.0.2(electron@43.6.0(supports-color@7.2.0)) + version: 3.0.2(electron@43.7.0(supports-color@7.2.0)) '@electron-toolkit/utils': specifier: ^4.0.0 - version: 4.0.0(electron@43.6.0(supports-color@7.2.0)) + version: 4.0.0(electron@43.7.0(supports-color@7.2.0)) '@floating-ui/dom': specifier: 1.7.6 version: 1.7.6 @@ -228,7 +228,7 @@ importers: version: 2.1.14(@playwright/test@1.59.1)(zod@4.5.4) '@tailwindcss/vite': specifier: ^4.2.4 - version: 4.2.4(rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(jiti@2.7.0)(yaml@2.8.4)) + version: 4.2.4(rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(esbuild@0.25.12)(jiti@2.7.0)(yaml@2.8.4)) '@tanstack/react-virtual': specifier: ^3.14.10 version: 3.14.10(react-dom@19.2.8(react@19.2.8))(react@19.2.8) @@ -318,7 +318,7 @@ importers: version: 8.18.1 '@vitejs/plugin-react': specifier: ^5.2.0 - version: 5.2.0(rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(jiti@2.7.0)(yaml@2.8.4)) + version: 5.2.0(rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(esbuild@0.25.12)(jiti@2.7.0)(yaml@2.8.4)) '@xterm/addon-fit': specifier: 0.12.0-beta.300 version: 0.12.0-beta.300(@xterm/xterm@6.1.0-beta.303(patch_hash=1f36ce689bc50c703ae09aeda0e064f107e18e4a5ecba19e746fa5edc4b02ef4)) @@ -353,8 +353,8 @@ importers: specifier: 3.4.14 version: 3.4.14 electron: - specifier: 43.6.0 - version: 43.6.0(supports-color@7.2.0) + specifier: 43.7.0 + version: 43.7.0(supports-color@7.2.0) electron-builder: specifier: ^26.15.3 version: 26.15.3(electron-builder-squirrel-windows@26.15.3) @@ -363,7 +363,7 @@ importers: version: 26.15.3(dmg-builder@26.15.3) electron-vite: specifier: ^5.0.0 - version: 5.0.0(@swc/core@1.15.46)(rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(jiti@2.7.0)(yaml@2.8.4)) + version: 5.0.0(@swc/core@1.15.46)(rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(esbuild@0.25.12)(jiti@2.7.0)(yaml@2.8.4)) emoji-picker-react: specifier: ^4.19.1 version: 4.19.1(react@19.2.8) @@ -501,10 +501,10 @@ importers: version: 11.0.5 vite: specifier: npm:rolldown-vite@7.3.1 - version: rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(jiti@2.7.0)(yaml@2.8.4) + version: rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(esbuild@0.25.12)(jiti@2.7.0)(yaml@2.8.4) vitest: specifier: ^4.1.11 - version: 4.1.11(@opentelemetry/api@1.9.1)(@types/node@25.9.5)(happy-dom@20.11.8)(msw@2.14.3(@types/node@25.9.5)(typescript@7.0.2))(rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(jiti@2.7.0)(yaml@2.8.4)) + version: 4.1.11(@opentelemetry/api@1.9.1)(@types/node@25.9.5)(happy-dom@20.11.8)(msw@2.14.3(@types/node@25.9.5)(typescript@7.0.2))(rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(esbuild@0.25.12)(jiti@2.7.0)(yaml@2.8.4)) vscode-oniguruma: specifier: ^2.0.1 version: 2.0.1 @@ -4411,8 +4411,8 @@ packages: resolution: {integrity: sha512-bO3y10YikuUwUuDUQRM4KfwNkKhnpVO7IPdbsrejwN9/AABJzzTQ4GeHwyzNSrVO+tEH3/Np255a3sVZpZDjvg==} engines: {node: '>=8.0.0'} - electron@43.6.0: - resolution: {integrity: sha512-DqVKYV+FXheMSLTxcMQ+NCo78BDgpnToSyIzXctlUtbP3lRGEuoo1P+C2n/90rJ7TvHgzP0bpP9fbbXxp4noIg==} + electron@43.7.0: + resolution: {integrity: sha512-m98FUehwnoo6q2D9Mr+n602Natb2CRFeKD81GhTdJlKh/Iyud0R1X8hChjpaMBLSsIX9r2ZEFnz0sdIALiO9ZQ==} engines: {node: '>= 22.12.0'} hasBin: true @@ -7438,17 +7438,17 @@ snapshots: '@electron-internal/extract-zip@1.0.4': {} - '@electron-toolkit/preload@3.0.2(electron@43.6.0(supports-color@7.2.0))': + '@electron-toolkit/preload@3.0.2(electron@43.7.0(supports-color@7.2.0))': dependencies: - electron: 43.6.0(supports-color@7.2.0) + electron: 43.7.0(supports-color@7.2.0) '@electron-toolkit/tsconfig@2.0.0(@types/node@25.9.5)': dependencies: '@types/node': 25.9.5 - '@electron-toolkit/utils@4.0.0(electron@43.6.0(supports-color@7.2.0))': + '@electron-toolkit/utils@4.0.0(electron@43.7.0(supports-color@7.2.0))': dependencies: - electron: 43.6.0(supports-color@7.2.0) + electron: 43.7.0(supports-color@7.2.0) '@electron/asar@3.4.1': dependencies: @@ -7845,7 +7845,7 @@ snapshots: eventsource: 3.0.7 eventsource-parser: 3.0.8 express: 5.2.1(supports-color@7.2.0) - express-rate-limit: 8.5.2(express@5.2.1) + express-rate-limit: 8.5.2(express@5.2.1(supports-color@7.2.0)) hono: 4.13.0 jose: 6.2.3 json-schema-typed: 8.0.2 @@ -7867,7 +7867,7 @@ snapshots: eventsource: 3.0.7 eventsource-parser: 3.0.8 express: 5.2.1(supports-color@7.2.0) - express-rate-limit: 8.5.2(express@5.2.1) + express-rate-limit: 8.5.2(express@5.2.1(supports-color@7.2.0)) hono: 4.13.0 jose: 6.2.3 json-schema-typed: 8.0.2 @@ -9327,12 +9327,12 @@ snapshots: '@tailwindcss/oxide-win32-arm64-msvc': 4.2.4 '@tailwindcss/oxide-win32-x64-msvc': 4.2.4 - '@tailwindcss/vite@4.2.4(rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(jiti@2.7.0)(yaml@2.8.4))': + '@tailwindcss/vite@4.2.4(rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(esbuild@0.25.12)(jiti@2.7.0)(yaml@2.8.4))': dependencies: '@tailwindcss/node': 4.2.4 '@tailwindcss/oxide': 4.2.4 tailwindcss: 4.2.4 - vite: rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(jiti@2.7.0)(yaml@2.8.4) + vite: rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(esbuild@0.25.12)(jiti@2.7.0)(yaml@2.8.4) '@tanstack/react-virtual@3.14.10(react-dom@19.2.8(react@19.2.8))(react@19.2.8)': dependencies: @@ -9947,7 +9947,7 @@ snapshots: d3-selection: 3.0.0 d3-transition: 3.0.1(d3-selection@3.0.0) - '@vitejs/plugin-react@5.2.0(rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(jiti@2.7.0)(yaml@2.8.4))': + '@vitejs/plugin-react@5.2.0(rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(esbuild@0.25.12)(jiti@2.7.0)(yaml@2.8.4))': dependencies: '@babel/core': 7.29.7 '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.29.7) @@ -9955,7 +9955,7 @@ snapshots: '@rolldown/pluginutils': 1.0.0-rc.3 '@types/babel__core': 7.20.5 react-refresh: 0.18.0 - vite: rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(jiti@2.7.0)(yaml@2.8.4) + vite: rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(esbuild@0.25.12)(jiti@2.7.0)(yaml@2.8.4) transitivePeerDependencies: - supports-color @@ -9968,14 +9968,14 @@ snapshots: chai: 6.2.2 tinyrainbow: 3.1.0 - '@vitest/mocker@4.1.11(msw@2.14.3(@types/node@25.9.5)(typescript@7.0.2))(rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(jiti@2.7.0)(yaml@2.8.4))': + '@vitest/mocker@4.1.11(msw@2.14.3(@types/node@25.9.5)(typescript@7.0.2))(rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(esbuild@0.25.12)(jiti@2.7.0)(yaml@2.8.4))': dependencies: '@vitest/spy': 4.1.11 estree-walker: 3.0.3 magic-string: 0.30.21 optionalDependencies: msw: 2.14.3(@types/node@25.9.5)(typescript@7.0.2) - vite: rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(jiti@2.7.0)(yaml@2.8.4) + vite: rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(esbuild@0.25.12)(jiti@2.7.0)(yaml@2.8.4) '@vitest/pretty-format@4.1.11': dependencies: @@ -10844,7 +10844,7 @@ snapshots: transitivePeerDependencies: - supports-color - electron-vite@5.0.0(@swc/core@1.15.46)(rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(jiti@2.7.0)(yaml@2.8.4)): + electron-vite@5.0.0(@swc/core@1.15.46)(rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(esbuild@0.25.12)(jiti@2.7.0)(yaml@2.8.4)): dependencies: '@babel/core': 7.29.7 '@babel/plugin-transform-arrow-functions': 7.27.1(@babel/core@7.29.7) @@ -10852,7 +10852,7 @@ snapshots: esbuild: 0.25.12 magic-string: 0.30.21 picocolors: 1.1.1 - vite: rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(jiti@2.7.0)(yaml@2.8.4) + vite: rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(esbuild@0.25.12)(jiti@2.7.0)(yaml@2.8.4) optionalDependencies: '@swc/core': 1.15.46 transitivePeerDependencies: @@ -10870,7 +10870,7 @@ snapshots: transitivePeerDependencies: - supports-color - electron@43.6.0(supports-color@7.2.0): + electron@43.7.0(supports-color@7.2.0): dependencies: '@electron-internal/extract-zip': 1.0.4 '@electron/get': 5.0.0(supports-color@7.2.0) @@ -11044,7 +11044,7 @@ snapshots: exponential-backoff@3.1.3: {} - express-rate-limit@8.5.2(express@5.2.1): + express-rate-limit@8.5.2(express@5.2.1(supports-color@7.2.0)): dependencies: express: 5.2.1(supports-color@7.2.0) ip-address: 10.4.0 @@ -13293,7 +13293,7 @@ snapshots: robust-predicates@3.0.3: {} - rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(jiti@2.7.0)(yaml@2.8.4): + rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(esbuild@0.25.12)(jiti@2.7.0)(yaml@2.8.4): dependencies: '@oxc-project/runtime': 0.101.0 fdir: 6.5.0(picomatch@4.0.4) @@ -13304,6 +13304,7 @@ snapshots: tinyglobby: 0.2.16 optionalDependencies: '@types/node': 25.9.5 + esbuild: 0.25.12 fsevents: 2.3.3 jiti: 2.7.0 yaml: 2.8.4 @@ -13944,10 +13945,10 @@ snapshots: '@types/unist': 3.0.3 vfile-message: 4.0.3 - vitest@4.1.11(@opentelemetry/api@1.9.1)(@types/node@25.9.5)(happy-dom@20.11.8)(msw@2.14.3(@types/node@25.9.5)(typescript@7.0.2))(rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(jiti@2.7.0)(yaml@2.8.4)): + vitest@4.1.11(@opentelemetry/api@1.9.1)(@types/node@25.9.5)(happy-dom@20.11.8)(msw@2.14.3(@types/node@25.9.5)(typescript@7.0.2))(rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(esbuild@0.25.12)(jiti@2.7.0)(yaml@2.8.4)): dependencies: '@vitest/expect': 4.1.11 - '@vitest/mocker': 4.1.11(msw@2.14.3(@types/node@25.9.5)(typescript@7.0.2))(rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(jiti@2.7.0)(yaml@2.8.4)) + '@vitest/mocker': 4.1.11(msw@2.14.3(@types/node@25.9.5)(typescript@7.0.2))(rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(esbuild@0.25.12)(jiti@2.7.0)(yaml@2.8.4)) '@vitest/pretty-format': 4.1.11 '@vitest/runner': 4.1.11 '@vitest/snapshot': 4.1.11 @@ -13964,7 +13965,7 @@ snapshots: tinyexec: 1.1.2 tinyglobby: 0.2.16 tinyrainbow: 3.1.0 - vite: rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(jiti@2.7.0)(yaml@2.8.4) + vite: rolldown-vite@7.3.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@25.9.5)(esbuild@0.25.12)(jiti@2.7.0)(yaml@2.8.4) why-is-node-running: 2.3.0 optionalDependencies: '@opentelemetry/api': 1.9.1 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index a26275aa6c6..dd18ec1306b 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -11,6 +11,7 @@ minimumReleaseAgeExclude: - pdfjs-dist@6.3.289 - zod@4.5.4 - '@pierre/diffs@1.4.1' + - electron@43.7.0 shamefullyHoist: true # Orca always launches the user's own resolved Claude CLI via diff --git a/src/cli/terminal-format.test.ts b/src/cli/terminal-format.test.ts index 42c036471eb..294fbc09cee 100644 --- a/src/cli/terminal-format.test.ts +++ b/src/cli/terminal-format.test.ts @@ -1,5 +1,16 @@ import { describe, expect, it } from 'vitest' -import { formatTerminalClose, formatTerminalFocus, formatTerminalSend } from './terminal-format' +import type { + RuntimeTerminalShow, + RuntimeTerminalWait, + RuntimeTerminalWaitBlockedReason +} from '../shared/runtime-terminal-contracts' +import { + formatTerminalClose, + formatTerminalFocus, + formatTerminalSend, + formatTerminalShow, + formatTerminalWait +} from './terminal-format' describe('formatTerminalFocus', () => { it('distinguishes superseded navigation from a winning focus', () => { @@ -171,3 +182,73 @@ describe('formatTerminalSend', () => { expect(output).toContain('--retry-request prompt-swallowed --wait-submit ') }) }) + +// Why: an older host still publishes the codex-* tokens for dialogs its matcher never proved were +// Codex's, so a Gemini/Cursor/Antigravity user reads a Codex label unless the CLI names the neutral one. +describe('blocked-reason rendering against a mixed-version host', () => { + function showResult(reason?: RuntimeTerminalWaitBlockedReason): { + terminal: RuntimeTerminalShow + } { + return { + terminal: { + handle: 'term_agy', + ptyId: 'pty-1', + paneRuntimeId: 1, + rendererGraphEpoch: 1, + worktreeId: 'worktree-1', + worktreePath: '/tmp/w', + branch: 'main', + tabId: 'tab-1', + leafId: 'leaf-1', + title: 'Antigravity', + connected: true, + writable: true, + lastOutputAt: null, + preview: 'Do you trust the files in this folder?', + agentWait: { source: 'prompt-text', reason } + } + } + } + + function waitResult(blockedReason: RuntimeTerminalWaitBlockedReason): { + wait: RuntimeTerminalWait + } { + return { + wait: { + handle: 'term_agy', + condition: 'tui-idle', + satisfied: false, + status: 'running', + exitCode: null, + blockedReason + } + } + } + + // Why one assertion over every reason: a test that only asserts the *absence* of an alias suffix + // passes when the aliasing code is deleted, so each case is paired with a legacy token that must + // gain one. + it.each([ + ['codex-trust-workspace', 'codex-trust-workspace (agent-trust-workspace)'], + ['codex-update-prompt', 'codex-update-prompt (agent-update-prompt)'], + ['codex-cwd-prompt', 'codex-cwd-prompt (agent-cwd-prompt)'], + ['codex-hooks-review-prompt', 'codex-hooks-review-prompt (agent-hooks-review-prompt)'], + ['codex-interactive-prompt', 'codex-interactive-prompt (agent-interactive-prompt)'], + // This build published these itself, so there is nothing to reinterpret. + ['agent-trust-workspace', 'agent-trust-workspace'], + ['codex-model-migration-prompt', 'codex-model-migration-prompt'] + ] as const)('renders %s as %s on both wait and show', (reason, rendered) => { + expect(formatTerminalWait(waitResult(reason)).split('\n').at(-1)).toBe( + `blockedReason: ${rendered}` + ) + expect(formatTerminalShow(showResult(reason))).toContain( + `agentWait: ${rendered} (via prompt-text)` + ) + }) + + it('still describes a wait with no reason at all', () => { + expect(formatTerminalShow(showResult(undefined))).toContain( + 'agentWait: interactive prompt (via prompt-text)' + ) + }) +}) diff --git a/src/cli/terminal-format.ts b/src/cli/terminal-format.ts index 46c26556889..06d897828fe 100644 --- a/src/cli/terminal-format.ts +++ b/src/cli/terminal-format.ts @@ -1,5 +1,6 @@ import { PTY_LIVE_NOTE, describeUnconfirmedStop } from '../shared/pty-liveness-verdict' import { structuredChatPtyWriteRefusalCopy } from '../shared/agent-session-pty-write-refusal-copy' +import { describeTerminalWaitBlockedReason } from '../shared/terminal-wait-blocked-reason-legacy-alias' import { formatListingHostScope, type WithAnnotatedHostScope } from './omitted-host-scope-selectors' import type { RuntimeTerminalClose, @@ -118,7 +119,10 @@ function formatAgentWait(agentWait: RuntimeTerminalShow['agentWait']): string { if (!agentWait) { return 'none' } - return `${agentWait.reason ?? 'interactive prompt'} (via ${agentWait.source})` + if (!agentWait.reason) { + return `interactive prompt (via ${agentWait.source})` + } + return `${describeTerminalWaitBlockedReason(agentWait.reason)} (via ${agentWait.source})` } export function formatTerminalRead(result: { terminal: RuntimeTerminalRead }): string { @@ -278,7 +282,7 @@ export function formatTerminalWait(result: { wait: RuntimeTerminalWait }): strin `exitCode: ${result.wait.exitCode ?? 'null'}` ] if (result.wait.blockedReason) { - lines.push(`blockedReason: ${result.wait.blockedReason}`) + lines.push(`blockedReason: ${describeTerminalWaitBlockedReason(result.wait.blockedReason)}`) } return lines.join('\n') } diff --git a/src/main/agent-awake-service-platform-assertions.test.ts b/src/main/agent-awake-service-platform-assertions.test.ts index 7b3566b322f..231b1aaaf13 100644 --- a/src/main/agent-awake-service-platform-assertions.test.ts +++ b/src/main/agent-awake-service-platform-assertions.test.ts @@ -16,6 +16,7 @@ vi.mock('electron', () => ({ function workingStatus(): AgentAwakeStatus { return { + paneKey: 'pane-1', state: 'working', receivedAt: 1_000, observedInCurrentRuntime: true diff --git a/src/main/agent-awake-service.test.ts b/src/main/agent-awake-service.test.ts index d1792e665fd..12dc5abaa63 100644 --- a/src/main/agent-awake-service.test.ts +++ b/src/main/agent-awake-service.test.ts @@ -16,6 +16,7 @@ vi.mock('electron', () => ({ function workingStatus(overrides: Partial = {}): AgentAwakeStatus { return { + paneKey: 'pane-1', state: 'working', receivedAt: 1_000, observedInCurrentRuntime: true, @@ -279,6 +280,35 @@ describe('AgentAwakeService', () => { service.dispose() }) + it('renews a working lease across two hours without semantic status churn', () => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + const blocker = createBlocker() + const service = createService(() => Date.now(), blocker) + const listener = vi.fn() + service.subscribe(listener) + service.setMode('auto') + service.setStatuses([workingStatus()]) + + for (let index = 0; index < 5; index += 1) { + vi.advanceTimersByTime(30 * 60 * 1000) + service.observeStatusFreshness( + workingStatus({ receivedAt: Date.now(), observedInCurrentRuntime: true }) + ) + } + + expect(Date.now()).toBeGreaterThan(1_000 + AGENT_AWAKE_STATUS_STALE_AFTER_MS) + expect(service.getStatus()).toEqual({ mode: 'auto', active: true }) + expect(blocker.stop).not.toHaveBeenCalled() + expect(listener).toHaveBeenCalledTimes(2) + + vi.advanceTimersByTime(AGENT_AWAKE_STATUS_STALE_AFTER_MS) + expect(service.getStatus()).toEqual({ mode: 'auto', active: true }) + vi.advanceTimersByTime(1) + expect(service.getStatus()).toEqual({ mode: 'auto', active: false }) + service.dispose() + }) + it('keeps the blocker id when stop fails and Electron reports it is still started', () => { const blocker = createBlocker() blocker.stop.mockImplementation(() => { diff --git a/src/main/agent-awake-service.ts b/src/main/agent-awake-service.ts index 6be27e9d0e6..45db4e8608b 100644 --- a/src/main/agent-awake-service.ts +++ b/src/main/agent-awake-service.ts @@ -1,5 +1,4 @@ import { powerMonitor, powerSaveBlocker } from 'electron' -import type { AgentStatusState } from '../shared/agent-status-types' import { normalizeComputerAwakeMode, type ComputerAwakeMode, @@ -7,14 +6,12 @@ import { } from '../shared/computer-awake-mode' import { LinuxLidSleepAssertion } from './linux-lid-sleep-assertion' import { MacosSystemSleepAssertion } from './macos-system-sleep-assertion' +import { AgentAwakeStatusLease, type AgentAwakeStatus } from './agent-awake-status-lease' -export const AGENT_AWAKE_STATUS_STALE_AFTER_MS = 2 * 60 * 60 * 1000 - -export type AgentAwakeStatus = { - state: AgentStatusState - receivedAt: number - observedInCurrentRuntime: boolean -} +export { + AGENT_AWAKE_STATUS_STALE_AFTER_MS, + type AgentAwakeStatus +} from './agent-awake-status-lease' type PowerSaveBlocker = { start: (type: 'prevent-app-suspension' | 'prevent-display-sleep') => number @@ -47,9 +44,7 @@ type AgentAwakeServiceOptions = { export class AgentAwakeService { private mode: ComputerAwakeMode = 'off' - private statuses: AgentAwakeStatus[] = [] private blockerId: number | null = null - private staleTimer: ReturnType | null = null private readonly statusListeners = new Set<(status: ComputerAwakeStatus) => void>() private lastPublishedStatus: ComputerAwakeStatus | null = null private readonly blocker: PowerSaveBlocker @@ -58,12 +53,14 @@ export class AgentAwakeService { private readonly macosAssertion: PlatformAwakeAssertion private readonly platform: NodeJS.Platform private readonly now: () => number + private readonly statusLease: AgentAwakeStatusLease private readonly unsubscribeResume: (() => void) | null constructor(options: AgentAwakeServiceOptions = {}) { this.blocker = options.blocker ?? powerSaveBlocker this.logger = options.logger ?? console this.now = options.now ?? Date.now + this.statusLease = new AgentAwakeStatusLease(this.now, () => this.refresh('stale-expiry')) // Windows lid close is intentionally not modeled as an assertion here: // keeping it awake requires mutating the user's global power plan. this.linuxAssertion = @@ -105,11 +102,20 @@ export class AgentAwakeService { } setStatuses(statuses: AgentAwakeStatus[]): void { - // Copy the array, not every row: the hook server allocates each row fresh per event. - this.statuses = [...statuses] + this.statusLease.replace(statuses) this.refresh('status-change') } + /** Renew one accepted observation without rescanning every active agent. */ + observeStatusFreshness(status: AgentAwakeStatus): void { + if (!this.statusLease.renew(status)) { + return + } + if (this.mode === 'auto' && this.lastPublishedStatus?.active !== true) { + this.applyAwakeDecision('status-freshness', 1) + } + } + getStatus(): ComputerAwakeStatus { const workingAgentCount = this.getEligibleRunningStatusCount() return { @@ -129,7 +135,7 @@ export class AgentAwakeService { } dispose(): void { - this.clearStaleTimer() + this.statusLease.dispose() this.unsubscribeResume?.() this.stopBlocker('dispose') this.macosAssertion.dispose() @@ -137,8 +143,11 @@ export class AgentAwakeService { } private refresh(reason: string): void { - this.scheduleStaleTimer() const runningStatusCount = this.getEligibleRunningStatusCount() + this.applyAwakeDecision(reason, runningStatusCount) + } + + private applyAwakeDecision(reason: string, runningStatusCount: number): void { const shouldBlock = this.mode === 'on' || (this.mode === 'auto' && runningStatusCount > 0) if (shouldBlock) { const macosAssertionActive = this.startMacosAssertion(reason) @@ -171,56 +180,7 @@ export class AgentAwakeService { } private getEligibleRunningStatusCount(): number { - const now = this.now() - // Counted in place: the filtered array was only ever measured, and this runs per hook event. - return this.statuses.reduce((count, s) => count + (this.isWakeEligible(s, now) ? 1 : 0), 0) - } - - private isWakeEligible(status: AgentAwakeStatus, now: number): boolean { - return ( - status.observedInCurrentRuntime && - status.state === 'working' && - Number.isFinite(status.receivedAt) && - now - status.receivedAt <= AGENT_AWAKE_STATUS_STALE_AFTER_MS - ) - } - - private scheduleStaleTimer(): void { - this.clearStaleTimer() - const now = this.now() - let earliestExpiry: number | null = null - for (const status of this.statuses) { - if ( - !status.observedInCurrentRuntime || - status.state !== 'working' || - !Number.isFinite(status.receivedAt) - ) { - continue - } - const expiry = status.receivedAt + AGENT_AWAKE_STATUS_STALE_AFTER_MS - if (expiry <= now) { - continue - } - earliestExpiry = earliestExpiry === null ? expiry : Math.min(earliestExpiry, expiry) - } - if (earliestExpiry === null) { - return - } - this.staleTimer = setTimeout(() => { - this.staleTimer = null - this.refresh('stale-expiry') - }, earliestExpiry - now) - if (typeof this.staleTimer.unref === 'function') { - this.staleTimer.unref() - } - } - - private clearStaleTimer(): void { - if (!this.staleTimer) { - return - } - clearTimeout(this.staleTimer) - this.staleTimer = null + return this.statusLease.countEligible() } private startBlocker(reason: string, runningStatusCount: number): void { diff --git a/src/main/agent-awake-status-lease.ts b/src/main/agent-awake-status-lease.ts new file mode 100644 index 00000000000..327bbc201ea --- /dev/null +++ b/src/main/agent-awake-status-lease.ts @@ -0,0 +1,106 @@ +import type { AgentStatusState } from '../shared/agent-status-types' + +export const AGENT_AWAKE_STATUS_STALE_AFTER_MS = 2 * 60 * 60 * 1000 + +export type AgentAwakeStatus = { + paneKey: string + state: AgentStatusState + receivedAt: number + observedInCurrentRuntime: boolean +} + +export class AgentAwakeStatusLease { + private statuses = new Map() + private timer: ReturnType | null = null + private timerExpiresAt: number | null = null + + constructor( + private readonly now: () => number, + private readonly onExpiry: () => void + ) {} + + replace(statuses: AgentAwakeStatus[]): void { + this.statuses = new Map(statuses.map((status) => [status.paneKey, status])) + this.scheduleNextExpiry() + } + + /** Returns whether the renewed row is currently wake-eligible. */ + renew(status: AgentAwakeStatus): boolean { + this.statuses.set(status.paneKey, status) + const now = this.now() + if (!this.isEligible(status, now)) { + return false + } + this.scheduleAt(status.receivedAt + AGENT_AWAKE_STATUS_STALE_AFTER_MS, now) + return true + } + + countEligible(): number { + const now = this.now() + let count = 0 + for (const status of this.statuses.values()) { + if (this.isEligible(status, now)) { + count += 1 + } + } + return count + } + + dispose(): void { + this.clearTimer() + } + + private isEligible(status: AgentAwakeStatus, now: number): boolean { + return ( + status.observedInCurrentRuntime && + status.state === 'working' && + Number.isFinite(status.receivedAt) && + now - status.receivedAt <= AGENT_AWAKE_STATUS_STALE_AFTER_MS + ) + } + + private scheduleNextExpiry(): void { + this.clearTimer() + const now = this.now() + let earliestExpiry: number | null = null + for (const status of this.statuses.values()) { + if (!this.isEligible(status, now)) { + continue + } + const expiry = status.receivedAt + AGENT_AWAKE_STATUS_STALE_AFTER_MS + const nextCheckAt = expiry === now ? now + 1 : expiry + earliestExpiry = earliestExpiry === null ? nextCheckAt : Math.min(earliestExpiry, nextCheckAt) + } + if (earliestExpiry !== null) { + this.scheduleAt(earliestExpiry, now) + } + } + + private scheduleAt(expiry: number, now: number): void { + if ( + expiry <= now || + (this.timer !== null && this.timerExpiresAt !== null && this.timerExpiresAt <= expiry) + ) { + return + } + this.clearTimer() + this.timerExpiresAt = expiry + this.timer = setTimeout(() => { + this.timer = null + this.timerExpiresAt = null + this.scheduleNextExpiry() + this.onExpiry() + }, expiry - now) + if (typeof this.timer.unref === 'function') { + this.timer.unref() + } + } + + private clearTimer(): void { + if (this.timer !== null) { + clearTimeout(this.timer) + this.timer = null + } + this.timerExpiresAt = null + } +} diff --git a/src/main/agent-hooks/hook-provider-session-invalidation.test.ts b/src/main/agent-hooks/hook-provider-session-invalidation.test.ts deleted file mode 100644 index 15338c20056..00000000000 --- a/src/main/agent-hooks/hook-provider-session-invalidation.test.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { createHookProviderSessionInvalidator } from './hook-provider-session-invalidation' - -describe('createHookProviderSessionInvalidator', () => { - it('names the worktree the first time a pane reports a provider session', () => { - const collect = createHookProviderSessionInvalidator() - - expect(collect([{ paneKey: 'tab:leaf', sessionId: 's1', worktreeId: 'w1' }])).toEqual(['w1']) - }) - - it('stays quiet while the same session keeps being reported', () => { - const collect = createHookProviderSessionInvalidator() - const rows = [{ paneKey: 'tab:leaf', sessionId: 's1', worktreeId: 'w1' }] - collect(rows) - - expect(collect(rows)).toEqual([]) - }) - - it('names the worktree when a pane relaunches under a new session', () => { - const collect = createHookProviderSessionInvalidator() - collect([{ paneKey: 'tab:leaf', sessionId: 's1', worktreeId: 'w1' }]) - - expect(collect([{ paneKey: 'tab:leaf', sessionId: 's2', worktreeId: 'w1' }])).toEqual(['w1']) - }) - - it('names the worktree when a pane loses its session entirely', () => { - const collect = createHookProviderSessionInvalidator() - collect([{ paneKey: 'tab:leaf', sessionId: 's1', worktreeId: 'w1' }]) - - expect(collect([])).toEqual(['w1']) - }) - - it('names both worktrees when a pane moves without changing session', () => { - const collect = createHookProviderSessionInvalidator() - collect([{ paneKey: 'tab:leaf', sessionId: 's1', worktreeId: 'w1' }]) - - expect(collect([{ paneKey: 'tab:leaf', sessionId: 's1', worktreeId: 'w2' }])).toEqual([ - 'w1', - 'w2' - ]) - }) - - it('invalidates when Pi keeps its session id but changes transcript path', () => { - const collect = createHookProviderSessionInvalidator() - collect([ - { paneKey: 'tab:leaf', sessionId: 's1', transcriptPath: '/pi/a.jsonl', worktreeId: 'w1' } - ]) - - expect( - collect([ - { paneKey: 'tab:leaf', sessionId: 's1', transcriptPath: '/pi/b.jsonl', worktreeId: 'w1' } - ]) - ).toEqual(['w1']) - }) - - it('retains the known worktree when a later hook omits it', () => { - const collect = createHookProviderSessionInvalidator() - collect([{ paneKey: 'tab:leaf', sessionId: 's1', worktreeId: 'w1' }]) - - expect(collect([{ paneKey: 'tab:leaf', sessionId: 's2' }])).toEqual(['w1']) - }) - - it('ignores a session with no worktree to invalidate', () => { - const collect = createHookProviderSessionInvalidator() - - expect(collect([{ paneKey: 'tab:leaf', sessionId: 's1' }])).toEqual([]) - }) -}) diff --git a/src/main/agent-hooks/hook-provider-session-invalidation.ts b/src/main/agent-hooks/hook-provider-session-invalidation.ts deleted file mode 100644 index 6ef1e6f7d63..00000000000 --- a/src/main/agent-hooks/hook-provider-session-invalidation.ts +++ /dev/null @@ -1,43 +0,0 @@ -import type { AgentHookProviderSessionIdentity } from './server' - -type KnownSession = { sessionId: string; transcriptPath?: string; worktreeId: string } - -/** Names worktrees whose hook-reported resume identity changed. */ -export function createHookProviderSessionInvalidator(): ( - identities: readonly AgentHookProviderSessionIdentity[] -) => string[] { - let known = new Map() - return (identities) => { - const next = new Map() - const changedWorktrees = new Set() - for (const identity of identities) { - const previous = known.get(identity.paneKey) - const worktreeId = identity.worktreeId ?? previous?.worktreeId - if (!worktreeId) { - continue - } - next.set(identity.paneKey, { - sessionId: identity.sessionId, - ...(identity.transcriptPath ? { transcriptPath: identity.transcriptPath } : {}), - worktreeId - }) - if ( - previous?.sessionId !== identity.sessionId || - previous?.transcriptPath !== identity.transcriptPath || - previous?.worktreeId !== worktreeId - ) { - if (previous?.worktreeId !== worktreeId) { - changedWorktrees.add(previous?.worktreeId ?? worktreeId) - } - changedWorktrees.add(worktreeId) - } - } - for (const [paneKey, previous] of known) { - if (!next.has(paneKey)) { - changedWorktrees.add(previous.worktreeId) - } - } - known = next - return [...changedWorktrees] - } -} diff --git a/src/main/agent-hooks/hook-status-session-tabs-invalidation.test.ts b/src/main/agent-hooks/hook-status-session-tabs-invalidation.test.ts deleted file mode 100644 index fc2482cbdb0..00000000000 --- a/src/main/agent-hooks/hook-status-session-tabs-invalidation.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { AgentHookEventPayload } from '../../shared/agent-hook-listener/listener-event' -import type { ParsedAgentStatusPayload } from '../../shared/agent-status-types' -import { createHookStatusSessionTabsInvalidator } from './hook-status-session-tabs-invalidation' - -function working( - overrides: Partial = {}, - payload: Partial = {} -): AgentHookEventPayload { - return { - paneKey: 'tab:leaf', - connectionId: null, - payload: { state: 'working', prompt: 'fix the tests', agentType: 'claude', ...payload }, - ...overrides - } -} - -describe('createHookStatusSessionTabsInvalidator', () => { - it('invalidates the first time a pane reports', () => { - const changed = createHookStatusSessionTabsInvalidator() - - expect(changed(working())).toBe(true) - }) - - it('stays quiet while the same status keeps being pinged', () => { - const changed = createHookStatusSessionTabsInvalidator() - changed(working()) - - expect(changed(working())).toBe(false) - }) - - it('invalidates when a restored row is confirmed by live activity', () => { - const changed = createHookStatusSessionTabsInvalidator() - changed(working({ restoredUnconfirmed: true })) - - expect(changed(working())).toBe(true) - }) - - it.each([ - ['state', { state: 'waiting' as const }], - ['workingMode', { workingMode: 'monitoring' as const }], - ['prompt', { prompt: 'ship it' }], - ['agentType', { agentType: 'codex' }], - ['toolName', { toolName: 'Bash' }], - ['interactivePrompt', { interactivePrompt: '{"questions":[]}' }], - ['interrupted', { interrupted: true }] - ])('invalidates when %s changes', (_field, payload) => { - const changed = createHookStatusSessionTabsInvalidator() - changed(working()) - - expect(changed(working({}, payload))).toBe(true) - }) - - it('invalidates when the completion stamp is added, changed, or removed', () => { - const changed = createHookStatusSessionTabsInvalidator() - changed(working()) - - expect(changed(working({}, { turnCompletedAt: 100 }))).toBe(true) - expect(changed(working({}, { turnCompletedAt: 200 }))).toBe(true) - expect(changed(working())).toBe(true) - }) - - it('invalidates when the assistant body changes', () => { - const changed = createHookStatusSessionTabsInvalidator() - changed(working({}, { lastAssistantMessage: 'First answer' })) - - expect(changed(working({}, { lastAssistantMessage: 'Corrected answer' }))).toBe(true) - }) - - it('ignores resume-identity rows, which the provider-session path owns', () => { - const changed = createHookStatusSessionTabsInvalidator() - - expect(changed(working({ providerSessionOnly: true }))).toBe(false) - }) - - it('tracks panes independently', () => { - const changed = createHookStatusSessionTabsInvalidator() - changed(working()) - - expect(changed(working({ paneKey: 'tab:other' }))).toBe(true) - expect(changed(working())).toBe(false) - }) - - it('re-arms a forgotten pane so an identical relaunch still invalidates', () => { - const changed = createHookStatusSessionTabsInvalidator() - changed(working()) - changed.forgetPane('tab:leaf') - - expect(changed(working())).toBe(true) - }) - - it("names an SSH host's panes so a disconnect can republish each of them", () => { - const changed = createHookStatusSessionTabsInvalidator() - changed(working({ connectionId: 'conn-1' })) - changed(working({ paneKey: 'tab:remote', connectionId: 'conn-1' })) - changed(working({ paneKey: 'tab:local' })) - - expect(changed.forgetConnection('conn-1').sort()).toEqual(['tab:leaf', 'tab:remote']) - expect(changed(working({ paneKey: 'tab:local' }))).toBe(false) - }) -}) diff --git a/src/main/agent-hooks/hook-status-session-tabs-invalidation.ts b/src/main/agent-hooks/hook-status-session-tabs-invalidation.ts deleted file mode 100644 index 04902579855..00000000000 --- a/src/main/agent-hooks/hook-status-session-tabs-invalidation.ts +++ /dev/null @@ -1,65 +0,0 @@ -import type { AgentHookEventPayload } from '../../shared/agent-hook-listener/listener-event' -import type { ParsedAgentStatusPayload } from '../../shared/agent-status-types' - -type KnownStatus = { - connectionId: string | null - payload: ParsedAgentStatusPayload - restoredUnconfirmed: boolean -} - -/** Reports whether a hook status event changed anything the `session.tabs` - * projection publishes, so a repeated same-state ping costs no snapshot rebuild. - * Mirrors `retainAgentRowSnapshot`'s change set plus hook restore provenance. */ -export function createHookStatusSessionTabsInvalidator(): { - (event: AgentHookEventPayload): boolean - forgetPane: (paneKey: string) => void - forgetConnection: (connectionId: string) => string[] -} { - const known = new Map() - const invalidator = (event: AgentHookEventPayload): boolean => { - // Why: resume-identity rows carry transport placeholders, not status; the - // provider-session invalidator owns their republish. - if (event.providerSessionOnly === true) { - return false - } - const previous = known.get(event.paneKey) - const next = event.payload - const restoredUnconfirmed = event.restoredUnconfirmed === true - known.set(event.paneKey, { - connectionId: event.connectionId, - payload: next, - restoredUnconfirmed - }) - return ( - !previous || - previous.payload.state !== next.state || - previous.payload.workingMode !== next.workingMode || - previous.payload.prompt !== next.prompt || - (previous.payload.agentType ?? null) !== (next.agentType ?? null) || - (previous.payload.toolName ?? null) !== (next.toolName ?? null) || - (previous.payload.interactivePrompt ?? null) !== (next.interactivePrompt ?? null) || - (previous.payload.interrupted ?? false) !== (next.interrupted ?? false) || - (previous.payload.turnCompletedAt ?? null) !== (next.turnCompletedAt ?? null) || - (previous.payload.lastAssistantMessage ?? null) !== (next.lastAssistantMessage ?? null) || - previous.restoredUnconfirmed !== restoredUnconfirmed - ) - } - // Why: a cleared pane must re-arm, else the memo swallows the first event of the - // next agent when it happens to match the one that just went away. - invalidator.forgetPane = (paneKey: string): void => { - known.delete(paneKey) - } - // Why: an SSH disconnect clears a whole host's rows at once and names no pane, so - // the caller needs the pane list back to republish each affected workspace. - invalidator.forgetConnection = (connectionId: string): string[] => { - const forgotten: string[] = [] - for (const [paneKey, status] of known) { - if (status.connectionId === connectionId) { - known.delete(paneKey) - forgotten.push(paneKey) - } - } - return forgotten - } - return invalidator -} diff --git a/src/main/agent-hooks/hook-status-session-tabs-republish.test.ts b/src/main/agent-hooks/hook-status-session-tabs-republish.test.ts new file mode 100644 index 00000000000..150c00a0137 --- /dev/null +++ b/src/main/agent-hooks/hook-status-session-tabs-republish.test.ts @@ -0,0 +1,139 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { AgentHookServer } from './server' +import { installHookStatusSessionTabsRepublish } from './hook-status-session-tabs-republish' +import { AGENT_STATUS_STALE_AFTER_MS } from '../../shared/agent-status-types' +import { + createMobileSessionTabsAgentStatusHeartbeat, + SESSION_TABS_AGENT_STATUS_HEARTBEAT_INTERVAL_MS +} from '../runtime/mobile-session-tabs-agent-status-heartbeat' + +const PANE = 'tab-provider:11111111-1111-4111-8111-111111111111' + +function providerOnly(server: AgentHookServer, transcriptPath: string): void { + server.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-provider', + worktreeId: 'repo::/worktree', + providerSession: { key: 'session_id', id: 'pi-session', transcriptPath }, + providerSessionOnly: true, + payload: { state: 'done', prompt: '', agentType: 'pi' } + }, + null + ) +} + +describe('hook status session-tabs republish', () => { + afterEach(() => { + vi.useRealTimers() + }) + + it('delivers provider-only changes and authority retirement from the owner mutation stream', () => { + const server = new AgentHookServer() + const touch = vi.fn() + const uninstall = installHookStatusSessionTabsRepublish(server, () => ({ + getTerminalWorktreeIdForHandle: () => null, + getTerminalWorktreeIdForPaneKey: () => null, + scheduleMobileSessionTabsAgentStatusHeartbeatForWorktree: vi.fn(), + touchMobileSessionTabsForWorktree: touch + })) + try { + providerOnly(server, '/sessions/first.jsonl') + expect(touch).toHaveBeenLastCalledWith('repo::/worktree') + + touch.mockClear() + providerOnly(server, '/sessions/first.jsonl') + expect(touch).not.toHaveBeenCalled() + + providerOnly(server, '/sessions/replaced.jsonl') + expect(touch).toHaveBeenCalledTimes(1) + + touch.mockClear() + server.retirePaneAuthority(PANE) + expect(touch).toHaveBeenCalledTimes(1) + expect(touch).toHaveBeenCalledWith('repo::/worktree') + } finally { + uninstall() + } + }) + + it('deduplicates the old and new ownership of one moved row', () => { + const server = new AgentHookServer() + const touch = vi.fn() + providerOnly(server, '/sessions/first.jsonl') + const uninstall = installHookStatusSessionTabsRepublish(server, () => ({ + getTerminalWorktreeIdForHandle: () => null, + getTerminalWorktreeIdForPaneKey: () => null, + scheduleMobileSessionTabsAgentStatusHeartbeatForWorktree: vi.fn(), + touchMobileSessionTabsForWorktree: touch + })) + try { + server.transferPaneAuthority(PANE, 'tab-new:22222222-2222-4222-8222-222222222222') + expect(touch).toHaveBeenCalledTimes(1) + expect(touch).toHaveBeenCalledWith('repo::/worktree') + } finally { + uninstall() + } + }) + + it('renews mobile freshness across its lease through a bounded heartbeat cadence', () => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + const server = new AgentHookServer() + const publications: number[] = [] + const rowMutations = vi.fn() + const enrichedStatuses = vi.fn() + const semanticStatuses = vi.fn() + let heartbeat: ReturnType + const runtime = { + getTerminalWorktreeIdForHandle: () => null, + getTerminalWorktreeIdForPaneKey: () => null, + scheduleMobileSessionTabsAgentStatusHeartbeatForWorktree: (worktreeId: string) => + heartbeat.scheduleWorktreeHeartbeat(worktreeId), + touchMobileSessionTabsForWorktree: (worktreeId: string) => { + heartbeat.observeWorktreeRefresh(worktreeId) + publications.push(Date.now()) + } + } + heartbeat = createMobileSessionTabsAgentStatusHeartbeat( + () => [], + (worktreeId) => runtime.touchMobileSessionTabsForWorktree(worktreeId) + ) + const uninstall = installHookStatusSessionTabsRepublish(server, () => runtime) + server.subscribeStatusRowMutations(rowMutations) + server.subscribeEnrichedStatus(enrichedStatuses) + server.subscribeStatusChanges(semanticStatuses) + const observation = { + paneKey: PANE, + tabId: 'tab-provider', + worktreeId: 'repo::/worktree', + payload: { state: 'working' as const, prompt: 'active', agentType: 'codex' as const } + } + + try { + server.ingestTerminalStatus(observation) + for (let minute = 1; minute <= 31; minute += 1) { + vi.advanceTimersByTime(60_000) + server.ingestTerminalStatus(observation) + vi.runOnlyPendingTimers() + } + + expect(Date.now()).toBeGreaterThan(1_000 + AGENT_STATUS_STALE_AFTER_MS) + const renewed = server.getStatusSnapshot()[0] + expect(renewed?.state).toBe('working') + expect(Date.now() - renewed!.receivedAt).toBeLessThan(AGENT_STATUS_STALE_AFTER_MS) + expect(publications).toEqual([ + 1_000, + 1_000 + SESSION_TABS_AGENT_STATUS_HEARTBEAT_INTERVAL_MS, + 1_000 + SESSION_TABS_AGENT_STATUS_HEARTBEAT_INTERVAL_MS * 2 + ]) + expect(rowMutations).toHaveBeenCalledTimes(1) + expect(enrichedStatuses).toHaveBeenCalledTimes(1) + expect(semanticStatuses).toHaveBeenCalledTimes(1) + } finally { + uninstall() + heartbeat.dispose() + server.stop() + } + }) +}) diff --git a/src/main/agent-hooks/hook-status-session-tabs-republish.ts b/src/main/agent-hooks/hook-status-session-tabs-republish.ts new file mode 100644 index 00000000000..b53e4e90501 --- /dev/null +++ b/src/main/agent-hooks/hook-status-session-tabs-republish.ts @@ -0,0 +1,67 @@ +import type { AgentHookServer } from './server' + +type SessionTabsRepublisher = { + getTerminalWorktreeIdForHandle(handle: string): string | null + getTerminalWorktreeIdForPaneKey(paneKey: string): string | null + scheduleMobileSessionTabsAgentStatusHeartbeatForWorktree(worktreeId: string): void + touchMobileSessionTabsForWorktree(worktreeId: string): void +} + +type StatusStore = Pick + +/** + * Republish `session.tabs` whenever a pane's status row changes. + * + * Every producer — hook posts, the relay receivers, and main's own OSC parse — lands in the + * store, so this is the one signal that a pane's published projection is out of date. Nothing + * else republishes on a status-only transition, so a paired client would otherwise keep the + * pane's last projection until an unrelated PTY touch came along (#7970). + */ +export function installHookStatusSessionTabsRepublish( + statusStore: StatusStore, + getRuntime: () => SessionTabsRepublisher | null | undefined +): () => void { + const resolveWorktreeId = ( + identity: { paneKey: string; worktreeId?: string; terminalHandle?: string }, + runtime: SessionTabsRepublisher + ): string | null => + identity.worktreeId ?? + (identity.terminalHandle + ? runtime.getTerminalWorktreeIdForHandle(identity.terminalHandle) + : null) ?? + runtime.getTerminalWorktreeIdForPaneKey(identity.paneKey) + + const unsubscribeMutations = statusStore.subscribeStatusRowMutations((mutation) => { + const runtime = getRuntime() + if (!runtime) { + return + } + const worktreeIds = new Set() + for (const identity of [mutation.before, mutation.after]) { + if (!identity) { + continue + } + const worktreeId = resolveWorktreeId(identity, runtime) + if (worktreeId) { + worktreeIds.add(worktreeId) + } + } + for (const worktreeId of worktreeIds) { + runtime.touchMobileSessionTabsForWorktree(worktreeId) + } + }) + const unsubscribeFreshness = statusStore.subscribeStatusFreshness((status) => { + const runtime = getRuntime() + if (!runtime) { + return + } + const worktreeId = resolveWorktreeId(status, runtime) + if (worktreeId) { + runtime.scheduleMobileSessionTabsAgentStatusHeartbeatForWorktree(worktreeId) + } + }) + return () => { + unsubscribeMutations() + unsubscribeFreshness() + } +} diff --git a/src/main/agent-hooks/managed-toml-ownership.test.ts b/src/main/agent-hooks/managed-toml-ownership.test.ts new file mode 100644 index 00000000000..a94ac3c2b09 --- /dev/null +++ b/src/main/agent-hooks/managed-toml-ownership.test.ts @@ -0,0 +1,154 @@ +import { describe, expect, it } from 'vitest' +import { + findManagedTomlBlocks, + findRecognizedManagedTables, + stripManagedTomlRegions, + type ManagedTomlMarkers +} from './managed-toml-ownership' + +const START = '# >>> start >>>' +const END = '# <<< end <<<' +const MARKERS: ManagedTomlMarkers = { startMarker: START, endMarker: END } + +// Recognizes an `[owned]` table plus its `k = ...` lines; anything else is user text. +const recognizeOwned = ( + lines: readonly string[], + index: number +): { lineCount: number; value: string } | null => { + if (lines[index].trim() !== '[owned]') { + return null + } + let cursor = index + 1 + while (cursor < lines.length && /^k\d* = /.test(lines[cursor].trim())) { + cursor++ + } + return { lineCount: cursor - index, value: lines[index].trim() } +} + +function strip(text: string): string { + return stripManagedTomlRegions(text, [ + ...findManagedTomlBlocks(text, MARKERS), + ...findRecognizedManagedTables(text, recognizeOwned) + ]).text +} + +describe('managed TOML marker blocks', () => { + it('finds nothing in a file without the start marker', () => { + expect(findManagedTomlBlocks('a = 1\n', MARKERS)).toEqual([]) + expect(stripManagedTomlRegions('a = 1\n', [])).toMatchObject({ + text: 'a = 1\n', + changed: false + }) + }) + + it('owns everything between the markers regardless of content', () => { + const text = `a = 1\n\n${START}\n[whatever]\nx = 2\n${END}\nb = 3\n` + expect(findManagedTomlBlocks(text, MARKERS)[0].terminated).toBe(true) + expect(strip(text)).toBe('a = 1\nb = 3\n') + }) + + it('an orphaned block owns only its stray marker line', () => { + const text = `${START}\n[anything]\nkeep = true\n` + const [region] = findManagedTomlBlocks(text, MARKERS) + expect(region.terminated).toBe(false) + expect(stripManagedTomlRegions(text, [region]).text).toBe('[anything]\nkeep = true\n') + }) + + it('does not let a terminated block swallow a later stray start marker', () => { + const text = `${START}\n[owned]\nk = 1\n${END}\n${START}\n[user]\nkeep = true\n` + expect(findManagedTomlBlocks(text, MARKERS).map((region) => region.terminated)).toEqual([ + true, + false + ]) + expect(strip(text)).toBe('[user]\nkeep = true\n') + }) + + it('absorbs the blank run above the marker without crossing the block above', () => { + expect(strip(`a = 1\n\n\n${START}\nx\n${END}\n`)).toBe('a = 1\n') + }) + + // CodeRabbit on #20148: a prefix match let a user's own comment open or close + // a region, deleting every byte between two quoted markers. + it("ignores a marker line carrying a trailing comment of the user's own", () => { + const text = [ + 'a = 1', + `${START} (example from the docs)`, + '[user]', + 'keep = true', + `${END} (end of example)`, + 'b = 2' + ].join('\n') + expect(findManagedTomlBlocks(text, MARKERS)).toEqual([]) + expect(strip(text)).toBe(text) + }) + + it('ignores a marker line with a prefix or altered text', () => { + for (const near of [`x ${START}`, START.replace('>>>', '>>'), `${START}x`]) { + expect(findManagedTomlBlocks(`${near}\n[user]\nkeep = true\n`, MARKERS)).toEqual([]) + } + }) + + it('still matches a marker indented or with trailing whitespace', () => { + const text = `a = 1\n ${START} \n[owned]\nk = 1\n ${END}\nb = 2\n` + expect(findManagedTomlBlocks(text, MARKERS)[0].terminated).toBe(true) + expect(strip(text)).toBe('a = 1\nb = 2\n') + }) + + it('handles a marker on the last line with no trailing newline', () => { + expect(strip(`a = 1\n${START}`)).toBe('a = 1\n') + expect(strip(`a = 1\n${START}\n[owned]\nk = 1`)).toBe('a = 1\n') + }) +}) + +describe('recognized managed tables', () => { + it('reclaims a recognized table wherever it sits, and nothing else', () => { + const text = `[user]\nkeep = true\n\n[owned]\nk = 1\nk2 = 2\n\n[user2]\nalso = true\n` + expect(findRecognizedManagedTables(text, recognizeOwned)).toHaveLength(1) + expect(strip(text)).toBe('[user]\nkeep = true\n\n[user2]\nalso = true\n') + }) + + it('reclaims tables stranded below user text after an orphaned marker', () => { + const text = `${START}\n[owned]\nk = 1\n[user]\nkeep = true\n[owned]\nk = 2\n` + expect(strip(text)).toBe('[user]\nkeep = true\n') + }) + + it('leaves an unrecognized table alone', () => { + const text = `${START}\n[user]\nkeep = true\n` + expect(strip(text)).toBe('[user]\nkeep = true\n') + }) + + it('reports each recognized table to readers', () => { + const text = `[owned]\nk = 1\n[user]\nx = 1\n[owned]\nk = 2\n` + expect(findRecognizedManagedTables(text, recognizeOwned).map((t) => t.value)).toEqual([ + '[owned]', + '[owned]' + ]) + }) + + it('clamps a recognizer that claims more lines than the file has', () => { + const greedy = (): { lineCount: number; value: null } => ({ lineCount: 999, value: null }) + const text = 'a = 1\n' + expect(stripManagedTomlRegions(text, findRecognizedManagedTables(text, greedy)).text).toBe('') + }) +}) + +describe('splicing owned regions', () => { + it('merges a recognized table nested inside a marker block', () => { + const text = `a = 1\n${START}\n[owned]\nk = 1\n${END}\nb = 2\n` + const regions = [ + ...findManagedTomlBlocks(text, MARKERS), + ...findRecognizedManagedTables(text, recognizeOwned) + ] + expect(regions).toHaveLength(2) + expect(stripManagedTomlRegions(text, regions).text).toBe('a = 1\nb = 2\n') + }) + + it('splices CRLF text back verbatim', () => { + expect(strip(`a = 1\r\n\r\n${START}\r\n[owned]\r\nk = 1\r\n${END}\r\nb = 2\r\n`)).toBe( + 'a = 1\r\nb = 2\r\n' + ) + expect(strip(`${START}\r\n[owned]\r\nk = 1\r\n[user]\r\nkeep = true\r\n`)).toBe( + '[user]\r\nkeep = true\r\n' + ) + }) +}) diff --git a/src/main/agent-hooks/managed-toml-ownership.ts b/src/main/agent-hooks/managed-toml-ownership.ts new file mode 100644 index 00000000000..940048c0132 --- /dev/null +++ b/src/main/agent-hooks/managed-toml-ownership.ts @@ -0,0 +1,161 @@ +// Orca appends marker-delimited blocks to user-owned TOML config files. Two +// independent things can make a byte Orca's: it sits between a matched start and +// end marker, or the provider positively recognizes it as content Orca emitted. +// The end marker is the only proof of a block's extent, so once a hand-edit +// deletes it the rest of the file is unknown text — #18861: assuming otherwise +// deleted user tables through EOF. An orphaned block therefore owns nothing but +// its own stray marker line, and anything Orca actually wrote is reclaimed by +// recognition instead, wherever in the file it ended up. + +export type ManagedTomlMarkers = { + startMarker: string + endMarker: string +} + +export type ManagedTomlRegion = { + /** First removable offset — includes the blank-line run above the content. */ + startOffset: number + /** Offset one past the last owned line, terminator included. */ + endOffset: number +} + +export type ManagedTomlBlockRegion = ManagedTomlRegion & { + /** Offset of the start-marker line itself. */ + markerOffset: number + /** End marker found: everything between the markers is Orca's. */ + terminated: boolean +} + +export type RecognizedManagedTable = ManagedTomlRegion & { value: T } + +/** Line count of the table starting at `index` plus what the reader needs, or null. */ +export type ManagedTableRecognizer = ( + lines: readonly string[], + index: number +) => { lineCount: number; value: T } | null + +type ScannedLine = { + text: string + offset: number + endOffset: number +} + +// Keeps offsets on the raw text so CRLF terminators are spliced back verbatim. +function scanLines(text: string): ScannedLine[] { + const lines: ScannedLine[] = [] + let offset = 0 + while (offset < text.length) { + const newlineIndex = text.indexOf('\n', offset) + const endOffset = newlineIndex === -1 ? text.length : newlineIndex + 1 + lines.push({ + text: text.slice(offset, endOffset).replace(/\r?\n$/, ''), + offset, + endOffset + }) + offset = endOffset + } + return lines +} + +// Absorb the blank run above so install/remove cycles do not accumulate +// whitespace; overlapping runs are merged away by stripManagedTomlRegions. +function startOffsetAbsorbingBlanksAbove(lines: readonly ScannedLine[], index: number): number { + let startLine = index + while (startLine > 0 && lines[startLine - 1].text.trim() === '') { + startLine-- + } + return lines[startLine].offset +} + +export function findManagedTomlBlocks( + text: string, + markers: ManagedTomlMarkers +): ManagedTomlBlockRegion[] { + const lines = scanLines(text) + // Exact, not startsWith: a user quoting a marker in a comment of their own + // ("# >>> ... >>> (example from the docs)") would otherwise open or close a + // region and take every byte between the two quoted lines. Both emitters + // write the marker as its own line, so nothing legitimate carries a suffix. + const isStart = (index: number): boolean => lines[index].text.trim() === markers.startMarker + const isEnd = (index: number): boolean => lines[index].text.trim() === markers.endMarker + + const regions: ManagedTomlBlockRegion[] = [] + for (let index = 0; index < lines.length; index++) { + if (!isStart(index)) { + continue + } + let last = index + let terminated = false + for (let cursor = index + 1; cursor < lines.length; cursor++) { + // A second start marker never belongs to the block already open. + if (isStart(cursor)) { + break + } + if (isEnd(cursor)) { + last = cursor + terminated = true + break + } + } + // Not terminated: `last` stays on the marker line, so the orphan owns only + // the stray marker. Its body, if Orca wrote it, is reclaimed by recognition. + regions.push({ + startOffset: startOffsetAbsorbingBlanksAbove(lines, index), + markerOffset: lines[index].offset, + endOffset: lines[last].endOffset, + terminated + }) + index = last + } + return regions +} + +/** + * Every table the provider recognizes as its own, anywhere in the file. Marker + * position is irrelevant: content Orca emitted is Orca's to remove even when a + * hand-edit stranded it outside the block (#18861). + */ +export function findRecognizedManagedTables( + text: string, + recognize: ManagedTableRecognizer +): RecognizedManagedTable[] { + const lines = scanLines(text) + const texts = lines.map((line) => line.text) + const tables: RecognizedManagedTable[] = [] + for (let index = 0; index < lines.length; index++) { + const match = recognize(texts, index) + if (!match || match.lineCount <= 0) { + continue + } + const last = Math.min(index + match.lineCount, lines.length) - 1 + tables.push({ + startOffset: startOffsetAbsorbingBlanksAbove(lines, index), + endOffset: lines[last].endOffset, + value: match.value + }) + index = last + } + return tables +} + +/** Splices every owned region out in one pass, merging overlaps and nesting. */ +export function stripManagedTomlRegions( + text: string, + regions: readonly ManagedTomlRegion[] +): { text: string; changed: boolean } { + if (regions.length === 0) { + return { text, changed: false } + } + const ordered = [...regions].sort((a, b) => a.startOffset - b.startOffset) + let stripped = '' + let cursor = 0 + for (const region of ordered) { + if (region.endOffset <= cursor) { + continue + } + stripped += text.slice(cursor, Math.max(cursor, region.startOffset)) + cursor = region.endOffset + } + stripped += text.slice(cursor) + return { text: stripped, changed: stripped !== text } +} diff --git a/src/main/agent-hooks/server-ingest-terminal-status.test.ts b/src/main/agent-hooks/server-ingest-terminal-status.test.ts index 0ac729fa72e..f54a5c26802 100644 --- a/src/main/agent-hooks/server-ingest-terminal-status.test.ts +++ b/src/main/agent-hooks/server-ingest-terminal-status.test.ts @@ -267,6 +267,7 @@ describe('AgentHookServer ingestTerminalStatus', () => { worktreeId: 'wt-1', connectionId: null, receivedAt: 1_000, + evidenceObservedAt: 1_000, stateStartedAt: 1_000, payload: { state: 'working', @@ -282,6 +283,7 @@ describe('AgentHookServer ingestTerminalStatus', () => { worktreeId: 'wt-1', connectionId: null, receivedAt: 1_000, + evidenceObservedAt: 1_000, stateStartedAt: 1_000, state: 'working', prompt: 'ship it', @@ -294,6 +296,49 @@ describe('AgentHookServer ingestTerminalStatus', () => { } }) + it('accepts a runtime-owned legacy pane without opening legacy relay ingress', () => { + const server = new AgentHookServer() + const event = { + paneKey: 'legacy-tab:7', + tabId: 'legacy-tab', + ptyId: 'legacy-pty', + terminalHandle: 'term_legacy', + worktreeId: 'wt-1', + payload: { state: 'working' as const, prompt: 'legacy task', agentType: 'codex' as const } + } + + server.ingestTerminalStatus(event) + + expect(server.getStatusSnapshot()).toEqual([ + expect.objectContaining({ + paneKey: 'legacy-tab:7', + tabId: 'legacy-tab', + terminalHandle: 'term_legacy', + prompt: 'legacy task' + }) + ]) + server.stop() + }) + + it.each([ + ['PTY id', { ptyId: undefined }], + ['terminal handle', { terminalHandle: undefined }], + ['matching tab', { tabId: 'other-tab' }] + ])('rejects a legacy terminal row without its runtime-owned %s', (_label, overrides) => { + const server = new AgentHookServer() + server.ingestTerminalStatus({ + paneKey: 'legacy-tab:7', + tabId: 'legacy-tab', + ptyId: 'legacy-pty', + terminalHandle: 'term_legacy', + payload: { state: 'working', prompt: 'legacy task', agentType: 'codex' }, + ...overrides + }) + + expect(server.getStatusSnapshot()).toEqual([]) + server.stop() + }) + it('suppresses exact duplicate runtime terminal status observations', () => { vi.useFakeTimers() vi.setSystemTime(1_000) @@ -320,7 +365,8 @@ describe('AgentHookServer ingestTerminalStatus', () => { expect(server.getStatusSnapshot()).toEqual([ expect.objectContaining({ paneKey: PANE, - receivedAt: 1_000, + receivedAt: 1_250, + evidenceObservedAt: 1_250, stateStartedAt: 1_000, state: 'working', prompt: 'same turn' diff --git a/src/main/agent-hooks/server-start-failure-lifecycle.test.ts b/src/main/agent-hooks/server-start-failure-lifecycle.test.ts new file mode 100644 index 00000000000..c4c28f71482 --- /dev/null +++ b/src/main/agent-hooks/server-start-failure-lifecycle.test.ts @@ -0,0 +1,167 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type * as NodeHttp from 'node:http' + +const { createServerMock, getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ + createServerMock: vi.fn(), + getCohortAtEmitMock: vi.fn(), + trackMock: vi.fn() +})) + +vi.mock('node:http', async (importOriginal) => { + const actual = await importOriginal() + createServerMock.mockImplementation(actual.createServer) + return { ...actual, createServer: createServerMock } +}) + +vi.mock('../telemetry/client', () => ({ track: trackMock })) +vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) + +import { AgentHookServer, _internals } from './server' +import { makePaneKey } from '../../shared/stable-pane-id' + +const PANE = makePaneKey('tab-lifecycle', '11111111-1111-4111-8111-111111111111') + +beforeEach(() => { + _internals.resetCachesForTests() + createServerMock.mockClear() + trackMock.mockReset() + getCohortAtEmitMock.mockReset() + getCohortAtEmitMock.mockReturnValue({ nth_repo_added: 2 }) +}) + +afterEach(() => { + vi.restoreAllMocks() +}) + +describe('AgentHookServer startup failure lifecycle', () => { + it('rolls back only transport on bind failure and preserves owner state through retry', async () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-hook-start-failure-')) + const persisted = new AgentHookServer() + await persisted.start({ env: 'production', userDataPath }) + persisted.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-lifecycle', + worktreeId: 'wt-lifecycle', + payload: { state: 'working', prompt: 'surviving PTY', agentType: 'codex' } + }, + 'ssh-lifecycle' + ) + persisted.stop() + const server = new AgentHookServer() + const rendererListener = vi.fn() + const statusChanges = vi.fn() + const freshness = vi.fn() + const enrichedStatuses = vi.fn() + const rowMutations = vi.fn() + server.setListener(rendererListener) + server.subscribeStatusChanges(statusChanges) + server.subscribeStatusFreshness(freshness) + server.subscribeEnrichedStatus(enrichedStatuses) + server.subscribeStatusRowMutations(rowMutations) + + try { + let startupErrorListener: ((error: Error) => void) | null = null + const failedServer = { + once: vi.fn((event: string, listener: (error: Error) => void) => { + if (event === 'error') { + startupErrorListener = listener + } + return failedServer + }), + off: vi.fn(() => failedServer), + listen: vi.fn(() => { + startupErrorListener?.(new Error('listener unavailable')) + return failedServer + }), + close: vi.fn(() => failedServer) + } + createServerMock.mockImplementationOnce(() => failedServer) + + await expect(server.start({ env: 'production', userDataPath })).rejects.toThrow( + 'listener unavailable' + ) + expect(failedServer.close).toHaveBeenCalledOnce() + expect(server.buildPtyEnv()).toEqual({}) + expect(server.getStatusSnapshot()).toEqual([ + expect.objectContaining({ paneKey: PANE, prompt: 'surviving PTY' }) + ]) + + server.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-lifecycle', + worktreeId: 'wt-lifecycle', + payload: { state: 'working', prompt: 'newer in-process state', agentType: 'codex' } + }, + 'ssh-lifecycle' + ) + const duplicateOsc = { + paneKey: PANE, + tabId: 'tab-lifecycle', + worktreeId: 'wt-lifecycle', + connectionId: 'ssh-lifecycle', + payload: { state: 'working' as const, prompt: 'newer in-process state', agentType: 'codex' } + } + server.ingestTerminalStatus(duplicateOsc) + + expect(rendererListener).toHaveBeenCalledTimes(1) + expect(enrichedStatuses).toHaveBeenCalledTimes(1) + expect(rowMutations).toHaveBeenCalledTimes(1) + expect(statusChanges).toHaveBeenCalledTimes(1) + expect(freshness).toHaveBeenCalledTimes(1) + expect( + JSON.parse(readFileSync(server.lastStatusPath!, 'utf8')).entries[PANE].payload.prompt + ).toBe('surviving PTY') + + await server.start({ env: 'production', userDataPath }) + expect(server.getStatusSnapshot()).toEqual([ + expect.objectContaining({ + paneKey: PANE, + worktreeId: 'wt-lifecycle', + prompt: 'newer in-process state' + }) + ]) + expect(server.buildPtyEnv()).toMatchObject({ + ORCA_AGENT_HOOK_ENV: 'production', + ORCA_AGENT_HOOK_PORT: expect.any(String), + ORCA_AGENT_HOOK_TOKEN: expect.any(String), + ORCA_AGENT_HOOK_ENDPOINT: server.endpointFilePath + }) + server.ingestTerminalStatus(duplicateOsc) + expect(freshness).toHaveBeenCalledTimes(2) + expect(rendererListener).toHaveBeenCalledTimes(1) + expect(enrichedStatuses).toHaveBeenCalledTimes(1) + expect(rowMutations).toHaveBeenCalledTimes(1) + expect(statusChanges).toHaveBeenCalledTimes(1) + + server.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-lifecycle', + worktreeId: 'wt-lifecycle', + payload: { state: 'done', prompt: 'newer in-process state', agentType: 'codex' } + }, + 'ssh-lifecycle' + ) + expect(rendererListener).toHaveBeenCalledTimes(2) + expect(enrichedStatuses).toHaveBeenCalledTimes(2) + expect(rowMutations).toHaveBeenCalledTimes(2) + expect(statusChanges).toHaveBeenCalledTimes(2) + + server.stop() + server.stop() + expect(server.buildPtyEnv()).toEqual({}) + expect(server.getStatusSnapshot()).toEqual([]) + expect(statusChanges).toHaveBeenCalledTimes(3) + expect(statusChanges).toHaveBeenLastCalledWith([]) + } finally { + server.stop() + persisted.stop() + rmSync(userDataPath, { recursive: true, force: true }) + } + }) +}) diff --git a/src/main/agent-hooks/server-status-listener-fanout.test.ts b/src/main/agent-hooks/server-status-listener-fanout.test.ts index b6633dbf6f1..ef35674e0ed 100644 --- a/src/main/agent-hooks/server-status-listener-fanout.test.ts +++ b/src/main/agent-hooks/server-status-listener-fanout.test.ts @@ -364,6 +364,39 @@ describe('AgentHookServer listener replay', () => { expect(listener).toHaveBeenCalledWith({ paneKey: PANE }) }) + it('fans out one pane clear per status evicted by tab teardown', () => { + const server = new AgentHookServer() + const siblingPane = makePaneKey('tab-1', '22222222-2222-4222-8222-222222222222') + const otherTabPane = makePaneKey('tab-2', '33333333-3333-4333-8333-333333333333') + for (const paneKey of [PANE, siblingPane, otherTabPane]) { + server.ingestRemote( + { + paneKey, + payload: { state: 'working', agentType: 'claude' } + }, + 'conn-1' + ) + } + const clearListener = vi.fn() + const statusListener = vi.fn() + server.subscribePaneStatusClear(clearListener) + server.subscribeStatusChanges(statusListener) + const evidenceObservedAtByPaneKey = ( + server as unknown as { evidenceObservedAtByPaneKey: Map } + ).evidenceObservedAtByPaneKey + expect(evidenceObservedAtByPaneKey.size).toBe(3) + + server.dropStatusEntriesByTabPrefix('tab-1') + + expect(clearListener.mock.calls.map(([clear]) => clear)).toEqual([ + { paneKey: PANE }, + { paneKey: siblingPane } + ]) + expect(statusListener).toHaveBeenCalledOnce() + expect(server.getStatusSnapshot()).toEqual([expect.objectContaining({ paneKey: otherTabPane })]) + expect([...evidenceObservedAtByPaneKey.keys()]).toEqual([otherTabPane]) + }) + it('batches connection cleanup and retains sibling and local statuses', () => { const server = new AgentHookServer() const paneKeyAt = (prefix: string, index: number): string => diff --git a/src/main/agent-hooks/server.ts b/src/main/agent-hooks/server.ts index f03484f14f9..3fb3f51f5f1 100644 --- a/src/main/agent-hooks/server.ts +++ b/src/main/agent-hooks/server.ts @@ -11,7 +11,9 @@ export type { AgentHookAuthorityAttestation, AgentHookAuthorityEvidence, AgentHookProviderSessionIdentity, + AgentHookStatusRowMutation, AgentHookStatusChangeEntry, + AgentHookStatusFreshnessObservation, EnrichedAgentHookEventPayload } from './server/server-types' export type { AgentHookSource } @@ -40,6 +42,7 @@ export const _internals = { parseFormEncodedBody, resetCachesForTests: (): void => { clearAllListenerCaches(agentHookServer._getStateForTests()) + agentHookServer._resetRowOwnershipForTests() agentHookServer._resetPromptSentDedupeForTests() agentHookServer._resetConnectionTimestampWatermarksForTests() } diff --git a/src/main/agent-hooks/server/server-authority-aliases.ts b/src/main/agent-hooks/server/server-authority-aliases.ts index 18756cb459c..b3debc397d2 100644 --- a/src/main/agent-hooks/server/server-authority-aliases.ts +++ b/src/main/agent-hooks/server/server-authority-aliases.ts @@ -133,7 +133,7 @@ export abstract class AgentHookServerAuthorityAliases extends AgentHookServerAut toPaneKey: string, ptyId?: string, updatedAt = Date.now(), - options?: { authorityVerified?: boolean } + options?: { authorityVerified?: boolean; emitStatusRowMutation?: boolean } ): void { if (!isValidPaneKey(fromPaneKey) || !isValidPaneKey(toPaneKey)) { return @@ -142,7 +142,10 @@ export abstract class AgentHookServerAuthorityAliases extends AgentHookServerAut const physicalPaneKey = this.getPhysicalPaneKeyForAuthority(fromPaneKey, ptyId) const existing = this.legacyPaneKeyAliases.get(physicalPaneKey) const normalizedPtyId = ptyId?.trim() || existing?.ptyId || null - const hadStatus = this.state.lastStatusByPaneKey.has(previousOwnerPaneKey) + const previousStatus = this.state.lastStatusByPaneKey.get(previousOwnerPaneKey) as + | EnrichedAgentHookEventPayload + | undefined + const hadStatus = previousStatus !== undefined movePaneCacheState(this.state, previousOwnerPaneKey, toPaneKey) const movedStatus = this.state.lastStatusByPaneKey.get(toPaneKey) as | EnrichedAgentHookEventPayload @@ -155,6 +158,9 @@ export abstract class AgentHookServerAuthorityAliases extends AgentHookServerAut tabId: owner?.tabId }) } + const transferredStatus = this.state.lastStatusByPaneKey.get(toPaneKey) as + | EnrichedAgentHookEventPayload + | undefined const hydratedLaunchTokenHash = this.hydratedLaunchTokenHashByPaneKey.get(previousOwnerPaneKey) if (hydratedLaunchTokenHash) { this.hydratedLaunchTokenHashByPaneKey.delete(previousOwnerPaneKey) @@ -188,6 +194,11 @@ export abstract class AgentHookServerAuthorityAliases extends AgentHookServerAut this.activeHookTurnCompletedAtByPaneKey.delete(previousOwnerPaneKey) this.activeHookTurnCompletedAtByPaneKey.set(toPaneKey, activeTurnCompletedAt) } + const evidenceObservedAt = this.evidenceObservedAtByPaneKey.get(previousOwnerPaneKey) + if (evidenceObservedAt !== undefined) { + this.evidenceObservedAtByPaneKey.delete(previousOwnerPaneKey) + this.evidenceObservedAtByPaneKey.set(toPaneKey, evidenceObservedAt) + } const authorityObservation = this.currentAuthorityObservations.get(previousOwnerPaneKey) if (authorityObservation) { const owner = parsePaneKey(toPaneKey) @@ -214,6 +225,11 @@ export abstract class AgentHookServerAuthorityAliases extends AgentHookServerAut this.boundPaneKeyAliases() this.closedAgentStatusPaneKeys.delete(toPaneKey) this.notifyPaneKeyAliasPersistenceListener() + this.commitStatusRowMutation( + previousStatus, + transferredStatus, + options?.emitStatusRowMutation !== false + ) if (hadStatus || persistedAuthority) { this.scheduleStatusPersist() this.notifyStatusChangeListeners() diff --git a/src/main/agent-hooks/server/server-authority-fences.ts b/src/main/agent-hooks/server/server-authority-fences.ts index 0ad1bdeba62..fdbc16d7012 100644 --- a/src/main/agent-hooks/server/server-authority-fences.ts +++ b/src/main/agent-hooks/server/server-authority-fences.ts @@ -1,7 +1,11 @@ import { clearPaneCacheState } from '../../../shared/agent-hook-listener/listener-state' import { parsePaneKey } from '../../../shared/stable-pane-id' import { AgentHookServerAuthorityAliases } from './server-authority-aliases' -import type { RetiredPaneAlias, RetiredPaneFence } from './server-types' +import type { + EnrichedAgentHookEventPayload, + RetiredPaneAlias, + RetiredPaneFence +} from './server-types' export abstract class AgentHookServerAuthorityFences extends AgentHookServerAuthorityAliases { // Why: retirement fences a pane and every alias of it, then deletes those aliases. @@ -21,7 +25,13 @@ export abstract class AgentHookServerAuthorityFences extends AgentHookServerAuth } this.recordRetiredPaneFence(paneKeys, retiredAliases) const authorityChanged = this.revokeHydratedAuthorityForPaneKeys(paneKeys) - const hadStatus = [...paneKeys].some((key) => this.state.lastStatusByPaneKey.has(key)) + const retiredRows = [...paneKeys].flatMap((key) => { + const row = this.state.lastStatusByPaneKey.get(key) as + | EnrichedAgentHookEventPayload + | undefined + return row ? [row] : [] + }) + const hadStatus = retiredRows.length > 0 for (const key of paneKeys) { this.markPaneClosedForAgentStatus(key) this.restartedStatusLaunchTokenHashByPaneKey.delete(key) @@ -37,6 +47,9 @@ export abstract class AgentHookServerAuthorityFences extends AgentHookServerAuth if (aliasChanged) { this.notifyPaneKeyAliasPersistenceListener() } + for (const row of retiredRows) { + this.commitStatusRowMutation(row, undefined) + } if (hadStatus || authorityChanged) { this.scheduleStatusPersist() this.notifyStatusChangeListeners() @@ -108,6 +121,7 @@ export abstract class AgentHookServerAuthorityFences extends AgentHookServerAuth let aliasChanged = false let statusChanged = false const clearedStatusPaneKeys = new Set() + const clearedStatusRows = new Map() for (const [legacyPaneKey, entry] of this.legacyPaneKeyAliases) { if (entry.ptyId !== ptyId) { continue @@ -129,6 +143,10 @@ export abstract class AgentHookServerAuthorityFences extends AgentHookServerAuth if (shouldClearStablePaneKey && this.state.lastStatusByPaneKey.has(entry.stablePaneKey)) { statusChanged = true clearedStatusPaneKeys.add(entry.stablePaneKey) + clearedStatusRows.set( + entry.stablePaneKey, + this.state.lastStatusByPaneKey.get(entry.stablePaneKey) as EnrichedAgentHookEventPayload + ) } if (shouldClearStablePaneKey) { // Why: hydrated rows live under the stable key; if this PTY dies before ptyPaneKey rebuilds, alias cleanup is the only evictor. @@ -143,6 +161,9 @@ export abstract class AgentHookServerAuthorityFences extends AgentHookServerAuth if (aliasChanged) { this.notifyPaneKeyAliasPersistenceListener() } + for (const row of clearedStatusRows.values()) { + this.commitStatusRowMutation(row, undefined) + } if (statusChanged) { this.scheduleStatusPersist() this.notifyStatusChangeListeners() diff --git a/src/main/agent-hooks/server/server-cleanup.ts b/src/main/agent-hooks/server/server-cleanup.ts index d7669c7449f..9f36d676143 100644 --- a/src/main/agent-hooks/server/server-cleanup.ts +++ b/src/main/agent-hooks/server/server-cleanup.ts @@ -37,6 +37,7 @@ export abstract class AgentHookServerCleanup extends AgentHookServerAuthorityFen if (retained) { this.state.lastStatusByPaneKey.set(deleted.paneKey, retained) } + this.commitStatusRowMutation(deleted, retained) this.scheduleStatusPersist() this.notifyStatusChangeListeners() this.emitStatusDropped(deleted.paneKey) @@ -74,6 +75,7 @@ export abstract class AgentHookServerCleanup extends AgentHookServerAuthorityFen if (retained) { this.state.lastStatusByPaneKey.set(deleted.paneKey, retained) } + this.commitStatusRowMutation(deleted, retained) evicted.push(deleted.paneKey) } if (evicted.length === 0) { @@ -119,12 +121,16 @@ export abstract class AgentHookServerCleanup extends AgentHookServerAuthorityFen | undefined ) : null - this.clearPaneState(resolvedPaneKey) + const previous = this.state.lastStatusByPaneKey.get(resolvedPaneKey) as + | EnrichedAgentHookEventPayload + | undefined + this.clearPaneState(resolvedPaneKey, { emitStatusRowMutation: false }) if (retained) { this.state.lastStatusByPaneKey.set(resolvedPaneKey, retained) this.scheduleStatusPersist() this.notifyStatusChangeListeners() } + this.commitStatusRowMutation(previous, retained) cleared += 1 } return cleared @@ -159,6 +165,7 @@ export abstract class AgentHookServerCleanup extends AgentHookServerAuthorityFen const deleted = this.deleteStatusEntry(paneKey, { preserveAuthority: true }) if (deleted) { statusChanged = true + this.commitStatusRowMutation(deleted, undefined) if (deleted.payload.agentType === 'codex') { // Why: a replacement remote process may reuse the pane; don't merge it with the lost connection's children. this.state.codexSubagentRosterByPaneKey.delete(paneKey) diff --git a/src/main/agent-hooks/server/server-ingest-terminal.ts b/src/main/agent-hooks/server/server-ingest-terminal.ts index 822c7e76f02..e7e68115659 100644 --- a/src/main/agent-hooks/server/server-ingest-terminal.ts +++ b/src/main/agent-hooks/server/server-ingest-terminal.ts @@ -1,6 +1,6 @@ import { track } from '../../telemetry/client' import { MAX_PANE_KEY_LEN } from '../../../shared/agent-hook-listener/listener-limits' -import { parsePaneKey } from '../../../shared/stable-pane-id' +import { parseLegacyNumericPaneKey, parsePaneKey } from '../../../shared/stable-pane-id' import { terminalStatusPayloadMatchesHook } from '../../../shared/agent-terminal-status-equivalence' import type { ParsedAgentStatusPayload } from '../../../shared/agent-status-types' import type { EnrichedAgentHookEventPayload } from './server-types' @@ -8,32 +8,40 @@ import { AgentHookServerIngestNormalization } from './server-ingest-normalizatio export abstract class AgentHookServerIngestTerminal extends AgentHookServerIngestNormalization { ingestTerminalStatus(event: { + ptyId?: string paneKey: string tabId?: string worktreeId?: string connectionId?: string | null + terminalHandle?: string payload: ParsedAgentStatusPayload }): void { const physicalPaneKey = event.paneKey.trim() - const paneKey = this.resolvePaneKeyAlias(physicalPaneKey) + let paneKey = this.resolvePaneKeyAlias(physicalPaneKey) const parsedPaneKey = parsePaneKey(paneKey) + const legacyPaneKey = parseLegacyNumericPaneKey(paneKey) if (paneKey.length === 0) { track('agent_hook_unattributed', { reason: 'empty_pane_key' }) return } - if (paneKey.length > MAX_PANE_KEY_LEN || !parsedPaneKey) { - return - } const reportedTabId = event.tabId !== undefined && event.tabId.trim().length > 0 ? event.tabId.trim() : undefined - if ( - paneKey === physicalPaneKey && - reportedTabId !== undefined && - reportedTabId !== parsedPaneKey.tabId - ) { + const runtimeOwnedLegacyPane = Boolean( + legacyPaneKey && + event.ptyId?.trim() && + event.terminalHandle?.trim() && + reportedTabId === legacyPaneKey.tabId + ) + // Legacy rows are accepted only from the in-process PTY ingress with both runtime identities; + // HTTP and relay paths still require a stable pane key or a registered alias. + if (paneKey.length > MAX_PANE_KEY_LEN || (!parsedPaneKey && !runtimeOwnedLegacyPane)) { return } - const tabId = paneKey !== physicalPaneKey ? parsedPaneKey.tabId : reportedTabId + const paneTabId = parsedPaneKey?.tabId ?? legacyPaneKey?.tabId + if (paneKey === physicalPaneKey && reportedTabId !== undefined && reportedTabId !== paneTabId) { + return + } + const tabId = paneKey !== physicalPaneKey ? parsedPaneKey?.tabId : reportedTabId if (this.getAgentStatusDisposition(paneKey) !== 'accept') { return } @@ -45,6 +53,31 @@ export abstract class AgentHookServerIngestTerminal extends AgentHookServerInges typeof event.connectionId === 'string' && event.connectionId.trim().length > 0 ? event.connectionId.trim() : null + const terminalHandle = + typeof event.terminalHandle === 'string' && event.terminalHandle.trim().length > 0 + ? event.terminalHandle.trim() + : undefined + let mutationBefore: EnrichedAgentHookEventPayload | undefined + const indexedPaneKey = terminalHandle + ? this.getStatusPaneKeyForTerminalHandle(terminalHandle) + : undefined + if (indexedPaneKey && indexedPaneKey !== paneKey) { + const indexedStatus = this.state.lastStatusByPaneKey.get(indexedPaneKey) as + | EnrichedAgentHookEventPayload + | undefined + if ( + indexedStatus && + indexedStatus.terminalHandle === terminalHandle && + this.sameTerminalOwner(indexedStatus, { connectionId, worktreeId }) + ) { + mutationBefore = indexedStatus + this.transferPaneAuthority(indexedPaneKey, paneKey, event.ptyId, Date.now(), { + authorityVerified: true, + emitStatusRowMutation: false + }) + paneKey = this.resolvePaneKeyAlias(paneKey) + } + } const previous = this.state.lastStatusByPaneKey.get(paneKey) as | EnrichedAgentHookEventPayload | undefined @@ -54,6 +87,10 @@ export abstract class AgentHookServerIngestTerminal extends AgentHookServerInges event.payload.agentType === 'claude' ) { // Why: OSC has no child identity or lead boundary, so it cannot replace a persisted child-only proof before the lifecycle hook arrives. + if (mutationBefore !== undefined) { + this.commitStatusRowMutation(mutationBefore, previous) + this.emitEnrichedStatus(previous) + } return } // Why: preserve the hook-completed turn stamp while OSC repaints the current state. @@ -65,8 +102,14 @@ export abstract class AgentHookServerIngestTerminal extends AgentHookServerInges previous?.connectionId === connectionId && previous.tabId === tabId && previous.worktreeId === worktreeId && + // Why in the unchanged gate: the handle is a join key readers match on, so a pane that + // only just acquired one (or moved to another) must still refresh the row it is stamped on. + previous.terminalHandle === (terminalHandle ?? previous.terminalHandle) && terminalStatusPayloadMatchesHook(previous.payload, event.payload, preserveActiveTurnStamp) ) { + // A handle-authority transfer is a new pane observation even when its payload is a + // duplicate; enriched subscribers must capture the replacement pane identity. + this.refreshTerminalStatusEvidence(previous, mutationBefore, mutationBefore !== undefined) return } // Why: the OSC 9999 wire payload has no providerSession field at all, so an OSC observation is @@ -95,10 +138,13 @@ export abstract class AgentHookServerIngestTerminal extends AgentHookServerInges worktreeId, connectionId, ...(preservedProviderSession ? { providerSession: preservedProviderSession } : {}), + ...(terminalHandle ? { terminalHandle } : {}), payload: event.payload }, undefined, - 'osc' + 'osc', + undefined, + mutationBefore ) } } diff --git a/src/main/agent-hooks/server/server-lifecycle.ts b/src/main/agent-hooks/server/server-lifecycle.ts index 9beb0ad0bbb..e7f68829f3b 100644 --- a/src/main/agent-hooks/server/server-lifecycle.ts +++ b/src/main/agent-hooks/server/server-lifecycle.ts @@ -36,19 +36,22 @@ export abstract class AgentHookServerLifecycle extends AgentHookServerRuntimeEnv this.token = randomUUID() this.endpointFileWritten = false this.lastWrittenJson = null - // Why: hydrate before binding the listener so an early hook POST runs against a populated map. - if (this.lastStatusFilePath) { - this.hydrateLastStatusFromDisk() - } - this.captureHydratedAuthorityCommitments() - // Drain before binding the listener so replay cannot race a live hook during startup. - if (this.endpointDir) { - drainAgentHookSpool({ - endpointDir: this.endpointDir, - getPersistedLaunchTokenHash: (paneKey) => - this.hydratedLaunchTokenHashByPaneKey.get(this.resolvePaneKeyAlias(paneKey)), - ingest: (record: SpoolRecord) => this.ingestSpoolRecord(record) - }) + if (!this.ownerStateInitialized) { + // Why: hydrate before binding the listener so an early hook POST runs against a populated map. + if (this.lastStatusFilePath) { + this.hydrateLastStatusFromDisk() + } + this.captureHydratedAuthorityCommitments() + // Drain before binding the listener so replay cannot race a live hook during startup. + if (this.endpointDir) { + drainAgentHookSpool({ + endpointDir: this.endpointDir, + getPersistedLaunchTokenHash: (paneKey) => + this.hydratedLaunchTokenHashByPaneKey.get(this.resolvePaneKeyAlias(paneKey)), + ingest: (record: SpoolRecord) => this.ingestSpoolRecord(record) + }) + } + this.ownerStateInitialized = true } const handleRequest = async (req: IncomingMessage, res: ServerResponse): Promise => { if (req.method !== 'POST') { @@ -134,39 +137,51 @@ export abstract class AgentHookServerLifecycle extends AgentHookServerRuntimeEnv this.server = createServer((req, res) => { void handleRequest(req, res) }) - await new Promise((resolve, reject) => { - const onStartupError = (err: Error): void => { - // Why: swap the startup reject-handler for a logging one so a later runtime 'error' can't crash main as an unhandled event. - this.server?.off('listening', onListening) - reject(err) - } - const onListening = (): void => { - this.server?.off('error', onStartupError) - this.server?.on('error', (err) => { - console.error('[agent-hooks] server error', err) - }) - const address = this.server!.address() - if (address && typeof address === 'object') { - this.port = address.port + try { + await new Promise((resolve, reject) => { + const onStartupError = (err: Error): void => { + this.server?.off('listening', onListening) + reject(err) } - this.maybeWriteEndpointFile() - resolve() - } - this.server!.once('error', onStartupError) - this.server!.listen(0, '127.0.0.1', onListening) - }) + const onListening = (): void => { + this.server?.off('error', onStartupError) + this.server?.on('error', (err) => { + console.error('[agent-hooks] server error', err) + }) + const address = this.server!.address() + if (address && typeof address === 'object') { + this.port = address.port + } + this.maybeWriteEndpointFile() + resolve() + } + this.server!.once('error', onStartupError) + this.server!.listen(0, '127.0.0.1', onListening) + }) + } catch (error) { + this.rollbackTransportStart() + throw error + } + } + + private rollbackTransportStart(): void { + this.server?.close() + this.server = null + this.port = 0 + this.token = '' + this.endpointFileWritten = false } stop(): void { // Why: flush the pending debounced write before clearing the map, else a hook <250ms before quit is lost on relaunch. this.flushStatusPersistSync() - this.server?.close() - this.server = null - this.port = 0 - this.token = '' + this.rollbackTransportStart() this.env = 'production' this.onAgentStatus = null + this.onClaudeStatusLine = null this.onPaneStatusCleared = null + this.onTransportInterference = null + this.transportInterference.reset() for (const timer of this.assistantMessageRetryTimers.values()) { clearTimeout(timer) } @@ -178,6 +193,7 @@ export abstract class AgentHookServerLifecycle extends AgentHookServerRuntimeEnv this.lastStatusFilePath = null this.lastWrittenJson = null this.runtimeObservedStatusPaneKeys.clear() + this.paneKeyByTerminalHandle.clear() this.hydratedAuthorityCommitments = Object.freeze([]) this.hydratedLaunchTokenHashByPaneKey.clear() this.persistedAuthorityCommitmentsByPaneKey.clear() @@ -189,9 +205,20 @@ export abstract class AgentHookServerLifecycle extends AgentHookServerRuntimeEnv this.restartedStatusLaunchTokenHashByPaneKey.clear() this.retiredPaneFencesByKey.clear() this.connectionTimestampWatermarkById.clear() + this.evidenceObservedAtByPaneKey.clear() + this.activeHookTurnCompletedAtByPaneKey.clear() this.legacyPaneKeyAliases.clear() + this.paneKeyAliasPersistenceListener = null + this.ownerStateInitialized = false // Why: don't unlink the endpoint file — a stale file matches fail-open and avoids a TOCTOU race with a concurrent Orca. clearAllListenerCaches(this.state) this.notifyStatusChangeListeners() + this.paneStatusClearListeners.clear() + this.statusDropListeners.clear() + this.statusChangeListeners.clear() + this.statusFreshnessListeners.clear() + this.providerSessionChangeListeners.clear() + this.enrichedStatusListeners.clear() + this.statusRowMutationListeners.clear() } } diff --git a/src/main/agent-hooks/server/server-listeners.ts b/src/main/agent-hooks/server/server-listeners.ts index 08d2ef21a70..44e2c940753 100644 --- a/src/main/agent-hooks/server/server-listeners.ts +++ b/src/main/agent-hooks/server/server-listeners.ts @@ -9,6 +9,7 @@ import type { AgentHookAuthorityEvidence, AgentHookProviderSessionIdentity, AgentHookStatusChangeEntry, + AgentHookStatusFreshnessObservation, EnrichedAgentHookEventPayload, StatusDropListener } from './server-types' @@ -57,6 +58,26 @@ export abstract class AgentHookServerListeners extends AgentHookServerState { } } + /** Accepted duplicate evidence renews leases without becoming a semantic row mutation. */ + subscribeStatusFreshness( + listener: (status: AgentHookStatusFreshnessObservation) => void + ): () => void { + this.statusFreshnessListeners.add(listener) + return () => { + this.statusFreshnessListeners.delete(listener) + } + } + + protected emitStatusFreshnessObservation(status: AgentHookStatusFreshnessObservation): void { + for (const listener of this.statusFreshnessListeners) { + try { + listener(status) + } catch (err) { + console.error('[agent-hooks] status-freshness listener threw', err) + } + } + } + subscribeProviderSessionChanges( listener: (providerSessions: AgentHookProviderSessionIdentity[]) => void ): () => void { @@ -177,6 +198,7 @@ export abstract class AgentHookServerListeners extends AgentHookServerState { } if (!enriched.providerSessionOnly) { statuses.push({ + paneKey, state: enriched.payload.state, receivedAt: enriched.receivedAt, observedInCurrentRuntime: this.runtimeObservedStatusPaneKeys.has(paneKey) diff --git a/src/main/agent-hooks/server/server-persistence.ts b/src/main/agent-hooks/server/server-persistence.ts index f5b66222d6d..6d811216f9f 100644 --- a/src/main/agent-hooks/server/server-persistence.ts +++ b/src/main/agent-hooks/server/server-persistence.ts @@ -42,6 +42,9 @@ export abstract class AgentHookServerPersistence extends AgentHookServerHydratio observation: _observation, // Replay provenance is runtime-only and must not survive another restart. isReplay: _isReplay, + // A terminal handle belongs to the runtime that issued it; a hydrated one could only + // rejoin a row to somebody else's terminal. + terminalHandle: _terminalHandle, launchToken, ...persistedPayload } = enrichedPayload diff --git a/src/main/agent-hooks/server/server-reaping.ts b/src/main/agent-hooks/server/server-reaping.ts index 7805303ced1..55a6addbc45 100644 --- a/src/main/agent-hooks/server/server-reaping.ts +++ b/src/main/agent-hooks/server/server-reaping.ts @@ -114,6 +114,7 @@ export abstract class AgentHookServerReaping extends AgentHookServerTabCleanup { } } this.state.lastStatusByPaneKey.set(paneKey, reconciled) + this.commitStatusRowMutation(enriched, reconciled) } if (changedPanes > 0) { this.scheduleStatusPersist() diff --git a/src/main/agent-hooks/server/server-row-ownership.ts b/src/main/agent-hooks/server/server-row-ownership.ts new file mode 100644 index 00000000000..2895eb463e4 --- /dev/null +++ b/src/main/agent-hooks/server/server-row-ownership.ts @@ -0,0 +1,132 @@ +import { + isWslHookRelayConnectionId, + wslHookRelayConnectionId +} from '../../../shared/wsl-hook-relay-contract' +import { splitWorktreeIdForFilesystem, worktreeIdsEqual } from '../../../shared/worktree/id' +import { parseWslUncPath } from '../../../shared/wsl-paths' +import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' +import type { + AgentHookStatusRowIdentity, + AgentHookStatusRowMutation, + EnrichedAgentHookEventPayload, + StatusRowMutationListener +} from './server-types' +import { toAgentStatusIpcPayload } from './server-status-identity' +import { AgentHookServerListeners } from './server-listeners' + +function toMutationIdentity( + row: EnrichedAgentHookEventPayload | null | undefined +): AgentHookStatusRowIdentity | null { + if (!row) { + return null + } + return { + paneKey: row.paneKey, + ...(row.worktreeId ? { worktreeId: row.worktreeId } : {}), + ...(row.terminalHandle ? { terminalHandle: row.terminalHandle } : {}) + } +} + +function semanticRowJson(row: EnrichedAgentHookEventPayload | null | undefined): string | null { + if (!row) { + return null + } + const { + receivedAt: _receivedAt, + evidenceObservedAt: _evidenceObservedAt, + observation: _observation, + launchToken: _launchToken, + promptInteractionKey: _promptInteractionKey, + ...semantic + } = toAgentStatusIpcPayload(row) + return JSON.stringify(semantic) +} + +function wslDistroForWorktree(worktreeId: string | undefined): string | null { + const worktreePath = worktreeId + ? splitWorktreeIdForFilesystem(worktreeId)?.worktreePath + : undefined + return worktreePath ? (parseWslUncPath(worktreePath)?.distro ?? null) : null +} + +export abstract class AgentHookServerRowOwnership extends AgentHookServerListeners { + _resetRowOwnershipForTests(): void { + this.paneKeyByTerminalHandle.clear() + } + + subscribeStatusRowMutations(listener: StatusRowMutationListener): () => void { + this.statusRowMutationListeners.add(listener) + return () => { + this.statusRowMutationListeners.delete(listener) + } + } + + protected getStatusPaneKeyForTerminalHandle(terminalHandle: string): string | undefined { + return this.paneKeyByTerminalHandle.get(terminalHandle) + } + + protected sameTerminalOwner( + previous: EnrichedAgentHookEventPayload, + incoming: Pick + ): boolean { + if ( + previous.worktreeId && + incoming.worktreeId && + !worktreeIdsEqual(previous.worktreeId, incoming.worktreeId) + ) { + return false + } + if (previous.connectionId === incoming.connectionId) { + return true + } + const relayConnection = isWslHookRelayConnectionId(previous.connectionId) + ? previous.connectionId + : isWslHookRelayConnectionId(incoming.connectionId) + ? incoming.connectionId + : null + const localConnection = previous.connectionId === null || incoming.connectionId === null + if (!relayConnection || !localConnection || !previous.worktreeId || !incoming.worktreeId) { + return false + } + const previousDistro = wslDistroForWorktree(previous.worktreeId) + const incomingDistro = wslDistroForWorktree(incoming.worktreeId) + return ( + previousDistro !== null && + incomingDistro !== null && + previousDistro === incomingDistro && + relayConnection === wslHookRelayConnectionId(previousDistro) && + worktreeIdsEqual(previous.worktreeId, incoming.worktreeId) + ) + } + + protected commitStatusRowMutation( + before: EnrichedAgentHookEventPayload | null | undefined, + after: EnrichedAgentHookEventPayload | null | undefined, + emit = true + ): boolean { + if ( + before?.terminalHandle && + this.paneKeyByTerminalHandle.get(before.terminalHandle) === before.paneKey + ) { + this.paneKeyByTerminalHandle.delete(before.terminalHandle) + } + if (after?.terminalHandle) { + this.paneKeyByTerminalHandle.set(after.terminalHandle, after.paneKey) + } + if (!emit || semanticRowJson(before) === semanticRowJson(after)) { + return false + } + const mutation: AgentHookStatusRowMutation = { + before: toMutationIdentity(before), + after: toMutationIdentity(after) + } + for (const listener of this.statusRowMutationListeners) { + try { + listener(mutation) + } catch (error) { + console.error('[agent-hooks] status-row mutation listener threw', error) + } + } + return true + } +} diff --git a/src/main/agent-hooks/server/server-state.ts b/src/main/agent-hooks/server/server-state.ts index b18677689d0..0df8ff70445 100644 --- a/src/main/agent-hooks/server/server-state.ts +++ b/src/main/agent-hooks/server/server-state.ts @@ -25,6 +25,7 @@ import type { AgentHookAuthorityEvidence, AgentHookProviderSessionIdentity, AgentHookStatusChangeEntry, + AgentHookStatusFreshnessObservation, AgentPromptSentDedupeEntry, EnrichedAgentHookEventPayload, NormalizedLocalHook, @@ -37,7 +38,9 @@ import type { ServerAgentStatusListener, ServerStatusLineListener, StatusChangeListener, - StatusDropListener + StatusDropListener, + StatusFreshnessListener, + StatusRowMutationListener } from './server-types' /** Shared mutable state for the layered hook-server implementation. */ @@ -53,7 +56,14 @@ export abstract class AgentHookServerState { protected paneStatusClearListeners = new Set() protected statusDropListeners = new Set() protected statusChangeListeners = new Set() + protected statusFreshnessListeners = new Set() protected providerSessionChangeListeners = new Set() + protected statusRowMutationListeners = new Set() + // Hydration and spool replay belong to the owner lifetime, not each transport bind attempt. + protected ownerStateInitialized = false + // Runtime terminal handles are stable across pane remints, unlike tab/leaf keys. This index is + // deliberately in-memory only and contains no rows of its own. + protected paneKeyByTerminalHandle = new Map() // Why: setListener is a single slot owned by the main-window fanout; the // plugin event bus (and future consumers) need an additive subscription // that also works in headless serve, where no window listener exists. @@ -117,6 +127,9 @@ export abstract class AgentHookServerState { providerSessions: AgentHookProviderSessionIdentity[] } protected abstract notifyStatusChangeListeners(): void + protected abstract emitStatusFreshnessObservation( + status: AgentHookStatusFreshnessObservation + ): void protected abstract markTabClosedForAgentStatus(tabId: string): void protected abstract getAgentStatusDisposition( paneKey: string, @@ -154,7 +167,8 @@ export abstract class AgentHookServerState { payload: AgentHookEventPayload, onAccepted?: () => void, origin?: AgentStatusObservationOrigin, - observedAt?: number + observedAt?: number, + mutationBefore?: EnrichedAgentHookEventPayload ): EnrichedAgentHookEventPayload protected abstract emitEnrichedStatus(enriched: EnrichedAgentHookEventPayload): void protected abstract clearAssistantMessageRetry(paneKey: string): void @@ -200,7 +214,10 @@ export abstract class AgentHookServerState { entry: EnrichedAgentHookEventPayload | null | undefined ): EnrichedAgentHookEventPayload | null protected abstract hasLiveClaimsForPaneKey(paneKey: string): boolean - protected abstract clearPaneState(paneKey: string): void + protected abstract clearPaneState( + paneKey: string, + options?: { emitStatusRowMutation?: boolean } + ): void protected abstract deleteStatusEntry( paneKey: string, options?: { preserveAuthority?: boolean } diff --git a/src/main/agent-hooks/server/server-status-disposition.ts b/src/main/agent-hooks/server/server-status-disposition.ts index b6c69967280..c4b7230bc2b 100644 --- a/src/main/agent-hooks/server/server-status-disposition.ts +++ b/src/main/agent-hooks/server/server-status-disposition.ts @@ -41,7 +41,8 @@ export abstract class AgentHookServerStatusDisposition extends AgentHookServerSt const paneRetired = this.closedAgentStatusPaneKeys.has(paneKey) || this.closedAgentStatusPaneKeys.has(ownerPaneKey) - const tabId = parsePaneKey(ownerPaneKey)?.tabId + const tabId = + parsePaneKey(ownerPaneKey)?.tabId ?? parseLegacyNumericPaneKey(ownerPaneKey)?.tabId if (tabId && this.closedAgentStatusTabIds.has(tabId)) { return 'suppress' } diff --git a/src/main/agent-hooks/server/server-status-identity.ts b/src/main/agent-hooks/server/server-status-identity.ts index 4f6e920d86e..1694c4b1b67 100644 --- a/src/main/agent-hooks/server/server-status-identity.ts +++ b/src/main/agent-hooks/server/server-status-identity.ts @@ -69,6 +69,7 @@ export function toAgentStatusIpcPayload( ...(entry.restoredUnconfirmed ? { restoredUnconfirmed: true } : {}), ...(entry.observation ? { observation: entry.observation } : {}), ...(entry.structuredHost ? { structuredHost: entry.structuredHost } : {}), + ...(entry.terminalHandle ? { terminalHandle: entry.terminalHandle } : {}), ...entry.payload } } diff --git a/src/main/agent-hooks/server/server-status-inference.ts b/src/main/agent-hooks/server/server-status-inference.ts index ec651691982..2bbe5508651 100644 --- a/src/main/agent-hooks/server/server-status-inference.ts +++ b/src/main/agent-hooks/server/server-status-inference.ts @@ -14,9 +14,9 @@ import { import { AGENT_STATUS_STALE_AFTER_MS, type AgentType } from '../../../shared/agent-status-types' import type { EnrichedAgentHookEventPayload } from './server-types' import { equivalentInterruptAgentType, isValidPaneKey } from './server-status-identity' -import { AgentHookServerListeners } from './server-listeners' +import { AgentHookServerRowOwnership } from './server-row-ownership' -export abstract class AgentHookServerStatusInference extends AgentHookServerListeners { +export abstract class AgentHookServerStatusInference extends AgentHookServerRowOwnership { inferInterrupt(request: AgentInterruptInferenceRequest): boolean { if (!isValidPaneKey(request.paneKey)) { return false diff --git a/src/main/agent-hooks/server/server-status-update.ts b/src/main/agent-hooks/server/server-status-update.ts index 1a3798efe47..5ea3b07739b 100644 --- a/src/main/agent-hooks/server/server-status-update.ts +++ b/src/main/agent-hooks/server/server-status-update.ts @@ -24,7 +24,8 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusA payload: AgentHookEventPayload, onAccepted?: () => void, origin: AgentStatusObservationOrigin = 'hook', - observedAt?: number + observedAt?: number, + mutationBefore?: EnrichedAgentHookEventPayload ): EnrichedAgentHookEventPayload { if (payload.hookEventName === 'UserPromptSubmit') { // Why: the prompt boundary is authoritative even when text is unchanged; its next OSC working row must not inherit the prior cron/background turn stamp. @@ -33,8 +34,16 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusA let previous = this.state.lastStatusByPaneKey.get(payload.paneKey) as | EnrichedAgentHookEventPayload | undefined - const connectionClearWatermark = payload.connectionId - ? this.connectionTimestampWatermarkById.get(payload.connectionId) + const rowBefore = mutationBefore ?? previous + const terminalHandle = + payload.terminalHandle ?? + (previous?.terminalHandle && this.sameTerminalOwner(previous, payload) + ? previous.terminalHandle + : undefined) + const terminalOwnedPayload = + terminalHandle === payload.terminalHandle ? payload : { ...payload, terminalHandle } + const connectionClearWatermark = terminalOwnedPayload.connectionId + ? this.connectionTimestampWatermarkById.get(terminalOwnedPayload.connectionId) : undefined // Why: renderer ordering rejects older rows; live evidence must sort after reconnect clears and restored rows across clock rollback. const restoredStatusWatermark = previous?.restoredUnconfirmed ? previous.receivedAt : undefined @@ -43,38 +52,41 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusA (connectionClearWatermark ?? -1) + 1, (restoredStatusWatermark ?? -1) + 1 ) - if (payload.connectionId) { - this.connectionTimestampWatermarkById.set(payload.connectionId, now) + if (terminalOwnedPayload.connectionId) { + this.connectionTimestampWatermarkById.set(terminalOwnedPayload.connectionId, now) } - if (payload.providerSessionOnly) { + if (terminalOwnedPayload.providerSessionOnly) { // Why: identity-only rows survive replay but must not emit prompt telemetry or a fabricated status. onAccepted?.() const enriched = { - ...this.attachStatusTiming(payload, now), - observation: this.stampObservation(payload, origin, now) + ...this.attachStatusTiming(terminalOwnedPayload, now), + observation: this.stampObservation(terminalOwnedPayload, origin, now) } this.clearAssistantMessageRetry(enriched.paneKey) this.runtimeObservedStatusPaneKeys.delete(enriched.paneKey) this.state.lastStatusByPaneKey.set(enriched.paneKey, enriched) + this.commitStatusRowMutation(rowBefore, enriched) this.scheduleStatusPersist() this.notifyStatusChangeListeners() this.emitEnrichedStatus(enriched) return enriched } const stateReconciledPayload = - payload.connectionId && payload.payload.agentType === 'codex' && payload.hookEventName + terminalOwnedPayload.connectionId && + terminalOwnedPayload.payload.agentType === 'codex' && + terminalOwnedPayload.hookEventName ? { - ...payload, + ...terminalOwnedPayload, payload: reconcileRemoteCodexState( this.state, - payload.paneKey, - payload.hookEventName, - payload.toolAgentId, - payload.payload, + terminalOwnedPayload.paneKey, + terminalOwnedPayload.hookEventName, + terminalOwnedPayload.toolAgentId, + terminalOwnedPayload.payload, previous?.payload ) } - : payload + : terminalOwnedPayload const previousCodexRoot = stateReconciledPayload.payload.agentType === 'codex' && stateReconciledPayload.toolAgentId && @@ -128,6 +140,7 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusA incomingState: rootContextPreservingPayload.payload.state }) ) { + this.commitStatusRowMutation(rowBefore, previous) return previous } const identityResolvedPayload = @@ -140,6 +153,7 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusA const effectivePayload = attachClaudePermissionToolUseId(previous, identityResolvedPayload) const boundaryAwarePayload = attachClaudeChildOnlyBoundary(previous, effectivePayload) if (previous && shouldKeepClaudePermissionVisible(previous, effectivePayload)) { + this.commitStatusRowMutation(rowBefore, previous) return previous } // Why: some TUIs emit a delayed tool/working hook after Ctrl+C stopped the turn; don't let it resurrect the row. @@ -151,6 +165,7 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusA previous.payload.prompt === effectivePayload.payload.prompt && Date.now() - previous.receivedAt <= INTERRUPTED_DONE_LATE_WORKING_SUPPRESSION_MS ) { + this.commitStatusRowMutation(rowBefore, previous) return previous } if ( @@ -167,6 +182,7 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusA if (effectivePayload.payload.agentType === 'codex') { markCodexLeadTurnInterrupted(this.state, effectivePayload.paneKey) } + this.commitStatusRowMutation(rowBefore, previous) return previous } if ( @@ -179,6 +195,8 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusA if (!identity.inheritedFromActivePane) { this.maybeTrackAgentPromptSent(effectivePayload, previous) } + // Why carried forward only within one host: main's OSC parse resolves the handle, so a later + // hook must not erase its terminal join; a connection change must not inherit another host's. const enriched = { ...this.attachStatusTiming(boundaryAwarePayload, now, observedAt), observation: this.stampObservation(boundaryAwarePayload, origin, observedAt ?? now) @@ -199,6 +217,7 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusA this.runtimeObservedStatusPaneKeys.add(enriched.paneKey) } this.state.lastStatusByPaneKey.set(enriched.paneKey, enriched) + this.commitStatusRowMutation(rowBefore, enriched) // Why skipped for structured rows: the serializer drops them, so the whole walk and stringify // can only ever reproduce the last file — once per debounce window for a streaming chat. if (!enriched.structuredHost) { @@ -209,6 +228,61 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusA return enriched } + protected refreshTerminalStatusEvidence( + previous: EnrichedAgentHookEventPayload, + mutationBefore?: EnrichedAgentHookEventPayload, + emitEnrichedStatus = false + ): void { + const connectionClearWatermark = previous.connectionId + ? this.connectionTimestampWatermarkById.get(previous.connectionId) + : undefined + const now = Math.max(Date.now(), (connectionClearWatermark ?? -1) + 1) + if (previous.connectionId) { + this.connectionTimestampWatermarkById.set(previous.connectionId, now) + } + const { + receivedAt: _receivedAt, + evidenceObservedAt: _evidenceObservedAt, + stateStartedAt, + observation: _observation, + restoredUnconfirmed: _restoredUnconfirmed, + isReplay: _isReplay, + ...payload + } = previous + const refreshed: EnrichedAgentHookEventPayload = { + ...payload, + receivedAt: now, + evidenceObservedAt: now, + stateStartedAt, + observation: this.stampObservation(payload, 'osc', now) + } + const firstRuntimeObservation = !this.runtimeObservedStatusPaneKeys.has(refreshed.paneKey) + this.runtimeObservedStatusPaneKeys.add(refreshed.paneKey) + this.state.lastStatusByPaneKey.set(refreshed.paneKey, refreshed) + this.commitStatusRowMutation(mutationBefore ?? previous, refreshed) + this.scheduleStatusPersist() + // A dismissed row may retain only provider resume identity. Its preserved payload can still + // read `working`, but it is deliberately hidden from live readers and must not renew awake or + // mobile freshness leases. + if (refreshed.providerSessionOnly === true) { + return + } + if (firstRuntimeObservation) { + this.notifyStatusChangeListeners() + } + this.emitStatusFreshnessObservation({ + paneKey: refreshed.paneKey, + state: refreshed.payload.state, + receivedAt: refreshed.receivedAt, + observedInCurrentRuntime: true, + ...(refreshed.worktreeId ? { worktreeId: refreshed.worktreeId } : {}), + ...(refreshed.terminalHandle ? { terminalHandle: refreshed.terminalHandle } : {}) + }) + if (emitEnrichedStatus) { + this.emitEnrichedStatus(refreshed) + } + } + // Why: every status emit must reach plugins too, so a new early-return path // upstream cannot silently leave the plugin tap behind the main-window fanout. protected emitEnrichedStatus(enriched: EnrichedAgentHookEventPayload): void { diff --git a/src/main/agent-hooks/server/server-tab-cleanup.ts b/src/main/agent-hooks/server/server-tab-cleanup.ts index 3ce2c4fce0a..a108bdbbd22 100644 --- a/src/main/agent-hooks/server/server-tab-cleanup.ts +++ b/src/main/agent-hooks/server/server-tab-cleanup.ts @@ -1,15 +1,25 @@ import { clearPaneCacheState } from '../../../shared/agent-hook-listener/listener-state' import { paneCacheKeyMatchesTab } from './server-status-identity' import { AgentHookServerCleanup } from './server-cleanup' +import type { EnrichedAgentHookEventPayload } from './server-types' export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { /** Drop every status/cache claim attributable to a closed tab prefix. */ dropStatusEntriesByTabPrefix(tabId: string): void { this.markTabClosedForAgentStatus(tabId) const paneKeysToClear = new Set() + const statusPaneKeysToClear = new Set() + const statusRowsToClear: EnrichedAgentHookEventPayload[] = [] for (const key of this.state.lastStatusByPaneKey.keys()) { if (paneCacheKeyMatchesTab(key, tabId)) { paneKeysToClear.add(key) + statusPaneKeysToClear.add(key) + const row = this.state.lastStatusByPaneKey.get(key) as + | EnrichedAgentHookEventPayload + | undefined + if (row) { + statusRowsToClear.push(row) + } } } for (const key of this.state.lastPromptByPaneKey.keys()) { @@ -72,21 +82,32 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { this.currentAuthorityObservations.delete(paneKey) this.promptSentDedupeByPaneKey.delete(paneKey) this.restartedStatusLaunchTokenHashByPaneKey.delete(paneKey) + this.evidenceObservedAtByPaneKey.delete(paneKey) } if (aliasChanged) { this.notifyPaneKeyAliasPersistenceListener() } + for (const row of statusRowsToClear) { + this.commitStatusRowMutation(row, undefined) + } if (statusChanged || authorityChanged) { this.scheduleStatusPersist() this.notifyStatusChangeListeners() } + // Why: tab teardown must retire status subscribers' pane-scoped memo state too. + for (const paneKey of statusPaneKeysToClear) { + this.emitPaneStatusCleared({ paneKey }) + } } - clearPaneState(paneKey: string): void { + clearPaneState(paneKey: string, options?: { emitStatusRowMutation?: boolean }): void { const resolvedPaneKey = this.resolvePaneKeyAlias(paneKey) const paneKeys = new Set([paneKey, resolvedPaneKey]) // Why: only persist when a status entry was actually evicted; dropping prompt/tool caches doesn't change the file. - const hadStatus = this.state.lastStatusByPaneKey.has(resolvedPaneKey) + const previousStatus = this.state.lastStatusByPaneKey.get(resolvedPaneKey) as + | EnrichedAgentHookEventPayload + | undefined + const hadStatus = previousStatus !== undefined this.clearAssistantMessageRetry(resolvedPaneKey) this.clearCodexSubagentPoll(resolvedPaneKey) clearPaneCacheState(this.state, resolvedPaneKey) @@ -115,6 +136,9 @@ export abstract class AgentHookServerTabCleanup extends AgentHookServerCleanup { if (clearedAlias) { this.notifyPaneKeyAliasPersistenceListener() } + if (options?.emitStatusRowMutation !== false) { + this.commitStatusRowMutation(previousStatus, undefined) + } if (hadStatus || authorityChanged) { this.runtimeObservedStatusPaneKeys.delete(resolvedPaneKey) this.scheduleStatusPersist() diff --git a/src/main/agent-hooks/server/server-types.ts b/src/main/agent-hooks/server/server-types.ts index c151c70d34b..b4cf176b176 100644 --- a/src/main/agent-hooks/server/server-types.ts +++ b/src/main/agent-hooks/server/server-types.ts @@ -36,6 +36,8 @@ export type PersistedAgentHookEventPayload = Omit< // Why: revision counters are in-memory and the authority id is regenerated per process, so // a stored observation could only rehydrate as a stale ordering claim from a dead authority. | 'observation' + // Same: a terminal handle is issued by one runtime and means nothing to the next. + | 'terminalHandle' > & { launchTokenHash?: string } @@ -50,11 +52,17 @@ export type PersistedAgentHookAuthorityCommitment = { } export type AgentHookStatusChangeEntry = { + paneKey: string state: AgentStatusState receivedAt: number observedInCurrentRuntime: boolean } +export type AgentHookStatusFreshnessObservation = AgentHookStatusChangeEntry & { + worktreeId?: string + terminalHandle?: string +} + export type AgentHookProviderSessionIdentity = { paneKey: string sessionId: string @@ -77,9 +85,20 @@ export type AgentHookAuthorityAttestation = Readonly<{ }> export type StatusChangeListener = (statuses: AgentHookStatusChangeEntry[]) => void +export type StatusFreshnessListener = (status: AgentHookStatusFreshnessObservation) => void export type ProviderSessionChangeListener = ( providerSessions: AgentHookProviderSessionIdentity[] ) => void +export type AgentHookStatusRowIdentity = { + paneKey: string + worktreeId?: string + terminalHandle?: string +} +export type AgentHookStatusRowMutation = { + before: AgentHookStatusRowIdentity | null + after: AgentHookStatusRowIdentity | null +} +export type StatusRowMutationListener = (mutation: AgentHookStatusRowMutation) => void export type PaneStatusClearListener = (clear: AgentStatusClearIpcPayload) => void export type StatusDropListener = (paneKey: string) => void export type PaneKeyAliasPersistenceListener = (entries: LegacyPaneKeyAliasEntry[]) => void diff --git a/src/main/agent-hooks/terminal-handle-row-identity.test.ts b/src/main/agent-hooks/terminal-handle-row-identity.test.ts new file mode 100644 index 00000000000..329ffd19958 --- /dev/null +++ b/src/main/agent-hooks/terminal-handle-row-identity.test.ts @@ -0,0 +1,261 @@ +import { describe, expect, it, vi } from 'vitest' +import { AgentHookServer } from './server' +import { AGENT_STATUS_STALE_AFTER_MS } from '../../shared/agent-status-types' +import { selectFreshExplicitAgentStatus } from '../runtime/runtime-hook-agent-row-selection' +import { wslHookRelayConnectionId } from '../../shared/wsl-hook-relay-contract' + +const PANE_KEY = 'tab-handle:33333333-3333-4333-8333-333333333333' +const HANDLE = 'term_identity' +const NEW_PANE_KEY = 'tab-reminted:44444444-4444-4444-8444-444444444444' + +function ingest(server: AgentHookServer, overrides: Record = {}): void { + server.ingestTerminalStatus({ + paneKey: PANE_KEY, + tabId: 'tab-handle', + worktreeId: 'worktree', + connectionId: null, + terminalHandle: HANDLE, + payload: { state: 'working', prompt: 'ship it', agentType: 'codex' }, + ...overrides + }) +} + +describe('the terminal handle a status row is stamped with', () => { + it('reaches the published row', () => { + const server = new AgentHookServer() + ingest(server) + expect(server.getStatusSnapshot()[0]).toMatchObject({ + paneKey: PANE_KEY, + terminalHandle: HANDLE + }) + }) + + it('survives a later write that resolved no handle', () => { + // Only main's OSC parse resolves one; an HTTP hook post for the same pane carries none and + // must not erase the row's only join back to its terminal. + const server = new AgentHookServer() + ingest(server) + ingest(server, { terminalHandle: undefined, payload: { state: 'done', prompt: 'ship it' } }) + expect(server.getStatusSnapshot()[0]).toMatchObject({ + state: 'done', + terminalHandle: HANDLE + }) + }) + + it('does not cross a connection ownership change on a colliding pane key', () => { + const server = new AgentHookServer() + ingest(server, { connectionId: 'ssh-a' }) + + server.ingestRemote( + { + paneKey: PANE_KEY, + tabId: 'tab-handle', + worktreeId: 'other-worktree', + payload: { state: 'done', prompt: 'other host', agentType: 'codex' } + }, + 'ssh-b' + ) + + expect(server.getStatusSnapshot()[0]).toMatchObject({ + connectionId: 'ssh-b', + worktreeId: 'other-worktree' + }) + expect(server.getStatusSnapshot()[0]).not.toHaveProperty('terminalHandle') + }) + + it('is never persisted, because it belongs to the runtime that issued it', () => { + const server = new AgentHookServer() + ingest(server) + const serialized = ( + server as unknown as { serializeStatusFile(): string } + ).serializeStatusFile() + expect(serialized).toContain(PANE_KEY) + expect(serialized).not.toContain(HANDLE) + }) + + it('moves one PTY row and all of its resume identity across a pane remint', () => { + const server = new AgentHookServer() + ingest(server) + server.ingestRemote( + { + paneKey: PANE_KEY, + tabId: 'tab-handle', + worktreeId: 'worktree', + providerSession: { key: 'session_id', id: 'session-1' }, + payload: { state: 'working', prompt: 'ship it', agentType: 'codex' } + }, + null + ) + const mutations: Parameters[0]>[0][] = [] + server.subscribeStatusRowMutations((mutation) => mutations.push(mutation)) + + ingest(server, { paneKey: NEW_PANE_KEY, tabId: 'tab-reminted' }) + + expect(server.getStatusSnapshot()).toEqual([ + expect.objectContaining({ + paneKey: NEW_PANE_KEY, + terminalHandle: HANDLE, + providerSession: { key: 'session_id', id: 'session-1' } + }) + ]) + expect(mutations).toEqual([ + { + before: { paneKey: PANE_KEY, worktreeId: 'worktree', terminalHandle: HANDLE }, + after: { paneKey: NEW_PANE_KEY, worktreeId: 'worktree', terminalHandle: HANDLE } + } + ]) + + server.dropStatusEntry(NEW_PANE_KEY) + expect(server.getStatusSnapshot()).toEqual([ + expect.objectContaining({ + paneKey: NEW_PANE_KEY, + providerSessionOnly: true, + providerSession: { key: 'session_id', id: 'session-1' } + }) + ]) + expect(server.reconcileEndedProcessForPaneKeys([NEW_PANE_KEY])).toBe(1) + expect(server.getStatusSnapshot()).toEqual([]) + expect(mutations).toHaveLength(3) + expect( + (server as unknown as { paneKeyByTerminalHandle: Map }) + .paneKeyByTerminalHandle + ).toEqual(new Map()) + }) + + it('preserves a local WSL terminal join only for its exact relay distro', () => { + const server = new AgentHookServer() + const worktreeId = String.raw`repo::\\wsl.localhost\Ubuntu\home\user\repo` + ingest(server, { worktreeId }) + + server.ingestRemote( + { + paneKey: PANE_KEY, + tabId: 'tab-handle', + worktreeId, + providerSession: { key: 'session_id', id: 'wsl-session' }, + payload: { state: 'working', prompt: 'ship it', agentType: 'codex' } + }, + wslHookRelayConnectionId('Ubuntu') + ) + expect(server.getStatusSnapshot()[0]).toMatchObject({ terminalHandle: HANDLE }) + + server.ingestRemote( + { + paneKey: PANE_KEY, + tabId: 'tab-handle', + worktreeId, + payload: { state: 'done', prompt: 'wrong distro', agentType: 'codex' } + }, + wslHookRelayConnectionId('Debian') + ) + expect(server.getStatusSnapshot()[0]).not.toHaveProperty('terminalHandle') + }) + + it('renews duplicate OSC evidence without publishing another semantic row', () => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + try { + const server = new AgentHookServer() + const enriched = vi.fn() + const mutated = vi.fn() + const statusChanges = vi.fn() + server.subscribeEnrichedStatus(enriched) + server.subscribeStatusRowMutations(mutated) + server.subscribeStatusChanges(statusChanges) + ingest(server) + enriched.mockClear() + mutated.mockClear() + statusChanges.mockClear() + + vi.setSystemTime(1_000 + AGENT_STATUS_STALE_AFTER_MS + 1) + ingest(server) + + const [row] = server.getStatusSnapshot() + expect(row.evidenceObservedAt).toBe(Date.now()) + expect( + selectFreshExplicitAgentStatus({ handle: HANDLE, paneKey: PANE_KEY, hookRows: [row] }) + ).toMatchObject({ status: 'working', updatedAt: Date.now() }) + expect(enriched).not.toHaveBeenCalled() + expect(mutated).not.toHaveBeenCalled() + expect(statusChanges).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) + + it('publishes an enriched observation when duplicate OSC transfers pane authority', () => { + const server = new AgentHookServer() + const enriched = vi.fn() + server.subscribeEnrichedStatus(enriched) + ingest(server) + enriched.mockClear() + + ingest(server, { paneKey: NEW_PANE_KEY, tabId: 'tab-reminted' }) + + expect(enriched).toHaveBeenCalledWith( + expect.objectContaining({ paneKey: NEW_PANE_KEY, terminalHandle: HANDLE }) + ) + }) + + it('publishes only the remint observation for a Claude child-only row', () => { + const server = new AgentHookServer() + const enriched = vi.fn() + const mutations = vi.fn() + server.subscribeEnrichedStatus(enriched) + server.subscribeStatusRowMutations(mutations) + const payload = { state: 'working' as const, prompt: 'ship it', agentType: 'claude' as const } + ingest(server, { payload }) + const row = server._getStateForTests().lastStatusByPaneKey.get(PANE_KEY) as + | { claudeLeadBoundaryChildOnly?: true } + | undefined + if (!row) { + throw new Error('expected seeded status row') + } + row.claudeLeadBoundaryChildOnly = true + enriched.mockClear() + mutations.mockClear() + + ingest(server, { payload }) + expect(enriched).not.toHaveBeenCalled() + expect(mutations).not.toHaveBeenCalled() + + ingest(server, { paneKey: NEW_PANE_KEY, tabId: 'tab-reminted', payload }) + expect(enriched).toHaveBeenCalledOnce() + expect(mutations).toHaveBeenCalledOnce() + expect(mutations).toHaveBeenCalledWith({ + before: { paneKey: PANE_KEY, worktreeId: 'worktree', terminalHandle: HANDLE }, + after: { paneKey: NEW_PANE_KEY, worktreeId: 'worktree', terminalHandle: HANDLE } + }) + expect(enriched).toHaveBeenCalledWith( + expect.objectContaining({ paneKey: NEW_PANE_KEY, terminalHandle: HANDLE }) + ) + }) + + it('does not renew freshness from a provider-session-only dismissal remnant', () => { + const server = new AgentHookServer() + const freshness = vi.fn() + server.subscribeStatusFreshness(freshness) + ingest(server) + server.ingestRemote( + { + paneKey: PANE_KEY, + tabId: 'tab-handle', + worktreeId: 'worktree', + providerSession: { key: 'session_id', id: 'resume-me' }, + payload: { state: 'working', prompt: 'ship it', agentType: 'codex' } + }, + null + ) + server.dropStatusEntry(PANE_KEY) + freshness.mockClear() + + ingest(server) + + expect(server.getStatusSnapshot()[0]).toMatchObject({ + paneKey: PANE_KEY, + providerSessionOnly: true, + providerSession: { key: 'session_id', id: 'resume-me' } + }) + expect(freshness).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/ai-vault-search/session-search-clock.ts b/src/main/ai-vault-search/session-search-clock.ts new file mode 100644 index 00000000000..c9eaf609a34 --- /dev/null +++ b/src/main/ai-vault-search/session-search-clock.ts @@ -0,0 +1,24 @@ +// Why injected rather than the globals: every freshness guarantee this indexer +// makes is "within one reconcile interval", and a guarantee stated in wall time +// is only a claim until a test can advance the clock and watch it hold. + +/** Opaque to the indexer; a fake clock hands back whatever it likes. */ +export type SessionSearchTimerHandle = object | number + +export type SessionSearchClock = { + now(): number + setTimeout(callback: () => void, ms: number): SessionSearchTimerHandle + clearTimeout(handle: SessionSearchTimerHandle): void +} + +export const systemSessionSearchClock: SessionSearchClock = { + now: () => Date.now(), + setTimeout: (callback, ms) => { + const timer = setTimeout(callback, ms) + // Nothing here should hold the process open: the index is a cache, and a + // pending reconcile is never a reason to keep a CLI or a child alive. + timer.unref?.() + return timer + }, + clearTimeout: (handle) => clearTimeout(handle as NodeJS.Timeout) +} diff --git a/src/main/ai-vault-search/session-search-content-hash.test.ts b/src/main/ai-vault-search/session-search-content-hash.test.ts new file mode 100644 index 00000000000..1e7232fc855 --- /dev/null +++ b/src/main/ai-vault-search/session-search-content-hash.test.ts @@ -0,0 +1,48 @@ +import { expect, it } from 'vitest' +import { + EMPTY_CONTENT_HASH, + foldContentHash, + isCollapsibleContentHash +} from './session-search-content-hash' +import { userMessages } from './session-search-index-test-fixture' + +it('reaches the same digest whether the prefix arrives whole or in two appends', () => { + const messages = userMessages('turn', 5) + const whole = foldContentHash(EMPTY_CONTENT_HASH, messages) + const resumed = foldContentHash( + foldContentHash(EMPTY_CONTENT_HASH, messages.slice(0, 2)), + messages.slice(2) + ) + + expect(resumed).toEqual(whole) + expect(whole.count).toBe(5) +}) + +it('freezes once the prefix limit is reached so later appends cannot move it', () => { + // Found rather than imported: the limit is the module's business, and a test + // that reads it off the export cannot notice the fold ignoring it. + const capped = foldContentHash(EMPTY_CONTENT_HASH, userMessages('turn', 64)) + expect(capped.count).toBeLessThan(64) + expect(foldContentHash(capped, userMessages('later', 20))).toEqual(capped) +}) + +it('separates two conversations that share an opening prompt', () => { + const shared = userMessages('same opening', 1) + const first = foldContentHash(EMPTY_CONTENT_HASH, [ + ...shared, + { role: 'user', text: 'left', timestamp: null } + ]) + const second = foldContentHash(EMPTY_CONTENT_HASH, [ + ...shared, + { role: 'user', text: 'right', timestamp: null } + ]) + expect(first.hash).not.toBe(second.hash) +}) + +it('refuses to collapse on a prefix too short to mean anything', () => { + const one = foldContentHash(EMPTY_CONTENT_HASH, userMessages('only turn', 1)) + expect(isCollapsibleContentHash(one.hash, one.count)).toBe(false) + const two = foldContentHash(EMPTY_CONTENT_HASH, userMessages('two turns', 2)) + expect(isCollapsibleContentHash(two.hash, two.count)).toBe(true) + expect(isCollapsibleContentHash(null, 9)).toBe(false) +}) diff --git a/src/main/ai-vault-search/session-search-content-hash.ts b/src/main/ai-vault-search/session-search-content-hash.ts new file mode 100644 index 00000000000..a9d2ab229da --- /dev/null +++ b/src/main/ai-vault-search/session-search-content-hash.ts @@ -0,0 +1,45 @@ +import { createHash } from 'node:crypto' +import type { TranscriptMessage } from '../ai-vault/session-transcript-consumers' + +// Why: Claude `--resume` and Codex fork copy the parent transcript into a new +// file under a new session id, so one conversation lands N times in results. +// The shared opening prefix is what identifies the copy; the tail diverges. +const CONTENT_HASH_MESSAGE_LIMIT = 8 +// One shared opening prompt is not evidence of a fork; two turns is. +const CONTENT_HASH_MIN_MESSAGES = 2 + +export type SessionContentHash = { hash: string | null; count: number } + +export const EMPTY_CONTENT_HASH: SessionContentHash = { hash: null, count: 0 } + +/** + * Chained digest over the first `CONTENT_HASH_MESSAGE_LIMIT` messages. Chaining + * (rather than hashing one joined string) makes it resumable, so an `append` + * can finish a prefix a short `replace` started; once the limit is reached the + * value is frozen and later appends leave it untouched. + */ +export function foldContentHash( + previous: SessionContentHash, + messages: readonly TranscriptMessage[] +): SessionContentHash { + let { hash, count } = previous + for (const message of messages) { + if (count >= CONTENT_HASH_MESSAGE_LIMIT) { + break + } + hash = createHash('sha256') + .update(hash ?? '') + .update('\0') + .update(message.role) + .update('\0') + .update(message.text) + .digest('hex') + count += 1 + } + return { hash, count } +} + +/** Sessions collapse only on a hash that covers enough turns to mean anything. */ +export function isCollapsibleContentHash(hash: string | null, count: number): hash is string { + return hash !== null && count >= CONTENT_HASH_MIN_MESSAGES +} diff --git a/src/main/ai-vault-search/session-search-cwd-key.test.ts b/src/main/ai-vault-search/session-search-cwd-key.test.ts new file mode 100644 index 00000000000..24d915eedc9 --- /dev/null +++ b/src/main/ai-vault-search/session-search-cwd-key.test.ts @@ -0,0 +1,37 @@ +import { expect, it } from 'vitest' +import { folderGroupKey } from '../../shared/ai-vault-session-filters' +import { cwdKey } from './session-search-file-records' + +// The sidebar groups sessions by `folderGroupKey`, which is the shared +// normalizer under a `folder:` prefix. A hit's `cwd_key` has to be the same +// string, or joining an indexed hit to a sidebar group returns nothing. +const CASES: [name: string, cwd: string][] = [ + ['a POSIX path', '/repo/app'], + ['a trailing slash', '/repo/app/'], + ['a Windows drive', 'C:\\Users\\me\\repo'], + ['a WSL interop mount', '/mnt/c/Users/me/repo'], + ['a WSL UNC path', '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo'], + ['the wsl$ alias for the same path', '//wsl$/Ubuntu/home/me/repo'], + ['a Linux path from inside WSL', '/home/me/repo'], + ['the filesystem root', '/'] +] + +it.each(CASES)('keys %s exactly as the sidebar does', (_name, cwd) => { + expect(`folder:${cwdKey(cwd)}`).toBe(folderGroupKey(cwd)) +}) + +it('keeps the root as a path rather than collapsing it to nothing', () => { + // An empty key is indistinguishable from "no cwd", and the scope filter builds + // its child prefix as `key + '/'`, which would be `//` for an empty key. + expect(cwdKey('/')).toBe('/') +}) + +it('has no key for a session whose cwd the transcript never recorded', () => { + expect(cwdKey(null)).toBeNull() +}) + +it('folds the two WSL UNC aliases onto one key', () => { + expect(cwdKey('\\\\wsl.localhost\\Ubuntu\\home\\me\\repo')).toBe( + cwdKey('//wsl$/ubuntu/home/me/repo') + ) +}) diff --git a/src/main/ai-vault-search/session-search-degraded-roots.ts b/src/main/ai-vault-search/session-search-degraded-roots.ts new file mode 100644 index 00000000000..0432cdbc99f --- /dev/null +++ b/src/main/ai-vault-search/session-search-degraded-roots.ts @@ -0,0 +1,88 @@ +import type { AiVaultScanIssue } from '../../shared/ai-vault-types' +import type { SessionSearchDirectoryReader } from './session-search-directory-listings' + +/** A scan root this pass could not read through, and what stopped it. */ +export type SessionSearchDegradedRoot = { root: string; reason: string } + +/** + * Roots a pass could not read, derived from that pass alone. + * + * There is no root-health state machine any more and nothing is carried between + * passes: "degraded" now means one of two things this pass observed, both of + * which are readdir results. + * + * 1. Discovery recorded a scan issue against the root itself — a stalled WSL + * distro, a gate refusal, an unreadable tree. + * 2. The retirement walk could not prove a file the index holds under that root + * either present or gone, because a directory between the file and the root + * refused to list, or because the root itself is not there. + * 3. A root that yielded no transcripts refuses to list at all. The file walker + * swallows a readdir failure and returns, so without this an EACCES root and + * an agent that was never installed both arrive as "no files" — reporting + * the first as an empty index is the loss-of-contact-as-absence mistake + * docs/reference/ssh-execution-boundary.md forbids. + * + * The second is what reports a detached volume, and it needs no memory of + * previous passes: the evidence is the index's own rows plus this pass's + * readdir errors. A root the index holds nothing under and cannot list is + * reported by the third; a root that is simply missing is not reported at all, + * because that is what an agent nobody installed looks like. + */ +export function scanIssueDegradedRoots( + roots: readonly string[], + issues: readonly AiVaultScanIssue[] +): SessionSearchDegradedRoot[] { + const degraded = new Map() + for (const issue of issues) { + // 'notice' rows are scanner commentary; a per-file failure is not a root's. + if (issue.kind !== 'notice' && roots.includes(issue.path)) { + degraded.set(issue.path, issue.message) + } + } + return [...degraded].map(([root, reason]) => ({ root, reason })) +} + +/** One entry per root, first reason kept, so a pass reports each root once. */ +export function mergeDegradedRoots( + ...groups: readonly (readonly SessionSearchDegradedRoot[])[] +): SessionSearchDegradedRoot[] { + const merged = new Map() + for (const group of groups) { + for (const degraded of group) { + if (!merged.has(degraded.root)) { + merged.set(degraded.root, degraded.reason) + } + } + } + return [...merged].map(([root, reason]) => ({ root, reason })) +} + +// A missing root is not a broken one: an uninstalled agent's root answers +// exactly this, and the index holding rows under it is what the retirement +// walk reports instead. +const MISSING_ROOT = new Set(['ENOENT', 'ENOTDIR']) + +/** + * Roots that yielded no transcripts and cannot be listed either. + * + * Only roots a pass found empty are read: one that returned files is readable + * by construction. The read shares the pass's listing cache, so a root the + * retirement walk also has to ask about costs one readdir between them. + */ +export async function unreadableRoots( + roots: readonly string[], + listings: SessionSearchDirectoryReader, + signal?: AbortSignal +): Promise { + const degraded: SessionSearchDegradedRoot[] = [] + for (const root of roots) { + if (signal?.aborted) { + break + } + const listing = await listings.namesIn(root, signal) + if (!listing.listed && !(listing.code !== null && MISSING_ROOT.has(listing.code))) { + degraded.push({ root, reason: listing.message }) + } + } + return degraded +} diff --git a/src/main/ai-vault-search/session-search-deleted-sources.test.ts b/src/main/ai-vault-search/session-search-deleted-sources.test.ts new file mode 100644 index 00000000000..d1c367d632f --- /dev/null +++ b/src/main/ai-vault-search/session-search-deleted-sources.test.ts @@ -0,0 +1,356 @@ +import { chmod, mkdir, rm, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import { parserPublishesMessages } from '../ai-vault/session-scanner-agent-parser' +import { resetTranscriptConsumersForTests } from '../ai-vault/session-transcript-consumers' +import { retireDeletedSessionSearchSources } from './session-search-deleted-sources' +import { + SessionSearchDirectoryListings, + type SessionSearchDirectoryListing, + type SessionSearchDirectoryReader +} from './session-search-directory-listings' +import { + openSessionSearchIndexerHarness, + type SessionSearchIndexerHarness +} from './session-search-indexer-test-fixture' +import { SessionSearchStore } from './session-search-store' + +// The invariants this file exists to pin are written at the top of +// session-search-deleted-sources.ts. Each one is named in the tests below. + +const CAN_DENY_READ = process.platform !== 'win32' && process.getuid?.() !== 0 + +let harness: SessionSearchIndexerHarness +let store: SessionSearchStore +let removed: string[] + +beforeEach(async () => { + resetTranscriptConsumersForTests() + harness = await openSessionSearchIndexerHarness('ss-deleted-sources') + removed = [] + store = new SessionSearchStore(harness.databasePath) + // Only the removal matters here; the store's own removal path has its own tests. + store.removeFile = (path: string) => removed.push(path) +}) + +afterEach(async () => { + store.close() + await harness.cleanup() +}) + +/** A reader that answers with whatever a stalled mount would, per directory. */ +function readerAnswering( + answers: Record +): SessionSearchDirectoryReader { + return { + namesIn: (directory) => + Promise.resolve( + answers[directory] ?? { listed: false, code: 'ENOENT', message: 'no such directory' } + ) + } +} + +function retire( + paths: readonly string[], + options: { + roots?: readonly string[] + emptiedRoots?: ReadonlySet + enumeratedContainers?: ReadonlyMap> + listings?: SessionSearchDirectoryReader + directoryLimit?: number + } = {} +) { + return retireDeletedSessionSearchSources({ + store, + paths, + roots: options.roots ?? [harness.roots.claudeProjectsDir ?? ''], + emptiedRoots: options.emptiedRoots, + enumeratedContainers: options.enumeratedContainers, + listings: options.listings ?? new SessionSearchDirectoryListings(), + directoryLimit: options.directoryLimit + }) +} + +// I4: a file the user deleted retires on the first pass that proves it, with no +// waiting period, because its directory listed and it was not in the listing. +it('retires a deleted file the moment its own directory lists without it', async () => { + const kept = join(harness.claudeProjectDir, 'kept.jsonl') + await mkdir(harness.claudeProjectDir, { recursive: true }) + await writeFile(kept, '{}') + const deleted = join(harness.claudeProjectDir, 'deleted.jsonl') + + const result = await retire([kept, deleted]) + expect(result.retired).toEqual([deleted]) + expect(removed).toEqual([deleted]) + // A file that is still there is settled, not watched: it is neither retired + // nor carried into the next pass as unfinished business. + expect(result.unverifiable).toEqual([]) + expect(result.degradedRoots).toEqual([]) +}) + +// I4, the other shape: the directory itself is gone, so the question moves up +// one level and the root answers it. +it('retires a whole project directory the user deleted', async () => { + const sibling = join(harness.roots.claudeProjectsDir ?? '', 'other', 'kept.jsonl') + await mkdir(join(harness.roots.claudeProjectsDir ?? '', 'other'), { recursive: true }) + await writeFile(sibling, '{}') + const gone = join(harness.claudeProjectDir, 'inside-a-deleted-project.jsonl') + + const result = await retire([gone]) + expect(result.retired).toEqual([gone]) + expect(result.unverifiable).toEqual([]) +}) + +// I1 and I2: a root that is not there proves nothing. The walk stops at the +// configured root and never asks what is above it, so a home directory on an +// unmounted volume — the shape a detached drive or a dropped SSH mount takes — +// leaves every row exactly where it was. +it('keeps every row under a root that is not there', async () => { + const root = harness.roots.claudeProjectsDir ?? '' + const held = [join(harness.claudeProjectDir, 'one.jsonl'), join(root, 'flat.jsonl')] + + const result = await retire(held) + expect(result.retired).toEqual([]) + expect(result.unverifiable).toEqual(held) + // The root is named, once, so a caller can say which tree is unreachable. + expect(result.degradedRoots).toEqual([{ root, reason: `${root} could not be listed.` }]) +}) + +// I3: the same answer with no memory at all. Nothing here is carried from a +// previous pass, which is what makes the first sweep after a restart — when a +// volume is most likely to be missing — behave like every other pass. +it('keeps a missing root on a pass that has seen nothing before it', async () => { + const root = harness.roots.claudeProjectsDir ?? '' + const held = join(harness.claudeProjectDir, 'one.jsonl') + const first = await retire([held], { emptiedRoots: new Set() }) + const second = await retire([held], { emptiedRoots: new Set() }) + expect([first.retired, second.retired]).toEqual([[], []]) + expect(second.degradedRoots.map((one) => one.root)).toEqual([root]) +}) + +// I2: an unreadable directory is not an empty one. EACCES stops the walk where +// it is rather than being walked up like a missing component. +it.skipIf(!CAN_DENY_READ)('keeps rows under a directory that refuses to list', async () => { + const blocked = join(harness.roots.claudeProjectsDir ?? '', 'blocked') + await mkdir(blocked, { recursive: true }) + const hidden = join(blocked, 'hidden.jsonl') + await writeFile(hidden, '{}') + await chmod(blocked, 0o000) + try { + const result = await retire([hidden]) + expect(result.retired).toEqual([]) + expect(result.unverifiable).toEqual([hidden]) + expect(result.degradedRoots.map((one) => one.root)).toEqual([harness.roots.claudeProjectsDir]) + } finally { + await chmod(blocked, 0o755) + } +}) + +// I2, without needing a filesystem that can produce it: a stalled network mount +// answers EIO or a WSL gate refusal, and neither is ENOENT. This is the SSH and +// WSL case — loss of contact is never evidence of absence. +it('keeps rows when a directory answers with a transport failure', async () => { + const root = harness.roots.claudeProjectsDir ?? '' + const held = join(harness.claudeProjectDir, 'one.jsonl') + for (const listing of [ + { listed: false as const, code: 'EIO', message: 'input/output error' }, + { listed: false as const, code: 'ETIMEDOUT', message: 'the mount stopped answering' }, + { listed: false as const, code: null, message: 'The distro stopped responding.' } + ]) { + const result = await retire([held], { + listings: readerAnswering({ [harness.claudeProjectDir]: listing }) + }) + expect(result.retired).toEqual([]) + expect(result.degradedRoots).toEqual([{ root, reason: listing.message }]) + } +}) + +// The one bit of memory, and the only thing it buys: a root that held +// transcripts on the previous pass and lists empty on this one gets one pass of +// grace, so a directory swapped out for a moment cannot retire a tree. +it('holds a root that went from holding transcripts to empty in one pass', async () => { + const root = harness.roots.claudeProjectsDir ?? '' + await mkdir(root, { recursive: true }) + const held = join(harness.claudeProjectDir, 'one.jsonl') + + const grace = await retire([held], { emptiedRoots: new Set([root]) }) + expect(grace.retired).toEqual([]) + expect(grace.unverifiable).toEqual([held]) + + // The next pass has no transition to point at, so the empty listing is what + // it says it is: the user emptied the root. + const after = await retire([held], { emptiedRoots: new Set() }) + expect(after.retired).toEqual([held]) +}) + +// A flat-layout agent, where the mountpoint IS the session directory, is the +// one shape the grace exists for: there is no intermediate directory whose +// absence could stop the walk. +it('holds a flat root that emptied in one pass, and retires it on the next', async () => { + const root = harness.roots.copilotSessionsDir ?? '' + await mkdir(root, { recursive: true }) + const held = join(root, 'session.jsonl') + + expect((await retire([held], { roots: [root], emptiedRoots: new Set([root]) })).retired).toEqual( + [] + ) + expect((await retire([held], { roots: [root] })).retired).toEqual([held]) +}) + +// OpenClaw's discovery merges two directories into one delimiter-joined label. +// Roots reach this function as the real directories behind that label, so one +// of them being unreachable never touches the other's rows. +it('judges each merged-root directory on its own', async () => { + const current = join(harness.roots.openclawStateDir ?? '', 'agents') + const legacy = join(harness.roots.openclawLegacyStateDir ?? '', 'agents') + const onMissing = join(current, 'main', 'sessions', 'mounted.jsonl') + const deleted = join(legacy, 'main', 'sessions', 'deleted.jsonl') + await mkdir(join(legacy, 'main', 'sessions'), { recursive: true }) + + const result = await retire([onMissing, deleted], { roots: [current, legacy] }) + expect(result.retired).toEqual([deleted]) + expect(result.unverifiable).toEqual([onMissing]) + expect(result.degradedRoots.map((one) => one.root)).toEqual([current]) +}) + +// A row under no configured root is judged by its own directory and nothing +// above it, so a moved profile is never retired on the strength of a root that +// no longer covers it. +it('judges a row under no configured root by its own directory', async () => { + const orphanDir = join(harness.root, 'moved-profile') + await mkdir(orphanDir, { recursive: true }) + const gone = join(orphanDir, 'gone.jsonl') + const present = join(orphanDir, 'present.jsonl') + await writeFile(present, '{}') + + const result = await retire([gone, present], { roots: [] }) + expect(result.retired).toEqual([gone]) + // No configured root owns it, so nothing is reported as degraded for it. + expect(result.degradedRoots).toEqual([]) +}) + +// I8. A synthetic row names a container and an entry inside it. Walking the +// row's own path would report every one of them gone, and walking only the +// container proves nothing about the entry: a session deleted inside a database +// that is still there would never be retired at all. +it('proves a synthetic row against its container, not against its own path', async () => { + const db = join(harness.root, 'opencode.db') + await writeFile(db, '') + const kept = `${db}#session-1` + const deleted = `${db}#session-2` + const enumeratedContainers = new Map([[db, new Set(['session-1'])]]) + + const result = await retire([kept, deleted], { roots: [], enumeratedContainers }) + expect(result.retired).toEqual([deleted]) + expect(result.unverifiable).toEqual([]) +}) + +it('keeps a synthetic row when this pass did not enumerate its container', async () => { + const db = join(harness.root, 'opencode.db') + await writeFile(db, '') + const row = `${db}#session-1` + + // A cycle asks for the newest N per agent, so a row it did not return may be + // the one after them. It enumerates nothing and therefore proves nothing. + await expect(retire([row], { roots: [] })).resolves.toMatchObject({ + retired: [], + unverifiable: [row] + }) + + // An enumeration that returned nothing at all is not evidence either: a + // database whose schema this scanner no longer recognises reads as empty + // with no error, and believing it would retire every session in one pass. + await expect( + retire([row], { roots: [], enumeratedContainers: new Map([[db, new Set()]]) }) + ).resolves.toMatchObject({ retired: [], unverifiable: [row] }) +}) + +it('retires a synthetic row when the container it came from is gone', async () => { + const db = join(harness.root, 'opencode.db') + await writeFile(db, '') + const row = `${db}#session-1` + const enumeratedContainers = new Map([[db, new Set(['session-1'])]]) + await expect(retire([row], { roots: [], enumeratedContainers })).resolves.toMatchObject({ + retired: [] + }) + + await rm(db) + await expect(retire([row], { roots: [], enumeratedContainers })).resolves.toMatchObject({ + retired: [row] + }) +}) + +// Nothing in this PR can hold a synthetic row: the index pass refuses a source +// whose parser decodes its messages where the message channel cannot reach +// them, and OpenCode's SQLite sessions are read on a worker thread. The rule +// above is the guard for the day that changes -- without it the walk would read +// `#` as a filename and retire every such row the moment it appeared. +it('does not index a source whose messages the channel cannot reach', () => { + const db = join(harness.root, 'opencode.db') + expect( + parserPublishesMessages({ + agent: 'opencode', + codexHome: null, + file: { path: `${db}#session-1`, mtimeMs: 1, modifiedAt: '', sizeBytes: 0 } + }) + ).toBe(false) +}) + +// Round 12, F1. The cap counts directories because that is what costs: rows +// sharing one are a single read and then map lookups. +it('caps the directories one pass reads, not the rows it answers', async () => { + const roots = [harness.claudeProjectDir] + const inside = (folder: string, name: string): string => + join(harness.claudeProjectDir, folder, name) + for (const folder of ['one', 'two', 'three']) { + await mkdir(join(harness.claudeProjectDir, folder), { recursive: true }) + } + // Four rows in each of three directories: three reads, twelve answers. + const paths = ['one', 'two', 'three'].flatMap((folder) => + ['a', 'b', 'c', 'd'].map((name) => inside(folder, name)) + ) + + const result = await retire(paths, { roots, directoryLimit: 2 }) + + // Two directories' worth answered, all eight of their rows, and the third + // directory's four left for the pass after this one. + expect(result.retired).toEqual(paths.slice(0, 8)) + expect(result.unchecked).toEqual(paths.slice(8)) +}) + +// The starvation this replaced: an unreadable directory answers `unverifiable` +// for every row under it and never becomes readable, so a cap on rows let one +// such directory hold the walk for as long as the permission stayed wrong. +it.skipIf(!CAN_DENY_READ)( + 'is not starved by many rows under one unreadable directory', + async () => { + const locked = join(harness.claudeProjectDir, 'locked') + await mkdir(locked, { recursive: true }) + const blocked = Array.from({ length: 520 }, (_unused, index) => + join(locked, `locked-${index}.jsonl`) + ) + const deleted = join(harness.claudeProjectDir, 'deleted.jsonl') + await chmod(locked, 0o000) + try { + const result = await retire([...blocked, deleted], { directoryLimit: 512 }) + + expect(result.retired).toEqual([deleted]) + expect(result.unverifiable).toHaveLength(blocked.length) + expect(result.unchecked).toEqual([]) + } finally { + await chmod(locked, 0o700) + } + } +) + +it('reads each directory once however many files it is asked about', async () => { + await mkdir(harness.claudeProjectDir, { recursive: true }) + const listings = new SessionSearchDirectoryListings() + await retire( + Array.from({ length: 50 }, (_unused, index) => + join(harness.claudeProjectDir, `gone-${index}.jsonl`) + ), + { listings } + ) + expect(listings.size).toBe(1) +}) diff --git a/src/main/ai-vault-search/session-search-deleted-sources.ts b/src/main/ai-vault-search/session-search-deleted-sources.ts new file mode 100644 index 00000000000..e600cd3c4b1 --- /dev/null +++ b/src/main/ai-vault-search/session-search-deleted-sources.ts @@ -0,0 +1,263 @@ +import { basename, dirname } from 'node:path' +import type { SessionSearchDegradedRoot } from './session-search-degraded-roots' +import type { SessionSearchDirectoryReader } from './session-search-directory-listings' +import { isUnderScanRoot } from './session-search-scan-roots' +import { splitSyntheticSessionSource } from './session-search-synthetic-sources' +import type { SessionSearchStore } from './session-search-store' + +/* + * Retirement invariants. Every one of these is a test; changing this file means + * changing the list, not working around it. + * + * I1. A row is retired only when its file is PROVEN gone: some directory + * between the file and its configured root lists successfully, and the next + * path component toward the file is absent from that listing. + * I2. If no directory from the file's parent up to the configured root can be + * listed, nothing is proven and no row is dropped. ENOENT/ENOTDIR is walked + * up (the directory itself is a missing component of some ancestor); + * EACCES, EIO, a WSL gate refusal, anything else, is unverifiable at once. + * I3. The rule is the same on the first pass after a process start and on every + * later pass. It needs no memory of what previous passes saw, because the + * walk is bounded at the configured root and never reasons about what is + * above it. + * I4. A file, or a project directory, the user really deleted retires on the + * first pass that proves it. There is no waiting period and no census. + * I8. A row whose path names an entry inside a container rather than a file of + * its own is proven the same way, one level up: the container must be + * present, and the pass must have enumerated it in full and successfully. + * A listing is a listing whether it comes from readdir or from a database. + * + * What I3 costs, stated rather than hidden: a volume mounted at exactly a + * configured root, unmounted so that the mountpoint stays present and lists + * empty, is indistinguishable from a root the user emptied. It retires. The + * realistic unmount shapes do not: a mount above the root leaves the root + * itself missing (the walk stops at the root boundary), and an unreadable root + * is an error, not a listing. One bit per root buys the remaining grace: a root + * that held transcripts on the previous pass and holds none on this one is + * unverifiable for that pass, so a single flap cannot retire a tree. + */ + +// Walked up rather than believed: a directory that ENOENTs is itself the +// missing component its parent has to be asked about. +const MISSING_DIRECTORY = new Set(['ENOENT', 'ENOTDIR']) + +export type SessionSearchRetirement = { + /** Paths proven gone and dropped from the index. */ + retired: string[] + /** Rows kept: this pass could prove the file neither present nor gone. */ + unverifiable: string[] + /** Paths the per-pass cap left for next time. */ + unchecked: string[] + /** Roots owning at least one unverifiable verdict, with the reason. */ + degradedRoots: SessionSearchDegradedRoot[] +} + +export type SessionSearchRetirementArgs = { + store: SessionSearchStore + /** Held paths this pass did not discover; everything else is still there. */ + paths: readonly string[] + /** The real directories this pass walked; the longest one containing a path bounds its walk. */ + roots: readonly string[] + /** Roots that listed transcripts on the previous pass and none on this one. */ + emptiedRoots?: ReadonlySet + /** + * Containers this pass enumerated in full, with the ids each holds. Only a + * census builds it; see session-search-synthetic-sources.ts for the bar a + * container has to meet before it appears here. + */ + enumeratedContainers?: ReadonlyMap> + /** One readdir per directory per pass, shared with the rest of the pass. */ + listings: SessionSearchDirectoryReader + /** + * Directories this walk may read before the pass moves on. + * + * Directories, not rows. A row whose walk finds its directory already read is + * answered from the pass's cache and costs nothing, so counting rows made an + * unreadable directory able to starve the whole walk: five hundred rows under + * one EACCES directory are one readdir and five hundred identical + * unverifiable verdicts, and a row for a file the user really deleted, sorted + * behind them, was never reached on any pass. + */ + directoryLimit?: number + signal?: AbortSignal +} + +type SessionSearchSourceVerdict = + | { verdict: 'gone' } + | { verdict: 'present' } + | { verdict: 'unverifiable'; reason: string } + +/** + * Retires index rows for sources that are provably gone. + * + * One function, called by both the sweep and the cycle, because either one + * alone deleting a user's history the first time a mount is missing is the bug + * this feature kept shipping. There is no separate root fence: the walk cannot + * reach a verdict of `gone` without a successful listing, so an unreadable or + * missing root produces `unverifiable` structurally rather than by a guard + * somebody has to remember to call (docs/reference/ssh-execution-boundary.md: + * loss of contact is never evidence of absence). + */ +export async function retireDeletedSessionSearchSources( + args: SessionSearchRetirementArgs +): Promise { + const { store, paths, signal } = args + const emptiedRoots = args.emptiedRoots ?? new Set() + const directoryLimit = args.directoryLimit ?? Number.POSITIVE_INFINITY + // Every directory this walk asked for, whether the pass had already read it + // or not. What it bounds is real work: a repeat of one already in here is a + // map lookup, and only a name that is new to it can cost a readdir. + const asked = new Set() + const listings: SessionSearchDirectoryReader = { + namesIn: (directory, signal) => { + asked.add(directory) + return args.listings.namesIn(directory, signal) + } + } + const retirement: SessionSearchRetirement = { + retired: [], + unverifiable: [], + unchecked: [], + degradedRoots: [] + } + const degraded = new Map() + for (const [index, path] of paths.entries()) { + // A synthetic row names a container and an entry inside it, never a file of + // its own; walking the row's own path would report every one of them gone. + const synthetic = splitSyntheticSessionSource(path) + const filePath = synthetic?.container ?? path + // Why capped at all: the sweep hands over every path it holds and did not + // discover, and under an unmount that is the whole index. What is left is + // simply still undiscovered next pass, so the walk finishes over the ones + // that follow rather than holding this one. + // + // Spent past the bound only by a row that starts somewhere new. One this + // walk has already read is answered from the map, so refusing it would buy + // nothing and would leave the budget hostage to whichever directory the + // rows happened to be sorted by. + if (signal?.aborted || (asked.size >= directoryLimit && !asked.has(dirname(filePath)))) { + retirement.unchecked.push(...paths.slice(index)) + break + } + const root = configuredRootFor(filePath, args.roots) + const containerProof = await proveSource(filePath, root ?? dirname(filePath), { + listings, + emptiedRoots, + signal + }) + const proof = synthetic + ? proveSyntheticSource(synthetic, containerProof, args.enumeratedContainers) + : containerProof + if (proof.verdict === 'gone') { + store.removeFile(path) + retirement.retired.push(path) + continue + } + if (proof.verdict === 'present') { + continue + } + retirement.unverifiable.push(path) + // Only a configured root is an alarm worth raising: a row under no root + // this scan walks is already reported on its own, as an orphan. + if (root !== null && !degraded.has(root)) { + degraded.set(root, proof.reason) + } + } + retirement.degradedRoots = [...degraded].map(([root, reason]) => ({ root, reason })) + return retirement +} + +/** + * Walks from the file toward its configured root, asking each directory whether + * the next component toward the file is there. The first directory that answers + * decides; a directory that is itself missing moves the question up one level. + * + * The loop cannot pass the configured root, which is what makes the whole thing + * memoryless: everything above the root — a home directory on an unmounted + * volume, a detached drive, an SSH mount that is not there — is out of scope by + * construction rather than by a state machine that has to remember it. + */ +async function proveSource( + path: string, + root: string, + context: { + listings: SessionSearchDirectoryReader + emptiedRoots: ReadonlySet + signal?: AbortSignal + } +): Promise { + let directory = dirname(path) + let child = basename(path) + while (directory === root || isUnderScanRoot(directory, root)) { + const listing = await context.listings.namesIn(directory, context.signal) + if (!listing.listed) { + if (listing.code !== null && MISSING_DIRECTORY.has(listing.code)) { + const parent = dirname(directory) + if (parent === directory) { + break + } + child = basename(directory) + directory = parent + continue + } + return { verdict: 'unverifiable', reason: listing.message } + } + if (listing.names.has(child)) { + return { verdict: 'present' } + } + if (directory === root && context.emptiedRoots.has(root)) { + // One pass of grace, so a root that blinks empty for a moment — a sync + // client mid-swap, a mount that has not settled — cannot retire a tree. + return { + verdict: 'unverifiable', + reason: 'Listed no transcripts where it listed some on the previous pass.' + } + } + return { verdict: 'gone' } + } + return { verdict: 'unverifiable', reason: `${root} could not be listed.` } +} + +/** + * A synthetic row is proven by its container's own enumeration, one level above + * where the filesystem walk stops. + * + * The container has to be present first: a database on a volume that is not + * there proves nothing about the sessions inside it, and a database that is + * gone takes its sessions with it. Only then does the enumeration decide, and + * only when this pass made one that was exhaustive and successful -- a cycle + * asks for the newest N per agent, so an id it did not return may just be the + * one after them. + */ +function proveSyntheticSource( + synthetic: { container: string; id: string }, + containerProof: SessionSearchSourceVerdict, + enumerated?: ReadonlyMap> +): SessionSearchSourceVerdict { + if (containerProof.verdict !== 'present') { + return containerProof + } + const ids = enumerated?.get(synthetic.container) + // An enumeration that returned nothing at all is not evidence that the + // container holds nothing: a source whose schema this scanner no longer + // recognises reads as empty with no error to see, and believing it would + // retire every entry in one pass. + if (!ids || ids.size === 0) { + return { + verdict: 'unverifiable', + reason: `${synthetic.container} was not enumerated in full this pass.` + } + } + return ids.has(synthetic.id) ? { verdict: 'present' } : { verdict: 'gone' } +} + +/** Longest configured root containing the path, or null for a row under none. */ +function configuredRootFor(path: string, roots: readonly string[]): string | null { + let owner: string | null = null + for (const root of roots) { + if (isUnderScanRoot(path, root) && (owner === null || root.length > owner.length)) { + owner = root + } + } + return owner +} diff --git a/src/main/ai-vault-search/session-search-directory-listings.test.ts b/src/main/ai-vault-search/session-search-directory-listings.test.ts new file mode 100644 index 00000000000..e0143cd7a27 --- /dev/null +++ b/src/main/ai-vault-search/session-search-directory-listings.test.ts @@ -0,0 +1,61 @@ +import { mkdir, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { beforeEach, expect, it, vi } from 'vitest' +import { SessionSearchDirectoryListings } from './session-search-directory-listings' + +const { readdir } = vi.hoisted(() => ({ readdir: vi.fn() })) + +vi.mock('../native-chat/wsl-transcript-fs-access', () => ({ + wslGatedReaddir: readdir +})) + +beforeEach(() => { + readdir.mockReset() +}) + +// A WSL root is a UNC path into the distro, and reading it with raw `fs` is +// what makes a stalled distro look like an empty directory. The gated primitive +// is the same one discovery walks with, so a refusal arrives as an error the +// walk treats as unverifiable rather than as "nothing here". +it('reads through the gated primitive, on the scan lane', async () => { + const unc = '\\\\wsl$\\Ubuntu\\home\\me\\.claude\\projects' + readdir.mockResolvedValueOnce([{ name: 'one.jsonl' }]) + const listings = new SessionSearchDirectoryListings() + + const listing = await listings.namesIn(unc) + + expect(readdir).toHaveBeenCalledWith(unc, 'scan', undefined) + expect(listing).toEqual({ listed: true, names: new Set(['one.jsonl']) }) +}) + +it('reports the code a failed read carried, so ENOENT and EACCES stay apart', async () => { + readdir.mockRejectedValueOnce(Object.assign(new Error('permission denied'), { code: 'EACCES' })) + const listings = new SessionSearchDirectoryListings() + expect(await listings.namesIn('/blocked')).toEqual({ + listed: false, + code: 'EACCES', + message: 'permission denied' + }) +}) + +it('reads a directory once per pass, error or not', async () => { + readdir.mockRejectedValue(Object.assign(new Error('gone'), { code: 'ENOENT' })) + const listings = new SessionSearchDirectoryListings() + await listings.namesIn('/gone') + await listings.namesIn('/gone') + expect(readdir).toHaveBeenCalledTimes(1) + expect(listings.size).toBe(1) +}) + +it('is a real directory read when nothing is mocked out from under it', async () => { + readdir.mockImplementation(async (path: string) => { + const { readdir: real } = await import('node:fs/promises') + return (await real(path, { withFileTypes: true })) as unknown + }) + const root = join(tmpdir(), `ss-listings-${process.pid}`) + await mkdir(root, { recursive: true }) + await writeFile(join(root, 'present.jsonl'), '{}') + const listing = await new SessionSearchDirectoryListings().namesIn(root) + expect(listing.listed && listing.names.has('present.jsonl')).toBe(true) +}) diff --git a/src/main/ai-vault-search/session-search-directory-listings.ts b/src/main/ai-vault-search/session-search-directory-listings.ts new file mode 100644 index 00000000000..f2cb13f9168 --- /dev/null +++ b/src/main/ai-vault-search/session-search-directory-listings.ts @@ -0,0 +1,70 @@ +import { wslGatedReaddir } from '../native-chat/wsl-transcript-fs-access' + +/** One directory read: the names it holds, or what stopped the read. */ +export type SessionSearchDirectoryListing = + | { listed: true; names: ReadonlySet } + | { listed: false; code: string | null; message: string } + +/** + * What the retirement walk needs of a directory: its names, or why not. + * + * An interface rather than the class, so a test can hand the walk an EIO or a + * gate refusal — the shapes a stalled network mount answers with, which no + * temporary directory can be made to produce. + */ +export type SessionSearchDirectoryReader = { + namesIn(directory: string, signal?: AbortSignal): Promise +} + +/** + * Every directory one pass had to read, read once. + * + * The retirement walk asks the same directories about many files — a project + * directory holds hundreds of transcripts — and under an unmount every path + * under a root walks up through the same ancestors. One readdir per directory + * per pass keeps that bounded, and it also makes the pass self-consistent: two + * files in one directory cannot get contradictory verdicts because the + * directory changed between them. + * + * Reads go through the same gated primitive discovery uses, so a WSL UNC path + * is routed to the distro's helper process rather than read with raw fs, and a + * gate refusal arrives as an error rather than as an empty directory. + */ +export class SessionSearchDirectoryListings implements SessionSearchDirectoryReader { + private readonly listings = new Map() + + async namesIn(directory: string, signal?: AbortSignal): Promise { + const cached = this.listings.get(directory) + if (cached) { + return cached + } + const listing = await readDirectory(directory, signal) + this.listings.set(directory, listing) + return listing + } + + /** Directories read this pass; only tests and cost accounting need it. */ + get size(): number { + return this.listings.size + } +} + +async function readDirectory( + directory: string, + signal?: AbortSignal +): Promise { + try { + const entries = await wslGatedReaddir(directory, 'scan', signal) + return { listed: true, names: new Set(entries.map((entry) => entry.name)) } + } catch (error) { + const code = + error && typeof error === 'object' && 'code' in error && typeof error.code === 'string' + ? error.code + : null + return { + listed: false, + code, + message: error instanceof Error ? error.message : String(error) + } + } +} diff --git a/src/main/ai-vault-search/session-search-engine-test-fixture.ts b/src/main/ai-vault-search/session-search-engine-test-fixture.ts new file mode 100644 index 00000000000..694a3d6397f --- /dev/null +++ b/src/main/ai-vault-search/session-search-engine-test-fixture.ts @@ -0,0 +1,113 @@ +import type { TranscriptMessageRole } from '../ai-vault/session-transcript-consumers' +import type SyncDatabase from '../sqlite/sync-database' +import { SessionSearchEngine, type SessionSearchEngineOptions } from './session-search-engine' +import { cwdKey } from './session-search-file-records' +import { identifierShadowText } from './session-search-identifier-split' +import { SessionSearchStore } from './session-search-store' +import { + openSessionSearchIndexFile, + type SessionSearchIndexFile +} from './session-search-index-test-fixture' + +// Synthetic index rows for the query tests. The write path has its own tests; +// driving it here would make every retrieval assertion depend on the parser. + +export type SessionSearchHarness = { + /** The engine's own connection; the store next to it keeps a second, private one. */ + db: SyncDatabase + /** A real writer on the same file, so a test can move the index under the engine. */ + store: SessionSearchStore + engine: SessionSearchEngine + close: () => Promise +} + +export async function openSessionSearchHarness( + name: string, + options: SessionSearchEngineOptions = {} +): Promise { + const index: SessionSearchIndexFile = await openSessionSearchIndexFile(name) + const store = new SessionSearchStore(index.path, (error) => { + throw error + }) + // Constructed before any row is planted, because constructing it is what + // installs the generation triggers the planted rows have to move. + const engine = new SessionSearchEngine(index.db, options) + return { + db: index.db, + store, + engine, + close: async () => { + store.close() + await index.close() + } + } +} + +export type SyntheticSession = { + id: number + cwd?: string | null + text?: string + /** Rows of `text` to write; one session with many rows is one hit. */ + rows?: number + role?: TranscriptMessageRole + /** + * Written into `tool_text` alongside `text`, which is the one row shape the + * conversation scope has to exclude while the `all` scope keeps it. + */ + toolText?: string + agent?: string + updatedAt?: string + messageCount?: number + /** Written into `files`, which is what makes the source `present`. */ + filePath?: string | null + /** `sessions.file_path`: the transcript `path:` searches alongside cwd. */ + sessionFilePath?: string +} + +/** One session and its message rows, in both FTS tables the way the writer does. */ +export function addSyntheticSession(db: SyncDatabase, session: SyntheticSession): void { + const { + id, + cwd = '/repo/app', + text = 'needle', + rows = 1, + role = 'user', + toolText = '', + agent = 'claude', + updatedAt = `2026-09-${String((id % 28) + 1).padStart(2, '0')}T00:00:00.000Z`, + messageCount = rows, + filePath = `/synthetic/${id}.jsonl`, + sessionFilePath = `/synthetic/${id}.jsonl` + } = session + db.prepare( + `INSERT INTO sessions(id,agent,session_id,file_path,title,cwd,cwd_key,updated_at,message_count,resume_command) + VALUES (?,?,?,?,'fixture',?,?,?,?,'resume')` + ).run(id, agent, String(id), sessionFilePath, cwd, cwdKey(cwd), updatedAt, messageCount) + if (filePath !== null) { + db.prepare( + 'INSERT INTO files(path,byte_offset,mtime_ms,session_row_id) VALUES (?,0,1740000000000,?)' + ).run(filePath, id) + } + for (let row = 0; row < rows; row++) { + const messageId = Number( + db + .prepare('INSERT INTO messages(session_row_id,role,ts) VALUES (?,?,?)') + .run(id, role, updatedAt).lastInsertRowid + ) + const user = role === 'user' ? text : '' + const assistant = role === 'assistant' ? text : '' + const tool = role === 'tool' ? `${text} ${toolText}`.trim() : toolText + db.prepare( + 'INSERT INTO messages_fts(rowid,user_text,assistant_text,tool_text,identifiers) VALUES (?,?,?,?,?)' + ).run(messageId, user, assistant, tool, identifierShadowText(`${text} ${toolText}`)) + } +} + +export function markFork(db: SyncDatabase, ids: readonly number[], hash: string): void { + for (const id of ids) { + db.prepare('UPDATE sessions SET content_hash = ?, content_hash_count = 8 WHERE id = ?').run( + hash, + id + ) + } +} diff --git a/src/main/ai-vault-search/session-search-engine-types.ts b/src/main/ai-vault-search/session-search-engine-types.ts new file mode 100644 index 00000000000..055bbe001af --- /dev/null +++ b/src/main/ai-vault-search/session-search-engine-types.ts @@ -0,0 +1,150 @@ +import type { AiVaultAgent } from '../../shared/ai-vault-types' +import type { TranscriptMessageRole } from '../ai-vault/session-transcript-consumers' + +// ENGINE types, deliberately not in src/shared: nothing here is a wire type. +// PR 5 owns the public contract and lifts what a caller may actually receive; +// until then a field can be added, renamed or dropped without a compat story. + +export const SESSION_SEARCH_LIMIT_DEFAULT = 20 +export const SESSION_SEARCH_LIMIT_MAX = 100 +// Longer than this is not a query, and FTS5 pays for every term it plans. +export const SESSION_SEARCH_QUERY_MAX_LENGTH = 512 + +// Snippet match markers. Why doubled: single brackets are everywhere in code +// transcripts (`arr[0]`, regex classes, markdown links) and would read as +// matches; doubled ones are rare. +export const SESSION_SEARCH_SNIPPET_MARK_OPEN = '[[' +export const SESSION_SEARCH_SNIPPET_MARK_CLOSE = ']]' + +/** + * Which corpus answers the query. + * + * - `conversation`: user and assistant turns only, as a column filter over + * `messages_fts` (see `scopedExpression`). + * - `all`: those turns plus tool calls and tool output, and the identifier + * shadow column, from `messages_fts`. + * + * The engine searches exactly the scope it is given. Switching corpus as the + * user types is a UI policy and lives in the panel (PR 7); an engine that + * second-guessed the scope would make a result impossible to reproduce from + * its own request. + */ +export type SessionSearchScope = 'conversation' | 'all' + +export type SessionSearchSort = 'relevance' | 'newest' + +export type SessionSearchFilters = { + agents?: readonly AiVaultAgent[] + /** Only sessions whose cwd is that path or inside it. */ + scopePaths?: readonly string[] + /** ISO timestamp; only sessions updated at or after it. */ + since?: string + sort?: SessionSearchSort +} + +export type SessionSearchRequest = { + query: string + /** Default `all`. */ + scope?: SessionSearchScope + limit?: number + /** From a previous response's `page.cursor`; only valid in its own generation. */ + cursor?: string + filters?: SessionSearchFilters +} + +export type SessionSearchRoute = 'phrase' | 'and' | 'or' | 'typo+phrase' | 'typo+and' | 'typo+or' + +/** + * How the query was executed. Diagnostics, not an answer: PR 5 decides which of + * these a caller ever sees (the reviewer's F5/F7 want them behind `debug`). + */ +export type SessionSearchPlannerReport = { + route: SessionSearchRoute + /** + * The whole body the repaired plan searched, in query order, when any term + * was changed. Not just the corrected terms: a caller rendering "searched + * for" needs the query it actually ran, and a repair never drops a term the + * original kept. A corrected term carries the index's own spelling, which the + * tokenizer has case-folded; untouched terms keep the case they were typed in. + */ + repairedTerms?: string[] + /** The corpus the route ran against; today always the requested scope. */ + tier: SessionSearchScope +} + +/** + * Where a source stands according to the index's own `files` table. The query + * path never stats a transcript, so it can report that the index has a live + * file record for a session or that it has none, and never that a source is + * gone: only a proven deletion may claim `missing`, and proving one is the + * indexer's job (docs/reference/ssh-execution-boundary.md). + */ +export type SessionSearchSourcePresence = 'present' | 'unverifiable' + +export type SessionSearchEvidence = { + role: TranscriptMessageRole + timestamp: string | null + /** FTS5 snippet with the matched terms wrapped in `[[` `]]`. */ + snippet: string + /** The snippet hit the engine's per-hit ceiling and was cut. */ + snippetTruncated?: boolean +} + +export type SessionSearchHit = { + agent: AiVaultAgent + sessionId: string + filePath: string + codexHome: string | null + title: string + cwd: string | null + branch: string | null + updatedAt: string | null + messageCount: number + resumeCommand: string + score: number + /** Sessions folded into this hit (forks sharing an opening prefix); absent when unique. */ + duplicateCount?: number + source: SessionSearchSourcePresence + /** Null when the operators alone put this session on the page, with no text match. */ + evidence: SessionSearchEvidence | null +} + +export type SessionSearchPage = { + /** Null when this page is the last one. */ + cursor: string | null + hasMore: boolean +} + +export type SessionSearchTruncation = { + /** + * Ranking saw only the first `sessionCandidateLimit` sessions, so a session + * past that cut cannot appear on any page of this query. + */ + candidates: boolean + /** Hits on this page whose snippet was cut. */ + snippets: number + /** + * The query itself was cut before it was searched: past the length ceiling, + * or past the number of terms the planner will plan. The terms that survived + * were searched in full, so a hit is still a hit; a miss is not proof of + * absence. + */ + query: boolean +} + +export type SessionSearchResponse = { + hits: SessionSearchHit[] + planner: SessionSearchPlannerReport + page: SessionSearchPage + truncated: SessionSearchTruncation + /** The index snapshot these hits came from; a cursor is only valid within it. */ + generation: number + durationMs: number +} + +export function resolveSessionSearchLimit(limit: number | undefined): number { + // Why clamped here and not at the caller: a non-positive limit becomes + // `slice(0, -1)`, which silently drops the last hit of every page. + const requested = Number.isInteger(limit) ? (limit as number) : SESSION_SEARCH_LIMIT_DEFAULT + return Math.min(Math.max(1, requested), SESSION_SEARCH_LIMIT_MAX) +} diff --git a/src/main/ai-vault-search/session-search-engine.test.ts b/src/main/ai-vault-search/session-search-engine.test.ts new file mode 100644 index 00000000000..6247144d4dc --- /dev/null +++ b/src/main/ai-vault-search/session-search-engine.test.ts @@ -0,0 +1,473 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { SESSION_SEARCH_QUERY_MAX_LENGTH } from './session-search-engine-types' +import type { SessionSearchRequest, SessionSearchResponse } from './session-search-engine-types' +import { planSessionSearchQuery } from './session-search-query-planner' +import { ensureSessionSearchQuerySchema } from './session-search-query-schema' +import { EMPTY_SNIPPET, sessionSearchSnippet } from './session-search-snippet' +import { + addSyntheticSession, + markFork, + openSessionSearchHarness, + type SessionSearchHarness +} from './session-search-engine-test-fixture' + +let harness: SessionSearchHarness | null = null + +afterEach(async () => { + await harness?.close() + harness = null +}) + +async function open(name: string, options = {}): Promise { + harness = await openSessionSearchHarness(name, options) + return harness +} + +function ids(result: SessionSearchResponse): string[] { + return result.hits.map((hit) => hit.sessionId) +} + +describe('the route ladder tries phrase, then AND, then repair, then OR', () => { + async function routeFor( + text: string, + request: SessionSearchRequest + ): Promise { + const { db, engine } = await open('ss-engine-route') + addSyntheticSession(db, { id: 1, text }) + return engine.search(request) + } + + it('takes the phrase route when the tokens are adjacent and in order', async () => { + const result = await routeFor('the alpha beta gamma line', { query: '"alpha beta"' }) + expect(result.planner.route).toBe('phrase') + expect(ids(result)).toEqual(['1']) + }) + + it('falls to AND when the tokens are present but not adjacent', async () => { + const result = await routeFor('beta separated alpha', { query: '"alpha beta"' }) + expect(result.planner.route).toBe('and') + expect(ids(result)).toEqual(['1']) + }) + + it('falls to OR for prose, where no phrase was ever claimed', async () => { + const result = await routeFor('the relay dropped a frame', { query: 'relay frames dropped' }) + expect(result.planner.route).toBe('or') + expect(ids(result)).toEqual(['1']) + }) + + it('repairs a typo before the OR fallback, and says which terms it changed', async () => { + const { db, engine } = await open('ss-engine-typo') + // Two copies: the repair only suggests a term the index really holds. + addSyntheticSession(db, { id: 1, text: 'the coalesces path is slow' }) + addSyntheticSession(db, { id: 2, text: 'coalesces again here' }) + const result = engine.search({ query: 'coalescs' }) + expect(result.planner.route).toBe('typo+or') + expect(result.planner.repairedTerms).toEqual(['coalesces']) + expect(ids(result).sort()).toEqual(['1', '2']) + }) + + it('keeps every term a repaired literal was typed with', async () => { + const { db, engine } = await open('ss-engine-typo-literal') + addSyntheticSession(db, { id: 1, text: 'parseJson the data' }) + addSyntheticSession(db, { id: 2, text: 'parseJson the data again' }) + // `parseJsonn(the, data)` is literal because of its punctuation; the + // corrected spelling read on its own is prose. Re-planning without carrying + // the original decision across would drop `the` and report a body that was + // never typed. + // A corrected term comes back in the index's own spelling, which unicode61 + // has folded; the terms the repair left alone keep the case they were typed. + const result = engine.search({ query: 'parseJsonn(the, data)' }) + expect(result.planner.repairedTerms).toEqual(['parsejson', 'the', 'data']) + }) + + it('does not repair a term the index already holds', async () => { + const { db, engine } = await open('ss-engine-no-typo') + addSyntheticSession(db, { id: 1, text: 'coalesces' }) + const result = engine.search({ query: 'coalesces' }) + expect(result.planner.repairedTerms).toBeUndefined() + expect(result.planner.route).toBe('or') + }) + + it('reports the scope it searched as the planner tier', async () => { + const { db, engine } = await open('ss-engine-tier') + addSyntheticSession(db, { id: 1, text: 'needle' }) + expect(engine.search({ query: 'needle' }).planner.tier).toBe('all') + expect(engine.search({ query: 'needle', scope: 'conversation' }).planner.tier).toBe( + 'conversation' + ) + }) +}) + +describe('scope picks the corpus and never switches it', () => { + async function corpus(): Promise { + const opened = await open('ss-engine-scope') + addSyntheticSession(opened.db, { id: 1, text: 'harbor pilot manifest', role: 'user' }) + addSyntheticSession(opened.db, { id: 2, text: 'harbor tool output line', role: 'tool' }) + return opened + } + + it('searches conversation turns only under `conversation`', async () => { + const { engine } = await corpus() + expect(ids(engine.search({ query: 'harbor', scope: 'conversation' }))).toEqual(['1']) + }) + + it('includes tool output under `all`, which is the default', async () => { + const { engine } = await corpus() + expect(ids(engine.search({ query: 'harbor', scope: 'all' })).sort()).toEqual(['1', '2']) + expect(ids(engine.search({ query: 'harbor' })).sort()).toEqual(['1', '2']) + }) + + it('returns nothing rather than widening when the narrow scope misses', async () => { + // The panel's two-tier typing is a UI policy (PR 7). An engine that widened + // here would make a result impossible to reproduce from its own request. + const { engine } = await corpus() + const result = engine.search({ query: 'output', scope: 'conversation' }) + expect(result.hits).toEqual([]) + expect(result.planner.tier).toBe('conversation') + }) + + it('matches an identifier through its pieces only in the full corpus', async () => { + const { db, engine } = await open('ss-engine-identifiers') + addSyntheticSession(db, { id: 1, text: 'resolveTerminalPath' }) + // The identifier shadow column lives in messages_fts alone. + expect(ids(engine.search({ query: 'terminal path' }))).toEqual(['1']) + expect(engine.search({ query: 'terminal path', scope: 'conversation' }).hits).toEqual([]) + }) +}) + +describe('the conversation scope is a column filter, and it binds the whole query', () => { + it('refuses an AND whose second term lives only in tool output', async () => { + // The filter binds to the expression it prefixes. `{cols}: (a AND b)` + // filters both terms; `{cols}: a AND b` filters only `a` and searches tool + // output for the rest, which is a conversation search answering from a + // column it promised not to read. + const { db, engine } = await open('ss-engine-scope-binding') + addSyntheticSession(db, { id: 1, text: 'alpha gamma beta' }) + addSyntheticSession(db, { id: 2, text: 'alpha gamma', toolText: 'beta' }) + // Quoted, so the query is literal; not adjacent, so the phrase rung misses + // and the AND rung is the one that answers. + const query = '"alpha" beta' + + const wide = engine.search({ query, scope: 'all' }) + expect(wide.planner.route).toBe('and') + expect(ids(wide).sort()).toEqual(['1', '2']) + + const narrowed = engine.search({ query, scope: 'conversation' }) + expect(narrowed.planner.route).toBe('and') + expect(ids(narrowed)).toEqual(['1']) + }) + + it('ranks a conversation hit down for tool output it will not show', async () => { + // The one behavioural difference the column filter carries, pinned rather + // than wished away. FTS5's bm25 normalises by the whole row's length and + // has no per-column length, so two rows with identical prose do not score + // identically when one of them also holds tool output. A dedicated + // two-column table scored them the same. The rowid set is unchanged, which + // is what the decision was measured on; the order within it can move. + const { db, engine } = await open('ss-engine-scope-weights') + addSyntheticSession(db, { id: 1, text: 'harbor pilot' }) + addSyntheticSession(db, { id: 2, text: 'harbor pilot', toolText: 'unrelated '.repeat(40) }) + const narrowed = engine.search({ query: 'harbor', scope: 'conversation' }) + expect(ids(narrowed)).toEqual(['1', '2']) + expect(narrowed.hits[0]!.score).toBeGreaterThan(narrowed.hits[1]!.score) + }) + + it('never snippets a conversation hit out of tool output', async () => { + const { db, engine } = await open('ss-engine-scope-snippet') + addSyntheticSession(db, { id: 1, text: 'harbor pilot', toolText: 'harbor tool output line' }) + const [hit] = engine.search({ query: 'harbor', scope: 'conversation' }).hits + expect(hit?.evidence?.snippet).toContain('pilot') + expect(hit?.evidence?.snippet).not.toContain('output') + // And asked for a tool-only row directly, it has nothing to show. + addSyntheticSession(db, { id: 2, text: 'harbor tool output line', role: 'tool' }) + const rowid = Number( + (db.prepare('SELECT max(id) AS id FROM messages').get() as { id: number }).id + ) + const plan = planSessionSearchQuery('harbor') + expect(sessionSearchSnippet(db, 'conversation', rowid, plan)).toEqual(EMPTY_SNIPPET) + expect(sessionSearchSnippet(db, 'all', rowid, plan).text).toContain('output') + }) +}) + +describe('a session is one hit, however many of its rows matched', () => { + it.each(['relevance', 'newest'] as const)( + 'keeps a short session on the %s page beside a 650-row session', + async (sort) => { + const { db, engine } = await open('ss-engine-aggregate', { sessionCandidateLimit: 600 }) + addSyntheticSession(db, { id: 1, rows: 650, updatedAt: '2026-09-06T00:00:00.000Z' }) + addSyntheticSession(db, { + id: 2, + text: 'needle padding', + updatedAt: '2026-09-05T00:00:00.000Z' + }) + // Collapsing to one row per session happens before the candidate limit, + // so the 650-row session cannot crowd the one-row session off the page on + // either order; which of them ranks first is the sort's business. + expect(ids(engine.search({ query: 'needle', filters: { sort } })).sort()).toEqual(['1', '2']) + } + ) + + it('folds forks the same way for an operator-only page as for a text page', async () => { + const { db, engine } = await open('ss-engine-forks') + for (const id of [1, 2, 3, 4]) { + addSyntheticSession(db, { id, updatedAt: `2026-09-0${id}T00:00:00.000Z` }) + } + markFork(db, [1, 2, 3, 4], 'shared-fork-prefix') + const operatorOnly = engine.search({ query: 'repo:app' }) + const withText = engine.search({ query: 'needle repo:app' }) + expect(ids(operatorOnly)).toEqual(['4']) + expect(operatorOnly.hits[0]?.duplicateCount).toBe(4) + expect(ids(withText)).toEqual(ids(operatorOnly)) + expect(withText.hits[0]?.duplicateCount).toBe(4) + }) + + it('answers an operator-only query with the newest sessions and no evidence', async () => { + const { db, engine } = await open('ss-engine-operator-only') + addSyntheticSession(db, { id: 1, updatedAt: '2026-09-01T00:00:00.000Z' }) + addSyntheticSession(db, { id: 2, updatedAt: '2026-09-09T00:00:00.000Z' }) + const result = engine.search({ query: 'repo:app' }) + expect(ids(result)).toEqual(['2', '1']) + expect(result.hits[0]?.evidence).toBeNull() + }) + + it('has no hits for a query with neither text nor operators', async () => { + const { db, engine } = await open('ss-engine-empty') + addSyntheticSession(db, { id: 1 }) + expect(engine.search({ query: ' ' }).hits).toEqual([]) + }) +}) + +describe('filters narrow retrieval, not just the page', () => { + it('finds a scoped match behind 600 out-of-scope rows', async () => { + const { db, engine } = await open('ss-engine-scoped') + addSyntheticSession(db, { id: 1, cwd: '/unrelated', rows: 600 }) + addSyntheticSession(db, { id: 2, cwd: '/target', text: 'needle padding' }) + expect(ids(engine.search({ query: 'needle', filters: { scopePaths: ['/target'] } }))).toEqual([ + '2' + ]) + }) + + it('falls back to a later rung when the exact hit is out of scope', async () => { + const { db, engine } = await open('ss-engine-scoped-route') + addSyntheticSession(db, { id: 1, cwd: '/unrelated', text: 'resolveTerminalPath' }) + addSyntheticSession(db, { id: 2, cwd: '/target', text: 'resolve terminal path' }) + expect( + ids(engine.search({ query: 'resolveTerminalPath', filters: { scopePaths: ['/target'] } })) + ).toEqual(['2']) + }) +}) + +describe('evidence', () => { + it('takes each snippet from that hit’s own best message', async () => { + const { db, engine } = await open('ss-engine-snippet') + // Written first, so its row owns the lowest rowid: the row a dropped rowid + // constraint would hand back for every hit. + addSyntheticSession(db, { + id: 1, + text: 'hydration marmoset appears once in a long paragraph about routing and caching', + updatedAt: '2026-09-01T00:00:00.000Z' + }) + addSyntheticSession(db, { + id: 2, + text: 'hydration capybara', + updatedAt: '2026-09-09T00:00:00.000Z' + }) + const hits = engine.search({ query: 'hydration' }).hits + expect(hits[0]?.evidence?.snippet).toContain('capybara') + expect(hits[0]?.evidence?.snippet).not.toContain('marmoset') + expect(hits.find((hit) => hit.sessionId === '1')?.evidence?.snippet).toContain('marmoset') + }) + + it('shows the prose column rather than the identifier shadow when both match', async () => { + const { db, engine } = await open('ss-engine-snippet-shadow') + addSyntheticSession(db, { + id: 1, + text: 'resolveTerminalPath is broken and the terminal never comes up for a pane, which is odd because every other pane on this host resolves its path' + }) + const snippet = engine.search({ query: 'terminal path' }).hits[0]?.evidence?.snippet ?? '' + expect(snippet).toContain('[[') + expect(snippet).not.toContain('resolve [[terminal]] [[path]]') + }) + + it('flags a snippet it had to cut, and counts it on the result', async () => { + const { db, engine } = await open('ss-engine-snippet-truncated') + // The window is twelve tokens wide, and one of them is 4000 characters, so + // the token count is no bound at all on what a hit carries. + addSyntheticSession(db, { id: 1, text: `needle ${'x'.repeat(4000)}` }) + const result = engine.search({ query: 'needle' }) + expect(result.hits[0]?.evidence?.snippetTruncated).toBe(true) + expect(result.hits[0]?.evidence?.snippet.length).toBeLessThan(600) + expect(result.truncated.snippets).toBe(1) + }) + + it('leaves an ordinary snippet unflagged', async () => { + const { db, engine } = await open('ss-engine-snippet-whole') + addSyntheticSession(db, { id: 1, text: 'needle in a short line' }) + const result = engine.search({ query: 'needle' }) + expect(result.hits[0]?.evidence?.snippetTruncated).toBeUndefined() + expect(result.truncated.snippets).toBe(0) + }) +}) + +describe('source presence comes from the files table, never a stat', () => { + it('calls a session with a live file record present', async () => { + const { db, engine } = await open('ss-engine-presence') + addSyntheticSession(db, { id: 1 }) + expect(engine.search({ query: 'needle' }).hits[0]?.source).toBe('present') + }) + + it('calls a session with no file record unverifiable, and still returns it', async () => { + // Loss of contact is never evidence of absence: the hit stays on the page. + const { db, engine } = await open('ss-engine-presence-unknown') + addSyntheticSession(db, { id: 1, filePath: null }) + const hits = engine.search({ query: 'needle' }).hits + expect(hits).toHaveLength(1) + expect(hits[0]?.source).toBe('unverifiable') + }) +}) + +describe('the engine carries its own schema and puts it back', () => { + it('installs the vocabulary over an index a writer built alone', async () => { + // The store creates none of these: PR 3's indexer can fill a whole index + // before anything opens an engine over it. + const { db, engine } = await open('ss-engine-installs') + addSyntheticSession(db, { id: 1, text: 'the coalesces path is slow' }) + addSyntheticSession(db, { id: 2, text: 'coalesces again here' }) + const result = engine.search({ query: 'coalescs' }) + expect(result.planner.route).toBe('typo+or') + expect(ids(result).sort()).toEqual(['1', '2']) + }) + + it('re-creates a vocabulary that vanished under a live engine', async () => { + const { db, engine } = await open('ss-engine-vocab-vanishes') + addSyntheticSession(db, { id: 1, text: 'coalesces here now' }) + addSyntheticSession(db, { id: 2, text: 'coalesces again here' }) + expect(engine.search({ query: 'coalescs' }).planner.route).toBe('typo+or') + + db.exec('DROP TABLE messages_vocab') + const after = engine.search({ query: 'coalescs' }) + expect(after.planner.route).toBe('typo+or') + }) + + it('fails clearly when the source index is missing', async () => { + const { db, engine } = await open('ss-engine-vocab-source-gone') + addSyntheticSession(db, { id: 1, text: 'coalesces here now', role: 'user' }) + db.exec('DROP TABLE messages_vocab; DROP TABLE messages_fts') + + expect(() => ensureSessionSearchQuerySchema(db)).toThrow('missing messages_fts') + for (const scope of ['all', 'conversation'] as const) { + expect(() => engine.search({ query: 'coalesces', scope })).toThrow(/missing messages_fts/i) + } + }) + + it('answers again after the source index is restored', async () => { + const { db, engine } = await open('ss-engine-vocab-returns') + addSyntheticSession(db, { id: 1, text: 'coalesces here now' }) + addSyntheticSession(db, { id: 2, text: 'coalesces again here' }) + const fts = ( + db.prepare("SELECT sql FROM sqlite_master WHERE name = 'messages_fts'").get() as { + sql: string + } + ).sql + db.exec('DROP TABLE messages_vocab; DROP TABLE messages_fts') + expect(() => ensureSessionSearchQuerySchema(db)).toThrow('missing messages_fts') + + db.exec(fts) + // Two, because the vocabulary only offers a term at least two rows carry. + addSyntheticSession(db, { id: 3, text: 'coalesces one more time' }) + addSyntheticSession(db, { id: 4, text: 'coalesces once again' }) + // Nothing throws on the way back up, so the recovery cannot come from the + // error path; it comes from the probe running per search. + const restored = engine.search({ query: 'coalescs' }) + expect(restored.planner.route).toBe('typo+or') + }) +}) + +describe('a query the engine had to cut says so', () => { + it('answers a query whose cap falls inside an astral character', async () => { + // The cut is on a whole code point rather than a code unit, so nothing + // downstream is handed half a surrogate pair. That is hygiene rather than a + // behaviour: the planner's tokenizer does not treat a lone surrogate as a + // token character, so it drops out of the terms either way. What this pins + // is that the boundary is answerable at all. + const { db, engine } = await open('ss-engine-surrogate-cap') + const kept = 'x'.repeat(SESSION_SEARCH_QUERY_MAX_LENGTH - 2) + addSyntheticSession(db, { id: 1, text: kept }) + const result = engine.search({ query: `${kept} 😀 tail` }) + expect(result.truncated.query).toBe(true) + expect(result.hits.map((hit) => hit.sessionId)).toEqual(['1']) + }) + + it('loads a candidate set larger than one batch of bound ids', async () => { + // The id list is as long as the candidate limit and every id is a bound + // parameter. No SQLite this stack can run refuses 1,100 of them, so this + // pins that batching returns the same answer, not that it rescues one. + const { db, engine } = await open('ss-engine-id-batching', { + sessionCandidateLimit: 1200 + }) + for (let id = 1; id <= 1100; id++) { + addSyntheticSession(db, { id, text: 'needle' }) + } + const result = engine.search({ query: 'needle', limit: 5 }) + expect(result.hits).toHaveLength(5) + expect(result.truncated.candidates).toBe(false) + }) + + it('reports truncation when the planner drops terms past its cap', async () => { + // The 56th term is the only one that matches. Without the flag this is a + // confident empty answer to a query the engine never finished reading. + const { db, engine } = await open('ss-engine-term-cap') + addSyntheticSession(db, { id: 1, text: 'onlyattheend' }) + const query = `${Array.from({ length: 55 }, (_unused, n) => `term${n}`).join(' ')} onlyattheend` + const result = engine.search({ query }) + expect(result.hits).toEqual([]) + expect(result.truncated.query).toBe(true) + }) + + it('reports truncation when the query is longer than the engine will plan', async () => { + const { db, engine } = await open('ss-engine-length-cap') + addSyntheticSession(db, { id: 1, text: 'needle' }) + const result = engine.search({ query: `needle ${'x'.repeat(SESSION_SEARCH_QUERY_MAX_LENGTH)}` }) + expect(result.truncated.query).toBe(true) + }) + + it('claims no truncation for a query that fit', async () => { + const { db, engine } = await open('ss-engine-no-cap') + addSyntheticSession(db, { id: 1, text: 'needle' }) + expect(engine.search({ query: 'needle' }).truncated.query).toBe(false) + }) +}) + +describe('a query longer than the engine will plan is cut, not refused', () => { + it('cuts one enormous token down to the cap before FTS5 ever sees it', async () => { + const { db, engine } = await open('ss-engine-long-query') + // The planner already caps how many terms it will plan, so a long query of + // ordinary words is bounded without this. What is not bounded is a single + // token: one 100 kB word is one term, and FTS5 would carry the whole thing + // into the MATCH expression. The cut is observable because the indexed + // token is exactly the capped length. + addSyntheticSession(db, { id: 1, text: 'x'.repeat(SESSION_SEARCH_QUERY_MAX_LENGTH) }) + expect(ids(engine.search({ query: 'x'.repeat(4000) }))).toEqual(['1']) + }) +}) + +describe('unicode terms survive the round trip', () => { + it.each(['café', 'C', 'R', 'x', '修復', '안녕하세요'])('searches %s', async (text) => { + const { db, engine } = await open('ss-engine-unicode') + addSyntheticSession(db, { id: 1, text }) + expect(engine.search({ query: text }).hits).toHaveLength(1) + }) +}) + +it.each(['repo:target', 'path:/work/target'])( + 'applies %s before selecting a route', + async (operator) => { + const { db, engine } = await open('ss-route-filter') + addSyntheticSession(db, { id: 1, cwd: '/work/other', text: 'alpha beta' }) + addSyntheticSession(db, { id: 2, cwd: '/work/target', text: 'alpha x beta' }) + const result = engine.search({ query: `"alpha beta" ${operator}` }) + expect(ids(result)).toEqual(['2']) + expect(result.planner.route).toBe('and') + expect(result.truncated.candidates).toBe(false) + } +) diff --git a/src/main/ai-vault-search/session-search-engine.ts b/src/main/ai-vault-search/session-search-engine.ts new file mode 100644 index 00000000000..ac7ddf9a3da --- /dev/null +++ b/src/main/ai-vault-search/session-search-engine.ts @@ -0,0 +1,259 @@ +import type SyncDatabase from '../sqlite/sync-database' +import type { TranscriptMessageRole } from '../ai-vault/session-transcript-consumers' +import { sliceAtCodeUnitLimit } from '../ai-vault/session-scanner-text-normalization' +import { + hasAiVaultSearchQueryOperators, + splitAiVaultSearchQuery, + type AiVaultSearchQuerySplit +} from '../../shared/ai-vault-search-query-operators' +import { matchesAiVaultQueryOperators } from '../../shared/ai-vault-session-filters' +import { + resolveSessionSearchLimit, + SESSION_SEARCH_QUERY_MAX_LENGTH, + type SessionSearchHit, + type SessionSearchRequest, + type SessionSearchResponse, + type SessionSearchScope, + type SessionSearchSourcePresence +} from './session-search-engine-types' +import { readIndexGeneration } from './session-search-index-generation' +import { + rankSessionHits, + type MessageRow, + type RankedSession, + type SessionRow +} from './session-search-hit-ranking' +import { + SessionSearchCursorError, + decodeSessionSearchCursor, + encodeSessionSearchCursor, + sessionSearchPageKey +} from './session-search-page-cursor' +import { planSessionSearchQuery } from './session-search-query-planner' +import { + SessionSearchRetrieval, + type RetrievalScope, + type Retrieved +} from './session-search-retrieval' +import { sessionRowFilter } from './session-search-row-filter' +import { ensureSessionSearchQuerySchema } from './session-search-query-schema' +import { EMPTY_SNIPPET, sessionSearchSnippet } from './session-search-snippet' +import { sessionSourcePresence } from './session-search-source-presence' + +/** + * Sessions retrieved before ranking cuts the page. + * + * Not a fixed constant (the reviewer's F13): it is the knob that trades page + * completeness for retrieval cost, and the right value depends on index size. + * Measurements behind this default, and what changing it costs, are in + * docs/reference/agent-session-search-query-tuning.md. + */ +export const SESSION_SEARCH_CANDIDATE_LIMIT_DEFAULT = 600 + +/** One ranked list plus what produced it; a page is a slice of `ranked`. */ +type RankedPage = { + ranked: RankedSession[] + /** Null when no text was searched, so there is nothing to snippet from. */ + retrieved: Retrieved | null + /** + * Retrieval may have missed a session: a cap ended it, not the data. True + * whether the candidate limit filled or the operator walk gave up scanning. + */ + incomplete: boolean +} + +export type SessionSearchEngineOptions = { + sessionCandidateLimit?: number + /** Oldest transcript mtime a hit may come from; PR 3 derives it from retention. */ + retentionCutoffMs?: number | null +} + +/** + * Synchronous searches use independent statements to avoid pinning the WAL. + * Generation checks bracket all content reads; concurrent writes reject the page. + * The connection's owner handles index rebuilds and engine reconstruction. + */ +export class SessionSearchEngine { + private readonly retrieval: SessionSearchRetrieval + private readonly candidateLimit: number + + constructor( + private readonly db: SyncDatabase, + private readonly options: SessionSearchEngineOptions = {} + ) { + this.candidateLimit = options.sessionCandidateLimit ?? SESSION_SEARCH_CANDIDATE_LIMIT_DEFAULT + // Installed here and not on the first search, so the generation triggers are + // watching before anything this engine will be asked to page over is + // written, and so retrieval below prepares against tables that exist. + ensureSessionSearchQuerySchema(this.db) + this.retrieval = new SessionSearchRetrieval(this.db) + } + + search(request: SessionSearchRequest): SessionSearchResponse { + const startedAt = performance.now() + ensureSessionSearchQuerySchema(this.db) + const generation = readIndexGeneration(this.db) + const scope = request.scope ?? 'all' + const sort = request.filters?.sort ?? 'relevance' + // Not a bare `slice`: cutting between a surrogate pair leaves a lone half + // that no tokenizer can match and that a caller cannot echo back. + const capped = sliceAtCodeUnitLimit(request.query, SESSION_SEARCH_QUERY_MAX_LENGTH) + const split = splitAiVaultSearchQuery(capped) + const retrievalScope: RetrievalScope = { + scope, + sort, + filter: sessionRowFilter(request.filters ?? {}, this.options.retentionCutoffMs ?? null), + matchesOperators: operatorPredicate(split), + candidateLimit: this.candidateLimit + } + // Decoded before any retrieval: a cursor the engine will refuse must not + // cost a query, and the caller has to hear about it either way. + const pageKey = sessionSearchPageKey(request) + const offset = request.cursor + ? decodeSessionSearchCursor(request.cursor, generation, pageKey) + : 0 + + const plan = planSessionSearchQuery(split.text) + const { ranked, retrieved, incomplete } = + plan.terms.length === 0 + ? this.operatorOnly(split, retrievalScope) + : this.text(plan, retrievalScope, sort) + + const limit = resolveSessionSearchLimit(request.limit) + const page = ranked.slice(offset, offset + limit) + const hits = this.hits(page, scope, retrieved) + const actualGeneration = readIndexGeneration(this.db) + if (actualGeneration !== generation) { + throw new SessionSearchCursorError('stale-generation', actualGeneration, generation) + } + const hasMore = ranked.length > offset + limit + const response: SessionSearchResponse = { + hits, + planner: { + route: retrieved?.route ?? 'or', + tier: scope, + ...(retrieved?.repairedTerms ? { repairedTerms: retrieved.repairedTerms } : {}) + }, + page: { + hasMore, + cursor: hasMore ? encodeSessionSearchCursor(generation, offset + limit, pageKey) : null + }, + truncated: { + // Decided by retrieval, which is the only layer that knows whether a cap + // ended it. Deriving it from the hits cannot work: an operator walk that + // gave up at its scan ceiling returns no hits, and so does a search that + // genuinely matched nothing. + candidates: incomplete, + snippets: hits.filter((hit) => hit.evidence?.snippetTruncated).length, + query: capped.length < request.query.length || plan.truncated + }, + generation, + durationMs: performance.now() - startedAt + } + return response + } + + /** + * Operators with no free text still name a scope, so the answer is the newest + * sessions inside it. Ranked through the same path as a text query, because + * forks must fold here exactly as they do there or the same sessions answer + * `repo:x` and `word repo:x` differently. There is no relevance signal + * without text, so the order is always newest. + */ + private operatorOnly(split: AiVaultSearchQuerySplit, scope: RetrievalScope): RankedPage { + if (!hasAiVaultSearchQueryOperators(split)) { + return { ranked: [], retrieved: null, incomplete: false } + } + const { sessions, incomplete } = this.retrieval.recent(scope) + return { ranked: rankSessionHits(sessions, new Map(), 'newest'), retrieved: null, incomplete } + } + + private text( + plan: ReturnType, + scope: RetrievalScope, + sort: 'relevance' | 'newest' + ): RankedPage { + const retrieved = this.retrieval.run(plan, scope) + // `match` already grouped to one best row per session. + const best = new Map(retrieved.rows.map((row) => [row.session_row_id, row])) + return { + ranked: rankSessionHits(retrieved.sessions, best, sort), + retrieved, + incomplete: retrieved.incomplete + } + } + + /** Snippets and source presence are paid for by the page, never by the list. */ + private hits( + page: readonly RankedSession[], + scope: SessionSearchScope, + retrieved: Retrieved | null + ): SessionSearchHit[] { + const presence = sessionSourcePresence( + this.db, + page.map((entry) => entry.session.id) + ) + return page.map((entry) => this.hit(entry, scope, retrieved, presence)) + } + + private hit( + entry: RankedSession, + scope: SessionSearchScope, + retrieved: Retrieved | null, + presence: ReadonlyMap + ): SessionSearchHit { + const { session, message } = entry + const snippet = + message && retrieved + ? sessionSearchSnippet(this.db, scope, message.rowid, retrieved.plan) + : EMPTY_SNIPPET + return { + ...sessionFields(session), + score: entry.score, + ...(entry.duplicateCount > 1 ? { duplicateCount: entry.duplicateCount } : {}), + source: presence.get(session.id) ?? 'unverifiable', + evidence: message + ? { + role: message.role as TranscriptMessageRole, + timestamp: message.ts, + snippet: snippet.text, + ...(snippet.truncated ? { snippetTruncated: true } : {}) + } + : null + } + } +} + +/** + * The one reading of `repo:` / `path:`: the sessions panel's own predicate, over + * the columns the index stores. The engine has no project map, so a session's + * repo label falls back to its folder label, which is what the panel does for + * every session it cannot resolve a project for. + */ +function operatorPredicate(split: AiVaultSearchQuerySplit): (session: SessionRow) => boolean { + if (!hasAiVaultSearchQueryOperators(split)) { + return () => true + } + return (session) => + matchesAiVaultQueryOperators( + { cwd: session.cwd, filePath: session.file_path }, + { repoTerms: split.repoTerms, pathTerms: split.pathTerms } + ) +} + +function sessionFields( + session: SessionRow +): Omit { + return { + agent: session.agent, + sessionId: session.session_id, + filePath: session.file_path, + codexHome: session.codex_home, + title: session.title, + cwd: session.cwd, + branch: session.branch, + updatedAt: session.updated_at, + messageCount: session.message_count, + resumeCommand: session.resume_command + } +} diff --git a/src/main/ai-vault-search/session-search-file-cursor.ts b/src/main/ai-vault-search/session-search-file-cursor.ts new file mode 100644 index 00000000000..2ba978b00ae --- /dev/null +++ b/src/main/ai-vault-search/session-search-file-cursor.ts @@ -0,0 +1,41 @@ +import type { FileWithMtime } from '../ai-vault/session-scanner-types' + +// Why the index keeps its own cursor: the parse cache's cursor answers "what +// does the session list already show", which is a different question from "what +// bytes of this file are already rows". They diverge the moment either side +// declines a read, so neither may consult the other. + +/** Filesystem identity, when discovery could prove it. */ +export type SessionSearchFileIdentity = { dev: number; ino: number } | null + +/** + * What the index holds for one transcript. + * + * A null `byteOffset` is a file the index holds rows for and cannot continue: + * a chunked read committed a prefix, and the reader only hands out an offset + * when a read finishes. Null rather than a flag because every caller that does + * arithmetic on the offset then has to say what it means here, at compile time, + * instead of ignoring a boolean it did not know to read. + */ +export type SessionSearchIndexedFile = { + byteOffset: number | null + mtimeMs: number + sizeBytes: number | null +} + +/** + * Whether this file has to be read from the start, whatever its stat says. + * + * The mtime and size are the real ones, so a freshness check that compares only + * those would call a half-written file current and never re-read it. Every such + * check must start here. + */ +export function requiresWholeRead(indexed: SessionSearchIndexedFile | null): boolean { + return indexed !== null && indexed.byteOffset === null +} + +export function fileIdentity(file: FileWithMtime): SessionSearchFileIdentity { + return typeof file.dev === 'number' && typeof file.ino === 'number' + ? { dev: file.dev, ino: file.ino } + : null +} diff --git a/src/main/ai-vault-search/session-search-file-records.ts b/src/main/ai-vault-search/session-search-file-records.ts new file mode 100644 index 00000000000..2ee79cbdc13 --- /dev/null +++ b/src/main/ai-vault-search/session-search-file-records.ts @@ -0,0 +1,134 @@ +import { fileIdentity } from './session-search-file-cursor' +import type { AiVaultSession } from '../../shared/ai-vault-types' +import type { TranscriptSessionIdentity } from '../ai-vault/session-transcript-consumers' +import type { SessionFileCandidate } from '../ai-vault/session-scanner-types' +import type SyncDatabase from '../sqlite/sync-database' +import { EMPTY_CONTENT_HASH, type SessionContentHash } from './session-search-content-hash' +import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-path' + +/** + * The stored comparison key for a session's working directory. + * + * Why the shared normalizer verbatim: the sidebar already groups sessions by + * `folderGroupKey`, which is this function under a prefix. A second spelling + * here means any later join between an indexed hit and a sidebar group returns + * nothing. An earlier version qualified a WSL cwd with its distro so two + * distros could not collide at `/home/me/repo`; that is a real collision, but it + * is one every SSH host has too, neither key qualifies for SSH, and the fix for + * it is a column that names the execution host, not a path key that only some + * hosts spell differently. + */ +export function cwdKey(cwd: string | null): string | null { + return cwd ? normalizeRuntimePathForComparison(cwd) : null +} + +export class SessionSearchFileRecords { + constructor(private readonly db: SyncDatabase) {} + /** + * The row a read hangs its messages off, before the parser has said what the + * session is. The same transaction fills it in: from the decoded session when + * the read finished, and from `updateProvisionalSession` when this is a chunk + * of one that has not. + */ + createSessionRow(candidate: SessionFileCandidate): number { + return Number( + this.db + .prepare( + `INSERT INTO sessions(agent,session_id,file_path,title,resume_command) + VALUES (?,'',?,'','')` + ) + .run(candidate.agent, candidate.file.path).lastInsertRowid + ) + } + + /** + * Writes what the parser knows so far onto a session a chunk is committing. + * + * Rows a chunk commits answer searches the moment they land, so the session + * they hang off has to be nameable before the read producing it ends — and it + * may never end, because a crash between chunks leaves exactly this row. That + * is why the identity is required rather than optional: a read that has none + * does not chunk at all. The final commit overwrites all of it from the + * decoded session; until then the title in particular is provisional. + */ + updateProvisionalSession(rowId: number, identity: TranscriptSessionIdentity): void { + this.db + .prepare( + `UPDATE sessions SET session_id = ?, title = ?, cwd = ?, cwd_key = ?, + created_at = ?, updated_at = ? WHERE id = ?` + ) + .run( + identity.sessionId, + identity.title ?? '', + identity.cwd, + cwdKey(identity.cwd), + identity.createdAt, + identity.updatedAt, + rowId + ) + } + + contentHash(rowId: number): SessionContentHash { + const row = this.db + .prepare('SELECT content_hash, content_hash_count FROM sessions WHERE id = ?') + .get(rowId) as { content_hash: string | null; content_hash_count: number } | undefined + return row ? { hash: row.content_hash, count: row.content_hash_count } : EMPTY_CONTENT_HASH + } + + updateSession(session: AiVaultSession, rowId: number, contentHash: SessionContentHash): void { + const values = [ + session.agent, + session.sessionId, + session.filePath, + session.codexHome, + session.title, + session.cwd, + cwdKey(session.cwd), + session.branch, + session.createdAt, + session.updatedAt, + session.messageCount, + session.resumeCommand, + contentHash.hash, + contentHash.count + ] + this.db + .prepare( + `UPDATE sessions SET agent = ?, session_id = ?, file_path = ?, codex_home = ?, title = ?, + cwd = ?, cwd_key = ?, branch = ?, created_at = ?, updated_at = ?, message_count = ?, resume_command = ?, + content_hash = ?, content_hash_count = ? WHERE id = ?` + ) + .run(...values, rowId) + } + + upsertFile( + candidate: SessionFileCandidate, + byteOffset: number, + sessionRowId: number | null + ): void { + const { file } = candidate + const identity = fileIdentity(file) + this.db + .prepare( + `INSERT INTO files(path, dev, ino, byte_offset, mtime_ms, size_bytes, session_row_id) + VALUES (?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(path) DO UPDATE SET + -- Partial observations must never create a pair that no stat proved. + dev = CASE WHEN excluded.dev IS NOT NULL AND excluded.ino IS NOT NULL + THEN excluded.dev ELSE files.dev END, + ino = CASE WHEN excluded.dev IS NOT NULL AND excluded.ino IS NOT NULL + THEN excluded.ino ELSE files.ino END, + byte_offset = excluded.byte_offset, mtime_ms = excluded.mtime_ms, + size_bytes = excluded.size_bytes, session_row_id = excluded.session_row_id` + ) + .run( + file.path, + identity?.dev ?? null, + identity?.ino ?? null, + byteOffset, + file.mtimeMs, + file.sizeBytes ?? null, + sessionRowId + ) + } +} diff --git a/src/main/ai-vault-search/session-search-file-write.test.ts b/src/main/ai-vault-search/session-search-file-write.test.ts new file mode 100644 index 00000000000..2c0be88b026 --- /dev/null +++ b/src/main/ai-vault-search/session-search-file-write.test.ts @@ -0,0 +1,623 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { resetTranscriptConsumersForTests } from '../ai-vault/session-transcript-consumers' +import SyncDatabase from '../sqlite/sync-database' +import { registerSessionSearchIndexConsumer } from './session-search-index-consumer' +import { cwdKey } from './session-search-file-records' +import { requiresWholeRead } from './session-search-file-cursor' +import { SessionSearchIndexWriter } from './session-search-index-writer' +import { deleteExpiredSearchFiles } from './session-search-retention-delete' +import { + openSessionSearchIndexFile, + replayTranscriptRead, + syntheticCandidate, + syntheticSession, + SYNTHETIC_TRANSCRIPT, + userMessages, + type SessionSearchIndexFile +} from './session-search-index-test-fixture' +import { SessionSearchStore } from './session-search-store' + +// Every assertion here reads through `index.db`, a second connection to the same +// file. That is the whole consistency model: one transaction per file in WAL +// mode, so another handle sees the last committed state and never a session part +// way through being rewritten. + +let index: SessionSearchIndexFile +let store: SessionSearchStore +let errors: unknown[] + +beforeEach(async () => { + index = await openSessionSearchIndexFile('ss-file-write') + errors = [] + store = new SessionSearchStore(index.path, (error) => errors.push(error)) + registerSessionSearchIndexConsumer(store) +}) + +afterEach(async () => { + vi.restoreAllMocks() + resetTranscriptConsumersForTests() + store.close() + await index.close() +}) + +function matches(db: SyncDatabase, table: string, term: string): number { + return ( + db + .prepare( + `SELECT count(*) AS n FROM ${table} JOIN messages m ON m.id = ${table}.rowid + JOIN sessions s ON s.id = m.session_row_id WHERE ${table} MATCH ?` + ) + .get(term) as { n: number } + ).n +} + +/** Fails the nth statement matching `pick`, wherever the writer prepares it. */ +function failOnStatement(pick: (sql: string) => boolean, nth: number): void { + const prepare = SyncDatabase.prototype.prepare + let seen = 0 + vi.spyOn(SyncDatabase.prototype, 'prepare').mockImplementation(function ( + this: SyncDatabase, + sql: string + ) { + if (pick(sql) && ++seen === nth) { + throw new Error('index write crashed mid transaction') + } + return prepare.call(this, sql) + }) +} + +function counts(db: SyncDatabase): Record { + const one = (sql: string): number => (db.prepare(sql).get() as { n: number }).n + return { + sessions: one('SELECT count(*) AS n FROM sessions'), + messages: one('SELECT count(*) AS n FROM messages'), + files: one('SELECT count(*) AS n FROM files'), + full: one('SELECT count(*) AS n FROM messages_fts') + } +} + +it('writes a whole read in one transaction', () => { + replayTranscriptRead({ messages: userMessages('needle text', 300) }) + + const after = counts(index.db) + expect(after.sessions).toBe(1) + expect(after.messages).toBe(300) + expect(after.full).toBe(300) + expect(errors).toEqual([]) +}) + +it('files every row in one FTS table, under the column its role owns', () => { + replayTranscriptRead({ + messages: [ + { role: 'user', text: 'alpha question', timestamp: null }, + { role: 'assistant', text: 'beta answer', timestamp: null }, + { role: 'tool', text: 'gamma tool output', timestamp: null } + ] + }) + + // One table carries all three; the conversation scope is a column filter over + // it, which is what the second table used to be. + expect(counts(index.db).full).toBe(3) + expect(matches(index.db, 'messages_fts', 'gamma')).toBe(1) + expect(matches(index.db, 'messages_fts', '{user_text assistant_text}: gamma')).toBe(0) + expect(matches(index.db, 'messages_fts', '{user_text assistant_text}: beta')).toBe(1) +}) + +it('leaves the index exactly as it found it when a read never finishes', () => { + const write = store.beginWrite(syntheticCandidate(), 'replace', 0)! + for (const message of userMessages('neverfinished', 200)) { + write.add(message) + } + // The process dies here: the rows only ever existed in this buffer. + expect(counts(index.db)).toMatchObject({ + sessions: 0, + messages: 0, + files: 0 + }) +}) + +it('rolls a whole file back when a write throws part way through its transaction', () => { + replayTranscriptRead({ + messages: userMessages('firstgeneration', 3), + outcome: { byteOffset: 40 } + }) + const before = counts(index.db) + + failOnStatement((sql) => sql.startsWith('INSERT INTO messages('), 50) + replayTranscriptRead({ + messages: userMessages('crashedgeneration', 100), + outcome: { byteOffset: 900 } + }) + vi.restoreAllMocks() + + // Not one of the 49 rows that were already inserted survived, the previous + // generation is untouched, and the cursor still describes what is really here. + expect(counts(index.db)).toEqual(before) + expect(matches(index.db, 'messages_fts', 'crashedgeneration')).toBe(0) + expect(matches(index.db, 'messages_fts', 'firstgeneration')).toBe(3) + expect(store.indexedFile(SYNTHETIC_TRANSCRIPT, null)?.byteOffset).toBe(40) + expect(errors).toHaveLength(1) + // The row itself says the read failed, which is the only reason anything was + // lost and the only record that outlives this read. + expect( + index.db.prepare('SELECT state, fail_count FROM files WHERE path = ?').get(SYNTHETIC_TRANSCRIPT) + ).toMatchObject({ state: 'failed', fail_count: 1 }) + + // And the connection is usable again: a transaction left open by the failure + // would take down every write after it, not just the one that threw. + replayTranscriptRead({ + messages: userMessages('afterthecrash', 2), + outcome: { byteOffset: 900 } + }) + expect(matches(index.db, 'messages_fts', 'afterthecrash')).toBe(2) + expect(store.indexedFile(SYNTHETIC_TRANSCRIPT, null)?.byteOffset).toBe(900) +}) + +it('takes the rows back when recording the cursor is what fails', () => { + replayTranscriptRead({ + messages: userMessages('firstgeneration', 3), + outcome: { byteOffset: 40 } + }) + + // The cursor is written last, so this is the crash point that would leave rows + // no cursor describes: a later append would continue from an offset those rows + // already cover, and index the same span twice. + failOnStatement((sql) => sql.startsWith('INSERT INTO files('), 1) + replayTranscriptRead({ + messages: userMessages('crashedgeneration', 5), + outcome: { byteOffset: 900 } + }) + vi.restoreAllMocks() + + expect(counts(index.db)).toMatchObject({ sessions: 1, messages: 3 }) + expect(matches(index.db, 'messages_fts', 'firstgeneration')).toBe(3) + expect(matches(index.db, 'messages_fts', 'crashedgeneration')).toBe(0) + expect(store.indexedFile(SYNTHETIC_TRANSCRIPT, null)?.byteOffset).toBe(40) +}) + +it('shows a reader on another handle one generation or the other, never a mixture', async () => { + replayTranscriptRead({ + messages: userMessages('firstgeneration', 3), + outcome: { byteOffset: 40 } + }) + expect(counts(index.db).messages).toBe(3) + + const write = store.beginWrite(syntheticCandidate(), 'replace', 0)! + for (const message of userMessages('secondgeneration', 7)) { + write.add(message) + // Every point at which the other handle could issue a query mid-read. + expect(counts(index.db).messages).toBe(3) + expect(matches(index.db, 'messages_fts', 'secondgeneration')).toBe(0) + } + expect( + write.commit({ + session: syntheticSession(), + byteOffset: 900, + incomplete: false + }) + ).toBe(true) + + expect(matches(index.db, 'messages_fts', 'firstgeneration')).toBe(0) + expect(matches(index.db, 'messages_fts', 'secondgeneration')).toBe(7) + // The old three are cut loose, not deleted, so they are still on disk and + // already unreachable; the drain the store scheduled hands them back. + expect(counts(index.db).messages).toBe(10) + await vi.waitFor(() => { + expect(counts(index.db).messages).toBe(7) + }) +}) + +// Four of these fill the 400-char ceiling the two tests below construct. +const CHUNKED_MESSAGE = `chunkedneedle ${'filler '.repeat(12)}nd` + +const PROVISIONAL_IDENTITY = { + sessionId: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee', + cwd: '/repo/app', + title: 'provisional title', + createdAt: '2026-05-01T10:00:00.000Z', + updatedAt: '2026-05-01T10:05:00.000Z' +} + +// Only a read that can name its session chunks at all, so every test below that +// wants a chunk has to supply one. +const named = (): typeof PROVISIONAL_IDENTITY => PROVISIONAL_IDENTITY + +it('leaves the session consistent after every chunk of a file too large for one transaction', () => { + expect(CHUNKED_MESSAGE.length).toBe(100) + const writer = new SessionSearchIndexWriter(index.db, 400) + const write = writer.beginWrite(syntheticCandidate(), 'replace', 0, named)! + for (const [position, message] of userMessages(CHUNKED_MESSAGE, 10).entries()) { + write.add(message) + const rows = counts(index.db).messages + // Four messages per chunk, and nothing else reaches the file between them. + expect(rows).toBe(Math.floor((position + 1) / 4) * 4) + // Whatever landed is a coherent prefix of this session and answers searches. + expect(matches(index.db, 'messages_fts', 'chunkedneedle')).toBe(rows) + if (rows > 0) { + // The cursor a chunk leaves refuses every append rather than inventing an + // offset the reader never gave it. + expect(requiresWholeRead(writer.indexedFile(SYNTHETIC_TRANSCRIPT, null))).toBe(true) + expect(writer.beginWrite(syntheticCandidate(), 'append', 0)).toBeNull() + } + } + expect(counts(index.db).messages).toBe(8) + + expect( + write.commit({ + session: syntheticSession(), + byteOffset: 4096, + incomplete: false + }) + ).toBe(true) + expect(counts(index.db)).toMatchObject({ + sessions: 1, + messages: 10, + full: 10 + }) + expect(writer.indexedFile(SYNTHETIC_TRANSCRIPT, null)?.byteOffset).toBe(4096) +}) + +it('holds the ceiling against a single message larger than it', () => { + const writer = new SessionSearchIndexWriter(index.db, 8000) + const write = writer.beginWrite(syntheticCandidate(), 'replace', 0, named)! + const exec = SyncDatabase.prototype.exec + let opened = 0 + vi.spyOn(SyncDatabase.prototype, 'exec').mockImplementation(function ( + this: SyncDatabase, + sql: string + ) { + if (sql === 'BEGIN IMMEDIATE') { + opened += 1 + } + exec.call(this, sql) + }) + + // One conversation turn, three times the ceiling. Checked once per message, + // this commits all 24,000 characters in a single transaction — the ceiling + // bounds nothing that a message can exceed on its own. + write.add({ role: 'assistant', text: 'a'.repeat(24_000), timestamp: null }) + vi.restoreAllMocks() + + expect(opened).toBe(3) + expect(counts(index.db).messages).toBe(3) + expect( + write.commit({ + session: syntheticSession(), + byteOffset: 4096, + incomplete: false + }) + ).toBe(true) + expect(counts(index.db)).toMatchObject({ sessions: 1, messages: 3 }) +}) + +it('names a session on its first chunk, not only when the read ends', () => { + const writer = new SessionSearchIndexWriter(index.db, 400) + const write = writer.beginWrite(syntheticCandidate(), 'replace', 0, named)! + for (const message of userMessages(CHUNKED_MESSAGE, 10)) { + write.add(message) + } + + // The chunks that landed already answer searches, so the session they hang + // off has to be nameable on another handle before the read ends. This is also + // the whole record a crash between chunks leaves behind. + expect(counts(index.db).messages).toBe(8) + expect( + index.db.prepare('SELECT session_id, cwd, cwd_key, title, created_at FROM sessions').get() + ).toEqual({ + session_id: PROVISIONAL_IDENTITY.sessionId, + cwd: '/repo/app', + cwd_key: cwdKey('/repo/app'), + title: 'provisional title', + created_at: '2026-05-01T10:00:00.000Z' + }) + + // And the decoded session still wins at the end: the mid-read title is + // provisional, never a value the final commit has to defer to. + expect( + write.commit({ + session: syntheticSession({ title: 'the settled title' }), + byteOffset: 4096, + incomplete: false + }) + ).toBe(true) + expect(index.db.prepare('SELECT title FROM sessions').get()).toEqual({ + title: 'the settled title' + }) +}) + +it('commits a whole-file read over the ceiling in one transaction, never a chunk', () => { + // The whole-file readers (Grok, Cursor, Gemini, OpenCode) pass no identity: + // their formats are rewritten in place and have no resumable state to ask. + const writer = new SessionSearchIndexWriter(index.db, 400) + const write = writer.beginWrite(syntheticCandidate(), 'replace', 0)! + const exec = SyncDatabase.prototype.exec + let opened = 0 + vi.spyOn(SyncDatabase.prototype, 'exec').mockImplementation(function ( + this: SyncDatabase, + sql: string + ) { + if (sql === 'BEGIN IMMEDIATE') { + opened += 1 + } + exec.call(this, sql) + }) + + for (const message of userMessages(CHUNKED_MESSAGE, 10)) { + write.add(message) + // Chunking here would publish rows under a session with an empty id, an + // empty title and a null cwd, and an interrupted read would leave that + // prefix answering searches for good. + expect(counts(index.db)).toMatchObject({ sessions: 0, messages: 0, files: 0 }) + } + expect(write.commit({ session: syntheticSession(), byteOffset: 4096, incomplete: false })).toBe( + true + ) + vi.restoreAllMocks() + + expect(opened).toBe(1) + expect(counts(index.db)).toMatchObject({ sessions: 1, messages: 10, full: 10 }) + // And a real cursor, not the partial sentinel a chunk would have left. + expect(writer.indexedFile(SYNTHETIC_TRANSCRIPT, null)?.byteOffset).toBe(4096) +}) + +it('starts chunking only once the parser has an id to name the session with', () => { + const writer = new SessionSearchIndexWriter(index.db, 400) + let decoded: typeof PROVISIONAL_IDENTITY | null = null + const write = writer.beginWrite(syntheticCandidate(), 'replace', 0, () => decoded)! + for (const message of userMessages(CHUNKED_MESSAGE, 4)) { + write.add(message) + } + // Past the ceiling, but the parser has decoded nothing: the buffer keeps + // growing rather than naming a session it cannot name. + expect(counts(index.db).messages).toBe(0) + + decoded = PROVISIONAL_IDENTITY + write.add(userMessages(CHUNKED_MESSAGE, 1)[0]!) + + // Everything held goes with the first chunk that can say what it is. + expect(counts(index.db).messages).toBe(5) + expect(index.db.prepare('SELECT session_id, cwd FROM sessions').get()).toEqual({ + session_id: PROVISIONAL_IDENTITY.sessionId, + cwd: '/repo/app' + }) +}) + +it('reports a chunk-partial file as held, and as one that must be read whole', () => { + const writer = new SessionSearchIndexWriter(index.db, 400) + const write = writer.beginWrite(syntheticCandidate(), 'replace', 0, named)! + for (const message of userMessages(CHUNKED_MESSAGE, 10)) { + write.add(message) + } + + // Held, with no cursor to continue. Reporting nothing here reads as "never + // indexed", so a caller asks for whatever read the parse cache offers, the + // reader picks append, and only a decline heals it a cycle later. + const held = writer.indexedFile(SYNTHETIC_TRANSCRIPT, null) + expect(held).not.toBeNull() + expect(held?.byteOffset).toBeNull() + expect(requiresWholeRead(held)).toBe(true) + expect(held?.mtimeMs).toBe(syntheticCandidate().file.mtimeMs) + + // A file this index has never seen is still the other answer, so the two + // states a caller has to tell apart are distinguishable. + expect(writer.indexedFile('/never-seen.jsonl', null)).toBeNull() + expect(requiresWholeRead(null)).toBe(false) + + // And no offset continues it, including the one the chunk recorded. + for (const offset of [0, -1, 400, 1000]) { + expect(writer.beginWrite(syntheticCandidate(), 'append', offset)).toBeNull() + } +}) + +it('re-reads a chunked file whole when its writer died between chunks', async () => { + const writer = new SessionSearchIndexWriter(index.db, 400) + const abandoned = writer.beginWrite(syntheticCandidate(), 'replace', 0, named)! + for (const message of userMessages(CHUNKED_MESSAGE, 10)) { + abandoned.add(message) + } + expect(counts(index.db).messages).toBe(8) + + // Nothing can continue that prefix, so the only way forward is a whole re-read, + // and that replaces every row the dead writer left. + expect(requiresWholeRead(writer.indexedFile(SYNTHETIC_TRANSCRIPT, null))).toBe(true) + const replacement = writer.beginWrite(syntheticCandidate(), 'replace', 0)! + replacement.add(userMessages('wholereread', 1)[0]!) + expect( + replacement.commit({ + session: syntheticSession(), + byteOffset: 4096, + incomplete: false + }) + ).toBe(true) + // The eight stranded rows stop answering the moment the replace commits, and + // the drain hands them back after it rather than inside it. + expect(counts(index.db)).toMatchObject({ sessions: 1, messages: 9 }) + expect(matches(index.db, 'messages_fts', 'chunkedneedle')).toBe(0) + await deleteExpiredSearchFiles(index.db, null, () => false) + expect(counts(index.db)).toMatchObject({ sessions: 1, messages: 1 }) +}) + +it('stops a chunked read whose file was removed between its chunks', () => { + const writer = new SessionSearchIndexWriter(index.db, 400) + const write = writer.beginWrite(syntheticCandidate(), 'replace', 0, named)! + const messages = userMessages(CHUNKED_MESSAGE, 10) + for (const message of messages.slice(0, 4)) { + write.add(message) + } + expect(counts(index.db).messages).toBe(4) + + writer.removeFile(SYNTHETIC_TRANSCRIPT) + const exec = SyncDatabase.prototype.exec + let opened = 0 + vi.spyOn(SyncDatabase.prototype, 'exec').mockImplementation(function ( + this: SyncDatabase, + sql: string + ) { + if (sql === 'BEGIN IMMEDIATE') { + opened += 1 + } + exec.call(this, sql) + }) + for (const message of messages.slice(4)) { + write.add(message) + } + expect(write.commit({ session: syntheticSession(), byteOffset: 4096, incomplete: false })).toBe( + false + ) + vi.restoreAllMocks() + + // Not one row of the removed source came back. The read stopped at the first + // refusal rather than reopening a transaction it already knows will roll back, + // once for every message left in a file that may be a hundred megabytes. + expect(opened).toBe(1) + expect(counts(index.db)).toMatchObject({ sessions: 0, messages: 0, files: 0, full: 0 }) +}) + +it('fences a first-ever read whose file was removed before it committed', () => { + const candidate = syntheticCandidate({ path: '/never-indexed.jsonl' }) + const write = store.beginWrite(candidate, 'replace', 0)! + for (const message of userMessages('removedbeforefirstcommit', 3)) { + write.add(message) + } + // The path was never indexed, so there is no cursor for the removal to move. + // PR 3's retirement sweep removes exactly these: paths the index deferred over + // budget and never wrote, while the registered consumer is fed concurrently. + store.removeFile('/never-indexed.jsonl') + + expect(write.commit({ session: syntheticSession(), byteOffset: 300, incomplete: false })).toBe( + false + ) + expect(counts(index.db)).toMatchObject({ sessions: 0, messages: 0, files: 0, full: 0 }) +}) + +it('replaces the previous generation without ever showing both', async () => { + replayTranscriptRead({ messages: userMessages('firstgeneration', 10) }) + replayTranscriptRead({ messages: userMessages('secondgeneration', 10) }) + + expect(matches(index.db, 'messages_fts', 'firstgeneration')).toBe(0) + expect(matches(index.db, 'messages_fts', 'secondgeneration')).toBe(10) + await vi.waitFor(() => { + expect(counts(index.db)).toMatchObject({ sessions: 1, messages: 10, full: 10 }) + }) +}) + +it('replaces a generation by cutting the old one loose, not by deleting it inline', async () => { + const writer = new SessionSearchIndexWriter(index.db) + const first = writer.beginWrite(syntheticCandidate(), 'replace', 0)! + for (const message of userMessages('firstgeneration', 200)) { + first.add(message) + } + expect(first.commit({ session: syntheticSession(), byteOffset: 100, incomplete: false })).toBe( + true + ) + const before = index.db.prepare('SELECT id FROM sessions').get() as { id: number } + expect(counts(index.db).messages).toBe(200) + + const second = writer.beginWrite(syntheticCandidate(), 'replace', 0)! + for (const message of userMessages('secondgeneration', 3)) { + second.add(message) + } + expect(second.commit({ session: syntheticSession(), byteOffset: 200, incomplete: false })).toBe( + true + ) + + // The transaction inserted three rows and deleted one, rather than deleting + // two hundred: all 203 are still on disk, and the old 200 already answer + // nothing, because every retrieval joins `sessions`. + expect(counts(index.db)).toMatchObject({ sessions: 1, messages: 203, full: 203 }) + expect(matches(index.db, 'messages_fts', 'firstgeneration')).toBe(0) + expect(matches(index.db, 'messages_fts', 'secondgeneration')).toBe(3) + + // A new session row, with `files` repointed at it in that same transaction. + // AUTOINCREMENT never hands the freed id back while orphans still name it. + const after = index.db.prepare('SELECT id FROM sessions').get() as { id: number } + expect(after.id).toBeGreaterThan(before.id) + expect(index.db.prepare('SELECT session_row_id FROM files').get()).toEqual({ + session_row_id: after.id + }) + + await deleteExpiredSearchFiles(index.db, null, () => false) + expect(counts(index.db)).toMatchObject({ sessions: 1, messages: 3, full: 3 }) +}) + +it('drains what a replace cut loose without being asked', async () => { + replayTranscriptRead({ messages: userMessages('firstgeneration', 200) }) + replayTranscriptRead({ messages: userMessages('secondgeneration', 3) }) + + // The store schedules the reclaim the way it schedules retention's. Hiding a + // generation and never reclaiming it would grow the file by every re-read. + expect(matches(index.db, 'messages_fts', 'firstgeneration')).toBe(0) + await vi.waitFor(() => { + expect(counts(index.db)).toMatchObject({ sessions: 1, messages: 3, full: 3 }) + }) + expect(errors).toEqual([]) +}) + +it('continues a session across an append rather than replaying it', () => { + replayTranscriptRead({ + messages: userMessages('openingturn', 3), + outcome: { byteOffset: 40 } + }) + replayTranscriptRead({ + messages: userMessages('laterturn', 2), + mode: 'append', + previousByteOffset: 40, + outcome: { byteOffset: 90 } + }) + + expect(counts(index.db)).toMatchObject({ sessions: 1, messages: 5 }) + expect(matches(index.db, 'messages_fts', 'openingturn')).toBe(3) + expect(matches(index.db, 'messages_fts', 'laterturn')).toBe(2) + expect(store.indexedFile(SYNTHETIC_TRANSCRIPT, null)?.byteOffset).toBe(90) +}) + +it('stops answering for a removed file the moment it is removed', () => { + replayTranscriptRead({ messages: userMessages('removedneedle', 3) }) + store.removeFile(SYNTHETIC_TRANSCRIPT) + + expect(counts(index.db)).toMatchObject({ + sessions: 0, + messages: 0, + files: 0, + full: 0 + }) + expect(matches(index.db, 'messages_fts', 'removedneedle')).toBe(0) +}) + +it('writes nothing for an incomplete read and owes the file a whole re-read', () => { + replayTranscriptRead({ + messages: userMessages('incompleteread', 300), + outcome: { incomplete: true } + }) + + expect(counts(index.db)).toMatchObject({ + sessions: 0, + messages: 0, + full: 0 + }) + // One row, holding nothing but the failure: an incomplete read indexes no + // content, and the count of how often it has happened at this stat is the + // only thing that stops the file being read again on every pass. + expect(index.db.prepare('SELECT byte_offset, state, fail_count FROM files').get()).toMatchObject({ + byte_offset: 0, + state: 'failed', + fail_count: 1 + }) + expect(errors).toEqual([]) +}) + +it('exposes the handle a composed reader queries through', () => { + replayTranscriptRead({ messages: userMessages('composedreader', 3) }) + + // PR 4's engine reads through this rather than opening a second connection, + // so it sees a write the moment the transaction commits. + expect(store.connection.prepare('SELECT count(*) AS n FROM messages').get()).toEqual({ n: 3 }) +}) + +it('closes twice without turning the second call into an error', () => { + store.close() + // node:sqlite throws ERR_INVALID_STATE on a second close of one handle, and a + // store is closed both by whoever owns it and by a teardown that cannot know. + expect(() => store.close()).not.toThrow() + store = new SessionSearchStore(index.path, (error) => errors.push(error)) +}) diff --git a/src/main/ai-vault-search/session-search-fts5-contract.test.ts b/src/main/ai-vault-search/session-search-fts5-contract.test.ts new file mode 100644 index 00000000000..be815623ce7 --- /dev/null +++ b/src/main/ai-vault-search/session-search-fts5-contract.test.ts @@ -0,0 +1,172 @@ +import { mkdtemp } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { removeTree } from '../../shared/windows-transient-lock-removal' +import type SyncDatabase from '../sqlite/sync-database' +import { indexTokens } from './session-search-query-planner' +import { ensureSessionSearchQuerySchema } from './session-search-query-schema' +import { openSessionSearchDatabase } from './session-search-schema' + +// SQLite/FTS5 behaviours the query layer depends on. Each one cost a live +// debugging session; a refactor that reintroduces the trap fails here. + +const FIRST_ROWID = 101 +const SECOND_ROWID = 202 + +let tempRoots: string[] = [] + +afterEach(async () => { + await Promise.all(tempRoots.map((root) => removeTree(root))) + tempRoots = [] +}) + +async function openDatabase(): Promise { + const root = await mkdtemp(join(tmpdir(), 'orca-fts5-contract-')) + tempRoots.push(root) + return openSessionSearchDatabase(join(root, 'index.sqlite')) +} + +function insertMessageRow(db: SyncDatabase, rowid: number, text: string): void { + db.prepare( + `INSERT INTO messages_fts(rowid, user_text, assistant_text, tool_text, identifiers) + VALUES (?, ?, '', '', '')` + ).run(rowid, text) +} + +describe('FTS5 aux functions take the table name, never an alias', () => { + it('rejects bm25 over an aliased table and accepts the table-name form', async () => { + const db = await openDatabase() + insertMessageRow(db, FIRST_ROWID, 'alpha marmoset one') + + expect(() => + db.prepare('SELECT bm25(f) AS score FROM messages_fts f WHERE f MATCH ?').all('alpha') + ).toThrow(/no such column: f/) + + const scored = db + .prepare('SELECT bm25(messages_fts) AS score FROM messages_fts WHERE messages_fts MATCH ?') + .all('alpha') as { score: number }[] + expect(scored).toHaveLength(1) + expect(Number.isFinite(scored[0]?.score)).toBe(true) + db.close() + }) + + it('rejects snippet over an aliased table too', async () => { + const db = await openDatabase() + insertMessageRow(db, FIRST_ROWID, 'alpha marmoset one') + + expect(() => + db + .prepare( + "SELECT snippet(f, -1, '[', ']', '…', 12) AS s FROM messages_fts f WHERE f MATCH ?" + ) + .all('alpha') + ).toThrow(/no such column: f/) + db.close() + }) +}) + +describe('a rowid constraint beside MATCH is honoured only as a subselect', () => { + it('ignores `rowid = ?` and returns every match, first row first', async () => { + const db = await openDatabase() + insertMessageRow(db, FIRST_ROWID, 'alpha marmoset one') + insertMessageRow(db, SECOND_ROWID, 'alpha capybara two') + + const rows = db + .prepare('SELECT rowid FROM messages_fts WHERE messages_fts MATCH ? AND rowid = ?') + .all('alpha', SECOND_ROWID) as { rowid: number }[] + // The planner drops the constraint entirely: both rows come back. + expect(rows.map((row) => row.rowid)).toEqual([FIRST_ROWID, SECOND_ROWID]) + // A caller reading one row therefore gets the first match, not the one asked for. + const single = db + .prepare('SELECT rowid FROM messages_fts WHERE messages_fts MATCH ? AND rowid = ?') + .get('alpha', SECOND_ROWID) as { rowid: number } | undefined + expect(single?.rowid).toBe(FIRST_ROWID) + db.close() + }) + + it('ignores `rowid IN (?)` the same way', async () => { + const db = await openDatabase() + insertMessageRow(db, FIRST_ROWID, 'alpha marmoset one') + insertMessageRow(db, SECOND_ROWID, 'alpha capybara two') + + const rows = db + .prepare('SELECT rowid FROM messages_fts WHERE messages_fts MATCH ? AND rowid IN (?)') + .all('alpha', SECOND_ROWID) as { rowid: number }[] + expect(rows.map((row) => row.rowid)).toEqual([FIRST_ROWID, SECOND_ROWID]) + db.close() + }) + + it('honours `rowid IN (SELECT ?)` even with the session join on', async () => { + const db = await openDatabase() + db.prepare( + `INSERT INTO sessions(id,agent,session_id,file_path,title,resume_command) + VALUES (1,'claude','1','/synthetic/1','fixture','')` + ).run() + for (const rowid of [FIRST_ROWID, SECOND_ROWID]) { + db.prepare("INSERT INTO messages(id,session_row_id,role) VALUES (?,1,'user')").run(rowid) + } + insertMessageRow(db, FIRST_ROWID, 'alpha marmoset one') + insertMessageRow(db, SECOND_ROWID, 'alpha capybara two') + + // The shape the snippet read uses: the joins are what subtract a row whose + // session a purge cut loose, and they must not cost the rowid constraint + // its effect. + const snippet = db + .prepare( + `SELECT snippet(messages_fts, -1, '[', ']', '…', 12) AS s + FROM messages_fts + JOIN messages m ON m.id = messages_fts.rowid + JOIN sessions s ON s.id = m.session_row_id + WHERE messages_fts MATCH ? AND messages_fts.rowid IN (SELECT ?)` + ) + .get('alpha', SECOND_ROWID) as { s: string } | undefined + expect(snippet?.s).toContain('capybara') + expect(snippet?.s).not.toContain('marmoset') + db.close() + }) +}) + +describe('sessions.file_path is deliberately not unique', () => { + it('accepts two sessions sharing one store path', async () => { + const db = await openDatabase() + const insert = db.prepare( + `INSERT INTO sessions(agent, session_id, file_path, title, resume_command) + VALUES (?, ?, ?, ?, ?)` + ) + // OpenCode and Cursor keep every session in one SQLite store; files.path is the key. + const storePath = '/home/user/.local/share/opencode/storage.db' + insert.run('opencode', 'ses_one', storePath, 'first', 'opencode --session ses_one') + expect(() => + insert.run('opencode', 'ses_two', storePath, 'second', 'opencode --session ses_two') + ).not.toThrow() + + const rows = db + .prepare('SELECT session_id FROM sessions WHERE file_path = ? ORDER BY session_id') + .all(storePath) as { session_id: string }[] + expect(rows.map((row) => row.session_id)).toEqual(['ses_one', 'ses_two']) + db.close() + }) +}) + +describe('the planner tokenizer draws the same boundaries as unicode61', () => { + // unicode61 folds case and strips Latin diacritics on both index and query side. + function asIndexed(token: string): string { + return token.toLowerCase().normalize('NFD').replaceAll(/\p{M}/gu, '') + } + + it('produces exactly the terms fts5vocab reports for the same text', async () => { + const db = await openDatabase() + // The vocabulary is the engine's own object, not the store's. + ensureSessionSearchQuerySchema(db) + const corpus = + 'resolveTerminalPath src/main/foo-bar.ts a.b C++ #123 修复 café naïve MAX_TOKEN x' + insertMessageRow(db, FIRST_ROWID, corpus) + const indexed = ( + db.prepare('SELECT term FROM messages_vocab ORDER BY term').all() as { term: string }[] + ).map((row) => row.term) + + expect([...new Set(indexTokens(corpus).map(asIndexed))].sort()).toEqual(indexed) + db.close() + }) +}) diff --git a/src/main/ai-vault-search/session-search-hit-ranking.test.ts b/src/main/ai-vault-search/session-search-hit-ranking.test.ts new file mode 100644 index 00000000000..54919bace0f --- /dev/null +++ b/src/main/ai-vault-search/session-search-hit-ranking.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, it } from 'vitest' +import { rankSessionHits, type MessageRow, type SessionRow } from './session-search-hit-ranking' + +function session(id: number, overrides: Partial = {}): SessionRow { + return { + id, + agent: 'claude', + session_id: String(id), + file_path: `/synthetic/${id}.jsonl`, + codex_home: null, + title: 'fixture', + cwd: '/repo/app', + branch: null, + updated_at: '2026-09-01T00:00:00.000Z', + message_count: 1, + resume_command: 'resume', + content_hash: null, + content_hash_count: 0, + ...overrides + } +} + +function match(id: number, score: number): MessageRow { + return { rowid: id, score, session_row_id: id, role: 'user', ts: null } +} + +function matches(...rows: MessageRow[]): Map { + return new Map(rows.map((row) => [row.session_row_id, row])) +} + +describe('order', () => { + it('ranks by score under relevance and by recency under newest', () => { + const sessions = [ + session(1, { updated_at: '2026-09-01T00:00:00.000Z' }), + session(2, { updated_at: '2026-09-09T00:00:00.000Z' }) + ] + const scores = matches(match(1, 10), match(2, 1)) + expect(rankSessionHits(sessions, scores, 'relevance').map((e) => e.session.id)).toEqual([1, 2]) + expect(rankSessionHits(sessions, scores, 'newest').map((e) => e.session.id)).toEqual([2, 1]) + }) + + it.each(['relevance', 'newest'] as const)( + 'breaks a %s tie by session, whatever order retrieval handed them over in', + (sort) => { + // A cursor is an offset into this list, so two entries that tie must not + // be free to swap between pages. Retrieval hands sessions over in + // whatever order the `IN (...)` lookup produced, which SQL does not + // promise, so the order below is deliberately reversed. + const sessions = [6, 5, 4, 3, 2, 1].map((id) => session(id)) + const scores = matches(...sessions.map((entry) => match(entry.id, 5))) + expect(rankSessionHits(sessions, scores, sort).map((entry) => entry.session.id)).toEqual([ + 1, 2, 3, 4, 5, 6 + ]) + } + ) + + it('prefers the shorter session when two match equally well', () => { + // The length prior: `0.02 · ln(1 + messages)`, subtracted per session. + const sessions = [session(1, { message_count: 5000 }), session(2, { message_count: 2 })] + const ranked = rankSessionHits(sessions, matches(match(1, 5), match(2, 5)), 'relevance') + expect(ranked.map((entry) => entry.session.id)).toEqual([2, 1]) + expect(ranked[0]!.score).toBeGreaterThan(ranked[1]!.score) + }) +}) + +describe('forks fold into one answer', () => { + const fork = (id: number, updatedAt: string): SessionRow => + session(id, { + updated_at: updatedAt, + content_hash: 'shared-opening-prefix', + content_hash_count: 8 + }) + + it('keeps the newest copy and counts the rest', () => { + const sessions = [ + fork(1, '2026-09-01T00:00:00.000Z'), + fork(2, '2026-09-09T00:00:00.000Z'), + fork(3, '2026-09-05T00:00:00.000Z') + ] + const ranked = rankSessionHits( + sessions, + matches(match(1, 9), match(2, 1), match(3, 5)), + 'relevance' + ) + expect(ranked).toHaveLength(1) + expect(ranked[0]!.session.id).toBe(2) + expect(ranked[0]!.duplicateCount).toBe(3) + }) + + it('leaves sessions with no shared prefix alone', () => { + const sessions = [session(1), session(2)] + const ranked = rankSessionHits(sessions, matches(match(1, 9), match(2, 5)), 'relevance') + expect(ranked.map((entry) => entry.duplicateCount)).toEqual([1, 1]) + }) +}) + +it('scores a session that matched no text at zero, less its length prior', () => { + // The operator-only page: there is no relevance signal, only an order. + const ranked = rankSessionHits([session(1, { message_count: 9 })], new Map(), 'newest') + expect(ranked[0]!.message).toBeNull() + expect(ranked[0]!.score).toBeLessThan(0) +}) diff --git a/src/main/ai-vault-search/session-search-hit-ranking.ts b/src/main/ai-vault-search/session-search-hit-ranking.ts new file mode 100644 index 00000000000..364858ea650 --- /dev/null +++ b/src/main/ai-vault-search/session-search-hit-ranking.ts @@ -0,0 +1,109 @@ +import type { AiVaultAgent } from '../../shared/ai-vault-types' +import { isCollapsibleContentHash } from './session-search-content-hash' +import type { SessionSearchSort } from './session-search-engine-types' + +// Subtracted per session: `0.02 · ln(1 + messages)`; slightly positive on both eval sets. +const LENGTH_PRIOR = 0.02 + +export type SessionRow = { + id: number + agent: AiVaultAgent + session_id: string + file_path: string + codex_home: string | null + title: string + cwd: string | null + branch: string | null + updated_at: string | null + message_count: number + resume_command: string + content_hash: string | null + content_hash_count: number +} + +/** The one message that stands for a session: its best-scoring match. */ +export type MessageRow = { + rowid: number + score: number + session_row_id: number + role: string + ts: string | null +} + +export type RankedSession = { + session: SessionRow + /** Null on an operator-only page: the session matched no text at all. */ + message: MessageRow | null + score: number + duplicateCount: number +} + +/** + * Everything between "these sessions matched" and "this is the ranked list": + * the length prior, fork folding and the caller's order. Retrieval stays in SQL + * and nothing here touches the database. + * + * The whole list is returned, not a page: a cursor indexes into it, and slicing + * here would make page two a different ranking from page one. The engine cuts + * the page and only then pays for a snippet. + */ +export function rankSessionHits( + sessions: readonly SessionRow[], + matches: ReadonlyMap, + sort: SessionSearchSort +): RankedSession[] { + const scored = collapseForks( + sessions.map((session) => { + const message = matches.get(session.id) ?? null + return { + session, + message, + score: (message?.score ?? 0) - LENGTH_PRIOR * Math.log(1 + session.message_count), + duplicateCount: 1 + } + }) + ) + // Why a total order and not just the key: a cursor is an offset into this + // list, so two entries that tie must not be free to swap between pages. + scored.sort( + (left, right) => + (sort === 'newest' + ? (right.session.updated_at ?? '').localeCompare(left.session.updated_at ?? '') + : right.score - left.score) || left.session.id - right.session.id + ) + return scored +} + +/** + * Folds forked copies of one conversation into a single entry: same opening + * prefix, newest `updated_at` wins, the rest become `duplicateCount`. Done here + * and not at write time so index rows stay per file (cursors and deletes). + */ +function collapseForks(scored: RankedSession[]): RankedSession[] { + const groups = new Map() + for (const entry of scored) { + const { content_hash: hash, content_hash_count: count, id } = entry.session + const key = isCollapsibleContentHash(hash, count) ? `hash:${hash}` : `session:${id}` + const group = groups.get(key) + if (group) { + group.push(entry) + } else { + groups.set(key, [entry]) + } + } + const collapsed: RankedSession[] = [] + for (const group of groups.values()) { + if (group.length === 1) { + collapsed.push(group[0]!) + continue + } + const winner = group.reduce((best, entry) => (isNewer(entry, best) ? entry : best)) + collapsed.push({ ...winner, duplicateCount: group.length }) + } + return collapsed +} + +function isNewer(entry: RankedSession, best: RankedSession): boolean { + const order = (entry.session.updated_at ?? '').localeCompare(best.session.updated_at ?? '') + return order === 0 ? entry.score > best.score : order > 0 +} diff --git a/src/main/ai-vault-search/session-search-identifier-split.test.ts b/src/main/ai-vault-search/session-search-identifier-split.test.ts new file mode 100644 index 00000000000..24f8a67d5c3 --- /dev/null +++ b/src/main/ai-vault-search/session-search-identifier-split.test.ts @@ -0,0 +1,29 @@ +import { expect, it } from 'vitest' +import { identifierShadowTerms, identifierShadowText } from './session-search-identifier-split' + +it('splits a camel-case symbol into its pieces and keeps the whole', () => { + expect(identifierShadowTerms('call resolveTerminalPath here')).toEqual([ + 'resolveterminalpath', + 'resolve', + 'terminal', + 'path' + ]) +}) + +it('splits a path into its segments and extension', () => { + // The whole path already tokenizes on its own; only the pieces need shadowing. + expect(identifierShadowText('src/main/foo-bar.ts')).toBe('src main foo bar ts') +}) + +it('leaves ordinary prose alone', () => { + expect(identifierShadowTerms('the quick brown fox')).toEqual([]) +}) + +it('shadows a screaming-case constant', () => { + expect(identifierShadowTerms('MAX_RETRIES')).toEqual(['max', 'retries']) +}) + +it('stops at the term limit rather than growing with the message', () => { + const text = Array.from({ length: 50 }, (_unused, index) => `alpha_beta${index}`).join(' ') + expect(identifierShadowTerms(text, 10)).toHaveLength(10) +}) diff --git a/src/main/ai-vault-search/session-search-identifier-split.ts b/src/main/ai-vault-search/session-search-identifier-split.ts new file mode 100644 index 00000000000..e2df1822cfa --- /dev/null +++ b/src/main/ai-vault-search/session-search-identifier-split.ts @@ -0,0 +1,54 @@ +// Identifier shadow terms: `resolveTerminalPath` → `resolve terminal path`, +// `src/main/foo-bar.ts` → `src main foo bar ts`. Stored in a separate FTS5 +// column so a partial identifier still matches; the largest single accuracy +// win measured in the retrieval shoot-out (MRR 0.50 → 0.55). + +const RAW_TOKEN = /[A-Za-z0-9_./-]+/g +const CAMEL_PIECE = /[A-Z]+(?![a-z])|[A-Z][a-z0-9]*|[a-z0-9]+/g +const SEPARATOR = /[_./-]+/ +// Worth shadowing: has a separator, a camel boundary, or is SCREAMING_CASE. +const INTERESTING = /[_./-]|[a-z0-9][A-Z]|^[A-Z]{2,}[0-9_]*$/ +const MIN_TOKEN = 3 +const MAX_TOKEN = 120 +const MIN_PIECE = 2 + +function hasMixedCase(piece: string): boolean { + return /[a-z]/.test(piece) && /[A-Z]/.test(piece) +} + +export function identifierShadowTerms(text: string, limit = 4000): string[] { + const out: string[] = [] + const seen = new Set() + for (const match of text.matchAll(RAW_TOKEN)) { + const token = match[0] + if (token.length < MIN_TOKEN || token.length > MAX_TOKEN || !INTERESTING.test(token)) { + continue + } + const parts: string[] = [] + for (const piece of token.split(SEPARATOR)) { + if (!piece) { + continue + } + parts.push(piece) + if (hasMixedCase(piece)) { + parts.push(...(piece.match(CAMEL_PIECE) ?? [])) + } + } + for (const part of parts) { + const lowered = part.toLowerCase() + if (lowered.length < MIN_PIECE || seen.has(lowered)) { + continue + } + seen.add(lowered) + out.push(lowered) + if (out.length >= limit) { + return out + } + } + } + return out +} + +export function identifierShadowText(text: string, limit?: number): string { + return identifierShadowTerms(text, limit).join(' ') +} diff --git a/src/main/ai-vault-search/session-search-index-consumer.test.ts b/src/main/ai-vault-search/session-search-index-consumer.test.ts new file mode 100644 index 00000000000..ee855409fb7 --- /dev/null +++ b/src/main/ai-vault-search/session-search-index-consumer.test.ts @@ -0,0 +1,342 @@ +import { afterEach, beforeEach, expect, it } from 'vitest' +import { resetTranscriptConsumersForTests } from '../ai-vault/session-transcript-consumers' +import { registerSessionSearchIndexConsumer } from './session-search-index-consumer' +import { + openSessionSearchIndexFile, + replayTranscriptRead, + syntheticCandidate, + syntheticSession, + SYNTHETIC_TRANSCRIPT, + userMessages, + type SessionSearchIndexFile +} from './session-search-index-test-fixture' +import { SessionSearchStore } from './session-search-store' + +let index: SessionSearchIndexFile +let store: SessionSearchStore +let errors: unknown[] + +beforeEach(async () => { + index = await openSessionSearchIndexFile('ss-index-consumer') + errors = [] + store = new SessionSearchStore(index.path, (error) => errors.push(error)) + registerSessionSearchIndexConsumer(store) +}) + +afterEach(async () => { + resetTranscriptConsumersForTests() + store.close() + await index.close() +}) + +function indexedMessages(): number { + return ( + index.db.prepare('SELECT count(*) AS n FROM messages').get() as { + n: number + } + ).n +} + +function cursor(): number | null | undefined { + return store.indexedFile(SYNTHETIC_TRANSCRIPT, null)?.byteOffset +} + +/** What the row itself says it still owes, which is the only record there is. */ +function owed(): { state: string; fail_count: number } | undefined { + return index.db + .prepare('SELECT state, fail_count FROM files WHERE path = ?') + .get(SYNTHETIC_TRANSCRIPT) as { state: string; fail_count: number } | undefined +} + +it('appends onto its own cursor and carries the content hash forward', async () => { + replayTranscriptRead({ + messages: userMessages('first half', 3), + outcome: { byteOffset: 100 } + }) + const first = index.db + .prepare('SELECT content_hash AS hash, content_hash_count AS count FROM sessions') + .get() as { hash: string; count: number } + + replayTranscriptRead({ + mode: 'append', + previousByteOffset: 100, + messages: userMessages('second half', 2), + outcome: { byteOffset: 220 } + }) + + expect(indexedMessages()).toBe(5) + expect(cursor()).toBe(220) + const second = index.db + .prepare('SELECT content_hash AS hash, content_hash_count AS count FROM sessions') + .get() as { hash: string; count: number } + expect(second.count).toBe(first.count + 2) + expect(second.hash).not.toBe(first.hash) + expect(owed()).toMatchObject({ state: 'current', fail_count: 0 }) +}) + +it('appends onto a file it read through and decoded no session from', async () => { + // An excluded Codex worker transcript: read through, nothing to index, and + // still growing. Its cursor is sound, so a re-read of the whole file every + // pass buys nothing. + replayTranscriptRead({ + messages: userMessages('excluded span', 3), + outcome: { session: null, byteOffset: 100 } + }) + expect(cursor()).toBe(100) + expect(owed()).toMatchObject({ state: 'current', fail_count: 0 }) + + replayTranscriptRead({ + mode: 'append', + previousByteOffset: 100, + messages: userMessages('decoded at last', 2), + outcome: { byteOffset: 220 } + }) + + expect(indexedMessages()).toBe(2) + expect(cursor()).toBe(220) + expect(owed()).toMatchObject({ state: 'current', fail_count: 0 }) +}) + +it('declines an append that starts past its own cursor and records the file', async () => { + replayTranscriptRead({ + messages: userMessages('indexed span', 3), + outcome: { byteOffset: 100 } + }) + + // The session list read further than this index did, so the appended span + // continues from bytes the index never saw. + replayTranscriptRead({ + mode: 'append', + previousByteOffset: 900, + messages: userMessages('unseen span', 4), + outcome: { byteOffset: 1200 } + }) + + expect(indexedMessages()).toBe(3) + expect(cursor()).toBe(100) + expect(owed()).toMatchObject({ state: 'due' }) +}) + +it('declines a file whose identity changed under the same path', async () => { + const original = syntheticCandidate({ dev: 1, ino: 10 }) + replayTranscriptRead({ + candidate: original, + messages: userMessages('original file', 2), + outcome: { byteOffset: 100 } + }) + + replayTranscriptRead({ + candidate: syntheticCandidate({ dev: 1, ino: 77 }), + mode: 'append', + previousByteOffset: 100, + messages: userMessages('replacement file', 2), + outcome: { byteOffset: 200 } + }) + + expect(indexedMessages()).toBe(2) + expect(owed()?.state).not.toBe('current') +}) + +it('never advances the cursor for an incomplete read', async () => { + replayTranscriptRead({ + messages: userMessages('complete span', 3), + outcome: { byteOffset: 100 } + }) + + replayTranscriptRead({ + mode: 'append', + previousByteOffset: 100, + messages: userMessages('partial span', 5), + outcome: { byteOffset: 400, incomplete: true } + }) + + expect(indexedMessages()).toBe(3) + expect(cursor()).toBe(100) + expect( + ( + index.db.prepare('SELECT count(*) AS n FROM messages').get() as { + n: number + } + ).n + ).toBe(3) + expect(owed()?.state).not.toBe('current') +}) + +it('indexes nothing at all from a read that was incomplete from the start', async () => { + replayTranscriptRead({ + messages: userMessages('unreachable', 4), + outcome: { byteOffset: 0, incomplete: true } + }) + + expect(index.db.prepare('SELECT count(*) AS n FROM sessions').get()).toEqual({ + n: 0 + }) + expect(index.db.prepare('SELECT count(*) AS n FROM messages').get()).toEqual({ + n: 0 + }) + // No cursor, because nothing was read through. The row exists all the same: + // it is where the failure is counted, and a file that fails on its first read + // is exactly the one that has no row of its own to count on. + expect(cursor()).toBe(0) + expect(owed()).toMatchObject({ state: 'failed', fail_count: 1 }) +}) + +it('drops a file whose parser returned no session', async () => { + replayTranscriptRead({ + messages: userMessages('was indexed', 3), + outcome: { byteOffset: 100 } + }) + + replayTranscriptRead({ + messages: userMessages('now rejected', 2), + outcome: { session: null, byteOffset: 300 } + }) + + expect(index.db.prepare('SELECT count(*) AS n FROM sessions').get()).toEqual({ + n: 0 + }) + expect(index.db.prepare('SELECT count(*) AS n FROM messages').get()).toEqual({ + n: 0 + }) + // The file is still read through, so a later scan does not re-read it. + expect(cursor()).toBe(300) +}) + +it('writes nothing for a source whose parser cannot reach the channel', async () => { + // An OpenCode SQLite candidate decodes in a worker, so every read of it is + // incomplete, and no re-read would help. + const candidate = { + ...syntheticCandidate({ path: '/opencode/opencode.db#session-1' }), + agent: 'opencode' as const + } + replayTranscriptRead({ + candidate, + messages: [], + outcome: { byteOffset: 0, incomplete: true } + }) + + expect(index.db.prepare('SELECT count(*) AS n FROM sessions').get()).toEqual({ + n: 0 + }) + // No row at all, which is the record: the next pass reads a path the + // file table does not name. + expect(owed()).toBeUndefined() +}) + +it('ignores a candidate older than the retention cutoff', async () => { + store.setRetentionCutoffMs(Date.now()) + replayTranscriptRead({ messages: userMessages('too old', 3) }) + + expect(index.db.prepare('SELECT count(*) AS n FROM sessions').get()).toEqual({ + n: 0 + }) + // No row at all, which is the record: the next pass reads a path the + // file table does not name. + expect(owed()).toBeUndefined() +}) + +it('keeps the session list running when the index write fails', async () => { + replayTranscriptRead({ + messages: userMessages('healthy', 2), + outcome: { byteOffset: 100 } + }) + index.db.exec('DROP TABLE messages_fts') + + expect(() => + replayTranscriptRead({ + mode: 'append', + previousByteOffset: 100, + messages: userMessages('broken', 400), + outcome: { byteOffset: 500 } + }) + ).not.toThrow() + expect(errors.length).toBeGreaterThan(0) + expect(owed()?.state).not.toBe('current') +}) + +it('unregisters cleanly, leaving later reads unindexed', async () => { + resetTranscriptConsumersForTests() + replayTranscriptRead({ messages: userMessages('after unregister', 3) }) + + expect(index.db.prepare('SELECT count(*) AS n FROM sessions').get()).toEqual({ + n: 0 + }) +}) + +it('drops a removed source and keeps its cursor gone', async () => { + replayTranscriptRead({ + messages: userMessages('present', 3), + outcome: { byteOffset: 100 } + }) + store.removeFile(SYNTHETIC_TRANSCRIPT) + + expect(cursor()).toBeUndefined() + expect(index.db.prepare('SELECT count(*) AS n FROM sessions').get()).toEqual({ + n: 0 + }) + expect(index.db.prepare('SELECT count(*) AS n FROM messages').get()).toEqual({ + n: 0 + }) +}) + +it('writes the session metadata the read decoded', async () => { + replayTranscriptRead({ + messages: userMessages('metadata', 1), + outcome: { + session: syntheticSession({ + sessionId: 'abc-123', + title: 'a titled session', + cwd: '/repo/app', + branch: 'main', + messageCount: 1, + resumeCommand: 'claude --resume abc-123' + }), + byteOffset: 42 + } + }) + + expect( + index.db + .prepare('SELECT session_id, title, cwd, cwd_key, branch, resume_command FROM sessions') + .get() + ).toEqual({ + session_id: 'abc-123', + title: 'a titled session', + cwd: '/repo/app', + cwd_key: '/repo/app', + branch: 'main', + resume_command: 'claude --resume abc-123' + }) +}) + +it('keeps a proven file identity when a later read cannot stat it', async () => { + const withIdentity = syntheticCandidate({ dev: 1, ino: 10 }) + replayTranscriptRead({ + candidate: withIdentity, + messages: userMessages('first', 2), + outcome: { byteOffset: 100 } + }) + + // A host that cannot prove identity re-reads the same file. + replayTranscriptRead({ + candidate: syntheticCandidate(), + mode: 'append', + previousByteOffset: 100, + messages: userMessages('second', 2), + outcome: { byteOffset: 200 } + }) + expect(indexedMessages()).toBe(4) + + // The stored identity survived, so a rename-replace is still detectable. + replayTranscriptRead({ + candidate: syntheticCandidate({ dev: 1, ino: 99 }), + mode: 'append', + previousByteOffset: 200, + messages: userMessages('replacement', 2), + outcome: { byteOffset: 300 } + }) + + expect(indexedMessages()).toBe(4) + expect(cursor()).toBe(200) + expect(owed()?.state).not.toBe('current') +}) diff --git a/src/main/ai-vault-search/session-search-index-consumer.ts b/src/main/ai-vault-search/session-search-index-consumer.ts new file mode 100644 index 00000000000..a457ca5e7c3 --- /dev/null +++ b/src/main/ai-vault-search/session-search-index-consumer.ts @@ -0,0 +1,146 @@ +import { parserPublishesMessages } from '../ai-vault/session-scanner-agent-parser' +import { + registerTranscriptConsumer, + type TranscriptConsumer, + type TranscriptMessage, + type TranscriptReadConsumer, + type TranscriptReadOutcome, + type TranscriptReadStart +} from '../ai-vault/session-transcript-consumers' +import type { SessionFileCandidate } from '../ai-vault/session-scanner-types' +import { fileIdentity } from './session-search-file-cursor' +import type { SessionSearchFileWrite } from './session-search-index-writer' +import type { SessionSearchStore } from './session-search-store' + +/** + * The search index as a consumer of the transcript reader. + * + * It keeps its own cursor in the `files` table and never consults the parse + * cache: the two answer different questions and diverge the moment either + * declines a read. + * + * Every refusal leaves the cursor where it was and writes what the next pass + * needs on the row itself, because the row is the only thing that outlives this + * read. A declined append is `due`: the index is behind on a span no append + * reaches, so the file has to be read whole. A read that started and did not + * commit is `failed`, counted, and stamped with the stat it failed at, which is + * what stops an unreadable transcript being retried on every pass for ever. + */ +export class SessionSearchIndexConsumer implements TranscriptConsumer { + constructor(private readonly store: SessionSearchStore) {} + + beginRead(start: TranscriptReadStart): TranscriptReadConsumer | null { + const { candidate } = start + if (!parserPublishesMessages(candidate)) { + this.noteUnreachableParser(candidate) + return null + } + if (start.mode === 'append') { + const cursor = this.store.indexedFile(candidate.file.path, fileIdentity(candidate.file)) + if (!cursor || cursor.byteOffset !== start.previousByteOffset) { + // This index never saw the span before `previousByteOffset`; appending + // here would leave a hole no later read can fill. A null cursor is the + // file a chunked read left half written, which no offset continues. + // Either way the next pass has to read this file from the start. + this.store.setFileState(candidate.file.path, 'due') + return null + } + } + const write = this.store.beginWrite( + candidate, + start.mode, + start.previousByteOffset, + start.identity + ) + if (!write) { + // A closed store, a candidate outside the retention window, or a row that + // moved under this read. Only a row that exists has anything to record. + this.store.setFileState(candidate.file.path, 'due') + return null + } + return new SessionSearchReadConsumer(this.store, start, write) + } + + /** + * A source no read can ever index, recorded as one this index has seen. + * + * A parser that decodes where the message channel cannot reach it -- OpenCode's + * SQLite sessions today -- publishes nothing, so no read of it will ever + * commit a row. Leaving the file table silent about it is not free: the next + * pass sees a path the index holds nothing for, asks for a read, and asking + * over a warm cache drops the session list's own resume point. The sidebar's + * fold is thrown away and the whole database is decoded again, on every pass, + * for ever. + * + * The row written is the shape the store already has for a read that went + * through and decoded no session: cursor at the file's size, no session row. + * The decide step then skips it until its stat moves, and the retirement walk + * retires it like any other row when it goes. + */ + private noteUnreachableParser(candidate: SessionFileCandidate): void { + const write = this.store.beginWrite(candidate, 'replace', 0) + const committed = + write?.commit({ + session: null, + byteOffset: candidate.file.sizeBytes ?? 0, + incomplete: false + }) === true + if (committed) { + this.store.writeCommitted(candidate) + } + } +} + +class SessionSearchReadConsumer implements TranscriptReadConsumer { + private failed = false + + constructor( + private readonly store: SessionSearchStore, + private readonly start: TranscriptReadStart, + private readonly write: SessionSearchFileWrite + ) {} + + message(message: TranscriptMessage): void { + if (this.failed) { + return + } + try { + this.write.add(message) + } catch (error) { + // Never throws back into the reader: the channel would drop this consumer + // for the rest of the read and `finish` would never run. Failing here + // keeps the whole read on one path — the buffer is dropped and the file is + // re-read. + this.failed = true + this.store.reportWriteFailure(error) + } + } + + finish(outcome: TranscriptReadOutcome): void { + const { candidate } = this.start + let committed = false + try { + // An incomplete read's rows are not the whole span, so the cursor must not + // move past them; the file is re-read whole instead. + committed = !this.failed && !outcome.incomplete && this.write.commit(outcome) + } catch (error) { + this.store.reportWriteFailure(error) + } + if (committed) { + this.store.writeCommitted(candidate) + return + } + // Counted against the stat it failed at, not merely recorded: a transcript + // the reader cannot open fails identically on every pass, and only a change + // to this stat can mean the file itself changed. + this.store.setFileState(candidate.file.path, 'failed', candidate.file.mtimeMs) + } +} + +/** + * Registers the index with the reader and returns the unregister function. + * Nothing in production calls this yet: PR 3 owns when the index is live. + */ +export function registerSessionSearchIndexConsumer(store: SessionSearchStore): () => void { + return registerTranscriptConsumer(new SessionSearchIndexConsumer(store)) +} diff --git a/src/main/ai-vault-search/session-search-index-generation.test.ts b/src/main/ai-vault-search/session-search-index-generation.test.ts new file mode 100644 index 00000000000..f728759c0e4 --- /dev/null +++ b/src/main/ai-vault-search/session-search-index-generation.test.ts @@ -0,0 +1,329 @@ +import { appendFile, mkdtemp, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it } from 'vitest' +import { removeTree } from '../../shared/windows-transient-lock-removal' +import type SyncDatabase from '../sqlite/sync-database' +import { SessionSearchEngine } from './session-search-engine' +import { readIndexGeneration } from './session-search-index-generation' +import { registerSessionSearchIndexConsumer } from './session-search-index-consumer' +import { resetSessionParseCacheForTests } from '../ai-vault/session-scanner-parse-cache' +import { resetTranscriptConsumersForTests } from '../ai-vault/session-transcript-consumers' +import type { SessionSearchCursorError } from './session-search-page-cursor' +import { openSessionSearchDatabase } from './session-search-schema' +import { SessionSearchStore } from './session-search-store' +import { parseTranscript, userRecord } from './session-search-transcript-fixtures' + +let roots: string[] = [] +let handles: SyncDatabase[] = [] + +afterEach(async () => { + resetTranscriptConsumersForTests() + resetSessionParseCacheForTests() + for (const handle of handles) { + handle.close() + } + handles = [] + await Promise.all(roots.map((root) => removeTree(root))) + roots = [] +}) + +async function tempRoot(): Promise { + const root = await mkdtemp(join(tmpdir(), 'orca-search-generation-')) + roots.push(root) + return root +} + +/** + * A reader's own handle on the index, with the engine's schema installed. + * + * PR 2's store keeps its connection private, so a reader opens its own — which + * is what the fence has to survive: nothing this handle does moves the + * generation, and it must still see every writer's move. + */ +function reader(path: string): SyncDatabase { + const db = openSessionSearchDatabase(path) + handles.push(db) + // Constructing an engine is what installs the triggers. + new SessionSearchEngine(db) + return db +} + +/** Indexes one transcript through the real consumer and returns its path. */ +async function indexOneTranscript(root: string, store: SessionSearchStore): Promise { + resetSessionParseCacheForTests() + const sessionId = `aaaaaaaa-0000-4000-8000-${String(roots.length).padStart(12, '0')}` + const path = join(root, `${Math.random().toString(36).slice(2)}.jsonl`) + await writeFile(path, `${userRecord(0, 'generation fixture needle', sessionId)}\n`) + const unregister = registerSessionSearchIndexConsumer(store) + try { + await parseTranscript(path) + } finally { + unregister() + } + return path +} + +it('moves the generation forward when a committed read changes what a read returns', async () => { + const root = await tempRoot() + const path = join(root, 'index.sqlite') + const db = reader(path) + const store = new SessionSearchStore(path, (error) => { + throw error + }) + try { + const before = readIndexGeneration(db) + await indexOneTranscript(root, store) + expect(readIndexGeneration(db)).toBeGreaterThan(before) + } finally { + store.close() + } +}) + +it('moves the generation forward when an append adds rows to a live session', async () => { + // The first read of a file inserts its `files` row; every read after that + // updates it. An append changes a session's rank and its message count, so a + // cursor minted before it indexes into a list that no longer exists. + const root = await tempRoot() + const path = join(root, 'index.sqlite') + const db = reader(path) + const store = new SessionSearchStore(path, (error) => { + throw error + }) + try { + const transcript = await indexOneTranscript(root, store) + const indexed = readIndexGeneration(db) + const unregister = registerSessionSearchIndexConsumer(store) + try { + resetSessionParseCacheForTests() + await appendFile(transcript, `${userRecord(1, 'a second needle turn')}\n`) + await parseTranscript(transcript) + } finally { + unregister() + } + expect(db.prepare('SELECT COUNT(*) AS c FROM messages').get()).toEqual({ c: 2 }) + expect(readIndexGeneration(db)).toBeGreaterThan(indexed) + } finally { + store.close() + } +}) + +it('moves the generation forward when a proven deletion hides a session', async () => { + const root = await tempRoot() + const path = join(root, 'index.sqlite') + const db = reader(path) + const store = new SessionSearchStore(path, (error) => { + throw error + }) + try { + const transcript = await indexOneTranscript(root, store) + const indexed = readIndexGeneration(db) + store.removeFile(transcript) + expect(readIndexGeneration(db)).toBeGreaterThan(indexed) + } finally { + store.close() + } +}) + +it('moves the generation forward when retention cuts a session loose', async () => { + // Retention deletes the session row and the file row in one transaction, then + // reclaims the messages over many. It is the first half that changes what a + // search returns, and the first half that has to move the generation. + const root = await tempRoot() + const path = join(root, 'index.sqlite') + const db = reader(path) + const store = new SessionSearchStore(path, (error) => { + throw error + }) + try { + await indexOneTranscript(root, store) + const indexed = readIndexGeneration(db) + await store.purgeOlderThan(Date.now() + 60_000) + expect(db.prepare('SELECT COUNT(*) AS c FROM sessions').get()).toEqual({ c: 0 }) + expect(readIndexGeneration(db)).toBeGreaterThan(indexed) + } finally { + store.close() + } +}) + +it('moves the generation when a purge reclaims rows nothing can reach', async () => { + // The drain writes only `messages`, and for a while that was argued to change + // no answer. Retrieval never saw those rows; the typo repair's dictionary + // did, because `messages_vocab` is a view over the FTS b-tree and lists a + // term whether or not a reader can reach it. See + // `session-search-orphan-rows.test.ts` for the answer that moved. The price + // of fencing it is a cursor refused once per batch while a purge runs. + const root = await tempRoot() + const path = join(root, 'index.sqlite') + const db = reader(path) + const store = new SessionSearchStore(path, (error) => { + throw error + }) + try { + await indexOneTranscript(root, store) + // The shape an interrupted purge leaves: rows with no session row. + db.prepare('DELETE FROM sessions').run() + const orphaned = readIndexGeneration(db) + expect(db.prepare('SELECT COUNT(*) AS c FROM messages').get()).not.toEqual({ c: 0 }) + await store.purgeOlderThan(null) + expect(db.prepare('SELECT COUNT(*) AS c FROM messages').get()).toEqual({ c: 0 }) + expect(readIndexGeneration(db)).toBeGreaterThan(orphaned) + } finally { + store.close() + } +}) + +it("leaves the generation alone when a replace swaps a session's own rows", async () => { + // The same trigger must not fire here, or every re-read of a large transcript + // would move the generation once per deleted row on top of the one bump its + // file record already makes. A replace deletes rows whose session row still + // stands, which is what the trigger's `WHEN` clause tests. + const root = await tempRoot() + const path = join(root, 'index.sqlite') + const db = reader(path) + const store = new SessionSearchStore(path, (error) => { + throw error + }) + try { + await indexOneTranscript(root, store) + const rows = db.prepare('SELECT COUNT(*) AS c FROM messages').get() as { c: number } + const indexed = readIndexGeneration(db) + db.prepare('DELETE FROM messages WHERE session_row_id IN (SELECT id FROM sessions)').run() + expect(rows.c).toBeGreaterThan(0) + expect(readIndexGeneration(db)).toBe(indexed) + } finally { + store.close() + } +}) + +it('leaves the generation alone when a removal hides nothing', async () => { + // A backfill retires paths it never held; if that moved the generation, every + // cursor would be refused for as long as indexing ran. + const root = await tempRoot() + const path = join(root, 'index.sqlite') + const db = reader(path) + const store = new SessionSearchStore(path, (error) => { + throw error + }) + try { + await indexOneTranscript(root, store) + const before = readIndexGeneration(db) + store.removeFile('/synthetic/never-indexed.jsonl') + expect(readIndexGeneration(db)).toBe(before) + } finally { + store.close() + } +}) + +it('keeps the generation across a reopen, because the bump rides its own commit', async () => { + // The bump is inside the transaction that changes visibility, so nothing can + // be lost to a crash and reopening need not invalidate anyone's cursor. + const root = await tempRoot() + const path = join(root, 'index.sqlite') + reader(path) + const first = new SessionSearchStore(path, (error) => { + throw error + }) + await indexOneTranscript(root, first) + const indexed = readIndexGeneration(reader(path)) + first.close() + + const second = new SessionSearchStore(path) + try { + expect(readIndexGeneration(reader(path))).toBe(indexed) + } finally { + second.close() + } +}) + +it('fences a reader against a writer it does not share a process with', async () => { + // The shape PR 3 creates: the indexer writes from the scanner child while an + // engine reads elsewhere. A generation cached in the reader's memory tracks + // only that reader's own writes, so it would stand still through the + // writer's deletion, honour the stale cursor, and skip a session. + const root = await tempRoot() + const path = join(root, 'index.sqlite') + const db = reader(path) + const writer = new SessionSearchStore(path, (error) => { + throw error + }) + try { + const transcripts: string[] = [] + for (let n = 0; n < 3; n++) { + transcripts.push(await indexOneTranscript(root, writer)) + } + const engine = new SessionSearchEngine(db) + const page = engine.search({ query: 'needle', limit: 1 }) + expect(page.page.cursor).not.toBeNull() + + writer.removeFile(transcripts[0]!) + + // The reader never wrote anything, and must still refuse. + try { + engine.search({ query: 'needle', limit: 1, cursor: page.page.cursor! }) + expect.unreachable('a page cursor must not survive another writer moving the index') + } catch (error) { + expect((error as SessionSearchCursorError).rejection).toBe('stale-generation') + } + } finally { + writer.close() + } +}) + +it('re-creates a fence something dropped, on the next search', async () => { + // An index whose triggers are gone cannot move its generation, so every stale + // cursor would compare equal and be honoured against a list the caller never + // saw. The engine owns those triggers, so it puts them back. + const root = await tempRoot() + const path = join(root, 'index.sqlite') + const db = reader(path) + const store = new SessionSearchStore(path, (error) => { + throw error + }) + try { + const transcript = await indexOneTranscript(root, store) + const engine = new SessionSearchEngine(db) + db.exec('DROP TRIGGER search_generation_file_update') + engine.search({ query: 'needle' }) + + expect( + db + .prepare("SELECT name FROM sqlite_master WHERE type = 'trigger' AND name = ?") + .get('search_generation_file_update') + ).toEqual({ name: 'search_generation_file_update' }) + + // An UPDATE of the row that already exists, because that is the trigger + // this dropped: re-indexing a transcript also inserts and deletes, so it + // moves the generation whether or not the dropped one came back. + const restored = readIndexGeneration(db) + db.exec(`UPDATE files SET mtime_ms = mtime_ms + 1 WHERE path = '${transcript}'`) + expect(readIndexGeneration(db)).toBeGreaterThan(restored) + } finally { + store.close() + } +}) + +it('mints a distinct generation per change even when two handles write', async () => { + const root = await tempRoot() + const path = join(root, 'index.sqlite') + const db = reader(path) + const first = new SessionSearchStore(path, (error) => { + throw error + }) + const second = new SessionSearchStore(path, (error) => { + throw error + }) + try { + const seen: number[] = [readIndexGeneration(db)] + for (const store of [first, second, first, second]) { + await indexOneTranscript(root, store) + seen.push(readIndexGeneration(db)) + } + // Read-then-write from two connections would hand out one value twice. + expect(new Set(seen).size).toBe(seen.length) + expect([...seen].sort((left, right) => left - right)).toEqual(seen) + } finally { + second.close() + first.close() + } +}) diff --git a/src/main/ai-vault-search/session-search-index-generation.ts b/src/main/ai-vault-search/session-search-index-generation.ts new file mode 100644 index 00000000000..ee10eb0e295 --- /dev/null +++ b/src/main/ai-vault-search/session-search-index-generation.ts @@ -0,0 +1,42 @@ +import type SyncDatabase from '../sqlite/sync-database' + +const GENERATION_KEY = 'index_generation' + +export const SESSION_SEARCH_GENERATION_TRIGGERS = [ + 'search_generation_file_insert', + 'search_generation_file_update', + 'search_generation_file_delete', + 'search_generation_orphan_reclaim' +] as const + +const BUMP = `INSERT INTO meta(key, value) VALUES ('${GENERATION_KEY}', '1') + ON CONFLICT(key) DO UPDATE SET value = CAST(value AS INTEGER) + 1;` + +/** + * Triggers commit the generation with writes from any connection. + * Orphan reclamation also changes the vocabulary used for typo suggestions. + */ +export const SESSION_SEARCH_GENERATION_SQL = ` +CREATE TRIGGER IF NOT EXISTS search_generation_file_insert AFTER INSERT ON files BEGIN + ${BUMP} +END; +CREATE TRIGGER IF NOT EXISTS search_generation_file_update AFTER UPDATE ON files BEGIN + ${BUMP} +END; +CREATE TRIGGER IF NOT EXISTS search_generation_file_delete AFTER DELETE ON files BEGIN + ${BUMP} +END; +CREATE TRIGGER IF NOT EXISTS search_generation_orphan_reclaim AFTER DELETE ON messages +WHEN NOT EXISTS (SELECT 1 FROM sessions WHERE id = OLD.session_row_id) BEGIN + ${BUMP} +END; +` + +/** Read the committed generation on each check, including other processes' writes. */ +export function readIndexGeneration(db: SyncDatabase): number { + const row = db.prepare('SELECT value FROM meta WHERE key = ?').get(GENERATION_KEY) as + | { value: string } + | undefined + const parsed = row ? Number(row.value) : Number.NaN + return Number.isInteger(parsed) && parsed >= 0 ? parsed : 0 +} diff --git a/src/main/ai-vault-search/session-search-index-pass.test.ts b/src/main/ai-vault-search/session-search-index-pass.test.ts new file mode 100644 index 00000000000..c32eec59a96 --- /dev/null +++ b/src/main/ai-vault-search/session-search-index-pass.test.ts @@ -0,0 +1,194 @@ +import { appendFile, rm, stat, utimes } from 'node:fs/promises' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import { resetSessionParseCacheForTests } from '../ai-vault/session-scanner-parse-cache' +import { resetTranscriptConsumersForTests } from '../ai-vault/session-transcript-consumers' +import { registerSessionSearchIndexConsumer } from './session-search-index-consumer' +import { runSessionSearchIndexPass } from './session-search-index-pass' +import { parseTranscript } from './session-search-transcript-fixtures' +import { + claudeLines, + openSessionSearchIndexerHarness, + writeClaudeTranscript, + type SessionSearchIndexerHarness +} from './session-search-indexer-test-fixture' +import { discoverSessionSearchCandidates } from './session-search-scan-roots' +import { SessionSearchStore } from './session-search-store' + +const FIRST = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' +const SECOND = 'bbbbbbbb-cccc-4ddd-8eee-ffffffffffff' + +let harness: SessionSearchIndexerHarness +let store: SessionSearchStore +let errors: unknown[] + +beforeEach(async () => { + resetSessionParseCacheForTests() + resetTranscriptConsumersForTests() + errors = [] + harness = await openSessionSearchIndexerHarness('ss-index-pass') + await writeClaudeTranscript(transcript(FIRST), ['the first transcript'], FIRST) + await writeClaudeTranscript(transcript(SECOND), ['the second transcript'], SECOND) + store = openStore() +}) + +afterEach(async () => { + resetTranscriptConsumersForTests() + store.close() + await harness.cleanup() +}) + +function transcript(sessionId: string): string { + return join(harness.claudeProjectDir, `${sessionId}.jsonl`) +} + +function openStore(): SessionSearchStore { + const opened = new SessionSearchStore(harness.databasePath, (error) => errors.push(error)) + registerSessionSearchIndexConsumer(opened) + return opened +} + +async function candidates() { + return ( + await discoverSessionSearchCandidates(harness.roots, { + limitPerAgent: Number.POSITIVE_INFINITY + }) + ).candidates +} + +/** What a pass hands the read loop: the store's rows, read once. */ +function rows() { + return new Map(store.files().map((row) => [row.path, row])) +} + +function pass(options: { overdue?: () => boolean } = {}) { + return runSessionSearchIndexPass(store, [], { rows: rows(), ...options }) +} + +async function passOverAll(options: { overdue?: () => boolean } = {}) { + return runSessionSearchIndexPass(store, await candidates(), { rows: rows(), ...options }) +} + +function states(): Record { + return Object.fromEntries(store.files().map((row) => [row.path, row.state])) +} + +it('re-reads nothing it already holds, even with a cold session-list cache', async () => { + const first = await passOverAll() + expect(first.stats.fullParses).toBe(2) + + // A restart: the parse cache is gone, the index's `files` table is not. + store.close() + resetTranscriptConsumersForTests() + resetSessionParseCacheForTests() + store = openStore() + + const second = await passOverAll() + expect(second.stats).toMatchObject({ fullParses: 0, incremental: 0, reused: 0, bytesRead: 0 }) + expect(errors).toEqual([]) +}) + +it('resumes into a grown transcript instead of re-reading it whole', async () => { + await passOverAll() + await appendFile(transcript(FIRST), `${claudeLines(['a later turn'], FIRST, 10).join('\n')}\n`) + + const second = await passOverAll() + expect(second.stats).toMatchObject({ incremental: 1, fullParses: 0 }) +}) + +// Nothing is recorded about what a deadline cut off, because being owed is a +// fact about the row: the file is read on the next pass for the same reason it +// was owed on this one. +it('leaves what it ran out of time for owed, with nothing written down', async () => { + const all = await candidates() + const cut = await runSessionSearchIndexPass(store, all, { rows: rows(), overdue: () => true }) + + expect(cut.outOfTime).toBe(true) + expect(store.files()).toHaveLength(1) + const second = await passOverAll() + expect(second.stats.fullParses).toBe(1) + expect(store.files()).toHaveLength(2) +}) + +// The deadline is never applied before the pass has read anything, so a single +// transcript larger than one deadline is read alone rather than starved. +it('reads one file even when the deadline has already expired', async () => { + const only = (await candidates()).slice(0, 1) + const alone = await runSessionSearchIndexPass(store, only, { rows: rows(), overdue: () => true }) + + expect(alone.outOfTime).toBe(false) + expect(store.files()).toHaveLength(1) +}) + +it('skips a source the reader cannot even open without failing the pass', async () => { + const all = await candidates() + await rm(transcript(FIRST)) + await runSessionSearchIndexPass(store, all, { rows: rows() }) + + // One session indexed, and the missing one recorded as a failed read rather + // than as content the index holds. + expect(harness.read((db) => db.prepare('SELECT count(*) AS n FROM sessions').get())).toEqual({ + n: 1 + }) + expect(states()[transcript(FIRST)]).toBe('failed') +}) + +// Finding 6: mtime alone is not the freshness key. A transcript that grows +// while keeping its mtime (a same-second append, a restored timestamp) is a +// different file to the index, and reading only mtime would skip it forever. +it('re-reads a file that grew without its mtime moving', async () => { + const path = transcript(FIRST) + // A whole-millisecond stamp, so restoring it later reproduces it exactly. + const frozen = new Date(1_740_000_000_000) + await utimes(path, frozen, frozen) + await passOverAll() + + await appendFile(path, `${claudeLines(['a same-mtime append'], FIRST, 20).join('\n')}\n`) + await utimes(path, frozen, frozen) + expect((await stat(path)).mtimeMs).toBe(frozen.getTime()) + + const second = await passOverAll() + expect(second.stats.fullParses + second.stats.incremental).toBe(1) +}) + +// Finding 5: the decision reads the session list's cache and then changes it, +// so outside the per-path lane an overlapping list parse stores its entry in +// between and the forced read degrades into a reuse. +it('is not overtaken by a list parse racing the same path', async () => { + const path = transcript(FIRST) + const all = await candidates() + const only = all.filter((candidate) => candidate.file.path === path) + + // The list parses this path first, so its cursor covers the file, and again + // concurrently with the index's pass so the two interleave. + await parseTranscript(path) + await Promise.all([ + parseTranscript(path), + runSessionSearchIndexPass(store, only, { rows: rows() }) + ]) + + expect(harness.read((db) => db.prepare('SELECT count(*) AS n FROM sessions').get())).toEqual({ + n: 1 + }) +}) + +// Finding 4d: a declined read is a parse that returns normally and indexes +// nothing. It has to leave the row owing a read, not looking covered. +it('leaves a declined read owed rather than recorded as held', async () => { + const only = (await candidates()).slice(0, 1) + // What a store that refuses a write looks like from the consumer's side: the + // read runs, and nothing is written. + store.beginWrite = () => null + + const stats = await runSessionSearchIndexPass(store, only, { rows: rows() }) + + expect(stats.stats.fullParses).toBe(1) + expect(harness.read((db) => db.prepare('SELECT count(*) AS n FROM sessions').get())).toEqual({ + n: 0 + }) + expect(store.files()).toEqual([]) +}) + +it('reads nothing when there is nothing to read', async () => { + expect((await pass()).stats).toMatchObject({ fullParses: 0 }) +}) diff --git a/src/main/ai-vault-search/session-search-index-pass.ts b/src/main/ai-vault-search/session-search-index-pass.ts new file mode 100644 index 00000000000..05ccea1a314 --- /dev/null +++ b/src/main/ai-vault-search/session-search-index-pass.ts @@ -0,0 +1,84 @@ +import { throwIfAiVaultScanCancelled } from '../ai-vault/ai-vault-scan-cancellation' +import { + createSessionParseStats, + parseAgentSessionFileCached, + type SessionParseStats +} from '../ai-vault/session-scanner-parse-cache' +import type { SessionFileCandidate } from '../ai-vault/session-scanner-types' +import { fileIdentity } from './session-search-file-cursor' +import { sessionSearchReadDecision } from './session-search-read-decision' +import type { SessionSearchFileRow, SessionSearchStore } from './session-search-store' + +export type SessionSearchIndexPassOptions = { + signal?: AbortSignal + /** The store's rows for this pass, read once. Absent means the index holds nothing. */ + rows: ReadonlyMap + /** + * True once the pass has spent its wall-clock deadline. The one bound on how + * long a pass reads for: files and bytes are proxies for time, and the thing + * worth capping is the share of the wall clock an unasked background index + * takes. Never applied before the pass has read anything, so an oversized + * transcript is read alone rather than deferred for ever. + */ + overdue?: () => boolean +} + +/** + * Reads whatever the decide step says is owed, until the deadline. + * + * Nothing is recorded about what it did not reach. A candidate the deadline cut + * off is still owed on the next pass for the same reason it was owed on this + * one — its row says so — so there is no queue to keep, nothing to bound, and + * nothing to drop. What the reads themselves leave behind is written by the + * index consumer onto the rows. + */ +export async function runSessionSearchIndexPass( + store: SessionSearchStore, + candidates: readonly SessionFileCandidate[], + options: SessionSearchIndexPassOptions +): Promise<{ stats: SessionParseStats; outOfTime: boolean }> { + const stats = createSessionParseStats() + const cutoffMs = store.retentionCutoff + let read = 0 + let outOfTime = false + for (const candidate of candidates) { + throwIfAiVaultScanCancelled(options.signal) + const path = candidate.file.path + const row = options.rows.get(path) + const decision = sessionSearchReadDecision({ + candidate, + row, + // Only asked for a path the index holds something for; for the rest the + // decision is already made and this would be a query per new file. + cursor: row ? store.indexedFile(path, fileIdentity(candidate.file)) : null, + cutoffMs + }) + if (decision === 'skip') { + continue + } + // The decide step is one cursor lookup, so it runs for the whole list even + // once the deadline has gone: knowing what is owed costs nothing, and the + // count of what a pass left is worth more than the microseconds. + outOfTime ||= read > 0 && options.overdue?.() === true + if (outOfTime) { + continue + } + // The clock the deadline reads is one the owner may close behind: the read + // below writes to the store, so stop here rather than on a shut handle. + throwIfAiVaultScanCancelled(options.signal) + read += 1 + try { + await parseAgentSessionFileCached(candidate, process.platform, stats, decision) + } catch (error) { + throwIfAiVaultScanCancelled(options.signal) + // The reader reports a read it could not finish to the consumer, which is + // what records the failure on the row; nothing is counted here. + console.warn( + '[ai-vault-search] indexing skipped', + candidate.agent, + error instanceof Error ? error.name : 'ParseError' + ) + } + } + return { stats, outOfTime } +} diff --git a/src/main/ai-vault-search/session-search-index-test-fixture.ts b/src/main/ai-vault-search/session-search-index-test-fixture.ts new file mode 100644 index 00000000000..baa3e2976fe --- /dev/null +++ b/src/main/ai-vault-search/session-search-index-test-fixture.ts @@ -0,0 +1,124 @@ +import { mkdtemp } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { removeTree } from '../../shared/windows-transient-lock-removal' +import type { AiVaultSession } from '../../shared/ai-vault-types' +import type { SessionFileCandidate } from '../ai-vault/session-scanner-types' +import { TranscriptMessageChannel } from '../ai-vault/session-transcript-channel' +import type { + TranscriptMessage, + TranscriptReadOutcome, + TranscriptReadStart +} from '../ai-vault/session-transcript-consumers' +import type SyncDatabase from '../sqlite/sync-database' +import { openSessionSearchDatabase } from './session-search-schema' + +export const SYNTHETIC_TRANSCRIPT = 'synthetic-transcript' + +export function syntheticCandidate( + overrides: Partial = {} +): SessionFileCandidate { + const at = new Date(1740000000000) + return { + agent: 'claude', + codexHome: null, + file: { + path: SYNTHETIC_TRANSCRIPT, + mtimeMs: at.getTime(), + modifiedAt: at.toISOString(), + sizeBytes: 4096, + ...overrides + } + } +} + +export function syntheticSession(overrides: Partial = {}): AiVaultSession { + const at = new Date(1740000000000).toISOString() + return { + id: 'fixture', + executionHostId: 'local', + agent: 'claude', + sessionId: 'fixture', + title: 'fixture session', + cwd: '/fixture', + branch: null, + model: null, + filePath: SYNTHETIC_TRANSCRIPT, + codexHome: null, + createdAt: at, + updatedAt: at, + modifiedAt: at, + messageCount: 0, + totalTokens: 0, + previewMessages: [], + queuedMessageCount: 0, + subagentTranscriptCount: 0, + resumeCommand: '', + subagent: null, + ...overrides + } +} + +export function userMessages(text: string, count: number): TranscriptMessage[] { + return Array.from({ length: count }, (_unused, index) => ({ + role: 'user' as const, + text, + timestamp: new Date(1740000000000 + index * 1000).toISOString() + })) +} + +/** + * Drives one read through the real fan-out channel, so a test exercises the + * registration path the transcript reader uses rather than the consumer alone. + */ +export function replayTranscriptRead(args: { + candidate?: SessionFileCandidate + mode?: TranscriptReadStart['mode'] + previousByteOffset?: number + messages: TranscriptMessage[] + outcome?: Partial +}): void { + const candidate = args.candidate ?? syntheticCandidate() + const mode = args.mode ?? 'replace' + const channel = new TranscriptMessageChannel() + channel.beginRead({ + candidate, + mode, + previousByteOffset: args.previousByteOffset ?? 0 + }) + for (const message of args.messages) { + channel.push(message) + } + channel.finishRead({ + session: syntheticSession(), + byteOffset: 4096, + incomplete: false, + ...args.outcome + }) +} + +export type SessionSearchIndexFile = { + path: string + /** The store keeps its own connection private, so row assertions need this one. */ + db: SyncDatabase + close: () => Promise +} + +/** An on-disk index: `:memory:` is per-connection, so a second reader needs a real file. */ +export async function openSessionSearchIndexFile(name: string): Promise { + const root = await mkdtemp(join(tmpdir(), `${name}-`)) + const path = join(root, 'index.sqlite') + const db = openSessionSearchDatabase(path) + let open = true + return { + path, + db, + close: async () => { + if (open) { + open = false + db.close() + } + await removeTree(root) + } + } +} diff --git a/src/main/ai-vault-search/session-search-index-writer.test.ts b/src/main/ai-vault-search/session-search-index-writer.test.ts new file mode 100644 index 00000000000..1be12e35bc7 --- /dev/null +++ b/src/main/ai-vault-search/session-search-index-writer.test.ts @@ -0,0 +1,226 @@ +import { afterEach, beforeEach, expect, it } from 'vitest' +import { SessionSearchIndexConsumer } from './session-search-index-consumer' +import { + openSessionSearchIndexFile, + syntheticCandidate, + syntheticSession, + SYNTHETIC_TRANSCRIPT, + userMessages, + type SessionSearchIndexFile +} from './session-search-index-test-fixture' +import { SessionSearchStore } from './session-search-store' + +// The store is driven directly here. Every guard below is also shadowed by the +// consumer's own check, so a test that goes through the consumer proves nothing +// about which of the two is holding. + +let index: SessionSearchIndexFile +let store: SessionSearchStore +let errors: unknown[] + +beforeEach(async () => { + index = await openSessionSearchIndexFile('ss-index-writer') + errors = [] + store = new SessionSearchStore(index.path, (error) => errors.push(error)) +}) + +afterEach(async () => { + store.close() + await index.close() +}) + +function count(table: string): number { + return ( + index.db.prepare(`SELECT count(*) AS n FROM ${table}`).get() as { + n: number + } + ).n +} + +function indexRead(previousByteOffset: number, byteOffset: number, text: string): boolean { + const write = store.beginWrite( + syntheticCandidate(), + previousByteOffset === 0 ? 'replace' : 'append', + previousByteOffset + ) + if (!write) { + return false + } + for (const message of userMessages(text, 2)) { + write.add(message) + } + return write.commit({ + session: syntheticSession(), + byteOffset, + incomplete: false + }) +} + +it('refuses an append whose predecessor offset is not the committed cursor', () => { + expect(indexRead(0, 100, 'first')).toBe(true) + + expect(store.beginWrite(syntheticCandidate(), 'append', 900)).toBeNull() + expect(store.beginWrite(syntheticCandidate(), 'append', 99)).toBeNull() + // The one offset that does continue the committed span is accepted. + expect(store.beginWrite(syntheticCandidate(), 'append', 100)).not.toBeNull() +}) + +it('refuses to commit a write whose cursor moved underneath it', () => { + const stale = store.beginWrite(syntheticCandidate(), 'replace', 0)! + for (const message of userMessages('stalegeneration', 40)) { + stale.add(message) + } + // A second read of the same path finishes first. Without the parse file lane + // this is the overlap that would otherwise resurrect the stale rows. + expect(indexRead(0, 200, 'winninggeneration')).toBe(true) + + expect( + stale.commit({ + session: syntheticSession(), + byteOffset: 100, + incomplete: false + }) + ).toBe(false) + expect(store.indexedFile(SYNTHETIC_TRANSCRIPT, null)?.byteOffset).toBe(200) + expect(count('sessions')).toBe(1) + expect(count('messages')).toBe(2) + expect(errors).toEqual([]) +}) + +it('refuses to commit a write whose file was removed mid-read', () => { + expect(indexRead(0, 100, 'firstgeneration')).toBe(true) + const write = store.beginWrite(syntheticCandidate(), 'append', 100)! + for (const message of userMessages('afterremoval', 10)) { + write.add(message) + } + store.removeFile(SYNTHETIC_TRANSCRIPT) + + // Committing here would put a source back that its owner proved was deleted. + expect( + write.commit({ + session: syntheticSession(), + byteOffset: 300, + incomplete: false + }) + ).toBe(false) + expect(store.indexedFile(SYNTHETIC_TRANSCRIPT, null)).toBeNull() + expect(count('sessions')).toBe(0) + expect(count('messages')).toBe(0) + expect(count('files')).toBe(0) +}) + +it('declines a behind cursor in beginRead before it ever reaches the store', () => { + const attempted: number[] = [] + const stub = { + indexedFile: () => ({ byteOffset: 100, mtimeMs: 1, sizeBytes: 1 }), + beginWrite: (_candidate: unknown, _mode: unknown, previousByteOffset: number) => { + attempted.push(previousByteOffset) + return { add: () => undefined, commit: () => true } + }, + setFileState: () => undefined + } as unknown as SessionSearchStore + const consumer = new SessionSearchIndexConsumer(stub) + + expect( + consumer.beginRead({ + candidate: syntheticCandidate(), + mode: 'append', + previousByteOffset: 900 + }) + ).toBeNull() + // The store was never asked, so the writer's own guard cannot be what refused. + expect(attempted).toEqual([]) + expect( + consumer.beginRead({ + candidate: syntheticCandidate(), + mode: 'append', + previousByteOffset: 100 + }) + ).not.toBeNull() + expect(attempted).toEqual([100]) +}) + +it("hands the read's identity accessor to the store", () => { + const captured: unknown[] = [] + const stub = { + indexedFile: () => null, + beginWrite: ( + _candidate: unknown, + _mode: unknown, + _previousByteOffset: unknown, + identity: unknown + ) => { + captured.push(identity) + return { add: () => undefined, commit: () => true } + }, + setFileState: () => undefined + } as unknown as SessionSearchStore + const identity = (): null => null + + new SessionSearchIndexConsumer(stub).beginRead({ + candidate: syntheticCandidate(), + mode: 'replace', + previousByteOffset: 0, + identity + }) + + // Dropped here, a chunked read writes rows under a session with no id and no + // cwd for as long as the read lasts, and for ever if it crashes first. + expect(captured).toEqual([identity]) +}) + +it('treats half a recorded identity as no identity at all', () => { + // New partial observations are not stored as identities. + const partial = { + ...syntheticCandidate({ dev: 7 }), + agent: 'claude' as const + } + const write = store.beginWrite(partial, 'replace', 0)! + for (const message of userMessages('halfidentity', 2)) { + write.add(message) + } + write.commit({ + session: syntheticSession(), + byteOffset: 100, + incomplete: false + }) + expect(index.db.prepare('SELECT dev, ino FROM files').get()).toEqual({ + dev: null, + ino: null + }) + // Older indexes may still carry a half-pair. + index.db.exec('UPDATE files SET dev = 7') + + // One matching number is not proof of sameness, and one mismatching number is + // not proof of replacement. Neither compares, so neither declines. + expect(store.indexedFile(SYNTHETIC_TRANSCRIPT, { dev: 7, ino: 99 })?.byteOffset).toBe(100) + expect(store.indexedFile(SYNTHETIC_TRANSCRIPT, { dev: 8, ino: 99 })?.byteOffset).toBe(100) + expect(store.beginWrite(syntheticCandidate({ dev: 8, ino: 99 }), 'append', 100)).not.toBeNull() +}) + +it.each([ + [null, { dev: null, ino: null }], + [ + { dev: 7, ino: 11 }, + { dev: 7, ino: 11 } + ] +])('never combines partial stats with the previous identity %j', (initial, expected) => { + const observations = [initial ?? {}, { dev: 9 }, { ino: 13 }, { dev: 17, ino: 19 }] + for (const [position, identity] of observations.entries()) { + const write = store.beginWrite( + syntheticCandidate(identity), + position ? 'append' : 'replace', + position * 100 + )! + expect( + write.commit({ + session: syntheticSession(), + byteOffset: (position + 1) * 100, + incomplete: false + }) + ).toBe(true) + expect(index.db.prepare('SELECT dev, ino FROM files').get()).toEqual( + position === 3 ? { dev: 17, ino: 19 } : expected + ) + } +}) diff --git a/src/main/ai-vault-search/session-search-index-writer.ts b/src/main/ai-vault-search/session-search-index-writer.ts new file mode 100644 index 00000000000..a5c981b5bb2 --- /dev/null +++ b/src/main/ai-vault-search/session-search-index-writer.ts @@ -0,0 +1,359 @@ +import type SyncDatabase from '../sqlite/sync-database' +import type { SessionFileCandidate } from '../ai-vault/session-scanner-types' +import type { + TranscriptMessage, + TranscriptReadOutcome, + TranscriptSessionIdentity +} from '../ai-vault/session-transcript-consumers' +import { EMPTY_CONTENT_HASH, foldContentHash } from './session-search-content-hash' +import type { + SessionSearchFileIdentity, + SessionSearchIndexedFile +} from './session-search-file-cursor' +import { SessionSearchFileRecords } from './session-search-file-records' +import { + deleteSearchMessages, + insertSearchMessage, + searchMessageRows +} from './session-search-message-rows' + +/** + * How much decoded text one transaction may carry. + * + * A file's rows are buffered in memory and written in one transaction, so the + * whole read is either in the index or not. The ceiling is what keeps that + * promise affordable: at the measured 26 MB of transcript per second it caps a + * single commit near a second and the WAL it produces near 64 MB, and it is far + * above the largest real transcript (the 40-session benchmark corpus is 10.5 MB + * in total), so an ordinary file never reaches it. Above the ceiling the read is + * cut into chunks that each leave the index consistent — but only a read that + * can name its session chunks at all. See `add`. + */ +export const SESSION_SEARCH_COMMIT_CHARS = 32 * 1024 * 1024 + +/** + * The cursor of a file whose rows are a prefix, written by a chunk of a read + * that has not reached the end of the file. + * + * The reader hands out byte offsets only when a read finishes, so a chunk has + * no honest offset to record. This one is unusable on purpose: `indexedFile` + * reports no cursor for it, so an append is declined and the file is re-read + * whole. The rows are still a coherent prefix of that session and answer + * searches until the re-read replaces them. + */ +const PARTIAL_FILE_CURSOR = -1 + +type FileRow = { + dev: number | null + ino: number | null + byte_offset: number + mtime_ms: number + size_bytes: number | null + session_row_id: number | null +} + +type FileCursor = Pick + +export type SessionSearchFileWrite = { + /** + * Buffers one message, committing a chunk when the buffer reaches the ceiling + * — and only while this read can name the session it is writing. + * + * A chunk's rows answer searches the moment they land, so a read with no + * `identity` would publish them under a session with an empty id, an empty + * title and a null cwd, and an interrupted read would leave that prefix + * behind for good. The readers that supply no identity are the whole-file + * ones (Grok, Cursor, Gemini, OpenCode), whose formats are rewritten in place + * and have no resumable state to ask; they are also small — the largest on + * the author's machine is 5 MB — so buffering one to the end and committing + * it whole costs nothing. Chunking stays reserved for the readers that can + * say which session this is before the read ends. + */ + add(message: TranscriptMessage): void + /** + * Writes this file's rows, its session and its cursor in one transaction. + * False when the file's record changed under this read — it was removed, or + * another writer moved the cursor these rows continue from. A read that never + * calls this leaves the index exactly as it found it, unless it chunked. + */ + commit(outcome: TranscriptReadOutcome): boolean +} + +export class SessionSearchIndexWriter { + private readonly records: SessionSearchFileRecords + // Removals per path, so a write can prove its source was not dropped under it + // rather than infer it from the cursor. In memory is enough: one process owns + // the index, and a removal only has to fence writes this process opened. + private readonly removals = new Map() + + constructor( + private readonly db: SyncDatabase, + private readonly commitChars: number = SESSION_SEARCH_COMMIT_CHARS, + /** + * Called after a transaction that left a session's messages with no session + * row, so the owner can start the bounded drain that reclaims them. + * Synchronous work here would put the cost back where it was taken from. + */ + private readonly onOrphanedRows: () => void = () => undefined + ) { + this.records = new SessionSearchFileRecords(db) + } + + /** + * What the index holds for this file, or null when it holds nothing usable: + * an unknown path, or one whose recorded identity no longer matches. + * + * A file a chunked read left half written is reported, with a null cursor. + * Reporting nothing for it would read as "never indexed", so the caller would + * ask for whatever read the parse cache offers, the reader would pick append, + * and the decline would be the only thing that ever forced the whole read. + */ + indexedFile(path: string, identity: SessionSearchFileIdentity): SessionSearchIndexedFile | null { + const row = this.db + .prepare( + 'SELECT dev, ino, byte_offset, mtime_ms, size_bytes, session_row_id FROM files WHERE path = ?' + ) + .get(path) as FileRow | undefined + if (!row) { + return null + } + // Older indexes can carry half-pairs; only a complete identity can prove replacement. + if (identity && row.dev !== null && row.ino !== null) { + if (row.dev !== identity.dev || row.ino !== identity.ino) { + return null + } + } + return { + byteOffset: row.byte_offset === PARTIAL_FILE_CURSOR ? null : row.byte_offset, + mtimeMs: row.mtime_ms, + sizeBytes: row.size_bytes + } + } + + /** + * Opens a buffered write for one read, or returns null when the read cannot + * extend what the index holds: an `append` whose predecessor byte offset is + * not this index's own cursor covers a span the index never saw. + */ + beginWrite( + candidate: SessionFileCandidate, + mode: 'replace' | 'append', + previousByteOffset: number, + identity?: () => TranscriptSessionIdentity | null + ): SessionSearchFileWrite | null { + const path = candidate.file.path + const cursor = this.cursor(path) + if (mode === 'append') { + // The partial sentinel is not a byte offset, so nothing continues it — + // including a caller that reads it back off the row and passes it in. + if (cursor === undefined || cursor.byte_offset === PARTIAL_FILE_CURSOR) { + return null + } + if (cursor.byte_offset !== previousByteOffset) { + return null + } + } + // A file the index read through and decoded no session from still has a + // cursor worth continuing: it has no session row to hang new rows off, so + // this read makes one. Declining instead would force a whole re-read of + // that file on every pass for as long as it grows. + return this.buffered(candidate, cursor, mode === 'append', identity) + } + + /** + * Drops a source: its session, its rows and its file record, in one + * transaction. Unbounded on purpose — the caller has proven this one file is + * gone and expects it out of results when the call returns, and a read of it + * that is still in flight is fenced by the cursor its commit re-reads. + */ + removeFile(path: string): void { + this.removals.set(path, (this.removals.get(path) ?? 0) + 1) + const cursor = this.cursor(path) + this.db.exec('BEGIN IMMEDIATE') + try { + this.dropSession(cursor?.session_row_id ?? null) + this.db.prepare('DELETE FROM files WHERE path = ?').run(path) + this.db.exec('COMMIT') + } catch (error) { + this.db.exec('ROLLBACK') + throw error + } + } + + private cursor(path: string): FileCursor | undefined { + return this.db + .prepare('SELECT session_row_id,byte_offset FROM files WHERE path = ?') + .get(path) as FileCursor | undefined + } + + private buffered( + candidate: SessionFileCandidate, + opened: FileCursor | undefined, + append: boolean, + identity?: () => TranscriptSessionIdentity | null + ): SessionSearchFileWrite { + const db = this.db + const path = candidate.file.path + const buffer: TranscriptMessage[] = [] + let bufferedChars = 0 + // What this write believes the file record holds. Re-read inside every + // transaction: a `removeFile` or another writer between two chunks means + // these rows no longer continue anything, and committing on top of that + // would resurrect a deleted source or duplicate a span. + let expected = opened + const removalsAtStart = this.removals.get(path) ?? 0 + // The session row is reused across re-reads of one file, so a `replace` + // swaps a session's rows rather than minting a second generation of it. + let session = opened?.session_row_id ?? null + let hash = append && session !== null ? this.records.contentHash(session) : EMPTY_CONTENT_HASH + // A replace owns the session's whole row set, so the old generation goes in + // the same transaction as the first of the new one. Chunk two onwards must + // not repeat it. + // + // It goes by being cut loose, not by being deleted. Deleting every old row + // inline sizes the transaction by the session being replaced rather than by + // the chunk being written: 1,286 ms against 720 ms fresh on the 100 MB + // corpus, and it grows with the history. Instead the first transaction + // mints a new session row, points `files` at it and deletes the one old + // `sessions` row. Every retrieval joins `sessions`, so the old generation + // stops answering the moment that commits, and its messages are reclaimed + // afterwards by the same bounded drain retention uses — which is where the + // old rows would have ended up had the process died here anyway. + // `sessions.id` is AUTOINCREMENT, so the freed id is never handed to + // another session while those rows still name it (round 8). + let replaced = append + // Set by the transaction that cut a generation loose; read once it commits. + let orphaned = false + // Set when the file record moved under this read. Nothing this write holds + // can land after that, so it stops buffering rather than reopening a + // transaction it already knows will roll back, once per remaining message. + let fenced = false + + // Why a counter and not the cursor alone: on a path this index never wrote, + // `expected` and the absent row are both undefined, so the cursor compare + // reads a removal as no change and the write recreates the source. + const current = (): boolean => { + if ((this.removals.get(path) ?? 0) !== removalsAtStart) { + return false + } + const row = this.cursor(path) + return ( + row?.session_row_id === expected?.session_row_id && + row?.byte_offset === expected?.byte_offset + ) + } + + /** + * `outcome` is null for a chunk of a read that has not reached the file's + * end, and `named` is what that chunk writes onto its session row. + */ + const write = ( + outcome: TranscriptReadOutcome | null, + named: TranscriptSessionIdentity | null + ): boolean => { + const decoded = outcome?.session ?? null + db.exec('BEGIN IMMEDIATE') + try { + if (!current()) { + db.exec('ROLLBACK') + return false + } + if (outcome && !decoded) { + // Read through, but nothing to search: the cursor advances so the file + // is not re-read whole on every pass, and whatever generation was here + // — including this read's own committed chunks — goes with it. + this.dropSession(session) + session = null + this.records.upsertFile(candidate, outcome.byteOffset, null) + } else { + if (replaced) { + session ??= this.records.createSessionRow(candidate) + } else { + const previous = session + session = this.records.createSessionRow(candidate) + if (previous !== null) { + db.prepare('DELETE FROM sessions WHERE id = ?').run(previous) + orphaned = true + } + replaced = true + } + for (const row of buffer) { + insertSearchMessage(db, session, row) + } + if (decoded) { + this.records.updateSession(decoded, session, hash) + } else if (named) { + // A chunk's rows answer searches as soon as they land, so the + // session they hang off is written with whatever the parser has + // decoded rather than left empty until a read that may never end. + // `add` refuses to chunk without this, so it is never absent here. + this.records.updateProvisionalSession(session, named) + } + this.records.upsertFile( + candidate, + outcome ? outcome.byteOffset : PARTIAL_FILE_CURSOR, + session + ) + } + db.exec('COMMIT') + } catch (error) { + db.exec('ROLLBACK') + throw error + } + // After the transaction that cut them loose is durable, never before: a + // rollback leaves the old session row standing and nothing to reclaim. + if (orphaned) { + orphaned = false + this.onOrphanedRows() + } + expected = { + session_row_id: session, + byte_offset: outcome ? outcome.byteOffset : PARTIAL_FILE_CURSOR + } + buffer.length = 0 + bufferedChars = 0 + return true + } + + return { + add: (message) => { + if (fenced) { + return + } + hash = foldContentHash(hash, [message]) + // The ceiling is checked per row, not per message: one message is a whole + // conversation turn and may be megabytes, so checking it after the whole + // message had been buffered let a single one carry a transaction as far + // past the ceiling as it was large. + for (const row of searchMessageRows([message])) { + buffer.push(row) + bufferedChars += row.text.length + if (bufferedChars < this.commitChars) { + continue + } + // Publishing a chunk under a session nothing can identify is worse + // than holding the buffer: the rows answer searches at once, and an + // interrupted read leaves that prefix for good. A read with nothing + // to name it keeps buffering and commits whole at `finish`. + const named = identity?.() ?? null + if (named && !write(null, named)) { + fenced = true + buffer.length = 0 + bufferedChars = 0 + return + } + } + }, + commit: (outcome) => !fenced && write(outcome, null) + } + } + + /** Caller's transaction: drops a session and every row that hangs off it. */ + private dropSession(sessionRowId: number | null): void { + if (sessionRowId === null) { + return + } + deleteSearchMessages(this.db, sessionRowId) + this.db.prepare('DELETE FROM sessions WHERE id = ?').run(sessionRowId) + } +} diff --git a/src/main/ai-vault-search/session-search-indexer-options.ts b/src/main/ai-vault-search/session-search-indexer-options.ts new file mode 100644 index 00000000000..08eb4aeb2af --- /dev/null +++ b/src/main/ai-vault-search/session-search-indexer-options.ts @@ -0,0 +1,49 @@ +import type { SessionSearchClock } from './session-search-clock' +import type { SessionSearchScanRoots } from './session-search-scan-roots' + +/** Default cycle. Long enough that a machine with thousands of transcripts is + * not re-statting continuously, short enough that a live conversation shows up + * while the user is still in it. */ +export const DEFAULT_SESSION_SEARCH_RECONCILE_INTERVAL_MS = 20_000 +/** Newest-N per agent root: the same recency rule the session sidebar applies. */ +export const DEFAULT_SESSION_SEARCH_RECENT_PER_AGENT = 12 +/** + * A quarter of the interval: the only bound on how long one pass reads for. + * + * The timer re-arms after a pass settles, so a pass that spends its whole + * deadline is followed by a full interval of quiet — five seconds of reading in + * every twenty-five, a fifth of the wall clock, and the stated ceiling is a + * quarter. Files the deadline cut off go back on the queue at full speed rather + * than being read slowly, which is what a load-average back-off did instead. + */ +export const DEFAULT_SESSION_SEARCH_PASS_DEADLINE_FRACTION = 4 +/** + * Cycles between whole-machine sweeps: five minutes at the default interval. + * + * A sweep is the only pass that sees a file nothing has told the indexer about + * — an old transcript deleted, a root that came back, a tree restored from a + * backup — so the cadence is what replaces every re-arm-on-recovery rule. A + * warm sweep is stats and readdirs, not reads, because the pass skips anything + * the index already covers at its current stat. + */ +export const DEFAULT_SESSION_SEARCH_FULL_SWEEP_EVERY_CYCLES = 15 + +/** + * Everything an indexer is. Immutable after construction: a settings change is + * `close()` and a new instance, which is also how the index is thrown away + * (`close()`, `removeSessionSearchDatabase(databasePath)`, construct again). + */ +export type SessionSearchIndexerOptions = { + databasePath: string + roots: SessionSearchScanRoots + /** null = all history; otherwise only transcripts modified within this many days. */ + historyDays: number | null + clock?: SessionSearchClock + reconcileIntervalMs?: number + recentPerAgent?: number + /** Wall time one pass may read for; the rest goes back on the queue. */ + passDeadlineMs?: number + /** Cycles between whole-machine sweeps. */ + fullSweepEveryCycles?: number + onError?: (error: unknown) => void +} diff --git a/src/main/ai-vault-search/session-search-indexer-test-fixture.ts b/src/main/ai-vault-search/session-search-indexer-test-fixture.ts new file mode 100644 index 00000000000..f8510510807 --- /dev/null +++ b/src/main/ai-vault-search/session-search-indexer-test-fixture.ts @@ -0,0 +1,168 @@ +import { mkdir, mkdtemp, rename, rm, stat, utimes, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import SyncDatabase from '../sqlite/sync-database' +import { isolatedScanRoots } from '../ai-vault/session-scanner-test-fixtures' +import type { SessionSearchClock, SessionSearchTimerHandle } from './session-search-clock' +import type { SessionSearchScanRoots } from './session-search-scan-roots' +import { assistantRecord, userRecord } from './session-search-transcript-fixtures' + +const CLOCK_EPOCH_MS = 1_740_000_000_000 + +/** Wall time the indexer's guarantee is stated in, under the test's control. */ +export class FakeSessionSearchClock implements SessionSearchClock { + private time = CLOCK_EPOCH_MS + private nextId = 1 + private nowCalls = 0 + private readonly timers = new Map void }>() + + /** + * What each `now()` reading costs. A pass reads the clock once per file it is + * about to read, so this is how a test spends a pass's deadline without + * waiting: it is the wall time the reads themselves take. + */ + costPerNowMs = 0 + + /** + * Runs on every `now()`, with the call number. The only synchronous seam into + * a running pass: the deadline check is what a pass consults between files. + */ + onNow: ((call: number) => void) | null = null + + now(): number { + const at = this.time + this.time += this.costPerNowMs + this.onNow?.(++this.nowCalls) + return at + } + + setTimeout(callback: () => void, ms: number): SessionSearchTimerHandle { + const id = this.nextId++ + this.timers.set(id, { at: this.time + ms, callback }) + return id + } + + clearTimeout(handle: SessionSearchTimerHandle): void { + this.timers.delete(handle as number) + } + + /** Moves time forward and fires every timer that came due, in order. */ + advance(ms: number): void { + this.time += ms + for (const [id, timer] of [...this.timers].sort((left, right) => left[1].at - right[1].at)) { + if (timer.at <= this.time) { + this.timers.delete(id) + timer.callback() + } + } + } + + get pendingTimers(): number { + return this.timers.size + } +} + +export type SessionSearchIndexerHarness = { + root: string + databasePath: string + roots: SessionSearchScanRoots + claudeProjectDir: string + /** A second connection: the store keeps its own private. */ + read: (query: (db: SyncDatabase) => T) => T + /** Plants what a killed writer would have left; nothing in the app writes here. */ + write: (query: (db: SyncDatabase) => T) => T + cleanup: () => Promise +} + +export async function openSessionSearchIndexerHarness( + name: string +): Promise { + const root = await mkdtemp(join(tmpdir(), `${name}-`)) + const roots = isolatedScanRoots(root) + const databasePath = join(root, 'index', 'index.sqlite') + return { + root, + databasePath, + roots, + claudeProjectDir: join(roots.claudeProjectsDir, 'project'), + read: (query) => withConnection(databasePath, true, query), + write: (query) => withConnection(databasePath, false, query), + cleanup: () => rm(root, { recursive: true, force: true }) + } +} + +function withConnection( + path: string, + readonlyConnection: boolean, + query: (db: SyncDatabase) => T +): T { + const db = new SyncDatabase(path, { readonly: readonlyConnection }) + try { + return query(db) + } finally { + db.close() + } +} + +/** A native-chat-shaped Claude transcript: the same records the app itself writes. */ +export async function writeClaudeTranscript( + path: string, + turns: readonly string[], + sessionId: string +): Promise { + await mkdir(dirname(path), { recursive: true }) + await writeFile(path, `${claudeLines(turns, sessionId, 0).join('\n')}\n`) +} + +export function claudeLines( + turns: readonly string[], + sessionId: string, + startIndex: number +): string[] { + return turns.flatMap((turn, offset) => [ + userRecord(startIndex + offset * 2, turn, sessionId), + assistantRecord(startIndex + offset * 2 + 1, `noted: ${turn}`, sessionId) + ]) +} + +/** + * Replaces a transcript the way an editor or a sync client does: a new inode + * renamed over the old name. Same byte length on purpose, so the only thing + * that can tell the two files apart is their filesystem identity. + */ +export async function renameReplaceTranscript( + path: string, + turns: readonly string[], + sessionId: string +): Promise { + const before = await stat(path) + const replacement = `${path}.replacement` + await writeClaudeTranscript(replacement, turns, sessionId) + await rename(replacement, path) + const later = new Date(before.mtimeMs + 5_000) + await utimes(path, later, later) +} + +/** + * A message-graph transcript, the shape OpenClaw, Pi, OMP and Prime Agent + * write. The session id comes from the file name, so callers name the file. + */ +export async function writeMessageGraphTranscript( + path: string, + turns: readonly string[] +): Promise { + await mkdir(dirname(path), { recursive: true }) + const lines = turns.flatMap((turn, index) => [ + JSON.stringify({ + type: 'message', + timestamp: new Date(CLOCK_EPOCH_MS + index * 120_000).toISOString(), + message: { role: 'user', content: turn } + }), + JSON.stringify({ + type: 'message', + timestamp: new Date(CLOCK_EPOCH_MS + index * 120_000 + 60_000).toISOString(), + message: { role: 'assistant', content: `noted: ${turn}` } + }) + ]) + await writeFile(path, `${lines.join('\n')}\n`) +} diff --git a/src/main/ai-vault-search/session-search-indexer.test.ts b/src/main/ai-vault-search/session-search-indexer.test.ts new file mode 100644 index 00000000000..5985628ba2d --- /dev/null +++ b/src/main/ai-vault-search/session-search-indexer.test.ts @@ -0,0 +1,1090 @@ +import { existsSync, mkdirSync, rmSync, utimesSync, writeFileSync } from 'node:fs' +import { appendFile, chmod, mkdir, rm, stat, utimes } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import { resetSessionParseCacheForTests } from '../ai-vault/session-scanner-parse-cache' +import { resetTranscriptConsumersForTests } from '../ai-vault/session-transcript-consumers' +import type SyncDatabase from '../sqlite/sync-database' +import { SessionSearchIndexer } from './session-search-indexer' +import { removeSessionSearchDatabase } from './session-search-schema' +import { parseTranscript } from './session-search-transcript-fixtures' +import { + claudeLines, + FakeSessionSearchClock, + openSessionSearchIndexerHarness, + renameReplaceTranscript, + writeClaudeTranscript, + type SessionSearchIndexerHarness +} from './session-search-indexer-test-fixture' + +const INTERVAL_MS = 20_000 +// chmod cannot deny root, and Windows ignores the mode bits entirely, so the +// two refusal tests would assert on an unreached branch there. +const CAN_DENY_READ = process.platform !== 'win32' && process.getuid?.() !== 0 +const SESSION_ID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' +const OTHER_SESSION_ID = 'bbbbbbbb-cccc-4ddd-8eee-ffffffffffff' +const SETTLED_SESSION_ID = 'dddddddd-cccc-4ddd-8eee-ffffffffffff' + +let harness: SessionSearchIndexerHarness +let clock: FakeSessionSearchClock +let indexer: SessionSearchIndexer | null +let errors: unknown[] + +beforeEach(async () => { + resetSessionParseCacheForTests() + resetTranscriptConsumersForTests() + errors = [] + clock = new FakeSessionSearchClock() + harness = await openSessionSearchIndexerHarness('ss-indexer') + indexer = null +}) + +afterEach(async () => { + indexer?.close() + resetTranscriptConsumersForTests() + resetSessionParseCacheForTests() + await harness.cleanup() +}) + +function newIndexer( + overrides: Partial[0]> = {} +) { + indexer = new SessionSearchIndexer({ + databasePath: harness.databasePath, + roots: harness.roots, + historyDays: null, + clock, + reconcileIntervalMs: INTERVAL_MS, + onError: (error) => errors.push(error), + ...overrides + }) + return indexer +} + +/** Sessions a published-view read returns for one term, the only legal shape. */ +function sessionsMatching(term: string): string[] { + return harness.read((db: SyncDatabase) => + ( + db + .prepare( + `SELECT DISTINCT s.session_id AS id FROM messages_fts + JOIN messages m ON m.id = messages_fts.rowid + JOIN sessions s ON s.id = m.session_row_id + WHERE messages_fts MATCH ? ORDER BY s.session_id` + ) + .all(term) as { id: string }[] + ).map((row) => row.id) + ) +} + +function indexedSessionCount(): number { + return harness.read( + (db: SyncDatabase) => + (db.prepare('SELECT count(*) AS n FROM sessions').get() as { n: number }).n + ) +} + +/** The row the store holds for a path, which is the indexer's whole memory of it. */ +function rowFor(path: string) { + return harness.read((db: SyncDatabase) => + db.prepare('SELECT state, fail_count AS failCount FROM files WHERE path = ?').get(path) + ) as { state: string; failCount: number } | undefined +} + +function fileState(path: string): string | undefined { + return rowFor(path)?.state +} + +/** The byte offset the index recorded; PR 2 stores -1 for a half-written file. */ +function indexedByteOffset(path: string): number | undefined { + return harness.read( + (db: SyncDatabase) => + ( + db.prepare('SELECT byte_offset AS offset FROM files WHERE path = ?').get(path) as + | { offset: number } + | undefined + )?.offset + ) +} + +/** What a chunk of a read that never finished leaves on the file row. */ +function plantPartialCursor(path: string): void { + harness.write((db: SyncDatabase) => + db.prepare('UPDATE files SET byte_offset = -1 WHERE path = ?').run(path) + ) +} + +function indexedCursor(path: string): { mtime_ms: number; size_bytes: number } | undefined { + return harness.read( + (db: SyncDatabase) => + db.prepare('SELECT mtime_ms, size_bytes FROM files WHERE path = ?').get(path) as + | { mtime_ms: number; size_bytes: number } + | undefined + ) +} + +function transcriptPath(name = SESSION_ID): string { + return join(harness.claudeProjectDir, `${name}.jsonl`) +} + +/** + * Starts the indexer over a root that already holds one indexed transcript, so + * the opening sweep is behind us and `reconcile()` runs a cycle. It is dated + * ahead of everything the caller writes afterwards, so it stays inside any + * recency window and is skipped rather than read. + */ +async function startAfterASweep( + overrides: Partial[0]> = {} +): Promise { + const settled = transcriptPath(SETTLED_SESSION_ID) + await writeClaudeTranscript(settled, ['a conversation from before'], SETTLED_SESSION_ID) + // Wall time, not the fake clock: recency is decided by real file mtimes. + const ahead = new Date(Date.now() + 3_600_000) + await utimes(settled, ahead, ahead) + await newIndexer(overrides).start() +} + +/** + * Makes every pass stop after `files` reads: the pass consults the clock once + * per file it is about to read, and each reading costs a quarter of the + * deadline it is measured against. + */ +function readsPerPass(files: number): { passDeadlineMs: number } { + clock.costPerNowMs = 1_000 + return { passDeadlineMs: files * 1_000 } +} + +/** Advances one reconcile interval and waits for the cycle it fires. */ +async function nextCycle(): Promise { + clock.advance(INTERVAL_MS) + await indexer?.settled() +} + +it('reflects a grown transcript within one reconcile interval', async () => { + const path = transcriptPath() + await writeClaudeTranscript(path, ['find the flaky terminal reattach'], SESSION_ID) + await newIndexer().start() + expect(sessionsMatching('reattach')).toEqual([SESSION_ID]) + expect(sessionsMatching('quarantine')).toEqual([]) + + await appendFile( + path, + `${claudeLines(['quarantine the leaking pty'], SESSION_ID, 10).join('\n')}\n` + ) + await nextCycle() + + expect(sessionsMatching('quarantine')).toEqual([SESSION_ID]) + expect(errors).toEqual([]) +}) + +it('reflects a rename-replaced transcript within one reconcile interval', async () => { + const path = transcriptPath() + await writeClaudeTranscript(path, ['original content aaaa'], SESSION_ID) + await newIndexer().start() + expect(sessionsMatching('original')).toEqual([SESSION_ID]) + const original = await stat(path) + + await renameReplaceTranscript(path, ['swapped content bbbbb'], SESSION_ID) + // Same length, different inode: only the identity check can tell them apart. + expect((await stat(path)).size).toBe(original.size) + await nextCycle() + + expect(sessionsMatching('swapped')).toEqual([SESSION_ID]) + expect(sessionsMatching('original')).toEqual([]) + expect(errors).toEqual([]) +}) + +it('retires a deleted transcript within one reconcile interval', async () => { + const path = transcriptPath() + await writeClaudeTranscript(path, ['a session about to be deleted'], SESSION_ID) + await writeClaudeTranscript( + transcriptPath(OTHER_SESSION_ID), + ['a surviving session'], + OTHER_SESSION_ID + ) + await newIndexer().start() + await nextCycle() + expect(sessionsMatching('deleted')).toEqual([SESSION_ID]) + + await rm(path) + await nextCycle() + + expect(sessionsMatching('deleted')).toEqual([]) + expect(sessionsMatching('surviving')).toEqual([OTHER_SESSION_ID]) +}) + +it.skipIf(!CAN_DENY_READ)( + 'keeps rows for a source it cannot stat, because loss of contact is not deletion', + async () => { + const path = transcriptPath() + await writeClaudeTranscript(path, ['an unverifiable session'], SESSION_ID) + await newIndexer().start() + await nextCycle() + + // The tree is gone from discovery's point of view, but the transcript itself + // was never proven absent: an unreadable parent is not a deleted file. + await chmod(harness.claudeProjectDir, 0o000) + try { + await nextCycle() + expect(sessionsMatching('unverifiable')).toEqual([SESSION_ID]) + } finally { + await chmod(harness.claudeProjectDir, 0o755) + } + } +) + +it('resumes after close and reopen without re-reading what it already indexed', async () => { + await writeClaudeTranscript(transcriptPath(), ['first indexed session'], SESSION_ID) + await writeClaudeTranscript( + transcriptPath(OTHER_SESSION_ID), + ['second indexed session'], + OTHER_SESSION_ID + ) + await newIndexer().start() + const indexedRows = harness.read((db: SyncDatabase) => + db.prepare('SELECT count(*) AS n FROM messages').get() + ) + indexer?.close() + + // A restart is a cold parse cache over a warm index; only the `files` table + // can say what has already been read. + resetSessionParseCacheForTests() + resetTranscriptConsumersForTests() + const reopened = newIndexer() + await reopened.start() + + // `filesIndexed` is the count of rows the index holds at their current stat, + // so it stays 2. That nothing was opened again is the read loop's own test. + expect(reopened.status()).toMatchObject({ filesIndexed: 2, filesDue: 0 }) + expect( + harness.read((db: SyncDatabase) => db.prepare('SELECT count(*) AS n FROM messages').get()) + ).toEqual(indexedRows) + expect(sessionsMatching('indexed')).toEqual([SESSION_ID, OTHER_SESSION_ID].sort()) +}) + +// F12, as the immutable design states it: the history window is a construction +// argument, so widening it is a new instance whose opening sweep admits the +// older files, and narrowing it is the purge that opens every full sweep. +it('widens history by constructing a new instance and narrows by purging on its first sweep', async () => { + const fresh = transcriptPath() + const old = transcriptPath(OTHER_SESSION_ID) + await writeClaudeTranscript(fresh, ['a recent conversation'], SESSION_ID) + await writeClaudeTranscript(old, ['an ancient conversation'], OTHER_SESSION_ID) + const longAgo = new Date(clock.now() - 120 * 86_400_000) + await utimes(old, longAgo, longAgo) + + // Newest-one per root, so the widened-in transcript is outside the recency + // window a cycle re-stats: only a full sweep can reach it. + await newIndexer({ historyDays: 30, recentPerAgent: 1 }).start() + expect(sessionsMatching('recent')).toEqual([SESSION_ID]) + expect(sessionsMatching('ancient')).toEqual([]) + + // Widening cannot be served from the index: those files were never read. + indexer?.close() + await newIndexer({ historyDays: null, recentPerAgent: 1 }).start() + expect(sessionsMatching('ancient')).toEqual([OTHER_SESSION_ID]) + + indexer?.close() + await newIndexer({ historyDays: 30, recentPerAgent: 1 }).start() + expect(sessionsMatching('ancient')).toEqual([]) + expect(sessionsMatching('recent')).toEqual([SESSION_ID]) +}) + +it.skipIf(!CAN_DENY_READ)( + 'names an unreadable root as degraded and keeps indexing the others', + async () => { + const blocked = join(harness.roots.codexSessionsDir ?? '', 'blocked') + await mkdir(blocked, { recursive: true }) + await writeClaudeTranscript(transcriptPath(), ['a readable claude session'], SESSION_ID) + await chmod(harness.roots.codexSessionsDir ?? '', 0o000) + try { + await newIndexer().start() + const status = indexer?.status() + expect(status?.phase).toBe('degraded') + expect(status?.degradedRoots.map((root) => root.root)).toContain( + harness.roots.codexSessionsDir + ) + expect(status?.degradedRoots[0]?.reason).toBeTruthy() + // A degraded root is not a degraded index: everything else still lands. + expect(sessionsMatching('readable')).toEqual([SESSION_ID]) + } finally { + await chmod(harness.roots.codexSessionsDir ?? '', 0o755) + } + } +) + +// The one bound on a pass. What it does not reach is owed on the next pass for +// the same reason it was owed on this one -- its row says so, or it has no row +// -- so nothing is written down and nothing can be lost. +it('reads what one pass has time for and finishes the rest on the next', async () => { + // The sweep is behind us, so this is the reconciler fitting four new files + // into a deadline that stops it after two. + await startAfterASweep(readsPerPass(2)) + for (let index = 0; index < 4; index++) { + const session = `0000000${index}-bbbb-4ccc-8ddd-eeeeeeeeeeee` + await writeClaudeTranscript( + transcriptPath(session), + [`deadlined session number ${index}`], + session + ) + } + await indexer?.reconcile() + expect(indexer?.status()).toMatchObject({ filesIndexed: 3, filesDue: 0 }) + + await indexer?.reconcile() + expect(sessionsMatching('deadlined')).toHaveLength(4) + expect(indexer?.status().filesIndexed).toBe(5) + + // Settled, and it stays settled: nothing changed, so the cycle after this + // one opens none of them. + clock.costPerNowMs = 0 + await nextCycle() + expect(indexer?.status()).toMatchObject({ filesIndexed: 5, phase: 'current' }) +}) + +// First enablement inside a running app is the normal case, not an edge: the +// session list has been scanning since launch, so every transcript already has +// a cursor sitting at its current stat and the index has nothing at all. +it('fills an empty index over a warm session-list cache on the first reconcile', async () => { + await startAfterASweep() + const path = transcriptPath() + await writeClaudeTranscript(path, ['scanned before the index existed'], SESSION_ID) + // An ordinary parse now reuses its cached fold and opens no file, so no + // consumer is asked and there is nothing for a decline to record. + await parseTranscript(path) + + await indexer?.reconcile() + + expect(sessionsMatching('scanned')).toEqual([SESSION_ID]) +}) + +it('fills an empty index over a warm session-list cache on the first sweep', async () => { + const path = transcriptPath() + await writeClaudeTranscript(path, ['scanned before the index existed'], SESSION_ID) + await parseTranscript(path) + + await newIndexer().start() + + expect(sessionsMatching('scanned')).toEqual([SESSION_ID]) +}) + +// Finding 1: a sweep cut short used to be abandoned part way through. A pass +// that hands reads back is not an unfinished sweep -- its discovery and its +// retirement both completed -- so it must not re-arm one, and the queue is what +// carries the reads it did not reach until the whole machine is covered. +it('covers the whole machine over the passes that follow a truncated sweep', async () => { + const sessions = Array.from( + { length: 20 }, + (_unused, index) => `0000${String(index).padStart(4, '0')}-bbbb-4ccc-8ddd-eeeeeeeeeeee` + ) + for (const session of sessions) { + await writeClaudeTranscript(transcriptPath(session), [`sweepwide session ${session}`], session) + } + + // One transcript a pass, so the opening sweep reaches a twentieth of them. + await newIndexer(readsPerPass(1)).start() + expect(indexedSessionCount()).toBeGreaterThan(0) + expect(indexedSessionCount()).toBeLessThan(sessions.length) + + for (let cycle = 0; cycle < sessions.length; cycle++) { + await nextCycle() + } + + expect(indexedSessionCount()).toBe(sessions.length) + expect(indexer?.status().phase).toBe('current') +}) + +// Finding 2: the store's cutoff was set once at construction while purges used +// a fresh one, so a sweep deleted the row and the accept check re-indexed it. +it('moves the retention window with the clock instead of freezing it at construction', async () => { + const path = transcriptPath() + await writeClaudeTranscript(path, ['an entry that ages out'], SESSION_ID) + // Dated on the same clock the retention window is measured against. + const now = new Date(clock.now()) + await utimes(path, now, now) + await newIndexer({ historyDays: 1 }).start() + expect(sessionsMatching('ages')).toEqual([SESSION_ID]) + + clock.advance(3 * 86_400_000) + await indexer?.reconcile({ full: true }) + + expect(sessionsMatching('ages')).toEqual([]) + await nextCycle() + expect(sessionsMatching('ages')).toEqual([]) +}) + +// Round 10, H1. A cycle proves a deletion by comparing what the previous pass +// watched against what it discovers. A sweep used to watch only what it could +// not settle, which is nothing on a healthy machine, so the cycle after a sweep +// had no candidates at all and the cycle after that no longer remembered the +// file: a transcript deleted in that interval survived until the next sweep, +// up to `fullSweepEveryCycles` later. +it('retires a transcript deleted between a sweep and the cycle after it', async () => { + const going = transcriptPath() + const staying = transcriptPath(OTHER_SESSION_ID) + await writeClaudeTranscript(going, ['a session deleted right after the sweep'], SESSION_ID) + await writeClaudeTranscript(staying, ['a surviving session'], OTHER_SESSION_ID) + await newIndexer().start() + expect(sessionsMatching('deleted')).toEqual([SESSION_ID]) + + // No cycle in between: the sweep is the only pass that has seen this file. + await rm(going) + await nextCycle() + + expect(sessionsMatching('deleted')).toEqual([]) + expect(sessionsMatching('surviving')).toEqual([OTHER_SESSION_ID]) +}) + +// Round 10, M2. A sweep that throws part way learned nothing, and the flag that +// says one is owed was taken on entry. Losing it there leaves nothing armed to +// try again, so the machine outside the recency window goes unread until +// something else happens to ask for a sweep. +it('keeps a sweep due when the one that was running threw', async () => { + const older = transcriptPath(OTHER_SESSION_ID) + await writeClaudeTranscript(older, ['an older conversation'], OTHER_SESSION_ID) + const yesterday = new Date(Date.now() - 86_400_000) + await utimes(older, yesterday, yesterday) + await writeClaudeTranscript(transcriptPath(), ['the newest conversation'], SESSION_ID) + + // Newest-one per root, so only a sweep can reach the older file. The clock is + // read inside the pass, which is where a failure part way through lands. + newIndexer({ recentPerAgent: 1 }) + let thrown = false + clock.onNow = () => { + if (thrown || indexedSessionCount() === 0) { + return + } + thrown = true + throw new Error('the sweep fell over') + } + await indexer?.start() + await indexer?.settled() + clock.onNow = null + + expect(errors.map((error) => (error as Error).message)).toEqual(['the sweep fell over']) + expect(sessionsMatching('older')).toEqual([]) + + // The pass after it is a sweep, not a cycle: a cycle reads one file per root. + await nextCycle() + expect(sessionsMatching('older')).toEqual([OTHER_SESSION_ID]) +}) + +// Round 10, M1. A transcript the reader cannot open is recorded stale by the +// consumer on every attempt, so it was re-read every cycle for ever: pending +// stuck at one, a failure count climbing without bound, and a phase that never +// left `indexing`. One file with the wrong mode bits read as a real backlog. +it.skipIf(!CAN_DENY_READ)('stops re-reading a transcript it cannot read', async () => { + const path = transcriptPath() + await writeClaudeTranscript(path, ['a session behind the wrong mode bits'], SESSION_ID) + await chmod(path, 0o000) + try { + await newIndexer().start() + for (let cycle = 0; cycle < 4; cycle++) { + await nextCycle() + } + + // Held out by its own row: three failures at one unchanged stat, counted on + // the row itself, and a phase that says the index knows it is not covering + // something rather than one that describes work it will never do. + expect(indexer?.status()).toMatchObject({ filesDue: 0, filesFailed: 1, phase: 'degraded' }) + expect(rowFor(path)?.failCount).toBeGreaterThanOrEqual(3) + + // And the hold is released by the only thing that can mean the file + // changed: its stat. + await chmod(path, 0o644) + const later = new Date(Date.now() + 60_000) + await utimes(path, later, later) + await nextCycle() + + expect(sessionsMatching('mode')).toEqual([SESSION_ID]) + expect(indexer?.status()).toMatchObject({ filesFailed: 0, phase: 'current' }) + } finally { + await chmod(path, 0o644) + } +}) + +// Round 10, M2. `close()` mid-pass left the pass reading a shut handle: three +// `database is not open` errors reached the owner, for a close they asked for. +it('reports nothing to its owner when it is closed part way through a pass', async () => { + await writeClaudeTranscript(transcriptPath(), ['one'], SESSION_ID) + const other = transcriptPath(OTHER_SESSION_ID) + await writeClaudeTranscript(other, ['two'], OTHER_SESSION_ID) + const later = new Date(Date.now() + 60_000) + await utimes(other, later, later) + newIndexer() + + // Between two files: the pass reads the clock once per file it is about to + // read, and closing there is what a quit during a sweep looks like. + let closed = false + clock.onNow = () => { + if (closed || indexedSessionCount() === 0) { + return + } + closed = true + indexer?.close() + } + await indexer?.start() + await indexer?.settled() + clock.onNow = null + + expect(errors).toEqual([]) +}) + +// Round 10, M2, the other half: `status()` on a closed indexer opened a shut +// database, reported the failure, and answered zero files. +it('reports what it last knew after it is closed, without reading the database', async () => { + await writeClaudeTranscript(transcriptPath(), ['indexed before the close'], SESSION_ID) + await newIndexer().start() + expect(indexer?.status().filesIndexed).toBe(1) + + indexer?.close() + + expect(indexer?.status()).toMatchObject({ phase: 'closed', filesIndexed: 1 }) + expect(errors).toEqual([]) +}) + +// Round 10, L1. Two indexers on one database both register with the reader, so +// every transcript is read and written twice and the second write is fenced by +// the first at random. The recipe for every configuration change is +// close-then-construct, so the ordering that causes this is the one the recipe +// rules out; this is what says so rather than letting it corrupt quietly. +// Round 12, F2. The claim was staked before the store opened, so an open that +// threw left the path owned by an object that does not exist and every later +// construction was refused -- including the one that fixes whatever broke it. +it('releases the database path when the open itself throws', () => { + // A directory where the database file goes: the open fails, nothing is owned. + mkdirSync(harness.databasePath, { recursive: true }) + expect(() => newIndexer()).toThrow() + + rmSync(harness.databasePath, { recursive: true, force: true }) + expect(() => newIndexer()).not.toThrow() +}) + +it('refuses a second indexer on a database one already owns', () => { + newIndexer() + expect(() => newIndexer()).toThrow(/already has a live indexer/) +}) + +// PR 2 records a cursor no append continues for a file a chunked read left half +// written, and reports it as a null offset. The mtime and size on that row are +// the whole file's, so a freshness check comparing only those calls a prefix +// current and leaves it in the index for good. +it('re-reads a file a chunked read left half written, and settles it in one pass', async () => { + const path = transcriptPath() + await writeClaudeTranscript(path, ['the committed half'], SESSION_ID) + await newIndexer().start() + const whole = (await stat(path)).size + expect(indexedByteOffset(path)).toBe(whole) + indexer?.close() + + plantPartialCursor(path) + await newIndexer().start() + + // Nothing about the file changed, and it was read anyway: the whole of it, + // because there is no cursor to continue from. + expect(indexedByteOffset(path)).toBe(whole) + expect(fileState(path)).toBe('current') + expect(indexer?.status().phase).toBe('current') + indexer?.close() + + // A half-written file that also grew is repaired by one pass rather than two. + // The session list's resume point would have the reader offer an append here, + // and an append onto a partial cursor is a read the consumer declines. + plantPartialCursor(path) + await appendFile(path, `${claudeLines(['the lost half'], SESSION_ID, 10).join('\n')}\n`) + await newIndexer().start() + + expect(sessionsMatching('lost')).toEqual([SESSION_ID]) + expect(indexer?.status()).toMatchObject({ filesDue: 0, phase: 'current' }) +}) + +it('reports closed once it is closed, whatever it was doing before', async () => { + await writeClaudeTranscript(transcriptPath(), ['before the close'], SESSION_ID) + await newIndexer().start() + expect(indexer?.status().phase).toBe('current') + indexer?.close() + expect(indexer?.status().phase).toBe('closed') +}) + +// Finding 6: a queued entry carries the stat it was recorded with. Reading at +// that stat writes a cursor describing a file that no longer looks like this, +// so the next cycle distrusts it and re-reads it, forever. +it('reads a deferred file at its current stat, not the one the pass first saw', async () => { + // One file a pass, so the older one is left for the pass after this. + await startAfterASweep(readsPerPass(1)) + const older = transcriptPath(OTHER_SESSION_ID) + await writeClaudeTranscript(older, ['the deferred conversation'], OTHER_SESSION_ID) + await writeClaudeTranscript(transcriptPath(), ['the newer conversation'], SESSION_ID) + const ahead = new Date((await stat(transcriptPath())).mtimeMs + 60_000) + await utimes(transcriptPath(), ahead, ahead) + + await indexer?.reconcile() + // No row for it at all, which is exactly why the next pass reads it. + expect(rowFor(older)).toBeUndefined() + + await appendFile( + older, + `${claudeLines(['appended while deferred'], OTHER_SESSION_ID, 10).join('\n')}\n` + ) + await indexer?.reconcile() + + expect(sessionsMatching('appended')).toEqual([OTHER_SESSION_ID]) + // The cursor has to describe the file as it is now; recorded against the + // stat the earlier pass saw it would be re-read on every cycle from here on. + const cursor = indexedCursor(older) + const current = await stat(older) + expect(cursor).toEqual({ mtime_ms: current.mtimeMs, size_bytes: current.size }) +}) + +// A declined read records the stat it was declined at. By the time the store +// hands it back the file has usually moved on again, and reading at the +// recorded stat writes a cursor the next cycle immediately distrusts. +it('reads a declined file at its current stat, not the one it was recorded with', async () => { + const path = transcriptPath() + await writeClaudeTranscript(path, ['the recorded conversation'], SESSION_ID) + await newIndexer().start() + + // A warm session-list cache over an empty index: the reader offers an append + // continuing an offset this index has never seen, so the consumer declines it + // and records the stat it declined at. + indexer?.close() + removeSessionSearchDatabase(harness.databasePath) + newIndexer() + await appendFile(path, `${claudeLines(['declined turn'], SESSION_ID, 10).join('\n')}\n`) + await parseTranscript(path) + // The index holds nothing for it, which is the record: a path the file table + // does not name is read from the start by the next pass. + expect(indexer?.status().filesIndexed).toBe(0) + + await appendFile(path, `${claudeLines(['later turn'], SESSION_ID, 20).join('\n')}\n`) + // The sweep is declined too -- the list's cursor is still ahead of the index + // -- so it is the pass after it that reads the file whole. + await indexer?.start() + await nextCycle() + + expect(sessionsMatching('later')).toEqual([SESSION_ID]) + const current = await stat(path) + expect(indexedCursor(path)).toEqual({ mtime_ms: current.mtimeMs, size_bytes: current.size }) +}) + +// Round 2, item 1: the sweep kept the rows and a cycle twenty seconds later +// deleted them, because the degraded-root fence was on the sweep path only. +it.skipIf(!CAN_DENY_READ)( + 'keeps an unlistable root through the cycles that follow the sweep', + async () => { + await writeClaudeTranscript(transcriptPath(), ['a session on a removable volume'], SESSION_ID) + await newIndexer().start() + expect(sessionsMatching('removable')).toEqual([SESSION_ID]) + + await chmod(harness.roots.claudeProjectsDir ?? '', 0o000) + try { + await indexer?.reconcile({ full: true }) + expect(sessionsMatching('removable')).toEqual([SESSION_ID]) + + await nextCycle() + expect(sessionsMatching('removable')).toEqual([SESSION_ID]) + expect(indexer?.status().phase).toBe('degraded') + } finally { + await chmod(harness.roots.claudeProjectsDir ?? '', 0o755) + } + } +) + +// A root that cannot be listed is never believed to be empty, however many +// times it is asked: an error is not a listing, and only a listing is proof. +it.skipIf(!CAN_DENY_READ)('keeps an unlistable root degraded across repeated sweeps', async () => { + await writeClaudeTranscript(transcriptPath(), ['a session on a removable volume'], SESSION_ID) + await newIndexer().start() + + await chmod(harness.roots.claudeProjectsDir ?? '', 0o000) + try { + for (let sweep = 0; sweep < 5; sweep++) { + await indexer?.reconcile({ full: true }) + } + expect(sessionsMatching('removable')).toEqual([SESSION_ID]) + expect(indexer?.status().phase).toBe('degraded') + } finally { + await chmod(harness.roots.claudeProjectsDir ?? '', 0o755) + } +}) + +// The first sweep of every process is exactly when a volume is most likely to +// be detached, and it is the pass with nothing behind it to compare against. +it('keeps a root that is gone at the first sweep after a restart', async () => { + await writeClaudeTranscript(transcriptPath(), ['a session on a removable volume'], SESSION_ID) + await newIndexer().start() + indexer?.close() + resetTranscriptConsumersForTests() + resetSessionParseCacheForTests() + + // The volume is not there when the process comes back. + await rm(harness.roots.claudeProjectsDir ?? '', { recursive: true, force: true }) + await newIndexer().start() + + const status = indexer?.status() + expect(status?.phase).toBe('degraded') + expect(status?.degradedRoots.map((root) => root.root)).toContain(harness.roots.claudeProjectsDir) + expect(sessionsMatching('removable')).toEqual([SESSION_ID]) + + // And it clears once the volume is back. + await writeClaudeTranscript(transcriptPath(), ['a session on a removable volume'], SESSION_ID) + await indexer?.reconcile({ full: true }) + expect(indexer?.status()).toMatchObject({ phase: 'current', degradedRoots: [] }) +}) + +// Round 7: what the stateless walk costs, stated rather than hidden. A volume +// mounted at EXACTLY a configured root, unmounted so the mountpoint stays +// present and lists empty, is indistinguishable from a root the user emptied: +// there is no directory left whose absence could stop the walk. Inside one +// process the transition buys a pass of grace; across a restart there is no +// transition to see and the rows retire. The unmounts that actually happen are +// above the root, and the next test is the one that covers them. +it('retires an emptied configured root, one pass after it emptied', async () => { + await writeClaudeTranscript(transcriptPath(), ['a session on the mounted volume'], SESSION_ID) + await newIndexer().start() + + // The transcripts go; the root itself stays there and stays readable. + await rm(harness.claudeProjectDir, { recursive: true, force: true }) + await indexer?.reconcile({ full: true }) + expect(sessionsMatching('mounted')).toEqual([SESSION_ID]) + expect(indexer?.status().phase).toBe('degraded') + + await indexer?.reconcile({ full: true }) + expect(sessionsMatching('mounted')).toEqual([]) + expect(indexer?.status()).toMatchObject({ phase: 'current', degradedRoots: [] }) +}) + +// The same root, with no previous pass to compare against: nothing carries the +// transition across a restart, and the empty listing is proof on its own. +it('retires an emptied configured root at once on the first pass of a process', async () => { + await writeClaudeTranscript(transcriptPath(), ['a session on the mounted volume'], SESSION_ID) + await newIndexer().start() + expect(sessionsMatching('mounted')).toEqual([SESSION_ID]) + indexer?.close() + resetTranscriptConsumersForTests() + resetSessionParseCacheForTests() + + await rm(harness.claudeProjectDir, { recursive: true, force: true }) + await newIndexer().start() + expect(sessionsMatching('mounted')).toEqual([]) +}) + +// The shape a real unmount takes: on Linux, WSL and sshfs the mountpoint is +// above the agent's root, so the root itself is missing. The walk stops at the +// root boundary and never asks the empty parent anything, which is what makes +// this hold with no memory on the first pass of a process. +it('proves nothing from an empty directory above the configured root', async () => { + for (let index = 0; index < 3; index++) { + const session = `0000000${index}-bbbb-4ccc-8ddd-eeeeeeeeeeee` + await writeClaudeTranscript(transcriptPath(session), [`mounted session ${index}`], session) + } + await newIndexer().start() + expect(sessionsMatching('mounted')).toHaveLength(3) + indexer?.close() + resetTranscriptConsumersForTests() + resetSessionParseCacheForTests() + + // The volume that carried the agent's root is gone; what it was mounted + // under is still there, still listable, and empty of it. + await rm(harness.roots.claudeProjectsDir ?? '', { recursive: true, force: true }) + await newIndexer().start() + + const status = indexer?.status() + expect(status?.phase).toBe('degraded') + expect(status?.degradedRoots.map((root) => root.root)).toContain(harness.roots.claudeProjectsDir) + expect(sessionsMatching('mounted')).toHaveLength(3) +}) + +// A cycle only reads the newest N per agent, so a remounted volume would give +// up its newest transcript and keep the rest unreachable. Nothing watches for a +// recovery any more: the sweep cadence is what reaches it. +it('reads a root that came back on the next periodic sweep', async () => { + // Detached before anything was ever indexed, so the sweep correctly finds + // nothing and reports no alarm. + await newIndexer({ recentPerAgent: 1, fullSweepEveryCycles: 2 }).start() + expect(indexer?.status()).toMatchObject({ degradedRoots: [], filesIndexed: 0 }) + + for (let index = 0; index < 3; index++) { + const session = `0000000${index}-bbbb-4ccc-8ddd-eeeeeeeeeeee` + await writeClaudeTranscript(transcriptPath(session), [`remounted session ${index}`], session) + } + + // Two cycles reach the newest one each; the sweep they are counting down to + // reads the rest. + await nextCycle() + await nextCycle() + expect(sessionsMatching('remounted')).toHaveLength(1) + + await nextCycle() + expect(sessionsMatching('remounted')).toHaveLength(3) +}) + +// Round 4, item 3: rows under no configured root. The walk judges each row on +// its own directory and proves nothing about one it cannot reach, so a profile +// that moved keeps its history rather than losing it. +it('keeps rows under no configured root, and retires them only when gone', async () => { + const moved = transcriptPath() + await writeClaudeTranscript(moved, ['a session in the old profile'], SESSION_ID) + await newIndexer().start() + indexer?.close() + resetTranscriptConsumersForTests() + resetSessionParseCacheForTests() + + // The profile moves: same index, a root that no longer covers those rows. + const elsewhere = join(harness.root, 'moved-profile') + newIndexer({ roots: { ...harness.roots, claudeProjectsDir: elsewhere } }) + await indexer?.start() + // Still on disk, so the rows stay: this is a configuration problem, not a + // licence to delete a user's history. + expect(sessionsMatching('profile')).toEqual([SESSION_ID]) + + await rm(moved) + await indexer?.reconcile({ full: true }) + expect(sessionsMatching('profile')).toEqual([]) +}) + +// Round 7 replaced "only a census may conclude" with "whoever can prove it". +// A cycle walks the same directories and reaches the same verdict, so a project +// directory the user deleted does not wait for the next sweep. +it('lets a cycle retire a project directory the user deleted', async () => { + await writeClaudeTranscript(transcriptPath(), ['a session about to vanish'], SESSION_ID) + await newIndexer().start() + + await rm(harness.claudeProjectDir, { recursive: true, force: true }) + // The pass that sees the root go from holding transcripts to holding none + // gives it one pass of grace, whether it is a sweep or a cycle. + await indexer?.reconcile({ full: true }) + expect(sessionsMatching('vanish')).toEqual([SESSION_ID]) + + await nextCycle() + expect(sessionsMatching('vanish')).toEqual([]) + expect(indexer?.status()).toMatchObject({ phase: 'current', degradedRoots: [] }) +}) + +// C1: `close()` disarmed the timer and aborted the task in flight, but left the +// queue running, so a task queued a moment earlier still reopened a store and +// registered a consumer behind an indexer whose caller had finished with it. +it('stops everything on close, including work already queued', async () => { + await writeClaudeTranscript(transcriptPath(), ['indexed before the close'], SESSION_ID) + await newIndexer().start() + + const queued = indexer?.reconcile({ full: true }) + indexer?.close() + await queued + + // The queued pass never ran: had it run, it would have reached for a store + // this close had already shut, and reported the failure. + expect(errors).toEqual([]) + // And the timer is gone with it, so no later tick can queue another. + expect(clock.pendingTimers).toBe(0) + clock.advance(5 * INTERVAL_MS) + await indexer?.settled() + expect(errors).toEqual([]) + + // No store and no consumer: a scan after the close writes nothing. + const after = transcriptPath(OTHER_SESSION_ID) + await writeClaudeTranscript(after, ['written after the close'], OTHER_SESSION_ID) + await parseTranscript(after) + expect(sessionsMatching('written')).toEqual([]) + expect(sessionsMatching('indexed')).toEqual([SESSION_ID]) +}) + +// What replaced `clear()`, exactly as the PR body documents it. The recipe is +// three statements because the indexer owns one store for one lifetime; the +// method it replaces owned a second one and had to keep the two in step. +it('throws the index away and rebuilds it by constructing a new instance', async () => { + await writeClaudeTranscript(transcriptPath(), ['indexed before the clear'], SESSION_ID) + await newIndexer().start() + expect(existsSync(harness.databasePath)).toBe(true) + + indexer?.close() + removeSessionSearchDatabase(harness.databasePath) + expect(existsSync(harness.databasePath)).toBe(false) + + // The session list's cache is warm, which is what a clear inside a running + // app leaves behind; the sweep reads whole rather than trusting it. + await newIndexer().start() + expect(sessionsMatching('indexed')).toEqual([SESSION_ID]) +}) + +it('refuses a reconcile before it is started and after it is closed', async () => { + newIndexer() + expect(() => indexer?.reconcile()).toThrow(/start\(\) first/) + + await indexer?.start() + await indexer?.reconcile() + indexer?.close() + expect(() => indexer?.reconcile()).toThrow(/closed/) +}) + +// I7: the sweep reads transcript bytes, so it stops at the same deadline every +// other pass does. It plans the whole machine and hands back what it had no +// time for; the passes that follow drain the plan without re-discovering. +it('stops the opening sweep at its deadline and drains the rest over the passes that follow', async () => { + for (let index = 0; index < 5; index++) { + const session = `0000000${index}-bbbb-4ccc-8ddd-eeeeeeeeeeee` + await writeClaudeTranscript(transcriptPath(session), [`backlogged session ${index}`], session) + } + await newIndexer(readsPerPass(2)).start() + expect(indexer?.status().filesIndexed).toBe(2) + + await nextCycle() + expect(indexer?.status().filesIndexed).toBe(4) + + await nextCycle() + expect(sessionsMatching('backlogged')).toHaveLength(5) + expect(indexer?.status()).toMatchObject({ filesIndexed: 5, filesDue: 0 }) +}) + +// The sweep cadence, with nobody asking for it: a file outside the recency +// window that appears after the opening sweep is unreachable until the next +// periodic one, and the count of cycles is the whole rule. +it('sweeps on its cadence without anyone asking', async () => { + await writeClaudeTranscript(transcriptPath(), ['the newest conversation'], SESSION_ID) + await newIndexer({ recentPerAgent: 1, fullSweepEveryCycles: 2 }).start() + + const older = transcriptPath(OTHER_SESSION_ID) + await writeClaudeTranscript(older, ['an older conversation'], OTHER_SESSION_ID) + const yesterday = new Date(Date.now() - 86_400_000) + await utimes(older, yesterday, yesterday) + + await nextCycle() + await nextCycle() + expect(sessionsMatching('older')).toEqual([]) + + await nextCycle() + expect(sessionsMatching('older')).toEqual([OTHER_SESSION_ID]) +}) + +// A cycle lists the newest N per agent, so every older row it holds is +// undiscovered and would be walked every twenty seconds. It proves the newest +// slice of them instead, capped: a transcript recent enough for the window is +// recent enough to be in the slice, and the rest are the next sweep's to reach. +// Round 12, F1. A directory that cannot be listed answers `unverifiable` for +// every row under it, on every pass, for as long as the permission stays wrong. +// With the walk capped at rows rather than at directories, five hundred such +// rows spent the whole budget on one readdir's worth of verdicts and a row for +// a file the user really deleted, sorted behind them, was never reached: six +// full sweeps and it was still held. +it.skipIf(!CAN_DENY_READ)('retires a deleted file behind a block of unreadable rows', async () => { + // A healthy project directory, so the root never looks emptied. + await writeClaudeTranscript(transcriptPath(), ['a live conversation'], SESSION_ID) + const locked = join(harness.roots.claudeProjectsDir ?? '', 'locked') + await mkdir(locked, { recursive: true }) + newIndexer() + + // What an unreadable tree leaves behind: rows the walk can never settle, + // planted ahead of the deleted one in the order the table returns them. + harness.write((db: SyncDatabase) => { + const insert = db.prepare( + `INSERT INTO files(path, byte_offset, mtime_ms, size_bytes, state) + VALUES (?, 0, ?, 10, 'current')` + ) + for (let index = 0; index < 520; index++) { + insert.run(join(locked, `locked-${index}.jsonl`), 1_700_000_000_000 + index) + } + return insert.run(join(harness.claudeProjectDir, 'deleted.jsonl'), 1_700_000_999_000) + }) + const deleted = join(harness.claudeProjectDir, 'deleted.jsonl') + const holdsDeleted = (): boolean => rowFor(deleted) !== undefined + + await chmod(locked, 0o000) + try { + await indexer?.start() + + expect(holdsDeleted()).toBe(false) + // And the block itself is neither retired nor forgotten: unreadable is not + // deleted, and the root is named as degraded rather than emptied. + expect(indexer?.status().filesIndexed).toBe(521) + expect(indexer?.status().phase).toBe('degraded') + } finally { + await chmod(locked, 0o700) + } +}) + +it('proves deletions for the newest rows it holds, and leaves the tail to a sweep', async () => { + const total = 530 + const oldest = transcriptPath('00000000-bbbb-4ccc-8ddd-eeeeeeeeeeee') + await writeClaudeTranscript( + oldest, + ['the oldest session'], + '00000000-bbbb-4ccc-8ddd-eeeeeeeeeeee' + ) + const longAgo = new Date(Date.now() - total * 60_000) + await utimes(oldest, longAgo, longAgo) + // Indexed on its own first, so it is the earliest row in the table as well as + // the oldest file. A slice that trusted the table's own order rather than the + // mtime would take it, and take it first. + await newIndexer().start() + + for (let index = 1; index < total; index++) { + const session = `0000${String(index).padStart(4, '0')}-bbbb-4ccc-8ddd-eeeeeeeeeeee` + const path = transcriptPath(session) + await writeClaudeTranscript(path, [`capped session ${index}`], session) + const at = new Date(Date.now() - (total - index) * 60_000) + await utimes(path, at, at) + } + await indexer?.reconcile({ full: true }) + expect(indexedSessionCount()).toBe(total) + + // Older than the cap reaches: 530 rows, twelve of them rediscovered by the + // cycle, leaves 518 undiscovered against a cap of 512. + await rm(oldest) + await nextCycle() + expect(indexedSessionCount()).toBe(total) + + await indexer?.reconcile({ full: true }) + expect(indexedSessionCount()).toBe(total - 1) +}) + +// F1: `fullSweepDue` stayed set across the sweep's await and was cleared on the +// way out, so a request raised while a sweep was running was erased by the +// sweep it arrived during. The pass takes the flag on entry now, and an +// unfinished sweep is what puts it back. +it('runs another sweep when one is asked for during a sweep', async () => { + for (let index = 0; index < 20; index++) { + const session = `0000${String(index).padStart(4, '0')}-bbbb-4ccc-8ddd-eeeeeeeeeeee` + await writeClaudeTranscript(transcriptPath(session), [`recent session ${index}`], session) + } + const late = transcriptPath(OTHER_SESSION_ID) + + // Newest-one per root, so nothing but a second sweep can reach a file that + // appears after this sweep's discovery has already run. The clock is the one + // synchronous seam into a pass: it is read between files. + newIndexer({ recentPerAgent: 1 }) + let armed = false + // Once a row has landed the pass is provably inside its read loop, which is + // after it took the sweep flag and before it hands its verdicts back. + clock.onNow = () => { + if (armed || indexedSessionCount() === 0) { + return + } + armed = true + mkdirSync(dirname(late), { recursive: true }) + writeFileSync(late, `${claudeLines(['a late conversation'], OTHER_SESSION_ID, 0).join('\n')}\n`) + const backdated = new Date(Date.now() - 86_400_000) + utimesSync(late, backdated, backdated) + void indexer?.reconcile({ full: true }) + } + await indexer?.start() + await indexer?.settled() + + expect(sessionsMatching('late')).toEqual([OTHER_SESSION_ID]) +}) + +// The duty cycle, as a test: a pass reads for at most its deadline and hands +// the rest back, and the timer only re-arms once the pass has settled, so the +// share of the wall clock the index takes is bounded by construction. +it('hands the rest of a pass back when it runs out of wall time', async () => { + for (let index = 0; index < 20; index++) { + const session = `0000${String(index).padStart(4, '0')}-bbbb-4ccc-8ddd-eeeeeeeeeeee` + await writeClaudeTranscript(transcriptPath(session), [`deadlined session ${index}`], session) + } + await newIndexer(readsPerPass(16)).start() + + expect(indexer?.status().filesIndexed).toBe(16) + + // And the pass after it picks up exactly the four it did not reach. + await nextCycle() + expect(indexer?.status()).toMatchObject({ filesIndexed: 20, filesDue: 0 }) +}) diff --git a/src/main/ai-vault-search/session-search-indexer.ts b/src/main/ai-vault-search/session-search-indexer.ts new file mode 100644 index 00000000000..26213242c49 --- /dev/null +++ b/src/main/ai-vault-search/session-search-indexer.ts @@ -0,0 +1,325 @@ +import { systemSessionSearchClock, type SessionSearchClock } from './session-search-clock' +import { + DEFAULT_SESSION_SEARCH_FULL_SWEEP_EVERY_CYCLES, + DEFAULT_SESSION_SEARCH_PASS_DEADLINE_FRACTION, + DEFAULT_SESSION_SEARCH_RECENT_PER_AGENT, + DEFAULT_SESSION_SEARCH_RECONCILE_INTERVAL_MS, + type SessionSearchIndexerOptions +} from './session-search-indexer-options' +import { SessionSearchDirectoryListings } from './session-search-directory-listings' +import { registerSessionSearchIndexConsumer } from './session-search-index-consumer' +import { runSessionSearchPass } from './session-search-pass' +import { sessionSearchHistoryCutoffMs } from './session-search-retention-policy' +import { SessionSearchStore, type SessionSearchStateCounts } from './session-search-store' +import type { SessionSearchDegradedRoot } from './session-search-degraded-roots' +import { SessionSearchWorkLoop } from './session-search-work-loop' + +/** + * Database paths a live indexer already owns. + * + * One process, one writer, one consumer registration per index. Two indexers on + * one path both register with the reader, so every transcript is read and + * written twice and the second write is fenced by the first at random. The + * recipe for every configuration change is close-then-construct, so the + * ordering that causes this is the one the recipe already rules out; this is + * what says so rather than letting it corrupt quietly. + */ +const liveIndexerPaths = new Set() + +export type SessionSearchIndexPhase = 'idle' | 'indexing' | 'current' | 'degraded' | 'closed' + +export type SessionSearchIndexStatus = { + phase: SessionSearchIndexPhase + /** Rows whose content matches the file at the stat the row records. */ + filesIndexed: number + /** Rows owed a whole read: a declined append, or a window that widened. */ + filesDue: number + /** Rows whose last read did not commit. */ + filesFailed: number + degradedRoots: SessionSearchDegradedRoot[] + lastReconcileAt: number | null + /** When a whole-machine sweep last finished; null until one has. */ + lastSweepCompletedAt: number | null +} + +/** + * Owns freshness for the index store: a whole-machine sweep, then a timer that + * keeps the newest N transcripts per agent reconciled and sweeps again every + * `fullSweepEveryCycles`. + * + * A library, not a service. It knows nothing about Electron, the app lifecycle, + * settings storage, IPC or the panel, and nothing here reads a setting or + * registers itself anywhere. Whoever constructs it decides all of that. + * + * **The store is the only memory.** Every question a pass asks between passes — + * what is owed a read, what has failed and how often, what the index holds and + * therefore what may have been deleted, what to report — is answered by a row + * in the `files` table. There is no queue, no watch set, no hold-out map and no + * counter with a reset rule. + * + * What is left here, and why none of it can be a row: + * - `previousRootsWithFiles`, the one bit per root the retirement walk's grace + * needs. Deliberately not durable: see the mountpoint trade in + * `session-search-deleted-sources.ts`. + * - `cyclesSinceSweep` and `sweepNext`, which are about the timer rather than + * about any file, and mean nothing to a second process. + * - `degradedRoots`, `lastReconcileAt` and `lastSweepCompletedAt`: what the last + * pass observed, held so `status()` can answer between passes. + * - `lastCounts`, the one cached query result, read only after `close()` so that + * describing what happened does not reopen a handle the owner has finished + * with. While the indexer is open every call re-queries. + * + * **Immutable after construction.** There is no `pause`, `resume`, `clear` or + * `setHistoryDays`. A configuration change is `close()` and a new instance; + * throwing the index away is + * `close(); removeSessionSearchDatabase(databasePath);` and a new instance. + * Widening retention is a new instance whose opening sweep admits the older + * files; narrowing is the purge that opens every full sweep. + * + * The guarantee it makes: while started, a transcript among the newest N per + * agent that grows, is replaced or is deleted is reflected in the index within + * one reconcile interval. Everything else is reached by the periodic sweep. + */ +export class SessionSearchIndexer { + private readonly ownershipPath: string + private readonly clock: SessionSearchClock + private readonly intervalMs: number + private readonly passDeadlineMs: number + private readonly recentPerAgent: number + private readonly fullSweepEveryCycles: number + private readonly onError: (error: unknown) => void + + private readonly loop: SessionSearchWorkLoop + private readonly store: SessionSearchStore + private readonly unregister: () => void + /** Null until a pass has recorded one; an empty set is a real observation. */ + private previousRootsWithFiles: ReadonlySet | null = null + private degradedRoots: SessionSearchDegradedRoot[] = [] + private lastReconcileAt: number | null = null + private lastSweepCompletedAt: number | null = null + private lastCounts: SessionSearchStateCounts | null = null + private cyclesSinceSweep = 0 + private sweepNext = false + private started = false + private closed = false + + constructor(private readonly options: SessionSearchIndexerOptions) { + this.ownershipPath = resolve(options.databasePath) + this.clock = options.clock ?? systemSessionSearchClock + this.intervalMs = options.reconcileIntervalMs ?? DEFAULT_SESSION_SEARCH_RECONCILE_INTERVAL_MS + this.passDeadlineMs = + options.passDeadlineMs ?? + Math.max(1, Math.floor(this.intervalMs / DEFAULT_SESSION_SEARCH_PASS_DEADLINE_FRACTION)) + this.recentPerAgent = options.recentPerAgent ?? DEFAULT_SESSION_SEARCH_RECENT_PER_AGENT + this.fullSweepEveryCycles = Math.max( + 1, + options.fullSweepEveryCycles ?? DEFAULT_SESSION_SEARCH_FULL_SWEEP_EVERY_CYCLES + ) + const onError = options.onError ?? ((error) => console.warn('[ai-vault-search]', error)) + this.onError = onError + this.loop = new SessionSearchWorkLoop({ + clock: this.clock, + intervalMs: this.intervalMs, + onFailure: onError + }) + if (liveIndexerPaths.has(this.ownershipPath)) { + throw new Error( + `SessionSearchIndexer: ${options.databasePath} already has a live indexer; close it first` + ) + } + // Store, registration and indexer share one lifetime, which is what makes + // the object immutable: there is no second open to get out of step with. + // Claimed only once the store is open, because a construction that throws + // has no `close()` to release the claim: registering first would leave the + // path owned by an object that does not exist, and every later attempt at + // it -- including the one that fixes whatever broke the open -- would be + // refused for the life of the process. + this.store = new SessionSearchStore(options.databasePath, onError) + liveIndexerPaths.add(this.ownershipPath) + this.store.setRetentionCutoffMs(this.cutoffMs()) + this.unregister = registerSessionSearchIndexConsumer(this.store) + } + + /** Runs a full sweep, then reconciles on the interval until closed. */ + start(): Promise { + if (this.closed || this.started) { + return this.loop.settled + } + this.started = true + this.sweepNext = true + return this.tick() + } + + /** + * Runs one pass now, off the timer. A full pass sweeps every root. + * + * Refused before `start()` and after `close()`: a pass against an indexer + * nobody started writes the index once and leaves it to go stale with no + * timer armed to notice the next change, and a pass against a closed one has + * no store to write to. Both are caller bugs, so both throw rather than + * resolving as though a pass had run. + */ + reconcile(options: { full?: boolean } = {}): Promise { + if (this.closed) { + throw new Error('SessionSearchIndexer.reconcile: the indexer is closed') + } + if (!this.started) { + throw new Error('SessionSearchIndexer.reconcile: start() first') + } + this.sweepNext ||= options.full === true + return this.tick() + } + + /** + * What the index holds, read from the rows rather than tallied. + * + * A second connection can compute every number here with one `GROUP BY`, + * which is the point: nothing is counted as it happens, so nothing can drift + * from what the database actually holds or need a rule about when to reset. + */ + status(): SessionSearchIndexStatus { + // A closed indexer reports what it last knew: opening a shut handle to + // answer a call whose whole job is to describe what happened is how a close + // came to report a database error to the owner who asked for it. + const settled = (this.closed ? this.lastCounts : this.readCounts()) ?? { + current: 0, + due: 0, + failed: 0 + } + return { + phase: this.phase(settled), + filesIndexed: settled.current, + filesDue: settled.due, + filesFailed: settled.failed, + degradedRoots: this.degradedRoots.map((root) => ({ ...root })), + lastReconcileAt: this.lastReconcileAt, + lastSweepCompletedAt: this.lastSweepCompletedAt + } + } + + /** Stops everything. Nothing queued before this call may run afterwards. */ + close(): void { + if (this.closed) { + return + } + // Read before the handle goes, so a status call afterwards reports what the + // index last held rather than opening a database its owner has finished with. + this.lastCounts = this.readCounts() ?? this.lastCounts + this.closed = true + // The loop, not just its timer: a task queued before this call would + // otherwise still run against a store this line is about to close. + this.loop.close() + this.unregister() + this.store.close() + liveIndexerPaths.delete(this.ownershipPath) + } + + /** Tests only: everything else drives this through the timer. */ + settled(): Promise { + return this.loop.settled + } + + private readCounts(): SessionSearchStateCounts | null { + try { + const counts = this.store.stateCounts() + this.lastCounts = counts + return counts + } catch (error) { + this.onError(error) + return this.lastCounts + } + } + + /** + * `current` is a claim, so it takes all three: no row owed a read, no row + * whose last read failed, and a whole sweep that finished. `idle` is the + * other end of it — an indexer nobody started has not promised to index + * anything, and calling that `current` would claim an index nobody built is + * up to date. + */ + private phase(counts: SessionSearchStateCounts): SessionSearchIndexPhase { + if (this.closed) { + return 'closed' + } + if (!this.started) { + return 'idle' + } + // A root the pass could not read, or a file it could not read: both are gaps + // the index knows about and cannot close on its own. + if (this.degradedRoots.length > 0 || counts.failed > 0) { + return 'degraded' + } + return counts.due === 0 && this.lastSweepCompletedAt !== null ? 'current' : 'indexing' + } + + private tick(): Promise { + return this.loop.queue( + (signal) => this.pass(signal), + () => void this.tick() + ) + } + + private async pass(signal: AbortSignal): Promise { + // The window moves with the clock, and the decide step reads it from the + // store. Setting it once at construction leaves a sweep purging rows that + // the very next candidate check happily re-indexes. + this.store.setRetentionCutoffMs(this.cutoffMs()) + // The one bound on a pass: wall time. What it does not reach is still owed, + // because a row says so and nothing had to be written down. + const startedAt = this.clock.now() + const full = this.sweepNext + // Taken on entry, not cleared on the way out: a `reconcile({ full: true })` + // raised while this pass is running sets it again, and clearing it at the + // end would erase that request along with this pass's own. + this.sweepNext = false + try { + const result = await runSessionSearchPass({ + store: this.store, + roots: this.options.roots, + full, + recentPerAgent: this.recentPerAgent, + previousRootsWithFiles: this.previousRootsWithFiles ?? undefined, + overdue: () => this.clock.now() - startedAt >= this.passDeadlineMs, + // One readdir per directory for the whole pass, shared by every step. + listings: new SessionSearchDirectoryListings(), + signal + }) + if (!result.completed) { + // A pass cut short learned nothing about root health, and publishing its + // empty findings would clear a live alarm. A sweep stays owed. + this.sweepNext ||= full + return + } + this.degradedRoots = result.degradedRoots + this.previousRootsWithFiles = result.rootsWithFiles + this.lastReconcileAt = this.clock.now() + // A backlog outside the recency window is only visible to a sweep, so a + // pass that ran out of time asks for one. It is self-limiting: the first + // pass that finishes its reads hands the interval back to cycles. + this.sweepNext ||= result.outOfTime + if (full) { + this.lastSweepCompletedAt = this.lastReconcileAt + this.cyclesSinceSweep = 0 + return + } + // A root that came back, a tree restored from a backup, an old transcript + // deleted: only a sweep sees any of it, and the count of cycles is the + // whole rule for when one is owed. + this.cyclesSinceSweep += 1 + if (this.cyclesSinceSweep >= this.fullSweepEveryCycles) { + this.sweepNext = true + } + } catch (error) { + // The flag is this method's to hold, so it is this method's to give back: + // a pass that threw part way learned nothing, and losing it here would + // leave nothing armed to try again. + this.sweepNext ||= full + throw error + } + } + + private cutoffMs(): number | null { + return sessionSearchHistoryCutoffMs(this.options.historyDays, this.clock.now()) + } +} +import { resolve } from 'node:path' diff --git a/src/main/ai-vault-search/session-search-lifecycle-matrix.test.ts b/src/main/ai-vault-search/session-search-lifecycle-matrix.test.ts new file mode 100644 index 00000000000..79cbe70eb7f --- /dev/null +++ b/src/main/ai-vault-search/session-search-lifecycle-matrix.test.ts @@ -0,0 +1,378 @@ +import { chmod, mkdir, rename, rm } from 'node:fs/promises' +import { delimiter, dirname, join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { resetSessionParseCacheForTests } from '../ai-vault/session-scanner-parse-cache' +import { resetTranscriptConsumersForTests } from '../ai-vault/session-transcript-consumers' +import type SyncDatabase from '../sqlite/sync-database' +import { SessionSearchIndexer } from './session-search-indexer' +import type { SessionSearchIndexerOptions } from './session-search-indexer-options' +import { removeSessionSearchDatabase } from './session-search-schema' +import { + FakeSessionSearchClock, + openSessionSearchIndexerHarness, + writeClaudeTranscript, + writeMessageGraphTranscript, + type SessionSearchIndexerHarness +} from './session-search-indexer-test-fixture' + +/* + * The lifecycle matrix: every operation a caller can perform, against every + * shape an unreachable root takes, against both ways discovery reports a root. + * + * The indexer is immutable, so "every operation" is a shorter list than it was: + * `pause`, `resume`, `clear`, `setHistoryDays` and `invalidate` are gone, and + * the two of them a caller still needs — a settings change and throwing the + * index away — are here as what replaced them, a new instance over the same + * path. In their place are the two passes the immutable design added: the + * periodic sweep, and a pass whose wall-clock deadline expires on its first file. + * + * What each cell asserts: + * A. No row is retired for a file that still exists. Throwing the index away + * is the one exception, and it is stated per operation rather than excused. + * B. The unreachable root is named in `degradedRoots`, by a real directory + * path — never the delimiter-joined label a merged discovery reports. + * C. The phase is never `current` while a root is degraded. + * D. Once the root is reachable again, a sweep indexes everything under it. + * + * Round 6 ran this as a throwaway harness on the previous design; it lives in + * the repository now. Two of its shapes changed with the stateless walk. The + * "present but empty mountpoint" shape is gone, because a readable root that + * lists nothing is no longer treated as unreachable — that is a root the user + * emptied, and `session-search-deleted-sources.ts` states the trade. In its + * place is a root whose transcripts sit behind an unreadable subdirectory, + * which is the partial-tree case the old shape never covered. + */ + +const CAN_DENY_READ = process.platform !== 'win32' && process.getuid?.() !== 0 +const INTERVAL_MS = 20_000 +const SESSIONS = ['aaaaaaaa', 'bbbbbbbb', 'cccccccc'] + +type RootShape = { + name: string + /** Where the unreachable root's transcripts live, and where its files go. */ + detachedRoot: (harness: SessionSearchIndexerHarness) => string + detachedFile: (harness: SessionSearchIndexerHarness, session: string) => string + writeDetached: (path: string, session: string) => Promise + healthyFile: (harness: SessionSearchIndexerHarness, session: string) => string + writeHealthy: (path: string, session: string) => Promise +} + +const OPENCLAW_SESSION_DIR = join('agents', 'main', 'sessions') + +const ROOT_SHAPES: RootShape[] = [ + { + name: 'roots discovery reports one per directory', + detachedRoot: (harness) => harness.roots.claudeProjectsDir ?? '', + detachedFile: (harness, session) => join(harness.claudeProjectDir, `${session}.jsonl`), + writeDetached: (path, session) => + writeClaudeTranscript(path, [`detached ${session}`], fullSessionId(session)), + healthyFile: (harness, session) => join(harness.roots.piSessionsDir ?? '', `${session}.jsonl`), + writeHealthy: (path, session) => writeMessageGraphTranscript(path, [`healthy ${session}`]) + }, + { + name: 'roots a merged discovery joins into one label', + detachedRoot: (harness) => join(harness.roots.openclawStateDir ?? '', 'agents'), + detachedFile: (harness, session) => + join(harness.roots.openclawStateDir ?? '', OPENCLAW_SESSION_DIR, `${session}.jsonl`), + writeDetached: (path, session) => writeMessageGraphTranscript(path, [`detached ${session}`]), + healthyFile: (harness, session) => + join(harness.roots.openclawLegacyStateDir ?? '', OPENCLAW_SESSION_DIR, `${session}.jsonl`), + writeHealthy: (path, session) => writeMessageGraphTranscript(path, [`healthy ${session}`]) + } +] + +type UnreachableShape = { + name: string + needsDeniedRead: boolean + /** + * Whether an empty index can see this at all. Reading the root itself is the + * one probe a pass makes with no rows to go on: a root that answers ENOENT is + * what an uninstalled agent answers too, and a readable root with an + * unreadable subdirectory is swallowed by the file walker, which returns + * rather than reporting. Both are invisible until the index holds a row under + * the root, which is the evidence the retirement walk runs on. + */ + visibleWithNoRows: boolean + detach: (root: string, transcriptDir: string, parked: string) => Promise + attach: (root: string, transcriptDir: string, parked: string) => Promise +} + +const UNREACHABLE_SHAPES: UnreachableShape[] = [ + { + name: 'the root itself is not there', + needsDeniedRead: false, + visibleWithNoRows: false, + detach: (root, _transcriptDir, parked) => rename(root, parked), + attach: (root, _transcriptDir, parked) => rename(parked, root) + }, + { + name: 'the root refuses to list', + needsDeniedRead: true, + visibleWithNoRows: true, + detach: (root) => chmod(root, 0o000), + attach: (root) => chmod(root, 0o755) + }, + { + name: 'the transcripts sit behind a directory that refuses to list', + needsDeniedRead: true, + visibleWithNoRows: false, + detach: (_root, transcriptDir) => chmod(transcriptDir, 0o000), + attach: (_root, transcriptDir) => chmod(transcriptDir, 0o755) + } +] + +type Operation = { + name: string + /** True when the operation throws the index away, so no row survives it. */ + clearsIndex?: boolean + /** Healthy-root sessions the operation deletes from disk. */ + deletes?: readonly string[] + /** Construction options for every indexer this cell opens. */ + options?: Partial + run: (context: MatrixContext) => Promise +} + +const OPERATIONS: Operation[] = [ + { name: 'one cycle', run: (context) => context.cycle() }, + { + name: 'two cycles', + run: async (context) => { + await context.cycle() + await context.cycle() + } + }, + { + name: 'close and restart', + run: (context) => context.reopen() + }, + { + name: 'two full reconciles', + run: async (context) => { + await context.indexer().reconcile({ full: true }) + await context.indexer().reconcile({ full: true }) + } + }, + { + name: 'one healthy transcript deleted', + deletes: SESSIONS.slice(0, 1), + run: (context) => context.cycle() + }, + { + name: 'every healthy transcript deleted', + deletes: SESSIONS, + run: async (context) => { + // Twice: a root that goes from holding transcripts to holding none in one + // pass is unverifiable for that pass, so the second is the proving one. + await context.indexer().reconcile({ full: true }) + await context.indexer().reconcile({ full: true }) + } + }, + { + // The cadence that replaced every re-arm-on-recovery rule: no caller asks + // for this sweep, so the cell drives it off the timer alone. + name: 'the periodic sweep comes round', + options: { fullSweepEveryCycles: 2 }, + run: async (context) => { + await context.cycle() + await context.cycle() + await context.cycle() + } + }, + { + // Every pass is out of wall time from its first file, so each one hands + // almost all of its work back. A pass that read almost nothing must still + // not conclude anything about what it did not reach. + name: 'every pass out of time at its first file', + options: { passDeadlineMs: 0 }, + run: async (context) => { + await context.cycle() + await context.cycle() + } + }, + { + // What replaced `setHistoryDays`: a new instance over the same database. + // Every transcript here was written just now, so a 30-day window holds all + // of them and no row may be purged. + name: 'reconstructed for a narrower history window', + run: (context) => context.reopen({ historyDays: 30 }) + }, + { + // What replaced `clear()`, exactly as the PR body documents it. + name: 'the index thrown away and rebuilt', + clearsIndex: true, + run: (context) => context.reopen({ removeDatabase: true }) + } +] + +type MatrixContext = { + indexer: () => SessionSearchIndexer + /** Closes and constructs again over the same path: the immutable design's one edit. */ + reopen: (args?: { historyDays?: number | null; removeDatabase?: boolean }) => Promise + cycle: () => Promise + detachedRoot: string + detachedPaths: string[] +} + +function fullSessionId(prefix: string): string { + return `${prefix}-bbbb-4ccc-8ddd-eeeeeeeeeeee` +} + +let harness: SessionSearchIndexerHarness +let clock: FakeSessionSearchClock +let indexer: SessionSearchIndexer | null + +beforeEach(async () => { + resetSessionParseCacheForTests() + resetTranscriptConsumersForTests() + clock = new FakeSessionSearchClock() + harness = await openSessionSearchIndexerHarness('ss-lifecycle') + indexer = null +}) + +afterEach(async () => { + indexer?.close() + resetTranscriptConsumersForTests() + resetSessionParseCacheForTests() + await harness.cleanup() +}) + +function open(overrides: Partial = {}): SessionSearchIndexer { + indexer = new SessionSearchIndexer({ + databasePath: harness.databasePath, + roots: harness.roots, + historyDays: null, + clock, + reconcileIntervalMs: INTERVAL_MS, + ...overrides + }) + return indexer +} + +/** + * Runs cycles until the index stops growing. Every operation but the + * out-of-time one settles on the first call; that one reads a transcript a pass. + */ +async function driveUntilIndexed(maxCycles: number): Promise { + let held = indexedSessions().length + for (let cycle = 0; cycle < maxCycles; cycle++) { + clock.advance(INTERVAL_MS) + await indexer?.settled() + const now = indexedSessions().length + if (now === held) { + return + } + held = now + } +} + +/** Session ids the index answers for, whichever agent wrote them. */ +function indexedSessions(): string[] { + return harness + .read( + (db: SyncDatabase) => + db.prepare('SELECT session_id AS id FROM sessions').all() as { id: string }[] + ) + .map((row) => row.id) + .sort() +} + +for (const roots of ROOT_SHAPES) { + for (const unreachable of UNREACHABLE_SHAPES) { + describe.skipIf(unreachable.needsDeniedRead && !CAN_DENY_READ)( + `${roots.name}, ${unreachable.name}`, + () => { + for (const operation of OPERATIONS) { + it(operation.name, async () => { + const detachedRoot = roots.detachedRoot(harness) + const detachedPaths = SESSIONS.map((session) => roots.detachedFile(harness, session)) + const healthyPaths = SESSIONS.map((session) => roots.healthyFile(harness, session)) + for (const [index, session] of SESSIONS.entries()) { + await roots.writeDetached(detachedPaths[index] ?? '', session) + await roots.writeHealthy(healthyPaths[index] ?? '', session) + } + const transcriptDir = dirname(detachedPaths[0] ?? '') + const parked = join(harness.root, 'parked-root') + + await open(operation.options).start() + // A deadline that expires on the first file reads one transcript a + // pass, so the setup drives passes until the index has caught up. + await driveUntilIndexed(SESSIONS.length * 2) + const detachedIds = detachedPaths.map((_path, index) => + roots === ROOT_SHAPES[0] + ? fullSessionId(SESSIONS[index] ?? '') + : (SESSIONS[index] ?? '') + ) + const healthyIds = SESSIONS.map((session) => session) + expect(indexedSessions()).toEqual([...detachedIds, ...healthyIds].sort()) + // One cycle so the watch set holds the recency window, which is the + // state a running indexer is in when a volume goes away. + clock.advance(INTERVAL_MS) + await indexer?.settled() + + await unreachable.detach(detachedRoot, transcriptDir, parked) + try { + const kept = SESSIONS.filter((session) => !operation.deletes?.includes(session)) + for (const session of operation.deletes ?? []) { + await rm(healthyPaths[SESSIONS.indexOf(session)] ?? '') + } + await operation.run({ + indexer: () => indexer as SessionSearchIndexer, + reopen: async (args = {}) => { + indexer?.close() + resetTranscriptConsumersForTests() + resetSessionParseCacheForTests() + if (args.removeDatabase === true) { + removeSessionSearchDatabase(harness.databasePath) + } + const overrides = { ...operation.options } + if ('historyDays' in args) { + overrides.historyDays = args.historyDays + } + await open(overrides).start() + await driveUntilIndexed(SESSIONS.length * 2) + }, + cycle: async () => { + clock.advance(INTERVAL_MS) + await indexer?.settled() + }, + detachedRoot, + detachedPaths + }) + + // A: nothing that still exists lost its rows. + const survivingDetached = operation.clearsIndex ? [] : detachedIds + expect(indexedSessions()).toEqual([...survivingDetached, ...kept].sort()) + + const status = indexer?.status() + const degraded = status?.degradedRoots.map((root) => root.root) ?? [] + // With no rows under it, the only thing a pass can go on is + // whether the root itself refuses to list. + if (operation.clearsIndex && !unreachable.visibleWithNoRows) { + expect(degraded).not.toContain(detachedRoot) + } else { + // B: named, by a real directory rather than a joined label. + expect(degraded).toContain(detachedRoot) + expect(degraded.every((root) => !root.includes(delimiter))).toBe(true) + // C: not current while a root is degraded. + expect(status?.phase).not.toBe('current') + } + } finally { + await unreachable.attach(detachedRoot, transcriptDir, parked) + } + + // D: reachable again, a sweep reads the whole tree back. + await mkdir(dirname(healthyPaths[0] ?? ''), { recursive: true }) + await indexer?.reconcile({ full: true }) + await driveUntilIndexed(SESSIONS.length * 2) + expect(indexedSessions()).toEqual( + [ + ...detachedIds, + ...SESSIONS.filter((session) => !operation.deletes?.includes(session)) + ].sort() + ) + }) + } + } + ) + } +} diff --git a/src/main/ai-vault-search/session-search-live-transcript.test.ts b/src/main/ai-vault-search/session-search-live-transcript.test.ts new file mode 100644 index 00000000000..1ea58ca5283 --- /dev/null +++ b/src/main/ai-vault-search/session-search-live-transcript.test.ts @@ -0,0 +1,208 @@ +import { mkdtemp, rm, writeFile, appendFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import { resetSessionParseCacheForTests } from '../ai-vault/session-scanner-parse-cache' +import { + registerTranscriptConsumer, + resetTranscriptConsumersForTests, + type TranscriptSessionIdentity +} from '../ai-vault/session-transcript-consumers' +import { requestWholeTranscriptRead } from '../ai-vault/session-transcript-reader' +import SyncDatabase from '../sqlite/sync-database' +import { registerSessionSearchIndexConsumer } from './session-search-index-consumer' +import { SessionSearchStore } from './session-search-store' +import { + assistantRecord, + CLAUDE_SESSION_ID as SESSION_ID, + CODEX_ROLLOUT_FILE, + CODEX_SESSION_ID, + codexRolloutLines, + parseTranscript, + userRecord +} from './session-search-transcript-fixtures' + +let tempRoots: string[] = [] +let store: SessionSearchStore +// The store keeps its connection private, so row assertions need a second one. +let reader: SyncDatabase +let errors: unknown[] + +beforeEach(async () => { + resetSessionParseCacheForTests() + resetTranscriptConsumersForTests() + errors = [] + const path = join(await makeTempDir(), 'index.sqlite') + store = new SessionSearchStore(path, (error) => errors.push(error)) + registerSessionSearchIndexConsumer(store) + reader = new SyncDatabase(path, { readonly: true }) +}) + +afterEach(async () => { + resetTranscriptConsumersForTests() + reader.close() + store.close() + await Promise.all(tempRoots.map((root) => rm(root, { recursive: true, force: true }))) + tempRoots = [] +}) + +async function makeTempDir(): Promise { + const root = await mkdtemp(join(tmpdir(), 'orca-session-search-live-')) + tempRoots.push(root) + return root +} + +/** Sessions a query would return for one FTS term, read on a second handle. */ +function sessionsMatching(term: string): string[] { + return ( + reader + .prepare( + `SELECT DISTINCT s.session_id AS id FROM messages_fts + JOIN messages m ON m.id = messages_fts.rowid + JOIN sessions s ON s.id = m.session_row_id + WHERE messages_fts MATCH ? ORDER BY s.session_id` + ) + .all(term) as { id: string }[] + ).map((row) => row.id) +} + +it('indexes a Claude transcript through the reader and resumes on append', async () => { + const root = await makeTempDir() + const path = join(root, `${SESSION_ID}.jsonl`) + await writeFile( + path, + `${[ + userRecord(0, 'find the flaky terminal reattach'), + assistantRecord(1, 'look at resolveTerminalPath first') + ].join('\n')}\n` + ) + await parseTranscript(path) + expect(errors).toEqual([]) + expect(sessionsMatching('reattach')).toEqual([SESSION_ID]) + // The identifier column shadows a camel-case symbol into its pieces. + expect(sessionsMatching('terminal')).toEqual([SESSION_ID]) + + await appendFile(path, `${assistantRecord(2, 'the zygomorphic follow-up landed')}\n`) + const resumed = await parseTranscript(path) + // The reader resumed, so the index saw an `append`, not a whole re-read. + expect(resumed.stats).toMatchObject({ incremental: 1, fullParses: 0 }) + expect(errors).toEqual([]) + expect(sessionsMatching('zygomorphic')).toEqual([SESSION_ID]) + // An append extends one session rather than creating a second. + expect(reader.prepare('SELECT count(*) AS n FROM sessions').get()).toEqual({ + n: 1 + }) +}) + +it('keeps a tool result searchable but out of the conversation half', async () => { + const root = await makeTempDir() + const codexHome = await makeTempDir() + const path = join(root, CODEX_ROLLOUT_FILE) + await writeFile( + path, + `${codexRolloutLines( + ['rg', 'pericardium'], + `outputonly ${'padding '.repeat(600)}tailonly`, + 'promptonly search for the module' + ).join('\n')}\n` + ) + await parseTranscript(path, 'codex', codexHome) + expect(errors).toEqual([]) + + expect(sessionsMatching('pericardium')).toHaveLength(1) + // The prompt is conversation; the command output is not, and the column + // filter is what tells them apart. + expect(sessionsMatching('outputonly')).toHaveLength(1) + expect(sessionsMatching('tailonly')).toHaveLength(0) + expect(sessionsMatching('rg')).toHaveLength(1) + expect(sessionsMatching('{user_text assistant_text}: promptonly')).toHaveLength(1) + expect(sessionsMatching('{user_text assistant_text}: outputonly')).toHaveLength(0) + expect(sessionsMatching('{user_text assistant_text}: rg')).toHaveLength(0) +}) + +/** What `start.identity()` returns at each message of one read. */ +function recordIdentityPerMessage(): (TranscriptSessionIdentity | null)[] { + const seen: (TranscriptSessionIdentity | null)[] = [] + registerTranscriptConsumer({ + beginRead: (start) => ({ + message: () => { + seen.push(start.identity?.() ?? null) + }, + finish: () => undefined + }) + }) + return seen +} + +it('names the session mid-read, before the reader has finished the file', async () => { + const root = await makeTempDir() + const path = join(root, `${SESSION_ID}.jsonl`) + await writeFile( + path, + `${[ + userRecord(0, 'find the flaky terminal reattach'), + assistantRecord(1, 'look at resolveTerminalPath first') + ].join('\n')}\n` + ) + const seen = recordIdentityPerMessage() + await parseTranscript(path) + + // A chunked read commits partway through a file this size or larger, so what + // it can name the session with is exactly this. + expect(seen.length).toBeGreaterThan(0) + expect(seen[0]).toMatchObject({ + sessionId: SESSION_ID, + cwd: '/repo/app', + createdAt: expect.any(String) + }) +}) + +it('names a Codex session mid-read from its own opening record', async () => { + const root = await makeTempDir() + const codexHome = await makeTempDir() + const path = join(root, CODEX_ROLLOUT_FILE) + await writeFile( + path, + `${codexRolloutLines(['rg', 'pericardium'], 'src/main/pericardium.ts:12: match', 'search for the pericardium module').join('\n')}\n` + ) + const seen = recordIdentityPerMessage() + await parseTranscript(path, 'codex', codexHome) + + // Codex builds its own resumable state rather than the shared accumulator + // fold, so it is the other half of the surface a chunked commit depends on. + expect(seen[0]).toMatchObject({ + sessionId: CODEX_SESSION_ID, + cwd: '/repo/app' + }) +}) + +it('indexes a file the session list already read past, once a whole read is asked for', async () => { + const root = await makeTempDir() + const path = join(root, `${SESSION_ID}.jsonl`) + await writeFile(path, `${userRecord(0, 'the opening prompt')}\n`) + + // The state on first enablement inside a running app: the session list has + // read this file, so the parse cache is warm, while the index is empty. + resetTranscriptConsumersForTests() + await parseTranscript(path) + registerSessionSearchIndexConsumer(store) + + await appendFile(path, `${assistantRecord(1, 'a zygomorphic reply')}\n`) + const appended = await parseTranscript(path) + expect(appended.stats).toMatchObject({ incremental: 1, fullParses: 0 }) + // The append continued from a byte offset the index never saw, so it declined. + expect(sessionsMatching('zygomorphic')).toEqual([]) + + // The index holds no row for this file at all, and that is the record: a + // path the file table does not name is read from the start by the next pass, + // which is what asks the reader to drop the session list's resume point. + expect(store.files()).toEqual([]) + requestWholeTranscriptRead(path) + + const reread = await parseTranscript(path) + expect(reread.stats).toMatchObject({ incremental: 0, fullParses: 1 }) + expect(errors).toEqual([]) + expect(sessionsMatching('zygomorphic')).toEqual([SESSION_ID]) + expect(sessionsMatching('opening')).toEqual([SESSION_ID]) + expect(store.files().map((row) => row.state)).toEqual(['current']) +}) diff --git a/src/main/ai-vault-search/session-search-merged-roots.test.ts b/src/main/ai-vault-search/session-search-merged-roots.test.ts new file mode 100644 index 00000000000..8d41b047cae --- /dev/null +++ b/src/main/ai-vault-search/session-search-merged-roots.test.ts @@ -0,0 +1,135 @@ +import { chmod, rm } from 'node:fs/promises' +import { delimiter, join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import { resetSessionParseCacheForTests } from '../ai-vault/session-scanner-parse-cache' +import { resetTranscriptConsumersForTests } from '../ai-vault/session-transcript-consumers' +import type SyncDatabase from '../sqlite/sync-database' +import { SessionSearchIndexer } from './session-search-indexer' +import { + FakeSessionSearchClock, + openSessionSearchIndexerHarness, + writeMessageGraphTranscript, + type SessionSearchIndexerHarness +} from './session-search-indexer-test-fixture' + +// OpenClaw is the one agent whose roots are alternates for a single install, so +// discovery reports them as ONE discovery whose rootDir is every path joined by +// the platform's path delimiter. That string is not a directory: readdir on it +// answers ENOENT, containment never matches a real file, and a scan issue +// recorded against a real root never compares equal to it. Everything that +// judges a root works on the constituent directories, taken from the same +// source table discovery reads, never by splitting the label -- a directory may +// legally contain the delimiter. + +const CAN_DENY_READ = process.platform !== 'win32' && process.getuid?.() !== 0 +const INTERVAL_MS = 20_000 + +let harness: SessionSearchIndexerHarness +let clock: FakeSessionSearchClock +let indexer: SessionSearchIndexer + +beforeEach(async () => { + resetSessionParseCacheForTests() + resetTranscriptConsumersForTests() + clock = new FakeSessionSearchClock() + harness = await openSessionSearchIndexerHarness('ss-merged-roots') +}) + +afterEach(async () => { + indexer.close() + resetTranscriptConsumersForTests() + resetSessionParseCacheForTests() + await harness.cleanup() +}) + +/** OpenClaw reads `/agents/**` and keeps only paths through `sessions`. */ +function openclawTranscript(stateDir: string, name: string): string { + return join(stateDir, 'agents', 'main', 'sessions', `${name}.jsonl`) +} + +function sessionsMatching(term: string): string[] { + return harness.read((db: SyncDatabase) => + ( + db + .prepare( + `SELECT DISTINCT s.session_id AS id FROM messages_fts + JOIN messages m ON m.id = messages_fts.rowid + JOIN sessions s ON s.id = m.session_row_id + WHERE messages_fts MATCH ? ORDER BY s.session_id` + ) + .all(term) as { id: string }[] + ).map((row) => row.id) + ) +} + +it.skipIf(!CAN_DENY_READ)('fences one merged root without taking its partner down', async () => { + const current = harness.roots.openclawStateDir ?? '' + const legacy = harness.roots.openclawLegacyStateDir ?? '' + const mounted = openclawTranscript(current, 'mounted-session') + const local = openclawTranscript(legacy, 'local-session') + await writeMessageGraphTranscript(mounted, ['a conversation on the mounted volume']) + await writeMessageGraphTranscript(local, ['a conversation on local disk']) + + indexer = new SessionSearchIndexer({ + databasePath: harness.databasePath, + roots: harness.roots, + historyDays: null, + clock, + reconcileIntervalMs: INTERVAL_MS + }) + await indexer.start() + expect(sessionsMatching('conversation').sort()).toEqual(['local-session', 'mounted-session']) + + // One of the two roots goes away; the other is untouched. + await chmod(join(current, 'agents'), 0o000) + try { + await indexer.reconcile({ full: true }) + + const status = indexer.status() + const degraded = status.degradedRoots.map((root) => root.root) + // A real directory, not the joined string discovery reports. + expect(degraded).toContain(join(current, 'agents')) + expect(degraded.every((root) => !root.includes(delimiter))).toBe(true) + // Unprovable, so the unreadable root keeps its rows. + expect(sessionsMatching('mounted')).toEqual(['mounted-session']) + } finally { + await chmod(join(current, 'agents'), 0o755) + } +}) + +it('retires from one merged root while its partner is healthy', async () => { + const current = harness.roots.openclawStateDir ?? '' + const legacy = harness.roots.openclawLegacyStateDir ?? '' + const going = openclawTranscript(current, 'going-session') + await writeMessageGraphTranscript(going, ['a conversation about to be deleted']) + // A sibling in the same root, so deleting one leaves the root listing files + // and therefore healthy: this is a deletion, not an unmount. + await writeMessageGraphTranscript(openclawTranscript(current, 'sibling-session'), [ + 'a conversation beside it' + ]) + await writeMessageGraphTranscript(openclawTranscript(legacy, 'staying-session'), [ + 'a conversation that stays' + ]) + + indexer = new SessionSearchIndexer({ + databasePath: harness.databasePath, + roots: harness.roots, + historyDays: null, + clock, + reconcileIntervalMs: INTERVAL_MS + }) + await indexer.start() + expect(sessionsMatching('conversation').sort()).toEqual([ + 'going-session', + 'sibling-session', + 'staying-session' + ]) + + // A genuine deletion inside a healthy root still retires normally. + await rm(going) + await indexer.reconcile({ full: true }) + + expect(sessionsMatching('deleted')).toEqual([]) + expect(indexer.status().degradedRoots).toEqual([]) + expect(sessionsMatching('conversation').sort()).toEqual(['sibling-session', 'staying-session']) +}) diff --git a/src/main/ai-vault-search/session-search-message-rows.test.ts b/src/main/ai-vault-search/session-search-message-rows.test.ts new file mode 100644 index 00000000000..d2cf2fbca61 --- /dev/null +++ b/src/main/ai-vault-search/session-search-message-rows.test.ts @@ -0,0 +1,249 @@ +import { expect, it } from 'vitest' +import type { TranscriptMessage } from '../ai-vault/session-transcript-consumers' +import { insertSearchMessage, searchMessageRows } from './session-search-message-rows' +import { + openSessionSearchIndexFile, + type SessionSearchIndexFile +} from './session-search-index-test-fixture' + +/** Every column of the FTS table, so an assertion cannot miss the shadow terms. */ +async function indexedColumns( + index: SessionSearchIndexFile, + message: TranscriptMessage +): Promise { + for (const row of searchMessageRows([message])) { + insertSearchMessage(index.db, 1, row) + } + const full = index.db + .prepare('SELECT user_text, assistant_text, tool_text, identifiers FROM messages_fts') + .all() as Record[] + return full.flatMap((row) => Object.values(row)) +} + +it('splits an oversized message on a line boundary and keeps every character', () => { + const line = `${'padding '.repeat(11)}word\n` + const text = line.repeat(400) + const chunks = [...searchMessageRows([{ role: 'user', text, timestamp: null }])].map( + (row) => row.text + ) + + expect(chunks.length).toBeGreaterThan(1) + expect(chunks.join('')).toBe(text) + for (const chunk of chunks) { + expect(chunk.length).toBeLessThanOrEqual(8000) + expect(chunk.endsWith('\n')).toBe(true) + } +}) + +it('cuts at whitespace rather than through the word on the boundary', async () => { + const index = await openSessionSearchIndexFile('ss-rows-whitespace') + try { + // The 8,000th character lands inside `pericardium`. Cutting at the target + // would file `per` under one row and `icardium` under another, and the word + // the user types would match neither. + const text = `${' '.repeat(7997)}pericardium` + const chunks = [...searchMessageRows([{ role: 'user', text, timestamp: null }])] + expect(chunks.map((row) => row.text).join('')).toBe(text) + for (const row of chunks) { + insertSearchMessage(index.db, 1, row) + } + + expect( + index.db + .prepare('SELECT count(*) AS n FROM messages_fts WHERE messages_fts MATCH ?') + .get('pericardium') + ).toEqual({ n: 1 }) + } finally { + await index.close() + } +}) + +it.each(['/repo/pericardium.ts', 'PROJ-12345', 'C++', 'cafe\u0301ine'])( + 'preserves the exact FTS token %s at a chunk boundary', + async (token) => { + const index = await openSessionSearchIndexFile('ss-rows-tokenchars') + try { + const text = ' '.repeat(7998) + token + const chunks = [...searchMessageRows([{ role: 'user', text, timestamp: null }])] + expect(chunks.map((row) => row.text).join('')).toBe(text) + for (const row of chunks) { + insertSearchMessage(index.db, 1, row) + } + expect( + index.db + .prepare('SELECT count(*) AS n FROM messages_fts WHERE messages_fts MATCH ?') + .get(`"${token}"`) + ).toEqual({ n: 1 }) + } finally { + await index.close() + } + } +) + +it.each(['\u0305', '\u030d', '\u0332'])( + 'cuts at a combining mark unicode61 treats as a separator: %s', + async (mark) => { + const index = await openSessionSearchIndexFile('ss-rows-unicode-separator') + try { + const text = `${'x'.repeat(7997)}${mark}pericardium` + for (const row of searchMessageRows([{ role: 'user', text, timestamp: null }])) { + insertSearchMessage(index.db, 1, row) + } + expect( + index.db + .prepare("SELECT count(*) AS n FROM messages_fts WHERE messages_fts MATCH 'pericardium'") + .get() + ).toEqual({ n: 1 }) + } finally { + await index.close() + } + } +) + +it('backs up to any whitespace, not only a newline', () => { + // An ideographic space separates words in a CJK transcript exactly as a + // space does here, and a newline-only backoff tears the token after it. + const text = `${'\u4e00'.repeat(7000)}\u3000${'\u4e8c'.repeat(2000)}` + const chunks = [...searchMessageRows([{ role: 'user', text, timestamp: null }])].map( + (row) => row.text + ) + + expect(chunks[0]).toBe(`${'\u4e00'.repeat(7000)}\u3000`) + expect(chunks.join('')).toBe(text) +}) + +it('cuts at punctuation when the window holds no whitespace at all', async () => { + const index = await openSessionSearchIndexFile('ss-rows-minified') + try { + // Valid minified JSON, the shape a tool result carries: 8,000 characters + // without a single space. The 8,000th lands inside `pericardium`, and a + // whitespace-only backoff has nothing in the window to back up to, so it + // files `perica` under one row and `rdium` under the next. + const text = `{"pad":"${'x'.repeat(7976)}","note":"pericardium"}` + expect(JSON.parse(text)).toEqual({ pad: 'x'.repeat(7976), note: 'pericardium' }) + expect(text.slice(7994, 8005)).toBe('pericardium') + expect(/\s/.test(text)).toBe(false) + + const chunks = [...searchMessageRows([{ role: 'user', text, timestamp: null }])] + expect(chunks.map((row) => row.text).join('')).toBe(text) + for (const row of chunks) { + insertSearchMessage(index.db, 1, row) + } + + expect( + index.db + .prepare('SELECT count(*) AS n FROM messages_fts WHERE messages_fts MATCH ?') + .get('pericardium') + ).toEqual({ n: 1 }) + } finally { + await index.close() + } +}) + +it('keeps a 9,000-character identifier whole rather than cutting at its underscores', () => { + // `_` sits inside a token for this tokenizer, so it is not a boundary. A + // snake_case name that long holds none at all, and the target itself is the + // honest cut — backing up to every `_` would file the name in pieces. + const text = 'ab_'.repeat(3000) + expect(text.length).toBe(9000) + const chunks = [...searchMessageRows([{ role: 'user', text, timestamp: null }])].map( + (row) => row.text + ) + + expect(chunks.map((chunk) => chunk.length)).toEqual([8000, 1000]) + expect(chunks.join('')).toBe(text) +}) + +it('still chunks a message that holds no whitespace at all', () => { + // A 20,000-character token is not a word, so the target itself is the cut and + // the message is still bounded. + const chunks = [ + ...searchMessageRows([{ role: 'user', text: 'a'.repeat(20_000), timestamp: null }]) + ] + expect(chunks.map((row) => row.text.length)).toEqual([8000, 8000, 4000]) +}) + +it('leaves a message that fits as a single row', () => { + const rows = [...searchMessageRows([{ role: 'user', text: 'short enough', timestamp: null }])] + expect(rows.map((row) => row.text)).toEqual(['short enough']) +}) + +it('caps a tool row at its head and never caps the conversation', async () => { + const index = await openSessionSearchIndexFile('ss-rows-tool-cap') + try { + // The reader hands over untruncated text (its own bound is 256 KB per + // message and a consumer may be handed more); the cap is this module's. + const output = `pericardium ${'padding '.repeat(140_000)}` + expect(output.length).toBeGreaterThan(1024 * 1024) + + const toolRows = [...searchMessageRows([{ role: 'tool', text: output, timestamp: null }])] + expect(toolRows).toHaveLength(1) + expect(toolRows[0]!.text.length).toBe(3072) + // The head is what identifies what ran, so it is what survives. + expect(toolRows[0]!.text.startsWith('pericardium ')).toBe(true) + + // The same text as an assistant turn is conversation, and keeps every byte. + const assistantRows = [ + ...searchMessageRows([{ role: 'assistant', text: output, timestamp: null }]) + ] + expect(assistantRows.map((row) => row.text).join('')).toBe(output) + expect(assistantRows.length).toBeGreaterThan(100) + + for (const row of toolRows) { + insertSearchMessage(index.db, 1, row) + } + expect( + index.db + .prepare('SELECT count(*) AS n FROM messages_fts WHERE messages_fts MATCH ?') + .get('pericardium') + ).toEqual({ n: 1 }) + } finally { + await index.close() + } +}) + +it('files a tool row under the tool column alone', async () => { + const index = await openSessionSearchIndexFile('ss-message-rows-tool') + try { + for (const row of searchMessageRows([ + { role: 'tool', text: 'rg pericardium', timestamp: null } + ])) { + insertSearchMessage(index.db, 1, row) + } + expect(index.db.prepare('SELECT count(*) AS n FROM messages_fts').get()).toEqual({ n: 1 }) + // What makes a conversation-scoped search exclude it: the column filter, not + // a second table. + expect( + index.db + .prepare('SELECT count(*) AS n FROM messages_fts WHERE messages_fts MATCH ?') + .get('{user_text assistant_text}: pericardium') + ).toEqual({ n: 0 }) + expect( + index.db + .prepare('SELECT count(*) AS n FROM messages_fts WHERE messages_fts MATCH ?') + .get('{tool_text}: pericardium') + ).toEqual({ n: 1 }) + } finally { + await index.close() + } +}) + +it('stores a chunk exactly as the transcript wrote it', async () => { + const index = await openSessionSearchIndexFile('ss-rows-verbatim') + try { + const text = 'deploy with AKIAIOSFODNN7EXAMPLE and the resolveTerminalPath fix' + const stored = await indexedColumns(index, { + role: 'assistant', + text, + timestamp: null + }) + + // The index is a second copy of content the user already holds in plaintext, + // so it neither rewrites nor drops any of it. + expect(stored).toContain(text) + // Identifier shadow terms come off that same raw chunk. + expect(stored.some((column) => column.includes('resolve terminal path'))).toBe(true) + } finally { + await index.close() + } +}) diff --git a/src/main/ai-vault-search/session-search-message-rows.ts b/src/main/ai-vault-search/session-search-message-rows.ts new file mode 100644 index 00000000000..21254c183aa --- /dev/null +++ b/src/main/ai-vault-search/session-search-message-rows.ts @@ -0,0 +1,135 @@ +import type SyncDatabase from '../sqlite/sync-database' +import type { TranscriptMessage } from '../ai-vault/session-transcript-consumers' +import { sliceAtCodeUnitLimit } from '../ai-vault/session-scanner-text-normalization' +import { identifierShadowText } from './session-search-identifier-split' + +const CHUNK_TARGET_CHARS = 8000 + +/** + * How much of one tool output is indexed. Its head: a command, its arguments and + * the first lines of what it printed are what a user searches for, while the + * tail is the padding that makes these messages large in the first place. + * + * Tool output is 80-97 % of a transcript's bytes, and a single one can be a + * quarter of a megabyte (the reader's own per-message bound). Without this the + * index, the in-memory buffer a read holds and the transaction it commits are + * all sized by how much a tool printed rather than by how much is worth + * searching. 3 KB was the accuracy/size sweet spot in the original design + * measurement. User and assistant text is never capped: it is the conversation, + * and it is small. + */ +const TOOL_ROW_CHARS = 3072 + +// Keep unicode61's tokenchars intact, including before an available space. +// SQLite ext/fts5/fts5_unicode2.c: sqlite3Fts5UnicodeIsdiacritic, with remove_diacritics=1. +const FOLDED_DIACRITIC = + /[\u0300-\u0304\u0306-\u030c\u030f\u0311\u031b\u0323-\u0328\u032d-\u032e\u0330-\u0331]/ +const TOKEN_BOUNDARY = /[^\p{L}\p{N}\p{Co}_.\-/+\uD800-\uDFFF]/u + +/** + * Index just past the last token boundary in `[floor, end)`, or -1 when the + * window holds none. Not only a newline: a wrapped paragraph, a CJK transcript + * separated by ideographic spaces and a minified log all chunk on a boundary a + * tokenizer would have picked anyway. + */ +function lastTokenBoundaryEnd(text: string, floor: number, end: number): number { + for (let at = end - 1; at >= floor; at--) { + if (TOKEN_BOUNDARY.test(text[at]!) && !FOLDED_DIACRITIC.test(text[at]!)) { + return at + 1 + } + } + return -1 +} + +/** + * Splits an oversized message into rows of at most `CHUNK_TARGET_CHARS`, cutting + * on a token boundary so no token is torn in half and every word stays + * searchable. A phrase that straddles two chunks is not matched: chunks are + * separate FTS rows and FTS5 cannot span them. + */ +function* textChunks(text: string): Generator { + if (text.length <= CHUNK_TARGET_CHARS) { + yield text + return + } + let start = 0 + while (start < text.length) { + let end = Math.min(text.length, start + CHUNK_TARGET_CHARS) + if (end < text.length) { + // Only the second half of the window: backing up further would trade a + // torn token for chunks half the size. No boundary at all in 4,000 + // characters is not a word, so the target itself is the honest cut. + const split = lastTokenBoundaryEnd(text, start + CHUNK_TARGET_CHARS / 2, end) + if (split > start) { + end = split + } + } + yield text.slice(start, end) + start = end + } +} + +/** + * The row policy for one message: a `tool` message becomes one capped row, and + * anything else becomes N chunks, because FTS5 ranks a short row far better + * than a huge one. + */ +export function* searchMessageRows( + messages: Iterable +): Generator { + for (const message of messages) { + if (message.role === 'tool') { + yield { + ...message, + text: sliceAtCodeUnitLimit(message.text, TOOL_ROW_CHARS) + } + continue + } + for (const text of textChunks(message.text)) { + yield { ...message, text } + } + } +} + +/** + * Writes one row into `messages` and `messages_fts` in the caller's + * transaction, so a message is never present in one and absent from the other. + * A conversation-scoped query filters the columns rather than reading a second + * table (see the schema). + */ +export function insertSearchMessage( + db: SyncDatabase, + sessionId: number, + message: TranscriptMessage +): void { + const text = message.text + const id = db + .prepare('INSERT INTO messages(session_row_id, role, ts) VALUES (?, ?, ?)') + .run(sessionId, message.role, message.timestamp).lastInsertRowid + const user = message.role === 'user' ? text : '' + const assistant = message.role === 'assistant' ? text : '' + const tool = message.role === 'tool' ? text : '' + db.prepare( + 'INSERT INTO messages_fts(rowid,user_text,assistant_text,tool_text,identifiers) VALUES (?,?,?,?,?)' + ).run(id, user, assistant, tool, identifierShadowText(text)) +} + +/** + * Deletes up to `limit` of a session's rows from `messages` and `messages_fts`, + * in the caller's transaction, and reports how many went. Bounded + * because a retention sweep must not hold one transaction over a whole + * session; a replace passes no limit, since its rows and their replacements + * have to land together. + */ +export function deleteSearchMessages(db: SyncDatabase, sessionId: number, limit = -1): number { + const ids = db + .prepare('SELECT id FROM messages WHERE session_row_id = ? LIMIT ?') + .all(sessionId, limit) as { id: number }[] + const full = db.prepare('DELETE FROM messages_fts WHERE rowid = ?') + const message = db.prepare('DELETE FROM messages WHERE id = ?') + for (const { id } of ids) { + full.run(id) + message.run(id) + } + return ids.length +} diff --git a/src/main/ai-vault-search/session-search-native-chat-indexing.test.ts b/src/main/ai-vault-search/session-search-native-chat-indexing.test.ts new file mode 100644 index 00000000000..deab4e8b785 --- /dev/null +++ b/src/main/ai-vault-search/session-search-native-chat-indexing.test.ts @@ -0,0 +1,113 @@ +import { appendFile, mkdir, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import { resetSessionParseCacheForTests } from '../ai-vault/session-scanner-parse-cache' +import { resetTranscriptConsumersForTests } from '../ai-vault/session-transcript-consumers' +import type SyncDatabase from '../sqlite/sync-database' +import { SessionSearchIndexer } from './session-search-indexer' +import { + FakeSessionSearchClock, + openSessionSearchIndexerHarness, + type SessionSearchIndexerHarness +} from './session-search-indexer-test-fixture' + +// Reviewer F4, and the plan's fourth open decision: a conversation held in +// Orca's own chat is the same file in the same place as one held in the +// terminal, so it must be searchable through the same path with no panel +// mounted, no scanner service running, and nobody calling refresh. Everything +// below is the library and the filesystem. + +const INTERVAL_MS = 20_000 +const SESSION_ID = 'cccccccc-dddd-4eee-8fff-000000000000' +const CWD = '/repo/orca' + +let harness: SessionSearchIndexerHarness +let clock: FakeSessionSearchClock +let indexer: SessionSearchIndexer + +beforeEach(async () => { + resetSessionParseCacheForTests() + resetTranscriptConsumersForTests() + clock = new FakeSessionSearchClock() + harness = await openSessionSearchIndexerHarness('ss-native-chat') +}) + +afterEach(async () => { + indexer.close() + resetTranscriptConsumersForTests() + resetSessionParseCacheForTests() + await harness.cleanup() +}) + +/** The rows Orca's native chat writes: uuid, block content, cwd on the first turn. */ +function nativeChatTurn(uuid: string, role: 'user' | 'assistant', text: string): string { + const timestamp = new Date(1_740_000_000_000 + Number(uuid.slice(-2)) * 60_000).toISOString() + return JSON.stringify({ + type: role, + uuid, + sessionId: SESSION_ID, + timestamp, + cwd: CWD, + gitBranch: 'main', + message: { + role, + ...(role === 'assistant' ? { model: 'claude-fable-5' } : {}), + content: [{ type: 'text', text }] + } + }) +} + +function messageTexts(term: string): { role: string; session: string }[] { + return harness.read( + (db: SyncDatabase) => + db + .prepare( + `SELECT m.role AS role, s.session_id AS session FROM messages_fts + JOIN messages m ON m.id = messages_fts.rowid + JOIN sessions s ON s.id = m.session_row_id + WHERE messages_fts MATCH ? ORDER BY m.id` + ) + .all(term) as { role: string; session: string }[] + ) +} + +it('indexes a native-chat conversation and its later turns with no panel and no service', async () => { + const path = join(harness.claudeProjectDir, `${SESSION_ID}.jsonl`) + await mkdir(harness.claudeProjectDir, { recursive: true }) + await writeFile( + path, + `${[ + nativeChatTurn('turn-01', 'user', 'why does the relay drop the lease at 105 seconds'), + nativeChatTurn('turn-02', 'assistant', 'that is the client silence watchdog, not a cliff') + ].join('\n')}\n` + ) + + indexer = new SessionSearchIndexer({ + databasePath: harness.databasePath, + roots: harness.roots, + historyDays: null, + clock, + reconcileIntervalMs: INTERVAL_MS + }) + await indexer.start() + + expect(messageTexts('watchdog')).toEqual([{ role: 'assistant', session: SESSION_ID }]) + expect(harness.read((db: SyncDatabase) => db.prepare('SELECT cwd FROM sessions').get())).toEqual({ + cwd: CWD + }) + + // The conversation continues in the panel; nothing tells the index about it. + await appendFile( + path, + `${[ + nativeChatTurn('turn-03', 'user', 'and the fleetwide 4408 bursts'), + nativeChatTurn('turn-04', 'assistant', 'those are desktop lease rotations, cohort waves') + ].join('\n')}\n` + ) + clock.advance(INTERVAL_MS) + await indexer.settled() + + expect(messageTexts('cohort')).toEqual([{ role: 'assistant', session: SESSION_ID }]) + expect(messageTexts('4408')).toEqual([{ role: 'user', session: SESSION_ID }]) + expect(indexer.status().phase).toBe('current') +}) diff --git a/src/main/ai-vault-search/session-search-opencode-decline.test.ts b/src/main/ai-vault-search/session-search-opencode-decline.test.ts new file mode 100644 index 00000000000..1ed3a201727 --- /dev/null +++ b/src/main/ai-vault-search/session-search-opencode-decline.test.ts @@ -0,0 +1,177 @@ +import { mkdirSync } from 'node:fs' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' + +// Only the thread hop is replaced: both implementations below are the repo's +// own in-process readers, which the worker entry calls on the other side. +export const openCodeParseCalls: string[] = [] +vi.mock('../ai-vault/session-scanner-opencode-sqlite-worker-spawn', async () => { + const list = await import('../ai-vault/session-scanner-opencode-sqlite-list') + const parse = await import('../ai-vault/session-scanner-opencode-sqlite') + const own = await import('./session-search-opencode-decline.test') + return { + resolveOpenCodeSqliteWorkerEntryPath: () => null, + listOpenCodeSqliteSessionsViaWorker: ( + args: Parameters[0] + ) => list.listOpenCodeSqliteSessions(args), + parseOpenCodeSqliteSessionViaWorker: ( + args: Parameters[0] + ) => { + own.openCodeParseCalls.push(args.sessionId) + return parse.parseOpenCodeSqliteSession(args) + } + } +}) +import Database from '../sqlite/sync-database' +import { getSessionParseCacheEntry } from '../ai-vault/session-parse-cache-store' +import { resetSessionParseCacheForTests } from '../ai-vault/session-scanner-parse-cache' +import { resetTranscriptConsumersForTests } from '../ai-vault/session-transcript-consumers' +import { buildOpenCodeSqliteCandidatePath } from '../ai-vault/session-scanner-opencode-sqlite-paths' +import { SessionSearchIndexer } from './session-search-indexer' +import { + FakeSessionSearchClock, + openSessionSearchIndexerHarness, + writeClaudeTranscript, + type SessionSearchIndexerHarness +} from './session-search-indexer-test-fixture' + +/* + * Round 12, F3. An OpenCode SQLite session decodes where the message channel + * cannot reach it, so no read of one will ever commit a row. The consumer + * declined it and wrote nothing, which left the file table silent about a + * source discovery returns on every pass: the decide step saw a path the index + * held nothing for, asked for a read, and asking for one over a warm cache + * drops the session list's own resume point. Every OpenCode session was fully + * decoded on every pass and the sidebar's fold was thrown away with it, which + * is the cache STA-1278 and STA-1417 added. + */ + +const SESSION = 'ses_r12' +const CLAUDE_SESSION = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' + +let harness: SessionSearchIndexerHarness +let clock: FakeSessionSearchClock +let indexer: SessionSearchIndexer | null = null + +beforeEach(async () => { + resetSessionParseCacheForTests() + resetTranscriptConsumersForTests() + clock = new FakeSessionSearchClock() + harness = await openSessionSearchIndexerHarness('ss-opencode-decline') + indexer = null + openCodeParseCalls.length = 0 +}) + +afterEach(async () => { + indexer?.close() + resetTranscriptConsumersForTests() + resetSessionParseCacheForTests() + await harness.cleanup() +}) + +function writeOpenCodeDb(path: string, sessionId: string): void { + const db = new Database(path) + db.exec(` + CREATE TABLE session ( + id TEXT PRIMARY KEY, project_id TEXT NOT NULL, parent_id TEXT, slug TEXT NOT NULL, + directory TEXT NOT NULL, title TEXT NOT NULL, version TEXT NOT NULL, share_url TEXT, + summary_additions INTEGER, summary_deletions INTEGER, summary_files INTEGER, + summary_diffs TEXT, revert TEXT, permission TEXT, + time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL, time_compacting INTEGER, + time_archived INTEGER, workspace_id TEXT, path TEXT, agent TEXT, model TEXT, + cost REAL DEFAULT 0 NOT NULL, tokens_input INTEGER DEFAULT 0 NOT NULL, + tokens_output INTEGER DEFAULT 0 NOT NULL, tokens_reasoning INTEGER DEFAULT 0 NOT NULL, + tokens_cache_read INTEGER DEFAULT 0 NOT NULL, tokens_cache_write INTEGER DEFAULT 0 NOT NULL, + metadata TEXT + ); + CREATE TABLE message ( + id TEXT PRIMARY KEY, session_id TEXT NOT NULL, time_created INTEGER NOT NULL, + time_updated INTEGER NOT NULL, data TEXT NOT NULL + ); + CREATE TABLE project ( + id TEXT PRIMARY KEY, worktree TEXT NOT NULL, vcs TEXT, name TEXT, icon_url TEXT, + icon_color TEXT, time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL, + time_initialized INTEGER, sandboxes TEXT NOT NULL, commands TEXT, icon_url_override TEXT + ); + CREATE TABLE part ( + id TEXT PRIMARY KEY, message_id TEXT NOT NULL, session_id TEXT NOT NULL, + time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL, data TEXT NOT NULL + ); + `) + db.prepare( + `INSERT INTO session (id, project_id, parent_id, slug, directory, title, version, + time_created, time_updated, agent, model, cost, tokens_input, tokens_output, + tokens_reasoning, tokens_cache_read, tokens_cache_write) + VALUES (?, 'proj-1', NULL, 'slug-1', '/tmp/opencode', 'OpenCode title', '1.0.0', + ?, ?, 'build', '{"id":"glm"}', 0, 1, 1, 0, 0, 0)` + ).run(sessionId, 1_740_000_000_000, 1_740_000_100_000) + db.prepare( + `INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?)` + ).run( + 'msg-1', + sessionId, + 1_740_000_000_000, + 1_740_000_000_000, + JSON.stringify({ role: 'user', time: { created: 1_740_000_000_000 } }) + ) + db.prepare( + `INSERT INTO part (id, message_id, session_id, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?, ?)` + ).run( + 'part-1', + 'msg-1', + sessionId, + 1_740_000_000_000, + 1_740_000_000_000, + JSON.stringify({ type: 'text', text: 'hello opencode' }) + ) + db.prepare( + `INSERT INTO project (id, worktree, name, time_created, time_updated, sandboxes) + VALUES ('proj-1', '/tmp/opencode', 'proj', ?, ?, '[]')` + ).run(1_740_000_000_000, 1_740_000_000_000) + db.close() +} + +it('reads an OpenCode session once, not on every pass', async () => { + const dbPath = join(harness.root, 'opencode-db', 'opencode.db') + mkdirSync(join(harness.root, 'opencode-db'), { recursive: true }) + writeOpenCodeDb(dbPath, SESSION) + const claudePath = join(harness.claudeProjectDir, 'control.jsonl') + await writeClaudeTranscript(claudePath, ['control turn'], CLAUDE_SESSION) + + indexer = new SessionSearchIndexer({ + databasePath: harness.databasePath, + roots: { ...harness.roots, opencodeDbPaths: [dbPath] }, + historyDays: null, + clock, + reconcileIntervalMs: 20_000, + onError: () => undefined + }) + await indexer.start() + + const syntheticPath = buildOpenCodeSqliteCandidatePath(dbPath, SESSION) + const openCodeAfterFirst = getSessionParseCacheEntry(syntheticPath) + const claudeAfterFirst = getSessionParseCacheEntry(claudePath) + + await indexer.reconcile() + await indexer.reconcile() + + // One decode across three passes, and the session list's cached fold for it + // is the same object it was after the first: nothing invalidated it. + expect(openCodeParseCalls).toHaveLength(1) + expect(getSessionParseCacheEntry(syntheticPath)).toBe(openCodeAfterFirst) + // The control, which the index really does hold, is untouched either way. + expect(getSessionParseCacheEntry(claudePath)).toBe(claudeAfterFirst) + + // What makes it skippable: a row saying the index has seen this source and + // holds no session for it, which is the shape a read-through-with-no-session + // already leaves. + const rows = harness.read((db) => + db.prepare('SELECT path, state, session_row_id FROM files ORDER BY path').all() + ) as { path: string; state: string; session_row_id: number | null }[] + expect(rows).toHaveLength(2) + expect(rows.find((row) => row.path === syntheticPath)).toMatchObject({ + state: 'current', + session_row_id: null + }) + expect(indexer.status()).toMatchObject({ filesDue: 0, filesFailed: 0, phase: 'current' }) +}) diff --git a/src/main/ai-vault-search/session-search-orphan-rows.test.ts b/src/main/ai-vault-search/session-search-orphan-rows.test.ts new file mode 100644 index 00000000000..dfda2303104 --- /dev/null +++ b/src/main/ai-vault-search/session-search-orphan-rows.test.ts @@ -0,0 +1,186 @@ +import { afterEach, describe, expect, it } from 'vitest' +import type SyncDatabase from '../sqlite/sync-database' +import { + addSyntheticSession, + openSessionSearchHarness, + type SessionSearchHarness +} from './session-search-engine-test-fixture' +import { identifierShadowText } from './session-search-identifier-split' +import { readIndexGeneration } from './session-search-index-generation' +import { planSessionSearchQuery } from './session-search-query-planner' +import { sessionSearchSnippet } from './session-search-snippet' +import type { SessionSearchCursorError } from './session-search-page-cursor' +import { SessionSearchTypoRepair } from './session-search-typo-repair' + +// Retention deletes a session row in one small transaction and reclaims its +// message rows in batches afterwards, so a `messages` row with no `sessions` row +// is a state every purge, every removed source and every interrupted drain +// passes through. Those rows are still in both FTS tables and still in the +// vocabulary, and nothing here may return one. +// +// A hit is a session row, and the ranked list is loaded `FROM sessions`, so the +// route ladder below cannot surface an orphan even if a join were loosened — +// those cases are a ratchet over the shape, not the proof. The two reads that +// can leak one are pinned separately and each is a real oracle: the snippet, +// which is handed a rowid and asked for its text, and the typo repair, whose +// dictionary is the FTS b-tree and lists an orphan's terms like any other. + +const ORPHAN_SESSION_ROW = 99 +const ORPHAN_TEXT = 'orphaned marmoset secret' + +let harness: SessionSearchHarness | null = null + +afterEach(async () => { + await harness?.close() + harness = null +}) + +/** Two rows in the FTS table and the vocabulary, and no session row for them. */ +function plantOrphans(db: SyncDatabase, text: string = ORPHAN_TEXT): number[] { + const rowids: number[] = [] + for (let n = 0; n < 2; n++) { + const rowid = Number( + db + .prepare("INSERT INTO messages(session_row_id,role,ts) VALUES (?,'user',?)") + .run(ORPHAN_SESSION_ROW, '2026-09-10T00:00:00.000Z').lastInsertRowid + ) + db.prepare( + 'INSERT INTO messages_fts(rowid,user_text,assistant_text,tool_text,identifiers) VALUES (?,?,?,?,?)' + ).run(rowid, text, '', '', identifierShadowText(text)) + rowids.push(rowid) + } + return rowids +} + +async function withOrphans(): Promise<{ harness: SessionSearchHarness; rowids: number[] }> { + harness = await openSessionSearchHarness('ss-orphan-rows') + addSyntheticSession(harness.db, { id: 1, text: 'the haystack line here' }) + const rowids = plantOrphans(harness.db) + // The oracle only means anything if the rows are really there to be found. + expect( + harness.db + .prepare("SELECT count(*) AS c FROM messages_fts WHERE messages_fts MATCH 'marmoset'") + .get() + ).toEqual({ c: 2 }) + expect( + harness.db.prepare("SELECT doc FROM messages_vocab WHERE term = 'marmoset'").get() + ).toEqual({ doc: 2 }) + return { harness, rowids } +} + +it.each([ + ['phrase', '"orphaned marmoset"'], + ['and', 'orphaned secret'], + ['single-token literal', 'marmoset'], + ['or', 'marmoset haystack orphaned'], + ['typo repair', 'marmosett'], + ['operator only', 'repo:app'] +])('returns no orphaned row on the %s route', async (_route, query) => { + const { harness: open } = await withOrphans() + for (const scope of ['all', 'conversation'] as const) { + const hits = open.engine.search({ query, scope }).hits + expect(hits.map((hit) => hit.sessionId)).not.toContain(String(ORPHAN_SESSION_ROW)) + expect(hits.filter((hit) => hit.evidence?.snippet.includes('marmoset'))).toEqual([]) + } +}) + +it('never repairs a term onto a spelling only orphaned rows carry', async () => { + const { harness: open } = await withOrphans() + // `marmoset` is in the vocabulary twice, which is what would make it the + // repair for `marmosett` if the repair trusted the vocabulary alone. + expect(new SessionSearchTypoRepair(open.db).correct('marmosett', 'all')).toBeNull() + expect(open.engine.search({ query: 'marmosett' }).planner.repairedTerms).toBeUndefined() +}) + +it('snippets nothing for an orphaned row, even asked for it by rowid', async () => { + const { harness: open, rowids } = await withOrphans() + const plan = planSessionSearchQuery('marmoset') + for (const scope of ['all', 'conversation'] as const) { + expect(sessionSearchSnippet(open.db, scope, rowids[0]!, plan)).toEqual({ + text: '', + truncated: false + }) + } +}) + +it('still answers for the live session beside them', async () => { + const { harness: open } = await withOrphans() + expect(open.engine.search({ query: 'haystack' }).hits.map((hit) => hit.sessionId)).toEqual(['1']) +}) + +// Reclaiming those rows is the other half. The drain deletes only from +// `messages`, so for a long time it was argued to change no answer and left +// outside the generation fence. Retrieval never saw them, but the typo repair's +// dictionary is `messages_vocab`, a view over the FTS b-tree that lists a term +// whether or not a reader can reach the rows carrying it — so the drain moved +// which word a query was repaired to, under a cursor that was still honoured. +describe('a purge reclaiming rows nothing can reach', () => { + /** A live session and a purged one that both carry `text`. */ + async function withReclaimable(): Promise { + harness = await openSessionSearchHarness('ss-orphan-drain') + // Two live rows, which is what makes `marmoset` eligible as a repair at all. + addSyntheticSession(harness.db, { id: 1, text: 'the marmoset lives here', rows: 2 }) + plantOrphans(harness.db) + return harness + } + + it('answers the same before and after, because the repair counts live rows', async () => { + const open = await withReclaimable() + const before = open.engine.search({ query: 'marmosett' }) + expect(before.planner.repairedTerms).toEqual(['marmoset']) + expect(before.hits.map((hit) => hit.sessionId)).toEqual(['1']) + + await open.store.purgeOlderThan(null) + expect(open.db.prepare('SELECT count(*) AS c FROM messages').get()).toEqual({ c: 2 }) + + const after = open.engine.search({ query: 'marmosett' }) + expect(after.planner.repairedTerms).toEqual(before.planner.repairedTerms) + expect(after.hits.map((hit) => hit.sessionId)).toEqual(before.hits.map((hit) => hit.sessionId)) + }) + + it('moves the generation anyway, so no cursor spans it', async () => { + // The repair counting live rows fixes the common case. It does not make the + // drain provably inert: `messages_vocab` still decides which candidates + // survive its scan limit, and reclaiming a term's last row changes where + // that limit cuts. The fence is what covers the rest, at the price of + // refusing a cursor once per batch while a purge runs. + const open = await withReclaimable() + // A second live session, so page one has a page two to be refused. + addSyntheticSession(open.db, { id: 2, text: 'the marmoset again', rows: 2 }) + const page = open.engine.search({ query: 'marmoset', limit: 1 }) + expect(page.page.cursor).not.toBeNull() + const before = readIndexGeneration(open.db) + + await open.store.purgeOlderThan(null) + + expect(readIndexGeneration(open.db)).toBeGreaterThan(before) + try { + open.engine.search({ query: 'marmoset', limit: 1, cursor: page.page.cursor! }) + expect.unreachable('a cursor must not span a purge') + } catch (error) { + expect((error as SessionSearchCursorError).rejection).toBe('stale-generation') + } + }) + + it('picks the same repair when an unreachable spelling was the more common one', async () => { + // Two candidates equally close to the query. `marmosetx` led on the old + // ranking only because two of its rows belonged to a session retention had + // already cut loose, so the drain swapped the repair under a live cursor. + harness = await openSessionSearchHarness('ss-orphan-drain-tie') + const db = harness.db + for (let id = 1; id <= 4; id++) { + addSyntheticSession(db, { id, text: `marmosetx session${id}` }) + } + for (let id = 5; id <= 9; id++) { + addSyntheticSession(db, { id, text: `marmosetq session${id}` }) + } + plantOrphans(db, 'marmosetx') + + const before = harness.engine.search({ query: 'marmosett' }) + expect(before.planner.repairedTerms).toEqual(['marmosetq']) + await harness.store.purgeOlderThan(null) + expect(harness.engine.search({ query: 'marmosett' }).planner.repairedTerms).toEqual( + before.planner.repairedTerms + ) + }) +}) diff --git a/src/main/ai-vault-search/session-search-page-cursor.ts b/src/main/ai-vault-search/session-search-page-cursor.ts new file mode 100644 index 00000000000..30e07fc9a6e --- /dev/null +++ b/src/main/ai-vault-search/session-search-page-cursor.ts @@ -0,0 +1,99 @@ +import { createHash } from 'node:crypto' +import type { SessionSearchRequest } from './session-search-engine-types' + +export type SessionSearchCursorRejection = 'stale-generation' | 'different-query' | 'malformed' + +/** Rejects invalid cursors or any page whose generation changes during its reads. */ +export class SessionSearchCursorError extends Error { + constructor( + readonly rejection: SessionSearchCursorRejection, + /** The generation observed when rejecting the request. */ + readonly actualGeneration: number, + /** Cursor generation, or the generation at the start of a first-page read. */ + readonly expectedGeneration?: number + ) { + super(`Search page rejected: ${rejection}`) + this.name = 'SessionSearchCursorError' + } +} + +type CursorPayload = { + /** Index generation. */ + g: number + /** + * Offset into the ranked list, not a session id. Ids are not in a cursor at + * all, so nothing here depends on `sessions.id` being unique over time — + * though it is, because PR 2 made the column AUTOINCREMENT so a purged + * session's id is never reissued to a live one. + */ + o: number + /** Query identity; see `sessionSearchPageKey`. */ + k: string +} + +/** + * Everything a page's ranking depends on except the limit. Two requests with + * the same key produce the same ranked list within one generation, so a cursor + * minted by one is meaningful to the other; the limit is left out on purpose so + * a caller may change its page size mid-pagination. + */ +export function sessionSearchPageKey(request: SessionSearchRequest): string { + const filters = request.filters ?? {} + const identity = JSON.stringify([ + request.query, + request.scope ?? 'all', + filters.sort ?? 'relevance', + filters.since ?? null, + [...(filters.agents ?? [])].sort(), + [...(filters.scopePaths ?? [])].sort() + ]) + return createHash('sha256').update(identity).digest('base64url').slice(0, 16) +} + +export function encodeSessionSearchCursor(generation: number, offset: number, key: string): string { + const payload: CursorPayload = { g: generation, o: offset, k: key } + return Buffer.from(JSON.stringify(payload), 'utf-8').toString('base64url') +} + +/** + * The offset this cursor points at, or a typed rejection. + * + * Every rejection carries `actualGeneration`, and every one that could read a + * generation out of the cursor carries `expectedGeneration` too, so a caller + * can tell "the index moved under you, ask for page one" from "this cursor is + * not ours" and act on the first without showing anyone an error. + */ +export function decodeSessionSearchCursor(cursor: string, generation: number, key: string): number { + let payload: CursorPayload + try { + payload = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf-8')) as CursorPayload + } catch { + throw new SessionSearchCursorError('malformed', generation) + } + // A generation that survived parsing is worth reporting even when the rest of + // the payload is unusable: it is what tells the caller which snapshot the + // cursor thought it was walking. + // A counter, so a fraction or a negative is forged rather than stale. + const claimed = + typeof payload?.g === 'number' && Number.isInteger(payload.g) && payload.g >= 0 + ? payload.g + : undefined + if ( + claimed === undefined || + !Number.isInteger(payload?.o) || + payload.o < 0 || + typeof payload?.k !== 'string' + ) { + throw new SessionSearchCursorError('malformed', generation, claimed) + } + // Generation first: a caller who changed the query AND waited through a + // publish should hear about the index moving, which is the condition it + // cannot fix by paging again. + if (claimed !== generation) { + throw new SessionSearchCursorError('stale-generation', generation, claimed) + } + if (payload.k !== key) { + throw new SessionSearchCursorError('different-query', generation, claimed) + } + return payload.o +} diff --git a/src/main/ai-vault-search/session-search-paging.test.ts b/src/main/ai-vault-search/session-search-paging.test.ts new file mode 100644 index 00000000000..31341853e28 --- /dev/null +++ b/src/main/ai-vault-search/session-search-paging.test.ts @@ -0,0 +1,351 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { SessionSearchRequest } from './session-search-engine-types' +import { + addSyntheticSession, + openSessionSearchHarness, + type SessionSearchHarness +} from './session-search-engine-test-fixture' +import { readIndexGeneration } from './session-search-index-generation' +import { + decodeSessionSearchCursor, + encodeSessionSearchCursor, + SessionSearchCursorError, + sessionSearchPageKey +} from './session-search-page-cursor' + +let harness: SessionSearchHarness | null = null + +afterEach(async () => { + await harness?.close() + harness = null +}) + +async function open(name: string, options = {}): Promise { + harness = await openSessionSearchHarness(name, options) + return harness +} + +async function withSessions(count: number, options = {}): Promise { + harness = await openSessionSearchHarness('ss-engine-paging', options) + for (let id = 1; id <= count; id++) { + addSyntheticSession(harness.db, { + id, + text: `needle padding ${'word '.repeat(id % 5)}`, + updatedAt: `2026-09-${String(id).padStart(2, '0')}T00:00:00.000Z` + }) + } + return harness +} + +describe('a cursor walks one ranked list', () => { + it('pages through every session exactly once, in one stable order', async () => { + const { engine } = await withSessions(25) + const request: SessionSearchRequest = { query: 'needle', limit: 10 } + const seen: string[] = [] + let cursor: string | null = null + let pages = 0 + do { + const page = engine.search(cursor ? { ...request, cursor } : request) + seen.push(...page.hits.map((hit) => hit.sessionId)) + cursor = page.page.cursor + pages++ + expect(pages).toBeLessThan(10) + } while (cursor !== null) + + expect(pages).toBe(3) + expect(seen).toHaveLength(25) + expect(new Set(seen).size).toBe(25) + // The same walk, run again against the same generation, is the same walk. + expect(engine.search(request).hits.map((hit) => hit.sessionId)).toEqual(seen.slice(0, 10)) + }) + + it('closes the page when the last hit has been handed out', async () => { + const { engine } = await withSessions(3) + const page = engine.search({ query: 'needle', limit: 10 }) + expect(page.hits).toHaveLength(3) + expect(page.page.hasMore).toBe(false) + expect(page.page.cursor).toBeNull() + }) + + it('lets a caller change page size mid-walk', async () => { + const { engine } = await withSessions(12) + const first = engine.search({ query: 'needle', limit: 5 }) + const rest = engine.search({ query: 'needle', limit: 20, cursor: first.page.cursor! }) + expect(rest.hits).toHaveLength(7) + expect(rest.page.hasMore).toBe(false) + }) + + it('breaks a tie by session, so two entries cannot swap between pages', async () => { + // Same text, same timestamp: every ranking key is equal, which is exactly + // where an unstable sort would hand one session out twice and lose another. + harness = await openSessionSearchHarness('ss-engine-ties') + for (let id = 1; id <= 6; id++) { + addSyntheticSession(harness.db, { id, text: 'needle', updatedAt: '2026-09-01T00:00:00.000Z' }) + } + const first = harness.engine.search({ query: 'needle', limit: 3 }) + const second = harness.engine.search({ query: 'needle', limit: 3, cursor: first.page.cursor! }) + const seen = [...first.hits, ...second.hits].map((hit) => hit.sessionId) + expect(seen).toEqual(['1', '2', '3', '4', '5', '6']) + }) +}) + +describe('a cursor is refused rather than reinterpreted', () => { + it('rejects a cursor minted before the index moved', async () => { + const { engine, store } = await withSessions(25) + const first = engine.search({ query: 'needle', limit: 10 }) + // A proven deletion of a path this index really held hides a session, which + // is exactly the change a cursor must not be allowed to page across. + store.removeFile('/synthetic/1.jsonl') + + expect(() => engine.search({ query: 'needle', limit: 10, cursor: first.page.cursor! })).toThrow( + SessionSearchCursorError + ) + try { + engine.search({ query: 'needle', limit: 10, cursor: first.page.cursor! }) + expect.unreachable('a stale cursor must not be silently re-run') + } catch (error) { + expect((error as SessionSearchCursorError).rejection).toBe('stale-generation') + } + }) + + it('names both generations, so a caller can tell a moved index from a bad cursor', async () => { + // What a caller does about it differs: a moved index means quietly ask for + // page one again, a bad cursor means something is wrong with the caller. + const { engine, store } = await withSessions(25) + const first = engine.search({ query: 'needle', limit: 10 }) + const minted = readIndexGeneration(harness!.db) + // Any published read moves the generation, including one for a file this + // page never mentioned. That is the fence working, not a defect. + store.removeFile('/synthetic/9.jsonl') + + try { + engine.search({ query: 'needle', limit: 10, cursor: first.page.cursor! }) + expect.unreachable('the index moved') + } catch (error) { + const rejected = error as SessionSearchCursorError + expect(rejected.rejection).toBe('stale-generation') + expect(rejected.expectedGeneration).toBe(minted) + expect(rejected.actualGeneration).toBe(readIndexGeneration(harness!.db)) + expect(rejected.actualGeneration).toBeGreaterThan(rejected.expectedGeneration!) + } + }) + + it('rejects a cursor carried over to a different query', async () => { + const { engine } = await withSessions(25) + const first = engine.search({ query: 'needle', limit: 10 }) + try { + engine.search({ query: 'padding', limit: 10, cursor: first.page.cursor! }) + expect.unreachable('a cursor indexes into one ranked list, not any list') + } catch (error) { + expect((error as SessionSearchCursorError).rejection).toBe('different-query') + } + }) + + it('rejects a cursor whose filters changed, which reranks the list', async () => { + const { engine } = await withSessions(25) + const first = engine.search({ query: 'needle', limit: 10 }) + try { + engine.search({ + query: 'needle', + limit: 10, + cursor: first.page.cursor!, + filters: { sort: 'newest' } + }) + expect.unreachable('a different sort is a different ranked list') + } catch (error) { + expect((error as SessionSearchCursorError).rejection).toBe('different-query') + } + }) + + // Every field the ranked list depends on has to be in the key, and a field + // that is in the key but never pinned is a field a refactor can drop while + // the suite stays green. One case each, through the engine, so the assertion + // is about a refused page and not about a hash. + it.each([ + ['scope', { scope: 'conversation' as const }], + ['sort', { filters: { sort: 'newest' as const } }], + ['agents', { filters: { agents: ['codex' as const] } }], + ['scopePaths', { filters: { scopePaths: ['/repo/app'] } }], + ['since', { filters: { since: '2026-09-01T00:00:00.000Z' } }] + ])('rejects a cursor presented with a different %s', async (_field, changed) => { + const { engine } = await withSessions(25) + const request: SessionSearchRequest = { + query: 'needle', + limit: 10, + scope: 'all', + filters: { sort: 'relevance', agents: ['claude'], scopePaths: ['/'], since: undefined } + } + const first = engine.search(request) + expect(first.page.cursor).not.toBeNull() + try { + engine.search({ + ...request, + ...changed, + filters: { ...request.filters, ...('filters' in changed ? changed.filters : {}) }, + cursor: first.page.cursor! + }) + expect.unreachable('a narrowing the ranked list depends on must invalidate the cursor') + } catch (error) { + expect((error as SessionSearchCursorError).rejection).toBe('different-query') + } + }) + + it('rejects a cursor that is not one of ours', async () => { + const { engine } = await withSessions(3) + try { + engine.search({ query: 'needle', cursor: 'not-a-cursor' }) + expect.unreachable('a malformed cursor is not an empty one') + } catch (error) { + expect((error as SessionSearchCursorError).rejection).toBe('malformed') + } + }) +}) + +describe('cursor encoding', () => { + const request: SessionSearchRequest = { query: 'needle', filters: { scopePaths: ['/a'] } } + + it('round-trips an offset within its own generation and query', () => { + const key = sessionSearchPageKey(request) + expect(decodeSessionSearchCursor(encodeSessionSearchCursor(7, 40, key), 7, key)).toBe(40) + }) + + it('keys a request by what changes its ranking, and not by its page size', () => { + expect(sessionSearchPageKey({ ...request, limit: 5 })).toBe( + sessionSearchPageKey({ ...request, limit: 50 }) + ) + expect(sessionSearchPageKey({ ...request, scope: 'conversation' })).not.toBe( + sessionSearchPageKey(request) + ) + }) + + it('reads a filter list in any order as the same request', () => { + expect(sessionSearchPageKey({ query: 'a', filters: { agents: ['claude', 'codex'] } })).toBe( + sessionSearchPageKey({ query: 'a', filters: { agents: ['codex', 'claude'] } }) + ) + }) + + it.each([ + ['a negative offset', encodeSessionSearchCursor(1, -1, 'k'), 1], + ['a non-integer offset', Buffer.from('{"g":1,"o":1.5,"k":"k"}').toString('base64url'), 1], + ['a payload that is not an object', Buffer.from('"nope"').toString('base64url'), undefined], + ['text that is not base64url JSON', 'zzz!!', undefined], + // A generation is a counter: neither of these is a snapshot that ever + // existed, so reporting one as stale would name a generation as expected. + [ + 'a fractional generation', + Buffer.from('{"g":7.5,"o":0,"k":"k"}').toString('base64url'), + undefined + ], + [ + 'a negative generation', + Buffer.from('{"g":-1,"o":0,"k":"k"}').toString('base64url'), + undefined + ] + ])('rejects %s as malformed, still naming the index generation', (_name, cursor, claimed) => { + // The caller has to know which snapshot it was refused against whatever was + // wrong with the cursor, and the generation it claimed whenever that + // survived parsing. + try { + decodeSessionSearchCursor(cursor, 7, 'k') + expect.unreachable('a malformed cursor is not an empty one') + } catch (error) { + const rejected = error as SessionSearchCursorError + expect(rejected.rejection).toBe('malformed') + expect(rejected.actualGeneration).toBe(7) + expect(rejected.expectedGeneration).toBe(claimed) + } + }) +}) + +describe('the candidate limit is a tunable default, and says when it cut', () => { + it('does not claim truncation when every session fits', async () => { + const { engine } = await withSessions(5, { sessionCandidateLimit: 600 }) + expect(engine.search({ query: 'needle' }).truncated.candidates).toBe(false) + }) + + it('claims truncation, and ranks only what it retrieved, at the limit', async () => { + const { engine } = await withSessions(10, { sessionCandidateLimit: 4 }) + const result = engine.search({ query: 'needle', limit: 100 }) + expect(result.truncated.candidates).toBe(true) + expect(result.hits).toHaveLength(4) + }) + + it('applies the same limit to an operator-only page', async () => { + const { engine } = await withSessions(10, { sessionCandidateLimit: 4 }) + const result = engine.search({ query: 'repo:app', limit: 100 }) + expect(result.truncated.candidates).toBe(true) + expect(result.hits).toHaveLength(4) + }) + + it('says it gave up when the operator walk stopped scanning, not that it is done', async () => { + // The shape that reads as a confident empty answer: the only match sits + // past the walk's ceiling, so the walk stops having found nothing. Zero + // hits and `truncated.candidates` false would tell a caller there is + // nothing to find, which is a different claim from "I stopped looking". + // The walk reads a page at a time and gives up past a ceiling of + // `candidateLimit` x 20, so the corpus has to be deeper than one page for + // the ceiling to be what ends it. The only match is the oldest session. + const deep = 600 + const { db, engine } = await open('ss-engine-sparse-deep', { sessionCandidateLimit: 2 }) + for (let id = 1; id <= deep; id++) { + addSyntheticSession(db, { + id, + cwd: id === deep ? '/repo/needleonly' : '/repo/app', + updatedAt: new Date(Date.UTC(2026, 8, 9) - id * 60_000).toISOString() + }) + } + const result = engine.search({ query: 'repo:needleonly' }) + expect(result.hits).toHaveLength(0) + expect(result.truncated.candidates).toBe(true) + }) + + it('does not claim it gave up when the walk really did read everything', async () => { + const { db, engine } = await open('ss-engine-sparse-shallow', { sessionCandidateLimit: 600 }) + addSyntheticSession(db, { id: 1, cwd: '/repo/app' }) + const result = engine.search({ query: 'repo:nothing-here' }) + expect(result.hits).toHaveLength(0) + expect(result.truncated.candidates).toBe(false) + }) +}) + +describe('the response carries the snapshot it was built from', () => { + it('reports the index generation on every result', async () => { + const { db, engine, store } = await withSessions(3) + const before = engine.search({ query: 'needle' }).generation + expect(before).toBe(readIndexGeneration(db)) + store.removeFile('/synthetic/1.jsonl') + const after = engine.search({ query: 'needle' }).generation + expect(after).toBe(readIndexGeneration(db)) + expect(after).toBeGreaterThan(before) + }) +}) + +it.each([false, true])('rejects a write during page assembly (cursor: %s)', async (withCursor) => { + const { db, engine, store } = await open('ss-concurrent-page') + for (let id = 1; id <= 3; id++) { + addSyntheticSession(db, { id, text: 'needle' }) + } + const first = engine.search({ query: 'needle', limit: 1 }) + const prepare = db.prepare.bind(db) + let committed = false + const hook = vi.spyOn(db, 'prepare').mockImplementation((sql) => { + if (!committed && sql.includes('SELECT DISTINCT session_row_id FROM files')) { + committed = true + store.removeFile('/synthetic/1.jsonl') + } + return prepare(sql) + }) + try { + expect(() => + engine.search({ + query: 'needle', + limit: 1, + ...(withCursor ? { cursor: first.page.cursor! } : {}) + }) + ).toThrow(SessionSearchCursorError) + expect(committed).toBe(true) + expect(readIndexGeneration(db)).toBeGreaterThan(first.generation) + } finally { + hook.mockRestore() + } +}) diff --git a/src/main/ai-vault-search/session-search-pass.ts b/src/main/ai-vault-search/session-search-pass.ts new file mode 100644 index 00000000000..d4f36015226 --- /dev/null +++ b/src/main/ai-vault-search/session-search-pass.ts @@ -0,0 +1,216 @@ +import type { AiVaultScanIssue } from '../../shared/ai-vault-types' +import { ensureSessionParseCacheLoaded } from '../ai-vault/session-parse-cache-persistence' +import { + cursorChatMetaRefusals, + withCursorChatMetaScan +} from '../ai-vault/session-scanner-cursor-chat-meta' +import { recordSessionScanIssue } from '../ai-vault/session-scan-issues' +import { + mergeDegradedRoots, + scanIssueDegradedRoots, + unreadableRoots, + type SessionSearchDegradedRoot +} from './session-search-degraded-roots' +import { retireDeletedSessionSearchSources } from './session-search-deleted-sources' +import type { SessionSearchDirectoryReader } from './session-search-directory-listings' +import { runSessionSearchIndexPass } from './session-search-index-pass' +import { + discoverSessionSearchCandidates, + isUnderScanRoot, + sessionSearchEmptiedRoots, + sessionSearchRootListings, + type SessionSearchScanRoots +} from './session-search-scan-roots' +import type { SessionSearchFileRow, SessionSearchStore } from './session-search-store' +import { sessionSearchEnumeratedContainers } from './session-search-synthetic-sources' + +/** + * Rows a cycle proves present or gone, newest first. + * + * Why bounded and why newest first: a cycle lists the newest N per agent, so + * every older row it holds is undiscovered and would otherwise be walked every + * twenty seconds. Newest first is what makes the guarantee hold — a transcript + * recent enough for the window to cover is recent enough to be in this slice, + * so its deletion is proven on the very next cycle whenever it happened. + */ +const RETIREMENT_ROWS_PER_CYCLE = 512 + +/** + * Directories either pass may read proving deletions. + * + * The bound on the walk is readdirs, not rows: rows sharing a directory are one + * read and then map lookups, and a directory that answers an error answers it + * once for every row under it. Counting rows instead let one unreadable + * directory hold the whole walk for as long as it stayed unreadable. + */ +const RETIREMENT_DIRECTORIES_PER_PASS = 512 + +export type SessionSearchPassArgs = { + store: SessionSearchStore + roots: SessionSearchScanRoots + /** A sweep lists every root; a cycle lists the newest N per agent. */ + full: boolean + recentPerAgent: number + /** Real roots that listed transcripts on the previous pass; undefined before the first. */ + previousRootsWithFiles?: ReadonlySet + /** True once the pass is out of wall time; reads stop, everything else finishes. */ + overdue?: () => boolean + /** One readdir per directory for the whole pass, shared by every step. */ + listings: SessionSearchDirectoryReader + signal?: AbortSignal +} + +export type SessionSearchPassResult = { + /** Real roots this pass listed transcripts under, for the next pass to compare against. */ + rootsWithFiles: Set + degradedRoots: SessionSearchDegradedRoot[] + /** False when the pass was cut short; its conclusions are not to be recorded. */ + completed: boolean + /** + * True when the deadline stopped the reads with candidates still owed. + * + * The caller's one use for it: a cycle lists the newest N per agent, so a + * backlog outside that window is only *visible* to a sweep. Without this a + * first run would index the recency window in its opening pass and then crawl, + * making progress only on the periodic sweep every five minutes. + */ + outOfTime: boolean +} + +/** + * One pass. Four steps, the same four whether it sweeps or cycles. + * + * 1. **Discover.** The only filesystem walk: every root on a sweep, the newest + * N per agent on a cycle. Everything below is decided from what it returns. + * 2. **Decide and read.** Per candidate, its stat against its row. Reads stop + * at the deadline and nothing is recorded about what was left, because being + * owed is a fact about the row and not an entry in a queue. + * 3. **Retire.** Candidates are the rows this pass's discovery did not return, + * inside the scope that discovery covered. The stateless walk proves each + * one gone, present or unverifiable; only `gone` deletes. + * 4. **Report.** Root health for this pass. The counts are a query, made by the + * caller against the same rows, so nothing here is tallied. + * + * The pass keeps nothing. Everything it learns is either on a row or in the + * result the caller compares against the next pass. + */ +export async function runSessionSearchPass( + args: SessionSearchPassArgs +): Promise { + const { store, signal } = args + if (args.full) { + // Every sweep opens with the purge, so a window narrower than the last + // instance held is applied by the first sweep of this one. + await store.purgeOlderThan(store.retentionCutoff, signal) + } + await ensureSessionParseCacheLoaded() + return withCursorChatMetaScan(async () => { + const swept = await discoverSessionSearchCandidates(args.roots, { + limitPerAgent: args.full ? Number.POSITIVE_INFINITY : args.recentPerAgent, + signal + }) + const issues: AiVaultScanIssue[] = [...swept.issues] + + let completed = true + let outOfTime = false + const rows = new Map(store.files().map((row) => [row.path, row])) + try { + const read = await runSessionSearchIndexPass(store, swept.candidates, { + signal, + rows, + overdue: args.overdue + }) + outOfTime = read.outOfTime + } catch (error) { + if (!signal?.aborted) { + throw error + } + completed = false + } + + const listings = sessionSearchRootListings(args.roots, swept.discoveries) + const roots = listings.map((listing) => listing.root) + const rootsWithFiles = new Set( + listings.filter((listing) => listing.files > 0).map((listing) => listing.root) + ) + // Undefined, not empty, before any pass has recorded one: an empty set is a + // real observation and this is the absence of one. + const previousRootsWithFiles = args.previousRootsWithFiles + // A pass cut short saw part of the machine, so its silence about a path is + // not evidence; it retires nothing and publishes no verdicts. + const retirement = completed + ? await retireDeletedSessionSearchSources({ + store, + paths: retirementCandidates(rows, swept, roots, args.full), + roots, + // Only a sweep enumerates without a per-agent limit, so only a sweep + // may prove a synthetic row's container holds it no longer. + enumeratedContainers: args.full + ? sessionSearchEnumeratedContainers(swept.candidates, issues) + : undefined, + emptiedRoots: previousRootsWithFiles + ? sessionSearchEmptiedRoots(previousRootsWithFiles, rootsWithFiles) + : new Set(), + listings: args.listings, + directoryLimit: RETIREMENT_DIRECTORIES_PER_PASS, + signal + }) + : { retired: [], unverifiable: [], unchecked: [], degradedRoots: [] } + + for (const refusal of cursorChatMetaRefusals()) { + // One issue per refused chats root, not one per Cursor transcript. + recordSessionScanIssue(issues, { + agent: 'cursor', + path: refusal.chatsRoot, + message: refusal.message + }) + } + // Roots that listed no transcripts and cannot be listed either: the walker + // swallows a readdir failure, so this is the only place it surfaces. + const unlistable = completed + ? await unreadableRoots( + roots.filter((root) => !rootsWithFiles.has(root)), + args.listings, + signal + ) + : [] + + return { + rootsWithFiles, + degradedRoots: mergeDegradedRoots( + scanIssueDegradedRoots(roots, issues), + retirement.degradedRoots, + unlistable + ), + completed, + outOfTime + } + }) +} + +/** + * Rows this pass's discovery did not return, inside the scope it covered. + * + * A sweep covers everything, so every undiscovered row is a candidate. A cycle + * covers the newest N per agent, so it may only judge rows under a root it + * actually listed, and it takes the newest of those: an older row is not + * evidence of anything a cycle looked for, and the next sweep is what reaches + * it. This is the whole of what used to be a watch set carried between passes. + */ +function retirementCandidates( + rows: ReadonlyMap, + swept: { candidates: readonly { file: { path: string } }[] }, + roots: readonly string[], + full: boolean +): string[] { + const discovered = new Set(swept.candidates.map((candidate) => candidate.file.path)) + const undiscovered = [...rows.values()].filter((row) => !discovered.has(row.path)) + if (full) { + return undiscovered.map((row) => row.path) + } + return undiscovered + .filter((row) => roots.some((root) => isUnderScanRoot(row.path, root))) + .sort((left, right) => right.mtimeMs - left.mtimeMs) + .slice(0, RETIREMENT_ROWS_PER_CYCLE) + .map((row) => row.path) +} diff --git a/src/main/ai-vault-search/session-search-query-planner.test.ts b/src/main/ai-vault-search/session-search-query-planner.test.ts new file mode 100644 index 00000000000..ac4874b1d10 --- /dev/null +++ b/src/main/ai-vault-search/session-search-query-planner.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it } from 'vitest' +import { + andExpression, + isLiteralQuery, + orExpression, + phraseExpression, + planSessionSearchQuery, + quoteFtsTerm +} from './session-search-query-planner' + +describe('literal shape decides whether the phrase route is even tried', () => { + it.each([ + 'resolveTerminalPath', + 'src/main/foo-bar.ts', + 'MAX_RETRY_COUNT', + 'kern.tty.ptmx_max', + '#19687', + 'STA-4850', + '"exact words here"', + 'TypeError: undefined', + 'foo() {' + ])('treats %s as quoting something from a transcript', (query) => { + expect(isLiteralQuery(query)).toBe(true) + }) + + it.each(['why is the terminal slow', 'how do I resume a session', 'relay capacity'])( + 'treats %s as prose', + (query) => { + expect(isLiteralQuery(query)).toBe(false) + } + ) +}) + +describe('the body is what the phrase and AND routes see', () => { + it('drops stop words from prose so the AND route is not defeated by "the"', () => { + expect(planSessionSearchQuery('why is the relay dropping frames').body).toEqual([ + 'relay', + 'dropping', + 'frames' + ]) + }) + + it('keeps stop words inside a literal, where they are part of what was quoted', () => { + // The literal shape is `foo.ts`; dropping `the` would change what was typed. + expect(planSessionSearchQuery('the foo.ts file').body).toEqual(['the', 'foo.ts', 'file']) + }) + + it('keeps a query that is nothing but stop words rather than answering nothing', () => { + expect(planSessionSearchQuery('how do I').body).toEqual(['how', 'do', 'I']) + }) + + it('has no terms for a query with no searchable token', () => { + expect(planSessionSearchQuery(' ... ').terms).toEqual([]) + }) +}) + +describe('the OR fallback fans an identifier out into its pieces', () => { + it('adds the split pieces after the whole term, never in place of it', () => { + const plan = planSessionSearchQuery('resolveTerminalPath') + expect(plan.terms[0]).toBe('resolveTerminalPath') + expect(plan.terms).toContain('terminal') + expect(plan.terms).toContain('path') + // `resolve` is not a stop word, so the whole identifier is reachable by piece. + expect(plan.terms).toContain('resolve') + }) + + it('leaves an ordinary word alone', () => { + expect(planSessionSearchQuery('relay').terms).toEqual(['relay']) + }) +}) + +describe('FTS5 expressions quote every term', () => { + it('quotes punctuation that would otherwise be syntax', () => { + expect(quoteFtsTerm('cli.mjs')).toBe('"cli.mjs"') + expect(quoteFtsTerm('C++')).toBe('"C++"') + expect(quoteFtsTerm('say "hi"')).toBe('"say ""hi"""') + }) + + it('builds one phrase, an AND chain, and an OR chain from the same terms', () => { + expect(phraseExpression(['alpha', 'beta'])).toBe('"alpha beta"') + expect(andExpression(['alpha', 'beta'])).toBe('"alpha" AND "beta"') + expect(orExpression(['alpha', 'beta'])).toBe('"alpha" OR "beta"') + }) +}) diff --git a/src/main/ai-vault-search/session-search-query-planner.ts b/src/main/ai-vault-search/session-search-query-planner.ts new file mode 100644 index 00000000000..6c2c2f3b91c --- /dev/null +++ b/src/main/ai-vault-search/session-search-query-planner.ts @@ -0,0 +1,140 @@ +import type { SessionSearchScope } from './session-search-engine-types' +import { identifierShadowTerms } from './session-search-identifier-split' + +// Tokens exactly as the unicode61 tokenizer with `_ . - / +` tokenchars emits them. +const INDEX_TOKEN = /[\p{L}\p{N}\p{M}\p{Co}_./+-]+/gu +const STOP_WORDS = new Set( + ( + 'a an and are as at be but by for from how i if in into is it its of on or that the this to ' + + 'was were what when where which who why with you your we my me do does did not no can could ' + + 'should would about our us they them there their has have had been being so such then than ' + + "these those there's im ive dont" + ).split(' ') +) +const MAX_BODY_TERMS = 48 +const MAX_TERMS = 64 + +// A query that quotes something from a transcript: camelCase, SCREAMING_SNAKE, +// a dotted or snake_case name, a path, a filename, a PR number, a ticket, code +// punctuation, or an error word. +const LITERAL_SHAPE = + /[A-Za-z0-9_]*[a-z][A-Z][A-Za-z0-9_]*|\b[A-Z][A-Z0-9]{2,}(_[A-Z0-9]+)+\b|\b\w{2,}[._]\w{2,}\b|\b[\w.-]+\/[\w/.-]+\b|\b\w+\.(ts|tsx|js|jsx|py|rs|go|json|md|sh|yml|yaml|toml|c|cc|h|java|sql)\b|#\d{3,}|\b[A-Z]{2,6}-\d{2,}\b|[(){};=]|::|->|--\w|\b(Error|Exception|Traceback|error:|warning:)\b/ +const QUOTED = /"[^"]{3,}"|'[^']{3,}'/ + +export type SessionSearchQueryPlan = { + literal: boolean + /** + * The query had more terms than the planner will search. What is dropped is + * the tail, so a match that only the last term would have found is missed; + * the caller is told rather than handed a confident empty answer. + */ + truncated: boolean + /** Deduplicated index-faithful terms for the OR fallback, incl. identifier pieces. */ + terms: string[] + /** Query-order tokens minus stop words: the phrase / AND candidate. */ + body: string[] +} + +export function isLiteralQuery(query: string): boolean { + return QUOTED.test(query) || LITERAL_SHAPE.test(query) +} + +/** + * The tokenizer contract, unfolded: the same boundaries FTS5 draws for + * `unicode61 tokenchars '_.-/+'`. Pinned against real `fts5vocab` output in + * session-search-fts5-contract.test.ts, which is what makes it safe to plan a + * query without asking SQLite. + */ +export function indexTokens(query: string, limit = Number.POSITIVE_INFINITY): string[] { + const out: string[] = [] + for (const match of query.matchAll(INDEX_TOKEN)) { + const token = match[0] + // Separators alone (`--`, `...`) are a token to FTS5 but never a search term. + if (/[\p{L}\p{N}\p{Co}]/u.test(token)) { + out.push(token) + if (out.length >= limit) { + break + } + } + } + return out +} + +/** + * `literal` overrides the shape test. Typo repair re-plans the query it + * corrected, and a corrected spelling can look like ordinary prose even though + * what was typed was a literal: `parseJsonn(the, data)` has the punctuation that + * makes it literal, `parsejson the data` does not. Without the override the + * re-plan would drop `the` as a stop word, so the repaired query would search + * for less than the original asked for and `repairedTerms` would report a body + * the user never typed. + */ +export function planSessionSearchQuery( + query: string, + literal = isLiteralQuery(query) +): SessionSearchQueryPlan { + // One past the cap, so the plan can tell a query that just fits from one that + // was cut. `indexTokens` stops at its limit, so it cannot be asked afterwards. + const overCap = indexTokens(query, MAX_BODY_TERMS + 1) + const truncated = overCap.length > MAX_BODY_TERMS + const raw = overCap.slice(0, MAX_BODY_TERMS) + let body = literal ? raw : raw.filter((token) => !STOP_WORDS.has(token.toLowerCase())) + if (body.length < 2) { + body = raw + } + const terms = [...new Set(body)] + const extra: string[] = [] + for (const term of terms) { + for (const piece of identifierShadowTerms(term, 12)) { + if (!terms.includes(piece) && !STOP_WORDS.has(piece) && !extra.includes(piece)) { + extra.push(piece) + } + } + } + return { + literal, + truncated, + terms: [...terms, ...extra].slice(0, MAX_TERMS), + body: body.slice(0, MAX_BODY_TERMS) + } +} + +// Why: `cli.mjs`, `foo-bar`, and `C++` are all FTS5 syntax errors unquoted. +export function quoteFtsTerm(term: string): string { + return `"${term.replaceAll('"', '""')}"` +} + +export function phraseExpression(terms: readonly string[]): string { + return quoteFtsTerm(terms.join(' ')) +} + +export function andExpression(terms: readonly string[]): string { + return terms.map(quoteFtsTerm).join(' AND ') +} + +export function orExpression(terms: readonly string[]): string { + return terms.map(quoteFtsTerm).join(' OR ') +} + +/** + * What a scope is, now that there is one FTS table. + * + * `conversation` used to be a second table holding a copy of the two prose + * columns. It is a column filter instead: PR 2 measured the filter at + * 1.16-1.36x the p95 of the dedicated table on a 105 MB corpus, against a 2x + * bar, and the table cost a tenth of the index to maintain. + * + * It lives beside the other expression builders, and not with the retrieval + * that uses it, because the typo repair has to ask the same question of the + * same scope and importing it from there is a cycle. + * + * The filter binds to the whole expression, so it is applied here and nowhere + * else — `{cols}: (a AND b)` filters both terms, while a prefix pasted in front + * of a bare `a AND b` would filter only `a` and quietly search tool output for + * the rest. + */ +const CONVERSATION_COLUMNS = '{user_text assistant_text}' + +export function scopedExpression(scope: SessionSearchScope, expression: string): string { + return scope === 'all' ? expression : `${CONVERSATION_COLUMNS}: (${expression})` +} diff --git a/src/main/ai-vault-search/session-search-query-schema.ts b/src/main/ai-vault-search/session-search-query-schema.ts new file mode 100644 index 00000000000..f01c2d42d18 --- /dev/null +++ b/src/main/ai-vault-search/session-search-query-schema.ts @@ -0,0 +1,42 @@ +import type SyncDatabase from '../sqlite/sync-database' +import { + SESSION_SEARCH_GENERATION_SQL, + SESSION_SEARCH_GENERATION_TRIGGERS +} from './session-search-index-generation' + +const QUERY_SCHEMA_SQL = ` +-- The typo repair's whole dictionary. Why the index's own vocabulary and not a +-- word list: it can never suggest a term this index does not hold, and it needs +-- no model. fts5vocab is a view over the FTS5 b-tree, so it costs no extra rows. +CREATE VIRTUAL TABLE IF NOT EXISTS messages_vocab USING fts5vocab(messages_fts, 'row'); +${SESSION_SEARCH_GENERATION_SQL}` + +/** Everything the SQL above creates, so a missing one is what triggers a re-run. */ +const OWNED = ['messages_vocab', ...SESSION_SEARCH_GENERATION_TRIGGERS] + +/** + * The vocabulary's target. Creating a fts5vocab table over a missing FTS table + * succeeds and every query against it then fails, so the feature's health is + * this name's presence rather than the vocabulary's own. + */ +const VOCABULARY_SOURCE = 'messages_fts' + +const PROBED = [...OWNED, VOCABULARY_SOURCE] + +/** Restore derived objects; a missing source index requires the owner to rebuild. */ +export function ensureSessionSearchQuerySchema(db: SyncDatabase): void { + const present = presentNames(db) + if (!present.has(VOCABULARY_SOURCE)) { + throw new Error('Session search index unavailable: missing messages_fts') + } + if (OWNED.some((name) => !present.has(name))) { + db.exec(QUERY_SCHEMA_SQL) + } +} + +function presentNames(db: SyncDatabase): Set { + const rows = db + .prepare(`SELECT name FROM sqlite_master WHERE name IN (${PROBED.map(() => '?').join(',')})`) + .all(...PROBED) as { name: string }[] + return new Set(rows.map((row) => row.name)) +} diff --git a/src/main/ai-vault-search/session-search-read-decision.test.ts b/src/main/ai-vault-search/session-search-read-decision.test.ts new file mode 100644 index 00000000000..64eb8866d02 --- /dev/null +++ b/src/main/ai-vault-search/session-search-read-decision.test.ts @@ -0,0 +1,117 @@ +import { expect, it } from 'vitest' +import type { SessionFileCandidate } from '../ai-vault/session-scanner-types' +import type { SessionSearchIndexedFile } from './session-search-file-cursor' +import { + SESSION_SEARCH_FAILURES_BEFORE_HELD_OUT, + sessionSearchReadDecision +} from './session-search-read-decision' +import type { SessionSearchFileRow } from './session-search-store' + +const PATH = '/transcripts/one.jsonl' +const MTIME = 1_740_000_000_000 + +function candidate(overrides: Partial = {}): SessionFileCandidate { + return { + agent: 'claude', + codexHome: null, + file: { + path: PATH, + mtimeMs: MTIME, + modifiedAt: new Date(MTIME).toISOString(), + sizeBytes: 100, + ...overrides + } + } +} + +function row(overrides: Partial = {}): SessionSearchFileRow { + return { + path: PATH, + identity: null, + mtimeMs: MTIME, + sizeBytes: 100, + state: 'current', + failCount: 0, + failedMtimeMs: null, + ...overrides + } +} + +const cursor: SessionSearchIndexedFile = { byteOffset: 100, mtimeMs: MTIME, sizeBytes: 100 } + +function decide(args: { + file?: Partial + row?: SessionSearchFileRow | undefined + cursor?: SessionSearchIndexedFile | null + cutoffMs?: number | null +}) { + return sessionSearchReadDecision({ + candidate: candidate(args.file), + row: 'row' in args ? args.row : row(), + cursor: 'cursor' in args ? (args.cursor ?? null) : cursor, + cutoffMs: args.cutoffMs ?? null + }) +} + +it('reads a path the index holds nothing for, and lets the reader continue where it can', () => { + // Not `whole`: there is no span this index has to reach past, and the first + // enablement inside a running app has a warm list cursor to make use of. + expect(decide({ row: undefined })).toBe('any') +}) + +it('skips a file the index already covers at this stat', () => { + expect(decide({})).toBe('skip') +}) + +it('reads a file whose stat moved, however it moved', () => { + expect(decide({ file: { mtimeMs: MTIME + 1 } })).toBe('any') + // Grown without its mtime moving: a same-second append, or a restored stamp. + expect(decide({ file: { sizeBytes: 200 } })).toBe('any') +}) + +it('reads a file outside the retention window not at all', () => { + expect(decide({ row: undefined, cutoffMs: MTIME + 1 })).toBe('skip') + // And retention wins over everything else that would have asked for a read. + expect(decide({ row: row({ state: 'due' }), cutoffMs: MTIME + 1 })).toBe('skip') +}) + +it('reads a row owed a whole read from the start', () => { + expect(decide({ row: row({ state: 'due' }) })).toBe('whole') +}) + +it('reads whole rather than appending onto a cursor that continues nothing', () => { + // A different file at the same name: the identity check hands back no cursor. + expect(decide({ cursor: null })).toBe('whole') + // A chunked read that committed a prefix and no offset any append continues. + expect(decide({ cursor: { byteOffset: null, mtimeMs: MTIME, sizeBytes: 100 } })).toBe('whole') + // Shorter than the index read to, so this is not that file any more. + expect(decide({ file: { sizeBytes: 40 }, cursor })).toBe('whole') +}) + +it('retries a failed read until it has failed enough times at one stat', () => { + for (let failures = 1; failures < SESSION_SEARCH_FAILURES_BEFORE_HELD_OUT; failures++) { + expect( + decide({ row: row({ state: 'failed', failCount: failures, failedMtimeMs: MTIME }) }) + ).toBe('any') + } + expect( + decide({ + row: row({ + state: 'failed', + failCount: SESSION_SEARCH_FAILURES_BEFORE_HELD_OUT, + failedMtimeMs: MTIME + }) + }) + ).toBe('skip') +}) + +it('starts trying again the moment a held-out file changes', () => { + // The stat is the whole release condition, so nothing has to remember when + // the failures happened or schedule a retry. + expect( + decide({ + file: { mtimeMs: MTIME + 1 }, + row: row({ state: 'failed', failCount: 9, failedMtimeMs: MTIME }) + }) + ).toBe('any') +}) diff --git a/src/main/ai-vault-search/session-search-read-decision.ts b/src/main/ai-vault-search/session-search-read-decision.ts new file mode 100644 index 00000000000..cb25ad27ccb --- /dev/null +++ b/src/main/ai-vault-search/session-search-read-decision.ts @@ -0,0 +1,100 @@ +import type { SessionFileCandidate } from '../ai-vault/session-scanner-types' +import type { SessionParseReadRequirement } from '../ai-vault/session-scanner-parse-cache' +import { requiresWholeRead, type SessionSearchIndexedFile } from './session-search-file-cursor' +import type { SessionSearchFileRow } from './session-search-store' + +/** + * Failures at one unchanged stat before a file is left alone. + * + * Three rather than one, because a single failure is often a transcript being + * rewritten under the read; three at the same mtime is not. The retry policy is + * the stat itself: an edit, a restore, or a `touch` after a `chmod` all move it, + * and nothing else does, so no timer is needed and none is kept. + */ +export const SESSION_SEARCH_FAILURES_BEFORE_HELD_OUT = 3 + +/** + * What a pass owes one candidate: nothing, a read, or a read from the start. + * + * `any` and `whole` are the reader's own lanes. `whole` drops the session + * list's resume point, which is the only way to reach a span this index never + * saw; `any` asks for some bytes and lets the reader continue where it can, + * which is what the first enablement inside a running app needs — a warm list + * cursor sitting at the file's current stat would otherwise open nothing. + */ +export type SessionSearchReadDecision = 'skip' | SessionParseReadRequirement + +/** + * The whole of the indexer's decide step, as a function of the candidate's stat + * and the row the store holds for it. No pass state, no queue, no memory: the + * same inputs give the same answer on the first pass after a restart as on the + * hundredth of a long-running process, which is what lets a deadline cut a pass + * short with nothing to record. What did not get read is still owed, because + * being owed is a fact about the row. + */ +export function sessionSearchReadDecision(args: { + candidate: SessionFileCandidate + /** The file table's row, or undefined when the index holds nothing for it. */ + row: SessionSearchFileRow | undefined + /** The cursor for this candidate's identity; null when it is not continuable. */ + cursor: SessionSearchIndexedFile | null + /** Oldest transcript mtime worth holding rows for, or null for all history. */ + cutoffMs: number | null +}): SessionSearchReadDecision { + const { candidate, row, cursor, cutoffMs } = args + const file = candidate.file + // Retention first: a file outside the window is not worth reading whatever + // else is true of it, and the purge is what removes any row it still has. + if (cutoffMs !== null && file.mtimeMs < cutoffMs) { + return 'skip' + } + if (!row) { + // Nothing held for this path. Not `whole`, because the reader can continue + // from wherever it likes: there is no span this index has to reach past. + return 'any' + } + if (heldOut(row, file.mtimeMs)) { + return 'skip' + } + if (row.state === 'due') { + // The index is behind on a span no append reaches: a declined append, or a + // window that widened to admit this file. + return 'whole' + } + if (cursor === null || requiresWholeRead(cursor)) { + // A different file at the same name, or a chunked read that left a prefix + // and no cursor. Appending onto either would splice two spans together. + return 'whole' + } + const size = file.sizeBytes + if (typeof size === 'number' && cursor.byteOffset !== null && cursor.byteOffset > size) { + // Shorter than the index read to: this is not the file that cursor came from. + return 'whole' + } + if (row.state === 'failed') { + // Still within its retries, or the stat moved since it last failed. + return 'any' + } + return statMatches(row, file) ? 'skip' : 'any' +} + +/** + * True when this file has failed enough times at exactly this stat to stop + * trying. The stat is the whole release condition, so a file nobody touches is + * never read again and one that changes is read on the next pass that sees it. + */ +function heldOut(row: SessionSearchFileRow, mtimeMs: number): boolean { + return ( + row.state === 'failed' && + row.failCount >= SESSION_SEARCH_FAILURES_BEFORE_HELD_OUT && + row.failedMtimeMs === mtimeMs + ) +} + +/** The row already describes the file as it is now. */ +function statMatches(row: SessionSearchFileRow, file: SessionFileCandidate['file']): boolean { + return ( + row.mtimeMs === file.mtimeMs && + (row.sizeBytes === null || file.sizeBytes === undefined || row.sizeBytes === file.sizeBytes) + ) +} diff --git a/src/main/ai-vault-search/session-search-retention-delete.test.ts b/src/main/ai-vault-search/session-search-retention-delete.test.ts new file mode 100644 index 00000000000..c21c8d7fe2b --- /dev/null +++ b/src/main/ai-vault-search/session-search-retention-delete.test.ts @@ -0,0 +1,188 @@ +import { expect, it } from 'vitest' +import type SyncDatabase from '../sqlite/sync-database' +import { + deleteExpiredSearchFiles, + RETENTION_DELETE_ROWS_PER_STEP +} from './session-search-retention-delete' +import { openSessionSearchIndexFile } from './session-search-index-test-fixture' +import { SessionSearchStore } from './session-search-store' + +function seed(db: SyncDatabase, id: number, rows: number, mtime: number): void { + db.prepare( + `INSERT INTO sessions(id,agent,session_id,file_path,title,cwd,cwd_key,resume_command) + VALUES (?, 'claude', ?, ?, 'synthetic retention', '/fixture', '/fixture', '')` + ).run(id, String(id), String(id)) + db.prepare('INSERT INTO files(path,byte_offset,mtime_ms,session_row_id) VALUES (?,1,?,?)').run( + String(id), + mtime, + id + ) + db.exec('BEGIN') + for (let i = 0; i < rows; i++) { + const row = db + .prepare("INSERT INTO messages(session_row_id,role) VALUES (?,'user')") + .run(id).lastInsertRowid + db.prepare('INSERT INTO messages_fts(rowid,user_text) VALUES (?,?)').run(row, 'retentionneedle') + } + db.exec('COMMIT') +} + +/** + * Sessions a search would still return. Every retrieval joins a message to its + * session, which is what makes cutting the session loose enough to hide the + * whole thing while its rows are still being reclaimed. + */ +function visibleSessionIds(db: SyncDatabase): string[] { + return ( + db + .prepare( + `SELECT DISTINCT s.session_id AS id FROM messages_fts + JOIN messages m ON m.id = messages_fts.rowid + JOIN sessions s ON s.id = m.session_row_id + WHERE messages_fts MATCH 'retentionneedle' ORDER BY s.session_id` + ) + .all() as { id: string }[] + ).map((row) => row.id) +} + +function count(db: SyncDatabase, table: string): number { + return (db.prepare(`SELECT count(*) AS n FROM ${table}`).get() as { n: number }).n +} + +it('seeks the expiring end of the file list instead of scanning it', async () => { + const index = await openSessionSearchIndexFile('ss-retention-plan') + try { + seed(index.db, 1, 1, 1) + const plan = ( + index.db + .prepare('EXPLAIN QUERY PLAN SELECT path FROM files WHERE mtime_ms < ? ORDER BY mtime_ms') + .all(100) as { detail: string }[] + ) + .map((row) => row.detail) + .join(' ') + // Without files_mtime this is "SCAN files" plus a "USE TEMP B-TREE FOR ORDER BY". + expect(plan).toContain('files_mtime') + expect(plan).not.toContain('TEMP B-TREE') + } finally { + await index.close() + } +}) + +it('hides an expiring session at once, then reclaims its rows in bounded steps', async () => { + const index = await openSessionSearchIndexFile('ss-retention-yield') + seed(index.db, 1, 1025, 1) + seed(index.db, 2, 1, 200) + let previous = 1025 + const steps: number[] = [] + try { + await deleteExpiredSearchFiles( + index.db, + 100, + () => false, + async () => { + const left = count(index.db, 'messages WHERE session_row_id=1') + steps.push(previous - left) + previous = left + // Cut loose in the very first transaction, so no query ever sees it with + // some of its messages already gone. + expect(visibleSessionIds(index.db)).toEqual(['2']) + } + ) + // The file transaction, then one bounded batch per step until the rows are gone. + expect(steps).toEqual([0, RETENTION_DELETE_ROWS_PER_STEP, 256, 256, 256, 1]) + expect(count(index.db, 'messages_fts')).toBe(1) + expect(count(index.db, 'sessions')).toBe(1) + } finally { + await index.close() + } +}) + +it('finishes an interrupted deletion after reopening', async () => { + const index = await openSessionSearchIndexFile('ss-retention-resume') + let store = new SessionSearchStore(index.path) + let closed = false + let steps = 0 + try { + seed(index.db, 1, 513, 1) + await deleteExpiredSearchFiles( + index.db, + 100, + () => closed, + async () => { + if (++steps === 2) { + store.close() + closed = true + } + } + ) + // Some rows went, the rest did not, and nothing recorded that anywhere. + const stranded = count(index.db, 'messages') + expect(stranded).toBeGreaterThan(0) + expect(stranded).toBeLessThan(513) + expect(visibleSessionIds(index.db)).toEqual([]) + + store = new SessionSearchStore(index.path) + closed = false + // Rows nothing points at are the whole record of unfinished work, so the + // rest goes even with retention now unlimited. + await store.purgeOlderThan(null) + expect(count(index.db, 'messages')).toBe(0) + expect(count(index.db, 'messages_fts')).toBe(0) + } finally { + if (!closed) { + store.close() + } + await index.close() + } +}) + +it('cancels retention between batches and resumes without exposing a partial session', async () => { + const index = await openSessionSearchIndexFile('ss-retention-cancel') + const store = new SessionSearchStore(index.path) + try { + seed(index.db, 1, 1025, 1) + const controller = new AbortController() + const purge = store.purgeOlderThan(100, controller.signal) + setImmediate(() => controller.abort()) + await purge + const remaining = count(index.db, 'messages') + expect(remaining).toBeGreaterThan(0) + expect(remaining).toBeLessThan(1025) + expect(visibleSessionIds(index.db)).toEqual([]) + await store.purgeOlderThan(null) + expect(count(index.db, 'messages')).toBe(0) + } finally { + store.close() + await index.close() + } +}) + +it('keeps a file a read refreshed after the expiry list was taken', async () => { + const index = await openSessionSearchIndexFile('ss-retention-refreshed') + try { + seed(index.db, 1, 2, 1) + seed(index.db, 2, 2, 2) + let refreshed = false + // The scan of `files` happens once, up front. A read of the second transcript + // lands while the first is being deleted, which makes it new enough to keep. + await deleteExpiredSearchFiles( + index.db, + 100, + () => false, + async () => { + if (!refreshed) { + refreshed = true + index.db.prepare('UPDATE files SET mtime_ms = 500 WHERE path = ?').run('2') + } + } + ) + + // Only the per-file transaction re-reading the mtime it is about to act on + // keeps that session; the list it came from says both should go. + expect(count(index.db, 'files')).toBe(1) + expect(visibleSessionIds(index.db)).toEqual(['2']) + expect(count(index.db, 'messages')).toBe(2) + } finally { + await index.close() + } +}) diff --git a/src/main/ai-vault-search/session-search-retention-delete.ts b/src/main/ai-vault-search/session-search-retention-delete.ts new file mode 100644 index 00000000000..e8d407f8be9 --- /dev/null +++ b/src/main/ai-vault-search/session-search-retention-delete.ts @@ -0,0 +1,102 @@ +import { setImmediate as yieldToEventLoop } from 'node:timers/promises' +import type SyncDatabase from '../sqlite/sync-database' +import { deleteSearchMessages } from './session-search-message-rows' + +export const RETENTION_DELETE_ROWS_PER_STEP = 256 +// Why in step with the deletes rather than one sweep at the end: `auto_vacuum = +// INCREMENTAL` holds every freed page until something asks for it back, and +// asking for a whole purge's worth at once is one long stall (40 ms per 22 MB +// freed, measured) instead of many short ones. +const RECLAIM_PAGES_PER_STEP = 2000 + +/** + * Drops every file older than the cutoff, then hands its rows back in bounded + * steps. + * + * The two halves are separate on purpose. Cutting a session loose from its file + * is one small transaction, and it is what makes the session stop answering + * searches — every read joins `sessions`, so a row whose session is gone is + * already unreachable. Reclaiming those rows is the expensive half, and it can + * be paused, interrupted or resumed at any point without a reader ever seeing a + * session that is half deleted. A crash in the middle leaves rows nothing + * points at, and `drainOrphanedMessages` finds them on the next pass. + */ +export async function deleteExpiredSearchFiles( + db: SyncDatabase, + cutoffMs: number | null, + closed: () => boolean, + yieldStep: () => Promise = yieldToEventLoop +): Promise { + if (cutoffMs !== null) { + const expired = db + .prepare('SELECT path FROM files WHERE mtime_ms < ? ORDER BY mtime_ms') + .all(cutoffMs) as { path: string }[] + for (const { path } of expired) { + if (closed()) { + return + } + db.exec('BEGIN IMMEDIATE') + try { + // Re-read under the lock: a read of this file may have landed since the + // list was taken, which makes it new enough to keep. + const file = db + .prepare('SELECT session_row_id FROM files WHERE path = ? AND mtime_ms < ?') + .get(path, cutoffMs) as { session_row_id: number | null } | undefined + if (file) { + db.prepare('DELETE FROM sessions WHERE id = ?').run(file.session_row_id) + db.prepare('DELETE FROM files WHERE path = ?').run(path) + } + db.exec('COMMIT') + } catch (error) { + db.exec('ROLLBACK') + throw error + } + await yieldStep() + } + } + await drainOrphanedMessages(db, closed, yieldStep) +} + +/** + * Deletes rows whose session no longer exists, a bounded batch per transaction. + * + * That set is exactly what retention, a replace that cut its old generation + * loose, a removed source and an interrupted earlier drain leave behind, so the + * index needs no record of unfinished work beyond the rows themselves. + * + * Exported for the store, which runs it after a replace commits for the same + * reason retention runs it after its own small transaction: cutting a session + * loose is what hides it, and reclaiming its rows is the half that must not + * hold one transaction. + */ +export async function drainOrphanedMessages( + db: SyncDatabase, + closed: () => boolean, + yieldStep: () => Promise = yieldToEventLoop +): Promise { + // Ordered by session so one call to this walks a session's rows to the end + // before paying for the scan that finds the next one. + const nextOrphan = db.prepare( + `SELECT session_row_id FROM messages + WHERE session_row_id NOT IN (SELECT id FROM sessions) LIMIT 1` + ) + let orphan = (nextOrphan.get() as { session_row_id: number } | undefined)?.session_row_id + while (orphan !== undefined && !closed()) { + db.exec('BEGIN IMMEDIATE') + let deleted = 0 + try { + deleted = deleteSearchMessages(db, orphan, RETENTION_DELETE_ROWS_PER_STEP) + db.exec('COMMIT') + } catch (error) { + db.exec('ROLLBACK') + throw error + } + db.pragma(`incremental_vacuum(${RECLAIM_PAGES_PER_STEP})`) + if (deleted < RETENTION_DELETE_ROWS_PER_STEP) { + orphan = (nextOrphan.get() as { session_row_id: number } | undefined)?.session_row_id + } + await yieldStep() + } + // A `removeFile` frees its pages outside this loop and may leave none to drain. + db.pragma(`incremental_vacuum(${RECLAIM_PAGES_PER_STEP})`) +} diff --git a/src/main/ai-vault-search/session-search-retention-policy.test.ts b/src/main/ai-vault-search/session-search-retention-policy.test.ts new file mode 100644 index 00000000000..71c6cdb0862 --- /dev/null +++ b/src/main/ai-vault-search/session-search-retention-policy.test.ts @@ -0,0 +1,26 @@ +import { expect, it } from 'vitest' +import { sessionSearchHistoryCutoffMs } from './session-search-retention-policy' + +const NOW = 1_740_000_000_000 + +it('treats a fractional or non-positive day count as no bound at all', () => { + // A day count that floors to zero would read as "all history" in one place + // and "cutoff is now" in the other; both sides answer null. + expect(sessionSearchHistoryCutoffMs(0.4, NOW)).toBeNull() + expect(sessionSearchHistoryCutoffMs(0, NOW)).toBeNull() + expect(sessionSearchHistoryCutoffMs(-30, NOW)).toBeNull() + expect(sessionSearchHistoryCutoffMs(30, NOW)).toBe(NOW - 30 * 86_400_000) + // Clamped rather than unbounded: a caller asking for three thousand years of + // history gets the ceiling, not an mtime before the epoch. + expect(sessionSearchHistoryCutoffMs(999_999, NOW)).toBe(NOW - 3_650 * 86_400_000) +}) + +// The cutoff is read from the clock on every pass, not frozen at construction: +// a purge and the accept check that follows it must not disagree about where +// the window is, or the sweep deletes rows the next candidate re-indexes. +it('moves the cutoff with the clock', () => { + const later = NOW + 86_400_000 + expect(sessionSearchHistoryCutoffMs(30, later)).toBe( + (sessionSearchHistoryCutoffMs(30, NOW) ?? 0) + 86_400_000 + ) +}) diff --git a/src/main/ai-vault-search/session-search-retention-policy.ts b/src/main/ai-vault-search/session-search-retention-policy.ts new file mode 100644 index 00000000000..c7fa8a0b6d1 --- /dev/null +++ b/src/main/ai-vault-search/session-search-retention-policy.ts @@ -0,0 +1,25 @@ +const DAY_MS = 86_400_000 +const HISTORY_DAYS_MAX = 3_650 + +/** + * The retention window, as the indexer's callers state it and as the store + * consumes it. Settings storage is PR 3b's problem; this is the arithmetic. + */ +function normalizeSessionSearchHistoryDays(value: number | null): number | null { + if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) { + return null + } + // Why floor then re-check: a fractional day floors to 0, which reads as "all + // history" on one side and "now" on the other; make the two agree. + const days = Math.floor(value) + return days <= 0 ? null : Math.min(HISTORY_DAYS_MAX, days) +} + +/** The oldest transcript mtime worth indexing; null means no bound. */ +export function sessionSearchHistoryCutoffMs( + historyDays: number | null, + nowMs: number +): number | null { + const days = normalizeSessionSearchHistoryDays(historyDays) + return days === null ? null : nowMs - days * DAY_MS +} diff --git a/src/main/ai-vault-search/session-search-retrieval.ts b/src/main/ai-vault-search/session-search-retrieval.ts new file mode 100644 index 00000000000..59fef23e903 --- /dev/null +++ b/src/main/ai-vault-search/session-search-retrieval.ts @@ -0,0 +1,244 @@ +import type SyncDatabase from '../sqlite/sync-database' +import type { SessionSearchRoute, SessionSearchScope } from './session-search-engine-types' +import type { MessageRow, SessionRow } from './session-search-hit-ranking' +import { + andExpression, + orExpression, + phraseExpression, + planSessionSearchQuery, + scopedExpression, + type SessionSearchQueryPlan +} from './session-search-query-planner' +import type { SessionRowFilter } from './session-search-row-filter' +import { SessionSearchTypoRepair } from './session-search-typo-repair' + +// The operator-only walk: rows per page, and how far past a full candidate set +// it will read before giving up on finding more matches. +const RECENT_PAGE_ROWS = 512 +// Ids per `loadSessions` statement, with room to spare for the filter's own +// bound values beside them. +const SESSION_ID_BATCH = 500 +const RECENT_SCAN_FACTOR = 20 + +// Measured: user 3 / assistant 2 / tool 1 / identifiers 1 (MRR 0.503 vs 0.475 flat). +const FULL_WEIGHTS = '3.0, 2.0, 1.0, 1.0' +// Tool and identifier columns do not contribute to conversation ranking. +const CONVERSATION_WEIGHTS = '3.0, 2.0, 0.0, 0.0' + +export type RetrievalScope = { + scope: SessionSearchScope + sort: 'relevance' | 'newest' + filter: SessionRowFilter + /** + * `repo:` / `path:`, which SQL cannot express. Applied over retrieved rows; + * see session-search-row-filter for why it cannot be pushed down. + */ + matchesOperators: (session: SessionRow) => boolean + /** + * Sessions retrieved before ranking cuts the page. See + * docs/reference/agent-session-search-query-tuning.md for the measurements + * behind the default; it is an option because the right value depends on how + * large an index is and no single number is right for every host. + */ + candidateLimit: number +} + +export type Retrieved = { + sessions: SessionRow[] + rows: MessageRow[] + incomplete: boolean + route: SessionSearchRoute + /** The plan the rows were actually retrieved by; snippets highlight from it. */ + plan: SessionSearchQueryPlan + repairedTerms?: string[] +} + +/** + * The bm25 weights a scope ranks with. The conversation pair stays here rather + * than beside `scopedExpression`, because weights are a property of this SQL + * and nothing else asks for them. + */ +export function scopedWeights(scope: SessionSearchScope): string { + return scope === 'all' ? FULL_WEIGHTS : CONVERSATION_WEIGHTS +} + +/** The FTS half of a search: the route ladder and the SQL each rung runs. */ +export class SessionSearchRetrieval { + private readonly typoRepair: SessionSearchTypoRepair + + constructor(private readonly db: SyncDatabase) { + this.typoRepair = new SessionSearchTypoRepair(db) + } + + /** + * The route ladder: phrase, then AND for a literal-looking query, then typo + * repair, then OR. + * + * Repair runs before the OR fallback rather than after it fails. A typo next + * to a common word would otherwise be masked: the common word alone retrieves + * plenty of rows over OR, so nothing would ever look like a miss worth + * repairing. + */ + run(plan: SessionSearchQueryPlan, scope: RetrievalScope): Retrieved { + let incomplete = false + let sessions: SessionRow[] = [] + const match = (expression: string): MessageRow[] => { + const rows = this.match(expression, scope) + incomplete ||= rows.length >= scope.candidateLimit + sessions = this.loadSessions( + rows.map((row) => row.session_row_id), + scope + ) + const eligible = new Set(sessions.map((row) => row.id)) + return rows.filter((row) => eligible.has(row.session_row_id)) + } + const exact = this.literal(plan, match) + if (exact) { + return { ...exact, plan, incomplete, sessions } + } + const repaired = this.repair(plan, scope.scope) + const effective = repaired ?? plan + const literal = repaired ? this.literal(repaired, match) : null + const found = literal ?? { + rows: match(orExpression(effective.terms)), + route: 'or' as const + } + return { + sessions, + rows: found.rows, + incomplete, + route: repaired ? (`typo+${found.route}` as SessionSearchRoute) : found.route, + plan: effective, + ...(repaired ? { repairedTerms: repaired.body } : {}) + } + } + + /** + * Newest sessions the constraints allow: what an operator-only query names. + * + * Walked in pages rather than taken in one `LIMIT`, because the operators are + * applied in JS. A single cut of the newest N would hand ranking whatever + * happened to be recent and then throw most of it away, so `repo:x` on a busy + * index could answer with nothing while plenty matched. The walk is bounded + * both ways: it stops at a full candidate set, and at a ceiling on rows read. + */ + recent(scope: RetrievalScope): { sessions: SessionRow[]; incomplete: boolean } { + const { conditions, values } = scope.filter + const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '' + const page = this.db.prepare( + `SELECT * FROM sessions ${where} + ORDER BY updated_at DESC, id DESC LIMIT ? OFFSET ?` + ) + const ceiling = scope.candidateLimit * RECENT_SCAN_FACTOR + const sessions: SessionRow[] = [] + let scanned = 0 + // Why the flag and not a count: both caps mean the same thing to a caller — + // a session it never saw may have matched — and only the loop knows which + // of them ended it. Reporting rows read instead let the engine infer + // completeness from a full candidate set alone, so giving up at the ceiling + // with nothing found looked exactly like a search that found nothing. + let incomplete = false + while (sessions.length < scope.candidateLimit) { + if (scanned >= ceiling) { + incomplete = true + break + } + const rows = page.all(...values, RECENT_PAGE_ROWS, scanned) as SessionRow[] + if (rows.length === 0) { + break + } + scanned += rows.length + for (const row of rows) { + if (sessions.length < scope.candidateLimit && scope.matchesOperators(row)) { + sessions.push(row) + } + } + } + return { sessions, incomplete: incomplete || sessions.length >= scope.candidateLimit } + } + + /** Bound SQL parameters independently of the configurable candidate limit. */ + private loadSessions(ids: readonly number[], scope: RetrievalScope): SessionRow[] { + const rows: SessionRow[] = [] + for (let start = 0; start < ids.length; start += SESSION_ID_BATCH) { + const batch = ids.slice(start, start + SESSION_ID_BATCH) + const conditions = [`id IN (${batch.map(() => '?').join(',')})`, ...scope.filter.conditions] + rows.push( + ...(this.db + .prepare(`SELECT * FROM sessions WHERE ${conditions.join(' AND ')}`) + .all(...batch, ...scope.filter.values) as SessionRow[]) + ) + } + return rows.filter((row) => scope.matchesOperators(row)) + } + + private repair( + plan: SessionSearchQueryPlan, + scope: SessionSearchScope + ): SessionSearchQueryPlan | null { + const typoRepair = this.typoRepair + let changed = false + const body = plan.body.map((term) => { + // Repaired inside the scope the search will run in, so a spelling only + // tool output carries neither suppresses a repair nor becomes one. + const fix = typoRepair.correct(term, scope) + if (fix && fix !== term.toLowerCase()) { + changed = true + return fix + } + return term + }) + // The repair changes spellings, not the query's character: the re-plan is + // told what the original decided so a corrected literal keeps every term it + // was typed with. + return changed ? planSessionSearchQuery(body.join(' '), plan.literal) : null + } + + /** Phrase, then AND, for literal-looking queries; null when neither matches. */ + private literal( + plan: SessionSearchQueryPlan, + match: (expression: string) => MessageRow[] + ): { rows: MessageRow[]; route: 'phrase' | 'and' } | null { + if (!plan.literal || plan.body.length === 0) { + return null + } + // A one-token literal (`resolveTerminalPath`, `src/a/b.ts`) is its own + // phrase: the tokenizer keeps it whole, so the exact token is the cheap, + // precise first try before the identifier pieces fan out over OR. + const phrase = match(phraseExpression(plan.body)) + if (phrase.length > 0) { + return { rows: phrase, route: 'phrase' } + } + if (plan.body.length < 2) { + return null + } + const and = match(andExpression(plan.body)) + return and.length > 0 ? { rows: and, route: 'and' } : null + } + + private match(expression: string, scope: RetrievalScope): MessageRow[] { + const { filter, sort, candidateLimit } = scope + const eligible = filter.conditions.length + ? ` AND m.session_row_id IN (SELECT id FROM sessions WHERE ${filter.conditions.join(' AND ')})` + : '' + const matched = `SELECT messages_fts.rowid AS rowid, + -bm25(messages_fts, ${scopedWeights(scope.scope)}) AS score, + m.session_row_id, m.role, m.ts, s.updated_at + FROM messages_fts JOIN messages m ON m.id = messages_fts.rowid + JOIN sessions s ON s.id = m.session_row_id WHERE messages_fts MATCH ?${eligible}` + // Why: collapse to one row per session BEFORE the candidate limit, on both + // sort orders, so a single long session cannot occupy the whole page. + // `max(score)` makes SQLite pick that session's best row for the bare columns. + // Cost of grouping instead of a bounded top-N sorter, measured: ~1.75x + // (49.6 vs 28.6 ms at 80k matching rows, 183.6 vs 104.1 ms at 240k) and a + // temp b-tree over every match. No inner LIMIT can bound it: the CTE has no + // order, so any cut drops whole sessions rather than their surplus rows. + const order = sort === 'newest' ? 'updated_at DESC, score DESC' : 'score DESC' + const sql = `WITH matched AS MATERIALIZED (${matched}) + SELECT rowid, max(score) AS score, session_row_id, role, ts FROM matched + GROUP BY session_row_id ORDER BY ${order} LIMIT ${candidateLimit}` + return this.db + .prepare(sql) + .all(scopedExpression(scope.scope, expression), ...filter.values) as MessageRow[] + } +} diff --git a/src/main/ai-vault-search/session-search-row-filter.test.ts b/src/main/ai-vault-search/session-search-row-filter.test.ts new file mode 100644 index 00000000000..1cec0a528f9 --- /dev/null +++ b/src/main/ai-vault-search/session-search-row-filter.test.ts @@ -0,0 +1,147 @@ +import { afterEach, describe, expect, it } from 'vitest' +import type SyncDatabase from '../sqlite/sync-database' +import type { SessionSearchFilters } from './session-search-engine-types' +import { cwdKey } from './session-search-file-records' +import { sessionRowFilter } from './session-search-row-filter' +import { + openSessionSearchIndexFile, + type SessionSearchIndexFile +} from './session-search-index-test-fixture' + +let index: SessionSearchIndexFile | null = null + +afterEach(async () => { + await index?.close() + index = null +}) + +async function openIndex(): Promise { + index = await openSessionSearchIndexFile('ss-row-filter') + return index.db +} + +function addSession( + db: SyncDatabase, + id: number, + cwd: string | null, + overrides: { agent?: string; updatedAt?: string } = {} +): void { + db.prepare( + `INSERT INTO sessions(id,agent,session_id,file_path,title,cwd,cwd_key,updated_at,resume_command) + VALUES (?,?,?,?,'fixture',?,?,?,'')` + ).run( + id, + overrides.agent ?? 'claude', + String(id), + `/synthetic/${id}`, + cwd, + cwdKey(cwd), + overrides.updatedAt ?? '2026-09-01T00:00:00.000Z' + ) +} + +function selected(db: SyncDatabase, filters: SessionSearchFilters = {}): number[] { + const filter = sessionRowFilter(filters) + const where = filter.conditions.length > 0 ? `WHERE ${filter.conditions.join(' AND ')}` : '' + return ( + db.prepare(`SELECT id FROM sessions ${where} ORDER BY id`).all(...filter.values) as { + id: number + }[] + ).map((row) => row.id) +} + +describe('a cwd scope is the sidebar key, or anything below it', () => { + it.each([ + ['C:\\Work\\App', 'c:/work/app', true], + ['C:\\Work\\App\\src', 'c:/work/app', true], + ['/work/APP/src', '/work/app', false], + ['/work/caf\u00e9', '/work/cafe\u0301', true], + ['/work/app-other', '/work/app', false], + ['/work/a_b/src', '/work/a_b', true], + ['/work/axb/src', '/work/a_b', false], + // Roots: `/` is the one key that is already a separator, which is where a + // range bound is easiest to get wrong. A Windows key is not under POSIX `/`. + ['/', '/', true], + ['/work/app', '/', true], + ['C:\\Work\\App', '/', false], + ['C:\\', 'C:\\', true], + ['C:\\Work\\App', 'C:\\', true] + ])('scopes %s under %s: %s', async (cwd, scope, expected) => { + const db = await openIndex() + addSession(db, 1, cwd) + expect(selected(db, { scopePaths: [scope] })).toEqual(expected ? [1] : []) + }) + + it('never matches a session whose transcript recorded no cwd', async () => { + const db = await openIndex() + addSession(db, 1, null) + expect(selected(db, { scopePaths: ['/work'] })).toEqual([]) + expect(selected(db)).toEqual([1]) + }) + + it('narrows to nothing when no scope the caller gave could be keyed', async () => { + // `cwdKey` returns null for a scope it cannot key, and a scope that matches + // nothing must return nothing; dropping it would answer the whole index. + const db = await openIndex() + addSession(db, 1, '/work/app') + addSession(db, 2, '/elsewhere') + expect(selected(db, { scopePaths: [''] })).toEqual([]) + expect(selected(db, { scopePaths: ['', '/work/app'] })).toEqual([1]) + }) + + it('keeps a WSL UNC workspace distinct from the bare Linux spelling', async () => { + // PR 2 decided cwd_key does not qualify a Linux path with its distro: the + // collision is real but every SSH host has it too, and the fix is a column + // naming the execution host, not a key only some hosts spell differently. + const db = await openIndex() + addSession(db, 1, '\\\\wsl.localhost\\Ubuntu\\home\\ada\\app') + addSession(db, 2, '/home/ada/app') + expect(selected(db, { scopePaths: ['\\\\wsl$\\Ubuntu\\home\\ada'] })).toEqual([1]) + expect(selected(db, { scopePaths: ['/home/ada/app'] })).toEqual([2]) + expect(selected(db, { scopePaths: ['\\\\wsl$\\Debian\\home\\ada\\app'] })).toEqual([]) + }) +}) + +describe('caller filters', () => { + it('narrows by agent, and by updated-at floor', async () => { + const db = await openIndex() + addSession(db, 1, '/work/app', { agent: 'claude', updatedAt: '2026-09-01T00:00:00.000Z' }) + addSession(db, 2, '/work/app', { agent: 'codex', updatedAt: '2026-09-05T00:00:00.000Z' }) + expect(selected(db, { agents: ['codex'] })).toEqual([2]) + expect(selected(db, { since: '2026-09-03T00:00:00.000Z' })).toEqual([2]) + expect(selected(db, { agents: ['claude'], since: '2026-09-03T00:00:00.000Z' })).toEqual([]) + }) + + it('applies the retention cutoff through the files table', async () => { + const db = await openIndex() + addSession(db, 1, '/work/app') + addSession(db, 2, '/work/app') + db.prepare( + "INSERT INTO files(path,byte_offset,mtime_ms,session_row_id) VALUES ('a',0,100,1)" + ).run() + db.prepare( + "INSERT INTO files(path,byte_offset,mtime_ms,session_row_id) VALUES ('b',0,500,2)" + ).run() + const filter = sessionRowFilter({}, 300) + const rows = db + .prepare(`SELECT id FROM sessions WHERE ${filter.conditions.join(' AND ')}`) + .all(...filter.values) as { id: number }[] + expect(rows.map((row) => row.id)).toEqual([2]) + }) +}) + +it('plans a cwd scope as a seek on sessions_cwd_key, never a scan', async () => { + const db = await openIndex() + const filter = sessionRowFilter({ scopePaths: ['/work/app'] }) + const plan = ( + db + .prepare( + `EXPLAIN QUERY PLAN SELECT id FROM sessions WHERE ${filter.conditions.join(' AND ')}` + ) + .all(...filter.values) as { detail: string }[] + ).map((row) => row.detail) + + expect(plan.join(' | ')).toContain('sessions_cwd_key') + expect(plan.some((detail) => detail.startsWith('SEARCH'))).toBe(true) + expect(plan.some((detail) => detail.startsWith('SCAN sessions'))).toBe(false) +}) diff --git a/src/main/ai-vault-search/session-search-row-filter.ts b/src/main/ai-vault-search/session-search-row-filter.ts new file mode 100644 index 00000000000..4f5b6106e7d --- /dev/null +++ b/src/main/ai-vault-search/session-search-row-filter.ts @@ -0,0 +1,90 @@ +import { cwdKey } from './session-search-file-records' +import type { SessionSearchFilters } from './session-search-engine-types' + +/** SQL fragments for the `sessions` WHERE clause; every condition is ANDed. */ +export type SessionRowFilter = { + conditions: string[] + values: (string | number)[] +} + +// Stored identity: `cwdKey` is the sidebar's `folderGroupKey` without its prefix, +// so a scope term and an indexed session are keyed by one function, never two. +const CWD = 'cwd_key' + +/** + * The narrowings SQL can express exactly, in one place, so retrieval, the + * operator-only page and the session load cannot drift apart. These conditions + * run over `sessions` itself. Reachability is not here and is not a condition: + * it is the INNER JOIN to `sessions` that every retrieval carries, which is + * what makes a message row a purge has not reclaimed yet unreadable. + * + * `repo:` and `path:` are deliberately absent. What they mean is the predicate + * the sessions panel applies (`matchesAiVaultQueryOperators`), and SQL cannot + * express it: LIKE folds ASCII and nothing else, so `path:CAFÉ` would miss + * `café`; `path:` searches the transcript path as well as the working + * directory, so `path:jsonl` would miss every session; and `repo:` compares the + * last two path segments, not one. A second spelling that came close would be a + * query meaning different things in the list and in the index, so the engine + * applies the panel's own predicate over the rows it retrieves instead. + * + * `scopePaths` stays here because it is exact: a prefix range over the key + * `cwdKey` produces, which folds exactly where the execution host folds — + * Windows drives, never a POSIX directory name. + */ +export function sessionRowFilter( + filters: SessionSearchFilters, + cutoffMs: number | null = null +): SessionRowFilter { + const filter: SessionRowFilter = { conditions: [], values: [] } + if (cutoffMs !== null) { + filter.conditions.push('id IN (SELECT session_row_id FROM files WHERE mtime_ms >= ?)') + filter.values.push(cutoffMs) + } + if (filters.agents && filters.agents.length > 0) { + filter.conditions.push(`agent IN (${filters.agents.map(() => '?').join(',')})`) + filter.values.push(...filters.agents) + } + if (filters.since) { + filter.conditions.push('updated_at >= ?') + filter.values.push(filters.since) + } + if (filters.scopePaths && filters.scopePaths.length > 0) { + // Several scopes mean any of them; every other narrowing is ANDed on. + const present = filters.scopePaths + .map((scope) => scopeCondition(filter, scope)) + .filter((condition) => condition !== null) + // Every scope unkeyable still means a scope, so it narrows to nothing; + // pushing no condition would widen the search to every session instead. + filter.conditions.push(present.length > 0 ? `(${present.join(' OR ')})` : '0 = 1') + } + return filter +} + +/** A scope the caller could not key is a scope nothing is inside of. */ +function scopeCondition(filter: SessionRowFilter, scope: string): string | null { + const key = cwdKey(scope) + return key === null ? null : insideCondition(filter, key) +} + +/** + * `key` itself, or anything below it. Why a half-open range and not + * `substr(key, 1, length(?)) = ?`: only `>=`/`<` can seek `sessions_cwd_key`; + * the substr form scans it. The bound is the child prefix with its last byte + * incremented, so it stops at the end of that prefix and nowhere else. The two + * arms cannot merge: one range over the bare key would also swallow a sibling + * like `/work/app-other`. No wildcards, so `%`/`_` in a folder name are literal. + * + * The filesystem root is the one key that already ends in a separator, and + * appending a second one would bound the range at `//`, which sorts below every + * real child; `cwdKey` keeps it as `/` for exactly this reason. + */ +function insideCondition(filter: SessionRowFilter, key: string): string { + const children = key.endsWith('/') ? key : `${key}/` + filter.values.push(key, children, nextAfterPrefix(children)) + return `(${CWD} = ? OR (${CWD} >= ? AND ${CWD} < ?))` +} + +/** The first string that sorts after every string starting with `prefix`. */ +function nextAfterPrefix(prefix: string): string { + return prefix.slice(0, -1) + String.fromCharCode(prefix.charCodeAt(prefix.length - 1) + 1) +} diff --git a/src/main/ai-vault-search/session-search-row-identity.test.ts b/src/main/ai-vault-search/session-search-row-identity.test.ts new file mode 100644 index 00000000000..4adc655b584 --- /dev/null +++ b/src/main/ai-vault-search/session-search-row-identity.test.ts @@ -0,0 +1,116 @@ +import { afterEach, beforeEach, expect, it } from 'vitest' +import type SyncDatabase from '../sqlite/sync-database' +import { deleteExpiredSearchFiles } from './session-search-retention-delete' +import { + openSessionSearchIndexFile, + syntheticCandidate, + syntheticSession, + userMessages, + type SessionSearchIndexFile +} from './session-search-index-test-fixture' +import { SessionSearchStore } from './session-search-store' + +// A session row id outlives the row: it names the rows in `messages` until a +// retention drain has walked all of them, which takes many transactions. These +// tests are about what may be handed that id in the meantime. + +let index: SessionSearchIndexFile +let store: SessionSearchStore +let errors: unknown[] + +beforeEach(async () => { + index = await openSessionSearchIndexFile('ss-row-identity') + errors = [] + store = new SessionSearchStore(index.path, (error) => errors.push(error)) +}) + +afterEach(async () => { + store.close() + await index.close() +}) + +const OLD_MTIME = 1_000 +const LIVE_MTIME = 1_000_000 +const LIVE_PATH = '/live.jsonl' + +function count(db: SyncDatabase, table: string): number { + return (db.prepare(`SELECT count(*) AS n FROM ${table}`).get() as { n: number }).n +} + +/** Rows a search would return for a term: the join every retrieval makes. */ +function matches(db: SyncDatabase, term: string): number { + return ( + db + .prepare( + `SELECT count(*) AS n FROM messages_fts JOIN messages m ON m.id = messages_fts.rowid + JOIN sessions s ON s.id = m.session_row_id WHERE messages_fts MATCH ?` + ) + .get(term) as { n: number } + ).n +} + +function indexFile(path: string, mtimeMs: number, text: string, rows: number): void { + const write = store.beginWrite(syntheticCandidate({ path, mtimeMs }), 'replace', 0)! + for (const message of userMessages(text, rows)) { + write.add(message) + } + expect(write.commit({ session: syntheticSession(), byteOffset: 50, incomplete: false })).toBe( + true + ) +} + +it('never hands a live session the rows of a purged one', async () => { + // Two expiring transcripts, each large enough that reclaiming their rows takes + // several transactions, and one live transcript the parser decoded no session + // from — so it holds a cursor and no session row of its own. + indexFile('/old-a.jsonl', OLD_MTIME, 'purgedneedle', 400) + indexFile('/old-b.jsonl', OLD_MTIME, 'purgedneedle', 400) + const live = syntheticCandidate({ path: LIVE_PATH, mtimeMs: LIVE_MTIME }) + const opening = store.beginWrite(live, 'replace', 0)! + opening.add(userMessages('excluded', 1)[0]!) + expect(opening.commit({ session: null, byteOffset: 50, incomplete: false })).toBe(true) + + let appended = false + await deleteExpiredSearchFiles( + index.db, + LIVE_MTIME, + () => false, + async () => { + // The window: both expiring sessions are cut loose, most of their rows are + // still on disk, and the live transcript grows. The append is legitimate — + // it continues this index's own cursor — and it needs a session row. + if (appended || count(index.db, 'sessions') > 0) { + return + } + appended = true + const write = store.beginWrite(live, 'append', 50)! + for (const message of userMessages('liveneedle', 2)) { + write.add(message) + } + expect( + write.commit({ session: syntheticSession(), byteOffset: 120, incomplete: false }) + ).toBe(true) + } + ) + + expect(appended).toBe(true) + // Reusing a freed id would adopt whatever of that session's rows the drain had + // not reached, and put them behind a live session no purge will visit again. + expect(matches(index.db, 'purgedneedle')).toBe(0) + expect(matches(index.db, 'liveneedle')).toBe(2) + expect(count(index.db, 'messages')).toBe(2) + expect(errors).toEqual([]) +}) + +it('never reissues a session row id a delete freed', () => { + for (const path of ['/a.jsonl', '/b.jsonl', '/c.jsonl']) { + indexFile(path, OLD_MTIME, 'seeded', 1) + } + const before = (index.db.prepare('SELECT max(id) AS id FROM sessions').get() as { id: number }).id + index.db.exec('DELETE FROM sessions') + + indexFile('/d.jsonl', OLD_MTIME, 'seeded', 1) + expect((index.db.prepare('SELECT id FROM sessions').get() as { id: number }).id).toBeGreaterThan( + before + ) +}) diff --git a/src/main/ai-vault-search/session-search-scan-roots.test.ts b/src/main/ai-vault-search/session-search-scan-roots.test.ts new file mode 100644 index 00000000000..51b7381c78b --- /dev/null +++ b/src/main/ai-vault-search/session-search-scan-roots.test.ts @@ -0,0 +1,58 @@ +import { expect, it } from 'vitest' +import { delimiter, join } from 'node:path' +import type { SessionFileDiscovery } from '../ai-vault/session-scanner-types' +import { sessionSearchRootListings } from './session-search-scan-roots' + +const STATE = '/tmp/ss-roots/openclaw-state' +const LEGACY = '/tmp/ss-roots/openclaw-legacy' + +function file(path: string): SessionFileDiscovery['files'][number] { + return { path, mtimeMs: 0, modifiedAt: new Date(0).toISOString() } +} + +it('splits a merged discovery into the real directories behind it', () => { + const current = join(STATE, 'agents') + const legacy = join(LEGACY, 'agents') + const listings = sessionSearchRootListings( + { openclawStateDir: STATE, openclawLegacyStateDir: LEGACY }, + [ + { + agent: 'openclaw', + // What discovery reports for an agent whose roots are alternates. + rootDir: [current, legacy].join(delimiter), + files: [ + file(join(current, 'a', 'sessions', 'one.jsonl')), + file(join(current, 'a', 'sessions', 'two.jsonl')), + file(join(legacy, 'b', 'sessions', 'three.jsonl')) + ] + } + ] + ) + + const byRoot = Object.fromEntries(listings.map((one) => [one.root, one.files])) + expect(byRoot[current]).toBe(2) + expect(byRoot[legacy]).toBe(1) + // The joined string is never reported as a directory. + expect(listings.every((one) => !one.root.includes(delimiter))).toBe(true) +}) + +it('attributes a file by path segment, not by string prefix', () => { + const agents = join(STATE, 'agents') + const legacy = join(LEGACY, 'agents') + const listings = sessionSearchRootListings( + { openclawStateDir: STATE, openclawLegacyStateDir: LEGACY }, + [ + { + agent: 'openclaw', + rootDir: [agents, legacy].join(delimiter), + // A sibling directory whose name merely starts with a root's name. It + // is under no root, so it belongs to none of them. + files: [file(join(`${agents}-old`, 'b', 'sessions', 'two.jsonl'))] + } + ] + ) + + const byRoot = Object.fromEntries(listings.map((one) => [one.root, one.files])) + expect(byRoot[agents]).toBe(0) + expect(byRoot[legacy]).toBe(0) +}) diff --git a/src/main/ai-vault-search/session-search-scan-roots.ts b/src/main/ai-vault-search/session-search-scan-roots.ts new file mode 100644 index 00000000000..8df3510199e --- /dev/null +++ b/src/main/ai-vault-search/session-search-scan-roots.ts @@ -0,0 +1,135 @@ +import type { AiVaultScanIssue } from '../../shared/ai-vault-types' +import { AI_VAULT_AGENT_SOURCES } from '../ai-vault/session-scanner-agent-sources' +import { normalizedWslHomeDirs } from '../ai-vault/session-scanner-roots' +import { sessionCandidatesFromDiscoveries } from '../ai-vault/session-scanner-candidates' +import { discoverAiVaultSessionSources } from '../ai-vault/session-scanner-source-discovery' +import type { + AiVaultScanOptions, + SessionFileCandidate, + SessionFileDiscovery +} from '../ai-vault/session-scanner-types' + +/** One real directory a scan walked, and what it listed there. */ +export type SessionSearchRootListing = { root: string; files: number } + +/** + * Where the indexer looks. The caller resolves these so the index enumerates + * exactly the trees the session list does; the indexer owns the bounds + * (`limit`, `limitPerAgent`, `unlimited`) and its own cancellation, so those + * are not the caller's to set. + */ +export type SessionSearchScanRoots = Omit< + AiVaultScanOptions, + 'signal' | 'limit' | 'unlimited' | 'limitPerAgent' | 'scopePaths' +> + +export type SessionSearchDiscovery = { + /** Newest first, Codex hardlink aliases collapsed, exactly as a list scan sees them. */ + candidates: SessionFileCandidate[] + discoveries: SessionFileDiscovery[] + issues: AiVaultScanIssue[] +} + +/** + * The discovery half of a list scan, without the parse. `limitPerAgent` is the + * sidebar's own recency rule (`SessionNewestFiles` keeps the newest N per root); + * passing Infinity is what makes a sweep whole. + */ +export async function discoverSessionSearchCandidates( + roots: SessionSearchScanRoots, + args: { limitPerAgent: number; signal?: AbortSignal } +): Promise { + const issues: AiVaultScanIssue[] = [] + const options: AiVaultScanOptions = { ...roots, signal: args.signal } + const discoveries = await discoverAiVaultSessionSources({ + options, + limitPerAgent: args.limitPerAgent, + issues + }) + const candidates = await sessionCandidatesFromDiscoveries(discoveries, options) + return { candidates, discoveries, issues } +} + +/** + * Containment on path segments, not on string prefix, and on both separators: + * discovery joins with the platform's, a configured root can arrive spelled + * with the other, and `/a/agents-old` is not inside `/a/agents`. + */ +export function isUnderScanRoot(path: string, root: string): boolean { + return root.length > 0 && (path.startsWith(`${root}/`) || path.startsWith(`${root}\\`)) +} + +/** + * The real directories behind a scan's discoveries, with their file counts. + * + * Why this exists: an agent whose roots are alternates for one install reports + * them as a single discovery whose `rootDir` is every path joined by the + * platform's path delimiter. That string is not a directory. Health probes + * readdir it and get ENOENT, a containment check never matches a file under it, + * and a scan issue recorded against a real root never equals it — so the fence + * meant to protect an unmounted tree is inert for exactly the agent most likely + * to have one. Splitting the joined string back apart would be worse: a + * directory may legally contain the delimiter. The constituent paths come from + * the same source table discovery read. + */ +export function sessionSearchRootListings( + roots: SessionSearchScanRoots, + discoveries: readonly SessionFileDiscovery[] +): SessionSearchRootListing[] { + const wslHomeDirs = normalizedWslHomeDirs(roots.wslHomeDirs) + const counts = new Map() + for (const discovery of discoveries) { + const constituents = constituentRoots(roots, wslHomeDirs, discovery) + for (const root of constituents) { + counts.set(root, counts.get(root) ?? 0) + } + for (const file of discovery.files) { + const owner = owningRoot(constituents, file.path) + if (owner !== null) { + counts.set(owner, (counts.get(owner) ?? 0) + 1) + } + } + } + return [...counts].map(([root, files]) => ({ root, files })) +} + +function constituentRoots( + roots: SessionSearchScanRoots, + wslHomeDirs: readonly string[], + discovery: SessionFileDiscovery +): string[] { + const declared = AI_VAULT_AGENT_SOURCES[discovery.agent]?.rootDirs(roots, wslHomeDirs) ?? [] + if (declared.includes(discovery.rootDir)) { + return [discovery.rootDir] + } + // Either a merged discovery, whose rootDir is the joined string, or a source + // that builds its own discoveries (OpenCode, Antigravity) and reports a real + // directory that this table does not list. + return declared.length > 0 ? declared : [discovery.rootDir] +} + +function owningRoot(constituents: readonly string[], path: string): string | null { + let owner: string | null = null + for (const root of constituents) { + if (isUnderScanRoot(path, root) && (owner === null || root.length > owner.length)) { + owner = root + } + } + return owner +} + +/** + * Roots that listed transcripts on the previous pass and list none on this one. + * + * The one bit of memory the retirement walk gets, and what it buys: a root that + * blinks empty for a single pass is unverifiable rather than proven gone, so a + * sync client swapping a directory out cannot retire a tree. It is deliberately + * not evidence that survives the process — see the invariant block in + * `session-search-deleted-sources.ts` for what that costs and why. + */ +export function sessionSearchEmptiedRoots( + previous: ReadonlySet, + current: ReadonlySet +): Set { + return new Set([...previous].filter((root) => !current.has(root))) +} diff --git a/src/main/ai-vault-search/session-search-schema.test.ts b/src/main/ai-vault-search/session-search-schema.test.ts new file mode 100644 index 00000000000..b23f36cde55 --- /dev/null +++ b/src/main/ai-vault-search/session-search-schema.test.ts @@ -0,0 +1,350 @@ +import type * as NodeFs from 'node:fs' +import { mkdtemp, readFile, stat, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + removeTree, + WINDOWS_RM_MAX_RETRIES, + WINDOWS_RM_RETRY_DELAY_MS +} from '../../shared/windows-transient-lock-removal' +import SyncDatabase from '../sqlite/sync-database' +import { + SESSION_SEARCH_SCHEMA_VERSION, + openSessionSearchDatabase, + removeSessionSearchDatabase +} from './session-search-schema' + +const recordedRmSync = vi.hoisted(() => vi.fn()) +vi.mock('node:fs', async () => { + const actual = await vi.importActual('node:fs') + return { + ...actual, + rmSync: (...args: Parameters) => { + recordedRmSync(...args) + return actual.rmSync(...args) + } + } +}) + +let roots: string[] = [] + +afterEach(async () => { + await Promise.all(roots.map((root) => removeTree(root))) + roots = [] +}) + +async function tempDatabasePath(): Promise { + const root = await mkdtemp(join(tmpdir(), 'orca-session-search-schema-')) + roots.push(root) + return join(root, 'index.sqlite') +} + +function schemaVersion(db: SyncDatabase): string | undefined { + return ( + db.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get() as + | { value: string } + | undefined + )?.value +} + +describe('openSessionSearchDatabase', () => { + it('keeps a current-version index and its rows', async () => { + const path = await tempDatabasePath() + const first = openSessionSearchDatabase(path) + first.prepare("INSERT INTO files(path,byte_offset,mtime_ms) VALUES ('a',1,1)").run() + first.close() + + const second = openSessionSearchDatabase(path) + expect(schemaVersion(second)).toBe(String(SESSION_SEARCH_SCHEMA_VERSION)) + expect(second.prepare('SELECT COUNT(*) AS c FROM files').get()).toEqual({ + c: 1 + }) + second.close() + }) + + it('carries one FTS table and throws away an index that carries two', async () => { + const path = await tempDatabasePath() + const fresh = openSessionSearchDatabase(path) + const tables = (): string[] => + ( + fresh + .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE '%_fts'") + .all() as { name: string }[] + ).map((row) => row.name) + expect(tables()).toEqual(['messages_fts']) + + // What an index written before this bump looks like: the second table, and + // rows in it. `CREATE TABLE IF NOT EXISTS` would leave both in place, so + // only the version bump makes that file go. + fresh.exec('CREATE VIRTUAL TABLE conversation_fts USING fts5(user_text, assistant_text)') + fresh.prepare("INSERT INTO files(path,byte_offset,mtime_ms) VALUES ('a',1,1)").run() + fresh.prepare("UPDATE meta SET value = '3' WHERE key = 'schema_version'").run() + fresh.close() + + const rebuilt = openSessionSearchDatabase(path) + expect(schemaVersion(rebuilt)).toBe(String(SESSION_SEARCH_SCHEMA_VERSION)) + expect( + rebuilt + .prepare("SELECT count(*) AS n FROM sqlite_master WHERE name = 'conversation_fts'") + .get() + ).toEqual({ n: 0 }) + expect(rebuilt.prepare('SELECT COUNT(*) AS c FROM files').get()).toEqual({ c: 0 }) + rebuilt.close() + }) + + it('replaces the file on a version mismatch instead of dropping tables in place', async () => { + const path = await tempDatabasePath() + const stale = openSessionSearchDatabase(path) + stale.prepare("INSERT INTO files(path,byte_offset,mtime_ms) VALUES ('a',1,1)").run() + stale + .prepare("UPDATE meta SET value = ? WHERE key = 'schema_version'") + .run(String(SESSION_SEARCH_SCHEMA_VERSION + 1)) + stale.close() + // Why: a stale sidecar must go with the main file, or SQLite replays it into the new one. + await writeFile(`${path}-wal`, 'stale wal bytes') + const before = await stat(path) + + const fresh = openSessionSearchDatabase(path) + expect(schemaVersion(fresh)).toBe(String(SESSION_SEARCH_SCHEMA_VERSION)) + expect(fresh.prepare('SELECT COUNT(*) AS c FROM files').get()).toEqual({ + c: 0 + }) + fresh.close() + // Why not inode: ext4 hands a freed inode straight back to the next create. + // The planted sidecar is gone (a fresh WAL is checkpointed away on close). + await expect(stat(`${path}-wal`)).rejects.toMatchObject({ code: 'ENOENT' }) + expect((await stat(path)).mtimeMs).toBeGreaterThanOrEqual(before.mtimeMs) + }) + + it('removes the database with every sidecar', async () => { + const path = await tempDatabasePath() + openSessionSearchDatabase(path).close() + await writeFile(`${path}-shm`, '') + removeSessionSearchDatabase(path) + for (const suffix of ['', '-wal', '-shm']) { + await expect(stat(`${path}${suffix}`)).rejects.toMatchObject({ + code: 'ENOENT' + }) + } + }) +}) + +it('rebuilds a file too corrupt to open instead of refusing forever', async () => { + const path = await tempDatabasePath() + const healthy = openSessionSearchDatabase(path) + healthy.prepare("INSERT INTO files(path,byte_offset,mtime_ms) VALUES ('a',1,1)").run() + healthy.close() + // A torn page, not a truncation: SQLite opens the header and fails on the read. + const bytes = await readFile(path) + bytes.fill(0x7f, 4096, Math.min(bytes.length, 12_288)) + await writeFile(path, bytes) + + const rebuilt = openSessionSearchDatabase(path) + try { + expect(schemaVersion(rebuilt)).toBe(String(SESSION_SEARCH_SCHEMA_VERSION)) + expect(rebuilt.prepare('SELECT COUNT(*) AS c FROM files').get()).toEqual({ + c: 0 + }) + } finally { + rebuilt.close() + } +}) + +it('rebuilds a file that is not a database at all', async () => { + const path = await tempDatabasePath() + await writeFile(path, 'not a SQLite database') + + const rebuilt = openSessionSearchDatabase(path) + try { + expect(schemaVersion(rebuilt)).toBe(String(SESSION_SEARCH_SCHEMA_VERSION)) + } finally { + rebuilt.close() + } +}) + +it('gives up rather than looping when a fresh file still cannot be opened', async () => { + const path = await tempDatabasePath() + await writeFile(path, 'not a SQLite database') + // Every open of this path fails, so the one permitted retry is exhausted. + const open = vi.spyOn(SyncDatabase.prototype, 'pragma').mockImplementation(() => { + throw Object.assign(new Error('database disk image is malformed'), { + code: 'SQLITE_CORRUPT' + }) + }) + try { + expect(() => openSessionSearchDatabase(path)).toThrow(/malformed/) + } finally { + open.mockRestore() + } +}) + +it('surfaces the unlink failure itself when a stale index cannot be removed', async () => { + const path = await tempDatabasePath() + const stale = openSessionSearchDatabase(path) + stale + .prepare("UPDATE meta SET value = ? WHERE key = 'schema_version'") + .run(String(SESSION_SEARCH_SCHEMA_VERSION + 1)) + stale.close() + recordedRmSync.mockReset() + recordedRmSync.mockImplementation(() => { + throw Object.assign(new Error('EPERM: operation not permitted, unlink'), { + code: 'EPERM' + }) + }) + try { + // The stale handle is closed before the unlink, so the failure path must not + // close it again: ERR_INVALID_STATE would bury the cause and would not be + // classified as worth a rebuild. + expect(() => openSessionSearchDatabase(path)).toThrow(/EPERM/) + expect(() => openSessionSearchDatabase(path)).not.toThrow(/not open/) + } finally { + recordedRmSync.mockReset() + } +}) + +it('creates the directory the index lives in', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-session-search-mkdir-')) + roots.push(root) + // The real layout: `/ai-vault-search/index.sqlite`, where nothing + // has made that folder yet. SQLite would fail with `unable to open database + // file`, which is correctly not treated as corruption, so it never retries. + const db = openSessionSearchDatabase(join(root, 'ai-vault-search', 'index.sqlite')) + try { + expect(schemaVersion(db)).toBe(String(SESSION_SEARCH_SCHEMA_VERSION)) + } finally { + db.close() + } +}) + +it('rebuilds a newer index rather than reading a schema it does not know', async () => { + const path = await tempDatabasePath() + const newer = openSessionSearchDatabase(path) + newer.prepare("INSERT INTO files(path,byte_offset,mtime_ms) VALUES ('a',1,1)").run() + newer + .prepare("UPDATE meta SET value = ? WHERE key = 'schema_version'") + .run(String(SESSION_SEARCH_SCHEMA_VERSION + 1)) + newer.close() + + const rebuilt = openSessionSearchDatabase(path) + try { + expect(schemaVersion(rebuilt)).toBe(String(SESSION_SEARCH_SCHEMA_VERSION)) + expect(rebuilt.prepare('SELECT COUNT(*) AS c FROM files').get()).toEqual({ + c: 0 + }) + } finally { + rebuilt.close() + } +}) + +it('rebuilds when meta exists but its version row is gone', async () => { + const path = await tempDatabasePath() + const damaged = openSessionSearchDatabase(path) + damaged.prepare("INSERT INTO files(path,byte_offset,mtime_ms) VALUES ('a',1,1)").run() + // A meta table with no version is a damaged index, never a fresh one: seeding + // the current version over it would keep whatever the old schema left behind. + damaged.prepare("DELETE FROM meta WHERE key = 'schema_version'").run() + damaged.close() + + const rebuilt = openSessionSearchDatabase(path) + try { + expect(schemaVersion(rebuilt)).toBe(String(SESSION_SEARCH_SCHEMA_VERSION)) + expect(rebuilt.prepare('SELECT COUNT(*) AS c FROM files').get()).toEqual({ + c: 0 + }) + } finally { + rebuilt.close() + } +}) + +it('opens with the pragmas the write path depends on', async () => { + const db = openSessionSearchDatabase(await tempDatabasePath()) + try { + // auto_vacuum=2 is INCREMENTAL, and only takes on an empty file: without it + // a purge cannot hand pages back in bounded steps. + expect(Number(db.pragma('auto_vacuum', { simple: true }))).toBe(2) + expect(String(db.pragma('journal_mode', { simple: true })).toLowerCase()).toBe('wal') + expect(Number(db.pragma('synchronous', { simple: true }))).toBe(1) + // A WAL with no size limit never hands its space back after a large write. + expect(Number(db.pragma('journal_size_limit', { simple: true }))).toBe(8388608) + // Zero here turns every contended write into an immediate SQLITE_BUSY. + expect(Number(db.pragma('busy_timeout', { simple: true }))).toBe(5000) + } finally { + db.close() + } +}) + +it("walks a session's rows through an index rather than scanning the table", async () => { + const db = openSessionSearchDatabase(await tempDatabasePath()) + try { + // The replace delete and the orphan drain both take this path, once per file. + const plan = ( + db + .prepare('EXPLAIN QUERY PLAN SELECT id FROM messages WHERE session_row_id = ? LIMIT ?') + .all(1, 1) as { detail: string }[] + ) + .map((row) => row.detail) + .join(' ') + expect(plan).toContain('messages_session') + } finally { + db.close() + } +}) + +it('keeps only the session indexes a retrieval query can seek', async () => { + const db = openSessionSearchDatabase(await tempDatabasePath()) + try { + const names = ( + db + .prepare("SELECT name FROM sqlite_master WHERE type='index' AND tbl_name='sessions'") + .all() as { name: string }[] + ) + .map((row) => row.name) + .sort() + // One per shape PR 4's retrieval seeks: the agent filter, the newest-first + // order and date window, and the folder-prefix range scan. Fork folding reads + // `content_hash` off rows it already holds, so that column is not indexed. + expect(names).toEqual(['sessions_agent', 'sessions_cwd_key', 'sessions_updated_at']) + } finally { + db.close() + } +}) + +it("retries a Windows lock that outlives rmSync's own retries", async () => { + const path = await tempDatabasePath() + openSessionSearchDatabase(path).close() + vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') + recordedRmSync.mockReset() + const locked = Object.assign(new Error('EPERM: operation not permitted'), { + code: 'EPERM' + }) + recordedRmSync.mockImplementationOnce(() => { + throw locked + }) + try { + expect(() => removeSessionSearchDatabase(path)).not.toThrow() + expect(recordedRmSync.mock.calls.length).toBe(5) + await expect(stat(path)).rejects.toMatchObject({ code: 'ENOENT' }) + } finally { + recordedRmSync.mockReset() + vi.restoreAllMocks() + } +}) + +it('gives Windows the shared retry options for a late handle release', async () => { + const path = await tempDatabasePath() + vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') + recordedRmSync.mockClear() + try { + removeSessionSearchDatabase(path) + expect(recordedRmSync).toHaveBeenCalled() + for (const [, options] of recordedRmSync.mock.calls) { + expect(options).toMatchObject({ + maxRetries: WINDOWS_RM_MAX_RETRIES, + retryDelay: WINDOWS_RM_RETRY_DELAY_MS + }) + } + } finally { + vi.restoreAllMocks() + } +}) diff --git a/src/main/ai-vault-search/session-search-schema.ts b/src/main/ai-vault-search/session-search-schema.ts new file mode 100644 index 00000000000..ca525c47c0e --- /dev/null +++ b/src/main/ai-vault-search/session-search-schema.ts @@ -0,0 +1,209 @@ +import { mkdirSync } from 'node:fs' +import { dirname } from 'node:path' +import SyncDatabase from '../sqlite/sync-database' +import { removeTreeSync } from '../../shared/windows-transient-lock-removal' + +// The index stores transcript content as written, with no redaction. A secret in +// a transcript is already plaintext under the user's home directory and is +// treated as compromised; this is a second copy of content the user already +// holds. What a snippet may carry once it leaves this machine is a transport +// policy, decided where the wire is. + +// Bump to drop and rebuild: the index is a cache over the transcripts, never a source. +export const SESSION_SEARCH_SCHEMA_VERSION = 5 + +// unicode61 keeps `_ . - /` inside tokens so paths and identifiers match exactly; +// the `identifiers` column carries the split form (see session-search-identifier-split). +// Why: `+` keeps `C++` a token of its own instead of the letter `c`; `#` is +// left out so `#123` still answers a search for `123`. +const TOKENIZER = `tokenize="unicode61 tokenchars '_.-/+'"` + +const SCHEMA_SQL = ` +CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY, value TEXT NOT NULL); +CREATE TABLE IF NOT EXISTS sessions( + -- AUTOINCREMENT, because this id names rows in the messages table for longer + -- than the row itself lives: retention cuts a session loose in one + -- transaction and reclaims its messages over many. A plain rowid is reissued + -- as max+1, so a session created inside that window would be handed a freed + -- id and adopt whatever of the purged conversation the drain had not reached, + -- behind a live session no later purge visits. + id INTEGER PRIMARY KEY AUTOINCREMENT, + agent TEXT NOT NULL, + session_id TEXT NOT NULL, + -- The transcript this session was decoded from. Not unique: OpenCode's SQLite + -- sessions all report the store's own path here, while files.path holds the + -- synthetic db#sessionId candidate that really is one per session. + file_path TEXT NOT NULL, + codex_home TEXT, + title TEXT NOT NULL, + cwd TEXT, + cwd_key TEXT, + branch TEXT, + created_at TEXT, + updated_at TEXT, + message_count INTEGER NOT NULL DEFAULT 0, + resume_command TEXT NOT NULL, + -- Chained digest of the first N messages; forks of one conversation share it. + content_hash TEXT, + content_hash_count INTEGER NOT NULL DEFAULT 0 +); +CREATE INDEX IF NOT EXISTS sessions_agent ON sessions(agent); +CREATE INDEX IF NOT EXISTS sessions_updated_at ON sessions(updated_at); +CREATE INDEX IF NOT EXISTS sessions_cwd_key ON sessions(cwd_key); +CREATE TABLE IF NOT EXISTS files( + path TEXT PRIMARY KEY, + dev INTEGER, + ino INTEGER, + byte_offset INTEGER NOT NULL, + mtime_ms REAL NOT NULL, + size_bytes INTEGER, + session_row_id INTEGER, + -- What this row still owes a reader, so that nothing has to be remembered + -- between passes. 'current': the rows match the file at the stat recorded + -- here. 'due': the index is behind on content it cannot reach by appending, + -- so the next pass reads the file whole. 'failed': the last read did not + -- commit, and the two columns below are what stop it being retried for ever. + state TEXT NOT NULL DEFAULT 'current', + fail_count INTEGER NOT NULL DEFAULT 0, + -- The mtime the failures were observed at. A file that fails at one stat is + -- left alone once it has failed enough times, and only a change to this stat + -- can mean the file itself changed, so it is the whole retry policy. + failed_mtime_ms REAL +); +-- Retention walks the expiring end of this column; without it that is a full scan and a sort. +CREATE INDEX IF NOT EXISTS files_mtime ON files(mtime_ms); +CREATE TABLE IF NOT EXISTS messages( + id INTEGER PRIMARY KEY, + session_row_id INTEGER NOT NULL, + role TEXT NOT NULL, + ts TEXT +); +-- Both the replace delete and the orphan drain walk a session's rows through this. +CREATE INDEX IF NOT EXISTS messages_session ON messages(session_row_id); +-- One FTS table, not two. A conversation-scoped search is a column filter on +-- this one — 'MATCH {user_text assistant_text}: q' with bm25 weights that zero +-- the other two — and PR 4 measured that at 1.16-1.36x the p95 of a dedicated +-- second table on a 105 MB corpus, under the 2x bar the decision was set at. +CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5( + user_text, assistant_text, tool_text, identifiers, ${TOKENIZER}, detail=full +); +` + +/** + * Opens the index, rebuilding it whenever what is on disk cannot be trusted: + * a different schema version, a version SQLite cannot report, or a file torn + * badly enough that opening or recovery fails. The index is a cache over the + * transcripts, so throwing away a bad one costs a re-scan and nothing else; + * refusing to open would strand the feature until a human deleted the file. + */ +export function openSessionSearchDatabase(path: string): SyncDatabase { + // SQLite will not create the directory, and its failure is `unable to open + // database file`, which is correctly not corruption — so without this the + // feature strands on a profile that has never held an index. + if (path !== ':memory:') { + mkdirSync(dirname(path), { recursive: true }) + } + try { + return openExisting(path) + } catch (error) { + if (!isUnusableDatabaseError(error)) { + throw error + } + // One retry only: a second failure on a file we just created is not corruption. + removeSessionSearchDatabase(path) + return openExisting(path) + } +} + +function openExisting(path: string): SyncDatabase { + // Nulled while no handle is open, because closing an already-closed handle + // throws ERR_INVALID_STATE, which would replace whatever really failed — + // an unlink refused by a virus scanner or a second Orca holding the file — + // with an error nothing classifies as worth rebuilding for. + let db: SyncDatabase | null = openWithPragmas(path) + try { + if (isStaleSchema(db)) { + // Why: DROP TABLE on a multi-GB FTS index takes minutes and runs inside the + // scanner service's init, past its ready timeout; unlinking is instant. + db.close() + db = null + removeSessionSearchDatabase(path) + db = openWithPragmas(path) + } + db.exec(SCHEMA_SQL) + db.prepare('INSERT OR REPLACE INTO meta(key, value) VALUES (?, ?)').run( + 'schema_version', + String(SESSION_SEARCH_SCHEMA_VERSION) + ) + return db + } catch (error) { + db?.close() + throw error + } +} + +// SQLite reports a torn file at the first statement that has to read a page, so +// this has to match on the message as well as the code. +const UNUSABLE_DATABASE = + /SQLITE_CORRUPT|SQLITE_NOTADB|file is not a database|database disk image is malformed/i + +function isUnusableDatabaseError(error: unknown): boolean { + if (!(error instanceof Error)) { + return false + } + const code = (error as { code?: unknown }).code + return ( + (typeof code === 'string' && UNUSABLE_DATABASE.test(code)) || + UNUSABLE_DATABASE.test(error.message) + ) +} + +function openWithPragmas(path: string): SyncDatabase { + const db = new SyncDatabase(path) + try { + // Why: only takes effect on an empty file; it is what lets a purge hand pages + // back in bounded steps instead of a full VACUUM. Set before any table exists. + db.pragma('auto_vacuum = INCREMENTAL') + // The whole consistency model: a file's rows and its cursor land in one + // transaction, and a reader on another handle sees the last committed state + // of the index rather than a session half way through being rewritten. + db.pragma('journal_mode = WAL') + db.pragma('synchronous = NORMAL') + db.pragma('journal_size_limit = 8388608') + db.pragma('busy_timeout = 5000') + return db + } catch (error) { + db?.close() + throw error + } +} + +export function removeSessionSearchDatabase(path: string): void { + if (path === ':memory:') { + return + } + for (const suffix of ['', '-wal', '-shm', '-journal']) { + removeTreeSync(`${path}${suffix}`) + } +} + +/** + * Whether what is on disk has to be thrown away. No `meta` table at all is a + * file with nothing in it to throw away, and removing it would make the first + * open of every new profile a create-remove-create. A meta table whose version + * row is missing or unparseable is a damaged index rather than a new one: + * seeding the current version over it would keep whatever rows the old schema + * left. + */ +function isStaleSchema(db: SyncDatabase): boolean { + const table = db + .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'meta'") + .get() + if (!table) { + return false + } + const row = db.prepare("SELECT value FROM meta WHERE key = 'schema_version'").get() as + | { value: string } + | undefined + return (row ? Number(row.value) : Number.NaN) !== SESSION_SEARCH_SCHEMA_VERSION +} diff --git a/src/main/ai-vault-search/session-search-sidebar-parity.test.ts b/src/main/ai-vault-search/session-search-sidebar-parity.test.ts new file mode 100644 index 00000000000..988ae248673 --- /dev/null +++ b/src/main/ai-vault-search/session-search-sidebar-parity.test.ts @@ -0,0 +1,146 @@ +import { afterEach, expect, it } from 'vitest' +import type { AiVaultSession } from '../../shared/ai-vault-types' +import { filterAiVaultSessions } from '../../shared/ai-vault-session-filters' +import { + addSyntheticSession, + openSessionSearchHarness, + type SessionSearchHarness +} from './session-search-engine-test-fixture' + +// `repo:` and `path:` have to mean one thing. The sessions panel and the index +// answer from different stores by different mechanisms, so the only way to keep +// them equal is for both to run the same predicate; this asserts they do, over +// the shapes where a second SQL spelling went wrong. + +let harness: SessionSearchHarness | null = null + +afterEach(async () => { + await harness?.close() + harness = null +}) + +type Fixture = { id: number; cwd: string; filePath: string; text: string } + +const SESSIONS: Fixture[] = [ + { + id: 1, + cwd: '/Users/Ada/orca/session-search', + filePath: '/Users/Ada/.claude/projects/a/one.jsonl', + text: 'harbor pilot manifest' + }, + { + id: 2, + cwd: '/Users/ada/work/café', + filePath: '/Users/ada/.codex/sessions/two.jsonl', + text: 'harbor dock crane' + }, + { + id: 3, + cwd: '/srv/other/service', + filePath: '/srv/.claude/projects/b/three.jsonl', + text: 'harbor manifest beta' + }, + { + id: 4, + cwd: 'C:\\Work\\Orca\\App', + filePath: 'C:\\Users\\Ada\\.claude\\four.jsonl', + text: 'harbor windows lane' + }, + // A space in the path, which is what a quoted operator value exists for. + { + id: 5, + cwd: '/Users/ada/My Project', + filePath: '/Users/ada/.claude/projects/c/five.jsonl', + text: 'harbor quay ledger' + } +] + +// Each of these matched in the panel and missed in the index while the engine +// tried to say `repo:` / `path:` in SQL. +const QUERIES = [ + 'harbor path:jsonl', + 'harbor repo:orca/session-search', + 'harbor path:CAFÉ', + 'harbor path:/Users/Ada/orca', + 'harbor repo:app', + 'harbor repo:Orca/App', + 'harbor path:.codex', + 'harbor path:/srv repo:other/service', + 'harbor repo:session-search path:jsonl', + 'harbor path:"/Users/ada/work"', + 'harbor repo:nothing-here', + 'harbor path:one.jsonl path:two.jsonl', + 'harbor path:"/Users/ada/My Project"', + 'harbor repo:"ada/My Project"', + 'harbor' +] + +function asSession(fixture: Fixture): AiVaultSession { + const at = '2026-09-01T00:00:00.000Z' + return { + id: String(fixture.id), + executionHostId: 'local', + agent: 'claude', + sessionId: String(fixture.id), + title: 'fixture', + cwd: fixture.cwd, + branch: null, + model: null, + filePath: fixture.filePath, + codexHome: null, + createdAt: at, + updatedAt: at, + modifiedAt: at, + messageCount: 1, + totalTokens: 0, + previewMessages: [{ role: 'user', text: fixture.text }], + queuedMessageCount: 0, + subagentTranscriptCount: 0, + resumeCommand: '', + subagent: null + } as AiVaultSession +} + +/** + * The panel's own answer. The whole query, not the operators cut out of it: a + * whitespace split would cut a quoted value in half, and every fixture's preview + * holds `harbor`, so the free text the panel also applies selects all of them. + */ +function sidebarIds(query: string): string[] { + return filterAiVaultSessions(SESSIONS.map(asSession), { + query, + agents: ['claude'], + scope: 'all', + sort: 'updated', + activeWorktreePaths: [], + hideEmptySessions: false + }) + .map((session) => session.sessionId) + .sort() +} + +it.each(QUERIES)('answers %s the way the sessions panel does', async (query) => { + harness = await openSessionSearchHarness('ss-sidebar-parity') + for (const fixture of SESSIONS) { + addSyntheticSession(harness.db, { + id: fixture.id, + cwd: fixture.cwd, + text: fixture.text, + filePath: fixture.filePath, + sessionFilePath: fixture.filePath + }) + } + const engineIds = harness.engine + .search({ query, limit: 100 }) + .hits.map((hit) => hit.sessionId) + .sort() + expect(engineIds).toEqual(sidebarIds(query)) +}) + +it('is not vacuous: these queries do select, and reject, real sessions', () => { + // A parity suite where every query matched everything, or nothing, would pass + // against any predicate at all. + const answers = QUERIES.map((query) => sidebarIds(query).length) + expect(answers.some((count) => count > 0 && count < SESSIONS.length)).toBe(true) + expect(answers.some((count) => count === 0)).toBe(true) +}) diff --git a/src/main/ai-vault-search/session-search-snippet-marks.test.ts b/src/main/ai-vault-search/session-search-snippet-marks.test.ts new file mode 100644 index 00000000000..d4237ce8b6f --- /dev/null +++ b/src/main/ai-vault-search/session-search-snippet-marks.test.ts @@ -0,0 +1,144 @@ +import { afterEach, expect, it } from 'vitest' +import { + SESSION_SEARCH_SNIPPET_MARK_CLOSE, + SESSION_SEARCH_SNIPPET_MARK_OPEN +} from './session-search-engine-types' +import { + addSyntheticSession, + openSessionSearchHarness, + type SessionSearchHarness +} from './session-search-engine-test-fixture' + +// A snippet has to name which of a row's four columns matched, and the marks +// FTS5 wraps a match in are the only signal. Searching the marked text for the +// public `[[` reads a transcript's own brackets as a highlight — and transcripts +// are full of them, because a bash `[[ -f x ]]` and numpy's `[[1, 2]]` are +// exactly the sort of thing an agent session holds. Whether a column matched is +// the difference between two renderings of the same text instead. + +let harness: SessionSearchHarness | null = null + +afterEach(async () => { + await harness?.close() + harness = null +}) + +const BASH = 'run this: if [[ -f /home/me/.aws/credentials ]]; then cat it; fi' +const TOOL = 'zebrafish appears only in the tool output here' + +it('shows the column that matched, not the one that happens to contain brackets', async () => { + harness = await openSessionSearchHarness('ss-snippet-marks') + // Session 1's match is in tool output while its user turn holds a bash test + // expression; session 2 is the same match with no brackets anywhere. + addSyntheticSession(harness.db, { id: 1, text: BASH, toolText: TOOL }) + addSyntheticSession(harness.db, { id: 2, text: 'run this script please', toolText: TOOL }) + + const hits = harness.engine.search({ query: 'zebrafish' }).hits + expect(hits).toHaveLength(2) + for (const hit of hits) { + expect(hit.evidence?.snippet).toContain( + `${SESSION_SEARCH_SNIPPET_MARK_OPEN}zebrafish${SESSION_SEARCH_SNIPPET_MARK_CLOSE}` + ) + expect(hit.evidence?.snippet).not.toContain('credentials') + } +}) + +it('falls back to any column for an identifier-only match, brackets or not', async () => { + // `zebra` reaches this row only through the identifier shadow column, which is + // what column -1 exists for. The user turn holds numpy output, so a bracket + // scan would have stopped at it and shown a column with no match in it. + harness = await openSessionSearchHarness('ss-snippet-marks-fallback') + addSyntheticSession(harness.db, { + id: 1, + text: 'numpy printed [[1, 2], [3, 4]] before the call', + toolText: 'zebra-fish-count = 4' + }) + + const [hit] = harness.engine.search({ query: 'zebra' }).hits + expect(hit?.evidence?.snippet).toContain( + `${SESSION_SEARCH_SNIPPET_MARK_OPEN}zebra${SESSION_SEARCH_SNIPPET_MARK_CLOSE}` + ) + expect(hit?.evidence?.snippet).not.toContain('numpy') +}) + +it('leaves a transcript’s own brackets in the text it shows', async () => { + // The marks are rewritten from private-use code points at the very end, so a + // row that both matches and contains `[[` keeps its own characters. + harness = await openSessionSearchHarness('ss-snippet-marks-literal') + addSyntheticSession(harness.db, { id: 1, text: `zebrafish ${BASH}` }) + + const [hit] = harness.engine.search({ query: 'zebrafish' }).hits + expect(hit?.evidence?.snippet).toContain( + `${SESSION_SEARCH_SNIPPET_MARK_OPEN}zebrafish${SESSION_SEARCH_SNIPPET_MARK_CLOSE}` + ) + expect(hit?.evidence?.snippet).toContain('[[ -f') +}) + +it('picks by comparison, so a private-use code point in content cannot pose as a mark', async () => { + // The marks are private-use code points, and a transcript may hold one: + // agent output carries Nerd Font glyphs, which live in the same block. So the + // column is chosen by comparing a marked rendering against an unmarked one, + // not by looking for a mark in the text. + harness = await openSessionSearchHarness('ss-snippet-marks-private-use') + addSyntheticSession(harness.db, { + id: 1, + text: 'the \uE000 glyph a font printed here', + toolText: TOOL + }) + + const [hit] = harness.engine.search({ query: 'zebrafish' }).hits + expect(hit?.evidence?.snippet).toContain('zebrafish') + expect(hit?.evidence?.snippet).not.toContain('glyph') +}) + +it('truncates on the last real mark, not on a bracket the transcript wrote', async () => { + // Over the character ceiling the snippet is cut, and it must not cut between + // an open mark and its close. Finding that open mark by searching for `[[` + // stops at the transcript's own bracket instead and throws away everything + // after it. + harness = await openSessionSearchHarness('ss-snippet-marks-truncation') + const long = (letter: string): string => + Array.from({ length: 5 }, () => `${letter.repeat(55)}/tail`).join(' ') + addSyntheticSession(harness.db, { + id: 1, + text: `zebrafish ${long('p')} [[ ${long('q')}` + }) + + const snippet = harness.engine.search({ query: 'zebrafish' }).hits[0]?.evidence?.snippet ?? '' + expect(snippet).toContain('[[zebrafish]]') + // The cut is the character ceiling, so the text after the transcript's own + // bracket survives up to it. + expect(snippet).toContain('qqqqq') +}) + +it('marks only what FTS5 marked, so a glyph in the text stays a glyph', async () => { + // The marked and plain renderings are compared character by character, so a + // private-use code point the transcript wrote has a counterpart in both and + // is text; replacing every one of them would show it as a highlight. + harness = await openSessionSearchHarness('ss-snippet-marks-literal-private-use') + addSyntheticSession(harness.db, { id: 1, text: 'a \uE000 glyph then zebrafish and \uE001 after' }) + + const snippet = harness.engine.search({ query: 'zebrafish' }).hits[0]?.evidence?.snippet ?? '' + expect(snippet).toContain( + `${SESSION_SEARCH_SNIPPET_MARK_OPEN}zebrafish${SESSION_SEARCH_SNIPPET_MARK_CLOSE}` + ) + expect(snippet).toContain('a \uE000 glyph') + expect(snippet).toContain('\uE001 after') + // One highlight, and only one: the literals are not a second pair. + expect(snippet.split(SESSION_SEARCH_SNIPPET_MARK_OPEN)).toHaveLength(2) +}) + +it('does not cut a snippet at a private-use code point the transcript wrote', async () => { + // The balance check looks for the last open mark, and a content glyph is not + // one; treating it as one throws away every character after it. + harness = await openSessionSearchHarness('ss-snippet-marks-literal-truncation') + const long = (letter: string): string => + Array.from({ length: 5 }, () => `${letter.repeat(55)}/tail`).join(' ') + addSyntheticSession(harness.db, { id: 1, text: `zebrafish ${long('p')} \uE000 ${long('q')}` }) + + const snippet = harness.engine.search({ query: 'zebrafish' }).hits[0]?.evidence?.snippet ?? '' + expect(snippet).toContain( + `${SESSION_SEARCH_SNIPPET_MARK_OPEN}zebrafish${SESSION_SEARCH_SNIPPET_MARK_CLOSE}` + ) + expect(snippet).toContain('qqqqq') +}) diff --git a/src/main/ai-vault-search/session-search-snippet.ts b/src/main/ai-vault-search/session-search-snippet.ts new file mode 100644 index 00000000000..1204cdd10a8 --- /dev/null +++ b/src/main/ai-vault-search/session-search-snippet.ts @@ -0,0 +1,171 @@ +import type SyncDatabase from '../sqlite/sync-database' +import { + SESSION_SEARCH_SNIPPET_MARK_CLOSE, + SESSION_SEARCH_SNIPPET_MARK_OPEN +} from './session-search-engine-types' +import { + orExpression, + scopedExpression, + type SessionSearchQueryPlan +} from './session-search-query-planner' +import type { SessionSearchScope } from './session-search-engine-types' + +// What FTS5 wraps a match in before this module rewrites it to the public +// marks. Private-use code points, and not `[[`, because two different jobs here +// have to tell a mark from content: choosing the column to show, and refusing +// to cut a snippet between an open mark and its close. Transcripts contain +// `[[` — a bash `[[ -f x ]]`, numpy's `[[1, 2]]` — and a mark the content can +// forge makes both of those decisions wrong on real text. +const MARK_OPEN = '\uE000' +const MARK_CLOSE = '\uE001' + +const SNIPPET_TOKENS = 12 +// Why a ceiling on top of the token count: a transcript chunk can be 8000 +// characters with no separator in it, which FTS5 reports as one token, so +// "twelve tokens" is not by itself a bound on what a hit carries. +const SNIPPET_MAX_CHARS = 512 + +export type SessionSearchSnippet = { + text: string + truncated: boolean +} + +export const EMPTY_SNIPPET: SessionSearchSnippet = { text: '', truncated: false } + +/** + * The window of one message that shows why it matched. + * + * The expression is the plan's OR form rather than the route's, so a hit found + * through typo repair is marked with the repaired terms it was actually + * retrieved by, and a phrase hit still marks each of its words. + */ +export function sessionSearchSnippet( + db: SyncDatabase, + scope: SessionSearchScope, + rowid: number, + plan: SessionSearchQueryPlan +): SessionSearchSnippet { + // Why: the identifier shadow column is word soup; a hit that also matches in a + // prose column should be shown from there. Column -1 (any column) is the + // fallback for rows that only matched through the shadow column. + // + // The same four for every scope, because the scope is already in the + // expression below. A conversation snippet cannot come out of `tool_text` for + // the reason the search could not: the row has to match + // `{user_text assistant_text}: …` before any of these columns is read, and a + // row that matches under that filter carries its mark in column 0 or 1. A + // second list here would be a guard with nothing left to guard, and the two + // would mask each other's mistakes. + const columns = [0, 1, 2, -1] + // Each column twice: once marked, once with empty marks. Whether a column + // matched is then the difference between two renderings of the same text, + // which content cannot forge — searching the marked one for a mark reads a + // transcript's own `[[` as a highlight and shows a column that matched + // nothing. + const select = columns + .flatMap((column, index) => [ + `snippet(messages_fts, ${column}, '${MARK_OPEN}', '${MARK_CLOSE}', '…', ${SNIPPET_TOKENS}) AS c${index}`, + `snippet(messages_fts, ${column}, '', '', '…', ${SNIPPET_TOKENS}) AS p${index}` + ]) + .join(', ') + try { + // Why the subselect: a bound `rowid = ?` or `rowid IN (?)` next to MATCH is + // silently ignored by the FTS5 planner, which then returns the first match + // in the table. Why the join to `sessions`: retrieval proved this rowid + // belonged to a live session, but a purge can commit between that statement + // and this one, and a message row outlives its session row until the drain + // reaches it. INNER, never LEFT — this is the last read before content is + // returned to a caller. + const row = db + .prepare( + `SELECT ${select} FROM messages_fts + JOIN messages m ON m.id = messages_fts.rowid + JOIN sessions s ON s.id = m.session_row_id + WHERE messages_fts MATCH ? AND messages_fts.rowid IN (SELECT ?)` + ) + .get(scopedExpression(scope, orExpression(plan.terms)), rowid) as + | Record + | undefined + if (!row) { + return EMPTY_SNIPPET + } + // A snippet with nothing highlighted tells the user nothing; omit it. + const index = columns.findIndex( + (_column, at) => row[`c${at}`] !== undefined && row[`c${at}`] !== row[`p${at}`] + ) + if (index === -1) { + return EMPTY_SNIPPET + } + const pieces = splitMarks(row[`c${index}`]!, row[`p${index}`]!) + return pieces === null ? EMPTY_SNIPPET : renderSnippet(pieces) + } catch { + return EMPTY_SNIPPET + } +} + +/** One run of the snippet's own text, or one mark FTS5 put between two runs. */ +type SnippetPiece = { kind: 'text'; value: string } | { kind: 'mark'; value: string } + +/** + * The marked rendering as its text and the marks FTS5 inserted into it. + * + * A mark is a private-use character the marked rendering has where the plain one + * has something else, so a Nerd Font glyph the transcript itself wrote stays + * text — replacing every private-use character would hand the renderer a + * highlight the content forged. Null when the two renderings differ for any + * other reason, which is not a difference this can attribute. + */ +function splitMarks(marked: string, plain: string): SnippetPiece[] | null { + const pieces: SnippetPiece[] = [] + const rest = [...plain] + let at = 0 + let run = '' + for (const point of marked) { + if (point === rest[at]) { + run += point + at++ + continue + } + if (point !== MARK_OPEN && point !== MARK_CLOSE) { + return null + } + pieces.push({ kind: 'text', value: run }, { kind: 'mark', value: point }) + run = '' + } + if (at !== rest.length) { + return null + } + pieces.push({ kind: 'text', value: run }) + return pieces +} + +/** + * The public marks, and the character ceiling. + * + * Cut on a code-point boundary, and never between a mark and its close: an open + * mark with no close hands the renderer something it can never close. The + * ceiling counts the snippet's own characters, so the marks cost the caller + * nothing and a transcript's own private-use character costs it one. + */ +function renderSnippet(pieces: SnippetPiece[]): SessionSearchSnippet { + let text = '' + let shown = 0 + let openedAt: number | null = null + for (const piece of pieces) { + if (piece.kind === 'mark') { + const open = piece.value === MARK_OPEN + openedAt = open ? text.length : null + text += open ? SESSION_SEARCH_SNIPPET_MARK_OPEN : SESSION_SEARCH_SNIPPET_MARK_CLOSE + continue + } + const points = [...piece.value] + if (shown + points.length <= SNIPPET_MAX_CHARS) { + shown += points.length + text += piece.value + continue + } + text += points.slice(0, SNIPPET_MAX_CHARS - shown).join('') + return { text: openedAt === null ? text : text.slice(0, openedAt), truncated: true } + } + return { text, truncated: false } +} diff --git a/src/main/ai-vault-search/session-search-source-presence.ts b/src/main/ai-vault-search/session-search-source-presence.ts new file mode 100644 index 00000000000..cc7155fccc8 --- /dev/null +++ b/src/main/ai-vault-search/session-search-source-presence.ts @@ -0,0 +1,40 @@ +import type SyncDatabase from '../sqlite/sync-database' +import type { SessionSearchSourcePresence } from './session-search-engine-types' + +/** + * Where each session's source stands, read from the index's own `files` table. + * + * Why not a stat: a search page of 20 hits would be 20 filesystem round trips + * on the query path, and on an SSH or WSL host each one can block for as long + * as the connection takes to answer — the reviewer's F11. The index already + * records what discovery last proved about every file it read, so the query + * path reads that instead of asking the disk again. + * + * The vocabulary is deliberately short of `missing`. A row here means the index + * holds a live file record for the session, which is `present`. No row means + * this read cannot tell whether the source is gone or merely unrecorded, and + * loss of contact is never evidence of absence + * (docs/reference/ssh-execution-boundary.md), so it is `unverifiable`. Proving + * a deletion is the indexer's job and it retires the session's rows outright. + */ +export function sessionSourcePresence( + db: SyncDatabase, + sessionRowIds: readonly number[] +): Map { + const presence = new Map( + sessionRowIds.map((id) => [id, 'unverifiable' as const]) + ) + if (sessionRowIds.length === 0) { + return presence + } + const rows = db + .prepare( + `SELECT DISTINCT session_row_id FROM files + WHERE session_row_id IN (${sessionRowIds.map(() => '?').join(',')})` + ) + .all(...sessionRowIds) as { session_row_id: number }[] + for (const row of rows) { + presence.set(row.session_row_id, 'present') + } + return presence +} diff --git a/src/main/ai-vault-search/session-search-store-is-memory.test.ts b/src/main/ai-vault-search/session-search-store-is-memory.test.ts new file mode 100644 index 00000000000..2e90a75862f --- /dev/null +++ b/src/main/ai-vault-search/session-search-store-is-memory.test.ts @@ -0,0 +1,265 @@ +import { chmod, rm, utimes } from 'node:fs/promises' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import { resetSessionParseCacheForTests } from '../ai-vault/session-scanner-parse-cache' +import { resetTranscriptConsumersForTests } from '../ai-vault/session-transcript-consumers' +import type SyncDatabase from '../sqlite/sync-database' +import { SessionSearchIndexer } from './session-search-indexer' +import { + FakeSessionSearchClock, + openSessionSearchIndexerHarness, + writeClaudeTranscript, + type SessionSearchIndexerHarness +} from './session-search-indexer-test-fixture' + +/* + * S1-S5: the store is the only memory. + * + * Every question the indexer answers between passes -- what is owed a read, + * what has failed and how often, what it holds and therefore what may have been + * deleted, what to report -- is a row in the `files` table. These tests check + * that from outside the object: a second connection, hand-written SQL, and the + * clock. Two things outlive a pass and are not rows, and both are named here: + * the timer, and one bit per root for the retirement walk's grace. + */ + +const INTERVAL_MS = 20_000 +const CAN_DENY_READ = process.platform !== 'win32' && process.getuid?.() !== 0 +const FIRST = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' +const SECOND = 'bbbbbbbb-cccc-4ddd-8eee-ffffffffffff' +const THIRD = 'cccccccc-dddd-4eee-8fff-000000000000' + +let harness: SessionSearchIndexerHarness +let clock: FakeSessionSearchClock +let indexer: SessionSearchIndexer | null +let errors: unknown[] + +beforeEach(async () => { + resetSessionParseCacheForTests() + resetTranscriptConsumersForTests() + errors = [] + clock = new FakeSessionSearchClock() + harness = await openSessionSearchIndexerHarness('ss-memory') + indexer = null +}) + +afterEach(async () => { + indexer?.close() + resetTranscriptConsumersForTests() + resetSessionParseCacheForTests() + await harness.cleanup() +}) + +function newIndexer( + overrides: Partial[0]> = {} +): SessionSearchIndexer { + indexer = new SessionSearchIndexer({ + databasePath: harness.databasePath, + roots: harness.roots, + historyDays: null, + clock, + reconcileIntervalMs: INTERVAL_MS, + onError: (error) => errors.push(error), + ...overrides + }) + return indexer +} + +function transcriptPath(name: string): string { + return join(harness.claudeProjectDir, `${name}.jsonl`) +} + +async function nextCycle(): Promise { + clock.advance(INTERVAL_MS) + await indexer?.settled() +} + +/** The whole `files` table as a second connection sees it, ordered for comparison. */ +function fileTable(): unknown[] { + return harness.read((db: SyncDatabase) => + db + .prepare( + `SELECT path, dev, ino, byte_offset, mtime_ms, size_bytes, session_row_id, + state, fail_count, failed_mtime_ms + FROM files ORDER BY path` + ) + .all() + ) +} + +// S1. The status is a query. A counter kept beside the rows is what needs a +// rule about when to reset, and every such rule this feature grew was wrong. +it('S1: reports exactly what a hand-written query over the rows reports', async () => { + await writeClaudeTranscript(transcriptPath(FIRST), ['one'], FIRST) + await writeClaudeTranscript(transcriptPath(SECOND), ['two'], SECOND) + await newIndexer().start() + + const bySql = (): Record => + Object.fromEntries( + ( + harness.read((db: SyncDatabase) => + db.prepare('SELECT state, count(*) AS n FROM files GROUP BY state').all() + ) as { state: string; n: number }[] + ).map((row) => [row.state, Number(row.n)]) + ) + + const reported = indexer?.status() + const counted = bySql() + expect(reported?.filesIndexed).toBe(counted.current ?? 0) + expect(reported?.filesDue).toBe(counted.due ?? 0) + expect(reported?.filesFailed).toBe(counted.failed ?? 0) + expect(reported?.filesIndexed).toBe(2) + + // And it stays a query: delete a row behind the indexer's back and the very + // next call reports the table, not a number it remembered. + harness.write((db: SyncDatabase) => + db.prepare('DELETE FROM files WHERE path = ?').run(transcriptPath(FIRST)) + ) + expect(indexer?.status().filesIndexed).toBe(1) +}) + +// S2. A deletion is proven by comparing the rows against what discovery +// returned, so the moment it happened does not matter. Every boundary a pass +// has is a moment a file can go. +it('S2: retires a file deleted right after the opening sweep', async () => { + await writeClaudeTranscript(transcriptPath(FIRST), ['going'], FIRST) + await writeClaudeTranscript(transcriptPath(SECOND), ['staying'], SECOND) + await newIndexer().start() + + await rm(transcriptPath(FIRST)) + await nextCycle() + + expect(fileTable()).toHaveLength(1) +}) + +it('S2: retires a file deleted right after a cycle', async () => { + await writeClaudeTranscript(transcriptPath(FIRST), ['going'], FIRST) + await writeClaudeTranscript(transcriptPath(SECOND), ['staying'], SECOND) + await newIndexer().start() + await nextCycle() + + await rm(transcriptPath(FIRST)) + await nextCycle() + + expect(fileTable()).toHaveLength(1) +}) + +it('S2: retires a file deleted right after a periodic sweep', async () => { + await writeClaudeTranscript(transcriptPath(FIRST), ['going'], FIRST) + await writeClaudeTranscript(transcriptPath(SECOND), ['staying'], SECOND) + await newIndexer({ fullSweepEveryCycles: 2 }).start() + await nextCycle() + await nextCycle() + // The third pass is the periodic sweep; the file goes the moment it ends. + await nextCycle() + + await rm(transcriptPath(FIRST)) + await nextCycle() + + expect(fileTable()).toHaveLength(1) +}) + +it('S2: retires a file deleted while a pass was out of time', async () => { + await writeClaudeTranscript(transcriptPath(FIRST), ['going'], FIRST) + await writeClaudeTranscript(transcriptPath(SECOND), ['staying'], SECOND) + await writeClaudeTranscript(transcriptPath(THIRD), ['also staying'], THIRD) + // One transcript a pass: the opening sweep leaves two of the three unread. + clock.costPerNowMs = 1_000 + await newIndexer({ passDeadlineMs: 1_000 }).start() + expect(fileTable()).toHaveLength(1) + + await rm(transcriptPath(FIRST)) + await nextCycle() + await nextCycle() + + // Read what it could, and proved the deletion in the same pass it was still + // catching up in: retirement is not what the deadline bounds. + expect((fileTable() as { path: string }[]).map((row) => row.path)).not.toContain( + transcriptPath(FIRST) + ) +}) + +// S3. The stat is the whole retry policy: a file that fails at one stat stops +// being read, and only a change to that stat starts it again. +it.skipIf(!CAN_DENY_READ)( + 'S3: stops reading a file that fails three times at one stat', + async () => { + const path = transcriptPath(FIRST) + await writeClaudeTranscript(path, ['behind the wrong mode bits'], FIRST) + await chmod(path, 0o000) + try { + await newIndexer().start() + for (let cycle = 0; cycle < 4; cycle++) { + await nextCycle() + } + + const row = harness.read((db: SyncDatabase) => + db.prepare('SELECT state, fail_count AS failCount FROM files WHERE path = ?').get(path) + ) as { state: string; failCount: number } + // Three, not four and not seven: the pass after the third costs nothing. + expect(row).toEqual({ state: 'failed', failCount: 3 }) + expect(indexer?.status()).toMatchObject({ filesFailed: 1, phase: 'degraded' }) + + // Only the stat releases it. + await chmod(path, 0o644) + const later = new Date(Date.now() + 60_000) + await utimes(path, later, later) + await nextCycle() + + expect(indexer?.status()).toMatchObject({ filesIndexed: 1, filesFailed: 0 }) + } finally { + await chmod(path, 0o644) + } + } +) + +// S4. Two passes over an unchanged filesystem leave the table byte for byte as +// they found it. Anything that drifted would be state the rows do not hold. +it('S4: leaves the file table identical across passes with no change on disk', async () => { + await writeClaudeTranscript(transcriptPath(FIRST), ['one'], FIRST) + await writeClaudeTranscript(transcriptPath(SECOND), ['two'], SECOND) + await newIndexer({ fullSweepEveryCycles: 2 }).start() + + const afterSweep = fileTable() + await nextCycle() + expect(fileTable()).toEqual(afterSweep) + await nextCycle() + expect(fileTable()).toEqual(afterSweep) + // Including across the periodic sweep, which reads the same rows again. + await nextCycle() + expect(fileTable()).toEqual(afterSweep) + expect(errors).toEqual([]) +}) + +// S5. Nothing a close interrupts needs repairing: the next instance reads the +// rows as they stand and decides from them alone. +it('S5: leaves the store consistent when a close interrupts a pass', async () => { + await writeClaudeTranscript(transcriptPath(FIRST), ['one'], FIRST) + await writeClaudeTranscript(transcriptPath(SECOND), ['two'], SECOND) + await writeClaudeTranscript(transcriptPath(THIRD), ['three'], THIRD) + newIndexer() + let closed = false + clock.onNow = () => { + if (closed || fileTable().length === 0) { + return + } + closed = true + indexer?.close() + } + await indexer?.start() + await indexer?.settled() + clock.onNow = null + + const interrupted = fileTable() + expect(interrupted.length).toBeGreaterThan(0) + expect(interrupted.length).toBeLessThan(3) + expect(errors).toEqual([]) + + // A new instance over the same database: no repair pass, no recovery, just + // the rows and what they say is owed. + resetTranscriptConsumersForTests() + resetSessionParseCacheForTests() + await newIndexer().start() + + expect(indexer?.status()).toMatchObject({ filesIndexed: 3, filesDue: 0, filesFailed: 0 }) +}) diff --git a/src/main/ai-vault-search/session-search-store.ts b/src/main/ai-vault-search/session-search-store.ts new file mode 100644 index 00000000000..daa9267561b --- /dev/null +++ b/src/main/ai-vault-search/session-search-store.ts @@ -0,0 +1,314 @@ +import type SyncDatabase from '../sqlite/sync-database' +import type { SessionFileCandidate } from '../ai-vault/session-scanner-types' +import type { TranscriptSessionIdentity } from '../ai-vault/session-transcript-consumers' +import type { + SessionSearchFileIdentity, + SessionSearchIndexedFile +} from './session-search-file-cursor' +import { + SESSION_SEARCH_COMMIT_CHARS, + SessionSearchIndexWriter, + type SessionSearchFileWrite +} from './session-search-index-writer' +import { deleteExpiredSearchFiles, drainOrphanedMessages } from './session-search-retention-delete' +import { openSessionSearchDatabase } from './session-search-schema' + +/** + * What a row still owes a reader. + * + * `current`: the rows match the file at the stat this row records. + * `due`: the index is behind on a span it cannot reach by appending, so the + * next pass must read the file whole. + * `failed`: the last read did not commit; `failCount` and `failedMtimeMs` are + * what stop it being retried for ever. + */ +export type SessionSearchFileState = 'current' | 'due' | 'failed' + +/** + * One row of the index's own file table. + * + * This is the indexer's whole memory between passes: what it holds, at what + * stat, and what each row still owes. Nothing it decides is answered from + * anywhere else, which is why a second connection can check its status. + */ +export type SessionSearchFileRow = { + path: string + identity: SessionSearchFileIdentity + mtimeMs: number + sizeBytes: number | null + state: SessionSearchFileState + failCount: number + failedMtimeMs: number | null +} + +/** How many rows are in each state; the whole of the indexer's progress report. */ +export type SessionSearchStateCounts = { current: number; due: number; failed: number } + +/** + * Owns the index database. PR 2 scope: the write half only — the transcript + * consumer writes through it and nothing reads from it yet. Lifecycle (who + * indexes, when, and how the re-read set is drained) belongs to the service. + */ +export class SessionSearchStore { + private readonly db: SyncDatabase + private readonly writer: SessionSearchIndexWriter + private closed = false + private retentionCutoffMs: number | null = null + // One drain at a time. A replace that commits while one is running asks for + // another pass rather than starting a second walk of the same rows. + private draining = false + private drainRequested = false + + constructor( + path: string, + private readonly onError: (error: unknown) => void = (error) => + console.warn( + '[ai-vault-search] index write failed:', + error instanceof Error ? error.name : 'IndexError' + ) + ) { + this.db = openSessionSearchDatabase(path) + this.writer = new SessionSearchIndexWriter(this.db, SESSION_SEARCH_COMMIT_CHARS, () => + this.scheduleOrphanDrain() + ) + } + + /** + * Reclaims the rows a replace cut loose, once its transaction has committed. + * + * The same split retention makes, for the same reason: deleting the old + * session row is what stops it answering, because every retrieval joins + * `sessions`, and handing its messages back is the expensive half that must + * not hold one transaction. Nothing records the work: rows whose session row + * is gone are the whole record, so a crash before or during a drain is found + * by the next one. + */ + private scheduleOrphanDrain(): void { + this.drainRequested = true + if (this.draining || this.closed) { + return + } + this.draining = true + // Off the committing stack. An async function runs synchronously up to its + // first `await`, so calling the drain here would put its first batch back + // inside the call that committed the replace — the cost this took out. + void Promise.resolve().then(() => this.runOrphanDrain()) + } + + private async runOrphanDrain(): Promise { + try { + while (this.drainRequested && !this.closed) { + this.drainRequested = false + await drainOrphanedMessages(this.db, () => this.closed) + } + } catch (error) { + if (!this.closed) { + this.onError(error) + } + } finally { + this.draining = false + } + } + + /** + * The index handle, for a reader composed over this store (PR 4's engine). + * + * Two rules come with it, both measured in this PR. **Never hold a read + * transaction across an `await`**: a checkpoint cannot pass an open read + * snapshot, so a paginated read that opened `BEGIN` and yielded between pages + * takes the WAL from 10 MB to 266 MB and it does not come back. And **no + * `.iterate()` that outlives its statement**, which is the same pin by + * another name. Every retrieval a single synchronous statement is the whole + * contract. + */ + get connection(): SyncDatabase { + return this.db + } + + /** The oldest transcript mtime worth indexing; PR 3 derives it from the retention setting. */ + setRetentionCutoffMs(cutoffMs: number | null): void { + this.retentionCutoffMs = cutoffMs + } + + /** The cutoff a caller's own decide step compares a candidate's mtime against. */ + get retentionCutoff(): number | null { + return this.retentionCutoffMs + } + + /** + * Whether this candidate is new enough to hold rows for. + * + * Enforced here as well as in the indexer's decide step, and not only there: + * the consumer observes every read the session list makes, not only the ones + * the index asked for, so a sidebar scan of a transcript outside the window + * would otherwise index rows the next purge deletes again. + */ + private withinRetention(candidate: SessionFileCandidate): boolean { + return this.retentionCutoffMs === null || candidate.file.mtimeMs >= this.retentionCutoffMs + } + + indexedFile(path: string, identity: SessionSearchFileIdentity): SessionSearchIndexedFile | null { + try { + return this.writer.indexedFile(path, identity) + } catch (error) { + this.onError(error) + return null + } + } + + /** Null when this read cannot extend the index, or when the store refuses writes. */ + beginWrite( + candidate: SessionFileCandidate, + mode: 'replace' | 'append', + previousByteOffset: number, + identity?: () => TranscriptSessionIdentity | null + ): SessionSearchFileWrite | null { + if (this.closed || !this.withinRetention(candidate)) { + return null + } + try { + return this.writer.beginWrite(candidate, mode, previousByteOffset, identity) + } catch (error) { + this.reportWriteFailure(error) + return null + } + } + + /** + * A read that landed. Written after the commit rather than inside it: the + * transaction owns the rows and the cursor, and a crash between the two + * leaves a row that says `failed` over content that is in fact current, which + * the next pass fixes by reading a file it did not have to. + */ + writeCommitted(candidate: SessionFileCandidate): void { + this.setFileState(candidate.file.path, 'current') + } + + reportWriteFailure(error: unknown): void { + this.onError(error) + } + + /** + * Every row this index holds. The candidate list for retirement and the whole + * of the status, read in one query so that no pass has to carry either. + * + * The cursor is deliberately not here: whether a row can be continued is + * `indexedFile`'s question, and one spelling of the half-written sentinel is + * enough. + */ + files(): SessionSearchFileRow[] { + return ( + this.db + .prepare( + `SELECT path, dev, ino, mtime_ms AS mtimeMs, size_bytes AS sizeBytes, + state, fail_count AS failCount, failed_mtime_ms AS failedMtimeMs + FROM files` + ) + .all() as (Omit & { + dev: number | null + ino: number | null + })[] + ).map((row) => ({ + path: row.path, + identity: + typeof row.dev === 'number' && typeof row.ino === 'number' + ? { dev: row.dev, ino: row.ino } + : null, + mtimeMs: row.mtimeMs, + sizeBytes: row.sizeBytes, + state: row.state, + failCount: row.failCount, + failedMtimeMs: row.failedMtimeMs + })) + } + + /** + * Moves a row's read state. + * + * `failed` also counts the failure and records the stat it happened at, which + * is what lets the next pass tell "this file has never worked" from "this + * file has changed since it last failed". A path with no row is a no-op: the + * next pass reads it because the index holds nothing for it. + */ + setFileState(path: string, state: SessionSearchFileState, atMtimeMs?: number): void { + try { + if (state === 'failed') { + // Inserted when there is no row, because the common unreadable file is + // one the index never managed to hold: a transcript behind the wrong + // mode bits fails on its very first read, and with nowhere to write the + // count it would be read again on every pass for the life of the + // process. The cursor is zero and there is no session, which is what + // "the index holds nothing for this file" already looks like. + this.db + .prepare( + `INSERT INTO files(path, byte_offset, mtime_ms, state, fail_count, failed_mtime_ms) + VALUES (?, 0, ?, 'failed', 1, ?) + ON CONFLICT(path) DO UPDATE SET + state = 'failed', + fail_count = files.fail_count + 1, + failed_mtime_ms = excluded.failed_mtime_ms` + ) + .run(path, atMtimeMs ?? 0, atMtimeMs ?? null) + return + } + this.db + .prepare( + 'UPDATE files SET state = ?, fail_count = 0, failed_mtime_ms = NULL WHERE path = ?' + ) + .run(state, path) + } catch (error) { + this.onError(error) + } + } + + /** Rows per state. The status is this query and the pass's own degraded roots. */ + stateCounts(): SessionSearchStateCounts { + const rows = this.db.prepare('SELECT state, count(*) AS n FROM files GROUP BY state').all() as { + state: SessionSearchFileState + n: number + }[] + const counts: SessionSearchStateCounts = { current: 0, due: 0, failed: 0 } + for (const row of rows) { + counts[row.state] = Number(row.n) + } + return counts + } + + /** + * Drops a source's rows. Only a proven deletion may call this: an unreadable + * source is `unverifiable`, not `missing`, and keeps its rows + * (docs/reference/ssh-execution-boundary.md). + */ + removeFile(path: string): void { + try { + this.writer.removeFile(path) + } catch (error) { + this.onError(error) + } + } + + /** Cuts expired sessions loose at once, then reclaims their rows in resumable batches. */ + async purgeOlderThan(cutoffMs: number | null, signal?: AbortSignal): Promise { + try { + await deleteExpiredSearchFiles( + this.db, + cutoffMs, + () => this.closed || signal?.aborted === true + ) + } catch (error) { + if (!this.closed) { + this.onError(error) + } + } + } + + close(): void { + // node:sqlite throws ERR_INVALID_STATE on a second close, and a store is + // closed both by its owner and by a test's teardown. + if (this.closed) { + return + } + this.closed = true + this.db.close() + } +} diff --git a/src/main/ai-vault-search/session-search-synthetic-corpus.test.ts b/src/main/ai-vault-search/session-search-synthetic-corpus.test.ts new file mode 100644 index 00000000000..9b6a48beb4e --- /dev/null +++ b/src/main/ai-vault-search/session-search-synthetic-corpus.test.ts @@ -0,0 +1,44 @@ +import { rm } from 'node:fs/promises' +import { join } from 'node:path' +import { expect, it } from 'vitest' +import { resetSessionParseCacheForTests } from '../ai-vault/session-scanner-parse-cache' +import { resetTranscriptConsumersForTests } from '../ai-vault/session-transcript-consumers' +import { registerSessionSearchIndexConsumer } from './session-search-index-consumer' +import { SessionSearchStore } from './session-search-store' +import { writeSyntheticTranscriptCorpus } from './session-search-synthetic-corpus' +import { parseTranscript } from './session-search-transcript-fixtures' + +it.each([Infinity, -Infinity, Number.NaN, -1, 1.5])( + 'rejects invalid corpus loop bounds: %s', + async (value) => { + for (const field of ['sessions', 'turnsPerSession', 'toolResultWords']) { + await expect(writeSyntheticTranscriptCorpus({ [field]: value })).rejects.toThrow(RangeError) + } + } +) + +it.each([0, 200, 2000])( + 'counts the indexed messages with %s tool words', + async (toolResultWords) => { + const corpus = await writeSyntheticTranscriptCorpus({ + sessions: 1, + turnsPerSession: 1, + toolResultWords + }) + const store = new SessionSearchStore(join(corpus.root, 'index.sqlite')) + const unregister = registerSessionSearchIndexConsumer(store) + try { + await parseTranscript(corpus.files[0]!) + expect(corpus.messageCount).toBe(toolResultWords === 0 ? 3 : 4) + expect(store.connection.prepare('SELECT count(*) AS n FROM messages').get()).toEqual({ + n: corpus.messageCount + }) + } finally { + unregister() + resetTranscriptConsumersForTests() + resetSessionParseCacheForTests() + store.close() + await rm(corpus.root, { recursive: true, force: true }) + } + } +) diff --git a/src/main/ai-vault-search/session-search-synthetic-corpus.ts b/src/main/ai-vault-search/session-search-synthetic-corpus.ts new file mode 100644 index 00000000000..14e8a27fe5f --- /dev/null +++ b/src/main/ai-vault-search/session-search-synthetic-corpus.ts @@ -0,0 +1,154 @@ +import { mkdtemp, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +// Why synthetic and in-repo: the cost model has to be reproducible on any host +// and must never read a real transcript. The shapes here mirror what a Claude +// JSONL transcript actually holds — prose turns, a pasted diff, tool calls and +// their output — because the index's disk cost tracks the mix, not the size. + +const WORDS = [ + 'terminal', + 'reattach', + 'worktree', + 'resolveTerminalPath', + 'src/main/ai-vault/session-transcript-reader.ts', + 'the', + 'index', + 'cursor', + 'byteOffset', + 'publish', + 'staged', + 'transaction', + 'MAX_RETRIES', + 'relay', + 'daemon', + 'pty', + 'snapshot', + 'because' +] + +/** Deterministic: the same seed gives the same corpus on every host and run. */ +function mulberry32(seed: number): () => number { + let state = seed >>> 0 + return () => { + state = (state + 0x6d2b79f5) >>> 0 + let t = Math.imul(state ^ (state >>> 15), 1 | state) + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 + } +} + +function words(random: () => number, count: number): string { + const out: string[] = [] + for (let index = 0; index < count; index++) { + out.push(WORDS[Math.floor(random() * WORDS.length)]) + } + return out.join(' ') +} + +export type SyntheticCorpus = { + root: string + files: string[] + /** Total bytes of transcript written, the denominator of write amplification. */ + transcriptBytes: number + messageCount: number +} + +export type SyntheticCorpusOptions = { + sessions?: number + turnsPerSession?: number + seed?: number + /** + * Words per tool result. The default keeps tool output at about half the + * message text; the real distribution is 80-97 %, which is what prices the + * tool-row cap, so the benchmark runs a second arm well above the default. + */ + toolResultWords?: number +} + +/** Writes a corpus of Claude JSONL transcripts and reports what it cost on disk. */ +export async function writeSyntheticTranscriptCorpus( + options: SyntheticCorpusOptions = {} +): Promise { + const sessions = options.sessions ?? 40 + const turns = options.turnsPerSession ?? 60 + const toolWords = options.toolResultWords ?? 200 + for (const [name, value] of Object.entries({ + sessions, + turnsPerSession: turns, + toolResultWords: toolWords + })) { + if (!Number.isSafeInteger(value) || value < 0) { + throw new RangeError(`${name} must be a finite non-negative safe integer`) + } + } + const random = mulberry32(options.seed ?? 1) + const root = await mkdtemp(join(tmpdir(), 'orca-search-corpus-')) + const files: string[] = [] + let transcriptBytes = 0 + let messageCount = 0 + + for (let session = 0; session < sessions; session++) { + const sessionId = `00000000-0000-4000-8000-${String(session).padStart(12, '0')}` + const lines: string[] = [] + for (let turn = 0; turn < turns; turn++) { + const at = new Date(1740000000000 + turn * 60_000).toISOString() + lines.push( + JSON.stringify({ + type: 'user', + sessionId, + timestamp: at, + cwd: `/repo/app-${session % 7}`, + gitBranch: 'main', + message: { role: 'user', content: words(random, 40) } + }) + ) + lines.push( + JSON.stringify({ + type: 'assistant', + sessionId, + timestamp: at, + message: { + role: 'assistant', + model: 'claude-fable-5', + content: [ + { type: 'text', text: words(random, 120) }, + { + type: 'tool_use', + name: 'Bash', + input: { command: `rg ${words(random, 3)}` } + } + ] + } + }) + ) + lines.push( + JSON.stringify({ + type: 'user', + sessionId, + timestamp: at, + message: { + role: 'user', + content: [ + { + type: 'tool_result', + tool_use_id: 'toolu_1', + content: words(random, toolWords) + } + ] + } + }) + ) + // Empty tool results emit no searchable message. + messageCount += toolWords === 0 ? 3 : 4 + } + const path = join(root, `${sessionId}.jsonl`) + const body = `${lines.join('\n')}\n` + await writeFile(path, body) + transcriptBytes += Buffer.byteLength(body) + files.push(path) + } + + return { root, files, transcriptBytes, messageCount } +} diff --git a/src/main/ai-vault-search/session-search-synthetic-sources.ts b/src/main/ai-vault-search/session-search-synthetic-sources.ts new file mode 100644 index 00000000000..86222b9c5fe --- /dev/null +++ b/src/main/ai-vault-search/session-search-synthetic-sources.ts @@ -0,0 +1,56 @@ +import type { AiVaultScanIssue } from '../../shared/ai-vault-types' +import { splitOpenCodeSqliteCandidate } from '../ai-vault/session-scanner-opencode-sqlite-paths' +import type { SessionFileCandidate } from '../ai-vault/session-scanner-types' + +/** + * A row whose path names a container and an entry inside it rather than a file + * of its own. OpenCode's SQLite sessions are the one shape today + * (`#`), which is why this reads through that source's + * own splitter rather than reinventing the encoding. + */ +export type SessionSearchSyntheticSource = { container: string; id: string } + +export function splitSyntheticSessionSource(path: string): SessionSearchSyntheticSource | null { + const openCode = splitOpenCodeSqliteCandidate(path) + return openCode ? { container: openCode.dbPath, id: openCode.sessionId } : null +} + +/** + * Which containers a pass enumerated in full, and every id each of them held. + * + * This is the synthetic equivalent of a directory listing, and it has to meet + * the same bar before the retirement walk may prove anything from it: + * + * - **Exhaustive.** Only a sweep enumerates without a per-agent limit. A cycle + * asks for the newest N, so an id it did not return may simply be the N+1th. + * Callers that are not a census do not build this at all. + * - **Successful.** A container a scan issue names could not be read, and a + * read that failed returns no ids rather than an error the walk can see. A + * named container is left out, so its rows stay unverifiable. + * - **Non-empty.** A container that returned nothing is not evidence that it + * holds nothing: a database whose schema this scanner no longer recognises + * returns an empty list with no error at all, and believing it would retire + * every session in one pass. The cost is one stale row per container whose + * last entry the user deletes, until the container gains an entry or goes. + */ +export function sessionSearchEnumeratedContainers( + candidates: readonly SessionFileCandidate[], + issues: readonly AiVaultScanIssue[] +): Map> { + const containers = new Map>() + for (const candidate of candidates) { + const synthetic = splitSyntheticSessionSource(candidate.file.path) + if (!synthetic) { + continue + } + const ids = containers.get(synthetic.container) ?? new Set() + ids.add(synthetic.id) + containers.set(synthetic.container, ids) + } + for (const issue of issues) { + if (issue.kind !== 'notice') { + containers.delete(issue.path) + } + } + return containers +} diff --git a/src/main/ai-vault-search/session-search-transcript-fixtures.ts b/src/main/ai-vault-search/session-search-transcript-fixtures.ts new file mode 100644 index 00000000000..bc7eda9a8ff --- /dev/null +++ b/src/main/ai-vault-search/session-search-transcript-fixtures.ts @@ -0,0 +1,118 @@ +import { stat } from 'node:fs/promises' +import { + createSessionParseStats, + parseAgentSessionFileCached, + type SessionParseStats +} from '../ai-vault/session-scanner-parse-cache' +import type { SessionFileCandidate } from '../ai-vault/session-scanner-types' + +// Transcript builders shared by the session-search store tests; each file owns +// its temp directories, this module only shapes records and drives the parser. + +export const CLAUDE_SESSION_ID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' +export const CODEX_SESSION_ID = '019f0000-1111-7222-8333-444444444444' +export const CODEX_ROLLOUT_FILE = `rollout-2026-05-01T10-00-00-${CODEX_SESSION_ID}.jsonl` + +const RECORD_EPOCH_MS = 1740000000000 + +export function recordTimestamp(index: number): string { + return new Date(RECORD_EPOCH_MS + index * 60_000).toISOString() +} + +export function userRecord( + index: number, + content: unknown, + sessionId = CLAUDE_SESSION_ID, + cwd = '/repo/app' +): string { + return JSON.stringify({ + type: 'user', + sessionId, + timestamp: recordTimestamp(index), + cwd, + gitBranch: 'main', + message: { role: 'user', content } + }) +} + +export function assistantRecord( + index: number, + content: unknown, + sessionId = CLAUDE_SESSION_ID +): string { + return JSON.stringify({ + type: 'assistant', + sessionId, + timestamp: recordTimestamp(index), + message: { role: 'assistant', model: 'claude-fable-5', content } + }) +} + +export async function sessionCandidate( + agent: SessionFileCandidate['agent'], + path: string, + codexHome: string | null = null +): Promise { + const fileStat = await stat(path) + return { + agent, + codexHome, + file: { + path, + mtimeMs: fileStat.mtimeMs, + modifiedAt: fileStat.mtime.toISOString(), + sizeBytes: fileStat.size, + dev: fileStat.dev, + ino: fileStat.ino + } + } +} + +export async function parseTranscript( + path: string, + agent: SessionFileCandidate['agent'] = 'claude', + codexHome: string | null = null +): Promise<{ stats: SessionParseStats }> { + const stats = createSessionParseStats() + await parseAgentSessionFileCached( + await sessionCandidate(agent, path, codexHome), + process.platform, + stats + ) + return { stats } +} + +function codexLine(record: Record): string { + return JSON.stringify(record) +} + +/** Minimal Codex rollout: meta, one user message, one completed shell command. */ +export function codexRolloutLines(command: string[], output: string, prompt: string): string[] { + return [ + codexLine({ + timestamp: recordTimestamp(0), + type: 'session_meta', + payload: { id: CODEX_SESSION_ID, cwd: '/repo/app', git: { branch: 'main' } } + }), + codexLine({ + timestamp: recordTimestamp(1), + type: 'response_item', + payload: { type: 'message', role: 'user', content: prompt } + }), + codexLine({ + timestamp: recordTimestamp(2), + type: 'response_item', + payload: { + type: 'function_call', + call_id: 'call-1', + name: 'shell', + arguments: JSON.stringify({ command }) + } + }), + codexLine({ + timestamp: recordTimestamp(3), + type: 'response_item', + payload: { type: 'function_call_output', call_id: 'call-1', output } + }) + ] +} diff --git a/src/main/ai-vault-search/session-search-typo-policy.test.ts b/src/main/ai-vault-search/session-search-typo-policy.test.ts new file mode 100644 index 00000000000..938c1e1fc3e --- /dev/null +++ b/src/main/ai-vault-search/session-search-typo-policy.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, it } from 'vitest' +import type SyncDatabase from '../sqlite/sync-database' +import { openSessionSearchIndexFile } from './session-search-index-test-fixture' +import { ensureSessionSearchQuerySchema } from './session-search-query-schema' +import { SessionSearchTypoRepair } from './session-search-typo-repair' + +/** A session row the planted messages below hang off, so a repair can see them. */ +function addSession(db: SyncDatabase, id: number): void { + db.prepare( + `INSERT INTO sessions(id,agent,session_id,file_path,title,resume_command) + VALUES (?, 'claude', ?, '/synthetic/fixture', 'typo fixture', '')` + ).run(id, String(id)) +} + +function addTerm(db: SyncDatabase, sessionRowId: number, term: string): void { + const rowid = db + .prepare("INSERT INTO messages(session_row_id, role) VALUES (?, 'user')") + .run(sessionRowId).lastInsertRowid + db.prepare('INSERT INTO messages_fts(rowid, user_text) VALUES (?, ?)').run(Number(rowid), term) +} + +describe('typo repair policy', () => { + it.each([ + { input: 'coalesces', candidate: 'coalesced', copies: 2, exact: true, expected: null }, + { input: 'coalescs', candidate: 'coalesces', copies: 1, exact: false, expected: null }, + { input: 'coalescs', candidate: 'coalesces', copies: 2, exact: false, expected: 'coalesces' }, + { input: 'café', candidate: 'cafe', copies: 1, exact: false, expected: null }, + { input: 'car', candidate: 'cars', copies: 2, exact: false, expected: null }, + { input: 'calm', candidate: 'clam', copies: 2, exact: false, expected: null } + ])( + 'repairs $input to $expected with $copies postings (exact=$exact)', + async ({ input, candidate, copies, exact, expected }) => { + const index = await openSessionSearchIndexFile('ss-typo-policy') + try { + ensureSessionSearchQuerySchema(index.db) + addSession(index.db, 1) + for (let i = 0; i < copies; i++) { + addTerm(index.db, 1, candidate) + } + if (exact) { + addTerm(index.db, 1, input) + } + expect(new SessionSearchTypoRepair(index.db).correct(input, 'all')).toBe(expected) + } finally { + await index.close() + } + } + ) + + // A purge cuts a session loose in one transaction and reclaims its rows over + // many, so the vocabulary can still list a term whose only rows nothing can + // reach. Abandoning the prefix at that term would lose a repair the rest of + // the index can already serve. + it('falls through to the best candidate a reader can still reach', async () => { + const index = await openSessionSearchIndexFile('ss-typo-orphaned') + try { + const { db } = index + ensureSessionSearchQuerySchema(db) + addSession(db, 1) + // `coalesces` scores higher against `coalescs` than `coalesced` does, and + // shares its prefix, so only the fall-through can reach the reachable one. + // Session 2 is never created: these rows are what an unfinished purge + // leaves behind, and the vocabulary counts them all the same. + for (const [term, session] of [ + ['coalesces', 2], + ['coalesces', 2], + ['coalesced', 1], + ['coalesced', 1] + ] as const) { + addTerm(db, session, term) + } + expect(db.prepare("SELECT doc FROM messages_vocab WHERE term='coalesces'").get()).toEqual({ + doc: 2 + }) + expect(new SessionSearchTypoRepair(db).correct('coalescs', 'all')).toBe('coalesced') + } finally { + await index.close() + } + }) +}) diff --git a/src/main/ai-vault-search/session-search-typo-repair.ts b/src/main/ai-vault-search/session-search-typo-repair.ts new file mode 100644 index 00000000000..1aed90e2991 --- /dev/null +++ b/src/main/ai-vault-search/session-search-typo-repair.ts @@ -0,0 +1,163 @@ +import type SyncDatabase from '../sqlite/sync-database' +import type { SessionSearchScope } from './session-search-engine-types' +import { quoteFtsTerm, scopedExpression } from './session-search-query-planner' + +// Why: a query term with zero postings is usually a typo. The index's own +// vocabulary (fts5vocab) is the dictionary, so repair needs no model and can +// never suggest a word the index does not contain. Measured MRR 0.553 → 0.566. +const MIN_TERM_LENGTH = 4 +const MAX_TERM_LENGTH = 40 +const LENGTH_SLACK = 2 +const MIN_DOC_FREQUENCY = 2 +const MIN_SIMILARITY = 0.82 +const MAX_CANDIDATES = 4000 +// Candidates counted against live rows per prefix before giving up on it. Only +// reached for a term the scope has no posting for, which is the rare case. +const MAX_VISIBILITY_PROBES = 8 +// How far a live count walks before it stops caring. It exists to break ties +// between candidates of equal similarity, and the difference between a term in +// sixty-four rows and one in six thousand does not change which is the better +// repair — but reading either in full would. +const MAX_COUNTED_ROWS = 64 + +// Longest common subsequence length; the indel distance is len(a)+len(b)-2·LCS. +function commonSubsequenceLength(a: string, b: string): number { + let previous = Array.from({ length: b.length + 1 }).fill(0) + let current = Array.from({ length: b.length + 1 }).fill(0) + for (let i = 1; i <= a.length; i += 1) { + for (let j = 1; j <= b.length; j += 1) { + current[j] = + a.charCodeAt(i - 1) === b.charCodeAt(j - 1) + ? previous[j - 1] + 1 + : Math.max(previous[j], current[j - 1]) + } + ;[previous, current] = [current, previous] + } + return previous[b.length] +} + +/** Normalized indel similarity in [0, 1], the scale rapidfuzz's `fuzz.ratio` uses. */ +function similarity(a: string, b: string): number { + const total = a.length + b.length + return total === 0 ? 1 : (2 * commonSubsequenceLength(a, b)) / total +} + +/** + * Spelling repair over the index's own vocabulary. + * + * The vocabulary proposes and a scoped count disposes. `messages_vocab` is a + * view over the whole FTS b-tree: it has no column filter, because fts5vocab is + * per table, and it counts rows whose session a purge already cut loose. So + * every decision that reaches the plan — whether a term is already spelled + * right, whether a candidate is eligible, and which of two equally close + * candidates wins — is taken from a `messages_fts MATCH` under the same column + * filter retrieval uses, joined to `sessions`. + * + * That is not tidiness. Reading the vocabulary directly made the repair depend + * on rows the search could never return: tool output suppressed a + * conversation-scope repair and supplied suggestions the scope would never + * show, and retention's orphan drain silently changed which word a query was + * repaired to. + * + * The cost is one bounded count per candidate examined, at most + * `MAX_VISIBILITY_PROBES` per prefix, and only for a term the scope has no + * posting for. See docs/reference/agent-session-search-query-tuning.md. + */ +export class SessionSearchTypoRepair { + private readonly liveRows: ReturnType + private readonly candidatesByPrefix: ReturnType + + constructor(db: SyncDatabase) { + this.liveRows = db.prepare( + `SELECT count(*) AS rows FROM ( + SELECT m.id FROM messages_fts + JOIN messages m ON m.id = messages_fts.rowid + JOIN sessions s ON s.id = m.session_row_id + WHERE messages_fts MATCH ? LIMIT ${MAX_COUNTED_ROWS})` + ) + // fts5vocab is ordered by term, so a prefix range plus a length band is a + // bounded scan and no sort. Ordered by term rather than by `doc`: the + // ordering decides which candidates survive the limit, and `doc` counts + // rows no reader can see, so the drain reclaiming them moved the cut. + this.candidatesByPrefix = db.prepare( + `SELECT term FROM messages_vocab + WHERE term >= ? AND term < ? AND length(term) BETWEEN ? AND ? + ORDER BY term LIMIT ?` + ) + } + + /** Live rows carrying this term inside `scope`, counted no further than it matters. */ + private countRows(term: string, scope: SessionSearchScope): number { + const row = this.liveRows.get(scopedExpression(scope, quoteFtsTerm(term))) as { rows: number } + return row.rows + } + + /** Whether a live row inside `scope` holds this term. */ + hasPostings(term: string, scope: SessionSearchScope): boolean { + return this.countRows(term, scope) > 0 + } + + /** Returns the closest indexed term, or null when `term` exists or nothing is close enough. */ + correct(term: string, scope: SessionSearchScope): string | null { + const lowered = term.toLowerCase() + if (lowered.length < MIN_TERM_LENGTH || lowered.length > MAX_TERM_LENGTH) { + return null + } + if (this.hasPostings(lowered, scope)) { + return null + } + // Two-letter prefix first (a typo rarely hits both), then the transposed + // pair, then the bare first letter as the wide fallback. + const prefixes = [lowered.slice(0, 2), lowered[1] + lowered[0], lowered[0]] + for (const prefix of prefixes) { + const best = this.bestVisible(lowered, prefix, scope) + if (best) { + return best + } + } + return null + } + + /** + * The closest candidate at `prefix` that this scope can actually answer with. + * + * Ranking is pure CPU, so the walk is bounded rather than the count: the + * closest term can be one the scope never shows, and abandoning the prefix + * there would lose a repair the rest of the index can serve. Ties on + * similarity go to the more common word, which is the same prior the + * vocabulary's `doc` used to supply — counted live here so the answer does + * not move when a purge reclaims rows nothing could reach. + */ + private bestVisible(lowered: string, prefix: string, scope: SessionSearchScope): string | null { + const counted = this.ranked(lowered, prefix) + .slice(0, MAX_VISIBILITY_PROBES) + .map((candidate) => ({ ...candidate, rows: this.countRows(candidate.term, scope) })) + .filter((candidate) => candidate.rows >= MIN_DOC_FREQUENCY) + if (counted.length === 0) { + return null + } + // Already sorted by similarity; a stable sort keeps that and orders the ties. + return counted.sort((left, right) => right.score - left.score || right.rows - left.rows)[0]! + .term + } + + /** Candidates similar enough to be a repair, closest first. */ + private ranked(lowered: string, prefix: string): { term: string; score: number }[] { + return this.candidates(prefix, lowered.length) + .map((row) => ({ term: row.term, score: similarity(lowered, row.term) })) + .filter((candidate) => candidate.score >= MIN_SIMILARITY) + .sort((left, right) => right.score - left.score || (left.term < right.term ? -1 : 1)) + } + + private candidates(prefix: string, length: number): { term: string }[] { + const last = prefix.charCodeAt(prefix.length - 1) + const upper = prefix.slice(0, -1) + String.fromCharCode(last + 1) + return this.candidatesByPrefix.all( + prefix, + upper, + Math.max(MIN_TERM_LENGTH - 1, length - LENGTH_SLACK), + length + LENGTH_SLACK, + MAX_CANDIDATES + ) as { term: string }[] + } +} diff --git a/src/main/ai-vault-search/session-search-typo-scope.test.ts b/src/main/ai-vault-search/session-search-typo-scope.test.ts new file mode 100644 index 00000000000..98e3938178e --- /dev/null +++ b/src/main/ai-vault-search/session-search-typo-scope.test.ts @@ -0,0 +1,71 @@ +import { afterEach, expect, it } from 'vitest' +import { + addSyntheticSession, + openSessionSearchHarness, + type SessionSearchHarness +} from './session-search-engine-test-fixture' + +// Typo repair used to read `messages_vocab` and probe `messages_fts` with no +// column filter, so tool output decided whether a conversation-scoped query was +// repaired — in both directions. A tool row carrying the misspelling made the +// query look correctly spelled and suppressed the repair; a tool row carrying a +// rare word offered it as the suggestion, naming in `repairedTerms` a string +// from a column the scope will never show. + +let harness: SessionSearchHarness | null = null +let control: SessionSearchHarness | null = null + +afterEach(async () => { + await harness?.close() + await control?.close() + harness = null + control = null +}) + +it('repairs a conversation query the same way with or without a tool row', async () => { + harness = await openSessionSearchHarness('ss-typo-scope-suppress') + addSyntheticSession(harness.db, { id: 1, text: 'we changed resolveTerminalPath today', rows: 2 }) + // A second session whose tool output happens to contain the misspelling. + addSyntheticSession(harness.db, { + id: 2, + text: 'ran the linter', + toolText: 'warning: unknown symbol resolveterminalpth in build log', + rows: 2, + role: 'assistant' + }) + + // The same index without that one tool row. + control = await openSessionSearchHarness('ss-typo-scope-control') + addSyntheticSession(control.db, { id: 1, text: 'we changed resolveTerminalPath today', rows: 2 }) + addSyntheticSession(control.db, { id: 2, text: 'ran the linter' }) + + const request = { query: 'resolveterminalpth', scope: 'conversation' } as const + const withTool = harness.engine.search(request) + const clean = control.engine.search(request) + + expect(clean.planner.repairedTerms).toEqual(['resolveterminalpath']) + expect(clean.hits.map((hit) => hit.sessionId)).toEqual(['1']) + expect(withTool.planner.repairedTerms).toEqual(clean.planner.repairedTerms) + expect(withTool.hits.map((hit) => hit.sessionId)).toEqual(clean.hits.map((hit) => hit.sessionId)) +}) + +it('never repairs a conversation query onto a word only tool output holds', async () => { + harness = await openSessionSearchHarness('ss-typo-scope-leak') + addSyntheticSession(harness.db, { + id: 1, + text: 'ran the deploy', + toolText: 'AWS_SESSION_TOKEN=quicksilverfox expired', + rows: 2, + role: 'assistant' + }) + addSyntheticSession(harness.db, { id: 2, text: 'ordinary prose about nothing' }) + + const narrowed = harness.engine.search({ query: 'quicksilverfx', scope: 'conversation' }) + expect(narrowed.planner.repairedTerms).toBeUndefined() + expect(narrowed.hits).toEqual([]) + // The same query over the whole corpus still finds it, which is the scope + // doing its job rather than the repair being broken. + const wide = harness.engine.search({ query: 'quicksilverfx', scope: 'all' }) + expect(wide.planner.repairedTerms).toEqual(['quicksilverfox']) + expect(wide.hits.map((hit) => hit.sessionId)).toEqual(['1']) +}) diff --git a/src/main/ai-vault-search/session-search-work-loop.ts b/src/main/ai-vault-search/session-search-work-loop.ts new file mode 100644 index 00000000000..41a0ad98497 --- /dev/null +++ b/src/main/ai-vault-search/session-search-work-loop.ts @@ -0,0 +1,87 @@ +import type { SessionSearchClock, SessionSearchTimerHandle } from './session-search-clock' + +export type SessionSearchWorkLoopOptions = { + clock: SessionSearchClock + intervalMs: number + /** A task that threw for a reason other than its own abort. */ + onFailure: (error: unknown) => void +} + +/** + * Runs the indexer's passes one at a time, on an interval, until it is closed. + * + * Separate from the indexer because it is the part with no opinion about + * transcripts: a task chain that never overlaps itself, a timer that only ever + * has one pending tick, and a close that cancels both. Arming inside the chain + * rather than beside it is what makes `settled` mean "everything queued so far + * has finished, including the re-arm", which is what a fake-clock test needs. + */ +export class SessionSearchWorkLoop { + private timer: SessionSearchTimerHandle | null = null + private controller: AbortController | null = null + private chain: Promise = Promise.resolve() + private closed = false + + constructor(private readonly options: SessionSearchWorkLoopOptions) {} + + /** Everything queued so far. Never rejects: a task's failure is reported, not thrown. */ + get settled(): Promise { + return this.chain + } + + /** Queues `work` behind whatever is running, then re-arms the interval. */ + queue(work: (signal: AbortSignal) => Promise, tick: () => void): Promise { + const chained = this.chain + .then( + () => this.run(work), + () => this.run(work) + ) + .then(() => this.arm(tick)) + this.chain = chained + return chained + } + + /** + * Stops the timer, the task in flight and everything queued behind it. Nothing + * queued before this call may run afterwards: that is what lets the indexer + * close its store here and know no pass will reach for it. + */ + close(): void { + this.closed = true + if (this.timer !== null) { + this.options.clock.clearTimeout(this.timer) + this.timer = null + } + this.controller?.abort() + } + + private arm(tick: () => void): void { + if (this.closed || this.timer !== null) { + return + } + this.timer = this.options.clock.setTimeout(() => { + this.timer = null + tick() + }, this.options.intervalMs) + } + + private async run(work: (signal: AbortSignal) => Promise): Promise { + if (this.closed) { + return + } + const controller = new AbortController() + this.controller = controller + try { + await work(controller.signal) + } catch (error) { + // An aborted task is a close, never a failure. + if (!controller.signal.aborted) { + this.options.onFailure(error) + } + } finally { + if (this.controller === controller) { + this.controller = null + } + } + } +} diff --git a/src/main/ai-vault/session-scanner-accumulator.ts b/src/main/ai-vault/session-scanner-accumulator.ts index 88e09627eb7..18f273d6be3 100644 --- a/src/main/ai-vault/session-scanner-accumulator.ts +++ b/src/main/ai-vault/session-scanner-accumulator.ts @@ -23,7 +23,11 @@ import { normalizePreviewText, timestampMs } from './session-scanner-values' -import { NO_TRANSCRIPT_MESSAGES, type TranscriptMessageSink } from './session-transcript-consumers' +import { + NO_TRANSCRIPT_MESSAGES, + type TranscriptMessageSink, + type TranscriptSessionIdentity +} from './session-transcript-consumers' import { boundedText, transcriptMessageRole, @@ -64,6 +68,28 @@ export function createAccumulator(args: { } } +/** + * The session identity a fold holds right now. Null until it has an id, which + * every supported format writes in the opening lines of the transcript. + */ +export function accumulatorSessionIdentity( + accumulator: SessionAccumulator +): TranscriptSessionIdentity | null { + const sessionId = accumulator.sessionId.trim() + if (!sessionId) { + return null + } + return { + sessionId, + cwd: accumulator.cwd, + // The generated fallback is `finalizeSession`'s, not this one's: a title + // that is still absent mid-read is better said to be absent. + title: accumulator.title ?? accumulator.fallbackTitle, + createdAt: accumulator.createdAt, + updatedAt: accumulator.updatedAt + } +} + export function cloneSessionAccumulator(accumulator: SessionAccumulator): SessionAccumulator { return { ...accumulator, previewMessages: [...accumulator.previewMessages] } } @@ -77,6 +103,7 @@ export function accumulatorFoldResumeState( ): ResumableSessionParseState { return { consumeLine: (line) => consumeRecordLine(accumulator, line), + identity: () => accumulatorSessionIdentity(accumulator), clone: () => accumulatorFoldResumeState(cloneSessionAccumulator(accumulator), consumeRecordLine), touchFile: (file) => { diff --git a/src/main/ai-vault/session-scanner-codex-message-records.ts b/src/main/ai-vault/session-scanner-codex-message-records.ts index 5aa739275ff..a8a5c3c9d13 100644 --- a/src/main/ai-vault/session-scanner-codex-message-records.ts +++ b/src/main/ai-vault/session-scanner-codex-message-records.ts @@ -1,3 +1,7 @@ +import { + publishCodexResponseTool, + publishCodexCompletedTool +} from './session-scanner-codex-tool-records' import { normalizePromptField } from '../../shared/agent-status-field-normalization' import { addPreviewContent } from './session-scanner-accumulator' import type { SessionAccumulator } from './session-scanner-types' @@ -8,6 +12,10 @@ export function consumeCodexResponseMessage( payload: Record, timestamp: unknown ): boolean { + publishCodexResponseTool(accumulator, payload, timestamp) + if (payload.type !== 'message') { + return false + } accumulator.messageCount++ const role = payload.role === 'assistant' ? 'assistant' : payload.role === 'user' ? 'user' : 'unknown' @@ -24,6 +32,7 @@ export function consumeCodexCompletedMessage( payload: Record, timestamp: unknown ): boolean { + publishCodexCompletedTool(accumulator, payload, timestamp) const item = asRecord(payload.item) if (!item) { return false diff --git a/src/main/ai-vault/session-scanner-codex-parser.ts b/src/main/ai-vault/session-scanner-codex-parser.ts index 02a385400de..b3571d4a337 100644 --- a/src/main/ai-vault/session-scanner-codex-parser.ts +++ b/src/main/ai-vault/session-scanner-codex-parser.ts @@ -4,6 +4,7 @@ import type { AiVaultSession } from '../../shared/ai-vault-types' import { readCodexSessionIndexTitle } from './session-scanner-codex-title-index' import type { ExecutionHostId } from '../../shared/execution-host' import { + accumulatorSessionIdentity, cloneSessionAccumulator, createAccumulator, finalizeSession, @@ -153,19 +154,13 @@ function consumeCodexRecordLine(state: CodexSessionParseState, line: string): vo accumulator.title = metadataTitle state.titleSource = 'meta' } - const cwd = extractString(payload.cwd) - if (cwd) { - accumulator.cwd = cwd - } + accumulator.cwd = extractString(payload.cwd) ?? accumulator.cwd accumulator.branch = extractGitBranch(payload.git) ?? accumulator.branch return } if (record.type === 'turn_context' && payload) { - const cwd = extractString(payload.cwd) - if (cwd) { - accumulator.cwd = cwd - } + accumulator.cwd = extractString(payload.cwd) ?? accumulator.cwd const model = extractModel(payload) if (model) { accumulator.model = model @@ -177,7 +172,7 @@ function consumeCodexRecordLine(state: CodexSessionParseState, line: string): vo return } - if (record.type === 'response_item' && payload.type === 'message') { + if (record.type === 'response_item') { if (state.historyMode === 'paginated') { return } @@ -285,7 +280,10 @@ function codexResumeStateFromParseState( return { consumeLine: (line) => consumeCodexRecordLine(state, line), consumeLineBytes: (line) => { - const timelineOnlyRecord = readCodexTimelineOnlyRecord(line) + const timelineOnlyRecord = readCodexTimelineOnlyRecord( + line, + state.accumulator.messages.active && state.historyMode !== 'paginated' + ) if (timelineOnlyRecord) { updateTimeline(state.accumulator, timelineOnlyRecord.timestamp) } else { @@ -293,6 +291,7 @@ function codexResumeStateFromParseState( } }, shouldStop: () => state.rejectedWorkerSession, + identity: () => accumulatorSessionIdentity(state.accumulator), clone: () => codexResumeStateFromParseState(cloneCodexParseState(state), codexHome, titleReader), touchFile: (file) => { diff --git a/src/main/ai-vault/session-scanner-codex-record-fast-path.ts b/src/main/ai-vault/session-scanner-codex-record-fast-path.ts index 1c4322f89f6..852ec174e95 100644 --- a/src/main/ai-vault/session-scanner-codex-record-fast-path.ts +++ b/src/main/ai-vault/session-scanner-codex-record-fast-path.ts @@ -1,3 +1,5 @@ +import { CODEX_TOOL_RESPONSE_TYPES } from './session-scanner-codex-tool-records' + // Records below this size are decoded and parsed exactly: JSON.parse on a // kilobyte costs less than the risk of a prefix heuristic, and the scan cost // this path exists to remove is entirely in megabyte-scale records. @@ -22,7 +24,10 @@ const PARSED_EVENT_TYPES = new Set([ ]) /** Returns the timestamp only when the record cannot affect other visible session fields. */ -export function readCodexTimelineOnlyRecord(line: Buffer): { timestamp: string } | null { +export function readCodexTimelineOnlyRecord( + line: Buffer, + includeTools = false +): { timestamp: string } | null { if (line.length <= CODEX_RECORD_PREFIX_LIMIT) { return null } @@ -41,6 +46,13 @@ export function readCodexTimelineOnlyRecord(line: Buffer): { timestamp: string } if (!payloadType) { return null } + if ( + includeTools && + recordType === 'response_item' && + CODEX_TOOL_RESPONSE_TYPES.has(payloadType) + ) { + return null + } const parsedPayloadTypes = recordType === 'response_item' ? PARSED_RESPONSE_ITEM_TYPES : PARSED_EVENT_TYPES return parsedPayloadTypes.has(payloadType) ? null : { timestamp } diff --git a/src/main/ai-vault/session-scanner-codex-tool-records.test.ts b/src/main/ai-vault/session-scanner-codex-tool-records.test.ts new file mode 100644 index 00000000000..a5aa909bfa1 --- /dev/null +++ b/src/main/ai-vault/session-scanner-codex-tool-records.test.ts @@ -0,0 +1,125 @@ +import { expect, it } from 'vitest' +import { createCodexSessionResumeState } from './session-scanner-codex-parser' +import type { TranscriptMessage } from './session-transcript-consumers' +import { readCodexTimelineOnlyRecord } from './session-scanner-codex-record-fast-path' + +const timestamp = '2026-05-01T10:00:00.000Z' +const file = { + path: '/fixture/rollout.jsonl', + mtimeMs: Date.parse(timestamp), + modifiedAt: timestamp +} +const record = (type: string, payload: Record): Buffer => + Buffer.from(JSON.stringify({ timestamp, type, payload })) + +it.each(['function_call_output', 'custom_tool_call_output'])( + 'reads large %s records only when a consumer needs them', + (type) => { + const line = record('response_item', { type, output: 'outputonly '.repeat(300) }) + expect(readCodexTimelineOnlyRecord(line)).toEqual({ timestamp }) + expect(readCodexTimelineOnlyRecord(line, true)).toBeNull() + const messages: TranscriptMessage[] = [] + const state = createCodexSessionResumeState(file, null, { + active: true, + push: (message) => messages.push(message) + }) + state.consumeLineBytes!(line) + expect(messages).toEqual([{ role: 'tool', text: 'outputonly '.repeat(300), timestamp }]) + } +) + +it.each([false, true])( + 'uses one tool representation across append when paginated=%s', + async (paginated) => { + const messages: TranscriptMessage[] = [] + let state = createCodexSessionResumeState(file, null, { + active: true, + push: (message) => messages.push(message) + }) + const consume = (type: string, payload: Record) => + state.consumeLineBytes!(record(type, payload)) + consume('session_meta', { id: 'session-1', history_mode: paginated ? 'paginated' : 'full' }) + consume('response_item', { type: 'message', role: 'user', content: 'promptonly' }) + consume('event_msg', { + type: 'item_completed', + item: { type: 'UserMessage', content: [{ type: 'text', text: 'promptonly' }] } + }) + consume('response_item', { + type: 'function_call', + name: 'shell', + arguments: '{"command":"commandonly"}' + }) + // The next scan resumes between the call and its output. + state = state.clone() + consume('response_item', { type: 'function_call_output', output: 'outputonly' }) + consume('event_msg', { + type: 'item_completed', + item: { type: 'CommandExecution', command: ['commandonly'], aggregated_output: 'outputonly' } + }) + expect(messages.filter((message) => message.text.includes('commandonly'))).toHaveLength(1) + expect(messages.filter((message) => message.text === 'outputonly')).toEqual([ + { role: 'tool', text: 'outputonly', timestamp } + ]) + expect(messages.filter((message) => message.role === 'user')).toHaveLength(1) + expect(await state.finalize(process.platform)).toMatchObject({ messageCount: 1 }) + } +) + +it.each([ + { type: 'add', content: '+ addedneedle' }, + { type: 'delete', content: '+ addedneedle' }, + { type: 'update', unified_diff: '+ addedneedle', move_path: null } +])('publishes paginated $type file changes', (change) => { + const messages: TranscriptMessage[] = [] + const state = createCodexSessionResumeState(file, null, { + active: true, + push: (message) => messages.push(message) + }) + state.consumeLineBytes!(record('session_meta', { id: 'session-1', history_mode: 'paginated' })) + state.consumeLineBytes!( + record('event_msg', { + type: 'item_completed', + item: { type: 'FileChange', changes: { 'src/changed.ts': change } } + }) + ) + expect(messages.map((message) => [message.role, message.text])).toEqual([ + ['tool', 'apply_patch: src/changed.ts'], + ['tool', '+ addedneedle'] + ]) +}) + +it('normalizes custom calls and structured results through the existing content reader', () => { + const messages: TranscriptMessage[] = [] + const state = createCodexSessionResumeState(file, null, { + active: true, + push: (message) => messages.push(message) + }) + state.consumeLineBytes!( + record('response_item', { type: 'custom_tool_call', name: 'apply_patch', input: 'patchneedle' }) + ) + state.consumeLineBytes!( + record('response_item', { + type: 'custom_tool_call_output', + output: { content: [{ type: 'text', text: 'resultneedle' }] } + }) + ) + expect(messages.map((message) => message.text)).toEqual([ + 'apply_patch: patchneedle', + 'resultneedle' + ]) +}) + +it('keeps local shell argv searchable', () => { + const messages: TranscriptMessage[] = [] + const state = createCodexSessionResumeState(file, null, { + active: true, + push: (message) => messages.push(message) + }) + state.consumeLineBytes!( + record('response_item', { + type: 'local_shell_call', + action: { type: 'exec', command: ['rg', 'argvneedle'] } + }) + ) + expect(messages.map((message) => message.text)).toEqual(['tool: rg argvneedle']) +}) diff --git a/src/main/ai-vault/session-scanner-codex-tool-records.ts b/src/main/ai-vault/session-scanner-codex-tool-records.ts new file mode 100644 index 00000000000..976d5eff36d --- /dev/null +++ b/src/main/ai-vault/session-scanner-codex-tool-records.ts @@ -0,0 +1,95 @@ +import { timestampIso } from './session-scanner-accumulator' +import { asRecord } from './session-scanner-record-value' +import type { SessionAccumulator } from './session-scanner-types' +import { transcriptMessagesFromContent } from './session-transcript-message-content' + +export const CODEX_TOOL_RESPONSE_TYPES = new Set([ + 'function_call', + 'local_shell_call', + 'custom_tool_call', + 'function_call_output', + 'custom_tool_call_output' +]) + +function publishToolContent( + accumulator: SessionAccumulator, + content: unknown, + timestamp: unknown +): void { + for (const message of transcriptMessagesFromContent('tool', content, timestampIso(timestamp))) { + accumulator.messages.push(message) + } +} + +export function publishCodexResponseTool( + accumulator: SessionAccumulator, + payload: Record, + timestamp: unknown +): void { + if (!accumulator.messages.active || !CODEX_TOOL_RESPONSE_TYPES.has(String(payload.type))) { + return + } + if (payload.type === 'function_call_output' || payload.type === 'custom_tool_call_output') { + const output = asRecord(payload.output) + publishToolContent( + accumulator, + [{ type: 'tool_result', content: output?.content ?? output?.output ?? payload.output }], + timestamp + ) + return + } + const input = payload.arguments ?? payload.input ?? payload.action + const action = asRecord(input) + const normalizedInput = + action && Array.isArray(action.command) + ? { ...action, command: action.command.filter((part) => typeof part === 'string').join(' ') } + : input + publishToolContent( + accumulator, + [ + { + type: 'tool_use', + name: payload.name ?? 'tool', + input: normalizedInput + } + ], + timestamp + ) +} + +export function publishCodexCompletedTool( + accumulator: SessionAccumulator, + payload: Record, + timestamp: unknown +): void { + if (!accumulator.messages.active) { + return + } + const item = asRecord(payload.item) + if (item?.type === 'CommandExecution' || item?.type === 'command_execution') { + const command = Array.isArray(item.command) + ? item.command.filter((part) => typeof part === 'string').join(' ') + : item.command + publishToolContent( + accumulator, + [ + { type: 'tool_use', name: 'shell', input: command }, + { type: 'tool_result', content: item.aggregated_output ?? item.aggregatedOutput } + ], + timestamp + ) + } else if (item?.type === 'FileChange' || item?.type === 'file_change') { + const changes = asRecord(item.changes) ?? {} + for (const [path, value] of Object.entries(changes)) { + const change = asRecord(value) + publishToolContent( + accumulator, + [ + { type: 'tool_use', name: 'apply_patch', input: { path } }, + { type: 'tool_result', content: change?.unified_diff ?? change?.content } + ], + timestamp + ) + } + } +} diff --git a/src/main/ai-vault/session-scanner-omp-subagent-transcripts.ts b/src/main/ai-vault/session-scanner-omp-subagent-transcripts.ts index 57cadebeee0..07f3646b537 100644 --- a/src/main/ai-vault/session-scanner-omp-subagent-transcripts.ts +++ b/src/main/ai-vault/session-scanner-omp-subagent-transcripts.ts @@ -101,6 +101,7 @@ export function withOmpSubagentTranscriptCount( ): ResumableSessionParseState { return { consumeLine: (line) => state.consumeLine(line), + identity: () => state.identity?.() ?? null, clone: () => withOmpSubagentTranscriptCount(state.clone(), transcriptFilePath), touchFile: (file) => state.touchFile(file), finalize: async (platform, options) => { diff --git a/src/main/ai-vault/session-scanner-parse-cache.ts b/src/main/ai-vault/session-scanner-parse-cache.ts index 46fb4754a32..6ebb1a76a2b 100644 --- a/src/main/ai-vault/session-scanner-parse-cache.ts +++ b/src/main/ai-vault/session-scanner-parse-cache.ts @@ -26,6 +26,7 @@ import { import { readResumableTranscript, readWholeTranscript, + requestWholeTranscriptRead, type TranscriptReadStats } from './session-transcript-reader' @@ -104,29 +105,67 @@ export function createSessionParseStats(): SessionParseStats { export async function parseAgentSessionFileCached( candidate: SessionFileCandidate, platform: NodeJS.Platform, - stats?: SessionParseStats + stats?: SessionParseStats, + requireRead?: SessionParseReadRequirement ): Promise { // The whole lookup-read-store sequence runs in the lane: a concurrent parse of // the same path shares this entry's resume point and its message channel. return inSessionParseFileLane(candidate.file.path, () => - parseCachedInLane(candidate, platform, stats) + parseCachedInLane(candidate, platform, stats, requireRead) + ) +} + +/** + * What a caller other than the session list needs out of this parse. + * + * `any`: some bytes must be read. A cursor already at the file's current stat + * is dropped so the reader opens it; one that is merely behind is left alone, + * because an append is a read. + * + * `whole`: the file must be re-read from zero, for a consumer whose own cursor + * covers a span this one does not. + * + * Why it is a parameter and not two calls around this one: the decision reads + * cache state and then changes it, so outside the per-path lane an overlapping + * list parse can store its entry in between and the forced read silently + * degrades to a reuse. + */ +export type SessionParseReadRequirement = 'any' | 'whole' + +/** + * True when this cursor already sits at the transcript's current stat, so a + * parse would reuse the cached fold and read no bytes at all. + */ +function sessionParseCacheCoversTranscript( + candidate: SessionFileCandidate, + platform: NodeJS.Platform +): boolean { + const { file } = candidate + const entry = getSessionParseCacheEntry(file.path) + return ( + entry !== undefined && + entry.platform === platform && + entry.mtimeMs === file.mtimeMs && + (entry.sizeBytes === null || file.sizeBytes === undefined || entry.sizeBytes === file.sizeBytes) ) } async function parseCachedInLane( candidate: SessionFileCandidate, platform: NodeJS.Platform, - stats?: SessionParseStats + stats?: SessionParseStats, + requireRead?: SessionParseReadRequirement ): Promise { const { file } = candidate + if ( + requireRead === 'whole' || + (requireRead === 'any' && sessionParseCacheCoversTranscript(candidate, platform)) + ) { + requestWholeTranscriptRead(file.path) + } const entry = getSessionParseCacheEntry(file.path) - const transcriptUnchanged = - entry !== undefined && - entry.platform === platform && - entry.mtimeMs === file.mtimeMs && - (entry.sizeBytes === null || file.sizeBytes === undefined || entry.sizeBytes === file.sizeBytes) - if (transcriptUnchanged) { + if (entry !== undefined && sessionParseCacheCoversTranscript(candidate, platform)) { if (sidecarUnchanged(entry.sidecar, file.sidecar)) { return reuseCachedSession(candidate, entry, stats) } diff --git a/src/main/ai-vault/session-scanner-primary-parsers.ts b/src/main/ai-vault/session-scanner-primary-parsers.ts index 9783f8a0520..62149920b5a 100644 --- a/src/main/ai-vault/session-scanner-primary-parsers.ts +++ b/src/main/ai-vault/session-scanner-primary-parsers.ts @@ -12,6 +12,7 @@ import type { } from './session-scanner-types' import type { TranscriptMessageSink } from './session-transcript-consumers' import { + accumulatorSessionIdentity, addPreviewContent, createAccumulator, finalizeSession, @@ -205,6 +206,7 @@ function claudeResumeStateFromParseState( ): ResumableSessionParseState { return { consumeLine: (line) => consumeClaudeSessionLine(state, line), + identity: () => accumulatorSessionIdentity(state.accumulator), clone: () => claudeResumeStateFromParseState(cloneClaudeSessionParseState(state)), touchFile: (file) => { state.accumulator.modifiedAt = file.modifiedAt diff --git a/src/main/ai-vault/session-scanner-text-normalization.ts b/src/main/ai-vault/session-scanner-text-normalization.ts index 99f73a93d02..50fc54ab7aa 100644 --- a/src/main/ai-vault/session-scanner-text-normalization.ts +++ b/src/main/ai-vault/session-scanner-text-normalization.ts @@ -1,3 +1,7 @@ +import { sliceAtCodeUnitLimit } from '../../shared/surrogate-safe-text-slice' + +export { sliceAtCodeUnitLimit } + const SESSION_TITLE_TEXT_LIMIT = 96 const SESSION_PREVIEW_TEXT_LIMIT = 220 const ELLIPSIS = '...' @@ -42,15 +46,6 @@ export function normalizePreviewText(value: string): string | null { return finalizeNormalizedText(normalizeStringText(value, SESSION_PREVIEW_TEXT_LIMIT)) } -/** Cut to `limit` UTF-16 code units without splitting a trailing surrogate pair. */ -export function sliceAtCodeUnitLimit(value: string, limit: number): string { - if (value.length <= limit) { - return value - } - const end = limit > 0 && isHighSurrogate(value.charCodeAt(limit - 1)) ? limit - 1 : limit - return value.slice(0, end) -} - function normalizeContentText(value: unknown, limit: number): string | null { if (typeof value === 'string') { return finalizeNormalizedText(normalizeStringText(value, limit)) diff --git a/src/main/ai-vault/session-scanner-types.ts b/src/main/ai-vault/session-scanner-types.ts index b1d480aa944..f4b60270544 100644 --- a/src/main/ai-vault/session-scanner-types.ts +++ b/src/main/ai-vault/session-scanner-types.ts @@ -5,7 +5,10 @@ import type { AiVaultSessionPreviewMessage } from '../../shared/ai-vault-types' import type { ExecutionHostId } from '../../shared/execution-host' -import type { TranscriptMessageSink } from './session-transcript-consumers' +import type { + TranscriptMessageSink, + TranscriptSessionIdentity +} from './session-transcript-consumers' import type { SessionSidecarObservation } from './session-sidecar-stat' export type AiVaultScanOptions = { @@ -103,6 +106,9 @@ export type ResumableSessionParseState = { consumeLineBytes?(line: Buffer): void // Lets a parser terminate an excluded transcript without draining the file. shouldStop?(): boolean + // What the fold knows about the session right now, for a consumer that has to + // commit before the read ends (see TranscriptSessionIdentity). + identity?(): TranscriptSessionIdentity | null clone(): ResumableSessionParseState // Refresh per-scan file metadata (mtime display string) without re-parsing. touchFile(file: FileWithMtime): void diff --git a/src/main/ai-vault/session-transcript-consumers.ts b/src/main/ai-vault/session-transcript-consumers.ts index 6707b298586..7aff8dcf87b 100644 --- a/src/main/ai-vault/session-transcript-consumers.ts +++ b/src/main/ai-vault/session-transcript-consumers.ts @@ -27,12 +27,34 @@ export const NO_TRANSCRIPT_MESSAGES: TranscriptMessageSink = { push: () => undefined } +/** + * What a parser has decoded about the session so far, mid-read. + * + * Provisional by construction: it is read before the file ends, so a title can + * still change and a timestamp can still move. Every field the transcript + * formats put in their opening lines, which is what a consumer that has to + * commit before the read finishes needs to name what it is holding. + */ +export type TranscriptSessionIdentity = { + sessionId: string + cwd: string | null + title: string | null + createdAt: string | null + updatedAt: string | null +} + export type TranscriptReadStart = { candidate: SessionFileCandidate /** `replace`: the whole file is being re-read; `append`: a resumed read. */ mode: 'replace' | 'append' /** Byte offset the messages of this read continue from. */ previousByteOffset: number + /** + * The session identity decoded so far, or null before the parser has an id. + * Called during the read, never here: nothing is decoded yet when a read + * begins. Absent when the read has no resumable parse state to ask. + */ + identity?: () => TranscriptSessionIdentity | null } export type TranscriptReadOutcome = { diff --git a/src/main/ai-vault/session-transcript-reader.ts b/src/main/ai-vault/session-transcript-reader.ts index 228b0c832a3..3fc0ddcc146 100644 --- a/src/main/ai-vault/session-transcript-reader.ts +++ b/src/main/ai-vault/session-transcript-reader.ts @@ -3,7 +3,10 @@ import type { AiVaultSession } from '../../shared/ai-vault-types' import { parseAgentSessionFile, parserPublishesMessages } from './session-scanner-agent-parser' import { consumeCompleteJsonlLines } from './session-scanner-jsonl-reader' import type { ResumableSessionParseState, SessionFileCandidate } from './session-scanner-types' -import type { SessionParseResumePoint } from './session-parse-cache-store' +import { + invalidateSessionParseCacheEntry, + type SessionParseResumePoint +} from './session-parse-cache-store' import { TranscriptMessageChannel } from './session-transcript-channel' const NEWLINE_BYTE = 0x0a @@ -29,6 +32,24 @@ export type ResumableTranscriptRead = { resume: SessionParseResumePoint } +/** + * Ask for the next read of `path` to be a whole-file `replace`. + * + * Why this lives here: a consumer never chooses its own mode. The reader picks + * `append` or `replace` from the resume point the session list left behind, so a + * consumer that declined an append has no way to get the span it missed — with + * an empty index and a warm parse cache, every read arrives as `append`, every + * one is declined, and nothing is ever indexed. Dropping the resume point is the + * one lever that changes the next read's mode, and only the reader's own cache + * owns it. + * + * The cost is a re-parse for the session list too. That is the honest price of a + * second consumer being behind, and it is paid once per file rather than per scan. + */ +export function requestWholeTranscriptRead(path: string): void { + invalidateSessionParseCacheEntry(path) +} + /** * Read an append-only transcript, resuming from `resume` when the file only * grew and the recorded offset still sits on a line boundary. Anything else @@ -70,7 +91,10 @@ export async function readResumableTranscript(args: { channel.beginRead({ candidate: args.candidate, mode: canResume ? 'append' : 'replace', - previousByteOffset: startOffset + previousByteOffset: startOffset, + // Read by a consumer during the read, not here: the fold has decoded + // nothing yet at this point of a whole-file read. + identity: () => state.identity?.() ?? null }) try { const readResult = await consumeCompleteJsonlLines({ diff --git a/src/main/browser/browser-cookie-chromium-scan.ts b/src/main/browser/browser-cookie-chromium-scan.ts index e3bdc6a6409..eb057712a11 100644 --- a/src/main/browser/browser-cookie-chromium-scan.ts +++ b/src/main/browser/browser-cookie-chromium-scan.ts @@ -7,7 +7,7 @@ import { } from './browser-cookie-import-policy' import { prepareStagedCookiesForImport } from './browser-cookie-staged-import' import { chromiumTimestampToUnix, buildChromiumCookieInsertParams } from './browser-cookie-sqlite' -import { chromiumSameSite } from './browser-cookie-validation' +import { databaseSameSite } from './browser-cookie-validation' import { buildUndecryptableWarning, cookieEncryptionVersion, @@ -97,7 +97,8 @@ export function scanChromiumCookieRows( const path = sourceRow.path as string const secure = sourceRow.is_secure === 1n const httpOnly = sourceRow.is_httponly === 1n - const sameSite = chromiumSameSite(Number(sourceRow.samesite ?? 0)) + // Why: pre-samesite schemas and NULL rows follow Chromium's own unspecified fallback. + const sameSite = databaseSameSite(Number(sourceRow.samesite ?? -1)) const expiresUtc = chromiumTimestampToUnix(sourceRow.expires_utc as bigint) const partition = partitionBySourceRow.get(sourceRow)! // Why: cookie values are raw bytes, not UTF-8; latin1 preserves 0x00–0xFF without lossy replacement. diff --git a/src/main/browser/browser-cookie-firefox-import.ts b/src/main/browser/browser-cookie-firefox-import.ts index 60482b30e31..d7ada7e76de 100644 --- a/src/main/browser/browser-cookie-firefox-import.ts +++ b/src/main/browser/browser-cookie-firefox-import.ts @@ -9,7 +9,7 @@ import { cookieImportTarget, type CookieImportOptions } from './browser-cookie-import-pipeline' -import { deriveUrl, firefoxSameSite, type ValidatedCookie } from './browser-cookie-validation' +import { databaseSameSite, deriveUrl, type ValidatedCookie } from './browser-cookie-validation' import type { DetectedBrowser } from './browser-cookie-detection-types' import { diag } from './browser-cookie-import-diagnostics' @@ -108,7 +108,7 @@ export async function importCookiesFromFirefox( path: row.path || '/', secure, httpOnly: row.isHttpOnly === 1, - sameSite: firefoxSameSite(row.sameSite), + sameSite: databaseSameSite(row.sameSite), expirationDate: row.expiry > 0 ? row.expiry : undefined, partition: readFirefoxRowPartition(row, firefoxColumns) }) diff --git a/src/main/browser/browser-cookie-import-test-database.ts b/src/main/browser/browser-cookie-import-test-database.ts index 31cdfc1f157..d3617928fb2 100644 --- a/src/main/browser/browser-cookie-import-test-database.ts +++ b/src/main/browser/browser-cookie-import-test-database.ts @@ -13,7 +13,7 @@ type ChromiumCookieTestRow = { hasCrossSiteAncestor?: 0 | 1 isSecure?: 0 | 1 isHttpOnly?: 0 | 1 - sameSite?: 0 | 1 | 2 | 3 + sameSite?: -1 | 0 | 1 | 2 | 3 | null } export function createChromiumCookieTestDatabase( @@ -38,7 +38,7 @@ export function createChromiumCookieTestDatabase( expires_utc INTEGER NOT NULL, is_secure INTEGER NOT NULL, is_httponly INTEGER NOT NULL, - samesite INTEGER NOT NULL, + samesite INTEGER, source_scheme INTEGER NOT NULL DEFAULT 0, source_port INTEGER NOT NULL DEFAULT -1, last_update_utc INTEGER NOT NULL DEFAULT 0, @@ -75,7 +75,7 @@ export function createChromiumCookieTestDatabase( row.encryptedValue ?? Buffer.alloc(0), row.isSecure ?? 0, row.isHttpOnly ?? 0, - row.sameSite ?? 0, + row.sameSite === undefined ? -1 : row.sameSite, 0, row.hasCrossSiteAncestor ?? 0 ) diff --git a/src/main/browser/browser-cookie-samesite.electron.test.ts b/src/main/browser/browser-cookie-samesite.electron.test.ts new file mode 100644 index 00000000000..4f04f93c72e --- /dev/null +++ b/src/main/browser/browser-cookie-samesite.electron.test.ts @@ -0,0 +1,268 @@ +import { spawnSync } from 'node:child_process' +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { DatabaseSync } from 'node:sqlite' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { build as buildVite } from 'vite' +import { createChromiumCookieTestDatabase } from './browser-cookie-import-test-database' + +type CookieSameSite = 'unspecified' | 'no_restriction' | 'lax' | 'strict' + +type ExpectedCookie = { + name: string + rawSameSite: -1 | 0 | 1 | 2 + secure: boolean + sameSite: CookieSameSite +} + +type JarCookie = Pick + +type ImportResult = { + ok: boolean + reason?: string + summary?: { importedCookies: number; skippedCookies: number } +} + +type FixtureResult = { + step: string + error?: string + beforeCookieCount: number + importResult: ImportResult + afterCookies: JarCookie[] +} + +type SourceShape = { + name: string + samesite: number | null + is_secure: number +} + +const electronBinary = createRequire(import.meta.url)('electron') as string +const fixtureRoots: string[] = [] + +const VALID_COMBINATIONS: readonly ExpectedCookie[] = [ + { + name: 'raw-minus-1-secure-0', + rawSameSite: -1, + secure: false, + sameSite: 'unspecified' + }, + // Ablation C: neither the old decoder nor the null-default regression affects this row. + { + name: 'raw-minus-1-secure-1', + rawSameSite: -1, + secure: true, + sameSite: 'unspecified' + }, + { name: 'raw-0-secure-1', rawSameSite: 0, secure: true, sameSite: 'no_restriction' }, + { name: 'raw-1-secure-0', rawSameSite: 1, secure: false, sameSite: 'lax' }, + { name: 'raw-1-secure-1', rawSameSite: 1, secure: true, sameSite: 'lax' }, + { name: 'raw-2-secure-0', rawSameSite: 2, secure: false, sameSite: 'strict' }, + { name: 'raw-2-secure-1', rawSameSite: 2, secure: true, sameSite: 'strict' } +] + +const REJECTION_CONTROL = { + name: 'raw-0-secure-0', + rawSameSite: 0, + secure: false +} as const + +const NULL_CASE = { + name: 'raw-null-secure-0', + rawSameSite: null, + secure: false, + sameSite: 'unspecified' +} as const + +afterAll(() => { + for (const root of fixtureRoots) { + rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) + } +}) + +function buildFixtureMain(bundlePath: string, resultPath: string, sourceDbPath: string): string { + return ` +const { app, BrowserWindow, session } = require('electron') +const { writeFileSync } = require('node:fs') +const { importCookiesFromBrowser } = require(${JSON.stringify(bundlePath)}) +const resultPath = ${JSON.stringify(resultPath)} +let currentStep = 'starting' + +const mark = (step) => { + currentStep = step + writeFileSync(resultPath, JSON.stringify({ step })) +} + +async function run() { + const timeout = setTimeout(() => { + writeFileSync(resultPath, JSON.stringify({ step: 'timed out after ' + currentStep })) + app.exit(1) + }, 30000) + await app.whenReady() + mark('ready') + const partition = 'persist:samesite-enum-cookie-test' + const targetSession = session.fromPartition(partition) + const window = new BrowserWindow({ show: false, webPreferences: { partition } }) + mark('window created') + await window.loadURL('data:text/html,same-site enum fixture') + mark('window loaded') + const beforeCookieCount = (await targetSession.cookies.get({})).length + + const importResult = await importCookiesFromBrowser( + { + family: 'chrome', + label: 'Google Chrome', + cookiesPath: ${JSON.stringify(sourceDbPath)}, + profiles: [], + selectedProfile: '' + }, + partition + ) + mark('import finished') + + const afterCookies = (await targetSession.cookies.get({})) + .filter((cookie) => cookie.name.startsWith('raw-')) + .map((cookie) => ({ + name: cookie.name, + sameSite: cookie.sameSite, + secure: cookie.secure + })) + clearTimeout(timeout) + writeFileSync(resultPath, JSON.stringify({ + step: currentStep, + beforeCookieCount, + importResult, + afterCookies + })) + window.destroy() + app.exit(0) +} + +run().catch((error) => { + writeFileSync(resultPath, JSON.stringify({ step: currentStep, error: String(error?.stack || error) })) + app.exit(1) +}) +` +} + +function readSourceShape(sourceDbPath: string): SourceShape[] { + const db = new DatabaseSync(sourceDbPath, { readOnly: true }) + try { + return db + .prepare('SELECT name, samesite, is_secure FROM cookies ORDER BY rowid') + .all() as SourceShape[] + } finally { + db.close() + } +} + +async function runFixture(): Promise<{ fixture: FixtureResult; sourceShape: SourceShape[] }> { + const root = mkdtempSync(join(tmpdir(), 'orca-samesite-enum-')) + fixtureRoots.push(root) + const bundlePath = join(root, 'cookie-import-samesite.cjs') + const bundleEntryPath = join(root, 'cookie-import-samesite.ts') + const resultPath = join(root, 'result.json') + const fixturePath = join(root, 'main.cjs') + const sourceDbPath = join(root, 'source-cookies.db') + const rows = [REJECTION_CONTROL, ...VALID_COMBINATIONS, NULL_CASE].map( + ({ name, rawSameSite, secure }) => ({ + domain: '.samesite.example', + name, + value: 'synthetic-value', + isSecure: secure ? (1 as const) : (0 as const), + sameSite: rawSameSite + }) + ) + createChromiumCookieTestDatabase(sourceDbPath, rows).close() + const sourceShape = readSourceShape(sourceDbPath) + writeFileSync( + bundleEntryPath, + `export { importCookiesFromBrowser } from ${JSON.stringify(join(process.cwd(), 'src/main/browser/browser-cookie-import.ts'))}` + ) + await buildVite({ + configFile: false, + logLevel: 'silent', + build: { + emptyOutDir: false, + lib: { + entry: bundleEntryPath, + formats: ['cjs'], + fileName: () => 'cookie-import-samesite.cjs' + }, + outDir: root, + target: 'node20', + rollupOptions: { external: ['electron', /^node:/] } + } + }) + writeFileSync(fixturePath, buildFixtureMain(bundlePath, resultPath, sourceDbPath)) + const { ELECTRON_RUN_AS_NODE: _electronRunAsNode, ...env } = process.env + const electronArgs = [fixturePath, `--user-data-dir=${join(root, 'profile')}`] + const executable = process.platform === 'linux' ? 'xvfb-run' : electronBinary + const args = + process.platform === 'linux' + ? ['--auto-servernum', electronBinary, ...electronArgs, '--no-sandbox'] + : electronArgs + const run = spawnSync(executable, args, { + encoding: 'utf8', + env: { ...env, ORCA_BACKGROUND_LAUNCH: '1' }, + timeout: 90_000 + }) + const fixtureResult = existsSync(resultPath) ? readFileSync(resultPath, 'utf8') : 'no result' + expect(run.error).toBeUndefined() + expect(run.status, `${fixtureResult}\n${run.stdout}\n${run.stderr}`).toBe(0) + return { fixture: JSON.parse(fixtureResult) as FixtureResult, sourceShape } +} + +describe('Chromium SameSite storage enum import', () => { + let fixture: FixtureResult + let sourceShape: SourceShape[] + + beforeAll(async () => { + ;({ fixture, sourceShape } = await runFixture()) + }, 120_000) + + it('runs the real Chromium import against the complete synthetic matrix', () => { + expect(fixture.step).toBe('import finished') + expect(fixture.beforeCookieCount).toBe(0) + expect(fixture.importResult.ok).toBe(true) + expect(sourceShape).toEqual( + [REJECTION_CONTROL, ...VALID_COMBINATIONS, NULL_CASE].map( + ({ name, rawSameSite, secure }) => ({ + name, + samesite: rawSameSite, + is_secure: secure ? 1 : 0 + }) + ) + ) + }) + + it.each(VALID_COMBINATIONS)( + 'imports $name with the decoded SameSite and authored Secure flag', + ({ name, sameSite, secure }) => { + expect(fixture.afterCookies.find((cookie) => cookie.name === name)).toEqual({ + name, + sameSite, + secure + }) + } + ) + + it('rejects the synthetic SameSite=None insecure control and continues later writes', () => { + // Chromium refuses this shape, so real profiles cannot contain it. Keeping the synthetic row + // proves the fixture can observe rejection instead of making every presence assertion vacuous. + expect( + fixture.afterCookies.find((cookie) => cookie.name === REJECTION_CONTROL.name) + ).toBeUndefined() + expect(fixture.afterCookies.find((cookie) => cookie.name === 'raw-2-secure-1')).toBeDefined() + }) + + it('imports a null SameSite column as unspecified without changing Secure', () => { + expect(fixture.afterCookies.find((cookie) => cookie.name === NULL_CASE.name)).toEqual({ + name: NULL_CASE.name, + sameSite: NULL_CASE.sameSite, + secure: NULL_CASE.secure + }) + }) +}) diff --git a/src/main/browser/browser-cookie-validation.test.ts b/src/main/browser/browser-cookie-validation.test.ts new file mode 100644 index 00000000000..d7b065beeda --- /dev/null +++ b/src/main/browser/browser-cookie-validation.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from 'vitest' +import { databaseSameSite } from './browser-cookie-validation' + +describe('databaseSameSite', () => { + it.each([ + { raw: -1, expected: 'unspecified' }, + { raw: 0, expected: 'no_restriction' }, + { raw: 1, expected: 'lax' }, + { raw: 2, expected: 'strict' }, + { raw: 3, expected: 'unspecified' }, + // Why: 256 is Firefox's nsICookie SAMESITE_UNSET, written for every cookie with no SameSite + // attribute -- the most common shape in a modern Firefox profile. It reaches the default arm, + // so without this case the decoder's busiest Firefox input would be untested. + { raw: 256, expected: 'unspecified' }, + { raw: 99, expected: 'unspecified' }, + { raw: 1.5, expected: 'unspecified' } + ] as const)('decodes $raw as $expected', ({ raw, expected }) => { + expect(databaseSameSite(raw)).toBe(expected) + }) + + // Why: pre-v10 Firefox rows carry NULL, and the Chromium scan feeds `?? -1`. Both arrive here as + // a non-integer rather than a number, and both must be unspecified rather than None (0). + it.each([ + { label: 'null', raw: null }, + { label: 'undefined', raw: undefined }, + { label: 'NaN', raw: Number.NaN } + ])('decodes $label as unspecified', ({ raw }) => { + expect(databaseSameSite(raw as unknown as number)).toBe('unspecified') + }) +}) diff --git a/src/main/browser/browser-cookie-validation.ts b/src/main/browser/browser-cookie-validation.ts index 6ae543245ef..7f08f713f2e 100644 --- a/src/main/browser/browser-cookie-validation.ts +++ b/src/main/browser/browser-cookie-validation.ts @@ -25,21 +25,16 @@ export type ValidatedCookie = ImportedCookieFields & { partition: SourcePartitionRead } -// Why: Chromium's CookieSameSiteForStorage enum (0=Unspecified,1=None,2=Lax,3=Strict) differs from Firefox's numbering. -export function chromiumSameSite(raw: number): 'unspecified' | 'no_restriction' | 'lax' | 'strict' { - switch (raw) { - case 1: - return 'no_restriction' - case 2: - return 'lax' - case 3: - return 'strict' - default: - return 'unspecified' - } -} - -export function firefoxSameSite(raw: number): 'unspecified' | 'no_restriction' | 'lax' | 'strict' { +// Chromium stores net::CookieSameSite unchanged; see net/cookies/cookie_constants.h and +// net/extras/sqlite/sqlite_persistent_cookie_store.cc (-1 unspecified, 0 None, 1 Lax, 2 Strict; +// 3 is the deprecated EXTENDED value Chromium itself folds to unspecified). +// Firefox's moz_cookies OVERLAPS on 1=Lax and 2=Strict but its domain is wider, so the default arm +// is load-bearing for it, not incidental: 256 (nsICookie SAMESITE_UNSET) is what modern Firefox +// writes for every cookie with no SameSite attribute, NULL appears on pre-v10 rows, and 0 means +// explicit None OR a legacy unset row the schema-15 migration left behind — the two are not +// distinguishable in the column. Every one of those must land on unspecified, so do NOT make this +// switch exhaustive or drop the default without re-checking both browsers' real value domains. +export function databaseSameSite(raw: number): 'unspecified' | 'no_restriction' | 'lax' | 'strict' { switch (raw) { case 0: return 'no_restriction' @@ -56,7 +51,7 @@ export function normalizeSameSite( raw: unknown ): 'unspecified' | 'no_restriction' | 'lax' | 'strict' { if (typeof raw === 'number') { - return chromiumSameSite(raw) + return databaseSameSite(raw) } if (typeof raw !== 'string') { return 'unspecified' diff --git a/src/main/claude/claude-slash-command-catalog.test.ts b/src/main/claude/claude-slash-command-catalog.test.ts index 20d79f9f53d..f4374e52e4f 100644 --- a/src/main/claude/claude-slash-command-catalog.test.ts +++ b/src/main/claude/claude-slash-command-catalog.test.ts @@ -86,8 +86,8 @@ it('accepts descriptor reloads, removing old skills while retaining terminal fil } expect(catalog.observe(reload)).toBe(true) expect(catalog.commands).toEqual([ - { name: 'clear', kind: 'command' }, - { name: 'new-skill', kind: 'skill' } + { name: 'clear', kind: 'command', description: 'Clear' }, + { name: 'new-skill', kind: 'skill', description: 'New' } ]) expect(catalog.observe(reload)).toBe(false) expect(catalog.observe({ ...reload, commands: [] })).toBe(true) @@ -130,3 +130,146 @@ it('publishes classification becoming authoritative even when the name and kind expect(catalog.observe(init({ slash_commands: ['clear'], skills: [] }))).toBe(true) expect(catalog.commands).toEqual([{ name: 'clear', kind: 'command' }]) }) + +it('keeps the description and argument hint a descriptor report authored', () => { + const catalog = new ClaudeSlashCommandCatalog(undefined, { + commands: [ + { name: 'goal', description: 'Set or view the goal', argumentHint: '' }, + { name: 'quiet', description: '', argumentHint: '' } + ] + }) + expect(catalog.commands).toEqual([ + { + name: 'goal', + kind: 'command', + kindUnspecified: true, + description: 'Set or view the goal', + argumentHint: '' + }, + { name: 'quiet', kind: 'command', kindUnspecified: true } + ]) +}) + +it('bounds the row text a provider can put in the picker', () => { + const catalog = new ClaudeSlashCommandCatalog(undefined, { + commands: [ + { name: 'long', description: 'x'.repeat(201), argumentHint: 'y'.repeat(101) }, + { name: 'wrong-type', description: 42, argumentHint: { text: 'no' } }, + { name: 'blank', description: ' ' }, + { name: 'long-whitespace', description: `Visible${' '.repeat(201)}` }, + { name: 'wrapped', description: 'first line\n second line' } + ] + }) + expect(catalog.commands).toEqual([ + { name: 'long', kind: 'command', kindUnspecified: true }, + { name: 'wrong-type', kind: 'command', kindUnspecified: true }, + { name: 'blank', kind: 'command', kindUnspecified: true }, + { name: 'long-whitespace', kind: 'command', kindUnspecified: true }, + { + name: 'wrapped', + kind: 'command', + kindUnspecified: true, + description: 'first line second line' + } + ]) +}) + +it('does not let malformed descriptor names consume the command detail budget', () => { + const catalog = new ClaudeSlashCommandCatalog(undefined, { + commands: [ + ...Array.from({ length: 512 }, (_, index) => ({ + name: `invalid name ${index}`, + description: 'Rejected with its name' + })), + { name: 'goal', description: 'Set or view the goal', argumentHint: '' } + ] + }) + expect(catalog.commands).toEqual([ + { + name: 'goal', + kind: 'command', + kindUnspecified: true, + description: 'Set or view the goal', + argumentHint: '' + } + ]) +}) + +it('combines non-empty fields from duplicate descriptors without discarding earlier text', () => { + const catalog = new ClaudeSlashCommandCatalog(undefined, { + commands: [ + { name: 'goal', description: 'Set or view the goal' }, + { name: 'goal', argumentHint: '' } + ] + }) + expect(catalog.commands).toEqual([ + { + name: 'goal', + kind: 'command', + kindUnspecified: true, + description: 'Set or view the goal', + argumentHint: '' + } + ]) +}) + +it('carries descriptor text across the name-only stream init that classifies it', () => { + const catalog = new ClaudeSlashCommandCatalog(undefined, { + commands: [ + { name: 'clear', description: 'Clear conversation' }, + { name: 'ref-oss', description: 'A skill' } + ] + }) + expect(catalog.observe(init({ slash_commands: ['clear', 'ref-oss'], skills: ['ref-oss'] }))).toBe( + true + ) + expect(catalog.commands).toEqual([ + { name: 'clear', kind: 'command', description: 'Clear conversation' }, + { name: 'ref-oss', kind: 'skill', description: 'A skill' } + ]) +}) + +it('reports a description-only change and lets a later report drop the text', () => { + const catalog = new ClaudeSlashCommandCatalog(init({ slash_commands: ['clear'], skills: [] })) + expect(catalog.commands).toEqual([{ name: 'clear', kind: 'command' }]) + const changed = { + type: 'system', + subtype: 'commands_changed', + commands: [{ name: 'clear', description: 'Clear conversation history' }] + } + expect(catalog.observe(changed)).toBe(true) + expect(catalog.commands).toEqual([ + { name: 'clear', kind: 'command', description: 'Clear conversation history' } + ]) + expect(catalog.observe(changed)).toBe(false) + expect(catalog.observe({ ...changed, commands: [{ name: 'clear' }] })).toBe(true) + expect(catalog.commands).toEqual([{ name: 'clear', kind: 'command' }]) +}) + +it('describes nothing when the session reported names only', () => { + expect(readClaudeSlashCommands(init())).toEqual([ + { name: 'clear', kind: 'command' }, + { name: 'ref-oss', kind: 'skill' }, + { name: 'opsx:apply', kind: 'command' } + ]) + expect(new ClaudeSlashCommandCatalog(init()).commands).toEqual([ + { name: 'clear', kind: 'command' }, + { name: 'ref-oss', kind: 'skill' }, + { name: 'opsx:apply', kind: 'command' } + ]) +}) + +it('still hides terminal-only names however well the provider describes them', () => { + const catalog = new ClaudeSlashCommandCatalog(init()) + expect( + catalog.observe({ + type: 'system', + subtype: 'commands_changed', + commands: [ + { name: 'doctor', description: 'Diagnose the CLI install' }, + { name: 'ref-oss', description: 'A skill' } + ] + }) + ).toBe(true) + expect(catalog.commands).toEqual([{ name: 'ref-oss', kind: 'skill', description: 'A skill' }]) +}) diff --git a/src/main/claude/claude-slash-command-catalog.ts b/src/main/claude/claude-slash-command-catalog.ts index b1f65d93d50..2a4d91260f0 100644 --- a/src/main/claude/claude-slash-command-catalog.ts +++ b/src/main/claude/claude-slash-command-catalog.ts @@ -3,6 +3,16 @@ import type { AgentSessionSlashCommand } from '../../shared/agent-session-wire' // Stream init carries name arrays; control initialization and reloads carry descriptors. const MAX_COMMANDS = 512 const MAX_NAME_LENGTH = 200 +const MAX_DESCRIPTION_LENGTH = 200 +const MAX_ARGUMENT_HINT_LENGTH = 100 + +/** The provider's own row text for one command, absent when it reported none. */ +type CommandDetail = Pick + +function commandName(value: unknown): string | undefined { + const name = typeof value === 'string' ? value.trim() : '' + return name.length > 0 && name.length <= MAX_NAME_LENGTH && !/\s/u.test(name) ? name : undefined +} function names(value: unknown): string[] { if (!Array.isArray(value)) { @@ -13,20 +23,61 @@ function names(value: unknown): string[] { if (seen.size >= MAX_COMMANDS) { break } - const name = typeof entry === 'string' ? entry.trim() : '' - if (name.length > 0 && name.length <= MAX_NAME_LENGTH && !/\s/u.test(name)) { + const name = commandName(entry) + if (name !== undefined) { seen.add(name) } } return [...seen] } -function descriptorNames(value: unknown): string[] { - return names( - Array.isArray(value) - ? value.map((entry) => (entry !== null && typeof entry === 'object' ? entry.name : undefined)) - : [] - ) +/** A single picker row's worth of provider text: unusable values are dropped, not truncated. */ +function rowText(value: unknown, maxLength: number): string | undefined { + if (typeof value !== 'string' || value.length > maxLength) { + return undefined + } + const collapsed = value.replace(/\s+/gu, ' ').trim() + return collapsed.length > 0 && collapsed.length <= maxLength ? collapsed : undefined +} + +function descriptorCatalog(value: unknown): { + names: string[] + details: Map +} { + const names: string[] = [] + const seen = new Set() + const details = new Map() + if (!Array.isArray(value)) { + return { names, details } + } + for (const entry of value) { + if (seen.size >= MAX_COMMANDS) { + break + } + if (entry === null || typeof entry !== 'object') { + continue + } + const name = commandName(entry.name) + if (name === undefined) { + continue + } + if (!seen.has(name)) { + seen.add(name) + names.push(name) + } + const previous = details.get(name) + const description = previous?.description ?? rowText(entry.description, MAX_DESCRIPTION_LENGTH) + const argumentHint = + previous?.argumentHint ?? rowText(entry.argumentHint, MAX_ARGUMENT_HINT_LENGTH) + if (description === undefined && argumentHint === undefined) { + continue + } + details.set(name, { + ...(description === undefined ? {} : { description }), + ...(argumentHint === undefined ? {} : { argumentHint }) + }) + } + return { names, details } } function carriesCommandCatalog(message: Record): boolean { @@ -56,6 +107,7 @@ export class ClaudeSlashCommandCatalog { private hasSkillClassification = false private hidden = new Set() private commandNames = new Set() + private details = new Map() constructor(initMessage?: Record, initialization?: unknown) { // SessionStart can prove acquisition before the first stream init exists. @@ -65,11 +117,15 @@ export class ClaudeSlashCommandCatalog { 'commands' in initialization && Array.isArray(initialization.commands) ) { - this.entries = descriptorNames(initialization.commands).map((name) => ({ - name, - kind: 'command', - kindUnspecified: true - })) + const catalog = descriptorCatalog(initialization.commands) + this.details = catalog.details + this.entries = this.describe( + catalog.names.map((name) => ({ + name, + kind: 'command', + kindUnspecified: true + })) + ) } if (initMessage) { this.observe(initMessage) @@ -80,13 +136,18 @@ export class ClaudeSlashCommandCatalog { return this.entries } + /** Provider row text, carried across the name-only frames that never restate it. */ + private describe(entries: AgentSessionSlashCommand[]): AgentSessionSlashCommand[] { + return entries.map((entry) => ({ ...entry, ...this.details.get(entry.name) })) + } + /** True when this frame replaced the catalog with a different one. */ observe(message: Record): boolean { let next: AgentSessionSlashCommand[] if (carriesCommandCatalog(message)) { this.hasSkillClassification = true this.hidden = new Set(names(message.terminal_slash_commands)) - next = readClaudeSlashCommands(message) + next = this.describe(readClaudeSlashCommands(message)) this.commandNames = new Set( next.filter((entry) => entry.kind === 'command').map((entry) => entry.name) ) @@ -95,13 +156,17 @@ export class ClaudeSlashCommandCatalog { message.subtype === 'commands_changed' && Array.isArray(message.commands) ) { - next = descriptorNames(message.commands) - .filter((name) => !this.hidden.has(name)) - .map((name) => - this.hasSkillClassification - ? { name, kind: this.commandNames.has(name) ? 'command' : 'skill' } - : { name, kind: 'command', kindUnspecified: true } - ) + const catalog = descriptorCatalog(message.commands) + this.details = catalog.details + next = this.describe( + catalog.names + .filter((name) => !this.hidden.has(name)) + .map((name) => + this.hasSkillClassification + ? { name, kind: this.commandNames.has(name) ? 'command' : 'skill' } + : { name, kind: 'command', kindUnspecified: true } + ) + ) } else { return false } @@ -112,7 +177,9 @@ export class ClaudeSlashCommandCatalog { (entry, index) => entry.name === this.entries?.[index]?.name && entry.kind === this.entries?.[index]?.kind && - entry.kindUnspecified === this.entries?.[index]?.kindUnspecified + entry.kindUnspecified === this.entries?.[index]?.kindUnspecified && + entry.description === this.entries?.[index]?.description && + entry.argumentHint === this.entries?.[index]?.argumentHint ) ) { return false diff --git a/src/main/claude/claude-structured-item-translation.ts b/src/main/claude/claude-structured-item-translation.ts index 1c1673b59cd..0fdb231f6ef 100644 --- a/src/main/claude/claude-structured-item-translation.ts +++ b/src/main/claude/claude-structured-item-translation.ts @@ -179,6 +179,7 @@ export function claudeToolBody(input: { kind: 'tool-call', name: input.tool.name, input: input.tool.input, + callId: input.tool.id, state: input.result ? (input.result.failed ? 'failed' : 'completed') : 'running', ...(input.result ? { output: boundInlineText(input.result.output, DEFAULT_JOURNAL_PAYLOAD_LIMITS).bounded } diff --git a/src/main/claude/claude-structured-journal-translation.test.ts b/src/main/claude/claude-structured-journal-translation.test.ts index 050fccc42b6..7a8ecf54344 100644 --- a/src/main/claude/claude-structured-journal-translation.test.ts +++ b/src/main/claude/claude-structured-journal-translation.test.ts @@ -528,6 +528,7 @@ describe('Claude structured journal translation', () => { expect(keyed.get('orca:claude-tool%3Aclaude-session%3Atool-1')).toMatchObject({ kind: 'tool-call', name: 'Bash', + callId: 'tool-1', state: 'completed', output: { head: 'a.ts\nb.ts', truncated: false } }) @@ -546,6 +547,7 @@ describe('Claude structured journal translation', () => { expect(state.items.at(-1)?.body).toMatchObject({ kind: 'tool-call', name: 'tool', + callId: 'tool-1', input: null, output: { head: 'done again' } }) @@ -567,8 +569,11 @@ describe('Claude structured journal translation', () => { translator.handle(message('assistant', 'assistant-thinking', [{ type: 'thinking', thinking }])) expect(state.items.at(-1)?.body).toEqual({ - kind: 'status', - text: boundInlineText(thinking, DEFAULT_JOURNAL_PAYLOAD_LIMITS).text + kind: 'message', + role: 'reasoning', + blocks: [ + { type: 'text', text: boundInlineText(thinking, DEFAULT_JOURNAL_PAYLOAD_LIMITS).text } + ] }) }) @@ -606,6 +611,7 @@ describe('Claude structured journal translation', () => { ]) expect(state.items[0]?.body).toMatchObject({ kind: 'tool-call', + callId: 'tool-1', state: 'completed', output: { head: 'done' } }) diff --git a/src/main/claude/claude-structured-journal-translation.ts b/src/main/claude/claude-structured-journal-translation.ts index 478645d62ed..8b71149cba2 100644 --- a/src/main/claude/claude-structured-journal-translation.ts +++ b/src/main/claude/claude-structured-journal-translation.ts @@ -180,8 +180,11 @@ export function createClaudeJournalTranslator( const thinking = claudeThinkingText(outputEnvelope) if (thinking) { deps.sink.appendItem(claudeThinkingIdentity(envelope.sessionId, envelope.uuid), { - kind: 'status', - text: boundInlineText(thinking, DEFAULT_JOURNAL_PAYLOAD_LIMITS).text + kind: 'message', + role: 'reasoning', + blocks: [ + { type: 'text', text: boundInlineText(thinking, DEFAULT_JOURNAL_PAYLOAD_LIMITS).text } + ] }) changed = true } diff --git a/src/main/claude/claude-structured-model-preflight.test.ts b/src/main/claude/claude-structured-model-preflight.test.ts new file mode 100644 index 00000000000..e4f5d00b196 --- /dev/null +++ b/src/main/claude/claude-structured-model-preflight.test.ts @@ -0,0 +1,130 @@ +import { describe, expect, it } from 'vitest' +import { AgentSessionOptionRejectedError } from '../native-chat/agent-session-wire/structured-agent-session-option-error' +import { + restoreClaudeStructuredSessionOptions, + setClaudeStructuredOption +} from './claude-structured-options' +import type { ClaudeSession } from './claude-structured-session-state' + +/** Verbatim row shapes from Claude Code 2.1.260's list_models response. */ +const DEFAULT_ROW = { value: 'default', resolvedModel: 'claude-opus-5', displayName: 'Default' } +const SONNET = { value: 'sonnet', resolvedModel: 'claude-sonnet-5', displayName: 'Sonnet' } +const HAIKU = { + value: 'haiku', + resolvedModel: 'claude-haiku-4-5-20251001', + displayName: 'Haiku' +} + +function sessionWith(catalog: readonly Record[] | 'unavailable') { + const calls: string[] = [] + return { + session: { + options: new Map(), + reportedOptions: {} as { model?: string; effort?: string }, + optionMutationSequence: 0, + reportedModelMutation: 0, + confirmedOptions: new Set(), + restoreSkippedOptions: new Set(), + connection: { + supportedModels: async () => { + calls.push('list_models') + if (catalog === 'unavailable') { + throw new Error('this CLI predates list_models') + } + return [...catalog] + }, + setModel: async (model: string) => { + calls.push(`set_model:${model}`) + } + } + } as unknown as ClaudeSession, + calls + } +} + +describe('Claude model pre-flight against the catalog the CLI listed', () => { + it('refuses a model the provider does not list', async () => { + const { session, calls } = sessionWith([DEFAULT_ROW, SONNET, HAIKU]) + + await expect( + setClaudeStructuredOption(session, { key: 'model', value: 'not-a-real-model-xyz' }, undefined) + ).rejects.toBeInstanceOf(AgentSessionOptionRejectedError) + // Measured on Claude Code 2.1.260: set_model resolves for an unlisted id and + // every later turn returns is_error with zero tokens. Nothing undoes the + // write, so the refusal has to land before it. + expect(calls).toEqual(['list_models']) + expect(session.options.has('model')).toBe(false) + }) + + it('refuses an unlisted model replayed by restore, and skips it', async () => { + // Needs no user error: a model valid when it was persisted can be retired. + const { session, calls } = sessionWith([DEFAULT_ROW, SONNET]) + session.options.set('model', 'claude-opus-4-retired') + + await restoreClaudeStructuredSessionOptions(session, undefined) + + expect(calls).toEqual(['list_models']) + expect(session.options.has('model')).toBe(false) + expect([...session.restoreSkippedOptions]).toEqual(['model']) + }) + + it('applies a model the provider lists', async () => { + const { session, calls } = sessionWith([DEFAULT_ROW, SONNET, HAIKU]) + + await expect( + setClaudeStructuredOption(session, { key: 'model', value: 'haiku' }, undefined) + ).resolves.toEqual({ model: 'haiku' }) + expect(calls).toEqual(['list_models', 'set_model:haiku']) + }) + + it('applies a resolved model id the catalog carries only under its alias', async () => { + const { session, calls } = sessionWith([DEFAULT_ROW, SONNET]) + + await expect( + setClaudeStructuredOption(session, { key: 'model', value: 'claude-sonnet-5' }, undefined) + ).resolves.toEqual({ model: 'claude-sonnet-5' }) + expect(calls).toEqual(['list_models', 'set_model:claude-sonnet-5']) + }) + + it('refuses nothing when list_models is unavailable', async () => { + // A CLI predating list_models would otherwise have every model refused, and + // restore swallows the rejection, so the user's pick would vanish silently. + const { session, calls } = sessionWith('unavailable') + + await expect( + setClaudeStructuredOption(session, { key: 'model', value: 'sonnet' }, undefined) + ).resolves.toEqual({ model: 'sonnet' }) + expect(calls).toEqual(['list_models', 'set_model:sonnet']) + }) + + it('refuses nothing when the listed catalog is empty', async () => { + // An empty answer identifies no model, so it is not evidence against one. + const { session, calls } = sessionWith([]) + + await expect( + setClaudeStructuredOption(session, { key: 'model', value: 'sonnet' }, undefined) + ).resolves.toEqual({ model: 'sonnet' }) + expect(calls).toEqual(['list_models', 'set_model:sonnet']) + }) + + it('refuses nothing when the catalog carries only the synthetic default row', async () => { + // listedModels drops that row, leaving a list that identifies no model. + const { session, calls } = sessionWith([DEFAULT_ROW]) + + await expect( + setClaudeStructuredOption(session, { key: 'model', value: 'sonnet' }, undefined) + ).resolves.toEqual({ model: 'sonnet' }) + expect(calls).toEqual(['list_models', 'set_model:sonnet']) + }) + + it('leaves a restored model the provider lists in place', async () => { + const { session, calls } = sessionWith([DEFAULT_ROW, SONNET]) + session.options.set('model', 'sonnet') + + await restoreClaudeStructuredSessionOptions(session, undefined) + + expect(calls).toEqual(['list_models', 'set_model:sonnet']) + expect(session.options.get('model')).toBe('sonnet') + expect([...session.restoreSkippedOptions]).toEqual([]) + }) +}) diff --git a/src/main/claude/claude-structured-options.test.ts b/src/main/claude/claude-structured-options.test.ts index 2375df12d93..1bfae10b592 100644 --- a/src/main/claude/claude-structured-options.test.ts +++ b/src/main/claude/claude-structured-options.test.ts @@ -6,7 +6,12 @@ import { ClaudeSlashCommandCatalog } from './claude-slash-command-catalog' function sessionFor(setModel: ClaudeSession['connection']['setModel']): ClaudeSession { return { - connection: { setModel } as ClaudeSession['connection'], + // An empty catalog identifies no model, so the pre-flight refuses nothing and + // this stays a test about fencing. + connection: { + setModel, + supportedModels: async (): Promise => [] + } as ClaudeSession['connection'], providerSessionId: 'provider-session', claudeConfigDir: '/accounts/claude', leafUuid: null, diff --git a/src/main/claude/claude-structured-options.ts b/src/main/claude/claude-structured-options.ts index 3d1377b12c6..7f607755563 100644 --- a/src/main/claude/claude-structured-options.ts +++ b/src/main/claude/claude-structured-options.ts @@ -5,6 +5,7 @@ import { isAgentSessionOptionRejectedError } from '../native-chat/agent-session-wire/structured-agent-session-option-error' import { + claudeCatalogAdmitsModel, readClaudeCurrentModel, readClaudeModelEffortLevels, readClaudeSettingsEffort @@ -66,6 +67,13 @@ export async function setClaudeStructuredOption( ) } } + // set_model resolves for a model the provider never lists and the session then + // fails every turn with zero tokens, so the acceptance proves nothing and only + // the catalog does. Restore replays a pick the provider may since have retired, + // which reaches here with no user error at all. + if (input.key === 'model' && !(await claudeCatalogAdmitsModel(session, input.value, timeoutMs))) { + throw new AgentSessionOptionRejectedError(`claude does not list a model named ${input.value}`) + } const modelWasConfirmed = readClaudeCurrentModel(session).confirmed const mutationSequence = ++session.optionMutationSequence // Only a model write can stale the model report — an effort or permission-mode diff --git a/src/main/claude/claude-structured-session-adapter-turns.test.ts b/src/main/claude/claude-structured-session-adapter-turns.test.ts index fc5eaa6b66e..00248b09f12 100644 --- a/src/main/claude/claude-structured-session-adapter-turns.test.ts +++ b/src/main/claude/claude-structured-session-adapter-turns.test.ts @@ -80,8 +80,11 @@ describe('ClaudeStructuredSessionAdapter turns and controls', () => { await expect( adapter.setOption({ sessionId: 'session-1', key: 'model', value: 'sonnet', fence: 7 }) ).resolves.toEqual({ model: 'sonnet' }) - expect(claude.connections[0].calls.slice(-2)).toEqual([ + // The model write pre-flights the catalog first; this CLI lists nothing, which + // identifies no model and so refuses none. + expect(claude.connections[0].calls.slice(-3)).toEqual([ { subtype: 'interrupt', params: {} }, + { subtype: 'list_models' }, { subtype: 'set_model', params: { model: 'sonnet' } } ]) diff --git a/src/main/claude/claude-structured-session-commands.test.ts b/src/main/claude/claude-structured-session-commands.test.ts index 1b2fb6bde31..29f2bcf4aa7 100644 --- a/src/main/claude/claude-structured-session-commands.test.ts +++ b/src/main/claude/claude-structured-session-commands.test.ts @@ -55,8 +55,14 @@ it.each([ const adapter = adapterFor(claude) try { await adapter.acquire({ identity: identityFor(), fence: 7, spawnToken: 'spawn-9' }) + const described = commands[0]?.description expect(adapter.readCommands('session-1')).toEqual( - commands.map(({ name }) => ({ name, kind: 'command', kindUnspecified: true })) + commands.map(({ name, description }) => ({ + name, + kind: 'command', + kindUnspecified: true, + ...(description ? { description } : {}) + })) ) expect(claude.connections[0].sent).toEqual([]) expect(claude.connections[0].calls.map(({ subtype }) => subtype)).toEqual([ @@ -70,7 +76,10 @@ it.each([ slash_commands: ['project:check'], skills: ['project:check'] }) - expect(adapter.readCommands('session-1')).toEqual([{ name: 'project:check', kind: 'skill' }]) + // The stream init classifies the name; the control seed's text survives it. + expect(adapter.readCommands('session-1')).toEqual([ + { name: 'project:check', kind: 'skill', ...(described ? { description: described } : {}) } + ]) } finally { await adapter.closeSession('session-1') } diff --git a/src/main/claude/claude-structured-session-options.ts b/src/main/claude/claude-structured-session-options.ts index afb4fd65076..2385f362c2a 100644 --- a/src/main/claude/claude-structured-session-options.ts +++ b/src/main/claude/claude-structured-session-options.ts @@ -149,6 +149,28 @@ export async function readClaudeModelEffortLevels( } } +/** + * Whether the catalog admits the model, matched by alias or resolved id so a pick + * stored as either one is found. The permissive case lives here rather than at the + * call site: every caller must treat an unidentified catalog the same way, and one + * that forgot would refuse every model on a CLI that cannot answer. + */ +export async function claudeCatalogAdmitsModel( + session: ClaudeSession, + modelId: string, + timeoutMs: number | undefined +): Promise { + const catalog = await session.connection.supportedModels({ timeoutMs }).catch(() => null) + const models = listedModels(catalog ? { models: catalog } : null) + // An empty list identifies no model, so it is not evidence against one — a live + // CLI predating `list_models` would otherwise have every model refused under it. + // Do not turn this into a refusal. + return ( + models.length === 0 || + models.some((model) => model.id === modelId || model.resolvedModel === modelId) + ) +} + export async function readClaudeStructuredSessionOptions( session: ClaudeSession, timeoutMs: number | undefined diff --git a/src/main/codex/codex-config-mirror.ts b/src/main/codex/codex-config-mirror.ts index 0b0e66c35be..d84a5bea542 100644 --- a/src/main/codex/codex-config-mirror.ts +++ b/src/main/codex/codex-config-mirror.ts @@ -93,12 +93,14 @@ export function syncSystemConfigIntoManagedCodexHome( } // Why: the baseline advances only after a successful mirror; recording an // unpromoted runtime change as Orca-written would strand it forever. - snapshotCodexRuntimeSettingsBaseline( - homes.runtimeHomePath, - new Map( + snapshotCodexRuntimeSettingsBaseline(homes.runtimeHomePath, { + conflicts: new Map( [...promotionPlan.conflicts].filter(([key]) => mirrorResult.preservedConflictKeys.has(key)) - ) - ) + ), + // Why: this pass made the runtime's marketplace and plugin tables canonical, + // so a later source config that lacks one is a removal, not an addition. + mirroredRegistrations: true + }) } /** diff --git a/src/main/codex/codex-config-settings-upsert.ts b/src/main/codex/codex-config-settings-upsert.ts index 963d46d239a..55fcd4db480 100644 --- a/src/main/codex/codex-config-settings-upsert.ts +++ b/src/main/codex/codex-config-settings-upsert.ts @@ -2,7 +2,10 @@ import { createTomlLineScanState, getTomlTableHeader, isTomlStructuralLine, - updateTomlLineScanState + joinPreservingTrailingNewline, + updateTomlLineScanState, + withCrLine, + withTrailingCr } from './config-toml-line-scan' import { parseTomlKeyPath, parseTomlTableHeaderPath } from './config-toml-key-path' @@ -302,21 +305,3 @@ function appendNewTuiTable(lines: string[], keyRenders: string[], usesCrlf: bool const block = appendAt > 0 ? ['', '[tui]', ...keyRenders] : ['[tui]', ...keyRenders] lines.splice(appendAt, 0, ...block.map((line) => withCrLine(line, usesCrlf))) } - -function withTrailingCr(originalLine: string, rendered: string): string { - return originalLine.endsWith('\r') ? `${rendered}\r` : rendered -} - -function withCrLine(rendered: string, usesCrlf: boolean): string { - return usesCrlf ? `${rendered}\r` : rendered -} - -// Why: a missing trailing newline is restored in the file's own EOL so a -// preamble-only or table-appended rewrite matches the source's newline behavior. -function joinPreservingTrailingNewline(lines: string[], usesCrlf: boolean): string { - const result = lines.join('\n') - if (result.endsWith('\n') || result.length === 0) { - return result - } - return result.endsWith('\r') ? `${result}\n` : `${result}${usesCrlf ? '\r\n' : '\n'}` -} diff --git a/src/main/codex/codex-goal-journal-identity.ts b/src/main/codex/codex-goal-journal-identity.ts new file mode 100644 index 00000000000..5203b7b62d5 --- /dev/null +++ b/src/main/codex/codex-goal-journal-identity.ts @@ -0,0 +1,47 @@ +import { createHash } from 'node:crypto' +import { parseAgentJournalItemKey } from '../../shared/agent-session-journal-item-key' +import type { AgentJournalItemIdentity } from '../../shared/agent-session-journal-types' + +export type CodexGoalJournalState = { + thread: string + signature: string + occurrence: string +} + +const GOAL_IDENTITY_PREFIX = 'codex-goal' +const DIGEST_PATTERN = /^[0-9a-f]{64}$/ + +export function codexGoalJournalDigest(value: string): string { + return createHash('sha256').update(value).digest('hex') +} + +export function codexGoalJournalIdentity( + thread: string, + signature: string, + occurrence: string +): AgentJournalItemIdentity { + return { + provider: 'orca', + clientMessageId: `${GOAL_IDENTITY_PREFIX}:${thread}:${signature}:${occurrence}` + } +} + +/** Recognizes only the host-owned rows used to record Codex goal lifecycle state. */ +export function parseCodexGoalJournalItemId(itemId: string): CodexGoalJournalState | null { + const identity = parseAgentJournalItemKey(itemId) + if (identity?.provider !== 'orca') { + return null + } + const [prefix, thread, signature, occurrence, ...rest] = identity.clientMessageId.split(':') + return prefix === GOAL_IDENTITY_PREFIX && + DIGEST_PATTERN.test(thread ?? '') && + DIGEST_PATTERN.test(signature ?? '') && + DIGEST_PATTERN.test(occurrence ?? '') && + rest.length === 0 + ? { + thread: thread as string, + signature: signature as string, + occurrence: occurrence as string + } + : null +} diff --git a/src/main/codex/codex-goal-journal-rows.test.ts b/src/main/codex/codex-goal-journal-rows.test.ts new file mode 100644 index 00000000000..dcbc11a816f --- /dev/null +++ b/src/main/codex/codex-goal-journal-rows.test.ts @@ -0,0 +1,127 @@ +import { describe, expect, it } from 'vitest' +import { unhandledProviderFrameJournalItem } from '../native-chat/agent-session-wire/unhandled-provider-frame' +import { codexGoalRowSignature, codexGoalRowText } from './codex-goal-journal-rows' + +/** The shape a live Codex app-server session emits for `thread/goal/updated`. */ +function goalFrame(overrides: { goal?: Record } = {}): Record { + return { + threadId: '01a08cc2-f96e-76d0-bb74-88b9bc0b03fc', + turnId: '01a08cc2-fa6a-7541-a4c7-67d98a6e40c2', + goal: { + threadId: '01a08cc2-f96e-76d0-bb74-88b9bc0b03fc', + objective: 'Keep the current scratch directory tidy.', + status: 'active', + tokenBudget: null, + tokensUsed: 0, + timeUsedSeconds: 0, + createdAt: 1789067988, + updatedAt: 1789067988, + ...overrides.goal + } + } +} + +describe('codexGoalRowText', () => { + it('leads with the objective the goal actually carries', () => { + expect(codexGoalRowText('thread/goal/updated', goalFrame())).toBe( + 'Goal set: Keep the current scratch directory tidy.' + ) + }) + + it.each([ + ['paused', 'Goal paused'], + ['blocked', 'Goal blocked'], + ['complete', 'Goal complete'], + ['usageLimited', 'Goal stopped — usage limit'], + ['budgetLimited', 'Goal stopped — token budget spent'] + ])('says what %s means rather than echoing the status', (status, prefix) => { + expect(codexGoalRowText('thread/goal/updated', goalFrame({ goal: { status } }))).toBe( + `${prefix}: Keep the current scratch directory tidy.` + ) + }) + + it('still says something true for a status this build does not know', () => { + expect( + codexGoalRowText('thread/goal/updated', goalFrame({ goal: { status: 'somethingNew' } })) + ).toBe('Goal updated: Keep the current scratch directory tidy.') + }) + + it('reports a cleared goal, and ignores unrelated methods', () => { + expect(codexGoalRowText('thread/goal/cleared', {})).toBe('Goal cleared') + expect(codexGoalRowText('thread/tokenUsage/updated', goalFrame())).toBeNull() + }) + + it('falls back to the prefix alone when no objective survives', () => { + expect(codexGoalRowText('thread/goal/updated', goalFrame({ goal: { objective: ' ' } }))).toBe( + 'Goal set' + ) + expect(codexGoalRowText('thread/goal/updated', {})).toBe('Goal updated') + }) +}) + +describe('codexGoalRowSignature', () => { + it('ignores the counters that climb on every turn', () => { + // Two frames one live turn apart: only accounting moved. + const first = codexGoalRowSignature('thread/goal/updated', goalFrame()) + const later = codexGoalRowSignature( + 'thread/goal/updated', + goalFrame({ goal: { tokensUsed: 25999, timeUsedSeconds: 8, updatedAt: 1789067996 } }) + ) + expect(later).toBe(first) + }) + + it('separates visible objective and status changes', () => { + const base = codexGoalRowSignature('thread/goal/updated', goalFrame()) + expect( + codexGoalRowSignature('thread/goal/updated', goalFrame({ goal: { status: 'complete' } })) + ).not.toBe(base) + expect( + codexGoalRowSignature('thread/goal/updated', goalFrame({ goal: { objective: 'Ship it.' } })) + ).not.toBe(base) + }) + + it('does not append an identical visible row for a budget-only change', () => { + const base = codexGoalRowSignature('thread/goal/updated', goalFrame()) + expect( + codexGoalRowSignature('thread/goal/updated', goalFrame({ goal: { tokenBudget: 50_000 } })) + ).toBe(base) + }) + + it('has no signature for a frame that is not a goal', () => { + expect(codexGoalRowSignature('thread/tokenUsage/updated', goalFrame())).toBeNull() + }) +}) + +describe('goal frames as journal rows', () => { + it('journals the goal instead of dropping it as chrome', () => { + const row = unhandledProviderFrameJournalItem( + 'codex', + 'notification:thread/goal/updated', + goalFrame() + ) + + expect(row?.classification).toBe('timeline-substantive') + expect(row?.body.text).toBe('Goal set: Keep the current scratch directory tidy.') + // The raw frame stays available behind the row's disclosure. + expect(row?.body.providerFrame?.kind).toBe('notification:thread/goal/updated') + }) + + it('journals a cleared goal', () => { + const row = unhandledProviderFrameJournalItem('codex', 'notification:thread/goal/cleared', { + threadId: '01a08cc2-f96e-76d0-bb74-88b9bc0b03fc' + }) + + expect(row?.body.text).toBe('Goal cleared') + }) + + it('never shows the bare opcode, which is what a plain reclassify would have done', () => { + const row = unhandledProviderFrameJournalItem( + 'codex', + 'notification:thread/goal/updated', + goalFrame() + ) + + expect(row?.body.text).not.toContain('notification:') + expect(row?.body.text).not.toContain('codex · ') + }) +}) diff --git a/src/main/codex/codex-goal-journal-rows.ts b/src/main/codex/codex-goal-journal-rows.ts new file mode 100644 index 00000000000..36dac339901 --- /dev/null +++ b/src/main/codex/codex-goal-journal-rows.ts @@ -0,0 +1,74 @@ +/** + * Codex thread goals reach us only as notifications: the `create_goal` tool call the + * model makes is never emitted as an item, so `thread/goal/updated` is the single + * truthful signal that a goal exists. The model narrates goals in prose either way, + * and that prose can be wrong — it claims "Goal created" in sessions where no goal + * was ever set — so the row below is what lets a reader tell the two apart. + */ + +const GOAL_UPDATED_METHOD = 'thread/goal/updated' +const GOAL_CLEARED_METHOD = 'thread/goal/cleared' + +/** Status values Codex can report, mapped to how a reader would say them. */ +const GOAL_STATUS_PREFIX: Record = { + active: 'Goal set', + paused: 'Goal paused', + blocked: 'Goal blocked', + complete: 'Goal complete', + usageLimited: 'Goal stopped — usage limit', + budgetLimited: 'Goal stopped — token budget spent' +} + +function goalRecord(payload: unknown): Record | null { + if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) { + return null + } + const goal = (payload as Record).goal + return typeof goal === 'object' && goal !== null && !Array.isArray(goal) + ? (goal as Record) + : null +} + +export function isCodexGoalFrameMethod(method: string): boolean { + return method === GOAL_UPDATED_METHOD || method === GOAL_CLEARED_METHOD +} + +/** The sentence for a goal frame, or null when the frame is not one. */ +export function codexGoalRowText(method: string, payload: unknown): string | null { + if (method === GOAL_CLEARED_METHOD) { + return 'Goal cleared' + } + if (method !== GOAL_UPDATED_METHOD) { + return null + } + const goal = goalRecord(payload) + const objective = typeof goal?.objective === 'string' ? goal.objective.trim() : '' + const status = typeof goal?.status === 'string' ? goal.status : '' + // An unknown future status still says something true rather than falling back to + // the bare opcode. + const prefix = GOAL_STATUS_PREFIX[status] ?? 'Goal updated' + return objective ? `${prefix}: ${objective}` : prefix +} + +/** + * What changes the visible sentence. Counters and budget stay in the raw disclosure but + * cannot append another row with identical copy. + */ +export function codexGoalRowSignature(method: string, payload: unknown): string | null { + if (method === GOAL_CLEARED_METHOD) { + return GOAL_CLEARED_METHOD + } + if (method !== GOAL_UPDATED_METHOD) { + return null + } + const goal = goalRecord(payload) + const objective = typeof goal?.objective === 'string' ? goal.objective.trim() : '' + const status = typeof goal?.status === 'string' ? goal.status : '' + return `${GOAL_UPDATED_METHOD}\u0000${status}\u0000${objective}` +} + +/** Provider-owned goal generation, stable while accounting counters change. */ +export function codexGoalGeneration(payload: unknown): string | null { + const createdAt = goalRecord(payload)?.createdAt + return typeof createdAt === 'number' && Number.isFinite(createdAt) ? String(createdAt) : null +} diff --git a/src/main/codex/codex-hook-legacy-cleanup.ts b/src/main/codex/codex-hook-legacy-cleanup.ts index 3177fdaa5a1..d2b5c3b586c 100644 --- a/src/main/codex/codex-hook-legacy-cleanup.ts +++ b/src/main/codex/codex-hook-legacy-cleanup.ts @@ -9,6 +9,7 @@ import { } from '../agent-hooks/installer-utils' import { resolveHooksJsonWritePath } from '../agent-hooks/hook-config-write-path' import { writeFileAtomically } from '../codex-accounts/fs-utils' +import { findManagedTomlBlocks } from '../agent-hooks/managed-toml-ownership' import { writeConfigAtomically, type CodexTrustEntry } from './config-toml-trust' import { getConfigPath, @@ -149,22 +150,37 @@ async function sweepLegacySystemManagedHooks(): Promise { } } -function stripLegacyManagedProfileBlock(content: string): string { - const start = content.indexOf(LEGACY_ORCA_PROFILE_BLOCK_START) - if (start === -1) { +export function stripLegacyManagedProfileBlock(content: string): string { + const regions = findManagedTomlBlocks(content, { + startMarker: LEGACY_ORCA_PROFILE_BLOCK_START, + endMarker: LEGACY_ORCA_PROFILE_BLOCK_END + }) + // A stray marker above a complete block must not hide it: take the first + // terminated region and leave the orphan (and the user text around it) alone. + const region = regions.find((candidate) => candidate.terminated) ?? regions[0] + if (!region) { return content } - const endMarker = content.indexOf(LEGACY_ORCA_PROFILE_BLOCK_END, start) - const end = endMarker === -1 ? content.length : endMarker + LEGACY_ORCA_PROFILE_BLOCK_END.length - const before = content.slice(0, start).replace(/[ \t]*(?:\r?\n)*$/, '') - const after = content.slice(end).replace(/^(?:\r?\n)+/, '') + if (!region.terminated) { + // #18861: deleting to EOF took user text appended below the block. This + // legacy body's shape is not knowable from current source, so there is + // nothing to recognize it by; leave the whole thing alone. The stale profile + // is inert (runtime CODEX_HOME supersedes it), so that costs nothing next to + // destroying the user's trust entries. + return content + } + // Rejoin with the file's own terminator; a bare \n seam here left Windows + // configs with mixed endings. + const eol = content.includes('\r\n') ? '\r\n' : '\n' + const before = content.slice(0, region.markerOffset).replace(/[ \t]*(?:\r?\n)*$/, '') + const after = content.slice(region.endOffset).replace(/^(?:\r?\n)+/, '') if (!before) { return after } if (!after) { - return before.endsWith('\n') ? before : `${before}\n` + return before.endsWith('\n') ? before : `${before}${eol}` } - return `${before}\n\n${after}` + return `${before}${eol}${eol}${after}` } function cleanupLegacyCodexProfileHooks(): void { diff --git a/src/main/codex/codex-hook-legacy-profile-block.test.ts b/src/main/codex/codex-hook-legacy-profile-block.test.ts new file mode 100644 index 00000000000..5225f482b13 --- /dev/null +++ b/src/main/codex/codex-hook-legacy-profile-block.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from 'vitest' +import { stripLegacyManagedProfileBlock } from './codex-hook-legacy-cleanup' + +const START = '# BEGIN ORCA AGENT STATUS HOOKS' +const END = '# END ORCA AGENT STATUS HOOKS' + +describe('legacy Codex managed profile block', () => { + it('strips a well-formed block and keeps the surrounding config', () => { + const content = `model = "o3"\n\n${START}\n[[hooks]]\nx = 1\n${END}\n\ntail = true\n` + expect(stripLegacyManagedProfileBlock(content)).toBe('model = "o3"\n\ntail = true\n') + }) + + it('leaves a file with no managed block untouched', () => { + expect(stripLegacyManagedProfileBlock('model = "o3"\n')).toBe('model = "o3"\n') + }) + + it('rejoins a CRLF config with CRLF', () => { + const content = `model = "o3"\r\n\r\n${START}\r\n[[hooks]]\r\n${END}\r\n\r\ntail = true\r\n` + const next = stripLegacyManagedProfileBlock(content) + expect(next).toBe('model = "o3"\r\n\r\ntail = true\r\n') + expect(next).not.toMatch(/[^\r]\n/) + }) + + // CodeRabbit on #20148: a stray marker above a complete block must not hide it. + it('removes a complete block that sits below an orphaned marker', () => { + const content = `${START}\nstray = 1\n\n${START}\n[[hooks]]\nx = 1\n${END}\n\ntail = true\n` + const next = stripLegacyManagedProfileBlock(content) + expect(next).not.toContain('[[hooks]]') + expect(next).toContain('stray = 1') + expect(next).toContain('tail = true') + }) + + // #18861: the old strip ran to EOF whenever the end marker was gone. + it('fails closed when the end marker was hand-deleted', () => { + const content = `model = "o3"\n${START}\n[[hooks]]\nx = 1\n\n[user.table]\nkeep = "mine"\n` + expect(stripLegacyManagedProfileBlock(content)).toBe(content) + }) +}) diff --git a/src/main/codex/codex-notice-item-translation.test.ts b/src/main/codex/codex-notice-item-translation.test.ts index 15f638c4015..14a87cb8cc5 100644 --- a/src/main/codex/codex-notice-item-translation.test.ts +++ b/src/main/codex/codex-notice-item-translation.test.ts @@ -22,11 +22,16 @@ describe('plan document translation', () => { expect( codexItemBody({ id: 'r', type: 'reasoning', summary: ['Thinking through the problem.'] }) ).toEqual({ - kind: 'status', - text: 'Thinking through the problem.' + kind: 'message', + role: 'reasoning', + blocks: [{ type: 'text', text: 'Thinking through the problem.' }] }) expect(codexStreamingJournalItem({ id: 'r', type: 'reasoning' }, 'Thinking…')).toEqual({ - body: { kind: 'status', text: 'Thinking…' }, + body: { + kind: 'message', + role: 'reasoning', + blocks: [{ type: 'text', text: 'Thinking…' }] + }, handled: true }) }) diff --git a/src/main/codex/codex-structured-item-translation.test.ts b/src/main/codex/codex-structured-item-translation.test.ts index 201df58bc90..53cf94e265c 100644 --- a/src/main/codex/codex-structured-item-translation.test.ts +++ b/src/main/codex/codex-structured-item-translation.test.ts @@ -10,6 +10,7 @@ import { codexItemIdentity, codexJournalItem, codexMessageBlocks, + codexStreamingJournalItem, CodexTurnOrdinals, MAX_CODEX_TURN_ORDINAL_BYTES, MAX_CODEX_TURN_ORDINAL_ENTRIES, @@ -201,6 +202,7 @@ describe('codex item bodies', () => { expect(codexItemBody(LIVE_TURN[2] as CodexThreadItem)).toEqual({ kind: 'tool-call', name: 'shell', + callId: 'item-2', input: { command: 'ls', cwd: '/tmp' }, exitCode: 0, state: 'completed', @@ -229,6 +231,7 @@ describe('codex item bodies', () => { expect(body).toEqual({ kind: 'tool-call', name: 'read', + callId: 'item-read', // `name` is the target's basename, which `path` already carries and no // label ever reads, so it stays out of the bounded journal payload. input: { command: "sed -n '1,200p' notes.txt", cwd: '/repo', path: '/repo/notes.txt' }, @@ -257,6 +260,7 @@ describe('codex item bodies', () => { ).toEqual({ kind: 'tool-call', name: 'search', + callId: 'item-search', input: { command: 'rg -n --no-heading beta .', cwd: '/repo', query: 'beta', directory: '.' }, state: 'running' }) @@ -276,6 +280,7 @@ describe('codex item bodies', () => { ).toEqual({ kind: 'tool-call', name: 'search', + callId: 'item-search-bare', input: { command: 'rg beta', cwd: '/repo' }, exitCode: 0, state: 'completed' @@ -296,6 +301,7 @@ describe('codex item bodies', () => { expect(body).toEqual({ kind: 'tool-call', name: 'list', + callId: 'item-list', input: { command: 'ls', cwd: '/repo' }, exitCode: 0, state: 'completed' @@ -326,6 +332,7 @@ describe('codex item bodies', () => { ).toEqual({ kind: 'tool-call', name: 'shell', + callId: 'item-mixed', input: { command: 'cat a.txt && ls src', cwd: '/repo' }, exitCode: 0, state: 'completed' @@ -349,6 +356,7 @@ describe('codex item bodies', () => { ).toEqual({ kind: 'tool-call', name: 'read', + callId: 'item-two-reads', input: { command: 'cat a.ts && cat b.ts', cwd: '/repo' }, exitCode: 0, state: 'completed' @@ -424,6 +432,7 @@ describe('codex item bodies', () => { ).toEqual({ kind: 'tool-call', name: 'read', + callId: 'item-read-null', input: { command: 'cat', cwd: '/repo' }, exitCode: 0, state: 'completed' @@ -451,6 +460,7 @@ describe('codex item bodies', () => { const shellRow = { kind: 'tool-call', name: 'shell', + callId: 'item-fallback', input: { command: 'ls', cwd: '/tmp' }, exitCode: 0, state: 'completed' @@ -592,12 +602,18 @@ describe('codex item bodies', () => { body: { kind: 'status', text, presentation: 'plan-document' }, handled: true }) + // A plan is a durable artifact, so it must never read as the model reasoning now. + expect(codexItemBody({ type: 'plan', id: 'plan-document', text })).not.toMatchObject({ + kind: 'message', + role: 'reasoning' + }) }) - it('renders reasoning as status and exposes an unknown item as a provider frame', () => { + it('renders reasoning as a typed message and exposes an unknown item as a provider frame', () => { expect(codexItemBody({ type: 'reasoning', id: 'r', text: 'thinking' })).toEqual({ - kind: 'status', - text: 'thinking' + kind: 'message', + role: 'reasoning', + blocks: [{ type: 'text', text: 'thinking' }] }) expect(codexItemBody({ type: 'reasoning', id: 'r' })).toBeNull() expect(codexItemBody({ type: 'agentMessage', id: 'm', text: '' })).toBeNull() @@ -608,6 +624,15 @@ describe('codex item bodies', () => { }) }) + it('keeps non-reasoning item streams as status activity', () => { + expect( + codexStreamingJournalItem({ type: 'somethingCodexAddedLater', id: 'x' }, 'still working') + ).toEqual({ + body: { kind: 'status', text: 'still working' }, + handled: true + }) + }) + it('gives an mcp tool call a typed body with its own arguments as input', () => { expect( codexItemBody({ @@ -624,6 +649,7 @@ describe('codex item bodies', () => { // Server-qualified, and the arguments stay top level so the row label can // read `query`/`command`/`file_path` out of them. name: 'weather/get_forecast', + callId: 'mcp-1', mcpIdentity: { server: 'weather', tool: 'get_forecast' }, input: { city: 'Oslo' }, state: 'completed', @@ -672,6 +698,7 @@ describe('codex item bodies', () => { expect(codexItemBody({ type: 'mcpToolCall', id: 'm', tool: 't', arguments: {} })).toEqual({ kind: 'tool-call', name: 't', + callId: 'm', input: null, state: 'running' }) @@ -719,6 +746,7 @@ describe('codex item bodies', () => { expect(codexItemBody({ type: 'webSearch', id: 'w', query: '', action: null })).toEqual({ kind: 'tool-call', name: 'web_search', + callId: 'w', input: null, state: 'running' }) @@ -733,6 +761,7 @@ describe('codex item bodies', () => { ).toEqual({ kind: 'tool-call', name: 'web_search', + callId: 'w', input: { query: 'orca release notes', description: 'search', @@ -830,7 +859,11 @@ describe('codex item bodies', () => { summary: ['first', 'second'], content: [{ text: 'fallback' }] }) - ).toEqual({ kind: 'status', text: 'first\nsecond' }) + ).toEqual({ + kind: 'message', + role: 'reasoning', + blocks: [{ type: 'text', text: 'first\nsecond' }] + }) }) it('refuses a value that is not a thread item at all', () => { diff --git a/src/main/codex/codex-structured-item-translation.ts b/src/main/codex/codex-structured-item-translation.ts index 576f3fb19ec..34f07eefda7 100644 --- a/src/main/codex/codex-structured-item-translation.ts +++ b/src/main/codex/codex-structured-item-translation.ts @@ -85,6 +85,10 @@ export type CodexJournalItem = { handled: boolean } +function reasoningMessageBody(text: string): AgentJournalItemBody { + return { kind: 'message', role: 'reasoning', blocks: [{ type: 'text', text }] } +} + function commandItem(item: CodexThreadItem): CodexJournalItem { const output = readFirstString(item, ['aggregatedOutput', 'aggregated_output']) const bounded = output === null ? null : boundInlineText(output, DEFAULT_JOURNAL_PAYLOAD_LIMITS) @@ -93,6 +97,7 @@ function commandItem(item: CodexThreadItem): CodexJournalItem { body: { kind: 'tool-call', name: parsed?.name ?? 'shell', + callId: item.id, // Raw command and cwd stay so the expanded view still shows what ran. input: boundToolInput( { command: item.command ?? null, cwd: item.cwd ?? null, ...parsed?.fields }, @@ -120,6 +125,7 @@ function fileChangeItem(item: CodexThreadItem): CodexJournalItem { body: { kind: 'tool-call', name: 'apply_patch', + callId: item.id, input: boundToolInput({ changes: item.changes ?? null }, DEFAULT_JOURNAL_PAYLOAD_LIMITS), state: commandState(item) }, @@ -171,6 +177,7 @@ function mcpToolCallItem(item: CodexThreadItem): CodexJournalItem { body: { kind: 'tool-call', name: mcpToolCallName(item), + callId: item.id, ...(server && tool ? { mcpIdentity: { server, tool } } : {}), input: boundToolInput(mcpToolArguments(item.arguments), DEFAULT_JOURNAL_PAYLOAD_LIMITS), state: failure === null ? commandState(item) : 'failed', @@ -213,6 +220,7 @@ function webSearchItem(item: CodexThreadItem): CodexJournalItem { body: { kind: 'tool-call', name: 'web_search', + callId: item.id, ...(results.length > 0 ? { webSearchResults: results } : {}), input: boundToolInput(webSearchInput(item), DEFAULT_JOURNAL_PAYLOAD_LIMITS), state: item.action === null || item.action === undefined ? 'running' : 'completed', @@ -268,7 +276,7 @@ export function codexJournalItem(item: CodexThreadItem): CodexJournalItem { handled: true } } - if (item.type === 'reasoning' || item.type === 'plan') { + if (item.type === 'reasoning') { const text = readTextContent(item, 'text') ?? readTextContent(item, 'summary') ?? @@ -277,7 +285,7 @@ export function codexJournalItem(item: CodexThreadItem): CodexJournalItem { body: text === null ? null - : { kind: 'status', text: boundInlineText(text, DEFAULT_JOURNAL_PAYLOAD_LIMITS).text }, + : reasoningMessageBody(boundInlineText(text, DEFAULT_JOURNAL_PAYLOAD_LIMITS).text), handled: true } } @@ -327,5 +335,11 @@ export function codexStreamingJournalItem(item: CodexThreadItem, text: string): } } const bounded = boundInlineText(text, DEFAULT_JOURNAL_PAYLOAD_LIMITS) - return { body: { kind: 'status', text: bounded.text }, handled: true } + return { + body: + item.type === 'reasoning' + ? reasoningMessageBody(bounded.text) + : { kind: 'status', text: bounded.text }, + handled: true + } } diff --git a/src/main/codex/codex-structured-journal-goal-admission.test.ts b/src/main/codex/codex-structured-journal-goal-admission.test.ts new file mode 100644 index 00000000000..5fe926d18c9 --- /dev/null +++ b/src/main/codex/codex-structured-journal-goal-admission.test.ts @@ -0,0 +1,231 @@ +import { describe, expect, it } from 'vitest' +import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key' +import type { + AgentJournalItemBody, + AgentJournalItemIdentity +} from '../../shared/agent-session-journal-types' +import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' +import { CodexJournalGoals } from './codex-structured-journal-goals' +import { + createCodexJournalTranslator, + MAX_CODEX_GENERIC_ROWS_PER_TURN +} from './codex-structured-journal-translation' +import { MAX_CODEX_GOAL_THREADS } from './codex-structured-journal-limits' + +const THREAD = '01a08cc2-f96e-76d0-bb74-88b9bc0b03fc' + +function goalFrame(goal: Record = {}): Record { + return { + threadId: THREAD, + turnId: 'turn-1', + goal: { + threadId: THREAD, + objective: 'Keep the current scratch directory tidy.', + status: 'active', + tokenBudget: null, + tokensUsed: 0, + timeUsedSeconds: 0, + createdAt: 1789067988, + updatedAt: 1789067988, + ...goal + } + } +} + +function texts(rows: readonly AgentJournalItemBody[]): string[] { + return rows.map((row) => (row.kind === 'status' ? row.text : '')) +} + +describe('codex goal lifecycle admission', () => { + it.each(['append', 'publish'] as const)( + 'retries the same goal after rejected %s without losing or duplicating its row', + (stage) => { + let reject = true + let successfulPublishes = 0 + const rows = new Map() + const identities: string[] = [] + const lifecycleOptions: boolean[] = [] + const sink = { + appendItem: () => {}, + appendTombstone: () => {}, + publish: () => {}, + tryAppendItem: (identity, body, options) => { + if (stage === 'append' && reject) { + return { accepted: false, reason: 'backpressure' } as const + } + const key = agentJournalItemKey(identity) + identities.push(key) + rows.set(key, body) + lifecycleOptions.push(options?.lifecycle === true) + return { accepted: true } as const + }, + tryPublish: (options) => { + if (stage === 'publish' && reject) { + return { accepted: false, reason: 'backpressure' } as const + } + successfulPublishes += 1 + lifecycleOptions.push(options?.lifecycle === true) + return { accepted: true } as const + } + } satisfies StructuredAgentSessionEventSink + const translator = createCodexJournalTranslator({ sink }) + const event = { + type: 'notification' as const, + sessionId: 'session', + threadId: THREAD, + method: 'thread/goal/updated', + params: goalFrame() + } + + expect(translator.handle(event)).toEqual({ accepted: false, reason: 'backpressure' }) + reject = false + expect(translator.handle(event)).toEqual({ accepted: true }) + + expect(rows.size).toBe(1) + expect(new Set(identities)).toHaveLength(1) + expect(successfulPublishes).toBe(1) + expect(lifecycleOptions.every(Boolean)).toBe(true) + translator.dispose() + } + ) + + it('does not let the generic-row cap permanently hide the first goal evidence', () => { + const rows: AgentJournalItemBody[] = [] + const sink = { + appendItem: (_identity: AgentJournalItemIdentity, body: AgentJournalItemBody) => + rows.push(body), + appendTombstone: () => {}, + publish: () => {} + } satisfies StructuredAgentSessionEventSink + const translator = createCodexJournalTranslator({ sink }) + for (let index = 0; index < MAX_CODEX_GENERIC_ROWS_PER_TURN; index += 1) { + translator.handle({ + type: 'notification', + sessionId: 'session', + threadId: THREAD, + method: 'process/exited', + params: { threadId: THREAD, turnId: 'turn-1', processId: `process-${index}` } + }) + } + + translator.handle({ + type: 'notification', + sessionId: 'session', + threadId: THREAD, + method: 'thread/goal/updated', + params: goalFrame() + }) + translator.handle({ + type: 'notification', + sessionId: 'session', + threadId: THREAD, + method: 'thread/goal/updated', + params: { ...goalFrame({ tokensUsed: 1 }), turnId: 'turn-2' } + }) + + expect(texts(rows).filter((text) => text.startsWith('Goal '))).toEqual([ + 'Goal set: Keep the current scratch directory tidy.' + ]) + translator.dispose() + }) + + it('keeps repeated lifecycle states distinct across status cycles and goal recreation', () => { + const rows = new Map() + const sink = { + appendItem: (identity: AgentJournalItemIdentity, body: AgentJournalItemBody) => + rows.set(agentJournalItemKey(identity), body), + appendTombstone: () => {}, + publish: () => {} + } satisfies StructuredAgentSessionEventSink + const goals = new CodexJournalGoals(sink) + const update = (goal: Record = {}) => + goals.handle({ threadId: THREAD, method: 'thread/goal/updated', params: goalFrame(goal) }) + const clear = () => + goals.handle({ + threadId: THREAD, + method: 'thread/goal/cleared', + params: { threadId: THREAD } + }) + + update() + update({ status: 'paused' }) + update() + clear() + update() + clear() + clear() + + expect(texts([...rows.values()])).toEqual([ + 'Goal set: Keep the current scratch directory tidy.', + 'Goal paused: Keep the current scratch directory tidy.', + 'Goal set: Keep the current scratch directory tidy.', + 'Goal cleared', + 'Goal set: Keep the current scratch directory tidy.', + 'Goal cleared' + ]) + goals.dispose() + }) + + it('bounds thread state with LRU eviction while stable identities keep one history row', () => { + const writes: string[] = [] + const rows = new Map() + const sink = { + appendItem: (identity: AgentJournalItemIdentity, body: AgentJournalItemBody) => { + const key = agentJournalItemKey(identity) + writes.push(key) + rows.set(key, body) + }, + appendTombstone: () => {}, + publish: () => {} + } satisfies StructuredAgentSessionEventSink + const goals = new CodexJournalGoals(sink) + const send = (threadId: string) => + goals.handle({ threadId, method: 'thread/goal/updated', params: goalFrame() }) + + for (let index = 0; index < MAX_CODEX_GOAL_THREADS; index += 1) { + send(`thread-${index}`) + } + const threadZeroIdentity = writes[0] + const threadOneIdentity = writes[1] + send('thread-0') + send('thread-over-cap') + expect(writes).toHaveLength(MAX_CODEX_GOAL_THREADS + 1) + + send('thread-1') + expect(writes).toHaveLength(MAX_CODEX_GOAL_THREADS + 2) + expect(writes.at(-1)).toBe(threadOneIdentity) + expect(rows).toHaveLength(MAX_CODEX_GOAL_THREADS + 1) + + send('thread-0') + expect(writes.at(-1)).toBe(threadOneIdentity) + expect(writes.filter((identity) => identity === threadZeroIdentity)).toHaveLength(1) + goals.dispose() + }) + + it('releases duplicate-suppression state on session clear and dispose', () => { + const identities: string[] = [] + const sink = { + appendItem: (identity: AgentJournalItemIdentity) => { + identities.push(agentJournalItemKey(identity)) + }, + appendTombstone: () => {}, + publish: () => {} + } satisfies StructuredAgentSessionEventSink + const goals = new CodexJournalGoals(sink) + const event = { threadId: THREAD, method: 'thread/goal/updated', params: goalFrame() } + + goals.handle(event) + goals.handle(event) + expect(identities).toHaveLength(1) + + goals.clear() + goals.handle(event) + expect(identities).toHaveLength(2) + expect(new Set(identities)).toHaveLength(1) + + goals.dispose() + goals.handle(event) + expect(identities).toHaveLength(3) + expect(new Set(identities)).toHaveLength(1) + }) +}) diff --git a/src/main/codex/codex-structured-journal-goal-resume.test.ts b/src/main/codex/codex-structured-journal-goal-resume.test.ts new file mode 100644 index 00000000000..4cf87b790bb --- /dev/null +++ b/src/main/codex/codex-structured-journal-goal-resume.test.ts @@ -0,0 +1,365 @@ +import { describe, expect, it } from 'vitest' +import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key' +import type { + AgentJournalItemBody, + AgentJournalItemIdentity, + AgentJournalRenderItem +} from '../../shared/agent-session-journal-types' +import { + createDeferredStructuredAgentSessionEventSink, + type StructuredAgentSessionEventTarget +} from '../native-chat/agent-session-wire/structured-agent-session-event-sink' +import { CodexJournalGoals } from './codex-structured-journal-goals' +import { MAX_CODEX_GOAL_THREADS } from './codex-structured-journal-limits' + +const THREAD = '01a08cc2-f96e-76d0-bb74-88b9bc0b03fc' + +function goalFrame(goal: Record = {}): Record { + return { + threadId: THREAD, + turnId: 'turn-1', + goal: { + threadId: THREAD, + objective: 'Keep the current scratch directory tidy.', + status: 'active', + tokenBudget: null, + tokensUsed: 0, + timeUsedSeconds: 0, + createdAt: 1789067988, + updatedAt: 1789067988, + ...goal + } + } +} + +function goalJournal( + options: Parameters[0] = {} +) { + let rowSequence = 0 + let publishes = 0 + let epochNumber = 1 + let visits = 0 + let visitedItems = 0 + const rows = new Map() + const writes: string[] = [] + const deferred = createDeferredStructuredAgentSessionEventSink(options) + const journal = { + get epoch() { + return `epoch-${epochNumber}` + }, + appendItem: async (identity: AgentJournalItemIdentity, body: AgentJournalItemBody) => { + rowSequence += 1 + const itemId = agentJournalItemKey(identity) + const existing = rows.get(itemId) + const revision = (existing?.revision ?? 0) + 1 + writes.push(itemId) + rows.set(itemId, { + itemId, + body, + revision, + sequence: existing?.sequence ?? rowSequence, + observedAt: existing?.observedAt ?? rowSequence + }) + return { cursor: { epoch: `epoch-${epochNumber}`, sequence: rowSequence }, itemId, revision } + }, + snapshot: () => ({ + sessionId: 'session', + cursor: { epoch: `epoch-${epochNumber}`, sequence: rowSequence }, + items: [...rows.values()].sort((left, right) => left.sequence - right.sequence), + submissions: [] + }), + visitItems: (visit: (itemId: string, sequence: number) => void) => { + visits += 1 + for (const item of rows.values()) { + visitedItems += 1 + visit(item.itemId, item.sequence) + } + } + } as unknown as StructuredAgentSessionEventTarget['journal'] + const target = { + journal, + fence: 1, + publish: () => { + publishes += 1 + } + } + deferred.bind(target) + return { + sink: deferred.sink, + writes, + rows: () => journal.snapshot().items, + publishes: () => publishes, + visits: () => visits, + visitedItems: () => visitedItems, + seedProviderItems: (count: number) => { + for (let index = 0; index < count; index += 1) { + rowSequence += 1 + const identity = { + provider: 'codex' as const, + threadId: THREAD, + turnId: `seed-${index}`, + ordinal: 0 + } + const itemId = agentJournalItemKey(identity) + rows.set(itemId, { + itemId, + body: { kind: 'message', role: 'assistant', blocks: [] }, + revision: 1, + sequence: rowSequence, + observedAt: rowSequence + }) + } + }, + replaceEpoch: () => { + epochNumber += 1 + rowSequence = 0 + rows.clear() + }, + rebind: () => deferred.bind(target), + unbind: deferred.unbind, + drained: deferred.drained + } +} + +function texts(rows: readonly AgentJournalItemBody[]): string[] { + return rows.map((row) => (row.kind === 'status' ? row.text : '')) +} + +describe('codex goal lifecycle resume', () => { + it('does not append a cleared snapshot when the journal has no prior goal occurrence', async () => { + const journal = goalJournal() + journal.unbind() + const resumed = new CodexJournalGoals(journal.sink) + + expect( + resumed.handle({ + threadId: THREAD, + method: 'thread/goal/cleared', + params: { threadId: THREAD, turnId: null, clearedAt: 1789068999 } + }) + ).toEqual({ accepted: true }) + expect(journal.writes).toHaveLength(0) + + journal.rebind() + await journal.drained() + + expect(journal.writes).toHaveLength(0) + expect(journal.publishes()).toBe(0) + resumed.dispose() + }) + + it('does not revisit durable history for accounting-only updates', async () => { + const journal = goalJournal() + const goals = new CodexJournalGoals(journal.sink) + goals.handle({ threadId: THREAD, method: 'thread/goal/updated', params: goalFrame() }) + await journal.drained() + const visits = journal.visits() + + for (let index = 1; index <= 10; index += 1) { + goals.handle({ + threadId: THREAD, + method: 'thread/goal/updated', + params: goalFrame({ + tokensUsed: index * 1_000, + timeUsedSeconds: index, + updatedAt: 1789067988 + index + }) + }) + } + await journal.drained() + + expect(journal.visits()).toBe(visits) + expect(journal.writes).toHaveLength(1) + goals.dispose() + }) + + it('rebuilds dedupe state after the journal epoch is replaced', async () => { + const journal = goalJournal() + const goals = new CodexJournalGoals(journal.sink) + const event = { threadId: THREAD, method: 'thread/goal/updated', params: goalFrame() } + + goals.handle(event) + await journal.drained() + expect(journal.writes).toHaveLength(1) + + journal.replaceEpoch() + goals.handle(event) + await journal.drained() + + expect(journal.writes).toHaveLength(2) + expect(texts(journal.rows().map((row) => row.body))).toEqual([ + 'Goal set: Keep the current scratch directory tidy.' + ]) + expect(journal.visits()).toBe(2) + goals.dispose() + }) + + it('visits a large journal once per epoch when thread churn exceeds the transient LRU', async () => { + const journal = goalJournal() + journal.seedProviderItems(10_000) + const goals = new CodexJournalGoals(journal.sink) + const threadCount = MAX_CODEX_GOAL_THREADS + 1 + const sendRound = () => { + for (let index = 0; index < threadCount; index += 1) { + goals.handle({ + threadId: `thread-${index}`, + method: 'thread/goal/updated', + params: goalFrame() + }) + } + } + + sendRound() + await journal.drained() + for (let round = 0; round < 10; round += 1) { + sendRound() + } + await journal.drained() + + expect(journal.visits()).toBe(1) + expect(journal.visitedItems()).toBe(10_000) + expect(journal.writes).toHaveLength(threadCount) + goals.dispose() + }) + + it('resolves queued thread transitions from one shared durable projection', async () => { + const journal = goalJournal() + journal.seedProviderItems(10_000) + journal.unbind() + const goals = new CodexJournalGoals(journal.sink) + + for (let index = 0; index < MAX_CODEX_GOAL_THREADS; index += 1) { + goals.handle({ + threadId: `thread-${index}`, + method: 'thread/goal/updated', + params: goalFrame() + }) + } + expect(journal.visits()).toBe(0) + + journal.rebind() + await journal.drained() + + expect(journal.visits()).toBe(1) + expect(journal.visitedItems()).toBe(10_000) + expect(journal.writes).toHaveLength(MAX_CODEX_GOAL_THREADS) + goals.dispose() + }) + + it('retries a journal-derived transition after lifecycle backpressure', async () => { + const journal = goalJournal({ watermarks: { maxLifecycleQueuedOperations: 1 } }) + const goals = new CodexJournalGoals(journal.sink) + journal.unbind() + + expect( + goals.handle({ + threadId: THREAD, + method: 'thread/goal/updated', + params: goalFrame() + }) + ).toEqual({ accepted: true }) + expect( + goals.handle({ + threadId: THREAD, + method: 'thread/goal/updated', + params: goalFrame({ status: 'paused' }) + }) + ).toEqual({ accepted: false, reason: 'backpressure' }) + + journal.rebind() + await journal.drained() + expect( + goals.handle({ + threadId: THREAD, + method: 'thread/goal/updated', + params: goalFrame({ status: 'paused' }) + }) + ).toEqual({ accepted: true }) + await journal.drained() + + expect(texts(journal.rows().map((row) => row.body))).toEqual([ + 'Goal set: Keep the current scratch directory tidy.', + 'Goal paused: Keep the current scratch directory tidy.' + ]) + goals.dispose() + }) + + it.each([ + { + name: 'paused', + beforeResume: ['active', 'paused'] as const, + resumed: { method: 'thread/goal/updated', goal: { status: 'paused' } }, + expected: ['Goal set', 'Goal paused'] + }, + { + name: 'cleared', + beforeResume: ['active', 'cleared'] as const, + resumed: { method: 'thread/goal/cleared', goal: {} }, + expected: ['Goal set', 'Goal cleared'] + }, + { + name: 'active after a pause', + beforeResume: ['active', 'paused', 'active'] as const, + resumed: { method: 'thread/goal/updated', goal: { status: 'active' } }, + expected: ['Goal set', 'Goal paused', 'Goal set'] + } + ])('does not duplicate a $name snapshot after translator recreation', async (scenario) => { + const journal = goalJournal() + const send = ( + goals: CodexJournalGoals, + state: (typeof scenario.beforeResume)[number] + ): void => { + goals.handle({ + threadId: THREAD, + method: state === 'cleared' ? 'thread/goal/cleared' : 'thread/goal/updated', + params: state === 'cleared' ? { threadId: THREAD } : goalFrame({ status: state }) + }) + } + + const prior = new CodexJournalGoals(journal.sink) + for (const state of scenario.beforeResume) { + send(prior, state) + } + await journal.drained() + const acceptedOccurrence = journal.writes.at(-1) + const writesBeforeResume = journal.writes.length + const publishesBeforeResume = journal.publishes() + const acceptedBody = journal.rows().find((row) => row.itemId === acceptedOccurrence)?.body + prior.dispose() + journal.unbind() + + const resumed = new CodexJournalGoals(journal.sink) + resumed.handle({ + threadId: THREAD, + method: scenario.resumed.method, + params: + scenario.resumed.method === 'thread/goal/cleared' + ? { threadId: THREAD, turnId: null, clearedAt: 1789068999 } + : { + ...goalFrame({ + ...scenario.resumed.goal, + tokensUsed: 12_345, + timeUsedSeconds: 42, + updatedAt: 1789068999 + }), + turnId: null + } + }) + expect(journal.writes).toHaveLength(writesBeforeResume) + journal.rebind() + await journal.drained() + + expect(texts(journal.rows().map((row) => row.body))).toEqual( + scenario.expected.map((prefix) => + prefix === 'Goal cleared' ? prefix : `${prefix}: Keep the current scratch directory tidy.` + ) + ) + expect(journal.writes).toHaveLength(writesBeforeResume) + expect(journal.publishes()).toBe(publishesBeforeResume) + expect(journal.writes.at(-1)).toBe(acceptedOccurrence) + expect(journal.rows().find((row) => row.itemId === acceptedOccurrence)?.body).toEqual( + acceptedBody + ) + resumed.dispose() + }) +}) diff --git a/src/main/codex/codex-structured-journal-goal-rows.test.ts b/src/main/codex/codex-structured-journal-goal-rows.test.ts new file mode 100644 index 00000000000..4c3837b4373 --- /dev/null +++ b/src/main/codex/codex-structured-journal-goal-rows.test.ts @@ -0,0 +1,156 @@ +import { describe, expect, it, vi } from 'vitest' +import type { AgentJournalItemBody } from '../../shared/agent-session-journal-types' +import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' +import { CodexJournalGenericFrames } from './codex-structured-journal-generic-frames' +import { CodexJournalGoals } from './codex-structured-journal-goals' + +const THREAD = '01a08cc2-f96e-76d0-bb74-88b9bc0b03fc' + +function goalFrame(goal: Record): Record { + return { + threadId: THREAD, + turnId: '01a08cc2-fa6a-7541-a4c7-67d98a6e40c2', + goal: { + threadId: THREAD, + objective: 'Keep the current scratch directory tidy.', + status: 'active', + tokenBudget: null, + tokensUsed: 0, + timeUsedSeconds: 0, + createdAt: 1789067988, + updatedAt: 1789067988, + ...goal + } + } +} + +function frames(): { + rows: AgentJournalItemBody[] + frames: Pick +} { + const rows: AgentJournalItemBody[] = [] + const sink = { + appendItem: (_identity: unknown, body: AgentJournalItemBody) => { + rows.push(body) + }, + publish: vi.fn() + } as unknown as StructuredAgentSessionEventSink + const goals = new CodexJournalGoals(sink) + const generic = new CodexJournalGenericFrames({ sink }, () => null) + return { + rows, + frames: { + appendUnhandled: (kind, payload, threadId = 'session') => { + const method = kind.startsWith('notification:') ? kind.slice('notification:'.length) : kind + return ( + goals.handle({ threadId, method, params: payload }) ?? + generic.appendUnhandled(kind, payload, threadId) + ) + } + } + } +} + +function texts(rows: AgentJournalItemBody[]): string[] { + return rows.map((row) => (row as { text?: string }).text ?? '') +} + +describe('codex goal frames as journal rows', () => { + it('writes one row when the goal appears', () => { + const { rows, frames: generic } = frames() + + generic.appendUnhandled('notification:thread/goal/updated', goalFrame({}), THREAD) + + expect(texts(rows)).toEqual(['Goal set: Keep the current scratch directory tidy.']) + }) + + it('does not repeat the row while only the counters climb', () => { + const { rows, frames: generic } = frames() + + // Codex re-sends the goal through the turn as accounting ticks; a live session + // emitted these two seconds apart with nothing else changed. + generic.appendUnhandled('notification:thread/goal/updated', goalFrame({}), THREAD) + generic.appendUnhandled( + 'notification:thread/goal/updated', + goalFrame({ tokensUsed: 23869, timeUsedSeconds: 8, updatedAt: 1789067905 }), + THREAD + ) + generic.appendUnhandled( + 'notification:thread/goal/updated', + goalFrame({ tokensUsed: 25999, timeUsedSeconds: 12, updatedAt: 1789067912 }), + THREAD + ) + + expect(rows).toHaveLength(1) + }) + + it('writes a second row when the status changes', () => { + const { rows, frames: generic } = frames() + + generic.appendUnhandled('notification:thread/goal/updated', goalFrame({}), THREAD) + generic.appendUnhandled( + 'notification:thread/goal/updated', + goalFrame({ status: 'complete', tokensUsed: 31_000 }), + THREAD + ) + + expect(texts(rows)).toEqual([ + 'Goal set: Keep the current scratch directory tidy.', + 'Goal complete: Keep the current scratch directory tidy.' + ]) + }) + + it('writes a row when the objective is replaced', () => { + const { rows, frames: generic } = frames() + + generic.appendUnhandled('notification:thread/goal/updated', goalFrame({}), THREAD) + generic.appendUnhandled( + 'notification:thread/goal/updated', + goalFrame({ objective: 'Ship the parser.' }), + THREAD + ) + + expect(texts(rows)).toEqual([ + 'Goal set: Keep the current scratch directory tidy.', + 'Goal set: Ship the parser.' + ]) + }) + + it('writes a row when the goal is cleared, and again if a new goal follows', () => { + const { rows, frames: generic } = frames() + + generic.appendUnhandled('notification:thread/goal/updated', goalFrame({}), THREAD) + generic.appendUnhandled('notification:thread/goal/cleared', { threadId: THREAD }, THREAD) + generic.appendUnhandled( + 'notification:thread/goal/updated', + goalFrame({ createdAt: 1789067989, updatedAt: 1789067989 }), + THREAD + ) + + expect(texts(rows)).toEqual([ + 'Goal set: Keep the current scratch directory tidy.', + 'Goal cleared', + 'Goal set: Keep the current scratch directory tidy.' + ]) + }) + + it('keeps each thread’s goal separate', () => { + const { rows, frames: generic } = frames() + const other = '01a08cc3-0000-7000-8000-000000000000' + + generic.appendUnhandled('notification:thread/goal/updated', goalFrame({}), THREAD) + generic.appendUnhandled('notification:thread/goal/updated', goalFrame({}), other) + + expect(rows).toHaveLength(2) + }) + + it('leaves non-goal frames to the existing path', () => { + const { rows, frames: generic } = frames() + + generic.appendUnhandled('notification:warning', { message: 'disk almost full' }, THREAD) + generic.appendUnhandled('notification:warning', { message: 'disk almost full' }, THREAD) + + // No goal dedupe applies, so both warnings still land. + expect(rows).toHaveLength(2) + }) +}) diff --git a/src/main/codex/codex-structured-journal-goals.ts b/src/main/codex/codex-structured-journal-goals.ts new file mode 100644 index 00000000000..83bb66551ae --- /dev/null +++ b/src/main/codex/codex-structured-journal-goals.ts @@ -0,0 +1,177 @@ +import type { AgentJournalItemIdentity } from '../../shared/agent-session-journal-types' +import { unhandledProviderFrameJournalItem } from '../native-chat/agent-session-wire/unhandled-provider-frame' +import type { + StructuredAgentSessionEventSink, + StructuredAgentSessionLifecycleJournal +} from '../native-chat/agent-session-wire/structured-agent-session-event-sink' +import { + codexGoalJournalDigest, + codexGoalJournalIdentity, + parseCodexGoalJournalItemId, + type CodexGoalJournalState +} from './codex-goal-journal-identity' +import { + codexGoalGeneration, + codexGoalRowSignature, + isCodexGoalFrameMethod +} from './codex-goal-journal-rows' +import { + CODEX_JOURNAL_ADMITTED, + type CodexJournalTranslationAdmission +} from './codex-structured-journal-contracts' +import { MAX_CODEX_GOAL_THREADS } from './codex-structured-journal-limits' +import { appendCodexLifecycleTransition } from './codex-structured-journal-sink' + +type GoalThreadState = { + signature: string + occurrence: string +} + +/** Persists provider-owned goal lifecycle notifications outside generic-row policy. */ +export class CodexJournalGoals { + private readonly stateByThread = new Map() + private readonly durableStateByThread = new Map() + private durableJournal: StructuredAgentSessionLifecycleJournal | null = null + private durableEpoch: string | null = null + private transientEpoch: string | null = null + + constructor(private readonly sink: StructuredAgentSessionEventSink) {} + + handle(event: { + threadId: string + method: string + params: unknown + }): CodexJournalTranslationAdmission | null { + if (!isCodexGoalFrameMethod(event.method)) { + return null + } + const signature = codexGoalRowSignature(event.method, event.params) + if (signature === null) { + return null + } + this.synchronizeTransientEpoch() + const thread = codexGoalJournalDigest(event.threadId) + const reportedGeneration = codexGoalGeneration(event.params) + const providerGeneration = + reportedGeneration === null ? null : codexGoalJournalDigest(`provider:${reportedGeneration}`) + const signatureKey = codexGoalJournalDigest(`${signature}\u0000${providerGeneration ?? ''}`) + const previous = this.stateByThread.get(thread) + if (previous?.signature === signatureKey) { + this.remember(thread, previous) + return CODEX_JOURNAL_ADMITTED + } + const occurrence = previous + ? codexGoalJournalDigest(JSON.stringify([previous.occurrence, signatureKey])) + : codexGoalJournalDigest(JSON.stringify([thread, signatureKey])) + const state = { signature: signatureKey, occurrence } + const translated = unhandledProviderFrameJournalItem( + 'codex', + `notification:${event.method}`, + event.params + ) + if (!translated) { + return { accepted: false, reason: 'untranslated' } + } + const admission = appendCodexLifecycleTransition( + this.sink, + codexGoalJournalIdentity(thread, signatureKey, occurrence), + translated.body, + (journal) => + this.persistedGoalIdentity( + journal, + thread, + signatureKey, + event.method === 'thread/goal/cleared' + ) + ) + if (!admission.accepted) { + return admission + } + this.remember(thread, state) + return CODEX_JOURNAL_ADMITTED + } + + clear(): void { + this.stateByThread.clear() + this.durableStateByThread.clear() + this.durableJournal = null + this.durableEpoch = null + this.transientEpoch = null + } + + dispose(): void { + this.clear() + } + + private remember(thread: string, state: GoalThreadState): void { + this.stateByThread.delete(thread) + this.stateByThread.set(thread, state) + while (this.stateByThread.size > MAX_CODEX_GOAL_THREADS) { + const oldest = this.stateByThread.keys().next().value + if (typeof oldest !== 'string') { + break + } + this.stateByThread.delete(oldest) + } + } + + private synchronizeTransientEpoch(): void { + const epoch = this.sink.journalEpoch?.() ?? null + if (epoch === null) { + return + } + if (this.transientEpoch !== null && this.transientEpoch !== epoch) { + this.stateByThread.clear() + } + this.transientEpoch = epoch + } + + private persistedGoalIdentity( + journal: StructuredAgentSessionLifecycleJournal, + thread: string, + signature: string, + requirePrevious: boolean + ): AgentJournalItemIdentity | null { + this.seedDurableState(journal) + const previous = this.durableStateByThread.get(thread) ?? null + if (previous?.signature === signature) { + return null + } + // Codex sends a cleared snapshot while resuming threads that never had a goal. + if (previous === null && requirePrevious) { + return null + } + const occurrence = previous + ? codexGoalJournalDigest(JSON.stringify([previous.occurrence, signature])) + : codexGoalJournalDigest(JSON.stringify([thread, signature])) + this.durableStateByThread.set(thread, { signature, occurrence }) + return codexGoalJournalIdentity(thread, signature, occurrence) + } + + private seedDurableState(journal: StructuredAgentSessionLifecycleJournal): void { + if (this.durableJournal === journal && this.durableEpoch === journal.epoch) { + return + } + const latest = new Map() + journal.visitItems((itemId, sequence) => { + const state = parseCodexGoalJournalItemId(itemId) + const previous = state ? latest.get(state.thread) : undefined + if (state && (!previous || sequence > previous.sequence)) { + latest.set(state.thread, { state, sequence }) + } + }) + this.durableStateByThread.clear() + for (const [thread, { state }] of latest) { + this.durableStateByThread.set(thread, { + signature: state.signature, + occurrence: state.occurrence + }) + } + this.durableJournal = journal + this.durableEpoch = journal.epoch + if (this.transientEpoch !== null && this.transientEpoch !== journal.epoch) { + this.stateByThread.clear() + } + this.transientEpoch = journal.epoch + } +} diff --git a/src/main/codex/codex-structured-journal-limits.ts b/src/main/codex/codex-structured-journal-limits.ts index 5137ea8dd16..4f56cd0e282 100644 --- a/src/main/codex/codex-structured-journal-limits.ts +++ b/src/main/codex/codex-structured-journal-limits.ts @@ -2,6 +2,8 @@ export const MAX_CODEX_GENERIC_ROWS_PER_TURN = 8 export const MAX_CODEX_GENERIC_TURN_BUCKETS = 64 export const MAX_CODEX_GENERIC_BOOKKEEPING_ENTRIES = 128 export const MAX_CODEX_GENERIC_BOOKKEEPING_BYTES = 32 * 1024 +/** Goal duplicate-suppression state is LRU-bounded per live translator. */ +export const MAX_CODEX_GOAL_THREADS = 64 export const MAX_CODEX_ACTIVE_ITEMS = 256 export const MAX_CODEX_PENDING_PROMPTS = 128 export const MAX_CODEX_IDENTITY_ENTRIES = 512 diff --git a/src/main/codex/codex-structured-journal-sink.ts b/src/main/codex/codex-structured-journal-sink.ts index 5c4ecec9658..7da381def41 100644 --- a/src/main/codex/codex-structured-journal-sink.ts +++ b/src/main/codex/codex-structured-journal-sink.ts @@ -4,6 +4,7 @@ import type { } from '../../shared/agent-session-journal-types' import type { StructuredAgentSessionEventSink, + StructuredAgentSessionLifecycleIdentityResolver, StructuredAgentSessionSinkAdmission } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' import type { CodexPendingJournalPrompt } from './codex-structured-journal-settlement' @@ -28,6 +29,21 @@ export function appendCodexLifecycleItem( return CODEX_JOURNAL_ADMITTED } +export function appendCodexLifecycleTransition( + sink: StructuredAgentSessionEventSink, + identitySizeBound: AgentJournalItemIdentity, + body: AgentJournalItemBody, + resolveIdentity: StructuredAgentSessionLifecycleIdentityResolver +): CodexJournalTranslationAdmission { + if (sink.tryAppendLifecycleTransition) { + return criticalAdmission( + sink.tryAppendLifecycleTransition(identitySizeBound, body, resolveIdentity) + ) + } + const admission = appendCodexLifecycleItem(sink, identitySizeBound, body) + return admission.accepted ? publishCodexLifecycle(sink) : admission +} + export function publishCodexLifecycle( sink: StructuredAgentSessionEventSink ): CodexJournalTranslationAdmission { diff --git a/src/main/codex/codex-structured-journal-translation-settlement.test.ts b/src/main/codex/codex-structured-journal-translation-settlement.test.ts index f8a5c7a1671..b5e60699ce1 100644 --- a/src/main/codex/codex-structured-journal-translation-settlement.test.ts +++ b/src/main/codex/codex-structured-journal-translation-settlement.test.ts @@ -799,8 +799,9 @@ describe('codex journal translation', () => { const reduced = new Map(tap.rows.map((row) => [row.key, row.body])) expect(reduced.get('orca:codex-item%3Athread-abc%3Ar-1')).toEqual({ - kind: 'status', - text: 'thinking' + kind: 'message', + role: 'reasoning', + blocks: [{ type: 'text', text: 'thinking' }] }) expect(reduced.get('orca:codex-item%3Athread-abc%3Apatch-1')).toMatchObject({ kind: 'diff', diff --git a/src/main/codex/codex-structured-journal-translation.ts b/src/main/codex/codex-structured-journal-translation.ts index 2907b34bc70..5c1e97310bc 100644 --- a/src/main/codex/codex-structured-journal-translation.ts +++ b/src/main/codex/codex-structured-journal-translation.ts @@ -7,6 +7,7 @@ import { CodexSubagentRoster } from './codex-subagent-roster' import { readCodexThreadItem } from './codex-structured-item-translation' import { CodexJournalGenericFrames } from './codex-structured-journal-generic-frames' import { CodexJournalCompactions } from './codex-structured-journal-compactions' +import { CodexJournalGoals } from './codex-structured-journal-goals' import { CodexJournalItems } from './codex-structured-journal-items' import { CodexJournalPrompts } from './codex-structured-journal-prompts' import { @@ -51,6 +52,7 @@ export function createCodexJournalTranslator( const genericFrames = new CodexJournalGenericFrames(deps, (threadId) => activeTurns.current(threadId) ) + const goals = new CodexJournalGoals(deps.sink) const items = new CodexJournalItems( deps, (threadId) => activeTurns.current(threadId), @@ -178,6 +180,7 @@ export function createCodexJournalTranslator( prompts.pending.clear() activeTurns.clear() compactions.clear() + goals.clear() return CODEX_JOURNAL_ADMITTED } if (event.type === 'notification') { @@ -221,6 +224,10 @@ export function createCodexJournalTranslator( if (compaction) { return publishActivity(event, compaction) } + const goal = goals.handle(event) + if (goal) { + return publishActivity(event, goal) + } if (event.method === CODEX_TOKEN_USAGE_METHOD) { // Classified `status-chrome`, so the generic-frame path swallows it // before the journal. The roster consumes it as a typed notification. @@ -274,6 +281,7 @@ export function createCodexJournalTranslator( subagents.dispose() activeTurns.clear() compactions.clear() + goals.dispose() } } } diff --git a/src/main/codex/config-plugin-registration-promotion.test.ts b/src/main/codex/config-plugin-registration-promotion.test.ts new file mode 100644 index 00000000000..53cc9873f01 --- /dev/null +++ b/src/main/codex/config-plugin-registration-promotion.test.ts @@ -0,0 +1,687 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { homedir, tmpdir } from 'node:os' +import type * as Os from 'node:os' +import { join } from 'node:path' +import type * as CodexFsUtils from '../codex-accounts/fs-utils' + +const { homedirMock, registrationTestState } = vi.hoisted(() => ({ + homedirMock: vi.fn<() => string>(), + registrationTestState: { failAtomicWrite: false } +})) + +vi.mock('node:os', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + homedir: homedirMock + } +}) + +vi.mock('../codex-accounts/fs-utils', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + writeFileAtomically: (...args: Parameters) => { + if (registrationTestState.failAtomicWrite) { + throw new Error('injected atomic write failure') + } + return actual.writeFileAtomically(...args) + } + } +}) + +import { syncSystemConfigIntoManagedCodexHome } from './codex-config-mirror' +import { + getCodexRegistrationKey, + readCodexRegistrationEntries +} from './config-toml-plugin-registration-tables' + +// The tables Codex 0.145 writes into CODEX_HOME for `plugin marketplace add` +// followed by `plugin add`, including the quoted `@` key. +const MARKETPLACE_TABLE = [ + '[marketplaces.ponytail]', + 'source_type = "git"', + 'source = "https://github.com/DietrichGebert/ponytail.git"', + 'ref_name = "main"', + 'last_updated = "2026-01-05T10:00:00Z"', + 'last_revision = "aaaa111"' +].join('\n') + +const PLUGIN_TABLE = ['[plugins."ponytail@ponytail"]', 'enabled = true', 'version = "4.8.4"'].join( + '\n' +) + +const MARKETPLACE_KEY = getCodexRegistrationKey('marketplaces', 'ponytail') +const PLUGIN_KEY = getCodexRegistrationKey('plugins', 'ponytail@ponytail') + +let tmpHome: string +let userDataDir: string +let previousUserDataPath: string | undefined + +beforeEach(() => { + tmpHome = mkdtempSync(join(tmpdir(), 'orca-codex-registration-home-')) + userDataDir = mkdtempSync(join(tmpdir(), 'orca-codex-registration-user-data-')) + previousUserDataPath = process.env.ORCA_USER_DATA_PATH + process.env.ORCA_USER_DATA_PATH = userDataDir + homedirMock.mockReturnValue(tmpHome) + registrationTestState.failAtomicWrite = false + // Why: promotion writes into homedir()/.codex — if the mock ever fails to + // intercept, these tests would rewrite the developer's real Codex config. + if (homedir() !== tmpHome) { + throw new Error('node:os homedir mock is not active; refusing to touch the real ~/.codex') + } +}) + +afterEach(() => { + rmSync(tmpHome, { recursive: true, force: true }) + rmSync(userDataDir, { recursive: true, force: true }) + if (previousUserDataPath === undefined) { + delete process.env.ORCA_USER_DATA_PATH + } else { + process.env.ORCA_USER_DATA_PATH = previousUserDataPath + } + vi.clearAllMocks() +}) + +function systemHomeDir(): string { + return join(tmpHome, '.codex') +} + +function runtimeHomeDir(): string { + return join(userDataDir, 'codex-runtime-home', 'home') +} + +function runtimeConfigPath(): string { + return join(runtimeHomeDir(), 'config.toml') +} + +function baselinePath(homePath = runtimeHomeDir()): string { + return join(homePath, '.orca-config-settings-baseline.json') +} + +function writeSystemConfig(content: string, homePath = systemHomeDir()): void { + mkdirSync(homePath, { recursive: true }) + writeFileSync(join(homePath, 'config.toml'), content, 'utf-8') +} + +function readSystemConfig(homePath = systemHomeDir()): string { + return readFileSync(join(homePath, 'config.toml'), 'utf-8') +} + +function readRuntimeConfig(homePath = runtimeHomeDir()): string { + return readFileSync(join(homePath, 'config.toml'), 'utf-8') +} + +/** Mimics Codex appending a registration table to the CODEX_HOME it was launched with. */ +function simulateCodexRegistrationWrite(block: string, homePath = runtimeHomeDir()): void { + mkdirSync(homePath, { recursive: true }) + const configPath = join(homePath, 'config.toml') + const existing = existsSync(configPath) ? readFileSync(configPath, 'utf-8') : '' + writeFileSync(configPath, `${existing.trimEnd()}\n\n${block}\n`, 'utf-8') +} + +/** Mimics Codex rewriting a value inside a registration table it already owns. */ +function simulateCodexRegistrationFieldWrite( + field: string, + rawValue: string, + homePath = runtimeHomeDir() +): void { + const configPath = join(homePath, 'config.toml') + const pattern = new RegExp(`^${field}[ \\t]*=.*$`, 'm') + const existing = readFileSync(configPath, 'utf-8') + writeFileSync(configPath, existing.replace(pattern, `${field} = ${rawValue}`), 'utf-8') +} + +function mirrorTwice(): void { + syncSystemConfigIntoManagedCodexHome() + syncSystemConfigIntoManagedCodexHome() +} + +describe('codex plugin registration survives the managed-home mirror', () => { + it('keeps a marketplace and a quoted plugin registered from the managed home across two mirrors', () => { + writeSystemConfig('model = "gpt-5"\n') + syncSystemConfigIntoManagedCodexHome() + + simulateCodexRegistrationWrite(`${MARKETPLACE_TABLE}\n\n${PLUGIN_TABLE}`) + mirrorTwice() + + const runtime = readRuntimeConfig() + expect(runtime).toContain('[marketplaces.ponytail]') + expect(runtime).toContain('[plugins."ponytail@ponytail"]') + expect(runtime).toContain('enabled = true') + expect(readSystemConfig()).toContain('[marketplaces.ponytail]') + expect(readSystemConfig()).toContain('[plugins."ponytail@ponytail"]') + }) + + it('reaches a byte-stable steady state, so a repeated mirror is a no-op', () => { + writeSystemConfig('model = "gpt-5"\n') + syncSystemConfigIntoManagedCodexHome() + simulateCodexRegistrationWrite(`${MARKETPLACE_TABLE}\n\n${PLUGIN_TABLE}`) + mirrorTwice() + + const settledRuntime = readRuntimeConfig() + const settledSystem = readSystemConfig() + syncSystemConfigIntoManagedCodexHome() + + expect(readRuntimeConfig()).toBe(settledRuntime) + expect(readSystemConfig()).toBe(settledSystem) + }) + + // Why: #11770's metadata-only policy deliberately skips runtime-only + // marketplaces, so it would drop this one even though its timestamps are fine. + it('promotes a runtime-only marketplace that a metadata-only policy would drop', () => { + writeSystemConfig('model = "gpt-5"\n\n[marketplaces.other]\nsource = "other"\n') + syncSystemConfigIntoManagedCodexHome() + + simulateCodexRegistrationWrite(MARKETPLACE_TABLE) + mirrorTwice() + + expect(readSystemConfig()).toContain('[marketplaces.ponytail]') + expect(readRuntimeConfig()).toContain('[marketplaces.ponytail]') + expect(readRuntimeConfig()).toContain('[marketplaces.other]') + }) + + it('does not treat a cached marketplace clone or plugin directory as a registration', () => { + writeSystemConfig('model = "gpt-5"\n') + syncSystemConfigIntoManagedCodexHome() + mkdirSync(join(runtimeHomeDir(), '.tmp', 'marketplaces', 'ponytail'), { + recursive: true + }) + mkdirSync(join(runtimeHomeDir(), 'plugins', 'ponytail'), { + recursive: true + }) + + mirrorTwice() + + expect(readSystemConfig()).not.toContain('marketplaces') + expect(readRuntimeConfig()).not.toContain('marketplaces') + }) + + it('honors a canonical removal instead of resurrecting the registration', () => { + writeSystemConfig('model = "gpt-5"\n') + syncSystemConfigIntoManagedCodexHome() + simulateCodexRegistrationWrite(`${MARKETPLACE_TABLE}\n\n${PLUGIN_TABLE}`) + mirrorTwice() + expect(readSystemConfig()).toContain('[marketplaces.ponytail]') + + // The user edits ~/.codex outside Orca and deletes both registrations. + writeSystemConfig('model = "gpt-5"\n') + mirrorTwice() + + expect(readSystemConfig()).toBe('model = "gpt-5"\n') + expect(readRuntimeConfig()).not.toContain('marketplaces.ponytail') + expect(readRuntimeConfig()).not.toContain('ponytail@ponytail') + }) + + it('re-mirrors a canonical registration the managed home deleted rather than propagating the delete', () => { + writeSystemConfig(`model = "gpt-5"\n\n${MARKETPLACE_TABLE}\n\n${PLUGIN_TABLE}\n`) + syncSystemConfigIntoManagedCodexHome() + + writeFileSync(runtimeConfigPath(), 'model = "gpt-5"\n', 'utf-8') + mirrorTwice() + + expect(readSystemConfig()).toContain('[plugins."ponytail@ponytail"]') + expect(readRuntimeConfig()).toContain('[plugins."ponytail@ponytail"]') + }) + + it('promotes an in-Codex plugin disable and keeps it disabled', () => { + writeSystemConfig(`model = "gpt-5"\n\n${MARKETPLACE_TABLE}\n\n${PLUGIN_TABLE}\n`) + syncSystemConfigIntoManagedCodexHome() + + simulateCodexRegistrationFieldWrite('enabled', 'false') + mirrorTwice() + + expect(readSystemConfig()).toContain('enabled = false') + expect(readRuntimeConfig()).toContain('enabled = false') + }) + + it('lets the canonical config win when both sides changed plugin enablement', () => { + writeSystemConfig(`model = "gpt-5"\n\n${MARKETPLACE_TABLE}\n\n${PLUGIN_TABLE}\n`) + syncSystemConfigIntoManagedCodexHome() + + simulateCodexRegistrationFieldWrite('enabled', 'false') + writeSystemConfig( + `model = "gpt-5"\n\n${MARKETPLACE_TABLE}\n\n${PLUGIN_TABLE.replace('enabled = true', 'enabled = false\ndisabled_reason = "canonical"')}\n` + ) + mirrorTwice() + + expect(readSystemConfig()).toContain('disabled_reason = "canonical"') + expect(readRuntimeConfig()).toContain('disabled_reason = "canonical"') + }) + + // Why: `enabled` is three-valued in practice — true, false, and absent — so + // "both sides changed" is only reachable when one of them adds the key. + it('lets the canonical config win when enablement changed to a different value on each side', () => { + writeSystemConfig( + `model = "gpt-5"\n\n${MARKETPLACE_TABLE}\n\n${PLUGIN_TABLE.replace('enabled = true\n', '')}\n` + ) + syncSystemConfigIntoManagedCodexHome() + expect(readFileSync(baselinePath(), 'utf-8')).not.toContain('"enabled"') + + writeFileSync( + runtimeConfigPath(), + readRuntimeConfig().replace('version = "4.8.4"', 'version = "4.8.4"\nenabled = false'), + 'utf-8' + ) + writeSystemConfig( + readSystemConfig().replace('version = "4.8.4"', 'version = "4.8.4"\nenabled = true') + ) + mirrorTwice() + + expect(readSystemConfig()).toContain('enabled = true') + expect(readSystemConfig()).not.toContain('enabled = false') + expect(readRuntimeConfig()).toContain('enabled = true') + }) + + it('lets the canonical config win when the registration has no mirrored ancestor', () => { + writeSystemConfig(`model = "gpt-5"\n\n${MARKETPLACE_TABLE}\n\n${PLUGIN_TABLE}\n`) + syncSystemConfigIntoManagedCodexHome() + + simulateCodexRegistrationFieldWrite('enabled', 'false') + // A v2 baseline, or one rebuilt after corruption, tracks no registration at all. + const baseline = JSON.parse(readFileSync(baselinePath(), 'utf-8')) + delete baseline.registrations + writeFileSync(baselinePath(), `${JSON.stringify(baseline, null, 2)}\n`, 'utf-8') + mirrorTwice() + + expect(readSystemConfig()).toContain('enabled = true') + expect(readRuntimeConfig()).toContain('enabled = true') + }) + + it('keeps an unrelated canonical edit authoritative while a registration is promoted', () => { + writeSystemConfig('model = "gpt-5"\n') + syncSystemConfigIntoManagedCodexHome() + + simulateCodexRegistrationWrite(MARKETPLACE_TABLE) + writeSystemConfig('model = "gpt-5-canonical"\n\n[features]\nhooks = true\n') + mirrorTwice() + + expect(readRuntimeConfig()).toContain('model = "gpt-5-canonical"') + expect(readRuntimeConfig()).toContain('hooks = true') + expect(readRuntimeConfig()).toContain('[marketplaces.ponytail]') + }) +}) + +describe('codex marketplace refresh metadata promotion', () => { + function seedMirroredMarketplace(): void { + writeSystemConfig( + `# user comment\nmodel = "gpt-5"\n\n${MARKETPLACE_TABLE}\n\n[mcp_servers.docs]\ncommand = "docs"\n` + ) + syncSystemConfigIntoManagedCodexHome() + } + + it('promotes a newer last_updated with its paired last_revision', () => { + seedMirroredMarketplace() + + simulateCodexRegistrationFieldWrite('last_updated', '"2026-02-01T09:30:00Z"') + simulateCodexRegistrationFieldWrite('last_revision', '"bbbb222"') + syncSystemConfigIntoManagedCodexHome() + + const system = readSystemConfig() + expect(system).toContain('last_updated = "2026-02-01T09:30:00Z"') + expect(system).toContain('last_revision = "bbbb222"') + // Every other field, the comment, and unrelated tables are untouched. + expect(system).toContain('# user comment') + expect(system).toContain('ref_name = "main"') + expect(system).toContain('[mcp_servers.docs]') + expect(system).toContain('source = "https://github.com/DietrichGebert/ponytail.git"') + }) + + it('does not repeat the refresh on the next synchronization', () => { + seedMirroredMarketplace() + simulateCodexRegistrationFieldWrite('last_updated', '"2026-02-01T09:30:00Z"') + simulateCodexRegistrationFieldWrite('last_revision', '"bbbb222"') + mirrorTwice() + + const settledSystem = readSystemConfig() + const settledRuntime = readRuntimeConfig() + syncSystemConfigIntoManagedCodexHome() + + expect(readSystemConfig()).toBe(settledSystem) + expect(readRuntimeConfig()).toBe(settledRuntime) + }) + + it('skips an older managed timestamp', () => { + seedMirroredMarketplace() + + simulateCodexRegistrationFieldWrite('last_updated', '"2020-01-01T00:00:00Z"') + simulateCodexRegistrationFieldWrite('last_revision', '"stale99"') + syncSystemConfigIntoManagedCodexHome() + + expect(readSystemConfig()).toContain('last_updated = "2026-01-05T10:00:00Z"') + expect(readSystemConfig()).toContain('last_revision = "aaaa111"') + }) + + it('skips a malformed managed timestamp', () => { + seedMirroredMarketplace() + + simulateCodexRegistrationFieldWrite('last_updated', '"not-a-timestamp"') + simulateCodexRegistrationFieldWrite('last_revision', '"cccc333"') + syncSystemConfigIntoManagedCodexHome() + + expect(readSystemConfig()).toContain('last_updated = "2026-01-05T10:00:00Z"') + expect(readSystemConfig()).toContain('last_revision = "aaaa111"') + }) + + // Why: Date.parse rolls an impossible day forward, which would read as newer. + it('rejects an impossible calendar date instead of rolling it forward', () => { + seedMirroredMarketplace() + + simulateCodexRegistrationFieldWrite('last_updated', '"2026-02-30T00:00:00Z"') + simulateCodexRegistrationFieldWrite('last_revision', '"rolled99"') + syncSystemConfigIntoManagedCodexHome() + + expect(readSystemConfig()).toContain('last_updated = "2026-01-05T10:00:00Z"') + expect(readSystemConfig()).toContain('last_revision = "aaaa111"') + }) + + it('skips the refresh when the runtime cannot supply the paired last_revision', () => { + seedMirroredMarketplace() + + writeFileSync( + runtimeConfigPath(), + readRuntimeConfig() + .replace('last_updated = "2026-01-05T10:00:00Z"', 'last_updated = "2026-09-01T00:00:00Z"') + .replace('last_revision = "aaaa111"\n', ''), + 'utf-8' + ) + syncSystemConfigIntoManagedCodexHome() + + expect(readSystemConfig()).toContain('last_updated = "2026-01-05T10:00:00Z"') + expect(readSystemConfig()).toContain('last_revision = "aaaa111"') + }) + + it('leaves the canonical config in control when the marketplace source changed', () => { + seedMirroredMarketplace() + + simulateCodexRegistrationFieldWrite('last_updated', '"2026-02-01T09:30:00Z"') + simulateCodexRegistrationFieldWrite('last_revision', '"bbbb222"') + writeSystemConfig( + readSystemConfig().replace( + 'source = "https://github.com/DietrichGebert/ponytail.git"', + 'source = "https://github.com/DietrichGebert/ponytail-fork.git"' + ) + ) + syncSystemConfigIntoManagedCodexHome() + + expect(readSystemConfig()).toContain('last_updated = "2026-01-05T10:00:00Z"') + expect(readSystemConfig()).toContain('ponytail-fork.git') + expect(readRuntimeConfig()).toContain('ponytail-fork.git') + }) + + it('refreshes several marketplaces independently', () => { + writeSystemConfig( + [ + 'model = "gpt-5"', + '', + MARKETPLACE_TABLE, + '', + '[marketplaces.other]', + 'source_type = "git"', + 'source = "https://example.test/other.git"', + 'last_updated = "2026-01-05T10:00:00Z"', + 'last_revision = "other111"', + '' + ].join('\n') + ) + syncSystemConfigIntoManagedCodexHome() + + const runtime = readRuntimeConfig() + .replace('last_updated = "2026-01-05T10:00:00Z"', 'last_updated = "2026-03-01T00:00:00Z"') + .replace('last_revision = "aaaa111"', 'last_revision = "fresh11"') + writeFileSync(runtimeConfigPath(), runtime, 'utf-8') + syncSystemConfigIntoManagedCodexHome() + + const system = readSystemConfig() + expect(system).toContain('last_updated = "2026-03-01T00:00:00Z"') + expect(system).toContain('last_revision = "fresh11"') + expect(system).toContain('last_revision = "other111"') + expect(system).toContain('last_updated = "2026-01-05T10:00:00Z"') + }) + + it('promotes only last_updated and last_revision, never another refreshed field', () => { + writeSystemConfig(`model = "gpt-5"\n\n${MARKETPLACE_TABLE}\ndescription = "canonical"\n`) + syncSystemConfigIntoManagedCodexHome() + + simulateCodexRegistrationFieldWrite('last_updated', '"2026-02-01T09:30:00Z"') + simulateCodexRegistrationFieldWrite('description', '"runtime"') + syncSystemConfigIntoManagedCodexHome() + + expect(readSystemConfig()).toContain('last_updated = "2026-02-01T09:30:00Z"') + expect(readSystemConfig()).toContain('description = "canonical"') + expect(readRuntimeConfig()).toContain('description = "canonical"') + }) + + it('seeds an absent canonical config from the runtime without duplicating its tables', () => { + writeSystemConfig('[features]\nhooks = true\n') + syncSystemConfigIntoManagedCodexHome() + + rmSync(join(systemHomeDir(), 'config.toml')) + simulateCodexRegistrationWrite(MARKETPLACE_TABLE) + writeFileSync(runtimeConfigPath(), `model = "o4"\n${readRuntimeConfig()}`, 'utf-8') + mirrorTwice() + + const system = readSystemConfig() + expect(system).toContain('model = "o4"') + expect(system.match(/\[marketplaces\.ponytail\]/g)).toHaveLength(1) + expect(readRuntimeConfig().match(/\[marketplaces\.ponytail\]/g)).toHaveLength(1) + }) + + it('preserves the managed config and its baseline when the promotion write fails', () => { + writeSystemConfig('model = "gpt-5"\n') + syncSystemConfigIntoManagedCodexHome() + simulateCodexRegistrationWrite(MARKETPLACE_TABLE) + const runtimeBeforeFailure = readRuntimeConfig() + const baselineBeforeFailure = readFileSync(baselinePath(), 'utf-8') + + registrationTestState.failAtomicWrite = true + syncSystemConfigIntoManagedCodexHome() + + expect(readSystemConfig()).toBe('model = "gpt-5"\n') + expect(readRuntimeConfig()).toBe(runtimeBeforeFailure) + expect(readFileSync(baselinePath(), 'utf-8')).toBe(baselineBeforeFailure) + + registrationTestState.failAtomicWrite = false + mirrorTwice() + + expect(readSystemConfig()).toContain('[marketplaces.ponytail]') + expect(readRuntimeConfig()).toContain('[marketplaces.ponytail]') + }) + + it('keeps CRLF line endings when it rewrites refresh metadata', () => { + writeSystemConfig(`model = "gpt-5"\r\n\r\n${MARKETPLACE_TABLE.replaceAll('\n', '\r\n')}\r\n`) + syncSystemConfigIntoManagedCodexHome() + + simulateCodexRegistrationFieldWrite('last_updated', '"2026-02-01T09:30:00Z"') + syncSystemConfigIntoManagedCodexHome() + + const system = readSystemConfig() + expect(system).toContain('last_updated = "2026-02-01T09:30:00Z"\r\n') + expect(system).not.toMatch(/[^\r]\n/) + }) +}) + +describe('codex registration reconciliation isolates accounts and source homes', () => { + function accountHome(name: string): string { + return join(userDataDir, 'codex-accounts', name) + } + + it('promotes each managed account registration into the shared source without crossing baselines', () => { + writeSystemConfig('model = "gpt-5"\n') + const accounts = [accountHome('a'), accountHome('b')] + for (const runtimeHomePath of accounts) { + syncSystemConfigIntoManagedCodexHome({ + runtimeHomePath, + systemHomePath: systemHomeDir() + }) + } + + simulateCodexRegistrationWrite(MARKETPLACE_TABLE, accounts[0]!) + simulateCodexRegistrationWrite( + '[marketplaces.beta]\nsource_type = "git"\nsource = "https://example.test/beta.git"', + accounts[1]! + ) + for (const runtimeHomePath of [...accounts, ...accounts]) { + syncSystemConfigIntoManagedCodexHome({ + runtimeHomePath, + systemHomePath: systemHomeDir() + }) + } + + expect(readSystemConfig()).toContain('[marketplaces.ponytail]') + expect(readSystemConfig()).toContain('[marketplaces.beta]') + for (const runtimeHomePath of accounts) { + expect(readRuntimeConfig(runtimeHomePath)).toContain('[marketplaces.ponytail]') + expect(readRuntimeConfig(runtimeHomePath)).toContain('[marketplaces.beta]') + expect(existsSync(baselinePath(runtimeHomePath))).toBe(true) + } + expect(readFileSync(baselinePath(accounts[0]!), 'utf-8')).toContain('marketplaces:ponytail') + }) + + it('promotes a WSL-lane registration into that distro source home, never the host one', () => { + const wslSourceHome = join(userDataDir, 'wsl-home', '.codex') + const wslRuntimeHome = accountHome('wsl') + writeSystemConfig('model = "host"\n') + writeSystemConfig('model = "wsl"\n', wslSourceHome) + syncSystemConfigIntoManagedCodexHome({ + runtimeHomePath: wslRuntimeHome, + systemHomePath: wslSourceHome + }) + + simulateCodexRegistrationWrite(MARKETPLACE_TABLE, wslRuntimeHome) + for (let pass = 0; pass < 2; pass += 1) { + syncSystemConfigIntoManagedCodexHome({ + runtimeHomePath: wslRuntimeHome, + systemHomePath: wslSourceHome + }) + } + + expect(readSystemConfig(wslSourceHome)).toContain('[marketplaces.ponytail]') + expect(readRuntimeConfig(wslRuntimeHome)).toContain('[marketplaces.ponytail]') + expect(readSystemConfig()).toBe('model = "host"\n') + }) + + it('heals a registration held only by a runtime home still on the v2 baseline schema', () => { + writeSystemConfig('model = "gpt-5"\n') + syncSystemConfigIntoManagedCodexHome() + const { settings } = JSON.parse(readFileSync(baselinePath(), 'utf-8')) + writeFileSync(baselinePath(), `${JSON.stringify({ version: 2, settings }, null, 2)}\n`, 'utf-8') + + simulateCodexRegistrationWrite(`${MARKETPLACE_TABLE}\n\n${PLUGIN_TABLE}`) + mirrorTwice() + + expect(readSystemConfig()).toContain('[marketplaces.ponytail]') + expect(readSystemConfig()).toContain('[plugins."ponytail@ponytail"]') + expect(readRuntimeConfig()).toContain('[plugins."ponytail@ponytail"]') + expect(JSON.parse(readFileSync(baselinePath(), 'utf-8'))).toMatchObject({ + version: 3, + registrations: { [MARKETPLACE_KEY]: {}, [PLUGIN_KEY]: { enabled: 'true' } } + }) + }) + + // Why: the baseline is the only record of what a mirror already made canonical, + // so losing it re-reads a pending canonical removal as a runtime-only addition. + it('re-promotes a canonically removed registration when the baseline is lost first', () => { + writeSystemConfig('model = "gpt-5"\n') + syncSystemConfigIntoManagedCodexHome() + simulateCodexRegistrationWrite(MARKETPLACE_TABLE) + mirrorTwice() + + writeSystemConfig('model = "gpt-5"\n') + rmSync(baselinePath()) + mirrorTwice() + expect(readSystemConfig()).toContain('[marketplaces.ponytail]') + + // Recoverable: with the rebuilt baseline in place, removing it again sticks. + writeSystemConfig('model = "gpt-5"\n') + mirrorTwice() + expect(readSystemConfig()).toBe('model = "gpt-5"\n') + }) + + it('leaves a settled config byte-identical when the baseline is lost with no removal pending', () => { + writeSystemConfig('model = "gpt-5"\n') + syncSystemConfigIntoManagedCodexHome() + simulateCodexRegistrationWrite(MARKETPLACE_TABLE) + mirrorTwice() + const settledSystem = readSystemConfig() + const settledRuntime = readRuntimeConfig() + + rmSync(baselinePath()) + mirrorTwice() + + expect(readSystemConfig()).toBe(settledSystem) + expect(readRuntimeConfig()).toBe(settledRuntime) + }) + + it('treats a runtime home seeded without a baseline as holding additions, not removals', () => { + mkdirSync(runtimeHomeDir(), { recursive: true }) + writeFileSync(runtimeConfigPath(), `model = "gpt-5"\n\n${MARKETPLACE_TABLE}\n`, 'utf-8') + writeSystemConfig('model = "gpt-5"\n') + + mirrorTwice() + + expect(readSystemConfig()).toContain('[marketplaces.ponytail]') + expect(readRuntimeConfig()).toContain('[marketplaces.ponytail]') + }) +}) + +describe('codex registration table identity', () => { + it('reads basic-quoted and literal-quoted table keys as the same registration', () => { + const basic = readCodexRegistrationEntries('[plugins."a@b"]\nenabled = true\n') + const literal = readCodexRegistrationEntries("[plugins.'a@b']\nenabled = false\n") + + expect([...basic.keys()]).toEqual([getCodexRegistrationKey('plugins', 'a@b')]) + expect([...literal.keys()]).toEqual([...basic.keys()]) + }) + + it('captures a multiline array field as one value and marks it unwritable', () => { + const entries = readCodexRegistrationEntries( + '[marketplaces.m]\nsparse_paths = [\n "a",\n "b"\n]\nsource = "s"\n' + ) + const entry = entries.get(getCodexRegistrationKey('marketplaces', 'm')) + + expect(entry?.fields.get('sparse_paths')?.multiline).toBe(true) + expect(entry?.fields.get('sparse_paths')?.raw).toContain('"b"') + expect(entry?.fields.get('source')?.raw).toBe('"s"') + }) + + it('attributes a subtable to its owning registration', () => { + const entries = readCodexRegistrationEntries( + '[marketplaces.m]\nsource = "s"\n\n[marketplaces.m.auth]\ntoken = "t"\n' + ) + const entry = entries.get(getCodexRegistrationKey('marketplaces', 'm')) + + expect(entries.size).toBe(1) + expect(entry?.block).toContain('[marketplaces.m.auth]') + expect(entry?.fields.has('token')).toBe(false) + }) + + it("leaves the next table's leading comment out of the captured block", () => { + const entries = readCodexRegistrationEntries( + '[marketplaces.m]\nsource = "s" # inline\n# keeps this one\nkey = 1\n\n# belongs to mcp_servers\n[mcp_servers.docs]\ncommand = "d"\n' + ) + const block = entries.get(getCodexRegistrationKey('marketplaces', 'm'))?.block + + expect(block).toContain('# keeps this one') + expect(block).toContain('source = "s" # inline') + expect(block).not.toContain('belongs to mcp_servers') + }) + + it('keeps a hash inside a multiline value out of the trailing-comment trim', () => { + const entries = readCodexRegistrationEntries( + '[marketplaces.m]\nnotes = """\n# not a comment"""\n\n[mcp_servers.docs]\ncommand = "d"\n' + ) + const block = entries.get(getCodexRegistrationKey('marketplaces', 'm'))?.block + + expect(block).toContain('# not a comment"""') + }) + + it('ignores an array-of-tables header under a registration root', () => { + expect(readCodexRegistrationEntries('[[marketplaces.m]]\nsource = "s"\n').size).toBe(0) + }) + + it('keys marketplace and plugin registrations in separate namespaces', () => { + expect(MARKETPLACE_KEY).not.toBe(PLUGIN_KEY) + }) +}) diff --git a/src/main/codex/config-plugin-registration-promotion.ts b/src/main/codex/config-plugin-registration-promotion.ts new file mode 100644 index 00000000000..b23df7844ac --- /dev/null +++ b/src/main/codex/config-plugin-registration-promotion.ts @@ -0,0 +1,273 @@ +import { joinPreservingTrailingNewline, withCrLine, withTrailingCr } from './config-toml-line-scan' +import { + normalizeCodexRegistrationValue, + parseCodexRegistrationTimestamp, + readCodexRegistrationEntries, + type CodexRegistrationEntry, + type CodexRegistrationRoot +} from './config-toml-plugin-registration-tables' + +/** + * Reconciles Codex plugin registration tables across the destructive managed-home + * mirror. Scalar promotion covers settings the TUI writes; these are whole tables + * Codex writes when a marketplace or plugin is registered or refreshed, and they + * need two different conflict rules inside one baseline-aware boundary: + * + * | Runtime vs canonical vs baseline | Policy | + * | ---------------------------------------------------- | ---------------------------------------------- | + * | in runtime, not canonical, not in baseline | runtime-only addition -> promote the table | + * | in runtime, not canonical, in baseline | canonical removal -> honor it, promote nothing | + * | in both, identity fields differ | canonical source change -> canonical wins | + * | in both, marketplace, newer valid `last_updated` | promote `last_updated` + paired `last_revision` | + * | in both, marketplace, stale/malformed `last_updated` | skip | + * | in both, plugin, `enabled` changed only in runtime | promote `enabled` | + * | in both, plugin, `enabled` changed on both sides | canonical wins | + * | anything else | canonical wins; the mirror overwrites it | + * + * Presence stays canonical-owned once mirrored, so a runtime-side removal is + * re-mirrored rather than propagated; `enabled` is the durable runtime lever. + */ + +// Why: a marketplace whose source moved is a different marketplace, so its +// refresh metadata describes a clone the canonical config no longer points at. +const MARKETPLACE_IDENTITY_FIELDS = ['source_type', 'source', 'ref_name', 'sparse_paths'] as const +const PLUGIN_IDENTITY_FIELDS = ['marketplace', 'source'] as const + +const MARKETPLACE_METADATA_FIELDS = ['last_updated', 'last_revision'] as const + +// Why: the only registration field the baseline needs a three-way ancestor for. +const PLUGIN_BASELINE_FIELDS = ['enabled'] as const + +export type CodexRegistrationPromotion = + | { kind: 'append'; key: string; block: string } + | { kind: 'field'; key: string; field: string; raw: string | null } + +export type CodexRegistrationBaseline = ReadonlyMap> + +export function planCodexRegistrationPromotion( + runtimeConfig: string, + systemConfig: string, + mirroredRegistrations: CodexRegistrationBaseline +): CodexRegistrationPromotion[] { + const runtimeEntries = readCodexRegistrationEntries(runtimeConfig) + const systemEntries = readCodexRegistrationEntries(systemConfig) + // Why: a marketplace must be declared before the plugins that name it, so the + // canonical file stays readable after an install promotes both at once. + const appends: Record = { + marketplaces: [], + plugins: [] + } + const fields: CodexRegistrationPromotion[] = [] + for (const entry of runtimeEntries.values()) { + const systemEntry = systemEntries.get(entry.key) + if (!systemEntry) { + if (!mirroredRegistrations.has(entry.key)) { + appends[entry.root].push({ kind: 'append', key: entry.key, block: entry.block }) + } + continue + } + if (!hasMatchingRegistrationIdentity(entry, systemEntry)) { + continue + } + fields.push( + ...(entry.root === 'marketplaces' + ? planMarketplaceRefreshPromotion(entry, systemEntry) + : planPluginEnablementPromotion(entry, systemEntry, mirroredRegistrations.get(entry.key))) + ) + } + return [...appends.marketplaces, ...appends.plugins, ...fields] +} + +export function applyCodexRegistrationPromotions( + content: string, + promotions: readonly CodexRegistrationPromotion[] +): string { + if (promotions.length === 0) { + return content + } + const usesCrlf = content.includes('\r\n') + const lines = content.split('\n') + const entries = readCodexRegistrationEntries(content) + const edits: { index: number; deleteCount: number; inserts: string[] }[] = [] + for (const promotion of promotions) { + if (promotion.kind !== 'field') { + continue + } + const entry = entries.get(promotion.key) + const existing = entry?.fields.get(promotion.field) + if (!entry || entry.ownerStart === -1 || existing?.multiline) { + continue + } + const rendered = `${promotion.field} = ${promotion.raw}` + if (existing) { + edits.push({ + index: existing.lineIndex, + deleteCount: 1, + inserts: + promotion.raw === null ? [] : [withTrailingCr(lines[existing.lineIndex] ?? '', rendered)] + }) + continue + } + if (promotion.raw === null) { + continue + } + edits.push({ + index: findTableBodyInsertIndex(lines, entry), + deleteCount: 0, + inserts: [withCrLine(rendered, usesCrlf)] + }) + } + // Why: splice from the bottom so an earlier edit never shifts an index a later + // one was measured against. + for (const edit of edits.sort((left, right) => right.index - left.index)) { + lines.splice(edit.index, edit.deleteCount, ...edit.inserts) + } + let result = joinPreservingTrailingNewline(lines, usesCrlf) + for (const promotion of promotions) { + if (promotion.kind === 'append') { + result = appendRegistrationBlock(result, promotion.block, usesCrlf) + } + } + return result +} + +/** The registration state a successful mirror made canonical, for the next pass's three-way. */ +export function readCodexRegistrationBaseline( + config: string +): Map> { + const baseline = new Map>() + for (const entry of readCodexRegistrationEntries(config).values()) { + const tracked = new Map() + for (const field of getBaselineFields(entry.root)) { + const value = entry.fields.get(field) + if (value && !value.multiline) { + tracked.set(field, normalizeCodexRegistrationValue(value.raw)) + } + } + baseline.set(entry.key, tracked) + } + return baseline +} + +function getBaselineFields(root: CodexRegistrationRoot): readonly string[] { + return root === 'plugins' ? PLUGIN_BASELINE_FIELDS : [] +} + +function hasMatchingRegistrationIdentity( + runtimeEntry: CodexRegistrationEntry, + systemEntry: CodexRegistrationEntry +): boolean { + const identityFields = + runtimeEntry.root === 'marketplaces' ? MARKETPLACE_IDENTITY_FIELDS : PLUGIN_IDENTITY_FIELDS + return identityFields.every( + (field) => readNormalizedField(runtimeEntry, field) === readNormalizedField(systemEntry, field) + ) +} + +function planMarketplaceRefreshPromotion( + runtimeEntry: CodexRegistrationEntry, + systemEntry: CodexRegistrationEntry +): CodexRegistrationPromotion[] { + const runtimeUpdated = runtimeEntry.fields.get('last_updated') + const runtimeRevision = runtimeEntry.fields.get('last_revision') + if (!runtimeUpdated || runtimeUpdated.multiline || runtimeRevision?.multiline) { + return [] + } + // Why: promoting the timestamp alone would clear a canonical revision the runtime + // cannot replace, publishing exactly the mismatched pair the pairing rule prevents. + if (!runtimeRevision && systemEntry.fields.has('last_revision')) { + return [] + } + const runtimeTimestamp = parseCodexRegistrationTimestamp(runtimeUpdated.raw) + if (runtimeTimestamp === null) { + return [] + } + const systemUpdated = systemEntry.fields.get('last_updated') + const systemTimestamp = + systemUpdated && !systemUpdated.multiline + ? parseCodexRegistrationTimestamp(systemUpdated.raw) + : null + if (systemTimestamp !== null && runtimeTimestamp <= systemTimestamp) { + return [] + } + // Why: the revision names the commit the timestamp refreshed to, so promoting + // one without the other would publish a pair that never existed together. + return MARKETPLACE_METADATA_FIELDS.flatMap((field) => + buildFieldPromotion(runtimeEntry, systemEntry, field) + ) +} + +function planPluginEnablementPromotion( + runtimeEntry: CodexRegistrationEntry, + systemEntry: CodexRegistrationEntry, + mirrored: ReadonlyMap | undefined +): CodexRegistrationPromotion[] { + const runtimeValue = readNormalizedField(runtimeEntry, 'enabled') + const systemValue = readNormalizedField(systemEntry, 'enabled') + // Why: without a mirrored ancestor an in-Codex toggle is indistinguishable from + // a stale runtime copy, so the canonical config stays source of truth. + const mirroredValue = mirrored?.get('enabled') ?? null + if ( + !mirrored || + runtimeValue === systemValue || + runtimeValue === mirroredValue || + systemValue !== mirroredValue + ) { + return [] + } + return buildFieldPromotion(runtimeEntry, systemEntry, 'enabled') +} + +function buildFieldPromotion( + runtimeEntry: CodexRegistrationEntry, + systemEntry: CodexRegistrationEntry, + field: string +): CodexRegistrationPromotion[] { + if (readNormalizedField(runtimeEntry, field) === readNormalizedField(systemEntry, field)) { + return [] + } + const runtimeField = runtimeEntry.fields.get(field) + if (runtimeField?.multiline) { + return [] + } + return [ + { + kind: 'field', + key: runtimeEntry.key, + field, + raw: runtimeField?.raw ?? null + } + ] +} + +function readNormalizedField(entry: CodexRegistrationEntry, field: string): string | null { + const value = entry.fields.get(field) + return value ? normalizeCodexRegistrationValue(value.raw) : null +} + +// Why: a key added after a `[root.name.*]` subtable opens would land in the wrong +// table, so absent fields go at the owner body's end, before its trailing blanks. +function findTableBodyInsertIndex(lines: string[], entry: CodexRegistrationEntry): number { + let insertAt = entry.ownerEnd + while (insertAt > entry.ownerStart + 1 && (lines[insertAt - 1] ?? '').trim() === '') { + insertAt -= 1 + } + return insertAt +} + +function appendRegistrationBlock(content: string, block: string, usesCrlf: boolean): string { + const eol = usesCrlf ? '\r\n' : '\n' + const rendered = block + .split('\n') + .map((line) => withCrLine(line.replace(/\r$/, ''), usesCrlf)) + .join('\n') + if (content.trim() === '') { + return `${rendered}${eol}` + } + const separator = content.endsWith(`${eol}${eol}`) + ? '' + : content.endsWith(eol) + ? eol + : `${eol}${eol}` + return `${content}${separator}${rendered}${eol}` +} diff --git a/src/main/codex/config-settings-baseline-upgrade.test.ts b/src/main/codex/config-settings-baseline-upgrade.test.ts index 443f5f429ec..1f49c2bafee 100644 --- a/src/main/codex/config-settings-baseline-upgrade.test.ts +++ b/src/main/codex/config-settings-baseline-upgrade.test.ts @@ -85,7 +85,7 @@ describe('Codex settings baseline schema upgrade', () => { syncSystemConfigIntoManagedCodexHome() expect(readBaseline()).toMatchObject({ - version: 2, + version: 3, settings: { model: '"gpt-5"', 'tui.theme': '"dark"' } }) expect(readBaseline().conflicts).toBeUndefined() diff --git a/src/main/codex/config-settings-baseline.ts b/src/main/codex/config-settings-baseline.ts index c771f3f7d37..5cc26e361b9 100644 --- a/src/main/codex/config-settings-baseline.ts +++ b/src/main/codex/config-settings-baseline.ts @@ -15,12 +15,19 @@ export type CodexSettingsConflict = { export type CodexSettingsBaseline = { settings: ReadonlyMap conflicts: ReadonlyMap + /** + * Plugin/marketplace tables the last mirror made canonical, with the fields a + * three-way needs. An absent entry means "never mirrored", so a runtime-only + * table reads as an addition rather than as a canonical removal. + */ + registrations: ReadonlyMap> } type StoredSettingsBaseline = { - version: 1 | 2 + version: 1 | 2 | 3 settings: Record conflicts?: Record + registrations?: Record> } /** @@ -74,7 +81,7 @@ function readParsedCodexSettingsBaseline( conflicts.set(key, conflict) } } - return { settings, conflicts } + return { settings, conflicts, registrations: readStoredRegistrations(parsed.registrations) } } catch (error) { // Why: invalid baseline state is still `null` — resetting it is the intent, // and only a read that FAILED must be preserved. @@ -82,6 +89,26 @@ function readParsedCodexSettingsBaseline( } } +function readStoredRegistrations( + stored: Record> | undefined +): Map> { + const registrations = new Map>() + for (const [key, fields] of Object.entries(stored ?? {})) { + if (!fields || typeof fields !== 'object' || Array.isArray(fields)) { + continue + } + registrations.set( + key, + new Map( + Object.entries(fields).filter((entry): entry is [string, string] => { + return typeof entry[1] === 'string' + }) + ) + ) + } + return registrations +} + /** Why: known-present baseline state outside its parse/capacity contract is rebuildable, not unreadable. */ function isRebuildableBaselineError(error: unknown): boolean { return ( @@ -96,12 +123,17 @@ export function writeCodexSettingsBaseline( baseline: CodexSettingsBaseline ): void { const file: StoredSettingsBaseline = { - version: 2, + version: 3, settings: Object.fromEntries(baseline.settings) } if (baseline.conflicts.size > 0) { file.conflicts = Object.fromEntries(baseline.conflicts) } + if (baseline.registrations.size > 0) { + file.registrations = Object.fromEntries( + [...baseline.registrations].map(([key, fields]) => [key, Object.fromEntries(fields)]) + ) + } const baselinePath = getCodexSettingsBaselinePath(runtimeHomePath) const serialized = `${JSON.stringify(file, null, 2)}\n` let existing: string | null = null @@ -130,7 +162,7 @@ function isStoredSettingsBaseline(value: unknown): value is StoredSettingsBaseli } const candidate = value as Partial return ( - (candidate.version === 1 || candidate.version === 2) && + (candidate.version === 1 || candidate.version === 2 || candidate.version === 3) && !!candidate.settings && typeof candidate.settings === 'object' && !Array.isArray(candidate.settings) diff --git a/src/main/codex/config-settings-promotion.test.ts b/src/main/codex/config-settings-promotion.test.ts index 5e0e5f10b78..e12d9168b00 100644 --- a/src/main/codex/config-settings-promotion.test.ts +++ b/src/main/codex/config-settings-promotion.test.ts @@ -201,7 +201,7 @@ describe('codex settings write-back promotion', () => { simulateCodexSettingWrite('model', '"o4"') syncSystemConfigIntoManagedCodexHome() expect(readSystemConfig()).toBe('model = "gpt-5"\n') - expect(JSON.parse(readFileSync(baselinePath(), 'utf-8'))).toMatchObject({ version: 2 }) + expect(JSON.parse(readFileSync(baselinePath(), 'utf-8'))).toMatchObject({ version: 3 }) simulateCodexSettingWrite('model', '"o4"') syncSystemConfigIntoManagedCodexHome() diff --git a/src/main/codex/config-settings-promotion.ts b/src/main/codex/config-settings-promotion.ts index 45d95a266b1..52f4d6eefcd 100644 --- a/src/main/codex/config-settings-promotion.ts +++ b/src/main/codex/config-settings-promotion.ts @@ -5,14 +5,13 @@ import { resolvePromotionWriteTarget } from './config-settings-promotion-write-t import { writeFileAtomically } from '../codex-accounts/fs-utils' import { parseWslUncPath } from '../../shared/wsl-paths' import { getOrcaManagedCodexHomePath, getSystemCodexHomePath } from './codex-home-paths' +import { upsertPromotedSettingsInContent } from './codex-config-settings-upsert' import { - createTomlLineScanState, - getTomlTableHeader, - isTomlStructuralLine, - updateTomlLineScanState -} from './config-toml-line-scan' -import { parseTomlKeyPath, parseTomlTableHeaderPath } from './config-toml-key-path' -import { tuiStructuredKey, upsertPromotedSettingsInContent } from './codex-config-settings-upsert' + PROMOTED_STRUCTURED_KEYS, + readPromotedSettingValues, + readPromotedSettingValuesFromContent, + type TopLevelSettingValue +} from './config-toml-promoted-setting-values' import { observeCodexSettingsBaseline, writeCodexSettingsBaseline, @@ -21,137 +20,23 @@ import { } from './config-settings-baseline' import { resolveUntrackedCodexSetting } from './config-settings-conflict-resolution' import { extractOrdinaryCodexSettings } from './config-toml-runtime-owned-sections' +import { + applyCodexRegistrationPromotions, + planCodexRegistrationPromotion, + readCodexRegistrationBaseline +} from './config-plugin-registration-promotion' +import { hasCodexRegistrationEntries } from './config-toml-plugin-registration-tables' // Why: the mirror reverts in-Codex config changes each launch; promotion salvages them by diffing the last baseline. -// Why: only scalars the Codex TUI persists; each key here is written to the user's real ~/.codex, so grow deliberately. -export const PROMOTED_CODEX_SETTING_KEYS = [ - 'model', - 'model_reasoning_effort', - 'approval_policy', - 'sandbox_mode' -] as const - -// Why: the [tui] keys the Codex TUI's user-facing pickers persist (status line, -// terminal title, theme). Like the top-level list, every key here gets written -// into the user's real ~/.codex/config.toml on promotion — grow it deliberately. -export const PROMOTED_CODEX_TUI_SETTING_KEYS = [ - 'status_line', - 'status_line_use_colors', - 'terminal_title', - 'theme' -] as const - -// Why: promotion diffs and upserts operate on structured keys — top-level keys -// keep their bare name, [tui] keys are namespaced tui. so their baseline -// entries cannot collide with a top-level key of the same name. -const PROMOTED_STRUCTURED_KEYS: readonly string[] = [ - ...PROMOTED_CODEX_SETTING_KEYS, - ...PROMOTED_CODEX_TUI_SETTING_KEYS.map(tuiStructuredKey) -] - -function isPromotedTuiKey(key: string): boolean { - return (PROMOTED_CODEX_TUI_SETTING_KEYS as readonly string[]).includes(key) -} - -// Returns the structured tui key a scanned line's key represents, or null. In -// the preamble it recognizes the dotted `tui.` form a user may hand-author; -// inside the first `[tui]` table body it recognizes the bare `` form Codex -// writes. Both map to the same structured key so either config shape promotes. -function matchTuiStructuredKey( - keyPath: string[], - inPreamble: boolean, - tuiBodyActive: boolean -): string | null { - if (inPreamble) { - const tuiKey = keyPath.length === 2 && keyPath[0] === 'tui' ? keyPath[1] : null - return tuiKey && isPromotedTuiKey(tuiKey) ? tuiStructuredKey(tuiKey) : null - } - const tuiKey = keyPath.length === 1 ? keyPath[0] : null - return tuiBodyActive && tuiKey && isPromotedTuiKey(tuiKey) ? tuiStructuredKey(tuiKey) : null -} - -type TopLevelSettingValue = { - raw: string - // Why: a multiline string/array value can't be replaced line-by-line, so it's excluded from promotion. - multiline: boolean -} - -function matchPromotedStructuredKey( - line: string, - inPreamble: boolean, - tuiBodyActive: boolean -): { structuredKey: string; raw: string } | null { - const parsed = parseTomlKeyPath(line) - if (!parsed || line[parsed.end] !== '=') { - return null - } - const raw = line.slice(parsed.end + 1).trim() - const topLevelKey = parsed.segments.length === 1 ? parsed.segments[0] : null - if ( - inPreamble && - topLevelKey && - (PROMOTED_CODEX_SETTING_KEYS as readonly string[]).includes(topLevelKey) - ) { - return { structuredKey: topLevelKey, raw } - } - const tuiKey = matchTuiStructuredKey(parsed.segments, inPreamble, tuiBodyActive) - return tuiKey ? { structuredKey: tuiKey, raw } : null -} - -// Why: top-level preamble scalars keep the historical behavior; [tui] keys are -// collected from the first bare [tui] table body or the dotted preamble form, -// keyed by structured path. Any table header (including [tui.*] subtables) ends -// the [tui] body, and [profiles.*]/other tables are still ignored. -function readPromotedSettingValues(configPath: string): Map { - const result = new Map() - // Why: an unreadable config held no settings only in the sense that we could - // not read them. Returning an empty map says the user cleared every promoted - // value, and the write below then acts on that. - const observation = observeAgentStateFile(configPath) - if (observation.kind === 'absent') { - return result - } - if (observation.kind === 'indeterminate') { - throw observation.error - } - const lines = observation.value.split('\n') - let state = createTomlLineScanState() - let inPreamble = true - let tuiTableSeen = false - let tuiBodyActive = false - for (const line of lines) { - if (isTomlStructuralLine(state)) { - const header = getTomlTableHeader(line) - if (header) { - const table = parseTomlTableHeaderPath(header) - tuiBodyActive = - table !== null && - !table.isArray && - table.segments.length === 1 && - table.segments[0] === 'tui' && - !tuiTableSeen - if (tuiBodyActive) { - tuiTableSeen = true - } - inPreamble = false - state = updateTomlLineScanState(state, line) - continue - } - const matched = matchPromotedStructuredKey(line, inPreamble, tuiBodyActive) - if (matched) { - const nextState = updateTomlLineScanState(state, line) - result.set(matched.structuredKey, { - raw: matched.raw, - multiline: !isTomlStructuralLine(nextState) - }) - state = nextState - continue - } - } - state = updateTomlLineScanState(state, line) - } - return result +export type CodexSettingsBaselineSnapshotOptions = { + conflicts?: ReadonlyMap + /** + * Whether a mirror actually made the runtime's registration tables canonical. + * A bootstrap baseline must leave this false: claiming tables Orca never + * mirrored would read a source config that never had them as a removal. + */ + mirroredRegistrations?: boolean } /** @@ -161,12 +46,18 @@ function readPromotedSettingValues(configPath: string): Map = new Map() + options: CodexSettingsBaselineSnapshotOptions = {} ): void { try { const runtimeTomlPath = join(runtimeHomePath, 'config.toml') // Why: record an empty baseline even for a missing runtime config, so Codex's first write still diffs and promotes. - const runtimeValues = readPromotedSettingValues(runtimeTomlPath) + const observation = observeAgentStateFile(runtimeTomlPath) + if (observation.kind === 'indeterminate') { + throw observation.error + } + const runtimeConfig = observation.kind === 'present' ? observation.value : '' + const conflicts = options.conflicts ?? new Map() + const runtimeValues = readPromotedSettingValuesFromContent(runtimeConfig) const settings = new Map() for (const key of PROMOTED_STRUCTURED_KEYS) { const value = runtimeValues.get(key) @@ -175,7 +66,13 @@ export function snapshotCodexRuntimeSettingsBaseline( settings.set(key, value?.raw ?? null) } } - writeCodexSettingsBaseline(runtimeHomePath, { settings, conflicts }) + writeCodexSettingsBaseline(runtimeHomePath, { + settings, + conflicts, + registrations: options.mirroredRegistrations + ? readCodexRegistrationBaseline(runtimeConfig) + : new Map() + }) } catch (error) { console.warn('[codex-settings-promotion] failed to snapshot settings baseline', error) } @@ -236,7 +133,7 @@ function promoteCodexRuntimeSettingsToSystemUnsafe( // config nobody read. throw runtimeTomlObservation.error } - // Why: without a baseline, a stale runtime value looks like a fresh in-Codex change; skip until the mirror writes one. + // Why: without a baseline, a stale runtime scalar looks like a fresh in-Codex change; skip until the mirror writes one. const baselineObservation = observeCodexSettingsBaseline(runtimeHomePath) if (baselineObservation.kind === 'indeterminate') { // Why: an empty plan here lets the mirror proceed and write the system value @@ -244,24 +141,25 @@ function promoteCodexRuntimeSettingsToSystemUnsafe( // turns a throw into the existing stall-and-retry null. throw new Error('Codex settings baseline could not be read') } - if (baselineObservation.kind === 'absent') { - return emptyPromotionPlan() - } - const baseline = baselineObservation.baseline - const runtimeValues = readPromotedSettingValues(runtimeTomlPath) - const systemValues = readPromotedSettingValues(systemTomlPath) + const baseline = baselineObservation.kind === 'present' ? baselineObservation.baseline : null const updates = new Map() const conflicts = new Map() const runtimeValuesToPreserve = new Map() - collectPromotionChanges({ - baseline, - runtimeValues, - systemValues, - updates, - conflicts, - runtimeValuesToPreserve - }) - if (updates.size === 0) { + if (baseline) { + collectPromotionChanges({ + baseline, + runtimeValues: readPromotedSettingValues(runtimeTomlPath), + systemValues: readPromotedSettingValues(systemTomlPath), + updates, + conflicts, + runtimeValuesToPreserve + }) + } + // Why: registration tables reconcile against the mirrored-table baseline, which + // is legitimately empty before the first mirror — a table Orca never made + // canonical is an addition, never a removal it must honor. Scalars still need a + // real baseline, so they stay gated above. + if (updates.size === 0 && !hasCodexRegistrationEntries(runtimeTomlObservation.value)) { return { conflicts, runtimeValuesToPreserve } } // Why: a fresh host has no ~/.codex; create it owner-only (holds auth.json) or the atomic write ENOENTs and the mirror wipes it. @@ -273,10 +171,11 @@ function promoteCodexRuntimeSettingsToSystemUnsafe( // existence probe sent it down the reconstruct branch below, which replaces // the canonical config with settings derived from Orca's runtime copy. One // read replaces the old existsSync + read pair and its TOCTOU gap. - // The indeterminate arm is a backstop rather than the live guard: an - // unreadable system config already refused in readPromotedSettingValues, - // because `writeTarget.path` always resolves to the same file as - // `systemTomlPath` (its realpath, its dangling-link target, or itself). + // With a baseline, this arm is a backstop — an unreadable system config + // already refused in readPromotedSettingValues, because `writeTarget.path` + // always resolves to the same file as `systemTomlPath` (its realpath, its + // dangling-link target, or itself). Registration reconciliation runs without + // a baseline and skips that read, so here it IS the live guard. const writeTargetObservation = observeAgentStateFile(writeTarget.path) if (writeTargetObservation.kind === 'indeterminate') { throw writeTargetObservation.error @@ -290,7 +189,18 @@ function promoteCodexRuntimeSettingsToSystemUnsafe( writeTargetObservation.kind === 'present' ? writeTargetObservation.value : extractOrdinaryCodexSettings(runtimeTomlObservation.value) - const nextContent = upsertPromotedSettingsInContent(systemContent, updates) + const withPromotedSettings = upsertPromotedSettingsInContent(systemContent, updates) + // Why: plan against the content actually being edited, not a second read of the + // source — when the system config is seeded from the runtime, its registration + // tables are already present and re-appending them would duplicate the table. + const nextContent = applyCodexRegistrationPromotions( + withPromotedSettings, + planCodexRegistrationPromotion( + runtimeTomlObservation.value, + withPromotedSettings, + baseline?.registrations ?? new Map() + ) + ) if (nextContent === systemContent) { return { conflicts, runtimeValuesToPreserve } } diff --git a/src/main/codex/config-toml-line-scan.ts b/src/main/codex/config-toml-line-scan.ts index 48216621636..98d096167fe 100644 --- a/src/main/codex/config-toml-line-scan.ts +++ b/src/main/codex/config-toml-line-scan.ts @@ -296,3 +296,21 @@ function parseTomlUnicodeEscape( return null } } + +export function withTrailingCr(originalLine: string, rendered: string): string { + return originalLine.endsWith('\r') ? `${rendered}\r` : rendered +} + +export function withCrLine(rendered: string, usesCrlf: boolean): string { + return usesCrlf ? `${rendered}\r` : rendered +} + +// Why: a missing trailing newline is restored in the file's own EOL so a +// preamble-only or table-appended rewrite matches the source's newline behavior. +export function joinPreservingTrailingNewline(lines: string[], usesCrlf: boolean): string { + const result = lines.join('\n') + if (result.endsWith('\n') || result.length === 0) { + return result + } + return result.endsWith('\r') ? `${result}\n` : `${result}${usesCrlf ? '\r\n' : '\n'}` +} diff --git a/src/main/codex/config-toml-plugin-registration-tables.ts b/src/main/codex/config-toml-plugin-registration-tables.ts new file mode 100644 index 00000000000..c968d3890b5 --- /dev/null +++ b/src/main/codex/config-toml-plugin-registration-tables.ts @@ -0,0 +1,242 @@ +import { + createTomlLineScanState, + getTomlTableHeader, + isTomlStructuralLine, + parseTomlSingleLineStringValue, + updateTomlLineScanState +} from './config-toml-line-scan' +import { parseTomlKeyPath, parseTomlTableHeaderPath } from './config-toml-key-path' + +// Why: Codex persists plugin registration as two table families under a +// managed CODEX_HOME — `[marketplaces.]` and `[plugins."@"]`. +// Reconciling them needs identity, not text, so the name is the parsed header +// segment: `[plugins."a@b"]` and `[plugins.'a@b']` are one registration. + +export const CODEX_REGISTRATION_ROOTS = ['marketplaces', 'plugins'] as const + +export type CodexRegistrationRoot = (typeof CODEX_REGISTRATION_ROOTS)[number] + +export type CodexRegistrationField = { + raw: string + /** A value spanning lines cannot be replaced line-by-line, so it is never rewritten. */ + multiline: boolean + lineIndex: number +} + +export type CodexRegistrationEntry = { + key: string + root: CodexRegistrationRoot + name: string + /** Line range of the `[root.name]` table itself; -1 when only subtables exist. */ + ownerStart: number + ownerEnd: number + /** The registration's full text, including any `[root.name.*]` subtables. */ + block: string + fields: ReadonlyMap +} + +export function getCodexRegistrationKey(root: CodexRegistrationRoot, name: string): string { + return `${root}:${name}` +} + +export function readCodexRegistrationEntries(config: string): Map { + const lines = config.split('\n') + const headers = scanTomlTableHeaders(lines) + const entries = new Map() + for (let index = 0; index < headers.length; index += 1) { + const header = headers[index]! + const root = header.segments[0] + const name = header.segments[1] + // Why: `[[marketplaces.x]]` is not a shape Codex writes; treating an array of + // tables as one registration would key it by a name it may not own. + if (header.isArray || !isCodexRegistrationRoot(root) || name === undefined) { + continue + } + const end = headers[index + 1]?.index ?? lines.length + const key = getCodexRegistrationKey(root, name) + const isOwner = header.segments.length === 2 + const existing = entries.get(key) + const block = readRegistrationBlock(lines, header.index, end) + if (!existing) { + entries.set(key, { + key, + root, + name, + ownerStart: isOwner ? header.index : -1, + ownerEnd: isOwner ? end : -1, + block, + fields: isOwner ? readTomlTableFields(lines, header.index, end) : new Map() + }) + continue + } + entries.set(key, { + ...existing, + // Why: a duplicate owner table is invalid TOML; the first one wins, exactly + // as a TOML reader that rejects the second would have read the file. + ownerStart: existing.ownerStart === -1 && isOwner ? header.index : existing.ownerStart, + ownerEnd: existing.ownerStart === -1 && isOwner ? end : existing.ownerEnd, + block: `${existing.block}\n\n${block}`, + fields: + existing.ownerStart === -1 && isOwner + ? readTomlTableFields(lines, header.index, end) + : existing.fields + }) + } + return entries +} + +export function hasCodexRegistrationEntries(config: string): boolean { + return readCodexRegistrationEntries(config).size > 0 +} + +// Why: the block ends at the NEXT header, so its trailing blank and comment lines +// are that table's leading comment — appending them would copy it into the wrong +// section. Only structural lines are inspected, so a `#` inside a multiline string +// is never mistaken for one. +function readRegistrationBlock(lines: string[], start: number, end: number): string { + let state = createTomlLineScanState() + let lastBodyLine = start + for (let index = start; index < end; index += 1) { + const line = lines[index] ?? '' + const trimmed = line.trim() + if (!isTomlStructuralLine(state) || (trimmed !== '' && !trimmed.startsWith('#'))) { + lastBodyLine = index + } + state = updateTomlLineScanState(state, line) + } + return lines + .slice(start, lastBodyLine + 1) + .join('\n') + .trimEnd() +} + +const REGISTRATION_TIMESTAMP_PATTERN = + /^(\d{4})-(\d{2})-(\d{2})[Tt ]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})?$/ + +function isRealCalendarDate(year: number, month: number, day: number): boolean { + if (month < 1 || month > 12 || day < 1) { + return false + } + // Day 0 of the following month is the last day of this one; setUTCFullYear avoids + // the two-digit-year remapping the Date constructor applies. + const lastOfMonth = new Date(0) + lastOfMonth.setUTCFullYear(year, month, 0) + return day <= lastOfMonth.getUTCDate() +} + +/** Compares values by meaning, so quote style and a trailing comment never read as a change. */ +export function normalizeCodexRegistrationValue(raw: string): string { + const stripped = stripTomlTrailingComment(raw) + const quoted = parseTomlSingleLineStringValue(stripped, 0) + return quoted && quoted.end === stripped.length ? `string:${quoted.value}` : stripped +} + +/** + * Milliseconds for a marketplace refresh timestamp, or null when the value is not + * an RFC 3339 / TOML date-time. Anything unparseable is malformed, never "older". + */ +export function parseCodexRegistrationTimestamp(raw: string): number | null { + const stripped = stripTomlTrailingComment(raw) + const quoted = parseTomlSingleLineStringValue(stripped, 0) + const text = quoted && quoted.end === stripped.length ? quoted.value : stripped + const match = REGISTRATION_TIMESTAMP_PATTERN.exec(text) + // Why: Date.parse rolls `2025-02-30` forward to March 2 rather than rejecting it, + // so a malformed runtime value would read as NEWER and win against canonical. + if (!match || !isRealCalendarDate(Number(match[1]), Number(match[2]), Number(match[3]))) { + return null + } + const parsed = Date.parse(text.replace(' ', 'T')) + return Number.isFinite(parsed) ? parsed : null +} + +function isCodexRegistrationRoot(value: string | undefined): value is CodexRegistrationRoot { + return (CODEX_REGISTRATION_ROOTS as readonly string[]).includes(value ?? '') +} + +type TomlTableHeaderMarker = { + index: number + segments: string[] + isArray: boolean +} + +// Why: an unparseable header still ends the previous table, so it is recorded +// with no segments rather than skipped — otherwise its lines would be attributed +// to the registration above it. +function scanTomlTableHeaders(lines: string[]): TomlTableHeaderMarker[] { + const markers: TomlTableHeaderMarker[] = [] + let state = createTomlLineScanState() + for (let index = 0; index < lines.length; index += 1) { + const line = lines[index] ?? '' + if (isTomlStructuralLine(state)) { + const header = getTomlTableHeader(line) + if (header) { + const table = parseTomlTableHeaderPath(header) + markers.push({ + index, + segments: table?.segments ?? [], + isArray: table?.isArray ?? false + }) + } + } + state = updateTomlLineScanState(state, line) + } + return markers +} + +function readTomlTableFields( + lines: string[], + headerIndex: number, + end: number +): Map { + const fields = new Map() + let state = createTomlLineScanState() + let index = headerIndex + 1 + while (index < end) { + const line = lines[index] ?? '' + const parsed = isTomlStructuralLine(state) ? parseTomlKeyPath(line) : null + const name = parsed?.segments.length === 1 ? parsed.segments[0] : null + if (!parsed || !name || line[parsed.end] !== '=') { + state = updateTomlLineScanState(state, line) + index += 1 + continue + } + let raw = line.slice(parsed.end + 1).trim() + state = updateTomlLineScanState(state, line) + let valueEnd = index + 1 + while (!isTomlStructuralLine(state) && valueEnd < end) { + const continuation = lines[valueEnd] ?? '' + raw += `\n${continuation.trim()}` + state = updateTomlLineScanState(state, continuation) + valueEnd += 1 + } + if (!fields.has(name)) { + fields.set(name, { + raw, + multiline: valueEnd > index + 1, + lineIndex: index + }) + } + index = valueEnd + } + return fields +} + +function stripTomlTrailingComment(raw: string): string { + let index = 0 + while (index < raw.length) { + const char = raw[index] + if (char === '#') { + return raw.slice(0, index).trim() + } + if (char === '"' || char === "'") { + const quoted = parseTomlSingleLineStringValue(raw, index) + if (!quoted) { + return raw.trim() + } + index = quoted.end + continue + } + index += 1 + } + return raw.trim() +} diff --git a/src/main/codex/config-toml-promoted-setting-values.ts b/src/main/codex/config-toml-promoted-setting-values.ts new file mode 100644 index 00000000000..543c6476843 --- /dev/null +++ b/src/main/codex/config-toml-promoted-setting-values.ts @@ -0,0 +1,145 @@ +import { observeAgentStateFile } from './codex-path-observation' +import { + createTomlLineScanState, + getTomlTableHeader, + isTomlStructuralLine, + updateTomlLineScanState +} from './config-toml-line-scan' +import { parseTomlKeyPath, parseTomlTableHeaderPath } from './config-toml-key-path' +import { tuiStructuredKey } from './codex-config-settings-upsert' + +// Why: only scalars the Codex TUI persists; each key here is written to the user's real ~/.codex, so grow deliberately. +export const PROMOTED_CODEX_SETTING_KEYS = [ + 'model', + 'model_reasoning_effort', + 'approval_policy', + 'sandbox_mode' +] as const + +// Why: the [tui] keys the Codex TUI's user-facing pickers persist (status line, +// terminal title, theme). Like the top-level list, every key here gets written +// into the user's real ~/.codex/config.toml on promotion — grow it deliberately. +export const PROMOTED_CODEX_TUI_SETTING_KEYS = [ + 'status_line', + 'status_line_use_colors', + 'terminal_title', + 'theme' +] as const + +// Why: promotion diffs and upserts operate on structured keys — top-level keys +// keep their bare name, [tui] keys are namespaced tui. so their baseline +// entries cannot collide with a top-level key of the same name. +export const PROMOTED_STRUCTURED_KEYS: readonly string[] = [ + ...PROMOTED_CODEX_SETTING_KEYS, + ...PROMOTED_CODEX_TUI_SETTING_KEYS.map(tuiStructuredKey) +] + +function isPromotedTuiKey(key: string): boolean { + return (PROMOTED_CODEX_TUI_SETTING_KEYS as readonly string[]).includes(key) +} + +// Returns the structured tui key a scanned line's key represents, or null. In +// the preamble it recognizes the dotted `tui.` form a user may hand-author; +// inside the first `[tui]` table body it recognizes the bare `` form Codex +// writes. Both map to the same structured key so either config shape promotes. +function matchTuiStructuredKey( + keyPath: string[], + inPreamble: boolean, + tuiBodyActive: boolean +): string | null { + if (inPreamble) { + const tuiKey = keyPath.length === 2 && keyPath[0] === 'tui' ? keyPath[1] : null + return tuiKey && isPromotedTuiKey(tuiKey) ? tuiStructuredKey(tuiKey) : null + } + const tuiKey = keyPath.length === 1 ? keyPath[0] : null + return tuiBodyActive && tuiKey && isPromotedTuiKey(tuiKey) ? tuiStructuredKey(tuiKey) : null +} + +export type TopLevelSettingValue = { + raw: string + // Why: a multiline string/array value can't be replaced line-by-line, so it's excluded from promotion. + multiline: boolean +} + +function matchPromotedStructuredKey( + line: string, + inPreamble: boolean, + tuiBodyActive: boolean +): { structuredKey: string; raw: string } | null { + const parsed = parseTomlKeyPath(line) + if (!parsed || line[parsed.end] !== '=') { + return null + } + const raw = line.slice(parsed.end + 1).trim() + const topLevelKey = parsed.segments.length === 1 ? parsed.segments[0] : null + if ( + inPreamble && + topLevelKey && + (PROMOTED_CODEX_SETTING_KEYS as readonly string[]).includes(topLevelKey) + ) { + return { structuredKey: topLevelKey, raw } + } + const tuiKey = matchTuiStructuredKey(parsed.segments, inPreamble, tuiBodyActive) + return tuiKey ? { structuredKey: tuiKey, raw } : null +} + +// Why: top-level preamble scalars keep the historical behavior; [tui] keys are +// collected from the first bare [tui] table body or the dotted preamble form, +// keyed by structured path. Any table header (including [tui.*] subtables) ends +// the [tui] body, and [profiles.*]/other tables are still ignored. +export function readPromotedSettingValues(configPath: string): Map { + // Why: an unreadable config held no settings only in the sense that we could + // not read them. Returning an empty map says the user cleared every promoted + // value, and the write below then acts on that. + const observation = observeAgentStateFile(configPath) + if (observation.kind === 'absent') { + return new Map() + } + if (observation.kind === 'indeterminate') { + throw observation.error + } + return readPromotedSettingValuesFromContent(observation.value) +} + +export function readPromotedSettingValuesFromContent( + config: string +): Map { + const result = new Map() + const lines = config.split('\n') + let state = createTomlLineScanState() + let inPreamble = true + let tuiTableSeen = false + let tuiBodyActive = false + for (const line of lines) { + if (isTomlStructuralLine(state)) { + const header = getTomlTableHeader(line) + if (header) { + const table = parseTomlTableHeaderPath(header) + tuiBodyActive = + table !== null && + !table.isArray && + table.segments.length === 1 && + table.segments[0] === 'tui' && + !tuiTableSeen + if (tuiBodyActive) { + tuiTableSeen = true + } + inPreamble = false + state = updateTomlLineScanState(state, line) + continue + } + const matched = matchPromotedStructuredKey(line, inPreamble, tuiBodyActive) + if (matched) { + const nextState = updateTomlLineScanState(state, line) + result.set(matched.structuredKey, { + raw: matched.raw, + multiline: !isTomlStructuralLine(nextState) + }) + state = nextState + continue + } + } + state = updateTomlLineScanState(state, line) + } + return result +} diff --git a/src/main/codex/sta-4823-shared-state-survives-a-failed-read.test.ts b/src/main/codex/sta-4823-shared-state-survives-a-failed-read.test.ts index adab285b592..e976a2a5660 100644 --- a/src/main/codex/sta-4823-shared-state-survives-a-failed-read.test.ts +++ b/src/main/codex/sta-4823-shared-state-survives-a-failed-read.test.ts @@ -368,7 +368,7 @@ describe('STA-4823 D26 — an unreadable settings baseline must stall the mirror // Asserted against the file rather than the new observation API, so this // anchor still means something when the fix is reverted. - expect(JSON.parse(realFs.readFileSync(baselinePath(), 'utf-8'))).toMatchObject({ version: 2 }) + expect(JSON.parse(realFs.readFileSync(baselinePath(), 'utf-8'))).toMatchObject({ version: 3 }) }) it('still replaces a fully-read baseline rejected by the JSON structure limit', () => { @@ -377,7 +377,7 @@ describe('STA-4823 D26 — an unreadable settings baseline must stall the mirror snapshotCodexRuntimeSettingsBaseline(runtimeHomePath) - expect(JSON.parse(realFs.readFileSync(baselinePath(), 'utf-8'))).toMatchObject({ version: 2 }) + expect(JSON.parse(realFs.readFileSync(baselinePath(), 'utf-8'))).toMatchObject({ version: 3 }) }) it('rebuilds an oversized baseline previously produced from a bounded runtime config', () => { diff --git a/src/main/daemon/daemon-launch-paths.ts b/src/main/daemon/daemon-launch-paths.ts index 9b5b2c3dca8..049800daff4 100644 --- a/src/main/daemon/daemon-launch-paths.ts +++ b/src/main/daemon/daemon-launch-paths.ts @@ -1,7 +1,9 @@ -import { existsSync, mkdirSync } from 'node:fs' +import { existsSync } from 'node:fs' import { connect } from 'node:net' import { join } from 'node:path' import { getAppEnvironment } from '../../shared/app-environment' +import { ensurePrivateDir } from './daemon-private-file-modes' +import { scheduleTerminalHistoryPermissionRepair } from './terminal-history-permission-repair' import { getDaemonLogFilePath } from '../observability/logs-directory' import { DaemonClient } from './client' import { daemonRecoveryProbeTimeoutMs } from './daemon-recovery-budget' @@ -10,13 +12,17 @@ import { PROTOCOL_VERSION, type ListSessionsResult } from './types' export function getDaemonRuntimeDir(): string { const dir = join(getAppEnvironment().getPath('userData'), 'daemon') - mkdirSync(dir, { recursive: true }) + ensurePrivateDir(dir) return dir } export function getDaemonHistoryDir(): string { const dir = join(getAppEnvironment().getPath('userData'), 'terminal-history') - mkdirSync(dir, { recursive: true }) + ensurePrivateDir(dir) + // Why here: the one accessor every history producer goes through, so the backlog sweep is hooked + // once per host that owns the files — native, WSL, or a remote SSH server's own main process. + // The scheduler defers and de-duplicates, so the several startup calls cost one late sweep. + void scheduleTerminalHistoryPermissionRepair(dir) return dir } diff --git a/src/main/daemon/daemon-private-file-modes.ts b/src/main/daemon/daemon-private-file-modes.ts new file mode 100644 index 00000000000..c0c96b9021d --- /dev/null +++ b/src/main/daemon/daemon-private-file-modes.ts @@ -0,0 +1,33 @@ +// Mode primitives for daemon-owned on-disk state. Terminal history persists verbatim screen and +// scrollback (checkpoint.json holds snapshotAnsi + scrollbackAnsi) and the runtime dir holds the +// daemon's auth token, so neither may be left at whatever umask applies to other local users. + +import { chmodSync, existsSync, mkdirSync } from 'node:fs' + +export const PRIVATE_DIR_MODE = 0o700 +export const PRIVATE_FILE_MODE = 0o600 + +/** Windows ignores POSIX mode bits and can reject chmod outright; hardening must never break a write. */ +export function supportsPosixFileModes(): boolean { + return process.platform !== 'win32' +} + +/** Best-effort repair for a path created before modes were pinned (or by an older daemon). */ +export function tightenPathMode(path: string, mode: number): void { + if (!supportsPosixFileModes()) { + return + } + try { + if (existsSync(path)) { + chmodSync(path, mode) + } + } catch { + // Read-only volumes, foreign ownership, exotic filesystems: leave the mode as found. + } +} + +/** mkdir with the private mode, plus a chmod repair for a directory that already existed. */ +export function ensurePrivateDir(dir: string): void { + mkdirSync(dir, { recursive: true, mode: PRIVATE_DIR_MODE }) + tightenPathMode(dir, PRIVATE_DIR_MODE) +} diff --git a/src/main/daemon/headless-osc-link-ranges.test.ts b/src/main/daemon/headless-osc-link-ranges.test.ts new file mode 100644 index 00000000000..cf8f9f757e2 --- /dev/null +++ b/src/main/daemon/headless-osc-link-ranges.test.ts @@ -0,0 +1,63 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { HeadlessEmulator } from './headless-emulator' + +// Why this suite: collectHeadlessOscLinkRanges skips its per-cell scan when +// xterm holds no OSC 8 registration. That skip is only safe if it can never +// fire while a link is reachable, so each case below pins one way it could. +let emulator: HeadlessEmulator | undefined + +const link = (uri: string, text: string): string => `\x1b]8;;${uri}\x1b\\${text}\x1b]8;;\x1b\\` + +afterEach(() => { + emulator?.dispose() + emulator = undefined +}) + +describe('headless OSC link ranges', () => { + it('finds a link written into the buffer', async () => { + emulator = new HeadlessEmulator({ cols: 80, rows: 24 }) + await emulator.write(`before ${link('https://example.com/a', 'CLICK')} after`) + + const ranges = emulator.getSnapshot().oscLinks ?? [] + expect(ranges).toHaveLength(1) + expect(ranges[0]).toMatchObject({ row: 0, uri: 'https://example.com/a' }) + }) + + it('returns nothing for a buffer that never emitted a link', async () => { + emulator = new HeadlessEmulator({ cols: 80, rows: 24 }) + await emulator.write('plain output with no hyperlink\r\n'.repeat(50)) + + expect(emulator.getSnapshot().oscLinks).toEqual([]) + }) + + // The dangerous case: restored ranges are seeded without xterm registering + // anything, so an early-out keyed only on the registry would drop them. + it('still maps restored ranges when the buffer itself has no link', async () => { + emulator = new HeadlessEmulator({ cols: 80, rows: 24 }) + await emulator.write('restored row') + const restored = { row: 0, startCol: 0, endCol: 4, uri: 'https://example.com/restored' } + emulator.setRestoredOscLinks([restored]) + + expect(emulator.getSnapshot().oscLinks).toEqual([restored]) + }) + + it('finds links far down a long scrollback, not just the visible screen', async () => { + emulator = new HeadlessEmulator({ cols: 80, rows: 24, scrollback: 5_000 }) + await emulator.write(`${link('https://example.com/top', 'TOP')}\r\n`) + await emulator.write('filler\r\n'.repeat(2_000)) + + const ranges = emulator.getSnapshot({ scrollbackRows: 5_000 }).oscLinks ?? [] + expect(ranges.map((range) => range.uri)).toContain('https://example.com/top') + }) + + it('keeps every distinct link when several are present', async () => { + emulator = new HeadlessEmulator({ cols: 80, rows: 24 }) + await emulator.write( + `${link('https://example.com/1', 'ONE')} ${link('https://example.com/2', 'TWO')}` + ) + + const uris = (emulator.getSnapshot().oscLinks ?? []).map((range) => range.uri) + expect(uris).toContain('https://example.com/1') + expect(uris).toContain('https://example.com/2') + }) +}) diff --git a/src/main/daemon/headless-osc-link-ranges.ts b/src/main/daemon/headless-osc-link-ranges.ts index 418a0c65166..ea017a7b928 100644 --- a/src/main/daemon/headless-osc-link-ranges.ts +++ b/src/main/daemon/headless-osc-link-ranges.ts @@ -1,10 +1,14 @@ -import type { Terminal } from '@xterm/headless' +import type { IBufferCell, IBufferLine, Terminal } from '@xterm/headless' import type { TerminalOscLinkRange } from '../../shared/terminal-osc-link-ranges' type TerminalWithOscLinks = Terminal & { _core?: { _oscLinkService?: { getLinkData: (linkId: number) => { uri?: string } | undefined + // Why read it: xterm registers every OSC 8 id here, so an empty registry + // proves the buffer holds no hyperlink and the per-cell scan can be skipped. + // Optional because it is private — an xterm that renames it just scans. + _dataByLinkId?: { size?: number } } } } @@ -14,6 +18,11 @@ type CellWithOscLink = { hasExtendedAttrs?: () => boolean } +/** True when xterm holds no OSC 8 registration at all, so no cell can carry one. */ +function hasNoRegisteredOscLinks(service: { _dataByLinkId?: { size?: number } }): boolean { + return service._dataByLinkId?.size === 0 +} + export function collectHeadlessOscLinkRanges( terminal: Terminal, scrollbackRows: number | undefined, @@ -26,9 +35,19 @@ export function collectHeadlessOscLinkRanges( return [] } const buffer = terminal.buffer.active + // Why before the scan: the walk below reads every cell of every row, and a + // session that never emitted a hyperlink — the overwhelming majority — would + // pay that for a guaranteed-empty result. `restoredLinks` still needs mapping. + if (hasNoRegisteredOscLinks(service) && restoredLinks.length === 0) { + return [] + } const startRow = scrollbackRows === undefined ? 0 : Math.max(0, buffer.length - terminal.rows - scrollbackRows) const ranges: TerminalOscLinkRange[] = [] + // Why one cell for the whole walk: xterm's getCell allocates a fresh CellData + // per call unless handed a target, which is a per-cell allocation across the + // entire scrollback. See the IBufferLine.getCell docs. + const scratchCell = buffer.getNullCell() for (let row = startRow; row < buffer.length; row += 1) { const line = buffer.getLine(row) if (!line) { @@ -38,7 +57,7 @@ export function collectHeadlessOscLinkRanges( let currentUrlId = 0 let currentStart = -1 for (let col = 0; col <= lineLength; col += 1) { - const urlId = col < lineLength ? getOscLinkIdAtCell(line, col) : 0 + const urlId = col < lineLength ? getOscLinkIdAtCell(line, col, scratchCell) : 0 if (urlId === currentUrlId) { continue } @@ -83,8 +102,8 @@ function dedupeOscLinkRanges(ranges: TerminalOscLinkRange[]): TerminalOscLinkRan }) } -function getOscLinkIdAtCell(line: { getCell: (col: number) => unknown }, col: number): number { - const cell = line.getCell(col) as CellWithOscLink | undefined +function getOscLinkIdAtCell(line: IBufferLine, col: number, scratchCell: IBufferCell): number { + const cell = line.getCell(col, scratchCell) as (IBufferCell & CellWithOscLink) | undefined // Why: OSC link IDs live in extended cell attrs; missing attrs means no link. return cell?.hasExtendedAttrs?.() && cell.extended?.urlId ? cell.extended.urlId : 0 } diff --git a/src/main/daemon/history-manager.ts b/src/main/daemon/history-manager.ts index 48517bb6653..200609ed703 100644 --- a/src/main/daemon/history-manager.ts +++ b/src/main/daemon/history-manager.ts @@ -1,7 +1,9 @@ import { join } from 'node:path' import { randomUUID } from 'node:crypto' -import { mkdirSync, writeFileSync, existsSync, unlinkSync } from 'node:fs' +import { existsSync } from 'node:fs' import { getHistorySessionDirName } from './history-paths' +import { ensurePrivateDir } from './daemon-private-file-modes' +import { clearReplayableTerminalHistorySessionFiles } from './terminal-history-session-files' import { fingerprintTerminalHistorySession, hasTerminalHistoryRecoveryProtection, @@ -9,6 +11,7 @@ import { type ActiveHistoryRecoveryFreeze, type HistoryRecoveryFreeze } from './terminal-history-recovery-quarantine' +import { TerminalHistoryRecoveryFreezes } from './terminal-history-recovery-freezes' import { removeTerminalHistorySessionTrees, schedulePendingSessionTreeRemovals @@ -17,6 +20,7 @@ import { TerminalHistorySessionWriter } from './terminal-history-session-writer' import { readTerminalHistoryMetaFromDir, updateTerminalHistoryMeta, + writeTerminalHistoryMeta, type SessionMeta } from './terminal-history-metadata' import type { PendingOutputRecord, TerminalSnapshot } from './types' @@ -36,7 +40,7 @@ export class HistoryManager { private writers = new Map() private disabledSessions = new Set() private mutations = new TerminalHistoryMutationTracker() - private recoveryFreezes = new Map() + private readonly recoveryFreezes: TerminalHistoryRecoveryFreezes private onWriteError?: (sessionId: string, error: Error) => void private checkpointMaxBytes: number @@ -46,6 +50,7 @@ export class HistoryManager { ) { this.onWriteError = opts?.onWriteError this.checkpointMaxBytes = opts?.checkpointMaxBytes ?? TERMINAL_HISTORY_CHECKPOINT_MAX_BYTES + this.recoveryFreezes = new TerminalHistoryRecoveryFreezes(basePath) // Why: a quit between tombstone and reclaim leaves the tree on disk; nothing else rescans the queue. schedulePendingSessionTreeRemovals(this.basePath) } @@ -54,7 +59,7 @@ export class HistoryManager { let recoveryFreeze = opts.recoveryFreeze try { this.disabledSessions.delete(sessionId) - const dir = join(this.basePath, getHistorySessionDirName(sessionId)) + const dir = this.sessionDir(sessionId) recoveryFreeze ??= await this.freezeForRecovery(sessionId) const activeFreeze = this.requireRecoveryFreeze(sessionId, recoveryFreeze) @@ -67,8 +72,8 @@ export class HistoryManager { ) { throw new Error('terminal_history_recovery_generation_changed') } - this.recoveryFreezes.delete(sessionId) - mkdirSync(dir, { recursive: true }) + this.recoveryFreezes.release(sessionId) + ensurePrivateDir(dir) const meta: SessionMeta = { cwd: opts.cwd, @@ -78,21 +83,10 @@ export class HistoryManager { endedAt: null, exitCode: null } - writeFileSync(join(dir, 'meta.json'), JSON.stringify(meta, null, 2)) + writeTerminalHistoryMeta(dir, meta) if (!opts.quarantineUnreadableRecovery) { - // Why: a crash before the first checkpoint must not replay a cleanly ended prior session. - for (const staleFile of [ - join(dir, 'checkpoint.json'), - join(dir, 'scrollback.bin'), - join(dir, 'output.log') - ]) { - try { - unlinkSync(staleFile) - } catch { - // ENOENT is expected for new sessions - } - } + clearReplayableTerminalHistorySessionFiles(dir) } this.writers.set( @@ -118,14 +112,14 @@ export class HistoryManager { token: randomUUID() } const activeFreeze: ActiveHistoryRecoveryFreeze = { handle } - this.recoveryFreezes.set(sessionId, activeFreeze) + this.recoveryFreezes.hold(sessionId, activeFreeze) try { await this.mutations.wait(sessionId) activeFreeze.fingerprint = fingerprintTerminalHistorySession(this.basePath, sessionId) return handle } catch (err) { if (this.recoveryFreezes.get(sessionId) === activeFreeze) { - this.recoveryFreezes.delete(sessionId) + this.recoveryFreezes.release(sessionId) } throw err } @@ -134,7 +128,7 @@ export class HistoryManager { abandonRecoveryFreeze(freeze?: HistoryRecoveryFreeze): void { const activeFreeze = freeze ? this.recoveryFreezes.get(freeze.sessionId) : undefined if (activeFreeze && activeFreeze.handle === freeze) { - this.recoveryFreezes.delete(activeFreeze.handle.sessionId) + this.recoveryFreezes.release(activeFreeze.handle.sessionId) } } @@ -155,7 +149,7 @@ export class HistoryManager { ) { throw new Error('terminal_history_recovery_generation_changed') } - this.recoveryFreezes.delete(sessionId) + this.recoveryFreezes.release(sessionId) } catch (err) { this.abandonRecoveryFreeze(recoveryFreeze) this.handleWriteError(sessionId, err) @@ -164,7 +158,7 @@ export class HistoryManager { } else if (this.recoveryFreezes.has(sessionId)) { return } - const dir = join(this.basePath, getHistorySessionDirName(sessionId)) + const dir = this.sessionDir(sessionId) this.writers.set( sessionId, new TerminalHistorySessionWriter(dir, false, this.checkpointMaxBytes) @@ -280,7 +274,7 @@ export class HistoryManager { async removeSession(sessionId: string): Promise { this.writers.delete(sessionId) this.disabledSessions.delete(sessionId) - this.recoveryFreezes.delete(sessionId) + this.recoveryFreezes.release(sessionId) await this.mutations.wait(sessionId) // Why tombstoned: writer handles are closed by here, so the trees only have to become unreachable — // they reach hundreds of MB and every terminal a worktree delete tears down awaits this. @@ -300,12 +294,11 @@ export class HistoryManager { } hasHistory(sessionId: string): boolean { - return existsSync(join(this.basePath, getHistorySessionDirName(sessionId), 'meta.json')) + return existsSync(join(this.sessionDir(sessionId), 'meta.json')) } readMeta(sessionId: string): SessionMeta | null { - const dir = join(this.basePath, getHistorySessionDirName(sessionId)) - return readTerminalHistoryMetaFromDir(dir) + return readTerminalHistoryMetaFromDir(this.sessionDir(sessionId)) } async dispose(): Promise { @@ -321,6 +314,7 @@ export class HistoryManager { } } this.writers.clear() + this.recoveryFreezes.releaseAll() } // Why: history is best-effort; callers fire-and-forget so a throw would be an unhandled rejection — disable instead. @@ -329,6 +323,10 @@ export class HistoryManager { this.onWriteError?.(sessionId, err as Error) } + private sessionDir(sessionId: string): string { + return join(this.basePath, getHistorySessionDirName(sessionId)) + } + private requireRecoveryFreeze( sessionId: string, recoveryFreeze: HistoryRecoveryFreeze diff --git a/src/main/daemon/terminal-history-metadata.ts b/src/main/daemon/terminal-history-metadata.ts index b93fd9a4a78..fd473a99f07 100644 --- a/src/main/daemon/terminal-history-metadata.ts +++ b/src/main/daemon/terminal-history-metadata.ts @@ -4,6 +4,7 @@ import { getHistorySessionDirName } from './history-paths' import { isValidTerminalHistorySize } from './terminal-history-dimensions' import { readTerminalHistoryJson } from './terminal-history-file-reader' import { TERMINAL_HISTORY_META_MAX_BYTES } from './terminal-history-file-limits' +import { PRIVATE_FILE_MODE, tightenPathMode } from './daemon-private-file-modes' export type SessionMeta = { cwd: string @@ -44,13 +45,21 @@ export function readTerminalHistoryMetaFromDir(dir: string): SessionMeta | null } } +/** meta.json records the session's cwd, so it is private like the rest of the tree. */ +export function writeTerminalHistoryMeta(dir: string, meta: SessionMeta): void { + const metaPath = join(dir, 'meta.json') + writeFileSync(metaPath, JSON.stringify(meta, null, 2), { mode: PRIVATE_FILE_MODE }) + // `mode` applies only at creation, so a rewrite of an older daemon's file needs the chmod. + tightenPathMode(metaPath, PRIVATE_FILE_MODE) +} + export function updateTerminalHistoryMeta(dir: string, updates: Partial): void { const meta = readTerminalHistoryMetaFromDir(dir) if (!meta) { return } Object.assign(meta, updates) - writeFileSync(join(dir, 'meta.json'), JSON.stringify(meta, null, 2)) + writeTerminalHistoryMeta(dir, meta) } function isSessionMeta(value: unknown): value is SessionMeta { diff --git a/src/main/daemon/terminal-history-permission-repair.ts b/src/main/daemon/terminal-history-permission-repair.ts new file mode 100644 index 00000000000..d2449efebfb --- /dev/null +++ b/src/main/daemon/terminal-history-permission-repair.ts @@ -0,0 +1,118 @@ +// History trees written before owner-only modes were pinned landed at whatever umask applied, which on +// a default umask leaves every checkpoint.json world-readable. This is the backlog repair: one bounded +// sweep of the base dir, marker-guarded so every later launch costs one existsSync rather than a walk +// over 10k session trees. Live trees are tightened per-session in terminal-history-session-files. +// +// The marker is a regular file, so `history-reader`'s directory-only session scan already skips it. + +import { existsSync, type Dirent } from 'node:fs' +import { chmod, readdir, writeFile } from 'node:fs/promises' +import { join, resolve } from 'node:path' +import { + PRIVATE_DIR_MODE, + PRIVATE_FILE_MODE, + supportsPosixFileModes +} from './daemon-private-file-modes' +import { isTerminalHistorySessionDirRecoveryProtected } from './terminal-history-recovery-quarantine' + +const REPAIR_MARKER_NAME = '.permissions-repaired-v1' +// Bounds the one-time walk: retention keeps 10k session trees, each a handful of files. +const MAX_REPAIR_ENTRIES = 200_000 +// base → session/quarantine owner → quarantined generation → files. +const MAX_REPAIR_DEPTH = 3 +// Same 10s the sibling history GC waits before walking this very tree, and for the same reason: +// stay off startup-critical I/O (see scheduleHistoryGc in src/main/terminal-history-gc.ts). +const REPAIR_START_DELAY_MS = 10_000 + +// Per-process, keyed by base path: getDaemonHistoryDir() is the accessor every history producer +// goes through, and a single startup calls it more than once. Never cleared, so a sweep that throws +// cannot wedge a retry loop — the on-disk marker is what carries the decision across launches. +const scheduledBasePaths = new Set() + +async function chmodQuietly(path: string, mode: number): Promise { + try { + await chmod(path, mode) + } catch { + // A path that cannot be tightened must not abort the rest of the sweep. + } +} + +async function tightenTree(root: string): Promise { + const queue: { dir: string; depth: number }[] = [{ dir: root, depth: 0 }] + let budget = MAX_REPAIR_ENTRIES + while (queue.length > 0 && budget > 0) { + const current = queue.shift() + if (!current) { + return + } + // Why skip: chmod moves the mode/ctime that the recovery fingerprint hashes, so sweeping a tree + // mid-freeze fails the re-check and silently stops that pane persisting for the rest of the run. + // Nothing is left loose — the session's own writer tightens its tree when it attaches. + if (current.depth > 0 && isTerminalHistorySessionDirRecoveryProtected(current.dir)) { + continue + } + await chmodQuietly(current.dir, PRIVATE_DIR_MODE) + let entries: Dirent[] + try { + entries = await readdir(current.dir, { withFileTypes: true }) + } catch { + continue + } + for (const entry of entries) { + budget -= 1 + if (budget <= 0) { + return + } + // Dirent types come from lstat, so symlinks match neither branch and are never chased. + const child = join(current.dir, entry.name) + if (entry.isDirectory()) { + if (current.depth < MAX_REPAIR_DEPTH) { + queue.push({ dir: child, depth: current.depth + 1 }) + } + } else if (entry.isFile()) { + // Re-checked per file: a freeze can open while this directory is being walked. + if (current.depth > 0 && isTerminalHistorySessionDirRecoveryProtected(current.dir)) { + break + } + await chmodQuietly(child, PRIVATE_FILE_MODE) + } + } + } +} + +/** Resolves `true` when the sweep ran. The marker is written even if some paths resisted chmod, so a + * permanently unfixable file cannot make every launch re-walk the tree. */ +export async function repairTerminalHistoryPermissions(basePath: string): Promise { + if (!supportsPosixFileModes() || !existsSync(basePath)) { + return false + } + const markerPath = join(basePath, REPAIR_MARKER_NAME) + if (existsSync(markerPath)) { + return false + } + await tightenTree(basePath) + try { + await writeFile(markerPath, '', { mode: PRIVATE_FILE_MODE }) + } catch { + // Marker write failed: the next launch repeats a bounded, idempotent sweep. + } + return true +} + +/** Deferred and once per base path per process, so daemon init neither waits on permission hardening + * nor runs two sweeps over one tree. Resolves with the sweep's outcome, or `null` when already + * scheduled; callers on the startup path ignore it. */ +export function scheduleTerminalHistoryPermissionRepair(basePath: string): Promise | null { + const key = resolve(basePath) + if (scheduledBasePaths.has(key)) { + return null + } + scheduledBasePaths.add(key) + const { promise, resolve: settle } = Promise.withResolvers() + const timer = setTimeout(() => { + repairTerminalHistoryPermissions(key).then(settle, () => settle(false)) + }, REPAIR_START_DELAY_MS) + // Why: a pending sweep must never be the reason the process (or a test worker) stays alive. + timer.unref() + return promise +} diff --git a/src/main/daemon/terminal-history-permissions.test.ts b/src/main/daemon/terminal-history-permissions.test.ts new file mode 100644 index 00000000000..91ea830b4b2 --- /dev/null +++ b/src/main/daemon/terminal-history-permissions.test.ts @@ -0,0 +1,334 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + writeFileSync +} from 'node:fs' +import type * as NodeFs from 'node:fs' +import type * as NodeFsPromises from 'node:fs/promises' +import { HistoryManager } from './history-manager' +import { HistoryReader } from './history-reader' +import { getHistorySessionDirName } from './history-paths' +import { flushPendingSessionTreeRemovals } from './terminal-history-session-tombstone' +import { + repairTerminalHistoryPermissions, + scheduleTerminalHistoryPermissionRepair +} from './terminal-history-permission-repair' +import { tightenTerminalHistorySessionDirMode } from './terminal-history-session-files' +import type { TerminalModes, TerminalSnapshot } from './types' + +const onPosix = it.skipIf(process.platform === 'win32') +const REPAIR_MARKER_NAME = '.permissions-repaired-v1' + +const defaultModes: TerminalModes = { + bracketedPaste: false, + mouseTracking: false, + applicationCursor: false, + alternateScreen: false +} + +function makeSnapshot(overrides: Partial = {}): TerminalSnapshot { + return { + snapshotAnsi: 'secret scrollback\r\n', + scrollbackAnsi: '', + rehydrateSequences: '', + cwd: '/tmp', + modes: defaultModes, + cols: 80, + rows: 24, + scrollbackLines: 0, + ...overrides + } +} + +function modeOf(path: string): number { + return statSync(path).mode & 0o777 +} + +function sessionPath(baseDir: string, sessionId: string, file: string): string { + return join(baseDir, getHistorySessionDirName(sessionId), file) +} + +/** `process.platform` is read at call time, so the Windows branch is reachable from a POSIX runner. */ +function stubPlatform(platform: NodeJS.Platform): () => void { + const original = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { value: platform, configurable: true }) + return () => { + if (original) { + Object.defineProperty(process, 'platform', original) + } + } +} + +describe('terminal history file permissions', () => { + const createdDirs: string[] = [] + + /** Repair tests need a base dir with no HistoryManager racing its own startup sweep against them. */ + function isolatedDir(): string { + const created = mkdtempSync(join(tmpdir(), 'history-perms-test-')) + createdDirs.push(created) + return created + } + + afterEach(async () => { + await flushPendingSessionTreeRemovals() + for (const created of createdDirs.splice(0)) { + rmSync(created, { recursive: true, force: true }) + } + }) + + describe('newly written history', () => { + let dir: string + let mgr: HistoryManager + + beforeEach(() => { + dir = isolatedDir() + mgr = new HistoryManager(dir) + }) + + afterEach(async () => { + await mgr.dispose() + }) + + onPosix('pins 0o700 on the session directory and 0o600 on meta.json', async () => { + await mgr.openSession('sess-1', { cwd: '/home/user', cols: 80, rows: 24 }) + + expect(modeOf(join(dir, getHistorySessionDirName('sess-1')))).toBe(0o700) + expect(modeOf(sessionPath(dir, 'sess-1', 'meta.json'))).toBe(0o600) + }) + + onPosix('pins 0o600 on checkpoint.json, which holds verbatim scrollback', async () => { + await mgr.openSession('sess-1', { cwd: '/tmp', cols: 80, rows: 24 }) + await mgr.checkpoint('sess-1', makeSnapshot()) + + const checkpointPath = sessionPath(dir, 'sess-1', 'checkpoint.json') + expect(readFileSync(checkpointPath, 'utf-8')).toContain('secret scrollback') + expect(modeOf(checkpointPath)).toBe(0o600) + }) + + onPosix('pins 0o600 on output.log', async () => { + await mgr.openSession('sess-1', { cwd: '/tmp', cols: 80, rows: 24 }) + await mgr.appendIncrements('sess-1', 1, [{ kind: 'output', data: 'secret increment' }]) + + expect(modeOf(sessionPath(dir, 'sess-1', 'output.log'))).toBe(0o600) + }) + + onPosix( + 'tightens a checkpoint tmp left behind by an older daemon before renaming it', + async () => { + await mgr.openSession('sess-1', { cwd: '/tmp', cols: 80, rows: 24 }) + const tmpPath = `${sessionPath(dir, 'sess-1', 'checkpoint.json')}.tmp` + writeFileSync(tmpPath, 'stale', { mode: 0o644 }) + + await mgr.checkpoint('sess-1', makeSnapshot()) + + expect(modeOf(sessionPath(dir, 'sess-1', 'checkpoint.json'))).toBe(0o600) + } + ) + + onPosix('keeps the sweep marker out of the restorable-session listing', async () => { + await mgr.openSession('sess-1', { cwd: '/tmp', cols: 80, rows: 24 }) + await repairTerminalHistoryPermissions(dir) + + expect(existsSync(join(dir, REPAIR_MARKER_NAME))).toBe(true) + expect(new HistoryReader(dir).listRestorable()).toEqual(['sess-1']) + }) + }) + + describe('repairing history written before modes were pinned', () => { + /** A base dir shaped like one written under a default umask: world-readable throughout. */ + function seedLegacyTree(): { base: string; sessionDir: string; checkpointPath: string } { + const base = isolatedDir() + const sessionDir = join(base, getHistorySessionDirName('legacy')) + mkdirSync(sessionDir, { recursive: true }) + chmodSync(base, 0o755) + chmodSync(sessionDir, 0o755) + const checkpointPath = join(sessionDir, 'checkpoint.json') + writeFileSync(checkpointPath, '{"scrollbackAnsi":"secret"}') + chmodSync(checkpointPath, 0o644) + return { base, sessionDir, checkpointPath } + } + + onPosix('tightens a pre-existing 0o644 session tree when its writer attaches', () => { + const { sessionDir, checkpointPath } = seedLegacyTree() + + tightenTerminalHistorySessionDirMode(sessionDir) + + expect(modeOf(sessionDir)).toBe(0o700) + expect(modeOf(checkpointPath)).toBe(0o600) + }) + + onPosix('sweeps the whole base dir once and then short-circuits', async () => { + const { base, sessionDir, checkpointPath } = seedLegacyTree() + + await expect(repairTerminalHistoryPermissions(base)).resolves.toBe(true) + expect(modeOf(base)).toBe(0o700) + expect(modeOf(sessionDir)).toBe(0o700) + expect(modeOf(checkpointPath)).toBe(0o600) + + // Marker-guarded: a later launch must not re-walk 10k session trees. + chmodSync(checkpointPath, 0o644) + await expect(repairTerminalHistoryPermissions(base)).resolves.toBe(false) + expect(modeOf(checkpointPath)).toBe(0o644) + }) + + onPosix('leaves a session under an open recovery freeze alone', async () => { + const { base, sessionDir: legacyDir, checkpointPath } = seedLegacyTree() + const writeErrors: Error[] = [] + const mgr = new HistoryManager(base, { + onWriteError: (_sessionId, error) => writeErrors.push(error) + }) + try { + await mgr.openSession('frozen', { cwd: '/tmp', cols: 80, rows: 24 }) + await mgr.checkpoint('frozen', makeSnapshot()) + + // The production ordering: freeze fingerprints, the sweep runs, then the writer re-registers. + const freeze = await mgr.freezeForRecovery('frozen') + await expect(repairTerminalHistoryPermissions(base)).resolves.toBe(true) + mgr.registerWriter('frozen', freeze) + + expect(writeErrors.map((error) => error.message)).toEqual([]) + expect(mgr.isSessionDisabled('frozen')).toBe(false) + // Persistence, not just the absence of an error: the pane must still reach disk. + await mgr.checkpoint('frozen', makeSnapshot({ snapshotAnsi: 'after the sweep\r\n' })) + expect(readFileSync(sessionPath(base, 'frozen', 'checkpoint.json'), 'utf-8')).toContain( + 'after the sweep' + ) + } finally { + await mgr.dispose() + } + + // Narrow skip: every session that is not frozen is still tightened by the same sweep. + expect(modeOf(legacyDir)).toBe(0o700) + expect(modeOf(checkpointPath)).toBe(0o600) + }) + + onPosix('sweeps a session tree once its recovery freeze is released', async () => { + const base = isolatedDir() + const mgr = new HistoryManager(base) + try { + await mgr.openSession('thawed', { cwd: '/tmp', cols: 80, rows: 24 }) + const freeze = await mgr.freezeForRecovery('thawed') + mgr.abandonRecoveryFreeze(freeze) + } finally { + await mgr.dispose() + } + const sessionDir = join(base, getHistorySessionDirName('thawed')) + chmodSync(sessionDir, 0o755) + + await expect(repairTerminalHistoryPermissions(base)).resolves.toBe(true) + + expect(modeOf(sessionDir)).toBe(0o700) + }) + + onPosix('defers the sweep off the daemon-init critical path and runs it once', async () => { + const { base, checkpointPath } = seedLegacyTree() + vi.useFakeTimers() + try { + const first = scheduleTerminalHistoryPermissionRepair(base) + // Both startup accessors ask for the same tree; only the first arms a sweep. + expect(scheduleTerminalHistoryPermissionRepair(base)).toBeNull() + expect(vi.getTimerCount()).toBe(1) + + // Still armed, and the tree still untouched, well past daemon init — the sibling + // history GC waits the same 10s over this directory for the same reason. + await vi.advanceTimersByTimeAsync(9_999) + expect(vi.getTimerCount()).toBe(1) + expect(existsSync(join(base, REPAIR_MARKER_NAME))).toBe(false) + expect(modeOf(checkpointPath)).toBe(0o644) + + await vi.advanceTimersByTimeAsync(1) + await expect(first).resolves.toBe(true) + } finally { + vi.useRealTimers() + } + expect(modeOf(checkpointPath)).toBe(0o600) + }) + + onPosix('finishes and marks the sweep done even when every chmod is rejected', async () => { + const { base } = seedLegacyTree() + vi.resetModules() + vi.doMock('node:fs/promises', async () => { + const actual = await vi.importActual('node:fs/promises') + return { + ...actual, + default: actual, + chmod: () => Promise.reject(Object.assign(new Error('EPERM'), { code: 'EPERM' })) + } + }) + try { + const { repairTerminalHistoryPermissions: patchedRepair } = + await import('./terminal-history-permission-repair') + await expect(patchedRepair(base)).resolves.toBe(true) + } finally { + vi.doUnmock('node:fs/promises') + vi.resetModules() + } + + expect(existsSync(join(base, REPAIR_MARKER_NAME))).toBe(true) + }) + }) + + describe('hosts where POSIX modes do not apply', () => { + it('skips the repair sweep on win32 rather than touching the tree', async () => { + const base = isolatedDir() + const restore = stubPlatform('win32') + try { + await expect(repairTerminalHistoryPermissions(base)).resolves.toBe(false) + } finally { + restore() + } + expect(existsSync(join(base, REPAIR_MARKER_NAME))).toBe(false) + }) + + it('still writes history when the platform reports win32', async () => { + const base = isolatedDir() + const restore = stubPlatform('win32') + const mgr = new HistoryManager(base) + try { + await mgr.openSession('win-sess', { cwd: 'C:\\tmp', cols: 80, rows: 24 }) + await mgr.checkpoint('win-sess', makeSnapshot()) + } finally { + await mgr.dispose() + restore() + } + + expect(readFileSync(sessionPath(base, 'win-sess', 'checkpoint.json'), 'utf-8')).toContain( + 'secret scrollback' + ) + }) + + onPosix('still writes history when chmod itself throws', async () => { + const base = isolatedDir() + vi.resetModules() + vi.doMock('node:fs', async () => { + const actual = await vi.importActual('node:fs') + const chmodSyncThrows = (): never => { + throw Object.assign(new Error('EPERM: operation not permitted'), { code: 'EPERM' }) + } + return { ...actual, default: actual, chmodSync: chmodSyncThrows } + }) + try { + const { HistoryManager: PatchedHistoryManager } = await import('./history-manager') + const mgr = new PatchedHistoryManager(base) + await mgr.openSession('chmodless', { cwd: '/tmp', cols: 80, rows: 24 }) + await mgr.checkpoint('chmodless', makeSnapshot()) + await mgr.dispose() + } finally { + vi.doUnmock('node:fs') + vi.resetModules() + } + + expect(readFileSync(sessionPath(base, 'chmodless', 'checkpoint.json'), 'utf-8')).toContain( + 'secret scrollback' + ) + }) + }) +}) diff --git a/src/main/daemon/terminal-history-recovery-freezes.ts b/src/main/daemon/terminal-history-recovery-freezes.ts new file mode 100644 index 00000000000..1ec1eff432d --- /dev/null +++ b/src/main/daemon/terminal-history-recovery-freezes.ts @@ -0,0 +1,48 @@ +import { join } from 'node:path' +import { getHistorySessionDirName } from './history-paths' +import { + markTerminalHistorySessionRecoveryFrozen, + unmarkTerminalHistorySessionRecoveryFrozen, + type ActiveHistoryRecoveryFreeze +} from './terminal-history-recovery-quarantine' + +/** The recovery freezes one HistoryManager holds, each paired with the process-wide hold that keeps + * the backlog permission sweep off a tree whose fingerprint has already been taken. Paired here so + * the in-memory freeze and that hold cannot drift apart across the manager's many release paths. */ +export class TerminalHistoryRecoveryFreezes { + private readonly bySessionId = new Map() + + constructor(private readonly basePath: string) {} + + get(sessionId: string): ActiveHistoryRecoveryFreeze | undefined { + return this.bySessionId.get(sessionId) + } + + has(sessionId: string): boolean { + return this.bySessionId.has(sessionId) + } + + hold(sessionId: string, freeze: ActiveHistoryRecoveryFreeze): void { + this.bySessionId.set(sessionId, freeze) + // Why before the caller's first await: the sweep must see the hold before the freeze reads the + // fingerprint it later re-checks, or a chmod in between silently disables the session's writer. + markTerminalHistorySessionRecoveryFrozen(this.sessionDir(sessionId)) + } + + release(sessionId: string): void { + if (this.bySessionId.delete(sessionId)) { + unmarkTerminalHistorySessionRecoveryFrozen(this.sessionDir(sessionId)) + } + } + + /** Why: an outstanding hold would keep the sweep off that tree for the rest of the process. */ + releaseAll(): void { + for (const sessionId of this.bySessionId.keys()) { + this.release(sessionId) + } + } + + private sessionDir(sessionId: string): string { + return join(this.basePath, getHistorySessionDirName(sessionId)) + } +} diff --git a/src/main/daemon/terminal-history-recovery-quarantine.ts b/src/main/daemon/terminal-history-recovery-quarantine.ts index 414fe4f58e5..ba60b951c52 100644 --- a/src/main/daemon/terminal-history-recovery-quarantine.ts +++ b/src/main/daemon/terminal-history-recovery-quarantine.ts @@ -1,14 +1,7 @@ import { createHash, randomUUID } from 'node:crypto' -import { - existsSync, - lstatSync, - mkdirSync, - readdirSync, - renameSync, - unlinkSync, - writeFileSync -} from 'node:fs' -import { join } from 'node:path' +import { existsSync, lstatSync, readdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs' +import { join, resolve } from 'node:path' +import { ensurePrivateDir, PRIVATE_FILE_MODE } from './daemon-private-file-modes' import { getHistorySessionDirName } from './history-paths' const QUARANTINE_DIR_NAME = '.recovery-quarantine' @@ -35,6 +28,39 @@ export function getTerminalHistoryQuarantineOwnerDir(basePath: string, sessionId return join(basePath, QUARANTINE_DIR_NAME, sessionHash) } +// Why process-wide and not a HistoryManager field: the freeze lives in this process's memory while +// the backlog permission sweep walks the same tree from an unrelated module, and its chmod moves the +// `mode`/`ctimeMs` that fingerprintTerminalHistorySession hashes. Refcounted because the legacy and +// current daemon adapters each hold their own HistoryManager over one base path. +const recoveryFrozenSessionDirs = new Map() + +export function markTerminalHistorySessionRecoveryFrozen(sessionDir: string): void { + const key = resolve(sessionDir) + recoveryFrozenSessionDirs.set(key, (recoveryFrozenSessionDirs.get(key) ?? 0) + 1) +} + +export function unmarkTerminalHistorySessionRecoveryFrozen(sessionDir: string): void { + const key = resolve(sessionDir) + const held = recoveryFrozenSessionDirs.get(key) + if (held === undefined) { + return + } + if (held > 1) { + recoveryFrozenSessionDirs.set(key, held - 1) + } else { + recoveryFrozenSessionDirs.delete(key) + } +} + +/** True while a session tree must not be touched by anything outside its own recovery handshake: + * an open freeze holds a fingerprint of it, or a failed quarantine left it fail-closed on disk. */ +export function isTerminalHistorySessionDirRecoveryProtected(sessionDir: string): boolean { + return ( + recoveryFrozenSessionDirs.has(resolve(sessionDir)) || + existsSync(join(sessionDir, RECOVERY_PROTECTION_MARKER)) + ) +} + export function hasTerminalHistoryRecoveryProtection(basePath: string, sessionId: string): boolean { return existsSync(join(basePath, getHistorySessionDirName(sessionId), RECOVERY_PROTECTION_MARKER)) } @@ -83,8 +109,8 @@ export function quarantineTerminalHistorySession( const sessionDir = join(basePath, getHistorySessionDirName(sessionId)) const ownerDir = getTerminalHistoryQuarantineOwnerDir(basePath, sessionId) // Why: if rename is blocked, a later adapter must not attach a writer to the unreadable generation. - writeFileSync(join(sessionDir, RECOVERY_PROTECTION_MARKER), '') - mkdirSync(ownerDir, { recursive: true }) + writeFileSync(join(sessionDir, RECOVERY_PROTECTION_MARKER), '', { mode: PRIVATE_FILE_MODE }) + ensurePrivateDir(ownerDir) const quarantineDir = join(ownerDir, randomUUID()) renameSync(sessionDir, quarantineDir) return quarantineDir diff --git a/src/main/daemon/terminal-history-session-files.ts b/src/main/daemon/terminal-history-session-files.ts new file mode 100644 index 00000000000..fb11b02c11f --- /dev/null +++ b/src/main/daemon/terminal-history-session-files.ts @@ -0,0 +1,36 @@ +// The files one terminal-history session tree owns, and the whole-tree operations over them. +// Single list so the stale-file reset and the permission tightening cannot drift apart. + +import { unlinkSync } from 'node:fs' +import { join } from 'node:path' +import { PRIVATE_DIR_MODE, PRIVATE_FILE_MODE, tightenPathMode } from './daemon-private-file-modes' + +export const TERMINAL_HISTORY_SESSION_FILE_NAMES = [ + 'checkpoint.json', + 'output.log', + 'meta.json', + 'scrollback.bin' +] as const + +// meta.json survives: a reset re-anchors replayable state, not the session's identity. +const REPLAYABLE_SESSION_FILE_NAMES = ['checkpoint.json', 'scrollback.bin', 'output.log'] as const + +/** Why: a crash before the first checkpoint must not replay a cleanly ended prior session. */ +export function clearReplayableTerminalHistorySessionFiles(dir: string): void { + for (const name of REPLAYABLE_SESSION_FILE_NAMES) { + try { + unlinkSync(join(dir, name)) + } catch { + // ENOENT is expected for new sessions. + } + } +} + +/** Idempotent and ~5 syscalls: tighten one session tree as it is opened for writing. Needed because + * `mode` on writeFile only applies at creation, so files an older daemon left at umask stay open. */ +export function tightenTerminalHistorySessionDirMode(dir: string): void { + tightenPathMode(dir, PRIVATE_DIR_MODE) + for (const name of TERMINAL_HISTORY_SESSION_FILE_NAMES) { + tightenPathMode(join(dir, name), PRIVATE_FILE_MODE) + } +} diff --git a/src/main/daemon/terminal-history-session-tombstone.ts b/src/main/daemon/terminal-history-session-tombstone.ts index d72f9e8f798..d557bdac03c 100644 --- a/src/main/daemon/terminal-history-session-tombstone.ts +++ b/src/main/daemon/terminal-history-session-tombstone.ts @@ -3,9 +3,10 @@ // so the stop-and-wait path is metadata-only, and drain the queue off the critical path. import { randomUUID } from 'node:crypto' -import { existsSync, mkdirSync, readdirSync, renameSync } from 'node:fs' +import { existsSync, readdirSync, renameSync } from 'node:fs' import { join } from 'node:path' import { removeHostTree } from '../host-tree-removal' +import { ensurePrivateDir } from './daemon-private-file-modes' import { getHistorySessionDirName } from './history-paths' import { getTerminalHistoryQuarantineOwnerDir } from './terminal-history-recovery-quarantine' @@ -29,7 +30,7 @@ function getPendingDeleteRoot(basePath: string): string { function tombstoneSessionTree(basePath: string, dir: string): string | null { const pendingRoot = getPendingDeleteRoot(basePath) try { - mkdirSync(pendingRoot, { recursive: true }) + ensurePrivateDir(pendingRoot) const tombstone = join(pendingRoot, randomUUID()) renameSync(dir, tombstone) return tombstone diff --git a/src/main/daemon/terminal-history-session-writer.ts b/src/main/daemon/terminal-history-session-writer.ts index 3abe8f7b485..a562f35e1ec 100644 --- a/src/main/daemon/terminal-history-session-writer.ts +++ b/src/main/daemon/terminal-history-session-writer.ts @@ -18,6 +18,8 @@ import { clearTerminalHistoryRecoveryProtection } from './terminal-history-recov import type { PendingOutputRecord, TerminalSnapshot } from './types' import { TERMINAL_HISTORY_CHECKPOINT_MAX_BYTES } from './terminal-history-file-limits' import { serializeTerminalCheckpointWithinLimit } from './terminal-checkpoint-serializer' +import { PRIVATE_FILE_MODE, tightenPathMode } from './daemon-private-file-modes' +import { tightenTerminalHistorySessionDirMode } from './terminal-history-session-files' // Why 5MB: bounds cold-restore replay time and per-session disk; hitting the cap triggers one checkpoint that resets the log. const LOG_MAX_BYTES = 5 * 1024 * 1024 @@ -37,6 +39,8 @@ export class TerminalHistorySessionWriter { this.logPath = join(dir, 'output.log') this.logGeneration = fresh ? 0 : null this.logBytes = fresh ? 0 : null + // Why here: a warm attach reuses files an older daemon created at umask, which `mode` cannot fix. + tightenTerminalHistorySessionDirMode(dir) } async appendIncrements( @@ -50,10 +54,12 @@ export class TerminalHistorySessionWriter { return 'needs-checkpoint' } if (this.logBytes === 0) { - await fsPromises.writeFile(this.logPath, encodeLogHeader(this.logGeneration ?? 0)) + await fsPromises.writeFile(this.logPath, encodeLogHeader(this.logGeneration ?? 0), { + mode: PRIVATE_FILE_MODE + }) this.logBytes = LOG_HEADER_BYTES } - await fsPromises.appendFile(this.logPath, batch) + await fsPromises.appendFile(this.logPath, batch, { mode: PRIVATE_FILE_MODE }) this.logBytes = (this.logBytes ?? LOG_HEADER_BYTES) + batch.length return 'ok' } @@ -87,9 +93,14 @@ export class TerminalHistorySessionWriter { } } const tmpPath = `${this.checkpointPath}.tmp` - await fsPromises.writeFile(tmpPath, data) + // Mode on the tmp file, not after the rename: the checkpoint is never briefly world-readable. + await fsPromises.writeFile(tmpPath, data, { mode: PRIVATE_FILE_MODE }) + // A tmp left behind by a pre-fix crash is reused in place, where `mode` no longer applies. + tightenPathMode(tmpPath, PRIVATE_FILE_MODE) await fsPromises.rename(tmpPath, this.checkpointPath) - await fsPromises.writeFile(this.logPath, encodeLogHeader(generation)) + await fsPromises.writeFile(this.logPath, encodeLogHeader(generation), { + mode: PRIVATE_FILE_MODE + }) this.logGeneration = generation this.logBytes = LOG_HEADER_BYTES clearTerminalHistoryRecoveryProtection(this.dir) diff --git a/src/main/git/command-runner/git-exec-options.ts b/src/main/git/command-runner/git-exec-options.ts index 4390d84658d..75ced0d3030 100644 --- a/src/main/git/command-runner/git-exec-options.ts +++ b/src/main/git/command-runner/git-exec-options.ts @@ -1,7 +1,10 @@ // Why: cap execFile output to prevent an uncatchable V8 string overflow; match relay MAX_GIT_BUFFER. export const DEFAULT_GIT_MAX_BUFFER = 10 * 1024 * 1024 -export type GitAdmissionTier = 'interactive' | 'status' | 'background' +// Why: the admission tier is a wire value, so it is declared with its params schema. +import type { GitAdmissionTier } from '../../../shared/rpc-contract/git-admission-tier-params' + +export type { GitAdmissionTier } export type GitExecOptions = { cwd: string diff --git a/src/main/global-fetch-call-site-audit.test.ts b/src/main/global-fetch-call-site-audit.test.ts index 023f7323b1a..a16171ea10c 100644 --- a/src/main/global-fetch-call-site-audit.test.ts +++ b/src/main/global-fetch-call-site-audit.test.ts @@ -23,9 +23,11 @@ const AUDITED_GLOBAL_FETCH_LINES = new Map([ ['main/orca-profiles/profile-cloud-client.ts', 1], ['main/orca-profiles/profile-cloud-org-members-client.ts', 1], ['main/rate-limits/codex-fetcher.ts', 3], + ['main/runtime/push/push-gateway-client.ts', 1], ['main/runtime/relay/relay-http-client.ts', 2], ['main/runtime/relay/relay-region-catalog-fetch.ts', 1], - ['main/runtime/relay/relay-region-preference.ts', 2], + // Measurement reuses the audited catalog/probe consumers, which consume or cancel every body. + ['main/runtime/relay/relay-region-preference.ts', 3], ['main/runtime/relay/relay-region-probe.ts', 1], ['main/source-control/hosted-review-api-request.ts', 1], ['main/speech/openai-transcription-client.ts', 1], diff --git a/src/main/host/electron-runtime-desktop-surface.ts b/src/main/host/electron-runtime-desktop-surface.ts index f709804955c..056db03176a 100644 --- a/src/main/host/electron-runtime-desktop-surface.ts +++ b/src/main/host/electron-runtime-desktop-surface.ts @@ -1,8 +1,10 @@ -import { BrowserWindow, ipcMain, Notification } from 'electron' +import { BrowserWindow, ipcMain, Notification, powerMonitor } from 'electron' +import { readDesktopAwayState } from '../notifications/desktop-away-state' import type { RuntimeDesktopSurface } from '../runtime/runtime-desktop-surface' /** The desktop implementation of the runtime's optional desktop facilities. */ export const electronRuntimeDesktopSurface: RuntimeDesktopSurface = { + isAwayForMobileNotifications: () => readDesktopAwayState(powerMonitor), showNotification: ({ title, body }) => { if (!Notification.isSupported()) { return false diff --git a/src/main/ipc/agent-hooks.test.ts b/src/main/ipc/agent-hooks.test.ts index 001380e934d..f8e3420720a 100644 --- a/src/main/ipc/agent-hooks.test.ts +++ b/src/main/ipc/agent-hooks.test.ts @@ -293,6 +293,17 @@ describe('agentStatus:drop IPC', () => { expect(clearMigrationUnsupportedPtysForPaneKey).toHaveBeenCalledWith(PANE_KEY) }) + it('forwards a runtime-owned legacy numeric row dismissal', async () => { + const { registerAgentHookHandlers } = await import('./agent-hooks') + registerAgentHookHandlers() + + const handler = onHandlers.get('agentStatus:drop')! + handler!({}, 'tab-1:0') + + expect(dropStatusEntry).toHaveBeenCalledWith('tab-1:0') + expect(clearMigrationUnsupportedPtysForPaneKey).toHaveBeenCalledWith('tab-1:0') + }) + it('rejects non-string paneKey (defensive against a malformed renderer message)', async () => { const { registerAgentHookHandlers } = await import('./agent-hooks') registerAgentHookHandlers() @@ -305,7 +316,6 @@ describe('agentStatus:drop IPC', () => { null, {}, [], - 'tab-1:0', // legacy numeric pane-key suffix 'no-colon', // missing colon — rejected by isValidPaneKey ':leading', // empty tabId half 'trailing:', // empty leafId half diff --git a/src/main/ipc/agent-status-row-teardown-ipc.ts b/src/main/ipc/agent-status-row-teardown-ipc.ts index 020cfa7259d..5e42312ec20 100644 --- a/src/main/ipc/agent-status-row-teardown-ipc.ts +++ b/src/main/ipc/agent-status-row-teardown-ipc.ts @@ -1,6 +1,7 @@ import { ipcMain } from 'electron' import { agentHookServer, isValidPaneKey } from '../agent-hooks/server' import type { AgentStatusCacheIdentity } from '../../shared/agent-status-types' +import { parseLegacyNumericPaneKey } from '../../shared/stable-pane-id' import { clearMigrationUnsupportedPtysByTabPrefix, clearMigrationUnsupportedPtysForPaneKey @@ -27,7 +28,10 @@ export function registerAgentStatusRowTeardownIpcHandlers(): void { ipcMain.removeAllListeners('agentStatus:dropByTabPrefix') ipcMain.on('agentStatus:drop', (_event, paneKey: unknown) => { - if (typeof paneKey !== 'string' || !isValidPaneKey(paneKey)) { + if ( + typeof paneKey !== 'string' || + (!isValidPaneKey(paneKey) && parseLegacyNumericPaneKey(paneKey) === null) + ) { return } try { diff --git a/src/main/ipc/notification-burst-cooldown.ts b/src/main/ipc/notification-burst-cooldown.ts index e7616c57746..91e879a7e47 100644 --- a/src/main/ipc/notification-burst-cooldown.ts +++ b/src/main/ipc/notification-burst-cooldown.ts @@ -1,37 +1 @@ -const NOTIFICATION_COOLDOWN_MS = 5000 -const MAX_RECENT_NOTIFICATION_KEYS = 50 - -function pruneRecentNotifications(recentNotifications: Map, now: number): void { - if (recentNotifications.size <= MAX_RECENT_NOTIFICATION_KEYS) { - return - } - - for (const [key, ts] of recentNotifications) { - if (now - ts >= NOTIFICATION_COOLDOWN_MS) { - recentNotifications.delete(key) - } - } - - while (recentNotifications.size > MAX_RECENT_NOTIFICATION_KEYS) { - const oldest = recentNotifications.keys().next() - if (oldest.done) { - break - } - recentNotifications.delete(oldest.value) - } -} - -export function reserveNotificationCooldown( - recentNotifications: Map, - dedupeKey: string, - now: number -): boolean { - const lastSentAt = recentNotifications.get(dedupeKey) ?? 0 - if (now - lastSentAt < NOTIFICATION_COOLDOWN_MS) { - return false - } - recentNotifications.delete(dedupeKey) - recentNotifications.set(dedupeKey, now) - pruneRecentNotifications(recentNotifications, now) - return true -} +export { reserveNotificationCooldown } from '../../shared/notification-burst-cooldown' diff --git a/src/main/ipc/notification-options.ts b/src/main/ipc/notification-options.ts index a2553f05a3c..deb0b93fd2f 100644 --- a/src/main/ipc/notification-options.ts +++ b/src/main/ipc/notification-options.ts @@ -1,3 +1,4 @@ +import { translateMain } from '../i18n/main-i18n' import type { NotificationDispatchRequest } from '../../shared/notification-settings-types' const NOTIFICATION_AGENT_LABEL_MAX_LENGTH = 40 @@ -57,12 +58,7 @@ function buildAgentTaskCompleteNotificationOptions( const agentLabel = formatNotificationAgentLabel(args.agentType) const worktreeContext = formatNotificationWorktreeContext(args) - const statusText = - args.agentState === 'blocked' || args.agentState === 'waiting' - ? 'needs input' - : args.agentState === 'done' && args.agentInterrupted - ? 'stopped' - : 'finished' + const statusText = formatAgentNotificationStatusText(args) return { title: `${worktreeContext} - ${agentLabel} ${statusText}`, @@ -70,6 +66,21 @@ function buildAgentTaskCompleteNotificationOptions( } } +// Why (#4375): a still-working agent must never be announced as finished. Only an +// explicit terminal state, or no state at all (the hook snapshot expired and the +// notification itself is the completion signal), may say "finished". +function formatAgentNotificationStatusText(args: NotificationDispatchRequest): string { + if (args.agentState === 'blocked' || args.agentState === 'waiting') { + return translateMain('notifications.agentStatus.needsInput', 'needs input') + } + if (args.agentState === 'working') { + return translateMain('notifications.agentStatus.working', 'working') + } + return args.agentState === 'done' && args.agentInterrupted + ? translateMain('notifications.agentStatus.stopped', 'stopped') + : translateMain('notifications.agentStatus.finished', 'finished') +} + function formatNotificationWorktreeContext(args: NotificationDispatchRequest): string { const worktreeLabel = normalizeNotificationText( args.worktreeLabel, diff --git a/src/main/ipc/notifications-message-formatting.test.ts b/src/main/ipc/notifications-message-formatting.test.ts index 4fcbc3e0b64..677c3131203 100644 --- a/src/main/ipc/notifications-message-formatting.test.ts +++ b/src/main/ipc/notifications-message-formatting.test.ts @@ -278,6 +278,73 @@ describe('registerNotificationHandlers', () => { expect(options.body.length).toBeLessThanOrEqual(180) }) + it.each([ + { agentState: 'working', expected: 'feat/notis - Claude working' }, + { agentState: 'blocked', expected: 'feat/notis - Claude needs input' }, + { agentState: 'waiting', expected: 'feat/notis - Claude needs input' }, + { agentState: 'done', expected: 'feat/notis - Claude finished' }, + { agentState: undefined, expected: 'feat/notis - Claude finished' } + ])('titles agentState $agentState without claiming a false finish', async (scenario) => { + registerNotificationHandlers({ + getSettings: () => ({ + notifications: { + enabled: true, + agentTaskComplete: true, + terminalBell: false, + suppressWhenFocused: true + } + }) + } as never) + + const handler = getDispatchHandler() + await handler( + {}, + { + source: 'agent-task-complete', + worktreeLabel: 'feat/notis', + agentType: 'claude', + ...(scenario.agentState ? { agentState: scenario.agentState } : {}), + agentLastAssistantMessage: 'Ran the suite.' + } + ) + + expect(notificationCtorMock).toHaveBeenCalledWith( + expectedNativeNotificationOptions({ title: scenario.expected, body: 'Ran the suite.' }) + ) + }) + + it('reports an interrupted finish as stopped', async () => { + registerNotificationHandlers({ + getSettings: () => ({ + notifications: { + enabled: true, + agentTaskComplete: true, + terminalBell: false, + suppressWhenFocused: true + } + }) + } as never) + + const handler = getDispatchHandler() + await handler( + {}, + { + source: 'agent-task-complete', + worktreeLabel: 'feat/notis', + agentType: 'claude', + agentState: 'done', + agentInterrupted: true + } + ) + + expect(notificationCtorMock).toHaveBeenCalledWith( + expectedNativeNotificationOptions({ + title: 'feat/notis - Claude stopped', + body: 'Claude stopped.' + }) + ) + }) + it('uses tool context before falling back when no prompt or assistant preview exists', async () => { registerNotificationHandlers({ getSettings: () => ({ @@ -308,7 +375,7 @@ describe('registerNotificationHandlers', () => { expect(notificationCtorMock).toHaveBeenCalledWith( expectedNativeNotificationOptions({ - title: 'feat/notis - Agent finished', + title: 'feat/notis - Agent working', body: 'Using Bash: pnpm test' }) ) diff --git a/src/main/ipc/notifications-mobile-fanout.test.ts b/src/main/ipc/notifications-mobile-fanout.test.ts index 94d2535a3cc..ab797293042 100644 --- a/src/main/ipc/notifications-mobile-fanout.test.ts +++ b/src/main/ipc/notifications-mobile-fanout.test.ts @@ -71,15 +71,17 @@ describe('registerNotificationHandlers', () => { expect(dispatchMobileNotification).toHaveBeenCalledWith({ type: 'notification', + emittedAt: expect.any(Number), source: 'agent-task-complete', title: 'feat/notis - Hermes finished', body: 'The diff updates notification formatting.', - worktreeId: 'repo::wt1' + worktreeId: 'repo::wt1', + agentState: 'done' }) expect(notificationCtorMock).not.toHaveBeenCalled() }) - it('does not dispatch mobile notifications when notifications are disabled', async () => { + it('offers disabled desktop events to independently configured phones', async () => { const dispatchMobileNotification = vi.fn() registerNotificationHandlers( { @@ -101,10 +103,12 @@ describe('registerNotificationHandlers', () => { reason: 'disabled' }) - expect(dispatchMobileNotification).not.toHaveBeenCalled() + expect(dispatchMobileNotification).toHaveBeenCalledWith( + expect.objectContaining({ desktopAllowed: false }) + ) }) - it('does not dispatch mobile notifications when the source is disabled', async () => { + it('marks a disabled desktop source for phones following desktop settings', async () => { const dispatchMobileNotification = vi.fn() registerNotificationHandlers( { @@ -126,7 +130,9 @@ describe('registerNotificationHandlers', () => { reason: 'source-disabled' }) - expect(dispatchMobileNotification).not.toHaveBeenCalled() + expect(dispatchMobileNotification).toHaveBeenCalledWith( + expect.objectContaining({ desktopAllowed: false }) + ) }) it('dispatches one mobile notification when the active worktree is focused on desktop', async () => { @@ -173,7 +179,7 @@ describe('registerNotificationHandlers', () => { expect(notificationCtorMock).not.toHaveBeenCalled() }) - it('does not dispatch mobile notifications for cooldown-suppressed bursts', async () => { + it('preserves different mobile event categories before per-phone burst suppression', async () => { const dispatchMobileNotification = vi.fn() registerNotificationHandlers( { @@ -198,7 +204,7 @@ describe('registerNotificationHandlers', () => { reason: 'cooldown' }) - expect(dispatchMobileNotification).toHaveBeenCalledTimes(1) + expect(dispatchMobileNotification).toHaveBeenCalledTimes(2) expect(dispatchMobileNotification).toHaveBeenCalledWith( expect.objectContaining({ source: 'agent-task-complete', worktreeId: 'repo::wt1' }) ) diff --git a/src/main/ipc/notifications.ts b/src/main/ipc/notifications.ts index 28f6bfd95e5..274ab2719d8 100644 --- a/src/main/ipc/notifications.ts +++ b/src/main/ipc/notifications.ts @@ -1,4 +1,5 @@ -import { BrowserWindow, Notification, ipcMain } from 'electron' +import { BrowserWindow, Notification, ipcMain, powerMonitor } from 'electron' +import { readDesktopAwayState } from '../notifications/desktop-away-state' import type { Store } from '../persistence' import type { NotificationDeliveryProbeResult, @@ -26,6 +27,8 @@ import { } from './notification-permission-probe' export function registerNotificationHandlers(store: Store, runtime?: OrcaRuntimeService): void { + ipcMain.removeHandler('notifications:getDesktopAwayState') + ipcMain.handle('notifications:getDesktopAwayState', () => readDesktopAwayState(powerMonitor)) const recentDesktopNotifications = new Map() const recentMobileNotifications = new Map() resetNotificationPermissionEvidence() @@ -119,34 +122,43 @@ export function registerNotificationHandlers(store: Store, runtime?: OrcaRuntime } const settings = store.getSettings().notifications - if (!settings.enabled) { - return { delivered: false, reason: 'disabled' } - } - - if ( - (args.source === 'agent-task-complete' && !settings.agentTaskComplete) || - (args.source === 'terminal-bell' && !settings.terminalBell) - ) { - return { delivered: false, reason: 'source-disabled' } - } + const desktopAllowed = + settings.enabled && + (args.source !== 'agent-task-complete' || settings.agentTaskComplete) && + (args.source !== 'terminal-bell' || settings.terminalBell) const notificationOptions = buildNotificationOptions(args) // Why: desktop focus only means this computer sees the worktree; the paired phone may still need the alert. if (runtime && args.source !== 'test') { const dedupeKey = args.worktreeId ?? args.worktreeLabel ?? 'global' - if (reserveNotificationCooldown(recentMobileNotifications, dedupeKey, Date.now())) { + if ( + reserveNotificationCooldown( + recentMobileNotifications, + JSON.stringify([desktopAllowed, args.source, args.agentState, dedupeKey]), + Date.now() + ) + ) { runtime.dispatchMobileNotification({ type: 'notification', + emittedAt: Date.now(), source: args.source, + ...(!desktopAllowed ? { desktopAllowed: false } : {}), title: notificationOptions.title, body: notificationOptions.body, worktreeId: args.worktreeId, - ...(args.notificationId ? { notificationId: args.notificationId } : {}) + ...(args.notificationId ? { notificationId: args.notificationId } : {}), + // Why: background push needs the agent's real state to pick "needs input" + // vs "finished" — and to stay silent while the agent is still working. + ...(args.agentState ? { agentState: args.agentState } : {}) }) } } + if (!desktopAllowed) { + return { delivered: false, reason: settings.enabled ? 'source-disabled' : 'disabled' } + } + const browserWindow = BrowserWindow.getAllWindows().find((window) => !window.isDestroyed()) ?? null if ( diff --git a/src/main/ipc/runtime-environment-capability-evidence.test.ts b/src/main/ipc/runtime-environment-capability-evidence.test.ts index 4671326ef02..8c9bce5f272 100644 --- a/src/main/ipc/runtime-environment-capability-evidence.test.ts +++ b/src/main/ipc/runtime-environment-capability-evidence.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { beforeEach, describe, expect, it } from 'vitest' import type { PairingOffer } from '../../shared/pairing' import { advanceRuntimeEnvironmentCapabilityIncarnation, @@ -17,7 +17,6 @@ describe('runtime environment capability evidence', () => { it('accepts evidence by dispatch order instead of completion order', () => { const older = captureRuntimeEnvironmentCapabilityEvidence('env', pairing()) const newer = captureRuntimeEnvironmentCapabilityEvidence('env', pairing()) - const pause = vi.fn() expect( applyRuntimeEnvironmentCapabilityVerdict({ @@ -30,12 +29,10 @@ describe('runtime environment capability evidence', () => { applyRuntimeEnvironmentCapabilityVerdict({ evidence: older, verdict: 'absent', - runtimeId: 'runtime-old', - onAbsent: pause + runtimeId: 'runtime-old' }) ).toBe(false) - expect(pause).not.toHaveBeenCalled() expect(isRuntimeEnvironmentCapabilityPaused('env')).toBe(false) }) diff --git a/src/main/ipc/runtime-environment-capability-evidence.ts b/src/main/ipc/runtime-environment-capability-evidence.ts index d32bda584e9..197ec71f4f8 100644 --- a/src/main/ipc/runtime-environment-capability-evidence.ts +++ b/src/main/ipc/runtime-environment-capability-evidence.ts @@ -68,8 +68,6 @@ export function applyRuntimeEnvironmentCapabilityVerdict(args: { evidence: RuntimeEnvironmentCapabilityEvidence verdict: RuntimeEnvironmentCapabilityVerdict runtimeId: string - onCapable?: () => void - onAbsent?: () => void }): boolean { const state = stateFor(args.evidence.environmentId) if ( @@ -83,11 +81,6 @@ export function applyRuntimeEnvironmentCapabilityVerdict(args: { verdict: args.verdict, runtimeId: args.runtimeId } - if (args.verdict === 'capable') { - args.onCapable?.() - } else { - args.onAbsent?.() - } return true } diff --git a/src/main/ipc/runtime-environment-connectivity-handlers.ts b/src/main/ipc/runtime-environment-connectivity-handlers.ts index 1e267d8675a..bfbc63847c4 100644 --- a/src/main/ipc/runtime-environment-connectivity-handlers.ts +++ b/src/main/ipc/runtime-environment-connectivity-handlers.ts @@ -20,6 +20,8 @@ import { verifyAndAddRuntimeEnvironmentFromPairingCode } from './runtime-environ import { clearRuntimeEnvironmentCapabilityEvidence } from './runtime-environment-capability-evidence' import { closeRemoteRuntimeRequestConnection, + getRuntimeEnvironmentStatusOwner, + getRuntimeEnvironmentStatusSnapshots, retryRemoteRuntimeSharedControlConnectionNow } from './runtime-environment-request-connections' import { @@ -29,7 +31,6 @@ import { } from './runtime-environment-manual-disconnect' import { callRuntimeEnvironment, - clearSharedControlSupport, getRuntimeEnvironmentStatus } from './runtime-environment-transport-routing' @@ -60,6 +61,9 @@ export function registerRuntimeEnvironmentConnectivityHandlers({ getUserDataPath, invalidateTransport }: ConnectivityHandlerOptions): void { + ipcMain.handle('runtimeEnvironments:getStatusSnapshots', () => + getRuntimeEnvironmentStatusSnapshots() + ) ipcMain.handle('runtimeEnvironments:list', () => listEnvironments(getUserDataPath()).map(redactRuntimeEnvironment) ) @@ -80,6 +84,12 @@ export function registerRuntimeEnvironmentConnectivityHandlers({ const result = await verifyAndAddRuntimeEnvironmentFromPairingCode(getUserDataPath(), args) if (result.ok) { clearRuntimeEnvironmentManualDisconnect(result.environment.id) + getRuntimeEnvironmentStatusOwner(getUserDataPath(), result.environment.id).acceptVerified({ + id: 'status.get', + ok: true, + result: result.runtimeStatus, + _meta: { runtimeId: result.runtimeStatus.runtimeId } + }) } return result } @@ -121,6 +131,8 @@ export function registerRuntimeEnvironmentConnectivityHandlers({ markRuntimeEnvironmentManuallyDisconnected(environment.id) invalidateTransport(environment.id) closeLegacySelectorTransport(args.selector, environment.id) + // Retain disconnected evidence for renderers that missed the teardown event. + getRuntimeEnvironmentStatusOwner(getUserDataPath(), environment.id) return { disconnected: redactRuntimeEnvironment(environment) } } ) @@ -132,7 +144,9 @@ export function registerRuntimeEnvironmentConnectivityHandlers({ ): Promise> => { const environment = resolveEnvironment(getUserDataPath(), args.selector) clearRuntimeEnvironmentManualDisconnect(environment.id) - return getRuntimeEnvironmentStatus(getUserDataPath(), environment.id, args.timeoutMs) + return getRuntimeEnvironmentStatus(getUserDataPath(), environment.id, args.timeoutMs, { + reconnect: true + }) } ) ipcMain.handle( @@ -156,7 +170,6 @@ function closeLegacySelectorTransport(selector: string, environmentId: string): return } closeRemoteRuntimeRequestConnection(selector) - clearSharedControlSupport(selector) } function registerPassiveStatusHandler(getUserDataPath: () => string): void { diff --git a/src/main/ipc/runtime-environment-federated-read-routing.test.ts b/src/main/ipc/runtime-environment-federated-read-routing.test.ts index c58a404fd39..51c77510a01 100644 --- a/src/main/ipc/runtime-environment-federated-read-routing.test.ts +++ b/src/main/ipc/runtime-environment-federated-read-routing.test.ts @@ -1,3 +1,5 @@ +import { resetRuntimeEnvironmentStatusOwners } from './runtime-environment-request-connections' +vi.mock('electron', () => ({ BrowserWindow: { getAllWindows: () => [] } })) import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -20,14 +22,17 @@ vi.mock('../../shared/remote-runtime-client', () => ({ sendRemoteRuntimeRequest: sendRemoteRuntimeRequestMock })) -vi.mock('./runtime-environment-request-connections', () => ({ - sendRemoteRuntimeConnectionRequest: vi.fn(), - sendRemoteRuntimeSharedControlRequest: sendRemoteRuntimeSharedControlRequestMock, - reconnectRemoteRuntimeSharedControlConnection: vi.fn(), - retryRemoteRuntimeSharedControlConnectionNow: vi.fn(), - ensureRemoteRuntimeSharedControlConnection: vi.fn(), - pauseRemoteRuntimeSharedControlRetry: vi.fn() -})) +vi.mock('./runtime-environment-request-connections', async () => { + const { withRuntimeStatusOwners } = await import('./runtime-environments-ipc-test-harness') + return withRuntimeStatusOwners({ + sendRemoteRuntimeConnectionRequest: vi.fn(), + sendRemoteRuntimeSharedControlRequest: sendRemoteRuntimeSharedControlRequestMock, + reconnectRemoteRuntimeSharedControlConnection: vi.fn(), + retryRemoteRuntimeSharedControlConnectionNow: vi.fn(), + ensureRemoteRuntimeSharedControlConnection: vi.fn(), + pauseRemoteRuntimeSharedControlRetry: vi.fn() + }) +}) import { callRuntimeEnvironment, @@ -55,6 +60,7 @@ describe('federated read RPC transport routing', () => { }) afterEach(() => { + resetRuntimeEnvironmentStatusOwners() rmSync(userDataPath, { recursive: true, force: true }) }) diff --git a/src/main/ipc/runtime-environment-handler-channels.ts b/src/main/ipc/runtime-environment-handler-channels.ts index 0b63dea943a..23b40fe5183 100644 --- a/src/main/ipc/runtime-environment-handler-channels.ts +++ b/src/main/ipc/runtime-environment-handler-channels.ts @@ -9,6 +9,7 @@ export const RUNTIME_ENVIRONMENT_HANDLER_CHANNELS = [ 'runtimeEnvironments:retryControlConnection', 'runtimeEnvironments:prepareBrowserClientHostPlacement', 'runtimeEnvironments:getStatus', + 'runtimeEnvironments:getStatusSnapshots', 'runtimeEnvironments:call', 'runtimeEnvironments:subscribe', 'runtimeEnvironments:unsubscribe' diff --git a/src/main/ipc/runtime-environment-request-connections.test.ts b/src/main/ipc/runtime-environment-request-connections.test.ts index 750d1becc6a..b02d1b06fb5 100644 --- a/src/main/ipc/runtime-environment-request-connections.test.ts +++ b/src/main/ipc/runtime-environment-request-connections.test.ts @@ -47,9 +47,9 @@ describe('runtime environment shared-control connection cache', () => { applyRuntimeEnvironmentCapabilityVerdict({ evidence: absent, verdict: 'absent', - runtimeId: 'runtime-test', - onAbsent: () => pauseRemoteRuntimeSharedControlRetry(ENVIRONMENT_ID) + runtimeId: 'runtime-test' }) + pauseRemoteRuntimeSharedControlRetry(ENVIRONMENT_ID) expect(getRemoteRuntimeSharedControlDiagnostics(ENVIRONMENT_ID)?.state).toBe('closed') await delay(400) expect(server.connectionCount()).toBe(1) @@ -58,12 +58,10 @@ describe('runtime environment shared-control connection cache', () => { applyRuntimeEnvironmentCapabilityVerdict({ evidence: capable, verdict: 'capable', - runtimeId: 'runtime-test', - onCapable: () => { - ensureRemoteRuntimeSharedControlConnection(ENVIRONMENT_ID, server.pairing) - reconnectRemoteRuntimeSharedControlConnection(ENVIRONMENT_ID) - } + runtimeId: 'runtime-test' }) + ensureRemoteRuntimeSharedControlConnection(ENVIRONMENT_ID, server.pairing) + reconnectRemoteRuntimeSharedControlConnection(ENVIRONMENT_ID) await waitFor(() => server.connectionCount() === 2) }) @@ -119,9 +117,9 @@ describe('runtime environment shared-control connection cache', () => { applyRuntimeEnvironmentCapabilityVerdict({ evidence, verdict: 'absent', - runtimeId: 'runtime-test', - onAbsent: () => pauseRemoteRuntimeSharedControlRetry(ENVIRONMENT_ID) + runtimeId: 'runtime-test' }) + pauseRemoteRuntimeSharedControlRetry(ENVIRONMENT_ID) expect(getRemoteRuntimeSharedControlDiagnostics(ENVIRONMENT_ID)?.state).toBe('reconnecting') await waitFor(() => server.connectionCount() === 2) diff --git a/src/main/ipc/runtime-environment-request-connections.ts b/src/main/ipc/runtime-environment-request-connections.ts index c1f855697e5..6ba9f273c1e 100644 --- a/src/main/ipc/runtime-environment-request-connections.ts +++ b/src/main/ipc/runtime-environment-request-connections.ts @@ -1,4 +1,9 @@ import type { PairingOffer } from '../../shared/pairing' +import { resolveEnvironment } from '../../shared/runtime-environment-store' +import { getPreferredPairingOffer } from '../../shared/runtime-environments' +import type { RuntimeHostStatusOwner } from '../../shared/runtime-host-status-owner' +import type { RuntimeStatus } from '../../shared/runtime-types' +import { createRuntimeEnvironmentStatusOwner } from './runtime-environment-status-owner' import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../shared/protocol-version' import type { RuntimeOrchestrationEnvelope, @@ -30,6 +35,56 @@ type CachedSharedControlConnection = { const requestConnections = new Map() const sharedControlConnections = new Map() +const statusOwners = new Map() + +export function getRuntimeEnvironmentStatusOwner( + userDataPath: string, + selector: string +): RuntimeHostStatusOwner { + const environment = resolveEnvironment(userDataPath, selector) + const pairing = getPreferredPairingOffer(environment) + const key = `${userDataPath}\0${environment.pairingRevision ?? environment.createdAt}\0${getPairingKey(pairing)}` + let cached = statusOwners.get(environment.id) + if (!cached || cached.key !== key || cached.owner.read().retired) { + if (cached) { + closeRemoteRuntimeRequestConnection(environment.id) + } + const owner = createRuntimeEnvironmentStatusOwner(userDataPath, environment, { + isReady: () => getRemoteRuntimeSharedControlDiagnostics(environment.id)?.state === 'ready', + request: (signal) => + sendRemoteRuntimeSharedControlRequest( + environment.id, + pairing, + 'status.get', + undefined, + 15_000, + undefined, + signal + ), + establish: () => { + ensureRemoteRuntimeSharedControlConnection(environment.id, pairing) + reconnectRemoteRuntimeSharedControlConnection(environment.id) + }, + pause: () => pauseRemoteRuntimeSharedControlRetry(environment.id) + }) + cached = { key, owner } + statusOwners.set(environment.id, cached) + if (isRuntimeEnvironmentManuallyDisconnected(environment.id)) { + owner.dispose() + } + } + return cached.owner +} + +export function resetRuntimeEnvironmentStatusOwners(): void { + for (const id of statusOwners.keys()) { + closeRemoteRuntimeRequestConnection(id) + } +} + +export function getRuntimeEnvironmentStatusSnapshots() { + return [...statusOwners.values()].map(({ owner }) => owner.read()) +} export function sendRemoteRuntimeConnectionRequest( environmentId: string, @@ -56,6 +111,9 @@ export function sendRemoteRuntimeConnectionRequest( } export function closeRemoteRuntimeRequestConnection(environmentId: string): void { + const status = statusOwners.get(environmentId) + statusOwners.delete(environmentId) + status?.owner.dispose() const cached = requestConnections.get(environmentId) requestConnections.delete(environmentId) cached?.connection.close() @@ -166,6 +224,16 @@ function getSharedControlConnection( transportGeneration, diagnostics }) + statusOwners + .get(environmentId) + ?.owner.connectionChanged( + diagnostics.state === 'ready' + ? 'ready' + : diagnostics.state === 'closed' || diagnostics.state === 'reconnecting' + ? 'disconnected' + : 'connecting', + diagnostics + ) } }) } diff --git a/src/main/ipc/runtime-environment-shared-control-support.ts b/src/main/ipc/runtime-environment-shared-control-support.ts index 29513e2970a..0de6a35e0f6 100644 --- a/src/main/ipc/runtime-environment-shared-control-support.ts +++ b/src/main/ipc/runtime-environment-shared-control-support.ts @@ -1,39 +1,23 @@ -import { - ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES, - REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY -} from '../../shared/protocol-version' -import { sendRemoteRuntimeRequest } from '../../shared/remote-runtime-client' -import { markEnvironmentUsed } from '../../shared/runtime-environment-store' import type { getPreferredPairingOffer, KnownRuntimeEnvironment } from '../../shared/runtime-environments' -import type { RuntimeStatus } from '../../shared/runtime-types' +import { RemoteRuntimeClientError } from '../../shared/remote-runtime-client-error' import { - applyRuntimeEnvironmentCapabilityVerdict, - captureRuntimeEnvironmentCapabilityEvidence, getAcceptedRuntimeEnvironmentCapabilityOutcome, - isRuntimeEnvironmentCapabilityOutcomeCurrent, - runtimeEnvironmentCapabilityOutcome, resetRuntimeEnvironmentCapabilityEvidence, type RuntimeEnvironmentCapabilityOutcome } from './runtime-environment-capability-evidence' -import { pauseRemoteRuntimeSharedControlRetry } from './runtime-environment-request-connections' - -const sharedControlSupport = new Map< - string, - { cacheKey: string; check: Promise } ->() +import { + getRuntimeEnvironmentStatusOwner, + resetRuntimeEnvironmentStatusOwners +} from './runtime-environment-request-connections' export function resetSharedControlSupport(): void { - sharedControlSupport.clear() + resetRuntimeEnvironmentStatusOwners() resetRuntimeEnvironmentCapabilityEvidence() } -export function clearSharedControlSupport(environmentId: string): void { - sharedControlSupport.delete(environmentId) -} - export async function supportsSharedControl( userDataPath: string, environment: KnownRuntimeEnvironment, @@ -48,85 +32,17 @@ export async function supportsSharedControl( if (accepted) { return accepted } - const cacheKey = getSharedControlSupportCacheKey(environment, pairing) - const cached = sharedControlSupport.get(environment.id) - if (cached?.cacheKey === cacheKey) { - const outcome = await cached.check - if (isRuntimeEnvironmentCapabilityOutcomeCurrent(outcome)) { - return outcome - } - if (sharedControlSupport.get(environment.id)?.check === cached.check) { - sharedControlSupport.delete(environment.id) - } - return { kind: 'stale_incarnation' } + const response = await getRuntimeEnvironmentStatusOwner(userDataPath, environment.id).refresh({ + timeoutMs + }) + if (!response.ok) { + throw new RemoteRuntimeClientError(response.error.code, response.error.message) } - let resolvedCacheKey = cacheKey - const evidence = captureRuntimeEnvironmentCapabilityEvidence(environment.id, pairing) - const check = (async () => { - const response = await sendRemoteRuntimeRequest( + return ( + getAcceptedRuntimeEnvironmentCapabilityOutcome( + environment.id, pairing, - 'status.get', - undefined, - timeoutMs, - undefined, - undefined, - ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES - ) - if (response.ok === true) { - const verdict = response.result.capabilities?.includes( - REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY - ) - ? 'capable' - : 'absent' - const acceptedEvidence = applyRuntimeEnvironmentCapabilityVerdict({ - evidence, - verdict, - runtimeId: response._meta.runtimeId, - onAbsent: () => pauseRemoteRuntimeSharedControlRetry(environment.id) - }) - if (!acceptedEvidence) { - return { kind: 'stale_incarnation' } as const - } - markEnvironmentUsed(userDataPath, environment.id, { runtimeId: response._meta.runtimeId }) - resolvedCacheKey = getSharedControlSupportCacheKey( - environment, - pairing, - response._meta.runtimeId - ) - return runtimeEnvironmentCapabilityOutcome(evidence, verdict, response._meta.runtimeId) - } - return runtimeEnvironmentCapabilityOutcome( - evidence, - 'absent', - environment.runtimeId ?? 'unknown-runtime' - ) - })() - // Why: support belongs to the saved pairing/runtime identity, not its mutable display name. - sharedControlSupport.set(environment.id, { cacheKey, check }) - try { - const outcome = await check - const cachedAfterCheck = sharedControlSupport.get(environment.id) - if (cachedAfterCheck?.check === check && cachedAfterCheck.cacheKey !== resolvedCacheKey) { - sharedControlSupport.set(environment.id, { cacheKey: resolvedCacheKey, check }) - } - return outcome - } catch (error) { - if (sharedControlSupport.get(environment.id)?.check === check) { - sharedControlSupport.delete(environment.id) - } - throw error - } -} - -function getSharedControlSupportCacheKey( - environment: KnownRuntimeEnvironment, - pairing: ReturnType, - runtimeId = environment.runtimeId -): string { - return [ - runtimeId ?? 'unknown-runtime', - pairing.endpoint, - pairing.deviceToken, - pairing.publicKeyB64 - ].join('\0') + response._meta.runtimeId + ) ?? { kind: 'stale_incarnation' } + ) } diff --git a/src/main/ipc/runtime-environment-status-connection.test.ts b/src/main/ipc/runtime-environment-status-connection.test.ts new file mode 100644 index 00000000000..8d4fad6f9b9 --- /dev/null +++ b/src/main/ipc/runtime-environment-status-connection.test.ts @@ -0,0 +1,65 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it, vi } from 'vitest' +import { encodePairingOffer } from '../../shared/pairing' +import { addEnvironmentFromPairingCode } from '../../shared/runtime-environment-store' +import { REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY } from '../../shared/protocol-version' +import { + createSharedControlTestServer, + closeSharedControlTestServers +} from '../../shared/remote-runtime-shared-control-test-server' +import { getRuntimeEnvironmentStatus } from './runtime-environment-transport-routing' +import { + getRuntimeEnvironmentStatusOwner, + resetRuntimeEnvironmentStatusOwners +} from './runtime-environment-request-connections' + +vi.mock('electron', () => ({ BrowserWindow: { getAllWindows: () => [] } })) +const profiles: string[] = [] +afterEach(async () => { + resetRuntimeEnvironmentStatusOwners() + await closeSharedControlTestServers() + profiles.splice(0).forEach((profile) => rmSync(profile, { recursive: true, force: true })) +}) + +it('publishes real same-socket verification after every authenticated reconnect', async () => { + let runtimeId = 'host-before' + const server = await createSharedControlTestServer({ + resultForRequest: () => ({ + runtimeId, + capabilities: [REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY] + }) + }) + const profile = mkdtempSync(join(tmpdir(), 'orca-status-socket-')) + profiles.push(profile) + const environment = addEnvironmentFromPairingCode(profile, { + name: 'host', + pairingCode: encodePairingOffer(server.pairing) + }) + await getRuntimeEnvironmentStatus(profile, environment.id) + const owner = getRuntimeEnvironmentStatusOwner(profile, environment.id) + await vi.waitFor( + () => { + expect(owner.read()).toMatchObject({ transport: 'ready', verification: 'verified' }) + expect(server.requests).toHaveLength(2) + }, + { timeout: 3_000 } + ) + expect(server.connectionCount()).toBe(2) // Bootstrap plus persistent control. + runtimeId = 'host-after' + server.closeClients() + await vi.waitFor( + () => { + expect(owner.read().status?.runtimeId).toBe('host-after') + expect(owner.read().verification).toBe('verified') + }, + { timeout: 3_000 } + ) + expect(server.connectionCount()).toBe(3) + expect(server.requests.map((request) => request.method)).toEqual([ + 'status.get', + 'status.get', + 'status.get' + ]) +}) diff --git a/src/main/ipc/runtime-environment-status-owner.ts b/src/main/ipc/runtime-environment-status-owner.ts new file mode 100644 index 00000000000..4ac3c067f74 --- /dev/null +++ b/src/main/ipc/runtime-environment-status-owner.ts @@ -0,0 +1,89 @@ +import { BrowserWindow } from 'electron' +import { sendRemoteRuntimeRequest } from '../../shared/remote-runtime-client' +import { + ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES, + REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY +} from '../../shared/protocol-version' +import { + getPreferredPairingOffer, + type KnownRuntimeEnvironment +} from '../../shared/runtime-environments' +import { markEnvironmentUsed } from '../../shared/runtime-environment-store' +import { RuntimeHostStatusOwner } from '../../shared/runtime-host-status-owner' +import { + RUNTIME_HOST_STATUS_CHANNEL, + type RuntimeHostStatusResponse +} from '../../shared/runtime-host-status' +import { + applyRuntimeEnvironmentCapabilityVerdict, + getAcceptedRuntimeEnvironmentCapabilityOutcome, + captureRuntimeEnvironmentCapabilityEvidence +} from './runtime-environment-capability-evidence' +import { isRuntimeEnvironmentManuallyDisconnected } from './runtime-environment-manual-disconnect' + +export function createRuntimeEnvironmentStatusOwner( + userDataPath: string, + environment: KnownRuntimeEnvironment, + transport: { + isReady: () => boolean + request: (signal: AbortSignal) => Promise + establish: () => void + pause: () => void + } +): RuntimeHostStatusOwner { + const pairing = getPreferredPairingOffer(environment) + let evidence = captureRuntimeEnvironmentCapabilityEvidence(environment.id, pairing) + return new RuntimeHostStatusOwner({ + environmentId: environment.id, + pairingRevision: environment.pairingRevision ?? environment.createdAt, + request: (signal) => { + evidence = captureRuntimeEnvironmentCapabilityEvidence(environment.id, pairing) + return transport.isReady() && + getAcceptedRuntimeEnvironmentCapabilityOutcome(environment.id, pairing, null)?.kind === + 'supported' + ? transport.request(signal) + : sendRemoteRuntimeRequest( + pairing, + 'status.get', + undefined, + 15_000, + undefined, + signal, + ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES + ) + }, + verified: (response, active) => { + const capable = + response.result.capabilities?.includes(REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY) ?? false + const accepted = applyRuntimeEnvironmentCapabilityVerdict({ + evidence, + verdict: capable ? 'capable' : 'absent', + runtimeId: response._meta.runtimeId + }) + if (accepted && active && !isRuntimeEnvironmentManuallyDisconnected(environment.id)) { + markEnvironmentUsed(userDataPath, environment.id, { + runtimeId: response._meta.runtimeId, + pairedDeviceId: response.result.pairedDeviceId + }) + if (capable) { + transport.establish() + } else { + transport.pause() + } + } + return capable && active + }, + publish: (snapshot) => { + for (const window of BrowserWindow.getAllWindows()) { + if (window.isDestroyed()) { + continue + } + try { + window.webContents.send(RUNTIME_HOST_STATUS_CHANNEL, snapshot) + } catch { + /* A renderer can close during publication. */ + } + } + } + }) +} diff --git a/src/main/ipc/runtime-environment-status-recovery.test.ts b/src/main/ipc/runtime-environment-status-recovery.test.ts new file mode 100644 index 00000000000..82e94ea62e0 --- /dev/null +++ b/src/main/ipc/runtime-environment-status-recovery.test.ts @@ -0,0 +1,89 @@ +import { REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY } from '../../shared/protocol-version' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { addEnvironmentFromPairingCode } from '../../shared/runtime-environment-store' +import { pairingCode } from './runtime-environments-ipc-test-harness' +import { + getRuntimeEnvironmentStatus, + resetSharedControlSupport +} from './runtime-environment-transport-routing' + +const { request, publish } = vi.hoisted(() => ({ request: vi.fn(), publish: vi.fn() })) +vi.mock('../../shared/remote-runtime-client', () => ({ + sendRemoteRuntimeRequest: request, + subscribeRemoteRuntimeRequest: vi.fn() +})) +vi.mock('electron', () => ({ + BrowserWindow: { + getAllWindows: () => [ + { + isDestroyed: () => false, + webContents: { send: publish } + } + ] + } +})) + +let profile: string +beforeEach(() => { + vi.useFakeTimers() + request.mockReset() + publish.mockReset() + profile = mkdtempSync(join(tmpdir(), 'orca-status-recovery-')) +}) +afterEach(() => { + resetSharedControlSupport() + vi.useRealTimers() + rmSync(profile, { recursive: true, force: true }) +}) + +it('recovers a saved host after its first status check fails, without another UI request', async () => { + const environment = addEnvironmentFromPairingCode(profile, { + name: 'offline-at-startup', + pairingCode: pairingCode() + }) + request + .mockRejectedValueOnce( + Object.assign(new Error('host offline'), { code: 'runtime_unavailable' }) + ) + .mockResolvedValue({ + id: 'status', + ok: true, + result: { runtimeId: 'host-1', graphStatus: 'ready', capabilities: [] }, + _meta: { runtimeId: 'host-1' } + }) + expect((await getRuntimeEnvironmentStatus(profile, environment.id)).ok).toBe(false) + await vi.advanceTimersByTimeAsync(3_000) + expect(request).toHaveBeenCalledTimes(2) + expect(publish).toHaveBeenCalledWith( + 'runtimeEnvironments:statusChanged', + expect.objectContaining({ + environmentId: environment.id, + verification: 'verified', + status: expect.objectContaining({ runtimeId: 'host-1' }) + }) + ) + await vi.advanceTimersByTimeAsync(300_000) + expect(request).toHaveBeenCalledTimes(2) +}) + +it('a passive capability check does not strand later active bootstrap recovery', async () => { + const environment = addEnvironmentFromPairingCode(profile, { + name: 'passive-first', + pairingCode: pairingCode() + }) + request + .mockResolvedValueOnce({ + id: 'status', + ok: true, + result: { runtimeId: 'host-1', capabilities: [REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY] }, + _meta: { runtimeId: 'host-1' } + }) + .mockRejectedValue(new Error('host offline')) + await getRuntimeEnvironmentStatus(profile, environment.id, undefined, { observeOnly: true }) + await getRuntimeEnvironmentStatus(profile, environment.id) + await vi.advanceTimersByTimeAsync(3_000) + expect(request).toHaveBeenCalledTimes(3) +}) diff --git a/src/main/ipc/runtime-environment-support-routing.test.ts b/src/main/ipc/runtime-environment-support-routing.test.ts index feb09ee481a..8fdde15a81c 100644 --- a/src/main/ipc/runtime-environment-support-routing.test.ts +++ b/src/main/ipc/runtime-environment-support-routing.test.ts @@ -57,7 +57,6 @@ describe('runtime environment support routing', () => { ).resolves.toMatchObject({ ok: true }) expect(supportsMock).toHaveBeenCalledTimes(2) - expect(clearSupportMock).toHaveBeenCalledOnce() expect(supported).toHaveBeenCalledOnce() expect(unsupported).not.toHaveBeenCalled() }) diff --git a/src/main/ipc/runtime-environment-support-routing.ts b/src/main/ipc/runtime-environment-support-routing.ts index e2503ad4445..9566b2fc1b7 100644 --- a/src/main/ipc/runtime-environment-support-routing.ts +++ b/src/main/ipc/runtime-environment-support-routing.ts @@ -18,10 +18,7 @@ import { type RuntimeEnvironmentCapabilityOutcome } from './runtime-environment-capability-evidence' import { runtimeEnvironmentRevisionFailure } from './runtime-environment-revision-guard' -import { - clearSharedControlSupport, - supportsSharedControl -} from './runtime-environment-shared-control-support' +import { supportsSharedControl } from './runtime-environment-shared-control-support' import { sendRemoteRuntimeRequestAbortable, sendRemoteRuntimeSharedControlRequestAbortable @@ -205,7 +202,6 @@ export async function routeRuntimeEnvironmentCallBySupport(args: { } return response } - clearSharedControlSupport(environment.id) environment = resolveEnvironment(args.userDataPath, environment.id) } return runtimeEnvironmentChangedFailure(environment, args.method) diff --git a/src/main/ipc/runtime-environment-transport-routing-tailscale-hint.test.ts b/src/main/ipc/runtime-environment-transport-routing-tailscale-hint.test.ts index a44f5df84c6..bb2bbdac322 100644 --- a/src/main/ipc/runtime-environment-transport-routing-tailscale-hint.test.ts +++ b/src/main/ipc/runtime-environment-transport-routing-tailscale-hint.test.ts @@ -1,20 +1,23 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { generateKeyPair, publicKeyToBase64 } from '../../shared/e2ee-crypto' import { encodePairingOffer, type PairingOffer } from '../../shared/pairing' import { addEnvironmentFromPairingCode } from '../../shared/runtime-environment-store' import { callRuntimeEnvironment, getRuntimeEnvironmentStatus, - subscribeRuntimeEnvironment + subscribeRuntimeEnvironment, + resetSharedControlSupport } from './runtime-environment-transport-routing' // Why: prove the wiring, not just the helper — an unreachable endpoint exercises // the real WebSocket failure → reject → Tailscale-hint join points the settings // probe (returned ok:false) and in-use calls (thrown) actually use. +vi.mock('electron', () => ({ BrowserWindow: { getAllWindows: () => [] } })) + let userDataPath: string function seedEnvironment(name: string, endpoint: string): string { @@ -39,6 +42,7 @@ beforeEach(() => { }) afterEach(() => { + resetSharedControlSupport() rmSync(userDataPath, { recursive: true, force: true }) }) diff --git a/src/main/ipc/runtime-environment-transport-routing.ts b/src/main/ipc/runtime-environment-transport-routing.ts index 70f49816603..b19b0d9e376 100644 --- a/src/main/ipc/runtime-environment-transport-routing.ts +++ b/src/main/ipc/runtime-environment-transport-routing.ts @@ -1,8 +1,5 @@ import { getPreferredPairingOffer } from '../../shared/runtime-environments' -import { - ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES, - REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY -} from '../../shared/protocol-version' +import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../shared/protocol-version' import { resolveEnvironment, markEnvironmentUsed } from '../../shared/runtime-environment-store' import { isOrchestrationMutation } from '../../shared/orchestration-rpc-contract' import type { @@ -11,33 +8,22 @@ import type { } from '../../shared/runtime-rpc-envelope' import type { RuntimeStatus } from '../../shared/runtime-types' import { - sendRemoteRuntimeRequest, subscribeRemoteRuntimeRequest, type RemoteRuntimeSubscription } from '../../shared/remote-runtime-client' import { withRemoteRuntimeTailscaleHint } from '../../shared/remote-runtime-tailscale-hint' import { enqueueRuntimeCall } from './runtime-environment-call-queue' -import { - ensureRemoteRuntimeSharedControlConnection, - pauseRemoteRuntimeSharedControlRetry, - reconnectRemoteRuntimeSharedControlConnection -} from './runtime-environment-request-connections' +import { getRuntimeEnvironmentStatusOwner } from './runtime-environment-request-connections' import { sendRemoteRuntimeConnectionRequestAbortable, sendRemoteRuntimeRequestAbortable } from './runtime-environment-abortable-requests' import { attachRemoteControlDiagnostics } from './runtime-environment-status-diagnostics' -import { - applyRuntimeEnvironmentCapabilityVerdict, - captureRuntimeEnvironmentCapabilityEvidence -} from './runtime-environment-capability-evidence' + import { isRuntimeEnvironmentManuallyDisconnected } from './runtime-environment-manual-disconnect' import { runtimeEnvironmentRevisionFailure } from './runtime-environment-revision-guard' import { withTailscaleHintForResponse } from './runtime-environment-tailscale-response' -import { - clearSharedControlSupport, - resetSharedControlSupport -} from './runtime-environment-shared-control-support' +import { resetSharedControlSupport } from './runtime-environment-shared-control-support' import { executeSupportRoutedCall, shouldRouteCallBySupport, @@ -47,72 +33,31 @@ import { const DEFAULT_REMOTE_RUNTIME_TIMEOUT_MS = 15_000 -export { clearSharedControlSupport, resetSharedControlSupport } +export { resetSharedControlSupport } export async function getRuntimeEnvironmentStatus( userDataPath: string, selector: string, timeoutMs?: number, - options?: { observeOnly?: true } + options?: { observeOnly?: true; signal?: AbortSignal; reconnect?: true } ): Promise> { const environment = resolveEnvironment(userDataPath, selector) - const pairing = getPreferredPairingOffer(environment) - const evidence = captureRuntimeEnvironmentCapabilityEvidence(environment.id, pairing) - let response: RuntimeRpcResponse - try { - response = await sendRemoteRuntimeRequest( - pairing, - 'status.get', - undefined, - timeoutMs ?? DEFAULT_REMOTE_RUNTIME_TIMEOUT_MS, - undefined, - undefined, - ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES - ) - } catch (error) { - // Why: the status UI needs shared-control diagnostics most when the - // fresh status probe failed and the host is reconnecting/offline. - return attachRemoteControlDiagnostics( - withTailscaleHintForResponse( - { - id: 'status.get', - ok: false, - error: { - code: 'runtime_unavailable', - message: error instanceof Error ? error.message : String(error) - }, - _meta: { runtimeId: environment.runtimeId } - }, - pairing.endpoint - ), - environment.id - ) - } - if (response.ok === true) { - const verdict = response.result.capabilities?.includes(REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY) - ? 'capable' - : 'absent' - const accepted = applyRuntimeEnvironmentCapabilityVerdict({ - evidence, - verdict, - runtimeId: response._meta.runtimeId, - onCapable: () => { - if (!options?.observeOnly && !isRuntimeEnvironmentManuallyDisconnected(environment.id)) { - ensureRemoteRuntimeSharedControlConnection(environment.id, pairing) - reconnectRemoteRuntimeSharedControlConnection(environment.id) - } - }, - onAbsent: () => pauseRemoteRuntimeSharedControlRetry(environment.id) - }) - if (accepted && !options?.observeOnly) { - markEnvironmentUsed(userDataPath, environment.id, { - runtimeId: response._meta.runtimeId, - pairedDeviceId: response.result.pairedDeviceId - }) + if (isRuntimeEnvironmentManuallyDisconnected(environment.id)) { + return { + id: 'status.get', + ok: false, + error: { + code: 'runtime_manually_disconnected', + message: 'Runtime environment is manually disconnected.' + } } } + const response = await getRuntimeEnvironmentStatusOwner(userDataPath, environment.id).refresh({ + timeoutMs, + ...options + }) return attachRemoteControlDiagnostics( - withTailscaleHintForResponse(response, pairing.endpoint), + withTailscaleHintForResponse(response, getPreferredPairingOffer(environment).endpoint), environment.id ) } @@ -127,6 +72,15 @@ export async function callRuntimeEnvironment( envelope?: RuntimeOrchestrationEnvelope, options?: { signal?: AbortSignal } ): Promise> { + if (method === 'status.get') { + const environment = resolveEnvironment(userDataPath, selector) + const failure = runtimeEnvironmentRevisionFailure( + environment, + expectedEnvironmentPairingRevision, + method + ) + return failure ?? getRuntimeEnvironmentStatus(userDataPath, selector, timeoutMs, options) + } const environment = resolveEnvironment(userDataPath, selector) // Why: connection failures reject (they don't resolve as ok:false), so the // Tailscale hint is applied to the thrown error here — wrapping the resolved diff --git a/src/main/ipc/runtime-environments-call-routing.test.ts b/src/main/ipc/runtime-environments-call-routing.test.ts index ef92dc66826..e6f8946527d 100644 --- a/src/main/ipc/runtime-environments-call-routing.test.ts +++ b/src/main/ipc/runtime-environments-call-routing.test.ts @@ -1,3 +1,4 @@ +import { resetRuntimeEnvironmentStatusOwners } from './runtime-environment-request-connections' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -44,6 +45,7 @@ const { })) vi.mock('electron', () => ({ + BrowserWindow: { getAllWindows: () => [] }, app: { getPath: getPathMock }, ipcMain: { handle: handleMock, @@ -58,18 +60,23 @@ vi.mock('../../shared/remote-runtime-client', () => ({ subscribeRemoteRuntimeRequest: subscribeRemoteRuntimeRequestMock })) -vi.mock('./runtime-environment-request-connections', () => ({ - sendRemoteRuntimeConnectionRequest: sendRemoteRuntimeConnectionRequestMock, - sendRemoteRuntimeSharedControlRequest: sendRemoteRuntimeSharedControlRequestMock, - subscribeRemoteRuntimeSharedControlRequest: subscribeRemoteRuntimeSharedControlRequestMock, - getRemoteRuntimeSharedControlDiagnostics: getRemoteRuntimeSharedControlDiagnosticsMock, - reconnectRemoteRuntimeSharedControlConnection: reconnectRemoteRuntimeSharedControlConnectionMock, - retryRemoteRuntimeSharedControlConnectionsNow: retryRemoteRuntimeSharedControlConnectionsNowMock, - retryRemoteRuntimeSharedControlConnectionNow: vi.fn(), - ensureRemoteRuntimeSharedControlConnection: vi.fn(), - pauseRemoteRuntimeSharedControlRetry: vi.fn(), - closeRemoteRuntimeRequestConnection: closeRemoteRuntimeRequestConnectionMock -})) +vi.mock('./runtime-environment-request-connections', async () => { + const { withRuntimeStatusOwners } = await import('./runtime-environments-ipc-test-harness') + return withRuntimeStatusOwners({ + sendRemoteRuntimeConnectionRequest: sendRemoteRuntimeConnectionRequestMock, + sendRemoteRuntimeSharedControlRequest: sendRemoteRuntimeSharedControlRequestMock, + subscribeRemoteRuntimeSharedControlRequest: subscribeRemoteRuntimeSharedControlRequestMock, + getRemoteRuntimeSharedControlDiagnostics: getRemoteRuntimeSharedControlDiagnosticsMock, + reconnectRemoteRuntimeSharedControlConnection: + reconnectRemoteRuntimeSharedControlConnectionMock, + retryRemoteRuntimeSharedControlConnectionsNow: + retryRemoteRuntimeSharedControlConnectionsNowMock, + retryRemoteRuntimeSharedControlConnectionNow: vi.fn(), + ensureRemoteRuntimeSharedControlConnection: vi.fn(), + pauseRemoteRuntimeSharedControlRetry: vi.fn(), + closeRemoteRuntimeRequestConnection: closeRemoteRuntimeRequestConnectionMock + }) +}) import { registerRuntimeEnvironmentHandlers } from './runtime-environments' import { channelHandlerLookup, pairingCode } from './runtime-environments-ipc-test-harness' @@ -112,6 +119,7 @@ describe('registerRuntimeEnvironmentHandlers', () => { }) afterEach(() => { + resetRuntimeEnvironmentStatusOwners() rmSync(userDataPath, { recursive: true, force: true }) }) @@ -339,7 +347,7 @@ describe('registerRuntimeEnvironmentHandlers', () => { undefined, 15_000, undefined, - undefined, + expect.any(AbortSignal), ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES ) expect(sendRemoteRuntimeSharedControlRequestMock).toHaveBeenCalledWith( @@ -451,7 +459,7 @@ describe('registerRuntimeEnvironmentHandlers', () => { } ) - it('keeps uncoded call failures on the rejected IPC fallback path', async () => { + it('returns uncoded status failures through the owner response', async () => { registerRuntimeEnvironmentHandlers(store as never) sendRemoteRuntimeRequestMock.mockRejectedValue(new Error('shared down')) @@ -464,9 +472,10 @@ describe('registerRuntimeEnvironmentHandlers', () => { 'runtimeEnvironments:call' ) - await expect(call(null, { selector: 'desk', method: 'status.get' })).rejects.toThrow( - 'shared down' - ) + await expect(call(null, { selector: 'desk', method: 'status.get' })).resolves.toMatchObject({ + ok: false, + error: { code: 'runtime_unavailable', message: 'shared down' } + }) }) it('does not fall back after a shared-control request fails on a supported runtime', async () => { diff --git a/src/main/ipc/runtime-environments-capability-cache.test.ts b/src/main/ipc/runtime-environments-capability-cache.test.ts index 8ac11d69dd1..32f724df981 100644 --- a/src/main/ipc/runtime-environments-capability-cache.test.ts +++ b/src/main/ipc/runtime-environments-capability-cache.test.ts @@ -1,3 +1,4 @@ +import { resetRuntimeEnvironmentStatusOwners } from './runtime-environment-request-connections' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -37,6 +38,7 @@ const { })) vi.mock('electron', () => ({ + BrowserWindow: { getAllWindows: () => [] }, app: { getPath: getPathMock }, ipcMain: { handle: handleMock, @@ -51,18 +53,23 @@ vi.mock('../../shared/remote-runtime-client', () => ({ subscribeRemoteRuntimeRequest: subscribeRemoteRuntimeRequestMock })) -vi.mock('./runtime-environment-request-connections', () => ({ - sendRemoteRuntimeConnectionRequest: sendRemoteRuntimeConnectionRequestMock, - sendRemoteRuntimeSharedControlRequest: sendRemoteRuntimeSharedControlRequestMock, - subscribeRemoteRuntimeSharedControlRequest: subscribeRemoteRuntimeSharedControlRequestMock, - getRemoteRuntimeSharedControlDiagnostics: getRemoteRuntimeSharedControlDiagnosticsMock, - reconnectRemoteRuntimeSharedControlConnection: reconnectRemoteRuntimeSharedControlConnectionMock, - retryRemoteRuntimeSharedControlConnectionsNow: retryRemoteRuntimeSharedControlConnectionsNowMock, - retryRemoteRuntimeSharedControlConnectionNow: vi.fn(), - ensureRemoteRuntimeSharedControlConnection: vi.fn(), - pauseRemoteRuntimeSharedControlRetry: vi.fn(), - closeRemoteRuntimeRequestConnection: closeRemoteRuntimeRequestConnectionMock -})) +vi.mock('./runtime-environment-request-connections', async () => { + const { withRuntimeStatusOwners } = await import('./runtime-environments-ipc-test-harness') + return withRuntimeStatusOwners({ + sendRemoteRuntimeConnectionRequest: sendRemoteRuntimeConnectionRequestMock, + sendRemoteRuntimeSharedControlRequest: sendRemoteRuntimeSharedControlRequestMock, + subscribeRemoteRuntimeSharedControlRequest: subscribeRemoteRuntimeSharedControlRequestMock, + getRemoteRuntimeSharedControlDiagnostics: getRemoteRuntimeSharedControlDiagnosticsMock, + reconnectRemoteRuntimeSharedControlConnection: + reconnectRemoteRuntimeSharedControlConnectionMock, + retryRemoteRuntimeSharedControlConnectionsNow: + retryRemoteRuntimeSharedControlConnectionsNowMock, + retryRemoteRuntimeSharedControlConnectionNow: vi.fn(), + ensureRemoteRuntimeSharedControlConnection: vi.fn(), + pauseRemoteRuntimeSharedControlRetry: vi.fn(), + closeRemoteRuntimeRequestConnection: closeRemoteRuntimeRequestConnectionMock + }) +}) import { registerRuntimeEnvironmentHandlers } from './runtime-environments' import { channelHandlerLookup, pairingCode } from './runtime-environments-ipc-test-harness' @@ -105,6 +112,7 @@ describe('registerRuntimeEnvironmentHandlers', () => { }) afterEach(() => { + resetRuntimeEnvironmentStatusOwners() rmSync(userDataPath, { recursive: true, force: true }) }) @@ -182,9 +190,10 @@ describe('registerRuntimeEnvironmentHandlers', () => { { selector: string; method: string; params?: unknown; timeoutMs?: number }, { ok: true; result: unknown } >('runtimeEnvironments:call') - await expect(call(null, { selector: 'desk', method: 'repo.list' })).rejects.toThrow( - 'probe failed' - ) + await expect(call(null, { selector: 'desk', method: 'repo.list' })).resolves.toMatchObject({ + ok: false, + error: { code: 'runtime_unavailable', message: 'probe failed' } + }) await expect(call(null, { selector: 'desk', method: 'repo.list' })).resolves.toMatchObject({ ok: true, result: { repos: [] } diff --git a/src/main/ipc/runtime-environments-ipc-test-harness.ts b/src/main/ipc/runtime-environments-ipc-test-harness.ts index 016352793cb..e97e45ede1a 100644 --- a/src/main/ipc/runtime-environments-ipc-test-harness.ts +++ b/src/main/ipc/runtime-environments-ipc-test-harness.ts @@ -1,6 +1,62 @@ import { expect } from 'vitest' import type { Mock } from 'vitest' +import { getPreferredPairingOffer } from '../../shared/runtime-environments' import { encodePairingOffer } from '../../shared/pairing' +import { resolveEnvironment } from '../../shared/runtime-environment-store' +import { createRuntimeEnvironmentStatusOwner } from './runtime-environment-status-owner' +import type { RuntimeHostStatusOwner } from '../../shared/runtime-host-status-owner' +import { isRuntimeEnvironmentManuallyDisconnected } from './runtime-environment-manual-disconnect' + +/** Keep IPC tests on the production owner while replacing only its transport. */ +export function withRuntimeStatusOwners>(transport: T) { + const owners = new Map() + return { + ...transport, + getRuntimeEnvironmentStatusOwner: (profile: string, selector: string) => { + const environment = resolveEnvironment(profile, selector) + let owner = owners.get(environment.id) + if (!owner || owner.read().retired) { + owner = createRuntimeEnvironmentStatusOwner(profile, environment, { + isReady: () => + transport.getRemoteRuntimeSharedControlDiagnostics?.(environment.id)?.state === 'ready', + request: (signal) => + transport.sendRemoteRuntimeSharedControlRequest( + environment.id, + undefined, + 'status.get', + undefined, + 15_000, + undefined, + signal + ), + establish: () => { + transport.ensureRemoteRuntimeSharedControlConnection?.( + environment.id, + getPreferredPairingOffer(environment) + ) + transport.reconnectRemoteRuntimeSharedControlConnection?.(environment.id) + }, + pause: () => transport.pauseRemoteRuntimeSharedControlRetry?.(environment.id) + }) + owners.set(environment.id, owner) + if (isRuntimeEnvironmentManuallyDisconnected(environment.id)) { + owner.dispose() + } + } + return owner + }, + getRuntimeEnvironmentStatusSnapshots: () => [...owners.values()].map((owner) => owner.read()), + resetRuntimeEnvironmentStatusOwners: () => { + owners.forEach((owner) => owner.dispose()) + owners.clear() + }, + closeRemoteRuntimeRequestConnection: (...args: unknown[]) => { + owners.get(args[0] as string)?.dispose() + owners.delete(args[0] as string) + transport.closeRemoteRuntimeRequestConnection(...args) + } + } +} export function pairingCode(endpoint = 'ws://127.0.0.1:6768'): string { return encodePairingOffer({ diff --git a/src/main/ipc/runtime-environments-pairing.test.ts b/src/main/ipc/runtime-environments-pairing.test.ts index 87d6c2698ab..ce492a7a740 100644 --- a/src/main/ipc/runtime-environments-pairing.test.ts +++ b/src/main/ipc/runtime-environments-pairing.test.ts @@ -1,3 +1,5 @@ +import type { RuntimeHostStatusSnapshot } from '../../shared/runtime-host-status' +import { resetRuntimeEnvironmentStatusOwners } from './runtime-environment-request-connections' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -44,6 +46,7 @@ const { })) vi.mock('electron', () => ({ + BrowserWindow: { getAllWindows: () => [] }, app: { getPath: getPathMock }, ipcMain: { handle: handleMock, @@ -58,18 +61,23 @@ vi.mock('../../shared/remote-runtime-client', () => ({ subscribeRemoteRuntimeRequest: subscribeRemoteRuntimeRequestMock })) -vi.mock('./runtime-environment-request-connections', () => ({ - sendRemoteRuntimeConnectionRequest: sendRemoteRuntimeConnectionRequestMock, - sendRemoteRuntimeSharedControlRequest: sendRemoteRuntimeSharedControlRequestMock, - subscribeRemoteRuntimeSharedControlRequest: subscribeRemoteRuntimeSharedControlRequestMock, - getRemoteRuntimeSharedControlDiagnostics: getRemoteRuntimeSharedControlDiagnosticsMock, - reconnectRemoteRuntimeSharedControlConnection: reconnectRemoteRuntimeSharedControlConnectionMock, - retryRemoteRuntimeSharedControlConnectionsNow: retryRemoteRuntimeSharedControlConnectionsNowMock, - retryRemoteRuntimeSharedControlConnectionNow: retryRemoteRuntimeSharedControlConnectionNowMock, - ensureRemoteRuntimeSharedControlConnection: vi.fn(), - pauseRemoteRuntimeSharedControlRetry: vi.fn(), - closeRemoteRuntimeRequestConnection: closeRemoteRuntimeRequestConnectionMock -})) +vi.mock('./runtime-environment-request-connections', async () => { + const { withRuntimeStatusOwners } = await import('./runtime-environments-ipc-test-harness') + return withRuntimeStatusOwners({ + sendRemoteRuntimeConnectionRequest: sendRemoteRuntimeConnectionRequestMock, + sendRemoteRuntimeSharedControlRequest: sendRemoteRuntimeSharedControlRequestMock, + subscribeRemoteRuntimeSharedControlRequest: subscribeRemoteRuntimeSharedControlRequestMock, + getRemoteRuntimeSharedControlDiagnostics: getRemoteRuntimeSharedControlDiagnosticsMock, + reconnectRemoteRuntimeSharedControlConnection: + reconnectRemoteRuntimeSharedControlConnectionMock, + retryRemoteRuntimeSharedControlConnectionsNow: + retryRemoteRuntimeSharedControlConnectionsNowMock, + retryRemoteRuntimeSharedControlConnectionNow: retryRemoteRuntimeSharedControlConnectionNowMock, + ensureRemoteRuntimeSharedControlConnection: vi.fn(), + pauseRemoteRuntimeSharedControlRetry: vi.fn(), + closeRemoteRuntimeRequestConnection: closeRemoteRuntimeRequestConnectionMock + }) +}) import { registerRuntimeEnvironmentHandlers } from './runtime-environments' import { channelHandlerLookup, pairingCode } from './runtime-environments-ipc-test-harness' @@ -125,6 +133,7 @@ describe('registerRuntimeEnvironmentHandlers', () => { }) afterEach(() => { + resetRuntimeEnvironmentStatusOwners() rmSync(userDataPath, { recursive: true, force: true }) }) @@ -132,6 +141,7 @@ describe('registerRuntimeEnvironmentHandlers', () => { registerRuntimeEnvironmentHandlers(store as never) expect(handleMock.mock.calls.map((call) => call[0])).toEqual([ + 'runtimeEnvironments:getStatusSnapshots', 'runtimeEnvironments:list', 'runtimeEnvironments:addFromPairingCode', 'runtimeEnvironments:verifyAndAddFromPairingCode', @@ -166,6 +176,7 @@ describe('registerRuntimeEnvironmentHandlers', () => { 'runtimeEnvironments:retryControlConnection', 'runtimeEnvironments:prepareBrowserClientHostPlacement', 'runtimeEnvironments:getStatus', + 'runtimeEnvironments:getStatusSnapshots', 'runtimeEnvironments:call', 'runtimeEnvironments:subscribe', 'runtimeEnvironments:unsubscribe', @@ -467,6 +478,13 @@ describe('registerRuntimeEnvironmentHandlers', () => { ok: false, error: { code: 'runtime_manually_disconnected' } }) + const getSnapshots = handler( + 'runtimeEnvironments:getStatusSnapshots' + ) + // A new renderer only has the snapshot read, not the earlier disconnect event. + expect(await getSnapshots(null, undefined)).toMatchObject([ + { environmentId: added.environment.id, retired: true, transport: 'disconnected' } + ]) const call = handler< { selector: string; method: string }, { ok: boolean; error?: { code: string } } @@ -492,6 +510,10 @@ describe('registerRuntimeEnvironmentHandlers', () => { result: { runtimeId: 'runtime-remote' } }) expect(sendRemoteRuntimeRequestMock).toHaveBeenCalledOnce() + expect(await getSnapshots(null, undefined)).toMatchObject([ + { environmentId: added.environment.id, verification: 'verified' } + ]) + expect((await getSnapshots(null, undefined))[0].retired).not.toBe(true) }) it('marks environments owned by ephemeral VM runtimes in the public list', async () => { diff --git a/src/main/ipc/runtime-environments-status-diagnostics.test.ts b/src/main/ipc/runtime-environments-status-diagnostics.test.ts index b210e7c209b..9fe3d6baf0e 100644 --- a/src/main/ipc/runtime-environments-status-diagnostics.test.ts +++ b/src/main/ipc/runtime-environments-status-diagnostics.test.ts @@ -1,3 +1,4 @@ +import { resetRuntimeEnvironmentStatusOwners } from './runtime-environment-request-connections' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -44,6 +45,7 @@ const { })) vi.mock('electron', () => ({ + BrowserWindow: { getAllWindows: () => [] }, app: { getPath: getPathMock }, ipcMain: { handle: handleMock, @@ -58,18 +60,23 @@ vi.mock('../../shared/remote-runtime-client', () => ({ subscribeRemoteRuntimeRequest: subscribeRemoteRuntimeRequestMock })) -vi.mock('./runtime-environment-request-connections', () => ({ - sendRemoteRuntimeConnectionRequest: sendRemoteRuntimeConnectionRequestMock, - sendRemoteRuntimeSharedControlRequest: sendRemoteRuntimeSharedControlRequestMock, - subscribeRemoteRuntimeSharedControlRequest: subscribeRemoteRuntimeSharedControlRequestMock, - getRemoteRuntimeSharedControlDiagnostics: getRemoteRuntimeSharedControlDiagnosticsMock, - reconnectRemoteRuntimeSharedControlConnection: reconnectRemoteRuntimeSharedControlConnectionMock, - retryRemoteRuntimeSharedControlConnectionsNow: retryRemoteRuntimeSharedControlConnectionsNowMock, - retryRemoteRuntimeSharedControlConnectionNow: vi.fn(), - ensureRemoteRuntimeSharedControlConnection: ensureRemoteRuntimeSharedControlConnectionMock, - pauseRemoteRuntimeSharedControlRetry: pauseRemoteRuntimeSharedControlRetryMock, - closeRemoteRuntimeRequestConnection: closeRemoteRuntimeRequestConnectionMock -})) +vi.mock('./runtime-environment-request-connections', async () => { + const { withRuntimeStatusOwners } = await import('./runtime-environments-ipc-test-harness') + return withRuntimeStatusOwners({ + sendRemoteRuntimeConnectionRequest: sendRemoteRuntimeConnectionRequestMock, + sendRemoteRuntimeSharedControlRequest: sendRemoteRuntimeSharedControlRequestMock, + subscribeRemoteRuntimeSharedControlRequest: subscribeRemoteRuntimeSharedControlRequestMock, + getRemoteRuntimeSharedControlDiagnostics: getRemoteRuntimeSharedControlDiagnosticsMock, + reconnectRemoteRuntimeSharedControlConnection: + reconnectRemoteRuntimeSharedControlConnectionMock, + retryRemoteRuntimeSharedControlConnectionsNow: + retryRemoteRuntimeSharedControlConnectionsNowMock, + retryRemoteRuntimeSharedControlConnectionNow: vi.fn(), + ensureRemoteRuntimeSharedControlConnection: ensureRemoteRuntimeSharedControlConnectionMock, + pauseRemoteRuntimeSharedControlRetry: pauseRemoteRuntimeSharedControlRetryMock, + closeRemoteRuntimeRequestConnection: closeRemoteRuntimeRequestConnectionMock + }) +}) import { registerRuntimeEnvironmentHandlers } from './runtime-environments' import { channelHandlerLookup, pairingCode } from './runtime-environments-ipc-test-harness' @@ -114,6 +121,7 @@ describe('registerRuntimeEnvironmentHandlers', () => { }) afterEach(() => { + resetRuntimeEnvironmentStatusOwners() rmSync(userDataPath, { recursive: true, force: true }) }) @@ -148,9 +156,9 @@ describe('registerRuntimeEnvironmentHandlers', () => { expect.objectContaining({ endpoint: 'ws://127.0.0.1:6768', deviceToken: 'device-token' }), 'status.get', undefined, - 50, - undefined, + 15_000, undefined, + expect.any(AbortSignal), ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES ) expect(reconnectRemoteRuntimeSharedControlConnectionMock).toHaveBeenCalledWith( @@ -319,36 +327,41 @@ describe('registerRuntimeEnvironmentHandlers', () => { }) }) - it('returns shared-control diagnostics when saved remote runtime status throws', async () => { - registerRuntimeEnvironmentHandlers(store as never) - getRemoteRuntimeSharedControlDiagnosticsMock.mockReturnValue({ - state: 'reconnecting', - pendingRequestCount: 0, - subscriptionCount: 1, - reconnectAttempt: 2, - lastConnectedAt: 123, - lastClose: { code: 1006, reason: '' }, - lastError: 'closed' - }) - sendRemoteRuntimeRequestMock.mockRejectedValue(new Error('socket closed')) + it.each(['runtimeEnvironments:getStatus', 'runtimeEnvironments:connect'])( + 'preserves failure diagnostics and guidance on %s', + async (channel) => { + registerRuntimeEnvironmentHandlers(store as never) + getRemoteRuntimeSharedControlDiagnosticsMock.mockReturnValue({ + state: 'reconnecting', + pendingRequestCount: 0, + subscriptionCount: 1, + reconnectAttempt: 2, + lastConnectedAt: 123, + lastClose: { code: 1006, reason: '' }, + lastError: 'closed' + }) + sendRemoteRuntimeRequestMock.mockRejectedValue( + new Error('Could not connect to the remote Orca runtime.') + ) - const add = handler< - { name: string; pairingCode: string }, - { environment: { id: string; name: string } } - >('runtimeEnvironments:addFromPairingCode') - await add(null, { name: 'desk', pairingCode: pairingCode() }) + const add = handler< + { name: string; pairingCode: string }, + { environment: { id: string; name: string } } + >('runtimeEnvironments:addFromPairingCode') + await add(null, { name: 'desk', pairingCode: pairingCode() }) - const getStatus = handler< - { selector: string; timeoutMs?: number }, - { ok: false; error: { message: string; data?: { remoteControl?: { state: string } } } } - >('runtimeEnvironments:getStatus') + const getStatus = handler< + { selector: string; timeoutMs?: number }, + { ok: false; error: { message: string; data?: { remoteControl?: { state: string } } } } + >(channel) - await expect(getStatus(null, { selector: 'desk' })).resolves.toMatchObject({ - ok: false, - error: { - message: 'socket closed', - data: { remoteControl: { state: 'reconnecting' } } - } - }) - }) + await expect(getStatus(null, { selector: 'desk' })).resolves.toMatchObject({ + ok: false, + error: { + message: expect.stringContaining('connect both devices to Tailscale'), + data: { remoteControl: { state: 'reconnecting' } } + } + }) + } + ) }) diff --git a/src/main/ipc/runtime-environments-subscription-lifecycle.test.ts b/src/main/ipc/runtime-environments-subscription-lifecycle.test.ts index 53a07442c3b..ed4dcd62182 100644 --- a/src/main/ipc/runtime-environments-subscription-lifecycle.test.ts +++ b/src/main/ipc/runtime-environments-subscription-lifecycle.test.ts @@ -1,3 +1,4 @@ +import { resetRuntimeEnvironmentStatusOwners } from './runtime-environment-request-connections' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -38,6 +39,7 @@ const { })) vi.mock('electron', () => ({ + BrowserWindow: { getAllWindows: () => [] }, app: { getPath: getPathMock }, ipcMain: { handle: handleMock, @@ -52,18 +54,23 @@ vi.mock('../../shared/remote-runtime-client', () => ({ subscribeRemoteRuntimeRequest: subscribeRemoteRuntimeRequestMock })) -vi.mock('./runtime-environment-request-connections', () => ({ - sendRemoteRuntimeConnectionRequest: sendRemoteRuntimeConnectionRequestMock, - sendRemoteRuntimeSharedControlRequest: sendRemoteRuntimeSharedControlRequestMock, - subscribeRemoteRuntimeSharedControlRequest: subscribeRemoteRuntimeSharedControlRequestMock, - getRemoteRuntimeSharedControlDiagnostics: getRemoteRuntimeSharedControlDiagnosticsMock, - reconnectRemoteRuntimeSharedControlConnection: reconnectRemoteRuntimeSharedControlConnectionMock, - retryRemoteRuntimeSharedControlConnectionsNow: retryRemoteRuntimeSharedControlConnectionsNowMock, - retryRemoteRuntimeSharedControlConnectionNow: vi.fn(), - ensureRemoteRuntimeSharedControlConnection: vi.fn(), - pauseRemoteRuntimeSharedControlRetry: vi.fn(), - closeRemoteRuntimeRequestConnection: closeRemoteRuntimeRequestConnectionMock -})) +vi.mock('./runtime-environment-request-connections', async () => { + const { withRuntimeStatusOwners } = await import('./runtime-environments-ipc-test-harness') + return withRuntimeStatusOwners({ + sendRemoteRuntimeConnectionRequest: sendRemoteRuntimeConnectionRequestMock, + sendRemoteRuntimeSharedControlRequest: sendRemoteRuntimeSharedControlRequestMock, + subscribeRemoteRuntimeSharedControlRequest: subscribeRemoteRuntimeSharedControlRequestMock, + getRemoteRuntimeSharedControlDiagnostics: getRemoteRuntimeSharedControlDiagnosticsMock, + reconnectRemoteRuntimeSharedControlConnection: + reconnectRemoteRuntimeSharedControlConnectionMock, + retryRemoteRuntimeSharedControlConnectionsNow: + retryRemoteRuntimeSharedControlConnectionsNowMock, + retryRemoteRuntimeSharedControlConnectionNow: vi.fn(), + ensureRemoteRuntimeSharedControlConnection: vi.fn(), + pauseRemoteRuntimeSharedControlRetry: vi.fn(), + closeRemoteRuntimeRequestConnection: closeRemoteRuntimeRequestConnectionMock + }) +}) import { invalidateRuntimeEnvironmentTransport, @@ -109,6 +116,7 @@ describe('registerRuntimeEnvironmentHandlers', () => { }) afterEach(() => { + resetRuntimeEnvironmentStatusOwners() rmSync(userDataPath, { recursive: true, force: true }) }) diff --git a/src/main/ipc/runtime-environments-subscription-routing.test.ts b/src/main/ipc/runtime-environments-subscription-routing.test.ts index 494f0b9ea6b..0ef70f7ac96 100644 --- a/src/main/ipc/runtime-environments-subscription-routing.test.ts +++ b/src/main/ipc/runtime-environments-subscription-routing.test.ts @@ -1,3 +1,4 @@ +import { resetRuntimeEnvironmentStatusOwners } from './runtime-environment-request-connections' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -40,6 +41,7 @@ const { })) vi.mock('electron', () => ({ + BrowserWindow: { getAllWindows: () => [] }, app: { getPath: getPathMock }, ipcMain: { handle: handleMock, @@ -54,18 +56,23 @@ vi.mock('../../shared/remote-runtime-client', () => ({ subscribeRemoteRuntimeRequest: subscribeRemoteRuntimeRequestMock })) -vi.mock('./runtime-environment-request-connections', () => ({ - sendRemoteRuntimeConnectionRequest: sendRemoteRuntimeConnectionRequestMock, - sendRemoteRuntimeSharedControlRequest: sendRemoteRuntimeSharedControlRequestMock, - subscribeRemoteRuntimeSharedControlRequest: subscribeRemoteRuntimeSharedControlRequestMock, - getRemoteRuntimeSharedControlDiagnostics: getRemoteRuntimeSharedControlDiagnosticsMock, - reconnectRemoteRuntimeSharedControlConnection: reconnectRemoteRuntimeSharedControlConnectionMock, - retryRemoteRuntimeSharedControlConnectionsNow: retryRemoteRuntimeSharedControlConnectionsNowMock, - retryRemoteRuntimeSharedControlConnectionNow: vi.fn(), - ensureRemoteRuntimeSharedControlConnection: vi.fn(), - pauseRemoteRuntimeSharedControlRetry: vi.fn(), - closeRemoteRuntimeRequestConnection: closeRemoteRuntimeRequestConnectionMock -})) +vi.mock('./runtime-environment-request-connections', async () => { + const { withRuntimeStatusOwners } = await import('./runtime-environments-ipc-test-harness') + return withRuntimeStatusOwners({ + sendRemoteRuntimeConnectionRequest: sendRemoteRuntimeConnectionRequestMock, + sendRemoteRuntimeSharedControlRequest: sendRemoteRuntimeSharedControlRequestMock, + subscribeRemoteRuntimeSharedControlRequest: subscribeRemoteRuntimeSharedControlRequestMock, + getRemoteRuntimeSharedControlDiagnostics: getRemoteRuntimeSharedControlDiagnosticsMock, + reconnectRemoteRuntimeSharedControlConnection: + reconnectRemoteRuntimeSharedControlConnectionMock, + retryRemoteRuntimeSharedControlConnectionsNow: + retryRemoteRuntimeSharedControlConnectionsNowMock, + retryRemoteRuntimeSharedControlConnectionNow: vi.fn(), + ensureRemoteRuntimeSharedControlConnection: vi.fn(), + pauseRemoteRuntimeSharedControlRetry: vi.fn(), + closeRemoteRuntimeRequestConnection: closeRemoteRuntimeRequestConnectionMock + }) +}) import { registerRuntimeEnvironmentHandlers } from './runtime-environments' import { channelHandlerLookup, pairingCode } from './runtime-environments-ipc-test-harness' @@ -108,6 +115,7 @@ describe('registerRuntimeEnvironmentHandlers', () => { }) afterEach(() => { + resetRuntimeEnvironmentStatusOwners() rmSync(userDataPath, { recursive: true, force: true }) }) diff --git a/src/main/ipc/runtime-environments-subscription-teardown.test.ts b/src/main/ipc/runtime-environments-subscription-teardown.test.ts index 13a98e1057a..afb1adf457a 100644 --- a/src/main/ipc/runtime-environments-subscription-teardown.test.ts +++ b/src/main/ipc/runtime-environments-subscription-teardown.test.ts @@ -1,3 +1,4 @@ +import { resetRuntimeEnvironmentStatusOwners } from './runtime-environment-request-connections' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -38,6 +39,7 @@ const { })) vi.mock('electron', () => ({ + BrowserWindow: { getAllWindows: () => [] }, app: { getPath: getPathMock }, ipcMain: { handle: handleMock, @@ -52,18 +54,23 @@ vi.mock('../../shared/remote-runtime-client', () => ({ subscribeRemoteRuntimeRequest: subscribeRemoteRuntimeRequestMock })) -vi.mock('./runtime-environment-request-connections', () => ({ - sendRemoteRuntimeConnectionRequest: sendRemoteRuntimeConnectionRequestMock, - sendRemoteRuntimeSharedControlRequest: sendRemoteRuntimeSharedControlRequestMock, - subscribeRemoteRuntimeSharedControlRequest: subscribeRemoteRuntimeSharedControlRequestMock, - getRemoteRuntimeSharedControlDiagnostics: getRemoteRuntimeSharedControlDiagnosticsMock, - reconnectRemoteRuntimeSharedControlConnection: reconnectRemoteRuntimeSharedControlConnectionMock, - retryRemoteRuntimeSharedControlConnectionsNow: retryRemoteRuntimeSharedControlConnectionsNowMock, - retryRemoteRuntimeSharedControlConnectionNow: vi.fn(), - ensureRemoteRuntimeSharedControlConnection: vi.fn(), - pauseRemoteRuntimeSharedControlRetry: vi.fn(), - closeRemoteRuntimeRequestConnection: closeRemoteRuntimeRequestConnectionMock -})) +vi.mock('./runtime-environment-request-connections', async () => { + const { withRuntimeStatusOwners } = await import('./runtime-environments-ipc-test-harness') + return withRuntimeStatusOwners({ + sendRemoteRuntimeConnectionRequest: sendRemoteRuntimeConnectionRequestMock, + sendRemoteRuntimeSharedControlRequest: sendRemoteRuntimeSharedControlRequestMock, + subscribeRemoteRuntimeSharedControlRequest: subscribeRemoteRuntimeSharedControlRequestMock, + getRemoteRuntimeSharedControlDiagnostics: getRemoteRuntimeSharedControlDiagnosticsMock, + reconnectRemoteRuntimeSharedControlConnection: + reconnectRemoteRuntimeSharedControlConnectionMock, + retryRemoteRuntimeSharedControlConnectionsNow: + retryRemoteRuntimeSharedControlConnectionsNowMock, + retryRemoteRuntimeSharedControlConnectionNow: vi.fn(), + ensureRemoteRuntimeSharedControlConnection: vi.fn(), + pauseRemoteRuntimeSharedControlRetry: vi.fn(), + closeRemoteRuntimeRequestConnection: closeRemoteRuntimeRequestConnectionMock + }) +}) vi.mock('../browser/paired-runtime-browser-client-host-runtime', () => ({ retirePairedRuntimeBrowserClientHostEnvironment: retirePairedRuntimeBrowserClientHostEnvironmentMock @@ -115,6 +122,7 @@ describe('registerRuntimeEnvironmentHandlers', () => { }) afterEach(() => { + resetRuntimeEnvironmentStatusOwners() rmSync(userDataPath, { recursive: true, force: true }) }) diff --git a/src/main/ipc/runtime-environments.ts b/src/main/ipc/runtime-environments.ts index 7d9a261eef9..ac7a4107bc8 100644 --- a/src/main/ipc/runtime-environments.ts +++ b/src/main/ipc/runtime-environments.ts @@ -1,6 +1,6 @@ import { app, ipcMain } from 'electron' import { randomUUID } from 'node:crypto' -import { resolveEnvironment } from '../../shared/runtime-environment-store' +import { listEnvironments, resolveEnvironment } from '../../shared/runtime-environment-store' import type { RemoteRuntimeSubscription } from '../../shared/remote-runtime-client' import type { Store } from '../persistence' import { @@ -8,14 +8,16 @@ import { registerRuntimeEnvironmentConnectivityHandlers, registerRuntimeEnvironmentPassiveHandlers } from './runtime-environment-connectivity-handlers' -import { closeRemoteRuntimeRequestConnection } from './runtime-environment-request-connections' +import { + closeRemoteRuntimeRequestConnection, + getRuntimeEnvironmentStatusOwner +} from './runtime-environment-request-connections' import { registerRuntimeEnvironmentRecoveryHandler } from './runtime-environment-recovery-handler' import { advanceRuntimeEnvironmentTransportGeneration, getRuntimeEnvironmentTransportGeneration } from './runtime-environment-transport-generation' import { - clearSharedControlSupport, resetSharedControlSupport, subscribeRuntimeEnvironment } from './runtime-environment-transport-routing' @@ -64,7 +66,6 @@ export function invalidateRuntimeEnvironmentTransport(environmentId: string): Pr advanceRuntimeEnvironmentCapabilityIncarnation(environmentId) advanceRuntimeEnvironmentTransportGeneration(environmentId) closeRemoteRuntimeRequestConnection(environmentId) - clearSharedControlSupport(environmentId) closeSubscriptionsForEnvironment(environmentId) return retirePairedRuntimeBrowserClientHostEnvironment( environmentId, @@ -97,6 +98,11 @@ export function registerRuntimeEnvironmentHandlers(store: Store): void { }) registerRuntimeEnvironmentRecoveryHandler() registerRuntimeEnvironmentPassiveHandlers(getUserDataPath) + for (const environment of listEnvironments(getUserDataPath())) { + if (!isRuntimeEnvironmentManuallyDisconnected(environment.id)) { + getRuntimeEnvironmentStatusOwner(getUserDataPath(), environment.id).activate() + } + } ipcMain.handle( 'runtimeEnvironments:subscribe', async ( diff --git a/src/main/ipc/worktrees/removal/worktree-removal-ownership.ts b/src/main/ipc/worktrees/removal/worktree-removal-ownership.ts index ec2198bcdb0..ecc982076c5 100644 --- a/src/main/ipc/worktrees/removal/worktree-removal-ownership.ts +++ b/src/main/ipc/worktrees/removal/worktree-removal-ownership.ts @@ -40,11 +40,17 @@ export async function stopPtysForDestructiveWorktreeRemoval( ...(allowUnverifiedStop ? { allowUnverifiedStop: true } : {}), ...(connectionId ? { includeLocalRegistry: false } : {}) }) + // Structured sessions are counted here too: closing a user's chat is now an ordinary outcome + // of this verb, and a removal that closed one but no PTY would otherwise log nothing at all. + const structuredStopped = teardownResult.structuredStopped ?? 0 const total = - teardownResult.runtimeStopped + teardownResult.providerStopped + teardownResult.registryStopped + teardownResult.runtimeStopped + + teardownResult.providerStopped + + teardownResult.registryStopped + + structuredStopped if (total > 0) { console.info( - `[worktree-teardown] ${worktreeId} killed runtime=${teardownResult.runtimeStopped} provider=${teardownResult.providerStopped} registry=${teardownResult.registryStopped}` + `[worktree-teardown] ${worktreeId} killed runtime=${teardownResult.runtimeStopped} provider=${teardownResult.providerStopped} registry=${teardownResult.registryStopped} structured=${structuredStopped}` ) } } diff --git a/src/main/kimi/hook-service.ts b/src/main/kimi/hook-service.ts index e397fa0b026..21fee64d276 100644 --- a/src/main/kimi/hook-service.ts +++ b/src/main/kimi/hook-service.ts @@ -51,6 +51,10 @@ function getConfigPath(): string { // single curl-based script body works on every platform. const MANAGED_SCRIPT_FILE_NAME = 'kimi-hook.sh' +// Ownership test for every managed-block path: status, install, remove and the +// bounded orphan recovery all agree on what counts as an Orca-written hook. +const isManagedKimiCommand = createManagedCommandMatcher(MANAGED_SCRIPT_FILE_NAME) + function getManagedScriptPath(): string { return getSharedManagedScriptPath(MANAGED_SCRIPT_FILE_NAME) } @@ -194,8 +198,7 @@ export class KimiHookService { detail: 'Could not read Kimi config.toml' } } - const isManagedCommand = createManagedCommandMatcher(MANAGED_SCRIPT_FILE_NAME) - return buildStatus(readManagedKimiHookEvents(text, isManagedCommand), configPath) + return buildStatus(readManagedKimiHookEvents(text, isManagedKimiCommand), configPath) } install(): AgentHookInstallStatus { @@ -214,7 +217,7 @@ export class KimiHookService { const command = getManagedCommand(scriptPath) // Write the script first so config.toml never points at a missing script. writeManagedScript(scriptPath, getManagedScript()) - writeConfigToml(configPath, applyManagedKimiHooks(text, command)) + writeConfigToml(configPath, applyManagedKimiHooks(text, command, isManagedKimiCommand)) return this.getStatus() } @@ -235,7 +238,11 @@ export class KimiHookService { const command = wrapPosixHookCommand(remoteScriptPath) // Write the script first so config.toml never points at a missing script. await writeManagedScriptRemote(sftp, remoteScriptPath, getManagedScript('posix')) - await writeTextFileRemoteAtomic(sftp, remoteConfigPath, applyManagedKimiHooks(text, command)) + await writeTextFileRemoteAtomic( + sftp, + remoteConfigPath, + applyManagedKimiHooks(text, command, isManagedKimiCommand) + ) return { agent: 'kimi', state: 'installed', @@ -266,7 +273,7 @@ export class KimiHookService { detail: 'Could not read Kimi config.toml' } } - const { text: nextText, changed } = removeManagedKimiHooks(text) + const { text: nextText, changed } = removeManagedKimiHooks(text, isManagedKimiCommand) if (changed) { writeConfigToml(configPath, nextText) } diff --git a/src/main/kimi/kimi-hook-config-toml.test.ts b/src/main/kimi/kimi-hook-config-toml.test.ts index 954e3639975..525cca03efc 100644 --- a/src/main/kimi/kimi-hook-config-toml.test.ts +++ b/src/main/kimi/kimi-hook-config-toml.test.ts @@ -12,6 +12,14 @@ const COMMAND = const isManaged = (command: string | undefined): boolean => typeof command === 'string' && command.includes('agent-hooks/kimi-hook.sh') +const END_MARKER_LINE = '# <<< orca-managed-kimi-hooks <<<' +const START_MARKER = '# >>> orca-managed-kimi-hooks (managed by Orca; do not edit) >>>' + +/** Drops only the `# <<< ... <<<` line, the hand-edit that orphans the block. */ +function deleteEndMarker(text: string): string { + return text.replace(/\r?\n# <<< orca-managed-kimi-hooks <<<(?=\r?\n|$)/, '') +} + describe('kimi managed hooks TOML block', () => { it('installs every managed event without a matcher', () => { const block = buildManagedKimiHooksBlock(COMMAND) @@ -20,9 +28,9 @@ describe('kimi managed hooks TOML block', () => { } // Kimi treats matcher as a regex; omitting it matches all tools. expect(block).not.toContain('matcher') - expect(readManagedKimiHookEvents(applyManagedKimiHooks('', COMMAND), isManaged)).toEqual( - new Set(KIMI_HOOK_EVENTS) - ) + expect( + readManagedKimiHookEvents(applyManagedKimiHooks('', COMMAND, isManaged), isManaged) + ).toEqual(new Set(KIMI_HOOK_EVENTS)) }) it('preserves existing user config above the managed block', () => { @@ -40,7 +48,7 @@ describe('kimi managed hooks TOML block', () => { '' ].join('\n') - const next = applyManagedKimiHooks(userConfig, COMMAND) + const next = applyManagedKimiHooks(userConfig, COMMAND, isManaged) expect(next).toContain('default_model = "kimi-k2.6"') expect(next).toContain('api_key = "sk-secret"') // The user's own hook survives untouched. @@ -49,8 +57,8 @@ describe('kimi managed hooks TOML block', () => { }) it('is idempotent — reinstalling does not duplicate the block', () => { - const once = applyManagedKimiHooks('default_model = "x"\n', COMMAND) - const twice = applyManagedKimiHooks(once, COMMAND) + const once = applyManagedKimiHooks('default_model = "x"\n', COMMAND, isManaged) + const twice = applyManagedKimiHooks(once, COMMAND, isManaged) expect(twice).toBe(once) const markerCount = (twice.match(/orca-managed-kimi-hooks \(/g) ?? []).length expect(markerCount).toBe(1) @@ -58,52 +66,385 @@ describe('kimi managed hooks TOML block', () => { it('removes the managed block and restores the user config', () => { const userConfig = 'default_model = "kimi-k2.6"\n' - const installed = applyManagedKimiHooks(userConfig, COMMAND) - const { text, changed } = removeManagedKimiHooks(installed) + const installed = applyManagedKimiHooks(userConfig, COMMAND, isManaged) + const { text, changed } = removeManagedKimiHooks(installed, isManaged) expect(changed).toBe(true) expect(text).toBe(userConfig) expect(readManagedKimiHookEvents(text, isManaged).size).toBe(0) }) it('reports no change when removing from a config without the managed block', () => { - const { text, changed } = removeManagedKimiHooks('default_model = "x"\n') + const { text, changed } = removeManagedKimiHooks('default_model = "x"\n', isManaged) expect(changed).toBe(false) expect(text).toBe('default_model = "x"\n') }) it('is stable across repeated calls (no stateful global-regex lastIndex drift)', () => { - const installed = applyManagedKimiHooks('default_model = "x"\n', COMMAND) + const installed = applyManagedKimiHooks('default_model = "x"\n', COMMAND, isManaged) // Repeated detection/removal on the same and on a clean input must be // consistent — a `g`-flagged .test() would drift lastIndex and flip results. - expect(removeManagedKimiHooks(installed).changed).toBe(true) - expect(removeManagedKimiHooks(installed).changed).toBe(true) - expect(removeManagedKimiHooks('default_model = "x"\n').changed).toBe(false) - expect(removeManagedKimiHooks(installed).changed).toBe(true) + expect(removeManagedKimiHooks(installed, isManaged).changed).toBe(true) + expect(removeManagedKimiHooks(installed, isManaged).changed).toBe(true) + expect(removeManagedKimiHooks('default_model = "x"\n', isManaged).changed).toBe(false) + expect(removeManagedKimiHooks(installed, isManaged).changed).toBe(true) expect(readManagedKimiHookEvents(installed, isManaged)).toEqual(new Set(KIMI_HOOK_EVENTS)) expect(readManagedKimiHookEvents(installed, isManaged)).toEqual(new Set(KIMI_HOOK_EVENTS)) }) it('recovers when a hand-edit deletes only the trailing end marker', () => { - const installed = applyManagedKimiHooks('default_model = "x"\n', COMMAND) - // Simulate a user deleting just the `# <<< ... <<<` end-marker line. - const orphaned = installed.replace(/\n# <<< orca-managed-kimi-hooks <<<\n?/, '\n') + const installed = applyManagedKimiHooks('default_model = "x"\n', COMMAND, isManaged) + const orphaned = deleteEndMarker(installed) expect(orphaned).not.toContain('<<<') // The orphaned (still-active) hook tables are still recognized... expect(readManagedKimiHookEvents(orphaned, isManaged)).toEqual(new Set(KIMI_HOOK_EVENTS)) // ...remove strips them... - expect(removeManagedKimiHooks(orphaned)).toEqual({ + expect(removeManagedKimiHooks(orphaned, isManaged)).toEqual({ text: 'default_model = "x"\n', changed: true }) // ...and reinstall converges to a single block instead of duplicating. - const reinstalled = applyManagedKimiHooks(orphaned, COMMAND) + const reinstalled = applyManagedKimiHooks(orphaned, COMMAND, isManaged) expect((reinstalled.match(/orca-managed-kimi-hooks \(/g) ?? []).length).toBe(1) }) it('treats stale managed entries pointing at a moved script path as managed', () => { const staleCommand = "if [ -x '/old/userData/agent-hooks/kimi-hook.sh' ]; then /bin/sh '/old/userData/agent-hooks/kimi-hook.sh'; fi" - const stale = applyManagedKimiHooks('', staleCommand) + const stale = applyManagedKimiHooks('', staleCommand, isManaged) expect(readManagedKimiHookEvents(stale, isManaged)).toEqual(new Set(KIMI_HOOK_EVENTS)) }) }) + +// #18861: an orphaned start marker used to make every following byte "managed". +describe('orphaned managed block ownership (#18861)', () => { + const USER_TAIL = [ + '[providers."mine"]', + 'type = "openai"', + 'api_key = "sk-secret"', + '', + '[[hooks]]', + 'event = "Stop"', + 'command = "node my-own-hook.mjs"' + ].join('\n') + + function orphanedWithUserTail(): string { + const installed = applyManagedKimiHooks('default_model = "x"\n', COMMAND, isManaged) + return `${deleteEndMarker(installed)}\n${USER_TAIL}\n` + } + + it('keeps user tables appended after an orphaned block through remove', () => { + const { text, changed } = removeManagedKimiHooks(orphanedWithUserTail(), isManaged) + expect(changed).toBe(true) + expect(text).toContain('api_key = "sk-secret"') + expect(text).toContain('command = "node my-own-hook.mjs"') + expect(text).toContain('default_model = "x"') + // The reclaimed managed tables and the stray marker are gone. + expect(text).not.toContain(START_MARKER) + expect(text).not.toContain('agent-hooks/kimi-hook.sh') + }) + + it('keeps user tables appended after an orphaned block through reinstall', () => { + const reinstalled = applyManagedKimiHooks(orphanedWithUserTail(), COMMAND, isManaged) + expect(reinstalled).toContain('api_key = "sk-secret"') + expect(reinstalled).toContain('command = "node my-own-hook.mjs"') + // Exactly one well-formed block, appended after the surviving user bytes. + expect((reinstalled.match(/orca-managed-kimi-hooks \(/g) ?? []).length).toBe(1) + expect(reinstalled.indexOf('sk-secret')).toBeLessThan(reinstalled.indexOf(START_MARKER)) + expect(readManagedKimiHookEvents(reinstalled, isManaged)).toEqual(new Set(KIMI_HOOK_EVENTS)) + // And a second install is a no-op, so the recovery converges. + expect(applyManagedKimiHooks(reinstalled, COMMAND, isManaged)).toBe(reinstalled) + }) + + it('reclaims a genuinely managed orphan table but stops at the first user line', () => { + const orphan = [ + 'default_model = "x"', + '', + START_MARKER, + '[[hooks]]', + `event = "Stop"`, + `command = "${COMMAND.replaceAll('"', '')}"`, + 'timeout = 10', + '[hand.written]', + 'value = "keep"', + '' + ].join('\n') + const { text, changed } = removeManagedKimiHooks(orphan, isManaged) + expect(changed).toBe(true) + expect(text).toBe('default_model = "x"\n[hand.written]\nvalue = "keep"\n') + }) + + it('removes only the stray marker when an orphan owns no managed content', () => { + const orphan = `default_model = "x"\n\n${START_MARKER}\n[user.table]\nvalue = "keep"\n` + const { text, changed } = removeManagedKimiHooks(orphan, isManaged) + expect(changed).toBe(true) + expect(text).toBe('default_model = "x"\n[user.table]\nvalue = "keep"\n') + }) + + it('does not treat a user [[hooks]] table as Orca-owned content', () => { + const orphan = [ + START_MARKER, + '[[hooks]]', + 'event = "Stop"', + 'command = "node my-own-hook.mjs"', + 'timeout = 10', + '' + ].join('\n') + const { text } = removeManagedKimiHooks(orphan, isManaged) + expect(text).toContain('command = "node my-own-hook.mjs"') + expect(text).not.toContain(START_MARKER) + }) + + // A user adding keys has customised Orca's hook, not authored their own: the + // command path is what makes it fire. Leaving it would keep sending Orca their + // events after uninstall, and reinstall would double-fire the event. + it('owns a managed table the user added an extra key to', () => { + const orphan = [ + START_MARKER, + '[[hooks]]', + 'event = "Stop"', + `command = "${COMMAND.replaceAll('"', '')}"`, + 'timeout = 10', + 'matcher = "Bash"', + '' + ].join('\n') + expect(removeManagedKimiHooks(orphan, isManaged).text).toBe('') + }) + + it('owns a customised managed table sitting outside any marker', () => { + const customised = [ + 'default_model = "x"', + '', + '[[hooks]]', + 'event = "Stop"', + `command = "${COMMAND.replaceAll('"', '')}"`, + 'timeout = 10', + 'matcher = "Bash"', + '' + ].join('\n') + expect(removeManagedKimiHooks(customised, isManaged).text).toBe('default_model = "x"\n') + // Status agrees, so install cannot append a second table for the same event. + expect(readManagedKimiHookEvents(customised, isManaged)).toEqual(new Set(['Stop'])) + const reinstalled = applyManagedKimiHooks(customised, COMMAND, isManaged) + expect((reinstalled.match(/event = "Stop"/g) ?? []).length).toBe(1) + }) + + // Extent safety: a multi-line value means the table's end is not knowable by + // line scanning, so splicing it would take the wrong bytes. + it('fails closed on a table whose value spans lines', () => { + const orphan = [ + START_MARKER, + '[[hooks]]', + 'event = "Stop"', + `command = "${COMMAND.replaceAll('"', '')}"`, + 'args = [', + ' "a"', + ']', + '' + ].join('\n') + const { text } = removeManagedKimiHooks(orphan, isManaged) + expect(text).toContain('args = [') + expect(text).not.toContain(START_MARKER) + }) + + // CodeRabbit on #20148: the old regex reader matched key *suffixes* and + // commented-out keys. Keys are parsed exactly now; these must not register. + it('does not read a managed event from key suffixes or commented keys', () => { + const nearMiss = [ + START_MARKER, + '[[hooks]]', + 'previous_event = "Stop"', + `fallback_command = "${COMMAND.replaceAll('"', '')}"`, + 'timeout = 10', + END_MARKER_LINE, + '', + '[[hooks]]', + '# event = "PreToolUse"', + `# command = "${COMMAND.replaceAll('"', '')}"`, + '' + ].join('\n') + expect(readManagedKimiHookEvents(nearMiss, isManaged)).toEqual(new Set()) + }) + + // CodeRabbit on #20148: a blank or comment between keys does not end a TOML + // table. Splicing the bounded run would strand `timeout` without its header. + it('fails closed when more keys follow a gap inside the table', () => { + for (const gap of ['', '# note']) { + const orphan = [ + START_MARKER, + '[[hooks]]', + 'event = "Stop"', + `command = "${COMMAND.replaceAll('"', '')}"`, + gap, + 'timeout = 10', + '' + ].join('\n') + const { text } = removeManagedKimiHooks(orphan, isManaged) + expect(text).toContain('timeout = 10') + expect(text).toContain('[[hooks]]') + expect(text).not.toContain(START_MARKER) + } + }) + + it('still owns a table whose keys are followed by a gap and a new table', () => { + const orphan = [ + START_MARKER, + '[[hooks]]', + 'event = "Stop"', + `command = "${COMMAND.replaceAll('"', '')}"`, + 'timeout = 10', + '', + '# a user comment', + '', + '[user.table]', + 'v = 1', + '' + ].join('\n') + const { text } = removeManagedKimiHooks(orphan, isManaged) + expect(text).not.toContain(START_MARKER) + expect(text).not.toContain('agent-hooks/kimi-hook.sh') + // The user's comment and table are theirs; only the managed table goes. + expect(text).toContain('# a user comment') + expect(text).toContain('[user.table]') + }) + + // pullfrog on #20148: ownership keys on `command`, so an `event` Orca cannot + // parse must never let status claim nothing is installed. + it('never reports not_installed for a table remove() would strip', () => { + for (const eventLine of [`event = 'Stop'`, 'event = "Stop" # note', 'event = 12']) { + const config = [ + START_MARKER, + '[[hooks]]', + eventLine, + `command = "${COMMAND.replaceAll('"', '')}"`, + 'timeout = 10', + END_MARKER_LINE, + '' + ].join('\n') + // remove() strips it, so status must see it too. + expect(removeManagedKimiHooks(config, isManaged).changed).toBe(true) + expect(readManagedKimiHookEvents(config, isManaged).size).toBeGreaterThan(0) + } + // The single-quoted form resolves to the real event name. + const singleQuoted = [ + START_MARKER, + '[[hooks]]', + `event = 'Stop'`, + `command = "${COMMAND.replaceAll('"', '')}"`, + 'timeout = 10', + END_MARKER_LINE, + '' + ].join('\n') + expect(readManagedKimiHookEvents(singleQuoted, isManaged)).toEqual(new Set(['Stop'])) + }) + + it('leaves a hook table that does not invoke the managed script', () => { + const orphan = [ + START_MARKER, + '[[hooks]]', + 'event = "Stop"', + 'command = "node my-own-hook.mjs"', + 'timeout = 10', + 'matcher = "Bash"', + '' + ].join('\n') + const { text } = removeManagedKimiHooks(orphan, isManaged) + expect(text).toContain('command = "node my-own-hook.mjs"') + expect(text).toContain('matcher = "Bash"') + }) + + // A stranded managed table still executes, so remove() must reclaim it wherever + // a hand-edit left it; only the user's own bytes are off limits. + it('reclaims managed tables stranded below user text', () => { + const managedTable = [ + '[[hooks]]', + 'event = "Stop"', + `command = "${COMMAND.replaceAll('"', '')}"`, + 'timeout = 10' + ].join('\n') + const orphan = `${START_MARKER}\n${managedTable}\n[user.table]\nv = 1\n${managedTable}\n` + const { text } = removeManagedKimiHooks(orphan, isManaged) + expect(text).toBe('[user.table]\nv = 1\n') + }) + + it('reports a stranded managed table as live so status cannot claim uninstalled', () => { + const stranded = [ + '[user.table]', + 'v = 1', + '', + '[[hooks]]', + 'event = "PreToolUse"', + `command = "${COMMAND.replaceAll('"', '')}"`, + 'timeout = 10', + '' + ].join('\n') + expect(readManagedKimiHookEvents(stranded, isManaged)).toEqual(new Set(['PreToolUse'])) + }) + + it('reinstalling over a stranded table does not double-register its event', () => { + const stranded = [ + '[user.table]', + 'v = 1', + '', + '[[hooks]]', + 'event = "PreToolUse"', + `command = "${COMMAND.replaceAll('"', '')}"`, + 'timeout = 10', + '' + ].join('\n') + const reinstalled = applyManagedKimiHooks(stranded, COMMAND, isManaged) + expect((reinstalled.match(/event = "PreToolUse"/g) ?? []).length).toBe(1) + expect(reinstalled).toContain('[user.table]') + expect(readManagedKimiHookEvents(reinstalled, isManaged)).toEqual(new Set(KIMI_HOOK_EVENTS)) + }) + + it('stops an orphaned block at a second start marker', () => { + const installed = applyManagedKimiHooks('default_model = "x"\n', COMMAND, isManaged) + const duplicated = `${deleteEndMarker(installed)}\n${START_MARKER}\n[user.table]\nv = 1\n` + const { text, changed } = removeManagedKimiHooks(duplicated, isManaged) + expect(changed).toBe(true) + expect(text).toContain('[user.table]') + expect(text).not.toContain(START_MARKER) + expect(text).not.toContain('agent-hooks/kimi-hook.sh') + }) + + it('removes both blocks when the markers are duplicated wholesale', () => { + const installed = applyManagedKimiHooks('default_model = "x"\n', COMMAND, isManaged) + const block = buildManagedKimiHooksBlock(COMMAND) + const doubled = `${installed}\n${block}\n[user.table]\nv = 1\n` + const { text, changed } = removeManagedKimiHooks(doubled, isManaged) + expect(changed).toBe(true) + expect(text).toBe('default_model = "x"\n[user.table]\nv = 1\n') + }) + + it('leaves a stray start marker after a well-formed block bounded', () => { + const installed = applyManagedKimiHooks('default_model = "x"\n', COMMAND, isManaged) + const withStray = `${installed}${START_MARKER}\n[user.table]\nv = 1\n` + const { text } = removeManagedKimiHooks(withStray, isManaged) + expect(text).toBe('default_model = "x"\n[user.table]\nv = 1\n') + }) +}) + +describe('CRLF configs', () => { + const userConfig = 'default_model = "kimi-k2.6"\r\n' + + it('writes the managed block with the file’s existing CRLF endings', () => { + const installed = applyManagedKimiHooks(userConfig, COMMAND, isManaged) + expect(installed).not.toMatch(/[^\r]\n/) + expect(readManagedKimiHookEvents(installed, isManaged)).toEqual(new Set(KIMI_HOOK_EVENTS)) + expect(applyManagedKimiHooks(installed, COMMAND, isManaged)).toBe(installed) + expect(removeManagedKimiHooks(installed, isManaged)).toEqual({ + text: userConfig, + changed: true + }) + }) + + it('keeps CRLF user bytes after an orphaned block', () => { + const installed = applyManagedKimiHooks(userConfig, COMMAND, isManaged) + const orphaned = `${deleteEndMarker(installed)}\r\n[providers."mine"]\r\napi_key = "sk-secret"\r\n` + const { text, changed } = removeManagedKimiHooks(orphaned, isManaged) + expect(changed).toBe(true) + expect(text).toContain('api_key = "sk-secret"') + expect(text).not.toContain('agent-hooks/kimi-hook.sh') + expect(text).not.toMatch(/[^\r]\n/) + }) +}) diff --git a/src/main/kimi/kimi-hook-config-toml.ts b/src/main/kimi/kimi-hook-config-toml.ts index aae898fd327..fe3dc9d816e 100644 --- a/src/main/kimi/kimi-hook-config-toml.ts +++ b/src/main/kimi/kimi-hook-config-toml.ts @@ -2,12 +2,19 @@ // lifecycle hooks from an array of `[[hooks]]` tables. There is no JSON settings // file to reuse the shared JSON installer with, and no TOML library is vendored, // so Orca manages only its own marker-delimited block: install rewrites the -// block, remove strips it, and arbitrary user config outside the markers is left -// untouched. Appending table headers is always valid TOML, so the block can live -// at the end of any existing file. +// block, remove strips it, and user config is left untouched apart from hook +// tables Orca itself emitted. Appending table headers is always valid TOML, so +// the block can live at the end of any existing file. import { MANAGED_HOOK_TIMEOUT_SECONDS } from '../agent-hooks/installer-utils' -import { escapeRegex } from '../../shared/string-utils' +import { + findManagedTomlBlocks, + findRecognizedManagedTables, + stripManagedTomlRegions, + type ManagedTomlMarkers, + type ManagedTomlRegion, + type RecognizedManagedTable +} from '../agent-hooks/managed-toml-ownership' // Why: mirror the Claude-compatible events Orca normalizes for status. Kimi uses // these exact event names (see normalizeKimiEvent), so each maps to a @@ -22,19 +29,112 @@ export const KIMI_HOOK_EVENTS = [ 'StopFailure' ] as const -const BLOCK_START = '# >>> orca-managed-kimi-hooks (managed by Orca; do not edit) >>>' -const BLOCK_END = '# <<< orca-managed-kimi-hooks <<<' +const MARKERS: ManagedTomlMarkers = { + startMarker: '# >>> orca-managed-kimi-hooks (managed by Orca; do not edit) >>>', + endMarker: '# <<< orca-managed-kimi-hooks <<<' +} +const HOOK_TABLE_HEADER = '[[hooks]]' -// Matches the managed block plus any blank lines immediately preceding it so -// repeated install/remove cycles do not accumulate whitespace. The `|$` -// fallback also matches from BLOCK_START to end-of-file when the trailing -// BLOCK_END marker is missing (e.g. a hand-edit deleted it): the managed block -// is always written last, so this recovers orphaned hook tables and lets -// install re-converge in one step instead of appending a duplicate block. -const MANAGED_BLOCK_RE = new RegExp( - `\\n*${escapeRegex(BLOCK_START)}[\\s\\S]*?(?:${escapeRegex(BLOCK_END)}[^\\n]*|$)`, - 'g' -) +export type ManagedCommandMatcher = (command: string | undefined) => boolean + +// A `[[hooks]]` table that invokes Orca's managed script is Orca's hook: that +// command path is the only reason it fires, and it is there because Orca put it +// there. Extra keys are a user customising our hook, not authoring their own, so +// uninstall still owns it — leaving it would keep feeding Orca their events +// after they asked it to stop, and reinstall would double-fire the event. +// +// The key run is still parsed strictly: an unrecognized line shape (a multi-line +// array or string, say) means the table's extent is unknown, and guessing it +// would splice the wrong bytes. That case fails closed. +function matchManagedHookTable( + lines: readonly string[], + index: number, + isManagedCommand: ManagedCommandMatcher +): { lineCount: number; value: string | null } | null { + if (lines[index].trim() !== HOOK_TABLE_HEADER) { + return null + } + const pairs = new Map() + let cursor = index + 1 + while (cursor < lines.length) { + const line = lines[cursor].trim() + // A blank, the next table header or a comment (the end marker included) + // ends the table's key run. + if (line === '' || line.startsWith('[') || line.startsWith('#')) { + break + } + const pair = line.match(/^([A-Za-z_][\w-]*)\s*=\s*(.*)$/) + if (!pair || pairs.has(pair[1])) { + return null + } + pairs.set(pair[1], pair[2].trim()) + cursor++ + } + // TOML lets blank lines and comments sit between keys of one table, so a gap + // is not proof the table ended. If more keys follow it, the run above covered + // only part of the table and splicing it would strand the rest without its + // header — the extent is unknown, so fail closed. + if (keysFollowGap(lines, cursor)) { + return null + } + // Raw (still-escaped) literal; createManagedCommandMatcher normalizes separators itself. + const command = readTomlString(pairs.get('command')) + if (!isManagedCommand(command)) { + return null + } + return { lineCount: cursor - index, value: readEventName(pairs.get('event')) } +} + +// True when a key line follows the gap before the next table header, meaning +// the table extends past the bounded key run above. +function keysFollowGap(lines: readonly string[], from: number): boolean { + for (let cursor = from; cursor < lines.length; cursor++) { + const line = lines[cursor].trim() + if (line === '' || line.startsWith('#')) { + continue + } + return !line.startsWith('[') + } + return false +} + +// Basic or literal TOML string, ignoring any inline comment after it. +function readTomlString(value: string | undefined): string | undefined { + return value?.match(/^"((?:[^"\\]|\\.)*)"/)?.[1] ?? value?.match(/^'([^']*)'/)?.[1] +} + +// Ownership keys on the command, so an event Orca cannot parse must still +// register: status reporting `not_installed` for a table remove() will strip is +// the exact split this recognizer exists to close. An unreadable literal falls +// back to its raw text, which matches no known event and lands status on +// `partial` rather than claiming nothing is installed. +function readEventName(value: string | undefined): string | null { + if (value === undefined) { + return null + } + return readTomlString(value) ?? value.trim() ?? null +} + +function recognizeManagedTables( + configText: string, + isManagedCommand: ManagedCommandMatcher +): RecognizedManagedTable[] { + return findRecognizedManagedTables(configText, (lines, index) => + matchManagedHookTable(lines, index, isManagedCommand) + ) +} + +// Orca owns two things here: whatever sits inside a matched marker pair, and +// every table it can positively recognize wherever that table ended up. +function findOwnedRegions( + configText: string, + isManagedCommand: ManagedCommandMatcher +): ManagedTomlRegion[] { + return [ + ...findManagedTomlBlocks(configText, MARKERS), + ...recognizeManagedTables(configText, isManagedCommand) + ] +} // TOML basic (double-quoted) string. The managed command may contain single // quotes (from POSIX quoting) but no double quotes or backslashes on the paths @@ -50,7 +150,7 @@ function tomlBasicString(value: string): string { return `"${escaped}"` } -export function buildManagedKimiHooksBlock(command: string): string { +export function buildManagedKimiHooksBlock(command: string, eol = '\n'): string { const commandLiteral = tomlBasicString(command) // Omit `matcher`: Kimi treats it as a regex (so Claude's literal "*" is // invalid) and an absent matcher already matches every tool. @@ -58,52 +158,64 @@ export function buildManagedKimiHooksBlock(command: string): string { // the normal dead-endpoint bound. const entries = KIMI_HOOK_EVENTS.map((event) => [ - `[[hooks]]`, + HOOK_TABLE_HEADER, `event = "${event}"`, `command = ${commandLiteral}`, `timeout = ${MANAGED_HOOK_TIMEOUT_SECONDS}` - ].join('\n') + ].join(eol) ) - return [BLOCK_START, ...entries, BLOCK_END].join('\n') + return [MARKERS.startMarker, ...entries, MARKERS.endMarker].join(eol) } -export function applyManagedKimiHooks(configText: string, command: string): string { - const withoutManaged = configText.replace(MANAGED_BLOCK_RE, '').replace(/\s+$/, '') - const block = buildManagedKimiHooksBlock(command) - return withoutManaged.length > 0 ? `${withoutManaged}\n\n${block}\n` : `${block}\n` +function detectEol(configText: string): string { + return configText.includes('\r\n') ? '\r\n' : '\n' } -export function removeManagedKimiHooks(configText: string): { text: string; changed: boolean } { - // Why: compare instead of MANAGED_BLOCK_RE.test() — the regex carries the `g` - // flag, so .test() advances lastIndex and would behave inconsistently across - // calls. .replace() ignores/resets lastIndex, so it is safe to reuse. - const stripped = configText.replace(MANAGED_BLOCK_RE, '') - if (stripped === configText) { +export function applyManagedKimiHooks( + configText: string, + command: string, + isManagedCommand: ManagedCommandMatcher +): string { + const eol = detectEol(configText) + const withoutManaged = stripManagedTomlRegions( + configText, + findOwnedRegions(configText, isManagedCommand) + ).text.replace(/\s+$/, '') + const block = buildManagedKimiHooksBlock(command, eol) + return withoutManaged.length > 0 + ? `${withoutManaged}${eol}${eol}${block}${eol}` + : `${block}${eol}` +} + +export function removeManagedKimiHooks( + configText: string, + isManagedCommand: ManagedCommandMatcher +): { text: string; changed: boolean } { + const stripped = stripManagedTomlRegions( + configText, + findOwnedRegions(configText, isManagedCommand) + ) + if (!stripped.changed) { return { text: configText, changed: false } } - const trimmed = stripped.replace(/\s+$/, '') - return { text: trimmed.length > 0 ? `${trimmed}\n` : '', changed: true } + const eol = detectEol(configText) + const trimmed = stripped.text.replace(/\s+$/, '') + return { text: trimmed.length > 0 ? `${trimmed}${eol}` : '', changed: true } } -// Returns the managed events present in the block whose command still matches an -// Orca-managed script (by filename, so a moved userData path is still swept). +// Events a managed table is live for, counted wherever the table sits (by script +// filename, so a moved userData path is still seen). Status must include tables +// stranded outside the markers — those still fire, so reporting them absent +// would tell the user a hook is uninstalled while Orca keeps receiving events. export function readManagedKimiHookEvents( configText: string, - isManagedCommand: (command: string | undefined) => boolean + isManagedCommand: ManagedCommandMatcher ): Set { - const present = new Set() - const match = configText.match(MANAGED_BLOCK_RE) - if (!match) { - return present - } - const blockText = match[0] - // Split on each table header and pair the `event`/`command` lines within. - for (const chunk of blockText.split('[[hooks]]').slice(1)) { - const event = chunk.match(/event\s*=\s*"([^"]+)"/)?.[1] - const command = chunk.match(/command\s*=\s*"((?:[^"\\]|\\.)*)"/)?.[1] - if (event && isManagedCommand(command)) { - present.add(event) + const events = new Set() + for (const table of recognizeManagedTables(configText, isManagedCommand)) { + if (table.value) { + events.add(table.value) } } - return present + return events } diff --git a/src/main/native-chat/agent-session-journal/journal-store.test.ts b/src/main/native-chat/agent-session-journal/journal-store.test.ts index 97eac02fe75..3592947faaa 100644 --- a/src/main/native-chat/agent-session-journal/journal-store.test.ts +++ b/src/main/native-chat/agent-session-journal/journal-store.test.ts @@ -8,6 +8,7 @@ import type { AgentSessionJournalIdentity } from '../../../shared/agent-session-journal-types' import { + agentJournalItemKey, boundJournalKeyComponent, MAX_JOURNAL_KEY_COMPONENT_CHARS } from '../../../shared/agent-session-journal-item-key' @@ -96,6 +97,21 @@ describe('sequences', () => { expect(journal.snapshot().items[0]?.revision).toBe(3) }) + it('visits reduced items at their creation sequence without promoting an older revision', async () => { + const journal = await open() + await journal.appendItem(item(0), body('first'), { fence: 1 }) + const latest = await journal.appendItem(item(1), body('second'), { fence: 1 }) + await journal.appendItem(item(0), body('first revised'), { fence: 1 }) + const visited: { itemId: string; sequence: number }[] = [] + + journal.visitItems((itemId, sequence) => visited.push({ itemId, sequence })) + + expect(visited).toEqual([ + { itemId: agentJournalItemKey(item(0)), sequence: 2 }, + { itemId: latest.itemId, sequence: latest.cursor.sequence } + ]) + }) + it('preserves an oversized identity and its raw digest-form mimic across reopen', async () => { const oversizedTurnId = 'a'.repeat(MAX_JOURNAL_KEY_COMPONENT_CHARS + 1) const digestFormMimic = boundJournalKeyComponent(oversizedTurnId) diff --git a/src/main/native-chat/agent-session-journal/journal-store.ts b/src/main/native-chat/agent-session-journal/journal-store.ts index 3be64d9ceca..2e372f9abae 100644 --- a/src/main/native-chat/agent-session-journal/journal-store.ts +++ b/src/main/native-chat/agent-session-journal/journal-store.ts @@ -162,6 +162,13 @@ export class AgentSessionJournal { snapshot = (): AgentJournalSnapshot => renderJournalState(this.state) + /** Visits reduced items without allocating and sorting a full snapshot. */ + visitItems = (visit: (itemId: string, sequence: number) => void): void => { + for (const item of this.state.items.values()) { + visit(item.itemId, item.sequence) + } + } + /** Includes revisions and completion tombstones, whose timestamps disappear from render items. */ lastActivityAt = (): number => this.state.lastActivityAt diff --git a/src/main/native-chat/agent-session-wire/provider-frame-disposition.ts b/src/main/native-chat/agent-session-wire/provider-frame-disposition.ts index d1bc7d0e7d3..548a719ceb1 100644 --- a/src/main/native-chat/agent-session-wire/provider-frame-disposition.ts +++ b/src/main/native-chat/agent-session-wire/provider-frame-disposition.ts @@ -25,8 +25,10 @@ export const PROVIDER_FRAME_CLASSIFICATIONS = { 'thread/closed': 'status-chrome', 'skills/changed': 'status-chrome', 'thread/name/updated': 'status-chrome', - 'thread/goal/updated': 'status-chrome', - 'thread/goal/cleared': 'status-chrome', + // The goal tool call is never emitted as an item, so these two frames are the only + // truthful evidence a goal exists; the model's prose about goals can be wrong. + 'thread/goal/updated': 'timeline-substantive', + 'thread/goal/cleared': 'timeline-substantive', 'thread/environment/connected': 'status-chrome', 'thread/environment/disconnected': 'status-chrome', 'thread/settings/updated': 'status-chrome', diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-event-sink-queue.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-event-sink-queue.ts index 510c1df2f4a..c9a32533db4 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-event-sink-queue.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-event-sink-queue.ts @@ -60,6 +60,8 @@ export class StructuredAgentSessionSinkQueue { failed: this.failure !== null }) + journalEpoch = (): string | null => this.target?.journal.epoch ?? null + bindReadingControl(control: StructuredAgentSessionReadingControl): () => void { this.readingControl = control if (this.backpressured) { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.test.ts index d1b7ea533a1..3d0a5e8a269 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.test.ts @@ -54,7 +54,8 @@ function target( appendLifecycleBatch: vi.fn(async (input: { settlementId: string }) => { log.push({ call: 'appendLifecycleBatch', fence, settlementId: input.settlementId }) return { epoch: 'e', sequence: 0 } - }) + }), + latestItemMatching: vi.fn(() => null) } as unknown as AgentSessionJournal return { journal, @@ -115,6 +116,25 @@ describe('deferred structured agent-session event sink', () => { expect(log).toEqual([{ call: 'appendItem', fence: 2, ordinal: 0 }]) }) + it('resolves a lifecycle transition after journal bind and skips an existing state', async () => { + const log: Recorded[] = [] + const deferred = createDeferredStructuredAgentSessionEventSink() + + expect( + deferred.sink.tryAppendLifecycleTransition?.(identity(0), BODY, () => identity(1)) + ).toEqual({ accepted: true }) + expect(deferred.sink.tryAppendLifecycleTransition?.(identity(0), BODY, () => null)).toEqual({ + accepted: true + }) + deferred.bind(target(2, log)) + await deferred.drained() + + expect(log).toEqual([ + { call: 'appendItem', fence: 2, ordinal: 1 }, + { call: 'publish', fence: 2 } + ]) + }) + it('drops buffered and later writes once closed, and refuses to rebind', async () => { const log: Recorded[] = [] const deferred = createDeferredStructuredAgentSessionEventSink() diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts index 784e3aa7b20..857aa118fe8 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts @@ -31,6 +31,15 @@ export type StructuredAgentSessionAppendOptions = { observedAt?: number } +export type StructuredAgentSessionLifecycleJournal = Pick< + AgentSessionJournal, + 'epoch' | 'visitItems' +> + +export type StructuredAgentSessionLifecycleIdentityResolver = ( + journal: StructuredAgentSessionLifecycleJournal +) => AgentJournalItemIdentity | null + export type StructuredAgentSessionEventSink = { appendItem( identity: AgentJournalItemIdentity, @@ -52,6 +61,14 @@ export type StructuredAgentSessionEventSink = { body: AgentJournalItemBody, options?: StructuredAgentSessionAppendOptions ): StructuredAgentSessionSinkAdmission + /** Queues one journal-derived lifecycle append; a null resolution is a no-op. */ + tryAppendLifecycleTransition?( + identitySizeBound: AgentJournalItemIdentity, + body: AgentJournalItemBody, + resolveIdentity: StructuredAgentSessionLifecycleIdentityResolver + ): StructuredAgentSessionSinkAdmission + /** Current durable epoch, when this deferred sink is bound to its journal. */ + journalEpoch?(): string | null appendLifecycleBatch?( settlementId: string, mutations: readonly JournalLifecycleMutationInput[], @@ -186,6 +203,28 @@ export function createDeferredStructuredAgentSessionEventSink( }, options ), + tryAppendLifecycleTransition: (identitySizeBound, body, resolveIdentity) => { + const bytes = estimateStructuredAgentSessionItemBytes(identitySizeBound, body) + return queue.submit( + { + bytes, + lifecycle: true, + run: async (bound) => { + const identity = resolveIdentity(bound.journal) + if (identity === null) { + return + } + if (estimateStructuredAgentSessionItemBytes(identity, body) > bytes) { + throw new Error('structured agent-session item identity exceeded its reserved size') + } + await bound.journal.appendItem(identity, body, { fence: bound.fence }) + bound.publish() + } + }, + { lifecycle: true } + ) + }, + journalEpoch: queue.journalEpoch, appendLifecycleBatch: (settlementId, mutations, options = {}) => { const admission = appendLifecycleBatch(settlementId, mutations, options) if (!admission.accepted) { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-mutation-admission.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-mutation-admission.ts index ac6dc23385a..4d0e0faab30 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-mutation-admission.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-mutation-admission.ts @@ -13,6 +13,7 @@ import type { AgentSessionMutationResult, AgentSessionWireRefusal } from '../../../shared/agent-session-wire' +import { AGENT_SESSION_UNATTACHED_REFUSAL_CODE } from '../../../shared/structured-agent-session-read-refusal' import type { AgentSessionRecordStore } from '../../runtime/agent-session-record-store' import type { AgentSessionJournal } from '../agent-session-journal/journal-store' import type { StructuredAgentSessionAdapter } from './structured-agent-session-adapter' @@ -21,8 +22,10 @@ import { runSettledAgentSessionMutation } from './structured-agent-session-opera import { resolveAgentSessionReplayOutcome } from './structured-agent-session-replay-outcome' import type { AgentSessionTurnContext } from './structured-agent-session-turns' +// The code is shared with the client so a read that refuses this way can be told apart from a +// transcript that failed to load; the two must never drift apart. export const AGENT_SESSION_NOT_ATTACHED: AgentSessionWireRefusal = { - code: 'agent_session_ownership_unknown', + code: AGENT_SESSION_UNATTACHED_REFUSAL_CODE, message: 'This host holds no attached session by that id.' } diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-rewind.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-rewind.test.ts index c75301c6461..e022f640403 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-rewind.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-rewind.test.ts @@ -420,7 +420,7 @@ describe('host rewind', () => { expect(await host.rewind(caller, params(target))).toMatchObject({ ok: true }) }) - it('keeps the host-stamped turn rows before the boundary through a Codex provider hydration', async () => { + it('keeps host-stamped turn and goal rows through a Codex provider hydration', async () => { expect(await host.attach(caller, hostTestAttachParams(null))).toMatchObject({ ok: true }) const message = (turnId: string) => ({ provider: 'codex' as const, @@ -434,6 +434,19 @@ describe('host rewind', () => { sessionId: HOST_TEST_SESSION, recordId: `turn-lifecycle:${turnId}` }) + const goalRow = { + provider: 'orca' as const, + clientMessageId: `codex-goal:${'a'.repeat(64)}:${'b'.repeat(64)}:${'c'.repeat(64)}` + } + const goalBody = { + kind: 'status' as const, + text: 'Goal set: Keep the retained evidence.', + providerFrame: { + provider: 'codex', + kind: 'notification:thread/goal/updated', + payload: { head: '{}', byteLength: 2, digest: 'd'.repeat(64), truncated: false } + } + } const keptTurn = { kind: 'turn' as const, turnId: 'kept', @@ -444,6 +457,7 @@ describe('host rewind', () => { durationMs: 5_000 } sink.appendItem(message('kept'), hostTestMessage('kept')) + sink.appendItem(goalRow, goalBody) sink.appendItem(turnRow('kept'), keptTurn) sink.appendItem(message('drop'), hostTestMessage('drop')) sink.appendItem(turnRow('drop'), { ...keptTurn, turnId: 'drop', durationMs: 1_000 }) @@ -465,11 +479,66 @@ describe('host rewind', () => { host.journalSnapshot(HOST_TEST_SESSION).items.map(({ itemId, body }) => ({ itemId, body })) ).toEqual([ { itemId: agentJournalItemKey(message('kept')), body: hostTestMessage('kept from provider') }, + { itemId: agentJournalItemKey(goalRow), body: goalBody }, { itemId: agentJournalItemKey(turnRow('kept')), body: keptTurn } ]) expect(store.getRecord(HOST_TEST_SESSION)?.rewind?.phase).toBe('completed') }) + it('keeps a host goal row when interrupted Codex rewind recovery rebuilds provider history', async () => { + expect(await host.attach(caller, hostTestAttachParams(null))).toMatchObject({ ok: true }) + const message = (turnId: string) => ({ + provider: 'codex' as const, + threadId: HOST_TEST_THREAD, + turnId, + ordinal: 0 + }) + const goalRow = { + provider: 'orca' as const, + clientMessageId: `codex-goal:${'1'.repeat(64)}:${'2'.repeat(64)}:${'3'.repeat(64)}` + } + const goalBody = { + kind: 'status' as const, + text: 'Goal set: Survive recovery.', + providerFrame: { + provider: 'codex', + kind: 'notification:thread/goal/updated', + payload: { head: '{}', byteLength: 2, digest: '4'.repeat(64), truncated: false } + } + } + sink.appendItem(message('kept'), hostTestMessage('kept')) + sink.appendItem(goalRow, goalBody) + sink.appendItem(message('drop'), hostTestMessage('drop')) + sink.appendItem(message('tip'), { ...hostTestMessage('tip'), role: 'assistant' }) + await host.flushStreamedEvents(HOST_TEST_SESSION) + rewind.mockImplementationOnce(async (input) => { + await input.onReverted?.() + throw new Error('lost after provider revert') + }) + + await expect(host.rewind(caller, params(agentJournalItemKey(message('drop'))))).rejects.toThrow( + 'lost after provider revert' + ) + recoverRewind.mockResolvedValueOnce({ + ok: true, + items: [{ identity: message('kept'), body: hostTestMessage('kept from recovery') }] + }) + expect( + await host.attach( + caller, + hostTestAttachParams(store.getRecord(HOST_TEST_SESSION)!.lease.runtimeFence) + ) + ).toMatchObject({ ok: true }) + + expect( + host.journalSnapshot(HOST_TEST_SESSION).items.map(({ itemId, body }) => ({ itemId, body })) + ).toEqual([ + { itemId: agentJournalItemKey(message('kept')), body: hostTestMessage('kept from recovery') }, + { itemId: agentJournalItemKey(goalRow), body: goalBody } + ]) + expect(store.getRecord(HOST_TEST_SESSION)?.rewind?.phase).toBe('completed') + }) + it('recovers against the complete provider preflight when the local journal omitted an older turn', async () => { const target = await seed() const items = ['older', 'kept'].map((turnId) => ({ diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-rewind.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-rewind.ts index 417a42fe414..cb7cbb1f20b 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-rewind.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-rewind.ts @@ -20,7 +20,7 @@ import { conversationCommandBlocked } from './structured-conversation-command-ad import { rewindRefusal } from './structured-rewind-refusal' import { persistRewindRecord, recoverStructuredRewind } from './structured-rewind-recovery' import { replaceClaudeRewindOwner } from './structured-rewind-claude-owner' -import { mergeRetainedTurnRows } from './structured-rewind-retained-turns' +import { mergeRetainedHostLifecycleRows } from './structured-rewind-retained-host-rows' export async function rewindStructuredAgentSession( context: StructuredAgentSessionMutationContext, @@ -174,7 +174,7 @@ export async function rewindStructuredAgentSession( fence: ctx.fence, beforeTurnId: key.provider === 'codex' ? key.turnId : '', onPrepared: async (items) => { - const retained = mergeRetainedTurnRows( + const retained = mergeRetainedHostLifecycleRows( prepared.retained, items.map(({ identity, body }) => ({ itemId: agentJournalItemKey(identity), @@ -220,7 +220,7 @@ export async function rewindStructuredAgentSession( return rewindRefusal(reason) } const confirmed = provider.items - ? mergeRetainedTurnRows( + ? mergeRetainedHostLifecycleRows( prepared.retained, provider.items.map(({ identity, body }) => ({ itemId: agentJournalItemKey(identity), diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-surface-lifetime.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-surface-lifetime.test.ts index 1cb8439c391..678b790ed4e 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-surface-lifetime.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-surface-lifetime.test.ts @@ -14,6 +14,7 @@ import type { AgentSessionMutationEnvelope, AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' +import { AGENT_SESSION_UNATTACHED_REFUSAL_CODE } from '../../../shared/structured-agent-session-read-refusal' import { AgentSessionRecordStore } from '../../runtime/agent-session-record-store' import type { StructuredAgentSessionAdapter } from './structured-agent-session-adapter' import type { StructuredAgentSessionEventSink } from './structured-agent-session-event-sink' @@ -180,6 +181,25 @@ describe('a chat that closes', () => { expect(host.hasSession(SESSION)).toBe(true) }) + // The pane outlives the close by a few frames — a workspace delete closes the chats inside it + // while their panes are still mounted — so whatever a read raises in that window is what the user + // sees. This is the code the client narrows on to keep that window off the pane; a host that + // starts raising a different one there puts the red error back. + it('answers a read from the pane that outlived it with the code the client treats as transitional', async () => { + await attach() + await host.hold(SESSION, SURFACE) + + await host.close(SESSION) + + expect(host.hasSession(SESSION)).toBe(false) + expect(() => host.history({ sessionId: SESSION, direction: 'tail' })).toThrow( + AGENT_SESSION_UNATTACHED_REFUSAL_CODE + ) + expect(() => + host.subscribe({ id: 'sub-1', sessionId: SESSION, emit: () => undefined }) + ).toThrow(AGENT_SESSION_UNATTACHED_REFUSAL_CODE) + }) + it('does not lose the session to a release the client sent twice', async () => { await attach() await host.hold(SESSION, SURFACE) diff --git a/src/main/native-chat/agent-session-wire/structured-rewind-recovery.ts b/src/main/native-chat/agent-session-wire/structured-rewind-recovery.ts index 8f5a8942a86..4916710e9c1 100644 --- a/src/main/native-chat/agent-session-wire/structured-rewind-recovery.ts +++ b/src/main/native-chat/agent-session-wire/structured-rewind-recovery.ts @@ -1,5 +1,5 @@ import { restoreRewindJournalBody } from './structured-rewind-journal-body' -import { isRetainedTurnRow, mergeRetainedTurnRows } from './structured-rewind-retained-turns' +import { mergeRetainedHostLifecycleRows } from './structured-rewind-retained-host-rows' import { isDeepStrictEqual } from 'node:util' import { agentJournalItemKey, @@ -61,9 +61,13 @@ export async function recoverStructuredRewind( } throw new Error(`agent_session_rewind:${recovered?.reason ?? 'outcome-unknown'}`) } - // Turn rows are the host's, never the provider's; the proof covers provider items only. const expectedItems = new Set( - rewind.retained.filter((item) => !isRetainedTurnRow(item)).map((item) => item.itemId) + rewind.retained + .filter((item) => { + const identity = parseAgentJournalItemKey(item.itemId) + return identity?.provider === 'codex' && identity.threadId === target.threadId + }) + .map((item) => item.itemId) ) const observedItems = new Set() for (const { identity } of recovered.items) { @@ -80,7 +84,7 @@ export async function recoverStructuredRewind( if (observedItems.size !== expectedItems.size) { throw new Error('agent_session_rewind:proof-mismatch') } - const retained = mergeRetainedTurnRows( + const retained = mergeRetainedHostLifecycleRows( rewind.retained, recovered.items.map(({ identity, body }) => ({ itemId: agentJournalItemKey(identity), diff --git a/src/main/native-chat/agent-session-wire/structured-rewind-retained-turns.ts b/src/main/native-chat/agent-session-wire/structured-rewind-retained-host-rows.ts similarity index 57% rename from src/main/native-chat/agent-session-wire/structured-rewind-retained-turns.ts rename to src/main/native-chat/agent-session-wire/structured-rewind-retained-host-rows.ts index aa0753b502c..35307566599 100644 --- a/src/main/native-chat/agent-session-wire/structured-rewind-retained-turns.ts +++ b/src/main/native-chat/agent-session-wire/structured-rewind-retained-host-rows.ts @@ -1,20 +1,23 @@ -// The Codex preflight returns provider items only. The host's turn rows are its own record, so a -// rewind that takes the provider's list as the new epoch would drop every duration before the -// boundary unless those rows are spliced back beside the item each one followed. +// Provider preflight returns provider items only. The host's lifecycle rows are its own record, so +// a rewind that takes the provider list as the new epoch must splice those rows back beside the +// provider item each one followed. +import { parseCodexGoalJournalItemId } from '../../codex/codex-goal-journal-identity' import type { AgentJournalItemBody } from '../../../shared/agent-session-journal-types' import type { AgentSessionRewindRecord } from '../../../shared/agent-session-rewind' import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' type RetainedRow = AgentSessionRewindRecord['retained'][number] -export function isRetainedTurnRow(item: Pick): boolean { - return readAgentJournalTurn(item.body as AgentJournalItemBody) !== null +export function isRetainedHostLifecycleRow(item: RetainedRow): boolean { + return ( + readAgentJournalTurn(item.body as AgentJournalItemBody) !== null || + parseCodexGoalJournalItemId(item.itemId) !== null + ) } -/** `reference` fixes where each turn row sits; the provider items are the spine and keep their - * own order, including turns the local journal never saw. */ -export function mergeRetainedTurnRows( +/** `reference` fixes where each host row sits; provider items are the ordered spine. */ +export function mergeRetainedHostLifecycleRows( reference: readonly RetainedRow[], providerItems: readonly RetainedRow[] ): RetainedRow[] { @@ -22,7 +25,7 @@ export function mergeRetainedTurnRows( const rowsAfter = new Map() let anchor = -1 for (const item of reference) { - if (!isRetainedTurnRow(item)) { + if (!isRetainedHostLifecycleRow(item)) { anchor = spineIndex.get(item.itemId) ?? anchor } else if (!spineIndex.has(item.itemId)) { rowsAfter.set(anchor, [...(rowsAfter.get(anchor) ?? []), item]) diff --git a/src/main/native-chat/agent-session-wire/unhandled-provider-frame.test.ts b/src/main/native-chat/agent-session-wire/unhandled-provider-frame.test.ts index 61544fd56ab..aefceacbca4 100644 --- a/src/main/native-chat/agent-session-wire/unhandled-provider-frame.test.ts +++ b/src/main/native-chat/agent-session-wire/unhandled-provider-frame.test.ts @@ -50,9 +50,6 @@ describe('unhandled provider frame journal fallback', () => { expect( unhandledProviderFrameJournalItem('codex', 'notification:thread/tokenUsage/updated', {}) ).toBeNull() - expect( - unhandledProviderFrameJournalItem('codex', 'notification:thread/goal/cleared', {}) - ).toBeNull() expect(unhandledProviderFrameJournalItem('claude', 'message:system:init', {})).toBeNull() expect( unhandledProviderFrameJournalItem('claude', 'message:result', { diff --git a/src/main/native-chat/agent-session-wire/unhandled-provider-frame.ts b/src/main/native-chat/agent-session-wire/unhandled-provider-frame.ts index 272e960b838..22ca3d89542 100644 --- a/src/main/native-chat/agent-session-wire/unhandled-provider-frame.ts +++ b/src/main/native-chat/agent-session-wire/unhandled-provider-frame.ts @@ -5,6 +5,7 @@ import { DEFAULT_JOURNAL_PAYLOAD_LIMITS, type JournalPayloadLimits } from '../agent-session-journal/journal-payload-bounds' +import { codexGoalRowText } from '../../codex/codex-goal-journal-rows' import { classifyProviderFrame } from './provider-frame-disposition' export type UnhandledProviderFrameJournalItem = { @@ -115,11 +116,15 @@ export function unhandledProviderFrameJournalItem( .filter((part): part is string => typeof part === 'string' && part.trim().length > 0) .join('\n\n') || message } + const goalText = provider === 'codex' ? codexGoalRowText(method, payload) : null const display = message ? boundInlineText(message, limits) : null + const goalDisplay = goalText ? boundInlineText(goalText, limits) : null return { body: { kind: 'status', - text: compaction ? 'Context compacted' : (display?.text ?? `${provider} · ${kind}`), + text: compaction + ? 'Context compacted' + : (goalDisplay?.text ?? display?.text ?? `${provider} · ${kind}`), ...(compaction ? { presentation: 'compaction' } : {}), ...(tone ? { tone } : {}), providerFrame: { provider, kind, payload: bounded } diff --git a/src/main/native-chat/transcript-line-decoders-codex.ts b/src/main/native-chat/transcript-line-decoders-codex.ts index 229ace2a461..ddc748dde03 100644 --- a/src/main/native-chat/transcript-line-decoders-codex.ts +++ b/src/main/native-chat/transcript-line-decoders-codex.ts @@ -92,10 +92,13 @@ function codexResponseItem( payload.type === 'custom_tool_call' ) { const name = extractString(payload.name) ?? 'tool' + const callId = extractString(payload.call_id) return { id, role: 'assistant', - blocks: [{ type: 'tool-call', name, input: codexCallInput(payload) }], + blocks: [ + { type: 'tool-call', name, input: codexCallInput(payload), ...(callId ? { callId } : {}) } + ], timestamp, source: 'transcript' } diff --git a/src/main/native-chat/transcript-reader-codex-history-mode.test.ts b/src/main/native-chat/transcript-reader-codex-history-mode.test.ts index 5d18bec8c85..9a9b2b76094 100644 --- a/src/main/native-chat/transcript-reader-codex-history-mode.test.ts +++ b/src/main/native-chat/transcript-reader-codex-history-mode.test.ts @@ -240,7 +240,7 @@ describe('Codex transcript history modes', () => { expect(call).toMatchObject({ id: 'call-1', role: 'assistant', - blocks: [{ type: 'tool-call', name: 'exec', input: 'pwd' }] + blocks: [{ type: 'tool-call', name: 'exec', input: 'pwd', callId: 'durable-call-1' }] }) expect(output).toMatchObject({ id: 'fallback-output', diff --git a/src/main/native-chat/transcript-reader.test.ts b/src/main/native-chat/transcript-reader.test.ts index ff48548804d..eb333cd8fda 100644 --- a/src/main/native-chat/transcript-reader.test.ts +++ b/src/main/native-chat/transcript-reader.test.ts @@ -67,7 +67,7 @@ describe('readNativeChatTranscript (claude)', () => { timestamp: '2026-06-01T10:05:00.000Z', message: { role: 'assistant', - content: [{ type: 'tool_use', name: 'Bash', input: { command: 'ls' } }] + content: [{ type: 'tool_use', id: 'tool-call-1', name: 'Bash', input: { command: 'ls' } }] } }) records.push({ @@ -98,7 +98,8 @@ describe('readNativeChatTranscript (claude)', () => { expect(toolCall?.blocks[0]).toEqual({ type: 'tool-call', name: 'Bash', - input: { command: 'ls' } + input: { command: 'ls' }, + callId: 'tool-call-1' }) const toolResult = result.messages.at(-1) diff --git a/src/main/native-chat/transcript-record-blocks.ts b/src/main/native-chat/transcript-record-blocks.ts index 6355df277e5..b82ff9672ca 100644 --- a/src/main/native-chat/transcript-record-blocks.ts +++ b/src/main/native-chat/transcript-record-blocks.ts @@ -81,7 +81,8 @@ function claudeContentBlock(record: Record): NativeChatBlock | } case 'tool_use': { const name = extractString(record.name) ?? 'tool' - return { type: 'tool-call', name, input: record.input } + const callId = extractString(record.id) + return { type: 'tool-call', name, input: record.input, ...(callId ? { callId } : {}) } } case 'tool_result': return toolResultBlock(record) diff --git a/src/main/notifications/desktop-away-state.test.ts b/src/main/notifications/desktop-away-state.test.ts new file mode 100644 index 00000000000..702539d6447 --- /dev/null +++ b/src/main/notifications/desktop-away-state.test.ts @@ -0,0 +1,25 @@ +import { expect, it } from 'vitest' +import { readDesktopAwayState } from './desktop-away-state' + +it.each([ + [179, false], + [180, true], + [181, true] +])('checks the three-minute boundary at %s seconds', (idle, away) => { + expect( + readDesktopAwayState({ getSystemIdleState: () => 'active', getSystemIdleTime: () => idle }) + ).toBe(away) +}) +it('allows immediate delivery when locked and fails open when presence cannot be read', () => { + expect( + readDesktopAwayState({ getSystemIdleState: () => 'locked', getSystemIdleTime: () => 0 }) + ).toBe(true) + expect( + readDesktopAwayState({ + getSystemIdleState: () => { + throw new Error('unsupported') + }, + getSystemIdleTime: () => 0 + }) + ).toBeUndefined() +}) diff --git a/src/main/notifications/desktop-away-state.ts b/src/main/notifications/desktop-away-state.ts new file mode 100644 index 00000000000..ccfbaeb5760 --- /dev/null +++ b/src/main/notifications/desktop-away-state.ts @@ -0,0 +1,20 @@ +export const MOBILE_NOTIFICATION_AWAY_SECONDS = 180 + +type IdleMonitor = { + getSystemIdleState(threshold: number): string + getSystemIdleTime(): number +} + +export function readDesktopAwayState(monitor: IdleMonitor): boolean | undefined { + try { + const state = monitor.getSystemIdleState(MOBILE_NOTIFICATION_AWAY_SECONDS) + if (state === 'locked' || state === 'idle') { + return true + } + const idle = monitor.getSystemIdleTime() + return Number.isFinite(idle) && idle >= 0 ? idle >= MOBILE_NOTIFICATION_AWAY_SECONDS : undefined + } catch { + // Unknown presence must not silence a phone. + return undefined + } +} diff --git a/src/main/orca-profiles/profile-cloud-auth-config.ts b/src/main/orca-profiles/profile-cloud-auth-config.ts index 09cfd8dfc6b..4e0e75bdd8e 100644 --- a/src/main/orca-profiles/profile-cloud-auth-config.ts +++ b/src/main/orca-profiles/profile-cloud-auth-config.ts @@ -1,4 +1,9 @@ import { app } from 'electron' +import { + cleanCloudServiceUrl as cleanUrl, + cleanCloudServiceOrigin as cleanOrigin +} from '../../shared/cloud-service-url' +import { resolvePushGatewayOrigin } from '../runtime/push/push-gateway-origin' export type OrcaCloudAuthConfig = { apiBaseUrl: string @@ -30,39 +35,10 @@ function isPackagedOrcaBuild(): boolean { } } -function cleanUrl(value: string | undefined, allowLoopbackHttp: boolean): string | null { - const trimmed = value?.trim() - if (!trimmed) { - return null - } - try { - const parsed = new URL(trimmed) - const loopbackHost = - parsed.hostname === '127.0.0.1' || - parsed.hostname === 'localhost' || - parsed.hostname === '[::1]' - if (parsed.protocol !== 'https:' && !(loopbackHost && allowLoopbackHttp)) { - return null - } - return parsed.toString().replace(/\/$/, '') - } catch { - return null - } -} - function endpoint(baseUrl: string, path: string): string { return new URL(path, `${baseUrl}/`).toString() } -function cleanOrigin(value: string | undefined, allowLoopbackHttp: boolean): string | null { - const cleaned = cleanUrl(value, allowLoopbackHttp) - if (!cleaned) { - return null - } - const parsed = new URL(cleaned) - return parsed.pathname === '/' && !parsed.search && !parsed.hash ? parsed.origin : null -} - export function getOrcaCloudAuthConfig( env: NodeJS.ProcessEnv = process.env, packaged: boolean = isPackagedOrcaBuild() @@ -124,6 +100,18 @@ export function getOrcaCloudAuthConfig( } } +/** + * Where the host registers phones for background push. Deliberately outside + * OrcaCloudAuthConfig: the push gateway authenticates with the host keypair, so an + * accountless host reaches it on exactly the same path as a signed-in one. + */ +export function getOrcaPushGatewayUrl( + env: NodeJS.ProcessEnv = process.env, + packaged: boolean = isPackagedOrcaBuild() +): string { + return resolvePushGatewayOrigin(env, packaged) +} + export function allowsPlaintextOrcaCloudSession( env: NodeJS.ProcessEnv = process.env, packaged: boolean = isPackagedOrcaBuild() diff --git a/src/main/orca-profiles/profile-cloud-auth-status.test.ts b/src/main/orca-profiles/profile-cloud-auth-status.test.ts new file mode 100644 index 00000000000..7a28783e9a9 --- /dev/null +++ b/src/main/orca-profiles/profile-cloud-auth-status.test.ts @@ -0,0 +1,106 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { ActiveOrcaProfileState } from './profile-index-store' +import type { OrcaCloudSessionReadResult } from './profile-cloud-session-store' +import { getOrcaProfileAuthStatusFromProfile } from './profile-cloud-auth-status' + +const { readSession, configuration } = vi.hoisted(() => ({ + readSession: vi.fn<() => OrcaCloudSessionReadResult>(), + configuration: { configured: true } +})) + +vi.mock('./profile-cloud-session-store', () => ({ readOrcaCloudSession: readSession })) +vi.mock('./profile-cloud-auth-config', () => ({ + getOrcaCloudAuthConfig: () => configuration, + isOrcaCloudDevAuthEnabled: () => false +})) + +function activeProfile(linked: boolean): ActiveOrcaProfileState { + const profile: ActiveOrcaProfileState['profile'] = { + id: 'profile-1', + name: 'Personal', + avatar: { kind: 'initials', initials: 'P', color: 'neutral' }, + kind: linked ? 'cloud-linked' : 'local', + createdAt: 0, + updatedAt: 0, + lastOpenedAt: 0, + ...(linked + ? { + cloud: { + cloudProfileId: 'cloud-1', + userId: 'user-1', + email: 'a@example.com', + linkedAt: 0 + } + } + : {}) + } + return { + profile, + index: { schemaVersion: 1, activeProfileId: profile.id, profiles: [profile] }, + dataFile: '', + profileDirectory: '' + } +} + +const absentSessions: OrcaCloudSessionReadResult[] = [ + { status: 'missing', persistence: 'none' }, + { status: 'decrypt-failed', persistence: 'none', error: 'Cannot decrypt' }, + { status: 'unreadable', persistence: 'none', error: 'Permission denied' } +] + +describe('unexpected sign-out auth evidence', () => { + beforeEach(() => { + readSession.mockReset() + configuration.configured = true + }) + + it.each(absentSessions)('requires a preserved cloud link for $status credentials', (session) => { + readSession.mockReturnValue(session) + const linked = activeProfile(true) + expect(getOrcaProfileAuthStatusFromProfile(linked, '')).toMatchObject({ + state: 'reconnect-required', + cloud: linked.profile.cloud, + persistence: 'none', + credentialError: 'error' in session ? session.error : undefined + }) + readSession.mockClear() + const signedOut = getOrcaProfileAuthStatusFromProfile(activeProfile(false), '') + expect(signedOut.state).toBe('local') + expect(signedOut.cloud).toBeUndefined() + expect(readSession).not.toHaveBeenCalled() + }) + + it.each(absentSessions)( + 'keeps unconfigured linked profiles out of reconnect for $status', + (session) => { + configuration.configured = false + readSession.mockReturnValue(session) + expect(getOrcaProfileAuthStatusFromProfile(activeProfile(true), '').state).toBe( + 'unconfigured' + ) + expect(getOrcaProfileAuthStatusFromProfile(activeProfile(false), '').state).toBe( + 'unconfigured' + ) + } + ) + + it('treats a live memory-only session as connected, then reconnects after its loss', () => { + readSession.mockReturnValue({ + status: 'found', + persistence: 'memory-only', + session: { + accessToken: 'access', + refreshToken: 'refresh', + expiresAt: Date.now() + 60_000, + capabilities: { flags: {}, refreshedAt: 0 } + } + }) + const linked = activeProfile(true) + expect(getOrcaProfileAuthStatusFromProfile(linked, '')).toMatchObject({ + state: 'connected', + persistence: 'memory-only' + }) + readSession.mockReturnValue({ status: 'missing', persistence: 'none' }) + expect(getOrcaProfileAuthStatusFromProfile(linked, '').state).toBe('reconnect-required') + }) +}) diff --git a/src/main/orcad/orcad-entry.ts b/src/main/orcad/orcad-entry.ts index 65d1b712051..137894f87b8 100644 --- a/src/main/orcad/orcad-entry.ts +++ b/src/main/orcad/orcad-entry.ts @@ -5,7 +5,7 @@ * desktop uses, installs a PTY controller via `registerHeadlessPtyRuntime`, and * serves runtime RPC. See docs/design/node-only-runtime-backend.html. * - * Desktop UI surfaces stay uninstalled: no notifications, no renderer window. The + * Desktop UI surfaces stay uninstalled: no native notifications, no renderer window. The * renderer window is faked as a destroyed one because `registerPtyHandlers` takes a * non-null `BrowserWindow`. Browser automation is different — it is installed through * the runtime factory, but only when an Electron serve sidecar or an operator-supplied @@ -16,18 +16,15 @@ import { setAppEnvironment, type AppEnvironment } from '../../shared/app-environ import { setSecretStore, type SecretStore } from '../../shared/secret-store' import type { ServeReadiness } from '../server/serve-readiness' import { setRuntimeBrowserCommandsFactory } from '../runtime/runtime-browser-commands-factory' -import { resolveOrcadBrowserProvider, type OrcadBrowserProvider } from './orcad-browser-provider' +import { resolveOrcadBrowserProvider } from './orcad-browser-provider' import { resolveOrcadInstallRoot, resolveOrcadPath, resolveUserDataPath } from './orcad-app-paths' import { describeOrcadBindExposure, OrcadBindAddressError, resolveOrcadBindHost } from './orcad-bind-address' -import { - acquireOrcadInstanceLock, - OrcadInstanceLockError, - type OrcadInstanceLock -} from './orcad-instance-lock' +import { acquireOrcadInstanceLock, OrcadInstanceLockError } from './orcad-instance-lock' +import { startOrcadWithLifecycle } from './orcad-lifecycle' let runOrcadQuitHandlers = (): void => {} @@ -116,22 +113,24 @@ export async function startOrcad(options: OrcadOptions = {}): Promise browserProvider.isAvailable() } : {}) }) - try { - return await startOrcadRuntime(options, browserProvider, instanceLock) - } catch (error) { - await browserProvider?.stop() - setRuntimeBrowserCommandsFactory(null) - runOrcadQuitHandlers() - instanceLock.release() - throw error - } + return startOrcadWithLifecycle( + (registerCleanup) => startOrcadRuntime(options, registerCleanup), + async () => { + try { + await browserProvider?.stop() + } finally { + setRuntimeBrowserCommandsFactory(null) + runOrcadQuitHandlers() + instanceLock.release() + } + } + ) } async function startOrcadRuntime( options: OrcadOptions, - browserProvider: OrcadBrowserProvider | null, - instanceLock: OrcadInstanceLock -): Promise { + registerCleanup: (cleanup: () => Promise) => void +): Promise> { const { OrcaRuntimeService } = await import('../runtime/orca-runtime') const { OrcaRuntimeRpcServer } = await import('../runtime/runtime-rpc') const { registerHeadlessPtyRuntime, getLocalPtyProvider, getSshPtyProvider } = @@ -146,13 +145,41 @@ async function startOrcadRuntime( const { startOrcadDaemon, stopOrcadDaemon } = await import('./orcad-daemon-supervision') const { daemonOwnsFreshPersistentPtys } = await import('../daemon/daemon-init') const { collectOrcadHealth } = await import('./orcad-health') - // Why importable here: the store is an in-memory singleton whose module tree never reaches - // Electron, and its file paths come from `start()`, which orcad never calls. + // Why importable here: the singleton's module tree never reaches Electron, and orcad supplies + // its persistence and endpoint paths explicitly below. const { agentHookServer } = await import('../agent-hooks/server') + const { isAgentStatusHooksEnabled } = await import('../agent-hooks/managed-agent-hook-controls') + const { installHookStatusSessionTabsRepublish } = + await import('../agent-hooks/hook-status-session-tabs-republish') + const { AgentStatusObservedPaneIdentities, AgentStatusObservedPaneIdentityCapture } = + await import('../runtime/agent-status-observed-pane-identity') + + let rpc: InstanceType | null = null + let uninstallHookStatusRepublish = (): void => {} + let uninstallObservedStatusIdentity = (): void => {} + registerCleanup(async () => { + try { + await rpc?.stop() + } finally { + try { + // Why disconnect and not shut down: the daemon must outlive this process, or an + // orcad restart goes back to killing every running terminal. + await stopOrcadDaemon() + } finally { + uninstallObservedStatusIdentity() + uninstallHookStatusRepublish() + agentHookServer.stop() + } + } + }) + const { DesktopPushService } = await import('../runtime/push/desktop-push-service') + const { resolvePushGatewayOrigin } = await import('../runtime/push/push-gateway-origin') const runtimeUserDataPath = getAppEnvironment().getPath('userData') initOrcaProfilePaths() const profile = ensureActiveOrcaProfile(runtimeUserDataPath) + const observedPaneIdentities = new AgentStatusObservedPaneIdentities() + const observedStatusCapture = new AgentStatusObservedPaneIdentityCapture(observedPaneIdentities) // Why a real Store: without one every persistence-backed RPC throws `runtime_unavailable` // and the read paths that use `this.store?.x ?? []` quietly answer "empty" instead — // a server that pairs and lists nothing looks healthy and is not. @@ -163,6 +190,13 @@ async function startOrcadRuntime( // which is safe but silently discards accept records on every launch. initSshHostKeyStoreFile(profile.dataFile) + uninstallObservedStatusIdentity = agentHookServer.subscribeEnrichedStatus((enriched) => + observedStatusCapture.observe(enriched) + ) + if (isAgentStatusHooksEnabled(store.getSettings())) { + await agentHookServer.start({ env: 'production', userDataPath: runtimeUserDataPath }) + } + // Why before the runtime and the PTY handlers: `setLocalPtyProvider` installs the daemon // adapter as THE local provider, and the registry's contract is that it lands before // registerPtyHandlers so the IPC layer routes through the daemon from the first call. @@ -184,16 +218,37 @@ async function startOrcadRuntime( // what powers serve→desktop promotion. A Node host can never do that, and the // constructor's default would advertise it. getDesktopWindowStatus: () => 'blocked', + // Why here too and not only on the desktop: main's OSC parse is the only producer for a + // PTY agent on this host, and the store is the only place `worktree.ps` and the mobile + // projection read from — unwired, orcad lists no PTY agents at all. + onTerminalAgentStatus: (event) => agentHookServer.ingestTerminalStatus(event), // Why here too and not only on the desktop: orcad serves `worktree.ps` and `agentSession.*`, // so without these a headless host publishes its structured chats nowhere and lists no agents. getAgentStatusSnapshot: () => agentHookServer.getStatusSnapshot().filter((entry) => entry.providerSessionOnly !== true), + getAgentProviderSessionSnapshot: () => agentHookServer.getStatusSnapshot(), + getAgentProviderSessionRowsForPane: (paneKey) => + agentHookServer.getStatusSnapshotForPane(paneKey), + // Why captured rather than resolved at read: the fleet snapshot remints cached rows on every + // read, so a row observed under one process otherwise acquires whatever process owns the pane now. + readObservedAgentStatusPaneIdentity: (paneKey) => observedPaneIdentities.read(paneKey), structuredAgentStatusSink: { publish: (summary) => agentHookServer.ingestStructuredStatus(summary), forget: (sessionId) => agentHookServer.dropStructuredStatus(sessionId) - } + }, + reconcileAgentStatusForEndedProcess: (paneKeys) => + agentHookServer.reconcileEndedProcessForPaneKeys(paneKeys), + buildAgentHookPtyEnv: () => + isAgentStatusHooksEnabled(store.getSettings()) ? agentHookServer.buildPtyEnv() : {} }) + // Why here too and not only on the desktop: nothing else republishes `session.tabs` when a + // pane's status row changes, and orcad's whole job is serving paired clients. + uninstallHookStatusRepublish = installHookStatusSessionTabsRepublish( + agentHookServer, + () => runtime + ) + // Why the headless entry point rather than registerPtyHandlers directly: this is the // same call `--serve` makes, and it threads the store through. Without the store the // handlers install fine and every terminal.create then fails at persistence time. @@ -211,8 +266,11 @@ async function startOrcadRuntime( await runtime.refreshRestoredOrchestrationAuthority() await runtime.reconcileLegacyWorkerTerminals() + // Recovery binds terminal and dispatch identities; only now can startup observations be fenced. + observedStatusCapture.attach(runtime) + const bindHost = resolveOrcadBindHost(options.bind) - const rpc = new OrcaRuntimeRpcServer({ + rpc = new OrcaRuntimeRpcServer({ runtime, userDataPath: runtimeUserDataPath, enableWebSocket: true, @@ -224,6 +282,13 @@ async function startOrcadRuntime( ...(options.port !== undefined ? { wsPort: options.port, preferPinnedWsPort: true } : {}) }) await rpc.start() + const pushService = DesktopPushService.create({ + runtime, + runtimeRpc: rpc, + gatewayUrl: resolvePushGatewayOrigin(process.env, getAppEnvironment().isPackaged()) + }) + pushService?.start() + getAppEnvironment().onWillQuit(() => pushService?.stop()) console.error(`[orcad] ${describeOrcadBindExposure(bindHost)}`) const boundEndpoint = rpc.getWebSocketEndpoint() @@ -270,23 +335,7 @@ async function startOrcadRuntime( mode: options.json ? 'json' : 'human' }) - return { - readiness, - stop: async () => { - try { - await rpc.stop() - } finally { - // Why disconnect and not shut down: the daemon must outlive this process, or an - // orcad restart goes back to killing every running terminal. See - // orcad-daemon-supervision.ts. - await stopOrcadDaemon() - await browserProvider?.stop() - setRuntimeBrowserCommandsFactory(null) - runOrcadQuitHandlers() - instanceLock.release() - } - } - } + return { readiness } } export function parseArgs(argv: string[]): OrcadOptions { diff --git a/src/main/orcad/orcad-launch-contract.test.ts b/src/main/orcad/orcad-launch-contract.test.ts index b22dc74f0e4..2d2e4e6157e 100644 --- a/src/main/orcad/orcad-launch-contract.test.ts +++ b/src/main/orcad/orcad-launch-contract.test.ts @@ -2,13 +2,14 @@ * The two things a supervisor reads off a launch: what the arguments mean, and what an exit * code means. Both are part of the ops contract in docs/reference/orcad-operations.md. */ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { ORCAD_EXIT_CONFIGURATION, ORCAD_EXIT_FAILED, parseArgs, resolveOrcadExitCode } from './orcad-entry' +import { startOrcadWithLifecycle } from './orcad-lifecycle' import { OrcadBindAddressError } from './orcad-bind-address' import { OrcadInstanceLockError } from './orcad-instance-lock' @@ -41,3 +42,58 @@ describe('resolveOrcadExitCode', () => { expect(ORCAD_EXIT_CONFIGURATION).not.toBe(ORCAD_EXIT_FAILED) }) }) + +describe('orcad lifecycle cleanup', () => { + it('uninstalls registered runtime resources when startup fails', async () => { + const cleanupRuntime = vi.fn(async () => {}) + const cleanupHost = vi.fn(async () => {}) + + await expect( + startOrcadWithLifecycle(async (registerCleanup) => { + registerCleanup(cleanupRuntime) + await Promise.resolve() + throw new Error('startup failed') + }, cleanupHost) + ).rejects.toThrow('startup failed') + + expect(cleanupRuntime).toHaveBeenCalledOnce() + expect(cleanupHost).toHaveBeenCalledOnce() + }) + + it('preserves the startup error when rollback also fails', async () => { + const startupError = new Error('bind failed') + const cleanupError = new Error('daemon stop failed') + const cleanupRuntime = vi.fn(async () => {}) + const cleanupHost = vi.fn(async () => { + throw cleanupError + }) + const report = vi.spyOn(console, 'error').mockImplementation(() => {}) + + try { + await expect( + startOrcadWithLifecycle(async (registerCleanup) => { + registerCleanup(cleanupRuntime) + throw startupError + }, cleanupHost) + ).rejects.toBe(startupError) + expect(report).toHaveBeenCalledWith('[orcad] startup cleanup failed:', cleanupError) + } finally { + report.mockRestore() + } + }) + + it('coalesces concurrent and repeated normal stops', async () => { + const cleanupRuntime = vi.fn(async () => {}) + const cleanupHost = vi.fn(async () => {}) + const handle = await startOrcadWithLifecycle(async (registerCleanup) => { + registerCleanup(cleanupRuntime) + return { readiness: 'ready' } + }, cleanupHost) + + await Promise.all([handle.stop(), handle.stop()]) + await handle.stop() + + expect(cleanupRuntime).toHaveBeenCalledOnce() + expect(cleanupHost).toHaveBeenCalledOnce() + }) +}) diff --git a/src/main/orcad/orcad-lifecycle.ts b/src/main/orcad/orcad-lifecycle.ts new file mode 100644 index 00000000000..913a21c4874 --- /dev/null +++ b/src/main/orcad/orcad-lifecycle.ts @@ -0,0 +1,35 @@ +function createIdempotentOrcadCleanup(cleanup: () => Promise): () => Promise { + let completion: Promise | null = null + return () => { + completion ??= Promise.resolve().then(cleanup) + return completion + } +} + +export async function startOrcadWithLifecycle( + start: (registerRuntimeCleanup: (cleanup: () => Promise) => void) => Promise, + cleanupHost: () => Promise +): Promise }> { + let cleanupRuntime = async (): Promise => {} + const cleanup = createIdempotentOrcadCleanup(async () => { + try { + await cleanupRuntime() + } finally { + await cleanupHost() + } + }) + try { + const handle = await start((nextCleanup) => { + cleanupRuntime = nextCleanup + }) + return { ...handle, stop: cleanup } + } catch (error) { + try { + await cleanup() + } catch (cleanupError) { + // Keep the launch failure as the supervisor-facing verdict; cleanup still needs a breadcrumb. + console.error('[orcad] startup cleanup failed:', cleanupError) + } + throw error + } +} diff --git a/src/main/orcad/orcad-push-startup.test.ts b/src/main/orcad/orcad-push-startup.test.ts new file mode 100644 index 00000000000..a8fbbc9fe16 --- /dev/null +++ b/src/main/orcad/orcad-push-startup.test.ts @@ -0,0 +1,147 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it, vi } from 'vitest' +import { DeviceRegistry } from '../runtime/device-registry' +import { RuntimeMobileNotificationController } from '../runtime/runtime-mobile-notification-controller' +import { PushUnregisterOutbox } from '../runtime/push/push-unregister-outbox' +import { createPushHostKeypair } from '../runtime/push/push-host-challenge-fixtures' + +const state = vi.hoisted(() => ({ + root: '', + controller: null as RuntimeMobileNotificationController | null, + registry: null as DeviceRegistry | null, + rpcStarted: false, + register: vi.fn(async () => ({ ok: true, registrationId: 'headless-registration' })), + send: vi.fn(async () => ({ ok: true, results: [] })) +})) +vi.mock('./orcad-app-paths', () => ({ + resolveOrcadInstallRoot: () => state.root, + resolveOrcadPath: () => state.root, + resolveUserDataPath: () => state.root +})) +vi.mock('./orcad-browser-provider', () => ({ resolveOrcadBrowserProvider: async () => null })) +vi.mock('./orcad-instance-lock', () => ({ acquireOrcadInstanceLock: () => ({ release() {} }) })) +vi.mock('./orcad-daemon-supervision', () => ({ + startOrcadDaemon: async () => {}, + stopOrcadDaemon: async () => {} +})) +vi.mock('./orcad-health', () => ({ collectOrcadHealth: async () => ({}) })) +vi.mock('../daemon/daemon-init', () => ({ daemonOwnsFreshPersistentPtys: () => false })) +vi.mock('../ipc/pty', () => ({ + registerHeadlessPtyRuntime: async () => {}, + getLocalPtyProvider: () => null, + getSshPtyProvider: () => null +})) +vi.mock('../persistence/loading-store/store', () => ({ + Store: class { + getSettings() { + return {} + } + } +})) +vi.mock('../orca-profiles/profile-index-store', () => ({ + initOrcaProfilePaths() {}, + ensureActiveOrcaProfile: () => ({ dataFile: join(state.root, 'profile.json') }) +})) +vi.mock('../ssh/ssh-host-key-store', () => ({ initSshHostKeyStoreFile() {} })) +vi.mock('../server/serve-readiness', () => ({ + ServeReadinessPublisher: class { + async publish() {} + } +})) +vi.mock('../runtime/orca-runtime', () => ({ + OrcaRuntimeService: class { + getRuntimeId() { + return 'headless-runtime' + } + rehydrateClientHostedBrowserPages() {} + async refreshRestoredOrchestrationAuthority() {} + async reconcileLegacyWorkerTerminals() {} + setMobilePushRegistrar( + registrar: Parameters[0] + ) { + state.controller!.setPushRegistrar(registrar) + } + onNotificationDispatched( + listener: Parameters[0] + ) { + return state.controller!.onDispatched(listener) + } + } +})) +vi.mock('../runtime/runtime-rpc', () => ({ + OrcaRuntimeRpcServer: class { + async start() { + state.rpcStarted = true + } + async stop() { + state.rpcStarted = false + } + getWebSocketEndpoint() { + return null + } + getE2EEKeypair() { + expect(state.rpcStarted).toBe(true) + return createPushHostKeypair() + } + getDeviceRegistry() { + return state.registry + } + getPushUnregisterOutbox() { + return new PushUnregisterOutbox(state.root) + } + setOnPushUnregisterQueued() {} + } +})) +vi.mock('../runtime/push/push-gateway-client', () => ({ + PushGatewayClient: class { + registerDevice = state.register + send = state.send + async deleteDevice() { + return { deleted: true, retryable: false } + } + } +})) + +afterEach(() => { + rmSync(state.root, { recursive: true, force: true }) + vi.clearAllMocks() +}) + +it('starts push after RPC identity is available and stops dispatch on shutdown', async () => { + state.root = mkdtempSync(join(tmpdir(), 'orca-headless-push-')) + state.controller = new RuntimeMobileNotificationController() + state.registry = new DeviceRegistry(state.root) + const phone = state.registry.addDevice('headless-phone', 'mobile') + const { startOrcad } = await import('./orcad-entry') + const host = await startOrcad({ noPairing: true, json: true }) + try { + const result = await state.controller.registerPushDevice({ + deviceId: phone.deviceId, + platform: 'android', + token: 'test-token', + filter: { + onlyWhenDesktopAway: true + } + }) + expect(result).toMatchObject({ registered: true }) + expect(state.registry.getDevice(phone.deviceId)?.pushRegistration?.expiresAt).toBeGreaterThan( + Date.now() + ) + state.controller.dispatch({ + type: 'notification', + source: 'agent-task-complete', + title: 'QA', + body: 'QA' + }) + await new Promise((resolve) => setImmediate(resolve)) + expect(state.send).toHaveBeenCalledTimes(1) + } finally { + await host.stop() + } + expect(state.controller.getListenerCount()).toBe(0) + expect(await state.controller.registerPushDevice({} as never)).toMatchObject({ + registered: false + }) +}) diff --git a/src/main/pi/agent-status-extension-test-harness.ts b/src/main/pi/agent-status-extension-test-harness.ts index eec2b615017..810bc3d04d5 100644 --- a/src/main/pi/agent-status-extension-test-harness.ts +++ b/src/main/pi/agent-status-extension-test-harness.ts @@ -24,6 +24,7 @@ type FakeCurlChild = { } export type AgentStatusExtensionHarness = { + killMock: ReturnType fetchMock: ReturnType spawnMock: ReturnType spawnedChildren: FakeCurlChild[] @@ -57,6 +58,7 @@ export const AGENT_STATUS_EXTENSION_SELF_PID = 4242 export function createAgentStatusExtensionHarness(args: { kind: 'pi' | 'omp' | 'prime-agent' + killImpl?: (pid: number, signal: number) => void env?: Record pid?: number title?: string @@ -115,7 +117,9 @@ export function createAgentStatusExtensionHarness(args: { throw new Error(`unexpected require(${specifier})`) }) + const killMock = vi.fn(args.killImpl ?? (() => undefined)) const processMock = { + kill: killMock, env: { ...BASE_ENV, ...(args.kind === 'prime-agent' ? { PRIME_AGENT_INTERNAL_DAEMON_WORKER: '1' } : {}), @@ -172,6 +176,7 @@ export function createAgentStatusExtensionHarness(args: { return { fetchMock, + killMock, spawnMock, spawnedChildren, fsMock, diff --git a/src/main/pi/agent-status-handler-source.ts b/src/main/pi/agent-status-handler-source.ts index 9d02abbd78d..5a778a1c81f 100644 --- a/src/main/pi/agent-status-handler-source.ts +++ b/src/main/pi/agent-status-handler-source.ts @@ -88,13 +88,31 @@ export function getPiAgentStatusHandlerSourceLines(kind: PiAgentKind): string[] '// etc.), so we forward the raw object verbatim under the same field', '// names Claude uses (tool_name / tool_input) and let the server pick the', '// preview. Keeps tool-name knowledge centralized on the receiver side.', + '// Why: a restarted agent inherits the previous owner PID through env, so a', + '// dead owner must be claimable or the pane goes silent for good. Only ESRCH', + '// proves the owner is gone -- every other probe result keeps suppression, so', + '// a live foreign owner still cannot double-report. Mirrors the tri-state in', + '// main/agent-hooks/managed-hook-owner-identity.ts, which this runtime cannot', + '// import (the extension loads inside pi/omp with no Orca deps).', + 'function isStatusOwnerAlive(pid: string): boolean {', + ' const parsed = Number(pid)', + ' if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > 0x7fffffff) return false', + " if (typeof process.kill !== 'function') return true", + ' try {', + ' process.kill(parsed, 0)', + ' return true', + ' } catch (err: unknown) {', + " return (err as { code?: string } | null)?.code !== 'ESRCH'", + ' }', + '}', + '', "// Why: child agents inherit the lead's pane env; only its process may", '// register status hooks. PID identity keeps in-process reloads reporting.', 'export default function (pi): void {', ...primeDaemonWorkerGuard, ` const ownerPid = process.env.${ownerEnv}`, ' const selfPid = String(process.pid)', - ' if (ownerPid && ownerPid !== selfPid) return', + ' if (ownerPid && ownerPid !== selfPid && isStatusOwnerAlive(ownerPid)) return', ` process.env.${ownerEnv} = selfPid`, ...sessionStartHandler, ` pi.on('before_agent_start', (event${ctxParam}) => {`, diff --git a/src/main/pi/agent-status-owner-recovery.test.ts b/src/main/pi/agent-status-owner-recovery.test.ts new file mode 100644 index 00000000000..d176bcb8dae --- /dev/null +++ b/src/main/pi/agent-status-owner-recovery.test.ts @@ -0,0 +1,89 @@ +import { describe, expect, it } from 'vitest' +import { + createAgentStatusExtensionHarness as createHarness, + AGENT_STATUS_EXTENSION_SELF_PID as SELF_PID +} from './agent-status-extension-test-harness' + +describe('Pi status owner recovery', () => { + it.each(['pi', 'omp', 'prime-agent'] as const)( + 'claims the pane for a restarted %s agent whose inherited owner PID is dead', + async (kind) => { + // Why: STA-5245 -- a restart leaves a dead owner PID in the inherited env. + // Without a liveness probe the guard suppresses every later load, so the + // pane never reports status again. + const ownerKey = + kind === 'prime-agent' ? 'ORCA_PRIME_AGENT_STATUS_OWNED' : 'ORCA_PI_STATUS_OWNED' + const harness = createHarness({ + kind, + pid: SELF_PID, + env: { [ownerKey]: String(SELF_PID - 1) }, + killImpl: () => { + throw Object.assign(new Error('ESRCH'), { code: 'ESRCH' }) + } + }) + + expect(harness.killMock).toHaveBeenCalledWith(SELF_PID - 1, 0) + expect(harness.handlers.agent_end).toBeTypeOf('function') + expect(harness.processEnv[ownerKey]).toBe(String(SELF_PID)) + + await harness.callHook('agent_end') + expect(harness.fetchMock).toHaveBeenCalledTimes(1) + } + ) + + it.each(['EPERM', 'EACCES', 'EINVAL', undefined])( + 'keeps suppression for unverifiable probe error %s', + (code) => { + // Why: EPERM means the owner exists but belongs to another user, so + // claiming the pane there would reintroduce double-reporting. + const harness = createHarness({ + kind: 'pi', + pid: SELF_PID, + env: { ORCA_PI_STATUS_OWNED: String(SELF_PID - 1) }, + killImpl: () => { + throw Object.assign(new Error('probe failed'), { code }) + } + }) + + expect(harness.handlers).toEqual({}) + expect(harness.processEnv.ORCA_PI_STATUS_OWNED).toBe(String(SELF_PID - 1)) + } + ) + + it('claims the pane when the inherited owner PID is not a usable pid', () => { + // Why: a truncated/garbage marker is not evidence of a live owner. + const harness = createHarness({ + kind: 'pi', + pid: SELF_PID, + env: { ORCA_PI_STATUS_OWNED: 'not-a-pid' } + }) + + expect(harness.killMock).not.toHaveBeenCalled() + expect(harness.handlers.agent_end).toBeTypeOf('function') + expect(harness.processEnv.ORCA_PI_STATUS_OWNED).toBe(String(SELF_PID)) + }) + + it('claims the pane when the inherited owner PID exceeds safe integer precision', () => { + const harness = createHarness({ + kind: 'pi', + pid: SELF_PID, + env: { ORCA_PI_STATUS_OWNED: '99999999999999999999999' } + }) + + expect(harness.killMock).not.toHaveBeenCalled() + expect(harness.handlers.agent_end).toBeTypeOf('function') + expect(harness.processEnv.ORCA_PI_STATUS_OWNED).toBe(String(SELF_PID)) + }) + + it('claims the pane when the inherited owner PID exceeds the process API range', () => { + const harness = createHarness({ + kind: 'pi', + pid: SELF_PID, + env: { ORCA_PI_STATUS_OWNED: String(2 ** 31) } + }) + + expect(harness.killMock).not.toHaveBeenCalled() + expect(harness.handlers.agent_end).toBeTypeOf('function') + expect(harness.processEnv.ORCA_PI_STATUS_OWNED).toBe(String(SELF_PID)) + }) +}) diff --git a/src/main/pi/titlebar-extension-lifetime-source.ts b/src/main/pi/titlebar-extension-lifetime-source.ts new file mode 100644 index 00000000000..1d7c4abd304 --- /dev/null +++ b/src/main/pi/titlebar-extension-lifetime-source.ts @@ -0,0 +1,30 @@ +export function getPiTitlebarLifetimeSourceLines(): string[] { + return [ + ' // Why: replacement factories share the process realm; retire the old owner before painting.', + " const ownersKey = Symbol.for('orca.pi.titlebar.owners')", + ' const owners = globalThis[ownersKey] ??= new Map()', + ' const paneKey = process.env.ORCA_PANE_KEY', + ' owners.get(paneKey)?.()', + ' let disposed = false', + ' function clearOwnedTimers() {', + ' clearPendingAgentEndCheck()', + ' clearAnimation()', + ' stopMarkerReassert()', + ' }', + '', + ' function dispose() {', + ' disposed = true', + ' clearOwnedTimers()', + ' resetPromptState()', + ' if (owners.get(paneKey) === dispose) owners.delete(paneKey)', + ' }', + ' owners.set(paneKey, dispose)', + '', + ' function on(name, handler) {', + ' pi.on(name, (event, ctx) => {', + ' if (!disposed) return handler(event, ctx)', + ' })', + ' }', + '' + ] +} diff --git a/src/main/pi/titlebar-extension-service.test.ts b/src/main/pi/titlebar-extension-service.test.ts index 3ad73bba6eb..69884d6591b 100644 --- a/src/main/pi/titlebar-extension-service.test.ts +++ b/src/main/pi/titlebar-extension-service.test.ts @@ -39,6 +39,7 @@ vi.mock('os', async (importOriginal) => { }) import { PiTitlebarExtensionService, isSafeDescendCandidate } from './titlebar-extension-service' +import { getPiTitlebarExtensionSource } from './titlebar-extension-source' function legacyOverlayPath(kind: 'pi' | 'omp', ptyId: string): string { const rootDir = kind === 'pi' ? 'pi-agent-overlays' : 'omp-agent-overlays' @@ -458,6 +459,16 @@ describe('PiTitlebarExtensionService', () => { expectPiHomeIntact() }) + it('refreshes a managed spinner in an explicitly selected senpi home', () => { + const agentDir = join(userDataDir, '.omo', 'agent') + const extensionPath = join(agentDir, 'extensions', 'orca-titlebar-spinner.ts') + mkdirSync(join(agentDir, 'extensions'), { recursive: true }) + writeFileSync(extensionPath, '// @orca-managed-pi-extension\nstale spinner') + const svc = new PiTitlebarExtensionService() + svc.buildPtyEnv('pty-senpi', agentDir, 'pi') + expect(readFileSync(extensionPath, 'utf8')).toContain(getPiTitlebarExtensionSource()) + }) + it('rebuilding updates Orca-owned extensions while preserving user files', () => { const svc = new PiTitlebarExtensionService() svc.buildPtyEnv('pty-refresh-1', piHome, 'pi') diff --git a/src/main/pi/titlebar-extension-source.test.ts b/src/main/pi/titlebar-extension-source.test.ts index be21f8c6a16..eb826c1903e 100644 --- a/src/main/pi/titlebar-extension-source.test.ts +++ b/src/main/pi/titlebar-extension-source.test.ts @@ -35,6 +35,8 @@ function createHarness( processTitle?: string cwdImpl?: () => string sessionNameImpl?: () => string + setTitle?: (title: string) => void + globals?: Record env?: Record } = {} ): Harness { @@ -42,6 +44,7 @@ function createHarness( const ctx: TitlebarContext = { ui: { setTitle: (title: string) => { + options.setTitle?.(title) titles.push(title) } }, @@ -75,7 +78,7 @@ function createHarness( setTimeout: (...args: Parameters) => setTimeout(...args), clearTimeout: (timer: ReturnType) => clearTimeout(timer) } as Record - context.globalThis = context + context.globalThis = options.globals ?? context const output = ts.transpileModule(getPiTitlebarExtensionSource(options.kind ?? 'pi'), { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 } @@ -588,4 +591,148 @@ describe('getPiTitlebarExtensionSource', () => { expect(harness.handlers.ui_prompt_start).toBeDefined() expect(() => harness.handlers.ui_prompt_start?.({}, undefined)).not.toThrow() }) + + it.each(['getter', 'title'] as const)( + 'retires a stale %s during animation without throwing or rescheduling', + async (failure) => { + let stale = false + const harness = createHarness({ + sessionNameImpl: () => { + if (stale && failure === 'getter') { + throw new Error('expired session') + } + return SESSION + }, + setTitle: () => { + if (stale && failure === 'title') { + throw new Error('expired UI') + } + } + }) + await harness.callHook('agent_start') + stale = true + expect(() => vi.advanceTimersByTime(80)).not.toThrow() + expect(vi.getTimerCount()).toBe(0) + await harness.callHook('agent_start') + expect(vi.getTimerCount()).toBe(0) + stale = false + await harness.callHook('agent_start') + expect(vi.getTimerCount()).toBe(1) + } + ) + + it.each(['getter', 'title'] as const)('contains stale %s during shutdown', async (failure) => { + let stale = false + const harness = createHarness({ + sessionNameImpl: () => { + if (stale && failure === 'getter') { + throw new Error('expired session') + } + return SESSION + }, + setTitle: () => { + if (stale && failure === 'title') { + throw new Error('expired UI') + } + }, + isIdle: () => false + }) + await harness.callHook('agent_start') + await harness.callHook('agent_end') + stale = true + await expect(harness.callHook('session_shutdown')).resolves.toBeUndefined() + expect(vi.getTimerCount()).toBe(0) + }) + + it('does not schedule a timer when the first frame fails', async () => { + const harness = createHarness({ + sessionNameImpl: () => { + throw new Error('expired') + } + }) + await harness.callHook('agent_start') + expect(vi.getTimerCount()).toBe(0) + }) + + it('retires animation when an idle recheck loses its session', async () => { + const harness = createHarness({ + isIdle: () => { + throw new Error('expired') + } + }) + await harness.callHook('agent_start') + await harness.callHook('agent_end') + expect(() => vi.advanceTimersByTime(1)).not.toThrow() + expect(vi.getTimerCount()).toBe(0) + }) + + it('clears animation and pending idle checks on session replacement', async () => { + const harness = createHarness({ isIdle: () => false }) + await harness.callHook('agent_start') + await harness.callHook('agent_end') + await harness.callHook('session_shutdown') + await harness.callHook('session_start') + expect(vi.getTimerCount()).toBe(0) + await harness.callHook('agent_start') + expect(vi.getTimerCount()).toBe(1) + }) + + it('reload replaces only its pane owner and ignores late old-generation events', async () => { + const globals = {} + const old = createHarness({ globals, isIdle: () => false }) + const other = createHarness({ globals, paneKey: 'pane-2' }) + await old.callHook('agent_start') + await old.callHook('ui_prompt_start') + await old.callHook('agent_end') + await other.callHook('agent_start') + const replacement = createHarness({ globals }) + expect(vi.getTimerCount()).toBe(1) + await replacement.callHook('agent_start') + const oldCount = old.titles.length + await old.callHook('session_shutdown') + await old.callHook('agent_start') + vi.advanceTimersByTime(80) + expect(old.titles).toHaveLength(oldCount) + expect(vi.getTimerCount()).toBe(2) + expect(replacement.lastTitle()).toMatch(BRAILLE_RE) + expect(other.lastTitle()).toMatch(BRAILLE_RE) + const third = createHarness({ globals }) + expect(vi.getTimerCount()).toBe(1) + await third.callHook('agent_start') + await replacement.callHook('session_shutdown') + expect(vi.getTimerCount()).toBe(2) + }) + + it('stops spinner, prompt reassertion and idle recheck together on invalidation', async () => { + let stale = false + const harness = createHarness({ + isIdle: () => false, + sessionNameImpl: () => { + if (stale) { + throw new Error('stale generation') + } + return SESSION + } + }) + await harness.callHook('agent_start') + await harness.callHook('ui_prompt_start') + await harness.callHook('agent_end') + expect(vi.getTimerCount()).toBe(3) + stale = true + await vi.advanceTimersByTimeAsync(80) + expect(vi.getTimerCount()).toBe(0) + }) + + it('clears prompt and idle timers at session_start without needing shutdown', async () => { + const harness = createHarness({ isIdle: () => false }) + await harness.callHook('agent_start') + await harness.callHook('ui_prompt_start') + await harness.callHook('agent_end') + expect(vi.getTimerCount()).toBe(3) + await harness.callHook('session_start') + expect(vi.getTimerCount()).toBe(0) + await harness.callHook('agent_start') + expect(harness.lastTitle()).toMatch(BRAILLE_RE) + expect(vi.getTimerCount()).toBe(1) + }) }) diff --git a/src/main/pi/titlebar-extension-source.ts b/src/main/pi/titlebar-extension-source.ts index 7fc15c191bc..570d23a15d3 100644 --- a/src/main/pi/titlebar-extension-source.ts +++ b/src/main/pi/titlebar-extension-source.ts @@ -1,3 +1,4 @@ +import { getPiTitlebarLifetimeSourceLines } from './titlebar-extension-lifetime-source' import type { PiAgentKind } from '../../shared/pi-agent-kind' import { getPiOmpRuntimeDetectionSourceLines } from './agent-status-runtime-detection-source' @@ -10,7 +11,7 @@ export function getPiTitlebarExtensionSource(kind: PiAgentKind = 'pi'): string { const uiPromptHandlers = kind === 'pi' ? [ - " pi.on('ui_prompt_start', async (_event, ctx) => {", + " on('ui_prompt_start', async (_event, ctx) => {", ' if (isOmpRuntime() || !ownsMarker) return', ' promptDepth++', ' // Why: retry on every open rather than only the outermost, so an outer ctx', @@ -25,7 +26,7 @@ export function getPiTitlebarExtensionSource(kind: PiAgentKind = 'pi'): string { ' startMarkerReassert(painter)', ' })', '', - " pi.on('ui_prompt_end', async (_event, ctx) => {", + " on('ui_prompt_end', async (_event, ctx) => {", ' if (isOmpRuntime() || !ownsMarker || promptDepth === 0) return', ' promptDepth--', ' if (promptDepth > 0) return', @@ -98,20 +99,6 @@ export function getPiTitlebarExtensionSource(kind: PiAgentKind = 'pi'): string { ' }', '}', '', - '// Why: buildTitle runs inside the try because it is not safe either — getSessionName()', - '// calls assertActive() and process.cwd() throws ENOENT once the worktree is deleted.', - '// Most call sites are timer callbacks, where an escape is an uncaught exception and pi', - '// exits(1) through its own uncaughtException handler.', - 'function paintTitle(ctx, buildTitle) {', - ' if (!ctx) return false', - ' try {', - ' ctx.ui.setTitle(buildTitle())', - ' return true', - ' } catch {', - ' return false', - ' }', - '}', - '', 'export default function (pi) {', ' if (!process.env.ORCA_PANE_KEY) return', ...(kind === 'pi' @@ -125,6 +112,7 @@ export function getPiTitlebarExtensionSource(kind: PiAgentKind = 'pi'): string { ] : []), + ...getPiTitlebarLifetimeSourceLines(), ' let timer = null', ' let frameIndex = 0', ' // Why: only idle maintenance owns a spinner of its own. A threshold compaction runs', @@ -144,6 +132,21 @@ export function getPiTitlebarExtensionSource(kind: PiAgentKind = 'pi'): string { ' let pendingAgentEndContext = null', ' let agentEndIdleRecheckMs = AGENT_END_IDLE_RECHECK_MS', '', + '// Why: buildTitle runs inside the try because it is not safe either — getSessionName()', + '// calls assertActive() and process.cwd() throws ENOENT once the worktree is deleted.', + '// Most call sites are timer callbacks, where an escape is an uncaught exception and pi', + '// exits(1) through its own uncaughtException handler.', + ' function paintTitle(ctx, buildTitle) {', + ' if (disposed || !ctx) return false', + ' try {', + ' ctx.ui.setTitle(buildTitle())', + ' return true', + ' } catch {', + ' clearOwnedTimers()', + ' return false', + ' }', + ' }', + '', ' function resetPromptState() {', ' stopMarkerReassert()', ' promptDepth = 0', @@ -199,23 +202,24 @@ export function getPiTitlebarExtensionSource(kind: PiAgentKind = 'pi'): string { ' // otherwise wipe the marker with nothing to restore it. The frame still counts,', ' // so the cap above keeps accruing in wall-clock.', ' if (markerPainted) {', - " paintTitle(ctx, () => getMarkedTitle(pi, '!'))", + " const painted = paintTitle(ctx, () => getMarkedTitle(pi, '!'))", ' frameIndex++', - ' return', + ' return painted', ' }', - ' paintTitle(ctx, () => {', + ' const painted = paintTitle(ctx, () => {', ' const frame = BRAILLE_FRAMES[frameIndex % BRAILLE_FRAMES.length]', ' const cwd = process.cwd().split(/[\\\\/]/).filter(Boolean).at(-1) || process.cwd()', ' const session = pi.getSessionName()', ' return session ? `${frame} \\u03c0 - ${session} - ${cwd}` : `${frame} \\u03c0 - ${cwd}`', ' })', ' frameIndex++', + ' return painted', ' }', '', ' function startAnimation(ctx) {', ' clearPendingAgentEndCheck()', ' clearAnimation()', - ' renderFrame(ctx)', + ' if (!renderFrame(ctx)) return', ' timer = setInterval(() => renderFrame(ctx), FRAME_INTERVAL_MS)', ' }', '', @@ -230,7 +234,7 @@ export function getPiTitlebarExtensionSource(kind: PiAgentKind = 'pi'): string { ' return', ' }', ' } catch {', - ' pendingAgentEndContext = null', + ' clearOwnedTimers()', ' return', ' }', ' pendingAgentEndCheck = setTimeout(checkPendingAgentEnd, agentEndIdleRecheckMs)', @@ -238,7 +242,7 @@ export function getPiTitlebarExtensionSource(kind: PiAgentKind = 'pi'): string { ' agentEndIdleRecheckMs = Math.min(agentEndIdleRecheckMs * 2, AGENT_END_IDLE_RECHECK_MAX_MS)', ' }', '', - " pi.on('agent_start', async (_event, ctx) => {", + " on('agent_start', async (_event, ctx) => {", ' resetPromptState()', ' startAnimation(ctx)', ' })', @@ -246,17 +250,18 @@ export function getPiTitlebarExtensionSource(kind: PiAgentKind = 'pi'): string { ' // Why: pi drops an open dialog through resetExtensionUI without resolving its promise,', ' // so a replaced or reloaded session never sends the matching close. Both boundaries', ' // prove no dialog from the old session is still on screen.', - " pi.on('session_start', async () => {", + " on('session_start', async () => {", + ' clearOwnedTimers()', ' resetPromptState()', ' })', '', ' // Why: modern Pi/OMP emit agent_end mid-run and only settle later, so settlement is the', ' // authoritative completion boundary. Legacy runtimes never emit it, so agent_end stays.', - " pi.on('agent_settled', async (_event, ctx) => {", + " on('agent_settled', async (_event, ctx) => {", ' stopAnimation(ctx)', ' })', '', - " pi.on('agent_end', async (event, ctx) => {", + " on('agent_end', async (event, ctx) => {", ' if (event?.willContinue === true) {', ' clearPendingAgentEndCheck()', ' return', @@ -273,7 +278,7 @@ export function getPiTitlebarExtensionSource(kind: PiAgentKind = 'pi'): string { ' })', '', ...uiPromptHandlers, - " pi.on('auto_compaction_start', async (event, ctx) => {", + " on('auto_compaction_start', async (event, ctx) => {", " if (event?.reason !== 'idle') return", ' // Why: the idle worker can fire against a turn that just started, and reason alone does', ' // not prove the pane is idle. Adopting a live agent spinner would let the matching', @@ -283,12 +288,12 @@ export function getPiTitlebarExtensionSource(kind: PiAgentKind = 'pi'): string { ' idleCompactionOwnsSpinner = true', ' })', '', - " pi.on('auto_compaction_end', async (_event, ctx) => {", + " on('auto_compaction_end', async (_event, ctx) => {", ' if (!idleCompactionOwnsSpinner) return', ' stopAnimation(ctx)', ' })', '', - " pi.on('session_shutdown', async (_event, ctx) => {", + " on('session_shutdown', async (_event, ctx) => {", ' resetPromptState()', ' stopAnimation(ctx)', ' })', diff --git a/src/main/runtime/__fixtures__/antigravity-busy-mid-turn.meta.json b/src/main/runtime/__fixtures__/antigravity-busy-mid-turn.meta.json new file mode 100644 index 00000000000..4e875eb047a --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-busy-mid-turn.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-09-11T06:10:52.713Z", + "platform": "darwin", + "command": ["agy"], + "cols": 120, + "rows": 40, + "note": "agy TUI 1.2.0; recording stopped ~0.3s after submit, while the spinner was live; no shutdown repaint in the file", + "exitCode": 0 +} diff --git a/src/main/runtime/__fixtures__/antigravity-busy-mid-turn.txt b/src/main/runtime/__fixtures__/antigravity-busy-mid-turn.txt new file mode 100644 index 00000000000..8f3645800f7 --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-busy-mid-turn.txt @@ -0,0 +1,38 @@ +[?2026$p[?2027$p[>4m[=0;1u[?1049h[?25l[?5W[?2004h[>4;2m[=1;1u[?u +▄▀▀▄ +▀▀▀▀▀▀ +▀▀▀▀▀▀▀▀ + ▄▀▀ ▀▀▄ + ▄▀▀ ▀▀▄ + + Welcome to the Antigravity CLI. You are currently not signed in. + + ⣾ Signing in... No authentication methods available. + + Press ctrl+c or ctrl+d twice to exit.[>4m[=0;1u[?1049l[>4;2m[=1;1u[?u[0 q  +▄▀▀▄ Antigravity CLI 1.2.0 +▀▀▀▀▀▀ Gemini API key +▀▀▀▀▀▀▀▀ Gemini 3.7 Flash (Low) + ▄▀▀ ▀▀▄ ~ + ▄▀▀ ▀▀▄ + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcutsGemini 3.7 Flash · low [?25h[?25lI[?25h[?25ln ab + + G[?25h[?25lout 8[?25h[?25l0 wo[?25h[?25lrds,[?25h[?25lexpla[?25h[?25lin w[?25h[?25lhat a[?25h[?25l pse[?25h[?25lud[?25h[?25loter[?25h[?25lminal[?25h[?25l is.[?25h[?25l[?25h[?25l + +? for shortcuts[?25h[?25lM +> In about 80 words, explain what a pseudoterminal is. +⣷ Generating... +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.7 Flash · low [?25h[?25lng + +[?25h[?25l ⣯ Generating + +[?25h[?25l ⣟ Generating. + +[?25h \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/antigravity-busy-turn-ended.meta.json b/src/main/runtime/__fixtures__/antigravity-busy-turn-ended.meta.json new file mode 100644 index 00000000000..084be8e54bc --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-busy-turn-ended.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-09-11T06:13:00.364Z", + "platform": "darwin", + "command": ["agy"], + "cols": 120, + "rows": 40, + "note": "agy TUI 1.2.0; recording stopped after the turn ended and the composer returned, with the process still alive. This account's API key cannot complete a turn, so the turn ends in a backend error", + "exitCode": 0 +} diff --git a/src/main/runtime/__fixtures__/antigravity-busy-turn-ended.txt b/src/main/runtime/__fixtures__/antigravity-busy-turn-ended.txt new file mode 100644 index 00000000000..e10de85d361 --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-busy-turn-ended.txt @@ -0,0 +1,42 @@ +[?2026$p[?2027$p[?5W[?2004h[>4;2m[=1;1u[?u[0 q  +▄▀▀▄ Antigravity CLI 1.2.0 +▀▀▀▀▀▀ Gemini API key +▀▀▀▀▀▀▀▀ Gemini 3.7 Flash (Low) + ▄▀▀ ▀▀▄ ~ + ▄▀▀ ▀▀▄ + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcutsGemini 3.7 Flash · low [?25h[?25lIn + + G[?25h[?25labo[?25h[?25lut 80[?25h[?25l wo[?25h[?25lrds[?25h[?25l, ex[?25h[?25lpla[?25h[?25lin wh[?25h[?25lat a[?25h[?25lpseudo[?25h[?25ltermi[?25h[?25lnal is[?25h[?25l.[?25h[?25l + +? for shortcuts[?25h[?25lM +> In about 80 words, explain what a pseudoterminal is. +⣾ Generating... +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.7 Flash · low [?25h[?25l ⣷ Generatin + +[?25h[?25l ⣯ Generating + +[?25h[?25l ⣟ Generating. + +[?25h[?25l ⡿ Generating... + +[?25h[?25l ⢿ Generatin + +[?25h[?25l  +⚠ Agent execution terminated due to error. +Error ID: 00000000-0000-4000-8000-000000000000-2 +⢿ Generating... +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +esc to cancelGemini 3.7 Flash · low [?25h[?25l  + + + +? for shortcuts[?25h \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/antigravity-dialog-command-palette.meta.json b/src/main/runtime/__fixtures__/antigravity-dialog-command-palette.meta.json new file mode 100644 index 00000000000..e098a1677ab --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-dialog-command-palette.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-09-11T04:34:32.974Z", + "platform": "darwin", + "command": ["agy"], + "cols": 120, + "rows": 40, + "note": "agy TUI 1.2.0; slash-command palette live, unanswered", + "exitCode": 0 +} diff --git a/src/main/runtime/__fixtures__/antigravity-dialog-command-palette.txt b/src/main/runtime/__fixtures__/antigravity-dialog-command-palette.txt new file mode 100644 index 00000000000..9bf02cc0ff9 --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-dialog-command-palette.txt @@ -0,0 +1,41 @@ +[?2026$p[?2027$p[?5W[?2004h[>4;2m[=1;1u[?u[0 q  +▄▀▀▄ Antigravity CLI 1.2.0 +▀▀▀▀▀▀ Gemini API key +▀▀▀▀▀▀▀▀ Gemini 3.7 Flash (Low) + ▄▀▀ ▀▀▄ ~ + ▄▀▀ ▀▀▄ + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcutsGemini 3.7 Flash · low [?25h[?25l/ + +> /add-dir  Add a directory to the workspace + /agents List available custom agents + /artifact View and review artifacts + /btw Ask a side question without interrupting the current task + /changelog Show release notes and changes + ↓ 50 more + + ↑/↓ Navigate · enter Select · tab Complete + Gemini 3.7 Flash · low [?25h[?25l + + + + + + + + + +esc to cancel[?25h[>4m[=0;1u + + + + + + + + + +[?2004l[0 q \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/antigravity-dialog-dismissed.meta.json b/src/main/runtime/__fixtures__/antigravity-dialog-dismissed.meta.json new file mode 100644 index 00000000000..8e8d5043fdf --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-dialog-dismissed.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-09-11T04:35:06.866Z", + "platform": "darwin", + "command": ["agy"], + "cols": 120, + "rows": 40, + "note": "agy TUI 1.2.0; /model picker opened then dismissed with esc, settled before stop", + "exitCode": 0 +} diff --git a/src/main/runtime/__fixtures__/antigravity-dialog-dismissed.txt b/src/main/runtime/__fixtures__/antigravity-dialog-dismissed.txt new file mode 100644 index 00000000000..bb35ae33af2 --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-dialog-dismissed.txt @@ -0,0 +1,54 @@ +[?2026$p[?2027$p[?5W[?2004h[>4;2m[=1;1u[?u[0 q  +▄▀▀▄ Antigravity CLI 1.2.0 +▀▀▀▀▀▀ Gemini API key +▀▀▀▀▀▀▀▀ Gemini 3.7 Flash (Low) + ▄▀▀ ▀▀▄ ~ + ▄▀▀ ▀▀▄ + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcutsGemini 3.7 Flash · low [?25h[?25l/mod + +> /model Set a model, or run a single prompt on another model + /permissioned-github Guidelines for interacting with GitHub and request permissions from the user when commands f... + + ↑/↓ Navigate · enter Select · tab Complete +esc to cancelGemini 3.7 Flash · low [?25h[?25l + + + + +/model + +  + + ↑/↓ Navigate · enter Select · tab Complete +esc to cancelGemini 3.7 Flash · low [?25h[?25l[0 q + +Switch Model + + Gemini 3.8 Flash +> Gemini 3.7 Flash (current) + Gemini 3.6 Flash + Gemini 3.1 Pro + + Effort ◂  ◉──────────────○──────────────○  ▸ +  low  medium high  + Faster responses, lighter reasoning — great for simpler tasks + +Keyboard: ↑/↓ Navigate ←/→ Effort enter Select esc Go Back + + Gemini 3.7 Flash · low [0 q> /model + ⎿ Exited /model command + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +Gemini 3.7 Flash · low [?25h[?25l + +? for shortcuts[?25h[>4m[=0;1u + +[?2004l[0 q +Resume with -c (or command below): +agy --conversation=00000000-0000-4000-8000-000000000000 diff --git a/src/main/runtime/__fixtures__/antigravity-dialog-model-picker.meta.json b/src/main/runtime/__fixtures__/antigravity-dialog-model-picker.meta.json new file mode 100644 index 00000000000..9a4e5c0c8e1 --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-dialog-model-picker.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-09-11T04:34:10.855Z", + "platform": "darwin", + "command": ["agy"], + "cols": 120, + "rows": 40, + "note": "agy TUI 1.2.0; /model picker live, unanswered, killed while it owns the screen", + "exitCode": 0 +} diff --git a/src/main/runtime/__fixtures__/antigravity-dialog-model-picker.txt b/src/main/runtime/__fixtures__/antigravity-dialog-model-picker.txt new file mode 100644 index 00000000000..6a09f6082f8 --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-dialog-model-picker.txt @@ -0,0 +1,56 @@ +[?2026$p[?2027$p[?5W[?2004h[>4;2m[=1;1u[?u[0 q  +▄▀▀▄ Antigravity CLI 1.2.0 +▀▀▀▀▀▀ Gemini API key +▀▀▀▀▀▀▀▀ Gemini 3.7 Flash (Low) + ▄▀▀ ▀▀▄ ~ + ▄▀▀ ▀▀▄ + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcutsGemini 3.7 Flash · low [?25h[?25l/mo + +> /model Set a model, or run a single prompt on another model + /migrate-workflows Automatically migrate legacy workflows to modern skills across global and workspace configur... + /permissions Manage tool permissions + /agy-customizations Comprehensive guide and reference for the Antigravity Customization System. Use to explain h... + /permissioned-github Guidelines for interacting with GitHub and request permissions from the user when commands f... + + ↑/↓ Navigate · enter Select · tab Complete +? for shortcutsGemini 3.7 Flash · low [?25h[?25l + + + + +/model + +  + + ↑/↓ Navigate · enter Select · tab Complete +esc to cancelGemini 3.7 Flash · low [?25h[?25l[0 q + +Switch Model + +> Gemini 3.8 Flash + Gemini 3.7 Flash (current) + Gemini 3.6 Flash + Gemini 3.1 Pro + + Effort ◂  ●━━━━━━━━━━━━━━◉──────────────○  ▸ +  low  medium  high  + Balanced speed and reasoning quality for most tasks + +Keyboard: ↑/↓ Navigate ←/→ Effort enter Select esc Go Back + +? for shortcutsGemini 3.7 Flash · low  Gemini 3.8 Flash +> Gemini 3.7 Flash + + + +◂  ◉──────────────○ + low  medium  +Faster responses, lighter reasoning — great for simpler tasks + + + +  G[>4m[=0;1u [?25h[?2004l \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/antigravity-dialog-trust-workspace.meta.json b/src/main/runtime/__fixtures__/antigravity-dialog-trust-workspace.meta.json new file mode 100644 index 00000000000..07fb15ab6f7 --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-dialog-trust-workspace.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-09-11T04:35:20.989Z", + "platform": "darwin", + "command": ["agy"], + "cols": 120, + "rows": 40, + "note": "agy TUI 1.2.0; workspace trust dialog live and unanswered in a throwaway untrusted directory", + "exitCode": 0 +} diff --git a/src/main/runtime/__fixtures__/antigravity-dialog-trust-workspace.txt b/src/main/runtime/__fixtures__/antigravity-dialog-trust-workspace.txt new file mode 100644 index 00000000000..b2e1b342199 --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-dialog-trust-workspace.txt @@ -0,0 +1,12 @@ +[?2026$p[?2027$p[>4m[=0;1u[?1049h[?25l[?5W[?2004h[>4;2m[=1;1u[?uAccessing workspace: + +/private/tmp/agy-trust-scratch-77950 + +Do you trust the contents of this project? + +Antigravity CLI requires permission to read, edit, and execute files here. + +> Yes, I trust this folder + No, exit + + ↑/↓ Navigate · enter ConfirmGemini 3.7 Flash · low[>4m[=0;1u [?1049l[?25h[?2004l \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/antigravity-ready-account-info-hidden.meta.json b/src/main/runtime/__fixtures__/antigravity-ready-account-info-hidden.meta.json new file mode 100644 index 00000000000..9607841cf6e --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-ready-account-info-hidden.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-09-11T04:33:34.954Z", + "platform": "darwin", + "command": ["agy"], + "cols": 120, + "rows": 40, + "note": "same session as antigravity-ready-api-key-gemini-model but with AGY_CLI_HIDE_ACCOUNT_INFO=1", + "exitCode": 0 +} diff --git a/src/main/runtime/__fixtures__/antigravity-ready-account-info-hidden.txt b/src/main/runtime/__fixtures__/antigravity-ready-account-info-hidden.txt new file mode 100644 index 00000000000..b93514374e0 --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-ready-account-info-hidden.txt @@ -0,0 +1,13 @@ +[?2026$p[?2027$p[?5W[?2004h[>4;2m[=1;1u[?u[0 q  +▄▀▀▄ Antigravity CLI 1.2.0 +▀▀▀▀▀▀ Gemini 3.7 Flash (Low) +▀▀▀▀▀▀▀▀ ~ + ▄▀▀ ▀▀▄ + ▄▀▀ ▀▀▄ + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcutsGemini 3.7 Flash · low [?25h[>4m[=0;1u + +[?2004l[0 q \ No newline at end of file diff --git a/src/main/runtime/__fixtures__/antigravity-ready-api-key-gemini-model.meta.json b/src/main/runtime/__fixtures__/antigravity-ready-api-key-gemini-model.meta.json new file mode 100644 index 00000000000..97a54e107dc --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-ready-api-key-gemini-model.meta.json @@ -0,0 +1,9 @@ +{ + "capturedAt": "2026-09-11T04:33:14.819Z", + "platform": "darwin", + "command": ["agy"], + "cols": 120, + "rows": 40, + "note": "agy binary 1.1.25, TUI banner 1.2.0; Gemini API key identity (no OAuth sign-in); model Gemini 3.7 Flash (Low); workspace ~", + "exitCode": 0 +} diff --git a/src/main/runtime/__fixtures__/antigravity-ready-api-key-gemini-model.txt b/src/main/runtime/__fixtures__/antigravity-ready-api-key-gemini-model.txt new file mode 100644 index 00000000000..c9501f1caac --- /dev/null +++ b/src/main/runtime/__fixtures__/antigravity-ready-api-key-gemini-model.txt @@ -0,0 +1,13 @@ +[?2026$p[?2027$p[?5W[?2004h[>4;2m[=1;1u[?u[0 q  +▄▀▀▄ Antigravity CLI 1.2.0 +▀▀▀▀▀▀ Gemini API key +▀▀▀▀▀▀▀▀ Gemini 3.7 Flash (Low) + ▄▀▀ ▀▀▄ ~ + ▄▀▀ ▀▀▄ + +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +> +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +? for shortcutsGemini 3.7 Flash · low [?25h[>4m[=0;1u + +[?2004l[0 q \ No newline at end of file diff --git a/src/main/runtime/agent-session-conversation-name-store.test.ts b/src/main/runtime/agent-session-conversation-name-store.test.ts new file mode 100644 index 00000000000..ce5d3fd2621 --- /dev/null +++ b/src/main/runtime/agent-session-conversation-name-store.test.ts @@ -0,0 +1,104 @@ +// The name is durable state on the record: the store is the only thing that writes it. +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import type { AgentSessionExecutionLocation } from '../../shared/agent-session-record' +import { AgentSessionRecordStore } from './agent-session-record-store' +import type { AgentSessionReserveRequest } from './agent-session-reservation-admission' + +const NOW = 1_800_000_000_000 +const SESSION = 'session-alpha' +const NATIVE: AgentSessionExecutionLocation = { + executionHostId: 'local', + wslDistro: null, + workspaceId: 'workspace-1', + workspaceKind: 'git-worktree' +} + +let counter = 0 +/** Same shape the store's own suite uses: `-<32 hex>`. */ +function operationId(): string { + counter += 1 + return `${NOW}-${String(counter) + .padStart(32, '0') + .replaceAll(/[^0-9a-f]/g, '0')}` +} + +const reserveRequest = (): AgentSessionReserveRequest => ({ + sessionId: SESSION, + location: NATIVE, + provider: 'claude', + accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: '/home/dev/.claude-work' }, + runtimeKind: 'native', + expectedFence: null, + spawnToken: 'spawn-a', + claimKeyId: 'key-1', + handoffOperationId: null, + probe: { outcome: 'indeterminate', reason: 'no answer' }, + operation: { callerKey: 'client-1', operationId: operationId(), fingerprint: 'fp-1' }, + now: NOW +}) + +let directory: string + +beforeEach(async () => { + directory = await mkdtemp(join(tmpdir(), 'orca-conversation-name-store-')) +}) +afterEach(async () => { + await rm(directory, { recursive: true, force: true }) +}) + +async function reservedStore(): Promise { + const store = await AgentSessionRecordStore.open({ directory, hostId: 'local' }) + await store.reserveOwner(reserveRequest()) + return store +} + +describe('AgentSessionRecordStore.setConversationName', () => { + it('stores the name and survives a reload, so the record is where it lives', async () => { + const store = await reservedStore() + + await store.setConversationName(SESSION, 'Fix the lease probe') + + const reloaded = await AgentSessionRecordStore.open({ directory, hostId: 'local' }) + expect(reloaded.getRecord(SESSION)?.conversationName).toBe('Fix the lease probe') + }) + + it('normalizes at the boundary, so no caller can persist an invalid record', async () => { + const store = await reservedStore() + + await store.setConversationName(SESSION, `Fix\nthe ${'x'.repeat(400)}`) + + const name = store.getRecord(SESSION)?.conversationName ?? '' + expect(name).toHaveLength(200) + expect(name.startsWith('Fix the ')).toBe(true) + // A reload validates every record; an over-long name would be dropped as unreadable. + const reloaded = await AgentSessionRecordStore.open({ directory, hostId: 'local' }) + expect(reloaded.getRecord(SESSION)?.conversationName).toBe(name) + }) + + it('clears the name with null', async () => { + const store = await reservedStore() + await store.setConversationName(SESSION, 'Fix the lease probe') + + await store.setConversationName(SESSION, null) + + expect(store.getRecord(SESSION)?.conversationName).toBeUndefined() + }) + + it('does not need the lease: an unfenced rename never contends with the writer', async () => { + const store = await reservedStore() + + // No fence argument exists to pass, and no fence error is raised. + await expect(store.setConversationName(SESSION, 'Fix the lease probe')).resolves.toBeDefined() + }) + + it('refuses a session it has no record for', async () => { + const store = await reservedStore() + + await expect(store.setConversationName('missing', 'A name')).rejects.toThrow( + 'agent_session_identity_required' + ) + }) +}) diff --git a/src/main/runtime/agent-session-record-conversation-name.test.ts b/src/main/runtime/agent-session-record-conversation-name.test.ts new file mode 100644 index 00000000000..3c5c55d83c6 --- /dev/null +++ b/src/main/runtime/agent-session-record-conversation-name.test.ts @@ -0,0 +1,129 @@ +import { describe, expect, it } from 'vitest' +import { isAgentSessionRecord } from '../../shared/agent-session-record' +import { agentSessionRecordFixture } from '../../shared/agent-session-record.test-fixture' +import { setAgentSessionRecordConversationName } from './agent-session-record-conversation-name' + +const NOW = 9_000 + +describe('agent session record conversationName validation', () => { + it('accepts a record carrying a bounded name', () => { + expect( + isAgentSessionRecord({ + ...agentSessionRecordFixture(), + conversationName: 'Fix the lease probe' + }) + ).toBe(true) + }) + + it('accepts a record with no name at all', () => { + expect(isAgentSessionRecord(agentSessionRecordFixture())).toBe(true) + }) + + it('rejects a name past the stored maximum', () => { + expect( + isAgentSessionRecord({ ...agentSessionRecordFixture(), conversationName: 'a'.repeat(201) }) + ).toBe(false) + }) + + it('rejects a name that is not a string', () => { + expect(isAgentSessionRecord({ ...agentSessionRecordFixture(), conversationName: 42 })).toBe( + false + ) + expect(isAgentSessionRecord({ ...agentSessionRecordFixture(), conversationName: '' })).toBe( + false + ) + }) + + it('rejects persisted names that bypassed canonical normalization', () => { + expect( + isAgentSessionRecord({ + ...agentSessionRecordFixture(), + conversationName: 'Fix\u202Egnp.exe probe' + }) + ).toBe(false) + expect( + isAgentSessionRecord({ ...agentSessionRecordFixture(), conversationName: 'Fix\nthe probe' }) + ).toBe(false) + }) +}) + +describe('setAgentSessionRecordConversationName', () => { + it('sets the name and stamps the update', () => { + const next = setAgentSessionRecordConversationName( + agentSessionRecordFixture(), + 'Fix the lease probe', + NOW + ) + + expect(next.conversationName).toBe('Fix the lease probe') + expect(next.updatedAt).toBe(NOW) + expect(isAgentSessionRecord(next)).toBe(true) + }) + + it('normalizes on the way in so the record stays valid whatever the caller sent', () => { + const next = setAgentSessionRecordConversationName( + agentSessionRecordFixture(), + `Fix\nthe probe`, + NOW + ) + + expect(next.conversationName).toBe('Fix the probe') + expect(isAgentSessionRecord(next)).toBe(true) + }) + + it('bounds an over-long name rather than storing a record the validator would reject', () => { + const next = setAgentSessionRecordConversationName( + agentSessionRecordFixture(), + 'a'.repeat(1000), + NOW + ) + + expect(next.conversationName).toHaveLength(200) + expect(isAgentSessionRecord(next)).toBe(true) + }) + + it('clears the name via null, deleting the key rather than storing an empty string', () => { + const named = setAgentSessionRecordConversationName( + agentSessionRecordFixture(), + 'Fix the probe', + NOW + ) + + const cleared = setAgentSessionRecordConversationName(named, null, NOW + 1) + + expect(Object.hasOwn(cleared, 'conversationName')).toBe(false) + expect(cleared.updatedAt).toBe(NOW + 1) + expect(isAgentSessionRecord(cleared)).toBe(true) + }) + + it('treats a name that normalizes to nothing as a clear', () => { + const named = setAgentSessionRecordConversationName( + agentSessionRecordFixture(), + 'Fix the probe', + NOW + ) + + expect( + Object.hasOwn( + setAgentSessionRecordConversationName(named, ' ', NOW + 1), + 'conversationName' + ) + ).toBe(false) + }) + + it('returns the same object when the name is unchanged, so no write is provoked', () => { + const named = setAgentSessionRecordConversationName( + agentSessionRecordFixture(), + 'Fix the probe', + NOW + ) + + expect(setAgentSessionRecordConversationName(named, 'Fix the probe', NOW + 1)).toBe(named) + }) + + it('returns the same object when clearing a record that has no name', () => { + const record = agentSessionRecordFixture() + + expect(setAgentSessionRecordConversationName(record, null, NOW)).toBe(record) + }) +}) diff --git a/src/main/runtime/agent-session-record-conversation-name.ts b/src/main/runtime/agent-session-record-conversation-name.ts new file mode 100644 index 00000000000..db4ad25d10a --- /dev/null +++ b/src/main/runtime/agent-session-record-conversation-name.ts @@ -0,0 +1,27 @@ +import { normalizeAgentSessionConversationName } from '../../shared/agent-session-conversation-name' +import type { AgentSessionRecord } from '../../shared/agent-session-record' + +/** + * Set or clear the conversation name on one record. + * + * Deliberately unfenced: the name is a durable note, not ownership, so writing it never contends + * with the writer lease. Normalizing here — the only writer of the field — keeps the record's own + * validator satisfied no matter which caller supplied the text. + */ +export function setAgentSessionRecordConversationName( + record: AgentSessionRecord, + name: string | null, + now: number +): AgentSessionRecord { + const normalized = name === null ? null : normalizeAgentSessionConversationName(name) + if ((record.conversationName ?? null) === normalized) { + return record + } + const next = { ...record, updatedAt: now } + if (normalized === null) { + delete next.conversationName + return next + } + next.conversationName = normalized + return next +} diff --git a/src/main/runtime/agent-session-record-store.ts b/src/main/runtime/agent-session-record-store.ts index 4325410ed81..1bfc9bbcb3c 100644 --- a/src/main/runtime/agent-session-record-store.ts +++ b/src/main/runtime/agent-session-record-store.ts @@ -1,9 +1,9 @@ import { setVisibleSessionId } from './agent-session-visible-tab-index' import { commitConversationCommandRecord } from './agent-session-conversation-command-record' +import { setAgentSessionRecordConversationName } from './agent-session-record-conversation-name' /** Durable single-writer session records and their operation ledger. */ import { - agentSessionOperationKey, settleAgentSessionOperation, type AgentSessionOperationDecision, type AgentSessionOperationOutcome, @@ -51,10 +51,7 @@ import { type AgentSessionReservationProcesslessProof } from './agent-session-processless-reservation' import { - admitPendingAgentSessionReservationReplay, - applyAgentSessionReservation, - evaluateAgentSessionReserveOperation, - requireAgentSessionRecordForReplay, + commitAgentSessionReservation, type AgentSessionReserveRequest, type AgentSessionReserveResult } from './agent-session-reservation-admission' @@ -145,6 +142,13 @@ export class AgentSessionRecordStore { ) } + /** Unfenced on purpose: the name is a durable note, so writing it never contends with the + * writer lease. `null` clears it. */ + setConversationName = (sessionId: string, name: string | null): Promise => + this.mutate(sessionId, (record) => + setAgentSessionRecordConversationName(record, name, Date.now()) + ) + /** A record this build cannot validate: readable as present, never grantable as a writer. */ isSessionUnreadable(sessionId: string): boolean { return this.state.unreadableRecords.has(sessionId) @@ -165,31 +169,10 @@ export class AgentSessionRecordStore { ) } - /** - * Compare-and-swap reservation plus its client-operation row, committed together. A replayed - * operation returns the recorded outcome and never reaches the reservation. - */ async reserveOwner(request: AgentSessionReserveRequest): Promise { - return this.transact(() => { - const decision = evaluateAgentSessionReserveOperation(this.state, request) - if (decision.decision === 'refused') { - throw new Error(decision.code) - } - if (decision.decision === 'replay') { - let record = requireAgentSessionRecordForReplay(this.state, decision.row, request.sessionId) - if (decision.row.outcome.status === 'pending' && request.handoffOperationId !== null) { - record = admitPendingAgentSessionReservationReplay(record, request) - } - return { record, disposition: 'replayed' as const, operationRow: decision.row } - } - const result = applyAgentSessionReservation(this.state, request, AGENT_SESSION_LEASE_TTL_MS) - this.state.operations.set( - agentSessionOperationKey(request.operation.callerKey, request.operation.operationId), - decision.row - ) - this.state.records.set(result.record.sessionId, result.record) - return { ...result, operationRow: decision.row } - }) + return this.transact(() => + commitAgentSessionReservation(this.state, request, AGENT_SESSION_LEASE_TTL_MS) + ) } async commitProcessIdentity( diff --git a/src/main/runtime/agent-session-reservation-admission.ts b/src/main/runtime/agent-session-reservation-admission.ts index 82176a05297..662ea481921 100644 --- a/src/main/runtime/agent-session-reservation-admission.ts +++ b/src/main/runtime/agent-session-reservation-admission.ts @@ -2,11 +2,15 @@ * Reservation admission: what a reserve request means against the persisted state. * * Pure over a store snapshot so the compare-and-swap, the idempotency replay, and the - * location-immutability check can be reasoned about without touching the disk. The store applies - * the result inside one transaction; nothing here mutates. + * location-immutability check can be reasoned about without touching the disk. + * + * `commitAgentSessionReservation` is the one exception and the only writer here: it sequences + * those decisions and applies the winning one to the state it was handed. The store calls it + * inside a transaction, which is what makes the record and its operation row land together. */ import { + agentSessionOperationKey, evaluateAgentSessionOperation, pruneAgentSessionOperationRows, type AgentSessionOperationDecision, @@ -265,3 +269,32 @@ function createAgentSessionRecord( } } } + +/** + * Compare-and-swap reservation plus its client-operation row, committed together. A replayed + * operation returns the recorded outcome and never reaches the reservation. + */ +export function commitAgentSessionReservation( + state: AgentSessionStoreState, + request: AgentSessionReserveRequest, + leaseTtlMs: number +): AgentSessionReserveResult { + const decision = evaluateAgentSessionReserveOperation(state, request) + if (decision.decision === 'refused') { + throw new Error(decision.code) + } + if (decision.decision === 'replay') { + let record = requireAgentSessionRecordForReplay(state, decision.row, request.sessionId) + if (decision.row.outcome.status === 'pending' && request.handoffOperationId !== null) { + record = admitPendingAgentSessionReservationReplay(record, request) + } + return { record, disposition: 'replayed' as const, operationRow: decision.row } + } + const result = applyAgentSessionReservation(state, request, leaseTtlMs) + state.operations.set( + agentSessionOperationKey(request.operation.callerKey, request.operation.operationId), + decision.row + ) + state.records.set(result.record.sessionId, result.record) + return { ...result, operationRow: decision.row } +} diff --git a/src/main/runtime/agent-status-observed-pane-identity.ts b/src/main/runtime/agent-status-observed-pane-identity.ts index 773bddc7f3c..e26929f2090 100644 --- a/src/main/runtime/agent-status-observed-pane-identity.ts +++ b/src/main/runtime/agent-status-observed-pane-identity.ts @@ -3,6 +3,7 @@ import { type AgentStatusRuntimeEnrichment, type ObservedAgentStatusPaneIdentity } from '../ipc/agent-status-ipc-boundary' +import type { EnrichedAgentHookEventPayload } from '../agent-hooks/server/server-types' /** Bounded like the hook server's own per-pane maps; eviction only degrades a row to `unobserved`. */ const MAX_OBSERVED_PANES = 1024 @@ -44,6 +45,30 @@ export class AgentStatusObservedPaneIdentities { } } +/** Buffers startup replay until PTY recovery has restored the runtime identities it fences. */ +export class AgentStatusObservedPaneIdentityCapture { + private readonly pending = new Map() + private runtime: AgentStatusRuntimeEnrichment | null = null + + constructor(private readonly identities: AgentStatusObservedPaneIdentities) {} + + observe(enriched: EnrichedAgentHookEventPayload): void { + if (this.runtime) { + recordObservedAgentStatusPaneIdentity(this.identities, enriched.paneKey, this.runtime) + return + } + this.pending.set(enriched.paneKey, enriched) + } + + attach(runtime: AgentStatusRuntimeEnrichment): void { + this.runtime = runtime + for (const enriched of this.pending.values()) { + recordObservedAgentStatusPaneIdentity(this.identities, enriched.paneKey, runtime) + } + this.pending.clear() + } +} + /** Ingest-time capture: resolve the pane once, as the status arrives, and keep that answer. */ export function recordObservedAgentStatusPaneIdentity( identities: AgentStatusObservedPaneIdentities, diff --git a/src/main/runtime/agent-status-store-wiring.test-fixture.ts b/src/main/runtime/agent-status-store-wiring.test-fixture.ts new file mode 100644 index 00000000000..1f399e0464f --- /dev/null +++ b/src/main/runtime/agent-status-store-wiring.test-fixture.ts @@ -0,0 +1,51 @@ +import { AgentHookServer } from '../agent-hooks/server' +import { installHookStatusSessionTabsRepublish } from '../agent-hooks/hook-status-session-tabs-republish' + +type WiredRuntime = { + getTerminalWorktreeIdForHandle(handle: string): string | null + getTerminalWorktreeIdForPaneKey(paneKey: string): string | null + scheduleMobileSessionTabsAgentStatusHeartbeatForWorktree(worktreeId: string): void + touchMobileSessionTabsForWorktree(worktreeId: string): void +} + +/** + * The agent-status wiring every real host performs, in one place for the runtime specs. + * + * `main-process-runtime-service.ts` and `orcad-entry.ts` both hand the runtime's OSC parse to + * the store, read the listing back out of it, and install the republish signal. A runtime + * constructed without these observes agent status and publishes it nowhere, so a spec that + * exercises OSC 9999 has to compose the same three parts. + */ +export function makeAgentStatusStoreWiring(): { + statusStore: AgentHookServer + deps: { + onTerminalAgentStatus: (event: Parameters[0]) => void + getAgentStatusSnapshot: () => ReturnType + getAgentProviderSessionSnapshot: () => ReturnType + getAgentProviderSessionRowsForPane: ( + paneKey: string + ) => ReturnType + reconcileAgentStatusForEndedProcess: ( + paneKeys: Parameters[0] + ) => void + } + /** Call once the runtime exists; returns the republish teardown. */ + attach: (runtime: WiredRuntime) => () => void +} { + const statusStore = new AgentHookServer() + return { + statusStore, + deps: { + onTerminalAgentStatus: (event) => statusStore.ingestTerminalStatus(event), + getAgentStatusSnapshot: () => + statusStore.getStatusSnapshot().filter((entry) => entry.providerSessionOnly !== true), + getAgentProviderSessionSnapshot: () => statusStore.getStatusSnapshot(), + getAgentProviderSessionRowsForPane: (paneKey) => + statusStore.getStatusSnapshotForPane(paneKey), + reconcileAgentStatusForEndedProcess: (paneKeys) => { + statusStore.reconcileEndedProcessForPaneKeys(paneKeys) + } + }, + attach: (runtime) => installHookStatusSessionTabsRepublish(statusStore, () => runtime) + } +} diff --git a/src/main/runtime/agent-transcript-pane-test-harness.ts b/src/main/runtime/agent-transcript-pane-test-harness.ts new file mode 100644 index 00000000000..4345e98fd93 --- /dev/null +++ b/src/main/runtime/agent-transcript-pane-test-harness.ts @@ -0,0 +1,80 @@ +// One pane builder for every suite that replays a captured agent transcript through the runtime. +import { vi } from 'vitest' +import { OrcaRuntimeService } from './orca-runtime' + +const TRANSCRIPT_PANE_LEAF_ID = '11111111-1111-4111-8111-111111111111' +const TRANSCRIPT_PANE_TAB_ID = 'tab-1' +const TRANSCRIPT_PANE_WORKTREE_ID = 'wt-1' +export const TRANSCRIPT_PANE_PTY_ID = 'pty-1' + +export type TranscriptPaneOptions = { + paneTitle: string + foregroundProcess: string | null + data: string + /** Set for a pane whose PTY lives on an SSH host or WSL distro rather than locally. */ + connectionId?: string + /** Simulates a PTY controller whose foreground probe never settles. */ + foregroundProbeHangs?: boolean + onForegroundProbe?: () => void +} + +export async function createTranscriptPane( + options: TranscriptPaneOptions, + runtimeDeps?: ConstructorParameters[2] +): Promise<{ runtime: OrcaRuntimeService; handle: string }> { + const runtime = new OrcaRuntimeService(null, undefined, runtimeDeps) + const internals = runtime as unknown as { + resolveTerminalWorkspaceLaunchScope: (selector: string) => Promise + } + vi.spyOn(internals, 'resolveTerminalWorkspaceLaunchScope').mockResolvedValue({ + id: TRANSCRIPT_PANE_WORKTREE_ID, + path: '/repo/app', + connectionId: options.connectionId ?? null, + repo: null, + folderWorkspace: null + }) + runtime.setPtyController({ + spawn: vi.fn().mockResolvedValue({ id: TRANSCRIPT_PANE_PTY_ID, incarnationId: 'inc-1' }), + write: () => true, + kill: () => true, + getForegroundProcess: (): Promise => { + options.onForegroundProbe?.() + return options.foregroundProbeHangs === true + ? new Promise(() => {}) + : Promise.resolve(options.foregroundProcess) + } + }) + const terminal = await runtime.createTerminal(`id:${TRANSCRIPT_PANE_WORKTREE_ID}`, { + tabId: TRANSCRIPT_PANE_TAB_ID, + leafId: TRANSCRIPT_PANE_LEAF_ID, + title: 'Terminal' + }) + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: TRANSCRIPT_PANE_TAB_ID, + worktreeId: TRANSCRIPT_PANE_WORKTREE_ID, + title: 'Terminal', + activeLeafId: TRANSCRIPT_PANE_LEAF_ID, + layout: null + } + ], + leaves: [ + { + tabId: TRANSCRIPT_PANE_TAB_ID, + worktreeId: TRANSCRIPT_PANE_WORKTREE_ID, + leafId: TRANSCRIPT_PANE_LEAF_ID, + paneRuntimeId: 1, + ptyId: TRANSCRIPT_PANE_PTY_ID, + paneTitle: options.paneTitle + } + ] + }) + // Why the guard: a restore seed is only applied to a never-written record, so the restore + // cases must not write an empty chunk first. + if (options.data.length > 0) { + runtime.onPtyData(TRANSCRIPT_PANE_PTY_ID, options.data, Date.now()) + } + return { runtime, handle: terminal.handle } +} diff --git a/src/main/runtime/antigravity-readiness-transcripts.test.ts b/src/main/runtime/antigravity-readiness-transcripts.test.ts new file mode 100644 index 00000000000..3ac7707565f --- /dev/null +++ b/src/main/runtime/antigravity-readiness-transcripts.test.ts @@ -0,0 +1,281 @@ +/** + * Pins Antigravity readiness to captured transcripts instead of hand-written fixtures. + * + * Five detector attempts were tuned against a five-line screen someone typed from memory, and + * three of them shipped worse behaviour than the bug they replaced. Nothing here asserts what + * Antigravity prints: the transcripts do. Six are recorded from a live `agy`; the rest name + * themselves as skipped until someone can reach them. + * + * Four cases are pinned as KNOWN DEFECT: on real output the shipped detector refuses the ready + * screen and accepts the live model picker. Those assert what it does, not what it should. + * + * Capture protocol: docs/reference/agent-pty-transcript-capture.md + * What each transcript decides: docs/reference/antigravity-readiness-evidence.md + */ +import { existsSync, readFileSync } from 'node:fs' +import { join } from 'node:path' +import { describe, expect, it, vi } from 'vitest' +import { createTranscriptPane } from './agent-transcript-pane-test-harness' +import { extractLastOscTitle } from '../../shared/osc-title-extraction' + +vi.mock('electron', () => ({ + BrowserWindow: { fromId: vi.fn(() => null) }, + webContents: { fromId: vi.fn(() => null) }, + ipcMain: { on: vi.fn(), removeListener: vi.fn() }, + app: { getPath: vi.fn(() => '/tmp') } +})) + +const FIXTURE_DIR = join(__dirname, '__fixtures__') +const EVIDENCE_DOC = join( + __dirname, + '..', + '..', + '..', + 'docs', + 'reference', + 'antigravity-readiness-evidence.md' +) +// Why asymmetric: a ready verdict has to survive the settle window, while a refusal only has to +// hold for one poll. Keeping the refusal short keeps seven transcripts off the suite's clock. +const READY_TIMEOUT_MS = 2_000 +const REFUSAL_TIMEOUT_MS = 600 +/** Antigravity's binary, as Orca launches and probes it (`tui-agent-config.ts` detectCmd). */ +const ANTIGRAVITY_COMMAND = 'agy' +// String.fromCharCode, not a literal: the formatter rewrites an escape sequence into a raw +// control byte in source, which is unreadable and survives badly in diffs. +const ESC = String.fromCharCode(27) + +type TranscriptCase = { + /** Fixture basename; `.txt` under `__fixtures__/`. */ + name: string + /** Capture in docs/reference/antigravity-readiness-evidence.md. */ + capture: string + what: string + /** What a correct detector must answer. Not what the shipped one answers. */ + expectReady: boolean + /** + * Set where the shipped detector contradicts the transcript. The case then runs inverted, so + * CI pins the defect instead of going permanently red — and flips to failing the moment + * someone fixes it, which is exactly when these expectations need re-reading. + */ + knownDefect?: string +} + +const TRANSCRIPTS: readonly TranscriptCase[] = [ + { + name: 'antigravity-ready-api-key-gemini-model', + capture: 'B', + what: 'ready screen, API-key identity — the account row reads "Gemini API key", not an email', + expectReady: true, + knownDefect: 'refused: the model row never starts a line, the logo shares it' + }, + { + name: 'antigravity-ready-account-info-hidden', + capture: 'B', + what: 'ready screen with AGY_CLI_HIDE_ACCOUNT_INFO=1 — no account row at all', + expectReady: true, + knownDefect: 'refused: same line-start defect, and no account row exists to require' + }, + { + name: 'antigravity-dialog-trust-workspace', + capture: 'C', + what: 'workspace trust dialog owning the screen', + expectReady: false + }, + { + name: 'antigravity-dialog-model-picker', + capture: 'C', + what: 'model picker owning the screen', + expectReady: false, + knownDefect: "accepted: the picker's own `Gemini 3.x Flash` rows satisfy the model rule" + }, + { + name: 'antigravity-dialog-command-palette', + capture: 'C', + what: 'slash-command palette owning the screen', + expectReady: false + }, + { + name: 'antigravity-busy-mid-turn', + capture: 'E', + what: 'mid-turn, spinner live — the pane is working, not waiting for a prompt', + expectReady: false + }, + { + // Expected ready because the turn is over and the composer is back on screen. The captured + // turn ends in a backend error, which is the only ending this account's key can produce. + name: 'antigravity-busy-turn-ended', + capture: 'E', + what: 'the turn has ended and the composer has returned, process still alive', + expectReady: true, + knownDefect: 'refused: the retained tail ends on the error block, with no composer row in it' + }, + { + name: 'antigravity-dialog-dismissed', + capture: 'D', + what: 'the screen immediately after the model picker is dismissed', + expectReady: true, + knownDefect: 'refused: the banner is not reprinted and no model row starts a line' + }, + // Not captured: this machine's agy has no OAuth session and offers only Gemini models, and + // reaching the rest would mean signing the operator out or deleting their config. See + // docs/reference/antigravity-readiness-evidence.md § What could not be captured. + { + name: 'antigravity-ready-business-non-gemini', + capture: 'A', + what: 'ready screen, Business account, non-Gemini model', + expectReady: true + }, + { + name: 'antigravity-dialog-sign-in', + capture: 'C', + what: 'sign-in dialog owning the screen', + expectReady: false + }, + { + name: 'antigravity-dialog-theme-picker', + capture: 'C', + what: 'theme picker owning the screen', + expectReady: false + }, + { + name: 'antigravity-dialog-privacy-notice', + capture: 'C', + what: 'privacy notice owning the screen', + expectReady: false + }, + { + name: 'antigravity-dialog-update-banner', + capture: 'C', + what: 'update banner owning the screen', + expectReady: false + } +] + +function fixturePath(name: string): string { + return join(FIXTURE_DIR, `${name}.txt`) +} + +/** + * A `tui-idle` wait ends three ways, and only one of them is readiness: it resolves satisfied, it + * resolves unsatisfied with a blocked reason, or it rejects with `timeout` because nothing ever + * looked ready. The orchestrator treats the last two identically — no prompt is delivered — so + * they are both `ready: false` here. This is the shape `worker-start` sees. + */ +async function readinessVerdict( + transcript: string, + timeoutMs: number +): Promise<{ ready: boolean; blockedReason: unknown; outcome: string }> { + const { runtime, handle } = await createTranscriptPane({ + // Why the transcript's own title: every attempt guessed at Antigravity's title. A raw + // capture carries the OSC bytes, so the pane wears whatever the CLI actually set. + paneTitle: extractLastOscTitle(transcript) ?? ANTIGRAVITY_COMMAND, + foregroundProcess: ANTIGRAVITY_COMMAND, + data: transcript + }) + try { + const result = (await runtime.waitForTerminal(handle, { + condition: 'tui-idle', + timeoutMs + })) as { satisfied?: boolean; blockedReason?: unknown } + return { + ready: result.satisfied === true, + blockedReason: result.blockedReason ?? null, + outcome: result.satisfied === true ? 'satisfied' : 'unsatisfied' + } + } catch (error) { + return { ready: false, blockedReason: null, outcome: `rejected: ${String(error)}` } + } +} + +describe('Antigravity readiness, decided by captured transcripts', () => { + for (const transcript of TRANSCRIPTS) { + const path = fixturePath(transcript.name) + const captured = existsSync(path) + const label = `capture ${transcript.capture}: ${transcript.what}` + + // A pinned defect asserts what the detector DOES, so CI is honest rather than permanently + // red; fixing the detector flips this case to failing, which is when these expectations + // need re-reading. The correct answer stays in `expectReady` and in the test's name. + const shipped = + transcript.knownDefect === undefined ? transcript.expectReady : !transcript.expectReady + const verdictName = + transcript.knownDefect === undefined + ? `${label} → ${transcript.expectReady ? 'ready' : 'not ready'}` + : `${label} → must be ${transcript.expectReady ? 'ready' : 'not ready'}; KNOWN DEFECT, ${transcript.knownDefect}` + + it.skipIf(!captured)( + verdictName, + async () => { + // A refusal only has to hold for one poll; a ready verdict has to survive the settle + // window. Keeping the refusal short keeps eleven transcripts off the suite's clock. + const verdict = await readinessVerdict( + readFileSync(path, 'utf8'), + transcript.expectReady ? READY_TIMEOUT_MS : REFUSAL_TIMEOUT_MS + ) + // A silent dialog carries no blocked-signal wording, so the assertion is only that Orca + // does not call the pane ready and type a prompt into a dialog that owns the screen. + expect({ ready: verdict.ready, outcome: verdict.outcome }).toMatchObject({ + ready: shipped + }) + }, + READY_TIMEOUT_MS + 10_000 + ) + + it.skipIf(!captured)(`${label} was captured raw, not pasted from a rendered screen`, () => { + const text = readFileSync(path, 'utf8') + // Why: a transcript with no escape bytes went through a terminal's renderer and a + // human's clipboard. It cannot answer what the caret or chrome looked like. + expect(text).toContain(ESC) + }) + } + + it('documents every transcript the detector is allowed to depend on', () => { + // Why a test: the doc is the operator's checklist. A name that drifts out of it is a + // transcript nobody will capture, and a case that silently skips forever. + const doc = readFileSync(EVIDENCE_DOC, 'utf8') + for (const transcript of TRANSCRIPTS) { + expect(doc).toContain(`${transcript.name}.txt`) + } + }) + + it('reports how much evidence exists, so a fully skipped run is visible', () => { + const missing = TRANSCRIPTS.filter( + (transcript) => !existsSync(fixturePath(transcript.name)) + ).map((transcript) => `${transcript.name}.txt`) + if (missing.length > 0) { + console.info( + `Antigravity transcripts: ${TRANSCRIPTS.length - missing.length}/${TRANSCRIPTS.length} captured. Missing: ${missing.join(', ')}` + ) + } + expect(missing.length).toBeLessThanOrEqual(TRANSCRIPTS.length) + }) +}) + +describe('scaffold self-check', () => { + // Why these two live here: when a transcript lands and fails, the failure has to mean the + // capture disagreed with the detector — not that the harness or the timeouts are broken. + // Neither case is evidence about Antigravity; both are shapes the current detector already + // decides, used only to prove the plumbing reaches a verdict. + it('reaches a ready verdict through the harness', async () => { + const verdict = await readinessVerdict( + [ + 'Antigravity CLI 1.0.3', + 'user@example.com (Antigravity Business)', + 'Gemini 3.5 Flash (High)', + '~/orca/workspaces/orca/agy-dispatch-issue', + '>' + ].join('\n'), + READY_TIMEOUT_MS + ) + expect(verdict.ready).toBe(true) + }) + + it('reaches a not-ready verdict through the harness', async () => { + const verdict = await readinessVerdict( + 'Do you trust this workspace directory?\nPress t to trust\n', + REFUSAL_TIMEOUT_MS + ) + expect(verdict.ready).toBe(false) + }) +}) diff --git a/src/main/runtime/device-registry.ts b/src/main/runtime/device-registry.ts index b2d5de8ef41..e3d848405f0 100644 --- a/src/main/runtime/device-registry.ts +++ b/src/main/runtime/device-registry.ts @@ -15,6 +15,10 @@ import { DEVICE_REGISTRY_FILENAME } from './mobile-pairing-files' import type { RelayDeviceBinding } from './relay/relay-revoke-outbox' import type { MobilePairingConnectionMode } from '../../shared/mobile-pairing-connection-mode' import type { RuntimePairingReach } from '../../shared/runtime-pairing-reach' +import { + parseMobilePushRegistration, + type MobilePushRegistration +} from '../../shared/mobile-push-contract' export type { DeviceScope } @@ -30,6 +34,9 @@ export type DeviceEntry = { // Why: STA-2370 — a grant minted for "This computer only" proves nothing about off-host reach when its // client connects, so the bind decision must be able to tell it apart from a LAN/phone grant. pairingReach?: RuntimePairingReach + // Why: survives a desktop restart so the host can keep pushing without the phone + // re-registering. Absent on every registry written before background push existed. + pushRegistration?: MobilePushRegistration } function validRelayBinding(value: unknown, deviceId: string): RelayDeviceBinding | undefined { @@ -179,6 +186,26 @@ export class DeviceRegistry { return true } + /** Passing null clears the registration (unregister, or a token the gateway reported dead). */ + setPushRegistration(deviceId: string, registration: MobilePushRegistration | null): boolean { + const index = this.devices.findIndex((candidate) => candidate.deviceId === deviceId) + if (index === -1 || this.devices[index]?.scope !== 'mobile') { + return false + } + const nextDevices = this.devices.map((device, candidateIndex) => { + if (candidateIndex !== index) { + return device + } + const { pushRegistration: _dropped, ...rest } = device + return registration ? { ...rest, pushRegistration: registration } : rest + }) + // Why: persist before the memory swap so a failed write cannot leave the dispatcher + // pushing to a registration disk says is gone (or vice versa on reload). + this.save(nextDevices) + this.devices = nextDevices + return true + } + setMobilePairingConnectionMode(deviceId: string, mode: MobilePairingConnectionMode): boolean { const index = this.devices.findIndex((candidate) => candidate.deviceId === deviceId) if (index === -1 || this.devices[index]?.scope !== 'mobile') { @@ -297,7 +324,10 @@ export class DeviceRegistry { device.mobilePairingConnectionMode === 'local-only' ? 'local-only' : 'automatic', // Why: registries written before this field existed only ever held network-reach grants (phones and // LAN links), so a missing value must keep binding every interface on reconnect. - pairingReach: device.pairingReach === 'this-computer' ? 'this-computer' : 'network' + pairingReach: device.pairingReach === 'this-computer' ? 'this-computer' : 'network', + // Why: a malformed row must degrade to "no background push", never fail the load + // and strand every paired device. + pushRegistration: parseMobilePushRegistration(device.pushRegistration) })) this.registryUnreadable = false } catch (error) { diff --git a/src/main/runtime/host-challenge-envelope.ts b/src/main/runtime/host-challenge-envelope.ts new file mode 100644 index 00000000000..6a00381c158 --- /dev/null +++ b/src/main/runtime/host-challenge-envelope.ts @@ -0,0 +1,139 @@ +// Why: the relay and the push gateway both authenticate this host with the same +// sealed-box challenge shape (the host keypair is X25519, so it cannot sign). +// Only the domain strings and the transcript fields differ, so the envelope +// handling lives here and each protocol owns its own field validation. +import { createHmac, timingSafeEqual } from 'node:crypto' +import nacl from 'tweetnacl' + +const textEncoder = new TextEncoder() +const textDecoder = new TextDecoder() + +export function decodeCanonicalBase64(value: string, expectedBytes: number): Uint8Array | null { + if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) { + return null + } + const decoded = Buffer.from(value, 'base64') + return decoded.byteLength === expectedBytes && decoded.toString('base64') === value + ? decoded + : null +} + +export function encodeUint64(value: number): Uint8Array { + const bytes = new Uint8Array(8) + new DataView(bytes.buffer).setBigUint64(0, BigInt(value), false) + return bytes +} + +export function equalBytes(left: Uint8Array | undefined, right: Uint8Array): boolean { + return Boolean(left && left.byteLength === right.byteLength && timingSafeEqual(left, right)) +} + +export function encodeText(value: string): Uint8Array { + return textEncoder.encode(value) +} + +/** Length-prefixed field map: u32be(len(name)) || name || u32be(len(value)) || value. */ +export function parseHostChallengeTranscript( + transcript: Uint8Array +): Map | null { + const fields = new Map() + const view = new DataView(transcript.buffer, transcript.byteOffset, transcript.byteLength) + let offset = 0 + try { + while (offset < transcript.byteLength) { + const nameLength = view.getUint32(offset, false) + offset += 4 + const name = textDecoder.decode(transcript.slice(offset, offset + nameLength)) + offset += nameLength + const valueLength = view.getUint32(offset, false) + offset += 4 + if (fields.has(name) || offset + valueLength > transcript.byteLength) { + return null + } + fields.set(name, transcript.slice(offset, offset + valueLength)) + offset += valueLength + } + } catch { + return null + } + return offset === transcript.byteLength ? fields : null +} + +export function readTranscriptUint64(value: Uint8Array | undefined): number | null { + if (!value || value.byteLength !== 8) { + return null + } + const parsed = new DataView(value.buffer, value.byteOffset, value.byteLength).getBigUint64( + 0, + false + ) + return parsed <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(parsed) : null +} + +export type HostChallengeEnvelope = { + transcript: Uint8Array + secret: Uint8Array + peerEphemeralPublicKey: Uint8Array + nonce: Uint8Array +} + +/** + * Opens the sealed challenge and splits out the transcript and the 32-byte secret. + * Returns null for any malformed or undecryptable challenge; the caller still has + * to validate the transcript's fields before answering. + */ +export function openHostChallengeEnvelope(input: { + peerEphemeralPublicKeyB64: string + nonceB64: string + ciphertextB64: string + hostSecretKey: Uint8Array + plaintextDomain: string + /** Reports the failing check by name only; never receives field values. */ + onInvalid?: (reason: string) => void +}): HostChallengeEnvelope | null { + const peerKey = decodeCanonicalBase64(input.peerEphemeralPublicKeyB64, 32) + const nonce = decodeCanonicalBase64(input.nonceB64, 24) + const ciphertext = Buffer.from(input.ciphertextB64, 'base64') + if (!peerKey || !nonce || ciphertext.toString('base64') !== input.ciphertextB64) { + return null + } + const plaintext = nacl.box.open(ciphertext, nonce, peerKey, input.hostSecretKey) + if (!plaintext) { + input.onInvalid?.('challenge-box-open') + return null + } + const domain = textEncoder.encode(`${input.plaintextDomain}\0`) + if ( + !equalBytes(plaintext.slice(0, domain.byteLength), domain) || + plaintext.byteLength < domain.byteLength + 36 + ) { + return null + } + const transcriptLength = new DataView( + plaintext.buffer, + plaintext.byteOffset + domain.byteLength, + 4 + ).getUint32(0, false) + const transcriptStart = domain.byteLength + 4 + const secretStart = transcriptStart + transcriptLength + if (secretStart + 32 !== plaintext.byteLength) { + return null + } + return { + transcript: plaintext.slice(transcriptStart, secretStart), + secret: plaintext.slice(secretStart), + peerEphemeralPublicKey: peerKey, + nonce + } +} + +export function hostChallengeAckProof(input: { + secret: Uint8Array + transcript: Uint8Array + proofDomain: string +}): string { + return createHmac('sha256', input.secret) + .update(textEncoder.encode(`${input.proofDomain}\0ack\0`)) + .update(input.transcript) + .digest('base64') +} diff --git a/src/main/runtime/mobile-agent-status-permission-renewal.test.ts b/src/main/runtime/mobile-agent-status-permission-renewal.test.ts index 9b7f0ef457d..a802844d826 100644 --- a/src/main/runtime/mobile-agent-status-permission-renewal.test.ts +++ b/src/main/runtime/mobile-agent-status-permission-renewal.test.ts @@ -92,6 +92,18 @@ describe('mobile/paired projection for a pane pending a human answer', () => { expect(out?.state).toBe('done') }) + it('does not let replay delivery time make old working evidence outrank a newer title', () => { + const hookAt = Date.now() - 1_000 + const replayedAt = Date.now() + const out = renewFromPtyTitle()( + { ...claudeStatus('working', replayedAt), evidenceObservedAt: hookAt }, + parkedOnPromptPty(hookAt), + { preserveQuestionUnderShellTitle: true } + ) + + expect(out?.state).toBe('done') + }) + // Why: an idle title is the ABSENCE of activity evidence, so it cannot outrank the hook. // A `working` title is positive evidence the agent resumed, which does — otherwise a // finished turn's question card would linger into the next working interval (#11761). diff --git a/src/main/runtime/mobile-notification-dismissal-read-failure.test.ts b/src/main/runtime/mobile-notification-dismissal-read-failure.test.ts new file mode 100644 index 00000000000..a665e9b4444 --- /dev/null +++ b/src/main/runtime/mobile-notification-dismissal-read-failure.test.ts @@ -0,0 +1,38 @@ +import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import type * as fs from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, vi } from 'vitest' +import { MobileNotificationDismissalStore } from './mobile-notification-dismissal-store' +vi.mock('node:fs', async (original) => { + const f = await original() + return { ...f, readFileSync: vi.fn(f.readFileSync) } +}) +it('preserves dismissal history after EIO', () => { + const dir = mkdtempSync(join(tmpdir(), 'push-comment-')) + try { + const store = new MobileNotificationDismissalStore(dir) + store.record({ + type: 'dismiss', + notificationId: 'old', + notificationEpoch: 'epoch', + notificationSeq: 1 + }) + const path = join(dir, 'mobile-notification-dismissals.json') + const before = readFileSync(path, 'utf8') + vi.mocked(readFileSync).mockImplementationOnce(() => { + throw Object.assign(new Error('read failed'), { code: 'EIO' }) + }) + const restarted = new MobileNotificationDismissalStore(dir) + restarted.record({ + type: 'dismiss', + notificationId: 'new', + notificationEpoch: 'epoch', + notificationSeq: 2 + }) + expect(readFileSync(path, 'utf8')).toBe(before) + } finally { + vi.restoreAllMocks() + rmSync(dir, { recursive: true, force: true }) + } +}) diff --git a/src/main/runtime/mobile-notification-dismissal-store.test.ts b/src/main/runtime/mobile-notification-dismissal-store.test.ts new file mode 100644 index 00000000000..7679c55d31d --- /dev/null +++ b/src/main/runtime/mobile-notification-dismissal-store.test.ts @@ -0,0 +1,57 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it, vi } from 'vitest' +import { MobileNotificationDismissalStore } from './mobile-notification-dismissal-store' +const paths: string[] = [] +afterEach(() => { + paths.splice(0).forEach((path) => rmSync(path, { recursive: true, force: true })) + vi.restoreAllMocks() +}) +function fixture() { + const path = mkdtempSync(join(tmpdir(), 'orca-dismissals-')) + paths.push(path) + return { path, store: new MobileNotificationDismissalStore(path) } +} +const shown = { notificationId: 'same', notificationEpoch: 'old', notificationSeq: 12 } +const alert = { + type: 'notification' as const, + source: 'terminal-bell' as const, + title: 'QA', + body: '' +} +it('reconciles an old delivered alert after desktop restart and preserves unrelated identities', () => { + const h = fixture() + h.store.record({ ...alert, ...shown }) + const restarted = new MobileNotificationDismissalStore(h.path) + restarted.record({ + type: 'dismiss', + notificationId: 'same', + notificationEpoch: 'new', + notificationSeq: 1 + }) + const loaded = new MobileNotificationDismissalStore(h.path) + expect( + loaded.reconcile([ + shown, + { ...shown, notificationEpoch: 'other' }, + { ...shown, notificationId: 'other' }, + { ...shown, notificationSeq: 13 } + ]) + ).toEqual([shown]) +}) +it('does not dismiss a newer replacement and does not treat missing or expired history as dismissal', () => { + const h = fixture() + const now = Date.now() + vi.spyOn(Date, 'now').mockReturnValue(now) + h.store.record({ ...alert, ...shown }) + h.store.record({ type: 'dismiss', ...shown, notificationSeq: 13 }) + expect(h.store.reconcile([shown])).toEqual([shown]) + h.store.record({ ...alert, ...shown, notificationSeq: 14 }) + expect(h.store.reconcile([{ ...shown, notificationSeq: 14 }])).toEqual([]) + expect(h.store.reconcile([shown])).toEqual([shown]) + h.store.record({ type: 'dismiss', ...shown, notificationSeq: 15 }) + vi.mocked(Date.now).mockReturnValue(now + 7 * 86400_000) + expect(h.store.reconcile([shown])).toEqual([]) + expect(new MobileNotificationDismissalStore(`${h.path}-unknown`).reconcile([shown])).toEqual([]) +}) diff --git a/src/main/runtime/mobile-notification-dismissal-store.ts b/src/main/runtime/mobile-notification-dismissal-store.ts new file mode 100644 index 00000000000..984a8c9a1e0 --- /dev/null +++ b/src/main/runtime/mobile-notification-dismissal-store.ts @@ -0,0 +1,114 @@ +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { + writeSecureJsonFile, + hardenExistingSecureFile, + isUnreadableError +} from '../../shared/secure-file' +import type { MobileNotificationEvent } from './runtime-mobile-notification-controller' + +export type DeliveredNotificationIdentity = { + notificationId: string + notificationEpoch: string + notificationSeq: number +} +type RecordEntry = DeliveredNotificationIdentity & { dismissedThrough: number; expiresAt: number } +const LIMIT = 4096 +const RETENTION_MS = 7 * 86400_000 + +export class MobileNotificationDismissalStore { + private readonly path: string + private entries: RecordEntry[] = [] + private unreadable = false + constructor(userDataPath: string) { + this.path = join(userDataPath, 'mobile-notification-dismissals.json') + try { + hardenExistingSecureFile(this.path) + const value: unknown = JSON.parse(readFileSync(this.path, 'utf8')) + if (Array.isArray(value)) { + this.entries = value.filter(isEntry).slice(-LIMIT) + } + } catch (error) { + this.unreadable = isUnreadableError(error) + // Missing history cannot establish that a delivered alert was dismissed. + } + } + + record( + event: MobileNotificationEvent & { notificationEpoch: string; notificationSeq: number } + ): void { + if (!event.notificationId) { + return + } + const now = Date.now() + const kept = this.entries.filter((entry) => entry.expiresAt > now) + const same = (entry: RecordEntry) => + entry.notificationId === event.notificationId && + entry.notificationEpoch === event.notificationEpoch + let next: RecordEntry[] + if (event.type === 'notification') { + next = [ + ...kept.filter((entry) => !same(entry)), + { + notificationId: event.notificationId, + notificationEpoch: event.notificationEpoch, + notificationSeq: event.notificationSeq, + dismissedThrough: kept.find(same)?.dismissedThrough ?? -1, + expiresAt: now + RETENTION_MS + } + ] + } else { + next = kept + .filter((entry) => !same(entry)) + .map((entry) => + entry.notificationId === event.notificationId + ? { ...entry, dismissedThrough: entry.notificationSeq, expiresAt: now + RETENTION_MS } + : entry + ) + next.push({ + notificationId: event.notificationId, + notificationEpoch: event.notificationEpoch, + notificationSeq: event.notificationSeq, + dismissedThrough: event.notificationSeq, + expiresAt: now + RETENTION_MS + }) + } + next = next.slice(-LIMIT) + if (!this.unreadable) { + writeSecureJsonFile(this.path, next) + } + this.entries = next + } + + reconcile(delivered: readonly DeliveredNotificationIdentity[]): DeliveredNotificationIdentity[] { + const now = Date.now() + return delivered.filter((item) => + this.entries.some( + (entry) => + entry.dismissedThrough >= 0 && + entry.expiresAt > now && + entry.notificationId === item.notificationId && + entry.notificationEpoch === item.notificationEpoch && + entry.dismissedThrough >= item.notificationSeq + ) + ) + } +} + +function isEntry(value: unknown): value is RecordEntry { + if (!value || typeof value !== 'object') { + return false + } + const item = value as RecordEntry + return ( + typeof item.notificationId === 'string' && + item.notificationId.length > 0 && + typeof item.notificationEpoch === 'string' && + item.notificationEpoch.length > 0 && + Number.isSafeInteger(item.notificationSeq) && + item.notificationSeq >= 0 && + Number.isSafeInteger(item.dismissedThrough) && + item.dismissedThrough >= -1 && + Number.isFinite(item.expiresAt) + ) +} diff --git a/src/main/runtime/mobile-session-tabs-agent-status-heartbeat.test.ts b/src/main/runtime/mobile-session-tabs-agent-status-heartbeat.test.ts index 582837826ac..416cb2fdf46 100644 --- a/src/main/runtime/mobile-session-tabs-agent-status-heartbeat.test.ts +++ b/src/main/runtime/mobile-session-tabs-agent-status-heartbeat.test.ts @@ -189,4 +189,19 @@ describe('mobile session-tabs agent-status heartbeat', () => { expect(emitted).toEqual([]) expect(vi.getTimerCount()).toBe(0) }) + + it('keeps a direct status heartbeat queued when an unrelated PTY is removed', () => { + const emitted: string[] = [] + const heartbeat = createMobileSessionTabsAgentStatusHeartbeat( + () => [], + (worktreeId) => emitted.push(worktreeId) + ) + + heartbeat.scheduleWorktreeHeartbeat('worktree-1') + heartbeat.removePty('unrelated-pty') + vi.runAllTimers() + + expect(emitted).toEqual(['worktree-1']) + heartbeat.dispose() + }) }) diff --git a/src/main/runtime/mobile-session-tabs-agent-status-heartbeat.ts b/src/main/runtime/mobile-session-tabs-agent-status-heartbeat.ts index 6c80cf4a35d..df457c6bb27 100644 --- a/src/main/runtime/mobile-session-tabs-agent-status-heartbeat.ts +++ b/src/main/runtime/mobile-session-tabs-agent-status-heartbeat.ts @@ -6,7 +6,9 @@ export const SESSION_TABS_AGENT_STATUS_HEARTBEAT_SPACING_MS = 50 export type MobileSessionTabsAgentStatusHeartbeat = { observeSemanticTitle: (ptyId: string) => void + observeWorktreeRefresh: (worktreeId: string) => void scheduleDecorativeHeartbeat: (ptyId: string) => void + scheduleWorktreeHeartbeat: (worktreeId: string) => void removePty: (ptyId: string) => void removeWorktree: (worktreeId: string) => void cancelPending: () => void @@ -19,7 +21,7 @@ export function createMobileSessionTabsAgentStatusHeartbeat( ): MobileSessionTabsAgentStatusHeartbeat { const lastEligibilityCheckAtByPtyId = new Map() const lastRefreshAtByWorktreeId = new Map() - const pendingPtyIdsByWorktreeId = new Map>() + const pendingByWorktreeId = new Map }>() let lastGlobalHeartbeatAt: number | null = null let timer: ReturnType | null = null @@ -30,8 +32,16 @@ export function createMobileSessionTabsAgentStatusHeartbeat( } } + const observeWorktreeRefresh = (worktreeId: string, observedAt = Date.now()): void => { + lastRefreshAtByWorktreeId.set(worktreeId, observedAt) + pendingByWorktreeId.delete(worktreeId) + if (pendingByWorktreeId.size === 0) { + clearTimer() + } + } + const arm = (): void => { - if (timer !== null || pendingPtyIdsByWorktreeId.size === 0) { + if (timer !== null || pendingByWorktreeId.size === 0) { return } const now = Date.now() @@ -44,15 +54,15 @@ export function createMobileSessionTabsAgentStatusHeartbeat( ) timer = setTimeout(() => { timer = null - const worktreeId = pendingPtyIdsByWorktreeId.keys().next().value + const worktreeId = pendingByWorktreeId.keys().next().value if (typeof worktreeId !== 'string') { return } - const pendingPtyIds = pendingPtyIdsByWorktreeId.get(worktreeId) - pendingPtyIdsByWorktreeId.delete(worktreeId) + const pending = pendingByWorktreeId.get(worktreeId) + pendingByWorktreeId.delete(worktreeId) const emittedAt = Date.now() lastRefreshAtByWorktreeId.set(worktreeId, emittedAt) - for (const ptyId of pendingPtyIds ?? []) { + for (const ptyId of pending?.ptyIds ?? []) { lastEligibilityCheckAtByPtyId.set(ptyId, emittedAt) } lastGlobalHeartbeatAt = emittedAt @@ -64,18 +74,37 @@ export function createMobileSessionTabsAgentStatusHeartbeat( } } + const scheduleWorktreeHeartbeat = (worktreeId: string, ptyId?: string): void => { + const now = Date.now() + const lastRefreshAt = lastRefreshAtByWorktreeId.get(worktreeId) + if ( + lastRefreshAt !== undefined && + now - lastRefreshAt < SESSION_TABS_AGENT_STATUS_HEARTBEAT_INTERVAL_MS + ) { + return + } + const pending = pendingByWorktreeId.get(worktreeId) ?? { + directObservation: false, + ptyIds: new Set() + } + if (ptyId) { + pending.ptyIds.add(ptyId) + } else { + pending.directObservation = true + } + pendingByWorktreeId.set(worktreeId, pending) + arm() + } + return { observeSemanticTitle(ptyId: string): void { const observedAt = Date.now() lastEligibilityCheckAtByPtyId.set(ptyId, observedAt) for (const worktreeId of resolveWorktreeIds(ptyId)) { - lastRefreshAtByWorktreeId.set(worktreeId, observedAt) - pendingPtyIdsByWorktreeId.delete(worktreeId) - } - if (pendingPtyIdsByWorktreeId.size === 0) { - clearTimer() + observeWorktreeRefresh(worktreeId, observedAt) } }, + observeWorktreeRefresh, scheduleDecorativeHeartbeat(ptyId: string): void { const now = Date.now() const lastEligibilityCheckAt = lastEligibilityCheckAtByPtyId.get(ptyId) @@ -87,44 +116,36 @@ export function createMobileSessionTabsAgentStatusHeartbeat( } lastEligibilityCheckAtByPtyId.set(ptyId, now) for (const worktreeId of resolveWorktreeIds(ptyId)) { - const lastRefreshAt = lastRefreshAtByWorktreeId.get(worktreeId) - if ( - lastRefreshAt === undefined || - now - lastRefreshAt >= SESSION_TABS_AGENT_STATUS_HEARTBEAT_INTERVAL_MS - ) { - const pendingPtyIds = pendingPtyIdsByWorktreeId.get(worktreeId) ?? new Set() - pendingPtyIds.add(ptyId) - pendingPtyIdsByWorktreeId.set(worktreeId, pendingPtyIds) - } + scheduleWorktreeHeartbeat(worktreeId, ptyId) } - arm() }, + scheduleWorktreeHeartbeat, removePty(ptyId: string): void { lastEligibilityCheckAtByPtyId.delete(ptyId) - for (const [worktreeId, pendingPtyIds] of pendingPtyIdsByWorktreeId) { - pendingPtyIds.delete(ptyId) - if (pendingPtyIds.size === 0) { - pendingPtyIdsByWorktreeId.delete(worktreeId) + for (const [worktreeId, pending] of pendingByWorktreeId) { + pending.ptyIds.delete(ptyId) + if (pending.ptyIds.size === 0 && !pending.directObservation) { + pendingByWorktreeId.delete(worktreeId) } } - if (pendingPtyIdsByWorktreeId.size === 0) { + if (pendingByWorktreeId.size === 0) { clearTimer() } }, removeWorktree(worktreeId: string): void { lastRefreshAtByWorktreeId.delete(worktreeId) - pendingPtyIdsByWorktreeId.delete(worktreeId) - if (pendingPtyIdsByWorktreeId.size === 0) { + pendingByWorktreeId.delete(worktreeId) + if (pendingByWorktreeId.size === 0) { clearTimer() } }, cancelPending(): void { clearTimer() - pendingPtyIdsByWorktreeId.clear() + pendingByWorktreeId.clear() }, dispose(): void { clearTimer() - pendingPtyIdsByWorktreeId.clear() + pendingByWorktreeId.clear() lastEligibilityCheckAtByPtyId.clear() lastRefreshAtByWorktreeId.clear() lastGlobalHeartbeatAt = null diff --git a/src/main/runtime/orca-runtime-apply-tracked-pty-title.ts b/src/main/runtime/orca-runtime-apply-tracked-pty-title.ts index 605eacdbe29..6d7e59c383f 100644 --- a/src/main/runtime/orca-runtime-apply-tracked-pty-title.ts +++ b/src/main/runtime/orca-runtime-apply-tracked-pty-title.ts @@ -173,8 +173,8 @@ export class OrcaRuntimeWithApplyTrackedPtyTitle extends OrcaRuntimeWithGetUnper leaf.waitBlockedAt = null leaf.tailWaitState = undefined } + this.reconcileAgentStatusForEndedProcessFn?.(this.collectAgentStatusPaneKeysForPty(ptyId)) this.primeWaitBlockedBaselineFromSeededTail(ptyId) - this.clearAgentRowSnapshotsForPty(ptyId) } protected setTerminalSideEffectConsumerAvailable(available: boolean): void { diff --git a/src/main/runtime/orca-runtime-bind-pty-incarnation-handle.ts b/src/main/runtime/orca-runtime-bind-pty-incarnation-handle.ts index 69f9be4ba85..3f1a79beb77 100644 --- a/src/main/runtime/orca-runtime-bind-pty-incarnation-handle.ts +++ b/src/main/runtime/orca-runtime-bind-pty-incarnation-handle.ts @@ -55,7 +55,7 @@ export class OrcaRuntimeWithBindPtyIncarnationHandle extends OrcaRuntimeWithBuil const pty = this.ptysById.get(ptyId) const leaves = this.getLeavesForPty(ptyId) if ( - !pty?.incarnationId || + !pty || pty.incarnationId !== retained.incarnationId || leaves.length !== 1 || this.handleByPtyId.has(ptyId) @@ -91,6 +91,10 @@ export class OrcaRuntimeWithBindPtyIncarnationHandle extends OrcaRuntimeWithBuil } protected issuePtyHandle(pty: RuntimePtyWorktreeRecord): string { + const retained = this.handleByPtyIncarnation.get(pty.ptyId) + if (retained?.incarnationId === pty.incarnationId) { + return retained.handle + } const existingHandle = this.handleByPtyId.get(pty.ptyId) ?? this.findHandleForPtyRecord(pty.ptyId) if (existingHandle) { diff --git a/src/main/runtime/orca-runtime-build-pty-terminal-summary.ts b/src/main/runtime/orca-runtime-build-pty-terminal-summary.ts index d781bd2ae90..615353bbc13 100644 --- a/src/main/runtime/orca-runtime-build-pty-terminal-summary.ts +++ b/src/main/runtime/orca-runtime-build-pty-terminal-summary.ts @@ -173,7 +173,7 @@ export class OrcaRuntimeWithBuildPtyTerminalSummary extends OrcaRuntimeWithGetPt ptyGeneration: leaf.ptyGeneration }) this.handleByLeafKey.set(leafKey, handle) - if (leaf.ptyId && incarnationId) { + if (leaf.ptyId) { this.handleByPtyIncarnation.set(leaf.ptyId, { handle, incarnationId, leafKey }) } return handle diff --git a/src/main/runtime/orca-runtime-create-terminal-side-effect-command-code-detector.ts b/src/main/runtime/orca-runtime-create-terminal-side-effect-command-code-detector.ts index 9a9a6c1c146..5486e953989 100644 --- a/src/main/runtime/orca-runtime-create-terminal-side-effect-command-code-detector.ts +++ b/src/main/runtime/orca-runtime-create-terminal-side-effect-command-code-detector.ts @@ -11,7 +11,6 @@ import { splitWorktreeIdForFilesystem } from '../../shared/worktree/id' import { isWindowsAbsolutePathLike } from '../../shared/cross-platform-path' import type { ProcessedAgentStatusChunk } from '../../shared/agent-status-osc' import { mapExplicitAgentStateToRuntimeTerminalStatus } from './runtime-worktree-status-projection' -import type { ParsedAgentStatusPayload } from '../../shared/agent-status-types' export class OrcaRuntimeWithCreateTerminalSideEffectCommandCodeDetector extends OrcaRuntimeWithApplyTrackedPtyTitle { protected createTerminalSideEffectCommandCodeDetector( @@ -86,17 +85,9 @@ export class OrcaRuntimeWithCreateTerminalSideEffectCommandCodeDetector extends return worktreePath && isWindowsAbsolutePathLike(worktreePath) ? 'win32' : 'posix' } - /** Returns true when any retained agent-row snapshot changed in a - * client-visible way, so the caller can republish session snapshots. */ - protected emitTerminalAgentStatusEvents( - ptyId: string, - chunk: ProcessedAgentStatusChunk - ): boolean { - // Why: snapshot retention (for mobile worktree.ps) must run even when no - // renderer listener is attached, so we don't early-return on a missing - // onTerminalAgentStatus — only the per-target emit below is gated on it. + protected emitTerminalAgentStatusEvents(ptyId: string, chunk: ProcessedAgentStatusChunk): void { if (chunk.payloads.length === 0) { - return false + return } const targets = new Map< string, @@ -106,6 +97,7 @@ export class OrcaRuntimeWithCreateTerminalSideEffectCommandCodeDetector extends tabId?: string worktreeId?: string connectionId?: string | null + terminalHandle?: string } >() const pty = this.ptysById.get(ptyId) @@ -129,22 +121,24 @@ export class OrcaRuntimeWithCreateTerminalSideEffectCommandCodeDetector extends connectionId }) } - let retainedChanged = false + // Why once per chunk and not per payload: the same lookup the renderer-facing IPC boundary + // runs, and it is the pane's only durable join back to its terminal once the pane key moves. + if (this.onTerminalAgentStatus) { + for (const target of targets.values()) { + const terminalHandle = this.getAgentStatusTerminalHandleForPaneKey(target.paneKey) + if (terminalHandle) { + target.terminalHandle = terminalHandle + } + } + } for (const payload of chunk.payloads) { + // Why not gated on a listener: the prompt lifecycle is main's own state, read by + // terminal waits that run with no status consumer attached. this.recordAgentPromptLifecycleState( ptyId, mapExplicitAgentStateToRuntimeTerminalStatus(payload.state) ) for (const target of targets.values()) { - retainedChanged = - this.retainAgentRowSnapshot( - ptyId, - target.paneKey, - target.worktreeId, - target.tabId, - target.connectionId ?? null, - payload - ) || retainedChanged if (!this.onTerminalAgentStatus) { continue } @@ -165,28 +159,5 @@ export class OrcaRuntimeWithCreateTerminalSideEffectCommandCodeDetector extends } } } - return retainedChanged - } - - protected retainAgentRowSnapshot( - ptyId: string, - paneKey: string, - worktreeId: string | undefined, - tabId: string | undefined, - connectionId: string | null, - payload: ParsedAgentStatusPayload - ): boolean { - return this.agentRows.retain({ - ptyId, - paneKey, - worktreeId, - tabId, - connectionId, - payload - }) - } - - protected clearAgentRowSnapshotsForPty(ptyId: string): void { - this.agentRows.clearPty(ptyId) } } diff --git a/src/main/runtime/orca-runtime-fit-override-listeners.ts b/src/main/runtime/orca-runtime-fit-override-listeners.ts index 63adb867d55..5ef17ce4c2e 100644 --- a/src/main/runtime/orca-runtime-fit-override-listeners.ts +++ b/src/main/runtime/orca-runtime-fit-override-listeners.ts @@ -13,7 +13,6 @@ import type { TerminalKittyKeyboardModeTracker } from '../../shared/terminal-kit import type { PtyProviderBufferSnapshot } from '../providers/types' import type { WaitBlockedCheckState } from './wait-blocked-check-state' import type { createAgentStatusOscProcessor } from '../../shared/agent-status-osc' -import { RuntimeAgentRowStore } from './runtime-agent-row-store' import { RuntimeTerminalViewSubscribers } from './runtime-terminal-view-subscribers' import { parseAppSshPtyId } from '../../shared/ssh-pty-id' @@ -125,11 +124,6 @@ export class OrcaRuntimeWithFitOverrideListeners extends OrcaRuntimeWithStopRequ protected terminalFileUriHostnameByPtyId = new Map() - // Why: latest agent-status payload per pane, retained so worktree.ps can serve - // mobile the same inline agent rows the desktop sidebar renders. Cleared on pty - // teardown so dead agents don't linger. See RuntimeAgentRowSnapshot. - protected readonly agentRows = new RuntimeAgentRowStore() - // Why: per-PTY hydration state guards against double-hydration. Keys: // 'pending' → maybeHydrateHeadlessFromRenderer is in flight // 'done' → hydration completed (success or skip); never run again diff --git a/src/main/runtime/orca-runtime-get-orchestration-dispatch-authority.ts b/src/main/runtime/orca-runtime-get-orchestration-dispatch-authority.ts index 14345d10a77..d61374c3466 100644 --- a/src/main/runtime/orca-runtime-get-orchestration-dispatch-authority.ts +++ b/src/main/runtime/orca-runtime-get-orchestration-dispatch-authority.ts @@ -2,7 +2,12 @@ import { OrcaRuntimeWithVerifyOrchestrationCompatibilityCaller } from './orca-runtime-verify-orchestration-compatibility-caller' import type { OrchestrationCompatibilityTerminalAuthority } from './runtime-terminal-contracts' import { createHash } from 'node:crypto' -import { isTerminalLeafId, makePaneKey, parsePaneKey } from '../../shared/stable-pane-id' +import { + isTerminalLeafId, + makePaneKey, + parseLegacyNumericPaneKey, + parsePaneKey +} from '../../shared/stable-pane-id' import { isValidTerminalTabId } from '../../shared/terminal-tab-id' import { RECENT_PTY_OUTPUT_LIMIT, RecentPtyOutputBuffer } from './recent-pty-output-buffer' import { appendRecentPtyPathCandidates } from './terminal-output-path-candidates' @@ -38,6 +43,30 @@ export class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends OrcaRuntim return paneKeys } + /** Status cleanup also owns runtime-admitted legacy OSC rows; orchestration authority does not. */ + protected collectAgentStatusPaneKeysForPty(ptyId: string): Set { + const paneKeys = this.collectPaneKeysForPty(ptyId) + const terminalHandles = new Set(this.getExistingTerminalHandlesForPtyId(ptyId)) + // The provider-session snapshot is the unfiltered store view, so certified exit can also + // retire a dismissed row's identity-only remnant after its pane binding moved. + for (const row of this.getAgentProviderSessionSnapshotFn?.() ?? []) { + if (row.terminalHandle && terminalHandles.has(row.terminalHandle)) { + paneKeys.add(row.paneKey) + } + } + const ptyPaneKey = this.ptysById.get(ptyId)?.paneKey + if (ptyPaneKey && parseLegacyNumericPaneKey(ptyPaneKey)) { + paneKeys.add(ptyPaneKey) + } + for (const leaf of this.getLeavesForPty(ptyId)) { + const paneKey = this.makeRuntimePaneKey(leaf) + if (parseLegacyNumericPaneKey(paneKey)) { + paneKeys.add(paneKey) + } + } + return paneKeys + } + getOrchestrationDispatchAuthority( terminalHandle: string ): OrchestrationCompatibilityTerminalAuthority | null { diff --git a/src/main/runtime/orca-runtime-get-pty-record-for-pane-key.ts b/src/main/runtime/orca-runtime-get-pty-record-for-pane-key.ts index 0c41b176d34..27012bdf8e9 100644 --- a/src/main/runtime/orca-runtime-get-pty-record-for-pane-key.ts +++ b/src/main/runtime/orca-runtime-get-pty-record-for-pane-key.ts @@ -64,7 +64,7 @@ export class OrcaRuntimeWithGetPtyRecordForPaneKey extends OrcaRuntimeWithPruneM return makePaneKey(record.tabId, record.leafId) } - protected getWorktreeIdForTerminalHandle(handle: string): string | null { + getTerminalWorktreeIdForHandle(handle: string): string | null { const livePty = this.getLivePtyForHandle(handle) if (livePty?.pty.worktreeId) { return livePty.pty.worktreeId diff --git a/src/main/runtime/orca-runtime-get-worktree-ps.ts b/src/main/runtime/orca-runtime-get-worktree-ps.ts index ade25ad1975..3eb7a6e9401 100644 --- a/src/main/runtime/orca-runtime-get-worktree-ps.ts +++ b/src/main/runtime/orca-runtime-get-worktree-ps.ts @@ -96,6 +96,7 @@ export class OrcaRuntimeWithGetWorktreePs extends OrcaRuntimeWithStructuredAgent missingIds: missingRuntimeWorktreeIds, ptysById: this.ptysById, tabs: this.tabs, + getTerminalHandlesForPty: (ptyId) => this.getExistingTerminalHandlesForPtyId(ptyId), getSummary: (summaryMap, pathIndex, missingIds, worktreeId) => this.getSummaryForRuntimeWorktreeId(summaryMap, pathIndex, missingIds, worktreeId) }) @@ -107,7 +108,6 @@ export class OrcaRuntimeWithGetWorktreePs extends OrcaRuntimeWithStructuredAgent rowSources: collectRuntimeWorktreeAgentSources({ mirroredWorktreeIdByTabId, connectedPtyEvidence, - retainedSnapshots: this.agentRows.values(), // Structured sessions are in here too: the host publishes them into the same store. hookSnapshots: this.getAgentStatusSnapshotFn?.() ?? [] }), diff --git a/src/main/runtime/orca-runtime-has-terminals-for-worktree.ts b/src/main/runtime/orca-runtime-has-terminals-for-worktree.ts index 77082530ed2..ebedfb362fc 100644 --- a/src/main/runtime/orca-runtime-has-terminals-for-worktree.ts +++ b/src/main/runtime/orca-runtime-has-terminals-for-worktree.ts @@ -55,6 +55,12 @@ export class OrcaRuntimeWithHasTerminalsForWorktree extends OrcaRuntimeWithStopE const revision = this.graphReloadLifecycle.begin(windowId) this.setTerminalSideEffectConsumerAvailable(false) this.rememberDetachedPreAllocatedLeaves() + // A null incarnation is safe within one graph diff, but cannot prove a same-id PTY survived a renderer reload. + for (const [ptyId, retained] of this.handleByPtyIncarnation) { + if (retained.incarnationId === null) { + this.invalidatePtyIncarnationHandle(ptyId) + } + } const retainedHandles = new Set([ ...this.handleByPtyId.values(), ...[...this.handleByPtyIncarnation.values()].map((record) => record.handle) diff --git a/src/main/runtime/orca-runtime-hook-agent-status-projection.test.ts b/src/main/runtime/orca-runtime-hook-agent-status-projection.test.ts index f8171862728..9fab2267d25 100644 --- a/src/main/runtime/orca-runtime-hook-agent-status-projection.test.ts +++ b/src/main/runtime/orca-runtime-hook-agent-status-projection.test.ts @@ -2,6 +2,7 @@ // live agent state, so `session.tabs` must project the hook row's status fields — not // just its identity — while still refusing rows that only prove an agent once existed. import { describe, expect, it, vi } from 'vitest' +import { makeAgentStatusStoreWiring } from './agent-status-store-wiring.test-fixture' import { OrcaRuntimeService } from './orca-runtime' import { AGENT_STATUS_STALE_AFTER_MS } from '../../shared/agent-status-types' import type { AgentStatusIpcPayload } from '../../shared/agent-status-types' @@ -58,11 +59,25 @@ function hookRow(overrides: Partial = {}): AgentStatusIpc } async function createRuntimeWithHookRows( - rows: AgentStatusIpcPayload[] + rows: AgentStatusIpcPayload[], + /** Pass a store to exercise the OSC producer; otherwise the rows stand in for it. */ + statusWiring?: ReturnType ): Promise { + const readRows = statusWiring + ? (): AgentStatusIpcPayload[] => [...rows, ...statusWiring.deps.getAgentStatusSnapshot()] + : (): AgentStatusIpcPayload[] => rows const runtime = new OrcaRuntimeService(null, undefined, { - getAgentStatusSnapshot: () => rows, - getAgentProviderSessionRowsForPane: () => rows + ...(statusWiring + ? { + onTerminalAgentStatus: statusWiring.deps.onTerminalAgentStatus, + reconcileAgentStatusForEndedProcess: + statusWiring.deps.reconcileAgentStatusForEndedProcess, + getAgentProviderSessionSnapshot: statusWiring.deps.getAgentProviderSessionSnapshot, + getAgentProviderSessionRowsForPane: statusWiring.deps.getAgentProviderSessionRowsForPane + } + : {}), + getAgentStatusSnapshot: readRows, + ...(statusWiring ? {} : { getAgentProviderSessionRowsForPane: readRows }) }) const internals = runtime as unknown as { resolveTerminalWorkspaceLaunchScope: (selector: string) => Promise @@ -224,8 +239,18 @@ describe('headless hook agent-status projection (#11761)', () => { }) // #7970: a retained OSC 9999 row is the pane's own report and keeps precedence. - it('prefers a retained OSC 9999 row over the hook row', async () => { - const runtime = await createRuntimeWithHookRows([hookRow()]) + it('projects the OSC turn that replaced the hook row in the store', async () => { + // One store: an OSC turn is a write, not a competing copy, so the pane projects whatever + // the store holds now rather than a reader-side preference between two rows. + const statusWiring = makeAgentStatusStoreWiring() + statusWiring.statusStore.ingestTerminalStatus({ + paneKey: PANE_KEY, + tabId: TAB_ID, + worktreeId: WORKTREE_ID, + connectionId: null, + payload: { state: 'waiting', prompt: 'Tabs or spaces?', agentType: 'claude' } + }) + const runtime = await createRuntimeWithHookRows([], statusWiring) runtime.onPtyData( PTY_ID, '\x1b]9999;{"state":"working","prompt":"fix the tests","agentType":"claude"}\x07', @@ -310,6 +335,124 @@ describe('headless hook agent-status projection (#11761)', () => { expect(tab?.type === 'terminal' && tab.agentStatus).not.toHaveProperty('interactivePrompt') }) + it('evicts the predecessor row at a certified provider generation reset', async () => { + const statusWiring = makeAgentStatusStoreWiring() + const runtime = await createRuntimeWithHookRows([], statusWiring) + runtime.onPtyData( + PTY_ID, + '\x1b]9999;{"state":"working","prompt":"predecessor","agentType":"claude"}\x07', + 1 + ) + expect(statusWiring.statusStore.getStatusSnapshot()).toHaveLength(1) + + const internals = runtime as unknown as { + resetTrackedTerminalStateForProviderGeneration: (ptyId: string) => void + } + internals.resetTrackedTerminalStateForProviderGeneration(PTY_ID) + + expect(statusWiring.statusStore.getStatusSnapshot()).toEqual([]) + statusWiring.statusStore.stop() + }) + + it('evicts a row joined only through the terminal handle on certified PTY exit', async () => { + const statusWiring = makeAgentStatusStoreWiring() + const runtime = await createRuntimeWithHookRows([], statusWiring) + const terminal = (await runtime.listTerminals()).terminals[0] + if (!terminal) { + throw new Error('expected a live terminal') + } + const priorPaneKey = makePaneKey('prior-tab', UNKNOWN_LEAF_ID) + statusWiring.statusStore.ingestTerminalStatus({ + paneKey: priorPaneKey, + tabId: 'prior-tab', + terminalHandle: terminal.handle, + payload: { state: 'working', prompt: 'prior pane', agentType: 'claude' } + }) + expect(statusWiring.statusStore.getStatusSnapshot()).toHaveLength(1) + + runtime.onPtyExit(PTY_ID, 0) + + expect(statusWiring.statusStore.getStatusSnapshot()).toEqual([]) + statusWiring.statusStore.stop() + }) + + it('evicts the central status row when a disconnected PTY record is pruned', async () => { + const statusWiring = makeAgentStatusStoreWiring() + const runtime = await createRuntimeWithHookRows([], statusWiring) + runtime.onPtyData( + PTY_ID, + '\x1b]9999;{"state":"working","prompt":"before prune","agentType":"claude"}\x07', + 1 + ) + expect(statusWiring.statusStore.getStatusSnapshot()).toHaveLength(1) + + const internals = runtime as unknown as { + dropDisconnectedPtyRecord: (ptyId: string) => void + } + internals.dropDisconnectedPtyRecord(PTY_ID) + + expect(statusWiring.statusStore.getStatusSnapshot()).toEqual([]) + statusWiring.statusStore.stop() + }) + + it('keeps an unverifiable remote row when its disconnected PTY record is pruned', async () => { + const statusWiring = makeAgentStatusStoreWiring() + const runtime = await createRuntimeWithHookRows([], statusWiring) + const internals = runtime as unknown as { + ptysById: Map + dropDisconnectedPtyRecord: (ptyId: string) => void + } + const pty = internals.ptysById.get(PTY_ID)! + pty.connectionId = 'ssh-target' + runtime.onPtyData( + PTY_ID, + '\x1b]9999;{"state":"working","prompt":"remote work","agentType":"claude"}\x07', + 1 + ) + pty.connected = false + + internals.dropDisconnectedPtyRecord(PTY_ID) + + expect(statusWiring.statusStore.getStatusSnapshot()).toEqual([ + expect.objectContaining({ connectionId: 'ssh-target', prompt: 'remote work' }) + ]) + statusWiring.statusStore.stop() + }) + + it('evicts a dismissed handle-joined remnant on certified PTY exit', async () => { + const statusWiring = makeAgentStatusStoreWiring() + const runtime = await createRuntimeWithHookRows([], statusWiring) + const terminal = (await runtime.listTerminals()).terminals[0] + if (!terminal) { + throw new Error('expected a live terminal') + } + const priorPaneKey = makePaneKey('prior-tab', UNKNOWN_LEAF_ID) + statusWiring.statusStore.ingestTerminalStatus({ + paneKey: priorPaneKey, + tabId: 'prior-tab', + terminalHandle: terminal.handle, + payload: { state: 'working', prompt: 'dismissed pane', agentType: 'claude' } + }) + statusWiring.statusStore.ingestRemote( + { + paneKey: priorPaneKey, + tabId: 'prior-tab', + providerSession: PROVIDER_SESSION, + payload: { state: 'working', prompt: 'dismissed pane', agentType: 'claude' } + }, + null + ) + statusWiring.statusStore.dropStatusEntry(priorPaneKey) + expect(statusWiring.statusStore.getStatusSnapshot()).toEqual([ + expect.objectContaining({ paneKey: priorPaneKey, providerSessionOnly: true }) + ]) + + runtime.onPtyExit(PTY_ID, 0) + + expect(statusWiring.statusStore.getStatusSnapshot()).toEqual([]) + statusWiring.statusStore.stop() + }) + it('does not carry a hook question across an identity-only owner title', async () => { const runtime = await createRuntimeWithHookRows([hookRow()]) const internals = runtime as unknown as { diff --git a/src/main/runtime/orca-runtime-on-pty-data.ts b/src/main/runtime/orca-runtime-on-pty-data.ts index 5d27da94c14..df384980fef 100644 --- a/src/main/runtime/orca-runtime-on-pty-data.ts +++ b/src/main/runtime/orca-runtime-on-pty-data.ts @@ -211,7 +211,6 @@ export class OrcaRuntimeWithOnPtyData extends OrcaRuntimeWithPreparePtyExecution } titleTrackerEntry.applyingChunk = true titleTrackerEntry.chunkTouchedSessionTabs = false - let retainedAgentStatusChanged = false try { for (const payload of agentStatusChunk.payloads) { titleTrackerEntry.pendingFacts.push({ kind: 'agent-status', payload }) @@ -230,7 +229,7 @@ export class OrcaRuntimeWithOnPtyData extends OrcaRuntimeWithPreparePtyExecution // Why: per-chunk cross-channel contract order is status → titles → // bell — the chunk's agentStatus:set events must reach the renderer // before its pty:sideEffect batch. - retainedAgentStatusChanged = this.emitTerminalAgentStatusEvents(ptyId, agentStatusChunk) + this.emitTerminalAgentStatusEvents(ptyId, agentStatusChunk) const lastPayloadTitleOffset = agentStatusChunk.lastPayloadCleanOffset === null ? null @@ -242,10 +241,10 @@ export class OrcaRuntimeWithOnPtyData extends OrcaRuntimeWithPreparePtyExecution this.flushPendingTerminalSideEffectFacts(ptyId, titleTrackerEntry) } } - // Why: hook (OSC 9999) transitions often arrive without a title change, so - // headless-serve snapshots would never republish and paired remote clients - // kept the stale agent state until the next title change (#7970). - if (titleTrackerEntry.chunkTouchedSessionTabs || retainedAgentStatusChanged) { + // Why only the title arm here: an OSC 9999 transition republishes off the store's own + // change signal (installHookStatusSessionTabsRepublish), which sees hook and OSC rows + // alike — a second per-chunk republish would only re-emit the same snapshot version. + if (titleTrackerEntry.chunkTouchedSessionTabs) { this.touchMobileSessionSnapshotsForPty(ptyId) } diff --git a/src/main/runtime/orca-runtime-on-pty-exit.ts b/src/main/runtime/orca-runtime-on-pty-exit.ts index 7d3626d4ef0..6ddf877f87c 100644 --- a/src/main/runtime/orca-runtime-on-pty-exit.ts +++ b/src/main/runtime/orca-runtime-on-pty-exit.ts @@ -47,7 +47,7 @@ export class OrcaRuntimeWithOnPtyExit extends OrcaRuntimeWithOnClientDisconnecte options.hostExitConfirmed !== true // Why: collect before retirePtyAgentLaunchAuthority, which deletes the restored-authority // receipt a receipt-only pane's key comes from. - const exitPaneKeys = this.collectPaneKeysForPty(ptyId) + const exitPaneKeys = this.collectAgentStatusPaneKeysForPty(ptyId) if (preservesAbnormalSshSurface) { const prior = this.ptyLivenessVerdictByPtyId.get(ptyId)?.verdict this.rememberPtyLivenessVerdict(ptyId, { @@ -153,7 +153,6 @@ export class OrcaRuntimeWithOnPtyExit extends OrcaRuntimeWithOnClientDisconnecte this.terminalCwdByPtyId.delete(ptyId) this.terminalFileUriHostnameByPtyId.delete(ptyId) this.wslDistroByPtyId.delete(ptyId) - this.clearAgentRowSnapshotsForPty(ptyId) // Why: a Claude agent-team leader whose PTY exits naturally (agent finished, // process died, renderer reload) must release its team + nested panes map. // Previously only explicit closeTerminal evicted it, so natural exits leaked diff --git a/src/main/runtime/orca-runtime-prune-mobile-session-tab-group-layout.ts b/src/main/runtime/orca-runtime-prune-mobile-session-tab-group-layout.ts index 2c704205b93..4a910f02451 100644 --- a/src/main/runtime/orca-runtime-prune-mobile-session-tab-group-layout.ts +++ b/src/main/runtime/orca-runtime-prune-mobile-session-tab-group-layout.ts @@ -1,4 +1,5 @@ // @ts-nocheck -- mechanically split from OrcaRuntimeService; behavior is covered by AST equivalence and characterization tests. +import { selectFreshAgentRowForMobileTab } from './runtime-hook-agent-row-selection' import { OrcaRuntimeWithScheduleMobileSessionTabsChanged } from './orca-runtime-schedule-mobile-session-tabs-changed' import type { TabGroupLayoutNode } from '../../shared/tab-types' import type { @@ -93,11 +94,12 @@ export class OrcaRuntimeWithPruneMobileSessionTabGroupLayout extends OrcaRuntime getLiveBrowserTabs: (worktreeId) => this.getLiveBrowserTabsByPageId(worktreeId), getProviderSessionRows: (paneKey) => this.getAgentProviderSessionRowsForPaneFn?.(paneKey), getProviderSessionSnapshot: () => this.getAgentProviderSessionSnapshotFn?.() ?? [], + getStatusSnapshot: () => this.getAgentStatusSnapshotFn?.() ?? [], getLeafKey: (tabId, leafId) => this.getLeafKey(tabId, leafId), findPty: (worktreeId, tab, options) => this.findPtyForMobileTerminalTab(worktreeId, tab, options), - getRetainedStatus: (paneKey, pty, tab) => - this.getFreshRetainedAgentStatusForMobileTab(paneKey, pty, tab), + getRetainedStatus: (paneKey, pty, tab, getRows) => + this.getFreshRetainedAgentStatusForMobileTab(paneKey, pty, tab, getRows), getTrackedTitle: (ptyId) => this.getUnpersistedTrackedTitleForPty(ptyId), issuePtyHandle: (pty) => this.issuePtyHandle(pty), recordPty: (ptyId, worktreeId, state) => this.recordPtyWorktree(ptyId, worktreeId, state), @@ -128,9 +130,30 @@ export class OrcaRuntimeWithPruneMobileSessionTabGroupLayout extends OrcaRuntime protected getFreshRetainedAgentStatusForMobileTab( paneKey: string, pty: RuntimePtyWorktreeRecord | null, - tab: RuntimeMobileSessionTerminalTab + _tab: RuntimeMobileSessionTerminalTab, + getRows: (paneKey: string, terminalHandle: string | null) => AgentStatusIpcPayload[] ): RuntimeAgentRowSnapshot | null { - return this.agentRows.getFreshForMobile(paneKey, pty, tab) + const paneMatch = selectFreshAgentRowForMobileTab({ + paneKey, + terminalHandle: null, + hookRows: getRows(paneKey, null) + }) + if (paneMatch || !pty) { + return paneMatch + } + // Why: the OSC producer can stamp a leaf or incarnation handle; use the same non-minting + // inventory as worktree.ps so a tab-id remint can rejoin the still-live central row. + for (const terminalHandle of this.getExistingTerminalHandlesForPtyId(pty.ptyId)) { + const handleMatch = selectFreshAgentRowForMobileTab({ + paneKey, + terminalHandle, + hookRows: getRows(paneKey, terminalHandle) + }) + if (handleMatch) { + return handleMatch + } + } + return null } protected findPtyForMobileTerminalTab( diff --git a/src/main/runtime/orca-runtime-pty-foreground-process-reads.ts b/src/main/runtime/orca-runtime-pty-foreground-process-reads.ts index a7e10247fed..84161b64789 100644 --- a/src/main/runtime/orca-runtime-pty-foreground-process-reads.ts +++ b/src/main/runtime/orca-runtime-pty-foreground-process-reads.ts @@ -149,13 +149,17 @@ export class OrcaRuntimeWithPtyForegroundProcessReads extends OrcaRuntimeWithSta ...(allowUnverifiedStop ? { allowUnverifiedStop: true } : {}), ...(connectionId ? { includeLocalRegistry: false } : {}) }) + // Structured sessions are counted here too, mirroring the IPC path: closing a user's chat is + // now an ordinary outcome of this verb, and a removal that closed one but no PTY logged nothing. + const structuredStopped = teardownResult.structuredStopped ?? 0 const total = teardownResult.runtimeStopped + teardownResult.providerStopped + - teardownResult.registryStopped + teardownResult.registryStopped + + structuredStopped if (total > 0) { console.info( - `[worktree-teardown] ${worktreeId} killed runtime=${teardownResult.runtimeStopped} provider=${teardownResult.providerStopped} registry=${teardownResult.registryStopped}` + `[worktree-teardown] ${worktreeId} killed runtime=${teardownResult.runtimeStopped} provider=${teardownResult.providerStopped} registry=${teardownResult.registryStopped} structured=${structuredStopped}` ) } } diff --git a/src/main/runtime/orca-runtime-refresh-floating-workspace-pty-liveness.ts b/src/main/runtime/orca-runtime-refresh-floating-workspace-pty-liveness.ts index e9871f24c75..de98831cdd5 100644 --- a/src/main/runtime/orca-runtime-refresh-floating-workspace-pty-liveness.ts +++ b/src/main/runtime/orca-runtime-refresh-floating-workspace-pty-liveness.ts @@ -119,6 +119,14 @@ export class OrcaRuntimeWithRefreshFloatingWorkspacePtyLiveness extends OrcaRunt protected dropDisconnectedPtyRecord(ptyId: string): void { // Why: pruning can remove a PTY without the normal exit callback. + const pty = this.ptysById.get(ptyId) + // Remote disconnect is unverifiable; its host-owned status survives until certified exit. + const processDeathCertified = + pty?.connectionId === null || + this.ptyLivenessVerdictByPtyId.get(ptyId)?.verdict.status === 'exited' + if (processDeathCertified) { + this.reconcileAgentStatusForEndedProcessFn?.(this.collectAgentStatusPaneKeysForPty(ptyId)) + } this.advancePtyLifecycleGeneration(ptyId) this.pairedRendererSessionOwnedPtyIds.delete(ptyId) this.ptysById.delete(ptyId) @@ -145,7 +153,6 @@ export class OrcaRuntimeWithRefreshFloatingWorkspacePtyLiveness extends OrcaRunt this.terminalCwdByPtyId.delete(ptyId) this.terminalFileUriHostnameByPtyId.delete(ptyId) this.wslDistroByPtyId.delete(ptyId) - this.clearAgentRowSnapshotsForPty(ptyId) const handle = this.handleByPtyId.get(ptyId) if (handle) { // Why: pruning can remove a PTY without onPtyExit firing; release this leader's agent team so it doesn't leak. diff --git a/src/main/runtime/orca-runtime-serialize-agent-prompt-submission.ts b/src/main/runtime/orca-runtime-serialize-agent-prompt-submission.ts index 81696fe4739..1e321bc7584 100644 --- a/src/main/runtime/orca-runtime-serialize-agent-prompt-submission.ts +++ b/src/main/runtime/orca-runtime-serialize-agent-prompt-submission.ts @@ -1,4 +1,5 @@ // @ts-nocheck -- mechanically split from OrcaRuntimeService; behavior is covered by AST equivalence and characterization tests. +import { selectFreshExplicitAgentStatus } from './runtime-hook-agent-row-selection' import { OrcaRuntimeWithControllerKnowsPtyIsLive } from './orca-runtime-controller-knows-pty-is-live' import type { RuntimeTerminalAgentStatus } from '../../shared/runtime-types' import type { RuntimeTerminalAgentStatusSnapshot } from './runtime-terminal-agent-status-query' @@ -181,7 +182,7 @@ export class OrcaRuntimeWithSerializeAgentPromptSubmission extends OrcaRuntimeWi updatedAt: number stateStartedAt: number } | null { - return this.agentRows.getFreshExplicit({ + return selectFreshExplicitAgentStatus({ handle, paneKey: paneKeyOverride ?? this.getPaneKeyForTerminalHandle(handle), hookRows: this.getAgentStatusSnapshotFn?.() ?? [] diff --git a/src/main/runtime/orca-runtime-stop-exact-terminals-for-worktree.ts b/src/main/runtime/orca-runtime-stop-exact-terminals-for-worktree.ts index be54620fde3..a96ae64e596 100644 --- a/src/main/runtime/orca-runtime-stop-exact-terminals-for-worktree.ts +++ b/src/main/runtime/orca-runtime-stop-exact-terminals-for-worktree.ts @@ -123,14 +123,11 @@ export class OrcaRuntimeWithStopExactTerminalsForWorktree extends OrcaRuntimeWit } protected getTerminalHandlesForPtyId(ptyId: string): string[] { - const handles = new Set( - this.getLeavesForPty(ptyId) - .filter((candidate) => candidate.connected) - .map((leaf) => this.issueHandle(leaf)) - ) - const runtimeHandle = this.handleByPtyId.get(ptyId) - if (runtimeHandle) { - handles.add(runtimeHandle) + const handles = new Set(this.getExistingTerminalHandlesForPtyId(ptyId)) + for (const handle of this.getLeavesForPty(ptyId) + .filter((candidate) => candidate.connected) + .map((leaf) => this.issueHandle(leaf))) { + handles.add(handle) } const pty = this.getOrCreatePtyWorktreeRecord(ptyId) if (!pty) { @@ -142,6 +139,23 @@ export class OrcaRuntimeWithStopExactTerminalsForWorktree extends OrcaRuntimeWit return [...handles].sort() } + protected getExistingTerminalHandlesForPtyId(ptyId: string): string[] { + const handles = new Set( + this.getLeavesForPty(ptyId) + .map((leaf) => this.handleByLeafKey.get(this.getLeafKey(leaf.tabId, leaf.leafId))) + .filter((handle): handle is string => handle !== undefined) + ) + const runtimeHandle = this.handleByPtyId.get(ptyId) + if (runtimeHandle) { + handles.add(runtimeHandle) + } + const incarnationHandle = this.handleByPtyIncarnation.get(ptyId)?.handle + if (incarnationHandle) { + handles.add(incarnationHandle) + } + return [...handles].sort() + } + protected getRecordedTerminalSleepHandles( ptyIds: Iterable, terminalHandlesByPtyId: Readonly> diff --git a/src/main/runtime/orca-runtime-stop-requested-pty-ids.ts b/src/main/runtime/orca-runtime-stop-requested-pty-ids.ts index a3785adb2bb..c7f883fcfcb 100644 --- a/src/main/runtime/orca-runtime-stop-requested-pty-ids.ts +++ b/src/main/runtime/orca-runtime-stop-requested-pty-ids.ts @@ -107,7 +107,7 @@ export class OrcaRuntimeWithStopRequestedPtyIds extends OrcaRuntimeWithRuntimeId issueLeafHandle: (leaf) => this.issueHandle(leaf), issuePtyHandle: (pty) => this.issuePtyHandle(pty), makePaneKey: (leaf) => this.makeRuntimePaneKey(leaf), - getWorktreeId: (handle) => this.getWorktreeIdForTerminalHandle(handle), + getWorktreeId: (handle) => this.getTerminalWorktreeIdForHandle(handle), getHandleForPaneKey: (paneKey) => this.getTerminalHandleForPaneKey(paneKey), getPaneKey: (handle) => this.getPaneKeyForTerminalHandle(handle), getDispatchAuthority: (handle) => this.getOrchestrationDispatchAuthority(handle), diff --git a/src/main/runtime/orca-runtime-tail-wait-memo.test.ts b/src/main/runtime/orca-runtime-tail-wait-memo.test.ts index f61431b7b86..5ce8d9710cd 100644 --- a/src/main/runtime/orca-runtime-tail-wait-memo.test.ts +++ b/src/main/runtime/orca-runtime-tail-wait-memo.test.ts @@ -134,7 +134,7 @@ describe('onPtyData tail wait memoization', () => { '' ) expect(blocked.fromTail).toBe(true) - expect(blocked.signal?.reason).toBe('codex-update-prompt') + expect(blocked.signal?.reason).toBe('agent-update-prompt') }) it('does not rebuild or repeatedly scan an ordinary saturated tail', () => { diff --git a/src/main/runtime/orca-runtime-tests/agent-status-and-waits.spec.ts b/src/main/runtime/orca-runtime-tests/agent-status-and-waits.spec.ts index 6fed887e741..23312f49420 100644 --- a/src/main/runtime/orca-runtime-tests/agent-status-and-waits.spec.ts +++ b/src/main/runtime/orca-runtime-tests/agent-status-and-waits.spec.ts @@ -41,6 +41,8 @@ describe('OrcaRuntimeService', () => { tabId: spawnedEnv.ORCA_TAB_ID, worktreeId: TEST_WORKTREE_ID, connectionId: null, + // The pane's handle rides the event so the store's row can rejoin its terminal. + terminalHandle: expect.stringMatching(/^term_/), payload: { state: 'done', prompt: 'ok' @@ -247,7 +249,7 @@ describe('OrcaRuntimeService', () => { runtime.waitForTerminal(terminal.handle, { condition: 'tui-idle', timeoutMs: 1_000 }) ).resolves.toMatchObject({ satisfied: false, - blockedReason: 'codex-interactive-prompt' + blockedReason: 'agent-interactive-prompt' }) }) diff --git a/src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts b/src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts index 4de568618cc..b9bb63fcea8 100644 --- a/src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts +++ b/src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts @@ -598,6 +598,8 @@ describe('OrcaRuntimeService', () => { tabId: 'tab-1', worktreeId: TEST_WORKTREE_ID, connectionId: null, + // The pane's handle rides the event so the store's row can rejoin its terminal. + terminalHandle: expect.stringMatching(/^term_/), payload: { state: 'working', prompt: 'ship it', diff --git a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts index 65de777139f..518d6805c5b 100644 --- a/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts +++ b/src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts @@ -1,4 +1,5 @@ import { describe, expect, it, vi } from 'vitest' +import type { AgentStatusIpcPayload } from '../../../shared/agent-status-types' import { OrcaRuntimeService, electronMocks } from '../orca-runtime-test-mocks.spec' import { HEADLESS_LEAF_ID, @@ -284,7 +285,11 @@ describe('OrcaRuntimeService', () => { const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession( makeWorkspaceSessionWithHeadlessTerminal() ) - const runtime = new OrcaRuntimeService(runtimeStore as never) + let rows: AgentStatusIpcPayload[] = [] + const runtime = new OrcaRuntimeService(runtimeStore as never, undefined, { + getAgentStatusSnapshot: () => rows, + getAgentProviderSessionRowsForPane: () => [] + }) runtime.setPtyController({ write: () => true, kill: () => true, @@ -293,7 +298,27 @@ describe('OrcaRuntimeService', () => { { id: 'persisted-pty', cwd: TEST_WORKTREE_PATH, title: 'Unrelated PTY' } ] }) + runtime.registerPty('persisted-pty', TEST_WORKTREE_ID, null, { + tabId: 'other-tab', + leafId: '99999999-9999-4999-8999-999999999999' + }) runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) + const unrelatedPty = runtime['ptysById'].get('persisted-pty')! + const unrelatedHandle = runtime['issuePtyHandle'](unrelatedPty) + rows = [ + { + paneKey: 'other-tab:99999999-9999-4999-8999-999999999999', + tabId: 'other-tab', + worktreeId: TEST_WORKTREE_ID, + terminalHandle: unrelatedHandle, + connectionId: null, + state: 'working', + prompt: 'unrelated task', + agentType: 'codex', + receivedAt: Date.now(), + stateStartedAt: Date.now() + } + ] const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) @@ -304,6 +329,45 @@ describe('OrcaRuntimeService', () => { status: 'pending-handle', terminal: null }) + expect(listed.tabs[0]).not.toHaveProperty('agentStatus') + }) + + it('reads and indexes the full agent-status snapshot once per mobile projection', async () => { + const tabCount = 20 + const session = makeWorkspaceSessionWithHeadlessTerminal() + const tabs = Array.from({ length: tabCount }, (_, index) => ({ + ...session.tabsByWorktree[TEST_WORKTREE_ID]![0]!, + id: `host-tab-${index}`, + ptyId: `missing-pty-${index}` + })) + const terminalLayoutsByTabId = Object.fromEntries( + tabs.map((tab, index) => [ + tab.id, + makeHeadlessTerminalLayout({ [HEADLESS_LEAF_ID]: `missing-pty-${index}` }) + ]) + ) + const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession({ + ...session, + tabsByWorktree: { [TEST_WORKTREE_ID]: tabs }, + terminalLayoutsByTabId + }) + const getAgentStatusSnapshot = vi.fn(() => []) + const runtime = new OrcaRuntimeService(runtimeStore as never, undefined, { + getAgentStatusSnapshot, + getAgentProviderSessionRowsForPane: () => [] + }) + runtime.setPtyController({ + write: () => true, + kill: () => true, + getForegroundProcess: async () => null, + listProcesses: async () => [] + }) + runtime.syncWindowGraph(0, { tabs: [], leaves: [] }) + + const listed = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) + + expect(listed.tabs).toHaveLength(tabCount) + expect(getAgentStatusSnapshot).toHaveBeenCalledOnce() }) it('kills persisted SSH PTYs when closing hydrated headless tabs before pane metadata is restored', async () => { diff --git a/src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts index bd39e91e460..58fa4ae750b 100644 --- a/src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts +++ b/src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts @@ -1,4 +1,5 @@ import { describe, expect, it, vi } from 'vitest' +import { makeAgentStatusStoreWiring } from '../agent-status-store-wiring.test-fixture' import { AGENT_STATUS_STALE_AFTER_MS, MOCK_GIT_WORKTREES, @@ -254,23 +255,18 @@ describe('OrcaRuntimeService', () => { }) it('keeps a fresh OSC row when the cached hook row for the same pane is older', async () => { - const now = Date.now() const leafId = '44444444-4444-4444-8444-444444444444' const paneKey = `tab-1:${leafId}` - const runtime = new OrcaRuntimeService(store, undefined, { - getAgentStatusSnapshot: () => [ - { - paneKey, - worktreeId: TEST_WORKTREE_ID, - tabId: 'tab-1', - state: 'working', - prompt: 'stale hook row', - agentType: 'claude', - connectionId: null, - receivedAt: now - AGENT_STATUS_STALE_AFTER_MS - 1, - stateStartedAt: now - AGENT_STATUS_STALE_AFTER_MS - 100 - } - ] + const statusWiring = makeAgentStatusStoreWiring() + const runtime = new OrcaRuntimeService(store, undefined, statusWiring.deps) + statusWiring.statusStore.ingestTerminalStatus({ + paneKey, + tabId: 'tab-1', + worktreeId: TEST_WORKTREE_ID, + connectionId: null, + // Same agent as the OSC turn below: the store resolves pane identity itself, and a + // cross-agent flip inside the inheritance window is a different rule's subject. + payload: { state: 'working', prompt: 'earlier hook row', agentType: 'codex' } }) runtime.attachWindow(1) runtime.syncWindowGraph(1, { @@ -567,15 +563,19 @@ describe('OrcaRuntimeService', () => { ]) }) - it('keeps a retained OSC row via its connected PTY after the pane binding is cleared', async () => { + it('keeps an OSC row via its connected PTY after the pane binding is cleared', async () => { // A controller incarnation change nulls pty.tabId/paneKey while the PTY - // stays connected (adoptControllerTerminalHandle); the ptyId conjunct is - // then the only rescue for the retained OSC row. + // stays connected (adoptControllerTerminalHandle); the terminal handle the row was + // stamped with is then the only rescue left for it. const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession({ ...getDefaultWorkspaceSession(), tabsByWorktree: {} }) - const runtime = new OrcaRuntimeService(runtimeStore as never) + const runtime = new OrcaRuntimeService( + runtimeStore as never, + undefined, + makeAgentStatusStoreWiring().deps + ) runtime['recordPtyWorktree']('osc-pty', TEST_WORKTREE_ID, { connected: true, tabId: 'osc-tab', @@ -604,21 +604,8 @@ describe('OrcaRuntimeService', () => { ...getDefaultWorkspaceSession(), tabsByWorktree: {} }) - const runtime = new OrcaRuntimeService(runtimeStore as never, undefined, { - getAgentStatusSnapshot: () => [ - { - paneKey, - worktreeId: TEST_WORKTREE_ID, - tabId: 'race-tab', - state: 'working', - prompt: 'hook-fresh agent', - agentType: 'codex', - connectionId: null, - receivedAt: Date.now() + 60_000, - stateStartedAt: Date.now() - 100 - } - ] - }) + const statusWiring = makeAgentStatusStoreWiring() + const runtime = new OrcaRuntimeService(runtimeStore as never, undefined, statusWiring.deps) runtime['recordPtyWorktree']('race-pty', TEST_WORKTREE_ID, { connected: true, tabId: 'race-tab', @@ -629,6 +616,13 @@ describe('OrcaRuntimeService', () => { '\x1b]9999;{"state":"working","prompt":"osc ping","agentType":"codex"}\x07', 1 ) + statusWiring.statusStore.ingestTerminalStatus({ + paneKey, + tabId: 'race-tab', + worktreeId: TEST_WORKTREE_ID, + connectionId: null, + payload: { state: 'working', prompt: 'hook-fresh agent', agentType: 'codex' } + }) const pty = runtime['ptysById'].get('race-pty')! pty.tabId = null pty.paneKey = null diff --git a/src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts index d1f60e8cda7..b82e5863c2e 100644 --- a/src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts +++ b/src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts @@ -1,4 +1,5 @@ import { describe, expect, it, vi } from 'vitest' +import { makeAgentStatusStoreWiring } from '../agent-status-store-wiring.test-fixture' import { OrcaRuntimeService, getDefaultWorkspaceSession, @@ -17,14 +18,18 @@ import { } from '../orca-runtime-test-fixtures.spec' describe('OrcaRuntimeService', () => { - it('keeps a retained OSC row from an SSH pane after its PTY disconnects', async () => { + it('keeps an OSC row from an SSH pane after its PTY disconnects', async () => { // Why: OSC snapshots must carry the pane transport; hardcoding local would // strip the SSH exemption off rows whose freshest update arrived via OSC. const { runtimeStore } = makeRuntimeStoreWithWorkspaceSession({ ...getDefaultWorkspaceSession(), tabsByWorktree: {} }) - const runtime = new OrcaRuntimeService(runtimeStore as never) + const runtime = new OrcaRuntimeService( + runtimeStore as never, + undefined, + makeAgentStatusStoreWiring().deps + ) runtime['recordPtyWorktree']('ssh-osc-pty', TEST_WORKTREE_ID, { connected: true, connectionId: 'ssh-osc-1', diff --git a/src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts index 60bd9086e56..64ad592209b 100644 --- a/src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts +++ b/src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts @@ -1,4 +1,5 @@ import { describe, expect, it, vi } from 'vitest' +import { makeAgentStatusStoreWiring } from '../agent-status-store-wiring.test-fixture' import { OrcaRuntimeService, listWorktrees } from '../orca-runtime-test-mocks.spec' import { HEADLESS_LEAF_ID, @@ -386,7 +387,7 @@ describe('OrcaRuntimeService', () => { }) it('attaches inline agent rows from the latest OSC 9999 status', async () => { - const runtime = new OrcaRuntimeService(store) + const runtime = new OrcaRuntimeService(store, undefined, makeAgentStatusStoreWiring().deps) const leafId = '22222222-2222-4222-8222-222222222222' runtime.attachWindow(1) runtime.syncWindowGraph(1, { @@ -611,24 +612,37 @@ describe('OrcaRuntimeService', () => { ]) }) it('does not carry hook monitoring mode into a newer OSC turn', async () => { - const now = Date.now() - const runtime = new OrcaRuntimeService(store, undefined, { - getAgentStatusSnapshot: () => [ + // One store, so the newer turn simply replaces the monitoring row; nothing reconciles them. + const leafId = '55555555-5555-4555-8555-555555555555' + const statusWiring = makeAgentStatusStoreWiring() + const runtime = new OrcaRuntimeService(store, undefined, statusWiring.deps) + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { + tabs: [ { - paneKey: 'tab-1:1', - worktreeId: TEST_WORKTREE_ID, tabId: 'tab-1', - state: 'working', - workingMode: 'monitoring', - prompt: 'watch tests', - agentType: 'claude', - connectionId: null, - receivedAt: now - 100, - stateStartedAt: now - 200 + worktreeId: TEST_WORKTREE_ID, + title: 'Claude', + activeLeafId: leafId, + layout: null } + ], + leaves: [ + { tabId: 'tab-1', worktreeId: TEST_WORKTREE_ID, leafId, paneRuntimeId: 1, ptyId: 'pty-1' } ] }) - syncSinglePty(runtime) + statusWiring.statusStore.ingestTerminalStatus({ + paneKey: `tab-1:${leafId}`, + tabId: 'tab-1', + worktreeId: TEST_WORKTREE_ID, + connectionId: null, + payload: { + state: 'working', + workingMode: 'monitoring', + prompt: 'watch tests', + agentType: 'claude' + } + }) runtime.onPtyData( 'pty-1', '\x1b]9999;{"state":"working","prompt":"fix tests","agentType":"claude"}\x07', diff --git a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts index e829be07d9f..682661f0fce 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts @@ -146,11 +146,11 @@ describe('OrcaRuntimeService', () => { condition: 'tui-idle', satisfied: false, status: 'running', - blockedReason: 'codex-hooks-review-prompt' + blockedReason: 'agent-hooks-review-prompt' }) }) - it('returns a blocked wait result for Codex update prompts', async () => { + it('returns an agent-neutral blocked wait result for update prompts', async () => { const runtime = new OrcaRuntimeService(store) runtime.setPtyController({ spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), @@ -177,11 +177,11 @@ describe('OrcaRuntimeService', () => { condition: 'tui-idle', satisfied: false, status: 'running', - blockedReason: 'codex-update-prompt' + blockedReason: 'agent-update-prompt' }) }) - it('returns a blocked wait result for Codex workspace trust prompts', async () => { + it('returns an agent-neutral blocked wait result for workspace trust prompts', async () => { const runtime = new OrcaRuntimeService(store) runtime.setPtyController({ spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), @@ -203,7 +203,7 @@ describe('OrcaRuntimeService', () => { condition: 'tui-idle', satisfied: false, status: 'running', - blockedReason: 'codex-trust-workspace' + blockedReason: 'agent-trust-workspace' }) }) @@ -270,7 +270,7 @@ describe('OrcaRuntimeService', () => { ).rejects.toThrow('timeout') }) - it('returns a blocked wait result for Codex cwd selection prompts', async () => { + it('returns an agent-neutral blocked wait result for cwd selection prompts', async () => { const runtime = new OrcaRuntimeService(store) runtime.setPtyController({ spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), @@ -297,7 +297,7 @@ describe('OrcaRuntimeService', () => { condition: 'tui-idle', satisfied: false, status: 'running', - blockedReason: 'codex-cwd-prompt' + blockedReason: 'agent-cwd-prompt' }) }) @@ -359,11 +359,11 @@ describe('OrcaRuntimeService', () => { condition: 'tui-idle', satisfied: false, status: 'running', - blockedReason: 'codex-hooks-review-prompt' + blockedReason: 'agent-hooks-review-prompt' }) }) - it('returns a blocked wait result for generic Codex interactive prompts', async () => { + it('returns an agent-neutral blocked wait result for generic interactive prompts', async () => { const runtime = new OrcaRuntimeService(store) runtime.setPtyController({ spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }), @@ -390,7 +390,7 @@ describe('OrcaRuntimeService', () => { condition: 'tui-idle', satisfied: false, status: 'running', - blockedReason: 'codex-interactive-prompt' + blockedReason: 'agent-interactive-prompt' }) }) diff --git a/src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts index 438ec34118e..170a20b278c 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts @@ -9,10 +9,10 @@ import { import { makePaneKey } from '../orca-runtime-test-mocks.spec' describe('OrcaRuntimeService', () => { - it('invalidates a re-keyed leaf-unique handle so in-flight waiters fail fast', async () => { + it('keeps a no-incarnation handle across an in-graph pane remint', async () => { const runtime = createRuntime() const tabId = 'tab-1' - // No preAllocateHandleForPty: a plain terminal's handle is leaf-unique, so a re-key leaves it with no next owner and it goes stale immediately. + // No preallocated handle or incarnation id: the live PTY itself is the continuity proof within this graph. runtime.attachWindow(TEST_WINDOW_ID) runtime.syncWindowGraph(TEST_WINDOW_ID, { tabs: [ @@ -36,8 +36,8 @@ describe('OrcaRuntimeService', () => { }) const before = await runtime.listTerminals(`id:${TEST_WORKTREE_ID}`) expect(before.terminals).toHaveLength(1) - const staleHandle = before.terminals[0].handle - const waiting = runtime.waitForTerminal(staleHandle, { condition: 'exit', timeoutMs: 30_000 }) + const stableHandle = before.terminals[0].handle + const waiting = runtime.waitForTerminal(stableHandle, { condition: 'exit', timeoutMs: 30_000 }) // Re-key WITHOUT a renderer reload (e.g. a pane moved across tabs) while the same PTY stays live under a new leaf. runtime.syncWindowGraph(TEST_WINDOW_ID, { @@ -61,11 +61,11 @@ describe('OrcaRuntimeService', () => { ] }) - // The waiter must fail fast, not hang until timeout on a dead leaf. - await expect(waiting).rejects.toThrow('terminal_handle_stale') const after = await runtime.listTerminals(`id:${TEST_WORKTREE_ID}`) expect(after.terminals).toHaveLength(1) - expect(after.terminals[0].handle).not.toBe(staleHandle) + expect(after.terminals[0].handle).toBe(stableHandle) + runtime.onPtyExit('pty-plain', 0) + await expect(waiting).resolves.toMatchObject({ handle: stableHandle, status: 'exited' }) }) it('keeps a live CLI waiter pending when a re-keyed shared handle transfers to the live leaf', async () => { diff --git a/src/main/runtime/orca-runtime-tests/terminal-handles.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-handles.spec.ts index 4ae933afef4..8433dc5a71e 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-handles.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-handles.spec.ts @@ -82,6 +82,7 @@ describe('OrcaRuntimeService', () => { if (!mobileHandle) { throw new Error('expected mobile terminal handle') } + expect(mobileHandle).toBe(terminals.terminals[0].handle) const processLists = [[{ id: 'pty-1', cwd: '/tmp/worktree-a', title: 'Claude' }], []] runtime.setPtyController({ @@ -101,7 +102,7 @@ describe('OrcaRuntimeService', () => { (event) => event.type === 'worktreeTerminalSleepState' && event.phase === 'started' ) ).toMatchObject({ - terminalHandles: [terminals.terminals[0].handle, mobileHandle].sort() + terminalHandles: [...new Set([terminals.terminals[0].handle, mobileHandle])].sort() }) }) diff --git a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts index a2d45395b26..ecf2ab53678 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts @@ -623,7 +623,7 @@ describe('OrcaRuntimeService', () => { runtime.waitForTerminal(terminal.handle, { condition: 'tui-idle', timeoutMs: 100 }) ).resolves.toMatchObject({ satisfied: false, - blockedReason: 'codex-trust-workspace' + blockedReason: 'agent-trust-workspace' }) serializeProviderBuffer.mockImplementationOnce(() => new Promise(() => {})) await expect( diff --git a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts index 4c17cc9df18..21d1450b641 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery.spec.ts @@ -1,4 +1,5 @@ import { settledWriteStub } from '../../providers/settled-pty-write-stub' +import { makeAgentStatusStoreWiring } from '../agent-status-store-wiring.test-fixture' import { describe, expect, it, vi } from 'vitest' import { OrcaRuntimeService, @@ -139,7 +140,9 @@ describe('OrcaRuntimeService', () => { // #7970: headless serve has no renderer syncing tab.agentStatus, so hook-only transitions must republish the snapshot carrying the retained hook payload. it('republishes mobile session tabs with hook payloads for title-less OSC 9999 transitions', async () => { const spawn = vi.fn().mockResolvedValue({ id: 'hook-only-pty' }) - const runtime = new OrcaRuntimeService(store) + const statusWiring = makeAgentStatusStoreWiring() + const runtime = new OrcaRuntimeService(store, undefined, statusWiring.deps) + const uninstallRepublish = statusWiring.attach(runtime) runtime.setPtyController({ spawn, write: () => true, @@ -188,12 +191,15 @@ describe('OrcaRuntimeService', () => { ) unsubscribe() + uninstallRepublish() }) // Why: restored OMP panes can retain the hook while the wrapped Pi owns foreground (#6364). it('keeps an OMP hook labeled OMP when the wrapped pi child owns the foreground', async () => { const spawn = vi.fn().mockResolvedValue({ id: 'omp-flicker-pty' }) - const runtime = new OrcaRuntimeService(store) + const statusWiring = makeAgentStatusStoreWiring() + const runtime = new OrcaRuntimeService(store, undefined, statusWiring.deps) + const uninstallRepublish = statusWiring.attach(runtime) runtime.setPtyController({ spawn, write: () => true, @@ -240,11 +246,14 @@ describe('OrcaRuntimeService', () => { ) unsubscribe() + uninstallRepublish() }) it('does not republish mobile session tabs for repeated identical OSC 9999 payloads', async () => { const spawn = vi.fn().mockResolvedValue({ id: 'hook-ping-pty' }) - const runtime = new OrcaRuntimeService(store) + const statusWiring = makeAgentStatusStoreWiring() + const runtime = new OrcaRuntimeService(store, undefined, statusWiring.deps) + const uninstallRepublish = statusWiring.attach(runtime) runtime.setPtyController({ spawn, write: () => true, @@ -270,6 +279,7 @@ describe('OrcaRuntimeService', () => { expect(events).toHaveLength(1) unsubscribe() + uninstallRepublish() }) it('suppresses a retained hook working status once the shell owns the pane title again', async () => { diff --git a/src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts b/src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts new file mode 100644 index 00000000000..351996166c2 --- /dev/null +++ b/src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts @@ -0,0 +1,313 @@ +import { describe, expect, it, vi } from 'vitest' +import { OrcaRuntimeService } from '../orca-runtime-test-mocks.spec' +import { TEST_WORKTREE_ID, store } from '../orca-runtime-test-fixtures.spec' +import { makeAgentStatusStoreWiring } from '../agent-status-store-wiring.test-fixture' + +/** + * One store means one dismissal. Before PR 1b the runtime kept its own copy of the OSC row, so a + * row the user dismissed on the desktop stayed in `orca worktree ps` and on the phone until the + * PTY exited. These drive the real OSC byte path so the producer under test is the runtime's own + * parse, not a hand-built snapshot. + */ +const LEAF_ID = '77777777-7777-4777-8777-777777777777' +const REMINTED_LEAF_ID = '88888888-8888-4888-8888-888888888888' +const PANE_KEY = `tab-dismiss:${LEAF_ID}` + +function wiredRuntime(incarnationId?: string): { + runtime: OrcaRuntimeService + statusWiring: ReturnType +} { + const statusWiring = makeAgentStatusStoreWiring() + const runtime = new OrcaRuntimeService(store, undefined, statusWiring.deps) + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'tab-dismiss', + worktreeId: TEST_WORKTREE_ID, + title: 'Codex', + activeLeafId: LEAF_ID, + layout: null + } + ], + leaves: [ + { + tabId: 'tab-dismiss', + worktreeId: TEST_WORKTREE_ID, + leafId: LEAF_ID, + paneRuntimeId: 1, + ptyId: 'dismiss-pty' + } + ] + }) + if (incarnationId) { + runtime.registerPty('dismiss-pty', TEST_WORKTREE_ID, null, { + tabId: 'tab-dismiss', + leafId: LEAF_ID, + incarnationId + }) + } + return { runtime, statusWiring } +} + +function emitWorkingStatus(runtime: OrcaRuntimeService, sequence: number): void { + runtime.onPtyData( + 'dismiss-pty', + '\x1b]9999;{"state":"working","prompt":"ship it","agentType":"codex"}\x07', + sequence + ) +} + +describe('worktree ps follows a dismissal out of the agent-status store', () => { + it('drops the row as soon as the user dismisses it, without waiting for the PTY to exit', async () => { + const { runtime, statusWiring } = wiredRuntime() + emitWorkingStatus(runtime, 1) + + const listed = await runtime.getWorktreePs() + expect( + listed.worktrees.find((worktree) => worktree.worktreeId === TEST_WORKTREE_ID)?.agents + ).toEqual([expect.objectContaining({ paneKey: PANE_KEY, prompt: 'ship it' })]) + + statusWiring.statusStore.dropStatusEntry(PANE_KEY) + + // The PTY is untouched and still connected; only the store was told. + expect(runtime['ptysById'].get('dismiss-pty')?.connected).toBe(true) + const afterDismissal = await runtime.getWorktreePs() + expect( + afterDismissal.worktrees.find((worktree) => worktree.worktreeId === TEST_WORKTREE_ID)?.agents + ).toEqual([]) + }) + + it('tells paired clients to republish on the transition and on the dismissal', async () => { + const { runtime, statusWiring } = wiredRuntime() + const republish = vi.spyOn(runtime, 'touchMobileSessionTabsForWorktree') + const uninstall = statusWiring.attach(runtime) + try { + emitWorkingStatus(runtime, 1) + expect(republish).toHaveBeenCalledWith(TEST_WORKTREE_ID) + + // The same payload again changes nothing a client would render. + republish.mockClear() + emitWorkingStatus(runtime, 2) + expect(republish).not.toHaveBeenCalled() + + runtime.onPtyData( + 'dismiss-pty', + '\x1b]9999;{"state":"done","prompt":"ship it","agentType":"codex"}\x07', + 3 + ) + expect(republish).toHaveBeenCalledWith(TEST_WORKTREE_ID) + + republish.mockClear() + statusWiring.statusStore.dropStatusEntry(PANE_KEY) + expect(republish).toHaveBeenCalledWith(TEST_WORKTREE_ID) + } finally { + uninstall() + republish.mockRestore() + } + }) + + it.each([ + ['leaf binding', undefined, false], + ['controller incarnation', 'incarnation-1', true] + ] as const)( + 'rejoins a row through its %s handle after pane ownership clears', + async (_, incarnationId, clearLeafBinding) => { + const { runtime, statusWiring } = wiredRuntime(incarnationId) + emitWorkingStatus(runtime, 1) + const row = statusWiring.statusStore.getStatusSnapshot()[0]! + const internals = runtime as unknown as { + handleByLeafKey: Map + handleByPtyIncarnation: Map + ptysById: Map + } + const pty = internals.ptysById.get('dismiss-pty')! + pty.paneKey = null + pty.tabId = null + if (clearLeafBinding) { + expect(internals.handleByPtyIncarnation.get('dismiss-pty')?.handle).toBe(row.terminalHandle) + internals.handleByLeafKey.clear() + } + + const listed = await runtime.getWorktreePs() + + expect( + listed.worktrees.find((worktree) => worktree.worktreeId === TEST_WORKTREE_ID)?.agents + ).toEqual([expect.objectContaining({ prompt: 'ship it' })]) + statusWiring.statusStore.stop() + } + ) + + it('publishes one provider-addressable row through remint, dismissal, and exit', async () => { + const { runtime, statusWiring } = wiredRuntime('incarnation-1') + emitWorkingStatus(runtime, 1) + const row = statusWiring.statusStore.getStatusSnapshot()[0]! + expect(row.terminalHandle).toMatch(/^term_/) + statusWiring.statusStore.ingestRemote( + { + paneKey: PANE_KEY, + tabId: 'tab-dismiss', + worktreeId: TEST_WORKTREE_ID, + providerSession: { key: 'session_id', id: 'provider-session-1' }, + payload: { state: 'working', prompt: 'ship it', agentType: 'codex' } + }, + null + ) + + runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'tab-reminted', + worktreeId: TEST_WORKTREE_ID, + title: 'Codex', + activeLeafId: REMINTED_LEAF_ID, + layout: null + } + ], + leaves: [ + { + tabId: 'tab-reminted', + worktreeId: TEST_WORKTREE_ID, + leafId: REMINTED_LEAF_ID, + paneRuntimeId: 1, + ptyId: 'dismiss-pty' + } + ], + mobileSessionTabs: [ + { + worktree: TEST_WORKTREE_ID, + publicationEpoch: 'reminted-epoch', + snapshotVersion: 1, + activeGroupId: null, + activeTabId: `tab-reminted::${REMINTED_LEAF_ID}`, + activeTabType: 'terminal', + tabs: [ + { + type: 'terminal', + id: `tab-reminted::${REMINTED_LEAF_ID}`, + parentTabId: 'tab-reminted', + leafId: REMINTED_LEAF_ID, + ptyId: 'dismiss-pty', + title: 'Codex', + isActive: true + } + ] + } + ] + }) + + const before = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) + const events: Awaited>[] = [] + const unsubscribe = runtime.onMobileSessionTabsChanged((snapshot) => events.push(snapshot)) + const uninstall = statusWiring.attach(runtime) + try { + emitWorkingStatus(runtime, 2) + await vi.waitFor(() => expect(events).toHaveLength(1)) + const remintedPaneKey = `tab-reminted:${REMINTED_LEAF_ID}` + expect(statusWiring.statusStore.getStatusSnapshot()).toEqual([ + expect.objectContaining({ + paneKey: remintedPaneKey, + terminalHandle: row.terminalHandle, + providerSession: { key: 'session_id', id: 'provider-session-1' } + }) + ]) + expect(events[0]).toMatchObject({ + snapshotVersion: before.snapshotVersion + 1, + tabs: [ + expect.objectContaining({ + agentStatus: expect.objectContaining({ + state: 'working', + providerSession: { key: 'session_id', id: 'provider-session-1' } + }) + }) + ] + }) + + statusWiring.statusStore.dropStatusEntry(remintedPaneKey) + await vi.waitFor(() => expect(events).toHaveLength(2)) + expect(events[1]).toMatchObject({ + snapshotVersion: before.snapshotVersion + 2, + tabs: [expect.objectContaining({ agentStatus: expect.objectContaining({ state: 'done' }) })] + }) + expect((await runtime.getWorktreePs()).worktrees[0]?.agents).toEqual([]) + + runtime.onPtyExit('dismiss-pty', 0) + await vi.waitFor(() => expect(events).toHaveLength(3)) + expect(events[2]).toMatchObject({ snapshotVersion: before.snapshotVersion + 4 }) + expect( + events[2]?.tabs.every((tab) => tab.type !== 'terminal' || tab.agentStatus === undefined) + ).toBe(true) + expect(statusWiring.statusStore.getStatusSnapshot()).toEqual([]) + } finally { + uninstall() + unsubscribe() + statusWiring.statusStore.stop() + } + }) + + it('keeps runtime-owned legacy OSC rows in worktree.ps and mobile projections', async () => { + const statusWiring = makeAgentStatusStoreWiring() + const runtime = new OrcaRuntimeService(store, undefined, statusWiring.deps) + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'legacy-tab', + worktreeId: TEST_WORKTREE_ID, + title: 'Codex', + activeLeafId: 'pane:7', + layout: null + } + ], + leaves: [ + { + tabId: 'legacy-tab', + worktreeId: TEST_WORKTREE_ID, + leafId: 'pane:7', + paneRuntimeId: 7, + ptyId: 'legacy-pty' + } + ], + mobileSessionTabs: [ + { + worktree: TEST_WORKTREE_ID, + publicationEpoch: 'legacy-epoch', + snapshotVersion: 1, + activeGroupId: null, + activeTabId: 'legacy-tab::pane:7', + activeTabType: 'terminal', + tabs: [ + { + type: 'terminal', + id: 'legacy-tab::pane:7', + parentTabId: 'legacy-tab', + leafId: 'pane:7', + ptyId: 'legacy-pty', + title: 'Codex', + isActive: true + } + ] + } + ] + }) + runtime.onPtyData( + 'legacy-pty', + '\x1b]9999;{"state":"working","prompt":"legacy task","agentType":"codex"}\x07', + 1 + ) + + const listed = await runtime.getWorktreePs() + const mobile = await runtime.listMobileSessionTabs(`id:${TEST_WORKTREE_ID}`) + + expect( + listed.worktrees.find((worktree) => worktree.worktreeId === TEST_WORKTREE_ID)?.agents + ).toEqual([expect.objectContaining({ paneKey: 'legacy-tab:7', prompt: 'legacy task' })]) + expect(mobile.tabs[0]).toMatchObject({ + type: 'terminal', + agentStatus: { paneKey: 'legacy-tab:7', prompt: 'legacy task' } + }) + runtime.onPtyExit('legacy-pty', 0) + expect(statusWiring.statusStore.getStatusSnapshot()).toEqual([]) + statusWiring.statusStore.stop() + }) +}) diff --git a/src/main/runtime/orca-runtime-touch-mobile-session-tabs-for-worktree.ts b/src/main/runtime/orca-runtime-touch-mobile-session-tabs-for-worktree.ts index b7ca09af705..7a08f8f3bac 100644 --- a/src/main/runtime/orca-runtime-touch-mobile-session-tabs-for-worktree.ts +++ b/src/main/runtime/orca-runtime-touch-mobile-session-tabs-for-worktree.ts @@ -21,6 +21,7 @@ export class OrcaRuntimeWithTouchMobileSessionTabsForWorktree extends OrcaRuntim if (!snapshot) { return } + this.mobileSessionTabsAgentStatusHeartbeat.observeWorktreeRefresh(worktreeId) this.storeMobileSessionSnapshot(worktreeId, { ...snapshot, snapshotVersion: snapshot.snapshotVersion + 1 @@ -36,6 +37,13 @@ export class OrcaRuntimeWithTouchMobileSessionTabsForWorktree extends OrcaRuntim this.scheduleMobileSessionTabsChanged(worktreeId) } + scheduleMobileSessionTabsAgentStatusHeartbeatForWorktree(worktreeId: string): void { + if (this.mobileSessionTabListeners.size === 0) { + return + } + this.mobileSessionTabsAgentStatusHeartbeat.scheduleWorktreeHeartbeat(worktreeId) + } + /** Republish the workspace snapshot after a pane's hook status changed. * Hook rows feed the headless `agentStatus` projection, which nothing else touches. */ touchMobileSessionTabsForPane(paneKey: string, worktreeId?: string | null): void { diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 74098040c27..7ec1fd5fc35 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -86,6 +86,7 @@ await import('./orca-runtime-tests/mobile-summaries-part-02.spec') await import('./orca-runtime-tests/mobile-summaries-part-03.spec') await import('./orca-runtime-tests/mobile-summaries-part-04.spec') await import('./orca-runtime-tests/worktree-ps-structured-host.spec') +await import('./orca-runtime-tests/worktree-ps-agent-row-dismissal.spec') await import('./orca-runtime-tests/terminal-sleep-and-teardown.spec') await import('./orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec') await import('./orca-runtime-tests/terminal-sleep-and-teardown-part-03.spec') diff --git a/src/main/runtime/push/desktop-push-service-unreadable-outbox.test.ts b/src/main/runtime/push/desktop-push-service-unreadable-outbox.test.ts new file mode 100644 index 00000000000..b3e98418460 --- /dev/null +++ b/src/main/runtime/push/desktop-push-service-unreadable-outbox.test.ts @@ -0,0 +1,89 @@ +import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import type * as fs from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, vi } from 'vitest' +import { DeviceRegistry } from '../device-registry' +import { DesktopPushService } from './desktop-push-service' +import { createPushHostKeypair } from './push-host-challenge-fixtures' +import { PushUnregisterOutbox } from './push-unregister-outbox' + +vi.mock('node:fs', async (importOriginal) => { + const original = await importOriginal() + return { ...original, readFileSync: vi.fn(original.readFileSync) } +}) + +it('refuses registration until unreadable cleanup is recovered and settled on restart', async () => { + const dir = mkdtempSync(join(tmpdir(), 'orca-push-unreadable-')) + let service: DesktopPushService | null = null + try { + let registry = new DeviceRegistry(dir) + const { deviceId } = registry.addDevice('phone', 'mobile') + const queued = new PushUnregisterOutbox(dir).enqueue({ deviceId, registrationId: 'stable-id' }) + const path = join(dir, 'mobile-push-unregister-outbox.json') + const bytes = readFileSync(path, 'utf-8') + vi.mocked(readFileSync).mockImplementationOnce(() => { + throw Object.assign(new Error('temporarily unavailable'), { code: 'EIO' }) + }) + const unreadable = new PushUnregisterOutbox(dir) + let gatewayLive = true + const calls: string[] = [] + const client = { + registerDevice: vi.fn(async () => { + calls.push('register') + gatewayLive = true + return { ok: true, registrationId: 'stable-id' } as const + }), + deleteDevice: vi.fn(async () => { + calls.push('delete') + gatewayLive = false + return true + }) + } + const createService = (outbox: PushUnregisterOutbox): DesktopPushService => + DesktopPushService.create({ + runtime: { + setMobilePushRegistrar: vi.fn(), + onNotificationDispatched: () => () => {} + } as never, + runtimeRpc: { + getE2EEKeypair: createPushHostKeypair, + getDeviceRegistry: () => registry, + getPushUnregisterOutbox: () => outbox, + setOnPushUnregisterQueued: vi.fn() + } as never, + client: client as never, + gatewayUrl: 'https://push.invalid', + scheduleRetry: vi.fn() + })! + const input = { deviceId, platform: 'android' as const, token: 'synthetic', filter: {} } + service = createService(unreadable) + service.start() + expect(await service.register(input)).toEqual({ + registered: false, + reason: 'registration_storage_failed' + }) + expect(client.registerDevice).not.toHaveBeenCalled() + expect(client.deleteDevice).not.toHaveBeenCalled() + expect(registry.getDevice(deviceId)?.pushRegistration).toBeUndefined() + expect(readFileSync(path, 'utf-8')).toBe(bytes) + service.stop() + + registry = new DeviceRegistry(dir) + const recovered = new PushUnregisterOutbox(dir) + expect(recovered.pending()).toEqual([queued]) + service = createService(recovered) + service.start() + expect(await service.register(input)).toEqual({ registered: true, registrationId: 'stable-id' }) + await service.flushUnregisterOutbox() + expect(calls).toEqual(['delete', 'register']) + expect(gatewayLive).toBe(true) + expect(new DeviceRegistry(dir).getDevice(deviceId)?.pushRegistration?.registrationId).toBe( + 'stable-id' + ) + expect(new PushUnregisterOutbox(dir).pending()).toEqual([]) + } finally { + service?.stop() + rmSync(dir, { recursive: true, force: true }) + } +}) diff --git a/src/main/runtime/push/desktop-push-service.test.ts b/src/main/runtime/push/desktop-push-service.test.ts new file mode 100644 index 00000000000..a9561be8487 --- /dev/null +++ b/src/main/runtime/push/desktop-push-service.test.ts @@ -0,0 +1,352 @@ +import { mkdtempSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it, vi } from 'vitest' +import type { MobileNotificationEvent } from '../runtime-mobile-notification-controller' +import { DeviceRegistry } from '../device-registry' +import { DesktopPushService } from './desktop-push-service' +import { PushRegisterThrottle } from './push-register-throttle' +import { PushUnregisterOutbox } from './push-unregister-outbox' +import { createPushHostKeypair } from './push-host-challenge-fixtures' + +const REGISTER_INPUT = { + platform: 'android' as const, + token: 'fcm-token', + filter: {} +} + +function createService( + options: { + registerFails?: boolean + deleteFails?: boolean + /** Runs before each delete resolves, so a suite can queue work mid-flush. */ + onDelete?: (registrationId: string) => void + now?: () => number + } = {} +): { + service: DesktopPushService + registry: DeviceRegistry + outbox: PushUnregisterOutbox + deviceId: string + deletes: string[] + send: ReturnType + dispatch: (event: MobileNotificationEvent) => void + retries: { run: () => void; delayMs: number }[] +} { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-push-service-')) + const registry = new DeviceRegistry(userDataPath) + const outbox = new PushUnregisterOutbox(userDataPath) + const device = registry.addDevice('phone', 'mobile') + const deletes: string[] = [] + let listener: ((event: MobileNotificationEvent) => void) | null = null + + const runtime = { + setMobilePushRegistrar: vi.fn(), + onNotificationDispatched: vi.fn((next: (event: MobileNotificationEvent) => void) => { + listener = next + return () => { + listener = null + } + }) + } + const runtimeRpc = { + getE2EEKeypair: () => createPushHostKeypair(), + getDeviceRegistry: () => registry, + getPushUnregisterOutbox: () => outbox, + setOnPushUnregisterQueued: vi.fn() + } + // A stub gateway keeps the suite on the service's own persistence decisions. + const client = { + registerDevice: vi.fn(async () => + options.registerFails + ? ({ ok: false, reason: 'unreachable' } as const) + : ({ ok: true, registrationId: 'reg-1' } as const) + ), + deleteDevice: vi.fn(async (registrationId: string) => { + deletes.push(registrationId) + options.onDelete?.(registrationId) + return !options.deleteFails + }), + send: vi.fn(async () => ({ ok: true, results: [] }) as const) + } + const retries: { run: () => void; delayMs: number }[] = [] + const service = DesktopPushService.create({ + runtime: runtime as never, + runtimeRpc: runtimeRpc as never, + gatewayUrl: 'https://push.onorca.dev', + client: client as never, + scheduleRetry: (run, delayMs) => { + retries.push({ run, delayMs }) + }, + ...(options.now ? { registerThrottle: new PushRegisterThrottle({ now: options.now }) } : {}) + })! + + service.start() + return { + service, + registry, + outbox, + deviceId: device.deviceId, + deletes, + send: client.send, + dispatch: (event) => listener?.(event), + retries + } +} + +describe('DesktopPushService', () => { + it('persists the registration the gateway hands back', async () => { + const harness = createService() + + expect( + await harness.service.register({ deviceId: harness.deviceId, ...REGISTER_INPUT }) + ).toEqual({ registered: true, registrationId: 'reg-1' }) + expect(harness.registry.getDevice(harness.deviceId)?.pushRegistration).toMatchObject({ + registrationId: 'reg-1', + filter: REGISTER_INPUT.filter + }) + }) + + it('persists nothing when the gateway is unreachable', async () => { + const harness = createService({ registerFails: true }) + + expect( + await harness.service.register({ deviceId: harness.deviceId, ...REGISTER_INPUT }) + ).toEqual({ registered: false, reason: 'gateway_unreachable' }) + expect(harness.registry.getDevice(harness.deviceId)?.pushRegistration).toBeUndefined() + }) + + it('refuses to register a device that is not a paired phone', async () => { + const harness = createService() + + expect(await harness.service.register({ deviceId: 'not-a-device', ...REGISTER_INPUT })).toEqual( + { + registered: false, + reason: 'not_mobile' + } + ) + }) + + it('clears the local registration and deletes at the gateway on unregister', async () => { + const harness = createService() + await harness.service.register({ deviceId: harness.deviceId, ...REGISTER_INPUT }) + + expect(await harness.service.unregister(harness.deviceId)).toEqual({ unregistered: true }) + await harness.service.flushUnregisterOutbox() + expect(harness.registry.getDevice(harness.deviceId)?.pushRegistration).toBeUndefined() + expect(harness.deletes).toEqual(['reg-1']) + expect(harness.outbox.pending()).toEqual([]) + }) + + it('keeps the delete queued when the gateway cannot be reached', async () => { + const harness = createService({ deleteFails: true }) + await harness.service.register({ deviceId: harness.deviceId, ...REGISTER_INPUT }) + + await harness.service.unregister(harness.deviceId) + + expect(harness.registry.getDevice(harness.deviceId)?.pushRegistration).toBeUndefined() + expect(harness.outbox.pending()).toEqual([ + expect.objectContaining({ registrationId: 'reg-1', deviceId: harness.deviceId }) + ]) + }) + + it('reports nothing to unregister for a device that never enabled push', async () => { + const harness = createService() + expect(await harness.service.unregister(harness.deviceId)).toEqual({ unregistered: false }) + }) + + it('drains a delete queued before this launch', async () => { + const harness = createService() + harness.outbox.enqueue({ registrationId: 'reg-stale', deviceId: 'device-gone' }) + + await harness.service.flushUnregisterOutbox() + + expect(harness.deletes).toEqual(['reg-stale']) + expect(harness.outbox.pending()).toEqual([]) + }) + + it('unregisters at the gateway when the device stopped being a phone mid-register', async () => { + const harness = createService() + vi.spyOn(harness.registry, 'setPushRegistration').mockReturnValue(false) + + expect( + await harness.service.register({ deviceId: harness.deviceId, ...REGISTER_INPUT }) + ).toEqual({ registered: false, reason: 'not_mobile' }) + // register() kicks the flush off without awaiting it; join the same run. + await harness.service.flushUnregisterOutbox() + expect(harness.deletes).toEqual(['reg-1']) + expect(harness.outbox.pending()).toEqual([]) + }) + + it('unregisters at the gateway when the registration cannot be written', async () => { + const harness = createService({ deleteFails: true }) + vi.spyOn(harness.registry, 'setPushRegistration').mockImplementation(() => { + throw new Error('disk full') + }) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + expect( + await harness.service.register({ deviceId: harness.deviceId, ...REGISTER_INPUT }) + ).toEqual({ registered: false, reason: 'registration_storage_failed' }) + // The gateway kept the token, so the delete stays queued until it lands. + expect(harness.outbox.pending()).toEqual([ + expect.objectContaining({ registrationId: 'reg-1', deviceId: harness.deviceId }) + ]) + warn.mockRestore() + }) + + it('drains a delete queued while a flush is already running', async () => { + let queued = false + const harness = createService({ + onDelete: () => { + if (queued) { + return + } + queued = true + harness.outbox.enqueue({ registrationId: 'reg-late', deviceId: 'device-late' }) + // Mirrors unregister(): the trigger arrives while the flush is mid-await. + void harness.service.flushUnregisterOutbox() + } + }) + harness.outbox.enqueue({ registrationId: 'reg-first', deviceId: 'device-first' }) + + await harness.service.flushUnregisterOutbox() + + expect(harness.deletes).toEqual(['reg-first', 'reg-late']) + expect(harness.outbox.pending()).toEqual([]) + }) + + it('retries a failed drain on a capped backoff instead of waiting for a relaunch', async () => { + const harness = createService({ deleteFails: true }) + harness.outbox.enqueue({ registrationId: 'reg-stuck', deviceId: 'device-1' }) + + await harness.service.flushUnregisterOutbox() + expect(harness.retries.map((entry) => entry.delayMs)).toEqual([30_000]) + + harness.retries[0]?.run() + await new Promise((resolve) => setImmediate(resolve)) + expect(harness.deletes).toEqual(['reg-stuck', 'reg-stuck']) + expect(harness.retries.map((entry) => entry.delayMs)).toEqual([30_000, 60_000]) + expect(harness.outbox.pending()).toHaveLength(1) + }) + + it('stops re-arming the retry once the service is stopped', async () => { + const harness = createService({ deleteFails: true }) + harness.outbox.enqueue({ registrationId: 'reg-stuck', deviceId: 'device-1' }) + await harness.service.flushUnregisterOutbox() + + harness.service.stop() + harness.retries[0]?.run() + await new Promise((resolve) => setImmediate(resolve)) + + expect(harness.retries).toHaveLength(1) + }) + + it('throttles a device that registers in a loop and lets it back in a minute later', async () => { + let clock = 1_700_000_000_000 + const harness = createService({ now: () => clock }) + const input = { deviceId: harness.deviceId, ...REGISTER_INPUT } + + for (let index = 0; index < 10; index++) { + expect(await harness.service.register(input)).toEqual({ + registered: true, + registrationId: 'reg-1' + }) + } + expect(await harness.service.register(input)).toEqual({ + registered: false, + reason: 'throttled' + }) + // The registration it already made stands; only the new write is refused. + expect(harness.registry.getDevice(harness.deviceId)?.pushRegistration?.registrationId).toBe( + 'reg-1' + ) + + clock += 60_000 + expect(await harness.service.register(input)).toEqual({ + registered: true, + registrationId: 'reg-1' + }) + }) + + it('pushes a dispatched notification through the subscribed dispatcher', async () => { + const harness = createService() + await harness.service.register({ deviceId: harness.deviceId, ...REGISTER_INPUT }) + + harness.dispatch({ + type: 'notification', + source: 'agent-task-complete', + title: 'feat/x - Claude finished', + body: 'Done.', + notificationSeq: 3, + notificationEpoch: 'epoch-1', + agentState: 'done' + }) + await new Promise((resolve) => setImmediate(resolve)) + + expect(harness.send).toHaveBeenCalledWith( + expect.objectContaining({ registrationIds: ['reg-1'] }) + ) + }) +}) + +it('renews a seven-day mobile lease only on explicit registration', async () => { + const now = 1_800_000_000_000 + const clock = vi.spyOn(Date, 'now').mockReturnValue(now) + const h = createService() + try { + await h.service.register({ + deviceId: h.deviceId, + ...REGISTER_INPUT + }) + expect(h.registry.getDevice(h.deviceId)?.pushRegistration?.expiresAt).toBe(now + 7 * 86400_000) + clock.mockReturnValue(now + 86400_000) + h.dispatch({ type: 'notification', source: 'terminal-bell', title: 'QA', body: 'QA' }) + expect(h.registry.getDevice(h.deviceId)?.pushRegistration?.expiresAt).toBe(now + 7 * 86400_000) + await h.service.register({ + deviceId: h.deviceId, + ...REGISTER_INPUT + }) + expect(h.registry.getDevice(h.deviceId)?.pushRegistration?.expiresAt).toBe(now + 8 * 86400_000) + } finally { + h.service.stop() + clock.mockRestore() + } +}) + +it('sends an explicit test only to the requesting registered phone and awaits gateway acceptance', async () => { + const { service, registry, deviceId, send } = createService() + await service.register({ + ...REGISTER_INPUT, + deviceId, + filter: { onlyWhenDesktopAway: true, sound: false } + }) + registry.addDevice('another phone', 'mobile') + send.mockResolvedValue({ ok: true, results: [{ registrationId: 'reg-1', status: 'queued' }] }) + await expect(service.test(deviceId)).resolves.toEqual({ accepted: true }) + expect(send).toHaveBeenCalledWith({ + registrationIds: ['reg-1'], + notification: expect.objectContaining({ + source: 'terminal-bell', + sound: false, + title: 'Test notification' + }) + }) +}) + +it('does not claim success for missing registrations or failed gateway sends', async () => { + const { service, deviceId, send } = createService() + await expect(service.test(deviceId)).resolves.toEqual({ + accepted: false, + reason: 'not_registered' + }) + expect(send).not.toHaveBeenCalled() + await service.register({ ...REGISTER_INPUT, deviceId }) + send.mockResolvedValue({ ok: false, reason: 'unreachable' }) + await expect(service.test(deviceId)).resolves.toEqual({ accepted: false, reason: 'unavailable' }) + send.mockResolvedValue({ + ok: true, + results: [{ registrationId: 'reg-1', status: 'rate_limited' }] + }) + await expect(service.test(deviceId)).resolves.toEqual({ accepted: false, reason: 'rate_limited' }) +}) diff --git a/src/main/runtime/push/desktop-push-service.ts b/src/main/runtime/push/desktop-push-service.ts new file mode 100644 index 00000000000..44e06dbcb2c --- /dev/null +++ b/src/main/runtime/push/desktop-push-service.ts @@ -0,0 +1,333 @@ +// Why: owns the desktop half of background push — the gateway session, the +// registration each paired phone asked for, and the durable delete queue. Built +// alongside DesktopRelayService but deliberately not gated on cloud sign-in: the +// gateway authenticates with the host keypair, so accountless hosts push too. +import { randomUUID } from 'node:crypto' +import type { + MobilePushTestResult, + MobilePushRegisterInput, + MobilePushRegisterResult +} from '../../../shared/mobile-push-contract' +import { runKeyedSerializedOperation } from '../../cli/keyed-promise-queue' +import type { DeviceRegistry } from '../device-registry' +import type { OrcaRuntimeService } from '../orca-runtime' +import type { OrcaRuntimeRpcServer } from '../runtime-rpc' +import { PushDispatcher } from './push-dispatcher' +import { PushGatewayClient } from './push-gateway-client' +import { PushRegisterThrottle } from './push-register-throttle' +import type { PushUnregisterOutbox } from './push-unregister-outbox' + +const OUTBOX_RETRY_BASE_MS = 30_000 +const OUTBOX_RETRY_MAX_MS = 10 * 60_000 + +type RegisterStorageFailure = 'not_mobile' | 'registration_storage_failed' + +type DesktopPushServiceOptions = { + runtime: OrcaRuntimeService + runtimeRpc: OrcaRuntimeRpcServer + gatewayUrl: string + /** Test seam: lets a suite drive the service without a live gateway. */ + client?: PushGatewayClient + /** Test seam: lets a suite drive the outbox backoff without real timers. */ + scheduleRetry?: (run: () => void, delayMs: number) => void + /** Test seam: lets a suite drive the per-device register bucket on its own clock. */ + registerThrottle?: PushRegisterThrottle +} + +export class DesktopPushService { + private readonly runtime: OrcaRuntimeService + private readonly runtimeRpc: OrcaRuntimeRpcServer + private readonly registry: DeviceRegistry + private readonly outbox: PushUnregisterOutbox + private readonly client: PushGatewayClient + private readonly dispatcher: PushDispatcher + private readonly registerThrottle: PushRegisterThrottle + private readonly scheduleRetry: (run: () => void, delayMs: number) => void + private unsubscribe: (() => void) | null = null + private flushLoop: Promise | null = null + private flushRequested = false + private retryArmed = false + private retryDelayMs = OUTBOX_RETRY_BASE_MS + private stopped = false + private readonly deviceOperations = new Map>() + + private constructor( + options: DesktopPushServiceOptions, + registry: DeviceRegistry, + client: PushGatewayClient + ) { + this.runtime = options.runtime + this.runtimeRpc = options.runtimeRpc + this.registry = registry + this.client = client + this.outbox = options.runtimeRpc.getPushUnregisterOutbox() + this.dispatcher = new PushDispatcher({ client, registry }) + this.registerThrottle = options.registerThrottle ?? new PushRegisterThrottle() + this.scheduleRetry = + options.scheduleRetry ?? + ((run, delayMs) => { + // Why: a queued gateway delete must never hold the app open at quit. + setTimeout(run, delayMs).unref?.() + }) + } + + /** Returns null when the mobile runtime never came up, so there is nothing to push for. */ + static create(options: DesktopPushServiceOptions): DesktopPushService | null { + const keypair = options.runtimeRpc.getE2EEKeypair() + const registry = options.runtimeRpc.getDeviceRegistry() + if (!keypair || !registry) { + return null + } + const client = + options.client ?? new PushGatewayClient({ gatewayUrl: options.gatewayUrl, keypair }) + return new DesktopPushService(options, registry, client) + } + + start(): void { + this.stopped = false + this.dispatcher.start() + this.runtime.setMobilePushRegistrar(this) + this.unsubscribe = this.runtime.onNotificationDispatched((event) => { + this.dispatcher.enqueue(event) + }) + // Unpairing queues a delete without going through this service; drain on that too. + this.runtimeRpc.setOnPushUnregisterQueued(() => { + void this.flushUnregisterOutbox() + }) + // Deletes queued while the gateway was unreachable — including across restarts. + void this.flushUnregisterOutbox() + } + + stop(): void { + this.stopped = true + this.dispatcher.stop() + this.unsubscribe?.() + this.unsubscribe = null + this.runtimeRpc.setOnPushUnregisterQueued(null) + this.runtime.setMobilePushRegistrar(null) + } + + async test(deviceId: string): Promise { + const device = this.registry.getDevice(deviceId) + const registration = device?.pushRegistration + if (device?.scope !== 'mobile' || !registration || registration.expiresAt <= Date.now()) { + return { accepted: false, reason: 'not_registered' } + } + if (this.stopped) { + return { accepted: false, reason: 'unavailable' } + } + // Explicit tests target only the caller and bypass automatic activity filters. + const result = await this.client.send({ + registrationIds: [registration.registrationId], + notification: { + source: 'terminal-bell', + agentState: null, + title: 'Test notification', + body: '', + notificationId: randomUUID(), + notificationEpoch: randomUUID(), + notificationSeq: 0, + expiresAt: Date.now() + 300_000, + sound: registration.filter.sound !== false + } + }) + if (!result.ok) { + return { + accepted: false, + reason: result.reason === 'unreachable' ? 'unavailable' : 'rejected' + } + } + const status = result.results.find( + (entry) => entry.registrationId === registration.registrationId + )?.status + if (status === 'queued') { + return { accepted: true } + } + return { + accepted: false, + reason: + status === 'rate_limited' + ? 'rate_limited' + : status === 'dead' + ? 'not_registered' + : 'rejected' + } + } + + async register(input: MobilePushRegisterInput): Promise { + if (this.registry.getDevice(input.deviceId)?.scope !== 'mobile') { + return { registered: false, reason: 'not_mobile' } + } + // Unregister needs no bucket: with nothing registered it is a lookup, and + // with something registered it can only run once per successful register. + if (!this.registerThrottle.allow(input.deviceId)) { + return { registered: false, reason: 'throttled' } + } + return runKeyedSerializedOperation(this.deviceOperations, input.deviceId, () => + this.registerAfterCleanup(input) + ) + } + + private async registerAfterCleanup( + input: MobilePushRegisterInput + ): Promise { + if (this.outbox.isUnreadable()) { + return { registered: false, reason: 'registration_storage_failed' } + } + // A stable gateway ID must not inherit a delete from an earlier registration. + for (const item of this.outbox.pending().filter((entry) => entry.deviceId === input.deviceId)) { + if (!(await this.deleteQueued(item.reqId, item.registrationId))) { + this.scheduleFlushRetry() + return { registered: false, reason: 'gateway_unreachable' } + } + } + if (this.registry.getDevice(input.deviceId)?.scope !== 'mobile') { + return { registered: false, reason: 'not_mobile' } + } + if (this.stopped) { + return { registered: false, reason: 'gateway_unreachable' } + } + const result = await this.client.registerDevice(input) + if (!result.ok) { + return { + registered: false, + reason: result.reason === 'unreachable' ? 'gateway_unreachable' : 'gateway_rejected' + } + } + const failure = this.storeRegistration(input, result.registrationId) + if (failure) { + // Why: the gateway now holds a token this host will never push to. Queue its + // delete instead of leaking it until the phone happens to register again. + this.outbox.enqueue({ registrationId: result.registrationId, deviceId: input.deviceId }) + } + void this.flushUnregisterOutbox() + return failure + ? { registered: false, reason: failure } + : { registered: true, registrationId: result.registrationId } + } + + async unregister(deviceId: string): Promise<{ unregistered: boolean }> { + return runKeyedSerializedOperation(this.deviceOperations, deviceId, async () => + this.unregisterCurrent(deviceId) + ) + } + + private unregisterCurrent(deviceId: string): { unregistered: boolean } { + const registrationId = this.registry.getDevice(deviceId)?.pushRegistration?.registrationId + if (!registrationId) { + return { unregistered: false } + } + // Persist cleanup before forgetting its ID; neither write waits on the gateway. + this.outbox.enqueue({ registrationId, deviceId }) + try { + this.registry.setPushRegistration(deviceId, null) + } finally { + void this.flushUnregisterOutbox() + } + return { unregistered: true } + } + + /** Joining an in-flight drain still waits for the item this call queued. */ + async flushUnregisterOutbox(): Promise { + if (this.stopped) { + return + } + this.flushRequested = true + this.flushLoop ??= this.runFlushLoop() + await this.flushLoop + } + + private async runFlushLoop(): Promise { + try { + while (this.flushRequested && !this.stopped) { + // Cleared before the pass, so a delete queued mid-drain earns another one. + this.flushRequested = false + if (await this.drainPending()) { + this.scheduleFlushRetry() + } else { + this.retryDelayMs = OUTBOX_RETRY_BASE_MS + } + } + } finally { + // Clear ownership before the runner settles, so a late request starts a new drain. + this.flushLoop = null + } + } + + /** Returns the refusal reason when a gateway-accepted registration cannot be stored. */ + private storeRegistration( + input: MobilePushRegisterInput, + registrationId: string + ): RegisterStorageFailure | null { + try { + const stored = this.registry.setPushRegistration(input.deviceId, { + registrationId, + filter: input.filter, + expiresAt: Date.now() + 7 * 24 * 60 * 60_000 + }) + // False means the device was removed or left mobile scope while the gateway + // call was in flight. + return stored ? null : 'not_mobile' + } catch (error) { + console.warn('[push] Failed to persist a push registration:', error) + return 'registration_storage_failed' + } + } + + /** Returns true when the pass left behind an item the gateway may still accept. */ + private async drainPending(): Promise { + let retryable = false + // Every enqueue requests a flush; the outer loop owns work added during this pass. + for (const item of this.outbox.pending()) { + try { + const deleted = await runKeyedSerializedOperation( + this.deviceOperations, + item.deviceId, + () => { + // Failed local removal must not delete a still-attached gateway registration. + if ( + this.registry.getDevice(item.deviceId)?.pushRegistration?.registrationId === + item.registrationId + ) { + return Promise.resolve(false) + } + return this.deleteQueued(item.reqId, item.registrationId) + } + ) + if (!deleted) { + retryable = true + } + } catch (error) { + // One bad delete must not strand the rest of the queue. + console.warn('[push] Failed to drain the push unregister outbox:', error) + retryable = true + } + } + return retryable + } + + private async deleteQueued(reqId: string, registrationId: string): Promise { + if (!this.outbox.pending().some((item) => item.reqId === reqId)) { + return true + } + const deleted = await this.client.deleteDevice(registrationId) + if (!deleted) { + return false + } + this.outbox.remove(reqId) + return true + } + + private scheduleFlushRetry(): void { + if (this.retryArmed || this.stopped) { + return + } + this.retryArmed = true + const delayMs = this.retryDelayMs + this.retryDelayMs = Math.min(delayMs * 2, OUTBOX_RETRY_MAX_MS) + this.scheduleRetry(() => { + this.retryArmed = false + void this.flushUnregisterOutbox() + }, delayMs) + } +} diff --git a/src/main/runtime/push/push-agent-state.test.ts b/src/main/runtime/push/push-agent-state.test.ts new file mode 100644 index 00000000000..e56d39ffb01 --- /dev/null +++ b/src/main/runtime/push/push-agent-state.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from 'vitest' +import { mapPushAgentState } from './push-dispatcher' + +describe('mapPushAgentState', () => { + it.each([ + ['blocked', 'needs-input'], + ['waiting', 'needs-input'], + ['done', 'finished'], + [undefined, 'finished'] + ] as const)('maps agent-task-complete %s to %s', (agentState, expected) => { + expect(mapPushAgentState('agent-task-complete', agentState)).toBe(expected) + }) + + it('suppresses a still-working agent', () => { + expect(mapPushAgentState('agent-task-complete', 'working')).toBeUndefined() + }) + + it('leaves non-agent sources without a state', () => { + expect(mapPushAgentState('terminal-bell', undefined)).toBeNull() + }) +}) diff --git a/src/main/runtime/push/push-cleanup-auth-expiry.test.ts b/src/main/runtime/push/push-cleanup-auth-expiry.test.ts new file mode 100644 index 00000000000..dc7ce5e1883 --- /dev/null +++ b/src/main/runtime/push/push-cleanup-auth-expiry.test.ts @@ -0,0 +1,41 @@ +import { createHash } from 'node:crypto' +import { expect, it } from 'vitest' +import { PushGatewayClient } from './push-gateway-client' +import { buildPushChallengeFixture, createPushHostKeypair } from './push-host-challenge-fixtures' + +it('retains a delete when its session proof expires before the DELETE is attempted', async () => { + const keypair = createPushHostKeypair() + const hostFingerprint = createHash('sha256') + .update(keypair.publicKey) + .digest('base64url') + .slice(0, 16) + let now = 1_770_000_000_000 + let deletes = 0 + const client = new PushGatewayClient({ + gatewayUrl: 'https://push.example.test', + keypair, + now: () => now, + fetch: (async (url, init) => { + if (String(url).endsWith('/challenge')) { + const fixture = buildPushChallengeFixture({ + hostKeypair: keypair, + hostFingerprint, + gatewayOrigin: 'https://push.example.test', + issuedAt: now, + challengeId: 'challenge-1' + }) + now += 11_000 + return Response.json(fixture.challenge) + } + if (String(url).endsWith('/session')) { + return Response.json({ error: 'invalid_proof' }, { status: 401 }) + } + if (init?.method === 'DELETE') { + deletes++ + } + return new Response(null, { status: 204 }) + }) as typeof fetch + }) + expect(await client.deleteDevice('registration-1')).toEqual(false) + expect(deletes).toBe(0) +}) diff --git a/src/main/runtime/push/push-delivery-policy.test.ts b/src/main/runtime/push/push-delivery-policy.test.ts new file mode 100644 index 00000000000..4451a9b9d85 --- /dev/null +++ b/src/main/runtime/push/push-delivery-policy.test.ts @@ -0,0 +1,48 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { createHarness, flush, notification, registration } from './push-dispatcher.test-fixture' +import { parseMobilePushRegistration } from '../../../shared/mobile-push-contract' + +afterEach(() => vi.useRealTimers()) + +it('does not send or consume cooldown while the desktop is active', async () => { + const reg = registration() + reg.filter = { ...reg.filter, onlyWhenDesktopAway: true } + const { dispatcher, sends } = createHarness({ + devices: [{ deviceId: 'phone', pushRegistration: reg }] + }) + dispatcher.enqueue(notification({ desktopAway: false, emittedAt: 10_000 })) + dispatcher.enqueue(notification({ desktopAway: true, emittedAt: 10_001 })) + await flush() + expect(sends).toHaveLength(1) +}) + +it('expires per phone at the boundary, preserves leases across persistence, and permits renewal', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(50_000) + const expired = parseMobilePushRegistration(registration({ expiresAt: 50_000 }))! + const devices = [{ deviceId: 'phone', pushRegistration: expired }] + const { dispatcher, sends } = createHarness({ devices }) + dispatcher.enqueue(notification()) + await flush() + expect(sends).toHaveLength(0) + devices[0].pushRegistration = registration({ expiresAt: 50_001 }) + dispatcher.enqueue(notification()) + await flush() + expect(sends).toHaveLength(1) +}) + +it('rechecks expiry before a retry', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(10) + const { dispatcher, sends, runRetry } = createHarness({ + devices: [{ deviceId: 'phone', pushRegistration: registration({ expiresAt: 20 }) }], + sendImpl: async () => ({ ok: false, reason: 'unreachable' }) as never + }) + dispatcher.enqueue(notification()) + await flush() + vi.setSystemTime(20) + runRetry() + await flush() + expect(sends).toHaveLength(1) + expect(parseMobilePushRegistration({ ...registration(), expiresAt: undefined })).toBeUndefined() +}) diff --git a/src/main/runtime/push/push-device-registration-persistence.test.ts b/src/main/runtime/push/push-device-registration-persistence.test.ts new file mode 100644 index 00000000000..1e2d3d6e51c --- /dev/null +++ b/src/main/runtime/push/push-device-registration-persistence.test.ts @@ -0,0 +1,123 @@ +import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' +import { DeviceRegistry } from '../device-registry' +import { DEVICE_REGISTRY_FILENAME } from '../mobile-pairing-files' +import type { MobilePushRegistration } from '../../../shared/mobile-push-contract' + +const REGISTRATION: MobilePushRegistration = { + registrationId: 'reg-1', + filter: {}, + expiresAt: Date.now() + 7 * 86400_000 +} + +function userDataDir(): string { + return mkdtempSync(join(tmpdir(), 'orca-push-registry-')) +} + +function rewriteRegistry(dir: string, mutate: (devices: Record[]) => void): void { + const path = join(dir, DEVICE_REGISTRY_FILENAME) + const devices: Record[] = JSON.parse(readFileSync(path, 'utf-8')) + mutate(devices) + writeFileSync(path, JSON.stringify(devices)) +} + +describe('DeviceRegistry push registrations', () => { + it('persists a registration across a restart', () => { + const dir = userDataDir() + const device = new DeviceRegistry(dir).addDevice('phone', 'mobile') + expect(new DeviceRegistry(dir).setPushRegistration(device.deviceId, REGISTRATION)).toBe(true) + + expect(new DeviceRegistry(dir).getDevice(device.deviceId)?.pushRegistration).toEqual( + REGISTRATION + ) + }) + + it('clears a registration when the gateway reports the token dead', () => { + const dir = userDataDir() + const registry = new DeviceRegistry(dir) + const device = registry.addDevice('phone', 'mobile') + registry.setPushRegistration(device.deviceId, REGISTRATION) + + expect(registry.setPushRegistration(device.deviceId, null)).toBe(true) + expect(new DeviceRegistry(dir).getDevice(device.deviceId)?.pushRegistration).toBeUndefined() + }) + + it.each([1_770_000_000_000, 'unused'])( + 'ignores the obsolete registeredAt field (%s)', + (registeredAt) => { + const dir = userDataDir() + const device = new DeviceRegistry(dir).addDevice('phone', 'mobile') + rewriteRegistry(dir, (devices) => { + for (const entry of devices) { + entry.pushRegistration = { ...REGISTRATION, registeredAt } + } + }) + + expect(new DeviceRegistry(dir).getDevice(device.deviceId)?.pushRegistration).toEqual( + REGISTRATION + ) + } + ) + + it('refuses to register a runtime-scoped device', () => { + const dir = userDataDir() + const registry = new DeviceRegistry(dir) + const cli = registry.addDevice('cli', 'runtime') + + expect(registry.setPushRegistration(cli.deviceId, REGISTRATION)).toBe(false) + }) + + it('loads a registry written before push existed', () => { + const dir = userDataDir() + const device = new DeviceRegistry(dir).addDevice('phone', 'mobile') + rewriteRegistry(dir, (devices) => { + for (const entry of devices) { + delete entry.pushRegistration + } + }) + + const reloaded = new DeviceRegistry(dir) + expect(reloaded.listDevices()).toHaveLength(1) + expect(reloaded.getDevice(device.deviceId)?.pushRegistration).toBeUndefined() + }) + + it.each([ + ['a malformed registration', { registrationId: 'reg-1' }], + ['a missing expiry', { ...REGISTRATION, expiresAt: undefined }], + ['a non-finite expiry', { ...REGISTRATION, expiresAt: Infinity }], + ['an array filter', { ...REGISTRATION, filter: [] }], + ['a missing filter', { ...REGISTRATION, filter: undefined }], + ['a non-object', 'nonsense'] + ])('keeps the device but drops %s', (_name, pushRegistration) => { + const dir = userDataDir() + const device = new DeviceRegistry(dir).addDevice('phone', 'mobile') + rewriteRegistry(dir, (devices) => { + for (const entry of devices) { + entry.pushRegistration = pushRegistration + } + }) + + const reloaded = new DeviceRegistry(dir) + expect(reloaded.listDevices()).toHaveLength(1) + expect(reloaded.getDevice(device.deviceId)?.pushRegistration).toBeUndefined() + }) + + it('drops only the unknown members of a stored filter', () => { + const dir = userDataDir() + const device = new DeviceRegistry(dir).addDevice('phone', 'mobile') + rewriteRegistry(dir, (devices) => { + for (const entry of devices) { + entry.pushRegistration = { + ...REGISTRATION, + filter: { sound: false, unknownSetting: true } + } + } + }) + + expect(new DeviceRegistry(dir).getDevice(device.deviceId)?.pushRegistration?.filter).toEqual({ + sound: false + }) + }) +}) diff --git a/src/main/runtime/push/push-dispatcher.test-fixture.ts b/src/main/runtime/push/push-dispatcher.test-fixture.ts new file mode 100644 index 00000000000..16baada47d8 --- /dev/null +++ b/src/main/runtime/push/push-dispatcher.test-fixture.ts @@ -0,0 +1,88 @@ +import { vi } from 'vitest' +import type { MobilePushRegistration } from '../../../shared/mobile-push-contract' +import type { MobileNotificationEvent } from '../runtime-mobile-notification-controller' +import type { PushGatewayClient, PushSendResult } from './push-gateway-client' +import { PushDispatcher, type PushDispatcherRegistry } from './push-dispatcher' + +export function registration( + overrides: Partial = {} +): MobilePushRegistration { + return { + registrationId: 'reg-1', + filter: {}, + expiresAt: Date.now() + 7 * 86400_000, + ...overrides + } +} + +export type SendCall = Parameters[0] + +export function createHarness(options: { + devices: { deviceId: string; pushRegistration?: MobilePushRegistration }[] + results?: PushSendResult[] + sendImpl?: () => Promise +}): { + dispatcher: PushDispatcher + sends: SendCall[] + cleared: (string | null)[] + runRetry: () => void +} { + const sends: SendCall[] = [] + const cleared: (string | null)[] = [] + let retry: (() => void) | null = null + const client = { + send: vi.fn(async (input: SendCall) => { + sends.push(input) + if (options.sendImpl) { + return await options.sendImpl() + } + return { + ok: true as const, + results: + options.results ?? + input.registrationIds.map((registrationId) => ({ + registrationId, + status: 'queued' as const + })) + } + }) + } as unknown as PushGatewayClient + const registry: PushDispatcherRegistry = { + listDevices: () => options.devices, + setPushRegistration: (deviceId, value) => { + cleared.push(value === null ? deviceId : null) + return true + } + } + return { + dispatcher: new PushDispatcher({ + client, + registry, + scheduleRetry: (run) => { + retry = run + } + }), + sends, + cleared, + runRetry: () => retry?.() + } +} + +export function notification( + overrides: Partial = {} +): MobileNotificationEvent { + return { + type: 'notification', + source: 'agent-task-complete', + title: 'feat/x - Claude finished', + body: 'All done.', + worktreeId: 'repo::wt1', + notificationId: 'agent:one', + notificationSeq: 7, + notificationEpoch: 'epoch-1', + agentState: 'done', + ...overrides + } as MobileNotificationEvent +} + +export const flush = (): Promise => new Promise((resolve) => setImmediate(resolve)) diff --git a/src/main/runtime/push/push-dispatcher.test.ts b/src/main/runtime/push/push-dispatcher.test.ts new file mode 100644 index 00000000000..47373045f28 --- /dev/null +++ b/src/main/runtime/push/push-dispatcher.test.ts @@ -0,0 +1,188 @@ +import { describe, expect, it, vi } from 'vitest' +import type { PushGatewayClient } from './push-gateway-client' +import { PushDispatcher } from './push-dispatcher' +import { + createHarness, + flush, + notification, + registration, + type SendCall +} from './push-dispatcher.test-fixture' + +describe('PushDispatcher', () => { + it('batches every matching registration into one send', async () => { + const harness = createHarness({ + devices: [ + { deviceId: 'a', pushRegistration: registration({ registrationId: 'reg-a' }) }, + { deviceId: 'b', pushRegistration: registration({ registrationId: 'reg-b' }) }, + { deviceId: 'c' } + ] + }) + + harness.dispatcher.enqueue(notification()) + await flush() + + expect(harness.sends).toHaveLength(1) + expect(harness.sends[0]?.registrationIds).toEqual(['reg-a', 'reg-b']) + expect(harness.sends[0]?.notification).toMatchObject({ + source: 'agent-task-complete', + agentState: 'finished', + notificationSeq: 7, + notificationEpoch: 'epoch-1', + worktreeId: 'repo::wt1' + }) + }) + + it('fans out past the per-request cap instead of starving the extra devices', async () => { + const devices = Array.from({ length: 25 }, (_, index) => ({ + deviceId: `device-${index}`, + pushRegistration: registration({ registrationId: `reg-${index}` }) + })) + const harness = createHarness({ devices }) + + harness.dispatcher.enqueue(notification()) + await flush() + + expect(harness.sends).toHaveLength(2) + expect(harness.sends[0]?.registrationIds).toHaveLength(20) + expect(harness.sends[1]?.registrationIds).toEqual([ + 'reg-20', + 'reg-21', + 'reg-22', + 'reg-23', + 'reg-24' + ]) + }) + + it('drops a dead registration reported by a later chunk', async () => { + const devices = Array.from({ length: 25 }, (_, index) => ({ + deviceId: `device-${index}`, + pushRegistration: registration({ registrationId: `reg-${index}` }) + })) + const harness = createHarness({ + devices, + results: [{ registrationId: 'reg-24', status: 'dead' }] + }) + + harness.dispatcher.enqueue(notification()) + await flush() + + expect(harness.cleared).toEqual(['device-24']) + }) + + it('pushes a silent dismissal with an absolute expiry', async () => { + const harness = createHarness({ + devices: [{ deviceId: 'a', pushRegistration: registration() }] + }) + + harness.dispatcher.enqueue({ + type: 'dismiss', + notificationId: 'agent:one', + notificationSeq: 8, + notificationEpoch: 'epoch-1' + }) + await flush() + + expect(harness.sends).toHaveLength(1) + expect(harness.sends[0]?.notification).toMatchObject({ + kind: 'dismiss', + sound: false, + notificationId: 'agent:one', + expiresAt: expect.any(Number) + }) + }) + + it('stays silent while the agent is still working', async () => { + const harness = createHarness({ + devices: [{ deviceId: 'a', pushRegistration: registration() }] + }) + + harness.dispatcher.enqueue(notification({ agentState: 'working' })) + await flush() + + expect(harness.sends).toHaveLength(0) + }) + + it('drops a registration the gateway reports dead', async () => { + const harness = createHarness({ + devices: [ + { deviceId: 'a', pushRegistration: registration({ registrationId: 'reg-a' }) }, + { deviceId: 'b', pushRegistration: registration({ registrationId: 'reg-b' }) } + ], + results: [ + { registrationId: 'reg-a', status: 'dead' }, + { registrationId: 'reg-b', status: 'queued' } + ] + }) + + harness.dispatcher.enqueue(notification()) + await flush() + + expect(harness.cleared).toEqual(['a']) + }) + + it('retries once when the gateway is unreachable', async () => { + const sends: SendCall[] = [] + const client = { + send: vi.fn(async (input: SendCall) => { + sends.push(input) + return { ok: false as const, reason: 'unreachable' as const } + }) + } as unknown as PushGatewayClient + const scheduled: (() => void)[] = [] + const devices = [{ deviceId: 'a', pushRegistration: registration() }] + const dispatcher = new PushDispatcher({ + client, + registry: { + listDevices: () => devices, + setPushRegistration: () => true + }, + scheduleRetry: (run, delayMs) => { + expect(delayMs).toBe(2_000) + scheduled.push(run) + } + }) + + dispatcher.enqueue(notification()) + await flush() + expect(sends).toHaveLength(1) + expect(scheduled).toHaveLength(1) + + scheduled[0]?.() + await flush() + expect(sends).toHaveLength(2) + // The second attempt is the last one; a further retry is never scheduled. + expect(scheduled).toHaveLength(1) + }) + + it('never throws into the caller when the client rejects', async () => { + const harness = createHarness({ + devices: [{ deviceId: 'a', pushRegistration: registration() }], + sendImpl: async () => { + throw new Error('boom') + } + }) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + expect(() => harness.dispatcher.enqueue(notification())).not.toThrow() + await flush() + expect(warn).toHaveBeenCalled() + warn.mockRestore() + }) + + it('never throws when the registry itself fails', async () => { + const dispatcher = new PushDispatcher({ + client: { send: vi.fn() } as unknown as PushGatewayClient, + registry: { + listDevices: () => { + throw new Error('registry unavailable') + }, + setPushRegistration: () => true + } + }) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + expect(() => dispatcher.enqueue(notification())).not.toThrow() + warn.mockRestore() + }) +}) diff --git a/src/main/runtime/push/push-dispatcher.ts b/src/main/runtime/push/push-dispatcher.ts new file mode 100644 index 00000000000..e028b80d858 --- /dev/null +++ b/src/main/runtime/push/push-dispatcher.ts @@ -0,0 +1,271 @@ +import { reserveNotificationCooldown } from '../../../shared/notification-burst-cooldown' +// Why: the out-of-band leg of the mobile notification fan-out. Every event that +// already went to connected sockets is offered to the push gateway so a phone +// with Orca closed still hears about it. Fire-and-forget by construction: the +// socket fan-out must never wait on, or fail because of, a push. +import { + MOBILE_PUSH_SOURCES, + type MobilePushAgentState, + type MobilePushRegistration +} from '../../../shared/mobile-push-contract' +import type { MobileNotificationEvent } from '../runtime-mobile-notification-controller' +import type { PushGatewayClient, PushSendNotification } from './push-gateway-client' +import { PushOutcomeCounters } from './push-outcome-counters' + +const PUSH_RETRY_DELAY_MS = 2_000 +// The gateway rejects a whole request above this, so a host with more paired +// phones fans out across several sends rather than starving the extras. +const MAX_REGISTRATIONS_PER_SEND = 20 +const PUSH_TITLE_MAX_LENGTH = 80 +const PUSH_BODY_MAX_LENGTH = 180 + +export type PushDispatcherRegistry = { + listDevices(): readonly { deviceId: string; pushRegistration?: MobilePushRegistration }[] + setPushRegistration(deviceId: string, registration: MobilePushRegistration | null): boolean +} + +type PushDispatcherOptions = { + client: PushGatewayClient + registry: PushDispatcherRegistry + /** Test seam: lets a suite drive the single retry without real time. */ + scheduleRetry?: (run: () => void, delayMs: number) => void +} + +type PushTarget = { deviceId: string; registration: MobilePushRegistration } + +function clip(value: string, maxLength: number): string { + const normalized = value.replace(/\s+/g, ' ').trim() + return normalized.length <= maxLength ? normalized : `${normalized.slice(0, maxLength - 1)}…` +} + +export function mapPushAgentState( + source: string, + state: string | undefined +): MobilePushAgentState | null | undefined { + if (source !== 'agent-task-complete') { + return null + } + if (state === 'blocked' || state === 'waiting' || state === 'needs-input') { + return 'needs-input' + } + return state === undefined || state === 'done' || state === 'finished' ? 'finished' : undefined +} + +function allowsPushDelivery( + registration: MobilePushRegistration, + event: MobileNotificationEvent +): boolean { + return ( + event.type === 'notification' && + event.desktopAllowed !== false && + (!registration.filter.onlyWhenDesktopAway || event.desktopAway !== false) + ) +} + +export class PushDispatcher { + private readonly recentNotifications = new Map() + private readonly outcomes = new PushOutcomeCounters() + private stopped = false + private readonly client: PushGatewayClient + private readonly registry: PushDispatcherRegistry + private readonly scheduleRetry: (run: () => void, delayMs: number) => void + + constructor(options: PushDispatcherOptions) { + this.client = options.client + this.registry = options.registry + this.scheduleRetry = + options.scheduleRetry ?? + ((run, delayMs) => { + // Why: a pending push retry must never hold the app open at quit. + setTimeout(run, delayMs).unref?.() + }) + } + + start(): void { + this.stopped = false + } + + stop(): void { + this.stopped = true + this.outcomes.flush() + } + + enqueue(event: MobileNotificationEvent): void { + if (this.stopped) { + return + } + try { + const plan = this.planSend(event) + if (!plan) { + return + } + for (const sound of [true, false]) { + const targets = plan.targets.filter( + (target) => (target.registration.filter.sound !== false) === sound + ) + for (let start = 0; start < targets.length; start += MAX_REGISTRATIONS_PER_SEND) { + void this.deliver( + targets.slice(start, start + MAX_REGISTRATIONS_PER_SEND), + { ...plan.notification, ...(!sound ? { sound: false } : {}) }, + 0 + ) + } + } + } catch (error) { + console.warn('[push] Failed to prepare a push notification:', error) + } + } + + private planSend( + event: MobileNotificationEvent + ): { targets: PushTarget[]; notification: PushSendNotification } | null { + if (event.type === 'dismiss') { + if (event.notificationSeq === undefined || !event.notificationEpoch) { + return null + } + const targets = this.registry + .listDevices() + .flatMap(({ deviceId, pushRegistration: registration }) => + registration && registration.expiresAt > Date.now() ? [{ deviceId, registration }] : [] + ) + return { + targets, + notification: { + kind: 'dismiss', + expiresAt: Date.now() + 300_000, + notificationId: event.notificationId, + notificationSeq: event.notificationSeq, + notificationEpoch: event.notificationEpoch, + source: 'agent-task-complete', + agentState: null, + title: 'Orca', + body: '', + sound: false + } + } + } + const source = MOBILE_PUSH_SOURCES.find((candidate) => candidate === event.source) + if (!source || event.notificationSeq === undefined || event.notificationEpoch === undefined) { + return null + } + const agentState = mapPushAgentState(source, event.agentState) + if (agentState === undefined) { + return null + } + const targets = this.registry.listDevices().flatMap((device) => { + const registration = device.pushRegistration + if ( + !registration || + registration.expiresAt <= Date.now() || + !allowsPushDelivery(registration, event) + ) { + return [] + } + if ( + event.emittedAt !== undefined && + !reserveNotificationCooldown( + this.recentNotifications, + JSON.stringify([device.deviceId, event.worktreeId ?? 'global']), + event.emittedAt + ) + ) { + return [] + } + return [{ deviceId: device.deviceId, registration }] + }) + if (targets.length === 0) { + return null + } + return { + targets, + notification: { + expiresAt: Date.now() + 300_000, + ...(event.notificationId ? { notificationId: event.notificationId } : {}), + notificationSeq: event.notificationSeq, + notificationEpoch: event.notificationEpoch, + source, + agentState, + title: clip(event.title, PUSH_TITLE_MAX_LENGTH), + body: clip(event.body, PUSH_BODY_MAX_LENGTH), + ...(event.worktreeId ? { worktreeId: event.worktreeId } : {}) + } + } + } + + private async deliver( + targets: readonly PushTarget[], + notification: PushSendNotification, + attempt: number + ): Promise { + if (this.stopped) { + return + } + const currentTargets = targets.filter((target) => + this.registry + .listDevices() + .some( + (device) => + device.deviceId === target.deviceId && + device.pushRegistration === target.registration && + target.registration.expiresAt > Date.now() + ) + ) + if (!currentTargets.length) { + return + } + try { + const result = await this.client.send({ + registrationIds: currentTargets.map((target) => target.registration.registrationId), + notification + }) + if (this.stopped) { + return + } + if (result.ok) { + for (const entry of result.results) { + if (entry.status === 'error' || entry.status === 'rate_limited') { + this.outcomes.record(entry.status) + } + } + this.dropDeadRegistrations(targets, result.results) + return + } + this.outcomes.record(result.reason) + // Only a transport-level miss is worth repeating; a gateway that refused + // this payload will refuse the identical retry. + if (attempt === 0 && result.reason === 'unreachable') { + this.scheduleRetry(() => { + void this.deliver(targets, notification, attempt + 1) + }, PUSH_RETRY_DELAY_MS) + } + } catch (error) { + console.warn('[push] Push send failed:', error) + } + } + + private dropDeadRegistrations( + targets: readonly PushTarget[], + results: readonly { registrationId: string; status: string }[] + ): void { + for (const result of results) { + if (result.status !== 'dead') { + continue + } + const target = targets.find( + (entry) => entry.registration.registrationId === result.registrationId + ) + if ( + !target || + this.registry.listDevices().find((device) => device.deviceId === target.deviceId) + ?.pushRegistration !== target.registration + ) { + continue + } + try { + this.registry.setPushRegistration(target.deviceId, null) + } catch (error) { + console.warn('[push] Failed to drop a dead push registration:', error) + } + } + } +} diff --git a/src/main/runtime/push/push-gateway-client.test.ts b/src/main/runtime/push/push-gateway-client.test.ts new file mode 100644 index 00000000000..0707f686fae --- /dev/null +++ b/src/main/runtime/push/push-gateway-client.test.ts @@ -0,0 +1,256 @@ +import { describe, expect, it, vi } from 'vitest' +import { createHash } from 'node:crypto' +import { buildPushChallengeFixture, createPushHostKeypair } from './push-host-challenge-fixtures' +import { PushGatewayClient } from './push-gateway-client' + +const GATEWAY_URL = 'https://push.onorca.dev' +const NOW = 1_770_000_000_000 + +type Recorded = { + url: string + method: string + authorization: string | null + body: unknown + redirect: RequestRedirect | undefined +} + +function fingerprintOf(publicKey: Uint8Array): string { + return createHash('sha256').update(publicKey).digest('base64url').slice(0, 16) +} + +function jsonResponse(status: number, body: unknown): Response { + return new Response(JSON.stringify(body), { + status, + headers: { 'content-type': 'application/json' } + }) +} + +function createFakeGateway( + options: { sessionTtlMs?: number; devicesStatus?: number; rejectBearer?: boolean } = {} +): { + client: PushGatewayClient + calls: Recorded[] + expireSession: () => void + now: { value: number } +} { + const hostKeypair = createPushHostKeypair() + const hostFingerprint = fingerprintOf(hostKeypair.publicKey) + const now = { value: NOW } + const calls: Recorded[] = [] + const liveTokens = new Set() + const knownRegistrations = new Set() + let issued = 0 + let pendingProof: string | null = null + + const fetchImpl = (async (input: string, init?: RequestInit): Promise => { + const url = String(input) + const headers = new Headers(init?.headers) + const body: unknown = init?.body ? JSON.parse(String(init.body)) : undefined + calls.push({ + url, + method: init?.method ?? 'GET', + authorization: headers.get('authorization'), + body, + redirect: init?.redirect + }) + if (url.endsWith('/v1/host/challenge')) { + const built = buildPushChallengeFixture({ + hostKeypair, + gatewayOrigin: GATEWAY_URL, + hostFingerprint, + issuedAt: now.value, + challengeId: `challenge-${++issued}` + }) + pendingProof = built.proof + return jsonResponse(200, built.challenge) + } + if (url.endsWith('/v1/host/session')) { + const params = body as { proofB64: string } + if (params.proofB64 !== pendingProof) { + return jsonResponse(401, { error: 'bad_proof' }) + } + const sessionToken = `session-${issued}` + liveTokens.add(sessionToken) + return jsonResponse(200, { + sessionToken, + expiresAt: now.value + (options.sessionTtlMs ?? 24 * 60 * 60_000), + hostFingerprint + }) + } + const bearer = headers.get('authorization')?.replace('Bearer ', '') ?? '' + if (options.rejectBearer || !liveTokens.has(bearer)) { + return jsonResponse(401, { error: 'session_expired' }) + } + if (url.endsWith('/v1/devices')) { + if (options.devicesStatus) { + return jsonResponse(options.devicesStatus, { error: 'nope' }) + } + knownRegistrations.add('reg-1') + return jsonResponse(200, { registrationId: 'reg-1' }) + } + if (url.endsWith('/v1/send')) { + return jsonResponse(200, { results: [{ registrationId: 'reg-1', status: 'queued' }] }) + } + // Why explicit: a catch-all 204 would report every delete as accepted and + // leave the 404 branch of deleteDevice untested. + const deleted = /\/v1\/devices\/([^/]+)$/.exec(url) + if (deleted && init?.method === 'DELETE') { + const registrationId = decodeURIComponent(deleted[1] ?? '') + return new Response(null, { status: knownRegistrations.has(registrationId) ? 204 : 404 }) + } + throw new Error(`unexpected request: ${init?.method ?? 'GET'} ${url}`) + }) as unknown as typeof globalThis.fetch + + return { + client: new PushGatewayClient({ + gatewayUrl: GATEWAY_URL, + keypair: hostKeypair, + fetch: fetchImpl, + now: () => now.value + }), + calls, + expireSession: () => liveTokens.clear(), + now + } +} + +const REGISTER_INPUT = { + deviceId: 'device-1', + platform: 'ios' as const, + token: 'a'.repeat(64), + apnsEnvironment: 'sandbox' as const +} + +describe('PushGatewayClient', () => { + it('runs the challenge handshake once and reuses the cached session', async () => { + const gateway = createFakeGateway() + + expect(await gateway.client.registerDevice(REGISTER_INPUT)).toEqual({ + ok: true, + registrationId: 'reg-1' + }) + expect( + await gateway.client.send({ + registrationIds: ['reg-1'], + notification: { + notificationSeq: 1, + notificationEpoch: 'epoch-1', + source: 'agent-task-complete', + agentState: 'finished', + title: 'Done', + body: 'Body' + } + }) + ).toEqual({ ok: true, results: [{ registrationId: 'reg-1', status: 'queued' }] }) + + const handshakes = gateway.calls.filter((call) => call.url.includes('/v1/host/')) + expect(handshakes).toHaveLength(2) + expect(gateway.calls.at(-1)?.authorization).toBe('Bearer session-1') + }) + + it('re-authenticates once when the gateway rejects the cached session', async () => { + const gateway = createFakeGateway() + await gateway.client.registerDevice(REGISTER_INPUT) + gateway.expireSession() + + expect(await gateway.client.registerDevice(REGISTER_INPUT)).toEqual({ + ok: true, + registrationId: 'reg-1' + }) + expect(gateway.calls.filter((call) => call.url.endsWith('/v1/host/challenge'))).toHaveLength(2) + expect(gateway.calls.at(-1)?.authorization).toBe('Bearer session-2') + }) + + it('re-authenticates before a session that is about to expire', async () => { + const gateway = createFakeGateway({ sessionTtlMs: 90_000 }) + await gateway.client.registerDevice(REGISTER_INPUT) + gateway.now.value += 60_000 + + await gateway.client.registerDevice(REGISTER_INPUT) + expect(gateway.calls.filter((call) => call.url.endsWith('/v1/host/challenge'))).toHaveLength(2) + }) + + it('shares one handshake across concurrent calls', async () => { + const gateway = createFakeGateway() + await Promise.all([ + gateway.client.registerDevice(REGISTER_INPUT), + gateway.client.registerDevice(REGISTER_INPUT) + ]) + expect(gateway.calls.filter((call) => call.url.endsWith('/v1/host/challenge'))).toHaveLength(1) + }) + + it('reports an unreachable gateway instead of throwing', async () => { + const keypair = createPushHostKeypair() + const client = new PushGatewayClient({ + gatewayUrl: GATEWAY_URL, + keypair, + fetch: vi.fn(async () => { + throw new Error('network down') + }) as unknown as typeof globalThis.fetch, + now: () => NOW + }) + expect(await client.registerDevice(REGISTER_INPUT)).toEqual({ + ok: false, + reason: 'unreachable' + }) + }) + + it('reports a refused registration as rejected', async () => { + const gateway = createFakeGateway({ devicesStatus: 400 }) + expect(await gateway.client.registerDevice(REGISTER_INPUT)).toEqual({ + ok: false, + reason: 'rejected' + }) + }) + + it('never follows a redirect, on the handshake or on an authorized call', async () => { + const gateway = createFakeGateway() + + await gateway.client.registerDevice(REGISTER_INPUT) + await gateway.client.deleteDevice('reg-1') + + // A 307 would replay the host proof, then the phone's token, to whatever + // origin the redirect named. + expect(gateway.calls.length).toBeGreaterThanOrEqual(4) + expect(gateway.calls.every((call) => call.redirect === 'error')).toBe(true) + }) + + it('reports a gateway 5xx as unreachable so the caller can retry', async () => { + const gateway = createFakeGateway({ devicesStatus: 503 }) + expect(await gateway.client.registerDevice(REGISTER_INPUT)).toEqual({ + ok: false, + reason: 'unreachable' + }) + }) + + it('treats a delete the gateway accepted as done', async () => { + const gateway = createFakeGateway() + await gateway.client.registerDevice(REGISTER_INPUT) + + expect(await gateway.client.deleteDevice('reg-1')).toEqual(true) + expect(gateway.calls.at(-1)).toMatchObject({ method: 'DELETE' }) + }) + + it('treats a delete of an unknown registration as done', async () => { + const gateway = createFakeGateway() + + expect(await gateway.client.deleteDevice('reg-gone')).toEqual(true) + }) + + it('reports a 401 that survives the forced re-auth as unreachable', async () => { + const gateway = createFakeGateway({ rejectBearer: true }) + + expect(await gateway.client.registerDevice(REGISTER_INPUT)).toEqual({ + ok: false, + reason: 'unreachable' + }) + // Exactly one forced re-auth, not a handshake loop. + expect(gateway.calls.filter((call) => call.url.endsWith('/v1/host/challenge'))).toHaveLength(2) + }) + + it('keeps an unreachable-classified 401 retryable for a queued delete', async () => { + const gateway = createFakeGateway({ rejectBearer: true }) + + expect(await gateway.client.deleteDevice('reg-1')).toEqual(false) + }) +}) diff --git a/src/main/runtime/push/push-gateway-client.ts b/src/main/runtime/push/push-gateway-client.ts new file mode 100644 index 00000000000..05fb9a1ffef --- /dev/null +++ b/src/main/runtime/push/push-gateway-client.ts @@ -0,0 +1,172 @@ +// Why: talks to the Orca push gateway (cloud/packages/push-contract/src). +// Every method returns a result instead of throwing — push is best-effort and +// must never break the socket fan-out it rides along with. +import { z } from 'zod' +import { cancelUnreadResponseBody } from '../../lib/unread-response-body' +import type { E2EEKeypair } from '../e2ee-keypair' +import type { + MobilePushAgentState, + MobilePushApnsEnvironment, + MobilePushPlatform, + MobilePushSource +} from '../../../shared/mobile-push-contract' +import { + PUSH_REQUEST_DEADLINE_MS, + readPushGatewayJson, + type PushGatewayFailure, + type PushGatewayResponse, + type PushGatewayResult +} from './push-gateway-response' +import { PushGatewaySession } from './push-gateway-session' + +export type { PushGatewayFailure, PushGatewayResult } + +const RegisterResponseSchema = z.object({ registrationId: z.string().min(1).max(512) }) + +const SendResponseSchema = z.object({ + results: z + .array( + z.object({ + registrationId: z.string().min(1).max(512), + status: z.enum(['queued', 'dead', 'rate_limited', 'error']) + }) + ) + .max(64) +}) + +export type PushSendResult = z.infer['results'][number] + +export type PushSendNotification = { + kind?: 'alert' | 'dismiss' + expiresAt?: number + sound?: boolean + notificationId?: string + notificationSeq: number + notificationEpoch: string + source: MobilePushSource + agentState: MobilePushAgentState | null + title: string + body: string + worktreeId?: string +} + +type PushGatewayClientOptions = { + gatewayUrl: string + keypair: E2EEKeypair + fetch?: typeof globalThis.fetch + now?: () => number +} + +type AuthorizedResponse = { ok: true; response: Response; token: string } | PushGatewayFailure + +export class PushGatewayClient { + private readonly origin: string + private readonly fetchImpl: typeof globalThis.fetch + private readonly session: PushGatewaySession + + constructor(options: PushGatewayClientOptions) { + this.origin = new URL(options.gatewayUrl).origin + this.fetchImpl = options.fetch ?? globalThis.fetch + this.session = new PushGatewaySession({ + origin: this.origin, + keypair: options.keypair, + fetchImpl: this.fetchImpl, + now: options.now ?? Date.now + }) + } + + async registerDevice(input: { + deviceId: string + platform: MobilePushPlatform + token: string + apnsEnvironment?: MobilePushApnsEnvironment + }): Promise> { + const response = await this.authorized('/v1/devices', { + method: 'POST', + body: { + v: 1, + deviceId: input.deviceId, + platform: input.platform, + token: input.token, + ...(input.apnsEnvironment ? { apnsEnvironment: input.apnsEnvironment } : {}) + } + }) + const parsed = await readPushGatewayJson(response, RegisterResponseSchema) + return parsed.ok ? { ok: true, registrationId: parsed.value.registrationId } : parsed + } + + async deleteDevice(registrationId: string): Promise { + const response = await this.authorized(`/v1/devices/${encodeURIComponent(registrationId)}`, { + method: 'DELETE' + }) + if (!response.ok) { + return false + } + await cancelUnreadResponseBody(response.response) + // A gateway that no longer knows the registration is as deleted as it gets. + return response.response.ok || response.response.status === 404 + } + + async send(input: { + registrationIds: readonly string[] + notification: PushSendNotification + }): Promise> { + const response = await this.authorized('/v1/send', { + method: 'POST', + body: { + v: 1, + registrationIds: [...input.registrationIds], + notification: input.notification + } + }) + const parsed = await readPushGatewayJson(response, SendResponseSchema) + return parsed.ok ? { ok: true, results: parsed.value.results } : parsed + } + + private async authorized( + path: string, + init: { method: string; body?: unknown } + ): Promise { + const first = await this.sendAuthorized(path, init, null) + if (!first.ok || first.response.status !== 401) { + return first + } + // A 401 means that one session died server-side; one forced re-auth, then stop. + await cancelUnreadResponseBody(first.response) + const retried = await this.sendAuthorized(path, init, first.token) + if (retried.ok && retried.response.status === 401) { + await cancelUnreadResponseBody(retried.response) + // A 401 that survives a freshly minted session is the gateway being unusable + // right now, not this request being wrong: register should report it as + // unreachable, and send should still spend its one retry. + return { ok: false, reason: 'unreachable' } + } + return retried + } + + private async sendAuthorized( + path: string, + init: { method: string; body?: unknown }, + staleToken: string | null + ): Promise { + const outcome = await this.session.ensure(staleToken) + if (!outcome.ok) { + return outcome + } + try { + const response = await this.fetchImpl(`${this.origin}${path}`, { + method: init.method, + headers: { + authorization: `Bearer ${outcome.session.token}`, + ...(init.body === undefined ? {} : { 'content-type': 'application/json' }) + }, + redirect: 'error', + signal: AbortSignal.timeout(PUSH_REQUEST_DEADLINE_MS), + ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }) + }) + return { ok: true, response, token: outcome.session.token } + } catch { + return { ok: false, reason: 'unreachable' } + } + } +} diff --git a/src/main/runtime/push/push-gateway-origin.ts b/src/main/runtime/push/push-gateway-origin.ts new file mode 100644 index 00000000000..f4f78f2ed38 --- /dev/null +++ b/src/main/runtime/push/push-gateway-origin.ts @@ -0,0 +1,5 @@ +import { cleanCloudServiceOrigin } from '../../../shared/cloud-service-url' + +export function resolvePushGatewayOrigin(env: NodeJS.ProcessEnv, packaged: boolean): string { + return cleanCloudServiceOrigin(env.ORCA_PUSH_GATEWAY_URL, !packaged) ?? 'https://push.onorca.dev' +} diff --git a/src/main/runtime/push/push-gateway-response.ts b/src/main/runtime/push/push-gateway-response.ts new file mode 100644 index 00000000000..12a901b2943 --- /dev/null +++ b/src/main/runtime/push/push-gateway-response.ts @@ -0,0 +1,61 @@ +// Why: the authorized request path and the handshake that authorizes it must +// classify a gateway response identically — otherwise the same 503 means "retry" +// on one leg and "give up" on the other, and register/send disagree about why. +import type { z } from 'zod' +import { cancelUnreadResponseBody } from '../../lib/unread-response-body' + +export const PUSH_REQUEST_DEADLINE_MS = 15_000 + +export type PushGatewayFailure = { ok: false; reason: 'unreachable' | 'rejected' } +export type PushGatewayResult = ({ ok: true } & T) | PushGatewayFailure +export type PushGatewayResponse = { ok: true; response: Response } | PushGatewayFailure + +/** Unauthenticated POST; the handshake legs run before any session exists. */ +export async function postPushGatewayJson( + fetchImpl: typeof globalThis.fetch, + url: string, + body: unknown +): Promise { + try { + const response = await fetchImpl(url, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + // A 307 would replay the proof, and later the phone's token, to whatever + // origin the redirect named. + redirect: 'error', + signal: AbortSignal.timeout(PUSH_REQUEST_DEADLINE_MS), + body: JSON.stringify(body) + }) + return { ok: true, response } + } catch { + return { ok: false, reason: 'unreachable' } + } +} + +export async function readPushGatewayJson( + result: PushGatewayResponse, + schema: TSchema +): Promise<{ ok: true; value: z.infer } | PushGatewayFailure> { + if (!result.ok) { + return result + } + const { response } = result + if (!response.ok) { + await cancelUnreadResponseBody(response) + // 5xx and 429 are worth another attempt later; anything else is the gateway + // refusing this request as written. + return { + ok: false, + reason: response.status >= 500 || response.status === 429 ? 'unreachable' : 'rejected' + } + } + let payload: unknown + try { + payload = await response.json() + } catch { + await cancelUnreadResponseBody(response) + return { ok: false, reason: 'unreachable' } + } + const parsed = schema.safeParse(payload) + return parsed.success ? { ok: true, value: parsed.data } : { ok: false, reason: 'rejected' } +} diff --git a/src/main/runtime/push/push-gateway-session.test.ts b/src/main/runtime/push/push-gateway-session.test.ts new file mode 100644 index 00000000000..8527430365a --- /dev/null +++ b/src/main/runtime/push/push-gateway-session.test.ts @@ -0,0 +1,169 @@ +import { createHash } from 'node:crypto' +import { describe, expect, it, vi } from 'vitest' +import { buildPushChallengeFixture, createPushHostKeypair } from './push-host-challenge-fixtures' +import { PushGatewaySession, type PushSessionOutcome } from './push-gateway-session' + +const GATEWAY_ORIGIN = 'https://push.onorca.dev' +const NOW = 1_770_000_000_000 + +function jsonResponse(status: number, body: unknown): Response { + return new Response(JSON.stringify(body), { + status, + headers: { 'content-type': 'application/json' } + }) +} + +function tokenOf(outcome: PushSessionOutcome): string | null { + return outcome.ok ? outcome.session.token : null +} + +function createSessionHarness( + options: { sessionStatus?: number; challengeStatus?: number; wrongFingerprint?: boolean } = {} +): { + session: PushGatewaySession + challenges: () => number + requests: () => number + now: { value: number } +} { + const hostKeypair = createPushHostKeypair() + const hostFingerprint = createHash('sha256') + .update(hostKeypair.publicKey) + .digest('base64url') + .slice(0, 16) + const now = { value: NOW } + let issued = 0 + let requests = 0 + let pendingProof: string | null = null + + const fetchImpl = (async (input: string, init?: RequestInit): Promise => { + const url = String(input) + requests += 1 + if (url.endsWith('/v1/host/challenge')) { + if (options.challengeStatus) { + return jsonResponse(options.challengeStatus, { error: 'rate_limited' }) + } + const built = buildPushChallengeFixture({ + hostKeypair, + gatewayOrigin: GATEWAY_ORIGIN, + hostFingerprint, + issuedAt: now.value, + challengeId: `challenge-${++issued}` + }) + pendingProof = built.proof + return jsonResponse(200, built.challenge) + } + if (options.sessionStatus) { + return jsonResponse(options.sessionStatus, { error: 'nope' }) + } + const body = init?.body ? (JSON.parse(String(init.body)) as { proofB64: string }) : null + if (body?.proofB64 !== pendingProof) { + return jsonResponse(401, { error: 'bad_proof' }) + } + return jsonResponse(200, { + sessionToken: `session-${issued}`, + expiresAt: now.value + 24 * 60 * 60_000, + hostFingerprint: options.wrongFingerprint ? 'someone-else' : hostFingerprint + }) + }) as unknown as typeof globalThis.fetch + + return { + session: new PushGatewaySession({ + origin: GATEWAY_ORIGIN, + keypair: hostKeypair, + fetchImpl, + now: () => now.value + }), + challenges: () => issued, + requests: () => requests, + now + } +} + +describe('PushGatewaySession', () => { + it('reuses the cached session until it nears expiry', async () => { + const harness = createSessionHarness() + + expect(tokenOf(await harness.session.ensure(null))).toBe('session-1') + expect(tokenOf(await harness.session.ensure(null))).toBe('session-1') + expect(harness.challenges()).toBe(1) + }) + + it('drops only the exact session that received the 401', async () => { + const harness = createSessionHarness() + expect(tokenOf(await harness.session.ensure(null))).toBe('session-1') + + // A request that 401ed on session-1 forces a fresh handshake. + expect(tokenOf(await harness.session.ensure('session-1'))).toBe('session-2') + // A second request whose 401 also named session-1 must keep the new token. + expect(tokenOf(await harness.session.ensure('session-1'))).toBe('session-2') + expect(harness.challenges()).toBe(2) + }) + + it('reports a refused handshake as rejected rather than unreachable', async () => { + const harness = createSessionHarness({ sessionStatus: 403 }) + + expect(await harness.session.ensure(null)).toEqual({ ok: false, reason: 'rejected' }) + }) + + it('reports a session minted for another host as rejected', async () => { + const harness = createSessionHarness({ wrongFingerprint: true }) + + expect(await harness.session.ensure(null)).toEqual({ ok: false, reason: 'rejected' }) + }) + + it('caches a refusal briefly instead of re-handshaking on every call', async () => { + const harness = createSessionHarness({ sessionStatus: 403 }) + + await harness.session.ensure(null) + await harness.session.ensure(null) + expect(harness.challenges()).toBe(1) + + harness.now.value += 30_000 + await harness.session.ensure(null) + expect(harness.challenges()).toBe(2) + }) + + it('never caches a transport failure, which may clear on the next try', async () => { + const fetchImpl = vi.fn(async () => { + throw new Error('network down') + }) as unknown as typeof globalThis.fetch + const session = new PushGatewaySession({ + origin: GATEWAY_ORIGIN, + keypair: createPushHostKeypair(), + fetchImpl, + now: () => NOW + }) + + expect(await session.ensure(null)).toEqual({ ok: false, reason: 'unreachable' }) + expect(await session.ensure(null)).toEqual({ ok: false, reason: 'unreachable' }) + expect(fetchImpl).toHaveBeenCalledTimes(2) + }) + + it('reports a rate-limited challenge as unreachable and backs off', async () => { + const harness = createSessionHarness({ challengeStatus: 429 }) + + expect(await harness.session.ensure(null)).toEqual({ ok: false, reason: 'unreachable' }) + expect(await harness.session.ensure(null)).toEqual({ ok: false, reason: 'unreachable' }) + expect(harness.requests()).toBe(1) + + harness.now.value += 60_000 + await harness.session.ensure(null) + expect(harness.requests()).toBe(2) + }) + + it('reports a rate-limited session mint as unreachable, not refused', async () => { + const harness = createSessionHarness({ sessionStatus: 429 }) + + expect(await harness.session.ensure(null)).toEqual({ ok: false, reason: 'unreachable' }) + // Cached for a minute, so the next dispatch does not spend more of the bucket. + expect(await harness.session.ensure(null)).toEqual({ ok: false, reason: 'unreachable' }) + expect(harness.challenges()).toBe(1) + }) + + it('shares one handshake across concurrent callers', async () => { + const harness = createSessionHarness() + + await Promise.all([harness.session.ensure(null), harness.session.ensure(null)]) + expect(harness.challenges()).toBe(1) + }) +}) diff --git a/src/main/runtime/push/push-gateway-session.ts b/src/main/runtime/push/push-gateway-session.ts new file mode 100644 index 00000000000..dd50b813f1d --- /dev/null +++ b/src/main/runtime/push/push-gateway-session.ts @@ -0,0 +1,157 @@ +// Why: the challenge/proof handshake every push request rides on, split out of +// push-gateway-client.ts so the session cache and its refusal cache stay readable +// next to the request methods rather than buried under them. +import { z } from 'zod' +import { cancelUnreadResponseBody } from '../../lib/unread-response-body' +import type { E2EEKeypair } from '../e2ee-keypair' +import { deriveRelayHostId } from '../relay/relay-http-client' +import { answerPushHostChallenge } from './push-host-proof' +import { + postPushGatewayJson, + readPushGatewayJson, + type PushGatewayFailure +} from './push-gateway-response' + +// Re-auth a little early so a send never spends its one retry on a token that +// expired between the check and the request. +const SESSION_RENEWAL_MARGIN_MS = 60_000 +// Why: a gateway that refuses this host's proof refuses the identical next one, +// so without this every dispatch pays two full handshake round trips to relearn it. +const HANDSHAKE_REFUSAL_TTL_MS = 30_000 +// Why: the handshake routes sit behind a per-IP bucket. Backing off keeps this +// host from spending the whole bucket on challenges it will never get to use. +const HANDSHAKE_RATE_LIMIT_TTL_MS = 60_000 + +const ChallengeResponseSchema = z + .object({ + challengeId: z.string().min(1).max(512), + gatewayEphemeralPublicKeyB64: z.string().min(1).max(128), + nonceB64: z.string().min(1).max(128), + ciphertextB64: z + .string() + .min(1) + .max(8 * 1024), + expiresAt: z.number().int().positive().max(Number.MAX_SAFE_INTEGER) + }) + .strict() + +const SessionResponseSchema = z + .object({ + sessionToken: z.string().min(1).max(1024), + expiresAt: z.number().int().positive().max(Number.MAX_SAFE_INTEGER), + hostFingerprint: z.string().min(1).max(64) + }) + .strict() + +export type PushSession = { token: string; expiresAt: number } +export type PushSessionOutcome = { ok: true; session: PushSession } | PushGatewayFailure + +type PushGatewaySessionOptions = { + origin: string + keypair: E2EEKeypair + fetchImpl: typeof globalThis.fetch + now: () => number +} + +export class PushGatewaySession { + private readonly origin: string + private readonly keypair: E2EEKeypair + private readonly fetchImpl: typeof globalThis.fetch + private readonly now: () => number + readonly hostFingerprint: string + private session: PushSession | null = null + private pending: Promise | null = null + private negative: { until: number; reason: PushGatewayFailure['reason'] } | null = null + + constructor(options: PushGatewaySessionOptions) { + this.origin = options.origin + this.keypair = options.keypair + this.fetchImpl = options.fetchImpl + this.now = options.now + this.hostFingerprint = deriveRelayHostId(options.keypair.publicKey) + } + + /** + * `staleToken` is the token that just received a 401. Only that exact session is + * dropped: a concurrent request may already have installed a good one, and + * clearing unconditionally would throw it away and re-handshake for nothing. + */ + async ensure(staleToken: string | null): Promise { + if (staleToken !== null && this.session?.token === staleToken) { + this.session = null + } + const cached = this.session + if (cached && cached.expiresAt - SESSION_RENEWAL_MARGIN_MS > this.now()) { + return { ok: true, session: cached } + } + if (this.negative && this.negative.until > this.now()) { + return { ok: false, reason: this.negative.reason } + } + // Concurrent sends must not each burn a challenge; share one handshake. + this.pending ??= this.open().finally(() => { + this.pending = null + }) + return await this.pending + } + + private async open(): Promise { + const challenge = await this.handshakePost( + '/v1/host/challenge', + { v: 1, hostPublicKeyB64: this.keypair.publicKeyB64 }, + ChallengeResponseSchema + ) + if (!challenge.ok) { + return this.remember(challenge) + } + const proofB64 = answerPushHostChallenge(challenge.value, { + gatewayOrigin: this.origin, + hostFingerprint: this.hostFingerprint, + hostPublicKey: this.keypair.publicKey, + hostSecretKey: this.keypair.secretKey, + now: this.now + }) + if (!proofB64) { + // A challenge this host cannot answer is a refusal, not a dropped packet. + return this.remember({ ok: false, reason: 'rejected' }) + } + const parsed = await this.handshakePost( + '/v1/host/session', + { v: 1, challengeId: challenge.value.challengeId, proofB64 }, + SessionResponseSchema + ) + if (!parsed.ok) { + return this.remember(parsed) + } + if (parsed.value.hostFingerprint !== this.hostFingerprint) { + // The gateway answered for some other host; that token is never usable here. + return this.remember({ ok: false, reason: 'rejected' }) + } + this.session = { token: parsed.value.sessionToken, expiresAt: parsed.value.expiresAt } + this.negative = null + return { ok: true, session: this.session } + } + + private async handshakePost( + path: string, + body: unknown, + schema: TSchema + ): Promise<{ ok: true; value: z.infer } | PushGatewayFailure> { + const response = await postPushGatewayJson(this.fetchImpl, `${this.origin}${path}`, body) + if (response.ok && response.response.status === 429) { + await cancelUnreadResponseBody(response.response) + // Rate limiting refuses the moment, not this host: back off, stay retryable + // so register reports gateway_unreachable and send keeps its one retry. + this.negative = { until: this.now() + HANDSHAKE_RATE_LIMIT_TTL_MS, reason: 'unreachable' } + return { ok: false, reason: 'unreachable' } + } + return await readPushGatewayJson(response, schema) + } + + /** Caches refusals only: a transport failure may clear on the very next try. */ + private remember(failure: PushGatewayFailure): PushGatewayFailure { + if (failure.reason === 'rejected') { + this.negative = { until: this.now() + HANDSHAKE_REFUSAL_TTL_MS, reason: 'rejected' } + } + return failure + } +} diff --git a/src/main/runtime/push/push-host-challenge-fixtures.ts b/src/main/runtime/push/push-host-challenge-fixtures.ts new file mode 100644 index 00000000000..e48dec33c7a --- /dev/null +++ b/src/main/runtime/push/push-host-challenge-fixtures.ts @@ -0,0 +1,136 @@ +// Test fixtures: builds the sealed challenge the push gateway would issue, so the +// proof answerer and the gateway client can both be exercised against a real box. +import { createHmac, randomBytes } from 'node:crypto' +import nacl from 'tweetnacl' +import type { E2EEKeypair } from '../e2ee-keypair' +import type { PushHostChallenge, PushHostProofContext } from './push-host-proof' + +const encoder = new TextEncoder() +export const PUSH_PROOF_DOMAIN = 'orca-push-host-proof/v1' +export const PUSH_CHALLENGE_DOMAIN = 'orca-push-host-challenge/v1' + +function concat(parts: readonly Uint8Array[]): Uint8Array { + const output = new Uint8Array(parts.reduce((total, part) => total + part.byteLength, 0)) + let offset = 0 + for (const part of parts) { + output.set(part, offset) + offset += part.byteLength + } + return output +} + +function uint32(value: number): Uint8Array { + const bytes = new Uint8Array(4) + new DataView(bytes.buffer).setUint32(0, value, false) + return bytes +} + +function uint64(value: number): Uint8Array { + const bytes = new Uint8Array(8) + new DataView(bytes.buffer).setBigUint64(0, BigInt(value), false) + return bytes +} + +function field(name: string, value: Uint8Array): Uint8Array { + const encodedName = encoder.encode(name) + return concat([uint32(encodedName.byteLength), encodedName, uint32(value.byteLength), value]) +} + +export function text(value: string): Uint8Array { + return encoder.encode(value) +} + +export type PushTranscriptInput = { + gatewayOrigin: string + gatewayKey: Uint8Array + nonce: Uint8Array + challengeId: string + issuedAt: number + expiresAt: number + hostFingerprint: string + hostKey: Uint8Array +} + +export function buildPushTranscript(input: PushTranscriptInput): Uint8Array { + return concat([ + field('protocol', text(PUSH_PROOF_DOMAIN)), + field('version', new Uint8Array([1])), + field('gatewayOrigin', text(input.gatewayOrigin)), + field('gatewayEphemeralPublicKey', input.gatewayKey), + field('challengeNonce', input.nonce), + field('challengeId', text(input.challengeId)), + field('issuedAt', uint64(input.issuedAt)), + field('expiresAt', uint64(input.expiresAt)), + field('hostFingerprint', text(input.hostFingerprint)), + field('hostPublicKey', input.hostKey) + ]) +} + +export function pushAckProof(secret: Uint8Array, transcript: Uint8Array): string { + return createHmac('sha256', secret) + .update(text(`${PUSH_PROOF_DOMAIN}\0ack\0`)) + .update(transcript) + .digest('base64') +} + +export function createPushHostKeypair(): E2EEKeypair { + const keys = nacl.box.keyPair() + return { + publicKey: keys.publicKey, + secretKey: keys.secretKey, + publicKeyB64: Buffer.from(keys.publicKey).toString('base64') + } +} + +/** Seals a challenge for `hostPublicKey`; overrides let a suite corrupt one field at a time. */ +export function buildPushChallengeFixture(input: { + hostKeypair: E2EEKeypair + gatewayOrigin: string + hostFingerprint: string + issuedAt: number + challengeId?: string + transcript?: Partial + challenge?: Partial +}): { challenge: PushHostChallenge; context: Omit; proof: string } { + const gatewayKeys = nacl.box.keyPair() + const nonce = randomBytes(24) + const secret = randomBytes(32) + const expiresAt = input.issuedAt + 10_000 + const challengeId = input.challengeId ?? 'challenge-1' + const transcript = buildPushTranscript({ + gatewayOrigin: input.gatewayOrigin, + gatewayKey: gatewayKeys.publicKey, + nonce, + challengeId, + issuedAt: input.issuedAt, + expiresAt, + hostFingerprint: input.hostFingerprint, + hostKey: input.hostKeypair.publicKey, + ...input.transcript + }) + const plaintext = concat([ + text(`${PUSH_CHALLENGE_DOMAIN}\0`), + uint32(transcript.byteLength), + transcript, + secret + ]) + return { + challenge: { + challengeId, + gatewayEphemeralPublicKeyB64: Buffer.from(gatewayKeys.publicKey).toString('base64'), + nonceB64: nonce.toString('base64'), + ciphertextB64: Buffer.from( + nacl.box(plaintext, nonce, input.hostKeypair.publicKey, gatewayKeys.secretKey) + ).toString('base64'), + expiresAt, + ...input.challenge + }, + context: { + gatewayOrigin: input.gatewayOrigin, + hostFingerprint: input.hostFingerprint, + hostPublicKey: input.hostKeypair.publicKey, + hostSecretKey: input.hostKeypair.secretKey + }, + proof: pushAckProof(secret, transcript) + } +} diff --git a/src/main/runtime/push/push-host-proof-vector.test.ts b/src/main/runtime/push/push-host-proof-vector.test.ts new file mode 100644 index 00000000000..6a012d9cd05 --- /dev/null +++ b/src/main/runtime/push/push-host-proof-vector.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from 'vitest' +import { createHmac } from 'node:crypto' +import vector from '../../../../cloud/packages/push-contract/src/push-host-proof-vector.json' +import { answerPushHostChallenge } from './push-host-proof' + +// Why: the gateway builds the challenge and this file answers it, in two +// workspaces that cannot import each other in CI. Both replay one checked-in +// vector; a transcript field drift on either side fails here and in the +// gateway's copy of this test. +describe('push host proof vector', () => { + it('answers the checked-in gateway challenge with the expected proof', () => { + const secret = Buffer.from(vector.challengeSecretB64, 'base64') + const transcript = Buffer.from(vector.transcriptB64, 'base64') + const expected = createHmac('sha256', secret) + .update(Buffer.from('orca-push-host-proof/v1\0ack\0')) + .update(transcript) + .digest('base64') + const reasons: string[] = [] + const proof = answerPushHostChallenge(vector.challenge, { + gatewayOrigin: vector.gatewayOrigin, + hostFingerprint: vector.hostFingerprint, + hostPublicKey: Buffer.from(vector.hostPublicKeyB64, 'base64'), + hostSecretKey: Buffer.from(vector.hostSecretKeyB64, 'base64'), + now: () => vector.issuedAt + 1_000, + onInvalid: (reason) => reasons.push(reason) + }) + expect(reasons).toEqual([]) + expect(proof).toBe(expected) + }) +}) diff --git a/src/main/runtime/push/push-host-proof.test.ts b/src/main/runtime/push/push-host-proof.test.ts new file mode 100644 index 00000000000..7ec59f3a1b4 --- /dev/null +++ b/src/main/runtime/push/push-host-proof.test.ts @@ -0,0 +1,106 @@ +import { describe, expect, it } from 'vitest' +import nacl from 'tweetnacl' +import { + buildPushChallengeFixture, + createPushHostKeypair, + type PushTranscriptInput +} from './push-host-challenge-fixtures' +import { answerPushHostChallenge, type PushHostProofContext } from './push-host-proof' + +const GATEWAY_ORIGIN = 'https://push.onorca.dev' +const HOST_FINGERPRINT = 'abcdef0123456789' +const ISSUED_AT = 1_770_000_000_000 + +function fixture( + overrides: { + transcript?: Partial + challenge?: Partial[0]> + context?: Partial + } = {} +): { + challenge: Parameters[0] + context: PushHostProofContext + proof: string +} { + const built = buildPushChallengeFixture({ + hostKeypair: createPushHostKeypair(), + gatewayOrigin: GATEWAY_ORIGIN, + hostFingerprint: HOST_FINGERPRINT, + issuedAt: ISSUED_AT, + transcript: overrides.transcript, + challenge: overrides.challenge + }) + return { + challenge: built.challenge, + context: { ...built.context, now: () => ISSUED_AT + 1_000, ...overrides.context }, + proof: built.proof + } +} + +describe('answerPushHostChallenge', () => { + it('answers a well-formed challenge with the ack HMAC', () => { + const { challenge, context, proof } = fixture() + expect(answerPushHostChallenge(challenge, context)).toBe(proof) + }) + + it('tolerates clock skew inside the 30s allowance', () => { + const { challenge, context, proof } = fixture({ context: { now: () => ISSUED_AT - 20_000 } }) + expect(answerPushHostChallenge(challenge, context)).toBe(proof) + }) + + it('refuses a challenge whose secret was sealed to another host', () => { + const { challenge, context } = fixture() + expect( + answerPushHostChallenge(challenge, { + ...context, + hostSecretKey: nacl.box.keyPair().secretKey + }) + ).toBeNull() + }) + + it.each([ + ['gatewayOrigin', { gatewayOrigin: 'https://push.evil.example' }], + ['hostFingerprint', { hostFingerprint: 'ffffffffffffffff' }], + ['challengeId', { challengeId: 'challenge-other' }], + ['issuedAt', { issuedAt: ISSUED_AT + 120_000 }] + ] as const)('refuses a transcript whose %s does not match the challenge', (_name, transcript) => { + const invalid: string[] = [] + const { challenge, context } = fixture({ + transcript, + context: { onInvalid: (reason) => invalid.push(reason) } + }) + expect(answerPushHostChallenge(challenge, context)).toBeNull() + expect(invalid.join(',')).toContain('transcript') + }) + + it('refuses a transcript that swaps in a different gateway ephemeral key', () => { + const { challenge, context } = fixture({ + transcript: { gatewayKey: nacl.box.keyPair().publicKey } + }) + expect(answerPushHostChallenge(challenge, context)).toBeNull() + }) + + it('refuses an expired challenge beyond the skew allowance', () => { + const { challenge, context } = fixture({ + context: { now: () => ISSUED_AT + 10_000 + 30_001 } + }) + expect(answerPushHostChallenge(challenge, context)).toBeNull() + }) + + it('refuses a challenge whose declared expiry disagrees with the transcript', () => { + const { challenge, context } = fixture() + expect( + answerPushHostChallenge({ ...challenge, expiresAt: challenge.expiresAt + 1 }, context) + ).toBeNull() + }) + + it('refuses a non-canonical base64 ephemeral key without opening the box', () => { + const { challenge, context } = fixture() + expect( + answerPushHostChallenge( + { ...challenge, gatewayEphemeralPublicKeyB64: 'not base64!' }, + context + ) + ).toBeNull() + }) +}) diff --git a/src/main/runtime/push/push-host-proof.ts b/src/main/runtime/push/push-host-proof.ts new file mode 100644 index 00000000000..33da29f4a03 --- /dev/null +++ b/src/main/runtime/push/push-host-proof.ts @@ -0,0 +1,113 @@ +// Why: the push gateway authenticates this host the same way the relay does — +// a sealed box the host can only open with its X25519 E2EE secret key — but with +// its own domain strings and a transcript that names the host by fingerprint +// instead of by account. See cloud/packages/push-contract/src. +import { + encodeText, + equalBytes, + hostChallengeAckProof, + openHostChallengeEnvelope, + parseHostChallengeTranscript, + readTranscriptUint64 +} from '../host-challenge-envelope' + +const PUSH_HOST_PROOF_TRANSCRIPT_DOMAIN = 'orca-push-host-proof/v1' +const PUSH_HOST_CHALLENGE_PLAINTEXT_DOMAIN = 'orca-push-host-challenge/v1' +const PUSH_HOST_PROOF_CLOCK_SKEW_MS = 30_000 +const MAX_PUSH_HOST_PROOF_CHALLENGE_WINDOW_MS = 10_000 +const PUSH_HOST_PROOF_TRANSCRIPT_FIELD_COUNT = 10 + +export type PushHostChallenge = { + challengeId: string + gatewayEphemeralPublicKeyB64: string + nonceB64: string + ciphertextB64: string + expiresAt: number +} + +export type PushHostProofContext = { + gatewayOrigin: string + hostFingerprint: string + hostPublicKey: Uint8Array + hostSecretKey: Uint8Array + now?: () => number + /** Reports the failing check by name only; never receives field values. */ + onInvalid?: (reason: string) => void +} + +function validateTranscript( + transcript: Uint8Array, + challenge: PushHostChallenge, + context: PushHostProofContext, + gatewayKey: Uint8Array, + nonce: Uint8Array +): boolean { + const fields = parseHostChallengeTranscript(transcript) + if (!fields || fields.size !== PUSH_HOST_PROOF_TRANSCRIPT_FIELD_COUNT) { + context.onInvalid?.('transcript-structure') + return false + } + const now = (context.now ?? Date.now)() + const issuedAt = readTranscriptUint64(fields.get('issuedAt')) + const expiresAt = readTranscriptUint64(fields.get('expiresAt')) + const checks: [string, boolean][] = [ + ['issuedAt-readable', issuedAt !== null], + ['issuedAt-not-future', issuedAt === null || issuedAt - PUSH_HOST_PROOF_CLOCK_SKEW_MS <= now], + ['not-expired', now - PUSH_HOST_PROOF_CLOCK_SKEW_MS <= challenge.expiresAt], + ['issuedAt-before-expiry', issuedAt === null || issuedAt <= challenge.expiresAt], + [ + 'window', + issuedAt === null || challenge.expiresAt - issuedAt <= MAX_PUSH_HOST_PROOF_CHALLENGE_WINDOW_MS + ], + ['expiry-consistent', expiresAt === challenge.expiresAt], + ['protocol', equalBytes(fields.get('protocol'), encodeText(PUSH_HOST_PROOF_TRANSCRIPT_DOMAIN))], + ['version', equalBytes(fields.get('version'), new Uint8Array([1]))], + ['gatewayOrigin', equalBytes(fields.get('gatewayOrigin'), encodeText(context.gatewayOrigin))], + ['gatewayEphemeralPublicKey', equalBytes(fields.get('gatewayEphemeralPublicKey'), gatewayKey)], + ['challengeNonce', equalBytes(fields.get('challengeNonce'), nonce)], + ['challengeId', equalBytes(fields.get('challengeId'), encodeText(challenge.challengeId))], + [ + 'hostFingerprint', + equalBytes(fields.get('hostFingerprint'), encodeText(context.hostFingerprint)) + ], + ['hostPublicKey', equalBytes(fields.get('hostPublicKey'), context.hostPublicKey)] + ] + const failed = checks.filter(([, ok]) => !ok).map(([name]) => name) + if (failed.length > 0) { + context.onInvalid?.(`transcript:${failed.join('+')}`) + return false + } + return true +} + +/** Returns the base64 HMAC proof for a valid challenge, or null for anything else. */ +export function answerPushHostChallenge( + challenge: PushHostChallenge, + context: PushHostProofContext +): string | null { + const envelope = openHostChallengeEnvelope({ + peerEphemeralPublicKeyB64: challenge.gatewayEphemeralPublicKeyB64, + nonceB64: challenge.nonceB64, + ciphertextB64: challenge.ciphertextB64, + hostSecretKey: context.hostSecretKey, + plaintextDomain: PUSH_HOST_CHALLENGE_PLAINTEXT_DOMAIN, + onInvalid: context.onInvalid + }) + if ( + !envelope || + !validateTranscript( + envelope.transcript, + challenge, + context, + envelope.peerEphemeralPublicKey, + envelope.nonce + ) + ) { + return null + } + return hostChallengeAckProof({ + secret: envelope.secret, + transcript: envelope.transcript, + proofDomain: PUSH_HOST_PROOF_TRANSCRIPT_DOMAIN + }) +} diff --git a/src/main/runtime/push/push-outcome-counters.test.ts b/src/main/runtime/push/push-outcome-counters.test.ts new file mode 100644 index 00000000000..67ccc475cfc --- /dev/null +++ b/src/main/runtime/push/push-outcome-counters.test.ts @@ -0,0 +1,25 @@ +import { expect, it, vi } from 'vitest' +import { PushOutcomeCounters } from './push-outcome-counters' +it('limits failure logs while retaining category counts', () => { + let now = 0 + const log = vi.spyOn(console, 'warn').mockImplementation(() => {}) + try { + const counters = new PushOutcomeCounters(() => now) + counters.record('rejected') + counters.record('error') + counters.record('error') + expect(log).toHaveBeenCalledTimes(1) + now += 60_000 + counters.record('rate_limited') + expect(JSON.parse(String(log.mock.calls[1]![0]))).toEqual({ + event: 'orca_desktop_push_failures', + error: 2, + rate_limited: 1 + }) + counters.record('unreachable') + counters.flush() + expect(log).toHaveBeenCalledTimes(3) + } finally { + log.mockRestore() + } +}) diff --git a/src/main/runtime/push/push-outcome-counters.ts b/src/main/runtime/push/push-outcome-counters.ts new file mode 100644 index 00000000000..6b2507e5a18 --- /dev/null +++ b/src/main/runtime/push/push-outcome-counters.ts @@ -0,0 +1,27 @@ +type PushOutcome = 'error' | 'rate_limited' | 'rejected' | 'unreachable' + +export class PushOutcomeCounters { + private readonly counts = new Map() + private nextLogAt = 0 + + constructor(private readonly now: () => number = Date.now) {} + + record(outcome: PushOutcome): void { + this.counts.set(outcome, (this.counts.get(outcome) ?? 0) + 1) + if (this.now() < this.nextLogAt) { + return + } + this.nextLogAt = this.now() + 60_000 + this.flush() + } + + flush(): void { + if (!this.counts.size) { + return + } + console.warn( + JSON.stringify({ event: 'orca_desktop_push_failures', ...Object.fromEntries(this.counts) }) + ) + this.counts.clear() + } +} diff --git a/src/main/runtime/push/push-policy-pipeline.integration.test.ts b/src/main/runtime/push/push-policy-pipeline.integration.test.ts new file mode 100644 index 00000000000..47ba42052f8 --- /dev/null +++ b/src/main/runtime/push/push-policy-pipeline.integration.test.ts @@ -0,0 +1,141 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it, vi } from 'vitest' +import { readDesktopAwayState } from '../../notifications/desktop-away-state' +import { DeviceRegistry } from '../device-registry' +import { RuntimeMobileNotificationController } from '../runtime-mobile-notification-controller' +import { setRuntimeDesktopSurface } from '../runtime-desktop-surface' +import { DesktopPushService } from './desktop-push-service' +import { PushUnregisterOutbox } from './push-unregister-outbox' +import { createPushHostKeypair } from './push-host-challenge-fixtures' + +const paths: string[] = [] +const services: DesktopPushService[] = [] +const filter = { + onlyWhenDesktopAway: true +} +const flush = () => new Promise((resolve) => setImmediate(resolve)) + +afterEach(() => { + services.splice(0).forEach((service) => service.stop()) + paths.splice(0).forEach((path) => rmSync(path, { recursive: true, force: true })) + setRuntimeDesktopSurface(null) + vi.restoreAllMocks() +}) + +async function pipeline() { + const path = mkdtempSync(join(tmpdir(), 'orca-push-policy-')) + paths.push(path) + const registry = new DeviceRegistry(path) + const device = registry.addDevice('policy-phone', 'mobile') + const controller = new RuntimeMobileNotificationController() + const client = { + registerDevice: vi.fn(async () => ({ ok: true, registrationId: 'policy-registration' })), + deleteDevice: vi.fn(async () => true), + send: vi.fn(async () => ({ ok: true, results: [] })) + } + const service = DesktopPushService.create({ + runtime: { + setMobilePushRegistrar: controller.setPushRegistrar.bind(controller), + onNotificationDispatched: controller.onDispatched.bind(controller) + } as never, + runtimeRpc: { + getE2EEKeypair: () => createPushHostKeypair(), + getDeviceRegistry: () => registry, + getPushUnregisterOutbox: () => new PushUnregisterOutbox(path), + setOnPushUnregisterQueued: () => {} + } as never, + gatewayUrl: 'https://push.onorca.dev', + client: client as never + })! + services.push(service) + service.start() + const register = () => + controller.registerPushDevice({ + deviceId: device.deviceId, + platform: 'ios', + token: 'test-token', + filter + }) + expect(await register()).toMatchObject({ registered: true }) + const dispatch = () => + controller.dispatch({ + type: 'notification', + source: 'agent-task-complete', + agentState: 'done', + notificationId: 'policy-event', + title: 'Policy test', + body: 'Policy test' + }) + return { path, registry, device, controller, client, register, dispatch } +} + +it('carries the native idle boundary through replay and push dispatch', async () => { + let idle = 179 + setRuntimeDesktopSurface({ + isAwayForMobileNotifications: () => + readDesktopAwayState({ + getSystemIdleState: () => 'active', + getSystemIdleTime: () => idle + }), + showNotification: () => false, + findWindowById: () => null, + onIpc: () => {}, + removeIpcListener: () => {} + }) + const h = await pipeline() + h.dispatch() + await flush() + expect(h.client.send).not.toHaveBeenCalled() + idle = 180 + h.dispatch() + await flush() + expect(h.client.send).toHaveBeenCalledTimes(1) + idle = 0 + h.dispatch() + await flush() + expect(h.client.send).toHaveBeenCalledTimes(1) + const replay = h.controller.getMissedSince(0) + expect(replay).toHaveLength(3) + expect(replay.map((event) => (event.type === 'notification' ? event.desktopAway : null))).toEqual( + [false, true, false] + ) +}) + +it('keeps headless presence unknown and legacy socket events readable', async () => { + setRuntimeDesktopSurface(null) + const h = await pipeline() + const events: unknown[] = [] + h.controller.onDispatched((event) => events.push(JSON.parse(JSON.stringify(event)))) + h.dispatch() + await flush() + expect(events[0]).not.toHaveProperty('desktopAway') + expect(h.client.send).toHaveBeenCalledTimes(1) +}) + +it('expires persisted registration at seven days despite host activity and renews explicitly', async () => { + const now = 1_800_000_000_000 + const clock = vi.spyOn(Date, 'now').mockReturnValue(now) + const h = await pipeline() + const deadline = now + 7 * 86400_000 + const persisted = new DeviceRegistry(h.path).getDevice(h.device.deviceId)?.pushRegistration + expect(persisted?.expiresAt).toBe(deadline) + clock.mockReturnValue(deadline - 1) + h.dispatch() + await flush() + expect(h.client.send).toHaveBeenCalledTimes(1) + expect(h.registry.getDevice(h.device.deviceId)?.pushRegistration?.expiresAt).toBe(deadline) + clock.mockReturnValue(deadline) + h.dispatch() + h.controller.dismiss('policy-event') + await flush() + expect(h.client.send).toHaveBeenCalledTimes(1) + await h.register() + expect(h.registry.getDevice(h.device.deviceId)?.pushRegistration?.expiresAt).toBe( + deadline + 7 * 86400_000 + ) + h.dispatch() + await flush() + expect(h.client.send).toHaveBeenCalledTimes(2) +}) diff --git a/src/main/runtime/push/push-preferences.test.ts b/src/main/runtime/push/push-preferences.test.ts new file mode 100644 index 00000000000..947cde4fa67 --- /dev/null +++ b/src/main/runtime/push/push-preferences.test.ts @@ -0,0 +1,85 @@ +import { expect, it } from 'vitest' +import { createHarness, notification, registration, flush } from './push-dispatcher.test-fixture' + +it('applies desktop category eligibility regardless of phone sound preferences', async () => { + const harness = createHarness({ + devices: [ + { + deviceId: 'mirror', + pushRegistration: registration({ + registrationId: 'mirror' + }) + }, + { + deviceId: 'quiet', + pushRegistration: registration({ + registrationId: 'quiet', + filter: { sound: false } + }) + }, + { + deviceId: 'second-phone', + pushRegistration: registration({ registrationId: 'second-phone' }) + } + ] + }) + harness.dispatcher.enqueue(notification({ source: 'terminal-bell', desktopAllowed: false })) + await flush() + expect(harness.sends).toHaveLength(0) + + harness.dispatcher.enqueue(notification({ source: 'terminal-bell', desktopAllowed: true })) + await flush() + expect(harness.sends).toHaveLength(2) + expect(harness.sends[0]).toMatchObject({ registrationIds: ['mirror', 'second-phone'] }) + expect(harness.sends[1]).toMatchObject({ + registrationIds: ['quiet'], + notification: { sound: false } + }) +}) + +it('keeps sound preferences separate when several phones receive the same event', async () => { + const harness = createHarness({ + devices: [ + { deviceId: 'loud', pushRegistration: registration({ registrationId: 'loud' }) }, + { + deviceId: 'quiet', + pushRegistration: registration({ + registrationId: 'quiet', + filter: { ...registration().filter, sound: false } + }) + } + ] + }) + harness.dispatcher.enqueue(notification()) + await flush() + expect(harness.sends).toHaveLength(2) + expect(harness.sends[0]).toMatchObject({ registrationIds: ['loud'] }) + expect(harness.sends[0].notification.sound).toBeUndefined() + expect(harness.sends[1]).toMatchObject({ + registrationIds: ['quiet'], + notification: { sound: false } + }) +}) + +it('applies burst suppression independently to each eligible phone', async () => { + const harness = createHarness({ + devices: [ + { + deviceId: 'all', + pushRegistration: registration({ + registrationId: 'all' + }) + }, + { + deviceId: 'second-phone', + pushRegistration: registration({ + registrationId: 'second-phone' + }) + } + ] + }) + harness.dispatcher.enqueue(notification({ source: 'terminal-bell', emittedAt: 10000 })) + harness.dispatcher.enqueue(notification({ emittedAt: 10250 })) + await flush() + expect(harness.sends.map((send) => send.registrationIds)).toEqual([['all', 'second-phone']]) +}) diff --git a/src/main/runtime/push/push-register-throttle.ts b/src/main/runtime/push/push-register-throttle.ts new file mode 100644 index 00000000000..7cc31bbb11d --- /dev/null +++ b/src/main/runtime/push/push-register-throttle.ts @@ -0,0 +1,45 @@ +// Why: notifications.registerPush costs a gateway write and a synchronous +// registry write on the main thread, and a paired phone may call it as often +// as it likes. A phone legitimately registers on switch-on, on each host +// connect, and on a token change, so a small per-device bucket bounds a loop +// without getting in the way of any of those. +const DEFAULT_CAPACITY = 10 +const DEFAULT_WINDOW_MS = 60_000 + +type Bucket = { tokens: number; updatedAt: number } + +export type PushRegisterThrottleOptions = { + capacity?: number + windowMs?: number + now?: () => number +} + +export class PushRegisterThrottle { + private readonly buckets = new Map() + private readonly capacity: number + private readonly windowMs: number + private readonly now: () => number + + constructor(options: PushRegisterThrottleOptions = {}) { + this.capacity = options.capacity ?? DEFAULT_CAPACITY + this.windowMs = options.windowMs ?? DEFAULT_WINDOW_MS + this.now = options.now ?? Date.now + } + + allow(deviceId: string): boolean { + const now = this.now() + const bucket = this.buckets.get(deviceId) + const refilled = bucket + ? Math.min( + this.capacity, + bucket.tokens + Math.max(0, ((now - bucket.updatedAt) * this.capacity) / this.windowMs) + ) + : this.capacity + if (refilled < 1) { + this.buckets.set(deviceId, { tokens: refilled, updatedAt: now }) + return false + } + this.buckets.set(deviceId, { tokens: refilled - 1, updatedAt: now }) + return true + } +} diff --git a/src/main/runtime/push/push-registration-races.test.ts b/src/main/runtime/push/push-registration-races.test.ts new file mode 100644 index 00000000000..1cd946daea2 --- /dev/null +++ b/src/main/runtime/push/push-registration-races.test.ts @@ -0,0 +1,294 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it, vi } from 'vitest' +import { DeviceRegistry } from '../device-registry' +import { DesktopPushService } from './desktop-push-service' +import { PushUnregisterOutbox } from './push-unregister-outbox' +import { createPushHostKeypair } from './push-host-challenge-fixtures' +import { PushDispatcher } from './push-dispatcher' + +const paths: string[] = [] +afterEach(() => { + for (const path of paths.splice(0)) { + rmSync(path, { recursive: true, force: true }) + } +}) +const input = { + platform: 'android' as const, + token: 'synthetic', + filter: {} +} +const tick = () => new Promise((resolve) => setImmediate(resolve)) + +function harness() { + const path = mkdtempSync(join(tmpdir(), 'push-races-')) + paths.push(path) + const registry = new DeviceRegistry(path) + const deviceId = registry.addDevice('phone', 'mobile').deviceId + const outbox = new PushUnregisterOutbox(path) + const retries: { run: () => void; delayMs: number }[] = [] + let live = false + let reachable = true + const client = { + registerDevice: vi.fn(async () => { + live = true + return { ok: true, registrationId: 'stable-id' } + }), + deleteDevice: vi.fn(async (_registrationId: string) => { + if (!reachable) { + return false + } + live = false + return true + }), + send: vi.fn() + } + const service = DesktopPushService.create({ + gatewayUrl: 'https://push.example.test', + client: client as never, + scheduleRetry: (run, delayMs) => retries.push({ run, delayMs }), + runtime: { + setMobilePushRegistrar: () => {}, + onNotificationDispatched: () => () => {} + } as never, + runtimeRpc: { + getE2EEKeypair: createPushHostKeypair, + getDeviceRegistry: () => registry, + getPushUnregisterOutbox: () => outbox, + setOnPushUnregisterQueued: () => {} + } as never + })! + service.start() + return { + path, + retries, + registry, + deviceId, + outbox, + client, + service, + live: () => live, + reachable: (value: boolean) => { + reachable = value + } + } +} + +it('deletes obsolete gateway state before reporting successful re-enable', async () => { + const h = harness() + await h.service.register({ ...input, deviceId: h.deviceId }) + h.reachable(false) + await h.service.unregister(h.deviceId) + await h.service.flushUnregisterOutbox() + expect(h.outbox.pending()).toHaveLength(1) + expect(await h.service.register({ ...input, deviceId: h.deviceId })).toMatchObject({ + registered: false + }) + h.reachable(true) + expect(await h.service.register({ ...input, deviceId: h.deviceId })).toMatchObject({ + registered: true + }) + await h.service.flushUnregisterOutbox() + expect(h.live()).toBe(true) + expect(h.outbox.pending()).toEqual([]) +}) + +it('waits for an already-running delete before re-registering', async () => { + const h = harness() + await h.service.register({ ...input, deviceId: h.deviceId }) + let release!: () => void + const normalDelete = h.client.deleteDevice.getMockImplementation()! + h.client.deleteDevice.mockImplementationOnce(async () => { + await new Promise((resolve) => { + release = resolve + }) + return normalDelete('stable-id') + }) + await h.service.unregister(h.deviceId) + await tick() + const registration = h.service.register({ ...input, deviceId: h.deviceId }) + await tick() + expect(h.client.registerDevice).toHaveBeenCalledTimes(1) + release() + await registration + await h.service.flushUnregisterOutbox() + expect(h.live()).toBe(true) +}) + +it('orders unregister after a register already in flight', async () => { + const h = harness() + let release!: () => void + const normalRegister = h.client.registerDevice.getMockImplementation()! + h.client.registerDevice.mockImplementationOnce(async () => { + await new Promise((resolve) => { + release = resolve + }) + return normalRegister() + }) + const registered = h.service.register({ ...input, deviceId: h.deviceId }) + await tick() + const unregistered = h.service.unregister(h.deviceId) + release() + await Promise.all([registered, unregistered]) + await h.service.flushUnregisterOutbox() + expect(h.registry.getDevice(h.deviceId)?.pushRegistration).toBeUndefined() + expect(h.live()).toBe(false) +}) + +it('does not clear a replacement with the same ID and timestamp after a stale dead response', async () => { + const h = harness() + await h.service.register({ ...input, deviceId: h.deviceId }) + let finish!: (value: unknown) => void + h.client.send.mockImplementation( + () => + new Promise((resolve) => { + finish = resolve + }) + ) + const dispatcher = new PushDispatcher({ registry: h.registry, client: h.client as never }) + dispatcher.enqueue({ + type: 'notification', + source: 'plugin', + title: 'test', + body: '', + notificationEpoch: 'epoch', + notificationSeq: 1 + }) + const original = h.registry.getDevice(h.deviceId)!.pushRegistration! + h.registry.setPushRegistration(h.deviceId, { ...original }) + finish({ ok: true, results: [{ registrationId: 'stable-id', status: 'dead' }] }) + await tick() + expect(h.registry.getDevice(h.deviceId)?.pushRegistration).toEqual(original) +}) + +it('drains a cleanup queued as an empty flush is completing', async () => { + const h = harness() + // Let the startup drain return, but queue cleanup before its promise finalizer runs. + await Promise.resolve() + h.outbox.enqueue({ registrationId: 'orphan', deviceId: h.deviceId }) + await h.service.flushUnregisterOutbox() + expect(h.client.deleteDevice).toHaveBeenCalledWith('orphan') + expect(h.outbox.pending()).toEqual([]) +}) + +it('preserves the live route when clearing local registration fails, then cleans before re-registering', async () => { + const h = harness() + await h.service.register({ ...input, deviceId: h.deviceId }) + await h.service.flushUnregisterOutbox() + const persist = vi.spyOn(h.registry, 'setPushRegistration').mockImplementation(() => { + throw new Error('disk full') + }) + await expect(h.service.unregister(h.deviceId)).rejects.toThrow('disk full') + await tick() + expect(h.client.deleteDevice).not.toHaveBeenCalled() + expect(h.outbox.pending()).toHaveLength(1) + expect(h.live()).toBe(true) + persist.mockRestore() + expect(await h.service.register({ ...input, deviceId: h.deviceId })).toMatchObject({ + registered: true + }) + await h.service.flushUnregisterOutbox() + expect(h.client.deleteDevice).toHaveBeenCalledWith('stable-id') + expect(h.outbox.pending()).toEqual([]) + expect(h.live()).toBe(true) + h.service.stop() +}) + +it('retries an old failure before mid-drain work, then waits for the armed backoff', async () => { + const h = harness() + await h.service.flushUnregisterOutbox() + const deletes: string[] = [] + h.client.deleteDevice.mockImplementation(async (registrationId) => { + deletes.push(registrationId) + if (deletes.length === 1) { + h.outbox.enqueue({ registrationId: 'new', deviceId: 'new-phone' }) + void h.service.flushUnregisterOutbox() + } + return registrationId === 'new' + }) + h.outbox.enqueue({ registrationId: 'old', deviceId: h.deviceId }) + await h.service.flushUnregisterOutbox() + expect(deletes).toEqual(['old', 'old', 'new']) + expect(h.outbox.pending().map((item) => item.registrationId)).toEqual(['old']) + expect(h.retries.map((retry) => retry.delayMs)).toEqual([30_000]) + await tick() + expect(deletes).toHaveLength(3) + h.retries[0].run() + await tick() + expect(deletes).toEqual(['old', 'old', 'new', 'old']) + expect(h.retries.map((retry) => retry.delayMs)).toEqual([30_000, 60_000]) + h.service.stop() +}) + +it('skips a snapshot delete consumed by same-device registration cleanup', async () => { + const h = harness() + await h.service.flushUnregisterOutbox() + let release!: () => void + h.client.deleteDevice.mockImplementationOnce( + () => + new Promise((resolve) => { + release = () => resolve(true) + }) + ) + h.outbox.enqueue({ registrationId: 'blocker', deviceId: 'other-phone' }) + h.outbox.enqueue({ registrationId: 'stable-id', deviceId: h.deviceId }) + const flush = h.service.flushUnregisterOutbox() + await tick() + expect(await h.service.register({ ...input, deviceId: h.deviceId })).toMatchObject({ + registered: true + }) + expect(h.live()).toBe(true) + release() + await flush + expect(h.client.deleteDevice.mock.calls).toEqual([['blocker'], ['stable-id']]) + expect(h.outbox.pending()).toEqual([]) + expect(h.live()).toBe(true) + h.service.stop() +}) + +it('finishes the current snapshot on stop and leaves later work durable for restart', async () => { + const h = harness() + await h.service.flushUnregisterOutbox() + let release!: () => void + h.client.deleteDevice.mockImplementationOnce( + () => + new Promise((resolve) => { + release = () => resolve(false) + }) + ) + h.outbox.enqueue({ registrationId: 'blocked', deviceId: h.deviceId }) + h.outbox.enqueue({ registrationId: 'in-snapshot', deviceId: 'other-phone' }) + const flush = h.service.flushUnregisterOutbox() + await tick() + h.outbox.enqueue({ registrationId: 'late', deviceId: 'late-phone' }) + void h.service.flushUnregisterOutbox() + h.service.stop() + release() + await flush + expect(h.client.deleteDevice.mock.calls).toEqual([['blocked'], ['in-snapshot']]) + expect(h.retries).toEqual([]) + const recovered = new PushUnregisterOutbox(h.path) + expect(recovered.pending().map((item) => item.registrationId)).toEqual(['blocked', 'late']) + await h.service.flushUnregisterOutbox() + expect(h.client.deleteDevice).toHaveBeenCalledTimes(2) + h.service.start() + await h.service.flushUnregisterOutbox() + expect(h.outbox.pending()).toEqual([]) + h.service.stop() +}) + +it('reports shutdown as retryable and allows registration after restart', async () => { + const h = harness() + h.service.stop() + expect(await h.service.register({ ...input, deviceId: h.deviceId })).toEqual({ + registered: false, + reason: 'gateway_unreachable' + }) + expect(h.client.registerDevice).not.toHaveBeenCalled() + h.service.start() + expect(await h.service.register({ ...input, deviceId: h.deviceId })).toMatchObject({ + registered: true + }) + h.service.stop() +}) diff --git a/src/main/runtime/push/push-registration-rpc.test.ts b/src/main/runtime/push/push-registration-rpc.test.ts new file mode 100644 index 00000000000..f19bfe71b4d --- /dev/null +++ b/src/main/runtime/push/push-registration-rpc.test.ts @@ -0,0 +1,179 @@ +import { mkdtempSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it, vi } from 'vitest' +import { eraseRpcMethods, type RpcContext, type RpcMethod } from '../rpc/core' +import { NOTIFICATION_METHODS } from '../rpc/methods/notifications' +import { DeviceRegistry } from '../device-registry' +import { OrcaRuntimeRpcServer } from '../runtime-rpc' +import { OrcaRuntimeService } from '../orca-runtime' + +function method(name: string): RpcMethod { + const found = eraseRpcMethods(NOTIFICATION_METHODS).find((candidate) => candidate.name === name) + if (!found || 'stream' in found) { + throw new Error(`${name} is not a one-shot RPC method`) + } + return found +} + +const REGISTER_PARAMS = { + platform: 'ios', + token: 'a'.repeat(64), + apnsEnvironment: 'sandbox', + filter: {} +} + +function contextFor(overrides: Partial): RpcContext { + return { + runtime: { + registerMobilePushDevice: vi.fn(async () => ({ + registered: true, + registrationId: 'reg-1' + })), + testMobilePushDevice: vi.fn(async () => ({ accepted: true })), + unregisterMobilePushDevice: vi.fn(async () => ({ unregistered: true })) + }, + ...overrides + } as unknown as RpcContext +} + +describe('notifications.registerPush', () => { + it('registers under the authenticated paired device id', async () => { + const registerPush = method('notifications.registerPush') + const ctx = contextFor({ clientKind: 'mobile', pairedDeviceId: 'device-1' }) + + const result = await registerPush.handler(registerPush.params!.parse(REGISTER_PARAMS), ctx) + + expect(result).toEqual({ registered: true, registrationId: 'reg-1' }) + expect(ctx.runtime.registerMobilePushDevice).toHaveBeenCalledWith({ + deviceId: 'device-1', + platform: 'ios', + token: REGISTER_PARAMS.token, + apnsEnvironment: 'sandbox', + filter: REGISTER_PARAMS.filter + }) + }) + + it.each([ + ['a runtime-scoped caller', { clientKind: 'runtime' as const, pairedDeviceId: 'device-1' }], + ['an in-process caller', {}], + ['a mobile caller with no paired device', { clientKind: 'mobile' as const }] + ])('refuses %s', async (_name, overrides) => { + const registerPush = method('notifications.registerPush') + const ctx = contextFor(overrides) + + expect(await registerPush.handler(registerPush.params!.parse(REGISTER_PARAMS), ctx)).toEqual({ + registered: false, + reason: 'not_mobile' + }) + expect(ctx.runtime.registerMobilePushDevice).not.toHaveBeenCalled() + }) + + it('requires an APNs environment for an iOS token', () => { + const registerPush = method('notifications.registerPush') + expect( + registerPush.params!.safeParse({ ...REGISTER_PARAMS, apnsEnvironment: undefined }).success + ).toBe(false) + expect( + registerPush.params!.safeParse({ + ...REGISTER_PARAMS, + platform: 'android', + apnsEnvironment: undefined + }).success + ).toBe(true) + }) + + it('rejects a caller-supplied device id instead of dropping it', () => { + const registerPush = method('notifications.registerPush') + expect( + registerPush.params!.safeParse({ ...REGISTER_PARAMS, deviceId: 'device-9' }).success + ).toBe(false) + }) + + it('rejects a malformed phone preference', () => { + const registerPush = method('notifications.registerPush') + expect( + registerPush.params!.safeParse({ + ...REGISTER_PARAMS, + filter: { sound: 'yes' } + }).success + ).toBe(false) + }) +}) + +describe('notifications.unregisterPush', () => { + it('unregisters the authenticated paired device', async () => { + const unregisterPush = method('notifications.unregisterPush') + const ctx = contextFor({ clientKind: 'mobile', pairedDeviceId: 'device-1' }) + + expect(await unregisterPush.handler(undefined, ctx)).toEqual({ unregistered: true }) + expect(ctx.runtime.unregisterMobilePushDevice).toHaveBeenCalledWith('device-1') + }) + + it('refuses a non-mobile caller', async () => { + const unregisterPush = method('notifications.unregisterPush') + const ctx = contextFor({ clientKind: 'runtime', pairedDeviceId: 'device-1' }) + + expect(await unregisterPush.handler(undefined, ctx)).toEqual({ unregistered: false }) + expect(ctx.runtime.unregisterMobilePushDevice).not.toHaveBeenCalled() + }) +}) + +describe('revokeMobileDevice', () => { + it('queues the gateway delete before the device row disappears', async () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-push-revoke-')) + const server = new OrcaRuntimeRpcServer({ + runtime: new OrcaRuntimeService(), + userDataPath, + enableWebSocket: false + }) + server['deviceRegistry'] = new DeviceRegistry(userDataPath) + const device = server['deviceRegistry']!.addDevice('phone', 'mobile') + server['deviceRegistry']!.setPushRegistration(device.deviceId, { + registrationId: 'reg-1', + filter: {}, + expiresAt: Date.now() + 7 * 86400_000 + }) + + expect(await server.revokeMobileDevice(device.deviceId)).toBe(true) + expect(server.getPushUnregisterOutbox().pending()).toEqual([ + expect.objectContaining({ registrationId: 'reg-1', deviceId: device.deviceId }) + ]) + }) + + it('queues nothing for a device that never enabled push', async () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-push-revoke-')) + const server = new OrcaRuntimeRpcServer({ + runtime: new OrcaRuntimeService(), + userDataPath, + enableWebSocket: false + }) + server['deviceRegistry'] = new DeviceRegistry(userDataPath) + const device = server['deviceRegistry']!.addDevice('phone', 'mobile') + + expect(await server.revokeMobileDevice(device.deviceId)).toBe(true) + expect(server.getPushUnregisterOutbox().pending()).toEqual([]) + }) +}) + +describe('notifications.testPush', () => { + it('targets the authenticated phone and returns the service result', async () => { + const ctx = contextFor({ clientKind: 'mobile', pairedDeviceId: 'device-1' }) + expect(await method('notifications.testPush').handler(null, ctx)).toEqual({ accepted: true }) + expect(ctx.runtime.testMobilePushDevice).toHaveBeenCalledWith('device-1') + }) + it('refuses callers without an authenticated mobile identity', async () => { + for (const overrides of [ + {}, + { clientKind: 'mobile' as const }, + { clientKind: 'runtime' as const, pairedDeviceId: 'device-1' } + ]) { + const ctx = contextFor(overrides) + expect(await method('notifications.testPush').handler(null, ctx)).toEqual({ + accepted: false, + reason: 'not_registered' + }) + expect(ctx.runtime.testMobilePushDevice).not.toHaveBeenCalled() + } + }) +}) diff --git a/src/main/runtime/push/push-unpair-persistence.test.ts b/src/main/runtime/push/push-unpair-persistence.test.ts new file mode 100644 index 00000000000..560afcccd6f --- /dev/null +++ b/src/main/runtime/push/push-unpair-persistence.test.ts @@ -0,0 +1,65 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it, vi } from 'vitest' +import { DeviceRegistry } from '../device-registry' +import { OrcaRuntimeService } from '../orca-runtime' +import { DesktopPushService } from './desktop-push-service' +import { createPushHostKeypair } from './push-host-challenge-fixtures' +import { OrcaRuntimeRpcServer } from '../runtime-rpc' + +describe('mobile revoke when the registry write fails', () => { + it('preserves a live route after failed unpair and deletes it after durable removal', async () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-revoke-write-failure-')) + const runtime = new OrcaRuntimeService() + const server = new OrcaRuntimeRpcServer({ runtime, userDataPath, enableWebSocket: false }) + const registry = new DeviceRegistry(userDataPath) + const device = registry.addDevice('phone', 'mobile') + registry.setPushRegistration(device.deviceId, { + registrationId: 'reg-live', + filter: {}, + expiresAt: Date.now() + 60_000 + }) + server['deviceRegistry'] = registry + server['e2eeKeypair'] = createPushHostKeypair() + + const deleted: string[] = [] + const client = { + registerDevice: vi.fn(), + deleteDevice: vi.fn(async (registrationId: string) => { + deleted.push(registrationId) + return true + }), + send: vi.fn(async () => ({ ok: true, results: [] }) as const) + } + const service = DesktopPushService.create({ + runtime, + runtimeRpc: server, + gatewayUrl: 'https://push.onorca.dev', + client: client as never + })! + service.start() + const save = registry['save'].bind(registry) + registry['save'] = vi.fn(() => { + throw new Error('disk full') + }) + + await expect(server.revokeMobileDevice(device.deviceId)).rejects.toThrow('disk full') + await service.flushUnregisterOutbox() + + expect(registry.getDevice(device.deviceId)?.pushRegistration?.registrationId).toBe('reg-live') + expect(deleted).toEqual([]) + expect(server.getPushUnregisterOutbox().pending()).toHaveLength(1) + service.stop() + service.start() + await service.flushUnregisterOutbox() + expect(deleted).toEqual([]) + registry['save'] = save + expect(await server.revokeMobileDevice(device.deviceId)).toBe(true) + await service.flushUnregisterOutbox() + expect(deleted).toEqual(['reg-live']) + expect(server.getPushUnregisterOutbox().pending()).toEqual([]) + service.stop() + rmSync(userDataPath, { recursive: true, force: true }) + }) +}) diff --git a/src/main/runtime/push/push-unregister-outbox.test.ts b/src/main/runtime/push/push-unregister-outbox.test.ts new file mode 100644 index 00000000000..5f2d856d6ab --- /dev/null +++ b/src/main/runtime/push/push-unregister-outbox.test.ts @@ -0,0 +1,93 @@ +import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs' +import type * as fs from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it, vi } from 'vitest' +import { PushUnregisterOutbox } from './push-unregister-outbox' + +vi.mock('node:fs', async (importOriginal) => { + const original = await importOriginal() + return { ...original, readFileSync: vi.fn(original.readFileSync) } +}) + +const OUTBOX_FILENAME = 'mobile-push-unregister-outbox.json' + +function userDataDir(): string { + return mkdtempSync(join(tmpdir(), 'orca-push-outbox-')) +} + +describe('PushUnregisterOutbox', () => { + it('survives a restart with the queued delete intact', () => { + const dir = userDataDir() + const first = new PushUnregisterOutbox(dir) + const item = first.enqueue({ registrationId: 'reg-1', deviceId: 'device-1' }) + + const reopened = new PushUnregisterOutbox(dir) + expect(reopened.pending()).toEqual([item]) + }) + + it('coalesces repeat enqueues of the same registration', () => { + const dir = userDataDir() + const outbox = new PushUnregisterOutbox(dir) + const first = outbox.enqueue({ registrationId: 'reg-1', deviceId: 'device-1' }) + const second = outbox.enqueue({ registrationId: 'reg-1', deviceId: 'device-1' }) + + expect(second.reqId).toBe(first.reqId) + expect(outbox.pending()).toHaveLength(1) + }) + + it('keeps a removal durable across a restart', () => { + const dir = userDataDir() + const outbox = new PushUnregisterOutbox(dir) + const kept = outbox.enqueue({ registrationId: 'reg-keep', deviceId: 'device-1' }) + const dropped = outbox.enqueue({ registrationId: 'reg-drop', deviceId: 'device-2' }) + outbox.remove(dropped.reqId) + + expect(new PushUnregisterOutbox(dir).pending()).toEqual([kept]) + }) + + it('drops malformed rows instead of failing the whole load', () => { + const dir = userDataDir() + const valid = new PushUnregisterOutbox(dir).enqueue({ + registrationId: 'reg-1', + deviceId: 'device-1' + }) + const path = join(dir, OUTBOX_FILENAME) + const stored: unknown[] = JSON.parse(readFileSync(path, 'utf-8')) + writeFileSync( + path, + JSON.stringify([...stored, { reqId: 'broken' }, null, 'nope', { registrationId: '' }]) + ) + + expect(new PushUnregisterOutbox(dir).pending()).toEqual([valid]) + }) + + it('preserves unreadable pending deletes until the outbox can be reloaded', () => { + const dir = userDataDir() + const pending = new PushUnregisterOutbox(dir).enqueue({ + registrationId: 'reg-1', + deviceId: 'device-1' + }) + const path = join(dir, OUTBOX_FILENAME) + const original = readFileSync(path, 'utf-8') + vi.mocked(readFileSync).mockImplementationOnce(() => { + throw Object.assign(new Error('temporarily unavailable'), { code: 'EIO' }) + }) + const unreadable = new PushUnregisterOutbox(dir) + + expect(() => unreadable.enqueue({ registrationId: 'reg-2', deviceId: 'device-2' })).toThrow( + 'Cannot overwrite unreadable push unregister outbox' + ) + expect(readFileSync(path, 'utf-8')).toBe(original) + const recovered = new PushUnregisterOutbox(dir) + expect(recovered.pending()).toEqual([pending]) + recovered.enqueue({ registrationId: 'reg-2', deviceId: 'device-2' }) + expect(new PushUnregisterOutbox(dir).pending()).toHaveLength(2) + }) + + it('starts empty when the file is not JSON at all', () => { + const dir = userDataDir() + writeFileSync(join(dir, OUTBOX_FILENAME), 'not json') + expect(new PushUnregisterOutbox(dir).pending()).toEqual([]) + }) +}) diff --git a/src/main/runtime/push/push-unregister-outbox.ts b/src/main/runtime/push/push-unregister-outbox.ts new file mode 100644 index 00000000000..81b9e7a769b --- /dev/null +++ b/src/main/runtime/push/push-unregister-outbox.ts @@ -0,0 +1,93 @@ +// Why: a phone that turns background notifications off, or gets unpaired, must +// have its token deleted at the gateway even if the gateway is unreachable right +// then. Modelled on relay-revoke-outbox.ts: durable, hardened, drained on start. +import { randomUUID } from 'node:crypto' +import { existsSync, readFileSync } from 'node:fs' +import { join } from 'node:path' +import { + hardenExistingSecureFile, + isUnreadableError, + writeSecureJsonFile +} from '../../../shared/secure-file' + +export type PushUnregisterOutboxItem = { + reqId: string + registrationId: string + deviceId: string +} + +const OUTBOX_FILENAME = 'mobile-push-unregister-outbox.json' + +function isItem(value: unknown): value is PushUnregisterOutboxItem { + if (!value || typeof value !== 'object') { + return false + } + const item = value as Partial + return ( + typeof item.reqId === 'string' && + typeof item.registrationId === 'string' && + item.registrationId.length > 0 && + typeof item.deviceId === 'string' + ) +} + +export class PushUnregisterOutbox { + private readonly path: string + private outboxUnreadable = false + private items: PushUnregisterOutboxItem[] + + constructor(userDataPath: string) { + this.path = join(userDataPath, OUTBOX_FILENAME) + this.items = this.load() + } + + enqueue(entry: { registrationId: string; deviceId: string }): PushUnregisterOutboxItem { + const existing = this.items.find((item) => item.registrationId === entry.registrationId) + if (existing) { + return existing + } + const item = { ...entry, reqId: randomUUID() } + const next = [...this.items, item] + this.save(next) + this.items = next + return item + } + + isUnreadable(): boolean { + return this.outboxUnreadable + } + + pending(): readonly PushUnregisterOutboxItem[] { + return this.items + } + + remove(reqId: string): void { + const next = this.items.filter((item) => item.reqId !== reqId) + if (next.length === this.items.length) { + return + } + this.save(next) + this.items = next + } + + private load(): PushUnregisterOutboxItem[] { + if (!existsSync(this.path)) { + return [] + } + try { + hardenExistingSecureFile(this.path) + const parsed: unknown = JSON.parse(readFileSync(this.path, 'utf-8')) + return Array.isArray(parsed) ? parsed.filter(isItem) : [] + } catch (error) { + this.outboxUnreadable = isUnreadableError(error) + return [] + } + } + + private save(items: readonly PushUnregisterOutboxItem[]): void { + if (this.outboxUnreadable) { + throw new Error('Cannot overwrite unreadable push unregister outbox') + } + writeSecureJsonFile(this.path, items) + } +} diff --git a/src/main/runtime/relay/desktop-relay-service.ts b/src/main/runtime/relay/desktop-relay-service.ts index a9b4f98f3b3..74bbd4e7254 100644 --- a/src/main/runtime/relay/desktop-relay-service.ts +++ b/src/main/runtime/relay/desktop-relay-service.ts @@ -19,7 +19,7 @@ import type { import type { DeviceCredentialInstallAuthorization } from './relay-control-requests' import { deriveRelayHostId } from './relay-http-client' import { RelayDemandLedger } from './relay-demand-ledger' -import { createRelayRegionPreferenceReader } from './relay-region-preference' +import { createRelayRegionPreferenceReader } from './relay-region-preference-reader' type DesktopRelayServiceOptions = { authConfig: OrcaCloudAuthConfig @@ -89,6 +89,7 @@ export class DesktopRelayService { isCurrent, refreshAccessToken, resolvePreferredRegion: regionPreference.resolvePreferredRegion, + measureRegionDecision: regionPreference.measureRegionDecision, onAssignedCellActive: regionPreference.noteAssignedCell, onStatus: options.onStatus }) @@ -327,10 +328,8 @@ export class DesktopRelayService { if (expiresAt !== null) { // Why: an unscanned QR must stop holding a standing control when its // server invite expires, even if no renderer survives to report closure. - this.demandExpiryTimer = setTimeout( - () => this.refreshDemand(), - Math.max(1, expiresAt - Date.now() + 1) - ) + const delay = Math.max(1, expiresAt - Date.now() + 1) + this.demandExpiryTimer = setTimeout(() => this.refreshDemand(), delay) } } } diff --git a/src/main/runtime/relay/relay-control-client-options.ts b/src/main/runtime/relay/relay-control-client-options.ts new file mode 100644 index 00000000000..5b98737d11a --- /dev/null +++ b/src/main/runtime/relay/relay-control-client-options.ts @@ -0,0 +1,25 @@ +import type WebSocket from 'ws' +import type { E2EEKeypair } from '../e2ee-keypair' +import type { + RelayConnectionOpenMessage, + RelayDrainMessage, +} from './relay-control-protocol' + +export type RelayControlClientOptions = { + cellUrl: string + relayJwt: string + relayHostId: string + assignmentEpoch: number + identity: { userId: string; profileId: string; organizationId: string } + keypair: E2EEKeypair + appVersion: string + previousGeneration?: number + controlResumeSecret?: string + onConnectionOpen: (message: RelayConnectionOpenMessage) => void + onDrain: (message: RelayDrainMessage) => void + onClose: (code: number) => void + onPendingChanged?: () => void + createSocket?: (url: string, relayJwt: string) => WebSocket + connectDeadlineMs?: number + silenceLimitMs?: number +} diff --git a/src/main/runtime/relay/relay-control-client.test.ts b/src/main/runtime/relay/relay-control-client.test.ts index daa68e0c225..745a79ac84e 100644 --- a/src/main/runtime/relay/relay-control-client.test.ts +++ b/src/main/runtime/relay/relay-control-client.test.ts @@ -221,7 +221,7 @@ describe('RelayControlClient', () => { expect(authorization).toBe('Bearer scoped-token') // Advertised on the upgrade, never in host-hello: a cell that predates the // capability parses host-hello strictly and would refuse the handshake. - expect(capabilities).toBe('pending-conn-details') + expect(capabilities).toBe('pending-conn-details,idle-regional-rehome-v1') expect(path).toBe('/v1/host/control') const hello = await nextJson(socket) expect(hello).toMatchObject({ diff --git a/src/main/runtime/relay/relay-control-client.ts b/src/main/runtime/relay/relay-control-client.ts index 139d63e5640..0c863cce3ad 100644 --- a/src/main/runtime/relay/relay-control-client.ts +++ b/src/main/runtime/relay/relay-control-client.ts @@ -1,8 +1,8 @@ +import type { RelayControlClientOptions } from './relay-control-client-options' import { randomUUID } from 'node:crypto' import WebSocket, { type RawData } from 'ws' import { MOBILE_RELAY_CLOSE_CODE } from '../../../shared/mobile-relay-close-codes' import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason' -import type { E2EEKeypair } from '../e2ee-keypair' import { RelayConnectionOpenMessageSchema, RelayDrainMessageSchema, @@ -12,8 +12,6 @@ import { RELAY_HOST_CAPABILITY_HEADERS, encodeRelayHostHello, parseRelayControlMessage, - type RelayConnectionOpenMessage, - type RelayDrainMessage, type RelayHostHelloAckMessage, type RelayInviteCreatedMessage } from './relay-control-protocol' @@ -29,24 +27,6 @@ import { controlWebSocketUrl } from './relay-control-url' type RelayControlState = 'idle' | 'opening' | 'proving' | 'active' | 'draining' | 'closed' -type RelayControlClientOptions = { - cellUrl: string - relayJwt: string - relayHostId: string - assignmentEpoch: number - identity: { userId: string; profileId: string; organizationId: string } - keypair: E2EEKeypair - appVersion: string - previousGeneration?: number - controlResumeSecret?: string - onConnectionOpen: (message: RelayConnectionOpenMessage) => void - onDrain: (message: RelayDrainMessage) => void - onClose: (code: number) => void - createSocket?: (url: string, relayJwt: string) => WebSocket - connectDeadlineMs?: number - silenceLimitMs?: number -} - const RELAY_CONTROL_CONNECT_DEADLINE_MS = 15_000 export class RelayControlClient { @@ -54,7 +34,7 @@ export class RelayControlClient { private readonly relayOrigin: string private readonly controlUrl: string private readonly createSocket: NonNullable - private readonly requests = new RelayControlRequests() + private readonly requests: RelayControlRequests private socket: WebSocket | null = null private state: RelayControlState = 'idle' private connectResolve: ((ack: RelayHostHelloAckMessage) => void) | null = null @@ -64,6 +44,7 @@ export class RelayControlClient { constructor(options: RelayControlClientOptions) { this.options = options + this.requests = new RelayControlRequests(options.onPendingChanged) const endpoint = controlWebSocketUrl(options.cellUrl) this.relayOrigin = endpoint.origin this.controlUrl = endpoint.url diff --git a/src/main/runtime/relay/relay-control-origin-options.ts b/src/main/runtime/relay/relay-control-origin-options.ts new file mode 100644 index 00000000000..503f4a7411d --- /dev/null +++ b/src/main/runtime/relay/relay-control-origin-options.ts @@ -0,0 +1,24 @@ +import type WebSocket from 'ws' +import type { E2EEKeypair } from '../e2ee-keypair' +import type { MobileSocketWiring } from '../rpc/mobile-socket-wiring' +import type { RelayIdentity } from './relay-session-broker-contract' +import type { RelayAssignment } from './relay-http-client' +import type { RelayControlOrigin } from './relay-control-origin' +import type { RelayDrainMessage } from './relay-control-protocol' + +export type RelayControlOriginOptions = { + assignment: RelayAssignment + relayJwt: string + relayHostId: string + identity: RelayIdentity + keypair: E2EEKeypair + appVersion: string + mobileSocketWiring: MobileSocketWiring + createControlSocket?: (url: string, relayJwt: string) => WebSocket + createDataSocket?: (url: string) => WebSocket + onConnectionOwned: (connectionId: string, origin: RelayControlOrigin) => void + onConnectionReleased: (connectionId: string, origin: RelayControlOrigin) => void + onDrain: (origin: RelayControlOrigin, message: RelayDrainMessage) => void + onClose: (origin: RelayControlOrigin, code: number) => void + onPendingChanged?: (origin: RelayControlOrigin) => void +} diff --git a/src/main/runtime/relay/relay-control-origin.ts b/src/main/runtime/relay/relay-control-origin.ts index 4145a4b1b6c..7bd34862d9c 100644 --- a/src/main/runtime/relay/relay-control-origin.ts +++ b/src/main/runtime/relay/relay-control-origin.ts @@ -1,39 +1,19 @@ -import type WebSocket from 'ws' -import type { E2EEKeypair } from '../e2ee-keypair' +import type { RelayControlOriginOptions } from './relay-control-origin-options' import { CloudRelayTransport } from '../rpc/relay-transport' -import type { MobileSocketWiring } from '../rpc/mobile-socket-wiring' import { RelayControlClient } from './relay-control-client' import { RELAY_HOST_ATTACH_DEADLINE_MS } from './relay-control-protocol' import type { RelayConnectionOpenMessage, - RelayDrainMessage, RelayHostHelloAckMessage, RelayPendingConnection } from './relay-control-protocol' import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason' -import type { RelayIdentity } from './relay-session-broker-contract' import type { RelayAssignment } from './relay-http-client' const OBSERVED_OPEN_LIMIT = 16 -type RelayControlOriginOptions = { - assignment: RelayAssignment - relayJwt: string - relayHostId: string - identity: RelayIdentity - keypair: E2EEKeypair - appVersion: string - mobileSocketWiring: MobileSocketWiring - createControlSocket?: (url: string, relayJwt: string) => WebSocket - createDataSocket?: (url: string) => WebSocket - onConnectionOwned: (connectionId: string, origin: RelayControlOrigin) => void - onConnectionReleased: (connectionId: string, origin: RelayControlOrigin) => void - onDrain: (origin: RelayControlOrigin, message: RelayDrainMessage) => void - onClose: (origin: RelayControlOrigin, code: number) => void -} - export class RelayControlOrigin { - readonly assignment: RelayAssignment + assignment: RelayAssignment readonly transport: CloudRelayTransport private readonly options: RelayControlOriginOptions private readonly controls = new Set() @@ -98,6 +78,17 @@ export class RelayControlOrigin { return this.leaseExpiresAt } + get controlGeneration(): number { + return this.generation + } + + updateAssignment(assignment: RelayAssignment): void { + if (assignment.cellUrl !== this.cellUrl || assignment.assignmentEpoch < this.assignmentEpoch) { + throw new Error('relay_assignment_origin_mismatch') + } + this.assignment = assignment + } + get pendingRequestCount(): number { let count = 0 for (const control of this.controls) { @@ -124,6 +115,7 @@ export class RelayControlOrigin { controlResumeSecret: this.controlResumeSecret }) this.activate(control, ack) + this.updateAssignment(assignment) // Why: the resumed control owns the same server generation and splices; // the predecessor remains only long enough for any idempotent reply in flight. if (previous && previous.pendingRequestCount === 0) { @@ -198,6 +190,7 @@ export class RelayControlOrigin { : {}), onConnectionOpen: (message) => this.openConnection(message), onDrain: (message) => this.options.onDrain(this, message), + onPendingChanged: () => this.options.onPendingChanged?.(this), onClose: (code) => { this.controls.delete(control) const timer = this.retiredControlTimers.get(control) diff --git a/src/main/runtime/relay/relay-control-protocol.ts b/src/main/runtime/relay/relay-control-protocol.ts index 5d41498c00f..ba05d976ed7 100644 --- a/src/main/runtime/relay/relay-control-protocol.ts +++ b/src/main/runtime/relay/relay-control-protocol.ts @@ -32,7 +32,7 @@ const ConnectionKindSchema = z.enum(['invite', 'resume']) // control upgrade rather than host-hello because the cell parses host-hello // strictly: a new hello key is refused by every already-deployed cell. export const RELAY_HOST_CAPABILITY_HEADERS = { - 'x-orca-host-capabilities': 'pending-conn-details' + 'x-orca-host-capabilities': 'pending-conn-details,idle-regional-rehome-v1' } as const // Mirrors RELAY_PROTOCOL_LIMITS.hostAttachDeadlineMs in the relay contract: the @@ -76,11 +76,7 @@ export const RelayConnectionOpenMessageSchema = z export const RelayDrainMessageSchema = z .object({ type: z.literal('drain'), - graceMs: z - .number() - .int() - .nonnegative() - .max(60 * 60 * 1000), + graceMs: z.number().int().nonnegative().max(60 * 60 * 1000), recovery: z.literal('resolve-director') }) .strict() diff --git a/src/main/runtime/relay/relay-control-request-retirement.test.ts b/src/main/runtime/relay/relay-control-request-retirement.test.ts new file mode 100644 index 00000000000..f2aab8dae93 --- /dev/null +++ b/src/main/runtime/relay/relay-control-request-retirement.test.ts @@ -0,0 +1,42 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { RelayControlRequests } from './relay-control-requests' + +afterEach(() => vi.useRealTimers()) +describe('final source request retirement notification', () => { + it.each(['reply', 'denial', 'timeout', 'send-failed', 'closed'] as const)( + 'notifies final work completion after %s', + async (outcome) => { + vi.useFakeTimers() + const changed = vi.fn() + const requests = new RelayControlRequests(changed) + const result = requests + .confirmResume('req', 'basis', () => { + if (outcome === 'send-failed') { + throw new Error('send-failed') + } + }) + .catch((error: Error) => error.message) + if (outcome === 'reply') { + requests.resolveMessage({ + type: 'device-resume-confirmed', + v: 1, + reqId: 'req', + currentVersion: 1, + acceptedAs: 'current', + renewed: true, + resumeExpiresAt: 123_000 + }) + } else if (outcome === 'denial') { + requests.resolveMessage({ type: 'control-error', reqId: 'req', code: 'denied' }) + } else if (outcome === 'timeout') { + await vi.advanceTimersByTimeAsync(10_000) + } else if (outcome === 'closed') { + requests.rejectAll(new Error('closed')) + } + await result + await vi.advanceTimersByTimeAsync(0) + expect(requests.size).toBe(0) + expect(changed).toHaveBeenCalledOnce() + } + ) +}) diff --git a/src/main/runtime/relay/relay-control-requests.ts b/src/main/runtime/relay/relay-control-requests.ts index 2a96b94e3ec..bbceb067a59 100644 --- a/src/main/runtime/relay/relay-control-requests.ts +++ b/src/main/runtime/relay/relay-control-requests.ts @@ -25,6 +25,8 @@ export type DeviceCredentialInstallAuthorization = export class RelayControlRequests { private readonly pending = new Map() + constructor(private readonly onPendingChanged?: () => void) {} + get size(): number { return this.pending.size } @@ -162,7 +164,7 @@ export class RelayControlRequests { } return new Promise((resolve, reject) => { const timer = setTimeout(() => { - this.pending.delete(reqId) + this.finish(reqId) reject(new Error('relay_control_request_timeout')) }, 10_000) this.pending.set(reqId, { kind, resolve, reject, timer }) @@ -180,6 +182,8 @@ export class RelayControlRequests { if (pending) { clearTimeout(pending.timer) this.pending.delete(reqId) + // Settle the request before its final waiter retires the owning origin. + queueMicrotask(() => this.onPendingChanged?.()) } } } diff --git a/src/main/runtime/relay/relay-control-rotation.ts b/src/main/runtime/relay/relay-control-rotation.ts new file mode 100644 index 00000000000..2f1de94e6c0 --- /dev/null +++ b/src/main/runtime/relay/relay-control-rotation.ts @@ -0,0 +1,64 @@ +import type { RelayControlOrigin } from './relay-control-origin' +import type { RelayAssignment } from './relay-http-client' +import { relayRenewalDelayMs } from './relay-renewal-jitter' + +type RotationOptions = { + current: () => RelayControlOrigin | null + available: () => boolean + token: () => string | null + assignment: () => RelayAssignment | null + busy: () => boolean + now?: () => number + random?: () => number +} +export class RelayControlRotation { + private timer: ReturnType | null = null + constructor(private readonly options: RotationOptions) {} + cancel(): void { + if (this.timer) { + clearTimeout(this.timer) + } + this.timer = null + } + schedule(): void { + this.cancel() + const origin = this.options.current() + if (!origin || !this.options.available()) { + return + } + const delay = relayRenewalDelayMs( + origin.controlLeaseExpiresAt, + (this.options.now ?? Date.now)(), + this.options.random ?? Math.random + ) + this.timer = setTimeout(() => void this.rebind(origin), delay) + } + private async rebind(origin: RelayControlOrigin): Promise { + this.timer = null + if (!this.options.available() || origin !== this.options.current()) { + return + } + if (this.options.busy()) { + this.timer = setTimeout(() => void this.rebind(origin), 5_000) + return + } + const token = this.options.token() + const assignment = this.options.assignment() + if (!token || !assignment) { + return + } + try { + await origin.rebind(token, assignment) + if (this.options.available() && origin === this.options.current()) { + this.schedule() + } + } catch { + if (this.options.available() && origin === this.options.current()) { + this.timer = setTimeout( + () => void this.rebind(origin), + 5_000 + Math.floor((this.options.random ?? Math.random)() * 10_001) + ) + } + } + } +} diff --git a/src/main/runtime/relay/relay-host-proof.ts b/src/main/runtime/relay/relay-host-proof.ts index 59c028b1ab1..a169540b5ee 100644 --- a/src/main/runtime/relay/relay-host-proof.ts +++ b/src/main/runtime/relay/relay-host-proof.ts @@ -1,13 +1,18 @@ -import { createHmac, timingSafeEqual } from 'node:crypto' -import nacl from 'tweetnacl' +import { + encodeText, + encodeUint64, + equalBytes, + hostChallengeAckProof, + openHostChallengeEnvelope, + parseHostChallengeTranscript, + readTranscriptUint64 +} from '../host-challenge-envelope' const HOST_PROOF_TRANSCRIPT_DOMAIN = 'orca-relay-host-proof/v1' const HOST_CHALLENGE_PLAINTEXT_DOMAIN = 'orca-relay-host-challenge/v1' // Covers routine NTP drift without extending the signed challenge window. const RELAY_HOST_PROOF_CLOCK_SKEW_MS = 30_000 const MAX_HOST_PROOF_CHALLENGE_WINDOW_MS = 10_000 -const textEncoder = new TextEncoder() -const textDecoder = new TextDecoder() export type RelayHostChallenge = { challengeId: string @@ -33,61 +38,6 @@ export type RelayHostProofContext = { onInvalid?: (reason: string) => void } -function decodeCanonicalBase64(value: string, expectedBytes: number): Uint8Array | null { - if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) { - return null - } - const decoded = Buffer.from(value, 'base64') - return decoded.byteLength === expectedBytes && decoded.toString('base64') === value - ? decoded - : null -} - -function uint64(value: number): Uint8Array { - const bytes = new Uint8Array(8) - new DataView(bytes.buffer).setBigUint64(0, BigInt(value), false) - return bytes -} - -function equal(left: Uint8Array | undefined, right: Uint8Array): boolean { - return Boolean(left && left.byteLength === right.byteLength && timingSafeEqual(left, right)) -} - -function parseTranscript(transcript: Uint8Array): Map | null { - const fields = new Map() - const view = new DataView(transcript.buffer, transcript.byteOffset, transcript.byteLength) - let offset = 0 - try { - while (offset < transcript.byteLength) { - const nameLength = view.getUint32(offset, false) - offset += 4 - const name = textDecoder.decode(transcript.slice(offset, offset + nameLength)) - offset += nameLength - const valueLength = view.getUint32(offset, false) - offset += 4 - if (fields.has(name) || offset + valueLength > transcript.byteLength) { - return null - } - fields.set(name, transcript.slice(offset, offset + valueLength)) - offset += valueLength - } - } catch { - return null - } - return offset === transcript.byteLength ? fields : null -} - -function readUint64(value: Uint8Array | undefined): number | null { - if (!value || value.byteLength !== 8) { - return null - } - const parsed = new DataView(value.buffer, value.byteOffset, value.byteLength).getBigUint64( - 0, - false - ) - return parsed <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(parsed) : null -} - function validateTranscript( transcript: Uint8Array, challenge: RelayHostChallenge, @@ -95,17 +45,19 @@ function validateTranscript( relayKey: Uint8Array, nonce: Uint8Array ): boolean { - const fields = parseTranscript(transcript) + const fields = parseHostChallengeTranscript(transcript) if (!fields || fields.size !== 16) { context.onInvalid?.('transcript-structure') return false } const now = (context.now ?? Date.now)() - const issuedAt = readUint64(fields.get('issuedAt')) - const expiresAt = readUint64(fields.get('expiresAt')) + const issuedAt = readTranscriptUint64(fields.get('issuedAt')) + const expiresAt = readTranscriptUint64(fields.get('expiresAt')) const previousGeneration = fields.get('previousGeneration') const expectedPrevious = - context.previousGeneration === undefined ? new Uint8Array() : uint64(context.previousGeneration) + context.previousGeneration === undefined + ? new Uint8Array() + : encodeUint64(context.previousGeneration) // Main's 30s skew bounds with named-check reporting kept from the incident // instrumentation; deltas are relative offsets only, never absolute values. const checks: [string, boolean][] = [ @@ -124,25 +76,28 @@ function validateTranscript( issuedAt === null || challenge.expiresAt - issuedAt <= MAX_HOST_PROOF_CHALLENGE_WINDOW_MS ], ['expiry-consistent', expiresAt === challenge.expiresAt], - ['protocol', equal(fields.get('protocol'), textEncoder.encode(HOST_PROOF_TRANSCRIPT_DOMAIN))], - ['version', equal(fields.get('version'), new Uint8Array([1]))], - ['relayOrigin', equal(fields.get('relayOrigin'), textEncoder.encode(context.relayOrigin))], - ['relayEphemeralPublicKey', equal(fields.get('relayEphemeralPublicKey'), relayKey)], - ['challengeNonce', equal(fields.get('challengeNonce'), nonce)], - ['challengeId', equal(fields.get('challengeId'), textEncoder.encode(challenge.challengeId))], - ['userId', equal(fields.get('userId'), textEncoder.encode(context.userId))], - ['profileId', equal(fields.get('profileId'), textEncoder.encode(context.profileId))], + ['protocol', equalBytes(fields.get('protocol'), encodeText(HOST_PROOF_TRANSCRIPT_DOMAIN))], + ['version', equalBytes(fields.get('version'), new Uint8Array([1]))], + ['relayOrigin', equalBytes(fields.get('relayOrigin'), encodeText(context.relayOrigin))], + ['relayEphemeralPublicKey', equalBytes(fields.get('relayEphemeralPublicKey'), relayKey)], + ['challengeNonce', equalBytes(fields.get('challengeNonce'), nonce)], + ['challengeId', equalBytes(fields.get('challengeId'), encodeText(challenge.challengeId))], + ['userId', equalBytes(fields.get('userId'), encodeText(context.userId))], + ['profileId', equalBytes(fields.get('profileId'), encodeText(context.profileId))], [ 'organizationId', - equal(fields.get('organizationId'), textEncoder.encode(context.organizationId)) + equalBytes(fields.get('organizationId'), encodeText(context.organizationId)) ], - ['relayHostId', equal(fields.get('relayHostId'), textEncoder.encode(context.relayHostId))], - ['hostPublicKey', equal(fields.get('hostPublicKey'), context.hostPublicKey)], - ['assignmentEpoch', equal(fields.get('assignmentEpoch'), uint64(context.assignmentEpoch))], - ['previousGeneration', equal(previousGeneration, expectedPrevious)], + ['relayHostId', equalBytes(fields.get('relayHostId'), encodeText(context.relayHostId))], + ['hostPublicKey', equalBytes(fields.get('hostPublicKey'), context.hostPublicKey)], + [ + 'assignmentEpoch', + equalBytes(fields.get('assignmentEpoch'), encodeUint64(context.assignmentEpoch)) + ], + ['previousGeneration', equalBytes(previousGeneration, expectedPrevious)], [ 'resumeRequested', - equal(fields.get('resumeRequested'), new Uint8Array([context.resumeRequested ? 1 : 0])) + equalBytes(fields.get('resumeRequested'), new Uint8Array([context.resumeRequested ? 1 : 0])) ] ] const failed = checks.filter(([, ok]) => !ok).map(([name]) => name) @@ -157,41 +112,29 @@ export function answerRelayHostChallenge( challenge: RelayHostChallenge, context: RelayHostProofContext ): string | null { - const relayKey = decodeCanonicalBase64(challenge.relayEphemeralPublicKeyB64, 32) - const nonce = decodeCanonicalBase64(challenge.nonceB64, 24) - const ciphertext = Buffer.from(challenge.ciphertextB64, 'base64') - if (!relayKey || !nonce || ciphertext.toString('base64') !== challenge.ciphertextB64) { - return null - } - const plaintext = nacl.box.open(ciphertext, nonce, relayKey, context.hostSecretKey) - if (!plaintext) { - context.onInvalid?.('challenge-box-open') - return null - } - const domain = textEncoder.encode(`${HOST_CHALLENGE_PLAINTEXT_DOMAIN}\0`) + const envelope = openHostChallengeEnvelope({ + peerEphemeralPublicKeyB64: challenge.relayEphemeralPublicKeyB64, + nonceB64: challenge.nonceB64, + ciphertextB64: challenge.ciphertextB64, + hostSecretKey: context.hostSecretKey, + plaintextDomain: HOST_CHALLENGE_PLAINTEXT_DOMAIN, + onInvalid: context.onInvalid + }) if ( - !equal(plaintext.slice(0, domain.byteLength), domain) || - plaintext.byteLength < domain.byteLength + 36 + !envelope || + !validateTranscript( + envelope.transcript, + challenge, + context, + envelope.peerEphemeralPublicKey, + envelope.nonce + ) ) { return null } - const transcriptLength = new DataView( - plaintext.buffer, - plaintext.byteOffset + domain.byteLength, - 4 - ).getUint32(0, false) - const transcriptStart = domain.byteLength + 4 - const secretStart = transcriptStart + transcriptLength - if (secretStart + 32 !== plaintext.byteLength) { - return null - } - const transcript = plaintext.slice(transcriptStart, secretStart) - if (!validateTranscript(transcript, challenge, context, relayKey, nonce)) { - return null - } - const secret = plaintext.slice(secretStart) - return createHmac('sha256', secret) - .update(textEncoder.encode(`${HOST_PROOF_TRANSCRIPT_DOMAIN}\0ack\0`)) - .update(transcript) - .digest('base64') + return hostChallengeAckProof({ + secret: envelope.secret, + transcript: envelope.transcript, + proofDomain: HOST_PROOF_TRANSCRIPT_DOMAIN + }) } diff --git a/src/main/runtime/relay/relay-http-client.ts b/src/main/runtime/relay/relay-http-client.ts index b31fe2ff9da..cb0fc519f9d 100644 --- a/src/main/runtime/relay/relay-http-client.ts +++ b/src/main/runtime/relay/relay-http-client.ts @@ -11,6 +11,10 @@ import { type RelayAssignRateGate } from './relay-assign-rate-gate' import type { RelayRegion } from './relay-region-preference' +import { + RelayRegionCorrectionResponseSchema, + type RelayRegionCorrectionRequest +} from './relay-region-correction-protocol' const RELAY_HTTP_REQUEST_DEADLINE_MS = 15_000 const RELAY_RETRY_AFTER_MAX_MS = 5 * 60_000 @@ -33,7 +37,9 @@ const AssignmentResponseSchema = z lease: z .string() .min(1) - .max(8 * 1024) + .max(8 * 1024), + // Optional correction must not make a healthy assignment depend on a future policy. + regionCorrection: RelayRegionCorrectionResponseSchema.optional().catch(undefined) }) .strict() @@ -133,6 +139,7 @@ type RelayAssignmentRequest = { relayHostId: string reconnect?: boolean preferredRegion?: RelayRegion + regionCorrection?: RelayRegionCorrectionRequest fetch?: typeof globalThis.fetch requestDeadlineMs?: number // Fencing for the throttle wait: a superseded caller aborts instead of assigning. @@ -185,6 +192,7 @@ async function sendRelayAssignment( body: JSON.stringify({ v: 1, relayHostId: input.relayHostId, + ...(input.regionCorrection ? { regionCorrection: input.regionCorrection } : {}), ...(input.preferredRegion ? { preferredRegion: input.preferredRegion } : {}), // Declares likely reconnection so the director can verify and admit // through its bounded fast lane instead of the placement queue. @@ -197,6 +205,9 @@ async function sendRelayAssignment( gate.noteRetryAfter(rateKey, retryAfterMs) } await cancelUnreadResponseBody(response) + if (input.regionCorrection && response.status === 400) { + return await sendRelayAssignment({ ...input, regionCorrection: undefined }, gate, rateKey) + } if (input.preferredRegion && response.status === 400) { // A rolled-back director rejects the regional hint; preserve the // reconnect lane while retrying without only that field. diff --git a/src/main/runtime/relay/relay-origin-pool-options.ts b/src/main/runtime/relay/relay-origin-pool-options.ts new file mode 100644 index 00000000000..ffb5455d1f4 --- /dev/null +++ b/src/main/runtime/relay/relay-origin-pool-options.ts @@ -0,0 +1,22 @@ +import type WebSocket from 'ws' +import type { E2EEKeypair } from '../e2ee-keypair' +import type { MobileSocketWiring } from '../rpc/mobile-socket-wiring' +import type { RelayBrokerStatus, RelayIdentity } from './relay-session-broker-contract' +import type { RelayRegion } from './relay-region-preference' + +export type RelayOriginPoolOptions = { + directorUrl: string + relayHostId: string + identity: RelayIdentity + keypair: E2EEKeypair + appVersion: string + mobileSocketWiring: MobileSocketWiring + isCurrent: () => boolean + onStatus: (status: RelayBrokerStatus) => void + resolvePreferredRegion?: () => Promise + fetch?: typeof globalThis.fetch + createControlSocket?: (url: string, relayJwt: string) => WebSocket + createDataSocket?: (url: string) => WebSocket + random?: () => number + now?: () => number +} diff --git a/src/main/runtime/relay/relay-origin-pool.ts b/src/main/runtime/relay/relay-origin-pool.ts index e8fd1d7d82a..15abcc4127c 100644 --- a/src/main/runtime/relay/relay-origin-pool.ts +++ b/src/main/runtime/relay/relay-origin-pool.ts @@ -1,50 +1,42 @@ -import type WebSocket from 'ws' -import type { E2EEKeypair } from '../e2ee-keypair' -import type { MobileSocketWiring } from '../rpc/mobile-socket-wiring' +import { RelayOriginRetirement } from './relay-origin-retirement' +import type { RelayOriginPoolOptions } from './relay-origin-pool-options' import { RelayControlOrigin } from './relay-control-origin' import type { RelayControlClient } from './relay-control-client' import type { RelayDrainMessage } from './relay-control-protocol' import type { RelayHostCloseReason } from '../../../shared/relay-host-close-reason' import { RelayDrainRetrySchedule } from './relay-drain-retry-schedule' import { RelayHttpError, requestRelayAssignment, type RelayAssignment } from './relay-http-client' -import { relayRenewalDelayMs } from './relay-renewal-jitter' -import type { RelayBrokerStatus, RelayIdentity } from './relay-session-broker-contract' -import type { RelayRegion } from './relay-region-preference' - -type RelayOriginPoolOptions = { - directorUrl: string - relayHostId: string - identity: RelayIdentity - keypair: E2EEKeypair - appVersion: string - mobileSocketWiring: MobileSocketWiring - isCurrent: () => boolean - onStatus: (status: RelayBrokerStatus) => void - resolvePreferredRegion?: () => Promise - fetch?: typeof globalThis.fetch - createControlSocket?: (url: string, relayJwt: string) => WebSocket - createDataSocket?: (url: string) => WebSocket - random?: () => number - now?: () => number -} +import { RelayControlRotation } from './relay-control-rotation' export class RelayOriginPool { - private readonly options: RelayOriginPoolOptions private activeOrigin: RelayControlOrigin | null = null private readonly origins = new Set() - private readonly drainingOrigins = new Set() - private readonly basisOrigins = new Map() - private readonly drainTimers = new Map>() + private readonly retirement = new RelayOriginRetirement( + () => this.activeOrigin, + (origin) => { + this.origins.delete(origin) + } + ) + private readonly drainingOrigins = this.retirement.draining + private readonly basisOrigins = this.retirement.basis private assignment: RelayAssignment | null = null + private deferredAssignment: RelayAssignment | null = null private relayJwt: string | null = null - private rotationTimer: ReturnType | null = null + private readonly rotation: RelayControlRotation private rotationPromise: Promise | null = null private readonly drainRetry: RelayDrainRetrySchedule private closed = false - constructor(options: RelayOriginPoolOptions) { - this.options = options + constructor(private readonly options: RelayOriginPoolOptions) { this.drainRetry = new RelayDrainRetrySchedule(options.random) + this.rotation = new RelayControlRotation({ + ...options, + current: () => this.activeOrigin, + available: () => this.isCurrent(), + token: () => this.relayJwt, + assignment: () => this.assignment, + busy: () => Boolean(this.rotationPromise) + }) } get activeAssignment(): RelayAssignment | null { @@ -63,6 +55,28 @@ export class RelayOriginPool { return this.activeOrigin?.hasLiveControl() ?? false } + applyAssignmentMetadata(assignment: RelayAssignment): boolean { + const current = this.assignment + if (!this.isCurrent() || !current || assignment.assignmentEpoch < current.assignmentEpoch) { + return false + } + if (assignment.assignmentEpoch > current.assignmentEpoch || this.rotationPromise) { + if ( + !this.deferredAssignment || + assignment.assignmentEpoch >= this.deferredAssignment.assignmentEpoch + ) { + this.deferredAssignment = assignment + } + return true + } + if (assignment.cellUrl !== current.cellUrl) { + return false + } + this.assignment = assignment + this.activeOrigin?.updateAssignment(assignment) + return true + } + async openInitial(assignment: RelayAssignment, relayJwt: string): Promise { this.assignment = assignment this.relayJwt = relayJwt @@ -71,7 +85,7 @@ export class RelayOriginPool { await origin.open() this.assertCurrent() this.activeOrigin = origin - this.scheduleControlRotation() + this.rotation.schedule() } refreshAuthorization(relayJwt: string): void { @@ -86,35 +100,21 @@ export class RelayOriginPool { return } this.closed = true - if (this.rotationTimer) { - clearTimeout(this.rotationTimer) - this.rotationTimer = null - } - this.drainRetry.cancel() - for (const timer of this.drainTimers.values()) { - clearTimeout(timer) - } - this.drainTimers.clear() + this.rotation.cancel() + this.drainRetry.reset() + this.retirement.clear() for (const origin of this.origins) { origin.closeNow(hostCloseReason) } this.origins.clear() - this.drainingOrigins.clear() - this.basisOrigins.clear() this.activeOrigin = null } private createOrigin(assignment: RelayAssignment, relayJwt: string): RelayControlOrigin { return new RelayControlOrigin({ + ...this.options, assignment, relayJwt, - relayHostId: this.options.relayHostId, - identity: this.options.identity, - keypair: this.options.keypair, - appVersion: this.options.appVersion, - mobileSocketWiring: this.options.mobileSocketWiring, - createControlSocket: this.options.createControlSocket, - createDataSocket: this.options.createDataSocket, onConnectionOwned: (connectionId, origin) => { if (this.isCurrent() && this.origins.has(origin)) { this.basisOrigins.set(connectionId, origin) @@ -124,9 +124,10 @@ export class RelayOriginPool { if (this.basisOrigins.get(connectionId) === origin) { this.basisOrigins.delete(connectionId) } - this.maybeCloseDrainedOrigin(origin) + this.retirement.maybeClose(origin) }, onDrain: (origin, message) => this.handleDrain(origin, message), + onPendingChanged: (origin) => this.retirement.maybeClose(origin), onClose: (origin) => { if (origin === this.activeOrigin && this.isCurrent()) { this.options.onStatus('offline') @@ -141,10 +142,12 @@ export class RelayOriginPool { } private handleDrain(origin: RelayControlOrigin, message: RelayDrainMessage): void { - if (!this.isCurrent() || origin !== this.activeOrigin) { + if (!this.isCurrent() || !this.origins.has(origin)) { + return + } + if (!this.retirement.adopt(origin, message)) { return } - this.drainingOrigins.add(origin) this.options.onStatus('draining') if (!this.rotationPromise && !this.drainRetry.pending) { this.rotationPromise = this.resolveDrainTarget(origin, message).finally(() => { @@ -164,7 +167,7 @@ export class RelayOriginPool { const preferredRegion = await this.options.resolvePreferredRegion?.().catch(() => undefined) this.assertCurrent() // Why: only the configured director can choose a migration target. - const assignment = await requestRelayAssignment({ + let assignment = await requestRelayAssignment({ directorUrl: this.options.directorUrl, relayToken: this.relayJwt, relayHostId: this.options.relayHostId, @@ -176,15 +179,27 @@ export class RelayOriginPool { fetch: this.options.fetch }) this.assertCurrent() + if ( + this.deferredAssignment && + this.deferredAssignment.assignmentEpoch > assignment.assignmentEpoch + ) { + assignment = this.deferredAssignment + } + this.deferredAssignment = null if (assignment.cellUrl === origin.cellUrl) { - let rebound = false + let rebound = false try { await origin.rebind(this.relayJwt, assignment) rebound = true } catch { // Why: a restarted cell cannot know the prior process's resume secret; // after rebind fails, a fresh generation is the only recoverable path. - await this.activateTarget(origin, assignment, this.relayJwt, message.graceMs) + await this.activateTarget( + origin, + assignment, + this.relayJwt, + message.graceMs, + ) } if (rebound) { this.assertCurrent() @@ -193,11 +208,16 @@ export class RelayOriginPool { this.drainingOrigins.delete(origin) } } else { - await this.activateTarget(origin, assignment, this.relayJwt, message.graceMs) + await this.activateTarget( + origin, + assignment, + this.relayJwt, + message.graceMs, + ) } this.options.onStatus('registered') this.drainRetry.reset() - this.scheduleControlRotation() + this.rotation.schedule() } catch (error) { if (this.isCurrent() && origin === this.activeOrigin) { // Why: this retry loop ran silently during the 2026-08 incident while @@ -230,89 +250,9 @@ export class RelayOriginPool { } this.activeOrigin = target this.assignment = assignment - this.scheduleDrainDeadline(origin, graceMs) - this.maybeCloseDrainedOrigin(origin) + this.retirement.schedule(origin, graceMs) + this.retirement.maybeClose(origin) } - - private scheduleControlRotation(): void { - if (this.rotationTimer) { - clearTimeout(this.rotationTimer) - } - const origin = this.activeOrigin - if (!origin || this.closed) { - this.rotationTimer = null - return - } - const now = (this.options.now ?? Date.now)() - const random = this.options.random ?? Math.random - const delay = relayRenewalDelayMs(origin.controlLeaseExpiresAt, now, random) - this.rotationTimer = setTimeout(() => void this.rebindActiveControl(origin), delay) - } - - private async rebindActiveControl(origin: RelayControlOrigin): Promise { - this.rotationTimer = null - if (!this.isCurrent() || origin !== this.activeOrigin || this.rotationPromise) { - return - } - if (!this.relayJwt || !this.assignment) { - return - } - try { - await origin.rebind(this.relayJwt, this.assignment) - this.assertCurrent() - this.scheduleControlRotation() - } catch { - if (this.isCurrent() && origin === this.activeOrigin) { - const random = this.options.random ?? Math.random - this.rotationTimer = setTimeout( - () => void this.rebindActiveControl(origin), - 5_000 + Math.floor(random() * 10_001) - ) - } - } - } - - private scheduleDrainDeadline(origin: RelayControlOrigin, graceMs: number): void { - const existing = this.drainTimers.get(origin) - if (existing) { - clearTimeout(existing) - } - this.drainTimers.set( - origin, - setTimeout(() => this.closeOrigin(origin), graceMs) - ) - } - - private maybeCloseDrainedOrigin(origin: RelayControlOrigin): void { - if ( - !this.drainingOrigins.has(origin) || - origin.pendingRequestCount > 0 || - [...this.basisOrigins.values()].includes(origin) - ) { - return - } - this.closeOrigin(origin) - } - - private closeOrigin(origin: RelayControlOrigin): void { - if (origin === this.activeOrigin) { - return - } - const timer = this.drainTimers.get(origin) - if (timer) { - clearTimeout(timer) - this.drainTimers.delete(origin) - } - for (const [connectionId, owner] of this.basisOrigins) { - if (owner === origin) { - this.basisOrigins.delete(connectionId) - } - } - this.drainingOrigins.delete(origin) - this.origins.delete(origin) - origin.closeNow() - } - private assertCurrent(): void { if (!this.isCurrent()) { throw new Error('stale_relay_origin_pool') diff --git a/src/main/runtime/relay/relay-origin-retirement.ts b/src/main/runtime/relay/relay-origin-retirement.ts new file mode 100644 index 00000000000..bcc2a439ef2 --- /dev/null +++ b/src/main/runtime/relay/relay-origin-retirement.ts @@ -0,0 +1,65 @@ +import type { RelayDrainMessage } from './relay-control-protocol' +import type { RelayControlOrigin } from './relay-control-origin' + +export class RelayOriginRetirement { + readonly draining = new Set() + readonly basis = new Map() + private readonly timers = new Map>() + constructor( + private readonly current: () => RelayControlOrigin | null, + private readonly remove: (origin: RelayControlOrigin) => void + ) {} + adopt(origin: RelayControlOrigin, _message: RelayDrainMessage): boolean { + if (origin !== this.current()) { + return false + } + this.draining.add(origin) + return true + } + schedule(origin: RelayControlOrigin, graceMs: number): void { + const timer = this.timers.get(origin) + if (timer) { + clearTimeout(timer) + } + this.timers.set( + origin, + setTimeout(() => this.close(origin), graceMs) + ) + } + maybeClose(origin: RelayControlOrigin): void { + if ( + !this.draining.has(origin) || + origin.pendingRequestCount > 0 || + [...this.basis.values()].includes(origin) + ) { + return + } + this.close(origin) + } + clear(): void { + for (const timer of this.timers.values()) { + clearTimeout(timer) + } + this.timers.clear() + this.draining.clear() + this.basis.clear() + } + private close(origin: RelayControlOrigin): void { + if (origin === this.current()) { + return + } + const timer = this.timers.get(origin) + if (timer) { + clearTimeout(timer) + this.timers.delete(origin) + } + for (const [id, owner] of this.basis) { + if (owner === origin) { + this.basis.delete(id) + } + } + this.draining.delete(origin) + this.remove(origin) + origin.closeNow() + } +} diff --git a/src/main/runtime/relay/relay-region-correction-protocol.ts b/src/main/runtime/relay/relay-region-correction-protocol.ts new file mode 100644 index 00000000000..59762de33c1 --- /dev/null +++ b/src/main/runtime/relay/relay-region-correction-protocol.ts @@ -0,0 +1,43 @@ +import { z } from 'zod' +import { RelayRegionSchema } from './relay-region-probe' + +const Counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER) +export const RelayRegionWindowSchema = z + .object({ + generation: Counter, + expiresAt: Counter, + assignmentEpoch: Counter, + incumbentRegion: RelayRegionSchema, + policyVersion: z.literal(1) + }) + .strict() + +export const RelayRegionCorrectionResponseSchema = z + .object({ + v: z.literal(1), + window: RelayRegionWindowSchema.optional(), + reportStatus: z.enum(['accepted', 'duplicate', 'stale', 'expired', 'basis-changed']).optional() + }) + .strict() + +export type RelayRegionWindow = z.infer +export type RelayRegionDecision = + | { outcome: 'conclusive'; measurements: Record, number> } + | { + outcome: 'inconclusive' + reason: + | 'diagnostic-override' + | 'catalog-unavailable' + | 'incomplete-measurement' + | 'insufficient-improvement' + | 'expired-window' + } +export type RelayRegionCorrectionRequest = + | { v: 1; action: 'issue-window' } + | ({ + v: 1 + action: 'report' + generation: number + assignmentEpoch: number + policyVersion: 1 + } & RelayRegionDecision) diff --git a/src/main/runtime/relay/relay-region-correction.test.ts b/src/main/runtime/relay/relay-region-correction.test.ts new file mode 100644 index 00000000000..1a72d3136c9 --- /dev/null +++ b/src/main/runtime/relay/relay-region-correction.test.ts @@ -0,0 +1,132 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { RelayRegionPreferenceResolver } from './relay-region-preference' +import { RelayAssignRateGate } from './relay-assign-rate-gate' +import { requestRelayAssignment } from './relay-http-client' +import type { RelayRegionWindow } from './relay-region-correction-protocol' + +const paths: string[] = [] +const US = 'https://us.director.example.test' +const ASIA = 'https://asia.director.example.test' +const DIRECTOR = 'https://director.example.test' +const window: RelayRegionWindow = { + generation: 1, + assignmentEpoch: 5, + incumbentRegion: 'asia-east2', + expiresAt: 1_000_000, + policyVersion: 1 +} +afterEach(() => { + for (const path of paths.splice(0)) { + rmSync(path, { recursive: true, force: true }) + } +}) +function resolver(us: number | null, asia: number | null, override?: string) { + const path = mkdtempSync(join(tmpdir(), 'relay-decision-')) + paths.push(path) + const probe = vi.fn(async (origin: string) => (origin === US ? us : asia)) + const fetch = vi.fn(async () => + Response.json({ + v: 1, + regions: [ + { region: 'us-central1', probeOrigins: [US] }, + { region: 'asia-east2', probeOrigins: [ASIA] } + ] + }) + ) + return { + path, + probe, + instance: new RelayRegionPreferenceResolver({ + directorUrl: DIRECTOR, + userDataPath: path, + probe, + fetch, + now: () => 0, + diagnosticOverride: override + }) + } +} +describe('window-bound region decisions', () => { + it('compares against the actual incumbent despite a previous US placement cache', async () => { + const { instance, path, probe } = resolver(50, 100) + writeFileSync( + join(path, 'orca-relay-region-preference.json'), + JSON.stringify({ v: 2, directorUrl: DIRECTOR, region: 'us-central1', expiresAt: 999_999 }) + ) + expect(await instance.measureDecision(window)).toEqual({ + outcome: 'conclusive', + measurements: { 'us-central1': 50, 'asia-east2': 100 } + }) + expect(probe).toHaveBeenCalledTimes(8) + }) + it.each([ + [76, 100], + [100, 124], + [400, 450] + ])( + 'reports stable insufficient margins as conclusive evidence for director filtering (%i / %i)', + async (us, asia) => { + expect(await resolver(us, asia).instance.measureDecision(window)).toEqual({ + outcome: 'conclusive', + measurements: { 'us-central1': us, 'asia-east2': asia } + }) + } + ) + it('allows the exact inclusive 25ms and 20 percent boundary', async () => { + expect(await resolver(100, 125).instance.measureDecision(window)).toMatchObject({ + outcome: 'conclusive' + }) + }) + it('does not certify a lone measurable region', async () => { + expect(await resolver(40, null).instance.measureDecision(window)).toEqual({ + outcome: 'inconclusive', + reason: 'incomplete-measurement' + }) + }) + it('never converts diagnostic overrides into measured eligibility', async () => { + const { instance, probe } = resolver(40, 100, 'us-central1') + expect(await instance.measureDecision(window)).toEqual({ + outcome: 'inconclusive', + reason: 'diagnostic-override' + }) + expect(probe).not.toHaveBeenCalled() + }) + it('invalidates legacy placement caches on upgrade', async () => { + const { instance, path, probe } = resolver(40, 100) + writeFileSync( + join(path, 'orca-relay-region-preference.json'), + JSON.stringify({ v: 1, directorUrl: DIRECTOR, region: 'asia-east2', expiresAt: 999_999 }) + ) + expect(await instance.resolve()).toBe('us-central1') + expect(probe).toHaveBeenCalledTimes(8) + }) + it('falls back from a strict old director without dropping the cold-start hint', async () => { + const fetch = vi + .fn() + .mockResolvedValueOnce(new Response(null, { status: 400 })) + .mockResolvedValueOnce( + Response.json({ v: 1, cellUrl: ASIA, assignmentEpoch: 1, lease: 'synthetic' }) + ) + const result = await requestRelayAssignment({ + directorUrl: DIRECTOR, + relayHostId: 'synthetic-host', + relayToken: 'synthetic-token', + preferredRegion: 'asia-east2', + reconnect: true, + regionCorrection: { v: 1, action: 'issue-window' }, + fetch, + assignRateGate: new RelayAssignRateGate() + }) + expect(result.cellUrl).toBe(ASIA) + expect(JSON.parse(String(fetch.mock.calls[1]![1]?.body))).toEqual({ + v: 1, + relayHostId: 'synthetic-host', + preferredRegion: 'asia-east2', + reconnect: true + }) + expect(result.regionCorrection).toBeUndefined() + }) +}) diff --git a/src/main/runtime/relay/relay-region-decision.ts b/src/main/runtime/relay/relay-region-decision.ts new file mode 100644 index 00000000000..677ae6faeb3 --- /dev/null +++ b/src/main/runtime/relay/relay-region-decision.ts @@ -0,0 +1,47 @@ +import type { RelayRegionDecision, RelayRegionWindow } from './relay-region-correction-protocol' +import { + RELAY_REGIONS, + regionMeasurement, + type RegionMeasurement, + type RelayRegionProbeReport +} from './relay-region-probe' + +export async function measureRelayRegionDecision( + window: RelayRegionWindow, + options: { + diagnosticOverride: boolean + now: () => number + measure: () => Promise + } +): Promise { + if (options.diagnosticOverride) { + return { outcome: 'inconclusive', reason: 'diagnostic-override' } + } + if (window.expiresAt <= options.now()) { + return { outcome: 'inconclusive', reason: 'expired-window' } + } + try { + // Placement caches are never evidence for a new server-issued window. + const reports = await options.measure() + const measurements = reports + .map(regionMeasurement) + .filter((entry): entry is RegionMeasurement => entry !== null) + const incumbent = measurements.find((entry) => entry.region === window.incumbentRegion) + if (window.expiresAt <= options.now()) { + return { outcome: 'inconclusive', reason: 'expired-window' } + } + if (!incumbent || measurements.length !== RELAY_REGIONS.length) { + return { outcome: 'inconclusive', reason: 'incomplete-measurement' } + } + // A stable tie is conclusive evidence; the director applies the incumbent margin. + return { + outcome: 'conclusive', + measurements: { + 'us-central1': measurements.find((entry) => entry.region === 'us-central1')!.latencyMs, + 'asia-east2': measurements.find((entry) => entry.region === 'asia-east2')!.latencyMs + } + } + } catch { + return { outcome: 'inconclusive', reason: 'catalog-unavailable' } + } +} diff --git a/src/main/runtime/relay/relay-region-preference-reader.ts b/src/main/runtime/relay/relay-region-preference-reader.ts new file mode 100644 index 00000000000..a856a598c85 --- /dev/null +++ b/src/main/runtime/relay/relay-region-preference-reader.ts @@ -0,0 +1,22 @@ +import { RelayRegionPreferenceResolver } from './relay-region-preference' +import type { RelayRegion } from './relay-region-probe' +import type { RelayRegionDecision, RelayRegionWindow } from './relay-region-correction-protocol' + +export function createRelayRegionPreferenceReader(input: { + authConfig: { relayDirectorUrl: string } + userDataPath: string +}): { + resolvePreferredRegion: () => Promise + measureRegionDecision: (window: RelayRegionWindow) => Promise + noteAssignedCell: (cellUrl: string) => void +} { + const resolver = new RelayRegionPreferenceResolver({ + directorUrl: input.authConfig.relayDirectorUrl, + userDataPath: input.userDataPath + }) + return { + resolvePreferredRegion: () => resolver.resolve(), + measureRegionDecision: (window) => resolver.measureDecision(window), + noteAssignedCell: (cellUrl) => void resolver.invalidateIfAssignedCellIsFar(cellUrl) + } +} diff --git a/src/main/runtime/relay/relay-region-preference.test.ts b/src/main/runtime/relay/relay-region-preference.test.ts index 700517d0b91..b3e2b845600 100644 --- a/src/main/runtime/relay/relay-region-preference.test.ts +++ b/src/main/runtime/relay/relay-region-preference.test.ts @@ -47,7 +47,7 @@ function sampledProbe(samples: Record) { function writeNoHintCache(path: string, expiresAt: number): void { writeFileSync( cachePath(path), - JSON.stringify({ v: 1, directorUrl: DIRECTOR, region: null, expiresAt }) + JSON.stringify({ v: 2, directorUrl: DIRECTOR, region: null, expiresAt }) ) } @@ -58,7 +58,7 @@ function cachePath(path: string): string { function writeCache(path: string, region: string, expiresAt = 999): void { writeFileSync( cachePath(path), - JSON.stringify({ v: 1, directorUrl: DIRECTOR, region, latencyMs: 100, expiresAt }) + JSON.stringify({ v: 2, directorUrl: DIRECTOR, region, latencyMs: 100, expiresAt }) ) } @@ -87,7 +87,7 @@ describe('Relay region preference', () => { expect(calls.filter((origin) => origin === US_SECONDARY)).toHaveLength(4) expect(calls.filter((origin) => origin === ASIA)).toHaveLength(4) expect(JSON.parse(readFileSync(cachePath(path), 'utf8'))).toMatchObject({ - v: 1, + v: 2, directorUrl: DIRECTOR, region: 'asia-east2', latencyMs: 30 @@ -175,7 +175,7 @@ describe('Relay region preference', () => { ).resolves.toBeUndefined() // The withheld hint is remembered briefly so a reconnect does not re-probe. const cached = JSON.parse(readFileSync(cachePath(path), 'utf8')) - expect(cached).toEqual({ v: 1, directorUrl: DIRECTOR, region: null, expiresAt: 3_601_000 }) + expect(cached).toEqual({ v: 2, directorUrl: DIRECTOR, region: null, expiresAt: 3_601_000 }) }) it('reuses the short-lived no-hint cache instead of re-probing on reconnect', async () => { diff --git a/src/main/runtime/relay/relay-region-preference.ts b/src/main/runtime/relay/relay-region-preference.ts index 9ad3743c972..a430e2d8a35 100644 --- a/src/main/runtime/relay/relay-region-preference.ts +++ b/src/main/runtime/relay/relay-region-preference.ts @@ -1,9 +1,11 @@ +import { measureRelayRegionDecision } from './relay-region-decision' import { existsSync, readFileSync, rmSync, statSync } from 'node:fs' import { join } from 'node:path' import { performance } from 'node:perf_hooks' import { z } from 'zod' import { hardenExistingSecureFile, writeSecureJsonFile } from '../../../shared/secure-file' import { fetchRelayRegionCatalog, relayDirectorHost } from './relay-region-catalog-fetch' +import type { RelayRegionDecision, RelayRegionWindow } from './relay-region-correction-protocol' import { logRelayRegionEvent, relayRegionCacheHitEvent, @@ -43,7 +45,7 @@ const FAR_CELL_RATIO = 3 const RelayRegionCacheSchema = z .object({ - v: z.literal(1), + v: z.literal(2), directorUrl: z.string().max(2_048), // Null records a deliberate "no hint"; the field is absent only for a region. region: RelayRegionSchema.nullable(), @@ -75,6 +77,14 @@ export class RelayRegionPreferenceResolver { this.options = options } + measureDecision(window: RelayRegionWindow): Promise { + return measureRelayRegionDecision(window, { + diagnosticOverride: Boolean(this.overrideRegion()), + now: this.options.now ?? Date.now, + measure: () => this.probeCatalog(this.options.fetch ?? globalThis.fetch) + }) + } + async resolve(): Promise { const override = this.overrideRegion() if (override) { @@ -233,7 +243,7 @@ export class RelayRegionPreferenceResolver { ): void { try { writeSecureJsonFile(this.cachePath(), { - v: 1, + v: 2, directorUrl: this.options.directorUrl, region: entry.region, ...(entry.latencyMs === undefined ? {} : { latencyMs: entry.latencyMs }), @@ -269,23 +279,6 @@ export class RelayRegionPreferenceResolver { } } -export function createRelayRegionPreferenceReader(input: { - authConfig: { relayDirectorUrl: string } - userDataPath: string -}): { - resolvePreferredRegion: () => Promise - noteAssignedCell: (cellUrl: string) => void -} { - const resolver = new RelayRegionPreferenceResolver({ - directorUrl: input.authConfig.relayDirectorUrl, - userDataPath: input.userDataPath - }) - return { - resolvePreferredRegion: () => resolver.resolve(), - noteAssignedCell: (cellUrl) => void resolver.invalidateIfAssignedCellIsFar(cellUrl) - } -} - function measuredRegions(reports: RelayRegionProbeReport[]): RegionMeasurement[] { return reports .map(regionMeasurement) diff --git a/src/main/runtime/relay/relay-region-probe-log.test.ts b/src/main/runtime/relay/relay-region-probe-log.test.ts index eb62939d9c7..d4c97866438 100644 --- a/src/main/runtime/relay/relay-region-probe-log.test.ts +++ b/src/main/runtime/relay/relay-region-probe-log.test.ts @@ -48,7 +48,7 @@ function sampledProbe(samples: Record) { function writeCache(path: string, region: string | null, expiresAt: number): void { writeFileSync( join(path, 'orca-relay-region-preference.json'), - JSON.stringify({ v: 1, directorUrl: DIRECTOR, region, expiresAt }) + JSON.stringify({ v: 2, directorUrl: DIRECTOR, region, expiresAt }) ) } diff --git a/src/main/runtime/relay/relay-region-refresh.test.ts b/src/main/runtime/relay/relay-region-refresh.test.ts new file mode 100644 index 00000000000..d6453191602 --- /dev/null +++ b/src/main/runtime/relay/relay-region-refresh.test.ts @@ -0,0 +1,158 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { RelayHttpError, type RelayAssignment } from './relay-http-client' +import type * as RelayHttpClientModule from './relay-http-client' +import type { RelayRegionWindow } from './relay-region-correction-protocol' +const fake = vi.hoisted(() => ({ assign: vi.fn() })) +vi.mock('./relay-http-client', async (original) => ({ + ...(await original()), + requestRelayAssignment: fake.assign +})) +import { RelayRegionRefresh } from './relay-region-refresh' +const HOUR = 60 * 60_000 +const window: RelayRegionWindow = { + generation: 1, + assignmentEpoch: 1, + incumbentRegion: 'asia-east2', + expiresAt: 24 * HOUR, + policyVersion: 1 +} +const assignment: RelayAssignment = { + v: 1, + cellUrl: 'https://source.example.test', + assignmentEpoch: 1, + lease: 'test', + regionCorrection: { v: 1, window } +} +let scheduler: RelayRegionRefresh +function setup(random = 0.5) { + const measure = vi.fn().mockResolvedValue({ + outcome: 'conclusive', + measurements: { 'us-central1': 30, 'asia-east2': 200 } + }) + const applyAssignment = vi.fn(() => true) + const isOnline = vi.fn(() => true) + scheduler = new RelayRegionRefresh({ + directorUrl: 'https://director.example.test', + relayHostId: 'test-host', + token: () => 'test-token', + assignment: () => assignment, + isCurrent: () => true, + isOnline, + applyAssignment, + measure, + random: () => random, + now: () => Date.now() + }) + return { measure, applyAssignment, isOnline } +} +describe('broker-owned region decision refresh', () => { + beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(0) + fake.assign.mockReset() + }) + afterEach(() => { + scheduler?.close() + vi.useRealTimers() + }) + it('measures only after the server window and reports the complete fixed basis', async () => { + const { measure } = setup() + fake.assign.mockResolvedValue({ + ...assignment, + regionCorrection: { v: 1, reportStatus: 'accepted' } + }) + scheduler.start(assignment) + await vi.advanceTimersByTimeAsync(0) + expect(measure).toHaveBeenCalledWith(window) + expect(fake.assign).toHaveBeenCalledWith( + expect.objectContaining({ + regionCorrection: { + v: 1, + action: 'report', + generation: 1, + assignmentEpoch: 1, + policyVersion: 1, + outcome: 'conclusive', + measurements: { 'us-central1': 30, 'asia-east2': 200 } + } + }) + ) + await vi.advanceTimersByTimeAsync(23 * HOUR) + expect(measure).toHaveBeenCalledOnce() + }) + it('never jitters a retry before the director Retry-After minimum', async () => { + setup(0) + fake.assign + .mockRejectedValueOnce(new RelayHttpError('assignment', 429, 120_000)) + .mockResolvedValue({ ...assignment, regionCorrection: { v: 1, reportStatus: 'accepted' } }) + scheduler.start(assignment) + await vi.advanceTimersByTimeAsync(119_999) + expect(fake.assign).toHaveBeenCalledOnce() + await vi.advanceTimersByTimeAsync(1) + expect(fake.assign).toHaveBeenCalledTimes(2) + }) + it('retries exactly the same report without probing or extending its window', async () => { + const { measure } = setup() + fake.assign + .mockRejectedValueOnce(new Error('offline')) + .mockResolvedValue({ ...assignment, regionCorrection: { v: 1, reportStatus: 'accepted' } }) + scheduler.start(assignment) + await vi.advanceTimersByTimeAsync(60_000) + expect(measure).toHaveBeenCalledOnce() + expect(fake.assign).toHaveBeenCalledTimes(2) + expect(fake.assign.mock.calls[0]![0].regionCorrection).toEqual( + fake.assign.mock.calls[1]![0].regionCorrection + ) + }) + it('records inconclusive reports and retries measurement after one hour', async () => { + const { measure } = setup() + measure.mockResolvedValue({ outcome: 'inconclusive', reason: 'incomplete-measurement' }) + fake.assign + .mockResolvedValueOnce({ + ...assignment, + regionCorrection: { v: 1, reportStatus: 'accepted' } + }) + .mockResolvedValue(assignment) + scheduler.start(assignment) + await vi.advanceTimersByTimeAsync(HOUR) + expect(measure).toHaveBeenCalledTimes(2) + expect(fake.assign.mock.calls[1]![0].regionCorrection).toEqual({ v: 1, action: 'issue-window' }) + }) + it('does not probe offline and cancels future work on close', async () => { + const { measure, isOnline } = setup() + isOnline.mockReturnValue(false) + scheduler.start(assignment) + await vi.advanceTimersByTimeAsync(60_000) + expect(measure).not.toHaveBeenCalled() + scheduler.close() + isOnline.mockReturnValue(true) + await vi.advanceTimersByTimeAsync(25 * HOUR) + expect(fake.assign).not.toHaveBeenCalled() + }) + it('does not report a measurement that completed after broker close', async () => { + const { measure } = setup() + let resolve!: (value: unknown) => void + measure.mockReturnValue( + new Promise((done) => { + resolve = done + }) + ) + scheduler.start(assignment) + scheduler.close() + resolve({ outcome: 'inconclusive', reason: 'incomplete-measurement' }) + await vi.advanceTimersByTimeAsync(0) + expect(fake.assign).not.toHaveBeenCalled() + }) + it('uses a successor window after an expired report retry', async () => { + setup() + fake.assign.mockRejectedValueOnce(new Error('offline')).mockResolvedValue({ + ...assignment, + regionCorrection: { v: 1, window: { ...window, generation: 2, expiresAt: 48 * HOUR } } + }) + scheduler.start(assignment) + await vi.advanceTimersByTimeAsync(0) + vi.setSystemTime(25 * HOUR) + await vi.advanceTimersByTimeAsync(60_000) + expect(fake.assign.mock.calls[1]![0].regionCorrection).toEqual({ v: 1, action: 'issue-window' }) + }) +}) diff --git a/src/main/runtime/relay/relay-region-refresh.ts b/src/main/runtime/relay/relay-region-refresh.ts new file mode 100644 index 00000000000..c93a9d9618e --- /dev/null +++ b/src/main/runtime/relay/relay-region-refresh.ts @@ -0,0 +1,172 @@ +import { RelayHttpError, requestRelayAssignment, type RelayAssignment } from './relay-http-client' +import type { + RelayRegionCorrectionRequest, + RelayRegionDecision, + RelayRegionWindow +} from './relay-region-correction-protocol' + +type RefreshOptions = { + directorUrl: string + relayHostId: string + token: () => string | undefined + assignment: () => RelayAssignment | null + isCurrent: () => boolean + isOnline: () => boolean + applyAssignment: (assignment: RelayAssignment) => boolean + measure: (window: RelayRegionWindow) => Promise + fetch?: typeof globalThis.fetch + now?: () => number + random?: () => number +} + +const HOUR = 60 * 60_000 + +export class RelayRegionRefresh { + private timer: ReturnType | null = null + private pending: Promise | null = null + private report: Extract | null = null + private window: RelayRegionWindow | null = null + private closed = false + private nextDeadline = 0 + + constructor(private readonly options: RefreshOptions) {} + + start(assignment: RelayAssignment): void { + this.window = assignment.regionCorrection?.window ?? null + if (this.window) { + this.checkDeadline() + } else { + this.schedule(HOUR) + } + } + + checkDeadline(): void { + if (!this.isCurrent() || this.pending) { + return + } + if (this.now() < this.nextDeadline) { + if (!this.timer) { + this.schedule(Math.min(HOUR, this.nextDeadline - this.now())) + } + return + } + if (!this.options.isOnline()) { + this.schedule(60_000) + return + } + this.pending = this.refresh().finally(() => { + this.pending = null + }) + } + + close(): void { + this.closed = true + if (this.timer) { + clearTimeout(this.timer) + } + this.timer = null + this.report = null + this.window = null + } + + private async exchange(regionCorrection: RelayRegionCorrectionRequest): Promise { + const token = this.options.token() + if (!token) { + throw new Error('relay_region_authorization_unavailable') + } + const assignment = await requestRelayAssignment({ + directorUrl: this.options.directorUrl, + relayHostId: this.options.relayHostId, + relayToken: token, + reconnect: true, + regionCorrection, + isCurrent: () => this.isCurrent(), + fetch: this.options.fetch + }) + if (!this.isCurrent()) { + throw new Error('stale_relay_region_refresh') + } + // The mode-bearing source drain owns migration activation; reports never rebind controls. + this.options.applyAssignment(assignment) + return assignment + } + + private async refresh(): Promise { + try { + const assignment = this.options.assignment() + if (!assignment) { + this.schedule(60_000) + return + } + if ( + this.window && + (this.window.expiresAt <= this.now() || + this.window.assignmentEpoch !== assignment.assignmentEpoch) + ) { + this.window = null + this.report = null + } + if (!this.window) { + this.window = + (await this.exchange({ v: 1, action: 'issue-window' })).regionCorrection?.window ?? null + } + const window = this.window + if (!window) { + this.schedule(HOUR) + return + } + if (!this.report) { + const decision = await this.options.measure(window) + if (!this.isCurrent()) { + return + } + this.report = { + v: 1, + action: 'report', + generation: window.generation, + assignmentEpoch: window.assignmentEpoch, + policyVersion: 1, + ...decision + } + } + const report = this.report + const response = await this.exchange(report) + const accepted = response.regionCorrection?.reportStatus + this.report = null + this.window = null + this.schedule( + (accepted === 'accepted' || accepted === 'duplicate') && report.outcome === 'conclusive' + ? 24 * HOUR + : HOUR + ) + } catch (error) { + // Retry the same report/window: auth and healthy sockets are independent of probing. + const retry = error instanceof RelayHttpError ? (error.retryAfterMs ?? 0) : 0 + this.schedule(Math.max(60_000, retry), retry) + } + } + + private schedule(delay: number, minimumDelay = 0): void { + if (!this.isCurrent()) { + return + } + if (this.timer) { + clearTimeout(this.timer) + } + const jitter = 0.9 + (this.options.random ?? Math.random)() * 0.2 + const scheduledDelay = Math.max(minimumDelay, Math.ceil(delay * jitter)) + this.nextDeadline = this.now() + scheduledDelay + this.timer = setTimeout(() => { + this.timer = null + this.checkDeadline() + }, scheduledDelay) + this.timer.unref?.() + } + + private now(): number { + return (this.options.now ?? Date.now)() + } + private isCurrent(): boolean { + return !this.closed && this.options.isCurrent() + } +} diff --git a/src/main/runtime/relay/relay-session-broker-contract.ts b/src/main/runtime/relay/relay-session-broker-contract.ts index 78849f80eba..355bed76360 100644 --- a/src/main/runtime/relay/relay-session-broker-contract.ts +++ b/src/main/runtime/relay/relay-session-broker-contract.ts @@ -4,6 +4,7 @@ import type { MobileRelayStatus } from '../../../shared/mobile-relay-status' import type { E2EEKeypair } from '../e2ee-keypair' import type { MobileSocketWiring } from '../rpc/mobile-socket-wiring' import type { RelayRegion } from './relay-region-preference' +import type { RelayRegionDecision, RelayRegionWindow } from './relay-region-correction-protocol' export type RelayBrokerStatus = MobileRelayStatus @@ -23,6 +24,7 @@ export type RelaySessionBrokerOptions = { isCurrent: () => boolean refreshAccessToken: () => Promise resolvePreferredRegion?: () => Promise + measureRegionDecision?: (window: RelayRegionWindow) => Promise onAssignedCellActive?: (cellUrl: string) => void /** `cellUrl` is absent whenever the host holds no active assignment. */ onStatus: (status: RelayBrokerStatus, cellUrl?: string) => void @@ -32,3 +34,9 @@ export type RelaySessionBrokerOptions = { random?: () => number now?: () => number } + +export class StaleRelayBrokerError extends Error { + constructor() { + super('stale_relay_broker') + } +} diff --git a/src/main/runtime/relay/relay-session-broker.ts b/src/main/runtime/relay/relay-session-broker.ts index e8af020daf8..f32a077885e 100644 --- a/src/main/runtime/relay/relay-session-broker.ts +++ b/src/main/runtime/relay/relay-session-broker.ts @@ -1,3 +1,5 @@ +import { StaleRelayBrokerError } from './relay-session-broker-contract' +export { StaleRelayBrokerError } from './relay-session-broker-contract' import { relayStatusCellUrl } from '../../../shared/mobile-relay-status' import type { PairingRelay } from '../../../shared/mobile-relay-pairing-offer' import type { @@ -17,21 +19,17 @@ import { type RelayAssignment } from './relay-http-client' import { RelayOriginPool } from './relay-origin-pool' +import { RelayRegionRefresh } from './relay-region-refresh' import { relayRenewalDelayMs } from './relay-renewal-jitter' import type { RelayBrokerStatus, RelaySessionBrokerOptions } from './relay-session-broker-contract' export type { RelayBrokerStatus } from './relay-session-broker-contract' -export class StaleRelayBrokerError extends Error { - constructor() { - super('stale_relay_broker') - } -} - export class RelaySessionBroker { private readonly options: RelaySessionBrokerOptions private readonly relayHostId: string private readonly originPool: RelayOriginPool + private readonly regionRefresh: RelayRegionRefresh | null private authorization: RelayAuthorization | null = null private refreshTimer: ReturnType | null = null private closed = false @@ -55,6 +53,21 @@ export class RelaySessionBroker { random: options.random, now: options.now }) + this.regionRefresh = options.measureRegionDecision + ? new RelayRegionRefresh({ + directorUrl: options.authConfig.relayDirectorUrl, + relayHostId: this.relayHostId, + token: () => this.authorization?.relayToken, + assignment: () => this.originPool.activeAssignment, + isCurrent: () => this.isCurrent(), + isOnline: () => this.originPool.hasLiveControl(), + applyAssignment: (assignment) => this.originPool.applyAssignmentMetadata(assignment), + measure: options.measureRegionDecision, + fetch: options.fetch, + now: options.now, + random: options.random + }) + : null } static async connect(options: RelaySessionBrokerOptions): Promise { @@ -194,6 +207,7 @@ export class RelaySessionBroker { this.refreshTimer = null } this.originPool.closeNow(hostCloseReason) + this.regionRefresh?.close() if (publishOffline) { this.options.onStatus('offline') } @@ -220,6 +234,9 @@ export class RelaySessionBroker { // through to the placement lane. reconnect: true, preferredRegion, + ...(this.regionRefresh + ? { regionCorrection: { v: 1 as const, action: 'issue-window' as const } } + : {}), isCurrent: () => this.isCurrent(), fetch: this.options.fetch }) @@ -236,6 +253,7 @@ export class RelaySessionBroker { this.authorization = authorization this.publishStatus('registered') this.scheduleRefresh() + this.regionRefresh?.start(assignment) } private scheduleRefresh(): void { @@ -267,6 +285,7 @@ export class RelaySessionBroker { this.assertCurrent() this.originPool.refreshAuthorization(authorization.relayToken) this.authorization = authorization + this.regionRefresh?.checkDeadline() this.scheduleRefresh() } catch { const expiry = this.authorization?.expiresAt ?? 0 diff --git a/src/main/runtime/remote-runtime-close-intent.integration.test.ts b/src/main/runtime/remote-runtime-close-intent.integration.test.ts index fec4a67388a..321d466e3f2 100644 --- a/src/main/runtime/remote-runtime-close-intent.integration.test.ts +++ b/src/main/runtime/remote-runtime-close-intent.integration.test.ts @@ -44,6 +44,7 @@ it( ] }) const runtime = { + configureNotificationDismissalStore: () => {}, getRuntimeId: () => 'close-intent-runtime-test', getStartedAt: () => 1, cleanupSubscriptionsForConnection: () => {}, diff --git a/src/main/runtime/remote-runtime-request-connection.integration.test.ts b/src/main/runtime/remote-runtime-request-connection.integration.test.ts index 7429b2aaa88..32dcb5d350e 100644 --- a/src/main/runtime/remote-runtime-request-connection.integration.test.ts +++ b/src/main/runtime/remote-runtime-request-connection.integration.test.ts @@ -44,6 +44,7 @@ describe('remote runtime request connection integration', () => { } ] const runtime = { + configureNotificationDismissalStore: () => {}, getRuntimeId: () => 'fetch-runtime-test', getStartedAt: () => 1, cleanupSubscriptionsForConnection: () => {}, @@ -115,6 +116,7 @@ describe('remote runtime request connection integration', () => { const clientEventListeners = new Set<(event: RuntimeClientEvent) => void>() const subscriptionCleanups = new Map void>() const runtime = { + configureNotificationDismissalStore: () => {}, getRuntimeId: () => 'events-runtime-test', getStartedAt: () => 1, cleanupSubscriptionsForConnection: (connectionId: string) => { @@ -280,6 +282,7 @@ describe('remote runtime request connection integration', () => { } } const runtime = { + configureNotificationDismissalStore: () => {}, getRuntimeId: () => 'remote-sleep-runtime-test', getStartedAt: () => 1, cleanupSubscriptionsForConnection: (connectionId: string) => { @@ -506,6 +509,7 @@ describe('remote runtime request connection integration', () => { tabs: [] } const runtime = { + configureNotificationDismissalStore: () => {}, getRuntimeId: () => 'shared-runtime-test', getStartedAt: () => 1, getStatus: () => ({ diff --git a/src/main/runtime/rpc/core-typed-method-contract.test.ts b/src/main/runtime/rpc/core-typed-method-contract.test.ts new file mode 100644 index 00000000000..fc1cdd1f97f --- /dev/null +++ b/src/main/runtime/rpc/core-typed-method-contract.test.ts @@ -0,0 +1,114 @@ +// The preserved types are the whole point of defineMethod, so they are asserted here: if a name +// widens to `string` or a result to `unknown`, these assertions fail at typecheck, not at runtime. +import { describe, expect, expectTypeOf, it } from 'vitest' +import { z } from 'zod' +import { + buildRegistry, + defineMethod, + defineStreamingMethod, + eraseRpcMethods, + isStreamingMethod, + type RpcContext, + type RpcMethod, + type RpcStreamingMethod +} from './core' +import type { ALL_RPC_METHODS } from './methods' +import { STATUS_METHODS } from './methods/status' +import type { HOST_CAPABILITY_METHODS } from './methods/host-capabilities' + +const ProbeParams = z.object({ id: z.string(), count: z.number().optional() }) + +const probe = defineMethod({ + name: 'test.typedProbe', + params: ProbeParams, + handler: (params) => ({ id: params.id, count: params.count ?? 0 }) +}) + +const schemalessProbe = defineMethod({ + name: 'test.schemalessProbe', + params: null, + handler: () => ['a', 'b'] +}) + +const streamingProbe = defineStreamingMethod({ + name: 'test.streamingProbe', + params: ProbeParams, + handler: async (params, _ctx, emit) => { + emit(params.id) + } +}) + +type ByName = Extract + +describe('defineMethod preserves the declared contract', () => { + it('keeps the literal method name', () => { + expectTypeOf(probe.name).toEqualTypeOf<'test.typedProbe'>() + expectTypeOf(streamingProbe.name).toEqualTypeOf<'test.streamingProbe'>() + expect(probe.name).toBe('test.typedProbe') + }) + + it('keeps the producer result type', () => { + expectTypeOf(probe.handler).returns.toEqualTypeOf<{ id: string; count: number }>() + expectTypeOf(schemalessProbe.handler).returns.toEqualTypeOf() + }) + + it('infers parsed params from the schema, and `void` without one', () => { + expectTypeOf(probe.handler) + .parameter(0) + .toEqualTypeOf<{ id: string; count?: number | undefined }>() + expectTypeOf(schemalessProbe.handler).parameter(0).toEqualTypeOf() + expectTypeOf(streamingProbe.handler) + .parameter(0) + .toEqualTypeOf<{ id: string; count?: number | undefined }>() + expectTypeOf(probe.params).toEqualTypeOf() + }) + + it('keeps a registered method addressable by its literal name', () => { + type StatusGet = ByName<(typeof STATUS_METHODS)[number], 'status.get'> + type ListDistros = ByName<(typeof HOST_CAPABILITY_METHODS)[number], 'host.wsl.listDistros'> + expectTypeOf().not.toBeNever() + expectTypeOf().returns.toExtend<{ runtimeId: string }>() + expectTypeOf().returns.toEqualTypeOf>() + // The manifest is the erasure boundary's input, so the literal names have to survive it too. + expectTypeOf>().not.toBeNever() + }) +}) + +describe('eraseRpcMethods is the registry boundary', () => { + it('erases to the shape the dispatcher calls, keeping the streaming split', () => { + expectTypeOf(eraseRpcMethods([probe])).toEqualTypeOf() + expectTypeOf(eraseRpcMethods([streamingProbe])).toEqualTypeOf() + expectTypeOf(eraseRpcMethods(STATUS_METHODS)).toEqualTypeOf() + expectTypeOf(eraseRpcMethods([probe])[0]!.handler) + .parameter(0) + .toEqualTypeOf() + }) + + it('returns the same methods, so nothing about the runtime value changes', () => { + const erased = eraseRpcMethods([probe, streamingProbe]) + + expect(erased[0]).toBe(probe) + expect(erased[1]).toBe(streamingProbe) + }) + + it('produces methods the registry accepts and the dispatcher can invoke', async () => { + const registry = buildRegistry([probe, streamingProbe, ...STATUS_METHODS]) + const registered = registry.get('test.typedProbe') + + expect(registered).toBe(probe) + expect(registry.get('status.get')).toBe(STATUS_METHODS[0]) + expect(isStreamingMethod(registry.get('test.streamingProbe')!)).toBe(true) + expect(registered && isStreamingMethod(registered)).toBe(false) + // The dispatcher parses params itself and then calls the erased handler with `unknown`. + const parsed: unknown = probe.params.parse({ id: 'a' }) + expect( + registered && !isStreamingMethod(registered) + ? await registered.handler(parsed, {} as RpcContext) + : undefined + ).toEqual({ id: 'a', count: 0 }) + }) + + it('rejects a duplicate name before erasure hides it', () => { + expect(() => buildRegistry([probe, probe])).toThrow('duplicate_rpc_method:test.typedProbe') + }) +}) diff --git a/src/main/runtime/rpc/core.ts b/src/main/runtime/rpc/core.ts index 702ea1b3aaa..c59c8da64d3 100644 --- a/src/main/runtime/rpc/core.ts +++ b/src/main/runtime/rpc/core.ts @@ -119,28 +119,27 @@ export type RpcContext = { ) => () => void } -export type RpcHandler = (params: TParams, ctx: RpcContext) => unknown +export type RpcHandler = (params: TParams, ctx: RpcContext) => TResult -// Why: RpcMethod erases the param type; centralizing the cast in defineMethod sidesteps RpcHandler's contravariance. -export type RpcMethod = { - readonly name: string - readonly params: ZodType | null - readonly handler: (params: unknown, ctx: RpcContext) => unknown +// Why: a schema-less method takes no params, so its handler must not be able to read the first argument. +type RpcParsedParams = TSchema extends ZodType + ? TSchema['_output'] + : void + +// Why: the authored shape — literal name, params schema, and producer result all survive for compile-time contracts. +export type RpcTypedMethod = { + readonly name: TName + readonly params: TSchema + readonly handler: RpcHandler, TResult> } -type DefineMethodSpec = { - name: string - params: TSchema - handler: RpcHandler -} - -export function defineMethod( - spec: DefineMethodSpec -): RpcMethod { +export function defineMethod( + spec: RpcTypedMethod +): RpcTypedMethod { return { name: spec.name, params: spec.params, - handler: spec.handler as RpcMethod['handler'] + handler: spec.handler } } @@ -150,6 +149,53 @@ export type RpcStreamingHandler = ( emit: (result: unknown) => void ) => Promise +// Why: emitted values stay `unknown` — the emit callback is an input, so there is no return position to infer them from. +export type RpcTypedStreamingMethod = { + readonly name: TName + readonly params: TSchema + readonly stream: true + readonly handler: RpcStreamingHandler> +} + +export function defineStreamingMethod( + spec: Omit, 'stream'> +): RpcTypedStreamingMethod { + return { + name: spec.name, + params: spec.params, + stream: true, + handler: spec.handler + } +} + +// Why `never` params: it makes the declaration a supertype of every parsed-params handler, so typed methods +// travel to the registry boundary — and only there get erased — without a cast in each methods module. +export type RpcMethodDeclaration = { + readonly name: string + readonly params: ZodType | null + readonly handler: (params: never, ctx: RpcContext) => unknown +} + +export type RpcStreamingMethodDeclaration = { + readonly name: string + readonly params: ZodType | null + readonly stream: true + readonly handler: ( + params: never, + ctx: RpcContext, + emit: (result: unknown) => void + ) => Promise +} + +export type RpcAnyMethodDeclaration = RpcMethodDeclaration | RpcStreamingMethodDeclaration + +// Why: RpcMethod is the registry's erased view; the dispatcher parses params itself and hands handlers `unknown`. +export type RpcMethod = { + readonly name: string + readonly params: ZodType | null + readonly handler: (params: unknown, ctx: RpcContext) => unknown +} + // Why: the `stream` flag lets the dispatcher route these to the emit-based path instead of the one-shot Promise path. export type RpcStreamingMethod = { readonly name: string @@ -162,34 +208,33 @@ export type RpcStreamingMethod = { ) => Promise } -type DefineStreamingMethodSpec = { - name: string - params: TSchema - handler: RpcStreamingHandler -} - -export function defineStreamingMethod( - spec: DefineStreamingMethodSpec -): RpcStreamingMethod { - return { - name: spec.name, - params: spec.params, - stream: true, - handler: spec.handler as RpcStreamingMethod['handler'] - } -} - export type RpcAnyMethod = RpcMethod | RpcStreamingMethod +// Why the overloads: erasure drops the parsed-params type, not the one-shot/streaming split the dispatcher routes on. +export function eraseRpcMethods(methods: readonly RpcMethodDeclaration[]): readonly RpcMethod[] +export function eraseRpcMethods( + methods: readonly RpcStreamingMethodDeclaration[] +): readonly RpcStreamingMethod[] +export function eraseRpcMethods( + methods: readonly RpcAnyMethodDeclaration[] +): readonly RpcAnyMethod[] +// Why: the one place the parsed-params type is dropped — contravariance makes it uncastable by assignment, and +// the dispatcher only ever calls a handler with an already-parsed `unknown`. Runtime value is untouched. +export function eraseRpcMethods( + methods: readonly RpcAnyMethodDeclaration[] +): readonly RpcAnyMethod[] { + return methods as readonly RpcAnyMethod[] +} + export function isStreamingMethod(method: RpcAnyMethod): method is RpcStreamingMethod { return 'stream' in method && method.stream === true } export type RpcRegistry = ReadonlyMap -export function buildRegistry(methods: readonly RpcAnyMethod[]): RpcRegistry { +export function buildRegistry(methods: readonly RpcAnyMethodDeclaration[]): RpcRegistry { const registry = new Map() - for (const method of methods) { + for (const method of eraseRpcMethods(methods)) { if (registry.has(method.name)) { throw new Error(`duplicate_rpc_method:${method.name}`) } diff --git a/src/main/runtime/rpc/dispatcher-request-parsing.ts b/src/main/runtime/rpc/dispatcher-request-parsing.ts index da4ec510e75..a4ada6df7c4 100644 --- a/src/main/runtime/rpc/dispatcher-request-parsing.ts +++ b/src/main/runtime/rpc/dispatcher-request-parsing.ts @@ -1,7 +1,7 @@ import { compile, type ZodType } from 'zod' import { formatZodError, - type RpcAnyMethod, + type RpcAnyMethodDeclaration, type RpcEnvelopeMeta, type RpcRequest, type RpcResponse @@ -12,7 +12,7 @@ const compiledParams = new WeakMap() export function parseRpcRequestParams( request: RpcRequest, - method: RpcAnyMethod, + method: RpcAnyMethodDeclaration, meta: RpcEnvelopeMeta ): { value: unknown; error?: undefined } | { value?: undefined; error: RpcResponse } { if (method.params === null) { diff --git a/src/main/runtime/rpc/dispatcher.ts b/src/main/runtime/rpc/dispatcher.ts index 73cfa596dd5..2c407207197 100644 --- a/src/main/runtime/rpc/dispatcher.ts +++ b/src/main/runtime/rpc/dispatcher.ts @@ -1,7 +1,7 @@ import { buildRegistry, isStreamingMethod, - type RpcAnyMethod, + type RpcAnyMethodDeclaration, type RpcEnvelopeMeta, type RpcRegistry, type RpcRequest, @@ -24,7 +24,10 @@ import { parseRpcRequestParams } from './dispatcher-request-parsing' import { RpcStreamingDispatcher } from './rpc-streaming-dispatcher' import { invokeDispatcherUnaryMethod } from './dispatcher-unary-method-invocation' -export type DispatcherOptions = { runtime: OrcaRuntimeService; methods?: readonly RpcAnyMethod[] } +export type DispatcherOptions = { + runtime: OrcaRuntimeService + methods?: readonly RpcAnyMethodDeclaration[] +} type DispatchCallOptions = RpcDispatchStreamingOptions diff --git a/src/main/runtime/rpc/methods/accounts.test.ts b/src/main/runtime/rpc/methods/accounts.test.ts index dc09f93fc22..ac8948422ac 100644 --- a/src/main/runtime/rpc/methods/accounts.test.ts +++ b/src/main/runtime/rpc/methods/accounts.test.ts @@ -2,11 +2,11 @@ import { describe, expect, it, vi } from 'vitest' import { tmpdir } from 'node:os' import { join } from 'node:path' import type { OrcaRuntimeService } from '../../orca-runtime' -import { isStreamingMethod } from '../core' +import { eraseRpcMethods, isStreamingMethod } from '../core' import { ACCOUNT_METHODS } from './accounts' function method(name: string) { - const found = ACCOUNT_METHODS.find((candidate) => candidate.name === name) + const found = eraseRpcMethods(ACCOUNT_METHODS).find((candidate) => candidate.name === name) if (!found) { throw new Error(`Missing method ${name}`) } diff --git a/src/main/runtime/rpc/methods/accounts.ts b/src/main/runtime/rpc/methods/accounts.ts index 41d82965d00..f7fe0af90ec 100644 --- a/src/main/runtime/rpc/methods/accounts.ts +++ b/src/main/runtime/rpc/methods/accounts.ts @@ -1,5 +1,14 @@ -import { z } from 'zod' -import { defineMethod, defineStreamingMethod, type RpcAnyMethod } from '../core' +import { defineMethod, defineStreamingMethod } from '../core' +import { + AccountsUnsubscribeParams, + AddClaudeFromConfigDirParams, + AddCodexFromHomeParams, + ConsumeCodexResetCreditParams, + ListAccountsParams, + RemoveAccountParams, + SelectAccountParams, + SelectCodexAccountForTargetParams +} from '../../../../shared/rpc-contract/accounts-params' // Why: monotonically increasing per-process counter avoids the Date.now() // collision that fired when two near-simultaneous accounts.subscribe calls @@ -7,86 +16,6 @@ import { defineMethod, defineStreamingMethod, type RpcAnyMethod } from '../core' // registerSubscriptionCleanup's existing-key eviction path. let accountsSubscriptionSeq = 0 -const CodexResetTarget = z.discriminatedUnion('runtime', [ - z.object({ runtime: z.literal('host'), wslDistro: z.null() }).strict(), - // Why: reset scope must identify one exact WSL distro; null means all slots only for selection. - z.object({ runtime: z.literal('wsl'), wslDistro: z.string().trim().min(1).max(255) }).strict() -]) - -const CodexSelectionTarget = z.discriminatedUnion('runtime', [ - z.object({ runtime: z.literal('host'), wslDistro: z.null() }).strict(), - z - .object({ - runtime: z.literal('wsl'), - // A null distro intentionally means all WSL selection slots. - wslDistro: z.string().trim().min(1).max(255).nullable() - }) - .strict() -]) - -const SelectAccountParams = z.object({ - accountId: z - .union([z.string().min(1, 'Missing accountId'), z.null()]) - .transform((v) => (v === null ? null : v)) -}) - -const SelectCodexAccountForTargetParams = SelectAccountParams.extend({ - target: CodexSelectionTarget -}) - -const RemoveAccountParams = z.object({ - accountId: z.string().min(1, 'Missing accountId') -}) - -const CodexResetExpectedScope = z - .object({ - target: CodexResetTarget, - accountId: z.string().min(1, 'Missing accountId').max(512), - accountRevision: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER), - offerRevision: z.string().startsWith('v1:', 'Invalid offerRevision').max(4_096) - }) - .strict() - -const ConsumeCodexResetCreditParams = z - .object({ - // Why: the phone owns the logical attempt key so a lost response can be - // retried without spending a finite earned credit twice. - idempotencyKey: z.uuid('Invalid idempotencyKey'), - expectedScope: CodexResetExpectedScope - }) - .strict() - -const AddClaudeFromConfigDirParams = z.object({ - configDir: z.string().min(1, 'Missing configDir'), - runtime: z.enum(['host', 'wsl']).optional(), - wslDistro: z.string().nullish(), - previousLegacyCredentialsSha256: z - .string() - .regex(/^[a-f0-9]{64}$/, 'Invalid legacy credential digest') - .nullable() - .optional() -}) - -const AddCodexFromHomeParams = z.object({ - sourceHome: z.string().min(1, 'Missing sourceHome'), - runtime: z.enum(['host', 'wsl']).optional(), - wslDistro: z.string().nullish() -}) - -// Why: `orca account list` prints only emails and the active ids, so it opts out -// of the forced all-provider usage refresh below — that lane bypasses the poll -// throttle and Retry-After gate and costs one serial round-trip per account. -const ListAccountsParams = z.object({ - refreshUsage: z.boolean().default(true) -}) - -const AccountsUnsubscribeParams = z.object({ - subscriptionId: z - .unknown() - .transform((value) => (typeof value === 'string' && value.length > 0 ? value : '')) - .pipe(z.string().min(1, 'Missing subscriptionId')) -}) - // Why: bridges the desktop ClaudeAccountService / CodexAccountService / // RateLimitService into the WebSocket / local-socket RPC. Read + switch + // remove for all clients; interactive add/re-auth flows spawn `claude login` @@ -95,7 +24,7 @@ const AccountsUnsubscribeParams = z.object({ // captures an already-authenticated CLAUDE_CONFIG_DIR (no PTY) so the local // `orca account add` CLI can register accounts on a headless host; it is gated // to the local runtime connection, never a mobile device token. See #1438. -export const ACCOUNT_METHODS: readonly RpcAnyMethod[] = [ +export const ACCOUNT_METHODS = [ defineMethod({ name: 'accounts.list', params: ListAccountsParams, diff --git a/src/main/runtime/rpc/methods/agent-hooks.test.ts b/src/main/runtime/rpc/methods/agent-hooks.test.ts index 5781045a1f7..f78e7709d6e 100644 --- a/src/main/runtime/rpc/methods/agent-hooks.test.ts +++ b/src/main/runtime/rpc/methods/agent-hooks.test.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import type { OrcaRuntimeService } from '../../orca-runtime' -import { isStreamingMethod, type RpcContext } from '../core' +import { eraseRpcMethods, isStreamingMethod, type RpcContext } from '../core' const { installForRuntimeHomeSerializedMock, realpathMock } = vi.hoisted(() => ({ installForRuntimeHomeSerializedMock: vi.fn(), @@ -23,7 +23,7 @@ const RUNTIME_HOME = '\\\\wsl.localhost\\Ubuntu-24.04\\home\\jin\\.local\\share\\orca\\codex-runtime-home\\home' function prepareMethod() { - const method = AGENT_HOOK_METHODS.find( + const method = eraseRpcMethods(AGENT_HOOK_METHODS).find( (candidate) => candidate.name === 'agentHooks.prepareCodexForWslPane' ) if (!method || isStreamingMethod(method)) { diff --git a/src/main/runtime/rpc/methods/agent-hooks.ts b/src/main/runtime/rpc/methods/agent-hooks.ts index b26b117bd32..4d9f4a7706c 100644 --- a/src/main/runtime/rpc/methods/agent-hooks.ts +++ b/src/main/runtime/rpc/methods/agent-hooks.ts @@ -1,21 +1,8 @@ -import { z } from 'zod' import { prepareManagedWslCodexHomeBeforeShellLaunch } from '../../../codex/managed-wsl-home-shell-preflight' -import { defineMethod, type RpcMethod } from '../core' +import { defineMethod } from '../core' +import { PrepareCodexForWslPaneParams } from '../../../../shared/rpc-contract/agent-hooks-params' -const PrepareCodexForWslPaneParams = z - .object({ - codexHome: z.string().max(4_096), - orcaCodexHome: z.string().max(4_096), - wslDistro: z - .string() - .trim() - .min(1) - .max(255) - .regex(/^[^\\/\r\n]+$/) - }) - .strict() - -export const AGENT_HOOK_METHODS: readonly RpcMethod[] = [ +export const AGENT_HOOK_METHODS = [ defineMethod({ name: 'agentHooks.prepareCodexForWslPane', params: PrepareCodexForWslPaneParams, diff --git a/src/main/runtime/rpc/methods/agent-session.ts b/src/main/runtime/rpc/methods/agent-session.ts index 08aaa91038e..84e008a7f55 100644 --- a/src/main/runtime/rpc/methods/agent-session.ts +++ b/src/main/runtime/rpc/methods/agent-session.ts @@ -1,9 +1,3 @@ -import { z } from 'zod' -import { - getAgentResumeArgv, - hasUnsafeProviderSessionIdChars, - RESUMABLE_TUI_AGENTS -} from '../../../../shared/agent-session-resume' import type { RuntimeAgentSessionRpcCaller, RuntimeCreateAgentSessionRequest, @@ -15,182 +9,13 @@ import { AGENT_SESSION_OPERATION_FUTURE_SKEW_MS, parseAgentSessionOperationTimestamp } from '../../../../shared/agent-session-host-authority' -import { isTuiAgent } from '../../../../shared/tui-agent-config' -import { isValidTerminalTabId } from '../../../../shared/terminal-tab-id' import type { OrcaRuntimeService } from '../../orca-runtime' -import { defineMethod, type RpcAnyMethod } from '../core' - -const MAX_WORKTREE_SELECTOR_LENGTH = 32_768 -const MAX_TRANSCRIPT_PATH_BYTES = 16 * 1024 -const MAX_PROMPT_BYTES = 256 * 1024 -const MAX_AGENT_ARGS_BYTES = 16 * 1024 -const MAX_LAUNCH_PREFERENCE_LENGTH = 512 - -const StrictNonEmptyString = (max: number, message: string) => - z - .string() - .min(1, message) - .max(max, message) - .refine((value) => value === value.trim(), `${message}; surrounding whitespace is invalid`) - -const WorktreeSelector = StrictNonEmptyString( - MAX_WORKTREE_SELECTOR_LENGTH, - 'Invalid worktree selector' -) - -const Presentation = z.enum(['background', 'focused']) - -const Placement = z - .object({ - tabId: z - .string() - .min(1) - .max(512) - .refine(isValidTerminalTabId, 'Invalid terminal tab ID') - .optional(), - leafId: z.string().min(1).max(128).optional() - }) - .strict() - .refine((value) => value.tabId !== undefined || value.leafId !== undefined, { - message: 'Placement must include a tab or leaf ID' - }) - -const LaunchPreferences = z - .object({ - model: StrictNonEmptyString( - MAX_LAUNCH_PREFERENCE_LENGTH, - 'Invalid model preference' - ).optional(), - effort: StrictNonEmptyString( - MAX_LAUNCH_PREFERENCE_LENGTH, - 'Invalid effort preference' - ).optional(), - mode: StrictNonEmptyString(MAX_LAUNCH_PREFERENCE_LENGTH, 'Invalid mode preference').optional() - }) - .strict() - -const PromptDelivery = z.enum(['auto-submit', 'draft']) - -const AgentArgs = z - .string() - .refine( - (value) => Buffer.byteLength(value, 'utf8') <= MAX_AGENT_ARGS_BYTES, - 'Agent arguments are too large' - ) - .nullable() - -const OmpResumeFilePath = z - .string() - .min(1) - .refine((value) => value === value.trim(), 'Invalid OMP resume path') - .refine( - (value) => - !hasUnsafeProviderSessionIdChars(value) && - Buffer.byteLength(value, 'utf8') <= MAX_TRANSCRIPT_PATH_BYTES, - 'Invalid OMP resume path' - ) - -const ProviderSession = z - .object({ - key: z.enum(['session_id', 'conversation_id']), - id: StrictNonEmptyString(512, 'Invalid provider session ID').refine( - (value) => !value.startsWith('-') && !hasUnsafeProviderSessionIdChars(value), - 'Invalid provider session ID' - ), - transcriptPath: z - .string() - .min(1) - .refine((value) => value === value.trim(), 'Invalid transcript path') - .refine( - (value) => - !hasUnsafeProviderSessionIdChars(value) && - Buffer.byteLength(value, 'utf8') <= MAX_TRANSCRIPT_PATH_BYTES, - 'Invalid transcript path' - ) - .optional() - }) - .strict() - -const AutomaticEnsure = z - .object({ - kind: z.literal('automatic'), - sleepingCheckpointId: z - .string() - .min(32) - .max(128) - .regex(/^[A-Za-z0-9_-]+$/), - presentation: Presentation.optional() - }) - .strict() - -const ExplicitEnsure = z - .object({ - kind: z.literal('explicit'), - worktree: WorktreeSelector, - agent: z.enum(RESUMABLE_TUI_AGENTS), - providerSession: ProviderSession, - ompResumeFilePath: OmpResumeFilePath.optional(), - agentArgs: AgentArgs.optional(), - launchPreferences: LaunchPreferences.optional(), - presentation: Presentation.optional(), - placement: Placement.optional() - }) - .strict() - .superRefine((value, context) => { - if (value.ompResumeFilePath !== undefined && value.agent !== 'omp') { - context.addIssue({ - code: z.ZodIssueCode.custom, - path: ['ompResumeFilePath'], - message: 'OMP resume path requires the OMP agent' - }) - } - if (getAgentResumeArgv(value.agent, value.providerSession, value.ompResumeFilePath) === null) { - context.addIssue({ - code: z.ZodIssueCode.custom, - path: ['providerSession'], - message: 'Provider session is not resumable for this agent' - }) - } - }) - -export const EnsureAgentSessionParams: z.ZodType = - z.discriminatedUnion('kind', [AutomaticEnsure, ExplicitEnsure]) - -export const CreateAgentSessionParams: z.ZodType = z - .object({ - clientOperationId: z - .string() - .refine( - (value) => parseAgentSessionOperationTimestamp(value) !== null, - 'Invalid agent operation ID' - ), - worktree: WorktreeSelector, - agent: z.string().refine(isTuiAgent, 'Unknown agent preset'), - prompt: z - .string() - .refine( - (value) => Buffer.byteLength(value, 'utf8') <= MAX_PROMPT_BYTES, - 'Prompt is too large' - ) - .optional(), - promptDelivery: PromptDelivery.optional(), - agentArgs: AgentArgs.optional(), - launchPreferences: LaunchPreferences.optional(), - startupCwd: z.string().min(1).max(MAX_WORKTREE_SELECTOR_LENGTH).optional(), - presentation: Presentation.optional(), - placement: Placement.optional(), - viewMode: z.enum(['terminal', 'chat']).optional() - }) - .strict() - .superRefine((value, context) => { - if (value.promptDelivery === 'draft' && !value.prompt?.trim()) { - context.addIssue({ - code: z.ZodIssueCode.custom, - path: ['prompt'], - message: 'Draft delivery requires a non-empty prompt' - }) - } - }) +import { defineMethod } from '../core' +import { + CreateAgentSessionParams, + EnsureAgentSessionParams +} from '../../../../shared/rpc-contract/agent-session-params' +export { CreateAgentSessionParams, EnsureAgentSessionParams } type AgentSessionRuntime = OrcaRuntimeService & { ensureAgentSession( @@ -233,7 +58,7 @@ function assertOperationTimestampWithinFutureSkew(clientOperationId: string): vo } } -export const AGENT_SESSION_METHODS: RpcAnyMethod[] = [ +export const AGENT_SESSION_METHODS = [ defineMethod({ name: 'terminal.ensureAgentSession', params: EnsureAgentSessionParams, diff --git a/src/main/runtime/rpc/methods/ai-vault.ts b/src/main/runtime/rpc/methods/ai-vault.ts index c689165924d..abc3aff2650 100644 --- a/src/main/runtime/rpc/methods/ai-vault.ts +++ b/src/main/runtime/rpc/methods/ai-vault.ts @@ -1,86 +1,21 @@ -import { z } from 'zod' -import { defineMethod, type RpcMethod } from '../core' -import { OptionalBoolean } from '../schemas' +import { defineMethod } from '../core' import { restampAiVaultListResult } from '../../../ai-vault/session-list-results' -import { AI_VAULT_AGENTS, AI_VAULT_SCOPE_PATHS_MAX_COUNT } from '../../../../shared/ai-vault-types' -import { AI_VAULT_SESSION_TITLE_REQUEST_MAX_COUNT } from '../../../../shared/ai-vault-session-title' import type { AiVaultPrepareSessionResumeArgs } from '../../../../shared/ai-vault-resume-preparation' -import { LOCAL_EXECUTION_HOST_ID, parseExecutionHostId } from '../../../../shared/execution-host' +import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host' import { describeAiVaultScanError } from '../../../../shared/ai-vault-scan-error-message' import { STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY } from '../../../../shared/protocol-version' import { assertLegacyAiVaultResumeAllowed, projectStructuredAiVaultSessions } from '../../../ai-vault/structured-session-ownership' +import { + AiVaultListSessionsParams, + AiVaultPrepareSessionResumeParams, + AiVaultSessionTitlesParams +} from '../../../../shared/rpc-contract/ai-vault-params' +export { AiVaultListSessionsParams, AiVaultPrepareSessionResumeParams, AiVaultSessionTitlesParams } -// Why: bound limit + scopePaths so a client cannot force an unbounded scan. -// Each scopePath is a host-local match prefix (validated/capped, never used for -// traversal); the count/length caps mirror the worktree-schemas bounding style. -const AI_VAULT_SCOPE_PATH_MAX_LENGTH = 4096 -const AI_VAULT_LIMIT_MAX = 2000 - -const executionHostIdSchema = z.string().transform((value, ctx): `runtime:${string}` => { - const parsed = parseExecutionHostId(value) - if (parsed?.kind === 'runtime') { - return parsed.id - } - ctx.addIssue({ - code: 'custom', - message: 'Invalid runtime execution host id' - }) - return z.NEVER -}) - -export const AiVaultListSessionsParams = z - .object({ - limit: z - .unknown() - .transform((value) => - typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined - ) - .pipe(z.union([z.number().int(), z.undefined()])) - .optional(), - unlimited: OptionalBoolean, - force: OptionalBoolean, - scopePaths: z - .array(z.string().min(1).max(AI_VAULT_SCOPE_PATH_MAX_LENGTH)) - // Why: clamp instead of reject — scope paths only ever widen discovery, and - // rejecting would hard-break older/uncapped producers (web client, pre-cap - // desktop parents) that send more than the bound. - .transform((paths) => paths.slice(0, AI_VAULT_SCOPE_PATHS_MAX_COUNT)) - .optional(), - // Why: desktop/web callers name the runtime host they are addressing; mobile - // omits it. The scan itself is host-local either way, so the id must never - // change what is scanned — it only restamps the shared cached result. - executionHostId: executionHostIdSchema.optional() - }) - .superRefine((params, ctx) => { - if (params.unlimited !== true && params.limit && params.limit > AI_VAULT_LIMIT_MAX) { - ctx.addIssue({ code: 'custom', path: ['limit'], message: 'Limit exceeds maximum' }) - } - }) - -export const AiVaultPrepareSessionResumeParams = z.object({ - agent: z.enum(AI_VAULT_AGENTS), - sessionId: z.string().min(1).max(512).optional(), - filePath: z.string().min(1).max(AI_VAULT_SCOPE_PATH_MAX_LENGTH), - codexHome: z.string().min(1).max(AI_VAULT_SCOPE_PATH_MAX_LENGTH).nullable(), - executionHostId: z.string().optional() -}) - -export const AiVaultSessionTitlesParams = z.object({ - requests: z - .array( - z.object({ - agent: z.enum(['claude', 'codex']), - sessionId: z.string().min(1).max(512), - transcriptPath: z.string().min(1).max(32_768).optional() - }) - ) - .max(AI_VAULT_SESSION_TITLE_REQUEST_MAX_COUNT) -}) - -export const AI_VAULT_METHODS: RpcMethod[] = [ +export const AI_VAULT_METHODS = [ defineMethod({ name: 'aiVault.resolveSessionTitles', params: AiVaultSessionTitlesParams, diff --git a/src/main/runtime/rpc/methods/artifacts.ts b/src/main/runtime/rpc/methods/artifacts.ts index 4b5d7b5ab3a..b6b91af8b0b 100644 --- a/src/main/runtime/rpc/methods/artifacts.ts +++ b/src/main/runtime/rpc/methods/artifacts.ts @@ -1,47 +1,12 @@ -import { z } from 'zod' +import { defineMethod } from '../core' import { - ARTIFACT_MAX_CONTENT_BYTES, - ARTIFACT_MAX_REQUEST_BYTES, - artifactContentByteLength, - artifactWriteRequestByteLength -} from '../../../../shared/artifacts' -import { defineMethod, type RpcAnyMethod } from '../core' + ArtifactsDeleteParams, + ListOptions, + SourceRequest, + WriteRequest +} from '../../../../shared/rpc-contract/artifacts-params' -const CloudOptions = { - apiUrl: z.string().max(2_048).optional(), - authToken: z.string().max(16_384).optional() -} - -const ListOptions = z.object({ - ...CloudOptions, - cursor: z.string().min(1).max(2_048).optional() -}) - -const SourceRequest = z.object({ - sourceKey: z.string().min(1).max(32_768), - ...CloudOptions -}) - -const WriteRequest = z - .object({ - sourceKey: z.string().min(1).max(32_768), - content: z - .string() - .min(1) - .max(ARTIFACT_MAX_CONTENT_BYTES) - .refine((content) => artifactContentByteLength(content) <= ARTIFACT_MAX_CONTENT_BYTES, { - message: 'Artifact content exceeds the 10 MiB limit.' - }), - contentType: z.enum(['text/html', 'text/markdown']), - fileName: z.string().min(1).max(512), - title: z.string().max(512).optional(), - ...CloudOptions - }) - .refine((request) => artifactWriteRequestByteLength(request) <= ARTIFACT_MAX_REQUEST_BYTES, { - message: 'Artifact request exceeds the supported size.' - }) - -export const ARTIFACT_METHODS: readonly RpcAnyMethod[] = [ +export const ARTIFACT_METHODS = [ defineMethod({ name: 'artifacts.list', params: ListOptions, @@ -74,7 +39,7 @@ export const ARTIFACT_METHODS: readonly RpcAnyMethod[] = [ }), defineMethod({ name: 'artifacts.delete', - params: z.object({ id: z.string().min(1), ...CloudOptions }), + params: ArtifactsDeleteParams, handler: (params, { runtime }) => runtime.deleteArtifact(params.id, params) }) ] diff --git a/src/main/runtime/rpc/methods/automation-schemas.ts b/src/main/runtime/rpc/methods/automation-schemas.ts index f2c829c1a9d..23962b84ccc 100644 --- a/src/main/runtime/rpc/methods/automation-schemas.ts +++ b/src/main/runtime/rpc/methods/automation-schemas.ts @@ -1,193 +1,10 @@ // Why: the automation method table stays readable only if its field-level validation lives beside it rather than inside it. -import { z } from 'zod' -import { isValidAutomationSchedule } from '../../../../shared/automation-schedule-parsing' -import { - MAX_AUTOMATION_PRECHECK_TIMEOUT_SECONDS, - normalizeAutomationPrecheckTimeoutSeconds -} from '../../../../shared/automation-precheck' -import { normalizeExecutionHostId } from '../../../../shared/execution-host' -import type { TaskProviderIdentity as SharedTaskProviderIdentity } from '../../../../shared/task-source-context' -import { isTuiAgent } from '../../../../shared/tui-agent-config' -import { - OptionalBoolean, - OptionalPlainString, - OptionalPositiveInt, - OptionalString, - requiredNumber, - requiredString -} from '../schemas' - -const TuiAgent = requiredString('Missing provider').refine(isTuiAgent, { - message: 'Unknown provider' -}) - -const AutomationWorkspaceMode = z.enum(['existing', 'new_per_run']).optional() -const SetupDecision = z.enum(['inherit', 'run', 'skip']).optional() -const ExecutionHostId = requiredString('Missing host id').transform((value, ctx) => { - const hostId = normalizeExecutionHostId(value) - if (!hostId) { - ctx.addIssue({ code: 'custom', message: 'Invalid host id' }) - return z.NEVER - } - return hostId -}) - -const AutomationSchedule = requiredString('Missing trigger').refine(isValidAutomationSchedule, { - message: 'Invalid automation trigger' -}) - -const AutomationPrecheck = z - .object({ - command: requiredString('Missing precheck command'), - timeoutSeconds: OptionalPositiveInt.transform((value) => - normalizeAutomationPrecheckTimeoutSeconds(value) - ).refine((value) => value <= MAX_AUTOMATION_PRECHECK_TIMEOUT_SECONDS, { - message: 'Precheck timeout is too large' - }) - }) - .nullable() - .optional() - -const OptionalNullablePlainString = z - .unknown() - .transform((value) => (value === null || typeof value === 'string' ? value : undefined)) - .pipe(z.union([z.string(), z.null(), z.undefined()])) - .optional() - -const TaskProviderIdentity = z - .custom( - (value) => - value !== null && - typeof value === 'object' && - 'provider' in value && - ['github', 'gitlab', 'linear', 'jira'].includes(String(value.provider)) - ) - .optional() - .nullable() - -const TaskSourceContext = z - .object({ - kind: z.literal('task-source'), - provider: z.enum(['github', 'gitlab', 'linear', 'jira']), - projectId: requiredString('Missing source project id'), - hostId: ExecutionHostId, - projectHostSetupId: OptionalNullablePlainString, - repoId: OptionalNullablePlainString, - providerIdentity: TaskProviderIdentity, - accountLabel: OptionalNullablePlainString - }) - .optional() - .nullable() - -const WorkspaceRunContext = z - .object({ - kind: z.literal('workspace-run'), - projectId: requiredString('Missing run project id'), - hostId: ExecutionHostId, - projectHostSetupId: requiredString('Missing project host setup id'), - repoId: requiredString('Missing repo id'), - path: requiredString('Missing run path') - }) - .optional() - .nullable() - -const SshTargetGeneration = requiredNumber('Missing SSH target generation').refine( - (value) => Number.isSafeInteger(value) && value >= 1, - { message: 'Invalid SSH target generation' } -) - -const OwnedSshSelector = z.object({ - kind: z.literal('ssh'), - targetId: requiredString('Missing SSH target id'), - targetGeneration: SshTargetGeneration -}) - -/** Orphan is accepted here, unlike a destination: a record with no executable host is still deletable. */ -const OwnerPreconditionSelector = z.discriminatedUnion('kind', [ - z.object({ kind: z.literal('self') }), - OwnedSshSelector, - z.object({ kind: z.literal('orphan') }) -]) - -const DestinationSelector = z.discriminatedUnion('kind', [ - z.object({ kind: z.literal('self') }), - OwnedSshSelector -]) - -export const ExpectedOwner = z.object({ selector: OwnerPreconditionSelector }).optional() -export const Destination = z.object({ selector: DestinationSelector }).optional() - -const ListScopeSelector = z.discriminatedUnion('kind', [ - z.object({ kind: z.literal('self') }), - z.object({ - kind: z.literal('ssh'), - targetId: requiredString('Missing SSH target id'), - expectedTargetGeneration: SshTargetGeneration - }), - z.object({ kind: z.literal('orphan') }) -]) - -/** An omitted selector is the legacy request; old clients keep the authority's complete list. */ -export const AutomationList = z.object({ selector: ListScopeSelector.optional() }) - -export const AutomationId = z.object({ - id: requiredString('Missing automation id'), - expectedOwner: ExpectedOwner -}) - -export const AutomationRuns = z.object({ - automationId: OptionalString, - expectedOwner: ExpectedOwner, - limit: OptionalPositiveInt, - cursor: OptionalString -}) - -export const AutomationCreate = z.object({ - creationKey: OptionalString, - name: requiredString('Missing automation name'), - prompt: requiredString('Missing automation prompt'), - precheck: AutomationPrecheck, - agentId: TuiAgent, - runContext: WorkspaceRunContext, - sourceContext: TaskSourceContext, - repo: OptionalString, - workspace: OptionalString, - workspaceMode: AutomationWorkspaceMode, - baseBranch: OptionalPlainString, - setupDecision: SetupDecision, - reuseSession: OptionalBoolean, - timezone: OptionalString, - rrule: AutomationSchedule, - dtstart: requiredNumber('Missing trigger start time'), - enabled: OptionalBoolean, - missedRunGraceMinutes: OptionalPositiveInt, - destination: Destination -}) - -const AutomationUpdateFields = z.object({ - name: OptionalString, - prompt: OptionalString, - precheck: AutomationPrecheck, - agentId: TuiAgent.optional(), - runContext: WorkspaceRunContext, - sourceContext: TaskSourceContext, - repo: OptionalString, - workspace: OptionalString, - workspaceMode: AutomationWorkspaceMode, - // Why: update patches distinguish omitted from null so callers can clear a saved base branch. - baseBranch: OptionalNullablePlainString, - setupDecision: SetupDecision, - reuseSession: OptionalBoolean, - timezone: OptionalString, - rrule: AutomationSchedule.optional(), - dtstart: requiredNumber('Missing trigger start time').optional(), - enabled: OptionalBoolean, - missedRunGraceMinutes: OptionalPositiveInt -}) - -export const AutomationUpdate = z.object({ - id: requiredString('Missing automation id'), - updates: AutomationUpdateFields, - expectedOwner: ExpectedOwner, - destination: Destination -}) +export { + AutomationCreate, + AutomationId, + AutomationList, + AutomationRuns, + AutomationUpdate, + Destination, + ExpectedOwner +} from '../../../../shared/rpc-contract/automation-params' diff --git a/src/main/runtime/rpc/methods/automation-scoped-list-methods.test.ts b/src/main/runtime/rpc/methods/automation-scoped-list-methods.test.ts index f1d2081dc6b..6af7ba467e9 100644 --- a/src/main/runtime/rpc/methods/automation-scoped-list-methods.test.ts +++ b/src/main/runtime/rpc/methods/automation-scoped-list-methods.test.ts @@ -4,14 +4,14 @@ * current callers also receive owner metadata. */ import { describe, expect, it, vi } from 'vitest' -import type { RpcContext, RpcRequest } from '../core' +import { eraseRpcMethods, type RpcContext, type RpcRequest } from '../core' import { RpcDispatcher } from '../dispatcher' import type { OrcaRuntimeService } from '../../orca-runtime' import { AUTOMATION_METHODS } from './automations' import { AUTOMATION_OWNER_FENCING_RUNTIME_CAPABILITY } from '../../../../shared/protocol-version' function method(name: string) { - const found = AUTOMATION_METHODS.find((entry) => entry.name === name) + const found = eraseRpcMethods(AUTOMATION_METHODS).find((entry) => entry.name === name) if (!found?.params) { throw new Error(`missing method ${name}`) } diff --git a/src/main/runtime/rpc/methods/automations.ts b/src/main/runtime/rpc/methods/automations.ts index ff5daca315c..b1e3eebe6eb 100644 --- a/src/main/runtime/rpc/methods/automations.ts +++ b/src/main/runtime/rpc/methods/automations.ts @@ -1,6 +1,6 @@ import { AUTOMATION_OWNER_FENCING_RUNTIME_CAPABILITY } from '../../../../shared/protocol-version' import type { AutomationOwnerPrecondition } from '../../../../shared/automation-owner-precondition' -import { defineMethod, type RpcContext, type RpcMethod } from '../core' +import { defineMethod, type RpcContext } from '../core' import { AutomationCreate, AutomationId, @@ -25,7 +25,7 @@ function mutationOwner( return context.runtime.automationOwnerPrecondition(id) ?? undefined } -export const AUTOMATION_METHODS: RpcMethod[] = [ +export const AUTOMATION_METHODS = [ defineMethod({ name: 'automation.list', params: AutomationList, diff --git a/src/main/runtime/rpc/methods/browser-client-file-channel.ts b/src/main/runtime/rpc/methods/browser-client-file-channel.ts index b2020488af2..362a1990531 100644 --- a/src/main/runtime/rpc/methods/browser-client-file-channel.ts +++ b/src/main/runtime/rpc/methods/browser-client-file-channel.ts @@ -7,7 +7,7 @@ import { BROWSER_CLIENT_HOST_RUNTIME_CAPABILITY } from '../../../../shared/proto import { getBrowserClientDownloadTransferStore } from '../../browser-client-download-transfer-store' import { getBrowserHostLeaseRegistry } from '../../browser-host-lease-registry-instance' import { getRuntimeBrowserPageRegistry } from '../../runtime-browser-page-registry' -import { defineMethod, type RpcAnyMethod, type RpcContext } from '../core' +import { defineMethod, type RpcContext } from '../core' type FileChannelAuthorityParams = { browserHostClientId: string @@ -64,7 +64,7 @@ function requireFileChannelPage( return page } -export const BROWSER_CLIENT_FILE_CHANNEL_METHODS: RpcAnyMethod[] = [ +export const BROWSER_CLIENT_FILE_CHANNEL_METHODS = [ defineMethod({ name: 'browser.clientHost.fileChannel.read', params: BrowserClientFileChannelReadParams, diff --git a/src/main/runtime/rpc/methods/browser-client-host.ts b/src/main/runtime/rpc/methods/browser-client-host.ts index 525fd4fde96..e06632f7959 100644 --- a/src/main/runtime/rpc/methods/browser-client-host.ts +++ b/src/main/runtime/rpc/methods/browser-client-host.ts @@ -14,9 +14,9 @@ import { getRuntimeBrowserPageRegistry } from '../../runtime-browser-page-regist import { adoptRuntimeBrowserClientPagesFromInventory } from '../../runtime-browser-client-page-adoption' import { recoverUnavailableRuntimeBrowserClientPages } from '../../runtime-browser-client-page-recovery' import { releaseRuntimeBrowserClientPageRecord } from '../../runtime-browser-client-page-release' -import { defineMethod, defineStreamingMethod, type RpcAnyMethod } from '../core' +import { defineMethod, defineStreamingMethod } from '../core' -export const BROWSER_CLIENT_HOST_METHODS: RpcAnyMethod[] = [ +export const BROWSER_CLIENT_HOST_METHODS = [ defineStreamingMethod({ name: 'browser.clientHost.attach', params: BrowserClientHostAttachParams, diff --git a/src/main/runtime/rpc/methods/browser-core.ts b/src/main/runtime/rpc/methods/browser-core.ts index 5e5fba227b6..780f40fb373 100644 --- a/src/main/runtime/rpc/methods/browser-core.ts +++ b/src/main/runtime/rpc/methods/browser-core.ts @@ -1,5 +1,5 @@ -import { defineMethod, type RpcMethod } from '../core' -import { BrowserTarget, requiredString } from '../schemas' +import { defineMethod } from '../core' +import { BrowserTarget } from '../schemas' import { Check, Drag, @@ -33,12 +33,9 @@ import { } from './browser-schemas' import { BrowserOpenUrlParams, BrowserTabCreateParams } from './browser-tab-create-schema' import { BROWSER_TEXT_METHODS } from './browser-text-rpc-methods' +import { CertificateProceed } from '../../../../shared/rpc-contract/browser-core-params' -const CertificateProceed = BrowserTarget.extend({ - challengeId: requiredString('Missing required challengeId') -}) - -export const BROWSER_CORE_METHODS: RpcMethod[] = [ +export const BROWSER_CORE_METHODS = [ defineMethod({ name: 'browser.snapshot', params: BrowserTarget, diff --git a/src/main/runtime/rpc/methods/browser-extras.ts b/src/main/runtime/rpc/methods/browser-extras.ts index 692c5e19b7f..000838c4938 100644 --- a/src/main/runtime/rpc/methods/browser-extras.ts +++ b/src/main/runtime/rpc/methods/browser-extras.ts @@ -1,7 +1,6 @@ -import { z } from 'zod' -import { defineMethod, type RpcMethod } from '../core' +import { defineMethod } from '../core' import { assertRpcClipboardTextWriteWithinLimit } from '../rpc-clipboard-text-validation' -import { BrowserTarget, OptionalFiniteNumber } from '../schemas' +import { BrowserTarget } from '../schemas' import { ClipboardWrite, CookieDelete, @@ -22,19 +21,9 @@ import { StorageKeyValue, Viewport } from './browser-schemas' +import { MouseClick } from '../../../../shared/rpc-contract/browser-extras-params' -const MouseModifiers = z - .unknown() - .transform((v) => (Array.isArray(v) ? v : undefined)) - .pipe(z.union([z.array(z.enum(['cmd', 'ctrl', 'alt', 'shift'])), z.undefined()])) - .optional() - -const MouseClick = MouseXY.merge(MouseButton).extend({ - radius: OptionalFiniteNumber, - modifiers: MouseModifiers -}) - -export const BROWSER_EXTRA_METHODS: RpcMethod[] = [ +export const BROWSER_EXTRA_METHODS = [ defineMethod({ name: 'browser.cookie.get', params: CookieGet, diff --git a/src/main/runtime/rpc/methods/browser-network-tunnel.ts b/src/main/runtime/rpc/methods/browser-network-tunnel.ts index 405419deef0..d610824b1f2 100644 --- a/src/main/runtime/rpc/methods/browser-network-tunnel.ts +++ b/src/main/runtime/rpc/methods/browser-network-tunnel.ts @@ -12,14 +12,14 @@ import { BROWSER_NETWORK_TUNNEL_RUNTIME_CAPABILITY } from '../../../../shared/protocol-version' import { getBrowserHostLeaseRegistry } from '../../browser-host-lease-registry-instance' -import { defineStreamingMethod, type RpcAnyMethod } from '../core' +import { defineStreamingMethod } from '../core' const outboundMemoryBudgets = new BrowserNetworkTunnelOutboundMemoryBudgetRegistry() export function createBrowserNetworkTunnelMethods( memoryBudgets: BrowserNetworkTunnelOutboundMemoryBudgetRegistry = outboundMemoryBudgets, resolveExecutionRoute: BrowserNetworkExecutionRouteResolver = resolveBrowserNetworkExecutionRoute -): RpcAnyMethod[] { +) { return [ defineStreamingMethod({ name: 'network.browserTunnel', diff --git a/src/main/runtime/rpc/methods/browser-schemas.ts b/src/main/runtime/rpc/methods/browser-schemas.ts index 03872b61cc0..034fee898ad 100644 --- a/src/main/runtime/rpc/methods/browser-schemas.ts +++ b/src/main/runtime/rpc/methods/browser-schemas.ts @@ -1,356 +1,55 @@ // Why: browser schemas stay separate from handler registration so both sides // remain under the line cap and dispatch wiring stays scannable. -import { z } from 'zod' -import { - BrowserTarget, - OptionalBoolean, - OptionalFiniteNumber, - OptionalPlainString, - OptionalString, - requiredStringAllowingEmpty, - requiredString -} from '../schemas' - -export const Element = BrowserTarget.extend({ - element: requiredString('Missing required --element') -}) - -export const Goto = BrowserTarget.extend({ - url: requiredString('Missing required --url') -}) - -export const Fill = BrowserTarget.extend({ - element: requiredString('Missing required --element'), - value: requiredStringAllowingEmpty('Missing required --value') -}) - -export const Type = BrowserTarget.extend({ - input: requiredString('Missing required --input') -}) - -export const Select = BrowserTarget.extend({ - element: requiredString('Missing required --element'), - value: z.custom((v) => typeof v === 'string', { - message: 'Missing required --value' - }) -}) - -export const Scroll = BrowserTarget.extend({ - direction: z.custom<'up' | 'down'>((v) => v === 'up' || v === 'down', { - message: 'Missing required --direction (up or down)' - }), - amount: z - .unknown() - .transform((v) => (typeof v === 'number' && v > 0 ? v : undefined)) - .pipe(z.union([z.number(), z.undefined()])) - .optional() -}) - -export const Screenshot = BrowserTarget.extend({ - format: z - .unknown() - .transform((v) => (v === 'png' || v === 'jpeg' ? v : undefined)) - .pipe(z.union([z.enum(['png', 'jpeg']), z.undefined()])) - .optional() -}) - -export const Screencast = BrowserTarget.extend({ - format: z - .unknown() - .optional() - .transform((v) => (v === 'png' ? 'png' : 'jpeg')) - .pipe(z.enum(['png', 'jpeg'])), - quality: OptionalFiniteNumber, - maxWidth: OptionalFiniteNumber, - maxHeight: OptionalFiniteNumber, - viewportWidth: OptionalFiniteNumber, - viewportHeight: OptionalFiniteNumber, - deviceScaleFactor: OptionalFiniteNumber, - mobile: OptionalBoolean, - everyNthFrame: OptionalFiniteNumber, - minFrameIntervalMs: OptionalFiniteNumber -}) - -export const FullScreenshot = BrowserTarget.extend({ - format: z - .unknown() - .optional() - .transform((v) => (v === 'jpeg' ? 'jpeg' : 'png')) - .pipe(z.enum(['png', 'jpeg'])) -}) - -export const Eval = BrowserTarget.extend({ - expression: requiredString('Missing required --expression') -}) - -export const TabList = z.object({ worktree: OptionalString }) -// Why: --index xor --page must be present. The refine guards that invariant -// so the dispatcher surfaces a single legible error instead of either shape -// leaking into the runtime. -// -// `focus` is opt-in: when true, the runtime sends `browser:pane-focus` to -// the renderer after the switch lands. The renderer surfaces the browser -// pane only if the user is already on the targeted worktree; otherwise it -// pre-stages per-worktree state silently. This avoids cross-worktree screen -// theft when multiple agents drive browsers in parallel worktrees. -export const TabSwitch = BrowserTarget.extend({ - index: z - .unknown() - .transform((v) => (typeof v === 'number' ? v : undefined)) - .pipe(z.union([z.number(), z.undefined()])) - .optional(), - focus: z.boolean().optional() -}).refine( - (val) => { - if (val.page !== undefined) { - return true - } - return val.index !== undefined && Number.isInteger(val.index) && val.index >= 0 - }, - { message: 'Missing required --index (non-negative integer) or --page' } -) - -export const TabShow = z.object({ - page: requiredString('Missing required --page'), - worktree: OptionalString -}) - -export const TabCurrent = z.object({ worktree: OptionalString }) - -export const TabClose = z.object({ - index: z - .unknown() - .transform((v) => (typeof v === 'number' ? v : undefined)) - .pipe(z.union([z.number(), z.undefined()])) - .optional(), - page: OptionalString, - worktree: OptionalString -}) - -export const TabSetProfile = BrowserTarget.extend({ - profileId: requiredString('Missing required --profile') -}) - -export const TabProfileClone = BrowserTarget.extend({ - profileId: requiredString('Missing required --profile') -}) - -export const ProfileCreate = z.object({ - label: requiredString('Missing required --label'), - // Strict enum so unknown scope values surface validation errors instead of being - // silently coerced to 'isolated' (pr-bug-scan finding from #1397). - scope: z.enum(['isolated', 'imported']), - userAgentMode: z.enum(['clean', 'native']).optional() -}) - -export const ProfileDelete = z.object({ profileId: requiredString('Missing required --profile') }) - -export const ProfileImportFromBrowser = z.object({ - profileId: requiredString('Missing required --profile'), - browserFamily: requiredString('Missing required --browser-family'), - browserProfile: OptionalString, - supportsPartitionSkippedCookies: z.literal(true).optional() -}) - -export const Drag = BrowserTarget.extend({ - from: requiredString('Missing required --from and --to element refs'), - to: requiredString('Missing required --from and --to element refs') -}) - -export const Upload = BrowserTarget.extend({ - element: requiredString('Missing required --element and --files'), - files: z.custom( - (v) => Array.isArray(v) && v.length > 0 && v.every((f) => typeof f === 'string'), - { message: 'Missing required --element and --files' } - ) -}) - -export const Wait = BrowserTarget.extend({ - selector: OptionalPlainString, - timeout: z - .unknown() - .transform((v) => (typeof v === 'number' && v > 0 ? v : undefined)) - .pipe(z.union([z.number(), z.undefined()])) - .optional(), - text: OptionalPlainString, - url: OptionalPlainString, - load: OptionalPlainString, - fn: OptionalPlainString, - state: OptionalPlainString -}) - -export const Check = BrowserTarget.extend({ - element: requiredString('Missing required --element'), - checked: z - .unknown() - .optional() - .transform((v) => (v === undefined ? true : v)) - .pipe(z.boolean()) -}) - -export const Keypress = BrowserTarget.extend({ - key: requiredString('Missing required --key') -}) - -export const SelectorPath = BrowserTarget.extend({ - selector: requiredString('Missing required --selector and --path'), - path: requiredString('Missing required --selector and --path') -}) - -export const Highlight = BrowserTarget.extend({ - selector: requiredString('Missing required --selector') -}) - -export const Exec = BrowserTarget.extend({ - command: requiredString('Missing required --command') -}) - -export const Get = BrowserTarget.extend({ - what: requiredString('Missing required --what'), - selector: OptionalString -}) - -export const Is = BrowserTarget.extend({ - what: z.custom((v) => typeof v === 'string' && v.length > 0, { - message: 'Missing required --what and --element' - }), - selector: z.custom((v) => typeof v === 'string' && v.length > 0, { - message: 'Missing required --what and --element' - }) -}) - -export const KeyboardInsert = BrowserTarget.extend({ - text: requiredString('Missing required --text') -}) - -export const LimitParam = BrowserTarget.extend({ - limit: OptionalFiniteNumber -}) - -export const Find = BrowserTarget.extend({ - locator: requiredString('Missing required --locator, --value, and --action'), - value: requiredString('Missing required --locator, --value, and --action'), - action: requiredString('Missing required --locator, --value, and --action'), - text: OptionalString -}) - -export const CookieGet = BrowserTarget.extend({ - url: OptionalPlainString -}) - -export const CookieSet = BrowserTarget.extend({ - name: z.custom((v) => typeof v === 'string' && v.length > 0, { - message: 'Missing name or value' - }), - value: z.custom((v) => typeof v === 'string', { - message: 'Missing name or value' - }), - domain: OptionalPlainString, - path: OptionalPlainString, - secure: OptionalBoolean, - httpOnly: OptionalBoolean, - sameSite: OptionalPlainString, - expires: OptionalFiniteNumber -}) - -export const CookieDelete = BrowserTarget.extend({ - name: requiredString('Missing cookie name'), - domain: OptionalPlainString, - url: OptionalPlainString -}) - -export const Viewport = BrowserTarget.extend({ - width: z.custom((v) => typeof v === 'number' && v > 0, { - message: 'Width and height must be positive numbers' - }), - height: z.custom((v) => typeof v === 'number' && v > 0, { - message: 'Width and height must be positive numbers' - }), - deviceScaleFactor: OptionalFiniteNumber, - mobile: OptionalBoolean -}) - -export const Geolocation = BrowserTarget.extend({ - latitude: z.custom((v) => typeof v === 'number', { - message: 'Missing latitude or longitude' - }), - longitude: z.custom((v) => typeof v === 'number', { - message: 'Missing latitude or longitude' - }), - accuracy: OptionalFiniteNumber -}) - -export const InterceptEnable = BrowserTarget.extend({ - patterns: z - .unknown() - .transform((v) => (Array.isArray(v) ? (v as string[]) : undefined)) - .pipe(z.union([z.array(z.string()), z.undefined()])) - .optional() -}) - -export const MouseXY = BrowserTarget.extend({ - x: z.custom((v) => typeof v === 'number', { - message: 'Missing required x and y coordinates' - }), - y: z.custom((v) => typeof v === 'number', { - message: 'Missing required x and y coordinates' - }) -}) - -export const MouseButton = BrowserTarget.extend({ - button: OptionalPlainString -}) - -export const MouseWheel = BrowserTarget.extend({ - dy: z.custom((v) => typeof v === 'number', { - message: 'Missing required --dy' - }), - dx: OptionalFiniteNumber -}) - -export const SetDevice = BrowserTarget.extend({ - name: requiredString('Missing required --name') -}) - -export const SetOffline = BrowserTarget.extend({ - state: OptionalPlainString -}) - -export const SetHeaders = BrowserTarget.extend({ - headers: requiredString('Missing required --headers (JSON string)') -}) - -export const SetCredentials = BrowserTarget.extend({ - user: z.custom((v) => typeof v === 'string' && v.length > 0, { - message: 'Missing required --user and --pass' - }), - pass: z.custom((v) => typeof v === 'string', { - message: 'Missing required --user and --pass' - }) -}) - -export const SetMedia = BrowserTarget.extend({ - colorScheme: OptionalPlainString, - reducedMotion: OptionalPlainString -}) - -export const ClipboardWrite = BrowserTarget.extend({ - text: requiredString('Missing required --text') -}) - -export const DialogAccept = BrowserTarget.extend({ - text: OptionalPlainString -}) - -export const StorageKey = BrowserTarget.extend({ - key: requiredString('Missing required --key') -}) - -export const StorageKeyValue = BrowserTarget.extend({ - key: z.custom((v) => typeof v === 'string' && v.length > 0, { - message: 'Missing required --key and --value' - }), - value: z.custom((v) => typeof v === 'string', { - message: 'Missing required --key and --value' - }) -}) +export { + Check, + ClipboardWrite, + CookieDelete, + CookieGet, + CookieSet, + DialogAccept, + Drag, + Element, + Eval, + Exec, + Fill, + Find, + FullScreenshot, + Geolocation, + Get, + Goto, + Highlight, + InterceptEnable, + Is, + KeyboardInsert, + Keypress, + LimitParam, + MouseButton, + MouseWheel, + MouseXY, + ProfileCreate, + ProfileDelete, + ProfileImportFromBrowser, + Screencast, + Screenshot, + Scroll, + Select, + SelectorPath, + SetCredentials, + SetDevice, + SetHeaders, + SetMedia, + SetOffline, + StorageKey, + StorageKeyValue, + TabClose, + TabCurrent, + TabList, + TabProfileClone, + TabSetProfile, + TabShow, + TabSwitch, + Type, + Upload, + Viewport, + Wait +} from '../../../../shared/rpc-contract/browser-params' diff --git a/src/main/runtime/rpc/methods/browser-screencast.ts b/src/main/runtime/rpc/methods/browser-screencast.ts index ea965a2b44a..798e1ed84d2 100644 --- a/src/main/runtime/rpc/methods/browser-screencast.ts +++ b/src/main/runtime/rpc/methods/browser-screencast.ts @@ -1,15 +1,11 @@ -import { z } from 'zod' -import { defineMethod, defineStreamingMethod, type RpcAnyMethod } from '../core' +import { defineMethod, defineStreamingMethod } from '../core' import { Screencast } from './browser-schemas' import { BrowserError } from '../../../browser/browser-error' import { BROWSER_UNAVAILABLE_ERROR_CODE } from '../../../../shared/runtime-types' import { runtimeBrowserCommandsFactoryIsAvailable } from '../../runtime-browser-commands-factory' +import { ScreencastUnsubscribe } from '../../../../shared/rpc-contract/browser-screencast-params' -const ScreencastUnsubscribe = z.object({ - subscriptionId: z.string().min(1, 'Missing required --subscription-id') -}) - -export const BROWSER_SCREENCAST_METHODS: RpcAnyMethod[] = [ +export const BROWSER_SCREENCAST_METHODS = [ defineStreamingMethod({ name: 'browser.screencast', params: Screencast, diff --git a/src/main/runtime/rpc/methods/browser-tab-create-schema.ts b/src/main/runtime/rpc/methods/browser-tab-create-schema.ts index 799111b2a6b..ad7c0ee5b75 100644 --- a/src/main/runtime/rpc/methods/browser-tab-create-schema.ts +++ b/src/main/runtime/rpc/methods/browser-tab-create-schema.ts @@ -1,23 +1,4 @@ -import { z } from 'zod' -import { OptionalString } from '../schemas' -import { BrowserPageCreationPlacement } from '../../../../shared/browser-client-host-placement' -import { RUNTIME_NAVIGATION_TARGETS } from '../../../../shared/runtime-navigation' - -export const BrowserTabCreateParams = z.object({ - url: OptionalString, - worktree: OptionalString, - page: OptionalString, - profileId: OptionalString, - waitForRegistration: z.boolean().optional(), - activate: z.boolean().optional(), - // Why: `activate` says the caller wants the new tab selected; `navigation` says on whose screens. - // Absent, a paired caller means 'caller' — one device's create must not steer every other UI. - navigation: z.enum(RUNTIME_NAVIGATION_TARGETS).optional(), - targetGroupId: OptionalString, - placement: BrowserPageCreationPlacement.optional() -}) - -export const BrowserOpenUrlParams = z.object({ - url: z.url(), - worktree: z.string().min(1) -}) +export { + BrowserOpenUrlParams, + BrowserTabCreateParams +} from '../../../../shared/rpc-contract/browser-tab-create-params' diff --git a/src/main/runtime/rpc/methods/browser-text-rpc-methods.ts b/src/main/runtime/rpc/methods/browser-text-rpc-methods.ts index 813dbe9d2e2..18fd19a0e6a 100644 --- a/src/main/runtime/rpc/methods/browser-text-rpc-methods.ts +++ b/src/main/runtime/rpc/methods/browser-text-rpc-methods.ts @@ -1,8 +1,8 @@ -import { defineMethod, type RpcMethod } from '../core' +import { defineMethod } from '../core' import { assertRpcClipboardTextWriteWithinLimit } from '../rpc-clipboard-text-validation' import { Fill, KeyboardInsert, Type } from './browser-schemas' -export const BROWSER_TEXT_METHODS: RpcMethod[] = [ +export const BROWSER_TEXT_METHODS = [ defineMethod({ name: 'browser.fill', params: Fill, diff --git a/src/main/runtime/rpc/methods/client-events.test.ts b/src/main/runtime/rpc/methods/client-events.test.ts index bf5026c819e..cae682ea4b4 100644 --- a/src/main/runtime/rpc/methods/client-events.test.ts +++ b/src/main/runtime/rpc/methods/client-events.test.ts @@ -1,11 +1,16 @@ import { describe, expect, it, vi } from 'vitest' import type { RuntimeClientEvent } from '../../../../shared/runtime-client-events' import type { OrcaRuntimeService } from '../../orca-runtime' -import { isStreamingMethod, type RpcContext, type RpcStreamingMethod } from '../core' +import { + eraseRpcMethods, + isStreamingMethod, + type RpcContext, + type RpcStreamingMethod +} from '../core' // Why: importing client-events directly trips its module-init cycle through ipc/ssh; the index resolves it. import { ALL_RPC_METHODS } from './index' -const subscribeMethod = ALL_RPC_METHODS.find( +const subscribeMethod = eraseRpcMethods(ALL_RPC_METHODS).find( (method) => method.name === 'runtime.clientEvents.subscribe' && isStreamingMethod(method) ) as RpcStreamingMethod diff --git a/src/main/runtime/rpc/methods/client-events.ts b/src/main/runtime/rpc/methods/client-events.ts index 0c3a079262f..e7506ad2f59 100644 --- a/src/main/runtime/rpc/methods/client-events.ts +++ b/src/main/runtime/rpc/methods/client-events.ts @@ -1,18 +1,11 @@ -import { z } from 'zod' import { getRegisteredSshState, listRegisteredSshTargets } from '../../../ssh/ssh-target-registry' import { getPublicSshState } from '../../public-ssh-state' -import { defineMethod, defineStreamingMethod, type RpcAnyMethod } from '../core' +import { defineMethod, defineStreamingMethod } from '../core' +import { ClientEventsUnsubscribeParams } from '../../../../shared/rpc-contract/client-events-params' let clientEventSubscriptionSeq = 0 -const ClientEventsUnsubscribeParams = z.object({ - subscriptionId: z - .unknown() - .transform((value) => (typeof value === 'string' && value.length > 0 ? value : '')) - .pipe(z.string().min(1, 'Missing subscriptionId')) -}) - -export const CLIENT_EVENT_METHODS: readonly RpcAnyMethod[] = [ +export const CLIENT_EVENT_METHODS = [ defineStreamingMethod({ name: 'runtime.clientEvents.subscribe', params: null, diff --git a/src/main/runtime/rpc/methods/client-settings-schemas.ts b/src/main/runtime/rpc/methods/client-settings-schemas.ts index e389ed9d12b..c8467636d9a 100644 --- a/src/main/runtime/rpc/methods/client-settings-schemas.ts +++ b/src/main/runtime/rpc/methods/client-settings-schemas.ts @@ -1,122 +1,5 @@ -import { z } from 'zod' -import { normalizePRBotAuthorOverrides } from '../../../../shared/pr-bot-author-overrides' -import { isTaskProvider } from '../../../../shared/task-providers' -import { isTuiAgent } from '../../../../shared/tui-agent-config' -import { - normalizeTuiAgentArgsRecord, - normalizeTuiAgentEnvRecord -} from '../../../../shared/tui-agent-launch-defaults' -import { normalizeDisabledTuiAgents } from '../../../../shared/tui-agent-selection' -import { WorktreeVisibilityDefaultsUpdate } from './worktree-visibility-defaults-schema' -import type { TaskProvider } from '../../../../shared/task-providers' - -const TaskProviderParam = z.custom(isTaskProvider, { - message: 'Unknown task provider' -}) - -export const PRBotAuthorOverrideUpdate = z - .object({ author: z.string(), isBot: z.boolean() }) - .strict() - -const NativeChatSessionOptionPickBase = { - modelId: z.string().trim().min(1).max(512), - adoptModelAsLaunchDefault: z.boolean().optional() -} - -const NativeChatSessionOptionPick = z.union([ - z - .object({ - ...NativeChatSessionOptionPickBase, - optionId: z.enum(['model', 'effort']), - value: z.string().trim().min(1).max(512) - }) - .strict(), - z - .object({ - ...NativeChatSessionOptionPickBase, - optionId: z.enum(['fastMode', 'thinking']), - value: z.boolean() - }) - .strict() -]) - -export const NativeChatSessionOptionsMutation = z.discriminatedUnion('type', [ - z - .object({ - type: z.literal('apply-picks'), - agent: z.enum(['claude', 'codex', 'gemini', 'cursor', 'grok']), - picks: z.array(NativeChatSessionOptionPick).min(1).max(8) - }) - .strict(), - z - .object({ - type: z.literal('clear-model-if-missing'), - agent: z.enum(['claude', 'codex', 'gemini', 'cursor', 'grok']), - availableModelIds: z.array(z.string().trim().min(1).max(512)).min(1).max(256) - }) - .strict() -]) - -const GitHubProjectRef = z - .object({ - owner: z.string(), - ownerType: z.enum(['organization', 'user']), - number: z.number().int(), - host: z.string().optional() - }) - .strict() -const GitHubProjectSettings = z - .object({ - pinned: z.array(GitHubProjectRef), - recent: z.array( - GitHubProjectRef.extend({ - lastOpenedAt: z.string() - }).strict() - ), - lastViewByProject: z.record(z.string(), z.object({ viewId: z.string() }).strict()), - activeProject: GitHubProjectRef.nullable() - }) - .strict() - -export const SettingsUpdate = z - .object({ - worktreeVisibilityDefaults: WorktreeVisibilityDefaultsUpdate.optional(), - defaultTuiAgent: z - .unknown() - .transform((value) => - value === null || value === 'blank' || isTuiAgent(value) ? value : undefined - ) - .optional(), - disabledTuiAgents: z - .unknown() - .transform((value) => normalizeDisabledTuiAgents(value)) - .optional(), - agentDefaultArgs: z - .unknown() - .transform((value) => normalizeTuiAgentArgsRecord(value)) - .optional(), - agentDefaultEnv: z - .unknown() - .transform((value) => normalizeTuiAgentEnvRecord(value)) - .optional(), - defaultTaskSource: TaskProviderParam.optional(), - visibleTaskProviders: z.array(TaskProviderParam).optional(), - defaultTaskViewPreset: z - .enum(['issues', 'my-issues', 'prs', 'my-prs', 'review', 'all']) - .optional(), - experimentalNewWorktreeCardStyle: z.boolean().optional(), - agentStatusHooksEnabled: z.boolean().optional(), - defaultRepoSelection: z.array(z.string()).nullable().optional(), - defaultLinearTeamSelection: z.array(z.string()).nullable().optional(), - compactWorktreeCards: z.boolean().optional(), - minimaxGroupId: z.string().optional(), - minimaxUsageModels: z.string().optional(), - minimaxEndpoint: z.enum(['overseas', 'cn']).optional(), - githubProjects: GitHubProjectSettings.optional(), - prBotAuthorOverrides: z - .unknown() - .transform((value) => normalizePRBotAuthorOverrides(value)) - .optional() - }) - .strict() - .default({}) +export { + NativeChatSessionOptionsMutation, + PRBotAuthorOverrideUpdate, + SettingsUpdate +} from '../../../../shared/rpc-contract/client-settings-params' diff --git a/src/main/runtime/rpc/methods/client-ui-schemas.ts b/src/main/runtime/rpc/methods/client-ui-schemas.ts index 943d0081fdf..f11bd7ca49c 100644 --- a/src/main/runtime/rpc/methods/client-ui-schemas.ts +++ b/src/main/runtime/rpc/methods/client-ui-schemas.ts @@ -1,244 +1,8 @@ -import { z } from 'zod' -import { - isFeatureInteractionId, - type FeatureInteractionId -} from '../../../../shared/feature-interactions' -import { - ACTIVITY_GROUP_BY_VALUES, - THREAD_READ_FILTER_VALUES -} from '../../../../shared/agents-view-thread-filters' -import { isFeatureTipId } from '../../../../shared/feature-tips' -import { isReleaseChannel, type ReleaseChannel } from '../../../../shared/release-channel' -import { - normalizeWorktreeCardProperties, - WORKTREE_CARD_PROPERTIES -} from '../../../../shared/worktree/card-properties' -import { isPluginPanelTabKey } from '../../../../shared/plugins/plugin-manifest' -import { ClientUiWorkspaceFilterFields } from './client-ui-workspace-filter-fields' -import { TaskResumeState } from './task-resume-state-schema' -import { WorkspaceCleanup } from './workspace-cleanup-ui-schema' -import { omitUndefinedValues, tolerateUnknownValues } from './ui-update-value-tolerance' - -const NullableString = z.string().nullable() -const StringArray = z.array(z.string()) -const FeatureTipIds = z.array(z.custom(isFeatureTipId, { message: 'Unknown feature tip id' })) -const UnknownRecord = z.record(z.string(), z.unknown()) -const UnknownRecordArray = z.array(UnknownRecord) -type StaticRightSidebarTab = (typeof STATIC_RIGHT_SIDEBAR_TABS)[number] -// Derived from the shared union so a new card property cannot drift out of the -// client schema — it previously omitted 'cli' and rejected the whole payload. -const WorktreeCardPropertyParam = z.enum(WORKTREE_CARD_PROPERTIES) -const WorktreeCardProperties = z - .array(WorktreeCardPropertyParam) - .transform((value) => normalizeWorktreeCardProperties(value)) -const STATIC_RIGHT_SIDEBAR_TABS = [ - 'explorer', - 'search', - 'vault', - 'workspaces', - 'pr-checks', - 'source-control', - 'checks', - 'ports' -] as const -// Plugin panels are open-ended `plugin:./` keys, so the -// schema validates their shape rather than enumerating them. -const RightSidebarTabParam = z.custom( - (value) => - typeof value === 'string' && - (STATIC_RIGHT_SIDEBAR_TABS.includes(value as StaticRightSidebarTab) || - isPluginPanelTabKey(value)), - { message: 'Unknown right sidebar tab' } -) -const AgentActivityDisplayMode = z.enum(['compact', 'full']) -const StatusBarItem = z.enum([ - 'claude', - 'codex', - 'gemini', - 'antigravity', - 'opencode-go', - 'kimi', - 'minimax', - 'grok', - 'ssh', - 'resource-usage', - 'ports' -]) -const WorkspaceStatusDefinition = z.object({ - id: z.string(), - label: z.string(), - color: z.string().optional(), - icon: z.string().optional() -}) -const FeatureInteractionRecord = z - .object({ - firstInteractedAt: z.number().finite().nonnegative(), - interactionCount: z.number().int().positive().optional() - }) - .strict() -const FeatureInteractions = z - .record(z.string(), FeatureInteractionRecord) - .superRefine((value, ctx) => { - for (const id of Object.keys(value)) { - if (!isFeatureInteractionId(id)) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: `Unknown feature interaction id: ${id}`, - path: [id] - }) - } - } - }) -export const FeatureInteractionIdParam = z.custom(isFeatureInteractionId, { - message: 'Unknown feature interaction id' -}) -const TopLevelViewSchema = z.enum([ - 'terminal', - 'settings', - 'tasks', - 'activity', - 'automations', - 'space', - 'skills', - 'artifacts', - 'mobile' -]) -const UiUpdateFields = z - .object({ - lastActiveRepoId: NullableString.optional(), - lastActiveWorktreeId: NullableString.optional(), - // Why: sync hydration ignores this persisted startup view, so paired windows stay put. - activeView: TopLevelViewSchema.optional(), - sidebarWidth: z.number().finite().optional(), - rightSidebarOpen: z.boolean().optional(), - rightSidebarTab: RightSidebarTabParam.optional(), - rightSidebarExplorerView: z.enum(['files', 'search']).optional(), - rightSidebarWidth: z.number().finite().optional(), - markdownTocPanelWidth: z.number().finite().optional(), - combinedDiffFileTreeWidth: z.number().finite().optional(), - groupBy: z.enum(['none', 'workspace-status', 'repo', 'pr-status']).optional(), - showWorkspaceLineage: z.boolean().optional(), - sortBy: z.enum(['name', 'smart', 'recent', 'repo', 'manual']).optional(), - projectOrderBy: z.enum(['manual', 'recent']).optional(), - showActiveOnly: z.boolean().optional(), - hideSleepingWorkspaces: z.boolean().optional(), - showSleepingWorkspaces: z.boolean().optional(), - showInactiveWorkspaces: z.boolean().optional(), - workspaceHostScope: z.string().optional(), - visibleWorkspaceHostIds: z.array(z.string()).nullable().optional(), - agentsVisibleHostIds: z.array(z.string()).nullable().optional(), - agentsFilterRepoIds: StringArray.optional(), - agentsShowChildAgents: z.boolean().optional(), - agentsCompactMode: z.boolean().optional(), - agentsShowSearch: z.boolean().optional(), - agentsReadFilter: z.enum(THREAD_READ_FILTER_VALUES).optional(), - agentsGroupBy: z.enum(ACTIVITY_GROUP_BY_VALUES).optional(), - workspaceHostOrder: z.array(z.string()).optional(), - automationHostFilter: z - .union([ - z.object({ kind: z.literal('all') }).strict(), - z.object({ kind: z.literal('host'), hostKey: z.string().min(1) }).strict() - ]) - .optional(), - manualRepoOrder: z - .array(z.object({ hostId: z.string(), repoId: z.string() }).strict()) - .optional(), - ...ClientUiWorkspaceFilterFields, - // Why: rides App.tsx's debounced writer, so omitting it rejected that entire - // payload (sidebar widths, filters, agent acks) for every paired client. - showDotfilesByWorktree: z.record(z.string(), z.boolean()).optional(), - collapsedGroups: StringArray.optional(), - uiZoomLevel: z.number().finite().optional(), - editorFontZoomLevel: z.number().finite().optional(), - worktreeCardProperties: WorktreeCardProperties.optional(), - _worktreeCardModeDefaulted: z.boolean().optional(), - agentActivityDisplayMode: AgentActivityDisplayMode.optional(), - workspaceStatuses: z.array(WorkspaceStatusDefinition).optional(), - workspaceBoardOpacity: z.number().finite().optional(), - workspaceBoardColumnWidth: z.number().finite().optional(), - syncTaskStatusFromWorkspaceBoard: z.boolean().optional(), - _workspaceStatusesDefaultOrderMigrated: z.boolean().optional(), - _workspaceStatusesReorderedDefaultRepaired: z.boolean().optional(), - _workspaceStatusesDefaultWorkflowMigrated: z.boolean().optional(), - _workspaceStatusesDefaultVisualsMigrated: z.boolean().optional(), - statusBarItems: z.array(StatusBarItem).optional(), - _portsStatusBarDefaultAdded: z.boolean().optional(), - _kimiStatusBarDefaultAdded: z.boolean().optional(), - _minimaxStatusBarDefaultAdded: z.boolean().optional(), - _antigravityStatusBarDefaultAdded: z.boolean().optional(), - _grokStatusBarDefaultAdded: z.boolean().optional(), - statusBarVisible: z.boolean().optional(), - usagePercentageDisplay: z.enum(['used', 'remaining']).optional(), - statusBarUsageMode: z.enum(['verbose', 'compact']).optional(), - dismissedUpdateVersion: NullableString.optional(), - lastUpdateCheckAt: z.number().finite().nullable().optional(), - pendingUpdateNudgeId: NullableString.optional(), - dismissedUpdateNudgeId: NullableString.optional(), - // Why the predicate rather than an inline z.enum: an enum here is a copy of - // RELEASE_CHANNELS, and a copy that drifts silently rejects the new - // channel's override on its way here — the picker moves, nothing installs. - releaseChannelOverride: z.custom(isReleaseChannel).nullable().optional(), - notificationPermissionRequested: z.boolean().optional(), - updateReassuranceSeen: z.boolean().optional(), - osc52ClipboardDefaultOnNoticePending: z.boolean().optional(), - acknowledgedAgentsByPaneKey: z.record(z.string(), z.number().finite()).optional(), - activityClearedAtByPaneKey: z.record(z.string(), z.number().finite()).optional(), - manuallyUnreadTurnsByPaneKey: z.record(z.string(), z.number().finite()).optional(), - browserDefaultUrl: NullableString.optional(), - browserDefaultSearchEngine: z - .enum(['google', 'duckduckgo', 'bing', 'kagi']) - .nullable() - .optional(), - browserDefaultZoomLevel: z.number().finite().optional(), - browserKagiSessionLink: NullableString.optional(), - windowBounds: z - .object({ - x: z.number().finite(), - y: z.number().finite(), - width: z.number().finite(), - height: z.number().finite() - }) - .nullable() - .optional(), - windowMaximized: z.boolean().optional(), - _sortBySmartMigrated: z.boolean().optional(), - _inlineAgentsDefaultedForExperiment: z.boolean().optional(), - _inlineAgentsDefaultedForAllUsers: z.boolean().optional(), - trustedOrcaHooks: z.record(z.string(), z.unknown()).optional(), - setupScriptPromptDismissedRepoIds: StringArray.optional(), - // Why: one-shot dismissals the renderer writes through ui.set; each was a - // whole-payload rejection for paired clients while unlisted. - setupGuideSidebarDismissed: z.boolean().optional(), - setupGuideBrowserMilestoneMigrated: z.boolean().optional(), - setupGuideBrowserMilestoneLegacyComplete: z.boolean().optional(), - browserImportHintHidden: z.boolean().optional(), - mobileEmulatorTabIntroDismissed: z.boolean().optional(), - mobileEmulatorAgentSetupDismissed: z.boolean().optional(), - projectOrderManualDefaultNoticeDismissed: z.boolean().optional(), - usagePercentageDisplayChangeNoticeDismissed: z.boolean().optional(), - usageEmptyStateDismissed: z.boolean().optional(), - petVisible: z.boolean().optional(), - petId: z.string().optional(), - customPets: UnknownRecordArray.optional(), - petSize: z.number().finite().optional(), - sidekickVisible: z.boolean().optional(), - sidekickId: z.string().optional(), - customSidekicks: UnknownRecordArray.optional(), - sidekickSize: z.number().finite().optional(), - taskResumeState: TaskResumeState.optional(), - workspaceCleanup: WorkspaceCleanup.optional(), - featureTipsSeenIds: FeatureTipIds.optional(), - featureInteractions: FeatureInteractions.optional(), - contextualToursSeenIds: StringArray.optional(), - contextualToursAutoEligible: z.boolean().optional() - }) - .strict() - -export const UiUpdate = z - .object(tolerateUnknownValues(UiUpdateFields.shape)) - .strict() - .default({}) - .transform(omitUndefinedValues) +import type { UiUpdateFields } from '../../../../shared/rpc-contract/client-ui-params' +export { + FeatureInteractionIdParam, + UiUpdate +} from '../../../../shared/rpc-contract/client-ui-params' // The key/value parity assertions over this live in ui-state-schema-parity-checks.ts. export type UiUpdateFieldsSchema = typeof UiUpdateFields diff --git a/src/main/runtime/rpc/methods/client-ui-workspace-filter-fields.ts b/src/main/runtime/rpc/methods/client-ui-workspace-filter-fields.ts index d0239b03ec3..be6bc445f6e 100644 --- a/src/main/runtime/rpc/methods/client-ui-workspace-filter-fields.ts +++ b/src/main/runtime/rpc/methods/client-ui-workspace-filter-fields.ts @@ -1,11 +1 @@ -import { z } from 'zod' - -export const ClientUiWorkspaceFilterFields = { - hideDefaultBranchWorkspace: z.boolean().optional(), - hideAutomationGeneratedWorkspaces: z.boolean().optional(), - hideCliCreatedWorkspaces: z.boolean().optional(), - hideDetachedHeadWorkspaces: z.boolean().optional(), - hideWorkspacesFromOtherDevices: z.boolean().optional(), - alwaysShowDefaultBranchWorkspace: z.boolean().optional(), - filterRepoIds: z.array(z.string()).optional() -} +export { ClientUiWorkspaceFilterFields } from '../../../../shared/rpc-contract/client-ui-workspace-filter-fields-params' diff --git a/src/main/runtime/rpc/methods/client-ui.test.ts b/src/main/runtime/rpc/methods/client-ui.test.ts index 39048611155..3a26b1c615d 100644 --- a/src/main/runtime/rpc/methods/client-ui.test.ts +++ b/src/main/runtime/rpc/methods/client-ui.test.ts @@ -607,6 +607,8 @@ describe('client UI RPC methods', () => { ], ['taskResumeState.jiraPreset', { taskResumeState: { jiraPreset: 'assigned' } }], ['taskResumeState.jiraQuery', { taskResumeState: { jiraQuery: 'ENG' } }], + ['dismissedUnexpectedSignoutVersion', { dismissedUnexpectedSignoutVersion: '1.2.3' }], + ['dismissedUnexpectedSignoutVersion null', { dismissedUnexpectedSignoutVersion: null }], ['activeView', { activeView: 'tasks' }], ['showDotfilesByWorktree', { showDotfilesByWorktree: { 'repo::/worktree': true } }], ['setupGuideSidebarDismissed', { setupGuideSidebarDismissed: true }], diff --git a/src/main/runtime/rpc/methods/client-ui.ts b/src/main/runtime/rpc/methods/client-ui.ts index ffd964b6be6..6ed36a6fe83 100644 --- a/src/main/runtime/rpc/methods/client-ui.ts +++ b/src/main/runtime/rpc/methods/client-ui.ts @@ -1,6 +1,6 @@ import { omitPairingLocalUiFields } from '../../../../shared/pairing-local-ui-fields' import type { PersistedUIState } from '../../../../shared/persisted-ui-state-types' -import { defineMethod, type RpcMethod } from '../core' +import { defineMethod } from '../core' import { NativeChatSessionOptionsMutation, PRBotAuthorOverrideUpdate, @@ -12,7 +12,7 @@ import { FeatureInteractionIdParam, UiUpdate } from './client-ui-schemas' import { TerminalQuickCommandsUpdate } from './terminal-quick-command-rpc-schema' -export const CLIENT_UI_METHODS: RpcMethod[] = [ +export const CLIENT_UI_METHODS = [ defineMethod({ name: 'settings.get', params: null, diff --git a/src/main/runtime/rpc/methods/clipboard.ts b/src/main/runtime/rpc/methods/clipboard.ts index e6b487d7761..3ec78265dc6 100644 --- a/src/main/runtime/rpc/methods/clipboard.ts +++ b/src/main/runtime/rpc/methods/clipboard.ts @@ -1,18 +1,18 @@ -import { z } from 'zod' -import { defineMethod, type RpcContext, type RpcMethod } from '../core' +import { defineMethod, type RpcContext } from '../core' import { saveClipboardImageBufferAsTempFile } from '../../../window/clipboard-image-temp-file' import { randomUUID } from 'node:crypto' -import { - CLIPBOARD_IMAGE_MAX_BASE64_CHARS, - CLIPBOARD_IMAGE_TOO_LARGE_ERROR -} from '../../../../shared/clipboard-image' import { recordMobileClipboardImagePath } from '../mobile-clipboard-image-provenance' - -const MAX_CLIPBOARD_IMAGE_BASE64_CHARS = CLIPBOARD_IMAGE_MAX_BASE64_CHARS -export const CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS = 512 * 1024 +import { + AbortImageUpload, + AppendImageUploadChunk, + CommitImageUpload, + SaveImageAsTempFile, + StartImageUpload, + isValidBase64 +} from '../../../../shared/rpc-contract/clipboard-params' +export { CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS } from '../../../../shared/rpc-contract/clipboard-params' export const CLIPBOARD_IMAGE_UPLOAD_MAX_CONCURRENT = 8 const CLIPBOARD_IMAGE_UPLOAD_TTL_MS = 5 * 60 * 1000 -const BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/ type ClipboardImageUpload = { expectedBase64Length: number @@ -26,10 +26,6 @@ type ClipboardImageUpload = { const clipboardImageUploads = new Map() -function isValidBase64(value: string): boolean { - return value.length % 4 !== 1 && BASE64_PATTERN.test(value) -} - function pruneExpiredUploads(now = Date.now()): void { for (const [uploadId, upload] of clipboardImageUploads) { if (upload.expiresAt <= now) { @@ -99,59 +95,7 @@ function assertValidBase64Content(value: string): void { } } -function clipboardImageBase64Payload(maxChars: number, tooLargeMessage: string) { - return z.unknown().transform((value, ctx): string => { - if (typeof value !== 'string') { - ctx.addIssue({ code: 'custom', message: 'Missing image content' }) - return z.NEVER - } - if (value.length > maxChars) { - ctx.addIssue({ code: 'custom', message: tooLargeMessage }) - return z.NEVER - } - if (!isValidBase64(value)) { - ctx.addIssue({ code: 'custom', message: 'Clipboard image content must be base64' }) - return z.NEVER - } - return value - }) -} - -const SaveImageAsTempFile = z.object({ - contentBase64: clipboardImageBase64Payload( - MAX_CLIPBOARD_IMAGE_BASE64_CHARS, - CLIPBOARD_IMAGE_TOO_LARGE_ERROR - ), - connectionId: z.string().min(1).nullable().optional() -}) - -const StartImageUpload = z.object({ - expectedBase64Length: z - .number() - .int() - .nonnegative() - .max(MAX_CLIPBOARD_IMAGE_BASE64_CHARS, CLIPBOARD_IMAGE_TOO_LARGE_ERROR), - connectionId: z.string().min(1).nullable().optional() -}) - -const AppendImageUploadChunk = z.object({ - uploadId: z.string().min(1), - offset: z.number().int().nonnegative(), - contentBase64: clipboardImageBase64Payload( - CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS, - 'Clipboard image chunk is too large' - ) -}) - -const CommitImageUpload = z.object({ - uploadId: z.string().min(1) -}) - -const AbortImageUpload = z.object({ - uploadId: z.string().min(1) -}) - -export const CLIPBOARD_METHODS: RpcMethod[] = [ +export const CLIPBOARD_METHODS = [ defineMethod({ name: 'clipboard.saveImageAsTempFile', params: SaveImageAsTempFile, diff --git a/src/main/runtime/rpc/methods/computer-actions.test.ts b/src/main/runtime/rpc/methods/computer-actions.test.ts index 96dc374e459..fa2b7d83ee1 100644 --- a/src/main/runtime/rpc/methods/computer-actions.test.ts +++ b/src/main/runtime/rpc/methods/computer-actions.test.ts @@ -27,6 +27,7 @@ vi.mock('../../../computer/macos-computer-use-permissions', () => ({ })) import { COMPUTER_METHODS, resetComputerSessionsForTest } from './computer' +import { eraseRpcMethods } from '../core' describe('computer action RPC methods', () => { beforeEach(() => { @@ -269,7 +270,7 @@ describe('computer action RPC methods', () => { }) function findMethod(name: string) { - const method = COMPUTER_METHODS.find((candidate) => candidate.name === name) + const method = eraseRpcMethods(COMPUTER_METHODS).find((candidate) => candidate.name === name) if (!method) { throw new Error(`missing method ${name}`) } diff --git a/src/main/runtime/rpc/methods/computer-schemas.ts b/src/main/runtime/rpc/methods/computer-schemas.ts index e3ef7ca88f3..f949fa0459c 100644 --- a/src/main/runtime/rpc/methods/computer-schemas.ts +++ b/src/main/runtime/rpc/methods/computer-schemas.ts @@ -1,226 +1,15 @@ -import { z } from 'zod' -import { - computerUseClickModifiersValidationMessage, - computerUseHotkeyValidationMessage, - computerUsePressKeyValidationMessage -} from '../../../../shared/computer-use-key-spec' -import { - OptionalBoolean, - OptionalFiniteNumber, - OptionalString, - requiredString, - requiredStringAllowingEmpty -} from '../schemas' - -const OptionalNonNegativeInt = z.number().int().nonnegative().optional() -const OptionalPositiveInt = z.number().int().positive().optional() - -const ComputerTarget = z.object({ - app: requiredString('Missing app'), - session: OptionalString, - worktree: OptionalString -}) - -const ComputerObserveTargetBase = ComputerTarget.extend({ - noScreenshot: OptionalBoolean, - restoreWindow: OptionalBoolean, - windowId: OptionalNonNegativeInt, - windowIndex: OptionalNonNegativeInt -}) - -function validateWindowTarget( - value: { windowId?: number; windowIndex?: number }, - ctx: z.RefinementCtx -): void { - if (value.windowId !== undefined && value.windowIndex !== undefined) { - ctx.addIssue({ - code: 'custom', - message: 'Window targeting accepts either --window-id or --window-index, not both' - }) - } -} - -function validateComputerTarget( - value: { session?: string; worktree?: string; windowId?: number; windowIndex?: number }, - ctx: z.RefinementCtx -): void { - if (value.session !== undefined && value.worktree !== undefined) { - ctx.addIssue({ - code: 'custom', - message: 'Computer-use targeting accepts either session or worktree, not both' - }) - } - validateWindowTarget(value, ctx) -} - -export const ComputerObserveTarget = ComputerObserveTargetBase.superRefine(validateComputerTarget) - -export const ListApps = z.object({}).strict() - -export const ListWindows = z - .object({ - app: requiredString('Missing app') - }) - .strict() - -export const Click = ComputerObserveTargetBase.extend({ - elementIndex: OptionalNonNegativeInt, - x: OptionalFiniteNumber, - y: OptionalFiniteNumber, - clickCount: OptionalPositiveInt, - mouseButton: z.enum(['left', 'right', 'middle']).optional(), - modifiers: z.string().optional() -}).superRefine((value, ctx) => { - validateComputerTarget(value, ctx) - const hasElement = value.elementIndex !== undefined - const hasX = value.x !== undefined - const hasY = value.y !== undefined - if (!hasElement && !(hasX && hasY)) { - ctx.addIssue({ - code: 'custom', - message: 'Click requires --element-index or both --x and --y' - }) - } - if (hasX !== hasY) { - ctx.addIssue({ - code: 'custom', - message: 'Click coordinates require both --x and --y' - }) - } - if (hasElement && (hasX || hasY)) { - ctx.addIssue({ - code: 'custom', - message: 'Click accepts either --element-index or coordinate flags, not both' - }) - } - if (value.modifiers !== undefined) { - const message = computerUseClickModifiersValidationMessage(value.modifiers) - if (message) { - ctx.addIssue({ code: 'custom', message }) - } - } -}) - -export const PerformSecondaryAction = ComputerObserveTargetBase.extend({ - elementIndex: OptionalNonNegativeInt, - action: requiredString('Missing action') -}).superRefine((value, ctx) => { - validateComputerTarget(value, ctx) - if (value.elementIndex === undefined) { - ctx.addIssue({ code: 'custom', message: 'Missing element index' }) - } -}) - -export const Scroll = ComputerObserveTargetBase.extend({ - elementIndex: OptionalNonNegativeInt, - x: OptionalFiniteNumber, - y: OptionalFiniteNumber, - direction: z.enum(['up', 'down', 'left', 'right']), - pages: z.number().positive().optional() -}).superRefine((value, ctx) => { - validateComputerTarget(value, ctx) - const hasElement = value.elementIndex !== undefined - const hasX = value.x !== undefined - const hasY = value.y !== undefined - if (!hasElement && !(hasX && hasY)) { - ctx.addIssue({ - code: 'custom', - message: 'Scroll requires --element-index or both --x and --y' - }) - } - if (hasX !== hasY) { - ctx.addIssue({ - code: 'custom', - message: 'Scroll coordinates require both --x and --y' - }) - } - if (hasElement && (hasX || hasY)) { - ctx.addIssue({ - code: 'custom', - message: 'Scroll accepts either --element-index or coordinate flags, not both' - }) - } -}) - -export const Drag = ComputerObserveTargetBase.extend({ - fromElementIndex: OptionalNonNegativeInt, - toElementIndex: OptionalNonNegativeInt, - fromX: OptionalFiniteNumber, - fromY: OptionalFiniteNumber, - toX: OptionalFiniteNumber, - toY: OptionalFiniteNumber -}).superRefine((value, ctx) => { - validateComputerTarget(value, ctx) - const hasElementPair = value.fromElementIndex !== undefined && value.toElementIndex !== undefined - const hasPartialElementPair = - value.fromElementIndex !== undefined || value.toElementIndex !== undefined - const coordinateKeys = [value.fromX, value.fromY, value.toX, value.toY] - const hasCoordinatePair = coordinateKeys.every((coordinate) => coordinate !== undefined) - const hasPartialCoordinatePair = coordinateKeys.some((coordinate) => coordinate !== undefined) - if (hasElementPair && hasCoordinatePair) { - ctx.addIssue({ - code: 'custom', - message: 'Drag accepts either element indexes or coordinate flags, not both' - }) - } - if (!hasElementPair && !hasCoordinatePair) { - ctx.addIssue({ - code: 'custom', - message: 'Drag requires --from-element-index and --to-element-index, or all coordinate flags' - }) - } - if (hasPartialElementPair && !hasElementPair) { - ctx.addIssue({ - code: 'custom', - message: 'Drag element targeting requires both --from-element-index and --to-element-index' - }) - } - if (hasPartialCoordinatePair && !hasCoordinatePair) { - ctx.addIssue({ - code: 'custom', - message: 'Drag coordinates require --from-x, --from-y, --to-x, and --to-y' - }) - } -}) - -export const TypeText = ComputerObserveTargetBase.extend({ - text: requiredString('Missing text') -}).superRefine(validateComputerTarget) - -export const PressKey = ComputerObserveTargetBase.extend({ - key: requiredString('Missing key') -}).superRefine((value, ctx) => { - validateComputerTarget(value, ctx) - const message = computerUsePressKeyValidationMessage(value.key) - if (message) { - ctx.addIssue({ code: 'custom', message }) - } -}) - -export const Hotkey = ComputerObserveTargetBase.extend({ - key: requiredString('Missing key') -}).superRefine((value, ctx) => { - validateComputerTarget(value, ctx) - const message = computerUseHotkeyValidationMessage(value.key) - if (message) { - ctx.addIssue({ code: 'custom', message }) - } -}) - -export const ComputerPermissions = z.object({ - id: z.enum(['accessibility', 'screenshots']).optional() -}) - -export const PasteText = ComputerObserveTargetBase.extend({ - text: requiredString('Missing text') -}).superRefine(validateComputerTarget) - -export const SetValue = ComputerObserveTargetBase.extend({ - elementIndex: OptionalNonNegativeInt, - value: requiredStringAllowingEmpty('Missing value') -}).superRefine((value, ctx) => { - validateComputerTarget(value, ctx) - if (value.elementIndex === undefined) { - ctx.addIssue({ code: 'custom', message: 'Missing element index' }) - } -}) +export { + Click, + ComputerObserveTarget, + ComputerPermissions, + Drag, + Hotkey, + ListApps, + ListWindows, + PasteText, + PerformSecondaryAction, + PressKey, + Scroll, + SetValue, + TypeText +} from '../../../../shared/rpc-contract/computer-schemas-params' diff --git a/src/main/runtime/rpc/methods/computer.test.ts b/src/main/runtime/rpc/methods/computer.test.ts index 6a01fac7d0a..073a1c0a363 100644 --- a/src/main/runtime/rpc/methods/computer.test.ts +++ b/src/main/runtime/rpc/methods/computer.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import { buildRegistry } from '../core' +import { eraseRpcMethods, buildRegistry } from '../core' import { CLIPBOARD_TEXT_WRITE_MAX_BYTES } from '../../../../shared/clipboard-text' const computerMocks = vi.hoisted(() => ({ @@ -249,7 +249,7 @@ describe('computer RPC methods', () => { }) function findMethod(name: string) { - const method = COMPUTER_METHODS.find((candidate) => candidate.name === name) + const method = eraseRpcMethods(COMPUTER_METHODS).find((candidate) => candidate.name === name) if (!method) { throw new Error(`missing method ${name}`) } diff --git a/src/main/runtime/rpc/methods/computer.ts b/src/main/runtime/rpc/methods/computer.ts index 1f928b97afe..e2708667633 100644 --- a/src/main/runtime/rpc/methods/computer.ts +++ b/src/main/runtime/rpc/methods/computer.ts @@ -1,4 +1,3 @@ -import { z } from 'zod' import { callComputerSidecarAction, callComputerSidecarCapabilities, @@ -7,7 +6,7 @@ import { callComputerSidecarSnapshot, resetComputerSidecarForTest } from '../../../computer/sidecar-client' -import { defineMethod, type RpcMethod } from '../core' +import { defineMethod } from '../core' import { Click, ComputerObserveTarget, @@ -23,15 +22,19 @@ import { SetValue, TypeText } from './computer-schemas' +import { + ComputerCapabilitiesParams, + ComputerPermissionsStatusParams +} from '../../../../shared/rpc-contract/computer-params' export function resetComputerSessionsForTest(): void { resetComputerSidecarForTest() } -export const COMPUTER_METHODS: RpcMethod[] = [ +export const COMPUTER_METHODS = [ defineMethod({ name: 'computer.capabilities', - params: z.object({}), + params: ComputerCapabilitiesParams, handler: async () => { return await callComputerSidecarCapabilities() } @@ -54,7 +57,7 @@ export const COMPUTER_METHODS: RpcMethod[] = [ }), defineMethod({ name: 'computer.permissionsStatus', - params: z.object({}), + params: ComputerPermissionsStatusParams, handler: async () => { const { getComputerUsePermissionStatus } = await import('../../../computer/macos-computer-use-permissions') diff --git a/src/main/runtime/rpc/methods/diagnostics.ts b/src/main/runtime/rpc/methods/diagnostics.ts index 4d158d98f63..953eccd5d51 100644 --- a/src/main/runtime/rpc/methods/diagnostics.ts +++ b/src/main/runtime/rpc/methods/diagnostics.ts @@ -1,6 +1,6 @@ -import { defineMethod, type RpcMethod } from '../core' +import { defineMethod } from '../core' -export const DIAGNOSTICS_METHODS: RpcMethod[] = [ +export const DIAGNOSTICS_METHODS = [ defineMethod({ name: 'diagnostics.memory', params: null, diff --git a/src/main/runtime/rpc/methods/emulator.ts b/src/main/runtime/rpc/methods/emulator.ts index 50354f790e4..b472e539603 100644 --- a/src/main/runtime/rpc/methods/emulator.ts +++ b/src/main/runtime/rpc/methods/emulator.ts @@ -1,66 +1,26 @@ -import { defineMethod, type RpcMethod } from '../core' +import { defineMethod } from '../core' import path from 'node:path' import { z } from 'zod' - -// Minimal schemas for emulator commands (loose for initial testing; can be tightened like browser-schemas). -const WorktreeParam = z.object({ worktree: z.string().optional() }).partial() - -const TapParams = z.object({ - x: z.number().min(0).max(1), - y: z.number().min(0).max(1), - device: z.string().optional(), - emulator: z.string().optional(), - worktree: z.string().optional() -}) - -const GesturePoint = z.object({ - edge: z.number().int().min(0).max(4).optional(), - type: z.enum(['begin', 'move', 'end']), - x: z.number().min(0).max(1), - y: z.number().min(0).max(1) -}) - -const GestureParams = z.object({ - points: z.array(GesturePoint).min(2).max(64), - device: z.string().optional(), - emulator: z.string().optional(), - worktree: z.string().optional() -}) - -const TypeParams = z.object({ - text: z.string(), - device: z.string().optional(), - emulator: z.string().optional(), - worktree: z.string().optional() -}) - -const ButtonParams = z.object({ - name: z.string(), - device: z.string().optional(), - emulator: z.string().optional(), - worktree: z.string().optional() -}) - -const RotateOrientation = z.enum([ - 'portrait', - 'portrait_upside_down', - 'landscape_left', - 'landscape_right' -]) - -const RotateParams = z.object({ - orientation: RotateOrientation, - device: z.string().optional(), - emulator: z.string().optional(), - worktree: z.string().optional() -}) - -const ExecParams = z.object({ - command: z.string(), - device: z.string().optional(), - emulator: z.string().optional(), - worktree: z.string().optional() -}) +import { + AttachParams, + AxParams, + ButtonParams, + EmulatorAvailabilityParams, + EmulatorListDevicesParams, + EmulatorListSimulatorsParams, + EmulatorUnregisterActiveParams, + ExecParams, + GestureParams, + KillParams, + LaunchParams, + ListParams, + LogcatParams, + PermissionsParams, + RotateParams, + ShutdownParams, + TapParams, + TypeParams +} from '../../../../shared/rpc-contract/emulator-params' const InstallParams = z.object({ path: z.string().refine((value) => path.isAbsolute(value), { @@ -72,90 +32,7 @@ const InstallParams = z.object({ worktree: z.string().optional() }) -const LaunchParams = z.object({ - package: z.string(), - activity: z.string().optional(), - device: z.string().optional(), - emulator: z.string().optional(), - worktree: z.string().optional() -}) - -const PermissionsParams = z - .object({ - op: z.enum(['grant', 'revoke', 'reset']), - package: z.string().optional(), - permission: z.string().optional(), - device: z.string().optional(), - emulator: z.string().optional(), - worktree: z.string().optional() - }) - .superRefine((value, ctx) => { - if (value.op === 'reset') { - if (value.package) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: ['package'], - message: 'package is not allowed for reset' - }) - } - if (value.permission) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: ['permission'], - message: 'permission is not allowed for reset' - }) - } - return - } - if (!value.package) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: ['package'], - message: 'package is required for grant/revoke' - }) - } - if (!value.permission) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: ['permission'], - message: 'permission is required for grant/revoke' - }) - } - }) - -const AxParams = z.object({ - device: z.string().optional(), - emulator: z.string().optional(), - worktree: z.string().optional() -}) - -const LogcatParams = z.object({ - lines: z.number().int().positive().optional(), - filters: z.array(z.string()).optional(), - device: z.string().optional(), - emulator: z.string().optional(), - worktree: z.string().optional() -}) - -const AttachParams = z.object({ - device: z.string().optional(), - worktree: z.string().optional(), - focus: z.boolean().optional() -}) - -const KillParams = z.object({ - device: z.string().optional(), - emulator: z.string().optional(), - worktree: z.string().optional() -}) - -const ShutdownParams = KillParams.extend({ - managedOnly: z.boolean().optional() -}) - -const ListParams = WorktreeParam - -export const EMULATOR_METHODS: RpcMethod[] = [ +export const EMULATOR_METHODS = [ defineMethod({ name: 'emulator.list', params: ListParams, @@ -208,17 +85,17 @@ export const EMULATOR_METHODS: RpcMethod[] = [ }), defineMethod({ name: 'emulator.listSimulators', - params: z.object({ worktree: z.string().optional() }).partial(), + params: EmulatorListSimulatorsParams, handler: async (params, { runtime }) => runtime.emulatorListSimulators(params) }), defineMethod({ name: 'emulator.availability', - params: z.object({ worktree: z.string().optional() }).partial(), + params: EmulatorAvailabilityParams, handler: async (params, { runtime }) => runtime.emulatorAvailability(params) }), defineMethod({ name: 'emulator.listDevices', - params: z.object({ worktree: z.string().optional() }).partial(), + params: EmulatorListDevicesParams, handler: async (params, { runtime }) => runtime.emulatorListDevices(params) }), defineMethod({ @@ -248,7 +125,7 @@ export const EMULATOR_METHODS: RpcMethod[] = [ }), defineMethod({ name: 'emulator.unregisterActive', - params: z.object({ worktree: z.string().optional() }).partial(), + params: EmulatorUnregisterActiveParams, handler: async (params, { runtime }) => runtime.emulatorUnregisterActive(params) }) ] diff --git a/src/main/runtime/rpc/methods/files-mutation-methods.ts b/src/main/runtime/rpc/methods/files-mutation-methods.ts index 1add0232055..eb734d5c8d6 100644 --- a/src/main/runtime/rpc/methods/files-mutation-methods.ts +++ b/src/main/runtime/rpc/methods/files-mutation-methods.ts @@ -1,14 +1,14 @@ -import { z } from 'zod' -import { defineMethod, type RpcAnyMethod } from '../core' -import { FileOpen, WorktreeSelector } from './files-target-schemas' - -const RUNTIME_FILE_BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/ - -function isValidRuntimeFileBase64(value: unknown): value is string { - return ( - typeof value === 'string' && value.length % 4 !== 1 && RUNTIME_FILE_BASE64_PATTERN.test(value) - ) -} +import { defineMethod } from '../core' +import { + FileCommitUpload, + FileCopy, + FileDelete, + FileMutationOpen, + FileRename, + FileWrite, + FileWriteBase64, + FileWriteBase64Chunk +} from '../../../../shared/rpc-contract/files-mutation-params' type SshMutationParams = { expectedExecutionHostId?: string @@ -33,81 +33,7 @@ function sshMutationArguments( ] } -const FileMutationOpen = FileOpen.extend({ - expectedExecutionHostId: z.string().min(1).optional(), - expectedSshTargetId: z.string().min(1).optional(), - expectedSshConnectionGeneration: z.number().int().nonnegative().optional() -}) - -// Why: write content must be a real string. Coercing a missing/non-string value -// to '' silently truncated the target file to empty instead of erroring. An -// explicit '' is still accepted (writing an empty file is legitimate). -const FileWrite = FileMutationOpen.extend({ - content: z - .unknown() - .refine((v): v is string => typeof v === 'string', { message: 'Missing file content' }) -}) - -const FileWriteBase64 = FileMutationOpen.extend({ - contentBase64: z - .unknown() - .refine((v): v is string => typeof v === 'string', { message: 'Missing file content' }) - // Why: Buffer.from(..., 'base64') accepts malformed input by dropping - // invalid bytes, which can silently create empty or corrupt uploaded files. - .refine(isValidRuntimeFileBase64, 'File content must be base64') -}) - -const FileWriteBase64Chunk = FileWriteBase64.extend({ - append: z.boolean().optional() -}) - -const FileRename = WorktreeSelector.extend({ - expectedExecutionHostId: z.string().min(1).optional(), - expectedSshTargetId: z.string().min(1).optional(), - expectedSshConnectionGeneration: z.number().int().nonnegative().optional(), - oldRelativePath: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing source path')), - newRelativePath: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing destination path')) -}) - -const FileCopy = WorktreeSelector.extend({ - expectedExecutionHostId: z.string().min(1).optional(), - expectedSshTargetId: z.string().min(1).optional(), - expectedSshConnectionGeneration: z.number().int().nonnegative().optional(), - sourceRelativePath: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing source path')), - destinationRelativePath: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing destination path')) -}) - -const FileCommitUpload = WorktreeSelector.extend({ - expectedExecutionHostId: z.string().min(1).optional(), - expectedSshTargetId: z.string().min(1).optional(), - expectedSshConnectionGeneration: z.number().int().nonnegative().optional(), - tempRelativePath: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing temporary path')), - finalRelativePath: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing final path')) -}) - -const FileDelete = FileMutationOpen.extend({ - recursive: z.boolean().optional() -}) - -export const FILE_MUTATION_METHODS: RpcAnyMethod[] = [ +export const FILE_MUTATION_METHODS = [ defineMethod({ name: 'files.write', params: FileWrite, diff --git a/src/main/runtime/rpc/methods/files-target-schemas.ts b/src/main/runtime/rpc/methods/files-target-schemas.ts index 6c546b3605e..945d3c6aa85 100644 --- a/src/main/runtime/rpc/methods/files-target-schemas.ts +++ b/src/main/runtime/rpc/methods/files-target-schemas.ts @@ -1,15 +1 @@ -import { z } from 'zod' - -export const WorktreeSelector = z.object({ - worktree: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing worktree selector')) -}) - -export const FileOpen = WorktreeSelector.extend({ - relativePath: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing relative path')) -}) +export { FileOpen, WorktreeSelector } from '../../../../shared/rpc-contract/files-target-params' diff --git a/src/main/runtime/rpc/methods/files-terminal-artifact-methods.ts b/src/main/runtime/rpc/methods/files-terminal-artifact-methods.ts index 08925e08689..20d52eb424d 100644 --- a/src/main/runtime/rpc/methods/files-terminal-artifact-methods.ts +++ b/src/main/runtime/rpc/methods/files-terminal-artifact-methods.ts @@ -1,26 +1,11 @@ -import { z } from 'zod' -import { defineMethod, type RpcAnyMethod } from '../core' +import { defineMethod } from '../core' import { remoteFileContentBudget } from './files-remote-content-budget' -import { WorktreeSelector } from './files-target-schemas' +import { + TerminalArtifactFile, + TerminalArtifactFileWrite +} from '../../../../shared/rpc-contract/files-terminal-artifact-params' -const TerminalArtifactFile = WorktreeSelector.extend({ - grantId: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing terminal artifact grant')), - absolutePath: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing terminal artifact path')) -}) - -const TerminalArtifactFileWrite = TerminalArtifactFile.extend({ - content: z - .unknown() - .refine((v): v is string => typeof v === 'string', { message: 'Missing file content' }) -}) - -export const FILE_TERMINAL_ARTIFACT_METHODS: RpcAnyMethod[] = [ +export const FILE_TERMINAL_ARTIFACT_METHODS = [ defineMethod({ name: 'files.readTerminalArtifact', params: TerminalArtifactFile, diff --git a/src/main/runtime/rpc/methods/files.ts b/src/main/runtime/rpc/methods/files.ts index ef349a22f84..055c02b3265 100644 --- a/src/main/runtime/rpc/methods/files.ts +++ b/src/main/runtime/rpc/methods/files.ts @@ -1,115 +1,27 @@ -import { z } from 'zod' -import { defineMethod, defineStreamingMethod, type RpcAnyMethod } from '../core' +import { defineMethod, defineStreamingMethod } from '../core' import { runFileWatchStream } from './file-watch-stream-lifecycle' import { FILE_MUTATION_METHODS } from './files-mutation-methods' import { remoteFileContentBudget } from './files-remote-content-budget' -import { - QUICK_OPEN_REMOTE_QUERY_MAX_CODE_UNITS, - QUICK_OPEN_SEARCH_VERSION -} from '../../../../shared/quick-open-path-search' +import { QUICK_OPEN_SEARCH_VERSION } from '../../../../shared/quick-open-path-search' import { limitQuickOpenSearchReplyBySerializedBytes } from '../../../../shared/quick-open-transport-budget' import { FileOpen, WorktreeSelector } from './files-target-schemas' import { FILE_TERMINAL_ARTIFACT_METHODS } from './files-terminal-artifact-methods' +import { + DocPreviewFileRead, + FileListAll, + FileOpenDiff, + FilePathSearch, + FileReadChunk, + FileSearch, + FileTreePath, + FileUnwatch, + ResolveTerminalPath, + ServerDirectoryBrowse +} from '../../../../shared/rpc-contract/files-params' let filesWatchSubscriptionSeq = 0 -const FilePathSearch = WorktreeSelector.extend({ - query: z.string().max(QUICK_OPEN_REMOTE_QUERY_MAX_CODE_UNITS).default(''), - limit: z.number().int().positive().max(32).default(16), - excludePaths: z.array(z.string()).optional(), - mode: z.literal('quick-open').optional() -}) - -const ResolveTerminalPath = WorktreeSelector.extend({ - pathText: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing path text')), - terminal: z - .unknown() - .transform((v) => (typeof v === 'string' && v.length > 0 ? v : null)) - .nullable() - .optional(), - cwd: z - .unknown() - .transform((v) => (typeof v === 'string' && v.length > 0 ? v : null)) - .nullable() - .optional(), - crossWorkspace: z - .unknown() - .transform((v) => v === true) - .optional(), - nativeChatContext: z - .object({ - tabId: z.string().min(1), - sessionId: z.string().min(1) - }) - .optional() -}) - -const FileOpenDiff = FileOpen.extend({ - staged: z.boolean().optional() -}) - -const DocPreviewFileRead = FileOpen.extend({ - entryRelativePath: z.string().min(1), - implicitRootRelativePath: z.string().nullable(), - authorizedRootRelativePaths: z.array(z.string()) -}) - -const FileTreePath = WorktreeSelector.extend({ - relativePath: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string()) -}) - -const ServerDirectoryBrowse = z.object({ - path: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string()) -}) - -const FileReadChunk = FileOpen.extend({ - offset: z.number().int().nonnegative(), - length: z - .number() - .int() - .positive() - .max(512 * 1024) -}) - -const FileSearch = WorktreeSelector.extend({ - query: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing search query')), - caseSensitive: z.boolean().optional(), - wholeWord: z.boolean().optional(), - useRegex: z.boolean().optional(), - includePattern: z.string().optional(), - excludePattern: z.string().optional(), - maxResults: z.number().int().positive().optional() -}) - -// Why: `maxResults` is a new optional field (wire rule 1) — an older host strips it and keeps its -// own default. It existed only on the Electron IPC hop, so "the client names its cap and a full page -// means there is more" was true for desktop and merely incidental for web and mobile, which were -// saved by `remoteFileContentBudget` defaulting the cap inside `listRuntimeFiles`. -const FileListAll = WorktreeSelector.extend({ - excludePaths: z.array(z.string()).optional(), - maxResults: z.number().int().positive().optional() -}) - -const FileUnwatch = z.object({ - subscriptionId: z - .unknown() - .transform((value) => (typeof value === 'string' && value.length > 0 ? value : '')) - .pipe(z.string().min(1, 'Missing subscriptionId')) -}) - -export const FILE_METHODS: RpcAnyMethod[] = [ +export const FILE_METHODS = [ defineMethod({ name: 'files.list', params: WorktreeSelector, diff --git a/src/main/runtime/rpc/methods/folder-workspace.ts b/src/main/runtime/rpc/methods/folder-workspace.ts index aa39654d9f8..a2e178b8ed9 100644 --- a/src/main/runtime/rpc/methods/folder-workspace.ts +++ b/src/main/runtime/rpc/methods/folder-workspace.ts @@ -1,92 +1,13 @@ -import { z } from 'zod' -import { defineMethod, type RpcMethod } from '../core' -import { OptionalFiniteNumber, OptionalString, requiredString } from '../schemas' -import { isTuiAgent } from '../../../../shared/tui-agent-config' -import { TaskSourceContextSchema } from '../../../../shared/task-source-context-schema' -import { WorkspaceLinkedItemSchema } from '../../../../shared/workspace-linked-item-schema' -import { isWorkspaceLinkedItemSourceContextMatch } from '../../../../shared/workspace-linked-item-source-context' +import { defineMethod } from '../core' import { resolveRpcWorkspaceCreatorProvenance } from '../workspace-creator-context' -import { DiffCommentSchema } from '../../../../shared/diff-comment-schema' +import { + FolderWorkspaceCreate, + FolderWorkspacePathStatus, + FolderWorkspaceSelector, + FolderWorkspaceUpdate +} from '../../../../shared/rpc-contract/folder-workspace-params' -const FolderWorkspaceLinkedTask = WorkspaceLinkedItemSchema.nullable() - -function assertLinkedTaskSourceContextMatch( - value: { - linkedTask?: z.infer - linkedTaskSourceContext?: z.infer | null - }, - ctx: z.RefinementCtx -): void { - if ( - value.linkedTask && - value.linkedTaskSourceContext && - !isWorkspaceLinkedItemSourceContextMatch(value.linkedTask, value.linkedTaskSourceContext) - ) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: 'Linked task and source context identities must match' - }) - } -} - -const FolderWorkspaceCreate = z - .object({ - projectGroupId: requiredString('Missing project group id'), - name: OptionalString, - folderPath: OptionalString.nullable().optional(), - connectionId: OptionalString.nullable().optional(), - linkedTask: FolderWorkspaceLinkedTask.optional(), - linkedTaskSourceContext: TaskSourceContextSchema.nullable().optional(), - createdWithAgent: z.string().refine(isTuiAgent).optional(), - pendingFirstAgentMessageRename: z.boolean().optional() - }) - .superRefine(assertLinkedTaskSourceContextMatch) - -const FolderWorkspaceUpdate = z.object({ - folderWorkspaceId: requiredString('Missing folder workspace id'), - updates: z - .object({ - name: OptionalString, - folderPath: OptionalString, - linkedTask: FolderWorkspaceLinkedTask.optional(), - linkedTaskSourceContext: TaskSourceContextSchema.nullable().optional(), - comment: z.string().optional(), - isArchived: z.boolean().optional(), - isUnread: z.boolean().optional(), - isPinned: z.boolean().optional(), - sortOrder: OptionalFiniteNumber, - manualOrder: OptionalFiniteNumber, - workspaceStatus: OptionalString, - createdWithAgent: z.string().refine(isTuiAgent).optional(), - pendingFirstAgentMessageRename: z.boolean().optional(), - firstAgentMessageRenameError: z.string().nullable().optional(), - lastActivityAt: OptionalFiniteNumber, - diffComments: z.array(DiffCommentSchema).optional() - }) - .superRefine(assertLinkedTaskSourceContextMatch) -}) - -const FolderWorkspaceSelector = z.object({ - folderWorkspaceId: requiredString('Missing folder workspace id') -}) - -const FolderWorkspacePathStatus = z.discriminatedUnion('scope', [ - z.object({ - scope: z.literal('folder-workspace'), - folderWorkspaceId: requiredString('Missing folder workspace id') - }), - z.object({ - scope: z.literal('project-group'), - projectGroupId: requiredString('Missing project group id') - }), - z.object({ - scope: z.literal('path'), - path: requiredString('Missing folder path'), - connectionId: OptionalString.nullable().optional() - }) -]) - -export const FOLDER_WORKSPACE_METHODS: RpcMethod[] = [ +export const FOLDER_WORKSPACE_METHODS = [ defineMethod({ name: 'folderWorkspace.list', params: null, diff --git a/src/main/runtime/rpc/methods/git-admission-tier-schema.ts b/src/main/runtime/rpc/methods/git-admission-tier-schema.ts index 926aba5b6f9..c5366441b4b 100644 --- a/src/main/runtime/rpc/methods/git-admission-tier-schema.ts +++ b/src/main/runtime/rpc/methods/git-admission-tier-schema.ts @@ -1,11 +1 @@ -import { z } from 'zod' -import type { GitAdmissionTier } from '../../../git/command-runner/git-exec-options' - -export const OptionalGitAdmissionTier = z - .unknown() - .optional() - .transform((value): GitAdmissionTier | undefined => { - return value === 'interactive' || value === 'status' || value === 'background' - ? value - : undefined - }) +export { OptionalGitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' diff --git a/src/main/runtime/rpc/methods/git-commit-message-generation-methods.ts b/src/main/runtime/rpc/methods/git-commit-message-generation-methods.ts index 787c8581dea..1dffcfb2211 100644 --- a/src/main/runtime/rpc/methods/git-commit-message-generation-methods.ts +++ b/src/main/runtime/rpc/methods/git-commit-message-generation-methods.ts @@ -1,4 +1,4 @@ -import { defineMethod, type RpcMethod } from '../core' +import { defineMethod } from '../core' import type { GlobalSettings } from '../../../../shared/global-settings-types' import type { ResolvedSourceControlAiGenerationParams } from '../../../../shared/source-control-ai' import { @@ -58,7 +58,7 @@ function buildCommitMessageGenerationOverride(params: { } } -export const GIT_COMMIT_MESSAGE_GENERATION_METHODS: RpcMethod[] = [ +export const GIT_COMMIT_MESSAGE_GENERATION_METHODS = [ defineMethod({ name: 'git.generateCommitMessage', params: GitGenerateCommitMessage, diff --git a/src/main/runtime/rpc/methods/git-diff-methods.ts b/src/main/runtime/rpc/methods/git-diff-methods.ts index 7b5c0661c0e..edcaebbdf42 100644 --- a/src/main/runtime/rpc/methods/git-diff-methods.ts +++ b/src/main/runtime/rpc/methods/git-diff-methods.ts @@ -1,4 +1,4 @@ -import { defineMethod, type RpcMethod } from '../core' +import { defineMethod } from '../core' import { remoteRpcContentBudget } from '../../../../shared/remote-rpc-content-budget' import { GitBranchDiff, GitCommitDiff, GitDiff } from './git-params' @@ -11,7 +11,7 @@ function remoteDiffContentBudget( return clientKind && requestId ? remoteRpcContentBudget(requestId) : undefined } -export const GIT_DIFF_METHODS: RpcMethod[] = [ +export const GIT_DIFF_METHODS = [ defineMethod({ name: 'git.diff', params: GitDiff, diff --git a/src/main/runtime/rpc/methods/git-params.ts b/src/main/runtime/rpc/methods/git-params.ts index f69b01cd053..ad80955ea76 100644 --- a/src/main/runtime/rpc/methods/git-params.ts +++ b/src/main/runtime/rpc/methods/git-params.ts @@ -1,271 +1,25 @@ -import { z } from 'zod' -import { OptionalGitAdmissionTier } from './git-admission-tier-schema' - -export const WorktreeSelector = z.object({ - worktree: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing worktree selector')) -}) - -export const GitStatusParams = WorktreeSelector.extend({ - admissionTier: OptionalGitAdmissionTier, - includeIgnored: z.boolean().optional(), - includeLineStats: z.boolean().optional(), - bypassEffectiveUpstreamNegativeCache: z.boolean().optional(), - reuseLineStats: z.boolean().optional(), - // Shape is re-validated host-side before it reaches a git argv. - branchLineTotalMergeBase: z.string().optional() -}) - -export const GitCheckIgnored = WorktreeSelector.extend({ - paths: z.array(z.string().min(1, 'Missing path')).max(2000) -}) - -export const GitSubmoduleStatus = WorktreeSelector.extend({ - submodulePath: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe( - z - .string() - .min(1, 'Missing submodule path') - // Why: never let a submodule path be parsed as a git flag (arg injection). - .refine((value) => !value.startsWith('-'), 'Submodule path must not start with -') - ), - // Why: submodule expansion is requested from a Source Control row; the row - // area determines whether the gitlink range is HEAD->index or index->worktree. - area: z.enum(['staged', 'unstaged', 'untracked']).optional() -}) - -export const GitFilePath = WorktreeSelector.extend({ - filePath: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing file path')) -}) - -export const GitDiff = GitFilePath.extend({ - staged: z.boolean(), - compareAgainstHead: z.boolean().optional() -}) - -export const GitBranchCompare = WorktreeSelector.extend({ - admissionTier: OptionalGitAdmissionTier, - baseRef: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe( - z - .string() - .min(1, 'Missing base ref') - .refine((value) => !value.startsWith('-'), 'Base ref must not start with -') - ) -}) - -const FullGitObjectId = z - .string() - .regex(/^(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})$/, 'Expected a full git object id') - -export const GitCommitCompare = WorktreeSelector.extend({ - commitId: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(FullGitObjectId) -}) - -export const GitHistory = WorktreeSelector.extend({ - limit: z.number().int().min(1).max(200).optional(), - baseRef: z.string().nullable().optional() -}) - -export const GitBranchDiff = GitFilePath.extend({ - compare: z.object({ - baseRef: z.string().optional(), - baseOid: FullGitObjectId.optional(), - headOid: FullGitObjectId, - mergeBase: FullGitObjectId - }), - oldPath: z.string().optional() -}) - -export const GitCommitDiff = GitFilePath.extend({ - commitOid: FullGitObjectId, - parentOid: FullGitObjectId.nullable().optional(), - oldPath: z.string().optional() -}) - -export const GitCommit = WorktreeSelector.extend({ - message: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing commit message')) -}) - -const CommitMessageModelCapability = z.object({ - id: z.string(), - label: z.string(), - thinkingLevels: z.array(z.object({ id: z.string(), label: z.string() })).optional(), - defaultThinkingLevel: z.string().optional() -}) - -const CommitMessageAiSettings = z.object({ - enabled: z.boolean(), - agentId: z.string().nullable(), - selectedModelByAgent: z.record(z.string(), z.string()), - selectedModelByAgentByHost: z.record(z.string(), z.record(z.string(), z.string())).optional(), - discoveredModelsByAgent: z.record(z.string(), z.array(CommitMessageModelCapability)).optional(), - discoveredModelsByAgentByHost: z - .record(z.string(), z.record(z.string(), z.array(CommitMessageModelCapability))) - .optional(), - selectedThinkingByModel: z.record(z.string(), z.string()), - customPrompt: z.string(), - customAgentCommand: z.string() -}) - -const SourceControlAiSettings = CommitMessageAiSettings.omit({ customPrompt: true }).extend({ - actions: z - .record( - z.string(), - z.object({ - agentId: z.string().nullable().optional(), - commandInputTemplate: z.string().optional(), - agentArgs: z.string().optional() - }) - ) - .optional(), - instructionsByOperation: z.record(z.string(), z.string()).optional(), - modelOverridesByOperation: z - .record( - z.string(), - z.object({ - selectedModelByAgent: z.record(z.string(), z.string()).optional(), - selectedModelByAgentByHost: z - .record(z.string(), z.record(z.string(), z.string())) - .optional(), - selectedThinkingByModel: z.record(z.string(), z.string()).optional() - }) - ) - .optional(), - prCreationDefaults: z - .object({ - draft: z.boolean().optional(), - useTemplate: z.boolean().optional(), - generateDetailsOnOpen: z.boolean().optional(), - openAfterCreate: z.boolean().optional() - }) - .optional(), - launchActionDefaults: z - .record( - z.string(), - z.object({ - agentId: z.string().nullable().optional(), - commandInputTemplate: z.string().optional(), - agentArgs: z.string().optional() - }) - ) - .optional() -}) - -const ResolvedSourceControlAiGenerationParams = z.object({ - agentId: z.string(), - model: z.string(), - thinkingLevel: z.string().optional(), - customPrompt: z.string().optional(), - commandInputTemplate: z.string().optional(), - agentArgs: z.string().optional(), - customAgentCommand: z.string().optional(), - agentCommandOverride: z.string().optional() -}) - -export const GitGenerateCommitMessage = WorktreeSelector.extend({ - commitMessageAi: CommitMessageAiSettings.optional(), - sourceControlAi: SourceControlAiSettings.optional(), - sourceControlAiResolvedParams: ResolvedSourceControlAiGenerationParams.optional(), - agentCmdOverrides: z.record(z.string(), z.string()).optional(), - commitMessageDiscoveryHostKey: z.string().optional() -}) - -export const GitDiscoverCommitMessageModels = WorktreeSelector.extend({ - agentId: z.string().min(1, 'Missing agent id'), - agentCmdOverrides: z.record(z.string(), z.string()).optional() -}) - -export const GitGeneratePullRequestFields = GitGenerateCommitMessage.extend({ - base: z.string().min(1, 'Missing base branch'), - title: z.string(), - body: z.string(), - draft: z.boolean(), - provider: z - .enum(['github', 'gitlab', 'bitbucket', 'azure-devops', 'gitea', 'unsupported']) - .optional(), - useTemplate: z.boolean().optional() -}) - -export const GitBulkPaths = WorktreeSelector.extend({ - filePaths: z.array(z.string().min(1, 'Missing file path')) -}) - -const GitPushTargetParam = z.object({ - remoteName: z.string(), - branchName: z.string(), - remoteUrl: z.string().optional(), - remoteCreated: z.boolean().optional() -}) - -export const GitPush = WorktreeSelector.extend({ - publish: z.boolean().optional(), - forceWithLease: z.boolean().optional(), - pushTarget: GitPushTargetParam.optional() -}) - -export const GitTargetedRemote = WorktreeSelector.extend({ - pushTarget: GitPushTargetParam.optional() -}) - -export const GitForkSync = WorktreeSelector.extend({ - expectedUpstream: z.object({ - owner: z.string().trim().min(1), - repo: z.string().trim().min(1) - }) -}) - -export const GitRebaseFromBase = WorktreeSelector.extend({ - baseRef: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe( - z - .string() - .min(1, 'Missing base ref') - .refine((value) => !value.startsWith('-'), 'Base ref must not start with -') - ) -}) - -export const GitCheckout = WorktreeSelector.extend({ - branch: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe( - z - .string() - .min(1, 'Missing branch') - // Why: never let a branch arg be parsed as a git flag (arg injection). - .refine((value) => !value.startsWith('-'), 'Branch must not start with -') - ) -}) - -export const GitRemoteFileUrl = WorktreeSelector.extend({ - relativePath: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing relative path')), - line: z.number().int().min(1) -}) - -export const GitRemoteCommitUrl = WorktreeSelector.extend({ - sha: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(FullGitObjectId) -}) +export { + GitBranchCompare, + GitBranchDiff, + GitBulkPaths, + GitCheckIgnored, + GitCheckout, + GitCommit, + GitCommitCompare, + GitCommitDiff, + GitDiff, + GitDiscoverCommitMessageModels, + GitFilePath, + GitForkSync, + GitGenerateCommitMessage, + GitGeneratePullRequestFields, + GitHistory, + GitPush, + GitRebaseFromBase, + GitRemoteCommitUrl, + GitRemoteFileUrl, + GitStatusParams, + GitSubmoduleStatus, + GitTargetedRemote, + WorktreeSelector +} from '../../../../shared/rpc-contract/git-params' diff --git a/src/main/runtime/rpc/methods/git.ts b/src/main/runtime/rpc/methods/git.ts index ddfbe7bf273..20102d71e28 100644 --- a/src/main/runtime/rpc/methods/git.ts +++ b/src/main/runtime/rpc/methods/git.ts @@ -1,4 +1,4 @@ -import { defineMethod, type RpcMethod } from '../core' +import { defineMethod } from '../core' import { GIT_COMMIT_MESSAGE_GENERATION_METHODS } from './git-commit-message-generation-methods' import { GIT_DIFF_METHODS } from './git-diff-methods' import { @@ -21,7 +21,7 @@ import { WorktreeSelector } from './git-params' -export const GIT_METHODS: RpcMethod[] = [ +export const GIT_METHODS = [ defineMethod({ name: 'git.status', params: GitStatusParams, diff --git a/src/main/runtime/rpc/methods/github-issue-methods.ts b/src/main/runtime/rpc/methods/github-issue-methods.ts index 75eb75c81b6..86300017741 100644 --- a/src/main/runtime/rpc/methods/github-issue-methods.ts +++ b/src/main/runtime/rpc/methods/github-issue-methods.ts @@ -1,33 +1,12 @@ -import { z } from 'zod' -import { defineMethod, type RpcMethod } from '../core' -import { requiredString } from '../schemas' -import { IssueUpdate } from './github-issue-update-schema' -import { RepoSelector, SlugRepo } from './github-repo-target-schemas' +import { defineMethod } from '../core' +import { + CreateIssue, + Issue, + IssueComment, + UpdateIssue +} from '../../../../shared/rpc-contract/github-issue-params' -const Issue = RepoSelector.extend({ - number: z.number().int().positive() -}) - -const CreateIssue = RepoSelector.extend({ - title: requiredString('Missing title'), - body: z.string(), - labels: z.array(z.string()).optional(), - assignees: z.array(z.string()).optional() -}) - -const UpdateIssue = RepoSelector.extend({ - number: z.number().int().positive(), - updates: IssueUpdate -}) - -const IssueComment = RepoSelector.extend({ - number: z.number().int().positive(), - body: requiredString('Comment body required'), - type: z.enum(['issue', 'pr']).optional(), - prRepo: SlugRepo.nullable().optional() -}) - -export const GITHUB_ISSUE_METHODS: RpcMethod[] = [ +export const GITHUB_ISSUE_METHODS = [ defineMethod({ name: 'github.issue', params: Issue, diff --git a/src/main/runtime/rpc/methods/github-issue-update-schema.ts b/src/main/runtime/rpc/methods/github-issue-update-schema.ts index 7b3020e91b5..6a9f860113b 100644 --- a/src/main/runtime/rpc/methods/github-issue-update-schema.ts +++ b/src/main/runtime/rpc/methods/github-issue-update-schema.ts @@ -1,13 +1 @@ -import { z } from 'zod' -import { OptionalString } from '../schemas' - -// Why: repo-selector and slug-addressed issue updates must accept the identical field set. -export const IssueUpdate = z.object({ - state: z.enum(['open', 'closed']).optional(), - title: OptionalString, - body: OptionalString, - addLabels: z.array(z.string()).optional(), - removeLabels: z.array(z.string()).optional(), - addAssignees: z.array(z.string()).optional(), - removeAssignees: z.array(z.string()).optional() -}) +export { IssueUpdate } from '../../../../shared/rpc-contract/github-issue-update-params' diff --git a/src/main/runtime/rpc/methods/github-project-methods.ts b/src/main/runtime/rpc/methods/github-project-methods.ts index ce70c200218..c05086decbf 100644 --- a/src/main/runtime/rpc/methods/github-project-methods.ts +++ b/src/main/runtime/rpc/methods/github-project-methods.ts @@ -1,135 +1,26 @@ -import { z } from 'zod' -import { defineMethod, type RpcMethod } from '../core' -import { OptionalString, requiredString } from '../schemas' -import { IssueUpdate } from './github-issue-update-schema' +import { defineMethod } from '../core' import { SlugRepo } from './github-repo-target-schemas' +import { + ClearProjectItemField, + GithubProjectListAccessibleParams, + ProjectItemField, + ProjectRef, + ProjectViewTable, + ProjectViews, + ProjectWorkItemDetailsBySlug, + SlugAssignableUsers, + SlugIssueComment, + SlugIssueCommentDelete, + SlugIssueCommentEdit, + SlugIssueTypeUpdate, + SlugIssueUpdate, + SlugPullRequestUpdate +} from '../../../../shared/rpc-contract/github-project-params' -const SlugAssignableUsers = SlugRepo.extend({ - seedLogins: z.array(z.string()).optional() -}) - -const ProjectOwnerType = z.enum(['organization', 'user']) - -const ProjectViewTable = z.object({ - owner: requiredString('Missing owner'), - // Why: Enterprise host identity must survive RPC parsing; Zod strips - // undeclared fields before the runtime can host-qualify gh requests. - host: OptionalString, - ownerType: ProjectOwnerType, - projectNumber: z.number().int().positive(), - viewId: OptionalString, - viewNumber: z.number().int().positive().optional(), - viewName: OptionalString, - queryOverride: OptionalString -}) - -const ProjectWorkItemDetailsBySlug = SlugRepo.extend({ - number: z.number().int().positive(), - type: z.enum(['issue', 'pr']) -}) - -const ProjectRef = z.object({ - input: requiredString('Missing project reference'), - // Why: Enterprise host identity must survive RPC parsing; Zod strips - // undeclared fields before the runtime can host-qualify gh requests. - host: OptionalString -}) - -const ProjectViews = z.object({ - owner: requiredString('Missing owner'), - // Why: Enterprise host identity must survive RPC parsing; Zod strips - // undeclared fields before the runtime can host-qualify gh requests. - host: OptionalString, - ownerType: ProjectOwnerType, - projectNumber: z.number().int().positive() -}) - -const ProjectItemField = z.object({ - projectId: requiredString('Missing project ID'), - // Why: Enterprise host identity must survive RPC parsing; Zod strips - // undeclared fields before the runtime can host-qualify gh requests. - host: OptionalString, - itemId: requiredString('Missing item ID'), - fieldId: requiredString('Missing field ID'), - value: z.any() -}) - -const ClearProjectItemField = z.object({ - projectId: requiredString('Missing project ID'), - // Why: Enterprise host identity must survive RPC parsing; Zod strips - // undeclared fields before the runtime can host-qualify gh requests. - host: OptionalString, - itemId: requiredString('Missing item ID'), - fieldId: requiredString('Missing field ID') -}) - -const SlugIssueUpdate = z.object({ - owner: requiredString('Missing owner'), - repo: requiredString('Missing repo'), - // Why: Enterprise host identity must survive RPC parsing; Zod strips - // undeclared fields before the runtime can host-qualify gh requests. - host: OptionalString, - number: z.number().int().positive(), - updates: IssueUpdate -}) - -const SlugPullRequestUpdate = z.object({ - owner: requiredString('Missing owner'), - repo: requiredString('Missing repo'), - // Why: Enterprise host identity must survive RPC parsing; Zod strips - // undeclared fields before the runtime can host-qualify gh requests. - host: OptionalString, - number: z.number().int().positive(), - updates: z.object({ - state: z.enum(['open', 'closed']).optional(), - title: OptionalString, - body: OptionalString - }) -}) - -const SlugIssueTypeUpdate = z.object({ - owner: requiredString('Missing owner'), - repo: requiredString('Missing repo'), - // Why: Enterprise host identity must survive RPC parsing; Zod strips - // undeclared fields before the runtime can host-qualify gh requests. - host: OptionalString, - number: z.number().int().positive(), - issueTypeId: z.string().nullable() -}) - -const SlugIssueComment = z.object({ - owner: requiredString('Missing owner'), - repo: requiredString('Missing repo'), - // Why: Enterprise host identity must survive RPC parsing; Zod strips - // undeclared fields before the runtime can host-qualify gh requests. - host: OptionalString, - number: z.number().int().positive(), - body: requiredString('Comment body required') -}) - -const SlugIssueCommentEdit = z.object({ - owner: requiredString('Missing owner'), - repo: requiredString('Missing repo'), - // Why: Enterprise host identity must survive RPC parsing; Zod strips - // undeclared fields before the runtime can host-qualify gh requests. - host: OptionalString, - commentId: z.number().int().positive(), - body: requiredString('Comment body required') -}) - -const SlugIssueCommentDelete = z.object({ - owner: requiredString('Missing owner'), - repo: requiredString('Missing repo'), - // Why: Enterprise host identity must survive RPC parsing; Zod strips - // undeclared fields before the runtime can host-qualify gh requests. - host: OptionalString, - commentId: z.number().int().positive() -}) - -export const GITHUB_PROJECT_METHODS: RpcMethod[] = [ +export const GITHUB_PROJECT_METHODS = [ defineMethod({ name: 'github.project.listAccessible', - params: z.object({ host: OptionalString }), + params: GithubProjectListAccessibleParams, handler: async (params, { runtime }) => runtime.listGitHubProjects(params) }), defineMethod({ diff --git a/src/main/runtime/rpc/methods/github-pull-request-methods.ts b/src/main/runtime/rpc/methods/github-pull-request-methods.ts index 958e08c439a..0a7f2efd522 100644 --- a/src/main/runtime/rpc/methods/github-pull-request-methods.ts +++ b/src/main/runtime/rpc/methods/github-pull-request-methods.ts @@ -1,85 +1,17 @@ -import { z } from 'zod' -import { defineMethod, type RpcMethod } from '../core' -import { OptionalString, requiredString } from '../schemas' -import { RepoSelector, SlugRepo } from './github-repo-target-schemas' -import type { GitHubPRRefreshReason } from '../../../../shared/github/pull-request-refresh-types' +import { defineMethod } from '../core' +import { + PRCommentReaction, + PrForBranch, + PullRequest, + PullRequestCheckDetails, + PullRequestChecks, + PullRequestFileContents, + PullRequestFileViewed, + RerunPullRequestChecks, + ReviewThread +} from '../../../../shared/rpc-contract/github-pull-request-params' -const OptionalPRRefreshReason = z - .unknown() - .optional() - .transform((value): GitHubPRRefreshReason | undefined => { - return value === 'visible' || - value === 'active' || - value === 'post-push' || - value === 'manual' || - value === 'swr' - ? value - : undefined - }) - -const PrForBranch = RepoSelector.extend({ - branch: requiredString('Missing branch'), - reason: OptionalPRRefreshReason, - linkedPRNumber: z.number().int().positive().nullable().optional(), - fallbackPRNumber: z.number().int().positive().nullable().optional(), - acceptMergedFallbackPR: z.boolean().optional(), - currentHeadOid: z.string().nullable().optional() -}) - -const PullRequest = RepoSelector.extend({ - prNumber: z.number().int().positive(), - noCache: z.boolean().optional(), - prRepo: SlugRepo.nullable().optional() -}) - -const PRCommentReaction = RepoSelector.extend({ - reactionSubjectId: requiredString('Missing reaction subject ID'), - content: z.enum(['+1', '-1', 'laugh', 'confused', 'heart', 'hooray', 'rocket', 'eyes']), - reacted: z.boolean(), - prRepo: SlugRepo.nullable().optional() -}) - -const PullRequestChecks = PullRequest.extend({ - headSha: OptionalString -}) - -const PullRequestCheckDetails = RepoSelector.extend({ - checkRunId: z.number().int().positive().optional(), - workflowRunId: z.number().int().positive().optional(), - checkName: OptionalString, - url: OptionalString.nullable().optional(), - prRepo: SlugRepo.nullable().optional() -}) - -const RerunPullRequestChecks = PullRequest.extend({ - headSha: OptionalString, - failedOnly: z.boolean().optional() -}) - -const PullRequestFileContents = RepoSelector.extend({ - prNumber: z.number().int().positive(), - prRepo: SlugRepo.nullable().optional(), - path: requiredString('Missing file path'), - oldPath: OptionalString, - status: z.enum(['added', 'removed', 'modified', 'renamed', 'copied', 'changed', 'unchanged']), - headSha: requiredString('Missing head SHA'), - baseSha: requiredString('Missing base SHA') -}) - -const PullRequestFileViewed = RepoSelector.extend({ - prRepo: SlugRepo.nullable().optional(), - pullRequestId: requiredString('Missing pull request ID'), - path: requiredString('Missing file path'), - viewed: z.boolean() -}) - -const ReviewThread = RepoSelector.extend({ - prRepo: SlugRepo.nullable().optional(), - threadId: requiredString('Missing thread ID'), - resolve: z.boolean() -}) - -export const GITHUB_PULL_REQUEST_METHODS: RpcMethod[] = [ +export const GITHUB_PULL_REQUEST_METHODS = [ defineMethod({ name: 'github.prForBranch', params: PrForBranch, diff --git a/src/main/runtime/rpc/methods/github-pull-request-update-methods.ts b/src/main/runtime/rpc/methods/github-pull-request-update-methods.ts index 4d34b89420e..59089b82015 100644 --- a/src/main/runtime/rpc/methods/github-pull-request-update-methods.ts +++ b/src/main/runtime/rpc/methods/github-pull-request-update-methods.ts @@ -1,82 +1,18 @@ -import { z } from 'zod' -import { defineMethod, type RpcMethod } from '../core' -import { OptionalString, requiredString } from '../schemas' -import { RepoSelector, SlugRepo } from './github-repo-target-schemas' +import { defineMethod } from '../core' +import { + MarkPrReadyForReview, + MergePr, + PRReviewComment, + PRReviewCommentReply, + RemovePrReviewers, + RequestPrReviewers, + SetPrAutoMerge, + UpdatePr, + UpdatePrState, + UpdatePrTitle +} from '../../../../shared/rpc-contract/github-pull-request-update-params' -const UpdatePrTitle = RepoSelector.extend({ - prNumber: z.number().int().positive(), - title: requiredString('Missing title'), - prRepo: SlugRepo.nullable().optional() -}) - -const UpdatePr = RepoSelector.extend({ - prNumber: z.number().int().positive(), - updates: z.object({ - title: OptionalString, - body: z.string().optional() - }), - prRepo: SlugRepo.nullable().optional() -}) - -const MergePr = RepoSelector.extend({ - prNumber: z.number().int().positive(), - method: z.enum(['merge', 'squash', 'rebase']).optional(), - prRepo: SlugRepo.nullable().optional() -}) - -const SetPrAutoMerge = RepoSelector.extend({ - prNumber: z.number().int().positive(), - enabled: z.boolean(), - method: z.enum(['merge', 'squash', 'rebase']).optional(), - prRepo: SlugRepo.nullable().optional() -}) - -const UpdatePrState = RepoSelector.extend({ - prNumber: z.number().int().positive(), - prRepo: SlugRepo.nullable().optional(), - updates: z.object({ - state: z.enum(['open', 'closed']) - }) -}) - -const MarkPrReadyForReview = RepoSelector.extend({ - prNumber: z.number().int().positive(), - prRepo: SlugRepo.nullable().optional() -}) - -const RequestPrReviewers = RepoSelector.extend({ - prNumber: z.number().int().positive(), - prRepo: SlugRepo.nullable().optional(), - reviewers: z.array(z.string()).min(1) -}) - -const RemovePrReviewers = RepoSelector.extend({ - prNumber: z.number().int().positive(), - prRepo: SlugRepo.nullable().optional(), - reviewers: z.array(z.string()).min(1) -}) - -const PRReviewComment = RepoSelector.extend({ - prNumber: z.number().int().positive(), - prRepo: SlugRepo.nullable().optional(), - commitId: requiredString('Missing PR head SHA'), - path: requiredString('File path required'), - line: z.number().int().positive(), - startLine: z.number().int().positive().optional(), - body: requiredString('Comment body required') -}) - -const PRReviewCommentReply = RepoSelector.extend({ - prNumber: z.number().int().positive(), - commentId: z.number().int().positive(), - body: requiredString('Comment body required'), - threadId: OptionalString, - path: OptionalString, - line: z.number().int().positive().optional(), - prRepo: SlugRepo.nullable().optional() -}) - -export const GITHUB_PULL_REQUEST_UPDATE_METHODS: RpcMethod[] = [ +export const GITHUB_PULL_REQUEST_UPDATE_METHODS = [ defineMethod({ name: 'github.updatePRTitle', params: UpdatePrTitle, diff --git a/src/main/runtime/rpc/methods/github-repo-target-schemas.ts b/src/main/runtime/rpc/methods/github-repo-target-schemas.ts index 3ea8b688910..06d47d47d9b 100644 --- a/src/main/runtime/rpc/methods/github-repo-target-schemas.ts +++ b/src/main/runtime/rpc/methods/github-repo-target-schemas.ts @@ -1,14 +1 @@ -import { z } from 'zod' -import { OptionalString, requiredString } from '../schemas' - -export const RepoSelector = z.object({ - repo: requiredString('Missing repo selector') -}) - -export const SlugRepo = z.object({ - owner: requiredString('Missing owner'), - repo: requiredString('Missing repo'), - // Why: Enterprise host identity must survive RPC parsing; Zod strips - // undeclared fields before the runtime can host-qualify gh requests. - host: OptionalString -}) +export { RepoSelector, SlugRepo } from '../../../../shared/rpc-contract/github-repo-target-params' diff --git a/src/main/runtime/rpc/methods/github-repo-work-item-methods.ts b/src/main/runtime/rpc/methods/github-repo-work-item-methods.ts index 9602ba6cb70..6b2d83988d7 100644 --- a/src/main/runtime/rpc/methods/github-repo-work-item-methods.ts +++ b/src/main/runtime/rpc/methods/github-repo-work-item-methods.ts @@ -1,45 +1,16 @@ -import { z } from 'zod' -import { defineMethod, type RpcMethod } from '../core' -import { OptionalFiniteNumber, OptionalString, requiredString } from '../schemas' +import { defineMethod } from '../core' import { RepoSelector } from './github-repo-target-schemas' +import { + IssuesList, + RateLimit, + WorkItem, + WorkItemByOwnerRepo, + WorkItemDetails, + WorkItemsCount, + WorkItemsList +} from '../../../../shared/rpc-contract/github-repo-work-item-params' -const WorkItemsList = RepoSelector.extend({ - limit: OptionalFiniteNumber, - query: OptionalString, - page: z.number().int().positive().optional(), - noCache: z.boolean().optional() -}) - -const IssuesList = RepoSelector.extend({ - limit: OptionalFiniteNumber -}) - -const WorkItem = RepoSelector.extend({ - number: z.number().int().positive(), - type: z.enum(['issue', 'pr']).optional() -}) - -const WorkItemByOwnerRepo = RepoSelector.extend({ - owner: requiredString('Missing owner'), - ownerRepo: requiredString('Missing repo'), - // Why: Enterprise host identity must survive RPC parsing; Zod strips - // undeclared fields before the runtime can host-qualify gh requests. - host: OptionalString, - number: z.number().int().positive(), - type: z.enum(['issue', 'pr']) -}) - -const WorkItemDetails = WorkItem - -const WorkItemsCount = RepoSelector.extend({ - query: OptionalString -}) - -const RateLimit = z.object({ - force: z.boolean().optional() -}) - -export const GITHUB_REPO_WORK_ITEM_METHODS: RpcMethod[] = [ +export const GITHUB_REPO_WORK_ITEM_METHODS = [ defineMethod({ name: 'github.repoSlug', params: RepoSelector, diff --git a/src/main/runtime/rpc/methods/github.ts b/src/main/runtime/rpc/methods/github.ts index 1dd4cb28823..d2113f9ac22 100644 --- a/src/main/runtime/rpc/methods/github.ts +++ b/src/main/runtime/rpc/methods/github.ts @@ -1,11 +1,10 @@ -import type { RpcMethod } from '../core' import { GITHUB_ISSUE_METHODS } from './github-issue-methods' import { GITHUB_PROJECT_METHODS } from './github-project-methods' import { GITHUB_PULL_REQUEST_METHODS } from './github-pull-request-methods' import { GITHUB_PULL_REQUEST_UPDATE_METHODS } from './github-pull-request-update-methods' import { GITHUB_REPO_WORK_ITEM_METHODS } from './github-repo-work-item-methods' -export const GITHUB_METHODS: RpcMethod[] = [ +export const GITHUB_METHODS = [ ...GITHUB_REPO_WORK_ITEM_METHODS, ...GITHUB_ISSUE_METHODS, ...GITHUB_PULL_REQUEST_METHODS, diff --git a/src/main/runtime/rpc/methods/gitlab.ts b/src/main/runtime/rpc/methods/gitlab.ts index ac8fcad6991..93f73d5f05c 100644 --- a/src/main/runtime/rpc/methods/gitlab.ts +++ b/src/main/runtime/rpc/methods/gitlab.ts @@ -1,156 +1,29 @@ -import { z } from 'zod' -import { defineMethod, type RpcMethod } from '../core' -import { OptionalFiniteNumber, OptionalString, requiredString } from '../schemas' +import { defineMethod } from '../core' import { normalizeGitLabIssueListArgs } from '../../../gitlab/gitlab-preload-args' import { toGitLabJobLogExcerptResult } from '../../../../shared/gitlab-job-log-excerpt' +import { + AddIssueComment, + AddMRComment, + AddMRInlineComment, + CreateIssue, + EmptyParams, + GitLabRateLimit, + IssuesList, + JobTrace, + MergeMr, + RepoSelector, + ResolveMRDiscussion, + RetryJob, + UpdateIssue, + UpdateMr, + UpdateMrReviewers, + UpdateMrState, + WorkItemByPath, + WorkItemDetails, + WorkItemsList +} from '../../../../shared/rpc-contract/gitlab-params' -const RepoSelector = z.object({ - repo: requiredString('Missing repo selector') -}) - -const EmptyParams = z.object({}).optional().default({}) -const GitLabRateLimit = z - .object({ - force: z.boolean().optional(), - host: OptionalString - }) - .optional() - .default({}) - -// nullish, not optional: renderer callers normalise a missing ref to `null` -// (`item.projectRef ?? null`), which a bare `.optional()` would reject outright. -const GitLabProjectRef = z - .object({ - host: requiredString('Missing GitLab host'), - path: requiredString('Missing GitLab project path') - }) - .nullish() - -const WorkItemsList = RepoSelector.extend({ - state: z.enum(['opened', 'merged', 'closed', 'all']).optional(), - page: OptionalFiniteNumber, - perPage: OptionalFiniteNumber, - query: OptionalString -}) - -const IssuesList = RepoSelector.extend({ - state: z.unknown().optional(), - assignee: OptionalString, - limit: OptionalFiniteNumber, - page: OptionalFiniteNumber -}) - -const CreateIssue = RepoSelector.extend({ - title: requiredString('Missing title'), - body: z.string() -}) - -const IssueUpdate = z.object({ - state: z.enum(['opened', 'closed']).optional(), - title: z.string().optional(), - body: z.string().optional(), - addLabels: z.array(z.string()).optional(), - removeLabels: z.array(z.string()).optional(), - addAssignees: z.array(z.string()).optional(), - removeAssignees: z.array(z.string()).optional() -}) - -const UpdateIssue = RepoSelector.extend({ - number: z.number().int().positive(), - updates: IssueUpdate, - projectRef: GitLabProjectRef -}) - -const UpdateMrState = RepoSelector.extend({ - iid: z.number().int().positive(), - state: z.enum(['opened', 'closed']), - projectRef: GitLabProjectRef -}) - -const UpdateMr = RepoSelector.extend({ - iid: z.number().int().positive(), - updates: z.object({ - title: z.string().optional(), - body: z.string().optional(), - addLabels: z.array(z.string()).optional(), - removeLabels: z.array(z.string()).optional(), - readyForReview: z.literal(true).optional() - }), - projectRef: GitLabProjectRef -}) - -const UpdateMrReviewers = RepoSelector.extend({ - iid: z.number().int().positive(), - reviewerIds: z.array(z.number().int().nonnegative()), - projectRef: GitLabProjectRef -}) - -const MergeMr = RepoSelector.extend({ - iid: z.number().int().positive(), - method: z.enum(['merge', 'squash', 'rebase']).optional(), - projectRef: GitLabProjectRef -}) - -const AddIssueComment = RepoSelector.extend({ - number: z.number().int().positive(), - body: requiredString('Comment body is required'), - projectRef: GitLabProjectRef -}) - -const AddMRComment = RepoSelector.extend({ - iid: z.number().int().positive(), - body: requiredString('Comment body is required'), - projectRef: GitLabProjectRef -}) - -const AddMRInlineComment = RepoSelector.extend({ - iid: z.number().int().positive(), - input: z.object({ - body: requiredString('Comment body is required'), - path: requiredString('File path is required'), - oldPath: z.string().optional(), - line: z.number().int().positive(), - baseSha: requiredString('Base SHA is required'), - startSha: requiredString('Start SHA is required'), - headSha: requiredString('Head SHA is required') - }), - projectRef: GitLabProjectRef -}) - -const ResolveMRDiscussion = RepoSelector.extend({ - iid: z.number().int().positive(), - discussionId: requiredString('Discussion id is required'), - resolved: z.boolean(), - projectRef: GitLabProjectRef -}) - -const JobTrace = RepoSelector.extend({ - jobId: z.number().int().positive(), - projectRef: GitLabProjectRef, - // Why: raw CI traces routinely exceed the 1 MB transport frame cap, so callers - // that only render an excerpt ask main to bound it before it crosses the wire. - logExcerpt: z.boolean().optional() -}) - -const RetryJob = RepoSelector.extend({ - jobId: z.number().int().positive(), - projectRef: GitLabProjectRef -}) - -const WorkItemDetails = RepoSelector.extend({ - iid: z.number().int().positive(), - type: z.enum(['issue', 'mr']), - projectRef: GitLabProjectRef -}) - -const WorkItemByPath = RepoSelector.extend({ - host: requiredString('Missing GitLab host'), - path: requiredString('Missing GitLab project path'), - iid: z.number().int().positive(), - type: z.enum(['issue', 'mr']) -}) - -export const GITLAB_METHODS: RpcMethod[] = [ +export const GITLAB_METHODS = [ defineMethod({ name: 'gitlab.listMRs', params: WorkItemsList, diff --git a/src/main/runtime/rpc/methods/host-capabilities.ts b/src/main/runtime/rpc/methods/host-capabilities.ts index afa1af88474..85a32fd1e5c 100644 --- a/src/main/runtime/rpc/methods/host-capabilities.ts +++ b/src/main/runtime/rpc/methods/host-capabilities.ts @@ -1,9 +1,9 @@ -import { defineMethod, type RpcMethod } from '../core' +import { defineMethod } from '../core' import { isPwshAvailableAsync } from '../../../pwsh' import { isWslAvailableAsync, listWslDistrosAsync } from '../../../wsl' import { isGitBashAvailable } from '../../../git-bash' -export const HOST_CAPABILITY_METHODS: RpcMethod[] = [ +export const HOST_CAPABILITY_METHODS = [ defineMethod({ name: 'host.platform', params: null, diff --git a/src/main/runtime/rpc/methods/hosted-review.ts b/src/main/runtime/rpc/methods/hosted-review.ts index fae2e8eb162..51d663210d8 100644 --- a/src/main/runtime/rpc/methods/hosted-review.ts +++ b/src/main/runtime/rpc/methods/hosted-review.ts @@ -1,53 +1,11 @@ -import { z } from 'zod' -import { defineMethod, type RpcMethod } from '../core' -import { requiredString } from '../schemas' -import { OptionalGitAdmissionTier } from './git-admission-tier-schema' +import { defineMethod } from '../core' +import { + HostedReviewCreate, + HostedReviewCreationEligibility, + HostedReviewForBranch +} from '../../../../shared/rpc-contract/hosted-review-params' -const HostedReviewForBranch = z.object({ - repo: requiredString('Missing repo selector'), - branch: requiredString('Missing branch'), - admissionTier: OptionalGitAdmissionTier, - currentHeadOid: z.string().nullable().optional(), - // Only the caller's selected worktree; the host caps how many earn the fast tier. - active: z.boolean().optional(), - linkedGitHubPR: z.number().int().positive().nullable().optional(), - fallbackGitHubPR: z.number().int().positive().nullable().optional(), - linkedGitLabMR: z.number().int().positive().nullable().optional(), - linkedBitbucketPR: z.number().int().positive().nullable().optional(), - linkedAzureDevOpsPR: z.number().int().positive().nullable().optional(), - linkedGiteaPR: z.number().int().positive().nullable().optional() -}) - -const HostedReviewCreationEligibility = z.object({ - repo: requiredString('Missing repo selector'), - worktree: z.string().min(1, 'Missing worktree selector').optional(), - branch: requiredString('Missing branch'), - base: z.string().nullable().optional(), - hasUncommittedChanges: z.boolean().optional(), - hasUpstream: z.boolean().optional(), - ahead: z.number().int().nonnegative().optional(), - behind: z.number().int().nonnegative().optional(), - linkedGitHubPR: z.number().int().positive().nullable().optional(), - fallbackGitHubPR: z.number().int().positive().nullable().optional(), - linkedGitLabMR: z.number().int().positive().nullable().optional(), - linkedBitbucketPR: z.number().int().positive().nullable().optional(), - linkedAzureDevOpsPR: z.number().int().positive().nullable().optional(), - linkedGiteaPR: z.number().int().positive().nullable().optional() -}) - -const HostedReviewCreate = z.object({ - repo: requiredString('Missing repo selector'), - worktree: z.string().min(1, 'Missing worktree selector').optional(), - provider: z.enum(['github', 'gitlab', 'bitbucket', 'azure-devops', 'gitea', 'unsupported']), - base: requiredString('Missing base branch'), - head: z.string().optional(), - title: requiredString('Missing title'), - body: z.string().optional(), - draft: z.boolean().optional(), - useTemplate: z.boolean().optional() -}) - -export const HOSTED_REVIEW_METHODS: RpcMethod[] = [ +export const HOSTED_REVIEW_METHODS = [ defineMethod({ name: 'hostedReview.forBranch', params: HostedReviewForBranch, diff --git a/src/main/runtime/rpc/methods/index.ts b/src/main/runtime/rpc/methods/index.ts index ba77b94803e..3a53bccb9ce 100644 --- a/src/main/runtime/rpc/methods/index.ts +++ b/src/main/runtime/rpc/methods/index.ts @@ -1,4 +1,3 @@ -import type { RpcAnyMethod } from '../core' import { STATUS_METHODS } from './status' import { AI_VAULT_METHODS } from './ai-vault' import { AUTOMATION_METHODS } from './automations' @@ -50,7 +49,7 @@ import { AGENT_HOOK_METHODS } from './agent-hooks' // Why: a flat manifest keeps registration order explicit and provides one // grep-point for "what methods does the RPC server expose?" — useful when // auditing the security boundary or wiring new CLI commands. -export const ALL_RPC_METHODS: readonly RpcAnyMethod[] = [ +export const ALL_RPC_METHODS = [ ...STATUS_METHODS, ...AGENT_HOOK_METHODS, ...AI_VAULT_METHODS, diff --git a/src/main/runtime/rpc/methods/jira.ts b/src/main/runtime/rpc/methods/jira.ts index 087aa25f36e..0e959cf0f5e 100644 --- a/src/main/runtime/rpc/methods/jira.ts +++ b/src/main/runtime/rpc/methods/jira.ts @@ -1,109 +1,24 @@ -import { z } from 'zod' import { JIRA_PAYLOAD_CHUNK_CHARS, JIRA_PAYLOAD_MAX_CHARS } from '../../../../shared/jira-payload-stream' -import { defineMethod, defineStreamingMethod, type RpcAnyMethod } from '../core' +import { defineMethod, defineStreamingMethod } from '../core' import { - OptionalFiniteNumber, - OptionalPlainString, - OptionalString, - requiredString -} from '../schemas' - -const VALID_FILTERS = ['assigned', 'reported', 'all', 'done'] as const - -const SiteSelection = z - .object({ - siteId: OptionalString - }) - .optional() - -const Connect = z.object({ - siteUrl: requiredString('Site URL is required'), - // Self-hosted PAT auth needs no email; connect() enforces it for Cloud. - email: OptionalPlainString, - apiToken: requiredString('API token is required'), - authType: z.enum(['cloud', 'server']).optional() -}) - -const SelectSite = z.object({ - siteId: requiredString('Site ID is required') -}) - -const SearchIssues = z.object({ - jql: requiredString('Missing JQL'), - limit: OptionalFiniteNumber, - siteId: OptionalString -}) - -const ListIssues = z - .object({ - filter: z.enum(VALID_FILTERS).optional(), - limit: OptionalFiniteNumber, - siteId: OptionalString - }) - .optional() - -const IssueKey = z.object({ - key: requiredString('Issue key is required'), - siteId: OptionalString -}) - -const CreateIssue = z.object({ - siteId: OptionalString, - projectId: requiredString('Project is required'), - issueTypeId: requiredString('Issue type is required'), - title: requiredString('Title is required'), - description: OptionalPlainString, - customFields: z.record(z.string(), z.unknown()).optional(), - userFieldKeys: z.array(z.string()).optional() -}) - -const IssueUpdate = z.object({ - key: requiredString('Issue key is required'), - siteId: OptionalString, - updates: z.object({ - title: OptionalString, - labels: z.array(z.string()).optional(), - assigneeAccountId: z.union([z.string(), z.null()]).optional(), - priorityId: z.union([z.string(), z.null()]).optional(), - transitionId: OptionalString - }) -}) - -const IssueComment = z.object({ - key: requiredString('Issue key is required'), - body: requiredString('Comment body is required'), - siteId: OptionalString -}) - -const ProjectIssueTypes = z.object({ - projectIdOrKey: requiredString('Project is required'), - siteId: OptionalString -}) - -const ProjectIssueTypeFields = z.object({ - projectIdOrKey: requiredString('Project is required'), - issueTypeId: requiredString('Issue type is required'), - siteId: OptionalString -}) - -const AssignableUsers = z.object({ - key: requiredString('Issue key is required'), - query: OptionalPlainString, - siteId: OptionalString -}) - -const UserSearch = z.object({ - query: OptionalPlainString, - siteId: OptionalString -}) - -const ProjectStatusOrder = z.object({ - projectKey: requiredString('Project key is required'), - siteId: OptionalString -}) + AssignableUsers, + Connect, + CreateIssue, + IssueComment, + IssueKey, + IssueUpdate, + ListIssues, + ProjectIssueTypeFields, + ProjectIssueTypes, + ProjectStatusOrder, + SearchIssues, + SelectSite, + SiteSelection, + UserSearch +} from '../../../../shared/rpc-contract/jira-params' /** Emits a Jira result over RPC, normalizing it to the shape clients decode. */ function emitJiraPayload(value: unknown, emit: (result: unknown) => void): void { @@ -119,7 +34,7 @@ function emitJiraPayload(value: unknown, emit: (result: unknown) => void): void emit({ type: 'end' }) } -export const JIRA_METHODS: RpcAnyMethod[] = [ +export const JIRA_METHODS = [ defineMethod({ name: 'jira.connect', params: Connect, diff --git a/src/main/runtime/rpc/methods/linear-agent-access.ts b/src/main/runtime/rpc/methods/linear-agent-access.ts index 50e7bfef3a2..2c46face39d 100644 --- a/src/main/runtime/rpc/methods/linear-agent-access.ts +++ b/src/main/runtime/rpc/methods/linear-agent-access.ts @@ -1,149 +1,22 @@ -import { z } from 'zod' -import { defineMethod, type RpcMethod } from '../core' -import { OptionalFiniteNumber, OptionalString, requiredString } from '../schemas' +import { defineMethod } from '../core' import { linearError } from '../../../linear/issue-context-errors' import { isLinearUuid } from '../../../../shared/linear/uuid' - -const LINEAR_DUE_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/ -const LinearDueDate = z.string().refine((value) => LINEAR_DUE_DATE_PATTERN.test(value), { - message: 'Linear due dates must use YYYY-MM-DD' -}) -const OptionalLinearDueDate = LinearDueDate.optional() -const OptionalLinearDueDateOrClear = z.union([LinearDueDate, z.null()]).optional() - -const AgentSearchIssues = z.object({ - query: requiredString('Missing query'), - limit: OptionalFiniteNumber, - workspaceId: z.union([z.string(), z.literal('all')]).optional() -}) - -const LinearWorkspaceRead = z.object({ - workspaceId: z.union([z.string(), z.literal('all')]).optional() -}) - -const LinearTeamLookup = z.object({ - teamInput: requiredString('Missing team'), - workspaceId: OptionalString.refine((value) => value !== 'all', { - message: '--workspace all is only valid for team list' - }) -}) - -const LinearIssueList = z.object({ - filter: z.enum(['assigned', 'created', 'all', 'completed', 'open']).optional(), - teamInput: OptionalString, - limit: OptionalFiniteNumber, - workspaceId: z.union([z.string(), z.literal('all')]).optional() -}) - -const LinearProjectList = z.object({ - query: OptionalString, - limit: OptionalFiniteNumber, - workspaceId: z.union([z.string(), z.literal('all')]).optional() -}) - -const LinearIncludeFlags = z.object({ - comments: z.boolean(), - children: z.boolean(), - attachments: z.boolean(), - relations: z.boolean(), - activity: z.boolean().default(false) -}) - -const LinearCurrentContext = z - .object({ - worktreeId: OptionalString, - terminalHandle: OptionalString, - cwd: OptionalString, - remote: z.boolean().optional() - }) - .optional() - -const LinearWriteTarget = z.object({ - input: OptionalString, - current: z.boolean().optional(), - workspaceId: OptionalString.refine((value) => value !== 'all', { - message: '--workspace all is not valid for Linear writes' - }), - context: LinearCurrentContext -}) - -const AgentIssueContext = z.object({ - input: OptionalString, - current: z.boolean().optional(), - workspaceId: OptionalString, - include: LinearIncludeFlags, - depth: z.number().int().min(0).max(5), - context: LinearCurrentContext -}) - -const LinearIssueSetState = LinearWriteTarget.extend({ - to: requiredString('Missing target state') -}) - -const LinearIssueUpdateTask = LinearWriteTarget.extend({ - operation: z.enum(['assignee', 'priority', 'estimate', 'dueDate', 'labels']), - assigneeId: z.string().nullable().optional(), - assigneeMe: z.boolean().optional(), - priority: z.number().int().min(0).max(4).optional(), - estimate: z.number().int().min(0).nullable().optional(), - dueDate: OptionalLinearDueDateOrClear, - labelMode: z.enum(['add', 'remove', 'set']).optional(), - labels: z.array(z.string()).optional() -}) - -const LinearIssueAddComment = LinearWriteTarget.extend({ - body: requiredString('Missing comment body'), - replyTo: OptionalString, - writeId: OptionalString -}) - -const LinearIssueRelationWrite = LinearWriteTarget.extend({ - relatedInput: requiredString('Missing related issue'), - relationship: z.enum(['blocks', 'blockedBy', 'relatedTo', 'duplicateOf']), - operation: z.enum(['add', 'remove']) -}) - -const LinearIssueAttachLink = LinearWriteTarget.extend({ - url: requiredString('Missing attachment URL'), - title: OptionalString, - writeId: OptionalString -}) - -const LinearIssueCreate = z.object({ - title: requiredString('Missing issue title'), - body: OptionalString, - teamInput: OptionalString, - teamKey: OptionalString, - state: OptionalString, - assignee: OptionalString, - priority: z.number().int().min(0).max(4).optional(), - estimate: z.number().int().min(0).optional(), - dueDate: OptionalLinearDueDate, - labels: z.array(z.string()).optional(), - projectInput: OptionalString, - parentInput: OptionalString, - parentCurrent: z.boolean().optional(), - workspaceId: OptionalString.refine((value) => value !== 'all', { - message: '--workspace all is not valid for Linear writes' - }), - writeId: OptionalString, - context: LinearCurrentContext -}) - -const LinearSaveIssue = LinearWriteTarget.extend({ - team: OptionalString, - title: OptionalString, - description: z.string().optional(), - state: OptionalString, - assignee: z.string().nullable().optional(), - priority: z.number().int().min(0).max(4).optional(), - estimate: z.number().min(0).nullable().optional(), - dueDate: OptionalLinearDueDateOrClear, - labels: z.array(z.string()).optional(), - project: z.string().nullable().optional(), - parentId: z.string().nullable().optional(), - writeId: OptionalString -}) +import { + AgentIssueContext, + AgentSearchIssues, + LinearCurrentContext, + LinearIssueAddComment, + LinearIssueAttachLink, + LinearIssueCreate, + LinearIssueList, + LinearIssueRelationWrite, + LinearIssueSetState, + LinearIssueUpdateTask, + LinearProjectList, + LinearSaveIssue, + LinearTeamLookup, + LinearWorkspaceRead +} from '../../../../shared/rpc-contract/linear-agent-access-params' function parseLinearWriteId(writeId: string | undefined): string | undefined { if (writeId === undefined) { @@ -155,7 +28,7 @@ function parseLinearWriteId(writeId: string | undefined): string | undefined { return writeId } -export const LINEAR_AGENT_ACCESS_METHODS: RpcMethod[] = [ +export const LINEAR_AGENT_ACCESS_METHODS = [ defineMethod({ name: 'linear.saveIssue', params: LinearSaveIssue, diff --git a/src/main/runtime/rpc/methods/linear-issue-attribute-filter-schema.ts b/src/main/runtime/rpc/methods/linear-issue-attribute-filter-schema.ts index 7b7176f48b8..b369a01a15c 100644 --- a/src/main/runtime/rpc/methods/linear-issue-attribute-filter-schema.ts +++ b/src/main/runtime/rpc/methods/linear-issue-attribute-filter-schema.ts @@ -1,35 +1 @@ -import { z } from 'zod' -import { - LINEAR_ISSUE_ATTRIBUTE_FILTER_ID_MAX_LENGTH, - LINEAR_ISSUE_ATTRIBUTE_FILTER_MAX_LABEL_IDS, - LINEAR_ISSUE_ATTRIBUTE_FILTER_MAX_PRIORITIES, - LINEAR_ISSUE_ATTRIBUTE_FILTER_MAX_STATE_IDS -} from '../../../../shared/linear/issue-attribute-filter' - -// Why: keep ListIssues param validation co-located with shared limits without -// pushing linear.ts past the max-lines ratchet. -const LinearAttributeFilterId = z - .string() - .trim() - .min(1) - .max(LINEAR_ISSUE_ATTRIBUTE_FILTER_ID_MAX_LENGTH) - -export const LinearIssueAttributeFilterSchema = z - .object({ - stateIds: z.array(LinearAttributeFilterId).max(LINEAR_ISSUE_ATTRIBUTE_FILTER_MAX_STATE_IDS), - priorities: z - .array(z.number().int().min(0).max(4)) - .max(LINEAR_ISSUE_ATTRIBUTE_FILTER_MAX_PRIORITIES), - assignee: z.union([ - z.object({ kind: z.literal('unassigned') }).strict(), - z - .object({ - kind: z.literal('user'), - id: LinearAttributeFilterId - }) - .strict(), - z.null() - ]), - labelIds: z.array(LinearAttributeFilterId).max(LINEAR_ISSUE_ATTRIBUTE_FILTER_MAX_LABEL_IDS) - }) - .strict() +export { LinearIssueAttributeFilterSchema } from '../../../../shared/rpc-contract/linear-issue-attribute-filter-params' diff --git a/src/main/runtime/rpc/methods/linear-issue-list-method.ts b/src/main/runtime/rpc/methods/linear-issue-list-method.ts index fa69b745377..9dd838c837a 100644 --- a/src/main/runtime/rpc/methods/linear-issue-list-method.ts +++ b/src/main/runtime/rpc/methods/linear-issue-list-method.ts @@ -1,42 +1,6 @@ -import { z } from 'zod' +import type { z } from 'zod' import { defineMethod } from '../core' -import { OptionalFiniteNumber, OptionalString } from '../schemas' -import { LinearIssueAttributeFilterSchema } from './linear-issue-attribute-filter-schema' - -const LegacyListIssues = z - .object({ - filter: z.enum(['assigned', 'created', 'all', 'completed']).optional(), - limit: OptionalFiniteNumber, - workspaceId: OptionalString, - attributeFilter: LinearIssueAttributeFilterSchema.optional() - }) - .strict() - .optional() - -const McpListIssues = z - .object({ - team: OptionalString, - cycle: OptionalString, - label: OptionalString, - limit: z.number().int().min(1).max(250).optional(), - query: OptionalString, - state: OptionalString, - cursor: OptionalString, - orderBy: z.enum(['createdAt', 'updatedAt']).optional(), - project: OptionalString, - release: OptionalString, - assignee: OptionalString, - delegate: OptionalString, - parentId: OptionalString, - priority: z.number().int().min(0).max(4).optional(), - createdAt: OptionalString, - updatedAt: OptionalString, - includeArchived: z.boolean().optional(), - workspaceId: OptionalString - }) - .strict() - -const ListIssues = z.union([McpListIssues, LegacyListIssues]) +import { ListIssues, McpListIssues } from '../../../../shared/rpc-contract/linear-issue-list-params' export const LINEAR_ISSUE_LIST_METHOD = defineMethod({ name: 'linear.listIssues', diff --git a/src/main/runtime/rpc/methods/linear-project-create.ts b/src/main/runtime/rpc/methods/linear-project-create.ts index 026c585aba2..8377b69acdf 100644 --- a/src/main/runtime/rpc/methods/linear-project-create.ts +++ b/src/main/runtime/rpc/methods/linear-project-create.ts @@ -1,25 +1,7 @@ -import { z } from 'zod' -import { defineMethod, type RpcMethod } from '../core' -import { OptionalString, requiredString } from '../schemas' +import { defineMethod } from '../core' +import { CreateProject } from '../../../../shared/rpc-contract/linear-project-create-params' -const LinearPriority = z.number().int().min(0).max(4).optional() -const LinearLabelIds = z.array(requiredString('Invalid label ID')).optional() - -const CreateProject = z.object({ - name: requiredString('Project name is required'), - description: OptionalString, - content: OptionalString, - workspaceId: OptionalString, - teamIds: z.array(requiredString('Invalid team ID')).min(1, 'At least one team is required'), - leadId: z.union([z.string(), z.null()]).optional(), - memberIds: z.array(requiredString('Invalid member ID')).optional(), - labelIds: LinearLabelIds, - priority: LinearPriority, - startDate: OptionalString, - targetDate: OptionalString -}) - -export const LINEAR_PROJECT_CREATE_METHOD: RpcMethod = defineMethod({ +export const LINEAR_PROJECT_CREATE_METHOD = defineMethod({ name: 'linear.createProject', params: CreateProject, handler: async (params, { runtime }) => diff --git a/src/main/runtime/rpc/methods/linear.ts b/src/main/runtime/rpc/methods/linear.ts index 1f3e474e78d..456b4c5b4e9 100644 --- a/src/main/runtime/rpc/methods/linear.ts +++ b/src/main/runtime/rpc/methods/linear.ts @@ -1,126 +1,26 @@ -import { z } from 'zod' -import { defineMethod, type RpcMethod } from '../core' -import { OptionalFiniteNumber, OptionalString, requiredString } from '../schemas' +import { defineMethod } from '../core' import { LINEAR_PROJECT_CREATE_METHOD } from './linear-project-create' import { LINEAR_ISSUE_LIST_METHOD, LINEAR_MCP_ISSUE_LIST_METHOD } from './linear-issue-list-method' +import { + Connect, + CreateIssue, + CustomViewContents, + CustomViewId, + IssueComment, + IssueId, + IssueUpdate, + LinearIssueCommentsParams, + ListCustomViews, + ListProjects, + ProjectId, + ProjectIssues, + SearchIssues, + SelectWorkspace, + TeamId, + WorkspaceSelection +} from '../../../../shared/rpc-contract/linear-params' -const VALID_CUSTOM_VIEW_MODELS = ['issue', 'project'] as const -const LinearPriority = z.number().int().min(0).max(4).optional() -const LinearLabelIds = z.array(requiredString('Invalid label ID')).optional() - -const Connect = z.object({ - apiKey: requiredString('Invalid API key') -}) - -const WorkspaceSelection = z - .object({ - workspaceId: OptionalString - }) - .optional() - -const ConcreteWorkspaceId = requiredString('Concrete Linear workspace ID is required').refine( - (value) => value !== 'all', - 'Concrete Linear workspace ID is required' -) - -const SelectWorkspace = z.object({ - workspaceId: requiredString('Workspace ID is required') -}) - -const SearchIssues = z.object({ - query: requiredString('Missing query'), - limit: OptionalFiniteNumber, - workspaceId: OptionalString -}) - -const CreateIssue = z.object({ - teamId: requiredString('Team ID is required'), - title: requiredString('Title is required'), - description: OptionalString, - workspaceId: OptionalString, - parentIssueId: OptionalString, - projectId: z.union([z.string(), z.null()]).optional(), - stateId: OptionalString, - priority: LinearPriority, - assigneeId: z.union([z.string(), z.null()]).optional(), - labelIds: LinearLabelIds -}) - -const IssueId = z.object({ - id: requiredString('Issue ID is required'), - workspaceId: OptionalString -}) - -const IssueComment = z.object({ - issueId: requiredString('Issue ID is required'), - body: requiredString('Comment body is required'), - workspaceId: OptionalString -}) - -const ListProjects = z - .object({ - query: OptionalString, - limit: OptionalFiniteNumber, - workspaceId: OptionalString, - force: z.boolean().optional() - }) - .optional() - -const ProjectId = z.object({ - id: requiredString('Project ID is required'), - workspaceId: ConcreteWorkspaceId, - force: z.boolean().optional() -}) - -const ProjectIssues = z.object({ - projectId: requiredString('Project ID is required'), - limit: OptionalFiniteNumber, - workspaceId: ConcreteWorkspaceId, - force: z.boolean().optional() -}) - -const ListCustomViews = z.object({ - model: z.enum(VALID_CUSTOM_VIEW_MODELS), - limit: OptionalFiniteNumber, - workspaceId: OptionalString, - force: z.boolean().optional() -}) - -const CustomViewId = z.object({ - viewId: requiredString('Custom view ID is required'), - model: z.enum(VALID_CUSTOM_VIEW_MODELS), - workspaceId: ConcreteWorkspaceId, - force: z.boolean().optional() -}) - -const CustomViewContents = z.object({ - viewId: requiredString('Custom view ID is required'), - limit: OptionalFiniteNumber, - workspaceId: ConcreteWorkspaceId, - force: z.boolean().optional() -}) - -const TeamId = z.object({ - teamId: requiredString('Team ID is required'), - workspaceId: OptionalString -}) - -const IssueUpdate = z.object({ - id: requiredString('Issue ID is required'), - workspaceId: OptionalString, - updates: z.object({ - stateId: OptionalString, - title: OptionalString, - description: z.string().optional(), - assigneeId: z.union([z.string(), z.null()]).optional(), - estimate: z.union([z.number().int().min(0), z.null()]).optional(), - priority: z.number().int().min(0).max(4).optional(), - labelIds: z.array(z.string()).optional(), - projectId: z.union([z.string(), z.null()]).optional() - }) -}) - -export const LINEAR_METHODS: RpcMethod[] = [ +export const LINEAR_METHODS = [ defineMethod({ name: 'linear.connect', params: Connect, @@ -193,10 +93,7 @@ export const LINEAR_METHODS: RpcMethod[] = [ }), defineMethod({ name: 'linear.issueComments', - params: z.object({ - issueId: requiredString('Issue ID is required'), - workspaceId: OptionalString - }), + params: LinearIssueCommentsParams, handler: async (params, { runtime }) => runtime.linearIssueComments(params.issueId.trim(), params.workspaceId) }), diff --git a/src/main/runtime/rpc/methods/mobile-markdown-tab-methods.ts b/src/main/runtime/rpc/methods/mobile-markdown-tab-methods.ts index dcba8b7b64e..756d4719f22 100644 --- a/src/main/runtime/rpc/methods/mobile-markdown-tab-methods.ts +++ b/src/main/runtime/rpc/methods/mobile-markdown-tab-methods.ts @@ -1,7 +1,7 @@ -import { defineMethod, type RpcAnyMethod } from '../core' +import { defineMethod } from '../core' import { ActivateTab, SaveMarkdownTab } from './session-tabs-schemas' -export const MOBILE_MARKDOWN_TAB_METHODS: RpcAnyMethod[] = [ +export const MOBILE_MARKDOWN_TAB_METHODS = [ defineMethod({ name: 'markdown.readTab', params: ActivateTab, diff --git a/src/main/runtime/rpc/methods/native-chat.ts b/src/main/runtime/rpc/methods/native-chat.ts index e1a92dd52db..05f8f7f8726 100644 --- a/src/main/runtime/rpc/methods/native-chat.ts +++ b/src/main/runtime/rpc/methods/native-chat.ts @@ -1,59 +1,17 @@ -import { z } from 'zod' -import type { NativeChatMessage, AgentType } from '../../../../shared/native-chat-types' +import type { NativeChatMessage } from '../../../../shared/native-chat-types' import { readNativeChatTranscriptTail, subscribeNativeChatTranscript, type NativeChatTranscriptSubscription, type SubscribeNativeChatTranscriptArgs } from '../../../native-chat/transcript-watch' -import { defineMethod, defineStreamingMethod, type RpcAnyMethod, type RpcContext } from '../core' +import { defineMethod, defineStreamingMethod, type RpcContext } from '../core' import { sanitizeNativeChatRpcBlock } from './native-chat-rpc-block-sanitize' - -// Why: native chat renders an agent's own transcript (Claude/Codex JSONL). The -// desktop reaches the readers via Electron IPC; mobile/web clients reach the -// same pure readers through these runtime RPC methods so the native chat view -// works over the paired connection, not just in the desktop renderer. - -const NativeChatSession = z.object({ - agent: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing agent')) - .transform((v) => v as AgentType), - sessionId: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing session id')), - // How many of the most-recent messages to return. Clients start small for a - // fast first paint and raise it to page older history in as the user scrolls. - // Clamp (don't reject) a limit past the max window so a client paging beyond it - // gets the capped tail and pagination stops cleanly — a hard `.max` rejection - // would fail the read and stall "load earlier" at the boundary. - limit: z - .number() - .int() - .positive() - .transform((value) => Math.min(value, MOBILE_NATIVE_CHAT_MAX_WINDOW)) - .optional(), - // Optional client-supplied cleanup token. When present, the subscribe handler - // keys the fs-watcher cleanup under it so registration and unsubscribe derive - // from the SAME token (back-compat: falls back to `agent:sessionId` when absent, - // which is exactly what existing mobile clients rely on). - subscriptionId: z.string().min(1).optional(), - // Authoritative transcript path from the agent hook (providerSession), used to - // locate the file directly when the session id no longer names it (recent - // Claude Code). Optional for back-compat with older clients. - transcriptPath: z.string().min(1).optional(), - // A pending snapshot is not authoritative transcript history. Only clients - // that advertise this semantic may receive one; legacy clients treat it as a - // settled empty read and can overwrite retention / unblock launch drafts. - capabilities: z.object({ transcriptPending: z.literal(1).optional() }).optional(), - beforeOffset: z.number().int().nonnegative().optional() -}) - -const NativeChatUnsubscribe = z.object({ - subscriptionId: z.string().min(1).optional() -}) +import { + MOBILE_NATIVE_CHAT_MAX_WINDOW, + NativeChatSession, + NativeChatUnsubscribe +} from '../../../../shared/rpc-contract/native-chat-params' // Why: a long agent session can hold thousands of turns (with full tool I/O). // Shipping all of them over the paired connection and rendering them at once @@ -63,7 +21,6 @@ const NativeChatUnsubscribe = z.object({ // Small first page for a fast initial paint; the client raises `limit` to load // older history as the user scrolls back. const MOBILE_NATIVE_CHAT_DEFAULT_WINDOW = 40 -const MOBILE_NATIVE_CHAT_MAX_WINDOW = 2000 function sanitizeMessage( message: NativeChatMessage, @@ -106,7 +63,7 @@ function windowForClient( return windowed.map((message) => sanitizeMessage(message, clientKind)) } -export const NATIVE_CHAT_METHODS: readonly RpcAnyMethod[] = [ +export const NATIVE_CHAT_METHODS = [ defineMethod({ name: 'nativeChat.readSession', params: NativeChatSession, diff --git a/src/main/runtime/rpc/methods/notification-preferences.test.ts b/src/main/runtime/rpc/methods/notification-preferences.test.ts new file mode 100644 index 00000000000..5686682376f --- /dev/null +++ b/src/main/runtime/rpc/methods/notification-preferences.test.ts @@ -0,0 +1,84 @@ +import { expect, it } from 'vitest' +import { NOTIFICATION_METHODS } from './notifications' +import { RuntimeMobileNotificationController } from '../../runtime-mobile-notification-controller' +import type { RpcContext, RpcStreamingMethod, RpcMethod } from '../core' + +it('keeps desktop-disabled events out of legacy live and replay streams', async () => { + const controller = new RuntimeMobileNotificationController() + const cleanups: (() => void)[] = [] + const runtime = { + onNotificationDispatched: controller.onDispatched.bind(controller), + getMobileNotificationEpoch: controller.getEpoch.bind(controller), + getMissedNotificationsSince: controller.getMissedSince.bind(controller), + registerSubscriptionCleanup: (_id: string, cleanup: () => void) => cleanups.push(cleanup) + } + const ctx = { runtime } as unknown as RpcContext + const subscribe = NOTIFICATION_METHODS.find( + (method) => method.name === 'notifications.subscribe' + ) as RpcStreamingMethod + const replay = NOTIFICATION_METHODS.find( + (method) => method.name === 'notifications.getMissedSince' + ) as RpcMethod + const legacy: unknown[] = [] + const current: unknown[] = [] + const pending = [ + subscribe.handler({}, ctx, (event) => legacy.push(event)), + subscribe.handler({ includeDesktopSuppressed: true }, ctx, (event) => current.push(event)) + ] + controller.dispatch({ + type: 'notification', + source: 'terminal-bell', + title: 'bell', + body: '', + desktopAllowed: false + }) + controller.dispatch({ + type: 'notification', + source: 'agent-task-complete', + title: 'done', + body: '' + }) + expect(legacy).toHaveLength(2) + expect(current).toHaveLength(3) + expect(legacy[1]).toMatchObject({ title: 'done' }) + expect(current[1]).toMatchObject({ desktopAllowed: false }) + expect(await replay.handler({ lastSeenSeq: 0 }, ctx)).toMatchObject({ + notifications: [{ title: 'done' }] + }) + const result = (await replay.handler( + { lastSeenSeq: 0, includeDesktopSuppressed: true }, + ctx + )) as { notifications: unknown[] } + expect(result.notifications).toHaveLength(2) + cleanups.forEach((cleanup) => cleanup()) + await Promise.all(pending) +}) + +it('preserves legacy workspace cooldown while letting current phones filter before cooldown', async () => { + const { createNotificationStreamFilter } = await import('./notification-stream-policy') + const events = [ + { + type: 'notification' as const, + source: 'terminal-bell' as const, + title: '', + body: '', + worktreeId: 'folder', + emittedAt: 10000 + }, + { + type: 'notification' as const, + source: 'agent-task-complete' as const, + title: '', + body: '', + worktreeId: 'folder', + emittedAt: 10250 + } + ] + const controller = new RuntimeMobileNotificationController() + events.forEach((event) => controller.dispatch(event)) + const recorded = controller.getMissedSince(0) + expect(recorded.filter(createNotificationStreamFilter())).toEqual([ + expect.objectContaining(events[0]) + ]) + expect(recorded.filter(createNotificationStreamFilter(true))).toHaveLength(2) +}) diff --git a/src/main/runtime/rpc/methods/notification-reconnect-cooldown.test.ts b/src/main/runtime/rpc/methods/notification-reconnect-cooldown.test.ts new file mode 100644 index 00000000000..acdf1f08d2d --- /dev/null +++ b/src/main/runtime/rpc/methods/notification-reconnect-cooldown.test.ts @@ -0,0 +1,65 @@ +import { expect, it } from 'vitest' +import { RuntimeMobileNotificationController } from '../../runtime-mobile-notification-controller' +import { NOTIFICATION_METHODS } from './notifications' +import type { RpcContext, RpcMethod, RpcStreamingMethod } from '../core' + +it.each([0, 255])( + 'preserves the live cooldown decision after %i intervening replay entries', + async (filler) => { + const controller = new RuntimeMobileNotificationController() + let stop!: () => void + const ctx = { + runtime: { + onNotificationDispatched: controller.onDispatched.bind(controller), + getMobileNotificationEpoch: controller.getEpoch.bind(controller), + getMissedNotificationsSince: controller.getMissedSince.bind(controller), + registerSubscriptionCleanup: (_id: string, cleanup: () => void) => { + stop = cleanup + } + } + } as unknown as RpcContext + const subscribe = NOTIFICATION_METHODS.find( + (m) => m.name === 'notifications.subscribe' + ) as RpcStreamingMethod + const replay = NOTIFICATION_METHODS.find( + (m) => m.name === 'notifications.getMissedSince' + ) as RpcMethod + const live: unknown[] = [] + const pending = subscribe.handler(undefined, ctx, (e) => live.push(e)) + try { + controller.dispatch({ + type: 'notification', + source: 'terminal-bell', + title: 'first', + body: '', + worktreeId: 'folder', + emittedAt: 10000 + }) + controller.dispatch({ + type: 'notification', + source: 'agent-task-complete', + title: 'suppressed', + body: '', + worktreeId: 'folder', + emittedAt: 10250 + }) + expect(live).toHaveLength(2) + for (let i = 0; i < filler; i++) { + controller.dispatch({ type: 'dismiss', notificationId: `other-${i}` }) + } + const result = (await replay.handler( + { lastSeenSeq: 1, epoch: controller.getEpoch() }, + ctx + )) as { notifications: { type: string }[] } + expect(result.notifications.filter((e) => e.type === 'notification')).toEqual([]) + const all = (await replay.handler( + { lastSeenSeq: 1, epoch: controller.getEpoch(), includeDesktopSuppressed: true }, + ctx + )) as { notifications: { title?: string }[] } + expect(all.notifications.some((e) => e.title === 'suppressed')).toBe(true) + } finally { + stop() + await pending + } + } +) diff --git a/src/main/runtime/rpc/methods/notification-stream-policy.ts b/src/main/runtime/rpc/methods/notification-stream-policy.ts new file mode 100644 index 00000000000..faee99aea02 --- /dev/null +++ b/src/main/runtime/rpc/methods/notification-stream-policy.ts @@ -0,0 +1,8 @@ +import type { MobileNotificationEvent } from '../../runtime-mobile-notification-controller' + +export function createNotificationStreamFilter(includeDesktopSuppressed = false) { + return (event: MobileNotificationEvent): boolean => + includeDesktopSuppressed || + event.type !== 'notification' || + (event.desktopAllowed !== false && event.legacySocketAllowed !== false) +} diff --git a/src/main/runtime/rpc/methods/notifications.ts b/src/main/runtime/rpc/methods/notifications.ts index 80c6af7caec..7df66b4acf4 100644 --- a/src/main/runtime/rpc/methods/notifications.ts +++ b/src/main/runtime/rpc/methods/notifications.ts @@ -1,46 +1,29 @@ -import { z } from 'zod' -import { defineStreamingMethod, defineMethod, type RpcAnyMethod } from '../core' +import { createNotificationStreamFilter } from './notification-stream-policy' +import { defineStreamingMethod, defineMethod } from '../core' +import { + NotificationGetMissedSinceParams, + NotificationRegisterPushParams, + NotificationUnsubscribeParams, + NotificationsSubscribeParams +} from '../../../../shared/rpc-contract/notifications-params' // Why: monotonically increasing per-process counter eliminates the // Date.now() collision that could fire when two near-simultaneous // notifications.subscribe calls landed on the same millisecond. let notificationsSubscriptionSeq = 0 -const NotificationUnsubscribeParams = z.object({ - subscriptionId: z - .unknown() - .transform((value) => (typeof value === 'string' && value.length > 0 ? value : '')) - .pipe(z.string().min(1, 'Missing subscriptionId')) -}) - -// Why: notifications.getMissedSince is the catch-up RPC for mobile reconnect -// (#8129). The client passes the highest seq it has already delivered; the -// runtime returns only notifications dispatched after that seq. Because the -// desktop assigns a monotonic seq to every dispatched notification, the cut is -// exact and idempotent — re-requesting with the same watermark can never -// return an already-delivered event, so reconnects never duplicate local -// pushes (the adversarial-review gate for #8129). -// `epoch` names the counter lifetime lastSeenSeq came from (#8591). The desktop's -// seq restarts at 0 on every launch while the client's watermark is persisted, so -// without it a post-restart watermark silently cuts away everything. Optional: a -// client that predates the field keeps the seq-only cut. -const NotificationGetMissedSinceParams = z.object({ - lastSeenSeq: z.number().int().min(0, 'lastSeenSeq must be a non-negative integer'), - epoch: z.string().optional() -}) - -// Why: notifications.subscribe streams desktop notification events to mobile -// clients over WebSocket. The mobile client shows a local push notification -// for each event. This avoids requiring Firebase/APNs — the existing -// persistent WebSocket connection doubles as the push channel. -export const NOTIFICATION_METHODS: readonly RpcAnyMethod[] = [ +// Legacy callers retain filtered socket alerts; push clients opt into the full event stream. +export const NOTIFICATION_METHODS = [ defineStreamingMethod({ name: 'notifications.subscribe', - params: null, - handler: async (_params, { runtime, connectionId }, emit) => { + params: NotificationsSubscribeParams, + handler: async (params, { runtime, connectionId }, emit) => { + const shouldEmit = createNotificationStreamFilter(params?.includeDesktopSuppressed) await new Promise((resolve) => { const unsubscribe = runtime.onNotificationDispatched((event) => { - emit(event) + if (shouldEmit(event)) { + emit(event) + } }) // Why: scope by per-ws connectionId + per-process counter so @@ -79,7 +62,51 @@ export const NOTIFICATION_METHODS: readonly RpcAnyMethod[] = [ // client missed while its socket was reaped. handler: async (params, { runtime }) => { const missed = runtime.getMissedNotificationsSince(params.lastSeenSeq, params.epoch) - return { notifications: missed, epoch: runtime.getMobileNotificationEpoch() } + return { + notifications: missed.filter( + createNotificationStreamFilter(params.includeDesktopSuppressed) + ), + epoch: runtime.getMobileNotificationEpoch(), + ...(params.deliveredPushes + ? { dismissedPushes: runtime.reconcileDismissedPushes(params.deliveredPushes) } + : {}) + } + } + }), + defineMethod({ + name: 'notifications.registerPush', + params: NotificationRegisterPushParams, + // Why: the registration is keyed by the revocable paired device identity, never + // by anything the caller can assert, so an in-process or CLI caller has no device + // to register and is refused outright. + handler: async (params, { runtime, clientKind, pairedDeviceId }) => { + if (clientKind !== 'mobile' || !pairedDeviceId) { + return { registered: false, reason: 'not_mobile' } + } + // The paired identity is spread last so no parameter can ever override it. + return await runtime.registerMobilePushDevice({ ...params, deviceId: pairedDeviceId }) + } + }), + defineMethod({ + name: 'notifications.testPush', + params: null, + handler: async (_params, { runtime, clientKind, pairedDeviceId }) => { + if (clientKind !== 'mobile' || !pairedDeviceId) { + return { accepted: false, reason: 'not_registered' } + } + return await runtime.testMobilePushDevice(pairedDeviceId) + } + }), + defineMethod({ + name: 'notifications.unregisterPush', + params: null, + // Deleting the gateway token is durable (outbox), so an offline gateway still + // reports success to the phone that asked to stop being pushed to. + handler: async (_params, { runtime, clientKind, pairedDeviceId }) => { + if (clientKind !== 'mobile' || !pairedDeviceId) { + return { unregistered: false } + } + return await runtime.unregisterMobilePushDevice(pairedDeviceId) } }) ] diff --git a/src/main/runtime/rpc/methods/orchestration.ts b/src/main/runtime/rpc/methods/orchestration.ts index ed89ae4519d..ab80b91e830 100644 --- a/src/main/runtime/rpc/methods/orchestration.ts +++ b/src/main/runtime/rpc/methods/orchestration.ts @@ -1,4 +1,3 @@ -import type { RpcMethod } from '../core' import { ORCHESTRATION_RUN_METHODS } from './orchestration/runs/runs' import { ORCHESTRATION_WORKER_METHODS } from './orchestration/worker/worker-methods' import { ORCHESTRATION_FEDERATION_METHODS } from './orchestration/federation/federation-methods' @@ -11,7 +10,7 @@ import { ORCHESTRATION_ASK_METHODS } from './orchestration/messaging/ask-methods import { ORCHESTRATION_GATE_METHODS } from './orchestration/gates/gates' import { ORCHESTRATION_RESET_METHODS } from './orchestration/runs/reset-methods' -export const ORCHESTRATION_METHODS: RpcMethod[] = [ +export const ORCHESTRATION_METHODS = [ ...ORCHESTRATION_RUN_METHODS, ...ORCHESTRATION_WORKER_METHODS, ...ORCHESTRATION_FEDERATION_METHODS, diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-release-safety.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/federated-release-safety.test.ts index d5150dc052e..87ac8f65356 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-release-safety.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federated-release-safety.test.ts @@ -3,6 +3,7 @@ import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../../../shared/protoco import { OrcaRuntimeService } from '../../../../orca-runtime' import { OrchestrationDb } from '../../../../orchestration/db' import { ORCHESTRATION_METHODS } from '../../orchestration' +import { eraseRpcMethods } from '../../../core' const HOME_FINGERPRINT = 'home-peer' const PANE_KEY = 'tab_remote:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' @@ -191,7 +192,9 @@ describe('federated worker release ownership', () => { dispatchId: string, params: Record = { dispatchId } ): Promise { - const method = ORCHESTRATION_METHODS.find((candidate) => candidate.name === name) + const method = eraseRpcMethods(ORCHESTRATION_METHODS).find( + (candidate) => candidate.name === name + ) if (!method) { throw new Error(`Method not found: ${name}`) } diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-control.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation-control.ts index 6091c1080fa..caec51d462e 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-control.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federation-control.ts @@ -1,9 +1,6 @@ -import { z } from 'zod' -import { ORCHESTRATION_WORKER_READ_SOURCES } from '../../../../../../shared/orchestration-worker-output' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import type { RemoteDispatchAttachmentRow } from '../../../../orchestration/types' -import { defineMethod, type RpcMethod } from '../../../core' -import { OptionalFiniteNumber, requiredString } from '../../../schemas' +import { defineMethod } from '../../../core' import { mapWithConcurrency } from '../../../../../../shared/map-with-concurrency' import { readExactWorkerOutput } from '../worker/worker-output' import { describeUnconfirmedAgentStop } from '../../../../../../shared/pty-liveness-verdict' @@ -12,24 +9,14 @@ import { readRemoteAttachmentArchive, releaseRemoteAttachment } from './federated-worker-release-host' +import { + FederationDispatchParams, + FederationFleetSnapshotParams, + FederationOutputReadParams, + FederationReadParams +} from '../../../../../../shared/rpc-contract/orchestration-federation-control-params' -const FederationDispatchParams = z.object({ - dispatchId: requiredString('Missing Dispatch ID') -}) -const FederationReadParams = FederationDispatchParams.extend({ - cursor: OptionalFiniteNumber, - limit: OptionalFiniteNumber -}) -const FederationOutputReadParams = FederationDispatchParams.extend({ - cursor: z.union([z.number().int().nonnegative(), z.string().min(1).max(2_048)]).optional(), - limit: OptionalFiniteNumber, - source: z.enum(ORCHESTRATION_WORKER_READ_SOURCES).optional() -}) -const FederationFleetSnapshotParams = z.object({ - dispatchIds: z.array(requiredString('Missing Dispatch ID')).min(1).max(100) -}) - -export const ORCHESTRATION_FEDERATION_CONTROL_METHODS: RpcMethod[] = [ +export const ORCHESTRATION_FEDERATION_CONTROL_METHODS = [ defineMethod({ name: 'orchestration.federationFleetSnapshot', params: FederationFleetSnapshotParams, diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-liveness-verdict.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation-liveness-verdict.test.ts index 7c75c52eb6c..dc5989fff2a 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-liveness-verdict.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federation-liveness-verdict.test.ts @@ -4,6 +4,7 @@ import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../../../shared/protoco import { OrcaRuntimeService } from '../../../../orca-runtime' import { OrchestrationDb } from '../../../../orchestration/db' import { ORCHESTRATION_METHODS } from '../../orchestration' +import { eraseRpcMethods } from '../../../core' // The federation host runs its own copy of the observation and stop logic, so // it needs the same rule: lost contact with a worker's host is not an exit, and @@ -87,7 +88,9 @@ describe('federation host liveness verdicts', () => { afterEach(() => db.close()) async function call(name: string, params: Record) { - const method = ORCHESTRATION_METHODS.find((candidate) => candidate.name === name) + const method = eraseRpcMethods(ORCHESTRATION_METHODS).find( + (candidate) => candidate.name === name + ) if (!method) { throw new Error(`Method not found: ${name}`) } @@ -138,7 +141,9 @@ describe('federation host liveness verdicts', () => { }) hostDb.markRemoteAttachmentReady(DISPATCH_ID) const callHost = async (name: string, params: Record) => { - const method = ORCHESTRATION_METHODS.find((candidate) => candidate.name === name) + const method = eraseRpcMethods(ORCHESTRATION_METHODS).find( + (candidate) => candidate.name === name + ) if (!method) { throw new Error(`Method not found: ${name}`) } diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-methods.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation-methods.ts index fbdbda6c7ca..589b69f3934 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federation-methods.ts @@ -1,9 +1,8 @@ -import type { RpcMethod } from '../../../core' import { ORCHESTRATION_FEDERATION_CONTROL_METHODS } from './federation-control' import { ORCHESTRATION_FEDERATION_RELAY_METHODS } from './federation-relay' import { ORCHESTRATION_FEDERATION_ATTACH_METHODS } from './federation' -export const ORCHESTRATION_FEDERATION_METHODS: RpcMethod[] = [ +export const ORCHESTRATION_FEDERATION_METHODS = [ ...ORCHESTRATION_FEDERATION_ATTACH_METHODS, ...ORCHESTRATION_FEDERATION_RELAY_METHODS, ...ORCHESTRATION_FEDERATION_CONTROL_METHODS diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-relay.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation-relay.ts index 8cb4e08f2f3..721232f194a 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-relay.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federation-relay.ts @@ -1,4 +1,3 @@ -import { z } from 'zod' import { ORCHESTRATION_FEDERATION_CONTROL_MAIL_PROTOCOL_VERSION } from '../../../../../../shared/protocol-version' import { importFederatedControlMessage } from '../../../../orchestration/federation-control-message' import { OrchestrationError } from '../../../../orchestration/orchestration-error' @@ -8,54 +7,13 @@ import { type FederatedLifecycleSettlement } from '../../../../orchestration/federation-lifecycle-settlement' import { defineMethod, type RpcMethod } from '../../../core' -import { OptionalFiniteNumber, requiredString } from '../../../schemas' +import { + FederationAckParams, + FederationImportParams, + FederationPullParams +} from '../../../../../../shared/rpc-contract/orchestration-federation-relay-params' -const FederationPullParams = z.object({ - dispatchId: requiredString('Missing Dispatch ID'), - afterSequence: OptionalFiniteNumber, - replayUnacknowledged: z.boolean().optional(), - limit: OptionalFiniteNumber -}) - -const FederationAckParams = z.object({ - dispatchId: requiredString('Missing Dispatch ID'), - throughSequence: z.number().int().nonnegative(), - settlements: z - .array( - z.object({ - sequence: z.number().int().positive(), - lifecycle: z.discriminatedUnion('action', [ - z.object({ - action: z.enum(['completed', 'failed']), - authority: z.literal('run_home') - }), - z.object({ - action: z.literal('rejected'), - code: z.string(), - reason: z.string(), - authority: z.literal('run_home') - }) - ]) - }) - ) - .optional() -}) - -const FederationImportParams = z.object({ - dispatchId: requiredString('Missing Dispatch ID'), - items: z.array( - z.object({ - dispatch_id: requiredString('Missing item Dispatch ID'), - direction: z.literal('to_worker'), - sequence: z.number().int().positive(), - message_id: requiredString('Missing relay message ID'), - kind: requiredString('Missing relay kind'), - payload: requiredString('Missing relay payload') - }) - ) -}) - -export const ORCHESTRATION_FEDERATION_RELAY_METHODS: RpcMethod[] = [ +export const ORCHESTRATION_FEDERATION_RELAY_METHODS = [ defineMethod({ name: 'orchestration.federationPull', params: FederationPullParams, diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-start-schema.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation-start-schema.ts index 84ed57d58cc..89b55c86a4c 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-start-schema.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federation-start-schema.ts @@ -1,31 +1,5 @@ -import { z } from 'zod' -import { OptionalFiniteNumber, OptionalString, requiredString } from '../../../schemas' -import { OptionalWorkerLaunchPreference } from '../worker/worker-start-schema' - -export const FederationAttachStartParams = z.object({ - /** Omitted by v1.4.198 coordinators; the worker host then mints a stub home Run. */ - runId: OptionalString, - dispatchId: requiredString('Missing Dispatch ID'), - taskId: requiredString('Missing Task ID'), - taskSpec: requiredString('Missing Task spec'), - /** Depth stamped by the Run home; omitted by older clients and defaults to 1. */ - depth: z.number().int().min(1).optional(), - protocolVersion: z.union([z.literal(1), z.literal(2), z.literal(3)]), - worktree: requiredString('Missing remote worktree selector'), - name: OptionalString, - repo: OptionalString, - baseBranch: OptionalString, - displayName: OptionalString, - displayNameKind: z.enum(['generated', 'user']).optional(), - comment: OptionalString, - setup: z.enum(['run', 'skip', 'inherit']).optional(), - setupSource: z.enum(['explicit_request', 'orchestration_default']).optional(), - terminal: OptionalString, - agent: OptionalString, - model: OptionalWorkerLaunchPreference, - effort: OptionalWorkerLaunchPreference, - timeoutMs: OptionalFiniteNumber, - devMode: z.boolean().optional() -}) +import type { z } from 'zod' +import { FederationAttachStartParams } from '../../../../../../shared/rpc-contract/orchestration-federation-start-params' +export { FederationAttachStartParams } export type FederationAttachStartInput = z.infer diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation.ts index 785f6a67eec..8d9d92547c8 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federation.ts @@ -1,7 +1,8 @@ import type { TuiAgent } from '../../../../../../shared/tui-agent' +import { describeTerminalWaitBlockedReason } from '../../../../../../shared/terminal-wait-blocked-reason-legacy-alias' import { buildDispatchPreamble } from '../../../../orchestration/preamble' import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { defineMethod, type RpcMethod } from '../../../core' +import { defineMethod } from '../../../core' import { assertOrchestrationWorktreeCreationSupported } from '../worker/folder-worktree-placement' import { appendFederationSetupEffect, @@ -24,7 +25,7 @@ import { } from '../../../../../../shared/orchestration-timing-budgets' import { assertWorkerStartTaskSpecWithinPromptBudget } from '../worker/worker-start-prompt-budget' -export const ORCHESTRATION_FEDERATION_ATTACH_METHODS: RpcMethod[] = [ +export const ORCHESTRATION_FEDERATION_ATTACH_METHODS = [ defineMethod({ name: 'orchestration.federationAttachStart', params: FederationAttachStartParams, @@ -222,7 +223,7 @@ export const ORCHESTRATION_FEDERATION_ATTACH_METHODS: RpcMethod[] = [ } throw new Error( wait.blockedReason - ? `Agent startup blocked: ${wait.blockedReason}` + ? `Agent startup blocked: ${describeTerminalWaitBlockedReason(wait.blockedReason)}` : `Agent did not become ready (${wait.status}).` ) } diff --git a/src/main/runtime/rpc/methods/orchestration/gates/gates.ts b/src/main/runtime/rpc/methods/orchestration/gates/gates.ts index 76bfd23b76e..29be91b4324 100644 --- a/src/main/runtime/rpc/methods/orchestration/gates/gates.ts +++ b/src/main/runtime/rpc/methods/orchestration/gates/gates.ts @@ -1,49 +1,22 @@ -import { z } from 'zod' -import { defineMethod, type RpcMethod } from '../../../core' -import { OptionalFiniteNumber, OptionalString, requiredString } from '../../../schemas' +import { defineMethod } from '../../../core' import type { GateStatus } from '../../../../orchestration/db' import { Coordinator } from '../../../../orchestration/coordinator' import { resolveRunScope } from '../runs/run-scope' import { taskNotFoundError } from '../../../../orchestration/task-dispatch-refusal' +import { + GateCreateParams, + GateListParams, + GateResolveParams, + RunParams, + RunStopParams +} from '../../../../../../shared/rpc-contract/orchestration-gates-params' // Why: the coordinator instance is stored at module scope so orchestration.runStop // can signal it to halt. Only one coordinator can run at a time (enforced by // the DB's active-run check), so a single reference suffices. let activeCoordinator: Coordinator | null = null -const RunParams = z.object({ - spec: requiredString('Missing --spec'), - from: OptionalString, - pollIntervalMs: OptionalFiniteNumber, - maxConcurrent: OptionalFiniteNumber, - worktree: OptionalString -}) - -const RunStopParams = z.object({}) - -const GateCreateParams = z.object({ - task: requiredString('Missing --task'), - question: requiredString('Missing --question'), - options: OptionalString, - from: OptionalString, - run: OptionalString -}) - -const GateResolveParams = z.object({ - id: requiredString('Missing --id'), - resolution: requiredString('Missing --resolution'), - from: OptionalString, - run: OptionalString -}) - -const GateListParams = z.object({ - task: OptionalString, - status: z.enum(['pending', 'resolved', 'timeout']).optional(), - from: OptionalString, - run: OptionalString -}) - -export const ORCHESTRATION_GATE_METHODS: RpcMethod[] = [ +export const ORCHESTRATION_GATE_METHODS = [ // Why: Section 4.12 — orchestration.run returns immediately with a run ID. // The coordinator loop runs in the background; progress is queried via // orchestration.taskList. This prevents the RPC call from blocking the diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/ask-methods.ts b/src/main/runtime/rpc/methods/orchestration/messaging/ask-methods.ts index f622cc9e67a..ef191250a8b 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/ask-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/ask-methods.ts @@ -1,4 +1,4 @@ -import { defineMethod, type RpcMethod } from '../../../core' +import { defineMethod } from '../../../core' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import { clampOrchestrationAskTimeoutMs } from '../../../../../../shared/orchestration-ask-timeout' import { isGroupAddress } from '../../../../orchestration/groups' @@ -6,7 +6,7 @@ import { AskParams } from '../schemas' import { rejectFederatedExplicitTarget } from '../routing' import { askRemoteRunHome } from './ask-remote' -export const ORCHESTRATION_ASK_METHODS: RpcMethod[] = [ +export const ORCHESTRATION_ASK_METHODS = [ defineMethod({ name: 'orchestration.ask', params: AskParams, diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/check-methods.ts b/src/main/runtime/rpc/methods/orchestration/messaging/check-methods.ts index a12428253c3..20ac25e6512 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/check-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/check-methods.ts @@ -1,4 +1,4 @@ -import { defineMethod, type RpcMethod } from '../../../core' +import { defineMethod } from '../../../core' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import { CheckParams } from '../schemas' import { parseMessageTypes } from '../routing' @@ -12,7 +12,7 @@ import { isSupersededDispatch } from './dispatch-mailbox-fence' -export const ORCHESTRATION_CHECK_METHODS: RpcMethod[] = [ +export const ORCHESTRATION_CHECK_METHODS = [ defineMethod({ name: 'orchestration.check', params: CheckParams, diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts b/src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts index 58e0b3aa0ca..f0d5e4933a6 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import { ORCHESTRATION_METHODS } from '../../orchestration' -import type { RpcContext } from '../../../core' +import { eraseRpcMethods, type RpcContext } from '../../../core' import { OrchestrationDb } from '../../../../orchestration/db' import { OrcaRuntimeService } from '../../../../orca-runtime' import { @@ -55,7 +55,9 @@ describe('orchestration.check on a federated attachment across a restart', () => } function check(ctx: RpcContext, params: Record = {}): Promise { - const method = ORCHESTRATION_METHODS.find((entry) => entry.name === 'orchestration.check') + const method = eraseRpcMethods(ORCHESTRATION_METHODS).find( + (entry) => entry.name === 'orchestration.check' + ) if (!method) { throw new Error('orchestration.check is not registered') } diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/message-methods.ts b/src/main/runtime/rpc/methods/orchestration/messaging/message-methods.ts index 61808c19aed..51a9d9bc0c5 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/message-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/message-methods.ts @@ -1,4 +1,4 @@ -import { defineMethod, type RpcMethod } from '../../../core' +import { defineMethod } from '../../../core' import type { TaskStatus } from '../../../../orchestration/db' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import { ORCHESTRATION_LEGACY_RUN_ID } from '../../../../../../shared/orchestration-rpc-contract' @@ -19,7 +19,7 @@ import { TaskUpdateParams } from '../schemas' -export const ORCHESTRATION_MESSAGE_METHODS: RpcMethod[] = [ +export const ORCHESTRATION_MESSAGE_METHODS = [ defineMethod({ name: 'orchestration.reply', params: ReplyParams, diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts b/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts index 567149e69d8..7d1edb77602 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts @@ -1,4 +1,4 @@ -import { defineMethod, type RpcMethod } from '../../../core' +import { defineMethod } from '../../../core' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import { isGroupAddress } from '../../../../orchestration/groups' import { orchestrationSkillRecoveryData } from '../../../../../../shared/orchestration-rpc-contract' @@ -20,7 +20,7 @@ import { sendPointToPointMessage } from './send-point-to-point' import { sendGroupMessage } from './send-group' import { sendFederatedControlMail } from './send-control-mail' -export const ORCHESTRATION_SEND_METHODS: RpcMethod[] = [ +export const ORCHESTRATION_SEND_METHODS = [ defineMethod({ name: 'orchestration.send', params: SendParams, diff --git a/src/main/runtime/rpc/methods/orchestration/rpc-test-harness.ts b/src/main/runtime/rpc/methods/orchestration/rpc-test-harness.ts index dfba4bd143f..19e636eca21 100644 --- a/src/main/runtime/rpc/methods/orchestration/rpc-test-harness.ts +++ b/src/main/runtime/rpc/methods/orchestration/rpc-test-harness.ts @@ -1,6 +1,6 @@ import { vi } from 'vitest' import { ORCHESTRATION_METHODS } from '../orchestration' -import type { RpcContext } from '../../core' +import { eraseRpcMethods, type RpcContext } from '../../core' import { OrchestrationDb } from '../../../orchestration/db' import { OrcaRuntimeService } from '../../../orca-runtime' @@ -66,7 +66,7 @@ export function createOrchestrationRpcHarness() { } function findMethod(name: string) { - const method = ORCHESTRATION_METHODS.find((m) => m.name === name) + const method = eraseRpcMethods(ORCHESTRATION_METHODS).find((m) => m.name === name) if (!method) { throw new Error(`Method not found: ${name}`) } diff --git a/src/main/runtime/rpc/methods/orchestration/runs/dispatch-methods.ts b/src/main/runtime/rpc/methods/orchestration/runs/dispatch-methods.ts index abc941bf98c..a4e6b427d7d 100644 --- a/src/main/runtime/rpc/methods/orchestration/runs/dispatch-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/runs/dispatch-methods.ts @@ -1,4 +1,4 @@ -import { defineMethod, type RpcMethod } from '../../../core' +import { defineMethod } from '../../../core' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import { buildDispatchPreamble } from '../../../../orchestration/preamble' import { resolveDispatchCreator } from './dispatch-creator' @@ -10,7 +10,7 @@ import { import { resolveRunScope } from './run-scope' import { DispatchParams, DispatchShowParams } from '../schemas' -export const ORCHESTRATION_DISPATCH_METHODS: RpcMethod[] = [ +export const ORCHESTRATION_DISPATCH_METHODS = [ defineMethod({ name: 'orchestration.dispatch', params: DispatchParams, diff --git a/src/main/runtime/rpc/methods/orchestration/runs/mutation-request-show.ts b/src/main/runtime/rpc/methods/orchestration/runs/mutation-request-show.ts index 5dd72b61c6e..a1cf43ab424 100644 --- a/src/main/runtime/rpc/methods/orchestration/runs/mutation-request-show.ts +++ b/src/main/runtime/rpc/methods/orchestration/runs/mutation-request-show.ts @@ -2,13 +2,10 @@ import { describeMutationRequestState, type OrchestrationMutationRequestShowResult } from '../../../../../../shared/orchestration-mutation-request' -import { defineMethod, type RpcMethod } from '../../../core' -import { requiredString } from '../../../schemas' -import { z } from 'zod' +import { defineMethod } from '../../../core' +import { RequestShowParams } from '../../../../../../shared/rpc-contract/orchestration-runs-mutation-request-show-params' -const RequestShowParams = z.object({ request: requiredString('Missing --request') }) - -export const ORCHESTRATION_MUTATION_REQUEST_METHODS: RpcMethod[] = [ +export const ORCHESTRATION_MUTATION_REQUEST_METHODS = [ defineMethod({ name: 'orchestration.requestShow', params: RequestShowParams, diff --git a/src/main/runtime/rpc/methods/orchestration/runs/reset-methods.ts b/src/main/runtime/rpc/methods/orchestration/runs/reset-methods.ts index b4be53ecad5..6946606651f 100644 --- a/src/main/runtime/rpc/methods/orchestration/runs/reset-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/runs/reset-methods.ts @@ -1,7 +1,7 @@ -import { defineMethod, type RpcMethod } from '../../../core' +import { defineMethod } from '../../../core' import { ResetParams } from '../schemas' -export const ORCHESTRATION_RESET_METHODS: RpcMethod[] = [ +export const ORCHESTRATION_RESET_METHODS = [ defineMethod({ name: 'orchestration.reset', params: ResetParams, diff --git a/src/main/runtime/rpc/methods/orchestration/runs/runs.ts b/src/main/runtime/rpc/methods/orchestration/runs/runs.ts index 77bcea4924c..eab6eb2913e 100644 --- a/src/main/runtime/rpc/methods/orchestration/runs/runs.ts +++ b/src/main/runtime/rpc/methods/orchestration/runs/runs.ts @@ -1,30 +1,16 @@ -import { z } from 'zod' -import { defineMethod, type RpcMethod } from '../../../core' -import { OptionalBoolean, OptionalString, requiredString } from '../../../schemas' -import { ORCHESTRATION_RUN_PAGE_LIMIT } from '../../../../../../shared/orchestration-run-pagination' +import { defineMethod } from '../../../core' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import { assertCallerHandleMatchesEvidence, resolveOrchestrationCaller } from './run-scope' import { exposeRun } from './run-receipt' +import { + RunCreateParams, + RunCurrentParams, + RunListParams, + RunShowParams, + RunUseParams +} from '../../../../../../shared/rpc-contract/orchestration-runs-params' -const RunCreateParams = z.object({ - objective: requiredString('Missing --objective'), - from: requiredString('Missing coordinator terminal') -}) - -const RunUseParams = z.object({ - id: requiredString('Missing --id'), - from: requiredString('Missing coordinator terminal'), - takeoverLegacy: OptionalBoolean -}) - -const RunCurrentParams = z.object({ from: requiredString('Missing coordinator terminal') }) -const RunListParams = z.object({ - limit: z.number().int().min(1).max(ORCHESTRATION_RUN_PAGE_LIMIT).optional(), - cursor: z.string().min(1).optional() -}) -const RunShowParams = z.object({ id: requiredString('Missing --id'), from: OptionalString }) - -export const ORCHESTRATION_RUN_METHODS: RpcMethod[] = [ +export const ORCHESTRATION_RUN_METHODS = [ defineMethod({ name: 'orchestration.runCreate', params: RunCreateParams, diff --git a/src/main/runtime/rpc/methods/orchestration/schemas.ts b/src/main/runtime/rpc/methods/orchestration/schemas.ts index 51b51137475..eae80849ffc 100644 --- a/src/main/runtime/rpc/methods/orchestration/schemas.ts +++ b/src/main/runtime/rpc/methods/orchestration/schemas.ts @@ -1,15 +1,26 @@ import { z } from 'zod' import { setImmediate as yieldToEventLoop } from 'node:timers/promises' -import { - OptionalFiniteNumber, - OptionalString, - OptionalBoolean, - requiredString -} from '../../schemas' +import { OptionalString, OptionalBoolean, requiredString } from '../../schemas' import type { TaskStatus } from '../../../orchestration/db' import { isGroupAddress } from '../../../orchestration/groups' import { MESSAGE_TYPES } from '../../../orchestration/types' import { OrchestrationError } from '../../../orchestration/orchestration-error' +import { + getLifecycleGroupRecipientError, + isDispatchMutationMessageType +} from '../../../../../shared/rpc-contract/orchestration-params' +export { + AskParams, + CheckParams, + DispatchParams, + DispatchShowParams, + InboxParams, + ReplyParams, + ResetParams, + TaskCreateParams, + TaskListParams +} from '../../../../../shared/rpc-contract/orchestration-params' +export { getLifecycleGroupRecipientError, isDispatchMutationMessageType } export const TASK_STATUSES: TaskStatus[] = [ 'pending', @@ -44,27 +55,6 @@ const SEND_MESSAGE_TYPE_ERROR = [ 'To answer a worker question, use the same Orca CLI executable with orchestration reply --id --body .' ].join(' ') -export type DispatchMutationMessageType = - | 'worker_done' - | 'heartbeat' - | 'escalation' - | 'decision_gate' - -export function isDispatchMutationMessageType( - type: string | undefined -): type is DispatchMutationMessageType { - return ( - type === 'worker_done' || - type === 'heartbeat' || - type === 'escalation' || - type === 'decision_gate' - ) -} - -export function getLifecycleGroupRecipientError(type: DispatchMutationMessageType): string { - return `${type} messages belong to one exact Dispatch and cannot target a group address.` -} - export function parseRemoteWorkerPayload(payload: string | undefined): Record { if (!payload) { return {} @@ -131,73 +121,6 @@ export const SendParams = z }) }) -export const CheckParams = z - .object({ - terminal: OptionalString, - terminalPaneKey: OptionalString, - unread: OptionalBoolean, - peek: OptionalBoolean, - // Why: `all` surfaces every message and skips mark-read; legacy encoding was the `{unread: false}` trick (design doc §3.2/§3.3). - all: OptionalBoolean, - types: OptionalString, - format: OptionalBoolean, - // Why: one-release RPC compatibility only; the public CLI uses --format because no terminal input is injected. - inject: OptionalBoolean, - ack: OptionalString, - compatibilityAck: OptionalString, - compatibilityQuestionAck: OptionalString, - compatibilityCliCommand: z.enum(['orca', 'orca-ide', 'orca-dev']).optional(), - run: OptionalString, - wait: OptionalBoolean, - timeoutMs: OptionalFiniteNumber - }) - .superRefine((params, ctx) => { - // Why: CLI encodes --peek as {peek:true, unread:false} for pre-peek runtimes, so that pair is one mode, not a conflict. - const modes = [ - params.unread === true, - params.peek === true, - params.all === true || (params.unread === false && params.peek !== true) - ].filter(Boolean) - if (modes.length > 1) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: 'Choose at most one message read mode: --unread, --peek, or --all.' - }) - } - }) - -export const ReplyParams = z.object({ - id: requiredString('Missing --id'), - body: requiredString('Missing --body'), - from: OptionalString, - run: OptionalString -}) - -export const InboxParams = z.object({ - limit: OptionalFiniteNumber, - // Why: filters the inbox to a handle so inbox and check --all give agreeing results (design doc §3.3). - terminal: OptionalString -}) - -export const TaskCreateParams = z.object({ - spec: requiredString('Missing --spec'), - taskTitle: OptionalString, - displayName: OptionalString, - deps: OptionalString, - parent: OptionalString, - callerTerminalHandle: OptionalString, - run: OptionalString -}) - -export const TaskListParams = z.object({ - status: z.enum(['pending', 'ready', 'dispatched', 'completed', 'failed', 'blocked']).optional(), - ready: OptionalBoolean, - // Why: server-side truncation keeps --brief cheap over SSH/relay instead of shipping full specs the CLI throws away. - brief: OptionalBoolean, - run: OptionalString, - callerTerminalHandle: OptionalString -}) - export const TaskUpdateParams = z.object({ id: requiredString('Missing --id'), status: z @@ -217,61 +140,4 @@ export const TaskUpdateParams = z.object({ run: OptionalString, callerTerminalHandle: OptionalString }) - -export const DispatchParams = z.object({ - task: requiredString('Missing --task'), - // Why: --to is optional so --dry-run can preview without a target; the handler enforces presence before any side-effecting work. - to: OptionalString, - from: OptionalString, - inject: OptionalBoolean, - dryRun: OptionalBoolean, - returnPreamble: OptionalBoolean, - devMode: OptionalBoolean, - run: OptionalString -}) - -export const DispatchShowParams = z.object({ - task: OptionalString, - preamble: OptionalBoolean, - from: OptionalString, - devMode: OptionalBoolean -}) - -export const AskParams = z - .object({ - to: OptionalString, - question: OptionalString, - resume: OptionalString, - options: OptionalString, - timeoutMs: OptionalFiniteNumber, - from: OptionalString, - run: OptionalString, - compatibilityCliCommand: z.enum(['orca', 'orca-ide', 'orca-dev']).optional(), - compatibilityWindowsCommand: z.enum(['orca', 'orca-ide']).optional() - }) - .superRefine((params, ctx) => { - if ((params.question ? 1 : 0) + (params.resume ? 1 : 0) !== 1) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: 'Choose exactly one of --question or --resume.' - }) - } - }) - -export const ResetParams = z - .object({ - all: OptionalBoolean, - tasks: OptionalBoolean, - messages: OptionalBoolean - }) - .superRefine((params, ctx) => { - const selectedScopeCount = [params.all, params.tasks, params.messages].filter( - (scope) => scope === true - ).length - if (selectedScopeCount !== 1) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: 'Choose exactly one reset scope: --all, --tasks, or --messages.' - }) - } - }) +export type { DispatchMutationMessageType } from '../../../../../shared/rpc-contract/orchestration-params' diff --git a/src/main/runtime/rpc/methods/orchestration/worker/agent-status-producer-census.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/agent-status-producer-census.test.ts index 61a28f4612c..afed92ec8aa 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/agent-status-producer-census.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/agent-status-producer-census.test.ts @@ -97,7 +97,7 @@ const CENSUS: readonly CensusRow[] = [ { path: 'main/orcad/orcad-entry.ts', kind: 'wiring', - role: 'binds the same snapshot and structured sink into the headless orcad runtime deps' + role: 'binds the same snapshot, OSC producer and structured sink into the headless orcad runtime deps' }, { path: 'main/runtime/orca-runtime-state-fields.ts', @@ -157,7 +157,7 @@ const CENSUS: readonly CensusRow[] = [ { path: 'main/runtime/orca-runtime-prune-mobile-session-tab-group-layout.ts', kind: 'consumes', - role: 'mobile tab-group pruning from provider-session rows, and the pane identity accessors' + role: 'mobile tab-group pruning and its live agent row, plus the pane identity accessors' } ] diff --git a/src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts index aee45e25259..c9e0f077bc1 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts @@ -476,9 +476,15 @@ describe('orchestration RPC methods', () => { ) }) - it.each(['codex-update-prompt', 'codex-trust-workspace'] as const)( + // Why the second column: an older host still publishes the codex-* token, and this receipt + // reaches the user verbatim -- so it names the neutral spelling the same way the CLI does. + it.each([ + ['codex-update-prompt', 'codex-update-prompt (agent-update-prompt)'], + ['codex-trust-workspace', 'codex-trust-workspace (agent-trust-workspace)'], + ['agent-trust-workspace', 'agent-trust-workspace'] + ] as const)( 'returns a truthful readiness failure for %s', - async (blockedReason) => { + async (blockedReason, expectedReason) => { setup() mockCurrentWorkerStart() vi.mocked(runtime.waitForTerminal).mockResolvedValueOnce({ @@ -500,7 +506,7 @@ describe('orchestration RPC methods', () => { expect(result).toMatchObject({ state: 'failed', failedStage: 'agent_readiness', - lastError: `Agent startup blocked: ${blockedReason}` + lastError: `Agent startup blocked: ${expectedReason}` }) expect(runtime.sendTerminalAgentPrompt).not.toHaveBeenCalled() } diff --git a/src/main/runtime/rpc/methods/orchestration/worker/fleet-status-observed-identity.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/fleet-status-observed-identity.test.ts index 0e5addf1ba3..8aa6d03ed84 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/fleet-status-observed-identity.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/fleet-status-observed-identity.test.ts @@ -5,9 +5,11 @@ import type { OrcaRuntimeService } from '../../../../orca-runtime' import type { OrchestrationDb } from '../../../../orchestration/db' import { OrcaRuntimeWithGetOrchestrationDispatchAuthority } from '../../../../orca-runtime-get-orchestration-dispatch-authority' import { + AgentStatusObservedPaneIdentityCapture, AgentStatusObservedPaneIdentities, recordObservedAgentStatusPaneIdentity } from '../../../../agent-status-observed-pane-identity' +import type { EnrichedAgentHookEventPayload } from '../../../../../agent-hooks/server/server-types' import { projectFleetWorkerPage } from './worker-observation' /** @@ -135,6 +137,33 @@ function livenessOf(world: ObservedWorld, db: OrchestrationDb, dispatchId: strin } describe('fleet evidence keeps the identity it was observed under', () => { + it('buffers startup observations until terminal recovery is ready', () => { + const identities = new AgentStatusObservedPaneIdentities() + const capture = new AgentStatusObservedPaneIdentityCapture(identities) + const runtime = { + getAgentStatusTerminalHandleForPaneKey: () => TERMINAL_HANDLE, + getTerminalProcessIncarnation: () => INCARNATION_ONE, + getAgentStatusOrchestrationContextForPaneKey: () => undefined + } + const entry = { + paneKey: PANE_KEY, + payload: { state: 'working', prompt: 'startup', agentType: 'claude' }, + receivedAt: 1, + stateStartedAt: 1 + } as EnrichedAgentHookEventPayload + + capture.observe(entry) + expect(identities.read(PANE_KEY)).toEqual({ kind: 'unobserved' }) + + capture.attach(runtime) + expect(identities.read(PANE_KEY)).toEqual({ + kind: 'observed', + terminalHandle: TERMINAL_HANDLE, + processIncarnation: INCARNATION_ONE, + dispatchId: null + }) + }) + it('reads live while the pane still runs the process the row was observed on', () => { const world = createWorld() world.bindPane(PANE_KEY, TERMINAL_HANDLE) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts b/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts index ec188695f5c..f8cd1033c97 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start.ts @@ -1,4 +1,5 @@ import type { OrcaRuntimeService } from '../../../../orca-runtime' +import { describeTerminalWaitBlockedReason } from '../../../../../../shared/terminal-wait-blocked-reason-legacy-alias' import type { OrchestrationDb } from '../../../../orchestration/db' import type { RunRow, TaskRow } from '../../../../orchestration/types' import { resolveDispatchCreator } from '../runs/dispatch-creator' @@ -186,7 +187,7 @@ export async function startLocalWorker(args: { } throw new Error( wait.blockedReason - ? `Agent startup blocked: ${wait.blockedReason}` + ? `Agent startup blocked: ${describeTerminalWaitBlockedReason(wait.blockedReason)}` : structuredSession ? `Setup did not finish before the structured worker started (${wait.status}).` : `Agent did not become ready (${wait.status}).` diff --git a/src/main/runtime/rpc/methods/orchestration/worker/manual-dispatch-observation.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/manual-dispatch-observation.test.ts index 2890fa08938..25da0b311a3 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/manual-dispatch-observation.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/manual-dispatch-observation.test.ts @@ -3,6 +3,7 @@ import { OrcaRuntimeService } from '../../../../orca-runtime' import { OrchestrationDb } from '../../../../orchestration/db' import { ORCHESTRATION_METHODS } from '../../orchestration' import { createRootDispatch } from '../../../../orchestration/db/root-dispatch-test-fixture' +import { eraseRpcMethods } from '../../../core' describe('manual Dispatch observation', () => { let db: OrchestrationDb | undefined @@ -51,7 +52,7 @@ describe('manual Dispatch observation', () => { coordinatorPaneKey }) const task = db.createTask({ spec: 'injected lane', runId: run.id }) - const dispatchMethod = ORCHESTRATION_METHODS.find( + const dispatchMethod = eraseRpcMethods(ORCHESTRATION_METHODS).find( (candidate) => candidate.name === 'orchestration.dispatch' ) if (!dispatchMethod) { @@ -77,7 +78,7 @@ describe('manual Dispatch observation', () => { capability_hash: expect.any(String) }) - const workerShowMethod = ORCHESTRATION_METHODS.find( + const workerShowMethod = eraseRpcMethods(ORCHESTRATION_METHODS).find( (candidate) => candidate.name === 'orchestration.workerShow' ) if (!workerShowMethod) { @@ -132,7 +133,9 @@ describe('manual Dispatch observation', () => { }) const context = { runtime } const call = async (name: string, params: Record) => { - const method = ORCHESTRATION_METHODS.find((candidate) => candidate.name === name) + const method = eraseRpcMethods(ORCHESTRATION_METHODS).find( + (candidate) => candidate.name === name + ) if (!method) { throw new Error(`Missing method ${name}`) } @@ -233,7 +236,7 @@ describe('manual Dispatch observation', () => { const task = db.createTask({ spec: 'operator lane', runId: run.id }) const dispatch = createRootDispatch(db, task.id, 'term_worker', 'tab_worker:leaf_worker') - const workerListMethod = ORCHESTRATION_METHODS.find( + const workerListMethod = eraseRpcMethods(ORCHESTRATION_METHODS).find( (candidate) => candidate.name === 'orchestration.workerList' ) if (!workerListMethod) { @@ -280,7 +283,9 @@ describe('manual Dispatch observation', () => { 'launch-hash', 'runtime_test:term_worker:1' ) - const method = ORCHESTRATION_METHODS.find((candidate) => candidate.name === name) + const method = eraseRpcMethods(ORCHESTRATION_METHODS).find( + (candidate) => candidate.name === name + ) if (!method) { throw new Error(`Missing method ${name}`) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/manual-dispatch-release.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/manual-dispatch-release.test.ts index ee1f5a3162a..e340e51b01d 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/manual-dispatch-release.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/manual-dispatch-release.test.ts @@ -3,6 +3,7 @@ import type Database from '../../../../../sqlite/sync-database' import { OrcaRuntimeService } from '../../../../orca-runtime' import { OrchestrationDb } from '../../../../orchestration/db' import { ORCHESTRATION_METHODS } from '../../orchestration' +import { eraseRpcMethods } from '../../../core' const COORDINATOR = 'term_coordinator' const TARGET = 'term_target' @@ -177,7 +178,9 @@ describe('manual Dispatch release', () => { } async function call(name: string, params: Record): Promise { - const method = ORCHESTRATION_METHODS.find((candidate) => candidate.name === name) + const method = eraseRpcMethods(ORCHESTRATION_METHODS).find( + (candidate) => candidate.name === name + ) if (!method) { throw new Error(`Method not found: ${name}`) } diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-control.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-control.ts index cf08ce31f69..5e8babf3c5e 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-control.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-control.ts @@ -1,9 +1,6 @@ -import { z } from 'zod' -import { ORCHESTRATION_WORKER_READ_SOURCES } from '../../../../../../shared/orchestration-worker-output' import { contextOnlyAbandonWarning } from '../../../../orchestration/context-only-dispatch-release' import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { defineMethod, type RpcMethod } from '../../../core' -import { OptionalFiniteNumber, requiredString } from '../../../schemas' +import { defineMethod } from '../../../core' import { exposeDispatchContext, exposeObservation, @@ -20,14 +17,12 @@ import { readExactWorkerOutput } from './worker-output' import { exposeWorkerTerminalResource } from './worker-release-completion' import { readFederatedWorkerOutput } from '../federation/federated-worker-read' import { showFederatedWorker } from '../federation/federated-worker-show' -const WorkerDispatchParams = z.object({ dispatch: requiredString('Missing --dispatch') }) -const WorkerReadParams = WorkerDispatchParams.extend({ - cursor: z.union([z.number().int().nonnegative(), z.string().min(1).max(2_048)]).optional(), - limit: OptionalFiniteNumber, - source: z.enum(ORCHESTRATION_WORKER_READ_SOURCES).optional() -}) +import { + WorkerDispatchParams, + WorkerReadParams +} from '../../../../../../shared/rpc-contract/orchestration-worker-control-params' -export const ORCHESTRATION_WORKER_CONTROL_METHODS: RpcMethod[] = [ +export const ORCHESTRATION_WORKER_CONTROL_METHODS = [ defineMethod({ name: 'orchestration.workerShow', params: WorkerDispatchParams, diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-list-method.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-list-method.ts index 5c8ae65fa86..c0f8097a690 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-list-method.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-list-method.ts @@ -4,7 +4,7 @@ import type { OrchestrationDb } from '../../../../orchestration/db' import { WORKER_LIST_CURSOR_EXPIRED_MESSAGE } from '../../../../orchestration/db/worker-terminal/worker-terminal-listing' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import type { OrcaRuntimeService } from '../../../../orca-runtime' -import { defineMethod, type RpcMethod } from '../../../core' +import { defineMethod } from '../../../core' import { applyFederatedFleetObservations, readFederatedFleetSnapshots @@ -24,7 +24,7 @@ import { projectWorkerFleet, type WorkerListPageParams } from './worker-list-pro import { exposeWorkerTerminalResource } from './worker-release-completion' import { WORKER_TERMINAL_LIST_STATES, WorkerListParams } from './worker-release-schemas' -export const ORCHESTRATION_WORKER_LIST_METHOD: RpcMethod = defineMethod({ +export const ORCHESTRATION_WORKER_LIST_METHOD = defineMethod({ name: 'orchestration.workerList', params: WorkerListParams, handler: async (params, { runtime }) => { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-methods.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-methods.ts index 238ad12fad8..7c324cdf798 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-methods.ts @@ -1,10 +1,9 @@ -import type { RpcMethod } from '../../../core' import { ORCHESTRATION_WORKER_CONTROL_METHODS } from './worker-control' import { ORCHESTRATION_WORKER_RELEASE_METHODS } from './worker-release' import { ORCHESTRATION_WORKER_STOP_METHODS } from './worker-stop' import { ORCHESTRATION_WORKER_START_METHODS } from './workers' -export const ORCHESTRATION_WORKER_METHODS: RpcMethod[] = [ +export const ORCHESTRATION_WORKER_METHODS = [ ...ORCHESTRATION_WORKER_START_METHODS, ...ORCHESTRATION_WORKER_CONTROL_METHODS, ...ORCHESTRATION_WORKER_STOP_METHODS, diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-mobile-report.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-release-mobile-report.test.ts index 68d40b4a04e..dd4ce2522ea 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-mobile-report.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-release-mobile-report.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' import { TERMINAL_SEND_METHODS } from '../../terminal/terminal-send-method' import { sendTerminalStreamInput } from '../../terminal/terminal-input-delivery' -import { isStreamingMethod, type RpcMethod } from '../../../core' +import { eraseRpcMethods, isStreamingMethod, type RpcMethod } from '../../../core' const h = createOrchestrationWorkerReleaseHarness() beforeEach(() => h.setup()) @@ -93,7 +93,7 @@ it.each(['unary', 'stream'])('mobile %s bytes do no orchestration database work' 'delivered' ) } else { - const method = TERMINAL_SEND_METHODS.find( + const method = eraseRpcMethods(TERMINAL_SEND_METHODS).find( (m): m is RpcMethod => m.name === 'terminal.send' && !isStreamingMethod(m) )! await expect( diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-recovery.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-release-recovery.test.ts index a7481ea3b68..177eb479d42 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-recovery.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-release-recovery.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { OrchestrationDb } from '../../../../orchestration/db' import { reconcileRequestedWorkerTerminalReleases } from '../../../../orchestration/worker-terminal-release-reconciliation' import { OrcaRuntimeService } from '../../../../orca-runtime' -import type { RpcContext } from '../../../core' +import { eraseRpcMethods, type RpcContext } from '../../../core' import { ORCHESTRATION_METHODS } from '../../orchestration' function deferred(): { promise: Promise; resolve: (value: T) => void } { @@ -101,7 +101,9 @@ describe('orchestration worker release recovery', () => { }) async function call(name: string, params: Record) { - const method = ORCHESTRATION_METHODS.find((candidate) => candidate.name === name) + const method = eraseRpcMethods(ORCHESTRATION_METHODS).find( + (candidate) => candidate.name === name + ) if (!method) { throw new Error(`Method not found: ${name}`) } diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-schemas.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-release-schemas.ts index 52310a2fd9b..66eaf2263f9 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-schemas.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-release-schemas.ts @@ -1,24 +1,6 @@ -import { z } from 'zod' -import { ORCHESTRATION_FLEET_PAGE_MAX } from '../../../../../../shared/orchestration-fleet-projection' -import { requiredString } from '../../../schemas' - -export const WorkerDispatchParams = z.object({ dispatch: requiredString('Missing --dispatch') }) -export const WorkerRetainParams = WorkerDispatchParams.strict() - -export const WORKER_TERMINAL_LIST_STATES = [ - 'active', - 'reclaimable', - 'retained', - 'release_pending', - 'release_unknown', - 'released' -] as const - -export const WorkerListParams = z.object({ - run: z.string().min(1).optional(), - terminalState: z.enum(WORKER_TERMINAL_LIST_STATES).optional(), - cursor: z.string().min(1).max(2_048).optional(), - limit: z.number().int().min(1).max(ORCHESTRATION_FLEET_PAGE_MAX).optional(), - includeRemote: z.boolean().optional(), - paginate: z.boolean().optional() -}) +export { + WORKER_TERMINAL_LIST_STATES, + WorkerDispatchParams, + WorkerListParams, + WorkerRetainParams +} from '../../../../../../shared/rpc-contract/orchestration-worker-release-schemas-params' diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release.test-support.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-release.test-support.ts index ff1ea59a263..a13ea320670 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release.test-support.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-release.test-support.ts @@ -1,6 +1,6 @@ import { expect, vi } from 'vitest' import { ORCHESTRATION_METHODS } from '../../orchestration' -import type { RpcContext } from '../../../core' +import { eraseRpcMethods, type RpcContext } from '../../../core' import { OrchestrationDb } from '../../../../orchestration/db' import { OrcaRuntimeService } from '../../../../orca-runtime' @@ -130,7 +130,7 @@ export function createOrchestrationWorkerReleaseHarness(): OrchestrationWorkerRe } function findMethod(name: string) { - const method = ORCHESTRATION_METHODS.find((m) => m.name === name) + const method = eraseRpcMethods(ORCHESTRATION_METHODS).find((m) => m.name === name) if (!method) { throw new Error(`Method not found: ${name}`) } diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-release.ts index e121f1b3f25..f641485e757 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-release.ts @@ -1,6 +1,5 @@ -import { z } from 'zod' import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { defineMethod, type RpcMethod } from '../../../core' +import { defineMethod } from '../../../core' import { releaseFederatedWorker } from '../federation/federated-worker-release' import { ORCHESTRATION_WORKER_LIST_METHOD } from './worker-list-method' import { resolvePinnedFederatedServer } from './worker-observation' @@ -10,8 +9,9 @@ import { type WorkerReleaseReceipt } from './worker-release-completion' import { WorkerDispatchParams, WorkerRetainParams } from './worker-release-schemas' +import { OrchestrationWorkerTerminalUserInputParams } from '../../../../../../shared/rpc-contract/orchestration-worker-release-params' -export const ORCHESTRATION_WORKER_RELEASE_METHODS: RpcMethod[] = [ +export const ORCHESTRATION_WORKER_RELEASE_METHODS = [ defineMethod({ name: 'orchestration.workerRelease', params: WorkerDispatchParams, @@ -135,16 +135,7 @@ export const ORCHESTRATION_WORKER_RELEASE_METHODS: RpcMethod[] = [ // `sessionId` addresses a worker that IS a structured agent session. Its pane key is a random // identity credential that never leaves main, so the caller names the session and the owning // runtime resolves it — a renderer echoing the pane key back would make it learnable. - params: z - .object({ - paneKey: z.string().min(1).optional(), - sessionId: z.string().min(1).optional(), - terminal: z.string().min(1).optional() - }) - .refine( - (value) => Boolean(value.paneKey ?? value.sessionId ?? value.terminal), - 'Missing paneKey, sessionId or terminal' - ), + params: OrchestrationWorkerTerminalUserInputParams, // Real user keystrokes durably relinquish orchestration ownership on the owning runtime, so // restarts, SSH drops, remote viewing, and renderer remounts cannot erase the takeover. handler: (params, { runtime }) => { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-schema.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-schema.ts index 2f9d9456609..b0f5328801d 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-schema.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-schema.ts @@ -1,63 +1,6 @@ -import { z } from 'zod' -import { OptionalFiniteNumber, OptionalString, requiredString } from '../../../schemas' - -export const OptionalWorkerLaunchPreference = z - .string() - .min(1) - .max(512) - .refine((value) => value === value.trim(), 'Surrounding whitespace is invalid') - .optional() - -export const WorkerStartParams = z - .object({ - task: OptionalString, - spec: OptionalString, - taskTitle: OptionalString, - deps: OptionalString, - parent: OptionalString, - on: OptionalString, - run: OptionalString, - from: requiredString('Missing --from'), - worktree: OptionalString, - name: OptionalString, - repo: OptionalString, - baseBranch: OptionalString, - displayName: OptionalString, - comment: OptionalString, - setup: z.enum(['run', 'skip', 'inherit']).optional(), - terminal: OptionalString, - agent: OptionalString, - model: OptionalWorkerLaunchPreference, - effort: OptionalWorkerLaunchPreference, - retryOf: OptionalString, - timeoutMs: OptionalFiniteNumber, - devMode: z.boolean().optional() - }) - .superRefine((params, ctx) => { - if (!params.task && !params.spec) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: ['task'], - message: 'Missing --task or --spec' - }) - } - if (params.task && params.spec) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: ['spec'], - message: '--task and --spec are mutually exclusive' - }) - } - // Why: --spec creates a new Task, so a retry link to a prior Dispatch could never resolve and - // the refusal named a Task id the caller never supplied. - if (params.retryOf && params.spec) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: ['retryOf'], - message: - '--retry-of needs --task naming the failed Task; --spec creates a new one' - }) - } - }) +import type { z } from 'zod' +import { WorkerStartParams } from '../../../../../../shared/rpc-contract/orchestration-worker-start-params' +export { OptionalWorkerLaunchPreference } from '../../../../../../shared/rpc-contract/orchestration-worker-start-params' +export { WorkerStartParams } export type WorkerStartInput = z.infer diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-liveness-verdict.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-liveness-verdict.test.ts index f0b65281df1..c8dec854e4c 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-liveness-verdict.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-liveness-verdict.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { OrcaRuntimeService } from '../../../../orca-runtime' import { OrchestrationDb } from '../../../../orchestration/db' import { ORCHESTRATION_METHODS } from '../../orchestration' +import { eraseRpcMethods } from '../../../core' // The aggregate terminal inventory only iterates registered providers, so a // dropped relay clears `connected` for every remote PTY at once. That is lost @@ -29,7 +30,9 @@ describe('worker-stop against a terminal we lost contact with', () => { afterEach(() => db.close()) async function call(name: string, params: Record) { - const method = ORCHESTRATION_METHODS.find((candidate) => candidate.name === name) + const method = eraseRpcMethods(ORCHESTRATION_METHODS).find( + (candidate) => candidate.name === name + ) if (!method) { throw new Error(`Method not found: ${name}`) } diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-stop.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-stop.ts index 643323cf62e..98d3c376f61 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-stop.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-stop.ts @@ -1,7 +1,5 @@ -import { z } from 'zod' import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { defineMethod, type RpcMethod } from '../../../core' -import { requiredString } from '../../../schemas' +import { defineMethod } from '../../../core' import { describeUnconfirmedAgentStop } from '../../../../../../shared/pty-liveness-verdict' import { ORCHESTRATION_WORKER_STOP_VERDICT_RUNTIME_CAPABILITY } from '../../../../../../shared/protocol-version' import type { RuntimeStatus } from '../../../../../../shared/runtime-types' @@ -12,10 +10,9 @@ import { stopStructuredWorker } from '../../orchestration-structured-worker-lifecycle' import { isStructuredWorkerHandle } from '../../../../structured-worker-identity' +import { WorkerDispatchParams } from '../../../../../../shared/rpc-contract/orchestration-worker-stop-params' -const WorkerDispatchParams = z.object({ dispatch: requiredString('Missing --dispatch') }) - -export const ORCHESTRATION_WORKER_STOP_METHODS: RpcMethod[] = [ +export const ORCHESTRATION_WORKER_STOP_METHODS = [ defineMethod({ name: 'orchestration.workerStop', params: WorkerDispatchParams, diff --git a/src/main/runtime/rpc/methods/orchestration/worker/workers-recovery.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/workers-recovery.test.ts index a635a316b23..9e95d7f33e2 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/workers-recovery.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/workers-recovery.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { OrcaRuntimeService } from '../../../../orca-runtime' import { OrchestrationDb } from '../../../../orchestration/db' import { ORCHESTRATION_METHODS } from '../../orchestration' +import { eraseRpcMethods } from '../../../core' function deferred(): { promise: Promise; resolve: (value: T) => void } { let resolve!: (value: T) => void @@ -46,7 +47,9 @@ describe('orchestration worker recovery', () => { afterEach(() => db.close()) async function call(name: string, params: Record) { - const method = ORCHESTRATION_METHODS.find((candidate) => candidate.name === name) + const method = eraseRpcMethods(ORCHESTRATION_METHODS).find( + (candidate) => candidate.name === name + ) if (!method) { throw new Error(`Method not found: ${name}`) } diff --git a/src/main/runtime/rpc/methods/orchestration/worker/workers.ts b/src/main/runtime/rpc/methods/orchestration/worker/workers.ts index 8b14ec044cf..b1a1f40d45a 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/workers.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/workers.ts @@ -1,5 +1,5 @@ import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { defineMethod, type RpcMethod } from '../../../core' +import { defineMethod } from '../../../core' import { startFederatedWorker } from '../federation/federated-worker-start' import { startLocalWorker } from './local-worker-start' import { @@ -14,7 +14,7 @@ import { } from '../../../../../../shared/orchestration-timing-budgets' import { assertWorkerStartTaskSpecWithinPromptBudget } from './worker-start-prompt-budget' -export const ORCHESTRATION_WORKER_START_METHODS: RpcMethod[] = [ +export const ORCHESTRATION_WORKER_START_METHODS = [ defineMethod({ name: 'orchestration.workerStart', params: WorkerStartParams, diff --git a/src/main/runtime/rpc/methods/pairing.ts b/src/main/runtime/rpc/methods/pairing.ts index 7762881ba37..5a32ddab62f 100644 --- a/src/main/runtime/rpc/methods/pairing.ts +++ b/src/main/runtime/rpc/methods/pairing.ts @@ -1,10 +1,10 @@ -import { defineMethod, type RpcAnyMethod } from '../core' +import { defineMethod } from '../core' import { PairingGetEndpointsParamsSchema, PairingProvisionRelayParamsSchema } from '../../../../shared/mobile-relay-credential-contract' -export const PAIRING_METHODS: readonly RpcAnyMethod[] = [ +export const PAIRING_METHODS = [ defineMethod({ name: 'pairing.getEndpoints', params: PairingGetEndpointsParamsSchema, diff --git a/src/main/runtime/rpc/methods/plugins.test.ts b/src/main/runtime/rpc/methods/plugins.test.ts index bf67d29f19a..e44570bab56 100644 --- a/src/main/runtime/rpc/methods/plugins.test.ts +++ b/src/main/runtime/rpc/methods/plugins.test.ts @@ -1,12 +1,12 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import type { RpcContext, RpcMethod } from '../core' +import { eraseRpcMethods, type RpcContext, type RpcMethod } from '../core' import type { PluginService } from '../../../plugins/plugin-service' import { PLUGIN_METHODS, setPluginServiceForRpc } from './plugins' const SESSION_TOKEN = 's'.repeat(43) function method(name: string): RpcMethod { - const found = PLUGIN_METHODS.find((entry) => entry.name === name) + const found = eraseRpcMethods(PLUGIN_METHODS).find((entry) => entry.name === name) if (!found) { throw new Error(`missing ${name}`) } diff --git a/src/main/runtime/rpc/methods/plugins.ts b/src/main/runtime/rpc/methods/plugins.ts index bb035b984eb..667aff9179d 100644 --- a/src/main/runtime/rpc/methods/plugins.ts +++ b/src/main/runtime/rpc/methods/plugins.ts @@ -1,5 +1,4 @@ -import { z } from 'zod' -import { defineMethod, type RpcContext, type RpcMethod } from '../core' +import { defineMethod, type RpcContext } from '../core' import type { PluginPanelEntry } from '../../../../shared/plugins/plugin-panel-bridge' import { listPluginsForClients } from '../../../plugins/plugin-client-list' import type { PluginListEntry } from '../../../plugins/plugin-list-projection' @@ -8,7 +7,12 @@ import { pluginConsentRequestSchema, type PluginConsentRequest } from '../../../../shared/plugins/plugin-consent-request' -import { isQualifiedPluginKey } from '../../../../shared/plugins/plugin-manifest' +import { + PluginInvokeCommandParams, + PluginReadPanelEntryParams, + PluginSetEnabledParams, + PluginsPanelActionParams +} from '../../../../shared/rpc-contract/plugins-params' /** * Serve/headless parity surface: the same consent, enablement, panel-action, @@ -45,22 +49,6 @@ function requirePluginService(): PluginService { return pluginServiceForRpc } -const PluginSetEnabledParams = z.object({ - pluginKey: z.string().refine(isQualifiedPluginKey, 'invalid qualified plugin key'), - enabled: z.boolean() -}) - -const PluginReadPanelEntryParams = z.object({ - pluginKey: z.string().min(1), - panelId: z.string().min(1) -}) - -const PluginInvokeCommandParams = z.object({ - pluginKey: z.string().min(1), - commandId: z.string().min(1), - args: z.unknown().optional() -}) - async function listForRpc(): Promise { return listPluginsForClients(requirePluginService()) } @@ -77,7 +65,7 @@ function bindRpcPanelOwner(service: PluginService, context: RpcContext): string return ownerKey } -export const PLUGIN_METHODS: readonly RpcMethod[] = [ +export const PLUGIN_METHODS = [ defineMethod({ name: 'plugins.list', params: null, @@ -118,7 +106,7 @@ export const PLUGIN_METHODS: readonly RpcMethod[] = [ name: 'plugins.panelAction', // Why: raw admission must run before strict schema parsing so malformed // and oversized traffic cannot bypass the panel budget. - params: z.unknown(), + params: PluginsPanelActionParams, handler: async (params, context) => { const service = requirePluginService() await service.whenReady() diff --git a/src/main/runtime/rpc/methods/preflight.ts b/src/main/runtime/rpc/methods/preflight.ts index f863a1941d1..cc1dd5705c3 100644 --- a/src/main/runtime/rpc/methods/preflight.ts +++ b/src/main/runtime/rpc/methods/preflight.ts @@ -1,5 +1,4 @@ -import { z } from 'zod' -import { defineMethod, type RpcMethod } from '../core' +import { defineMethod } from '../core' import { detectRemoteAgents, detectRemoteWindowsTerminalCapabilities, @@ -7,18 +6,13 @@ import { refreshShellPathAndDetectAgents, runPreflightCheck } from '../../../preflight/agent-detection' +import { + PreflightCheck, + PreflightDetectRemoteAgents, + PreflightDetectRemoteWindowsTerminalCapabilities +} from '../../../../shared/rpc-contract/preflight-params' -const PreflightCheck = z.object({ - force: z.boolean().optional() -}) -const PreflightDetectRemoteAgents = z.object({ - connectionId: z.string().min(1) -}) -const PreflightDetectRemoteWindowsTerminalCapabilities = z.object({ - connectionId: z.string().min(1) -}) - -export const PREFLIGHT_METHODS: RpcMethod[] = [ +export const PREFLIGHT_METHODS = [ defineMethod({ name: 'preflight.check', params: PreflightCheck, diff --git a/src/main/runtime/rpc/methods/project-runtime-rpc-methods.ts b/src/main/runtime/rpc/methods/project-runtime-rpc-methods.ts index c25671d5bed..f67705f6cdd 100644 --- a/src/main/runtime/rpc/methods/project-runtime-rpc-methods.ts +++ b/src/main/runtime/rpc/methods/project-runtime-rpc-methods.ts @@ -1,102 +1,15 @@ -import { z } from 'zod' -import { - LOCAL_EXECUTION_HOST_ID, - normalizeExecutionHostId, - parseExecutionHostId -} from '../../../../shared/execution-host' -import { defineMethod, type RpcMethod } from '../core' -import { OptionalString, requiredString } from '../schemas' +import { defineMethod } from '../core' import { projectRepoResultVisibilityForClient } from '../repo-visibility-projection' +import { + ProjectHostSetupClone, + ProjectHostSetupCreate, + ProjectHostSetupDelete, + ProjectHostSetupExistingFolder, + ProjectHostSetupUpdate, + ProjectUpdate +} from '../../../../shared/rpc-contract/project-runtime-params' -const ProjectProviderIdentity = z.object({ - provider: z.literal('github'), - owner: requiredString('Missing project owner'), - repo: requiredString('Missing project repository'), - host: OptionalString -}) - -// Why: `runtime:` ids are minted by the calling client's own pairing store -// (addEnvironmentFromPairingCode -> randomUUID), so they name a machine only relative to that -// client. A client sending one to this runtime is addressing *us*, and runtimes do not proxy -// these calls onward, so the host it names is this machine. Persisting the caller's id verbatim -// makes one machine look like a different host to every other client, hides its rows from them, -// and defeats the (projectId, hostId) duplicate check. Store our own spelling instead: `local`. -// Rows written before this normalization keep their client-minted stamp; readers still project -// `local` back to `runtime:`, so the client-visible model is unchanged. -const RequestedHostId = requiredString('Missing host ID').transform((value, ctx) => { - const hostId = normalizeExecutionHostId(value) - if (!hostId) { - ctx.addIssue({ code: 'custom', message: 'Invalid host ID' }) - return z.NEVER - } - return parseExecutionHostId(hostId)?.kind === 'runtime' ? LOCAL_EXECUTION_HOST_ID : hostId -}) - -const ProjectHostSetupExistingFolder = z.object({ - projectId: requiredString('Missing project ID'), - projectProviderIdentity: ProjectProviderIdentity.optional(), - hostId: RequestedHostId, - path: requiredString('Missing project path'), - kind: z.enum(['git', 'folder']).optional(), - displayName: OptionalString, - setupMethod: z.enum(['imported-existing-folder', 'cloned']).optional() -}) - -const ProjectHostSetupClone = z.object({ - projectId: requiredString('Missing project ID'), - projectProviderIdentity: ProjectProviderIdentity.optional(), - hostId: RequestedHostId, - url: requiredString('Missing clone URL'), - destination: requiredString('Missing clone destination'), - displayName: OptionalString -}) - -const LocalWindowsRuntimePreference = z.discriminatedUnion('kind', [ - z.object({ kind: z.literal('inherit-global') }), - z.object({ kind: z.literal('windows-host') }), - z.object({ kind: z.literal('wsl'), distro: requiredString('Missing WSL distro') }) -]) - -const ProjectUpdate = z.object({ - projectId: requiredString('Missing project ID'), - updates: z.object({ - localWindowsRuntimePreference: LocalWindowsRuntimePreference.optional() - }) -}) - -const ProjectHostSetupCreate = z.object({ - projectId: requiredString('Missing project ID'), - hostId: RequestedHostId, - setupId: OptionalString, - path: OptionalString, - kind: z.enum(['git', 'folder']).optional(), - displayName: OptionalString, - worktreeBasePath: OptionalString, - gitUsername: OptionalString, - setupState: z.enum(['ready', 'not-set-up', 'setting-up', 'error', 'unsupported']).optional(), - setupMethod: z.enum(['imported-existing-folder', 'cloned', 'provisioned']).optional() -}) - -const ProjectHostSetupUpdate = z.object({ - setupId: requiredString('Missing setup ID'), - updates: z.object({ - displayName: OptionalString, - path: OptionalString, - worktreeBasePath: OptionalString, - setupState: z.enum(['ready', 'not-set-up', 'setting-up', 'error', 'unsupported']).optional(), - setupMethod: z - .enum(['legacy-repo', 'imported-existing-folder', 'cloned', 'provisioned']) - .optional(), - gitUsername: OptionalString, - kind: z.enum(['git', 'folder']).optional() - }) -}) - -const ProjectHostSetupDelete = z.object({ - setupId: requiredString('Missing setup ID') -}) - -export const PROJECT_RUNTIME_METHODS: RpcMethod[] = [ +export const PROJECT_RUNTIME_METHODS = [ defineMethod({ name: 'project.list', params: null, diff --git a/src/main/runtime/rpc/methods/repo-update-schema.ts b/src/main/runtime/rpc/methods/repo-update-schema.ts index b613b35d8ba..f4e189f84a7 100644 --- a/src/main/runtime/rpc/methods/repo-update-schema.ts +++ b/src/main/runtime/rpc/methods/repo-update-schema.ts @@ -1,76 +1,4 @@ -import { z } from 'zod' -import { OptionalFiniteNumber, OptionalString } from '../schemas' -import { sanitizeRepoIcon } from '../../../../shared/repo-icon' -import { normalizeRepoBadgeColor } from '../../../../shared/repo-badge-color' -import { normalizeRepoSourceControlAiOverrides } from '../../../../shared/source-control-ai' -import { - normalizeCustomWorktreeVisibilitySources, - normalizeWorktreeVisibilitySourcePreferences -} from '../../../../shared/worktree/visibility-sources' - -export const RepoSourceControlAiOverrides = z - .unknown() - .optional() - .transform((value) => - value === undefined - ? undefined - : value === null - ? null - : normalizeRepoSourceControlAiOverrides(value) - ) - -const RepoBadgeColor = z - .unknown() - .optional() - .transform((value) => - value === undefined ? undefined : (normalizeRepoBadgeColor(value) ?? undefined) - ) - -const RepoUpstream = z - .object({ - owner: z.string().min(1), - repo: z.string().min(1) - }) - .nullable() - .optional() - -export function createRepoUpdateSchema( - selectorShape: T -): z.ZodObject }> { - return z.object({ - ...selectorShape, - updates: z.object({ - displayName: OptionalString, - badgeColor: RepoBadgeColor, - repoIcon: z - .unknown() - .transform((value) => sanitizeRepoIcon(value)) - .optional(), - upstream: RepoUpstream, - hookSettings: z.unknown().optional(), - worktreeBaseRef: OptionalString, - worktreeBasePath: OptionalString, - kind: z.enum(['git', 'folder']).optional(), - symlinkPaths: z.array(z.string()).optional(), - issueSourcePreference: z.enum(['auto', 'upstream', 'origin']).optional(), - forkSyncMode: z.enum(['ask', 'safe-auto', 'off']).optional(), - externalWorktreeVisibility: z.enum(['hide', 'show']).nullable().optional(), - externalWorktreeVisibilityPromptDismissedAt: z.number().finite().optional(), - externalWorktreeInboxBaselinePaths: z.array(z.string()).optional(), - importedExternalWorktreePaths: z.array(z.string()).optional(), - agentWorktreeVisibility: z.enum(['hide', 'show']).nullable().optional(), - customWorktreeVisibilitySources: z - .unknown() - .transform((value) => normalizeCustomWorktreeVisibilitySources(value)) - .optional(), - worktreeVisibilitySourcePreferences: z - .unknown() - .transform((value) => normalizeWorktreeVisibilitySourcePreferences(value)) - .optional(), - externalWorktreeDiscoverySuppressedAt: z.number().finite().nullable().optional(), - projectGroupId: OptionalString.nullable().optional(), - projectGroupOrder: OptionalFiniteNumber, - sourceControlAi: RepoSourceControlAiOverrides - }) - }) as z.ZodObject }> -} +export { + RepoSourceControlAiOverrides, + createRepoUpdateSchema +} from '../../../../shared/rpc-contract/repo-update-params' diff --git a/src/main/runtime/rpc/methods/repo.ts b/src/main/runtime/rpc/methods/repo.ts index 7bf42922db8..6498de8a4f3 100644 --- a/src/main/runtime/rpc/methods/repo.ts +++ b/src/main/runtime/rpc/methods/repo.ts @@ -1,115 +1,30 @@ -import { z } from 'zod' -import { defineMethod, type RpcMethod } from '../core' -import { OptionalFiniteNumber, OptionalString, requiredString } from '../schemas' +import { defineMethod } from '../core' import { PROJECT_RUNTIME_METHODS } from './project-runtime-rpc-methods' import { FOLDER_WORKSPACE_METHODS } from './folder-workspace' -import { createRepoUpdateSchema } from './repo-update-schema' +import { RepoSelector } from './github-repo-target-schemas' import { projectRepoResultVisibilityForClient, projectRepoVisibilityForClient } from '../repo-visibility-projection' +import { + ProjectGroupCreate, + ProjectGroupImportNested, + ProjectGroupMoveProject, + ProjectGroupScanNested, + ProjectGroupSelector, + ProjectGroupUpdate, + RepoClone, + RepoCreate, + RepoIssueCommandWrite, + RepoPath, + RepoReorder, + RepoSearchRefs, + RepoSetBaseRef, + RepoSparsePresetSave, + RepoUpdate +} from '../../../../shared/rpc-contract/repo-params' -const RepoSelector = z.object({ - repo: requiredString('Missing repo selector') -}) - -const RepoPath = z.object({ - path: requiredString('Missing repo path'), - kind: z.enum(['git', 'folder']).optional(), - displayName: OptionalString -}) - -const RepoCreate = z.object({ - parentPath: requiredString('Missing parent path'), - name: requiredString('Missing repo name'), - kind: z.enum(['git', 'folder']).optional() -}) - -const RepoClone = z.object({ - url: requiredString('Missing clone URL'), - destination: requiredString('Missing clone destination') -}) - -const RepoSetBaseRef = z.object({ - repo: requiredString('Missing repo selector'), - ref: requiredString('Missing base ref') -}) - -const RepoUpdate = createRepoUpdateSchema(RepoSelector.shape) - -const RepoSearchRefs = z.object({ - repo: requiredString('Missing repo selector'), - query: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : undefined)) - .pipe(z.string({ message: 'Missing query' })), - limit: OptionalFiniteNumber -}) - -const RepoReorder = z.object({ - orderedIds: z.array(z.string()) -}) - -const ProjectGroupCreate = z.object({ - name: requiredString('Missing group name'), - parentPath: OptionalString, - connectionId: OptionalString.nullable().optional(), - parentGroupId: OptionalString.nullable().optional(), - createdFrom: z.enum(['manual', 'folder-scan', 'migration']).optional() -}) - -const ProjectGroupUpdate = z.object({ - groupId: requiredString('Missing group id'), - updates: z.object({ - name: OptionalString, - isCollapsed: z.boolean().optional(), - tabOrder: OptionalFiniteNumber, - color: OptionalString.nullable().optional() - }) -}) - -const ProjectGroupSelector = z.object({ - groupId: requiredString('Missing group id') -}) - -const ProjectGroupMoveProject = z.object({ - repo: requiredString('Missing repo selector'), - groupId: OptionalString.nullable(), - order: OptionalFiniteNumber -}) - -const ProjectGroupScanNested = z.object({ - path: requiredString('Missing folder path') -}) - -const ProjectGroupImportNested = z.discriminatedUnion('mode', [ - z.object({ - parentPath: requiredString('Missing parent path'), - groupName: z.string().optional().default(''), - projectPaths: z.array(z.string()), - mode: z.literal('group') - }), - z.object({ - parentPath: requiredString('Missing parent path'), - // Why: blank group names fall back to the scanned folder basename; separate - // imports do not create a group but share the same renderer payload shape. - groupName: z.string().optional().default(''), - projectPaths: z.array(z.string()), - mode: z.literal('separate') - }) -]) - -const RepoIssueCommandWrite = RepoSelector.extend({ - content: z.string() -}) - -const RepoSparsePresetSave = RepoSelector.extend({ - id: OptionalString, - name: requiredString('Missing preset name'), - directories: z.array(z.string()) -}) - -export const REPO_METHODS: RpcMethod[] = [ +export const REPO_METHODS = [ defineMethod({ name: 'repo.list', params: null, diff --git a/src/main/runtime/rpc/methods/runtime-client-capabilities.ts b/src/main/runtime/rpc/methods/runtime-client-capabilities.ts index a1ab53267b3..2fa62b53934 100644 --- a/src/main/runtime/rpc/methods/runtime-client-capabilities.ts +++ b/src/main/runtime/rpc/methods/runtime-client-capabilities.ts @@ -1,14 +1,8 @@ -import { z } from 'zod' import type { RuntimeCapability } from '../../../../shared/protocol-version' -import { defineMethod, type RpcAnyMethod } from '../core' +import { defineMethod } from '../core' +import { ClientCapabilitiesUpdate } from '../../../../shared/rpc-contract/runtime-client-capabilities-params' -const ClientCapabilitiesUpdate = z - .object({ - clientCapabilities: z.array(z.string().min(1).max(128)).max(64) - }) - .strict() - -export const RUNTIME_CLIENT_CAPABILITY_METHODS: RpcAnyMethod[] = [ +export const RUNTIME_CLIENT_CAPABILITY_METHODS = [ defineMethod({ name: 'runtime.clientCapabilities.update', params: ClientCapabilitiesUpdate, diff --git a/src/main/runtime/rpc/methods/session-tab-close-methods.ts b/src/main/runtime/rpc/methods/session-tab-close-methods.ts index 4800b7d33c1..a7065cf6ba2 100644 --- a/src/main/runtime/rpc/methods/session-tab-close-methods.ts +++ b/src/main/runtime/rpc/methods/session-tab-close-methods.ts @@ -1,13 +1,13 @@ import { withSpan } from '../../../observability/tracer' import { SESSION_TAB_CLOSE_INTENT_RUNTIME_CAPABILITY } from '../../../../shared/protocol-version' -import { defineMethod, type RpcAnyMethod } from '../core' +import { defineMethod } from '../core' import { CloseLifecycleTab, CloseTab } from './session-tabs-schemas' import { assertProjectedSessionTabVisible } from './session-tab-browser-placement-projection' import { assertAgentSessionTabDestructiveMutationSupported } from './session-tab-agent-status-projection' import { projectSessionTabsForClient } from './session-tabs-inventory' import { isStructuredNativeChatEnabled } from './structured-agent-session-policy' -export const SESSION_TAB_CLOSE_METHODS: RpcAnyMethod[] = [ +export const SESSION_TAB_CLOSE_METHODS = [ defineMethod({ name: 'session.tabs.close', params: CloseTab, diff --git a/src/main/runtime/rpc/methods/session-tab-markdown-methods.ts b/src/main/runtime/rpc/methods/session-tab-markdown-methods.ts index 6144cd3e546..f2be1d4a61d 100644 --- a/src/main/runtime/rpc/methods/session-tab-markdown-methods.ts +++ b/src/main/runtime/rpc/methods/session-tab-markdown-methods.ts @@ -1,7 +1,7 @@ -import { defineMethod, type RpcAnyMethod } from '../core' +import { defineMethod } from '../core' import { ActivateTab, SaveMarkdownTab } from './session-tabs-schemas' -export const SESSION_TAB_MARKDOWN_METHODS: RpcAnyMethod[] = [ +export const SESSION_TAB_MARKDOWN_METHODS = [ defineMethod({ name: 'markdown.readTab', params: ActivateTab, diff --git a/src/main/runtime/rpc/methods/session-tab-mutation-methods.ts b/src/main/runtime/rpc/methods/session-tab-mutation-methods.ts index 462d00d869d..d62f50be595 100644 --- a/src/main/runtime/rpc/methods/session-tab-mutation-methods.ts +++ b/src/main/runtime/rpc/methods/session-tab-mutation-methods.ts @@ -1,6 +1,6 @@ import { resolveRuntimeNavigationTarget } from '../../../../shared/runtime-navigation' import type { OrcaRuntimeService } from '../../orca-runtime' -import { defineMethod, type RpcAnyMethod } from '../core' +import { defineMethod } from '../core' import { assertProjectedSessionTabVisible, translateProjectedSessionTabMove @@ -9,7 +9,7 @@ import { projectSessionTabsForClient } from './session-tabs-inventory' import { isStructuredNativeChatEnabled } from './structured-agent-session-policy' import { ActivateTab, MoveTab, SetTabProps, UpdatePaneLayout } from './session-tabs-schemas' -export const SESSION_TAB_MUTATION_METHODS: RpcAnyMethod[] = [ +export const SESSION_TAB_MUTATION_METHODS = [ defineMethod({ name: 'session.tabs.activate', params: ActivateTab, diff --git a/src/main/runtime/rpc/methods/session-tabs-schemas.ts b/src/main/runtime/rpc/methods/session-tabs-schemas.ts index 1f44e17ea0b..ecd434f1e0a 100644 --- a/src/main/runtime/rpc/methods/session-tabs-schemas.ts +++ b/src/main/runtime/rpc/methods/session-tabs-schemas.ts @@ -1,229 +1,14 @@ -import { z } from 'zod' -import { MAX_QUICK_COMMAND_AGENT_PROMPT_LENGTH } from '../../../../shared/terminal-quick-commands' -import { isTuiAgent } from '../../../../shared/tui-agent-config' -import type { TuiAgent } from '../../../../shared/tui-agent' -import { sleepingAgentLaunchConfigSchema } from '../../../../shared/workspace-session-sleeping-agents' -import { RUNTIME_NAVIGATION_TARGETS } from '../../../../shared/runtime-navigation' -import { TAB_ACTIVATION_INTENTS } from '../../../../shared/tab-activation-intent' -import { OptionalBoolean } from '../schemas' - -export const WorktreeTabSelector = z.object({ - worktree: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing worktree selector')) -}) - -export const SessionTabsUnsubscribe = WorktreeTabSelector.extend({ - subscriptionId: z.string().min(1).optional() -}) - -export const ActivateTab = WorktreeTabSelector.extend({ - tabId: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing tab id')), - leafId: z.string().max(128).optional(), - notifyClients: OptionalBoolean, - navigation: z.enum(RUNTIME_NAVIGATION_TARGETS).optional(), - // Why: absent means user intent, so clients that predate this field keep the - // tab-open wake gesture. Only 'automatic' may be refused for a slept pane. - intent: z.enum(TAB_ACTIVATION_INTENTS).optional() -}) - -export const CloseTab = ActivateTab.extend({ - // Why: optional preserves authenticated legacy user closes; lifecycle intent - // uses the additive evidence-bearing method instead. - reason: z.literal('user').optional() -}) - -export const CloseLifecycleTab = ActivateTab.extend({ - reason: z.enum(['pty-exit', 'cleanup']), - publicationEpoch: z.string().min(1).max(128), - terminal: z.string().min(1).max(256) -}) - -export type TerminalPaneLayoutNodeInput = - | { type: 'leaf'; leafId: string } - | { - type: 'split' - direction: 'horizontal' | 'vertical' - first: TerminalPaneLayoutNodeInput - second: TerminalPaneLayoutNodeInput - ratio?: number - } - -// Why: this schema parses UNTRUSTED remote-client input. A recursive zod parse -// of a deeply-nested tree would overflow the main-process stack, so validate -// iteratively with hard depth + node-count caps before building the typed value. -const MAX_PANE_LAYOUT_DEPTH = 64 -const MAX_PANE_LAYOUT_NODES = 1024 - -function parseTerminalPaneLayoutNode(value: unknown): TerminalPaneLayoutNodeInput | null { - // Iterative validate-then-build: first walk the raw tree with an explicit - // stack (no recursion) enforcing caps, then build bottom-up. - let nodeCount = 0 - const stack: { raw: unknown; depth: number }[] = [{ raw: value, depth: 0 }] - while (stack.length > 0) { - const { raw, depth } = stack.pop()! - if (depth > MAX_PANE_LAYOUT_DEPTH || ++nodeCount > MAX_PANE_LAYOUT_NODES) { - return null - } - if (typeof raw !== 'object' || raw === null) { - return null - } - const node = raw as Record - if (node.type === 'leaf') { - if (typeof node.leafId !== 'string' || node.leafId.length < 1 || node.leafId.length > 128) { - return null - } - continue - } - if (node.type === 'split') { - if (node.direction !== 'horizontal' && node.direction !== 'vertical') { - return null - } - if ( - node.ratio !== undefined && - (typeof node.ratio !== 'number' || - !Number.isFinite(node.ratio) || - node.ratio < 0 || - node.ratio > 1) - ) { - return null - } - stack.push({ raw: node.first, depth: depth + 1 }, { raw: node.second, depth: depth + 1 }) - continue - } - return null - } - return value as TerminalPaneLayoutNodeInput -} - -export const TerminalPaneLayoutNodeSchema = z - .unknown() - .transform((value) => parseTerminalPaneLayoutNode(value)) - .pipe( - z.custom((value) => value !== null, { - message: 'Invalid or too-deep pane layout tree' - }) - ) - -export const UpdatePaneLayout = WorktreeTabSelector.extend({ - tabId: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing tab id')), - root: z.union([z.null(), TerminalPaneLayoutNodeSchema]), - expandedLeafId: z.string().max(128).nullable().optional(), - titlesByLeafId: z.record(z.string(), z.string()).optional() -}) - -export const SetTabProps = WorktreeTabSelector.extend({ - tabId: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing tab id')), - // undefined = leave unchanged; null = clear color / unset. - color: z.string().max(64).nullable().optional(), - isPinned: z.boolean().optional(), - // undefined = leave unchanged; no "clear" semantic (absence means default 'terminal'). - viewMode: z.enum(['terminal', 'chat']).optional() -}) - -export const CreateTerminalTab = WorktreeTabSelector.extend({ - afterTabId: z.string().optional(), - targetGroupId: z.string().optional(), - command: z.string().optional(), - cwd: z.string().min(1).optional(), - env: z.record(z.string(), z.string()).optional(), - envToDelete: z.array(z.string().min(1).max(256)).max(32).optional(), - startupCommandDelivery: z.enum(['fast', 'shell-ready']).optional(), - launchConfig: sleepingAgentLaunchConfigSchema, - launchToken: z.string().min(1).max(128).optional(), - agent: z - .custom(isTuiAgent, { - message: 'Unknown agent preset' - }) - .optional(), - // Why: agent prompts must be quoted and injected for the host shell (native, - // WSL, or SSH) instead of pasted from the mobile client before the TUI is ready. - agentPrompt: z - .string() - .max(MAX_QUICK_COMMAND_AGENT_PROMPT_LENGTH) - .refine((value) => value.trim().length > 0, { message: 'Agent prompt cannot be empty' }) - .optional(), - // Why: `agent` is the legacy preset field; `launchAgent` is the launch-plan - // identity used when preserving resume config across runtime boundaries. - launchAgent: z - .custom(isTuiAgent, { - message: 'Unknown launch agent' - }) - .optional(), - viewMode: z.enum(['terminal', 'chat']).optional(), - activate: z.boolean().optional(), - select: z.boolean().optional(), - navigation: z.enum(RUNTIME_NAVIGATION_TARGETS).optional(), - // Why: idempotency key so a retried create (double-tap, reconnect replay) - // returns the in-flight operation instead of spawning a duplicate terminal. - clientMutationId: z.string().min(1).max(128).optional() -}).superRefine((value, context) => { - if (value.agentPrompt !== undefined && value.agent === undefined) { - context.addIssue({ - code: 'custom', - path: ['agentPrompt'], - message: 'Agent prompt requires an agent preset' - }) - } - if (value.agentPrompt !== undefined && value.command !== undefined) { - context.addIssue({ - code: 'custom', - path: ['agentPrompt'], - message: 'Agent prompt cannot be combined with a startup command' - }) - } -}) - -const MoveTabBase = { - worktree: WorktreeTabSelector.shape.worktree, - tabId: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing tab id')), - targetGroupId: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing target group id')) -} as const - -export const MoveTab = z.discriminatedUnion('kind', [ - z - .object({ - ...MoveTabBase, - kind: z.literal('reorder'), - tabOrder: z.array(z.string().min(1)).min(1, 'Missing tab order') - }) - .strict(), - z - .object({ - ...MoveTabBase, - kind: z.literal('move-to-group'), - index: z.number().int().nonnegative().optional() - }) - .strict(), - z - .object({ - ...MoveTabBase, - kind: z.literal('split'), - splitDirection: z.enum(['left', 'right', 'up', 'down']) - }) - .strict() -]) - -export const SaveMarkdownTab = ActivateTab.extend({ - baseVersion: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing base version')), - content: z.string() -}) +export { + ActivateTab, + CloseLifecycleTab, + CloseTab, + CreateTerminalTab, + MoveTab, + SaveMarkdownTab, + SessionTabsUnsubscribe, + SetTabProps, + TerminalPaneLayoutNodeSchema, + UpdatePaneLayout, + WorktreeTabSelector +} from '../../../../shared/rpc-contract/session-tabs-schemas-params' +export type { TerminalPaneLayoutNodeInput } from '../../../../shared/rpc-contract/session-tabs-schemas-params' diff --git a/src/main/runtime/rpc/methods/session-tabs.ts b/src/main/runtime/rpc/methods/session-tabs.ts index aa0e0b24939..d6441ee84cb 100644 --- a/src/main/runtime/rpc/methods/session-tabs.ts +++ b/src/main/runtime/rpc/methods/session-tabs.ts @@ -1,6 +1,5 @@ -import { z } from 'zod' import { resolveRuntimeNavigationTarget } from '../../../../shared/runtime-navigation' -import { defineMethod, defineStreamingMethod, type RpcAnyMethod } from '../core' +import { defineMethod, defineStreamingMethod } from '../core' import { CreateTerminalTab, SessionTabsUnsubscribe, @@ -18,8 +17,9 @@ import { createSessionTabsRetirementProofDelta } from './session-tabs-retirement import { restoreStructuredTabsIfSupported } from './structured-session-tab-restore' import { isStructuredNativeChatEnabled } from './structured-agent-session-policy' import { assertLegacyAiVaultResumeCommandAllowed } from '../../../ai-vault/structured-session-ownership' +import { SessionTabsUnsubscribeAllParams } from '../../../../shared/rpc-contract/session-tabs-params' -export const SESSION_TAB_METHODS: RpcAnyMethod[] = [ +export const SESSION_TAB_METHODS = [ defineMethod({ name: 'session.tabs.list', params: WorktreeTabSelector, @@ -181,11 +181,7 @@ export const SESSION_TAB_METHODS: RpcAnyMethod[] = [ }), defineMethod({ name: 'session.tabs.unsubscribeAll', - params: z - .object({ - subscriptionId: z.string().min(1).optional() - }) - .nullish(), + params: SessionTabsUnsubscribeAllParams, handler: async (params, { runtime, connectionId }) => { const cleanupPrefix = `session.tabs:${connectionId ?? 'local'}:*` if (params?.subscriptionId) { diff --git a/src/main/runtime/rpc/methods/skills.test.ts b/src/main/runtime/rpc/methods/skills.test.ts index 0425e5922eb..9bc5a647c82 100644 --- a/src/main/runtime/rpc/methods/skills.test.ts +++ b/src/main/runtime/rpc/methods/skills.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { RpcContext } from '../core' +import { eraseRpcMethods, type RpcContext } from '../core' vi.mock('electron', () => ({ app: { getPath: () => '/orca-state', isPackaged: true } @@ -41,7 +41,7 @@ function makeContext(overrides: { } function discoverMethod() { - const method = SKILL_METHODS.find((entry) => entry.name === 'skills.discover') + const method = eraseRpcMethods(SKILL_METHODS).find((entry) => entry.name === 'skills.discover') if (!method) { throw new Error('skills.discover method not registered') } @@ -49,7 +49,7 @@ function discoverMethod() { } function installMethod() { - const method = SKILL_METHODS.find((entry) => entry.name === 'skills.install') + const method = eraseRpcMethods(SKILL_METHODS).find((entry) => entry.name === 'skills.install') if (!method) { throw new Error('skills.install method not registered') } @@ -57,7 +57,7 @@ function installMethod() { } function method(name: string) { - const value = SKILL_METHODS.find((entry) => entry.name === name) + const value = eraseRpcMethods(SKILL_METHODS).find((entry) => entry.name === name) if (!value) { throw new Error(`${name} method not registered`) } diff --git a/src/main/runtime/rpc/methods/skills.ts b/src/main/runtime/rpc/methods/skills.ts index 13ecbefc3c7..39a3a73eb7c 100644 --- a/src/main/runtime/rpc/methods/skills.ts +++ b/src/main/runtime/rpc/methods/skills.ts @@ -1,5 +1,5 @@ -import { defineMethod, type RpcMethod } from '../core' -import { z } from 'zod' +import { defineMethod } from '../core' +import type { z } from 'zod' import { getAppEnvironment } from '../../../../shared/app-environment' import { SkillDeleteRequestSchema } from '../../../../shared/skill-delete-contract' import { @@ -7,7 +7,7 @@ import { runSkillDeleteRequest, type SkillDeleteRequestDependencies } from '../../../skills/skill-delete/request-service' -import { SkillDiscoveryTargetSchema } from '../../../../shared/skills' +import type { SkillDiscoveryTargetSchema } from '../../../../shared/skills' import { SkillInstallPreviewRequestSchema, SkillInstallRequestSchema, @@ -33,6 +33,11 @@ import { AgentSkillShareRequestSchema, AgentSkillSharingError } from '../../../../shared/agent-skill-sharing-contract' +import { + SkillsCancelInstallParams, + SkillsDiscoverParams, + SkillsGetInstallProgressParams +} from '../../../../shared/rpc-contract/skills-params' /** Exported so the delete plan's root rebuild resolves its target exactly the * way `skills.discover` resolved the scan's — including WSL. */ @@ -59,10 +64,10 @@ function skillDeleteDependencies( } } -export const SKILL_METHODS: RpcMethod[] = [ +export const SKILL_METHODS = [ defineMethod({ name: 'skills.discover', - params: SkillDiscoveryTargetSchema.default({}), + params: SkillsDiscoverParams, handler: async (params, { runtime }) => { // Why: the executing runtime owns WSL project preferences. Remote callers // send worktree identity only; trusting their projectRuntime absence @@ -146,14 +151,14 @@ export const SKILL_METHODS: RpcMethod[] = [ }), defineMethod({ name: 'skills.cancelInstall', - params: z.object({ operationId: z.string().min(1).max(128) }).strict(), + params: SkillsCancelInstallParams, handler: (params, { runtime }) => ({ cancelled: runtime.cancelSharedSkillInstall(params.operationId) }) }), defineMethod({ name: 'skills.getInstallProgress', - params: z.object({ operationId: z.string().min(1).max(128) }).strict(), + params: SkillsGetInstallProgressParams, handler: (params, { runtime }) => { const progress = runtime.getSharedSkillInstallProgress(params.operationId) return progress ? SkillBundleInstallProgressSchema.parse(progress) : null diff --git a/src/main/runtime/rpc/methods/speech.ts b/src/main/runtime/rpc/methods/speech.ts index d686475ab3f..086a528ab0e 100644 --- a/src/main/runtime/rpc/methods/speech.ts +++ b/src/main/runtime/rpc/methods/speech.ts @@ -1,54 +1,13 @@ -import { z } from 'zod' -import { defineMethod, type RpcMethod } from '../core' -import { OptionalString, requiredString } from '../schemas' +import { defineMethod } from '../core' +import { + DictationChunk, + DictationHandle, + DictationSetup, + DictationStart, + SpeechModelAction +} from '../../../../shared/rpc-contract/speech-params' -const AUDIO_BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/ -const DICTATION_SAMPLE_RATE = 16_000 -const PCM_BYTES_PER_SAMPLE = 2 -const MAX_DICTATION_AUDIO_SECONDS = 5 -const MAX_DICTATION_AUDIO_CHUNK_BYTES = - DICTATION_SAMPLE_RATE * PCM_BYTES_PER_SAMPLE * MAX_DICTATION_AUDIO_SECONDS -const MAX_DICTATION_AUDIO_CHUNK_BASE64_LENGTH = Math.ceil(MAX_DICTATION_AUDIO_CHUNK_BYTES / 3) * 4 - -function isValidAudioBase64(value: string): boolean { - return value.length % 4 !== 1 && AUDIO_BASE64_PATTERN.test(value) -} - -const DictationStart = z.object({ - dictationId: requiredString('Missing dictation ID'), - modelId: OptionalString -}) - -const DictationChunk = z.object({ - dictationId: requiredString('Missing dictation ID'), - audioBase64: requiredString('Missing audio chunk') - // Why: feedMobileDictation decodes into Buffer + Float32Array; reject - // oversized chunks before allocation. This mirrors the mobile pending-audio budget. - .refine( - (value) => value.length <= MAX_DICTATION_AUDIO_CHUNK_BASE64_LENGTH, - 'Audio chunk is too large' - ) - // Why: Buffer.from(..., 'base64') silently drops malformed bytes; reject - // bad mobile audio chunks instead of feeding empty/corrupt PCM. - .refine(isValidAudioBase64, 'Audio chunk must be base64'), - sampleRate: z.number().finite().positive() -}) - -const DictationHandle = z.object({ - dictationId: requiredString('Missing dictation ID') -}) - -const SpeechModelAction = z.object({ - modelId: requiredString('Missing model ID') -}) - -const DictationSetup = z.object({ - enabled: z.boolean().optional(), - modelId: OptionalString, - dictationMode: z.enum(['toggle', 'hold']).optional() -}) - -export const SPEECH_METHODS: RpcMethod[] = [ +export const SPEECH_METHODS = [ defineMethod({ name: 'speech.models.list', params: null, diff --git a/src/main/runtime/rpc/methods/ssh.ts b/src/main/runtime/rpc/methods/ssh.ts index e6cb6b47b50..2c8e2520f9b 100644 --- a/src/main/runtime/rpc/methods/ssh.ts +++ b/src/main/runtime/rpc/methods/ssh.ts @@ -1,17 +1,13 @@ -import { z } from 'zod' import { connectRegisteredSshTarget, getRegisteredSshState, listRegisteredRemovedSshTargetLabels, listRegisteredSshTargets } from '../../../ssh/ssh-target-registry' -import { defineMethod, type RpcMethod } from '../core' +import { defineMethod } from '../core' import { getPublicSshError, getPublicSshState } from '../../public-ssh-state' import type { SshTargetSummary } from '../../../../shared/ssh-types' - -const SshTarget = z.object({ - targetId: z.string().min(1) -}) +import { SshTarget } from '../../../../shared/rpc-contract/ssh-params' // Why: `generation` stays optional on the wire — an old server simply omits it and its rows key on target id alone. function listRegisteredSshTargetSummaries(): SshTargetSummary[] { @@ -29,7 +25,7 @@ function listRegisteredSshTargetSummaries(): SshTargetSummary[] { }) } -export const SSH_METHODS: RpcMethod[] = [ +export const SSH_METHODS = [ defineMethod({ name: 'ssh.getState', params: SshTarget, diff --git a/src/main/runtime/rpc/methods/stats.ts b/src/main/runtime/rpc/methods/stats.ts index 59f71701c3a..9cdfe5269d3 100644 --- a/src/main/runtime/rpc/methods/stats.ts +++ b/src/main/runtime/rpc/methods/stats.ts @@ -1,6 +1,6 @@ -import { defineMethod, type RpcMethod } from '../core' +import { defineMethod } from '../core' -export const STATS_METHODS: RpcMethod[] = [ +export const STATS_METHODS = [ defineMethod({ name: 'stats.summary', params: null, diff --git a/src/main/runtime/rpc/methods/status.ts b/src/main/runtime/rpc/methods/status.ts index 03d66f84fb1..dac38097b7a 100644 --- a/src/main/runtime/rpc/methods/status.ts +++ b/src/main/runtime/rpc/methods/status.ts @@ -1,7 +1,7 @@ -import { defineMethod, type RpcMethod } from '../core' +import { defineMethod } from '../core' import { getRemoteServerUpdaterSnapshot } from '../../remote-server-updater' -export const STATUS_METHODS: RpcMethod[] = [ +export const STATUS_METHODS = [ defineMethod({ name: 'status.get', params: null, diff --git a/src/main/runtime/rpc/methods/structured-agent-session-hold.ts b/src/main/runtime/rpc/methods/structured-agent-session-hold.ts index 280804711e6..18fb600a949 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-hold.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-hold.ts @@ -9,7 +9,7 @@ // the hold is deliberate: re-registering an id runs the previous cleanup synchronously, so the // stale release lands before this hold rather than after it. -import { defineMethod, type RpcAnyMethod, type RpcContext } from '../core' +import { defineMethod, type RpcContext } from '../core' import { ensureStructuredHostInstalled, requireStructuredCleanupHost, @@ -28,7 +28,7 @@ function holdCleanupIdFor(sessionId: string, holderKey: string): string { return `${HOLD_CLEANUP_PREFIX}:${holderKey}:${sessionId}` } -export const STRUCTURED_AGENT_SESSION_HOLD_METHODS: RpcAnyMethod[] = [ +export const STRUCTURED_AGENT_SESSION_HOLD_METHODS = [ defineMethod({ name: 'agentSession.hold', params: HoldParams, diff --git a/src/main/runtime/rpc/methods/structured-agent-session-reveal.ts b/src/main/runtime/rpc/methods/structured-agent-session-reveal.ts index 5f2ab0e8cac..47f30a5030d 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-reveal.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-reveal.ts @@ -12,7 +12,7 @@ import { isAgentSessionWireRefusalCode } from '../../../../shared/agent-session-wire' import type { StructuredAgentSessionReveal } from '../../../native-chat/agent-session-wire/structured-agent-session-host-types' import { refuseAgentSessionMutation } from '../../../native-chat/agent-session-wire/structured-agent-session-mutation-admission' -import { defineMethod, type RpcAnyMethod } from '../core' +import { defineMethod } from '../core' import { ensureStructuredHostInstalled, requireStructuredCapability, @@ -20,7 +20,7 @@ import { } from './structured-agent-session-gate' import { OptionsParams } from './structured-agent-session-schemas' -export const STRUCTURED_AGENT_SESSION_REVEAL_METHODS: RpcAnyMethod[] = [ +export const STRUCTURED_AGENT_SESSION_REVEAL_METHODS = [ defineMethod({ name: 'agentSession.reveal', params: OptionsParams, diff --git a/src/main/runtime/rpc/methods/structured-agent-session-schemas.ts b/src/main/runtime/rpc/methods/structured-agent-session-schemas.ts index 5c7f40d7f35..7725e70bded 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-schemas.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-schemas.ts @@ -2,246 +2,25 @@ // // Strict objects throughout: zod drops unknown keys, and a silently dropped key // is how a newer client's field becomes a different effect on an older host. - -import { z } from 'zod' -import { isAgentSessionId } from '../../../../shared/agent-session-record' -import { - AGENT_SESSION_HISTORY_DIRECTIONS, - AGENT_SESSION_HISTORY_MAX_LIMIT -} from '../../../../shared/agent-session-wire' -import { normalizeExecutionHostId } from '../../../../shared/execution-host' - -const MAX_ID_LENGTH = 512 -// Four Claude questions with all four generated choices occupy 610 chars when fully percent-encoded. -const MAX_RESPONSE_OPTION_ID_LENGTH = 1024 -const MAX_PROMPT_BYTES = 256 * 1024 -const MAX_BLOCKS = 64 -const MAX_OPTION_LABEL = 512 - -export const SessionId = z - .string() - .max(MAX_ID_LENGTH) - .refine(isAgentSessionId, 'Invalid agent session id') - -const Identifier = (message: string, maxLength = MAX_ID_LENGTH) => - z - .string() - .min(1, message) - .max(maxLength, message) - .refine((value) => value === value.trim(), message) - -export const JournalCursor = z - .object({ - epoch: Identifier('Invalid journal epoch'), - sequence: z.number().int().nonnegative() - }) - .strict() - -export const MutationEnvelope = z - .object({ - sessionId: SessionId, - clientOperationId: Identifier('Invalid client operation id'), - /** Null is the "must not exist yet" case; every other call fences. */ - expectedRuntimeFence: z.number().int().positive().nullable(), - payloadFingerprint: z - .string() - .regex(/^[0-9a-f]{64}$/, 'Payload fingerprint must be a sha256 hex digest') - }) - .strict() - -const ProviderHandle = z.discriminatedUnion('kind', [ - z.object({ kind: z.literal('codex'), threadId: Identifier('Invalid thread id') }).strict(), - z - .object({ - kind: z.literal('claude'), - sessionId: Identifier('Invalid provider session id'), - leafUuid: Identifier('Invalid leaf uuid').nullable() - }) - .strict() -]) - -const ExecutionHostId = z - .string() - .max(MAX_ID_LENGTH) - .transform((value) => normalizeExecutionHostId(value)) - .refine((value): value is NonNullable => value !== null, { - message: 'Invalid execution host id' - }) - -const ExecutionLocation = z - .object({ - executionHostId: ExecutionHostId, - wslDistro: Identifier('Invalid WSL distro').nullable(), - workspaceId: Identifier('Invalid workspace id'), - workspaceKind: z.enum(['git-worktree', 'folder']) - }) - .strict() - -const AccountHome = z - .object({ - variable: z.enum(['CLAUDE_CONFIG_DIR', 'CODEX_HOME']), - path: z.string().min(1).max(4096) - }) - .strict() - -export const AttachParams = z - .object({ - envelope: MutationEnvelope, - location: ExecutionLocation, - provider: z.enum(['codex', 'claude']), - agent: Identifier('Invalid agent'), - accountHome: AccountHome, - runtimeKind: z.enum(['native', 'tui']), - providerHandle: ProviderHandle - }) - .strict() - -/** An identity, and nothing the host would otherwise read off disk. A transcript path or account - * home here would let a client choose which file this host imports and which credential directory - * the provider child launches against; both are derived host-side from this id instead. */ -const ResumeSource = z - .object({ - providerSessionId: Identifier('Invalid provider session id') - }) - .strict() - -export const CreateIntentParams = z - .object({ - envelope: MutationEnvelope, - worktree: Identifier('Invalid worktree selector'), - agent: z.enum(['claude', 'codex']), - resumeFrom: ResumeSource.optional() - }) - .strict() - -export const CreateParams = z.union([AttachParams, CreateIntentParams]) - -export const CreateSupportParams = z - .object({ - worktree: Identifier('Invalid worktree selector'), - agent: z.enum(['claude', 'codex']) - }) - .strict() - -/** Clients may only author user turns. Accepting an assistant or tool role here - * would let one client write words into the agent's mouth in another's - * timeline, and the provider — not the client — owns those. */ -const SendBlock = z.discriminatedUnion('type', [ - z.object({ type: z.literal('text'), text: z.string() }).strict(), - z - .object({ - type: z.literal('image-ref'), - path: z.string().min(1).max(4096).optional(), - url: z.string().min(1).max(4096).optional(), - alt: z.string().max(MAX_OPTION_LABEL).optional() - }) - .strict() - .refine( - (value) => Boolean(value.path) !== Boolean(value.url), - 'Provide exactly one of path/url' - ) -]) - -export const SendParams = z - .object({ - envelope: MutationEnvelope, - retryUnknown: z.literal(true).optional(), - body: z - .object({ - kind: z.literal('message'), - role: z.literal('user'), - blocks: z.array(SendBlock).min(1).max(MAX_BLOCKS) - }) - .strict() - .refine( - (value) => Buffer.byteLength(JSON.stringify(value.blocks), 'utf8') <= MAX_PROMPT_BYTES, - 'Message is too large' - ) - }) - .strict() - -export const CancelParams = z - .object({ - envelope: MutationEnvelope, - turnId: Identifier('Invalid turn id'), - scope: z.literal('background-tasks').optional(), - taskId: Identifier('Invalid task id').optional() - }) - .strict() - .refine((value) => value.taskId === undefined || value.scope === 'background-tasks', { - message: 'A task id requires background-task scope' - }) - -export const RespondParams = z - .object({ - envelope: MutationEnvelope, - itemId: Identifier('Invalid item id'), - /** Compare-and-set: the revision the client had on screen. */ - expectedRevision: z.number().int().positive(), - optionId: Identifier('Invalid option id', MAX_RESPONSE_OPTION_ID_LENGTH) - }) - .strict() - -export const SetOptionParams = z - .object({ - envelope: MutationEnvelope, - key: Identifier('Invalid option key'), - value: z.string().max(MAX_OPTION_LABEL) - }) - .strict() - -export const HandoffParams = z - .object({ - envelope: MutationEnvelope, - direction: z.enum(['to-tui', 'to-native']), - mode: z.enum(['now', 'after-turn', 'stop-turn']), - action: z.enum(['start', 'cancel-queued', 'retry', 'recover']).optional() - }) - .strict() - -export const OptionsParams = z.object({ sessionId: SessionId }).strict() - -export const ConversationCommandParams = z - .object({ - envelope: MutationEnvelope, - command: z.enum(['clear', 'compact']) - }) - .strict() - -/** One surface's claim on one session. The id names the surface, not the client: two chat views - * looking at the same session are two holders, and either leaving must not release - * the other's. */ -export const HoldParams = z - .object({ sessionId: SessionId, holderId: Identifier('Invalid holder id') }) - .strict() - -export const HistoryParams = z - .object({ - sessionId: SessionId, - direction: z.enum(AGENT_SESSION_HISTORY_DIRECTIONS), - cursor: JournalCursor.optional(), - limit: z.number().int().positive().max(AGENT_SESSION_HISTORY_MAX_LIMIT).optional() - }) - .strict() - -export const SubscribeParams = z - .object({ sessionId: SessionId, cursor: JournalCursor.optional() }) - .strict() - -export const UnsubscribeParams = z - .object({ - sessionId: SessionId, - subscriptionId: Identifier('Invalid subscription id').optional() - }) - .strict() - -/** Read-only owner classification retained for restart safety; mutation handoff is separate. */ -export const HandoffStatusParams = z.object({ sessionId: SessionId }).strict() - -export const RewindParams = z - .object({ - envelope: MutationEnvelope, - itemId: Identifier('Invalid item id', 4096), - expectedEpoch: Identifier('Invalid journal epoch') - }) - .strict() +export { + AttachParams, + CancelParams, + ConversationCommandParams, + CreateIntentParams, + CreateParams, + CreateSupportParams, + HandoffParams, + HandoffStatusParams, + HistoryParams, + HoldParams, + JournalCursor, + MutationEnvelope, + OptionsParams, + RespondParams, + RewindParams, + SendParams, + SessionId, + SetOptionParams, + SubscribeParams, + UnsubscribeParams +} from '../../../../shared/rpc-contract/structured-agent-session-params' diff --git a/src/main/runtime/rpc/methods/structured-agent-session-status-stream.ts b/src/main/runtime/rpc/methods/structured-agent-session-status-stream.ts index 8637089c254..c93401e0e22 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-status-stream.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-status-stream.ts @@ -3,7 +3,7 @@ // Session lists read turn state from here instead of replaying transcripts: one stream per client // covers every session, and unlike a transcript subscription it retains none of them. -import { defineStreamingMethod, type RpcAnyMethod, type RpcContext } from '../core' +import { defineStreamingMethod, type RpcContext } from '../core' import { requireStructuredHost as requireHost } from './structured-agent-session-gate' import { structuredAgentSessionStatusSubscriptionId } from './structured-agent-session-subscription-id' @@ -41,7 +41,7 @@ export function bindStructuredAgentSessionStream( return { isClosed: () => closed } } -export const STRUCTURED_AGENT_SESSION_STATUS_METHODS: RpcAnyMethod[] = [ +export const STRUCTURED_AGENT_SESSION_STATUS_METHODS = [ defineStreamingMethod({ name: 'agentSession.subscribeStatus', params: null, diff --git a/src/main/runtime/rpc/methods/structured-agent-session.ts b/src/main/runtime/rpc/methods/structured-agent-session.ts index c09ae4cfcbf..f1d0fc59ec5 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session.ts @@ -18,7 +18,7 @@ import { projectTurnItemEvent, projectTurnItemHistory } from './structured-agent-session-turn-item-capability' -import { defineMethod, defineStreamingMethod, type RpcAnyMethod, type RpcContext } from '../core' +import { defineMethod, defineStreamingMethod, type RpcContext } from '../core' import { ensureStructuredHostInstalled as ensureHostInstalled, requireStructuredCapability, @@ -91,7 +91,7 @@ async function attachClientSuppliedLocation( return host.attach(callerFor(ctx), attachParams) } -export const STRUCTURED_AGENT_SESSION_METHODS: RpcAnyMethod[] = [ +export const STRUCTURED_AGENT_SESSION_METHODS = [ defineMethod({ name: 'agentSession.rewind', params: RewindParams, diff --git a/src/main/runtime/rpc/methods/structured-worker-stop-receipt.test.ts b/src/main/runtime/rpc/methods/structured-worker-stop-receipt.test.ts index 151285ffb1e..aebb420fa8b 100644 --- a/src/main/runtime/rpc/methods/structured-worker-stop-receipt.test.ts +++ b/src/main/runtime/rpc/methods/structured-worker-stop-receipt.test.ts @@ -16,6 +16,7 @@ import { structuredWorkerProcessIncarnation } from '../../structured-worker-identity' import { ORCHESTRATION_METHODS } from './orchestration' +import { eraseRpcMethods } from '../core' const SESSION = 'session-stop-receipt' const HANDLE = 'structworker_22222222-2222-4222-a222-222222222222' @@ -43,7 +44,9 @@ describe('worker-stop on a structured worker this runtime cannot reach', () => { }) async function call(name: string, params: Record) { - const method = ORCHESTRATION_METHODS.find((candidate) => candidate.name === name) + const method = eraseRpcMethods(ORCHESTRATION_METHODS).find( + (candidate) => candidate.name === name + ) if (!method) { throw new Error(`Method not found: ${name}`) } diff --git a/src/main/runtime/rpc/methods/task-resume-state-schema.ts b/src/main/runtime/rpc/methods/task-resume-state-schema.ts index fc85cad6270..f923d3993b3 100644 --- a/src/main/runtime/rpc/methods/task-resume-state-schema.ts +++ b/src/main/runtime/rpc/methods/task-resume-state-schema.ts @@ -1,37 +1,8 @@ -import { z } from 'zod' +import type { z } from 'zod' import type { TaskResumeState as TaskResumeStateType } from '../../../../shared/ui-chrome-types' import type { AssertNoMissingKeys } from './ui-state-schema-parity' - -/** - * Tasks page-position state persisted through `ui.set`; mirrors `TaskResumeState`. - * - * This object is `.strict()` and sits behind `ui.set`'s field-level `.catch`, so a key - * a host predates makes that host drop the ENTIRE resume state — github and jira with - * it — and report success. Only add a field here when clients must agree on it across - * versions; per-device view preferences belong in client-local storage instead. - */ -export const TaskResumeState = z - .object({ - githubMode: z.enum(['items', 'project']).optional(), - githubItemsPreset: z.string().nullable().optional(), - githubItemsQuery: z.string().optional(), - githubProjectHiddenFieldIdsByView: z.record(z.string(), z.array(z.string())).optional(), - linearMode: z.enum(['issues', 'projects', 'views', 'in-orca']).optional(), - linearPreset: z.enum(['assigned', 'created', 'all', 'completed']).optional(), - linearQuery: z.string().optional(), - linearContext: z - .object({ - kind: z.enum(['project', 'view']), - id: z.string(), - workspaceId: z.string(), - model: z.enum(['issue', 'project']).optional() - }) - .strict() - .optional(), - jiraPreset: z.enum(['assigned', 'reported', 'all', 'done']).optional(), - jiraQuery: z.string().optional() - }) - .strict() +import { TaskResumeState } from '../../../../shared/rpc-contract/task-resume-state-params' +export { TaskResumeState } const _taskResumeStateParity: AssertNoMissingKeys< TaskResumeStateType, diff --git a/src/main/runtime/rpc/methods/terminal-create-idempotency.test.ts b/src/main/runtime/rpc/methods/terminal-create-idempotency.test.ts index 51001605be0..a1e221d5a7a 100644 --- a/src/main/runtime/rpc/methods/terminal-create-idempotency.test.ts +++ b/src/main/runtime/rpc/methods/terminal-create-idempotency.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from 'vitest' -import type { RpcContext } from '../core' +import { eraseRpcMethods, type RpcContext } from '../core' import { TERMINAL_METHODS } from './terminal' describe('terminal.create RPC idempotency', () => { @@ -15,7 +15,9 @@ describe('terminal.create RPC idempotency', () => { run: (worktree: string | undefined, handle: string | undefined) => Promise ) => run('id:worktree-1', 'term_stable') ) - const method = TERMINAL_METHODS.find((candidate) => candidate.name === 'terminal.create') + const method = eraseRpcMethods(TERMINAL_METHODS).find( + (candidate) => candidate.name === 'terminal.create' + ) if (!method) { throw new Error('terminal.create method missing') } @@ -73,7 +75,9 @@ describe('terminal.create RPC idempotency', () => { run: (worktree: string | undefined, handle: string | undefined) => Promise ) => run('id:worktree-1', undefined) ) - const method = TERMINAL_METHODS.find((candidate) => candidate.name === 'terminal.create') + const method = eraseRpcMethods(TERMINAL_METHODS).find( + (candidate) => candidate.name === 'terminal.create' + ) if (!method) { throw new Error('terminal.create method missing') } @@ -114,7 +118,9 @@ describe('terminal.create RPC idempotency', () => { run: (worktree: string | undefined, handle: string | undefined) => Promise ) => run('id:worktree-1', undefined) ) - const method = TERMINAL_METHODS.find((candidate) => candidate.name === 'terminal.create') + const method = eraseRpcMethods(TERMINAL_METHODS).find( + (candidate) => candidate.name === 'terminal.create' + ) if (!method) { throw new Error('terminal.create method missing') } diff --git a/src/main/runtime/rpc/methods/terminal-manifest-characterization.test.ts b/src/main/runtime/rpc/methods/terminal-manifest-characterization.test.ts index ccdcf5fb7b1..e26788d5d46 100644 --- a/src/main/runtime/rpc/methods/terminal-manifest-characterization.test.ts +++ b/src/main/runtime/rpc/methods/terminal-manifest-characterization.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import type { OrcaRuntimeService } from '../../orca-runtime' import { TERMINAL_METHODS } from './terminal' +import { eraseRpcMethods } from '../core' import { TerminalMultiplexLegacyAckFrame, TerminalMultiplexSourceRangeAckFrame, @@ -50,14 +51,14 @@ const METHOD_CASES: readonly (readonly [string, unknown, boolean])[] = [ ] function schemaFor(name: string) { - const method = TERMINAL_METHODS.find((candidate) => candidate.name === name) + const method = eraseRpcMethods(TERMINAL_METHODS).find((candidate) => candidate.name === name) if (!method?.params) { throw new Error(`Missing terminal schema: ${name}`) } return method.params } async function invoke(name: string, params: unknown, runtime: Partial) { - const method = TERMINAL_METHODS.find((candidate) => candidate.name === name) + const method = eraseRpcMethods(TERMINAL_METHODS).find((candidate) => candidate.name === name) if (!method?.params || 'stream' in method) { throw new Error(`Missing unary terminal method: ${name}`) } diff --git a/src/main/runtime/rpc/methods/terminal-orphan.ts b/src/main/runtime/rpc/methods/terminal-orphan.ts index 97296d0fac5..0b728629dcb 100644 --- a/src/main/runtime/rpc/methods/terminal-orphan.ts +++ b/src/main/runtime/rpc/methods/terminal-orphan.ts @@ -1,110 +1,7 @@ -import { z } from 'zod' -import type { TabGroupLayoutNode } from '../../../../shared/tab-types' -import { isPtyIncarnationId, type PtyIncarnationId } from '../../../../shared/pty-incarnation' -import { defineMethod, type RpcAnyMethod } from '../core' -import { OptionalString, requiredString } from '../schemas' -import { TerminalPaneLayoutNodeSchema } from './session-tabs-schemas' +import { defineMethod } from '../core' +import { TerminalAdoptOrphans } from '../../../../shared/rpc-contract/terminal-orphan-params' -function parseOrphanGroupLayout(value: unknown): TabGroupLayoutNode | null { - const stack: { value: unknown; depth: number }[] = [{ value, depth: 0 }] - let count = 0 - while (stack.length > 0) { - const current = stack.pop()! - if ( - current.depth > 64 || - ++count > 1_024 || - !current.value || - typeof current.value !== 'object' - ) { - return null - } - const node = current.value as Record - if (node.type === 'leaf') { - if ( - typeof node.groupId !== 'string' || - node.groupId.length < 1 || - node.groupId.length > 256 - ) { - return null - } - continue - } - if ( - node.type !== 'split' || - (node.direction !== 'horizontal' && node.direction !== 'vertical') || - (node.ratio !== undefined && - (typeof node.ratio !== 'number' || - !Number.isFinite(node.ratio) || - node.ratio < 0 || - node.ratio > 1)) - ) { - return null - } - stack.push( - { value: node.first, depth: current.depth + 1 }, - { value: node.second, depth: current.depth + 1 } - ) - } - return value as TabGroupLayoutNode -} - -const TerminalOrphanGroupLayout = z - .unknown() - .transform(parseOrphanGroupLayout) - .pipe(z.custom((value) => value !== null, 'Invalid orphan group layout')) - -const TerminalOrphanTopology = z.object({ - tabs: z - .array( - z.object({ - tabId: requiredString('Missing topology tab id').pipe(z.string().max(256)), - root: TerminalPaneLayoutNodeSchema, - activeLeafId: requiredString('Missing active leaf id').pipe(z.string().max(128)), - expandedLeafId: z.string().max(128).nullable() - }) - ) - .min(1) - .max(64), - groups: z - .array( - z.object({ - id: z.string().min(1).max(256), - activeTabId: z.string().min(1).max(256), - tabOrder: z.array(z.string().min(1).max(256)).min(1).max(64), - recentTabIds: z.array(z.string().min(1).max(256)).max(64).optional() - }) - ) - .min(1) - .max(64), - groupLayout: TerminalOrphanGroupLayout.optional() -}) - -const TerminalOrphanIncarnationId = z.custom( - isPtyIncarnationId, - 'Invalid PTY incarnation' -) - -const TerminalAdoptOrphans = z.object({ - worktree: requiredString('Missing worktree selector').pipe(z.string().max(32_768)), - expectedTopologyRevision: z.number().int().nonnegative(), - claims: z - .array( - z.object({ - terminal: requiredString('Missing terminal handle').pipe(z.string().max(256)), - ptyId: requiredString('Missing PTY id').pipe(z.string().max(8_192)), - incarnationId: TerminalOrphanIncarnationId, - tabId: requiredString('Missing tab id').pipe(z.string().max(256)), - leafId: requiredString('Missing leaf id').pipe(z.string().max(128)) - }) - ) - .min(1) - .max(64), - activeTabId: OptionalString.pipe(z.string().max(256).optional()), - activeGroupId: OptionalString.pipe(z.string().max(256).optional()), - topology: TerminalOrphanTopology.optional() -}) - -export const TERMINAL_ORPHAN_METHODS: RpcAnyMethod[] = [ +export const TERMINAL_ORPHAN_METHODS = [ defineMethod({ name: 'terminal.adoptOrphans', params: TerminalAdoptOrphans, diff --git a/src/main/runtime/rpc/methods/terminal-quick-command-rpc-schema.ts b/src/main/runtime/rpc/methods/terminal-quick-command-rpc-schema.ts index 18661f10b57..9d4511bbd4d 100644 --- a/src/main/runtime/rpc/methods/terminal-quick-command-rpc-schema.ts +++ b/src/main/runtime/rpc/methods/terminal-quick-command-rpc-schema.ts @@ -1,73 +1 @@ -import { z } from 'zod' -import type { TerminalQuickCommand } from '../../../../shared/terminal-quick-command-types' -import { - MAX_QUICK_COMMAND_AGENT_PROMPT_LENGTH, - MAX_QUICK_COMMAND_ID_LENGTH, - MAX_QUICK_COMMAND_LABEL_LENGTH, - MAX_QUICK_COMMAND_REPO_ID_LENGTH, - MAX_QUICK_COMMAND_TERMINAL_TEXT_LENGTH, - normalizeTerminalQuickCommands, - supportsTerminalAgentQuickCommand -} from '../../../../shared/terminal-quick-commands' - -const TerminalQuickCommandScopeUpdate = z.discriminatedUnion('type', [ - z.object({ type: z.literal('global') }).strict(), - z - .object({ - type: z.literal('repo'), - repoId: z.string().max(MAX_QUICK_COMMAND_REPO_ID_LENGTH) - }) - .strict() -]) - -const TerminalQuickCommandUpdateItem = z.union([ - z - .object({ - id: z.string().max(MAX_QUICK_COMMAND_ID_LENGTH), - label: z.string().max(MAX_QUICK_COMMAND_LABEL_LENGTH), - action: z.literal('terminal-command').optional(), - command: z.string().max(MAX_QUICK_COMMAND_TERMINAL_TEXT_LENGTH), - appendEnter: z.boolean(), - scope: TerminalQuickCommandScopeUpdate.optional() - }) - .strict(), - z - .object({ - id: z.string().max(MAX_QUICK_COMMAND_ID_LENGTH), - label: z.string().max(MAX_QUICK_COMMAND_LABEL_LENGTH), - action: z.literal('agent-prompt'), - agent: z.custom(supportsTerminalAgentQuickCommand, { - message: 'Agent does not support prompt commands' - }), - prompt: z.string().max(MAX_QUICK_COMMAND_AGENT_PROMPT_LENGTH), - scope: TerminalQuickCommandScopeUpdate.optional() - }) - .strict() -]) - -export const TerminalQuickCommandsUpdate = z - .object({ - // Why: a single host-side mutation preserves unrelated desktop/mobile edits - // and avoids retransmitting the full ~240 KB list for every small change. - mutation: z.union([ - z - .object({ - type: z.literal('upsert'), - command: TerminalQuickCommandUpdateItem.transform( - (value) => normalizeTerminalQuickCommands([value])[0] - ).pipe( - z.custom((value) => value !== undefined, { - message: 'Quick command cannot be normalized' - }) - ) - }) - .strict(), - z - .object({ - type: z.literal('delete'), - id: z.string().min(1).max(MAX_QUICK_COMMAND_ID_LENGTH) - }) - .strict() - ]) - }) - .strict() +export { TerminalQuickCommandsUpdate } from '../../../../shared/rpc-contract/terminal-quick-command-params' diff --git a/src/main/runtime/rpc/methods/terminal.ts b/src/main/runtime/rpc/methods/terminal.ts index e80d07773dc..607a29329cd 100644 --- a/src/main/runtime/rpc/methods/terminal.ts +++ b/src/main/runtime/rpc/methods/terminal.ts @@ -1,4 +1,3 @@ -import type { RpcAnyMethod } from '../core' import { TERMINAL_LIFECYCLE_METHODS } from './terminal/terminal-lifecycle-methods' import { TERMINAL_MULTIPLEX_METHODS } from './terminal/terminal-multiplex-method' import { TERMINAL_QUERY_METHODS } from './terminal/terminal-query-methods' @@ -11,7 +10,7 @@ import { // The manifest order is part of the released RPC contract. Keep composition here so the // public entry point owns registration rather than forwarding an aggregated child export. -export const TERMINAL_METHODS: RpcAnyMethod[] = [ +export const TERMINAL_METHODS = [ ...TERMINAL_QUERY_METHODS, ...TERMINAL_SEND_METHODS, ...TERMINAL_LIFECYCLE_METHODS, diff --git a/src/main/runtime/rpc/methods/terminal/stream-schemas.ts b/src/main/runtime/rpc/methods/terminal/stream-schemas.ts index 04a6990fe51..f3e6e3a7870 100644 --- a/src/main/runtime/rpc/methods/terminal/stream-schemas.ts +++ b/src/main/runtime/rpc/methods/terminal/stream-schemas.ts @@ -1,43 +1,12 @@ import { z } from 'zod' import { requiredString } from '../../schemas' import { TerminalViewport } from './unary-schemas' - -const TerminalHandle = z.object({ terminal: requiredString('Missing terminal handle') }) - -export const TerminalResizeForClient = z.discriminatedUnion('mode', [ - z.object({ - terminal: requiredString('Missing terminal handle'), - mode: z.literal('mobile-fit'), - cols: z.number().finite().positive(), - rows: z.number().finite().positive(), - clientId: requiredString('Missing client ID') - }), - z.object({ - terminal: requiredString('Missing terminal handle'), - mode: z.literal('restore'), - clientId: requiredString('Missing client ID') - }) -]) - -export const TerminalSubscribe = TerminalHandle.extend({ - client: z - .object({ - id: requiredString('Missing client ID'), - type: z.enum(['mobile', 'desktop']).default('desktop') - }) - .optional(), - viewport: TerminalViewport.optional(), - capabilities: z - .object({ - terminalBinaryStream: z.literal(1).optional(), - desktopViewportClaims: z.literal(1).optional(), - mobileInputLeaseOnly: z.literal(1).optional(), - writeUnavailable: z.literal(1).optional() - }) - .optional() -}) - -export const TerminalMultiplex = z.object({}) +import { TerminalHandle } from '../../../../../shared/rpc-contract/terminal-stream-params' +export { + TerminalMultiplex, + TerminalResizeForClient, + TerminalSubscribe +} from '../../../../../shared/rpc-contract/terminal-stream-params' export const TerminalMultiplexSubscribeFrame = TerminalHandle.extend({ streamId: z.number().int().min(1), diff --git a/src/main/runtime/rpc/methods/terminal/terminal-inspect-process-params.test.ts b/src/main/runtime/rpc/methods/terminal/terminal-inspect-process-params.test.ts index 48649bc372c..8377f923ecc 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-inspect-process-params.test.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-inspect-process-params.test.ts @@ -6,10 +6,13 @@ import { describe, expect, it, vi } from 'vitest' import type { ZodType } from 'zod' import { TERMINAL_QUERY_METHODS } from './terminal-query-methods' import { TerminalHandle, TerminalInspectProcess } from './unary-schemas' +import { eraseRpcMethods } from '../../core' /** The method as registered, so a schema swap on the definition cannot pass unseen. */ function inspectProcessMethod() { - const method = TERMINAL_QUERY_METHODS.find((entry) => entry.name === 'terminal.inspectProcess') + const method = eraseRpcMethods(TERMINAL_QUERY_METHODS).find( + (entry) => entry.name === 'terminal.inspectProcess' + ) if (!method) { throw new Error('terminal.inspectProcess is not registered') } @@ -25,7 +28,7 @@ async function callRegisteredHandler( foregroundProcess: null, hasChildProcesses: false })) - await method.handler(parsed, { runtime: { inspectTerminalProcess } } as never, undefined as never) + await method.handler(parsed, { runtime: { inspectTerminalProcess } } as never) const [terminal, options] = inspectTerminalProcess.mock.calls[0] as unknown as [string, unknown] return { terminal, options } } diff --git a/src/main/runtime/rpc/methods/terminal/terminal-lifecycle-methods.ts b/src/main/runtime/rpc/methods/terminal/terminal-lifecycle-methods.ts index 51dde7df4d8..891ed65a13f 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-lifecycle-methods.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-lifecycle-methods.ts @@ -1,4 +1,4 @@ -import { defineMethod, type RpcAnyMethod } from '../../core' +import { defineMethod } from '../../core' import { navigationTargetsHost, resolveRuntimeNavigationTarget @@ -19,7 +19,7 @@ import { } from './unary-schemas' import { TerminalResizeForClient } from './stream-schemas' -export const TERMINAL_LIFECYCLE_METHODS: RpcAnyMethod[] = [ +export const TERMINAL_LIFECYCLE_METHODS = [ defineMethod({ name: 'terminal.wait', params: TerminalWait, diff --git a/src/main/runtime/rpc/methods/terminal/terminal-multiplex-method.ts b/src/main/runtime/rpc/methods/terminal/terminal-multiplex-method.ts index 11fd0c4d039..e811614e400 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-multiplex-method.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-multiplex-method.ts @@ -1,4 +1,4 @@ -import { defineStreamingMethod, type RpcAnyMethod } from '../../core' +import { defineStreamingMethod } from '../../core' import { TerminalStreamOpcode } from '../../../../../shared/terminal-stream-protocol' import { TERMINAL_MULTIPLEX_ACK_TOTAL_INITIAL_WINDOW_BYTES } from '../../../../../shared/terminal-multiplex-flow-control' import { TerminalSourceRangeRegistry } from '../../terminal-source-range-registry' @@ -11,7 +11,7 @@ import { installMultiplexCleanup } from './terminal-multiplex-cleanup' import { installMultiplexSlotFrames } from './terminal-multiplex-slot-frames' import { installMultiplexSubscribeFrame } from './terminal-multiplex-subscribe-frame' -export const TERMINAL_MULTIPLEX_METHODS: RpcAnyMethod[] = [ +export const TERMINAL_MULTIPLEX_METHODS = [ defineStreamingMethod({ name: 'terminal.multiplex', params: TerminalMultiplex, diff --git a/src/main/runtime/rpc/methods/terminal/terminal-query-methods.ts b/src/main/runtime/rpc/methods/terminal/terminal-query-methods.ts index 82edd55cd79..52c1063b0cc 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-query-methods.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-query-methods.ts @@ -1,4 +1,4 @@ -import { defineMethod, type RpcAnyMethod } from '../../core' +import { defineMethod } from '../../core' import { TerminalHandle, TerminalInspectProcess, @@ -10,7 +10,7 @@ import { TerminalResolvePane } from './unary-schemas' -export const TERMINAL_QUERY_METHODS: RpcAnyMethod[] = [ +export const TERMINAL_QUERY_METHODS = [ defineMethod({ name: 'terminal.list', params: TerminalListParams, diff --git a/src/main/runtime/rpc/methods/terminal/terminal-send-method.ts b/src/main/runtime/rpc/methods/terminal/terminal-send-method.ts index ad471098e49..c62c70c5905 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-send-method.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-send-method.ts @@ -1,6 +1,6 @@ import { isAgentSessionPtyWriteRefusedError } from '../../../../../shared/agent-session-pty-write-admission' import { assertLegacyAiVaultResumeCommandAllowed } from '../../../../ai-vault/structured-session-ownership' -import { InvalidArgumentError, defineMethod, type RpcAnyMethod } from '../../core' +import { InvalidArgumentError, defineMethod } from '../../core' import { isTerminalQueryReply } from '../../../../../shared/terminal-query-reply' import { assertTerminalAgentSendable } from '../../terminal-agent-send-guard' import { TerminalSend } from './unary-schemas' @@ -20,7 +20,7 @@ import { observeReplayedTerminalPrompt } from './terminal-prompt-receipt' -export const TERMINAL_SEND_METHODS: RpcAnyMethod[] = [ +export const TERMINAL_SEND_METHODS = [ defineMethod({ name: 'terminal.send', params: TerminalSend, diff --git a/src/main/runtime/rpc/methods/terminal/terminal-subscribe-method.ts b/src/main/runtime/rpc/methods/terminal/terminal-subscribe-method.ts index bd16382d747..7572d41496f 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-subscribe-method.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-subscribe-method.ts @@ -1,4 +1,4 @@ -import { defineStreamingMethod, type RpcAnyMethod } from '../../core' +import { defineStreamingMethod } from '../../core' import { TerminalSubscribe } from './stream-schemas' import { isTerminalReadPayloadIncomplete } from './terminal-stream-replay' import { runTerminalBinarySubscription } from './terminal-legacy-subscribe-binary' @@ -8,7 +8,7 @@ import { } from './terminal-legacy-simple-subscriptions' import type { TerminalSubscriptionArgs } from './terminal-legacy-subscription-types' -export const TERMINAL_SUBSCRIBE_METHODS: RpcAnyMethod[] = [ +export const TERMINAL_SUBSCRIBE_METHODS = [ // Streams live terminal output over WebSocket; mobile clients pass client+viewport for server-side auto-fit. defineStreamingMethod({ name: 'terminal.subscribe', diff --git a/src/main/runtime/rpc/methods/terminal/terminal-viewport-methods.ts b/src/main/runtime/rpc/methods/terminal/terminal-viewport-methods.ts index 71feee4f24d..91bdf25d84d 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-viewport-methods.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-viewport-methods.ts @@ -1,5 +1,4 @@ -import { z } from 'zod' -import { defineMethod, type RpcAnyMethod } from '../../core' +import { defineMethod } from '../../core' import { TerminalHandle } from './unary-schemas' import { TerminalSetAutoRestoreFit, @@ -8,8 +7,9 @@ import { TerminalUpdateViewport } from './viewport-schemas' import { updateViewportForClient } from './terminal-viewport-update' +import { TerminalGetAutoRestoreFitParams } from '../../../../../shared/rpc-contract/terminal-viewport-methods-params' -export const TERMINAL_VIEWPORT_METHODS_BEFORE_STREAMS: RpcAnyMethod[] = [ +export const TERMINAL_VIEWPORT_METHODS_BEFORE_STREAMS = [ defineMethod({ name: 'terminal.setDisplayMode', params: TerminalSetDisplayMode, @@ -78,7 +78,7 @@ export const TERMINAL_VIEWPORT_METHODS_BEFORE_STREAMS: RpcAnyMethod[] = [ }) ] -export const TERMINAL_VIEWPORT_METHODS_AFTER_STREAMS: RpcAnyMethod[] = [ +export const TERMINAL_VIEWPORT_METHODS_AFTER_STREAMS = [ defineMethod({ name: 'terminal.unsubscribe', params: TerminalUnsubscribe, @@ -105,7 +105,7 @@ export const TERMINAL_VIEWPORT_METHODS_AFTER_STREAMS: RpcAnyMethod[] = [ }), defineMethod({ name: 'terminal.getAutoRestoreFit', - params: z.object({}), + params: TerminalGetAutoRestoreFitParams, handler: async (_params, { runtime }) => ({ ms: runtime.getMobileAutoRestoreFitMs() }) diff --git a/src/main/runtime/rpc/methods/terminal/unary-schemas.ts b/src/main/runtime/rpc/methods/terminal/unary-schemas.ts index 89928128e69..0b7f9d90408 100644 --- a/src/main/runtime/rpc/methods/terminal/unary-schemas.ts +++ b/src/main/runtime/rpc/methods/terminal/unary-schemas.ts @@ -1,222 +1,22 @@ -import { z } from 'zod' -import { OptionalFiniteNumber, OptionalString, requiredString } from '../../schemas' -import { TERMINAL_PANE_SPLIT_SOURCES } from '../../../../../shared/feature-education-telemetry' -import { isTuiAgent } from '../../../../../shared/tui-agent-config' - -export const TerminalHandle = z.object({ - terminal: requiredString('Missing terminal handle'), - // Additive fence understood by newer hosts; legacy hosts safely ignore it. - expectedIncarnationId: requiredString('Missing PTY incarnation').optional() -}) - -export const TerminalFocus = TerminalHandle.extend({ - navigation: z.enum(['caller', 'host']).optional() -}) - -/** - * `terminal.inspectProcess` carries one member the sibling handle methods must not: whether the - * caller's answer decides something once, which is what licenses the host to pay for a process-table - * read. Extended rather than added to `TerminalHandle` so `clearBuffer`/`agentStatus`/`isRunningAgent` - * keep refusing an option they have no use for. - */ -export const TerminalInspectProcess = TerminalHandle.extend({ - // Additive request member understood by newer hosts; legacy hosts safely ignore it. - scanChildProcesses: z.boolean().optional() -}) - -export const TerminalListParams = z.object({ - worktree: OptionalString, - limit: OptionalFiniteNumber, - handles: z - .array(requiredString('Missing terminal handle').pipe(z.string().max(256))) - .max(64) - .optional(), - requireFreshPtyLiveness: z.boolean().optional(), - // Why: layouts are ~31% of a large listing and only the human CLI formatter - // reads them. Absent means "include" so pre-flag clients keep rendering them. - includeVisualLayouts: z.boolean().optional() -}) - -export const TerminalResolveActive = z.object({ - worktree: OptionalString, - /** Refuse instead of guessing when several leaves could be the caller's own terminal. */ - requireUnambiguous: z.boolean().optional() -}) - -export const TerminalResolvePane = z.object({ - paneKey: requiredString('Missing pane key'), - worktreeId: OptionalString -}) - -export const TerminalRecoverPane = z.object({ - paneKey: requiredString('Missing pane key'), - worktreeId: requiredString('Missing worktree ID'), - expectedTerminal: requiredString('Missing expected terminal handle').optional() -}) - -export const TerminalRead = TerminalHandle.extend({ - cursor: z - .unknown() - .transform((value) => { - if (value === undefined) { - return undefined - } - if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) { - return Number.NaN - } - return value - }) - .pipe( - z - .number() - .optional() - .refine((v) => v === undefined || Number.isFinite(v), { - message: 'Cursor must be a non-negative integer' - }) - ) - .optional(), - limit: OptionalFiniteNumber, - // Why: optional so an older host that does not understand it simply drops the key and answers - // with its usual stream read; the response's `source` is what tells the caller which it got. - screen: z.literal(true).optional() -}).refine((params) => !(params.screen === true && params.cursor !== undefined), { - // Why: a cursor pages through accumulated output; a screen is the current frame with nothing - // behind it. Honoring both would answer with rendered lines carrying the stream's pagination - // metadata — two frames of reference in one payload, which is the confusion `source` exists to - // remove. The CLI already refuses the pair, but the RPC is reachable without it. - message: 'Cursor cannot be combined with a screen read' -}) - -// Why: preserve the legacy contract — `title: string | null` only, `undefined` rejected, so the CLI's "reset" signal stays distinct. -export const TerminalRename = TerminalHandle.extend({ - title: z.custom((value) => value === null || typeof value === 'string', { - message: 'Missing --title (pass empty string or null to reset)' - }) -}) - -export const TerminalSend = TerminalHandle.extend({ - text: OptionalString, - enter: z.unknown().optional(), - interrupt: z.unknown().optional(), - // Why: older hosts strip this optional intent and retain their direct-send behavior. - agentPrompt: z.literal(true).optional(), - // Why: waiting observes the same prompt receipt; it never authorizes a second write. - waitSubmitMs: z.number().int().min(0).max(3_600_000).optional(), - resolvedLaunchDraft: z - .object({ - text: z.string(), - createdAt: z.number().finite() - }) - .optional(), - requireAgentStatus: z.enum(['sendable']).optional(), - // Why: terminal-generated replies are valid input but must not transfer the shared terminal floor. - inputKind: z.enum(['query-reply']).optional(), - // Why: identifies the caller for the driver state machine; when absent (older clients) the server falls back to the most recent mobile actor (docs/mobile-presence-lock.md). - client: z - .object({ - id: requiredString('Missing client ID'), - type: z.enum(['mobile', 'desktop']).default('desktop').optional() - }) - .optional(), - viewport: z - .object({ - cols: z.number().int().min(1).max(1000), - rows: z.number().int().min(1).max(500) - }) - .optional(), - claimViewport: z.literal(true).optional() -}) - -export const TerminalViewport = z.object({ - cols: z.number().int().min(1).max(1000), - rows: z.number().int().min(1).max(500) -}) - -export const TerminalWait = TerminalHandle.extend({ - for: z.custom<'exit' | 'tui-idle'>((value) => value === 'exit' || value === 'tui-idle', { - message: 'Invalid --for value. Supported: exit, tui-idle' - }), - timeoutMs: OptionalFiniteNumber -}) - -export const TerminalCreateParams = z.object({ - worktree: OptionalString, - clientMutationId: z.string().min(1).max(128).optional(), - reconcileExisting: z.boolean().optional(), - command: OptionalString, - startupCommandDelivery: z.enum(['fast', 'shell-ready']).optional(), - env: z.record(z.string(), z.string()).optional(), - envToDelete: z.array(z.string().min(1).max(256)).max(32).optional(), - launchConfig: z - .object({ - agentCommand: z.string().optional(), - agentArgs: z.string(), - agentEnv: z.record(z.string(), z.string()), - ompResumeFilePath: z - .string() - .min(1) - .max(32 * 1024) - .optional() - }) - .optional(), - resumeProviderSession: z - .object({ - key: z.enum(['session_id', 'conversation_id']), - id: z.string().min(1).max(512), - transcriptPath: z.string().min(1).max(32_768).optional() - }) - .optional(), - launchToken: OptionalString, - launchAgent: z.string().refine(isTuiAgent).optional(), - terminalColorQueryReplies: z - .object({ - foreground: z.string().max(128).optional(), - background: z.string().max(128).optional() - }) - .optional(), - title: OptionalString, - focus: z.unknown().optional(), - rendererBacked: z.unknown().optional(), - activate: z.unknown().optional(), - presentation: z.enum(['background', 'focused']).optional(), - tabId: OptionalString, - leafId: OptionalString -}) - -export const TerminalSplit = TerminalHandle.extend({ - direction: z - .unknown() - .transform((v) => (v === 'vertical' || v === 'horizontal' ? v : undefined)) - .pipe(z.union([z.enum(['vertical', 'horizontal']), z.undefined()])) - .optional(), - command: OptionalString, - env: z.record(z.string(), z.string()).optional(), - telemetrySource: z.enum(TERMINAL_PANE_SPLIT_SOURCES).optional() -}) - -export const TerminalStop = z.object({ - worktree: requiredString('Missing worktree selector') -}) - -export const TerminalCloseAll = TerminalStop - -export const TerminalSleep = TerminalStop - -export const TerminalStopExact = TerminalStop.extend({ - expectedPtyIds: z.array(requiredString('Missing PTY ID')).min(1), - keepHistory: z.boolean().optional(), - targetOnly: z.boolean().optional() -}) - -export const AgentTeamsTmuxCompat = z.object({ - teamId: requiredString('Missing agent team ID'), - token: requiredString('Missing agent team token'), - envPane: requiredString('Missing tmux pane identity'), - cwd: OptionalString, - argv: z.array(z.string()) -}) - -export const AgentTeamsPrepareLaunch = z.object({ - paneKey: requiredString('Missing pane key'), - env: z.record(z.string(), z.string()).optional() -}) +export { + AgentTeamsPrepareLaunch, + AgentTeamsTmuxCompat, + TerminalCloseAll, + TerminalCreateParams, + TerminalFocus, + TerminalHandle, + TerminalInspectProcess, + TerminalListParams, + TerminalRead, + TerminalRecoverPane, + TerminalRename, + TerminalResolveActive, + TerminalResolvePane, + TerminalSend, + TerminalSleep, + TerminalSplit, + TerminalStop, + TerminalStopExact, + TerminalViewport, + TerminalWait +} from '../../../../../shared/rpc-contract/terminal-unary-params' diff --git a/src/main/runtime/rpc/methods/terminal/viewport-schemas.ts b/src/main/runtime/rpc/methods/terminal/viewport-schemas.ts index d9b76d66ea1..70ecd9037d1 100644 --- a/src/main/runtime/rpc/methods/terminal/viewport-schemas.ts +++ b/src/main/runtime/rpc/methods/terminal/viewport-schemas.ts @@ -1,51 +1,6 @@ -import { z } from 'zod' -import { requiredString } from '../../schemas' - -const TerminalHandle = z.object({ terminal: requiredString('Missing terminal handle') }) - -export const TerminalSetDisplayMode = TerminalHandle.extend({ - // Why: 'auto' = mobile drives dims while subscribed (desktop restores on last-leave); 'desktop' = no resize, mobile scales to fit. - mode: z.enum(['auto', 'desktop']), - // Why: identifies the caller for the driver state machine; optional for older mobile clients. - client: z - .object({ - id: requiredString('Missing client ID'), - type: z.enum(['mobile', 'desktop']).default('desktop').optional() - }) - .optional(), - // Why: carries the measured viewport so an 'auto' toggle on a viewport-less record can phone-fit instead of no-op'ing. - viewport: z - .object({ - cols: z.number().int().positive(), - rows: z.number().int().positive() - }) - .optional() -}) - -export const TerminalUnsubscribe = z.object({ - subscriptionId: requiredString('Missing subscription ID'), - // Why: lets the server rebuild the composite `${terminal}:${clientId}` cleanup key when older clients pass a bare subscriptionId (docs/mobile-presence-lock.md). - client: z - .object({ - id: requiredString('Missing client ID') - }) - .optional() -}) - -// Why: in-place update avoids an unsubscribe→resubscribe that flashed the lock banner and stranded the PTY at phone dims (docs/mobile-presence-lock.md). -export const TerminalUpdateViewport = TerminalHandle.extend({ - client: z.object({ - id: requiredString('Missing client ID'), - type: z.enum(['mobile', 'desktop']).default('mobile').optional() - }), - viewport: z.object({ - cols: z.number().int().min(20).max(240), - rows: z.number().int().min(8).max(120) - }), - claim: z.boolean().optional() -}) - -// Why: phone-fit auto-restore preference (docs/mobile-fit-hold.md); `null` = Indefinite, finite ms clamped to [5_000, 60min] server-side. -export const TerminalSetAutoRestoreFit = z.object({ - ms: z.number().nullable() -}) +export { + TerminalSetAutoRestoreFit, + TerminalSetDisplayMode, + TerminalUnsubscribe, + TerminalUpdateViewport +} from '../../../../../shared/rpc-contract/terminal-viewport-schemas-params' diff --git a/src/main/runtime/rpc/methods/ui-update-value-tolerance.ts b/src/main/runtime/rpc/methods/ui-update-value-tolerance.ts index 1b8ca0c2cd4..e03a9bfad06 100644 --- a/src/main/runtime/rpc/methods/ui-update-value-tolerance.ts +++ b/src/main/runtime/rpc/methods/ui-update-value-tolerance.ts @@ -1,25 +1,4 @@ -import type { z } from 'zod' - -/** - * `UiUpdate` rides App.tsx's debounced writer, so one drifted enum member used - * to fail the WHOLE batch and silently drop sidebar widths, filters and agent - * acks alongside it. Degrade instead: a value the schema cannot express is - * dropped from the payload and the rest of the batch still lands. Unknown KEYS - * stay a hard rejection — the parity assertions exist to catch those. - */ -export function tolerateUnknownValues(shape: TShape): TShape { - return Object.fromEntries( - Object.entries(shape).map(([key, schema]) => [ - key, - (schema as z.ZodType).catch(() => undefined) - ]) - ) as unknown as TShape -} - -/** Drops the `undefined` entries `tolerateUnknownValues` leaves behind, so a - * rejected value reads as absent rather than as an explicit clear. */ -export function omitUndefinedValues>(value: TValue): TValue { - return Object.fromEntries( - Object.entries(value).filter(([, entry]) => entry !== undefined) - ) as TValue -} +export { + omitUndefinedValues, + tolerateUnknownValues +} from '../../../../shared/rpc-contract/ui-update-value-tolerance-params' diff --git a/src/main/runtime/rpc/methods/updater.test.ts b/src/main/runtime/rpc/methods/updater.test.ts index 9c3ce0ef810..1a925cbe767 100644 --- a/src/main/runtime/rpc/methods/updater.test.ts +++ b/src/main/runtime/rpc/methods/updater.test.ts @@ -1,4 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' +import { eraseRpcMethods, type RpcMethodDeclaration } from '../core' import { configureRemoteServerUpdater } from '../../remote-server-updater' import { STATUS_METHODS } from './status' import { UPDATER_METHODS } from './updater' @@ -10,8 +11,8 @@ const snapshot = { status: { state: 'available', version: '1.5.1', changelog: null } } as const -function handler(methods: typeof UPDATER_METHODS, name: string) { - const method = methods.find((candidate) => candidate.name === name) +function handler(methods: readonly RpcMethodDeclaration[], name: string) { + const method = eraseRpcMethods(methods).find((candidate) => candidate.name === name) if (!method) { throw new Error(`Missing method ${name}`) } diff --git a/src/main/runtime/rpc/methods/updater.ts b/src/main/runtime/rpc/methods/updater.ts index 1baa2aff53b..a14fb5ab6a4 100644 --- a/src/main/runtime/rpc/methods/updater.ts +++ b/src/main/runtime/rpc/methods/updater.ts @@ -1,13 +1,13 @@ -import { defineMethod, type RpcMethod } from '../core' -import { z } from 'zod' +import { defineMethod } from '../core' import { checkRemoteServerUpdater, downloadRemoteServerUpdater, getRemoteServerUpdaterSnapshot, installRemoteServerUpdater } from '../../remote-server-updater' +import { UpdaterCheckParams } from '../../../../shared/rpc-contract/updater-params' -export const UPDATER_METHODS: RpcMethod[] = [ +export const UPDATER_METHODS = [ defineMethod({ name: 'updater.getStatus', params: null, @@ -15,10 +15,7 @@ export const UPDATER_METHODS: RpcMethod[] = [ }), defineMethod({ name: 'updater.check', - params: z.object({ - includePrerelease: z.boolean().optional(), - includePerfPrerelease: z.boolean().optional() - }), + params: UpdaterCheckParams, handler: (params, { runtime }) => checkRemoteServerUpdater(runtime.getRuntimeId(), params) }), defineMethod({ diff --git a/src/main/runtime/rpc/methods/workspace-cleanup-ui-schema.ts b/src/main/runtime/rpc/methods/workspace-cleanup-ui-schema.ts index 624a63ff44e..11e6cab4ee3 100644 --- a/src/main/runtime/rpc/methods/workspace-cleanup-ui-schema.ts +++ b/src/main/runtime/rpc/methods/workspace-cleanup-ui-schema.ts @@ -1,30 +1 @@ -import { z } from 'zod' -import { - normalizeWorkspaceCleanupBrowseState, - type WorkspaceCleanupBrowseState -} from '../../../../shared/workspace-cleanup-browse-state' - -const WorkspaceCleanupDismissal = z.object({ - worktreeId: z.string(), - dismissedAt: z.number().finite(), - fingerprint: z.string(), - classifierVersion: z.number().finite(), - executionHostId: z.string().min(1).optional() -}) - -/** - * Deliberately unvalidated shape, then normalized: the filter groups must NOT be - * strict or enumerated here. A newer client sends filters this build has never - * heard of, and a per-field zod shape would reject the whole `ui.set` payload - * instead of persisting the parts the host does understand. The shared - * normalizer never throws and degrades field by field, so an older host narrows - * the state rather than refusing it. - */ -const WorkspaceCleanupBrowse = z - .custom() - .transform((value) => normalizeWorkspaceCleanupBrowseState(value)) - -export const WorkspaceCleanup = z.object({ - dismissals: z.record(z.string(), WorkspaceCleanupDismissal), - browse: WorkspaceCleanupBrowse.optional() -}) +export { WorkspaceCleanup } from '../../../../shared/rpc-contract/workspace-cleanup-ui-params' diff --git a/src/main/runtime/rpc/methods/workspace-ports.ts b/src/main/runtime/rpc/methods/workspace-ports.ts index 9a6ff82764b..c96c91b436d 100644 --- a/src/main/runtime/rpc/methods/workspace-ports.ts +++ b/src/main/runtime/rpc/methods/workspace-ports.ts @@ -1,18 +1,10 @@ -import { z } from 'zod' -import { defineMethod, type RpcMethod } from '../core' -import { OptionalString, requiredNumber } from '../schemas' +import { defineMethod } from '../core' +import { + WorkspacePortKillParams, + WorkspacePortScanParams +} from '../../../../shared/rpc-contract/workspace-ports-params' -const WorkspacePortScanParams = z.object({ - repoId: OptionalString -}) - -const WorkspacePortKillParams = z.object({ - repoId: OptionalString, - pid: requiredNumber('Missing process id'), - port: requiredNumber('Missing port') -}) - -export const WORKSPACE_PORT_METHODS: RpcMethod[] = [ +export const WORKSPACE_PORT_METHODS = [ defineMethod({ name: 'workspacePorts.scan', params: WorkspacePortScanParams, diff --git a/src/main/runtime/rpc/methods/worktree-catalog-methods.ts b/src/main/runtime/rpc/methods/worktree-catalog-methods.ts index 2010a219b7c..8b230c169d8 100644 --- a/src/main/runtime/rpc/methods/worktree-catalog-methods.ts +++ b/src/main/runtime/rpc/methods/worktree-catalog-methods.ts @@ -1,4 +1,4 @@ -import { defineMethod, type RpcMethod } from '../core' +import { defineMethod } from '../core' import { resolveWorktreeCatalogSnapshot } from '../worktree-catalog-snapshot' import { supportsWorktreeVisibilitySourceDefaults } from '../worktree-visibility-client-capability' import { @@ -7,7 +7,7 @@ import { WorktreePsParams } from './worktree-schemas' -export const WORKTREE_CATALOG_METHODS: RpcMethod[] = [ +export const WORKTREE_CATALOG_METHODS = [ defineMethod({ name: 'worktree.ps', params: WorktreePsParams, diff --git a/src/main/runtime/rpc/methods/worktree-create-schemas.ts b/src/main/runtime/rpc/methods/worktree-create-schemas.ts index 61f6eb65e35..659f0c87fcf 100644 --- a/src/main/runtime/rpc/methods/worktree-create-schemas.ts +++ b/src/main/runtime/rpc/methods/worktree-create-schemas.ts @@ -1,154 +1,4 @@ -import { z } from 'zod' -import { isTuiAgent } from '../../../../shared/tui-agent-config' -import { workspaceSourceSchema } from '../../../../shared/telemetry-events' -import { sleepingAgentLaunchConfigSchema } from '../../../../shared/workspace-session-sleeping-agents' -import { RUNTIME_NAVIGATION_TARGETS } from '../../../../shared/runtime-navigation' -import { TaskSourceContextSchema } from '../../../../shared/task-source-context-schema' -import { WorkspaceLinkedItemSchema } from '../../../../shared/workspace-linked-item-schema' -import { - OptionalBoolean, - OptionalFiniteNumber, - OptionalString, - TriStateLinkedIssue -} from '../schemas' -import { - assertLinkedWorkItemSourceContextMatch, - AutomationWorkspaceProvenanceRequest, - CliWorkspaceProvenanceRequest, - OptionalTuiAgent -} from './worktree-schemas' - -export const WorktreeCreate = z - .object({ - repo: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing repo selector')), - name: OptionalString, - /** Set by clients that fell back to a generated creature name. Absent means user-typed, so the - * host neither skips a retired candidate nor retires the name it lands on. */ - nameWasGenerated: z.boolean().optional(), - baseBranch: OptionalString, - compareBaseRef: OptionalString, - branchNameOverride: OptionalString, - linkedIssue: TriStateLinkedIssue, - linkedPR: TriStateLinkedIssue, - linkedLinearIssue: z.string().optional(), - linkedLinearIssueWorkspaceId: z.union([z.string(), z.null()]).optional(), - linkedLinearIssueOrganizationUrlKey: z.union([z.string(), z.null()]).optional(), - linkedGitLabMR: TriStateLinkedIssue, - linkedGitLabIssue: TriStateLinkedIssue, - linkedBitbucketPR: TriStateLinkedIssue, - linkedAzureDevOpsPR: TriStateLinkedIssue, - linkedGiteaPR: TriStateLinkedIssue, - linkedWorkItem: WorkspaceLinkedItemSchema.nullable().optional(), - linkedTaskSourceContext: TaskSourceContextSchema.nullable().optional(), - comment: OptionalString, - displayName: OptionalString, - displayNameKind: z.enum(['generated', 'user']).optional(), - telemetrySource: z - .unknown() - .transform((value) => { - const parsed = workspaceSourceSchema.safeParse(value) - return parsed.success ? parsed.data : undefined - }) - .optional(), - workspaceStatus: OptionalString, - manualOrder: OptionalFiniteNumber, - sparseCheckout: z - .object({ - directories: z.array(z.string()), - presetId: OptionalString - }) - .optional(), - pushTarget: z - .object({ - remoteName: z.string(), - branchName: z.string(), - remoteUrl: OptionalString - }) - .optional(), - runHooks: OptionalBoolean, - activate: OptionalBoolean, - // Why: activation on create is view intent, so it is addressed like worktree.activate. - // Contract: a paired desktop/web caller resolves to 'caller' and therefore receives NO - // activateWorktree event — it must reveal from this call's result, which carries setup, - // startup and defaultTabs. Pass an explicit target to opt into an all-surface reveal. - navigation: z.enum(RUNTIME_NAVIGATION_TARGETS).optional(), - parentWorkspace: OptionalString, - // Why: an app-selected parent is a manual action, not the CLI's `--parent-workspace` flag. - // Absent keeps the CLI provenance older clients rely on. - parentWorkspaceOrigin: z.literal('manual').optional(), - envParentWorkspace: OptionalString, - parentWorktree: OptionalString, - cwdParentWorktree: OptionalString, - noParent: OptionalBoolean, - callerTerminalHandle: OptionalString, - orchestrationContext: z - .object({ - parentWorktreeId: OptionalString, - orchestrationRunId: OptionalString, - taskId: OptionalString, - coordinatorHandle: OptionalString - }) - .optional(), - setupDecision: z - .unknown() - .transform((v) => - typeof v === 'string' && (v === 'run' || v === 'skip' || v === 'inherit') ? v : undefined - ) - .pipe(z.union([z.enum(['run', 'skip', 'inherit']), z.undefined()])) - .optional(), - // Why: some clients (e.g. desktop) pass a pre-built launch command so the - // first terminal pane launches the selected agent instead of an idle shell. - // Clients that can't quote for the host shell send `startupAgent` instead. - startupCommand: OptionalString, - startupEnv: z.record(z.string(), z.string()).optional(), - startupLaunchConfig: sleepingAgentLaunchConfigSchema, - startupCommandDelivery: z.enum(['fast', 'shell-ready']).optional(), - // Why: CLI clients should not hardcode agent launch quoting because SSH - // workspaces execute in a different shell than the client process. - startupAgent: OptionalTuiAgent, - startupPrompt: OptionalString, - // Why: task-driven mobile creates need desktop parity: the host chooses - // the same default/detected agent and drafts the linked issue/PR URL into it. - startupDraft: OptionalString, - createdWithAgent: z - .unknown() - .transform((value) => (isTuiAgent(value) ? value : undefined)) - .optional(), - // Why: mobile retries a create interrupted by a connection migration with the - // same key so the host dedupes instead of spawning a duplicate worktree. - clientMutationId: z.string().min(1).max(128).optional(), - automationProvenanceRequest: AutomationWorkspaceProvenanceRequest.optional(), - cliProvenanceRequest: CliWorkspaceProvenanceRequest.optional() - }) - .superRefine((params, ctx) => { - assertLinkedWorkItemSourceContextMatch(params, ctx) - if ((params.parentWorkspace || params.parentWorktree) && params.noParent === true) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: 'Choose either one parent selector or --no-parent.' - }) - } - if (params.parentWorkspace && params.parentWorktree) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: 'Choose either one parent selector or --no-parent.' - }) - } - if (params.startupPrompt !== undefined && params.startupAgent === undefined) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: 'startupPrompt requires startupAgent' - }) - } - }) - -export const WorktreePrefetchCreateBase = z.object({ - repo: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing repo selector')), - baseBranch: OptionalString -}) +export { + WorktreeCreate, + WorktreePrefetchCreateBase +} from '../../../../shared/rpc-contract/worktree-create-params' diff --git a/src/main/runtime/rpc/methods/worktree-schemas.ts b/src/main/runtime/rpc/methods/worktree-schemas.ts index b7c3b9493a9..41d2c38fec7 100644 --- a/src/main/runtime/rpc/methods/worktree-schemas.ts +++ b/src/main/runtime/rpc/methods/worktree-schemas.ts @@ -1,215 +1,18 @@ -import { z } from 'zod' -import { isTuiAgent } from '../../../../shared/tui-agent-config' -import type { TuiAgent } from '../../../../shared/tui-agent' -import { RUNTIME_NAVIGATION_TARGETS } from '../../../../shared/runtime-navigation' -import { - OptionalBoolean, - OptionalFiniteNumber, - OptionalPlainString, - OptionalString, - TriStateLinkedIssue -} from '../schemas' -import { TaskSourceContextSchema } from '../../../../shared/task-source-context-schema' -import { WorkspaceLinkedItemSchema } from '../../../../shared/workspace-linked-item-schema' -import { isWorkspaceLinkedItemSourceContextMatch } from '../../../../shared/workspace-linked-item-source-context' -import { normalizeExecutionHostId } from '../../../../shared/execution-host' - -const OptionalExecutionHostId = z - .string() - .transform((value, ctx) => { - const hostId = normalizeExecutionHostId(value) - if (!hostId) { - ctx.addIssue({ code: 'custom', message: 'Invalid host id' }) - return z.NEVER - } - return hostId - }) - .optional() - -export const OptionalTuiAgent = z - .unknown() - .superRefine((value, ctx) => { - if (value !== undefined && !isTuiAgent(value)) { - ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Unknown TUI agent' }) - } - }) - .transform((value): TuiAgent | undefined => (isTuiAgent(value) ? value : undefined)) - .optional() - -export const AutomationWorkspaceProvenanceRequest = z.object({ - automationId: z.string(), - automationRunId: z.string(), - dispatchToken: z.string(), - createRequestId: z.string() -}) - -// Why no dispatch token (unlike automation provenance): this is a descriptive -// origin marker for sidebar filtering, not an authority grant. The host stamps -// createdAt itself so a client clock can't skew sort order. -export const CliWorkspaceProvenanceRequest = z.object({ - callerTerminalHandle: OptionalString -}) - -export const WorktreeListParams = z.object({ - repo: OptionalString, - limit: OptionalFiniteNumber -}) - -export const WorktreeDetectedListParams = z.object({ - repo: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing repo selector')) -}) - -export const WorktreeTeardownMissingTerminalsParams = WorktreeDetectedListParams.extend({ - worktreeIds: z.array(z.string().min(1)).max(10_000), - connectionId: z.string().nullable().optional() -}) - -export const WorktreePsParams = z.object({ - limit: OptionalFiniteNumber, - afterSnapshotId: z.string().min(1).max(128).nullable().optional(), - supportsWorktreeVisibilitySourceDefaults: z.literal(true).optional() -}) - -export const WorktreeSortOrder = z.object({ - orderedIds: z.array(z.string()) -}) - -export const WorktreeSelector = z.object({ - worktree: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing worktree selector')) -}) - -export const WorktreeActivate = WorktreeSelector.extend({ - notifyClients: OptionalBoolean, - navigation: z.enum(RUNTIME_NAVIGATION_TARGETS).optional() -}) - -/** Shared by WorktreeCreate and WorktreeSet so the two error messages cannot drift. */ -export function assertLinkedWorkItemSourceContextMatch( - params: { - linkedWorkItem?: z.infer | null - linkedTaskSourceContext?: z.infer | null - }, - ctx: z.RefinementCtx -): void { - if ( - params.linkedWorkItem && - params.linkedTaskSourceContext && - !isWorkspaceLinkedItemSourceContextMatch(params.linkedWorkItem, params.linkedTaskSourceContext) - ) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: 'Linked work item and source context identities must match' - }) - } -} - -export const WorktreeSet = WorktreeSelector.extend({ - // Why: '' is the blanking contract — "fall back to the branch/folder name". - // OptionalString coerced it to undefined, so on remote/SSH hosts clearing the - // name was dropped here and the old name came back on the next refresh. - displayName: OptionalPlainString, - // Why: empty comments are meaningful metadata updates, so use the plain - // string parser instead of OptionalString's empty-as-undefined behavior. - comment: OptionalPlainString, - linkedIssue: TriStateLinkedIssue, - linkedPR: TriStateLinkedIssue, - suppressedGitHubPR: z.number().int().positive().nullable().optional(), - linkedLinearIssue: z.union([z.string(), z.null()]).optional(), - linkedLinearIssueWorkspaceId: z.union([z.string(), z.null()]).optional(), - linkedLinearIssueOrganizationUrlKey: z.union([z.string(), z.null()]).optional(), - linkedGitLabMR: TriStateLinkedIssue, - linkedGitLabIssue: TriStateLinkedIssue, - linkedBitbucketPR: TriStateLinkedIssue, - linkedAzureDevOpsPR: TriStateLinkedIssue, - linkedGiteaPR: TriStateLinkedIssue, - linkedWorkItem: WorkspaceLinkedItemSchema.nullable().optional(), - linkedTaskSourceContext: TaskSourceContextSchema.nullable().optional(), - isArchived: OptionalBoolean, - isUnread: OptionalBoolean, - isPinned: OptionalBoolean, - sortOrder: OptionalFiniteNumber, - manualOrder: OptionalFiniteNumber, - lastActivityAt: OptionalFiniteNumber, - createdAt: OptionalFiniteNumber, - sparseDirectories: z.array(z.string()).optional(), - sparseBaseRef: OptionalString, - sparsePresetId: OptionalString, - baseRef: OptionalString, - workspaceStatus: OptionalString, - pushTarget: z - .object({ - remoteName: z.string(), - branchName: z.string(), - remoteUrl: OptionalString - }) - .nullable() - .optional(), - diffComments: z.array(z.unknown()).optional(), - mobileDiffReview: z.unknown().optional(), - parentWorktree: OptionalString, - noParent: OptionalBoolean -}).superRefine((params, ctx) => { - assertLinkedWorkItemSourceContextMatch(params, ctx) - if (params.parentWorktree && params.noParent === true) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: 'Choose either --parent-worktree or --no-parent, not both.' - }) - } -}) - -export const WorktreeRemove = WorktreeSelector.extend({ - hostId: OptionalExecutionHostId, - force: OptionalBoolean, - // Why (#11960): the CLI's --force is an unambiguous force affordance, but the - // desktop sets `force` for an ordinary confirmed delete too, so the PTY-stop - // waiver travels on its own field. - allowUnverifiedPtyStop: OptionalBoolean, - runHooks: OptionalBoolean -}) - -export const WorktreeForceDeleteBranch = WorktreeSelector.extend({ - hostId: OptionalExecutionHostId, - branchName: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing branch name')), - expectedHead: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing expected branch head')) -}) - -export const WorktreeResolvePrBase = z.object({ - repo: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing repo selector')), - prNumber: z - .unknown() - .transform((v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0)) - .pipe(z.number().int().positive('Missing PR number')), - headRefName: OptionalString, - baseRefName: OptionalString, - isCrossRepository: OptionalBoolean -}) - -export const WorktreeResolveMrBase = z.object({ - repo: z - .unknown() - .transform((v) => (typeof v === 'string' ? v : '')) - .pipe(z.string().min(1, 'Missing repo selector')), - mrIid: z - .unknown() - .transform((v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0)) - .pipe(z.number().int().positive('Missing MR number')), - sourceBranch: OptionalString, - targetBranch: OptionalString, - isCrossRepository: OptionalBoolean -}) +export { + AutomationWorkspaceProvenanceRequest, + CliWorkspaceProvenanceRequest, + OptionalTuiAgent, + WorktreeActivate, + WorktreeDetectedListParams, + WorktreeForceDeleteBranch, + WorktreeListParams, + WorktreePsParams, + WorktreeRemove, + WorktreeResolveMrBase, + WorktreeResolvePrBase, + WorktreeSelector, + WorktreeSet, + WorktreeSortOrder, + WorktreeTeardownMissingTerminalsParams, + assertLinkedWorkItemSourceContextMatch +} from '../../../../shared/rpc-contract/worktree-params' diff --git a/src/main/runtime/rpc/methods/worktree-visibility-defaults-schema.ts b/src/main/runtime/rpc/methods/worktree-visibility-defaults-schema.ts index 8bb7e1d081e..19a6dba90be 100644 --- a/src/main/runtime/rpc/methods/worktree-visibility-defaults-schema.ts +++ b/src/main/runtime/rpc/methods/worktree-visibility-defaults-schema.ts @@ -1,19 +1 @@ -import { z } from 'zod' -import { - normalizeCustomWorktreeVisibilitySources, - normalizeWorktreeVisibilitySourcePreferences -} from '../../../../shared/worktree/visibility-sources' - -export const WorktreeVisibilityDefaultsUpdate = z - .object({ - external: z.enum(['hide', 'show']).optional(), - customSources: z - .unknown() - .transform((value) => normalizeCustomWorktreeVisibilitySources(value)) - .optional(), - sourcePreferences: z - .unknown() - .transform((value) => normalizeWorktreeVisibilitySourcePreferences(value)) - .optional() - }) - .strict() +export { WorktreeVisibilityDefaultsUpdate } from '../../../../shared/rpc-contract/worktree-visibility-defaults-params' diff --git a/src/main/runtime/rpc/methods/worktree.ts b/src/main/runtime/rpc/methods/worktree.ts index b3d816496c3..be8a0983036 100644 --- a/src/main/runtime/rpc/methods/worktree.ts +++ b/src/main/runtime/rpc/methods/worktree.ts @@ -5,7 +5,7 @@ import { } from '../../../automations/workspace-provenance' import { buildCliWorkspaceProvenance } from '../../../../shared/cli-workspace-provenance' import { displayNameUpdatePinsLabel } from '../../../../shared/worktree/display-name-provenance' -import { defineMethod, type RpcMethod } from '../core' +import { defineMethod } from '../core' import { buildManagedWorktreeCreateArgs } from './worktree-create-args' import { resolvePairedCallerHostId } from './paired-caller-host-id' import { resolveRuntimeNavigationTarget } from '../../../../shared/runtime-navigation' @@ -24,7 +24,7 @@ import { } from './worktree-schemas' import { WORKTREE_CATALOG_METHODS } from './worktree-catalog-methods' -export const WORKTREE_METHODS: RpcMethod[] = [ +export const WORKTREE_METHODS = [ ...WORKTREE_CATALOG_METHODS, defineMethod({ name: 'worktree.teardownMissingTerminals', diff --git a/src/main/runtime/rpc/schemas.ts b/src/main/runtime/rpc/schemas.ts index fb7b09d8ceb..2c469341be5 100644 --- a/src/main/runtime/rpc/schemas.ts +++ b/src/main/runtime/rpc/schemas.ts @@ -3,87 +3,15 @@ // recur across domains (optional worktree selector, bounded limit, browser // target envelope, etc.). Methods compose these to declare their real // contract without repeating the same `typeof` gymnastics 90 times. -import { z } from 'zod' - -// Why: the original handlers treated non-numeric/NaN limit values as "no -// limit" rather than as errors. Preserve that forgiving behavior so CLI -// callers passing stringified numbers or Infinity still reach the runtime. -// The outer optional() is required for omitted keys in Zod v4; an optional -// schema hidden behind pipe() still makes z.object require the property. -export const OptionalFiniteNumber = z - .unknown() - .transform((value) => (typeof value === 'number' && Number.isFinite(value) ? value : undefined)) - .pipe(z.union([z.number(), z.undefined()])) - .optional() - -export const OptionalPositiveInt = z - .unknown() - .transform((value) => - typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined - ) - .pipe(z.union([z.number(), z.undefined()])) - .optional() - -export const OptionalString = z - .unknown() - .transform((value) => (typeof value === 'string' && value.length > 0 ? value : undefined)) - .pipe(z.union([z.string(), z.undefined()])) - .optional() - -export const OptionalPlainString = z - .unknown() - .transform((value) => (typeof value === 'string' ? value : undefined)) - .pipe(z.union([z.string(), z.undefined()])) - .optional() - -export const OptionalBoolean = z - .unknown() - .transform((value) => (typeof value === 'boolean' ? value : undefined)) - .pipe(z.union([z.boolean(), z.undefined()])) - .optional() - -// Why: runtime handlers accept `linkedIssue: number | null | undefined` with -// distinct meanings — undefined means "no update", null means "clear", number -// means "set". The ambient JSON decode produces all three shapes as-is. -export const TriStateLinkedIssue = z - .unknown() - .transform((value) => { - if (value === null) { - return null - } - if (typeof value === 'number' && Number.isFinite(value)) { - return value - } - return undefined - }) - .pipe(z.union([z.number(), z.null(), z.undefined()])) - .optional() - -// Why: the legacy extractBrowserTarget treated worktree as a plain-string -// passthrough (empty string preserved) but `page` as non-empty-string. The -// browser bridge uses worktree-as-empty-string to mean "any worktree", so -// keep that asymmetry intact to avoid widening scope unexpectedly. -export const BrowserTarget = z.object({ - worktree: OptionalPlainString, - page: OptionalString -}) - -export function requiredString(message: string) { - return z - .unknown() - .transform((value) => (typeof value === 'string' ? value : '')) - .pipe(z.string().min(1, message)) -} - -export function requiredStringAllowingEmpty(message: string) { - return z.unknown().refine((value): value is string => typeof value === 'string', { message }) -} - -export function requiredNumber(message: string) { - return z - .unknown() - .transform((value) => - typeof value === 'number' && Number.isFinite(value) ? value : Number.NaN - ) - .pipe(z.number().refine((v) => Number.isFinite(v), { message })) -} +export { + BrowserTarget, + OptionalBoolean, + OptionalFiniteNumber, + OptionalPlainString, + OptionalPositiveInt, + OptionalString, + TriStateLinkedIssue, + requiredNumber, + requiredString, + requiredStringAllowingEmpty +} from '../../../shared/rpc-contract/rpc-param-primitives' diff --git a/src/main/runtime/runtime-agent-row-store.ts b/src/main/runtime/runtime-agent-row-store.ts deleted file mode 100644 index c0c58d7ca82..00000000000 --- a/src/main/runtime/runtime-agent-row-store.ts +++ /dev/null @@ -1,125 +0,0 @@ -import { - AGENT_STATUS_STALE_AFTER_MS, - type AgentStatusEntry, - type AgentStatusIpcPayload, - type ParsedAgentStatusPayload -} from '../../shared/agent-status-types' -import type { - RuntimeTerminalAgentStatus, - RuntimeMobileSessionTerminalTab -} from '../../shared/runtime-types' -import { mapExplicitAgentStateToRuntimeTerminalStatus } from './runtime-worktree-status-projection' -import type { RuntimeAgentRowSnapshot } from './runtime-worktree-agent-rows' -import type { RuntimePtyWorktreeRecord } from './runtime-terminal-state-records' - -export class RuntimeAgentRowStore { - private readonly byPaneKey = new Map() - - values(): IterableIterator { - return this.byPaneKey.values() - } - - retain(args: { - ptyId: string - paneKey: string - worktreeId?: string - tabId?: string - connectionId: string | null - payload: ParsedAgentStatusPayload - }): boolean { - const now = Date.now() - const previous = this.byPaneKey.get(args.paneKey) - const stateStartedAt = - previous?.payload.state === args.payload.state ? previous.stateStartedAt : now - this.byPaneKey.set(args.paneKey, { ...args, stateStartedAt, updatedAt: now }) - return ( - !previous || - previous.payload.state !== args.payload.state || - previous.payload.workingMode !== args.payload.workingMode || - previous.payload.prompt !== args.payload.prompt || - (previous.payload.agentType ?? null) !== (args.payload.agentType ?? null) || - (previous.payload.toolName ?? null) !== (args.payload.toolName ?? null) || - (previous.payload.interactivePrompt ?? null) !== (args.payload.interactivePrompt ?? null) || - (previous.payload.interrupted ?? false) !== (args.payload.interrupted ?? false) || - (previous.payload.turnCompletedAt ?? null) !== (args.payload.turnCompletedAt ?? null) || - (previous.payload.lastAssistantMessage ?? null) !== - (args.payload.lastAssistantMessage ?? null) - ) - } - - clearPty(ptyId: string): void { - for (const [paneKey, snapshot] of this.byPaneKey) { - if (snapshot.ptyId === ptyId) { - this.byPaneKey.delete(paneKey) - } - } - } - - getFreshForMobile( - paneKey: string, - pty: RuntimePtyWorktreeRecord | null, - tab: RuntimeMobileSessionTerminalTab - ): RuntimeAgentRowSnapshot | null { - let retained = this.byPaneKey.get(paneKey) ?? null - if (!retained) { - const ptyId = pty?.ptyId ?? tab.ptyId ?? null - if (ptyId) { - for (const snapshot of this.byPaneKey.values()) { - if (snapshot.ptyId === ptyId && (!retained || snapshot.updatedAt > retained.updatedAt)) { - retained = snapshot - } - } - } - } - return retained && Date.now() - retained.updatedAt <= AGENT_STATUS_STALE_AFTER_MS - ? retained - : null - } - - getFreshExplicit(args: { - handle: string - paneKey: string | null - hookRows: readonly AgentStatusIpcPayload[] - }): { - status: NonNullable - updatedAt: number - stateStartedAt: number - } | null { - const now = Date.now() - let bestStatus: NonNullable | null = null - let bestUpdatedAt = -1 - let bestStateStartedAt = -1 - const consider = ( - state: AgentStatusEntry['state'] | undefined, - updatedAt: number | null | undefined, - restoredUnconfirmed = false, - stateStartedAt?: number | null - ): void => { - if (!state || restoredUnconfirmed || typeof updatedAt !== 'number') { - return - } - if (now - updatedAt > AGENT_STATUS_STALE_AFTER_MS) { - return - } - const status = mapExplicitAgentStateToRuntimeTerminalStatus(state) - if (updatedAt > bestUpdatedAt || (updatedAt === bestUpdatedAt && status === 'permission')) { - bestStatus = status - bestUpdatedAt = updatedAt - bestStateStartedAt = typeof stateStartedAt === 'number' ? stateStartedAt : updatedAt - } - } - if (args.paneKey) { - const retained = this.byPaneKey.get(args.paneKey) - consider(retained?.payload.state, retained?.updatedAt, false, retained?.stateStartedAt) - } - for (const row of args.hookRows) { - if (row.terminalHandle !== args.handle && (!args.paneKey || row.paneKey !== args.paneKey)) { - continue - } - consider(row.state, row.receivedAt, row.restoredUnconfirmed, row.stateStartedAt) - } - return bestStatus - ? { status: bestStatus, updatedAt: bestUpdatedAt, stateStartedAt: bestStateStartedAt } - : null - } -} diff --git a/src/main/runtime/runtime-desktop-surface.ts b/src/main/runtime/runtime-desktop-surface.ts index ac1086e4f35..a36cc0b71f4 100644 --- a/src/main/runtime/runtime-desktop-surface.ts +++ b/src/main/runtime/runtime-desktop-surface.ts @@ -17,6 +17,7 @@ import type { BrowserWindow, IpcMainEvent } from 'electron' export type RuntimeDesktopSurface = { /** Show a native notification. Returns false when the host cannot, so callers can say so. */ + isAwayForMobileNotifications?(): boolean | undefined showNotification(input: { title: string; body: string }): boolean /** The renderer window with this id, or null when there is no desktop. */ findWindowById(id: number): BrowserWindow | null diff --git a/src/main/runtime/runtime-folder-worktree-create.ts b/src/main/runtime/runtime-folder-worktree-create.ts index efea3c22c72..ef7798c91f9 100644 --- a/src/main/runtime/runtime-folder-worktree-create.ts +++ b/src/main/runtime/runtime-folder-worktree-create.ts @@ -172,7 +172,7 @@ export async function createRuntimeFolderWorktree(args: { undefined, args.startup && !didSpawnStartup ? args.startup : undefined ) - } else if (deps.ptySpawnAvailable && !didSpawnStartup) { + } else if (deps.ptySpawnAvailable && !didSpawnStartup && !args.createdWithAgent) { try { await deps.createTerminal(`id:${worktree.id}`, { surfaceOwner: false }) } catch (error) { diff --git a/src/main/runtime/runtime-hook-agent-row-selection.test.ts b/src/main/runtime/runtime-hook-agent-row-selection.test.ts new file mode 100644 index 00000000000..662fc5c160f --- /dev/null +++ b/src/main/runtime/runtime-hook-agent-row-selection.test.ts @@ -0,0 +1,159 @@ +import { describe, expect, it } from 'vitest' +import { + selectFreshAgentRowForMobileTab, + selectFreshExplicitAgentStatus +} from './runtime-hook-agent-row-selection' +import { AGENT_STATUS_STALE_AFTER_MS } from '../../shared/agent-status-types' +import type { AgentStatusIpcPayload } from '../../shared/agent-status-types' + +const PANE_KEY = 'tab-1:11111111-1111-4111-8111-111111111111' +const OTHER_PANE_KEY = 'tab-1:22222222-2222-4222-8222-222222222222' +const HANDLE = 'term_selection' +const PROVIDER_SESSION = { key: 'session_id' as const, id: 'session-1' } + +function row(overrides: Partial = {}): AgentStatusIpcPayload { + const now = Date.now() + return { + paneKey: PANE_KEY, + tabId: 'tab-1', + worktreeId: 'worktree', + connectionId: null, + terminalHandle: HANDLE, + state: 'working', + prompt: 'ship it', + agentType: 'codex', + receivedAt: now, + stateStartedAt: now - 500, + ...overrides + } +} + +describe('selectFreshExplicitAgentStatus', () => { + it('matches on the terminal handle when the pane key has moved', () => { + const selected = selectFreshExplicitAgentStatus({ + handle: HANDLE, + paneKey: OTHER_PANE_KEY, + hookRows: [row()] + }) + expect(selected).toMatchObject({ status: 'working' }) + }) + + it('ignores a row belonging to neither the handle nor the pane', () => { + expect( + selectFreshExplicitAgentStatus({ + handle: 'term_other', + paneKey: OTHER_PANE_KEY, + hookRows: [row()] + }) + ).toBeNull() + }) + + it('refuses restored, identity-only and stale evidence rows', () => { + const args = { handle: HANDLE, paneKey: PANE_KEY } + expect( + selectFreshExplicitAgentStatus({ ...args, hookRows: [row({ restoredUnconfirmed: true })] }) + ).toBeNull() + expect( + selectFreshExplicitAgentStatus({ ...args, hookRows: [row({ providerSessionOnly: true })] }) + ).toBeNull() + expect( + selectFreshExplicitAgentStatus({ + ...args, + hookRows: [row({ receivedAt: Date.now() - AGENT_STATUS_STALE_AFTER_MS - 1 })] + }) + ).toBeNull() + expect( + selectFreshExplicitAgentStatus({ + ...args, + hookRows: [ + row({ + receivedAt: Date.now(), + evidenceObservedAt: Date.now() - AGENT_STATUS_STALE_AFTER_MS - 1 + }) + ] + }) + ).toBeNull() + }) + + it('prefers a permission row over a working row stamped at the same instant', () => { + const at = Date.now() + const selected = selectFreshExplicitAgentStatus({ + handle: HANDLE, + paneKey: PANE_KEY, + hookRows: [ + row({ receivedAt: at }), + row({ paneKey: OTHER_PANE_KEY, state: 'blocked', receivedAt: at }) + ] + }) + expect(selected?.status).toBe('permission') + }) +}) + +describe('selectFreshAgentRowForMobileTab', () => { + it('prefers the pane own row over one that only shares its terminal', () => { + const selected = selectFreshAgentRowForMobileTab({ + paneKey: PANE_KEY, + terminalHandle: HANDLE, + hookRows: [ + row({ paneKey: OTHER_PANE_KEY, prompt: 'sibling pane', receivedAt: Date.now() }), + row({ prompt: 'this pane', receivedAt: Date.now() - 50 }) + ] + }) + expect(selected?.payload.prompt).toBe('this pane') + }) + + it('falls back to the terminal handle once the pane key no longer matches', () => { + const selected = selectFreshAgentRowForMobileTab({ + paneKey: OTHER_PANE_KEY, + terminalHandle: HANDLE, + hookRows: [row()] + }) + expect(selected).toMatchObject({ paneKey: PANE_KEY, payload: { prompt: 'ship it' } }) + }) + + it('carries provider-session identity through a terminal-handle rejoin', () => { + const selected = selectFreshAgentRowForMobileTab({ + paneKey: OTHER_PANE_KEY, + terminalHandle: HANDLE, + hookRows: [row({ providerSession: PROVIDER_SESSION })] + }) + expect(selected?.providerSession).toEqual(PROVIDER_SESSION) + }) + + it('has no fallback when the tab is bound to no terminal', () => { + expect( + selectFreshAgentRowForMobileTab({ + paneKey: OTHER_PANE_KEY, + terminalHandle: null, + hookRows: [row()] + }) + ).toBeNull() + }) + + it('refuses restored, resume-identity and stale rows', () => { + const args = { paneKey: PANE_KEY, terminalHandle: HANDLE } + expect( + selectFreshAgentRowForMobileTab({ ...args, hookRows: [row({ restoredUnconfirmed: true })] }) + ).toBeNull() + expect( + selectFreshAgentRowForMobileTab({ ...args, hookRows: [row({ providerSessionOnly: true })] }) + ).toBeNull() + expect( + selectFreshAgentRowForMobileTab({ + ...args, + hookRows: [row({ receivedAt: Date.now() - AGENT_STATUS_STALE_AFTER_MS - 1 })] + }) + ).toBeNull() + expect( + selectFreshAgentRowForMobileTab({ + ...args, + hookRows: [ + row({ + receivedAt: Date.now(), + evidenceObservedAt: Date.now() - AGENT_STATUS_STALE_AFTER_MS - 1 + }) + ] + }) + ).toBeNull() + }) +}) diff --git a/src/main/runtime/runtime-hook-agent-row-selection.ts b/src/main/runtime/runtime-hook-agent-row-selection.ts new file mode 100644 index 00000000000..67c1b698a1d --- /dev/null +++ b/src/main/runtime/runtime-hook-agent-row-selection.ts @@ -0,0 +1,135 @@ +import { + AGENT_STATUS_STALE_AFTER_MS, + pickParsedAgentStatusPayload, + type AgentStatusEntry, + type AgentStatusIpcPayload, + type ParsedAgentStatusPayload +} from '../../shared/agent-status-types' +import type { AgentProviderSessionMetadata } from '../../shared/agent-session-resume' +import type { RuntimeTerminalAgentStatus } from '../../shared/runtime-types' +import { mapExplicitAgentStateToRuntimeTerminalStatus } from './runtime-worktree-status-projection' + +/** One hook-server row projected into the shape the runtime's own readers consume. */ +export type RuntimeAgentRowSnapshot = { + paneKey: string + worktreeId?: string + tabId?: string + connectionId: string | null + payload: ParsedAgentStatusPayload + stateStartedAt: number + updatedAt: number + evidenceObservedAt?: number + providerSession?: AgentProviderSessionMetadata +} + +function isLiveObservation(row: AgentStatusIpcPayload): boolean { + // A restored row cannot prove liveness (the turn may have ended while offline), and a + // resume-identity row carries no status at all. + return row.restoredUnconfirmed !== true && row.providerSessionOnly !== true +} + +/** The freshest explicit state for a terminal, matched on its handle or its pane key. */ +export function selectFreshExplicitAgentStatus(args: { + handle: string + paneKey: string | null + hookRows: readonly AgentStatusIpcPayload[] +}): { + status: NonNullable + updatedAt: number + stateStartedAt: number +} | null { + const now = Date.now() + let bestStatus: NonNullable | null = null + let bestUpdatedAt = -1 + let bestStateStartedAt = -1 + const consider = ( + state: AgentStatusEntry['state'] | undefined, + updatedAt: number | null | undefined, + evidenceObservedAt: number | null | undefined, + restoredUnconfirmed = false, + providerSessionOnly = false, + stateStartedAt?: number | null + ): void => { + if (!state || restoredUnconfirmed || providerSessionOnly || typeof updatedAt !== 'number') { + return + } + if (now - (evidenceObservedAt ?? updatedAt) > AGENT_STATUS_STALE_AFTER_MS) { + return + } + const status = mapExplicitAgentStateToRuntimeTerminalStatus(state) + if (updatedAt > bestUpdatedAt || (updatedAt === bestUpdatedAt && status === 'permission')) { + bestStatus = status + bestUpdatedAt = updatedAt + bestStateStartedAt = typeof stateStartedAt === 'number' ? stateStartedAt : updatedAt + } + } + for (const row of args.hookRows) { + if (row.terminalHandle !== args.handle && (!args.paneKey || row.paneKey !== args.paneKey)) { + continue + } + consider( + row.state, + row.receivedAt, + row.evidenceObservedAt, + row.restoredUnconfirmed, + row.providerSessionOnly, + row.stateStartedAt + ) + } + return bestStatus + ? { + status: bestStatus, + updatedAt: bestUpdatedAt, + stateStartedAt: bestStateStartedAt + } + : null +} + +/** The pane's live row for the mobile projection: its own key first, then the terminal it is + * bound to, which is the only join left once a pane key has moved. */ +export function selectFreshAgentRowForMobileTab(args: { + paneKey: string + terminalHandle: string | null + hookRows: readonly AgentStatusIpcPayload[] +}): RuntimeAgentRowSnapshot | null { + let match: AgentStatusIpcPayload | null = null + const now = Date.now() + for (const row of args.hookRows) { + if ( + !isLiveObservation(row) || + now - (row.evidenceObservedAt ?? row.receivedAt) > AGENT_STATUS_STALE_AFTER_MS + ) { + continue + } + if (row.paneKey === args.paneKey) { + if (!match || match.paneKey !== args.paneKey || row.receivedAt > match.receivedAt) { + match = row + } + continue + } + if ( + match?.paneKey !== args.paneKey && + args.terminalHandle !== null && + row.terminalHandle === args.terminalHandle && + (!match || row.receivedAt > match.receivedAt) + ) { + match = row + } + } + if (!match) { + return null + } + return { + paneKey: match.paneKey, + connectionId: match.connectionId ?? null, + ...(match.worktreeId ? { worktreeId: match.worktreeId } : {}), + ...(match.tabId ? { tabId: match.tabId } : {}), + payload: pickParsedAgentStatusPayload(match), + stateStartedAt: match.stateStartedAt ?? match.receivedAt, + updatedAt: match.receivedAt, + ...(match.providerSession ? { providerSession: match.providerSession } : {}), + ...(match.evidenceObservedAt !== undefined + ? { evidenceObservedAt: match.evidenceObservedAt } + : {}) + } +} diff --git a/src/main/runtime/runtime-local-worktree-terminal-startup.test.ts b/src/main/runtime/runtime-local-worktree-terminal-startup.test.ts new file mode 100644 index 00000000000..1153b173553 --- /dev/null +++ b/src/main/runtime/runtime-local-worktree-terminal-startup.test.ts @@ -0,0 +1,74 @@ +import { describe, expect, it, vi } from 'vitest' +import type { Repo } from '../../shared/repo-types' +import type { Worktree } from '../../shared/worktree/types' +import { startRuntimeLocalWorktreeTerminals } from './runtime-local-worktree-terminal-startup' + +const repo: Repo = { + id: 'repo-1', + path: '/repo', + displayName: 'repo', + badgeColor: 'blue', + addedAt: 1 +} + +const worktree: Worktree = { + id: 'worktree-1', + repoId: repo.id, + path: '/worktree', + head: 'abc', + branch: 'feature', + isBare: false, + isMainWorktree: false, + displayName: 'feature', + comment: '', + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 1 +} + +type StartupArgs = Parameters[0] + +function createPorts() { + const createTerminal = vi.fn().mockResolvedValue({ + handle: 'term-1', + worktreeId: worktree.id, + title: null + }) + const ports: StartupArgs['ports'] = { + canSpawn: true, + markTrusted: vi.fn(), + createTerminal, + pasteDraft: vi.fn(), + sendFollowup: vi.fn(), + provision: vi.fn().mockResolvedValue({ setupSpawned: false, setupTerminalHandle: null }), + activate: vi.fn() + } + return { createTerminal, ports } +} + +describe('startRuntimeLocalWorktreeTerminals default shell seeding', () => { + it.each([ + ['Blank Terminal', undefined, 1], + ['an agent', 'codex' as const, 0] + ])('seeds a background shell for %s selection only', async (_label, agent, expectedCalls) => { + const { createTerminal, ports } = createPorts() + + await startRuntimeLocalWorktreeTerminals({ + request: { repoSelector: `id:${repo.id}`, name: worktree.displayName }, + repo, + worktree, + ...(agent ? { createdWithAgent: agent } : {}), + ports + }) + + expect(createTerminal).toHaveBeenCalledTimes(expectedCalls) + if (expectedCalls > 0) { + expect(createTerminal).toHaveBeenCalledWith(`id:${worktree.id}`, { surfaceOwner: false }) + } + }) +}) diff --git a/src/main/runtime/runtime-local-worktree-terminal-startup.ts b/src/main/runtime/runtime-local-worktree-terminal-startup.ts index 35985b53497..7babcd7da7d 100644 --- a/src/main/runtime/runtime-local-worktree-terminal-startup.ts +++ b/src/main/runtime/runtime-local-worktree-terminal-startup.ts @@ -163,7 +163,7 @@ export async function startRuntimeLocalWorktreeTerminals(args: { didSpawnSetup = true } } - } else if (ports.canSpawn) { + } else if (ports.canSpawn && !args.createdWithAgent) { try { await ports.createTerminal(`id:${worktree.id}`, { surfaceOwner: false }) } catch (error) { diff --git a/src/main/runtime/runtime-mobile-agent-status-builder.test.ts b/src/main/runtime/runtime-mobile-agent-status-builder.test.ts new file mode 100644 index 00000000000..f9e21d7e323 --- /dev/null +++ b/src/main/runtime/runtime-mobile-agent-status-builder.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from 'vitest' +import type { RuntimeMobileSessionTerminalTab } from '../../shared/runtime-types' +import type { RuntimeAgentRowSnapshot } from './runtime-hook-agent-row-selection' +import { buildRuntimeMobileAgentStatus } from './runtime-mobile-agent-status-builder' + +const PROVIDER_SESSION = { key: 'session_id' as const, id: 'session-1' } +const TAB: RuntimeMobileSessionTerminalTab = { + type: 'terminal', + id: 'tab::leaf', + parentTabId: 'tab', + leafId: 'leaf', + title: 'Terminal', + isActive: true +} + +describe('mobile agent status builder', () => { + it('keeps provider-session identity from a terminal-handle row rejoin', () => { + const retained: RuntimeAgentRowSnapshot = { + paneKey: 'old-tab:old-leaf', + connectionId: null, + payload: { state: 'working', prompt: 'ship it', agentType: 'codex' }, + stateStartedAt: 10, + updatedAt: 10, + providerSession: PROVIDER_SESSION + } + + const result = buildRuntimeMobileAgentStatus(null, TAB, 'term-1', retained, () => [], { + getPaneKey: () => 'new-tab:new-leaf', + getLeaf: () => null, + getTrackedTitle: () => null + }) + + expect(result).toEqual( + expect.objectContaining({ + agentStatus: expect.objectContaining({ providerSession: PROVIDER_SESSION }) + }) + ) + }) +}) diff --git a/src/main/runtime/runtime-mobile-agent-status-builder.ts b/src/main/runtime/runtime-mobile-agent-status-builder.ts index 2f8480b7580..5ce39d49d6a 100644 --- a/src/main/runtime/runtime-mobile-agent-status-builder.ts +++ b/src/main/runtime/runtime-mobile-agent-status-builder.ts @@ -33,13 +33,13 @@ export function buildRuntimeMobileAgentStatus( host: RuntimeMobileAgentStatusHost ): { agentStatus: AgentStatusEntry } | Record { const paneKey = host.getPaneKey(tab) - // Why: neither the OSC-retained row nor a title-derived status can carry a - // provider session — only the hook payload does, and headless serve has no + // Why: neither the live-status projection nor a title-derived status carries a + // provider session — only the full hook payload does, and headless serve has no // renderer to publish `tab.agentStatus`. Without it mobile native chat has no // transcript to address and sits on the empty state forever. const hookRow = selectRuntimeHookAgentRowForPane(getHookRowsForPane(paneKey)) // Why: the hook row is evidence in its own right. Returning early on a missing - // PTY status/retained row put this check ahead of the only headless carrier, so + // PTY status/projected row put this check ahead of the only headless carrier, so // an agent that reported its session but never emitted a recognized title got no // `agentStatus` at all — exactly the hook-only case the fallback exists for. if (!pty?.lastAgentStatus && !retained && !hookRow.agentType && !hookRow.providerSession) { @@ -47,7 +47,9 @@ export function buildRuntimeMobileAgentStatus( } const providerSession = hookRow.providerSession ? { providerSession: hookRow.providerSession } - : {} + : retained?.providerSession + ? { providerSession: retained.providerSession } + : {} const leaf = host.getLeaf(tab) const trackerOnlyTitle = host.getTrackedTitle(pty?.ptyId ?? leaf?.ptyId ?? null) const ptyTitle = pty @@ -101,6 +103,9 @@ export function buildRuntimeMobileAgentStatus( ...liveRow.payload, paneKey, updatedAt: liveRow.updatedAt, + ...(liveRow.evidenceObservedAt !== undefined + ? { evidenceObservedAt: liveRow.evidenceObservedAt } + : {}), stateStartedAt: liveRow.stateStartedAt, stateHistory: [], ...(terminalHandle ? { terminalHandle } : {}), diff --git a/src/main/runtime/runtime-mobile-agent-status-projection.ts b/src/main/runtime/runtime-mobile-agent-status-projection.ts index 7c7749c76ab..b21fd8bb3ff 100644 --- a/src/main/runtime/runtime-mobile-agent-status-projection.ts +++ b/src/main/runtime/runtime-mobile-agent-status-projection.ts @@ -1,5 +1,6 @@ import { AGENT_STATUS_STALE_AFTER_MS, + agentStatusAuthorityObservedAt, pickParsedAgentStatusPayload, type AgentStatusEntry, type AgentStatusIpcPayload @@ -22,7 +23,7 @@ export function renewRuntimeMobileAgentStatusFromPtyTitle( if ( (status.state === 'waiting' || status.state === 'blocked') && pty.lastAgentStatus === 'idle' && - Date.now() - status.updatedAt <= AGENT_STATUS_STALE_AFTER_MS + Date.now() - agentStatusAuthorityObservedAt(status) <= AGENT_STATUS_STALE_AFTER_MS ) { return status } @@ -35,7 +36,7 @@ export function renewRuntimeMobileAgentStatusFromPtyTitle( } const richStatusCanOwnTitleInterval = pty.lastAgentStatusRichInvalidatedAtEpochMs === null || - status.updatedAt > pty.lastAgentStatusRichInvalidatedAtEpochMs + agentStatusAuthorityObservedAt(status) > pty.lastAgentStatusRichInvalidatedAtEpochMs const titleEvidenceAt = pty.lastOscTitleEpochMs if (titleEvidenceAt === null) { return richStatusCanOwnTitleInterval ? status : null @@ -63,7 +64,10 @@ export function renewRuntimeMobileAgentStatusFromPtyTitle( (pty.lastAgentStatus === 'permission' && (status.state === 'blocked' || status.state === 'waiting')) if (!titleConfirmsState) { - if (richStatusCanOwnTitleInterval && status.updatedAt >= titleEvidenceAt) { + if ( + richStatusCanOwnTitleInterval && + agentStatusAuthorityObservedAt(status) >= titleEvidenceAt + ) { return status } if (pty.lastAgentStatus === null && !terminalTitleBlocksExplicitAgentStatus(pty.lastOscTitle)) { @@ -82,7 +86,8 @@ export function renewRuntimeMobileAgentStatusFromPtyTitle( ) } const richStatusOwnsCurrentState = - Date.now() - status.updatedAt <= AGENT_STATUS_STALE_AFTER_MS && richStatusCanOwnTitleInterval + Date.now() - agentStatusAuthorityObservedAt(status) <= AGENT_STATUS_STALE_AFTER_MS && + richStatusCanOwnTitleInterval // Fresh explicit evidence from this title interval owns acknowledgement identity. const stateStartedAt = richStatusOwnsCurrentState ? status.stateStartedAt @@ -124,7 +129,7 @@ export function selectRuntimeHookAgentRowForPane( entry.agentType && (entry.providerSessionOnly !== true || (entry.agentType === 'pi' && entry.providerSession != null)) && - entry.receivedAt >= freshAfter && + (entry.evidenceObservedAt ?? entry.receivedAt) >= freshAfter && (!agent || entry.receivedAt > agent.receivedAt) ) { agent = entry @@ -133,7 +138,7 @@ export function selectRuntimeHookAgentRowForPane( entry.providerSessionOnly !== true && // Restored rows cannot prove liveness because the turn may have ended while offline (#12346). entry.restoredUnconfirmed !== true && - entry.receivedAt >= freshAfter && + (entry.evidenceObservedAt ?? entry.receivedAt) >= freshAfter && (!live || entry.receivedAt > live.receivedAt) ) { live = entry @@ -149,6 +154,9 @@ export function selectRuntimeHookAgentRowForPane( ? { payload: pickParsedAgentStatusPayload(live), updatedAt: live.receivedAt, + ...(live.evidenceObservedAt !== undefined + ? { evidenceObservedAt: live.evidenceObservedAt } + : {}), stateStartedAt: live.stateStartedAt ?? live.receivedAt, ...(live.worktreeId ? { worktreeId: live.worktreeId } : {}) } @@ -167,6 +175,13 @@ export function resolveRuntimeHookLiveAgentRow( if (live.payload.interactivePrompt != null) { return live } - // This is the pane's only wall-clock title timestamp comparable to hook `receivedAt`. - return !nonAgentTitle && live.updatedAt >= (pty?.lastOscTitleEpochMs ?? 0) ? live : null + // This is the pane's only wall-clock title timestamp comparable to when the hook evidence + // was observed; replay delivery order must not make old evidence outrank a newer title. + return !nonAgentTitle && + agentStatusAuthorityObservedAt({ + updatedAt: live.updatedAt, + evidenceObservedAt: live.evidenceObservedAt + }) >= (pty?.lastOscTitleEpochMs ?? 0) + ? live + : null } diff --git a/src/main/runtime/runtime-mobile-notification-controller.ts b/src/main/runtime/runtime-mobile-notification-controller.ts index a9c1d437f95..174e897f4e1 100644 --- a/src/main/runtime/runtime-mobile-notification-controller.ts +++ b/src/main/runtime/runtime-mobile-notification-controller.ts @@ -1,9 +1,24 @@ +import { reserveNotificationCooldown } from '../../shared/notification-burst-cooldown' +import type { AgentStatusState } from '../../shared/agent-status-types' +import type { + MobilePushTestResult, + MobilePushRegisterInput, + MobilePushRegisterResult +} from '../../shared/mobile-push-contract' import { MobileNotificationReplayBuffer } from './mobile-notification-replay' import { notifyRuntimeListeners } from './runtime-async-boundaries' import { getRuntimeDesktopSurface } from './runtime-desktop-surface' +import { + MobileNotificationDismissalStore, + type DeliveredNotificationIdentity +} from './mobile-notification-dismissal-store' export type MobileNotificationDispatchEvent = { type: 'notification' + legacySocketAllowed?: boolean + desktopAllowed?: boolean + desktopAway?: boolean + emittedAt?: number source: 'agent-task-complete' | 'terminal-bell' | 'test' | 'plugin' title: string body: string @@ -11,6 +26,9 @@ export type MobileNotificationDispatchEvent = { notificationId?: string notificationSeq?: number notificationEpoch?: string + // Why: background push must tell "needs input" from "finished" without re-deriving + // it from the title. Optional and additive — old clients ignore it. + agentState?: AgentStatusState } export type MobileNotificationDismissEvent = { @@ -24,9 +42,50 @@ export type MobileNotificationEvent = | MobileNotificationDispatchEvent | MobileNotificationDismissEvent +/** The desktop push service, once it exists; absent on hosts that never started one. */ +export type MobilePushRegistrar = { + test(deviceId: string): Promise + register(input: MobilePushRegisterInput): Promise + unregister(deviceId: string): Promise<{ unregistered: boolean }> +} + export class RuntimeMobileNotificationController { private readonly listeners = new Set<(event: MobileNotificationEvent) => void>() + private readonly legacyCooldown = new Map() private readonly replay = new MobileNotificationReplayBuffer() + private pushRegistrar: MobilePushRegistrar | null = null + private dismissalStore: MobileNotificationDismissalStore | null = null + + configureDismissalStore(userDataPath: string): void { + this.dismissalStore = new MobileNotificationDismissalStore(userDataPath) + } + + reconcileDismissedPushes( + delivered: readonly DeliveredNotificationIdentity[] + ): DeliveredNotificationIdentity[] { + return this.dismissalStore?.reconcile(delivered) ?? [] + } + + setPushRegistrar(registrar: MobilePushRegistrar | null): void { + this.pushRegistrar = registrar + } + + async registerPushDevice(input: MobilePushRegisterInput): Promise { + return ( + (await this.pushRegistrar?.register(input)) ?? { + registered: false, + reason: 'gateway_unreachable' + } + ) + } + + async testPushDevice(deviceId: string): Promise { + return (await this.pushRegistrar?.test(deviceId)) ?? { accepted: false, reason: 'unavailable' } + } + + async unregisterPushDevice(deviceId: string): Promise<{ unregistered: boolean }> { + return (await this.pushRegistrar?.unregister(deviceId)) ?? { unregistered: false } + } onDispatched(listener: (event: MobileNotificationEvent) => void): () => void { this.listeners.add(listener) @@ -38,7 +97,32 @@ export class RuntimeMobileNotificationController { } dispatch(event: MobileNotificationEvent): void { + if (event.type === 'notification') { + // Decide once before recording so reconnect and buffer eviction cannot reset cooldown. + const legacySocketAllowed = + event.desktopAllowed !== false && + (event.emittedAt === undefined || + reserveNotificationCooldown( + this.legacyCooldown, + event.worktreeId ?? 'global', + event.emittedAt + )) + event = { + ...event, + legacySocketAllowed, + desktopAway: getRuntimeDesktopSurface().isAwayForMobileNotifications?.() + } + } const seq = this.replay.record(event) + try { + this.dismissalStore?.record({ + ...event, + notificationSeq: seq, + notificationEpoch: this.replay.epoch + }) + } catch { + console.warn('[notifications] Could not persist dismissal recovery state') + } notifyRuntimeListeners( this.listeners, (listener) => diff --git a/src/main/runtime/runtime-mobile-session-projection-contract.ts b/src/main/runtime/runtime-mobile-session-projection-contract.ts index 6aaed42764c..f4174b7715a 100644 --- a/src/main/runtime/runtime-mobile-session-projection-contract.ts +++ b/src/main/runtime/runtime-mobile-session-projection-contract.ts @@ -18,6 +18,7 @@ export type RuntimeMobileSessionProjectionHost = { getLiveBrowserTabs(worktreeId: string): Map getProviderSessionRows(paneKey: string): AgentStatusIpcPayload[] | undefined getProviderSessionSnapshot(): AgentStatusIpcPayload[] + getStatusSnapshot(): AgentStatusIpcPayload[] getLeafKey(tabId: string, leafId: string): string findPty( worktreeId: string, @@ -27,7 +28,8 @@ export type RuntimeMobileSessionProjectionHost = { getRetainedStatus( paneKey: string, pty: RuntimePtyWorktreeRecord | null, - tab: RuntimeMobileSessionTerminalTab + tab: RuntimeMobileSessionTerminalTab, + getRows: (paneKey: string, terminalHandle: string | null) => AgentStatusIpcPayload[] ): RuntimeAgentRowSnapshot | null getTrackedTitle(ptyId: string | null): string | null issuePtyHandle(pty: RuntimePtyWorktreeRecord): string diff --git a/src/main/runtime/runtime-mobile-session-projection.ts b/src/main/runtime/runtime-mobile-session-projection.ts index 8fa9bb954dc..db1ef0619ca 100644 --- a/src/main/runtime/runtime-mobile-session-projection.ts +++ b/src/main/runtime/runtime-mobile-session-projection.ts @@ -48,6 +48,42 @@ export function projectRuntimeMobileSessionTabs( hookRowsForPane.set(paneKey, rows) return rows } + let statusRowsByPaneKey: Map | null = null + let statusRowsByTerminalHandle: Map | null = null + const getStatusRows = ( + paneKey: string, + terminalHandle: string | null + ): AgentStatusIpcPayload[] => { + if (!statusRowsByPaneKey || !statusRowsByTerminalHandle) { + statusRowsByPaneKey = new Map() + statusRowsByTerminalHandle = new Map() + for (const row of host.getStatusSnapshot()) { + const paneRows = statusRowsByPaneKey.get(row.paneKey) + if (paneRows) { + paneRows.push(row) + } else { + statusRowsByPaneKey.set(row.paneKey, [row]) + } + if (row.terminalHandle) { + const handleRows = statusRowsByTerminalHandle.get(row.terminalHandle) + if (handleRows) { + handleRows.push(row) + } else { + statusRowsByTerminalHandle.set(row.terminalHandle, [row]) + } + } + } + } + const paneRows = statusRowsByPaneKey.get(paneKey) ?? [] + if (!terminalHandle) { + return paneRows + } + const handleRows = statusRowsByTerminalHandle.get(terminalHandle) ?? [] + if (paneRows.length === 0) { + return handleRows + } + return [...paneRows, ...handleRows.filter((row) => !paneRows.includes(row))] + } // Why: a live PTY backs one surface; claim each once so two leaves resolving to it can't emit duplicate React keys and crash the client. const claimedLivePtyIds = new Set() for (const tab of snapshot.tabs) { @@ -98,11 +134,11 @@ export function projectRuntimeMobileSessionTabs( ? makePaneKey(tab.parentTabId, tab.leafId) : `${tab.parentTabId}:${legacyPaneId ?? tab.leafId}` const mobileStatusPty = livePty ?? pty - // Why: headless hooks live only in main's retained rows; reuse this lookup + // Why: headless hooks live in main's status store; reuse this lookup // for both title ownership and status publication so the two cannot diverge. const retainedAgentStatus = tab.agentStatus ? null - : host.getRetainedStatus(paneKey, liveLeafPty ?? mobileStatusPty, tab) + : host.getRetainedStatus(paneKey, liveLeafPty ?? mobileStatusPty, tab, getStatusRows) const hookAgentStatus = tab.agentStatus ? selectRuntimeHookAgentRowForPane(getHookRowsForPane(paneKey)) : null diff --git a/src/main/runtime/runtime-remote-managed-worktree-create.ts b/src/main/runtime/runtime-remote-managed-worktree-create.ts index 01a49142dc4..83de82b0594 100644 --- a/src/main/runtime/runtime-remote-managed-worktree-create.ts +++ b/src/main/runtime/runtime-remote-managed-worktree-create.ts @@ -222,7 +222,7 @@ export async function createRuntimeRemoteManagedWorktree( didSpawnSetup = true } } - } else if (!shouldActivate && deps.canSpawn()) { + } else if (!shouldActivate && deps.canSpawn() && !args.createdWithAgent) { try { await deps.createTerminal(`path:${result.worktree.path}`, { surfaceOwner: false }) } catch (err) { diff --git a/src/main/runtime/runtime-rpc-mobile-method-allowlist-fixtures.ts b/src/main/runtime/runtime-rpc-mobile-method-allowlist-fixtures.ts index 7a97745764d..00bf253fe89 100644 --- a/src/main/runtime/runtime-rpc-mobile-method-allowlist-fixtures.ts +++ b/src/main/runtime/runtime-rpc-mobile-method-allowlist-fixtures.ts @@ -117,6 +117,7 @@ export function createMobileRpcSurfaceRuntime() { .fn() .mockResolvedValue({ ok: true, id: 'comment-1' }) const runtime = { + configureNotificationDismissalStore: () => {}, getRuntimeId: () => 'test-runtime', getStatus, pushRuntimeGit, diff --git a/src/main/runtime/runtime-rpc-mobile-terminal-streaming.test.ts b/src/main/runtime/runtime-rpc-mobile-terminal-streaming.test.ts index e558d19b54b..c094f54cee3 100644 --- a/src/main/runtime/runtime-rpc-mobile-terminal-streaming.test.ts +++ b/src/main/runtime/runtime-rpc-mobile-terminal-streaming.test.ts @@ -404,6 +404,7 @@ describe('OrcaRuntimeRpcServer', () => { // activation is a local-host concern, so the proxy legitimately lacks // activateRecentPtyPathCandidateTracking and onReady must not throw. const runtimeProxy = { + configureNotificationDismissalStore: () => {}, getRuntimeId: () => 'proxy-runtime-test', getStartedAt: () => 1, getStatus: () => ({ graphStatus: 'unavailable' }), diff --git a/src/main/runtime/runtime-rpc-request-authorization.test.ts b/src/main/runtime/runtime-rpc-request-authorization.test.ts index 5ff19f94563..d5a083a56bf 100644 --- a/src/main/runtime/runtime-rpc-request-authorization.test.ts +++ b/src/main/runtime/runtime-rpc-request-authorization.test.ts @@ -30,6 +30,7 @@ describe('OrcaRuntimeRpcServer', () => { it('rejects WebSocket requests whose request token differs from the authenticated channel token', async () => { const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) const runtime = { + configureNotificationDismissalStore: () => {}, getRuntimeId: () => 'test-runtime', getStatus: vi.fn().mockResolvedValue({ graphStatus: 'ok' }) } as unknown as OrcaRuntimeService @@ -184,6 +185,7 @@ describe('OrcaRuntimeRpcServer', () => { const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) const createMobileSessionTerminal = vi.fn() const runtime = { + configureNotificationDismissalStore: () => {}, getRuntimeId: () => 'test-runtime', createMobileSessionTerminal } as unknown as OrcaRuntimeService @@ -225,6 +227,7 @@ describe('OrcaRuntimeRpcServer', () => { const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) const pushRuntimeGit = vi.fn().mockResolvedValue({ ok: true }) const runtime = { + configureNotificationDismissalStore: () => {}, getRuntimeId: () => 'test-runtime', pushRuntimeGit } as unknown as OrcaRuntimeService diff --git a/src/main/runtime/runtime-rpc-websocket-long-poll-caps.test.ts b/src/main/runtime/runtime-rpc-websocket-long-poll-caps.test.ts index 7c2b5bd11d7..ea8837c01c9 100644 --- a/src/main/runtime/runtime-rpc-websocket-long-poll-caps.test.ts +++ b/src/main/runtime/runtime-rpc-websocket-long-poll-caps.test.ts @@ -206,7 +206,10 @@ describe('OrcaRuntimeRpcServer', () => { it('shares one socket close listener across concurrent WebSocket dispatches', async () => { const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) - const runtime = { getRuntimeId: () => 'test-runtime' } as unknown as OrcaRuntimeService + const runtime = { + configureNotificationDismissalStore: () => {}, + getRuntimeId: () => 'test-runtime' + } as unknown as OrcaRuntimeService const server = new OrcaRuntimeRpcServer({ runtime, userDataPath, enableWebSocket: false }) server['deviceRegistry'] = new DeviceRegistry(userDataPath) const entry = server['deviceRegistry']!.addDevice('runtime-test', 'runtime') diff --git a/src/main/runtime/runtime-rpc/runtime-rpc-mobile-method-allowlist.ts b/src/main/runtime/runtime-rpc/runtime-rpc-mobile-method-allowlist.ts index 534cf04b883..85cf306a0e5 100644 --- a/src/main/runtime/runtime-rpc/runtime-rpc-mobile-method-allowlist.ts +++ b/src/main/runtime/runtime-rpc/runtime-rpc-mobile-method-allowlist.ts @@ -172,7 +172,10 @@ export const MOBILE_RPC_METHOD_ALLOWLIST = new Set([ 'markdown.readTab', 'markdown.saveTab', 'notifications.getMissedSince', + 'notifications.registerPush', 'notifications.subscribe', + 'notifications.testPush', + 'notifications.unregisterPush', 'notifications.unsubscribe', 'pairing.getEndpoints', 'pairing.provisionRelay', diff --git a/src/main/runtime/runtime-rpc/runtime-rpc-pairing-types.ts b/src/main/runtime/runtime-rpc/runtime-rpc-pairing-types.ts index 3cd3c1a54fb..4923dec1dec 100644 --- a/src/main/runtime/runtime-rpc/runtime-rpc-pairing-types.ts +++ b/src/main/runtime/runtime-rpc/runtime-rpc-pairing-types.ts @@ -1,5 +1,5 @@ import type { OrcaRuntimeService } from '../orca-runtime' -import type { RpcAnyMethod } from '../rpc/core' +import type { RpcAnyMethodDeclaration } from '../rpc/core' import type { DeviceRegistry } from '../device-registry' import type { E2EEKeypair } from '../e2ee-keypair' import type { MobileSocketTransportMetadata } from '../rpc/mobile-socket-wiring' @@ -56,7 +56,7 @@ export type OrcaRuntimeRpcServerOptions = { // Why: test-only override for the ownership reclaim cadence. metadataOwnershipPollMs?: number // Why: tests may inject inert protocol stages before production authorization registers them. - methods?: readonly RpcAnyMethod[] + methods?: readonly RpcAnyMethodDeclaration[] } export type PairingOfferUnavailableReason = diff --git a/src/main/runtime/runtime-rpc/runtime-rpc-pairing.ts b/src/main/runtime/runtime-rpc/runtime-rpc-pairing.ts index 592131779eb..7d8bba9f958 100644 --- a/src/main/runtime/runtime-rpc/runtime-rpc-pairing.ts +++ b/src/main/runtime/runtime-rpc/runtime-rpc-pairing.ts @@ -6,6 +6,7 @@ import type { RelayRevokeOutbox, RelayRevokeOutboxItem } from '../relay/relay-revoke-outbox' +import type { PushUnregisterOutbox } from '../push/push-unregister-outbox' import { encodePairingOffer, PAIRING_OFFER_VERSION } from '../../../shared/pairing' import type { RuntimePairingReach } from '../../../shared/runtime-pairing-reach' import { resolveAdvertisedPairingEndpoint } from '../pairing-endpoint' @@ -20,6 +21,8 @@ import { } from './runtime-rpc-pairing-types' export class RuntimeRpcPairing extends RuntimeRpcNetworkExposure { + private onPushUnregisterQueued?: () => void + getDeviceRegistry(): DeviceRegistry | null { return this.deviceRegistry } @@ -44,6 +47,10 @@ export class RuntimeRpcPairing extends RuntimeRpcNetworkExposure { return this.relayRevokeOutbox } + getPushUnregisterOutbox(): PushUnregisterOutbox { + return this.pushUnregisterOutbox + } + setMobileRelayBinding(deviceId: string, binding: RelayDeviceBinding): boolean { const current = this.deviceRegistry?.getDevice(deviceId) if ( @@ -88,6 +95,9 @@ export class RuntimeRpcPairing extends RuntimeRpcNetworkExposure { return false } } + // Why: unpairing must delete the phone's push token at the gateway too, and the + // registration id is only readable while the device row still exists. + this.queuePushUnregister(deviceId, device.pushRegistration?.registrationId) if (!this.deviceRegistry?.removeDevice(deviceId)) { return false } @@ -182,6 +192,23 @@ export class RuntimeRpcPairing extends RuntimeRpcNetworkExposure { } } + /** Best-effort: a failed enqueue must never block the revoke the user asked for. */ + protected queuePushUnregister(deviceId: string, registrationId: string | undefined): void { + if (!registrationId) { + return + } + try { + this.pushUnregisterOutbox.enqueue({ registrationId, deviceId }) + this.onPushUnregisterQueued?.() + } catch (error) { + console.error('[runtime] Failed to persist a push token cleanup:', error) + } + } + + setOnPushUnregisterQueued(callback: (() => void) | null): void { + this.onPushUnregisterQueued = callback ?? undefined + } + protected queueOrRetainRelayDeviceRevoke(deviceId: string, binding: RelayDeviceBinding): void { if (this.queueRelayDeviceRevoke(binding)) { return diff --git a/src/main/runtime/runtime-rpc/runtime-rpc-state.ts b/src/main/runtime/runtime-rpc/runtime-rpc-state.ts index ca9ab173feb..e7f56ceed13 100644 --- a/src/main/runtime/runtime-rpc/runtime-rpc-state.ts +++ b/src/main/runtime/runtime-rpc/runtime-rpc-state.ts @@ -10,6 +10,7 @@ import type { E2EEKeypair } from '../e2ee-keypair' import type { UnpairedDeviceAuthThrottle } from '../rpc/unpaired-device-auth-throttle' import type { MobileSocketWiring } from '../rpc/mobile-socket-wiring' import { RelayRevokeOutbox } from '../relay/relay-revoke-outbox' +import { PushUnregisterOutbox } from '../push/push-unregister-outbox' import { RuntimeBinaryMessageRouter } from '../runtime-binary-message-router' import type { RuntimeMetadataOwnershipWatch } from '../runtime-metadata-ownership-watch' import { RUNTIME_METADATA_OWNERSHIP_POLL_MS } from '../runtime-metadata-ownership-watch' @@ -56,6 +57,7 @@ export class RuntimeRpcState { protected readonly browserHostLongPollCapPerDevice: number protected readonly specializedLongPollCap: number protected readonly relayRevokeOutbox: RelayRevokeOutbox + protected readonly pushUnregisterOutbox: PushUnregisterOutbox protected deviceRegistry: DeviceRegistry | null = null protected e2eeKeypair: E2EEKeypair | null = null protected pairingInitializationFailure: PairingOfferUnavailable | null = null @@ -129,5 +131,7 @@ export class RuntimeRpcState { this.browserHostLongPollCapPerDevice = Math.max(1, Math.floor(this.browserHostLongPollCap / 2)) this.specializedLongPollCap = Math.max(1, Math.floor(longPollCap * SPECIALIZED_LONG_POLL_SHARE)) this.relayRevokeOutbox = new RelayRevokeOutbox(userDataPath) + this.pushUnregisterOutbox = new PushUnregisterOutbox(userDataPath) + this.runtime.configureNotificationDismissalStore(userDataPath) } } diff --git a/src/main/runtime/runtime-service-command-surface.ts b/src/main/runtime/runtime-service-command-surface.ts index 19545cc76e6..4290fadecf1 100644 --- a/src/main/runtime/runtime-service-command-surface.ts +++ b/src/main/runtime/runtime-service-command-surface.ts @@ -27,9 +27,15 @@ export type RuntimeServiceCommandSurface = { getMobileNotificationListenerCount: RuntimeMobileNotificationController['getListenerCount'] dispatchMobileNotification: RuntimeMobileNotificationController['dispatch'] getMissedNotificationsSince: RuntimeMobileNotificationController['getMissedSince'] + configureNotificationDismissalStore: RuntimeMobileNotificationController['configureDismissalStore'] + reconcileDismissedPushes: RuntimeMobileNotificationController['reconcileDismissedPushes'] getMobileNotificationEpoch: RuntimeMobileNotificationController['getEpoch'] dismissMobileNotification: RuntimeMobileNotificationController['dismiss'] dispatchPluginNotification: RuntimeMobileNotificationController['dispatchPlugin'] + setMobilePushRegistrar: RuntimeMobileNotificationController['setPushRegistrar'] + testMobilePushDevice: RuntimeMobileNotificationController['testPushDevice'] + registerMobilePushDevice: RuntimeMobileNotificationController['registerPushDevice'] + unregisterMobilePushDevice: RuntimeMobileNotificationController['unregisterPushDevice'] setAccountServices: RuntimeAccountController['setServices'] setCommitMessageAgentEnvironmentResolvers: RuntimeAccountController['setCommitMessageAgentEnvironment'] getCommitMessageAgentEnvironmentResolvers: RuntimeAccountController['getCommitMessageAgentEnvironment'] @@ -107,9 +113,15 @@ export function installRuntimeServiceCommandSurface( getMobileNotificationListenerCount: notifications.getListenerCount.bind(notifications), dispatchMobileNotification: notifications.dispatch.bind(notifications), getMissedNotificationsSince: notifications.getMissedSince.bind(notifications), + configureNotificationDismissalStore: notifications.configureDismissalStore.bind(notifications), + reconcileDismissedPushes: notifications.reconcileDismissedPushes.bind(notifications), getMobileNotificationEpoch: notifications.getEpoch.bind(notifications), dismissMobileNotification: notifications.dismiss.bind(notifications), dispatchPluginNotification: notifications.dispatchPlugin.bind(notifications), + setMobilePushRegistrar: notifications.setPushRegistrar.bind(notifications), + testMobilePushDevice: notifications.testPushDevice.bind(notifications), + registerMobilePushDevice: notifications.registerPushDevice.bind(notifications), + unregisterMobilePushDevice: notifications.unregisterPushDevice.bind(notifications), setAccountServices: accounts.setServices.bind(accounts), setCommitMessageAgentEnvironmentResolvers: accounts.setCommitMessageAgentEnvironment.bind(accounts), diff --git a/src/main/runtime/runtime-terminal-contracts.ts b/src/main/runtime/runtime-terminal-contracts.ts index 875eef03600..227788af7e1 100644 --- a/src/main/runtime/runtime-terminal-contracts.ts +++ b/src/main/runtime/runtime-terminal-contracts.ts @@ -96,12 +96,15 @@ export type RuntimeTerminalAgentStatusEvent = { tabId?: string worktreeId?: string connectionId?: string | null + /** The pane's terminal handle, when it is bound to one. Stamped on the stored row so a + * reader can rejoin it to the terminal after the pane key moved. */ + terminalHandle?: string payload: ParsedAgentStatusPayload } export type HookLiveAgentRow = Pick< RuntimeAgentRowSnapshot, - 'payload' | 'updatedAt' | 'stateStartedAt' | 'worktreeId' + 'payload' | 'updatedAt' | 'evidenceObservedAt' | 'stateStartedAt' | 'worktreeId' > export type RuntimePtyDataAdmission = Readonly<{ diff --git a/src/main/runtime/runtime-worktree-agent-rows-structured.test.ts b/src/main/runtime/runtime-worktree-agent-rows-structured.test.ts index 83b3d651642..5b517f1bfc8 100644 --- a/src/main/runtime/runtime-worktree-agent-rows-structured.test.ts +++ b/src/main/runtime/runtime-worktree-agent-rows-structured.test.ts @@ -54,8 +54,11 @@ function attach(summaries: AgentSessionStatusSummary[]): RuntimeWorktreePsSummar workingTerminalEvidenceByWorktreeId: new Map(), rowSources: collectRuntimeWorktreeAgentSources({ mirroredWorktreeIdByTabId: new Map(), - connectedPtyEvidence: { tabIds: new Set(), paneKeys: new Set(), ptyIds: new Set() }, - retainedSnapshots: [], + connectedPtyEvidence: { + tabIds: new Set(), + paneKeys: new Set(), + ptyIdByTerminalHandle: new Map() + }, hookSnapshots: store.getStatusSnapshot() }), orchestrationByPaneKey: null, diff --git a/src/main/runtime/runtime-worktree-agent-rows.ts b/src/main/runtime/runtime-worktree-agent-rows.ts index da145b67091..20c17f9b01a 100644 --- a/src/main/runtime/runtime-worktree-agent-rows.ts +++ b/src/main/runtime/runtime-worktree-agent-rows.ts @@ -4,7 +4,7 @@ import { mergeWorktreeSummaryStatus } from './runtime-worktree-status-projection import type { RuntimeWorktreeSummaryPathIndex } from './runtime-worktree-summary-paths' import type { RuntimeWorkingTerminalEvidence } from './runtime-worktree-ps-activity' import type { RuntimeWorktreeAgentSource } from './runtime-worktree-agent-source' -export type { RuntimeAgentRowSnapshot } from './runtime-worktree-pty-agent-sources' +export type { RuntimeAgentRowSnapshot } from './runtime-hook-agent-row-selection' type OrchestrationDisplay = { taskTitle?: string | null diff --git a/src/main/runtime/runtime-worktree-agent-sources.test.ts b/src/main/runtime/runtime-worktree-agent-sources.test.ts index c0395cd6831..5da2f6e8550 100644 --- a/src/main/runtime/runtime-worktree-agent-sources.test.ts +++ b/src/main/runtime/runtime-worktree-agent-sources.test.ts @@ -1,47 +1,48 @@ import { describe, expect, it } from 'vitest' import { collectRuntimeWorktreeAgentSources } from './runtime-worktree-agent-sources' -import type { RuntimeAgentRowSnapshot } from './runtime-worktree-pty-agent-sources' import type { AgentStatusIpcPayload } from '../../shared/agent-status-types' const paneKey = 'worktree:tab:0' const now = Date.now() -const retained: RuntimeAgentRowSnapshot = { +const hookRow: AgentStatusIpcPayload = { paneKey, - ptyId: 'pty', tabId: 'tab', + terminalHandle: 'term_row', worktreeId: 'worktree', connectionId: null, - payload: { state: 'working', prompt: 'implement', agentType: 'codex' }, + state: 'working', + prompt: 'implement', + agentType: 'codex', stateStartedAt: now, - updatedAt: now + receivedAt: now } const base = { - retainedSnapshots: [retained], - hookSnapshots: [] as AgentStatusIpcPayload[], - structuredSummaries: [], + hookSnapshots: [hookRow], mirroredWorktreeIdByTabId: new Map(), connectedPtyEvidence: { tabIds: new Set(), paneKeys: new Set(), - ptyIds: new Set() + ptyIdByTerminalHandle: new Map() + } +} +const connected = { + ...base, + connectedPtyEvidence: { + tabIds: new Set(['tab']), + paneKeys: new Set([paneKey]), + ptyIdByTerminalHandle: new Map([['term_row', 'pty']]) } } describe('worktree agent source admission', () => { it('rejects a disconnected local terminal before row assembly', () => { expect(collectRuntimeWorktreeAgentSources(base).size).toBe(0) - const connected = { - ...base, - connectedPtyEvidence: { ...base.connectedPtyEvidence, ptyIds: new Set(['pty']) } - } expect(collectRuntimeWorktreeAgentSources(connected).get(paneKey)?.state).toBe('working') }) it('keeps remote evidence and resolves mirrored workspace ownership', () => { - const remote = { ...retained, connectionId: 'ssh-connection' } - expect(collectRuntimeWorktreeAgentSources({ ...base, retainedSnapshots: [remote] }).size).toBe( - 1 - ) + const remote = { ...hookRow, connectionId: 'ssh-connection' } + expect(collectRuntimeWorktreeAgentSources({ ...base, hookSnapshots: [remote] }).size).toBe(1) const sources = collectRuntimeWorktreeAgentSources({ ...base, mirroredWorktreeIdByTabId: new Map([['tab', 'remote-worktree']]) @@ -49,22 +50,38 @@ describe('worktree agent source admission', () => { expect(sources.get(paneKey)?.worktreeId).toBe('remote-worktree') }) - it('preserves fresh monitoring enrichment on a newer retained report', () => { - const hook: AgentStatusIpcPayload = { - ...retained.payload, - paneKey, - tabId: 'tab', - worktreeId: 'worktree', - connectionId: null, - stateStartedAt: now - 1, - receivedAt: now - 1, - workingMode: 'monitoring' - } - const sources = collectRuntimeWorktreeAgentSources({ + it('rejoins the row to the connected PTY behind its terminal handle', () => { + expect(collectRuntimeWorktreeAgentSources(connected).get(paneKey)?.ptyId).toBe('pty') + // The handle is the last rescue once a controller incarnation nulls the pane binding. + const bindingCleared = collectRuntimeWorktreeAgentSources({ ...base, - hookSnapshots: [hook], - connectedPtyEvidence: { ...base.connectedPtyEvidence, ptyIds: new Set(['pty']) } + connectedPtyEvidence: { + ...base.connectedPtyEvidence, + ptyIdByTerminalHandle: new Map([['term_row', 'pty']]) + } }) - expect(sources.get(paneKey)).toMatchObject({ updatedAt: now, workingMode: 'monitoring' }) + expect(bindingCleared.get(paneKey)?.ptyId).toBe('pty') + // No connected PTY answers to the handle and no pane evidence: the row is not admitted. + expect(collectRuntimeWorktreeAgentSources(base).size).toBe(0) + }) + + it('carries the row own working mode and drops non-live rows', () => { + const monitoring = collectRuntimeWorktreeAgentSources({ + ...connected, + hookSnapshots: [{ ...hookRow, workingMode: 'monitoring' as const }] + }) + expect(monitoring.get(paneKey)).toMatchObject({ updatedAt: now, workingMode: 'monitoring' }) + + const restored = collectRuntimeWorktreeAgentSources({ + ...connected, + hookSnapshots: [{ ...hookRow, restoredUnconfirmed: true as const }] + }) + expect(restored.size).toBe(0) + + const providerSessionOnly = collectRuntimeWorktreeAgentSources({ + ...connected, + hookSnapshots: [{ ...hookRow, providerSessionOnly: true }] + }) + expect(providerSessionOnly.size).toBe(0) }) }) diff --git a/src/main/runtime/runtime-worktree-ps-activity.ts b/src/main/runtime/runtime-worktree-ps-activity.ts index c6c8d7fafc3..ae3ecdee4c3 100644 --- a/src/main/runtime/runtime-worktree-ps-activity.ts +++ b/src/main/runtime/runtime-worktree-ps-activity.ts @@ -188,10 +188,16 @@ export function applyRuntimeWorktreePsSessionActivity(args: { missingIds: Set ptysById: ReadonlyMap tabs: ReadonlyMap + /** Non-minting: a listing must not issue handles, only recognise the ones already bound. */ + getTerminalHandlesForPty: (ptyId: string) => readonly string[] getSummary: SummaryLookup }): { mirroredWorktreeIdByTabId: Map - connectedPtyEvidence: { tabIds: Set; paneKeys: Set; ptyIds: Set } + connectedPtyEvidence: { + tabIds: Set + paneKeys: Set + ptyIdByTerminalHandle: Map + } } { const mirroredWorktreeIdByTabId = new Map() const sessionsByHostId = new Map() @@ -244,19 +250,21 @@ export function applyRuntimeWorktreePsSessionActivity(args: { const connectedPtyEvidence = { tabIds: new Set(), paneKeys: new Set(), - ptyIds: new Set() + ptyIdByTerminalHandle: new Map() } for (const pty of args.ptysById.values()) { if (!pty.connected) { continue } - connectedPtyEvidence.ptyIds.add(pty.ptyId) if (pty.tabId) { connectedPtyEvidence.tabIds.add(pty.tabId) } if (pty.paneKey) { connectedPtyEvidence.paneKeys.add(pty.paneKey) } + for (const terminalHandle of args.getTerminalHandlesForPty(pty.ptyId)) { + connectedPtyEvidence.ptyIdByTerminalHandle.set(terminalHandle, pty.ptyId) + } } return { mirroredWorktreeIdByTabId, connectedPtyEvidence } } diff --git a/src/main/runtime/runtime-worktree-pty-agent-sources.ts b/src/main/runtime/runtime-worktree-pty-agent-sources.ts index 9f297d7edf7..058d378df11 100644 --- a/src/main/runtime/runtime-worktree-pty-agent-sources.ts +++ b/src/main/runtime/runtime-worktree-pty-agent-sources.ts @@ -1,34 +1,23 @@ import { - AGENT_STATUS_STALE_AFTER_MS, pickParsedAgentStatusPayload, type AgentStatusIpcPayload, type ParsedAgentStatusPayload } from '../../shared/agent-status-types' -import { terminalStatusPayloadMatchesHook } from '../../shared/agent-terminal-status-equivalence' import { parseLegacyNumericPaneKey, parsePaneKey } from '../../shared/stable-pane-id' import { isWslHookRelayConnectionId } from '../../shared/wsl-hook-relay-contract' import type { RuntimeWorktreeAgentSource } from './runtime-worktree-agent-source' -export type RuntimeAgentRowSnapshot = { - paneKey: string - ptyId: string - worktreeId?: string - tabId?: string - connectionId: string | null - payload: ParsedAgentStatusPayload - stateStartedAt: number - updatedAt: number -} - export type ConnectedPtyEvidence = { tabIds: ReadonlySet paneKeys: ReadonlySet - ptyIds: ReadonlySet + /** The connected PTY behind each issued terminal handle. A status row names a pane and the + * handle it was observed under, never a process, so this is where it rejoins its terminal — + * and it is the only rescue left for a row whose pane binding was cleared under it. */ + ptyIdByTerminalHandle: ReadonlyMap } -/** Reconcile terminal status, then admit rows using their execution-host evidence. */ +/** Admit hook-server rows using their execution-host evidence. */ export function collectRuntimeWorktreePtyAgentSources(args: { - retainedSnapshots: Iterable hookSnapshots: readonly AgentStatusIpcPayload[] mirroredWorktreeIdByTabId: ReadonlyMap connectedPtyEvidence: ConnectedPtyEvidence @@ -37,50 +26,16 @@ export function collectRuntimeWorktreePtyAgentSources(args: { string, RuntimeWorktreeAgentSource & { payload: ParsedAgentStatusPayload } >() - const now = Date.now() - for (const snapshot of args.retainedSnapshots) { - const { payload } = snapshot - rowSources.set(snapshot.paneKey, { - paneKey: snapshot.paneKey, - ptyId: snapshot.ptyId, - tabId: snapshot.tabId, - worktreeId: snapshot.worktreeId, - connectionId: snapshot.connectionId, - payload, - state: payload.state, - ...(payload.workingMode ? { workingMode: payload.workingMode } : {}), - agentType: payload.agentType ?? null, - prompt: payload.prompt, - lastAssistantMessage: payload.lastAssistantMessage ?? null, - toolName: payload.toolName ?? null, - toolInput: payload.toolInput ?? null, - interrupted: payload.interrupted ?? false, - stateStartedAt: snapshot.stateStartedAt, - updatedAt: snapshot.updatedAt - }) - } for (const entry of args.hookSnapshots) { - if (entry.restoredUnconfirmed === true) { + if (entry.restoredUnconfirmed === true || entry.providerSessionOnly === true) { continue } - const existing = rowSources.get(entry.paneKey) const hookPayload = pickParsedAgentStatusPayload(entry) - if (existing && existing.updatedAt > entry.receivedAt) { - if ( - entry.workingMode === 'monitoring' && - now - entry.receivedAt <= AGENT_STATUS_STALE_AFTER_MS && - terminalStatusPayloadMatchesHook(hookPayload, existing.payload) - ) { - existing.workingMode = 'monitoring' - if (existing.payload.workingMode === undefined) { - existing.payload = { ...existing.payload, workingMode: 'monitoring' } - } - } - continue - } rowSources.set(entry.paneKey, { paneKey: entry.paneKey, - ptyId: existing?.ptyId, + ptyId: entry.terminalHandle + ? args.connectedPtyEvidence.ptyIdByTerminalHandle.get(entry.terminalHandle) + : undefined, tabId: entry.tabId, worktreeId: entry.worktreeId, connectionId: entry.connectionId, @@ -94,10 +49,8 @@ export function collectRuntimeWorktreePtyAgentSources(args: { toolInput: entry.toolInput ?? null, interrupted: entry.interrupted ?? false, stateStartedAt: entry.stateStartedAt, - // A structured row's clock is its journal, so a restart's republish does not read as new. - updatedAt: entry.structuredHost - ? (entry.evidenceObservedAt ?? entry.receivedAt) - : entry.receivedAt, + // A replay advances delivery order, not the age of the evidence shown by worktree.ps. + updatedAt: entry.evidenceObservedAt ?? entry.receivedAt, ...(entry.structuredHost ? { structuredHost: entry.structuredHost } : {}) }) } @@ -117,7 +70,8 @@ export function collectRuntimeWorktreePtyAgentSources(args: { (source.connectionId === null || isWslHookRelayConnectionId(source.connectionId)) && !args.connectedPtyEvidence.tabIds.has(tabId) && !args.connectedPtyEvidence.paneKeys.has(source.paneKey) && - (source.ptyId === undefined || !args.connectedPtyEvidence.ptyIds.has(source.ptyId)) + // Resolved only from a connected PTY's handle, so its presence is the liveness evidence. + source.ptyId === undefined ) { continue } diff --git a/src/main/runtime/runtime-worktree-structured-agent-rows-liveness.test.ts b/src/main/runtime/runtime-worktree-structured-agent-rows-liveness.test.ts index 519b9026f17..afe5a3a2a71 100644 --- a/src/main/runtime/runtime-worktree-structured-agent-rows-liveness.test.ts +++ b/src/main/runtime/runtime-worktree-structured-agent-rows-liveness.test.ts @@ -115,8 +115,11 @@ function worktreeFor(store: AgentHookServer): RuntimeWorktreePsSummary { workingTerminalEvidenceByWorktreeId: new Map(), rowSources: collectRuntimeWorktreeAgentSources({ mirroredWorktreeIdByTabId: new Map(), - connectedPtyEvidence: { tabIds: new Set(), paneKeys: new Set(), ptyIds: new Set() }, - retainedSnapshots: [], + connectedPtyEvidence: { + tabIds: new Set(), + paneKeys: new Set(), + ptyIdByTerminalHandle: new Map() + }, hookSnapshots: store.getStatusSnapshot() }), orchestrationByPaneKey: null, diff --git a/src/main/runtime/structured-agent-session-close.test.ts b/src/main/runtime/structured-agent-session-close.test.ts new file mode 100644 index 00000000000..531ca0aa129 --- /dev/null +++ b/src/main/runtime/structured-agent-session-close.test.ts @@ -0,0 +1,237 @@ +/** + * The chat tab must survive a close that did not land. + * + * `closeStructuredAgentSessionChild` hides the tab BEFORE it issues the close, so every failure + * shape past that point used to leave the user's chat tab pulled out of the durable restore index + * for a session that is still running — a destructive operation that refused, and still took + * something away. + */ + +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { AgentSessionRecord } from '../../shared/agent-session-record' + +const hostRef: { current: unknown } = { current: null } + +vi.mock('../native-chat/agent-session-wire/structured-agent-session-registry', () => ({ + getStructuredAgentSessionHost: () => hostRef.current +})) + +const { closeStructuredAgentSessionChild } = await import('./structured-agent-session-close') + +const SESSION = 'session-1' + +function record(sessionId: string): AgentSessionRecord { + return { + sessionId, + provider: 'claude', + location: { + executionHostId: 'local', + wslDistro: null, + workspaceId: 'repo_1::/tmp/wt-a', + workspaceKind: 'folder' + }, + lease: { + sessionId, + runtimeKind: 'native', + claimStatus: 'live', + handoffStage: null, + runtimeFence: 1, + deathEvidence: null + } + } as unknown as AgentSessionRecord +} + +type HostOptions = { + /** Sessions the host keeps holding through a close, so the post-close observation is `live`. */ + stuck?: boolean + /** Rejects the close, without the child going. */ + closeThrows?: Error + /** The child dies and is recorded dead, but the close then fails past that proof. */ + settledThenThrows?: boolean + /** Rejects the visibility write itself, so the hide never lands. */ + visibilityThrows?: Error + /** Sessions already in the persisted visible-tab index. */ + visible?: string[] + /** Blows up the index read, so the rollback cannot prove the tab was ever visible. */ + indexThrows?: boolean +} + +function installHost(options: HostOptions = {}) { + const entry = record(SESSION) + const held = new Set([SESSION]) + const visible = new Set(options.visible ?? [SESSION]) + const setSessionTabVisibility = vi.fn(async (sessionId: string, isVisible: boolean) => { + if (options.visibilityThrows) { + throw options.visibilityThrows + } + if (isVisible) { + visible.add(sessionId) + } else { + visible.delete(sessionId) + } + }) + const close = vi.fn(async (sessionId: string) => { + if (options.closeThrows) { + throw options.closeThrows + } + if (options.stuck) { + return + } + held.delete(sessionId) + entry.lease.claimStatus = 'released' + entry.lease.deathEvidence = { kind: 'exit-observed', detail: 'closed', observedAt: 1 } + if (options.settledThenThrows) { + throw new Error('the event sink could not be flushed') + } + }) + hostRef.current = { + deps: { store: { getRecord: (id: string) => (id === SESSION ? entry : null) } }, + hasSession: (sessionId: string) => held.has(sessionId), + getPersistedVisibleSessionTabIndex: () => { + if (options.indexThrows) { + throw new Error('visible tab index unreadable') + } + return { present: true, sessionIds: [...visible] } + }, + setSessionTabVisibility, + close + } + return { close, setSessionTabVisibility, visible } +} + +describe('closeStructuredAgentSessionChild tab-visibility rollback', () => { + beforeEach(() => { + hostRef.current = null + vi.restoreAllMocks() + }) + + it('retires the tab and reports the close on the success path', async () => { + const host = installHost() + const retire = vi.fn(() => true) + + const outcome = await closeStructuredAgentSessionChild(SESSION, { + runtime: { + retireStructuredAgentSessionTabFromSnapshot: retire + } as never + }) + + expect(outcome).toEqual({ stopped: true, closeAttempted: true }) + expect(host.visible.has(SESSION)).toBe(false) + expect(retire).toHaveBeenCalledWith(SESSION) + // The hide is the only visibility write a settled close performs. + expect(host.setSessionTabVisibility.mock.calls).toEqual([[SESSION, false]]) + }) + + it('restores the tab when the close throws and the child is still there', async () => { + const host = installHost({ closeThrows: new Error('provider round trip failed') }) + + const outcome = await closeStructuredAgentSessionChild(SESSION) + + expect(outcome.stopped).toBe(false) + expect(outcome.closeAttempted).toBe(true) + expect(outcome.reason).toBe('provider round trip failed') + expect(host.visible.has(SESSION)).toBe(true) + expect(host.setSessionTabVisibility.mock.calls).toEqual([ + [SESSION, false], + [SESSION, true] + ]) + }) + + it('restores the tab when the post-close observation is not `exited`', async () => { + const host = installHost({ stuck: true }) + + const outcome = await closeStructuredAgentSessionChild(SESSION) + + expect(outcome.stopped).toBe(false) + expect(outcome.closeAttempted).toBe(true) + expect(host.visible.has(SESSION)).toBe(true) + expect(host.setSessionTabVisibility.mock.calls).toEqual([ + [SESSION, false], + [SESSION, true] + ]) + }) + + it('leaves the tab retired when a close throws PAST a proven exit', async () => { + // `closeStructuredSessionsForWorktree` re-observes and counts this session closed; republishing + // the tab here would resurrect it at the next launch for a workspace that is gone. + const host = installHost({ settledThenThrows: true }) + + const outcome = await closeStructuredAgentSessionChild(SESSION) + + expect(outcome.stopped).toBe(false) + expect(host.visible.has(SESSION)).toBe(false) + expect(host.setSessionTabVisibility.mock.calls).toEqual([[SESSION, false]]) + }) + + it('does not put the tab back when the caller is discarding the workspace anyway', async () => { + // Worktree teardown passes this off for a removal that cannot refuse — force, and the + // folder-workspace paths. A tab put back there is a durable reference to a workspace that is + // about to be gone, so it republishes the chat at the next launch pointing at it. + const host = installHost({ stuck: true }) + + const outcome = await closeStructuredAgentSessionChild(SESSION, { + restoreTabOnUnprovenClose: false + }) + + expect(outcome.stopped).toBe(false) + expect(host.visible.has(SESSION)).toBe(false) + expect(host.setSessionTabVisibility.mock.calls).toEqual([[SESSION, false]]) + }) + + it('does not publish a tab for a session that was already hidden', async () => { + const host = installHost({ closeThrows: new Error('provider round trip failed'), visible: [] }) + + await closeStructuredAgentSessionChild(SESSION) + + expect(host.visible.has(SESSION)).toBe(false) + expect(host.setSessionTabVisibility.mock.calls).toEqual([[SESSION, false]]) + }) + + it('does not roll back a visibility write that never landed', async () => { + const host = installHost({ visibilityThrows: new Error('visibility write failed') }) + + const outcome = await closeStructuredAgentSessionChild(SESSION) + + expect(outcome).toEqual({ + stopped: false, + closeAttempted: false, + reason: 'visibility write failed' + }) + expect(host.close).not.toHaveBeenCalled() + expect(host.setSessionTabVisibility.mock.calls).toEqual([[SESSION, false]]) + }) + + it('keeps the original failure when the restore itself throws', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const host = installHost({ stuck: true }) + host.setSessionTabVisibility.mockImplementation(async (_sessionId, isVisible) => { + if (isVisible) { + throw new Error('agent_session_identity_required') + } + }) + + const outcome = await closeStructuredAgentSessionChild(SESSION) + + expect(outcome.stopped).toBe(false) + expect(outcome.closeAttempted).toBe(true) + expect(outcome.reason).not.toContain('agent_session_identity_required') + expect(warn).toHaveBeenCalled() + }) + + it('claims nothing when the visible-tab index cannot be read', async () => { + const host = installHost({ indexThrows: true, closeThrows: new Error('boom') }) + + await closeStructuredAgentSessionChild(SESSION) + + expect(host.setSessionTabVisibility.mock.calls).toEqual([[SESSION, false]]) + }) + + it('reports no close attempt when no host is installed', async () => { + hostRef.current = null + + const outcome = await closeStructuredAgentSessionChild(SESSION) + + expect(outcome.stopped).toBe(false) + expect(outcome.closeAttempted).toBe(false) + }) +}) diff --git a/src/main/runtime/structured-agent-session-close.ts b/src/main/runtime/structured-agent-session-close.ts index 756dbdeaef4..f65d1204db9 100644 --- a/src/main/runtime/structured-agent-session-close.ts +++ b/src/main/runtime/structured-agent-session-close.ts @@ -11,6 +11,7 @@ * longer live is proven gone. Anything else is retained rather than settled. */ +import type { StructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-host' import { getStructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-registry' import type { OrcaRuntimeService } from './orca-runtime' import { retireSettledStructuredWorkerTab } from './structured-agent-session-tab-retirement' @@ -35,6 +36,15 @@ export type StructuredAgentSessionCloseOptions = { * keep the child un-evictable for the life of the app. Every settlement has to reach it. */ afterClose?: () => void + /** + * Whether an unproven close may put the chat tab back in the durable restore index. + * + * On by default, which is the retryable case: a stop that refused and still took the user's tab + * away is the loss the rollback exists to undo. A caller that will discard the WORKSPACE + * whatever this close reports passes false — a tab put back there is a durable reference to a + * workspace about to be gone, and it republishes the chat at the next launch pointing at it. + */ + restoreTabOnUnprovenClose?: boolean } export async function closeStructuredAgentSessionChild( @@ -50,6 +60,11 @@ export async function closeStructuredAgentSessionChild( reason: 'The structured agent-session host is not installed; no session was closed.' } } + // Read BEFORE the hide, so a rollback puts the tab back exactly as it was. Restoring + // unconditionally would publish a tab for a session that was already hidden — a worker started + // without a chat tab, or one the user had closed — which is a new side effect, not an undo. + const restoreTabIfCloseFails = + options.restoreTabOnUnprovenClose !== false && readPersistedTabVisibility(host, sessionId) // Set only once the close is actually issued: `setSessionTabVisibility` throwing first leaves a // running child, and a receipt that still said `closed_agent_terminal` for it would be the // close-that-never-happened this flag exists to rule out. @@ -59,6 +74,11 @@ export async function closeStructuredAgentSessionChild( closeAttempted = true await host.close(sessionId) } catch (error) { + // Only `closeAttempted` proves the hide landed: the store transaction restores its own state on + // failure, so a `setSessionTabVisibility` that threw hid nothing and has nothing to undo. + if (closeAttempted) { + await restorePersistedTabVisibility(host, sessionId, restoreTabIfCloseFails) + } return { stopped: false, closeAttempted, @@ -68,6 +88,7 @@ export async function closeStructuredAgentSessionChild( options.afterClose?.() const observation = observeStructuredWorker({ sessionId }) if (observation.status !== 'exited') { + await restorePersistedTabVisibility(host, sessionId, restoreTabIfCloseFails) return { stopped: false, closeAttempted: true, @@ -79,3 +100,52 @@ export async function closeStructuredAgentSessionChild( retireSettledStructuredWorkerTab(sessionId, options.runtime) return { stopped: true, closeAttempted: true } } + +function readPersistedTabVisibility(host: StructuredAgentSessionHost, sessionId: string): boolean { + try { + return host.getPersistedVisibleSessionTabIndex?.().sessionIds.includes(sessionId) ?? false + } catch { + // Unreadable index: claim nothing. A rollback that cannot prove the tab was visible must not + // publish one, for the same reason the read exists at all. + return false + } +} + +/** + * Puts the chat tab back after a close that did not settle. + * + * The hide is the one visible side effect this function performs before the destructive step, so a + * failed close that kept it left the user's chat tab gone from the durable restore index — the + * conversation survived under `userData`, but nothing brought the tab back at the next launch. + * + * Re-observed first rather than restored outright: a close can throw PAST its own proof and still + * have taken the child with it, and `closeStructuredSessionsForWorktree` reads exactly that, + * counting such a session closed and retiring its tab. Republishing there would resurrect a tab for + * a session that is demonstrably gone, at the next launch, pointing at a deleted workspace. + * + * That observation NARROWS the window; it does not close it. This one and the sweep's are taken a + * store write apart, so a child that dies in between is unverifiable here and exited there — which + * is why the sweep re-drops the tab reference when it takes that proof. Do not delete either half + * on the strength of the other. + * + * Never throws: the caller's `reason` is what the user is asked to act on, and a rollback failure + * must not replace it. `agent_session_identity_required` is the expected one — the record can be + * gone by now, which is itself the exit this restore is declining to undo. + */ +async function restorePersistedTabVisibility( + host: StructuredAgentSessionHost, + sessionId: string, + restoreTab: boolean +): Promise { + if (!restoreTab || observeStructuredWorker({ sessionId }).status === 'exited') { + return + } + try { + await host.setSessionTabVisibility?.(sessionId, true) + } catch (error) { + console.warn( + `[structured-session-close] could not restore the chat tab for ${sessionId} after a failed close`, + error + ) + } +} diff --git a/src/main/runtime/structured-conversation-tab-replacement.ts b/src/main/runtime/structured-conversation-tab-replacement.ts index 94d9bdf52d9..7384a374c91 100644 --- a/src/main/runtime/structured-conversation-tab-replacement.ts +++ b/src/main/runtime/structured-conversation-tab-replacement.ts @@ -1,3 +1,4 @@ +import { defaultAgentChatLabel } from '../../shared/agent-session-chat-label' import type { RuntimeMobileSessionTabsSnapshot } from '../../shared/runtime-types' import type { ConversationReplacement } from '../native-chat/agent-session-wire/structured-conversation-command' @@ -30,7 +31,7 @@ export function replaceConversationInSnapshot( id, sessionId: replacement.sessionId, agent: replacement.agent, - title: replacement.agent === 'claude' ? 'Claude Chat' : 'Codex Chat', + title: defaultAgentChatLabel(replacement.agent), replacesSessionId: replacement.sourceSessionId } : tab diff --git a/src/main/runtime/structured-session-worktree-teardown.test.ts b/src/main/runtime/structured-session-worktree-teardown.test.ts index a9bdf6aa45c..bb022d4ba16 100644 --- a/src/main/runtime/structured-session-worktree-teardown.test.ts +++ b/src/main/runtime/structured-session-worktree-teardown.test.ts @@ -8,18 +8,31 @@ vi.mock('../native-chat/agent-session-wire/structured-agent-session-registry', ( })) const { killAllProcessesForWorktree } = await import('./worktree-teardown') -const { classifyWorktreeForceDeleteReason } = await import('../../shared/worktree/removal') +const { + classifyWorktreeForceDeleteReason, + isProvenLiveStructuredSessionRemovalError, + isUnstoppedPtyRemovalError +} = await import('../../shared/worktree/removal') const { listLiveStructuredSessionsForWorktree } = await import('./structured-session-worktree-teardown') const WORKTREE = 'repo_1::/tmp/wt-a' const OTHER_WORKTREE = 'repo_1::/tmp/wt-b' -function record(sessionId: string, workspaceId: string): AgentSessionRecord { +function record( + sessionId: string, + workspaceId: string, + options: { provider?: 'claude' | 'codex'; executionHostId?: string } = {} +): AgentSessionRecord { return { sessionId, - provider: 'claude', - location: { executionHostId: 'local', wslDistro: null, workspaceId, workspaceKind: 'folder' }, + provider: options.provider ?? 'claude', + location: { + executionHostId: options.executionHostId ?? 'local', + wslDistro: null, + workspaceId, + workspaceKind: 'folder' + }, lease: { sessionId, runtimeKind: 'native', @@ -33,24 +46,66 @@ function record(sessionId: string, workspaceId: string): AgentSessionRecord { function installHost(options: { records: AgentSessionRecord[] - /** Sessions the host still holds; a close removes one unless it is listed as stuck. */ + /** Sessions the host keeps holding through a close, so the post-close observation is `live`. */ stuck?: Set -}): { closed: string[] } { + /** Sessions the host drops without death evidence, so the observation is `unverifiable`. */ + unverifiable?: Set + /** Sessions whose child dies and is recorded dead, but whose close then fails past that point. */ + settledThenThrows?: Set + /** Blocks every close, to exercise the shared sweep budget without fake timers. */ + closeGate?: Promise + /** Blocks ONE session's close, so the serial loop can be caught part-way through. */ + closeGates?: Record> + /** Sessions in the persisted visible-tab index, so a rollback has something to put back. */ + visible?: string[] + /** + * Sessions whose death evidence lands DURING the close's tab-restore write. + * + * `setSessionTabVisibility` is a store transaction — a real disk write — so the close's own + * observation and the sweep's re-read straddle it and can disagree about the same session. + */ + exitsDuringTabRestore?: Set +}): { closed: string[]; visible: Set } { const held = new Set(options.records.map((entry) => entry.sessionId)) const closed: string[] = [] + const visible = new Set(options.visible ?? []) + const recordExit = (sessionId: string): void => { + const entry = options.records.find((candidate) => candidate.sessionId === sessionId) + if (entry) { + entry.lease.claimStatus = 'released' + entry.lease.deathEvidence = { kind: 'exit-observed', detail: 'closed', observedAt: 1 } + } + } hostRef.current = { deps: { store: { listRecords: () => options.records, getRecord: () => null } }, hasSession: (sessionId: string) => held.has(sessionId), - setSessionTabVisibility: async () => {}, + getPersistedVisibleSessionTabIndex: () => ({ present: true, sessionIds: [...visible] }), + setSessionTabVisibility: async (sessionId: string, isVisible: boolean) => { + if (!isVisible) { + visible.delete(sessionId) + return + } + if (options.exitsDuringTabRestore?.has(sessionId)) { + recordExit(sessionId) + } + visible.add(sessionId) + }, close: async (sessionId: string) => { closed.push(sessionId) - if (!options.stuck?.has(sessionId)) { - held.delete(sessionId) - const record = options.records.find((entry) => entry.sessionId === sessionId) - if (record) { - record.lease.claimStatus = 'released' - record.lease.deathEvidence = { kind: 'exit-observed', detail: 'closed', observedAt: 1 } - } + await options.closeGate + await options.closeGates?.[sessionId] + if (options.stuck?.has(sessionId)) { + return + } + held.delete(sessionId) + if (options.unverifiable?.has(sessionId)) { + return + } + if (!options.exitsDuringTabRestore?.has(sessionId)) { + recordExit(sessionId) + } + if (options.settledThenThrows?.has(sessionId)) { + throw new Error('the event sink could not be flushed') } } } @@ -59,7 +114,7 @@ function installHost(options: { hostRef.current as { deps: { store: { getRecord: (id: string) => unknown } } } ).deps.store.getRecord = (sessionId: string) => options.records.find((entry) => entry.sessionId === sessionId) ?? null - return { closed } + return { closed, visible } } const localProvider = { @@ -67,7 +122,7 @@ const localProvider = { shutdown: async () => {} } as never -function destructiveDeps(extra: { allowUnverifiedStop?: boolean } = {}) { +function destructiveDeps(extra: { allowUnverifiedStop?: boolean; timeoutMs?: number } = {}) { return { localProvider, requirePhysicalStop: true, @@ -77,6 +132,15 @@ function destructiveDeps(extra: { allowUnverifiedStop?: boolean } = {}) { } } +/** The structured sweep's own warn — a forced removal can emit a PTY-sweep one onto the same spy. */ +function structuredSessionWarning(warn: { mock: { calls: unknown[][] } }): string { + return ( + warn.mock.calls + .map((call) => String(call[0])) + .find((message) => message.includes('agent session')) ?? '' + ) +} + describe('worktree teardown and structured agent sessions', () => { beforeEach(() => { hostRef.current = null @@ -84,24 +148,98 @@ describe('worktree teardown and structured agent sessions', () => { it('finds sessions by workspace, and ignores a sibling worktree', () => { installHost({ records: [record('s1', WORKTREE), record('s2', OTHER_WORKTREE)] }) - expect(listLiveStructuredSessionsForWorktree(WORKTREE)).toEqual([ + expect(listLiveStructuredSessionsForWorktree(WORKTREE, {})).toEqual([ { sessionId: 's1', agent: 'claude' } ]) }) - it('refuses a destructive removal rather than deleting the checkout under a live child', async () => { - // The defect this pins: all three PTY sweeps enumerate leaves, provider sessions and the local - // registry, and a structured session is on NONE of them. Every sweep answered zero, nothing - // errored, and removal proceeded — leaving the provider child running with its `cwd` deleted - // and the dispatch still reporting the worker live and exact. - installHost({ records: [record('s1', WORKTREE)] }) + it('closes a live session on an ordinary removal instead of refusing it', async () => { + // The defect this pins, and the reason the guard is not simply deleted: all three PTY sweeps + // enumerate leaves, provider sessions and the local registry, and a structured session is on + // NONE of them, so removal used to proceed leaving the provider child running with its `cwd` + // deleted. The stop belongs on the ordinary path — the same one that kills a terminal running + // the same agent — so an idle chat is no harder to delete than that terminal. + const host = installHost({ records: [record('s1', WORKTREE)] }) + await expect(killAllProcessesForWorktree(WORKTREE, destructiveDeps())).resolves.toMatchObject({ + structuredStopped: 1 + }) + expect(host.closed).toEqual(['s1']) + }) + + it('refuses only when the close does not settle', async () => { + installHost({ records: [record('s1', WORKTREE)], stuck: new Set(['s1']) }) await expect(killAllProcessesForWorktree(WORKTREE, destructiveDeps())).rejects.toThrow( - /1 running agent session/ + /still live: 1 agent session \(claude\)/ ) }) + it('puts the chat tab back when the removal refuses over the session', async () => { + // The workspace survives a refusal, so the tab has to survive it too: a destructive operation + // that refused and still took the user's chat tab away is the loss the rollback exists to undo. + const host = installHost({ + records: [record('s1', WORKTREE)], + stuck: new Set(['s1']), + visible: ['s1'] + }) + await expect(killAllProcessesForWorktree(WORKTREE, destructiveDeps())).rejects.toThrow( + /still live: 1 agent session \(claude\)/ + ) + expect([...host.visible]).toEqual(['s1']) + }) + + it('leaves the chat tab dropped when a forced removal deletes the workspace anyway', async () => { + // The other half of the same rollback. Force does not refuse — it warns and goes on to delete + // the checkout — so putting the tab back leaves a DURABLE reference to a workspace that is + // about to be gone, which republishes the chat at the next launch pointing at a deleted + // worktree: the exact outcome this whole sweep exists to remove. + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const host = installHost({ + records: [record('s1', WORKTREE)], + stuck: new Set(['s1']), + visible: ['s1'] + }) + await killAllProcessesForWorktree(WORKTREE, destructiveDeps({ allowUnverifiedStop: true })) + expect([...host.visible]).toEqual([]) + warn.mockRestore() + }) + + it('leaves the chat tab dropped for a folder-workspace removal, which never refuses', async () => { + // Same reasoning without the force waiver: this caller cannot refuse at all, so the workspace + // is forgotten whatever the close reports. + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const host = installHost({ + records: [record('s1', WORKTREE)], + stuck: new Set(['s1']), + visible: ['s1'] + }) + await killAllProcessesForWorktree(WORKTREE, { + localProvider, + includeProviderInventory: false as const, + includeLocalRegistry: false as const, + closeStructuredSessions: true + }) + expect([...host.visible]).toEqual([]) + warn.mockRestore() + }) + + it('drops the chat tab for a session the sweep proves exited after the close gave up', async () => { + // `host.close` can return BEFORE the child's exit is recorded, so the close's own observation + // reads unverifiable and puts the tab back — and the sweep's re-read, one store write later, + // proves the exit and counts the session closed. The two observations straddle that write and + // can disagree; the tab must not survive the disagreement, because this removal proceeds. + const host = installHost({ + records: [record('s1', WORKTREE)], + visible: ['s1'], + exitsDuringTabRestore: new Set(['s1']) + }) + await expect(killAllProcessesForWorktree(WORKTREE, destructiveDeps())).resolves.toMatchObject({ + structuredStopped: 1 + }) + expect([...host.visible]).toEqual([]) + }) + it('names the force escape hatch in the refusal, like the unstopped-PTY gate', async () => { - installHost({ records: [record('s1', WORKTREE)] }) + installHost({ records: [record('s1', WORKTREE)], stuck: new Set(['s1']) }) await expect(killAllProcessesForWorktree(WORKTREE, destructiveDeps())).rejects.toThrow(/force/i) }) @@ -109,7 +247,7 @@ describe('worktree teardown and structured agent sessions', () => { // The #11960 dead end, and the shape this file's own comments warn about: the desktop // affordance comes ONLY from the classifier, and an ordinary delete already passes force:true // for the dirty-file skip — so a refusal with no matcher shows raw CLI wording with no button. - installHost({ records: [record('s1', WORKTREE)] }) + installHost({ records: [record('s1', WORKTREE)], stuck: new Set(['s1']) }) const error = await killAllProcessesForWorktree(WORKTREE, destructiveDeps()).catch( (thrown: Error) => thrown.message ) @@ -123,12 +261,12 @@ describe('worktree teardown and structured agent sessions', () => { // A session id is one tab-id hop from the random pane key that gates a worker's mailbox, and // this string reaches CLI output and a desktop toast. A count and the providers are what a // user deciding whether to force actually needs. - installHost({ records: [record('s1', WORKTREE)] }) + installHost({ records: [record('s1', WORKTREE)], stuck: new Set(['s1']) }) const error = await killAllProcessesForWorktree(WORKTREE, destructiveDeps()).catch( (thrown: Error) => thrown.message ) expect(error).not.toContain('s1') - expect(error).toContain('1 running agent session') + expect(error).toContain('1 agent session (claude)') }) it('closes best-effort for a folder-workspace removal, which requires no stop proof', async () => { @@ -166,10 +304,33 @@ describe('worktree teardown and structured agent sessions', () => { destructiveDeps({ allowUnverifiedStop: true }) ) expect(result.structuredStopped).toBeUndefined() - expect(warn).toHaveBeenCalledWith(expect.stringContaining('still attached')) + // The live arm of that record, carrying the verdict the refusal would have shown. + expect(structuredSessionWarning(warn)).toContain('still live: 1 agent session (claude)') warn.mockRestore() }) + it('takes the proof when a failed close is re-observed as exited', async () => { + // `closeStructuredAgentSessionChild` reports `stopped: false` for anything that throws past its + // own observation, and for a record whose death evidence lands after it read. The re-read here + // can still PROVE the exit — refusing a delete over a child that is demonstrably gone is the + // defect this whole sweep exists to remove, so the proof has to win over the close's verdict. + const retired: string[] = [] + const runtime = { + stopTerminalsForWorktree: async () => ({ stopped: 0 }), + retireStructuredAgentSessionTabFromSnapshot: (sessionId: string) => { + retired.push(sessionId) + return true + } + } as never + installHost({ records: [record('s1', WORKTREE)], settledThenThrows: new Set(['s1']) }) + await expect( + killAllProcessesForWorktree(WORKTREE, { ...destructiveDeps(), runtime }) + ).resolves.toMatchObject({ structuredStopped: 1 }) + // Retired here because the close gave up before its own retirement step, and a chat tab left + // behind re-attaches a released session pointing at a workspace that is about to be deleted. + expect(retired).toEqual(['s1']) + }) + it('leaves the best-effort reconciliation paths alone', async () => { // Those callers repair state and delete nothing, so a refusal there would wedge a repair. installHost({ records: [record('s1', WORKTREE)] }) @@ -182,6 +343,266 @@ describe('worktree teardown and structured agent sessions', () => { ).resolves.toMatchObject({ runtimeStopped: 0 }) }) + it('leaves a same-id workspace on another execution host alone', async () => { + // A workspace id is `repoId::path` with no host component, so the local, SSH and paired-runtime + // copies of one id are DIFFERENT workspaces. Unfenced, deleting the local one closed a chat + // running on somebody else's machine — a destructive cross-host act, not a spurious refusal. + const host = installHost({ + records: [record('s1', WORKTREE, { executionHostId: 'ssh:host-a' })] + }) + await expect(killAllProcessesForWorktree(WORKTREE, destructiveDeps())).resolves.toMatchObject({ + runtimeStopped: 0 + }) + expect(host.closed).toEqual([]) + }) + + it('reads an explicit local fence the way the PTY sweeps do', () => { + // This helper reuses the PTY fence's own type, so the two cannot answer `null` differently: + // there it means this machine, and it has to mean this machine here. ABSENT is the one + // deliberate difference — no fence at all for the PTY sweeps, narrowed to local here, because + // a single-host-id comparison cannot express match-all and closing every host's chats is + // destructive. Latent today only because `WorktreeTeardownDeps` cannot yet carry the `null`. + installHost({ + records: [record('s1', WORKTREE, { executionHostId: 'ssh:host-a' }), record('s2', WORKTREE)] + }) + const local = [{ sessionId: 's2', agent: 'claude' }] + expect(listLiveStructuredSessionsForWorktree(WORKTREE, { resolvedConnectionId: null })).toEqual( + local + ) + expect(listLiveStructuredSessionsForWorktree(WORKTREE, {})).toEqual(local) + }) + + it('closes only the session on the host the removal resolved to', async () => { + const host = installHost({ + records: [record('s1', WORKTREE, { executionHostId: 'ssh:host-a' }), record('s2', WORKTREE)] + }) + await expect( + killAllProcessesForWorktree(WORKTREE, { + ...destructiveDeps(), + resolvedConnectionId: 'host-a' + }) + ).resolves.toMatchObject({ structuredStopped: 1 }) + expect(host.closed).toEqual(['s1']) + }) + + it('names only the sessions that stayed, and every provider still there', async () => { + installHost({ + records: [ + record('s1', WORKTREE), + record('s2', WORKTREE, { provider: 'codex' }), + record('s3', WORKTREE) + ], + stuck: new Set(['s2', 's3']) + }) + const error = await killAllProcessesForWorktree(WORKTREE, destructiveDeps()).catch( + (thrown: Error) => thrown.message + ) + expect(error).toContain('still live: 2 agent sessions (claude, codex)') + }) + + it('names the unconfirmed sessions too, instead of counting only the live ones', async () => { + // The PTY sibling may drop everything outside its live list because a fresh inventory PROVED + // those exited. Nothing proves that here: an `unverifiable` session is unclosed as well, so + // naming only the live subset told the user "1 agent session" while two were about to go. + installHost({ + records: [record('s1', WORKTREE), record('s2', WORKTREE, { provider: 'codex' })], + stuck: new Set(['s1']), + unverifiable: new Set(['s2']) + }) + const error = await killAllProcessesForWorktree(WORKTREE, destructiveDeps()).catch( + (thrown: Error) => thrown.message + ) + expect(error).toContain( + 'still live: 1 agent session (claude); could not confirm these closed: 1 agent session (codex)' + ) + // The marker still leads, so the toast keeps showing the stronger of the two warnings. + expect(isProvenLiveStructuredSessionRemovalError(error as string)).toBe(true) + }) + + it('still reports what it closed when a forced removal skips the PTY verdict', async () => { + // A sweep that fails outright short-circuits the per-PTY verdict — but not the structured + // close that already ran, so the count has to survive that return or the removal log claims + // `structured=0` for chats it just ended. + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const runtime = { + stopTerminalsForWorktree: async () => { + throw new Error('the terminal sweep died') + } + } as never + const host = installHost({ records: [record('s1', WORKTREE)] }) + const result = await killAllProcessesForWorktree(WORKTREE, { + ...destructiveDeps({ allowUnverifiedStop: true }), + runtime + }) + expect(host.closed).toEqual(['s1']) + expect(result.structuredStopped).toBe(1) + warn.mockRestore() + }) + + it('separates a close it could not confirm from one it watched stay attached', async () => { + // `src/shared/worktree/removal.ts` keeps these two apart on purpose: a user waiving "we could + // not confirm" is making a different decision than one discarding a conversation Orca just saw + // running. The toast branches on this marker, so flattening them makes one of the two a lie. + installHost({ records: [record('s1', WORKTREE)], unverifiable: new Set(['s1']) }) + const unconfirmed = await killAllProcessesForWorktree(WORKTREE, destructiveDeps()).catch( + (thrown: Error) => thrown.message + ) + expect(unconfirmed).toContain('could not confirm these closed: 1 agent session (claude)') + expect(isProvenLiveStructuredSessionRemovalError(unconfirmed as string)).toBe(false) + + installHost({ records: [record('s1', WORKTREE)], stuck: new Set(['s1']) }) + const live = await killAllProcessesForWorktree(WORKTREE, destructiveDeps()).catch( + (thrown: Error) => thrown.message + ) + expect(isProvenLiveStructuredSessionRemovalError(live as string)).toBe(true) + }) + + it('refuses in agent-session wording when the close outlives the sweep budget', async () => { + // A structured close that runs out of time used to reject with the PTY timeout sentinel, which + // the classifier reads FIRST — so the toast blamed terminals, and the Force Delete meant to + // clear the wedge hit the same rejection again (#11960). + installHost({ records: [record('s1', WORKTREE)], closeGate: new Promise(() => {}) }) + const error = await killAllProcessesForWorktree( + WORKTREE, + destructiveDeps({ timeoutMs: 5 }) + ).catch((thrown: Error) => thrown.message) + expect(error).toContain('could not confirm these closed: 1 agent session (claude)') + expect(isUnstoppedPtyRemovalError(error as string)).toBe(false) + expect(classifyWorktreeForceDeleteReason(error as string, true)).toBe('running-agent-session') + }) + + it('never wedges Force Delete on a close that will not settle', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + installHost({ records: [record('s1', WORKTREE)], closeGate: new Promise(() => {}) }) + await expect( + killAllProcessesForWorktree( + WORKTREE, + destructiveDeps({ allowUnverifiedStop: true, timeoutMs: 5 }) + ) + ).resolves.toMatchObject({ runtimeStopped: 0 }) + const message = structuredSessionWarning(warn) + expect(message).toContain('could not confirm these closed: 1 agent session (claude)') + // The pin: a close that ran out of time was never watched stay attached. This warn is the only + // record a forced removal leaves, and the removal.ts split exists precisely so "we could not + // confirm" is never reported as "we saw it running" — including here. + expect(message).not.toContain('still attached') + warn.mockRestore() + }) + + it('names only the sessions still open when the budget expires mid-close', async () => { + // The close loop is serial, so a deadline can land part-way through it. A fallback assembled + // at the deadline could only name the whole list — so a removal that had already closed the + // first chat still told the user both were still there, which is the exact thing this sweep + // exists to stop doing: never report state nobody observed. + installHost({ + records: [record('s1', WORKTREE), record('s2', WORKTREE, { provider: 'codex' })], + closeGates: { s2: new Promise(() => {}) } + }) + const error = await killAllProcessesForWorktree( + WORKTREE, + destructiveDeps({ timeoutMs: 40 }) + ).catch((thrown: Error) => thrown.message) + expect(error).toContain('could not confirm these closed: 1 agent session (codex)') + expect(error).not.toContain('claude') + }) + + it('counts the closes that landed before the budget expired', async () => { + // The other half of the same fallback: it reported zero closes, so the removal log said + // `structured=0` for a chat it had just ended. + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const slowClose = new Promise((resolve) => { + setTimeout(resolve, 300) + }) + installHost({ + records: [record('s1', WORKTREE), record('s2', WORKTREE, { provider: 'codex' })], + closeGates: { s2: slowClose } + }) + const result = await killAllProcessesForWorktree( + WORKTREE, + destructiveDeps({ allowUnverifiedStop: true, timeoutMs: 40 }) + ) + expect(result.structuredStopped).toBe(1) + expect(structuredSessionWarning(warn)).toContain( + 'could not confirm these closed: 1 agent session (codex)' + ) + warn.mockRestore() + }) + + it('stops issuing new closes once the budget is spent', async () => { + // One slow provider round trip used to starve every session behind it: the outer race had + // already given up on the loop, and it went on issuing closes whose outcome nobody would read. + // The in-flight one is NOT cancelled — nothing here can cancel a provider round trip — so it + // still has to be reported, which is why both sessions are named below. + let releaseFirstClose: () => void = () => {} + const firstClose = new Promise((resolve) => { + releaseFirstClose = resolve + }) + const host = installHost({ + records: [record('s1', WORKTREE), record('s2', WORKTREE)], + closeGates: { s1: firstClose } + }) + vi.useFakeTimers() + try { + const outcome = killAllProcessesForWorktree( + WORKTREE, + destructiveDeps({ timeoutMs: 5 }) + ).catch((thrown: Error) => thrown.message) + await vi.advanceTimersByTimeAsync(5) + expect(await outcome).toContain('could not confirm these closed: 2 agent sessions (claude)') + releaseFirstClose() + await vi.advanceTimersByTimeAsync(0) + expect(host.closed).toEqual(['s1']) + } finally { + vi.useRealTimers() + } + }) + + it('leaves the terminals already stopped when it refuses over a stuck session', async () => { + // Pins a tradeoff that was accepted, not an outcome that is wanted. The PTY sweeps now run + // concurrently with the structured close, so a removal that refuses over a session that will + // not close has ALREADY killed that workspace's terminals — the head-first serial order spared + // them. Serialising it back is worse: it spends the whole shared budget before a single PTY is + // asked, and the alternative — refusing before the PTY sweeps — leaves force-delete removing + // files while PTY handles are open. The PTY gate itself already kills first and refuses only + // on what it could not verify stopped. A later change must not flip this back silently. + let terminalSweeps = 0 + const runtime = { + stopTerminalsForWorktree: async () => { + terminalSweeps += 1 + return { stopped: 2 } + } + } as never + installHost({ records: [record('s1', WORKTREE)], stuck: new Set(['s1']) }) + await expect( + killAllProcessesForWorktree(WORKTREE, { ...destructiveDeps(), runtime }) + ).rejects.toThrow(/still live: 1 agent session \(claude\)/) + expect(terminalSweeps).toBe(1) + }) + + it('starts the terminal sweeps while the structured close is still in flight', async () => { + // The close is serial and each one waits on a provider round trip. Awaiting it before the + // sweeps exist spends the shared budget head-first, and the sweeps then report a timeout for + // a stop they never attempted. + let releaseClose: () => void = () => {} + const closeGate = new Promise((resolve) => { + releaseClose = resolve + }) + installHost({ records: [record('s1', WORKTREE)], closeGate }) + let terminalSweepStarted = false + const runtime = { + stopTerminalsForWorktree: async () => { + terminalSweepStarted = true + return { stopped: 0 } + } + } as never + const removal = killAllProcessesForWorktree(WORKTREE, { ...destructiveDeps(), runtime }) + await vi.waitFor(() => { + expect(terminalSweepStarted).toBe(true) + }) + releaseClose() + await expect(removal).resolves.toMatchObject({ structuredStopped: 1 }) + }) + it('does not block removal when no structured host is installed', async () => { // Not being able to look is not evidence a child is there, and reading the persisted store // directly would force-install the host as a side effect of a teardown. diff --git a/src/main/runtime/structured-session-worktree-teardown.ts b/src/main/runtime/structured-session-worktree-teardown.ts index 226f785f039..8b161e4f5a8 100644 --- a/src/main/runtime/structured-session-worktree-teardown.ts +++ b/src/main/runtime/structured-session-worktree-teardown.ts @@ -8,15 +8,29 @@ * kept running with its `cwd` gone, the durable record and chat tab survived to republish at the * next launch pointing at a deleted worktree, and `worker-show` still reported the worker live. * - * Membership is `location.workspaceId`, which every structured session carries — so this covers a - * plain chat session in the worktree as well as a dispatched worker. Liveness is - * `observeStructuredWorker`, the same `live` / `unverifiable` / `exited` vocabulary the rest of the - * structured surface uses; only a PROVEN live child is worth refusing a removal over. + * Membership is `location.workspaceId` PLUS the host fence below, and every structured session + * carries both — so this covers a plain chat session in the worktree as well as a dispatched + * worker. Liveness is `observeStructuredWorker`, the same `live` / `unverifiable` / `exited` + * vocabulary the rest of the structured surface uses. + * + * `live` here is lease state — a provider child is attached — not work in flight, so it says + * nothing about whether the user would lose anything. It selects what to CLOSE, never what to + * refuse over: a removal refuses only on a close that did not settle, exactly as the PTY sweep + * refuses only on a stop it could not verify. */ +import { + LOCAL_EXECUTION_HOST_ID, + toRuntimeExecutionHostId, + toSshExecutionHostId, + type ExecutionHostId +} from '../../shared/execution-host' +import { STILL_LIVE_DETAIL_PREFIX } from '../../shared/worktree/removal' import { getStructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-registry' import { observeStructuredWorker } from './structured-worker-authority' import { closeStructuredAgentSessionChild } from './structured-agent-session-close' +import { retireSettledStructuredWorkerTab } from './structured-agent-session-tab-retirement' +import type { WorktreePtyHostFence } from './worktree-pty-host-fence' import type { OrcaRuntimeService } from './orca-runtime' export type LiveStructuredSessionInWorkspace = { @@ -24,13 +38,52 @@ export type LiveStructuredSessionInWorkspace = { agent: 'claude' | 'codex' } +export type UnclosedStructuredSession = LiveStructuredSessionInWorkspace & { + /** Read AFTER the close: `live` is a child watched stay attached, not merely one left unproven. */ + status: 'live' | 'unverifiable' +} + export type StructuredWorktreeSweepRuntime = Pick< OrcaRuntimeService, 'forgetStructuredSessionMail' | 'retireStructuredAgentSessionTabFromSnapshot' > /** - * Structured sessions with a proven-live child in this worktree. + * The two fields every teardown caller already resolves to fence its PTY sweeps to one host. + * + * Deliberately the PTY fence's own type rather than a look-alike: these two helpers are written + * against each other, so a widening on one side must not become a silent disagreement on the + * other. `resolvedConnectionId: null` means this machine on both. + * + * They differ in exactly one reading, and only that one: ABSENT. The PTY fence takes it as no + * fence at all and matches every host, which a single-host-id comparison cannot express — and + * closing every host's chats is destructive, not merely noisy. So this side reads absent as local + * too, the narrower half of that pair. Pinned by test, not left to the next reader to rediscover. + */ +export type StructuredSessionHostFence = WorktreePtyHostFence + +/** + * The one execution host this teardown may touch. + * + * A workspace id is `repoId::path` with no host component, so the local machine, an SSH host and a + * paired runtime can all publish the SAME id and each names a DIFFERENT workspace (STA-4343). The + * PTY sweeps fence on exactly these two fields; a structured session records its host directly, so + * the comparison is on `location.executionHostId` instead of on a pty-id shape. + */ +export function structuredSessionTeardownHostId( + fence: StructuredSessionHostFence +): ExecutionHostId { + if (fence.resolvedRuntimeEnvironmentId !== undefined) { + return toRuntimeExecutionHostId(fence.resolvedRuntimeEnvironmentId) + } + // Both no-connection readings collapse here on purpose — see the fence type. A caller that + // resolved no host, and one that resolved this machine, each close nothing on anyone else's. + const connectionId = fence.resolvedConnectionId ?? null + return connectionId === null ? LOCAL_EXECUTION_HOST_ID : toSshExecutionHostId(connectionId) +} + +/** + * Structured sessions with a proven-live child in this worktree, on the fenced host only. * * An uninstalled host answers empty rather than throwing: no host in this generation means no * provider child was started by this process, and the three PTY sweeps fall through the same way @@ -38,7 +91,8 @@ export type StructuredWorktreeSweepRuntime = Pick< * directly — that would force-install the host, which is itself a side effect on a teardown path. */ export function listLiveStructuredSessionsForWorktree( - worktreeId: string + worktreeId: string, + fence: StructuredSessionHostFence ): LiveStructuredSessionInWorkspace[] { const host = getStructuredAgentSessionHost() if (!host) { @@ -50,58 +104,191 @@ export function listLiveStructuredSessionsForWorktree( } catch { return [] } + const hostId = structuredSessionTeardownHostId(fence) return records .filter( (record) => record.location.workspaceId === worktreeId && + record.location.executionHostId === hostId && observeStructuredWorker({ sessionId: record.sessionId }).status === 'live' ) .map((record) => ({ sessionId: record.sessionId, agent: record.provider })) } /** - * Counts and providers, never session ids. + * A count and its providers — never session ids. * * A session id is one tab-id hop from the random pane key that gates a worker's mailbox, and this * string reaches agent-readable CLI output and a desktop toast. The count and the providers are * what a user deciding whether to force actually needs; the ids identify nothing they can act on. */ -export function describeLiveStructuredSessions( - sessions: readonly LiveStructuredSessionInWorkspace[] -): string { +function countStructuredSessions(sessions: readonly UnclosedStructuredSession[]): string { const noun = sessions.length === 1 ? 'agent session' : 'agent sessions' const providers = [...new Set(sessions.map((session) => session.agent))].sort().join(', ') - return `${sessions.length} running ${noun} (${providers})` + return `${sessions.length} ${noun} (${providers})` } /** - * Closes every live structured session in the worktree, and reports what stayed. + * The two post-close verdicts, each with its own count. * - * Force is the documented escape hatch, so it closes rather than orphaning: a child left running - * against a deleted `cwd` is the exact outcome this whole sweep exists to prevent. + * The split is here for the reason `describeUnstoppedPtys` carries one: "we watched it stay + * attached" and "we could not confirm it went" are different decisions to waive, and the delete + * toast branches on the marker a proven-live session leads with. + * + * Both groups are named, though, which is where this differs from the PTY sibling: there, the + * verdict is a fresh inventory, so anything absent from the live list is PROVEN exited and + * rightly dropped. Here an `unverifiable` session is unclosed too — folding it into the live + * count would overstate what Orca watched, and dropping it said "1 agent session" while three + * were about to be discarded. + */ +export function describeUnclosedStructuredSessions( + sessions: readonly UnclosedStructuredSession[] +): string { + const stillLive = sessions.filter((session) => session.status === 'live') + const unconfirmed = sessions.filter((session) => session.status !== 'live') + if (stillLive.length === 0) { + return `could not confirm these closed: ${countStructuredSessions(unconfirmed)}` + } + const live = `${STILL_LIVE_DETAIL_PREFIX} ${countStructuredSessions(stillLive)}` + return unconfirmed.length === 0 + ? live + : `${live}; could not confirm these closed: ${countStructuredSessions(unconfirmed)}` +} + +/** + * What the close loop has done so far, readable while it is still running. + * + * The loop is serial and every close waits on a provider round trip, so the shared sweep budget can + * expire part-way through it. This is written as it goes rather than returned at the end, because + * the caller's timeout path reads THIS: a fabricated whole-list fallback reported sessions the + * sweep had already closed as unclosed, named them in the refusal the user reads, and logged + * `structured=0` for closes that landed. Saying only what was observed is the point of the sweep. + */ +export type StructuredSweepProgress = { + /** The sessions this sweep closes, in the order the loop reaches them. */ + readonly sessions: readonly LiveStructuredSessionInWorkspace[] + /** Sessions no longer attached after their close — the count this sweep reports. */ + closed: number + /** Attempted closes that did not settle, each carrying the verdict re-read after the attempt. */ + unstopped: UnclosedStructuredSession[] + /** How many of `sessions`, from the front, have an outcome recorded. */ + settled: number +} + +export function createStructuredSweepProgress( + sessions: readonly LiveStructuredSessionInWorkspace[] +): StructuredSweepProgress { + return { sessions, closed: 0, unstopped: [], settled: 0 } +} + +/** + * Everything this sweep did not prove closed. + * + * A session with no recorded outcome — never started, or still in flight — reports `unverifiable`, + * the same verdict as an attempted close that stayed unproven. Chosen, not conflated: the vocabulary is `live` / `unverifiable` / `exited` with no + * synonyms, and "we never asked" and "we asked and could not confirm" are both exactly "not + * observed exited". A fourth bucket would need its own refusal wording and its own toast + * classification for a distinction the user cannot act on any differently — and `live` is the only + * verdict either could be mistaken for, which is the one thing neither is allowed to claim. + */ +export function unclosedStructuredSessions( + progress: StructuredSweepProgress +): UnclosedStructuredSession[] { + return [ + ...progress.unstopped, + ...progress.sessions + .slice(progress.settled) + .map((session) => ({ ...session, status: 'unverifiable' as const })) + ] +} + +/** + * Closes the structured sessions in `progress`, recording what stayed as it goes. + * + * Runs on the ordinary removal too, not just force: a child left running against a deleted `cwd` is + * the outcome this whole sweep exists to prevent, and closing is how you prevent it. What stayed is + * the only thing worth refusing over. + * + * Takes the list rather than re-deriving it, so the refusal can only ever name a session out of + * the set this sweep was handed — re-enumerating would run every liveness observation twice and + * let it name one this call never touched. Not every one of them is a session a close was + * attempted on: the deadline check below can leave the tail of the list unasked, and + * `unclosedStructuredSessions` reports those as `unverifiable` precisely because nobody looked. */ export async function closeStructuredSessionsForWorktree( - worktreeId: string, - runtime?: StructuredWorktreeSweepRuntime -): Promise<{ closed: number; unstopped: LiveStructuredSessionInWorkspace[] }> { + progress: StructuredSweepProgress, + deadline: number, + options: { + runtime?: StructuredWorktreeSweepRuntime + /** + * Whether this removal can still refuse over an unclosed session. + * + * It is the only case where the workspace — and therefore its chat tabs — survives, so it is + * the only case where an unproven close may put a tab back. Force and the folder-workspace + * paths discard the workspace whatever the sweep reports. + */ + mayRefuse?: boolean + } = {} +): Promise { + const { runtime, mayRefuse } = options // No `afterClose` for a dispatched worker: `host.close` drops the holds, so nothing keeps a // provider child un-evictable, but the dispatch's redrive subscription and registry entry do // survive until it settles by another verb. That is a bounded leak, not a hazard — and passing // one here would mean resolving a dispatch id per session on a teardown path that must stay // inside the sweep deadline. - const sessions = listLiveStructuredSessionsForWorktree(worktreeId) - const unstopped: LiveStructuredSessionInWorkspace[] = [] - let closed = 0 - for (const session of sessions) { - const outcome = await closeStructuredAgentSessionChild( - session.sessionId, - runtime ? { runtime } : {} - ) - if (outcome.stopped) { - closed += 1 - } else { - unstopped.push(session) + for (const session of progress.sessions) { + // Stops ISSUING new closes once the budget is spent; an in-flight one is left to finish, since + // nothing here can cancel a provider round trip. Without this, one slow round trip starved + // every session behind it: the caller's race had already given up, and the loop went on + // closing sessions whose outcome nobody would read. + if (Date.now() >= deadline) { + return } + const outcome = await closeStructuredAgentSessionChild(session.sessionId, { + ...(runtime ? { runtime } : {}), + restoreTabOnUnprovenClose: mayRefuse === true + }) + if (outcome.stopped) { + progress.closed += 1 + } else { + // Re-observed rather than reusing the close's own reason string: what the user is asked to + // waive is the state AFTER the attempt, and a close that threw never reached an observation. + const status = observeStructuredWorker({ sessionId: session.sessionId }).status + if (status === 'exited') { + // The re-read can PROVE the exit a failed close could not — it threw past its own + // observation, or the record's death evidence landed after it read. Refusing on a child + // that is demonstrably gone is the defect this sweep exists to remove, so take the proof + // and run the retirement `closeStructuredAgentSessionChild` skipped when it gave up. + // + // Including the hide it UNDID: its rollback ran against an observation taken one store + // write before this one, so a child that died in between left the tab republished for a + // session this sweep is about to count closed. Taking the proof has to take that back. + await dropDurableChatTabReference(session.sessionId) + retireSettledStructuredWorkerTab(session.sessionId, runtime) + progress.closed += 1 + } else { + progress.unstopped.push({ ...session, status }) + } + } + // Advanced only once an outcome is recorded, so a close still in flight when the deadline + // lands stays reported as unclosed instead of falling out of both counts. + progress.settled += 1 + } +} + +/** + * Drops a settled session's durable chat-tab reference, and cannot fail the settlement. + * + * The close's own hide is the ordinary path; this is only for the session whose exit this sweep + * proved after that close had already rolled the hide back. + */ +async function dropDurableChatTabReference(sessionId: string): Promise { + try { + await getStructuredAgentSessionHost()?.setSessionTabVisibility?.(sessionId, false) + } catch (error) { + console.warn( + `[worktree-teardown] could not drop the chat tab reference for ${sessionId}`, + error + ) } - return { closed, unstopped } } diff --git a/src/main/runtime/terminal-interactive-wait-visibility.test.ts b/src/main/runtime/terminal-interactive-wait-visibility.test.ts index 987bdbb15b7..3a6470b41f9 100644 --- a/src/main/runtime/terminal-interactive-wait-visibility.test.ts +++ b/src/main/runtime/terminal-interactive-wait-visibility.test.ts @@ -1,9 +1,14 @@ // A worker parked on an interactive prompt must be distinguishable from one that is thinking // or inside a long tool call (STA-4513, STA-3714). import { readFileSync } from 'node:fs' +import { makeAgentStatusStoreWiring } from './agent-status-store-wiring.test-fixture' import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' -import { OrcaRuntimeService } from './orca-runtime' +import { + createTranscriptPane, + type TranscriptPaneOptions, + TRANSCRIPT_PANE_PTY_ID as PTY_ID +} from './agent-transcript-pane-test-harness' import { assertTerminalAgentSendable } from './rpc/terminal-agent-send-guard' vi.mock('electron', () => ({ @@ -13,12 +18,11 @@ vi.mock('electron', () => ({ app: { getPath: vi.fn(() => '/tmp') } })) -const LEAF_ID = '11111111-1111-4111-8111-111111111111' -const TAB_ID = 'tab-1' -const WORKTREE_ID = 'wt-1' -const PTY_ID = 'pty-1' - -// Captured verbatim from cursor-agent 2026.08.11-e8db854 driven through Orca. +// cursor-agent 2026.08.11-e8db854's screens, but NOT raw PTY output: these files contain no +// escape bytes and no carriage returns, so they came through a terminal's renderer and a +// clipboard. They evidence wording, ordering and glyphs — which is all the rules below key on — +// and evidence nothing about the caret, cursor moves, repaints or the alternate screen buffer. +// Record new fixtures with config/scripts/capture-agent-pty-transcript.mjs, which keeps the bytes. function fixture(name: string): string { return readFileSync(join(__dirname, '__fixtures__', `${name}.txt`), 'utf8') } @@ -39,71 +43,13 @@ function agentStatusOsc(state: string): string { return `]9999;${JSON.stringify({ state, prompt: 'ship it', agentType: 'claude' })}` } -async function createPane(options: { - paneTitle: string - foregroundProcess: string | null - data: string - /** Set for a pane whose PTY lives on an SSH host or WSL distro rather than locally. */ - connectionId?: string - /** Simulates a PTY controller whose foreground probe never settles. */ - foregroundProbeHangs?: boolean - onForegroundProbe?: () => void -}): Promise<{ runtime: OrcaRuntimeService; handle: string }> { - const runtime = new OrcaRuntimeService(null) - const internals = runtime as unknown as { - resolveTerminalWorkspaceLaunchScope: (selector: string) => Promise - } - vi.spyOn(internals, 'resolveTerminalWorkspaceLaunchScope').mockResolvedValue({ - id: WORKTREE_ID, - path: '/repo/app', - connectionId: options.connectionId ?? null, - repo: null, - folderWorkspace: null - }) - runtime.setPtyController({ - spawn: vi.fn().mockResolvedValue({ id: PTY_ID, incarnationId: 'inc-1' }), - write: () => true, - kill: () => true, - getForegroundProcess: (): Promise => { - options.onForegroundProbe?.() - return options.foregroundProbeHangs === true - ? new Promise(() => {}) - : Promise.resolve(options.foregroundProcess) - } - }) - const terminal = await runtime.createTerminal(`id:${WORKTREE_ID}`, { - tabId: TAB_ID, - leafId: LEAF_ID, - title: 'Terminal' - }) - runtime.attachWindow(1) - runtime.syncWindowGraph(1, { - tabs: [ - { - tabId: TAB_ID, - worktreeId: WORKTREE_ID, - title: 'Terminal', - activeLeafId: LEAF_ID, - layout: null - } - ], - leaves: [ - { - tabId: TAB_ID, - worktreeId: WORKTREE_ID, - leafId: LEAF_ID, - paneRuntimeId: 1, - ptyId: PTY_ID, - paneTitle: options.paneTitle - } - ] - }) - // Why the guard: a restore seed is only applied to a never-written record, so the restore - // cases must not write an empty chunk first. - if (options.data.length > 0) { - runtime.onPtyData(PTY_ID, options.data, Date.now()) - } - return { runtime, handle: terminal.handle } +async function createPane( + options: TranscriptPaneOptions +): Promise>> { + // Compose the same central hook-store wiring as desktop and orcad so OSC rows exercise the + // production status path rather than silently disappearing in a bare runtime fixture. + const statusWiring = makeAgentStatusStoreWiring() + return createTranscriptPane(options, statusWiring.deps) } // cursor-agent renders a braille spinner in its OSC title while it works, and Orca reads @@ -299,7 +245,7 @@ describe('terminal interactive-wait visibility (STA-4513, STA-3714)', () => { }) await expect(runtime.showTerminal(handle)).resolves.toMatchObject({ - agentWait: { source: 'prompt-text', reason: 'codex-trust-workspace' } + agentWait: { source: 'prompt-text', reason: 'agent-trust-workspace' } }) }) diff --git a/src/main/runtime/terminal-tail-sentinel-index.test.ts b/src/main/runtime/terminal-tail-sentinel-index.test.ts index 2b33b2770ea..cd8bf2e68fb 100644 --- a/src/main/runtime/terminal-tail-sentinel-index.test.ts +++ b/src/main/runtime/terminal-tail-sentinel-index.test.ts @@ -193,7 +193,7 @@ describe('terminal tail sentinel index', () => { expect(tailMayContainBlockedSignal(seeded)).toBe(true) const state = computeTerminalTailWaitState(seeded, '', '') expect(state.fromTail).toBe(true) - expect(state.signal?.reason).toBe('codex-update-prompt') + expect(state.signal?.reason).toBe('agent-update-prompt') const clean = ['boot log', 'no prompt here', 'trailing'] expect(tailMayContainBlockedSignal(clean)).toBe(false) diff --git a/src/main/runtime/terminal-wait-detection.test.ts b/src/main/runtime/terminal-wait-detection.test.ts index eda02e60bbb..e52344c5dc0 100644 --- a/src/main/runtime/terminal-wait-detection.test.ts +++ b/src/main/runtime/terminal-wait-detection.test.ts @@ -98,12 +98,12 @@ const LIVE_CODEX_PROMPTS: { name: string; lines: string[]; reason: string }[] = '2. Trust all and continue', 'Press enter to confirm or esc to go back' ], - reason: 'codex-hooks-review-prompt' + reason: 'agent-hooks-review-prompt' }, { name: 'trust workspace', lines: ['Do you trust this workspace directory?', '1. Yes', '2. No'], - reason: 'codex-trust-workspace' + reason: 'agent-trust-workspace' }, { name: 'update', @@ -113,7 +113,7 @@ const LIVE_CODEX_PROMPTS: { name: string; lines: string[]; reason: string }[] = '2. Skip', 'Press enter to continue' ], - reason: 'codex-update-prompt' + reason: 'agent-update-prompt' }, { name: 'cwd selection', @@ -123,7 +123,7 @@ const LIVE_CODEX_PROMPTS: { name: string; lines: string[]; reason: string }[] = ' Current = your current working directory', ' Press enter to continue' ], - reason: 'codex-cwd-prompt' + reason: 'agent-cwd-prompt' }, { name: 'model migration', @@ -142,7 +142,7 @@ const LIVE_CODEX_PROMPTS: { name: string; lines: string[]; reason: string }[] = '2. No, continue without permissions', 'Press enter to confirm or esc to cancel' ], - reason: 'codex-interactive-prompt' + reason: 'agent-interactive-prompt' }, { name: 'permission required', @@ -153,7 +153,7 @@ const LIVE_CODEX_PROMPTS: { name: string; lines: string[]; reason: string }[] = 'Allow always', 'Reject' ], - reason: 'codex-interactive-prompt' + reason: 'agent-interactive-prompt' } ] @@ -195,6 +195,301 @@ describe('detectTerminalWaitBlockedReason live prompts', () => { 'Press enter to confirm' ]) - expect(detectTerminalWaitBlockedReason(waitText)).toBe('codex-hooks-review-prompt') + expect(detectTerminalWaitBlockedReason(waitText)).toBe('agent-hooks-review-prompt') }) }) + +// Why: these matchers never inspect the pane's agent, so a Codex-named reason on a non-Codex screen +// reaches the user verbatim through the CLI and the worker receipt's "Agent startup blocked:" line. +describe('detectTerminalWaitBlockedReason on non-Codex agents', () => { + const NON_CODEX_PROMPTS: { name: string; lines: string[]; reason: string }[] = [ + { + name: 'an Antigravity workspace trust dialog', + lines: [ + 'Antigravity CLI 1.0.3', + 'Do you trust the files in this folder?', + '1. Yes, I trust this folder', + '2. No, exit' + ], + reason: 'agent-trust-workspace' + }, + { + name: 'a Claude Code trusted-workspace dialog', + lines: [ + 'Claude Code', + 'Trusted workspace?', + 'This directory has not been opened before.', + '1. Yes, proceed', + '2. No, exit' + ], + reason: 'agent-trust-workspace' + }, + { + name: 'a Gemini CLI update banner', + lines: [ + 'Gemini CLI', + 'Update available! 1.4.0 -> 1.5.0', + '1. Update now', + '2. Skip', + 'Press enter to continue' + ], + reason: 'agent-update-prompt' + }, + { + name: 'a Gemini CLI permission dialog', + lines: [ + 'Gemini CLI', + 'Permission required', + 'Running this tool requires permission', + 'Allow once', + 'Allow always', + 'Reject' + ], + reason: 'agent-interactive-prompt' + }, + { + name: 'a Claude Code hooks review dialog', + lines: [ + 'Claude Code', + 'Hooks need review', + 'PreToolUse:Bash .claude/hooks/guard.sh', + 'Press enter to confirm' + ], + reason: 'agent-hooks-review-prompt' + }, + { + name: 'an Antigravity sandbox confirmation', + lines: [ + 'Antigravity CLI 1.0.3', + 'This action runs outside the sandbox.', + 'Press enter to confirm or esc to go back' + ], + reason: 'agent-interactive-prompt' + } + ] + + // Why: the reason was previously picked by looking for 'codex' in 600 chars of scrollback, so any + // agent that merely narrated about Codex handed its user a Codex label. + it('does not borrow a Codex label from scrollback that only mentions Codex', () => { + const waitText = waitTextFor([ + 'Antigravity CLI 1.0.3', + 'I read src/codex-notes.md for you.', + 'This action runs outside the sandbox.', + 'Press enter to confirm or esc to go back' + ]) + + expect(waitText.toLowerCase()).toContain('codex') + expect(detectTerminalWaitBlockedReason(waitText)).toBe('agent-interactive-prompt') + }) + + for (const prompt of NON_CODEX_PROMPTS) { + it(`reports an agent-neutral reason for ${prompt.name}`, () => { + const waitText = waitTextFor(prompt.lines) + const reason = detectTerminalWaitBlockedReason(waitText) + + expect(waitText.toLowerCase()).not.toContain('codex') + expect(reason).toBe(prompt.reason) + expect(reason?.startsWith('codex-')).toBe(false) + }) + } +}) + +// Antigravity readiness, and what this file does NOT claim about it. +// +// The detector recognizes a ready screen by header + a 'gemini'-prefixed model line + a lone '>' +// caret. That is narrow: an Antigravity user on a non-Gemini model never reaches ready and the pane +// wedges. Widening it was attempted and reverted -- every candidate rule was tuned against the +// constructed fixtures below, and the last one let a live sign-in dialog read as ready (the +// orchestrator then types the task prompt into an authentication dialog, which is strictly worse +// than a timeout). No real Antigravity transcript exists in this repo; the cursor-agent rules are +// derived from captures under src/main/runtime/__fixtures__ and Antigravity has no equivalent. +// Widening the model rule needs one first. See the ratchet at the bottom of this block for the +// shapes any replacement has to refuse. +describe('Antigravity readiness does not absorb its own startup dialog', () => { + const TRUST_DIALOG_WITH_CARET = [ + 'Antigravity CLI 1.0.3', + 'Do you trust the files in this folder?', + '1. Yes, I trust this folder', + '2. No, exit', + '>' + ] + + const LIVE_DIALOGS_UNDER_THE_HEADER: { name: string; lines: string[]; reason: string | null }[] = + [ + { + name: 'a bare trust dialog', + lines: TRUST_DIALOG_WITH_CARET, + reason: 'agent-trust-workspace' + }, + { + name: 'a trust dialog with an ordinary sentence in it', + lines: [ + 'Antigravity CLI 1.0.3', + 'This workspace has not been opened before.', + 'Do you trust the files in this folder?', + '1. Yes, I trust this folder', + '2. No, exit', + '>' + ], + reason: 'agent-trust-workspace' + }, + { + name: 'a trust dialog printing the folder on its own line', + lines: [ + 'Antigravity CLI 1.0.3', + 'Do you trust the files in this folder?', + '~/orca/workspaces/orca/agy-dispatch-issue', + '1. Yes', + '2. No', + '>' + ], + reason: 'agent-trust-workspace' + } + ] + + for (const dialog of LIVE_DIALOGS_UNDER_THE_HEADER) { + it(`reports ${dialog.name} drawn under the header and stays unready`, () => { + const waitText = waitTextFor(dialog.lines) + + expect(detectTerminalWaitBlockedReason(waitText)).toBe(dialog.reason) + expect(isKnownReadyPromptPreview(waitText)).toBe(false) + }) + } + + // Discriminating: the Gemini model line and caret satisfy readiness, so only the dialog sitting + // *below* them keeps this unready. Drop the ordering rule and this goes green-to-red. + it('keeps reporting a dialog that opens after a Gemini ready screen', () => { + const waitText = waitTextFor([ + 'Antigravity CLI 1.0.3', + 'user@example.com (Antigravity Business)', + 'Gemini 3.5 Flash (High)', + '~/orca/workspaces/orca/agy-dispatch-issue', + '>', + 'Permission required', + 'Allow once', + 'Reject' + ]) + + expect(isKnownReadyPromptPreview(waitText)).toBe(false) + expect(detectTerminalWaitBlockedReason(waitText)).toBe('agent-interactive-prompt') + }) + + // Discriminating: a stale dialog above a reprinted Gemini ready screen must stop being reported, + // which is the whole point of the dismissed-modal rule. + it('clears once a Gemini ready screen replaces the dialog', () => { + const waitText = waitTextFor([ + ...TRUST_DIALOG_WITH_CARET, + 'Antigravity CLI 1.0.3', + 'user@example.com (Antigravity Business)', + 'Gemini 3.5 Flash (High)', + '>' + ]) + + expect(isKnownReadyPromptPreview(waitText)).toBe(true) + expect(detectTerminalWaitBlockedReason(waitText)).toBeNull() + }) + + // Characterization, not a guard: records the wedge this file has not fixed. An Antigravity user on + // a non-Gemini model has no 'gemini' line, so readiness never resolves and the wait times out. + // Flipping this to true is the goal of the follow-up, and needs a captured transcript first. + it('does not yet recognize a non-Gemini ready screen (known wedge)', () => { + const waitText = waitTextFor([ + 'Antigravity CLI 1.0.3', + 'user@example.com (Antigravity Business)', + 'Claude Sonnet 4.5 (High)', + '~/orca/workspaces/orca/agy-dispatch-issue', + '>' + ]) + + expect(isKnownReadyPromptPreview(waitText)).toBe(false) + }) + + // Ratchet, not a guard of today's code: these pass now only because none of them prints a 'gemini' + // model line. They exist so the next attempt to widen the model rule has to refuse them -- the + // reverted attempt accepted all five as ready on the strength of the account row alone (and an + // 'x@y.z' anywhere in the dialog body did just as well), and readiness is what gates typing the + // task prompt into the pane. A replacement must rest on positive evidence that the agent's input + // prompt is accepting input, not on absence-of-dialog plus an account row. + const SILENT_STARTUP_DIALOGS: { name: string; lines: string[] }[] = [ + { + name: 'an update banner', + lines: [ + 'Antigravity CLI 1.0.3', + 'user@example.com (Antigravity Business)', + 'A new version is available', + '~/orca/workspaces/orca/agy-dispatch-issue', + 'Press enter to continue', + '>' + ] + }, + { + name: 'a sign-in dialog', + lines: [ + 'Antigravity CLI 1.0.3', + 'user@example.com (Antigravity Business)', + 'Sign in to continue', + '~/orca/workspaces/orca/agy-dispatch-issue', + '1. Open browser', + '2. Paste an API key', + '>' + ] + }, + { + name: 'a model picker', + lines: [ + 'Antigravity CLI 1.0.3', + 'user@example.com (Antigravity Business)', + 'Select a model', + '~/orca/workspaces/orca/agy-dispatch-issue', + '1. Claude Sonnet 4.5', + '2. GPT-5.1', + '>' + ] + }, + { + name: 'a privacy notice', + lines: [ + 'Antigravity CLI 1.0.3', + 'user@example.com (Antigravity Business)', + 'We collect usage data to improve the product', + '~/orca/workspaces/orca/agy-dispatch-issue', + '1. Accept', + '2. Decline', + '>' + ] + }, + { + name: 'an onboarding theme picker', + lines: [ + 'Antigravity CLI 1.0.3', + 'user@example.com (Antigravity Business)', + 'Welcome! Choose a theme', + '~/orca/workspaces/orca/agy-dispatch-issue', + '1. Dark', + '2. Light', + '>' + ] + } + ] + + for (const dialog of SILENT_STARTUP_DIALOGS) { + it(`refuses ${dialog.name} whose wording names no blocked reason, account row and all`, () => { + const waitText = waitTextFor(dialog.lines) + + // No blocked-signal rule matches, so the ordering defense cannot reach these: readiness has to + // refuse them on its own or the orchestrator types into a live dialog. + expect(detectTerminalWaitBlockedReason(waitText)).toBeNull() + expect(isKnownReadyPromptPreview(waitText)).toBe(false) + }) + + it(`refuses ${dialog.name} that merely narrates an email address`, () => { + const waitText = waitTextFor([ + ...dialog.lines.slice(0, -1), + 'contact support@antigravity.dev for help', + '>' + ]) + + expect(isKnownReadyPromptPreview(waitText)).toBe(false) + }) + } +}) diff --git a/src/main/runtime/terminal-wait-detection.ts b/src/main/runtime/terminal-wait-detection.ts index ed957d1fe2d..cae25e8bfa6 100644 --- a/src/main/runtime/terminal-wait-detection.ts +++ b/src/main/runtime/terminal-wait-detection.ts @@ -231,11 +231,11 @@ function findBlockedSignalInLiveWindow( const candidates: { reason: RuntimeTerminalWaitBlockedReason; index: number }[] = [] const updateIndex = normalized.lastIndexOf('update available') if (updateIndex !== -1 && normalized.includes('press enter to continue', updateIndex)) { - candidates.push({ reason: 'codex-update-prompt', index: updateIndex }) + candidates.push({ reason: 'agent-update-prompt', index: updateIndex }) } const cwdIndex = normalized.lastIndexOf('choose working directory to') if (cwdIndex !== -1 && normalized.includes('press enter to continue', cwdIndex)) { - candidates.push({ reason: 'codex-cwd-prompt', index: cwdIndex }) + candidates.push({ reason: 'agent-cwd-prompt', index: cwdIndex }) } const modelMigrationIndex = normalized.lastIndexOf('codex just got an upgrade') if ( @@ -246,7 +246,8 @@ function findBlockedSignalInLiveWindow( } const hooksIndex = normalized.lastIndexOf('hooks need review') if (hooksIndex !== -1 && normalized.includes('press enter to confirm', hooksIndex)) { - candidates.push({ reason: 'codex-hooks-review-prompt', index: hooksIndex }) + // Why neutral: this matcher never inspects the agent -- 'hooks need review' is not Codex-only wording. + candidates.push({ reason: 'agent-hooks-review-prompt', index: hooksIndex }) } const trustIndex = Math.max( normalized.lastIndexOf('do you trust'), @@ -261,7 +262,8 @@ function findBlockedSignalInLiveWindow( trustSegment.includes('directory') || trustSegment.includes('repo')) ) { - candidates.push({ reason: 'codex-trust-workspace', index: trustIndex }) + // Why neutral: this matcher never inspects the agent -- every TUI agent ships a workspace-trust dialog. + candidates.push({ reason: 'agent-trust-workspace', index: trustIndex }) } const interactivePromptIndex = Math.max( normalized.lastIndexOf('press enter to confirm'), @@ -274,19 +276,22 @@ function findBlockedSignalInLiveWindow( interactivePromptIndex === -1 ? '' : normalized.slice(Math.max(0, interactivePromptIndex - 600), interactivePromptIndex + 200) - const hasCodexInteractiveContext = + // Why 'codex' only widens detection and never names the reason: the sole Codex evidence here is + // that word somewhere in 600 chars of scrollback, which an agent narrating about Codex satisfies + // on any pane -- enough to suspect a dialog, not enough to label a non-Codex user's pane. + const hasInteractiveDialogContext = interactivePromptContext.includes('codex') || interactivePromptContext.includes('permission') || interactivePromptContext.includes('sandbox') || interactivePromptContext.includes('trust') || interactivePromptContext.includes('hook') - if (interactivePromptIndex !== -1 && hasCodexInteractiveContext) { + if (interactivePromptIndex !== -1 && hasInteractiveDialogContext) { const contextStart = Math.max(0, interactivePromptIndex - 600) const hasSpecificPromptInContext = candidates.some( (candidate) => candidate.index >= contextStart && candidate.index <= interactivePromptIndex ) if (!hasSpecificPromptInContext) { - candidates.push({ reason: 'codex-interactive-prompt', index: interactivePromptIndex }) + candidates.push({ reason: 'agent-interactive-prompt', index: interactivePromptIndex }) } } const cursorApprovalIndex = findCursorApprovalPromptIndex(normalized) @@ -303,8 +308,13 @@ function findBlockedSignalInLiveWindow( permissionSegment.includes(choice) ).length if (decisionCount >= 2) { - // Why: preserve the existing remote receipt value for mixed-version clients. - candidates.push({ reason: 'codex-interactive-prompt', index: permissionPromptIndex }) + // Why neutral: an approval dialog with named choices identifies no agent; older hosts publish + // 'codex-interactive-prompt' here and clients alias the two. Rule 1 additive member -- + // remote-wire-compatibility.md names RuntimeTerminalWaitBlockedReason as Rule 1 because no + // consumer switches exhaustively on it. + // Why alias rather than drop the old spelling: preserve the existing remote receipt value for + // mixed-version clients -- an older host still publishes codex-* on this path. + candidates.push({ reason: 'agent-interactive-prompt', index: permissionPromptIndex }) } } return candidates.length > 0 diff --git a/src/main/runtime/unstopped-pty-verification.ts b/src/main/runtime/unstopped-pty-verification.ts index a2cd83b8eec..7cfd5907797 100644 --- a/src/main/runtime/unstopped-pty-verification.ts +++ b/src/main/runtime/unstopped-pty-verification.ts @@ -2,7 +2,7 @@ import type { IPtyProvider } from '../providers/types' import type { OrcaRuntimeService } from './orca-runtime' import { UNSTOPPED_PTY_DETAIL_SEPARATOR, - UNSTOPPED_PTY_LIVE_DETAIL_PREFIX, + STILL_LIVE_DETAIL_PREFIX, UNSTOPPED_PTY_REMOVAL_PREFIX } from '../../shared/worktree/removal' import { @@ -105,7 +105,7 @@ export function describeUnstoppedPtys( ): string { const detail = verdict.status === 'live' - ? `${UNSTOPPED_PTY_LIVE_DETAIL_PREFIX} ${verdict.ptyIds.join(', ')}` + ? `${STILL_LIVE_DETAIL_PREFIX} ${verdict.ptyIds.join(', ')}` : `could not verify these exited: ${failedPtyIds.join(', ')} (${verdict.reason})` return `${UNSTOPPED_PTY_REMOVAL_PREFIX} ${worktreeId}${UNSTOPPED_PTY_DETAIL_SEPARATOR}${detail}` } diff --git a/src/main/runtime/worktree-pty-host-fence.ts b/src/main/runtime/worktree-pty-host-fence.ts index 855371c4aef..a2a6099bf11 100644 --- a/src/main/runtime/worktree-pty-host-fence.ts +++ b/src/main/runtime/worktree-pty-host-fence.ts @@ -1,8 +1,14 @@ export type WorktreePtyHostFence = { + /** `null` is this machine; ABSENT is no fence at all, so every host matches. */ resolvedConnectionId?: string | null resolvedRuntimeEnvironmentId?: string } +/** + * Also fences the structured sweep, through `structuredSessionTeardownHostId`, which reuses this + * exact type so the two cannot drift. That helper narrows ABSENT to local — the one deliberate + * difference, documented where it is made. + */ export function worktreePtyBelongsToHost( ptyId: string, connectionId: string | null | undefined, diff --git a/src/main/runtime/worktree-teardown.ts b/src/main/runtime/worktree-teardown.ts index 82fa055cc3a..84275b40eed 100644 --- a/src/main/runtime/worktree-teardown.ts +++ b/src/main/runtime/worktree-teardown.ts @@ -15,10 +15,16 @@ import { } from './worktree-pty-surface-sweeps' import { closeStructuredSessionsForWorktree, - describeLiveStructuredSessions, - listLiveStructuredSessionsForWorktree + createStructuredSweepProgress, + describeUnclosedStructuredSessions, + listLiveStructuredSessionsForWorktree, + unclosedStructuredSessions } from './structured-session-worktree-teardown' -import { createWorktreeSweepTracker, settleSweepsForForcedRemoval } from './forced-sweep-settlement' +import { + createWorktreeSweepTracker, + settleSweepsForForcedRemoval, + type WorktreeSweepTracker +} from './forced-sweep-settlement' import { describeError, describeFailedPtySweep, @@ -57,7 +63,7 @@ export type WorktreeTeardownResult = { runtimeStopped: number providerStopped: number registryStopped: number - /** Structured agent sessions closed by the force path; absent when none were found. */ + /** Structured agent sessions this teardown closed; absent when it closed none. */ structuredStopped?: number } @@ -99,12 +105,18 @@ export async function killAllProcessesForWorktree( const deadlineError = new Error( `${WORKTREE_TEARDOWN_TIMEOUT_PREFIX} ${worktreeId}. ${WORKTREE_TEARDOWN_FORCE_HINT}` ) - // FIRST, and before a single PTY sweep starts: a structured agent session is registered on none - // of the three surfaces below, so all three answered zero and removal deleted the checkout out - // from under a running provider child. Refusing costs nothing when there are none, and the check - // is synchronous, so a destructive removal fails fast instead of after the whole sweep budget. - const structuredStopped = await sweepStructuredSessions(worktreeId, deps, deadline, deadlineError) const sweeps = createWorktreeSweepTracker() + // ISSUED first, before a single PTY is touched: a structured agent session is registered on none + // of the three surfaces below, so all three answered zero and removal deleted the checkout out + // from under a running provider child. Asking the agent plane ahead of the terminal plane also + // keeps an intentional stop from reading as a failed process exit. + // + // Not AWAITED first, though. Its close is serial and each one waits on a provider round trip, so + // awaiting here would spend the shared budget before a single PTY was asked — and the sweeps + // would then report a timeout for a stop they never attempted. It is joined below, ahead of the + // PTY verdict, so a structured refusal still outranks one. + const structuredSweep = sweepStructuredSessions(worktreeId, deps, deadline, sweeps) + void structuredSweep.catch(() => undefined) const stopAttempts = new Map>() const stopPty = ( ptyId: string, @@ -196,6 +208,7 @@ export async function killAllProcessesForWorktree( for (const sweep of [runtimeSweep, providerSweep, registrySweep]) { void sweep.catch(() => undefined) } + const structuredStopped = await structuredSweep let runtimeResult: { stopped: number } let providerStopped: number let registryStopped: number @@ -207,7 +220,10 @@ export async function killAllProcessesForWorktree( deadlineError ) if (forced.incomplete) { - return forced.stopped + // Carries the structured count out too: this early return skips the PTY verdict, not the + // sweep that already closed a user's chats, and dropping it makes the log say `structured=0` + // for a removal that closed some. + return { ...forced.stopped, ...(structuredStopped > 0 ? { structuredStopped } : {}) } } runtimeResult = { stopped: forced.stopped.runtimeStopped } providerStopped = forced.stopped.providerStopped @@ -277,59 +293,84 @@ export async function killAllProcessesForWorktree( } /** - * The fourth sweep: structured agent sessions bound to this worktree. + * The fourth sweep: structured agent sessions bound to this worktree, on this host. * - * Refuses rather than auto-closing on the ordinary destructive path. `worktree rm` is the verb - * that deletes a user's work, and a running agent session is exactly the thing they would want to - * be told about before it goes — the same bargain the unstopped-PTY gate already strikes, using - * the same `--force` escape hatch. Force closes them properly instead of orphaning a child against - * a `cwd` that is about to disappear. + * Stops first and refuses only on unproven stops, which is the bargain the unstopped-PTY gate + * actually strikes: that gate kills every PTY — a terminal running an agent included — and refuses + * only for the ones whose exit it could not then verify. Refusing merely because a session is + * attached made an idle chat, which the user is done with, harder to delete than a terminal running + * the same agent. Attachment is lease state, not work in flight, so it was never the right proxy. * - * Two callers participate, for different reasons. A proof-requiring removal (`requirePhysicalStop`) - * refuses, then closes under force. A folder-workspace removal (`closeStructuredSessions`) closes - * best-effort without refusing: it shares its root so no checkout vanishes under the child, and one - * of those paths is a never-throw forget that a refusal would wedge. Reconciliation sweeps set - * neither — they repair state, delete nothing, and must never close a session. + * Two callers participate. A proof-requiring removal (`requirePhysicalStop`) refuses when a close + * does not settle, so nothing deletes a checkout out from under a child that is still there. A + * folder-workspace removal (`closeStructuredSessions`) never refuses: it shares its root so no + * checkout vanishes under the child, and every one of those call sites discards a rejection, so a + * refusal there would be words nobody reads. Reconciliation sweeps set neither — they repair state, + * delete nothing, and must never close a session. */ async function sweepStructuredSessions( worktreeId: string, deps: WorktreeTeardownDeps, deadline: number, - deadlineError: Error + sweeps: WorktreeSweepTracker ): Promise { if (!deps.requirePhysicalStop && !deps.closeStructuredSessions) { return 0 } - const live = listLiveStructuredSessionsForWorktree(worktreeId) + // `deps` carries the same two host fields the PTY sweeps fence on, and a `repoId::path` id names + // a different workspace on every host — so an unfenced list would close a live chat belonging to + // an SSH or paired-runtime copy of the id being removed here. + const live = listLiveStructuredSessionsForWorktree(worktreeId, deps) if (live.length === 0) { return 0 } + // Raced against the same sweep budget every PTY surface is bounded by, because `host.close` + // awaits a provider round trip whose own eviction steps are each bounded well past this budget. + // + // Deliberately NOT fail-closed, unlike the PTY sweeps: their timeout sentinel carries the PTY + // timeout prefix, which the desktop classifier reads as a TERMINAL failure — so a wedged session + // close would refuse in terminal wording, and refuse identically again under the Force Delete + // that is meant to clear it (#11960). A close that ran out of time is a session this removal + // could not confirm closed, which is exactly what the branch below already words. Tracked so a + // forced removal still waits out the abandoned-sweep grace before it deletes files. + // + // The verdict is read off `progress`, which the serial loop fills as it goes, rather than off + // this call's result: the deadline can land mid-loop, and a fallback assembled here could only + // guess — it named every session, including the ones already closed, and reported zero closes. + const progress = createStructuredSweepProgress(live) + await settleBeforeDeadline( + sweeps.track(() => + closeStructuredSessionsForWorktree(progress, deadline, { + ...(deps.runtime ? { runtime: deps.runtime } : {}), + // The only shape of removal that can leave this workspace — and its chat tabs — in place. + mayRefuse: Boolean(deps.requirePhysicalStop) && !deps.allowUnverifiedStop + }) + ), + undefined, + deadline + ) + const closed = progress.closed + const unstopped = unclosedStructuredSessions(progress) + if (unstopped.length === 0) { + return closed + } // Only a proof-requiring removal may refuse. A folder-workspace removal shares its root, so no // checkout disappears under the child — the harm is a session left pointing at a workspace Orca - // has forgotten — and one of those paths is a never-throw forget, which a refusal would wedge. + // has forgotten — and every one of those callers discards a rejection anyway. if (deps.requirePhysicalStop && !deps.allowUnverifiedStop) { // The prefix is what the desktop classifier matches on; without it the toast shows raw CLI // wording and hides the Force Delete button — the #11960 dead end this file already documents. throw new Error( - `${RUNNING_AGENT_SESSION_REMOVAL_PREFIX} ${worktreeId}${UNSTOPPED_PTY_DETAIL_SEPARATOR}${describeLiveStructuredSessions(live)}. ${WORKTREE_TEARDOWN_FORCE_HINT}` + `${RUNNING_AGENT_SESSION_REMOVAL_PREFIX} ${worktreeId}${UNSTOPPED_PTY_DETAIL_SEPARATOR}${describeUnclosedStructuredSessions(unstopped)}. ${WORKTREE_TEARDOWN_FORCE_HINT}` ) } - // Raced against the same sweep budget every PTY surface is bounded by: `host.close` awaits a - // provider round trip, and a wedged one would otherwise hang `worktree rm --force` forever with - // no timeout error at all. On expiry the force path reports the timeout exactly as the PTY - // sweeps do rather than proceeding as if the sessions had closed. - const { closed, unstopped } = await settleBeforeDeadline( - () => closeStructuredSessionsForWorktree(worktreeId, deps.runtime), - { closed: 0, unstopped: live }, - deadline, - deadlineError + // Force is the documented escape hatch, so removal continues — but say so, because the child + // outliving its `cwd` is the failure this sweep exists to make visible. Carries the verdict + // verbatim, like the unstopped-PTY warn above: this line is the only record a forced removal + // leaves, and appending "still attached" asserted the live verdict over sessions the sweep had + // just said it could not confirm either way. + console.warn( + `[worktree-teardown] forcing removal of ${worktreeId}${UNSTOPPED_PTY_DETAIL_SEPARATOR}${describeUnclosedStructuredSessions(unstopped)}` ) - if (unstopped.length > 0) { - // Force is the documented escape hatch, so removal continues — but say so, because the child - // outliving its `cwd` is the failure this sweep exists to make visible. - console.warn( - `[worktree-teardown] forcing removal of ${worktreeId} with ${describeLiveStructuredSessions(unstopped)} still attached` - ) - } return closed } diff --git a/src/main/skills/skill-root-file-walk.test.ts b/src/main/skills/skill-root-file-walk.test.ts index ad84eced6b6..81e9b167fcc 100644 --- a/src/main/skills/skill-root-file-walk.test.ts +++ b/src/main/skills/skill-root-file-walk.test.ts @@ -66,10 +66,15 @@ describe('findSkillFiles', () => { expect(await findSkillFiles(root, 4)).toEqual([join(edge, 'SKILL.md')]) expect(statPaths).toEqual([]) - expect(await findSkillFiles(root, 5)).toEqual([ - join(edge, 'SKILL.md'), - join(edge, 'link00', 'SKILL.md') - ]) + // Why not a fixed array: `readdir` order is filesystem-dependent, and both + // the result order and which link survives dedup follow it. NTFS enumerates + // its name index alphabetically, so `link00` precedes `SKILL.md` on Windows + // and follows it on APFS/ext4. All 32 links share one realpath, so the + // visited set collapses them to a single entry beside the real file. + const withinDepth = await findSkillFiles(root, 5) + expect(withinDepth).toContain(join(edge, 'SKILL.md')) + expect(withinDepth.filter((path) => /[\\/]link\d{2}[\\/]SKILL\.md$/.test(path))).toHaveLength(1) + expect(withinDepth).toHaveLength(2) expect(statPaths).toHaveLength(32) }) diff --git a/src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts b/src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts index 76d92e77e9a..87d5c77f205 100644 --- a/src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts +++ b/src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts @@ -412,7 +412,7 @@ describe('SshRelaySession agent hooks over a fake relay transport', () => { expect(events).toHaveLength(2) }) - it('clears stamped status on reconnect loss but not final shutdown', async () => { + it('keeps stamped status unverifiable across reconnect loss and final shutdown', async () => { const initialRelay = createFakeRelay() relay = createFakeRelay() vi.mocked(deployAndLaunchRelay) @@ -436,16 +436,13 @@ describe('SshRelaySession agent hooks over a fake relay transport', () => { await session.reconnect({} as SshConnection) initialRelay.dispose() - expect(agentHookServer.getStatusSnapshot()).toEqual([]) - expect(clearListener).toHaveBeenCalledOnce() - expect(clearListener).toHaveBeenCalledWith({ - transient: true, - connectionId: 'conn-clear', - clearedAt: expect.any(Number) - }) + expect(agentHookServer.getStatusSnapshot()).toEqual([ + expect.objectContaining({ connectionId: 'conn-clear', state: 'working' }) + ]) + expect(clearListener).not.toHaveBeenCalled() session.dispose() session = null - expect(clearListener).toHaveBeenCalledOnce() + expect(clearListener).not.toHaveBeenCalled() }) it('asks the fake relay for cached hook replay after the session wires its listener', async () => { diff --git a/src/main/ssh/ssh-relay-session.ts b/src/main/ssh/ssh-relay-session.ts index a4fdb0f0fa7..08754ca76e1 100644 --- a/src/main/ssh/ssh-relay-session.ts +++ b/src/main/ssh/ssh-relay-session.ts @@ -1679,10 +1679,9 @@ export class SshRelaySession { if (reason === 'shutdown') { clearPtyOwnershipForConnection(this.targetId) - } else { - // Why: handlers detached above, so no late event can re-stamp status between this clear and reconnect replay. - agentHookServer.clearStatusEntriesForConnection(this.targetId) } + // Connection loss makes remote status unverifiable, not exited. Keep the last observation; + // replay or certified process teardown will update or remove it on the execution host. const ptyProvider = getSshPtyProvider(this.targetId) if (ptyProvider && 'dispose' in ptyProvider) { diff --git a/src/main/startup/headless-pty-hydration-ordering.test.ts b/src/main/startup/headless-pty-hydration-ordering.test.ts index e866a5d1926..3b661dede99 100644 --- a/src/main/startup/headless-pty-hydration-ordering.test.ts +++ b/src/main/startup/headless-pty-hydration-ordering.test.ts @@ -52,4 +52,64 @@ describe('headless PTY registry hydration ordering', () => { expect(rpc).toBeGreaterThan(handlersAndHydration) expect(readiness).toBeGreaterThan(rpc) }) + + it('starts the orcad hook owner after Store hydration and before daemon PTY recovery', () => { + const source = readFileSync(join(process.cwd(), 'src/main/orcad/orcad-entry.ts'), 'utf8') + const cleanup = source.indexOf('registerCleanup(async () => {') + const hookStop = source.indexOf('agentHookServer.stop()', cleanup) + const store = source.indexOf('const store = new Store(') + const hookStart = source.indexOf('await agentHookServer.start(', store) + const daemon = source.indexOf('await startOrcadDaemon()', hookStart) + const hookEnv = source.indexOf('buildAgentHookPtyEnv:', daemon) + const handlersAndHydration = source.indexOf('await registerHeadlessPtyRuntime(', hookEnv) + + expect(cleanup).toBeGreaterThanOrEqual(0) + expect(hookStop).toBeGreaterThan(cleanup) + expect(store).toBeGreaterThan(hookStop) + expect(hookStart).toBeGreaterThan(store) + expect(daemon).toBeGreaterThan(hookStart) + expect(hookEnv).toBeGreaterThan(daemon) + expect(source.slice(hookEnv, handlersAndHydration)).toContain('agentHookServer.buildPtyEnv()') + expect(handlersAndHydration).toBeGreaterThan(hookEnv) + }) + + it('captures orcad status identity at ingest for fleet stale-row fencing', () => { + const source = readFileSync(join(process.cwd(), 'src/main/orcad/orcad-entry.ts'), 'utf8') + const runtime = source.indexOf('const runtime = new OrcaRuntimeService(') + const identityReader = source.indexOf('readObservedAgentStatusPaneIdentity:', runtime) + const identitySubscription = source.indexOf('agentHookServer.subscribeEnrichedStatus(') + const hooksEnabled = source.indexOf('if (isAgentStatusHooksEnabled(', identitySubscription) + const identityFlush = source.indexOf('observedStatusCapture.attach(runtime)', runtime) + + expect(runtime).toBeGreaterThanOrEqual(0) + expect(identityReader).toBeGreaterThan(runtime) + expect(identitySubscription).toBeGreaterThanOrEqual(0) + expect(identitySubscription).toBeLessThan(runtime) + expect(hooksEnabled).toBeGreaterThan(identitySubscription) + expect(identityFlush).toBeGreaterThan(runtime) + expect(source.slice(identitySubscription, runtime)).toContain( + 'observedStatusCapture.observe(enriched)' + ) + }) + + it('captures spool-replayed identity after the orcad runtime is ready', () => { + const source = readFileSync(join(process.cwd(), 'src/main/orcad/orcad-entry.ts'), 'utf8') + const subscription = source.indexOf('agentHookServer.subscribeEnrichedStatus(') + const hookStart = source.indexOf('await agentHookServer.start(', subscription) + const runtime = source.indexOf('const runtime = new OrcaRuntimeService(') + const handlers = source.indexOf('await registerHeadlessPtyRuntime(', runtime) + const identityRecovery = source.indexOf('await runtime.refreshRestoredOrchestrationAuthority()') + const workerRecovery = source.indexOf('await runtime.reconcileLegacyWorkerTerminals()') + const replay = source.indexOf('observedStatusCapture.attach(runtime)', runtime) + + expect(subscription).toBeGreaterThanOrEqual(0) + expect(hookStart).toBeGreaterThan(subscription) + expect(runtime).toBeGreaterThan(hookStart) + expect(handlers).toBeGreaterThan(runtime) + expect(identityRecovery).toBeGreaterThan(handlers) + expect(workerRecovery).toBeGreaterThan(identityRecovery) + expect(replay).toBeGreaterThan(workerRecovery) + expect(source.slice(subscription, runtime)).toContain('observedStatusCapture.observe(enriched)') + expect(source.slice(replay)).toContain('observedStatusCapture.attach(runtime)') + }) }) diff --git a/src/main/startup/main-process-observers.ts b/src/main/startup/main-process-observers.ts index ba37b0a312f..86f7992e10d 100644 --- a/src/main/startup/main-process-observers.ts +++ b/src/main/startup/main-process-observers.ts @@ -3,9 +3,8 @@ import { join } from 'node:path' import { AgentAwakeService } from '../agent-awake-service' import { normalizeComputerAwakeMode } from '../../shared/computer-awake-mode' import { registerSystemResumeBroadcast } from '../system-resume-broadcast' -import { agentHookServer, type AgentHookProviderSessionIdentity } from '../agent-hooks/server' -import { createHookProviderSessionInvalidator } from '../agent-hooks/hook-provider-session-invalidation' -import { createHookStatusSessionTabsInvalidator } from '../agent-hooks/hook-status-session-tabs-invalidation' +import { agentHookServer } from '../agent-hooks/server' +import { installHookStatusSessionTabsRepublish } from '../agent-hooks/hook-status-session-tabs-republish' import { initTelemetry, track } from '../telemetry/client' import { setCodexTrustGrantTelemetry } from '../codex/codex-trust-grant-telemetry' import { initObservability } from '../observability' @@ -40,55 +39,20 @@ export function initializeMainProcessObservers(): void { isQuitting: () => state.isQuitting, getWorkingAgentCount: () => state.agentAwakeService?.getWorkingAgentCount() ?? 0 }) - const collectChangedProviderSessionWorktrees = createHookProviderSessionInvalidator() - const publishProviderSessionChanges = (identities: AgentHookProviderSessionIdentity[]): void => { - const ownedIdentities = identities.map((identity) => ({ - ...identity, - worktreeId: - identity.worktreeId ?? - state.runtime?.getTerminalWorktreeIdForPaneKey(identity.paneKey) ?? - undefined - })) - for (const worktreeId of collectChangedProviderSessionWorktrees(ownedIdentities)) { - // Why not `notifyMobileSessionTabsChanged` alone: it re-emits at the unchanged - // `snapshotVersion`, which every client drops on its monotonic gate. - state.runtime?.touchMobileSessionTabsForWorktree(worktreeId, { immediate: true }) - } - } - state.publishProviderSessionChanges = publishProviderSessionChanges const unsubscribeStatusChanges = agentHookServer.subscribeStatusChanges((statuses) => { state.agentAwakeService?.setStatuses(statuses) }) - // Healthy session.tabs streams need a push when transcript identity changes. - const unsubscribeProviderSessionChanges = agentHookServer.subscribeProviderSessionChanges( - (sessions) => publishProviderSessionChanges(sessions) + const unsubscribeStatusFreshness = agentHookServer.subscribeStatusFreshness((status) => { + state.agentAwakeService?.observeStatusFreshness(status) + }) + const uninstallHookStatusRepublish = installHookStatusSessionTabsRepublish( + agentHookServer, + () => state.runtime ) - // Why: hook rows are the only carrier of live agent state on a headless host, and - // nothing else republishes `session.tabs` when one changes — so a paired client - // would keep the pane's last projection until an unrelated PTY touch came along. - const hookStatusChangedSessionTabs = createHookStatusSessionTabsInvalidator() - const unsubscribeHookStatusSessionTabs = agentHookServer.subscribeEnrichedStatus((enriched) => { - if (hookStatusChangedSessionTabs(enriched)) { - state.runtime?.touchMobileSessionTabsForPane(enriched.paneKey, enriched.worktreeId ?? null) - } - }) - // Teardown: agent exit, pane close, and the SSH transient-disconnect batch all land - // here. Without it the live state published above becomes a zombie question card. - const unsubscribeHookStatusClear = agentHookServer.subscribePaneStatusClear((clear) => { - const clearedPaneKeys = - 'paneKey' in clear - ? [clear.paneKey] - : hookStatusChangedSessionTabs.forgetConnection(clear.connectionId) - for (const paneKey of clearedPaneKeys) { - hookStatusChangedSessionTabs.forgetPane(paneKey) - state.runtime?.touchMobileSessionTabsForPane(paneKey) - } - }) state.unsubscribeAgentAwakeStatusChanges = () => { unsubscribeStatusChanges() - unsubscribeProviderSessionChanges() - unsubscribeHookStatusSessionTabs() - unsubscribeHookStatusClear() + unsubscribeStatusFreshness() + uninstallHookStatusRepublish() } // Why: telemetry must init before any IPC handler/renderer can call track(); it's a no-op in dev and while TELEMETRY_ENABLED is false, so it's safe early. initTelemetry(store) diff --git a/src/main/startup/main-process-push-startup.ts b/src/main/startup/main-process-push-startup.ts new file mode 100644 index 00000000000..6d1b9fda1bd --- /dev/null +++ b/src/main/startup/main-process-push-startup.ts @@ -0,0 +1,32 @@ +import { getOrcaPushGatewayUrl } from '../orca-profiles/profile-cloud-auth-config' +import { DesktopPushService } from '../runtime/push/desktop-push-service' +import type { OrcaRuntimeService } from '../runtime/orca-runtime' +import type { OrcaRuntimeRpcServer } from '../runtime/runtime-rpc' +import { mainProcessState as state } from './main-process-state' + +// Why: deliberately not gated on cloud sign-in like the relay is — the push gateway +// authenticates with the host keypair, so an accountless host registers phones on +// exactly the same path. The runtime is read from shared state because both launch +// modes have already stored it there; threading it as a parameter would push the +// launch module past its line budget for no gain. +export function startDesktopPushService(runtimeRpc: OrcaRuntimeRpcServer): void { + const runtime: OrcaRuntimeService | null = state.runtime + if (!runtime) { + console.warn('[push] Background push startup skipped: runtime not started') + return + } + try { + const pushService = DesktopPushService.create({ + runtime, + runtimeRpc, + gatewayUrl: getOrcaPushGatewayUrl() + }) + pushService?.start() + state.desktopPushService = pushService + } catch (error) { + console.warn( + '[push] Background push startup unavailable:', + error instanceof Error ? error.message : String(error) + ) + } +} diff --git a/src/main/startup/main-process-quit.ts b/src/main/startup/main-process-quit.ts index a4149e13ba7..a136981c873 100644 --- a/src/main/startup/main-process-quit.ts +++ b/src/main/startup/main-process-quit.ts @@ -105,6 +105,8 @@ function installWillQuitHandler(): void { if (!quitTeardownStartGate.tryStart(event)) { return } + // A renderer can veto before-quit; push must survive until quit is committed. + state.desktopPushService?.stop() state.unsubscribeSystemResumeBroadcast?.() state.unsubscribeSystemResumeBroadcast = null // Why: renderer guards can still cancel before this committed phase; `log stream` must survive those vetoes. diff --git a/src/main/startup/main-process-relay-status.ts b/src/main/startup/main-process-relay-status.ts new file mode 100644 index 00000000000..1dd254df8b3 --- /dev/null +++ b/src/main/startup/main-process-relay-status.ts @@ -0,0 +1,18 @@ +import type { MobileRelayStatusDetail } from '../../shared/mobile-relay-status' +import { mainProcessState as state } from './main-process-state' + +export function getDesktopRelayStatus(): MobileRelayStatusDetail { + return { + status: state.desktopRelayStatus, + ...(state.desktopRelayCellUrl === undefined ? {} : { cellUrl: state.desktopRelayCellUrl }) + } +} + +export function publishDesktopRelayStatus( + status: MobileRelayStatusDetail['status'], + cellUrl?: string +): void { + state.desktopRelayStatus = status + state.desktopRelayCellUrl = cellUrl + state.mainWindow?.webContents.send('mobile:relayStatusChanged', getDesktopRelayStatus()) +} diff --git a/src/main/startup/main-process-runtime-launch.ts b/src/main/startup/main-process-runtime-launch.ts index 4ec2bd7bfac..fdedf310cbb 100644 --- a/src/main/startup/main-process-runtime-launch.ts +++ b/src/main/startup/main-process-runtime-launch.ts @@ -13,7 +13,7 @@ import { LocalPtyProvider } from '../providers/local-pty-provider' import { HEADLESS_RUNTIME_WINDOW_ID } from '../../shared/runtime-types' import { OffscreenBrowserBackend } from '../browser/offscreen-browser-backend' import { browserManager } from '../browser/browser-manager' -import type { MobileRelayStatusDetail } from '../../shared/mobile-relay-status' +import { getDesktopRelayStatus, publishDesktopRelayStatus } from './main-process-relay-status' import { DesktopRelayService } from '../runtime/relay/desktop-relay-service' import { getServeOptions, getBundledWebClientRoot, printServeReady } from './main-process-serve' import { @@ -36,6 +36,7 @@ import { CliInstaller } from '../cli/cli-installer' import { installLinuxBareOrcaDispatcher } from '../cli/linux-bare-orca-dispatcher' import { scheduleAllPendingHistoryTreeRemovals } from '../terminal-history-deletion' import { triggerStartupNotificationRegistration } from '../ipc/startup-notification-registration' +import { startDesktopPushService } from './main-process-push-startup' import { mainProcessState as state } from './main-process-state' import { logStartupMilestone } from './startup-diagnostics' @@ -92,10 +93,7 @@ function installRuntimeRpc( }) state.runtimeRpc = runtimeRpc registerMobileHandlers(runtimeRpc, { - getRelayStatus: () => ({ - status: state.desktopRelayStatus, - ...(state.desktopRelayCellUrl === undefined ? {} : { cellUrl: state.desktopRelayCellUrl }) - }), + getRelayStatus: getDesktopRelayStatus, consumePendingUnpairedDeviceAuthFailure: (webContentsId) => { if ( !state.mainWindow || @@ -162,6 +160,9 @@ async function launchServeMode( console.error('[runtime] Failed to start headless RPC transport:', error) throw error }) + // Why: a phone paired to a headless host still registers and unregisters its token; + // it simply never receives a push, because nothing dispatches notifications here. + startDesktopPushService(runtimeRpc) settleDesktopActivation() // Why: every attempt must reach app.quit(); a page beforeunload can veto an earlier signal. registerServeSignalHandlers(process, () => app.quit()) @@ -245,6 +246,9 @@ async function launchDesktopMode( // fetcher until the persisted proxy lands, so this only has to keep the launch phase itself // ordered ahead of the relay — it must not gate the renderer. await state.initialProxyApplicationReady + // Why after the proxy await: the push gateway client is an app-owned fetcher, so it must not + // issue its first request ahead of the persisted proxy. + startDesktopPushService(runtimeRpc) const cloudAuth = getOrcaCloudAuthConfig() if (cloudAuth.configured) { try { @@ -253,14 +257,7 @@ async function launchDesktopMode( userDataPath: getProfileUserDataPath(), appVersion: app.getVersion(), runtimeRpc, - onStatus: (status, cellUrl) => { - state.desktopRelayStatus = status - state.desktopRelayCellUrl = cellUrl - state.mainWindow?.webContents.send('mobile:relayStatusChanged', { - status, - ...(cellUrl === undefined ? {} : { cellUrl }) - } satisfies MobileRelayStatusDetail) - } + onStatus: publishDesktopRelayStatus }) state.desktopRelayService = relayService runtimeRpc.setMobileRelayPairingProvider({ diff --git a/src/main/startup/main-process-runtime-service.ts b/src/main/startup/main-process-runtime-service.ts index 8af5630e02b..3aac4a03b3c 100644 --- a/src/main/startup/main-process-runtime-service.ts +++ b/src/main/startup/main-process-runtime-service.ts @@ -138,7 +138,6 @@ export function initializeMainProcessRuntime(): OrcaRuntimeService { // Why before anything can attach: a client host that reattaches to a restarted runtime is only // handed its pages back if the runtime found them first. runtime.rehydrateClientHostedBrowserPages() - state.publishProviderSessionChanges?.(agentHookServer.getProviderSessionIdentities()) browserManager.setBrowserGuestStateChangedListener((worktreeId) => { runtime.notifyMobileSessionTabsChanged(worktreeId) }) diff --git a/src/main/startup/main-process-state.ts b/src/main/startup/main-process-state.ts index d69518d710a..2b9361a6d51 100644 --- a/src/main/startup/main-process-state.ts +++ b/src/main/startup/main-process-state.ts @@ -13,6 +13,7 @@ import type { OrcaRuntimeService } from '../runtime/orca-runtime' import type { RateLimitService } from '../rate-limits/service' import type { OrcaRuntimeRpcServer } from '../runtime/runtime-rpc' import type { DesktopRelayService } from '../runtime/relay/desktop-relay-service' +import type { DesktopPushService } from '../runtime/push/desktop-push-service' import type { StarNagService } from '../star-nag/service' import type { AgentAwakeService } from '../agent-awake-service' import type { CrashReportStore } from '../crash-reporting/crash-report-store' @@ -24,7 +25,6 @@ import type { PluginMarketplaceInstaller } from '../plugins/plugin-marketplace-i import type { KeybindingService } from '../keybindings/keybinding-service' import type { RelayBrokerStatus } from '../runtime/relay/relay-session-broker' import type { AgentBrowserBridge } from '../browser/agent-browser-bridge' -import type { AgentHookProviderSessionIdentity } from '../agent-hooks/server' import type { EmulatorBridge } from '../emulator/emulator-bridge' import type { GpuFallbackMarker, GpuFallbackEnvironment } from './gpu-fallback-marker' import type { createCodexSessionMigrationScheduler } from '../codex/codex-session-migration-scheduler' @@ -65,6 +65,7 @@ export const mainProcessState = { runtimeRpc: null as OrcaRuntimeRpcServer | null, serveReadinessPublisher: new ServeReadinessPublisher(), desktopRelayService: null as DesktopRelayService | null, + desktopPushService: null as DesktopPushService | null, desktopRelayStatus: 'offline' as RelayBrokerStatus, desktopRelayCellUrl: undefined as string | undefined, pendingUnpairedDeviceAuthFailure: false, @@ -76,9 +77,6 @@ export const mainProcessState = { repoMaintenanceShutdown: Promise.resolve() as Promise, crashReports: null as CrashReportStore | null, unsubscribeAgentAwakeStatusChanges: null as (() => void) | null, - publishProviderSessionChanges: null as - | ((identities: AgentHookProviderSessionIdentity[]) => void) - | null, unsubscribeSystemResumeBroadcast: null as (() => void) | null, watcherShutdownPromise: null as Promise | null, watcherShutdownDone: false, diff --git a/src/preload/api/notifications-bridge.ts b/src/preload/api/notifications-bridge.ts index 70c64d4ce0d..210352ff981 100644 --- a/src/preload/api/notifications-bridge.ts +++ b/src/preload/api/notifications-bridge.ts @@ -37,6 +37,8 @@ function disposeCachedNotificationSound(): void { } export const notificationsApi = { + getDesktopAwayState: (): Promise => + ipcRenderer.invoke('notifications:getDesktopAwayState'), dispatch: (args: Record): Promise => ipcRenderer.invoke('notifications:dispatch', args), dismiss: (ids: string[]): Promise => diff --git a/src/preload/api/os-permission-api.ts b/src/preload/api/os-permission-api.ts index 8718cfc29a5..f2033c2fe1c 100644 --- a/src/preload/api/os-permission-api.ts +++ b/src/preload/api/os-permission-api.ts @@ -20,6 +20,7 @@ import type { } from '../../shared/notification-settings-types' export type NotificationsApi = { + getDesktopAwayState: () => Promise dispatch: (args: NotificationDispatchRequest) => Promise dismiss: (ids: string[]) => Promise openSystemSettings: () => Promise diff --git a/src/preload/api/runtime-api.ts b/src/preload/api/runtime-api.ts index f7f553ec2c0..7fdf229dd88 100644 --- a/src/preload/api/runtime-api.ts +++ b/src/preload/api/runtime-api.ts @@ -1,3 +1,4 @@ +import type { RuntimeHostStatusSnapshot } from '../../shared/runtime-host-status' import type { RuntimeBrowserDriverState, RuntimeRendererSyncWindowGraph, @@ -77,6 +78,8 @@ export type RuntimeApi = { ) => () => void } runtimeEnvironments: { + getStatusSnapshots: () => Promise + onStatusChanged: (callback: (snapshot: RuntimeHostStatusSnapshot) => void) => () => void list: () => Promise addFromPairingCode: (args: { name: string diff --git a/src/preload/api/runtime-environments-bridge.ts b/src/preload/api/runtime-environments-bridge.ts index ddfa498dc74..63c31df52f8 100644 --- a/src/preload/api/runtime-environments-bridge.ts +++ b/src/preload/api/runtime-environments-bridge.ts @@ -1,4 +1,8 @@ import { ipcRenderer } from 'electron' +import { + RUNTIME_HOST_STATUS_CHANNEL, + type RuntimeHostStatusSnapshot +} from '../../shared/runtime-host-status' import type { VerifyAndAddRuntimeEnvironmentResult } from '../../shared/remote-pairing-verification' import type { RuntimeStatus } from '../../shared/runtime-types' import type { RuntimeRpcResponse } from '../../shared/runtime-rpc-envelope' @@ -12,6 +16,16 @@ import { import type { PreloadApi } from '../api-types' export const runtimeEnvironmentsApi = { + getStatusSnapshots: (): Promise => + ipcRenderer.invoke('runtimeEnvironments:getStatusSnapshots'), + onStatusChanged: (callback: (snapshot: RuntimeHostStatusSnapshot) => void): (() => void) => { + const listener = ( + _event: Electron.IpcRendererEvent, + snapshot: RuntimeHostStatusSnapshot + ): void => callback(snapshot) + ipcRenderer.on(RUNTIME_HOST_STATUS_CHANNEL, listener) + return () => ipcRenderer.removeListener(RUNTIME_HOST_STATUS_CHANNEL, listener) + }, list: (): Promise => ipcRenderer.invoke('runtimeEnvironments:list'), addFromPairingCode: (args: { diff --git a/src/renderer/src/app-shell/AppRootSurfaces.tsx b/src/renderer/src/app-shell/AppRootSurfaces.tsx index 202c99df4d2..31de9b1ce8d 100644 --- a/src/renderer/src/app-shell/AppRootSurfaces.tsx +++ b/src/renderer/src/app-shell/AppRootSurfaces.tsx @@ -1,3 +1,4 @@ +import { NotificationCardStack } from '../components/NotificationCardStack' import { Suspense } from 'react' import { lazyWithRetry as lazy } from '@/lib/lazy-with-retry' import { translate } from '@/i18n/i18n' @@ -58,6 +59,11 @@ const SshPassphraseDialog = lazy(() => const UpdateCard = lazy(() => import('../components/UpdateCard').then((module) => ({ default: module.UpdateCard })) ) +const UnexpectedSignoutCard = lazy(() => + import('../components/UnexpectedSignoutCard').then((module) => ({ + default: module.UnexpectedSignoutCard + })) +) const RemoteServerUpdateDialog = lazy( () => import('../components/settings/RemoteServerUpdateDialog') ) @@ -273,16 +279,23 @@ export function AppRootSurfaces(props: { ) : null} - {shouldMountUpdateCard ? ( + + {shouldMountUpdateCard ? ( + + + + + + ) : null} - - + + - ) : null} - - - + + + + diff --git a/src/renderer/src/components/NewWorkspaceComposerCard.tsx b/src/renderer/src/components/NewWorkspaceComposerCard.tsx index d17bb8ba56d..7145bed732c 100644 --- a/src/renderer/src/components/NewWorkspaceComposerCard.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerCard.tsx @@ -242,17 +242,11 @@ export default function NewWorkspaceComposerCard( selector: action.environmentId, timeoutMs: 15_000 }) - const runtimeStatus = unwrapRuntimeRpcResult(response) - useAppStore.getState().setRuntimeEnvironmentStatus(action.environmentId, { - status: runtimeStatus, - checkedAt: Date.now() - }) + unwrapRuntimeRpcResult(response) + await useAppStore.getState().readRuntimeHostStatusSnapshots() } catch (error) { if (action.kind === 'runtime') { - useAppStore.getState().setRuntimeEnvironmentStatus(action.environmentId, { - status: null, - checkedAt: Date.now() - }) + await useAppStore.getState().readRuntimeHostStatusSnapshots() } toast.error( error instanceof Error diff --git a/src/renderer/src/components/NotificationCardStack.tsx b/src/renderer/src/components/NotificationCardStack.tsx new file mode 100644 index 00000000000..9d3d5cddf3c --- /dev/null +++ b/src/renderer/src/components/NotificationCardStack.tsx @@ -0,0 +1,9 @@ +import type { ReactNode } from 'react' + +export function NotificationCardStack({ children }: { children: ReactNode }): React.JSX.Element { + return ( +
+ {children} +
+ ) +} diff --git a/src/renderer/src/components/StarNagCard.tsx b/src/renderer/src/components/StarNagCard.tsx index f0e184143fc..0bf3312463e 100644 --- a/src/renderer/src/components/StarNagCard.tsx +++ b/src/renderer/src/components/StarNagCard.tsx @@ -2,7 +2,6 @@ import { useCallback, useEffect, useState } from 'react' import { ExternalLink, Star, X } from 'lucide-react' import { Card } from './ui/card' import { Button } from './ui/button' -import { useAppStore } from '../store' import { useMountedRef } from '@/hooks/useMountedRef' import { translate } from '@/i18n/i18n' @@ -25,12 +24,6 @@ export function StarNagCard(): React.JSX.Element | null { const [busy, setBusy] = useState(false) const [mode, setMode] = useState('gh') const mountedRef = useMountedRef() - // Why: UpdateCard lives at the same bottom-right slot. When it is visible - // (any non-idle / non-not-available state), stack the star-nag card above - // it instead of overlapping — we must not cover a pending update prompt - // because that's a higher-priority action. - const updateStatus = useAppStore((s) => s.updateStatus) - const updateCardVisible = updateStatus.state !== 'idle' && updateStatus.state !== 'not-available' useEffect(() => { const unsubscribeShow = window.api.starNag.onShow((payload) => { @@ -147,15 +140,7 @@ export function StarNagCard(): React.JSX.Element | null { } return ( -
+
diff --git a/src/renderer/src/components/UnexpectedSignoutCard.tsx b/src/renderer/src/components/UnexpectedSignoutCard.tsx new file mode 100644 index 00000000000..ee0e8949ec3 --- /dev/null +++ b/src/renderer/src/components/UnexpectedSignoutCard.tsx @@ -0,0 +1,269 @@ +import { useEffect, useRef, useState } from 'react' +import { BookOpen, ChevronDown, CircleUserRound, Files, Smartphone, X } from 'lucide-react' +import { useAppStore } from '../store' +import { translate } from '@/i18n/i18n' +import { cn } from '@/lib/utils' +import { Button } from './ui/button' +import { Card } from './ui/card' +import { Collapsible, CollapsibleContent, CollapsibleTrigger } from './ui/collapsible' +import { shouldShowUnexpectedSignoutCard } from './unexpected-signout/unexpected-signout-visibility' + +function readPreviewFlag(): boolean { + if (!import.meta.env.DEV) { + return false + } + try { + if (new URLSearchParams(window.location.search).get('showSignoutCard') === '1') { + return true + } + return window.localStorage.getItem('orca-debug-show-signout-card') === '1' + } catch { + return false + } +} + +function FeatureRow({ + icon: Icon, + title, + description +}: { + icon: typeof Files + title: string + description: string +}): React.JSX.Element { + return ( +
+ +
+

{title}

+

{description}

+
+
+ ) +} + +export function UnexpectedSignoutCard(): React.JSX.Element | null { + const authStatus = useAppStore((s) => s.orcaProfileAuthStatus) + const persistedUIReady = useAppStore((s) => s.persistedUIReady) + const persistedDismissedVersion = useAppStore((s) => s.dismissedUnexpectedSignoutVersion) + const dismissedVersions = useAppStore((s) => s.unexpectedSignoutDismissedVersions) + const dismissForVersion = useAppStore((s) => s.dismissUnexpectedSignoutCard) + const connecting = useAppStore((s) => s.orcaProfileConnecting) + const connect = useAppStore((s) => s.connectCurrentOrcaProfile) + const [appVersion, setAppVersion] = useState(null) + const [authRefreshReady, setAuthRefreshReady] = useState(false) + const [expanded, setExpanded] = useState(false) + const [preview] = useState(readPreviewFlag) + const [previewDismissed, setPreviewDismissed] = useState(false) + const reconnectingProfile = useRef(null) + + useEffect(() => { + let cancelled = false + let attempts = 0 + const refresh = (): void => { + attempts += 1 + void useAppStore + .getState() + .fetchOrcaProfileAuthStatus() + .then((status) => { + if (cancelled) { + return + } + if (status != null) { + setAuthRefreshReady(true) + } else if (attempts < 3) { + window.setTimeout(refresh, 500) + } + }) + } + refresh() + return () => { + cancelled = true + } + }, []) + + useEffect(() => { + let cancelled = false + void window.api.updater + .getVersion() + .then((version) => { + if (!cancelled) { + setAppVersion(version) + } + }) + .catch(() => { + if (!cancelled) { + setAppVersion(null) + } + }) + return () => { + cancelled = true + } + }, []) + + const dismissedVersion = + appVersion && dismissedVersions.includes(appVersion) ? appVersion : persistedDismissedVersion + const eligible = shouldShowUnexpectedSignoutCard({ + authStatus, + persistedUIReady, + appVersion, + dismissedVersion + }) + + const visible = preview ? persistedUIReady && !previewDismissed : authRefreshReady && eligible + + // Observe recovery independently of visibility and asynchronous version/hydration reads. + useEffect(() => { + if (preview || !authRefreshReady) { + return + } + if (authStatus?.state === 'reconnect-required' && authStatus.configured && authStatus.cloud) { + reconnectingProfile.current = authStatus.activeProfileId + } else if (authStatus?.state === 'connected') { + if ( + reconnectingProfile.current === authStatus.activeProfileId && + persistedUIReady && + appVersion + ) { + reconnectingProfile.current = null + if (dismissedVersion !== appVersion) { + dismissForVersion(appVersion) + } + } + } else { + reconnectingProfile.current = null + } + }, [ + preview, + authRefreshReady, + authStatus, + persistedUIReady, + appVersion, + dismissedVersion, + dismissForVersion + ]) + + if (!visible) { + return null + } + + const email = authStatus?.cloud?.email?.trim() || null + const canConnect = authStatus?.configured === true + + const handleDismiss = (): void => { + if (preview) { + setPreviewDismissed(true) + } else if (appVersion) { + dismissForVersion(appVersion) + } + } + + return ( +
+ +
+
+
+ +

+ {translate( + 'auto.components.UnexpectedSignoutCard.9f2c1a4b7d', + "You've been signed out" + )} +

+
+ +
+ +

+ {email + ? translate( + 'auto.components.UnexpectedSignoutCard.7b4d9e1f2a', + 'Sign in again as {{value0}} to restore Artifact sharing, Orca Relay, and skill sharing.', + { value0: email } + ) + : translate( + 'auto.components.UnexpectedSignoutCard.5a1c8d3e6f', + 'Sign in again to restore Artifact sharing, Orca Relay, and skill sharing.' + )} +

+ + + + + + + + + + + + +
+ +
+
+
+
+ ) +} diff --git a/src/renderer/src/components/UpdateCard.error-card.test.tsx b/src/renderer/src/components/UpdateCard.error-card.test.tsx index 1e6da6879f7..186a285b26d 100644 --- a/src/renderer/src/components/UpdateCard.error-card.test.tsx +++ b/src/renderer/src/components/UpdateCard.error-card.test.tsx @@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { LinuxPackageInstallRecovery, UpdateStatus } from '../../../shared/update-status-types' import { useAppStore } from '../store' import { UpdateCard } from './UpdateCard' +import { NotificationCardStack } from './NotificationCardStack' const openUrl = vi.fn() const download = vi.fn() @@ -31,7 +32,11 @@ function renderWithInitialStatus(updateStatus: UpdateStatus): RenderResult { updateCardCollapsed: false, updateReassuranceSeen: true }) - return render() + return render( + + + + ) } function renderAfterAvailableStatus(): RenderResult { diff --git a/src/renderer/src/components/UpdateCard.tsx b/src/renderer/src/components/UpdateCard.tsx index 4ccf95ff252..e2023ae21e1 100644 --- a/src/renderer/src/components/UpdateCard.tsx +++ b/src/renderer/src/components/UpdateCard.tsx @@ -239,10 +239,7 @@ export function UpdateCard(): React.JSX.Element | null { !reassuranceSeen && ((status.state === 'available' && !status.externallyManaged) || status.state === 'downloading') return ( -
+
{showReassurance && (
diff --git a/src/renderer/src/components/cmd-j/palette-host-badge.test.ts b/src/renderer/src/components/cmd-j/palette-host-badge.test.ts index cd6310c8580..8d15ff8d034 100644 --- a/src/renderer/src/components/cmd-j/palette-host-badge.test.ts +++ b/src/renderer/src/components/cmd-j/palette-host-badge.test.ts @@ -83,8 +83,7 @@ describe('getPaletteHostBadge', () => { repos: [{ executionHostId: 'runtime:env-1' }], sshTargetLabels: new Map(), settings: { activeRuntimeEnvironmentId: 'env-2' }, - // A live status makes the runtime 'available'; without it the host reads - // 'disconnected' and the badge is suppressed (covered below). + // Only verified availability enables unfiltered host badges. runtimeStatusByEnvironmentId: new Map([ [ 'env-1', @@ -145,3 +144,19 @@ describe('getPaletteHostBadge', () => { expect(getPaletteHostBadge(null, hosts)).toBeNull() }) }) + +it.each(['connecting', 'blocked', 'disconnected', 'error'] as const)( + 'does not infer reachability from %s health, but preserves explicit filter labels', + (health) => { + const hosts = buildSidebarHostOptions({ + repos: [{ executionHostId: 'runtime:env-1' }], + sshTargetLabels: new Map(), + settings: { activeRuntimeEnvironmentId: null } + }).map((host) => (host.kind === 'runtime' ? { ...host, health } : host)) + expect(getPaletteHostBadge({ connectionId: null }, hosts)).toBeNull() + expect(getPaletteHostBadge({ executionHostId: 'runtime:env-1' }, hosts, true)).toEqual({ + hostId: 'runtime:env-1', + label: 'env-1' + }) + } +) diff --git a/src/renderer/src/components/cmd-j/palette-host-badge.ts b/src/renderer/src/components/cmd-j/palette-host-badge.ts index 8ac94adeae4..01a9e33d3ac 100644 --- a/src/renderer/src/components/cmd-j/palette-host-badge.ts +++ b/src/renderer/src/components/cmd-j/palette-host-badge.ts @@ -17,7 +17,7 @@ export type PaletteHostBadge = { // unlike the sidebar gate, which lists disconnected hosts so users can connect. function hasActiveRemoteHost(hostOptions: readonly SidebarHostOption[]): boolean { return hostOptions.some( - (host) => host.id !== LOCAL_EXECUTION_HOST_ID && host.health !== 'disconnected' + (host) => host.id !== LOCAL_EXECUTION_HOST_ID && host.health === 'available' ) } diff --git a/src/renderer/src/components/dashboard/build-dashboard-snapshot.rows-cache.test.ts b/src/renderer/src/components/dashboard/build-dashboard-snapshot.rows-cache.test.ts index f99738a5c4a..3a1254004a6 100644 --- a/src/renderer/src/components/dashboard/build-dashboard-snapshot.rows-cache.test.ts +++ b/src/renderer/src/components/dashboard/build-dashboard-snapshot.rows-cache.test.ts @@ -3,6 +3,7 @@ import type { AgentStatusEntry } from '../../../../shared/agent-status-types' import { makePaneKey } from '../../../../shared/stable-pane-id' import type { TerminalTab } from '../../../../shared/terminal-tab-types' import type { Worktree } from '../../../../shared/worktree/types' +import type { RetainedAgentEntry } from '@/store/slices/agent-status' import { buildDashboardSnapshot, type DashboardSnapshotState } from './build-dashboard-snapshot' import { createWorktreeAgentRowsCache } from './worktree-agent-rows-cache' @@ -139,4 +140,52 @@ describe('buildDashboardSnapshot rows cache', () => { buildDashboardSnapshot(state, NOW + 60_000, { rowsCache: cache, rowsGeneration: 2 }) expect(cache.lastComputedWorktreeIds.sort()).toEqual(['w1', 'w2']) }) + + it('refreshes a retained row from a provider title published to its current tab', () => { + const cache = createWorktreeAgentRowsCache() + const retainedTab = { ...tab('tab1', 'w1'), title: 'Claude ready' } + const retained: RetainedAgentEntry = { + entry: { + ...entry(PANE_1, 'tab1', 'w1'), + providerSession: { key: 'session_id', id: 'session-a' } + }, + worktreeId: 'w1', + tab: retainedTab, + agentType: 'claude', + startedAt: NOW - 10_000 + } + const initial: DashboardSnapshotState = { + ...baseState(), + tabsByWorktree: { w1: [retainedTab], w2: [tab('tab2', 'w2')] }, + agentStatusByPaneKey: { [PANE_2]: entry(PANE_2, 'tab2', 'w2') }, + retainedAgentsByPaneKey: { [PANE_1]: retained } + } + expect( + buildDashboardSnapshot(initial, NOW, { rowsCache: cache, rowsGeneration: 1 }).cards.find( + (card) => card.paneKey === PANE_1 + )?.conversationName + ).toBeUndefined() + + const titled: DashboardSnapshotState = { + ...initial, + tabsByWorktree: { + ...initial.tabsByWorktree, + w1: [ + { + ...retainedTab, + aiVaultTitle: { agent: 'claude', sessionId: 'session-a', title: 'Provider title' } + } + ] + } + } + const refreshed = buildDashboardSnapshot(titled, NOW, { + rowsCache: cache, + rowsGeneration: 1 + }) + + expect(cache.lastComputedWorktreeIds).toEqual(['w1']) + expect(refreshed.cards.find((card) => card.paneKey === PANE_1)?.conversationName).toBe( + 'Provider title' + ) + }) }) diff --git a/src/renderer/src/components/dashboard/dashboard-card-labels.test.ts b/src/renderer/src/components/dashboard/dashboard-card-labels.test.ts new file mode 100644 index 00000000000..7d08ee7f9d8 --- /dev/null +++ b/src/renderer/src/components/dashboard/dashboard-card-labels.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from 'vitest' +import type { AgentStatusEntry } from '../../../../shared/agent-status-types' +import { makePaneKey } from '../../../../shared/stable-pane-id' +import type { TerminalLayoutSnapshot, TerminalTab } from '../../../../shared/terminal-tab-types' +import { rowConversationName } from './dashboard-card-labels' +import type { DashboardAgentRow } from './useDashboardData' + +const LEAF_A = '11111111-1111-4111-8111-111111111111' +const LEAF_B = '22222222-2222-4222-8222-222222222222' +const TAB_ID = 'tab-1' +const TAB: TerminalTab = { + id: TAB_ID, + ptyId: 'pty-1', + worktreeId: 'wt-1', + title: '\u2733 Linear work log', + customTitle: null, + aiVaultTitle: { agent: 'claude', sessionId: 'session-a', title: 'Provider title' }, + color: null, + sortOrder: 0, + createdAt: 0 +} +const LAYOUT: TerminalLayoutSnapshot = { + root: { + type: 'split', + direction: 'horizontal', + first: { type: 'leaf', leafId: LEAF_A }, + second: { type: 'leaf', leafId: LEAF_B } + }, + activeLeafId: LEAF_A, + expandedLeafId: null +} + +function row(leafId: string, sessionId: string): DashboardAgentRow { + const paneKey = makePaneKey(TAB_ID, leafId) + const entry: AgentStatusEntry = { + state: 'working', + prompt: '', + updatedAt: 0, + stateStartedAt: 0, + stateHistory: [], + agentType: 'claude', + paneKey, + providerSession: { key: 'session_id', id: sessionId } + } + return { paneKey, entry, tab: TAB, agentType: 'claude', state: 'working', startedAt: 0 } +} + +describe('rowConversationName', () => { + it('publishes a provider title only for the split-pane session that owns it', () => { + const paneTitles = { 1: '\u2733 Linear work log', 2: '\u2733 Redis cache strategy' } + + expect(rowConversationName(row(LEAF_A, 'session-a'), false, LAYOUT, paneTitles)).toBe( + 'Provider title' + ) + expect(rowConversationName(row(LEAF_B, 'session-b'), false, LAYOUT, paneTitles)).toBe( + 'Redis cache strategy' + ) + }) +}) diff --git a/src/renderer/src/components/dashboard/dashboard-card-labels.ts b/src/renderer/src/components/dashboard/dashboard-card-labels.ts index c6ea3a52bec..5c2b66b1d50 100644 --- a/src/renderer/src/components/dashboard/dashboard-card-labels.ts +++ b/src/renderer/src/components/dashboard/dashboard-card-labels.ts @@ -49,7 +49,12 @@ export function rowConversationName( parsePaneKey(row.paneKey)?.leafId ) return ( - getAgentRowConversationName(row.tab, row.agentType, generatedTitlesEnabled, paneLiveTitle) ?? - undefined + getAgentRowConversationName( + row.tab, + row.agentType, + generatedTitlesEnabled, + paneLiveTitle, + row.entry.providerSession?.id + ) ?? undefined ) } diff --git a/src/renderer/src/components/dashboard/use-agent-row-conversation-name.test.ts b/src/renderer/src/components/dashboard/use-agent-row-conversation-name.test.ts index f6aca88795b..dbf5cae455b 100644 --- a/src/renderer/src/components/dashboard/use-agent-row-conversation-name.test.ts +++ b/src/renderer/src/components/dashboard/use-agent-row-conversation-name.test.ts @@ -197,6 +197,24 @@ describe('useAgentRowConversationName', () => { ) }) + it('gives a provider session title only to the pane that owns that session', () => { + setSplitStore('\u2733 Linear work log') + storeState.current.tabsByWorktree['wt-1'][0] = { + id: 'tab-1', + worktreeId: 'wt-1', + customTitle: null, + title: '\u2733 Linear work log', + aiVaultTitle: { agent: 'claude', sessionId: 'session-a', title: 'Provider title' } + } + const sessionA = splitRow(LEAF_A, '\u2733 Linear work log') + sessionA.entry.providerSession = { key: 'session_id', id: 'session-a' } + const sessionB = splitRow(LEAF_B, '\u2733 Linear work log') + sessionB.entry.providerSession = { key: 'session_id', id: 'session-b' } + + expect(useAgentRowConversationName(sessionA)).toBe('Provider title') + expect(useAgentRowConversationName(sessionB)).toBe('Redis cache strategy') + }) + it('does not rename the sibling row when the other pane is clicked', () => { // Clicking pane B re-syncs the tab title to B's; both rows must be unmoved. setSplitStore('\u2733 Redis cache strategy') diff --git a/src/renderer/src/components/dashboard/use-agent-row-conversation-name.ts b/src/renderer/src/components/dashboard/use-agent-row-conversation-name.ts index 692d0cc20f1..6cdb38f2305 100644 --- a/src/renderer/src/components/dashboard/use-agent-row-conversation-name.ts +++ b/src/renderer/src/components/dashboard/use-agent-row-conversation-name.ts @@ -64,6 +64,7 @@ export function useAgentRowConversationName(agent: DashboardAgentRow): string | liveTab ?? agent.tab, agent.agentType, generatedTitlesEnabled, - paneLiveTitle + paneLiveTitle, + agent.entry.providerSession?.id ) } diff --git a/src/renderer/src/components/editor/EditorPanelHeaderPath.tsx b/src/renderer/src/components/editor/EditorPanelHeaderPath.tsx index f1d0ae5e7b6..eaa5db71209 100644 --- a/src/renderer/src/components/editor/EditorPanelHeaderPath.tsx +++ b/src/renderer/src/components/editor/EditorPanelHeaderPath.tsx @@ -20,11 +20,19 @@ const isMac = navigator.userAgent.includes('Mac') const isLinux = navigator.userAgent.includes('Linux') /** Platform-appropriate label: macOS -> Finder, Windows -> File Explorer, Linux -> Files */ -const revealLabel = isMac - ? 'Reveal in Finder' - : isLinux - ? 'Open Containing Folder' - : 'Reveal in File Explorer' +function getRevealLabel(): string { + return isMac + ? translate('auto.components.editor.EditorPanelHeader.revealInFinder', 'Reveal in Finder') + : isLinux + ? translate( + 'auto.components.editor.EditorPanelHeader.openContainingFolder', + 'Open Containing Folder' + ) + : translate( + 'auto.components.editor.EditorPanelHeader.revealInFileExplorer', + 'Reveal in File Explorer' + ) +} type EditorPanelHeaderPathProps = { activeFile: OpenFile @@ -196,7 +204,7 @@ export function EditorPanelHeaderPath({ {!isVirtualEditorTab && ( - {revealLabel} + {getRevealLabel()} )} diff --git a/src/renderer/src/components/editor/MonacoEditor.tsx b/src/renderer/src/components/editor/MonacoEditor.tsx index 27b1c240e82..31c473bf29f 100644 --- a/src/renderer/src/components/editor/MonacoEditor.tsx +++ b/src/renderer/src/components/editor/MonacoEditor.tsx @@ -10,6 +10,7 @@ import { computeEditorFontSize, resolveEditorFontFamily } from '@/lib/editor-fon import { useContextualCopySetup } from './useContextualCopySetup' import { MonacoGutterContextMenu } from './MonacoGutterContextMenu' import { isLinuxUserAgent } from '../terminal-pane/pane-helpers' +import { MAX_TOKENIZATION_LINE_LENGTH } from '@/lib/monaco-languages/monarch-embed-entry-budget' import { buildFileEditorWordWrapOptions } from './file-editor-word-wrap-options' import { getMonacoAutoHeightForContent, isMonacoAutoHeightCapped } from './monaco-auto-height' import { monacoFindOptions } from './monaco-find-options' @@ -235,6 +236,11 @@ export default function MonacoEditor({ onChange={contentSync.handleChange} onMount={handleMount} options={{ + // `IGlobalEditorOptions`, not per-editor: setting it here pins it for every + // Monaco surface (diff, Peek) too, so this is the only site that needs it. + // Defense-in-depth only — it does NOT guard the Monarch embed recursion, + // which overflowed at ~17_000 chars, under this cap. See the budget module. + maxTokenizationLineLength: MAX_TOKENIZATION_LINE_LENGTH, // Why: only the file editor honors this; Monaco 0.55 DiffEditor hard-overrides minimap.enabled=false on sub-editors (see diffEditorEditors._adjustOptionsForSubEditor). minimap: { enabled: settings?.editorMinimapEnabled ?? false }, scrollBeyondLastLine: false, diff --git a/src/renderer/src/components/editor/markdown-round-trip.test.ts b/src/renderer/src/components/editor/markdown-round-trip.test.ts index 3f896f80e38..8804cc06125 100644 --- a/src/renderer/src/components/editor/markdown-round-trip.test.ts +++ b/src/renderer/src/components/editor/markdown-round-trip.test.ts @@ -16,6 +16,10 @@ function roundTripMarkdown(content: string): string { }) try { + // Why: markdown serialization walks the document without running + // NodeType.checkContent, so it emits byte-identical output from a + // schema-invalid document that would crash on the user's next keystroke. + editor.state.doc.check() return editor.getMarkdown().trimEnd() } finally { editor.destroy() @@ -52,6 +56,32 @@ function markdownAfterTextReplace(content: string, search: string, replacement: } } +function markdownAfterTypingBesideImage(content: string, typed: string): string { + const codec = createRichMarkdownEditorCodec() + const editor = new Editor({ + element: null, + extensions: createRichMarkdownExtensions({ codec }), + content: encodeRawMarkdownHtmlForRichEditor(content, codec), + contentType: 'markdown' + }) + + try { + let after = -1 + editor.state.doc.descendants((node, pos) => { + if (after === -1 && node.type.name === 'image') { + after = pos + node.nodeSize + } + }) + if (after === -1) { + throw new Error('Missing image node') + } + editor.view.dispatch(editor.state.tr.insertText(typed, after, after)) + return editor.getMarkdown().trimEnd() + } finally { + editor.destroy() + } +} + function slashCommandMarkdown(commandId: SlashCommandId): string { const codec = createRichMarkdownEditorCodec() const editor = new Editor({ @@ -116,6 +146,28 @@ describe('rich markdown round trip', () => { ) }) + it('preserves an image in a details summary across an edit', () => { + expect( + markdownAfterTextReplace( + '
Toggle ![i](x.png)

Body

\n', + 'Toggle', + 'Switch' + ) + ).toBe( + '
\nSwitch ![i](x.png)\n\nBody\n\n
' + ) + }) + + it('preserves inline math in a details summary across an edit', () => { + expect( + markdownAfterTextReplace( + '
Toggle $x^2$

Body

\n', + 'Toggle', + 'Switch' + ) + ).toBe('
\nSwitch $x^2$\n\nBody\n\n
') + }) + it('does not double-escape entities in editable details summaries', () => { expect(roundTripMarkdown('
A & B

Body

\n')).toBe( '
\nA & B\n\nBody\n\n
' @@ -298,6 +350,42 @@ describe('rich markdown round trip', () => { ) }) + it('preserves an image that sits mid-sentence inside a paragraph', () => { + expect(roundTripMarkdown('Install the ![icon](icon.png) extension\n')).toBe( + 'Install the ![icon](icon.png) extension' + ) + }) + + it('preserves a mid-sentence image after an editor transaction', () => { + expect( + markdownAfterTextReplace('Install the ![icon](icon.png) extension\n', 'extension', 'add-on') + ).toBe('Install the ![icon](icon.png) add-on') + }) + + it('preserves a standalone image as its own block', () => { + expect(roundTripMarkdown('Intro\n\n![shot](shot.png)\n\nOutro\n')).toBe( + 'Intro\n\n![shot](shot.png)\n\nOutro' + ) + // Typing beside the image must join its paragraph instead of opening a new block, + // which only holds while the standalone image stays wrapped in a paragraph. + expect(markdownAfterTypingBesideImage('Intro\n\n![shot](shot.png)\n\nOutro\n', 'X')).toBe( + 'Intro\n\n![shot](shot.png)X\n\nOutro' + ) + }) + + it('preserves images nested in list items and table cells', () => { + expect(roundTripMarkdown('- step ![shot](shot.png)\n')).toBe('- step ![shot](shot.png)') + expect(roundTripMarkdown('| a |\n| - |\n| ![shot](shot.png) |\n')).toContain( + '![shot](shot.png)' + ) + expect(markdownAfterTextReplace('- step ![shot](shot.png)\n', 'step', 'stage')).toBe( + '- stage ![shot](shot.png)' + ) + expect( + markdownAfterTextReplace('| a |\n| - |\n| b ![shot](shot.png) |\n', 'b ', 'c ') + ).toContain('![shot](shot.png)') + }) + it('preserves links whose label is inline code', () => { expect(roundTripMarkdown('Link to [`foo.md`](./foo.md) here\n')).toBe( 'Link to [`foo.md`](./foo.md) here' diff --git a/src/renderer/src/components/editor/rich-markdown-details-extension.ts b/src/renderer/src/components/editor/rich-markdown-details-extension.ts index 151fe512330..1bfcfc09a15 100644 --- a/src/renderer/src/components/editor/rich-markdown-details-extension.ts +++ b/src/renderer/src/components/editor/rich-markdown-details-extension.ts @@ -286,6 +286,13 @@ const OrcaDetails = Details.extend({ } }) +const OrcaDetailsSummary = DetailsSummary.extend({ + // Why: the summary parser runs parseInline, which emits image/math nodes that + // upstream's text*-only summary rejects, so the doc is schema-invalid until the + // first edit reassembles the summary and ProseMirror throws. + content: 'inline*' +}) + const OrcaDetailsContent = DetailsContent.extend({ // Why: detailsContent's double-Enter escape must run before StarterKit's // generic paragraph split, otherwise users can get stuck inside a toggle. @@ -314,7 +321,7 @@ export function createOrcaDetailsExtensions(): AnyExtension[] { class: 'orca-details' } }), - DetailsSummary, + OrcaDetailsSummary, OrcaDetailsContent ] } diff --git a/src/renderer/src/components/editor/rich-markdown-extensions.ts b/src/renderer/src/components/editor/rich-markdown-extensions.ts index 42904291a23..8286c34077c 100644 --- a/src/renderer/src/components/editor/rich-markdown-extensions.ts +++ b/src/renderer/src/components/editor/rich-markdown-extensions.ts @@ -37,6 +37,7 @@ import type { RichMarkdownEditorCodec } from './rich-markdown-source-transport' import { createRichMarkdownHtmlSuperscriptLink } from './rich-markdown-html-superscript-link' import type { RichMarkdownHtmlSuperscriptLinkContext } from './rich-markdown-html-superscript-link-context' import { RichMarkdownOrderedList } from './rich-markdown-ordered-list' +import { RichMarkdownParagraph } from './rich-markdown-paragraph' import { RichMarkdownCodeBlockLowlight } from './rich-markdown-lowlight' import { RichMarkdownTaskList } from './rich-markdown-task-list' import { createCachedLowlight } from './rich-markdown-lowlight-cache' @@ -77,8 +78,10 @@ export function createRichMarkdownExtensions({ link: false, code: false, codeBlock: false, - orderedList: false + orderedList: false, + paragraph: false }), + RichMarkdownParagraph, RichMarkdownCode, RichMarkdownCodeBlockLowlight.extend({ addNodeView() { @@ -116,8 +119,12 @@ export function createRichMarkdownExtensions({ // native image drag (which sends image bytes) from conflicting with // ProseMirror's node-level drag (which serializes the schema node // for relocation within the document). - const dom = document.createElement('div') + const dom = document.createElement('span') + // Why: the wrapper sits in inline content, so it must not introduce a + // block box or the surrounding text would break onto its own line. + dom.style.display = 'inline-block' dom.style.lineHeight = '0' + dom.style.maxWidth = '100%' const img = document.createElement('img') img.draggable = false @@ -205,7 +212,11 @@ export function createRichMarkdownExtensions({ } } }).configure({ - allowBase64: true + allowBase64: true, + // Why: the markdown parser nests images inside paragraphs, so a block image + // node yields a schema-invalid document that only throws on the first edit + // that reassembles the paragraph. + inline: true }), RichMarkdownOrderedList, RichMarkdownTaskList, diff --git a/src/renderer/src/components/editor/rich-markdown-image-insert-code-block.test.ts b/src/renderer/src/components/editor/rich-markdown-image-insert-code-block.test.ts new file mode 100644 index 00000000000..a83de8559f8 --- /dev/null +++ b/src/renderer/src/components/editor/rich-markdown-image-insert-code-block.test.ts @@ -0,0 +1,149 @@ +// @vitest-environment happy-dom + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { Editor } from '@tiptap/core' +import { renderHook } from '@testing-library/react' +import { createRichMarkdownExtensions } from './rich-markdown-extensions' +import { createRichMarkdownEditorCodec } from './rich-markdown-source-transport' +import { useLocalImagePick } from './useLocalImagePick' +import { handleRichMarkdownImagePaste } from './rich-markdown-paste-image' +import { runSlashCommand, slashCommands } from './rich-markdown-slash-commands' + +vi.mock('@/runtime/runtime-file-client', () => ({ + importExternalPathsToRuntime: vi.fn().mockResolvedValue({ + results: [{ status: 'imported', destPath: '/repo/shot.png' }] + }) +})) + +vi.mock('@/lib/connection-context', () => ({ + getConnectionId: vi.fn(() => null) +})) + +vi.mock('@/store', () => ({ + useAppStore: { + getState: vi.fn(() => ({ + settings: { activeRuntimeEnvironmentId: null }, + folderWorkspaces: [], + worktreesByRepo: { repo1: [{ id: 'wt-1', path: '/repo' }] } + })) + } +})) + +vi.mock('@/runtime/runtime-rpc-client', () => ({ + settingsForRuntimeOwner: vi.fn((settings) => settings) +})) + +vi.mock('sonner', () => ({ + toast: { error: vi.fn() } +})) + +const CODE_BLOCK_SOURCE = '```ts\nconst a = 1\n```\n' +// The image splits the fence; both halves keep their ``` fencing and `ts` language. +const SPLIT_CODE_BLOCK = '```ts\nconst\n```\n\n![](shot.png)\n\n```ts\n a = 1\n```' + +function expectFencedSplit(target: Editor): void { + expect(target.getMarkdown().trimEnd()).toBe(SPLIT_CODE_BLOCK) + expect(() => target.state.doc.check()).not.toThrow() +} + +let editor: Editor + +function mountRichMarkdownEditor(markdown: string): Editor { + const host = document.createElement('div') + document.body.appendChild(host) + return new Editor({ + element: host, + extensions: createRichMarkdownExtensions({ codec: createRichMarkdownEditorCodec() }), + content: markdown, + contentType: 'markdown' + }) +} + +function positionInsideCodeBlock(target: Editor): number { + let pos = -1 + target.state.doc.descendants((node, nodePos) => { + if (pos === -1 && node.isText && node.text?.startsWith('const')) { + pos = nodePos + 'const'.length + } + }) + if (pos === -1) { + throw new Error('Missing code block text') + } + return pos +} + +async function flushPromises(): Promise { + for (let index = 0; index < 8; index += 1) { + await Promise.resolve() + } +} + +describe('inserting an image while the cursor is inside a fenced code block', () => { + beforeEach(() => { + document.body.replaceChildren() + vi.clearAllMocks() + editor = mountRichMarkdownEditor(CODE_BLOCK_SOURCE) + editor.commands.setTextSelection(positionInsideCodeBlock(editor)) + globalThis.window.api = { + ...globalThis.window.api, + shell: { pickImage: vi.fn().mockResolvedValue('/tmp/shot.png') }, + ui: { saveClipboardImageAsTempFile: vi.fn().mockResolvedValue('/tmp/shot.png') } + } as unknown as Window['api'] + }) + + afterEach(() => { + editor.destroy() + vi.restoreAllMocks() + }) + + it('keeps both halves fenced when the toolbar picker inserts the image', async () => { + const { result } = renderHook(() => useLocalImagePick(editor as never, '/repo/note.md', 'wt-1')) + + await result.current() + await flushPromises() + + expectFencedSplit(editor) + }) + + it('keeps both halves fenced when the slash command inserts the image', async () => { + const imageCommand = slashCommands.find((command) => command.id === 'image') + expect(imageCommand).toBeDefined() + const { result } = renderHook(() => useLocalImagePick(editor as never, '/repo/note.md', 'wt-1')) + const from = editor.state.selection.from + + runSlashCommand(editor as never, { from, to: from }, imageCommand!, () => { + void result.current() + }) + await flushPromises() + + expectFencedSplit(editor) + }) + + it('keeps both halves fenced when a clipboard screenshot is pasted', async () => { + const handled = handleRichMarkdownImagePaste({ + editor: editor as never, + event: { + clipboardData: { items: [{ kind: 'file', type: 'image/png' }] }, + preventDefault: vi.fn() + } as unknown as ClipboardEvent, + filePath: '/repo/note.md', + worktreeId: 'wt-1' + }) + await flushPromises() + + expect(handled).toBe(true) + expectFencedSplit(editor) + }) + + it('still inserts the image inline when the cursor is in ordinary prose', async () => { + editor.destroy() + editor = mountRichMarkdownEditor('Install the extension\n') + editor.commands.setTextSelection(13) + const { result } = renderHook(() => useLocalImagePick(editor as never, '/repo/note.md', 'wt-1')) + + await result.current() + await flushPromises() + + expect(editor.getMarkdown().trimEnd()).toBe('Install the ![](shot.png)extension') + }) +}) diff --git a/src/renderer/src/components/editor/rich-markdown-image-insert-content.ts b/src/renderer/src/components/editor/rich-markdown-image-insert-content.ts new file mode 100644 index 00000000000..2d0f256bd41 --- /dev/null +++ b/src/renderer/src/components/editor/rich-markdown-image-insert-content.ts @@ -0,0 +1,26 @@ +import type { Editor, JSONContent } from '@tiptap/react' + +/** + * Why: an inline image cannot be fitted into `codeBlock` (`text*`), so inserting one at a + * position inside a fence makes ProseMirror dissolve the block — the remaining code escapes + * as prose and the language attribute is lost. Wrapping the image in a paragraph makes + * ProseMirror split the fence instead, leaving both halves intact. + */ +export function buildRichMarkdownImageInsertContent( + editor: Editor, + pos: number, + attrs: { src: string } +): JSONContent { + const image: JSONContent = { type: 'image', attrs } + const imageType = editor.schema.nodes.image + const doc = editor.state.doc + if (!imageType || pos < 0 || pos > doc.content.size) { + return image + } + const $pos = doc.resolve(pos) + const index = $pos.index() + if ($pos.parent.canReplaceWith(index, index, imageType)) { + return image + } + return { type: 'paragraph', content: [image] } +} diff --git a/src/renderer/src/components/editor/rich-markdown-image-insert.test.ts b/src/renderer/src/components/editor/rich-markdown-image-insert.test.ts index 6eb68d924ad..d9fba294124 100644 --- a/src/renderer/src/components/editor/rich-markdown-image-insert.test.ts +++ b/src/renderer/src/components/editor/rich-markdown-image-insert.test.ts @@ -1,6 +1,11 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' +// @vitest-environment happy-dom + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { Editor } from '@tiptap/core' import { toast } from 'sonner' import { insertRichMarkdownImageFromPath } from './rich-markdown-image-insert' +import { createRichMarkdownExtensions } from './rich-markdown-extensions' +import { createRichMarkdownEditorCodec } from './rich-markdown-source-transport' import { importExternalPathsToRuntime } from '@/runtime/runtime-file-client' vi.mock('@/runtime/runtime-file-client', () => ({ @@ -27,12 +32,28 @@ vi.mock('sonner', () => ({ toast: { error: vi.fn() } })) -function editorWithRunResult(runResult: boolean) { +const openEditors: Editor[] = [] + +function createRichMarkdownEditor(markdown: string): Editor { + const editor = new Editor({ + element: null, + extensions: createRichMarkdownExtensions({ codec: createRichMarkdownEditorCodec() }), + content: markdown, + contentType: 'markdown' + }) + openEditors.push(editor) + return editor +} + +function editorWithRunResult(runResult: boolean, markdown = 'hello world') { const run = vi.fn(() => runResult) const insertContentAt = vi.fn(() => ({ run })) const focus = vi.fn(() => ({ insertContentAt })) const chain = vi.fn(() => ({ focus })) - return { editor: { chain }, chain, focus, insertContentAt, run } + // Why: the insert path reads the real schema and document to decide whether an + // inline image fits at the target position, so the stub borrows both. + const { schema, state } = createRichMarkdownEditor(markdown) + return { editor: { chain, schema, state }, chain, focus, insertContentAt, run } } describe('insertRichMarkdownImageFromPath', () => { @@ -51,6 +72,12 @@ describe('insertRichMarkdownImageFromPath', () => { } as never) }) + afterEach(() => { + while (openEditors.length > 0) { + openEditors.pop()?.destroy() + } + }) + it('shows an error when TipTap rejects image insertion without throwing', async () => { const { editor } = editorWithRunResult(false) diff --git a/src/renderer/src/components/editor/rich-markdown-image-insert.ts b/src/renderer/src/components/editor/rich-markdown-image-insert.ts index 7051502f45c..3c1354a06b6 100644 --- a/src/renderer/src/components/editor/rich-markdown-image-insert.ts +++ b/src/renderer/src/components/editor/rich-markdown-image-insert.ts @@ -10,6 +10,7 @@ import { captureDirectSshMutationExpectation } from '@/lib/ssh-mutation-expectat import { translate } from '@/i18n/i18n' import { parseWorkspaceKey } from '../../../../shared/workspace-scope' import { extractIpcErrorMessage } from './rich-markdown-ipc-error-message' +import { buildRichMarkdownImageInsertContent } from './rich-markdown-image-insert-content' export type RichMarkdownImageInsertArgs = { editor: Editor @@ -88,7 +89,10 @@ export async function insertRichMarkdownImageFromPath({ const inserted = editor .chain() .focus() - .insertContentAt(insertPos, { type: 'image', attrs: { src: imageSrc } }) + .insertContentAt( + insertPos, + buildRichMarkdownImageInsertContent(editor, insertPos, { src: imageSrc }) + ) .run() if (!inserted) { toast.error( diff --git a/src/renderer/src/components/editor/rich-markdown-inline-image-paragraph.test.ts b/src/renderer/src/components/editor/rich-markdown-inline-image-paragraph.test.ts new file mode 100644 index 00000000000..99f35343760 --- /dev/null +++ b/src/renderer/src/components/editor/rich-markdown-inline-image-paragraph.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, it } from 'vitest' +import { Editor } from '@tiptap/core' +import { encodeRawMarkdownHtmlForRichEditor } from './raw-markdown-html' +import { createRichMarkdownExtensions } from './rich-markdown-extensions' +import { createRichMarkdownEditorCodec } from './rich-markdown-source-transport' +import { createRichMarkdownHtmlSuperscriptLinkContext } from './rich-markdown-html-superscript-link-context' + +// Crash report 0e46c048: Vietnamese prose with a soft line break, an inline code +// span and an inline image, which the markdown parser nests inside one paragraph. +const CRASH_SOURCE = + 'Trình duyệt chỉ cho phép cài từ Web Store.\nnh `.crx` (tham chiếu, KHÔNG chặn) ![ảnh](chrome.png) và tiếp tục\n' + +function createRichMarkdownEditorFromSource(source: string): Editor { + const codec = createRichMarkdownEditorCodec() + return new Editor({ + element: null, + extensions: createRichMarkdownExtensions({ + codec, + htmlSuperscriptLinks: true, + htmlSuperscriptLinkContext: createRichMarkdownHtmlSuperscriptLinkContext({ + sourceFilePath: '', + worktreeId: '', + worktreeRoot: null, + sourceOwner: { kind: 'unknown' } + }) + }), + content: encodeRawMarkdownHtmlForRichEditor(source, codec, { htmlSuperscriptLinks: true }), + contentType: 'markdown' + }) +} + +describe('rich markdown inline images inside a paragraph', () => { + it('parses an inline image into a schema-valid paragraph', () => { + const editor = createRichMarkdownEditorFromSource(CRASH_SOURCE) + + try { + expect(() => editor.state.doc.check()).not.toThrow() + } finally { + editor.destroy() + } + }) + + it('survives an ordinary edit in a paragraph that holds an inline image', () => { + const editor = createRichMarkdownEditorFromSource(CRASH_SOURCE) + + try { + // Any ReplaceStep that rebuilds the paragraph runs NodeType.checkContent on + // the reassembled content — the exact frame the crash report bottoms out in. + expect(() => editor.view.dispatch(editor.state.tr.insertText('X', 5, 8))).not.toThrow() + } finally { + editor.destroy() + } + }) + + it('round-trips the reported document without dropping the inline image', () => { + const editor = createRichMarkdownEditorFromSource(CRASH_SOURCE) + + try { + // Why: serialization never runs NodeType.checkContent, so the markdown + // matches byte-for-byte even when the document is schema-invalid. + expect(() => editor.state.doc.check()).not.toThrow() + expect(editor.getMarkdown().trimEnd()).toBe(CRASH_SOURCE.trimEnd()) + } finally { + editor.destroy() + } + }) + + it('keeps a standalone image inside a paragraph rather than directly under the doc', () => { + // Upstream's paragraph parser hoists a lone image out of its paragraph, which + // leaves an inline node as a direct child of `doc` once images are inline. + const editor = createRichMarkdownEditorFromSource('Intro\n\n![shot](shot.png)\n\nOutro\n') + + try { + expect(() => editor.state.doc.check()).not.toThrow() + expect(editor.state.doc.child(1).type.name).toBe('paragraph') + } finally { + editor.destroy() + } + }) + + it('keeps a markdown inline image as an inline node', () => { + const editor = createRichMarkdownEditorFromSource(CRASH_SOURCE) + + try { + const paragraph = editor.state.doc.child(0) + const imageIndex = [...Array(paragraph.childCount).keys()].find( + (index) => paragraph.child(index).type.name === 'image' + ) + expect(imageIndex).toBeDefined() + expect(paragraph.child(imageIndex!).type.isInline).toBe(true) + } finally { + editor.destroy() + } + }) +}) diff --git a/src/renderer/src/components/editor/rich-markdown-local-image.test.ts b/src/renderer/src/components/editor/rich-markdown-local-image.test.ts index bcd4e64c6f1..056fbdd8d33 100644 --- a/src/renderer/src/components/editor/rich-markdown-local-image.test.ts +++ b/src/renderer/src/components/editor/rich-markdown-local-image.test.ts @@ -88,4 +88,23 @@ describe('rich markdown local images', () => { editor.destroy() } }) + + it('renders a mid-sentence image inside its paragraph without a block box', () => { + const host = document.createElement('div') + document.body.appendChild(host) + const editor = new Editor({ + element: host, + extensions: createRichMarkdownExtensions({ codec: createRichMarkdownEditorCodec() }), + content: 'before ![](diagram.png) after', + contentType: 'markdown' + }) + + try { + const img = host.querySelector('p img') + expect(img).not.toBeNull() + expect((img!.parentElement as HTMLElement).style.display).toBe('inline-block') + } finally { + editor.destroy() + } + }) }) diff --git a/src/renderer/src/components/editor/rich-markdown-paragraph.test.ts b/src/renderer/src/components/editor/rich-markdown-paragraph.test.ts new file mode 100644 index 00000000000..d59cb0c4c04 --- /dev/null +++ b/src/renderer/src/components/editor/rich-markdown-paragraph.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it, vi } from 'vitest' +import { RichMarkdownParagraph } from './rich-markdown-paragraph' + +vi.mock('@tiptap/extension-paragraph', async () => { + const actual = (await vi.importActual('@tiptap/extension-paragraph')) as { + Paragraph: { extend: (config: object) => { config: Record } } + } + // Simulates a Tiptap upgrade that drops `parseMarkdown` from the upstream paragraph. + const Paragraph = actual.Paragraph.extend({}) + Paragraph.config.parseMarkdown = undefined + return { ...actual, Paragraph } +}) + +describe('RichMarkdownParagraph without an upstream markdown parser', () => { + it('parses paragraphs through parseInline instead of throwing', () => { + const parseInline = vi.fn(() => [{ type: 'text', text: 'Install the extension' }]) + const createNode = vi.fn((type: string, attrs: unknown, content: unknown) => ({ + type, + attrs, + content + })) + const parseMarkdown = RichMarkdownParagraph.config.parseMarkdown as ( + token: unknown, + helpers: unknown + ) => unknown + const token = { type: 'paragraph', tokens: [{ type: 'text' }, { type: 'image' }] } + + expect(() => parseMarkdown(token, { createNode, parseInline })).not.toThrow() + expect(createNode).toHaveBeenCalledWith('paragraph', undefined, [ + { type: 'text', text: 'Install the extension' } + ]) + }) +}) diff --git a/src/renderer/src/components/editor/rich-markdown-paragraph.ts b/src/renderer/src/components/editor/rich-markdown-paragraph.ts new file mode 100644 index 00000000000..ad3fa4f1a1e --- /dev/null +++ b/src/renderer/src/components/editor/rich-markdown-paragraph.ts @@ -0,0 +1,23 @@ +import type { MarkdownParseHelpers, MarkdownParseResult, MarkdownToken } from '@tiptap/core' +import { Paragraph } from '@tiptap/extension-paragraph' + +type ParagraphMarkdownParser = ( + token: MarkdownToken, + helpers: MarkdownParseHelpers +) => MarkdownParseResult + +const baseParseMarkdown = Paragraph.config.parseMarkdown as ParagraphMarkdownParser | undefined + +export const RichMarkdownParagraph = Paragraph.extend({ + parseMarkdown: (token, helpers) => { + const tokens = token.tokens ?? [] + // Why: upstream hoists a lone image out of its paragraph, which produces an + // inline image node directly under `doc` now that images are inline nodes. + // The missing-base fallback keeps a Tiptap upgrade that drops the field from + // turning every paragraph parse into a TypeError. + if (!baseParseMarkdown || (tokens.length === 1 && tokens[0]?.type === 'image')) { + return helpers.createNode('paragraph', undefined, helpers.parseInline(tokens)) + } + return baseParseMarkdown(token, helpers) + } +}) diff --git a/src/renderer/src/components/github/use-image-input.test.ts b/src/renderer/src/components/github/use-image-input.test.ts new file mode 100644 index 00000000000..06a059d569e --- /dev/null +++ b/src/renderer/src/components/github/use-image-input.test.ts @@ -0,0 +1,71 @@ +// @vitest-environment happy-dom + +import { afterEach, describe, expect, it, vi } from 'vitest' +import { Editor } from '@tiptap/core' +import { act, renderHook } from '@testing-library/react' +import { createRichMarkdownExtensions } from '@/components/editor/rich-markdown-extensions' +import { createRichMarkdownEditorCodec } from '@/components/editor/rich-markdown-source-transport' +import { useImageInput } from './use-image-input' + +vi.mock('sonner', () => ({ + toast: { error: vi.fn() } +})) + +let editor: Editor | null = null + +function mountComposerEditor(markdown: string): Editor { + const host = document.createElement('div') + document.body.appendChild(host) + editor = new Editor({ + element: host, + extensions: createRichMarkdownExtensions({ codec: createRichMarkdownEditorCodec() }), + content: markdown, + contentType: 'markdown' + }) + return editor +} + +function renderImageInput(target: Editor) { + return renderHook(() => useImageInput({ current: target } as never, { current: false })) +} + +describe('useImageInput', () => { + afterEach(() => { + editor?.destroy() + editor = null + document.body.replaceChildren() + }) + + it('splits a fenced code block instead of dissolving it when inserting an image URL', () => { + const target = mountComposerEditor('```ts\nconst a = 1\n```\n') + let pos = -1 + target.state.doc.descendants((node, nodePos) => { + if (pos === -1 && node.isText && node.text?.startsWith('const')) { + pos = nodePos + 'const'.length + } + }) + target.commands.setTextSelection(pos) + const { result } = renderImageInput(target) + + act(() => result.current.setImageUrl('https://example.com/shot.png')) + act(() => result.current.insertImageUrl()) + + expect(target.getMarkdown().trimEnd()).toBe( + '```ts\nconst\n```\n\n![](https://example.com/shot.png)\n\n```ts\n a = 1\n```' + ) + expect(() => target.state.doc.check()).not.toThrow() + }) + + it('keeps an image URL inline when the cursor is in ordinary prose', () => { + const target = mountComposerEditor('Install the extension\n') + target.commands.setTextSelection(13) + const { result } = renderImageInput(target) + + act(() => result.current.setImageUrl('https://example.com/shot.png')) + act(() => result.current.insertImageUrl()) + + expect(target.getMarkdown().trimEnd()).toBe( + 'Install the ![](https://example.com/shot.png)extension' + ) + }) +}) diff --git a/src/renderer/src/components/github/use-image-input.ts b/src/renderer/src/components/github/use-image-input.ts index 30569ba084f..8decc6e9557 100644 --- a/src/renderer/src/components/github/use-image-input.ts +++ b/src/renderer/src/components/github/use-image-input.ts @@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react' import { toast } from 'sonner' import type { Editor } from '@tiptap/react' import { getGitHubMarkdownImageUrlState } from './github-markdown-image-url' +import { buildRichMarkdownImageInsertContent } from '@/components/editor/rich-markdown-image-insert-content' import { translate } from '@/i18n/i18n' export function useImageInput( @@ -54,7 +55,11 @@ export function useImageInput( editor .chain() .focus() - .insertContent({ type: 'image', attrs: { src: imageUrlState.url } }) + .insertContent( + buildRichMarkdownImageInsertContent(editor, editor.state.selection.from, { + src: imageUrlState.url + }) + ) .run() setImageUrl('') setImageInputOpen(false) diff --git a/src/renderer/src/components/native-chat/NativeChatAutocompleteMenus.test.tsx b/src/renderer/src/components/native-chat/NativeChatAutocompleteMenus.test.tsx index 88506c51838..60c70baee66 100644 --- a/src/renderer/src/components/native-chat/NativeChatAutocompleteMenus.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatAutocompleteMenus.test.tsx @@ -3,6 +3,8 @@ import { cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' import { NativeChatPickerMenu } from './NativeChatAutocompleteMenus' +import { buildNativeChatPickerItems } from './native-chat-picker-items' +import { sessionSlashCommandSuggestions } from '../../../../shared/native-chat-slash-commands' import type { ComposerAutocomplete } from './native-chat-composer-state' function autocomplete( @@ -128,6 +130,45 @@ describe('NativeChatPickerMenu', () => { expect(screen.getAllByText('No matching commands')).toHaveLength(2) }) + it('shows the argument hint the provider reported beside the command token', () => { + render( + ' + }, + { name: 'clear', kind: 'command' }, + { name: 'wordy', kind: 'command', argumentHint: `<${'a'.repeat(200)}>` } + ]), + [], + '', + '/' + ) + })} + activeIndex={0} + listboxId="picker" + onChoose={vi.fn()} + onRetry={vi.fn()} + /> + ) + const goal = screen.getByRole('option', { name: /goal/i }) + expect(goal.textContent).toContain('') + expect(goal.textContent).toContain('Set a goal and keep working until it is met') + // A command the report left hintless renders its row unchanged. + expect(screen.getByRole('option', { name: /clear/i }).textContent).toBe( + '/clearClear conversation history' + ) + // A hint long enough to swamp the row is capped before it reaches the DOM. + expect(screen.getByRole('option', { name: /wordy/i }).textContent).toBe( + `/wordy<${'a'.repeat(79)}` + ) + }) + it('announces a successful empty skill result distinctly from loading', () => { render( ) : null} - {item.token} + + {item.token} + {item.kind === 'command' && item.argumentHint ? ( + + {item.argumentHint} + + ) : null} + {item.description ? ( {item.description} ) : null} diff --git a/src/renderer/src/components/native-chat/NativeChatComposer.test.tsx b/src/renderer/src/components/native-chat/NativeChatComposer.test.tsx index 45d95140f9e..055230c1a4e 100644 --- a/src/renderer/src/components/native-chat/NativeChatComposer.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatComposer.test.tsx @@ -306,12 +306,14 @@ describe('NativeChatComposer', () => { expect(mocks.setDraft).toHaveBeenCalledWith('') }) - // The structured menu offers only what the dispatcher can carry out. Listing the - // agent's TUI catalog here answered every pick with "not available in chat sessions". + // The structured menu offers only what a pick can carry out: the host's own + // commands, plus the ones the agent itself runs from message text (Codex `/goal`). + // Listing the agent's whole TUI catalog here answered every pick with + // "not available in chat sessions". it.each([ - ['claude', 'compact'], - ['codex', 'vim'] - ] as const)('offers %s only actionable structured slash commands', (agent, withheld) => { + ['claude', 'compact', ['model', 'effort']], + ['codex', 'vim', ['model', 'effort', 'goal']] + ] as const)('offers %s only actionable structured slash commands', (agent, withheld, offered) => { mocks.draft = '/' render( { const names = (mocks.fieldProps?.autocomplete?.items ?? []) .filter((item) => item.kind === 'command') .map((item) => item.name) - expect(names).toEqual(['model', 'effort']) + expect(names).toEqual([...offered]) expect(names).not.toContain(withheld) }) diff --git a/src/renderer/src/components/native-chat/NativeChatDiffCard.tsx b/src/renderer/src/components/native-chat/NativeChatDiffCard.tsx index a69ae1252f1..91d113f15e0 100644 --- a/src/renderer/src/components/native-chat/NativeChatDiffCard.tsx +++ b/src/renderer/src/components/native-chat/NativeChatDiffCard.tsx @@ -1,4 +1,5 @@ -import { useLayoutEffect, useMemo, useRef, useState } from 'react' +import { useLayoutEffect, useMemo, useRef } from 'react' +import { useNativeChatDisclosure } from './native-chat-disclosure-store' import { ChevronRight, FilePlus2, FileMinus2, FilePen } from 'lucide-react' import { cn } from '@/lib/utils' import { translate } from '@/i18n/i18n' @@ -113,21 +114,29 @@ export function NativeChatDiffCard({ file, revealSignal, onReveal, - initiallyExpanded = false + initiallyExpanded = false, + disclosureKey }: { file: NativeChatEditFile revealSignal?: number onReveal?: (element: HTMLElement) => void initiallyExpanded?: boolean + /** Identity this card's open state is remembered under while it is unmounted. */ + disclosureKey?: string }): React.JSX.Element { - const [expanded, setExpanded] = useState(initiallyExpanded) + const { open: expanded, setOpen: setExpanded } = useNativeChatDisclosure( + disclosureKey, + initiallyExpanded + ) const cardRef = useRef(null) useLayoutEffect(() => { if (revealSignal && cardRef.current) { setExpanded(true) + // Reported from the card, not the row: a turn that touched four files must + // land on the one that was asked for, and only the card knows where it is. onReveal?.(cardRef.current) } - }, [revealSignal, onReveal]) + }, [revealSignal, onReveal, setExpanded]) // Joining every row to seed the copy button is the card's most expensive // work, and a collapsed card renders none of those rows. const copyText = useMemo(() => patchText(file.lines), [file.lines]) @@ -141,7 +150,7 @@ export function NativeChatDiffCard({
+
+
+ {hasMore ? ( +
+ +
+ ) : null} + + {showTurnStatus && isWorking ? ( + + ) : null} + {!showTurnStatus && showTypingIndicator ? : null}
- ) : null} - {messages.map((message, index) => { - const turnKey = turnKeys[index] - const isCurrentTurn = currentTurnKey - ? turnKey === currentTurnKey - : turnKey === undefined - const status = - index === latestUserIndex - ? turnStatuses.active - : message.role === 'user' && turnKey - ? turnStatuses.completedByTurn[turnKey] - : undefined - const receipt = receipts.get(message.id) - const turnDiff = - turnKey && turnKeys[index + 1] !== turnKey ? turnDiffs.get(turnKey) : undefined - return ( - - {receipt ? ( - - ) : ( - - )} - {showTurnStatus && - status && - (index !== latestUserIndex || showTypingIndicator || !isWorking) ? ( - toggleExpandedTurn(turnKey) - : undefined - } - /> - ) : null} - {turnDiff ? ( - - ) : null} - - ) - })} - {showTurnStatus && - latestUserIndex === -1 && - turnStatuses.active && - showTypingIndicator ? ( - - ) : null} - {showTurnStatus && isWorking ? ( - - ) : null} - {!showTurnStatus && showTypingIndicator ? : null} +
+ {showJump ? ( + + ) : null}
- {showJump ? ( - + {taskListState.list && taskListState.list.tasks.length > 0 ? ( +
+
+ +
+
) : null}
- {taskListState.list && taskListState.list.tasks.length > 0 ? ( -
-
- -
-
- ) : null} -
+ ) } diff --git a/src/renderer/src/components/native-chat/NativeChatMessageList.turn-history.test.tsx b/src/renderer/src/components/native-chat/NativeChatMessageList.turn-history.test.tsx index 628d78b4c58..6447dfcbec0 100644 --- a/src/renderer/src/components/native-chat/NativeChatMessageList.turn-history.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatMessageList.turn-history.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment happy-dom import '@testing-library/jest-dom/vitest' import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' import type { AgentJournalItemBody, AgentJournalRenderItem @@ -9,8 +9,14 @@ import type { import { projectStructuredItemsToNativeChat } from '../../../../shared/structured-agent-session-projection' import { NativeChatMessageList } from './NativeChatMessageList' import type { NativeChatLiveSession } from './use-native-chat-live-session' +import { installNativeChatMessageListTestViewport } from './native-chat-message-list-test-viewport' const scrollTo = vi.fn() +let restoreViewport = (): void => {} +beforeAll(() => { + restoreViewport = installNativeChatMessageListTestViewport() +}) +afterAll(() => restoreViewport()) afterEach(() => { cleanup() vi.restoreAllMocks() diff --git a/src/renderer/src/components/native-chat/NativeChatMessageList.turn-indicator.test.tsx b/src/renderer/src/components/native-chat/NativeChatMessageList.turn-indicator.test.tsx new file mode 100644 index 00000000000..ab706436f91 --- /dev/null +++ b/src/renderer/src/components/native-chat/NativeChatMessageList.turn-indicator.test.tsx @@ -0,0 +1,563 @@ +// @vitest-environment happy-dom + +import '@testing-library/jest-dom/vitest' + +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' +import type { NativeChatLiveSession } from './use-native-chat-live-session' +import { NativeChatMessageList } from './NativeChatMessageList' +import { installNativeChatMessageListTestViewport } from './native-chat-message-list-test-viewport' +import type { + AgentJournalItemBody, + AgentJournalRenderItem +} from '../../../../shared/agent-session-journal-types' + +// The turn record this host writes, and the legacy status row an older host sends. +const turnItem: AgentJournalItemBody = { kind: 'turn', turnId: 'turn-1', state: 'running' } +const legacyTurnRow: AgentJournalItemBody = { + kind: 'status', + text: 'Codex is working…', + turnLifecycle: { turnId: 'turn-1', state: 'running' } +} +const reasoningRow: AgentJournalItemBody = { + kind: 'message', + role: 'reasoning', + blocks: [{ type: 'text', text: '' }] +} + +function journalItem(sequence: number, body: AgentJournalItemBody): AgentJournalRenderItem { + return { itemId: `item-${sequence}`, revision: 1, sequence, observedAt: sequence, body } +} + +let restoreViewport = (): void => {} +beforeAll(() => { + restoreViewport = installNativeChatMessageListTestViewport() +}) +afterAll(() => restoreViewport()) +afterEach(cleanup) + +const session: NativeChatLiveSession = { + messages: [ + { + id: 'assistant-1', + role: 'assistant', + blocks: [{ type: 'text', text: 'Selectable agent response.' }], + timestamp: 1, + source: 'transcript' + } + ], + status: 'ready', + sessionId: 'session-1', + agent: 'codex', + hasMore: false, + loadingEarlier: false, + loadEarlier: vi.fn(), + readPhase: 'ready' +} + +// The live turn renders exactly one indicator row; a settled turn keeps its own. +describe('NativeChatMessageList turn indicator', () => { + it('keeps a reduced-motion-safe spinner on the live row of a no-tool Codex turn', () => { + render( + + ) + + const activity = screen.getByText('Working for 0s') + const row = activity.closest('[data-native-chat-turn-activity]') + const spinner = row?.querySelector('svg') + expect(activity).not.toHaveClass('animate-pulse', 'animate-spin') + expect(spinner).toHaveClass('size-4', 'animate-spin', 'motion-reduce:animate-none') + expect(row).toHaveAttribute('aria-live', 'polite') + expect(screen.getByText('The answer is still streaming.').compareDocumentPosition(row!)).toBe( + Node.DOCUMENT_POSITION_FOLLOWING + ) + }) + + it('keeps the live row distinct from the running tool row', () => { + render( + + ) + + const toolLabel = screen.getByText('Running pnpm test') + expect(toolLabel).toHaveClass('animate-pulse') + expect(screen.getAllByText('Running pnpm test')).toHaveLength(1) + const activity = screen.getByText('Working for 0s') + expect(activity.textContent).not.toBe(toolLabel.textContent) + expect(activity).not.toHaveTextContent('shell') + expect(activity).not.toHaveTextContent('pnpm test') + const spinner = activity.closest('[data-native-chat-turn-activity]')?.querySelector('svg') + expect(activity).not.toHaveClass('animate-pulse', 'animate-spin') + expect(spinner).toHaveClass('animate-spin', 'motion-reduce:animate-none') + }) + + it('keeps the live row up after a tool settles', () => { + render( + + ) + + const settledTool = screen.getByText('shell') + const activity = screen.getByText('Working for 0s') + expect(activity.textContent).not.toBe(settledTool.textContent) + expect(activity).not.toHaveTextContent('shell') + expect(activity).not.toHaveTextContent('pnpm test') + expect(activity).not.toHaveClass('animate-pulse', 'animate-spin') + expect(activity.closest('[data-native-chat-turn-activity]')?.querySelector('svg')).toHaveClass( + 'animate-spin' + ) + }) + + it('keeps a completed tool row static while the turn tail spins, then removes the tail', () => { + const workingSession: NativeChatLiveSession = { + ...session, + status: 'working', + messages: [ + { + id: 'assistant-settled-tool', + role: 'assistant', + blocks: [ + { + type: 'tool-call', + name: 'shell', + input: { command: 'pnpm test' }, + state: 'completed' + }, + { type: 'tool-result', output: 'passed' } + ], + timestamp: 1, + source: 'transcript' + } + ] + } + const { container, rerender } = render( + + ) + + const settledTool = screen.getByText('shell') + expect(settledTool).toHaveTextContent('shell pnpm test') + expect(settledTool.closest('button')?.querySelector('.animate-pulse')).toBeNull() + expect(settledTool.closest('button')?.querySelector('.lucide-check')).toBeInTheDocument() + const activity = screen.getByText('Preparing the answer') + expect(activity).not.toHaveClass('animate-pulse', 'animate-spin') + expect(activity.closest('[data-native-chat-turn-activity]')?.querySelector('svg')).toHaveClass( + 'animate-spin' + ) + + rerender( + + ) + + expect(container.querySelector('[data-native-chat-turn-activity]')).toBeNull() + expect(container.querySelector('.animate-pulse')).toBeNull() + expect(container.querySelector('.animate-spin')).toBeNull() + }) + + it('keeps bridge chats on the legacy activity chrome', () => { + render( + + ) + + expect(screen.queryByText('Thinking')).toBeNull() + expect(screen.queryByRole('button', { name: 'Toggle turn details' })).toBeNull() + expect(screen.queryByText('Running sleep 5')).toBeNull() + expect(document.querySelectorAll('.animate-bounce')).toHaveLength(3) + }) + + it('reads "Thinking" on the one live row while the turn is reasoning', () => { + const { container } = render( + + ) + + const user = screen.getByText('Start the task') + const thinking = screen.getByText('Thinking') + expect(user.compareDocumentPosition(thinking)).toBe(Node.DOCUMENT_POSITION_FOLLOWING) + // One indicator, not a "Thinking" row stacked above a spinning "Working…" row. + expect(container.querySelectorAll('[data-native-chat-turn-status]')).toHaveLength(1) + expect(thinking.closest('[data-native-chat-turn-activity]')?.querySelector('svg')).toHaveClass( + 'animate-spin' + ) + expect(container.querySelector('.animate-bounce')).toBeNull() + }) + + it('does not reuse completed-turn reasoning while the next dispatch is pending', () => { + render( + + ) + + expect(screen.queryByText('Thinking')).toBeNull() + expect(screen.getByText('Working for 0s')).toBeInTheDocument() + }) + + it('lets provider activity text beat the reasoning label on the same single row', () => { + const { container } = render( + + ) + + expect(screen.getByText('Exploring the repo layout')).toBeInTheDocument() + expect(screen.queryByText('Thinking')).toBeNull() + expect(container.querySelectorAll('[data-native-chat-turn-status]')).toHaveLength(1) + }) + + it('places the one live row after the newest content in the turn', () => { + render( + + ) + + const status = screen.getByText('Working for 0s') + const assistant = screen.getByText('I am checking now.') + // The live row trails the newest content instead of sitting under the prompt. + expect(assistant.compareDocumentPosition(status)).toBe(Node.DOCUMENT_POSITION_FOLLOWING) + expect(document.querySelectorAll('[data-native-chat-turn-status]')).toHaveLength(1) + }) + + it('shows elapsed working time once tool activity starts', () => { + render( + + ) + + expect(screen.getByText('Working for 3s')).toBeInTheDocument() + }) + + it('keeps the completed duration below the user message', () => { + const startedAt = Date.now() - 3000 + const turnSession: NativeChatLiveSession = { + ...session, + status: 'working', + messages: [ + { + id: 'user-complete', + role: 'user', + blocks: [{ type: 'text', text: 'Complete this task' }], + timestamp: startedAt, + source: 'transcript' + }, + { + id: 'assistant-complete', + role: 'assistant', + blocks: [{ type: 'text', text: 'Task complete.' }], + timestamp: Date.now(), + source: 'transcript' + } + ] + } + const { rerender } = render( + + ) + + rerender( + + ) + + const user = screen.getByText('Complete this task') + const status = screen.getByText('Worked for 3s') + const assistant = screen.getByText('Task complete.') + expect(user.compareDocumentPosition(status)).toBe(Node.DOCUMENT_POSITION_FOLLOWING) + expect(status.compareDocumentPosition(assistant)).toBe(Node.DOCUMENT_POSITION_FOLLOWING) + + rerender( + + ) + + expect(screen.getByText('Worked for 3s')).toBeInTheDocument() + expect(screen.getByText('Working for 0s')).toBeInTheDocument() + }) + + it("uses the completed caret to expand that turn's tool details", () => { + const startedAt = Date.now() - 3000 + render( + + ) + + const status = screen.getByRole('button', { name: 'Toggle turn details' }) + expect(status).toHaveAttribute('aria-expanded', 'false') + expect(screen.queryByRole('button', { name: /1× shell/ })).toBeNull() + fireEvent.click(status) + expect(status).toHaveAttribute('aria-expanded', 'true') + const tool = screen.getByRole('button', { name: /1× shell/ }) + expect(tool).toHaveAttribute('aria-expanded', 'true') + expect(screen.getAllByRole('button', { name: /shell pwd/ })[1]).toHaveAttribute( + 'aria-expanded', + 'false' + ) + }) +}) diff --git a/src/renderer/src/components/native-chat/NativeChatMessageList.turn-timing.test.tsx b/src/renderer/src/components/native-chat/NativeChatMessageList.turn-timing.test.tsx index 022750d83cc..2eacc13ed07 100644 --- a/src/renderer/src/components/native-chat/NativeChatMessageList.turn-timing.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatMessageList.turn-timing.test.tsx @@ -3,12 +3,21 @@ import '@testing-library/jest-dom/vitest' import { cleanup, render, screen } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' import type { NativeChatLiveSession } from './use-native-chat-live-session' import { NativeChatMessageList } from './NativeChatMessageList' +import { installNativeChatMessageListTestViewport } from './native-chat-message-list-test-viewport' afterEach(cleanup) +let restoreViewport = (): void => {} + +beforeAll(() => { + restoreViewport = installNativeChatMessageListTestViewport() +}) + +afterAll(() => restoreViewport()) + const session: NativeChatLiveSession = { messages: [ { diff --git a/src/renderer/src/components/native-chat/NativeChatMessageList.windowing.test.tsx b/src/renderer/src/components/native-chat/NativeChatMessageList.windowing.test.tsx new file mode 100644 index 00000000000..c4de79ceeed --- /dev/null +++ b/src/renderer/src/components/native-chat/NativeChatMessageList.windowing.test.tsx @@ -0,0 +1,640 @@ +// @vitest-environment happy-dom + +import '@testing-library/jest-dom/vitest' + +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { + AgentJournalItemBody, + AgentJournalRenderItem +} from '../../../../shared/agent-session-journal-types' +import { projectStructuredItemsToNativeChat } from '../../../../shared/structured-agent-session-projection' +import type { NativeChatMessage } from '../../../../shared/native-chat-types' +import type { NativeChatLiveSession } from './use-native-chat-live-session' +import { NativeChatMessageList } from './NativeChatMessageList' +import { NATIVE_CHAT_BOTTOM_THRESHOLD_PX } from './native-chat-autoscroll' +import { + estimateNativeChatRowHeight, + NATIVE_CHAT_ROW_GAP_PX, + nativeChatRowContentMetrics +} from './native-chat-row-height-estimate' + +afterEach(cleanup) + +const VIEWPORT_PX = 600 +const TRANSCRIPT_LENGTH = 200 + +/** Everything the document holds below the last row: the transcript column's + * trailing chrome and the scroll root's bottom padding. Non-zero on purpose — + * the document's bottom sits past the window's last row, which is exactly where + * a pin computed from the virtualizer's totals and one computed from the + * document disagree. */ +const BELOW_TRANSCRIPT_PX = 24 + +/** Heights the stubbed layout reports per row index, when a case wants a row to + * measure as something other than its estimate. Empty means "every row at its + * estimate", which is what every non-growth case wants. */ +let measuredRowHeights: readonly number[] = [] + +function marker(index: number): NativeChatMessage { + return { + id: `message-${index}`, + role: 'assistant', + blocks: [{ type: 'text', text: `marker-${index}` }], + timestamp: index + 1, + source: 'transcript' + } +} + +const ROW_PX = estimateNativeChatRowHeight(nativeChatRowContentMetrics(marker(0)), { + hasReceipt: false, + hasStatus: false, + hasTurnDiff: false +}) +const ROW_PITCH_PX = ROW_PX + NATIVE_CHAT_ROW_GAP_PX + +/** Replace a layout property on every element, and hand back the undo. */ +function overrideLayoutProperty(name: string, descriptor: PropertyDescriptor): () => void { + const original = Object.getOwnPropertyDescriptor(HTMLElement.prototype, name) + Object.defineProperty(HTMLElement.prototype, name, { configurable: true, ...descriptor }) + return () => { + if (original) { + Object.defineProperty(HTMLElement.prototype, name, original) + } else { + Reflect.deleteProperty(HTMLElement.prototype, name) + } + } +} + +/** The spacer's reserved height, which is the transcript's whole rendered height: + * windowed rows are absolutely positioned inside it, so a row growing in place + * reaches the document only through the height the window reserves for it. */ +function reservedTranscriptHeight(root: ParentNode): number { + const spacer = root.querySelector('[data-native-chat-window]') + return spacer ? Number.parseFloat(spacer.style.height) || 0 : 0 +} + +// The virtualizer measures with `offsetHeight` — not `clientHeight`, not a +// bounding rect — so that is the one thing a DOM without layout has to answer +// for windowing to engage at all. Rows report the height their own estimate +// predicted, which keeps the totals exact and independent of which rows happen +// to have been mounted long enough to be measured; `measuredRowHeights` is how a +// case says a row measures as something else. +// +// `scrollGeometry` additionally gives the scroll root a document to scroll: a +// height, a viewport, and a `scrollTop` that clamps the way a real one does. +// Off by default, because a transcript with a real document opens pinned to its +// bottom and the cases above are about where the window sits, not where it lands. +function stubLayout({ + scrollGeometry = false, + viewportHeight = () => VIEWPORT_PX +}: { + scrollGeometry?: boolean + viewportHeight?: () => number +} = {}): () => void { + const scrollTops = new WeakMap() + const restores = [ + overrideLayoutProperty('offsetHeight', { + get(this: HTMLElement): number { + if (this.hasAttribute('data-native-chat-scroll')) { + return viewportHeight() + } + if (this.hasAttribute('data-native-chat-window')) { + return reservedTranscriptHeight(this.parentElement ?? this) + } + const index = this.dataset.index + if (index !== undefined) { + return measuredRowHeights[Number(index)] ?? ROW_PX + } + // The transcript column: as tall as the window it wraps, plus what sits + // under it. This is the element the list observes for streamed growth. + return this.classList.contains('max-w-4xl') + ? reservedTranscriptHeight(this) + BELOW_TRANSCRIPT_PX + : 0 + } + }) + ] + if (scrollGeometry) { + restores.push( + overrideLayoutProperty('clientHeight', { + get(this: HTMLElement): number { + return this.hasAttribute('data-native-chat-scroll') ? viewportHeight() : 0 + } + }), + overrideLayoutProperty('scrollHeight', { + get(this: HTMLElement): number { + return this.hasAttribute('data-native-chat-scroll') + ? reservedTranscriptHeight(this) + BELOW_TRANSCRIPT_PX + : 0 + } + }), + overrideLayoutProperty('scrollTop', { + get(this: HTMLElement): number { + return scrollTops.get(this) ?? 0 + }, + set(this: HTMLElement, value: number): void { + // A browser clamps; without this `scrollTop = scrollHeight` would park + // the view past the end and every distance-from-bottom would read 0. + const max = Math.max(0, this.scrollHeight - this.clientHeight) + scrollTops.set(this, Math.min(Math.max(0, value), max)) + } + }) + ) + } + return () => { + for (const restore of restores.toReversed()) { + restore() + } + } +} + +type FakeResizeObservation = { + callback: ResizeObserverCallback + /** Target -> height last delivered. -1 means "never", so the first flush + * delivers, the way a real observer's initial callback does. */ + observed: Map +} + +const resizeObservations = new Set() + +/** happy-dom's ResizeObserver never fires, so nothing that re-measures ever runs. + * This one records what production observes and delivers only when a target's + * height actually changed — the browser's own rule — and only when a test says + * a frame was painted. Entries carry no `borderBoxSize`, so the virtualizer + * falls back to `offsetHeight`, which is the path being modelled. */ +function stubResizeObserver(): () => void { + const original = window.ResizeObserver + class TestResizeObserver { + private readonly observation: FakeResizeObservation + constructor(callback: ResizeObserverCallback) { + this.observation = { callback, observed: new Map() } + resizeObservations.add(this.observation) + } + observe(target: Element): void { + this.observation.observed.set(target, -1) + } + unobserve(target: Element): void { + this.observation.observed.delete(target) + } + disconnect(): void { + this.observation.observed.clear() + resizeObservations.delete(this.observation) + } + } + window.ResizeObserver = TestResizeObserver as unknown as typeof ResizeObserver + return () => { + resizeObservations.clear() + window.ResizeObserver = original + } +} + +/** Deliver one round of resize callbacks; true when anything was delivered. */ +function deliverResizes(): boolean { + let delivered = false + // A copy: a callback may disconnect its own observer mid-delivery. + for (const observation of Array.from(resizeObservations)) { + const entries: ResizeObserverEntry[] = [] + for (const [target, lastHeight] of observation.observed) { + const height = (target as HTMLElement).offsetHeight + if (height !== lastHeight) { + observation.observed.set(target, height) + entries.push({ target } as unknown as ResizeObserverEntry) + } + } + if (entries.length > 0) { + delivered = true + observation.callback(entries, undefined as unknown as ResizeObserver) + } + } + return delivered +} + +function session(messages: NativeChatMessage[]): NativeChatLiveSession { + return { + messages, + status: 'ready', + sessionId: 'session-1', + agent: 'codex', + hasMore: false, + loadingEarlier: false, + loadEarlier: vi.fn(), + readPhase: 'ready' + } +} + +function list(messages: NativeChatMessage[]): React.JSX.Element { + return ( + + ) +} + +/** Reads the window, and refuses to pass if there is no window to read. + * + * Without this a change to the usability gate would quietly send every case + * below down the whole-transcript path, where "fewer rows than messages" is + * false but every other assertion still holds. */ +function windowState(container: HTMLElement): { totalSize: number; indexes: number[] } { + const spacer = container.querySelector('[data-native-chat-window]') + if (!spacer) { + throw new Error('transcript is not windowed: no spacer, every row is mounted') + } + const totalSize = Number.parseFloat(spacer.style.height) + if (!(totalSize > 0)) { + throw new Error(`transcript reserved no height (${spacer.style.height})`) + } + return { + totalSize, + indexes: Array.from(container.querySelectorAll('[data-index]')) + .map((row) => Number(row.dataset.index)) + .sort((left, right) => left - right) + } +} + +/** happy-dom fires no scroll event for an assignment to `scrollTop`. */ +function scrollTranscript(container: HTMLElement, top: number): void { + const scroller = container.querySelector('[data-native-chat-scroll]') + if (!scroller) { + throw new Error('no transcript scroll root') + } + scroller.scrollTop = top + fireEvent.scroll(scroller) +} + +describe('windowed transcript', () => { + let restoreLayout = (): void => {} + beforeEach(() => { + restoreLayout = stubLayout() + }) + afterEach(() => { + restoreLayout() + }) + + const transcript = Array.from({ length: TRANSCRIPT_LENGTH }, (_, index) => marker(index)) + + it('mounts a window over the transcript rather than all of it', () => { + const { container } = render(list(transcript)) + const { indexes } = windowState(container) + + expect(indexes.length).toBeGreaterThan(0) + expect(indexes.length).toBeLessThan(TRANSCRIPT_LENGTH / 4) + expect(indexes).toContain(0) + expect(screen.getByText('marker-0')).toBeInTheDocument() + expect(screen.queryByText(`marker-${TRANSCRIPT_LENGTH - 2}`)).toBeNull() + }) + + // One gap per pair of rows, and none after the last one. The other half of + // this — that a row's own reservation does not include the gap as well — is + // pinned on the estimate itself, where it can be seen without layout. + it('reserves each row once and one gap between each pair', () => { + const { container } = render(list(transcript)) + + expect(windowState(container).totalSize).toBe( + TRANSCRIPT_LENGTH * ROW_PX + (TRANSCRIPT_LENGTH - 1) * NATIVE_CHAT_ROW_GAP_PX + ) + }) + + it('moves the mounted rows to bracket the offset the reader scrolled to', () => { + const { container } = render(list(transcript)) + const offset = 5000 + scrollTranscript(container, offset) + const { indexes } = windowState(container) + const focused = Math.floor(offset / ROW_PITCH_PX) + + expect(indexes).toContain(focused) + expect(indexes[0]).toBeLessThanOrEqual(focused) + expect(indexes.at(-1)).toBeGreaterThanOrEqual(focused) + expect(indexes).not.toContain(0) + expect(indexes.length).toBeLessThan(TRANSCRIPT_LENGTH / 4) + }) + + // The live row announces a running tool through `aria-live`, which says nothing + // from a row that is not in the document. + it('keeps the newest row mounted after the reader scrolls away from it', () => { + const { container } = render(list(transcript)) + scrollTranscript(container, 5000) + + expect(windowState(container).indexes).toContain(TRANSCRIPT_LENGTH - 1) + }) + + it('gives no slot to a message that draws nothing', () => { + const withBlanks = Array.from({ length: TRANSCRIPT_LENGTH }, (_, index) => + index % 4 === 0 + ? { ...marker(index), blocks: [{ type: 'text' as const, text: '' }] } + : marker(index) + ) + const drawn = TRANSCRIPT_LENGTH - TRANSCRIPT_LENGTH / 4 + const { container } = render(list(withBlanks)) + const { totalSize, indexes } = windowState(container) + + expect(totalSize).toBe(drawn * ROW_PX + (drawn - 1) * NATIVE_CHAT_ROW_GAP_PX) + expect(indexes.at(-1)).toBeLessThanOrEqual(drawn - 1) + }) + + it('still has the tool run open when the row carrying it comes back', () => { + const withTool = [...transcript] + withTool[1] = { + ...marker(1), + blocks: [ + { type: 'text', text: 'marker-1' }, + { type: 'tool-call', name: 'shell', input: { command: 'ls' }, state: 'completed' } + ] + } + const { container } = render(list(withTool)) + + const header = screen.getByRole('button', { name: /1×/ }) + expect(header).toHaveAttribute('aria-expanded', 'false') + fireEvent.click(header) + expect(screen.getByRole('button', { name: /1×/ })).toHaveAttribute('aria-expanded', 'true') + + scrollTranscript(container, 5000) + expect(windowState(container).indexes).not.toContain(1) + expect(screen.queryByRole('button', { name: /1×/ })).toBeNull() + + scrollTranscript(container, 0) + expect(screen.getByRole('button', { name: /1×/ })).toHaveAttribute('aria-expanded', 'true') + }) +}) + +// The reveal chain runs message -> tool run -> diff card and lands on a card in +// a DIFFERENT, earlier message than the rollup that was clicked. Under windowing +// that message may not be mounted to be pointed at, so the reveal names it by id +// and the row is pinned into the window until the card can answer for itself. +describe('revealing a diff from a turn rollup', () => { + let restoreLayout = (): void => {} + beforeEach(() => { + restoreLayout = stubLayout() + }) + afterEach(() => { + restoreLayout() + vi.restoreAllMocks() + }) + + function journalItem(itemId: string, body: AgentJournalItemBody, sequence: number) { + return { itemId, body, sequence, observedAt: sequence * 1000, revision: 1 } + } + + const patch = '@@ -1 +1 @@\n-before\n+after' + const items: AgentJournalRenderItem[] = [ + journalItem( + 'user', + { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Edit it' }] }, + 1 + ), + journalItem( + 'diff', + { + kind: 'diff', + path: 'src/a.ts', + patch: { head: patch, truncated: false, digest: 'fixture', byteLength: patch.length } + }, + 2 + ), + ...Array.from({ length: TRANSCRIPT_LENGTH }, (_, index) => + journalItem( + `tail-${index}`, + { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: `marker-${index}` }] }, + index + 3 + ) + ) + ] + + it('mounts the row a reveal names even when the window has left it behind', () => { + const scrollTo = vi.fn() + vi.spyOn(HTMLElement.prototype, 'scrollTo').mockImplementation(scrollTo) + const { container } = render( + + ) + // The rollup rides the turn's last row, which is pinned; the diff it points + // at is near the top and long gone from the window. + scrollTranscript(container, 4000) + expect(screen.queryByText('Edited file')).toBeNull() + const mountedBefore = windowState(container).indexes.length + + fireEvent.click(screen.getByRole('button', { name: /1 changed file/ })) + scrollTo.mockClear() + fireEvent.click(screen.getByRole('button', { name: /src\/a.ts/ })) + + expect(screen.getByText('Edited file')).toBeInTheDocument() + expect(screen.getByText('after')).toBeInTheDocument() + expect(scrollTo).toHaveBeenCalled() + // Pinned, not paged to: the window is still a window. + expect(windowState(container).indexes.length).toBeLessThanOrEqual(mountedBefore + 2) + }) +}) + +describe('transcript with a hidden scroll root', () => { + const transcript = Array.from({ length: 40 }, (_, index) => marker(index)) + + it('keeps the transcript bounded and rehydrates when the viewport becomes measurable', () => { + let viewportHeight = 0 + const restoreLayout = stubLayout({ viewportHeight: () => viewportHeight }) + const restoreResizeObserver = stubResizeObserver() + try { + const { container } = render(list(transcript)) + + expect(container.querySelector('[data-native-chat-window]')).toBeInTheDocument() + expect(container.querySelectorAll('[data-index]')).toHaveLength(0) + expect(screen.queryByText(/^marker-/)).toBeNull() + const column = container.querySelector('.max-w-4xl') + expect(column?.children).toHaveLength(1) + + viewportHeight = VIEWPORT_PX + act(() => { + deliverResizes() + }) + const { indexes } = windowState(container) + expect(indexes.length).toBeGreaterThan(0) + expect(indexes.length).toBeLessThan(transcript.length) + } finally { + restoreResizeObserver() + restoreLayout() + } + }) +}) + +// A row that grows in place: the same message id, more content, a taller measured +// box — what a streaming reply looks like to the window. Whole-message appends +// arrive at their final height and are a different case; this is the one where +// the row the reader is looking at keeps changing size underneath them. +// +// Two mechanisms are supposed to hold the pin, and both are exercised here: the +// list's own resize observer on the transcript column (which re-runs +// `scrollToBottom` against the document) and the virtualizer's end anchor (which +// compensates `scrollTop` by the growth when the view was already at the end). +describe('a row growing in place while the view is pinned to the bottom', () => { + const TAIL_INDEX = TRANSCRIPT_LENGTH - 1 + const GROWTH_STEPS = 24 + const LINES_PER_STEP = 12 + /** One wrapped prose line. Content and measured height grow from this one + * number, so a step that adds lines is a step that adds pixels. */ + const STREAM_LINE_PX = 22 + /** Every row but the growing one measures at its estimate, so the reserved + * total is arithmetic rather than a snapshot. */ + const BASE_TOTAL_PX = + (TRANSCRIPT_LENGTH - 1) * ROW_PX + (TRANSCRIPT_LENGTH - 1) * NATIVE_CHAT_ROW_GAP_PX + + /** Fixed so a re-render never restamps the turn and moves the status row. */ + const TURN_STARTED_AT = Date.now() + + const transcript = Array.from({ length: TRANSCRIPT_LENGTH }, (_, index) => marker(index)) + + function tailHeightAt(step: number): number { + return Math.max(ROW_PX, (1 + step * LINES_PER_STEP) * STREAM_LINE_PX) + } + + function transcriptAt(step: number): NativeChatMessage[] { + const lines = Array.from( + { length: step * LINES_PER_STEP }, + (_, index) => `streamed line ${index}` + ) + const next = [...transcript] + next[TAIL_INDEX] = { + ...marker(TAIL_INDEX), + blocks: [{ type: 'text', text: [`marker-${TAIL_INDEX}`, ...lines].join('\n') }] + } + return next + } + + function streamingList(step: number): React.JSX.Element { + return ( + + ) + } + + function scrollRoot(container: HTMLElement): HTMLElement { + const scroller = container.querySelector('[data-native-chat-scroll]') + if (!scroller) { + throw new Error('no transcript scroll root') + } + return scroller + } + + /** One painted frame, repeated to a fixed point: deliver the resize callbacks + * the growth caused, then fire the scroll event a browser fires for any + * `scrollTop` the code wrote itself. Refusing to settle is a failure in its + * own right — that is the view oscillating. */ + function paint(container: HTMLElement): void { + const scroller = scrollRoot(container) + let lastScrollTop = scroller.scrollTop + for (let pass = 0; pass < 12; pass += 1) { + let changed = false + act(() => { + changed = deliverResizes() + }) + if (scroller.scrollTop !== lastScrollTop) { + lastScrollTop = scroller.scrollTop + fireEvent.scroll(scroller) + changed = true + } + if (!changed) { + return + } + } + throw new Error('the transcript never settled: resize and scroll kept moving it') + } + + function distanceFromBottom(container: HTMLElement): number { + const scroller = scrollRoot(container) + return scroller.scrollHeight - scroller.clientHeight - scroller.scrollTop + } + + function setMeasuredTail(step: number): void { + const heights = Array.from({ length: TRANSCRIPT_LENGTH }, () => ROW_PX) + heights[TAIL_INDEX] = tailHeightAt(step) + measuredRowHeights = heights + } + + let restoreLayout = (): void => {} + let restoreResizeObserver = (): void => {} + beforeEach(() => { + restoreLayout = stubLayout({ scrollGeometry: true }) + restoreResizeObserver = stubResizeObserver() + setMeasuredTail(0) + }) + afterEach(() => { + restoreResizeObserver() + restoreLayout() + measuredRowHeights = [] + }) + + it('holds the pin, the mount and the reserved total at every frame of the growth', () => { + setMeasuredTail(0) + const { container, rerender } = render(streamingList(0)) + paint(container) + + expect(distanceFromBottom(container)).toBeLessThanOrEqual(NATIVE_CHAT_BOTTOM_THRESHOLD_PX) + expect(windowState(container).totalSize).toBe(BASE_TOTAL_PX + tailHeightAt(0)) + + const frames: { step: number; tail: number; total: number; distance: number }[] = [] + for (let step = 1; step <= GROWTH_STEPS; step += 1) { + setMeasuredTail(step) + rerender(streamingList(step)) + paint(container) + + const { totalSize, indexes } = windowState(container) + const distance = distanceFromBottom(container) + frames.push({ step, tail: tailHeightAt(step), total: totalSize, distance }) + + // Pinned: the reader is still looking at the bottom of the row. + expect(distance).toBeLessThanOrEqual(NATIVE_CHAT_BOTTOM_THRESHOLD_PX) + // Mounted: never swapped for reserved space while it is the live row. + expect(indexes).toContain(TAIL_INDEX) + expect(screen.getByText(/streamed line 0/)).toBeInTheDocument() + // Tracking: the reservation follows the measurement, not the estimate. + expect(totalSize).toBe(BASE_TOTAL_PX + tailHeightAt(step)) + // Still a window, not the whole transcript remounted by the growth. + expect(indexes.length).toBeLessThan(TRANSCRIPT_LENGTH / 4) + } + + expect(frames).toHaveLength(GROWTH_STEPS) + expect(frames.at(-1)?.tail).toBeGreaterThan(VIEWPORT_PX * 10) + expect(Math.max(...frames.map((frame) => frame.distance))).toBeLessThanOrEqual( + NATIVE_CHAT_BOTTOM_THRESHOLD_PX + ) + }) + + it('leaves a reader who scrolled up where they were, however far the row grows', () => { + setMeasuredTail(4) + const { container, rerender } = render(streamingList(4)) + paint(container) + + const readingAt = 2000 + scrollTranscript(container, readingAt) + paint(container) + expect(distanceFromBottom(container)).toBeGreaterThan(NATIVE_CHAT_BOTTOM_THRESHOLD_PX) + expect(screen.getByRole('button', { name: /jump to latest/i })).toBeInTheDocument() + + for (let step = 5; step <= GROWTH_STEPS; step += 1) { + setMeasuredTail(step) + rerender(streamingList(step)) + paint(container) + + const { totalSize, indexes } = windowState(container) + // Not yanked: the offset the reader chose is the offset they still have. + expect(scrollRoot(container).scrollTop).toBe(readingAt) + // The row is off screen but still measured, which is what keeps the + // reserved total — and so the scrollbar — honest while it grows. + expect(indexes).toContain(TAIL_INDEX) + expect(totalSize).toBe(BASE_TOTAL_PX + tailHeightAt(step)) + } + + expect(screen.getByRole('button', { name: /jump to latest/i })).toBeInTheDocument() + }) +}) diff --git a/src/renderer/src/components/native-chat/NativeChatMessageRow.tsx b/src/renderer/src/components/native-chat/NativeChatMessageRow.tsx index 773e6f2c2ff..d73772dfaf9 100644 --- a/src/renderer/src/components/native-chat/NativeChatMessageRow.tsx +++ b/src/renderer/src/components/native-chat/NativeChatMessageRow.tsx @@ -1,23 +1,17 @@ -import { memo, useCallback, useMemo, useRef } from 'react' +import { memo, useCallback, useRef } from 'react' import CommentMarkdown, { type CommentMarkdownLinkClickHandler } from '@/components/sidebar/CommentMarkdown' import { cn } from '@/lib/utils' import { translate } from '@/i18n/i18n' -import { - isSubagentGroupFallbackText, - subagentGroupBlocks -} from '../../../../shared/native-chat-subagent-summary' -import { - isSubagentGroupBlock, - type NativeChatMessage, - type NativeChatToolCallBlock +import type { + NativeChatMessage, + NativeChatToolCallBlock } from '../../../../shared/native-chat-types' -import { splitNativeChatBlocks } from './native-chat-tool-fold' +import { deriveNativeChatRowContent } from './native-chat-row-content' import { NativeChatToolRun } from './NativeChatToolRun' import { NativeChatNoticeRow } from './NativeChatNoticeRow' import { NativeChatMessageTimestamp } from './NativeChatMessageTimestamp' -import { nativeChatProseToMarkdown } from './native-chat-prose' import { NativeChatAgentControls, NativeChatImageAttachments, @@ -62,32 +56,11 @@ export const MessageRow = memo(function MessageRow({ runtimeContext?: RuntimeFileOperationArgs | null }): React.JSX.Element | null { const rowRef = useRef(null) - // One pass per block set: a streaming turn re-renders this row on every frame, and these - // derivations used to re-run each time even though `message.blocks` had not changed. - const { hasImages, markdown, prose, subagentGroups, tools } = useMemo(() => { - const split = splitNativeChatBlocks(message.blocks) - const groups = subagentGroupBlocks(split.prose) - // A spawn-group row carries a plain-text twin so a client without the block - // type still reads the roster. This one draws the block, so the twin is - // dropped rather than printed beside it — only the twin, never the prose - // beside it: the block is provider-agnostic, so a lane that folds a roster - // into a message with real text must not lose that text here. - const prose = - groups.length === 0 - ? split.prose - : split.prose.filter( - (block) => - !isSubagentGroupBlock(block) && - !(block.type === 'text' && isSubagentGroupFallbackText(block.text)) - ) - return { - tools: split.tools, - prose, - subagentGroups: groups, - markdown: nativeChatProseToMarkdown(prose), - hasImages: prose.some((block) => block.type === 'image-ref') - } - }, [message.blocks]) + // One pass per block set, shared with the list that decides whether this row + // occupies a slot — so "draws nothing" means the same thing to both. + const { hasImages, markdown, prose, subagentGroups, tools } = deriveNativeChatRowContent( + message.blocks + ) const isUser = message.role === 'user' const isReasoning = message.role === 'reasoning' const isSystem = message.role === 'system' @@ -220,6 +193,7 @@ export const MessageRow = memo(function MessageRow({ expandOverride={activityExpandOverride} activeTurnIsWorking={activeTurnIsWorking} structuredActivityUi={structuredActivityUi} + disclosureId={message.id} /> ) : null} {showControls ? ( diff --git a/src/renderer/src/components/native-chat/NativeChatPromptEditor.test.tsx b/src/renderer/src/components/native-chat/NativeChatPromptEditor.test.tsx index 3934cf7be23..78d8da92530 100644 --- a/src/renderer/src/components/native-chat/NativeChatPromptEditor.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatPromptEditor.test.tsx @@ -34,7 +34,10 @@ describe('native chat skill editor', () => { it('renders only picker insertions as pills and serializes the exact invocation', () => { const { input, container } = setup('Please $rev') act(() => input.insertSkill!(7, 11, '$review')) - expect(container.querySelector('[data-native-chat-skill]')?.textContent).toBe('Review') + const pill = container.querySelector('[data-native-chat-skill]') + expect(pill?.textContent).toBe('Review') + expect(pill?.classList.contains('text-xs')).toBe(true) + expect(pill?.classList.contains('text-sm')).toBe(false) expect(input.value).toBe('Please $review ') expect(input.selectionStart).toBe(15) act(() => { diff --git a/src/renderer/src/components/native-chat/NativeChatSkillPill.tsx b/src/renderer/src/components/native-chat/NativeChatSkillPill.tsx index fee86dd0f98..9bde1a5a1c9 100644 --- a/src/renderer/src/components/native-chat/NativeChatSkillPill.tsx +++ b/src/renderer/src/components/native-chat/NativeChatSkillPill.tsx @@ -18,9 +18,9 @@ export function NativeChatSkillPill({ node, selected }: NodeViewProps): React.JS - diff --git a/src/renderer/src/components/native-chat/NativeChatToolLine.tsx b/src/renderer/src/components/native-chat/NativeChatToolLine.tsx new file mode 100644 index 00000000000..883244d8f91 --- /dev/null +++ b/src/renderer/src/components/native-chat/NativeChatToolLine.tsx @@ -0,0 +1,139 @@ +import type { CommentMarkdownLinkClickHandler } from '@/components/sidebar/CommentMarkdown' +import { ChevronRight } from 'lucide-react' +import { cn } from '@/lib/utils' +import { translate } from '@/i18n/i18n' +import { + isToolCallBlock, + isToolResultBlock, + type NativeChatBlock +} from '../../../../shared/native-chat-types' +import { + NativeChatCommandMetadata, + NativeChatSearchResults, + NativeChatToolName +} from './NativeChatToolAnnotations' +import { NativeChatToolIcon } from './NativeChatToolIcon' +import { NativeChatDiffView } from './NativeChatDiffView' +import { diffFromText, diffFromToolCall, type DiffLine } from './native-chat-diff' +import { useNativeChatDisclosure } from './native-chat-disclosure-store' +import { createToolInputDisplay, truncateToolDetail } from './native-chat-tool-summary' + +/** A single inline tool line — `▸ ToolName preview` — that expands in place to + * show the call's diff/input or the result's body. Tool calls read as flat + * lines in the conversation rather than boxed blocks (mobile parity). Lines only + * mount while the parent run is open and are individually collapsible. */ +export function NativeChatToolLine({ + block, + initiallyExpanded = true, + disclosureKey, + onLinkClick +}: { + block: NativeChatBlock + initiallyExpanded?: boolean + /** Identity this line's open state is remembered under while it is unmounted. */ + disclosureKey?: string + onLinkClick?: CommentMarkdownLinkClickHandler +}): React.JSX.Element | null { + const { open: expanded, setOpen: setExpanded } = useNativeChatDisclosure( + disclosureKey, + initiallyExpanded + ) + + let name: string + let preview: string + let diff: DiffLine[] | null = null + let body: { output: string; isError?: boolean } | null = null + let detail: string | null = null + let inputHasDetail = false + const isCall = isToolCallBlock(block) + + if (isCall) { + name = block.name + const inputDisplay = createToolInputDisplay(block.input) + preview = inputDisplay.label + inputHasDetail = inputDisplay.hasDetail + diff = expanded ? diffFromToolCall(block.name, block.input) : null + detail = expanded && !diff ? inputDisplay.formatDetail() : null + } else if (isToolResultBlock(block)) { + name = translate('components.native-chat.tool.result', 'Result') + preview = block.output.split('\n')[0]?.slice(0, 80) ?? '' + diff = expanded ? diffFromText(block.output) : null + body = { output: block.output, isError: block.isError } + } else { + return null + } + + const hasResults = isCall && (block.webSearchResults?.length ?? 0) > 0 + const hasDetail = diff !== null || body !== null || inputHasDetail || hasResults + + return ( +
+ + {hasDetail && expanded ? ( +
+ {isCall && hasResults ? ( + + ) : null} + {diff ? : null} + {!diff && body ? ( +
+              {truncateToolDetail(body.output)}
+            
+ ) : null} + {!diff && !body && detail ? ( +
+              {detail}
+            
+ ) : null} +
+ ) : null} +
+ ) +} diff --git a/src/renderer/src/components/native-chat/NativeChatToolRun.identity.test.tsx b/src/renderer/src/components/native-chat/NativeChatToolRun.identity.test.tsx index 2b83f86d14a..86d962ae81d 100644 --- a/src/renderer/src/components/native-chat/NativeChatToolRun.identity.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatToolRun.identity.test.tsx @@ -3,10 +3,24 @@ import { cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' import { NativeChatToolRun } from './NativeChatToolRun' import type { NativeChatToolCallBlock } from '../../../../shared/native-chat-types' +import { + NativeChatDisclosureContext, + useNativeChatDisclosures +} from './native-chat-disclosure-store' vi.mock('./NativeChatDiffCard', () => ({ NativeChatDiffCard: () => null })) vi.mock('./NativeChatDiffView', () => ({ NativeChatDiffView: () => null })) -afterEach(cleanup) + +const disclosureWrite = vi.fn() +const capturedDisclosures = { + read: (_key: string) => undefined, + write: (key: string, open: boolean) => disclosureWrite(key, open) +} + +afterEach(() => { + cleanup() + disclosureWrite.mockReset() +}) const shell: NativeChatToolCallBlock = { type: 'tool-call', @@ -17,7 +31,100 @@ const shell: NativeChatToolCallBlock = { durationMs: 400 } +function ToolRunDisclosureHarness({ expandOverride }: { expandOverride: boolean }) { + const disclosures = useNativeChatDisclosures() + return ( + + + + ) +} + describe('inline tool annotations', () => { + it('restores a per-run deviation when its turn returns to the same disclosure state', () => { + const { rerender } = render() + const run = screen.getByRole('button', { expanded: true }) + + fireEvent.click(run) + expect(run.getAttribute('aria-expanded')).toBe('false') + + rerender() + expect(screen.queryByRole('button')).toBeNull() + + rerender() + expect(screen.getByRole('button', { name: /1×/ }).getAttribute('aria-expanded')).toBe('false') + }) + + it('resynchronizes a standalone run when the toolbar signal flips', () => { + const { rerender } = render( + + ) + expect(screen.getByRole('button').getAttribute('aria-expanded')).toBe('false') + + rerender() + + expect(screen.getByRole('button', { name: /1×/ }).getAttribute('aria-expanded')).toBe('true') + }) + + it('uses provider call identities for byte-identical line disclosure keys', () => { + const blocks = [ + { ...shell, callId: 'call-a' }, + { ...shell, callId: 'call-b' } + ] + render( + + + + ) + + fireEvent.click(screen.getAllByRole('button')[2]!) + + expect(disclosureWrite).toHaveBeenCalledExactlyOnceWith('line:message-1:call:call-b', false) + }) + + it('keeps occurrence identity as the fallback for calls without provider IDs', () => { + render( + + + + ) + + fireEvent.click(screen.getAllByRole('button')[2]!) + + expect(disclosureWrite).toHaveBeenCalledExactlyOnceWith( + 'line:message-1:tool-call:shell:{"command":"missing-command"}:1', + false + ) + }) + + it('keeps occurrence identity for whitespace-only provider IDs', () => { + render( + + + + ) + + fireEvent.click(screen.getAllByRole('button')[2]!) + + expect(disclosureWrite).toHaveBeenCalledExactlyOnceWith( + 'line:message-1:tool-call:shell:{"command":"missing-command"}:1', + false + ) + }) + it('keeps command completion annotations on the collapsed tool line', () => { render( 0 - const hasDetail = diff !== null || body !== null || inputHasDetail || hasResults - - return ( -
- - {hasDetail && expanded ? ( -
- {isCall && hasResults ? ( - - ) : null} - {diff ? : null} - {!diff && body ? ( -
-              {truncateToolDetail(body.output)}
-            
- ) : null} - {!diff && !body && detail ? ( -
-              {detail}
-            
- ) : null} -
- ) : null} -
- ) -} - /** A run of a message's tool calls/results, collapsed to a one-line summary that - * expands to the individual inline tool lines. `expandSignal` lets the global - * toolbar toggle drive every run at once while still allowing per-run override. */ + * expands to the individual inline tool lines. */ export function NativeChatToolRun({ blocks, previousTodoWrite, @@ -170,6 +47,7 @@ export function NativeChatToolRun({ activeTurnIsWorking, expandOverride, structuredActivityUi = true, + disclosureId, onLinkClick }: { blocks: NativeChatBlock[] @@ -179,32 +57,28 @@ export function NativeChatToolRun({ onRevealDiff?: (element: HTMLElement) => void /** Spawn-group rosters that belong with this run's activity, one row each. */ subagentGroups?: NativeChatSubagentGroupBlock[] - /** Toolbar-driven desired open state. Each change re-syncs this run's state. */ + /** Legacy view-level default; production native-chat entry points pass false. */ expandSignal: boolean /** Per-turn disclosure state controlled by the completed turn status row. */ expandOverride?: boolean /** Structured lifecycle state, when available, keeps orphaned running calls from spinning. */ activeTurnIsWorking?: boolean structuredActivityUi?: boolean + /** Message this run belongs to. Windowing unmounts rows, so a run the reader + * opened has to be remembered somewhere that outlives the row. */ + disclosureId?: string onLinkClick?: CommentMarkdownLinkClickHandler }): React.JSX.Element | null { - const [open, setOpen] = useState(revealedDiff ? true : (expandOverride ?? expandSignal)) - const [controls, setControls] = useState({ expandOverride, expandSignal, revealedDiff }) - if ( - controls.expandOverride !== expandOverride || - controls.expandSignal !== expandSignal || - controls.revealedDiff !== revealedDiff - ) { - setControls({ expandOverride, expandSignal, revealedDiff }) - if (revealedDiff && controls.revealedDiff !== revealedDiff) { - setOpen(true) - } else if ( - controls.expandOverride !== expandOverride || - controls.expandSignal !== expandSignal - ) { - setOpen(expandOverride ?? expandSignal) - } - } + // A reader's deviation belongs to the controlling disclosure state, so returning + // to that state restores the same choice without writing to the store mid-render. + const runKey = + disclosureId === undefined + ? undefined + : `run:${disclosureId}:${expandOverride ?? '-'}:${expandSignal}:${revealedDiff?.requestId ?? '-'}` + const { open, setOpen } = useNativeChatDisclosure( + runKey, + revealedDiff ? true : (expandOverride ?? expandSignal) + ) // Childless groups are dropped so `subagentRows.length` stays an honest test of // "something will draw": the roster-only branch below returns a margin-bearing @@ -236,8 +110,7 @@ export function NativeChatToolRun({ : null const isSettled = latestActiveCall == null const hasRunningCall = blocks.some((block) => isToolCallBlock(block) && block.state === 'running') - // The turn caret opens the activity group, while each child tool remains - // collapsed. The global expand toolbar still opens child details together. + // The turn caret opens the activity group while each child tool stays collapsed. const expandToolLines = expandOverride === undefined ? open : false // Diffing every edit is the run's most expensive work, so a collapsed run — // which renders none of it — never pays for it. @@ -307,7 +180,7 @@ export function NativeChatToolRun({ {latestActiveCall ? (
@@ -440,12 +318,25 @@ export function NativeChatToolRun({ : `${block.type}` const occurrence = seen.get(signature) ?? 0 seen.set(signature, occurrence + 1) + const providerCallId = + block.type === 'tool-call' && + block.callId !== undefined && + block.callId.trim().length > 0 + ? block.callId + : undefined + const lineIdentity = + providerCallId !== undefined + ? `call:${providerCallId}` + : `${signature}:${occurrence}` return ( - ) }) diff --git a/src/renderer/src/components/native-chat/NativeChatTranscriptItems.tsx b/src/renderer/src/components/native-chat/NativeChatTranscriptItems.tsx new file mode 100644 index 00000000000..c8b51e0263e --- /dev/null +++ b/src/renderer/src/components/native-chat/NativeChatTranscriptItems.tsx @@ -0,0 +1,50 @@ +import { + NativeChatTranscriptRow, + type NativeChatTranscriptRowContext +} from './NativeChatTranscriptRow' +import type { NativeChatTranscriptSlot } from './native-chat-transcript-slots' +import type { NativeChatTranscriptWindow } from './use-native-chat-transcript-window' + +/** Windowed transcript rows, absolutely positioned inside a full-height spacer. */ +export function NativeChatTranscriptItems({ + slots, + context, + window +}: { + slots: readonly NativeChatTranscriptSlot[] + context: NativeChatTranscriptRowContext + window: NativeChatTranscriptWindow +}): React.JSX.Element { + return ( +
+ {window.virtualItems.map((item) => { + const slot = slots[item.index] + if (!slot) { + return null + } + return ( +
+ +
+ ) + })} +
+ ) +} diff --git a/src/renderer/src/components/native-chat/NativeChatTranscriptRow.tsx b/src/renderer/src/components/native-chat/NativeChatTranscriptRow.tsx new file mode 100644 index 00000000000..93c5676cddb --- /dev/null +++ b/src/renderer/src/components/native-chat/NativeChatTranscriptRow.tsx @@ -0,0 +1,86 @@ +import { memo } from 'react' +import type { CommentMarkdownLinkClickHandler } from '@/components/sidebar/CommentMarkdown' +import type { RuntimeFileOperationArgs } from '@/runtime/runtime-file-client' +import { MessageRow } from './NativeChatMessageRow' +import { NativeChatResolutionReceipt } from './NativeChatResolutionReceipt' +import { NativeChatWorkingStatus } from './NativeChatWorkingStatus' +import { NativeChatTurnDiffRollup } from './NativeChatTurnDiffRollup' +import type { NativeChatTaskListPredecessors } from './native-chat-task-list-history' +import type { NativeChatTranscriptSlot } from './native-chat-transcript-slots' +import type { NativeChatDiffReveal, NativeChatDiffTarget } from './native-chat-turn-diffs' + +/** Everything a row needs that is the same for every row. Held as one memoized + * object so a row's props change only when that row's own slot does. */ +export type NativeChatTranscriptRowContext = { + expandSignal: boolean + showTurnStatus: boolean + revealedDiff: NativeChatDiffReveal | null + taskListPredecessors: ReadonlyMap + expandedTurnIds: ReadonlySet + failedDeliveryMessageIds?: ReadonlySet + allowFileUriLinks: boolean + runtimeContext?: RuntimeFileOperationArgs | null + onLinkClick?: CommentMarkdownLinkClickHandler + onToggleExpandedTurn: (turnKey: string) => void + onScrollMessageToTop: (element: HTMLElement) => void + onRevealDiff: (target: NativeChatDiffTarget) => void +} + +/** One transcript row: the message (or the receipt standing in for it), the turn + * status under it, and the turn's diff rollup. + * + * These three were siblings in the transcript column and took their spacing from + * it. Windowing needs one element per row to position and measure, so the + * wrapper carries that spacing itself — the gap BETWEEN rows is the window's. */ +export const NativeChatTranscriptRow = memo(function NativeChatTranscriptRow({ + slot, + context +}: { + slot: NativeChatTranscriptSlot + context: NativeChatTranscriptRowContext +}): React.JSX.Element { + const { message, turnKey, status, receipt, turnDiff } = slot + const predecessors = context.taskListPredecessors.get(message.id) + const expanded = turnKey ? context.expandedTurnIds.has(turnKey) : undefined + return ( +
+ {receipt ? ( + + ) : ( + + )} + {status ? ( + context.onToggleExpandedTurn(turnKey) + : undefined + } + /> + ) : null} + {turnDiff ? ( + + ) : null} +
+ ) +}) diff --git a/src/renderer/src/components/native-chat/NativeChatTurnActivityLine.tsx b/src/renderer/src/components/native-chat/NativeChatTurnActivityLine.tsx index da11773105d..72e11ad25a8 100644 --- a/src/renderer/src/components/native-chat/NativeChatTurnActivityLine.tsx +++ b/src/renderer/src/components/native-chat/NativeChatTurnActivityLine.tsx @@ -1,18 +1,55 @@ import { Loader2 } from 'lucide-react' import { translate } from '@/i18n/i18n' -import type { NativeChatTurnActivity } from './native-chat-turn-activity' +import type { NativeChatTurnActivity } from '../../../../shared/native-chat-turn-activity' +import { + describeNativeChatActiveTurnLabel, + NATIVE_CHAT_TURN_STATUS_COPY, + type NativeChatTurnStatus +} from '../../../../shared/native-chat-turn-status' +import { useNativeChatElapsedSeconds } from './use-native-chat-elapsed-seconds' +/** The live turn's one indicator: a spinner plus whatever the turn can say about + * itself — the provider's activity text, else that it is reasoning, else how + * long it has been working. A settled turn keeps its own `NativeChatWorkingStatus` + * row; this one is only ever rendered while the turn is in flight. */ export function NativeChatTurnActivityLine({ - activity + activity, + status }: { activity?: NativeChatTurnActivity | null + status?: NativeChatTurnStatus | null }): React.JSX.Element { - const label = activity?.text ?? translate('components.native-chat.status.working', 'Working…') + const thinking = status?.thinking === true + // The clock only ticks when its number is the label; activity text and + // "Thinking" carry no duration. + const counting = status != null && !thinking && !activity?.text + const elapsedSeconds = useNativeChatElapsedSeconds(status?.startedAt ?? null, counting) + const resolved = describeNativeChatActiveTurnLabel({ + activityText: activity?.text, + thinking, + elapsedSeconds + }) + const label = + resolved.source === 'activity' + ? resolved.text + : status == null + ? translate('components.native-chat.status.working', 'Working…') + : resolved.key === 'thinking' + ? translate( + 'components.native-chat.status.thinking', + NATIVE_CHAT_TURN_STATUS_COPY.thinking + ) + : translate( + 'components.native-chat.status.workingFor', + NATIVE_CHAT_TURN_STATUS_COPY.workingFor, + { value0: resolved.duration } + ) return (
diff --git a/src/renderer/src/components/native-chat/NativeChatWorkingStatus.tsx b/src/renderer/src/components/native-chat/NativeChatWorkingStatus.tsx index e6c38de83f5..8b910daa936 100644 --- a/src/renderer/src/components/native-chat/NativeChatWorkingStatus.tsx +++ b/src/renderer/src/components/native-chat/NativeChatWorkingStatus.tsx @@ -1,13 +1,11 @@ -import { useState } from 'react' import { ChevronRight } from 'lucide-react' import { translate } from '@/i18n/i18n' -import { useNow } from '@/hooks/use-now' import { describeNativeChatTurnStatus, formatNativeChatDuration, - NATIVE_CHAT_TURN_STATUS_COPY, - nativeChatElapsedSeconds + NATIVE_CHAT_TURN_STATUS_COPY } from '../../../../shared/native-chat-turn-status' +import { useNativeChatElapsedSeconds } from './use-native-chat-elapsed-seconds' export { formatNativeChatDuration } @@ -24,15 +22,8 @@ export function NativeChatWorkingStatus({ expanded?: boolean onToggleExpanded?: () => void }): React.JSX.Element { - // Why: elapsed seconds is ordinary render dataflow, not an external system. - // The shared 1s clock is visibility-gated and collapses every in-flight turn - // onto one tick, instead of one interval plus one commit per turn. const counting = !thinking && workedSeconds == null - const now = useNow(1_000, counting) - // Why: preserves the old effect's `startedAt ?? Date.now()` epoch for the - // single frame before the turn's startedAt lands. - const [mountedAt] = useState(() => Date.now()) - const elapsedSeconds = counting ? nativeChatElapsedSeconds(startedAt, mountedAt, now) : 0 + const elapsedSeconds = useNativeChatElapsedSeconds(startedAt, counting) const { key, duration } = describeNativeChatTurnStatus({ thinking, @@ -67,6 +58,7 @@ export function NativeChatWorkingStatus({ return (
) diff --git a/src/renderer/src/components/settings/appearance-search.ts b/src/renderer/src/components/settings/appearance-search.ts index 726ecaa1b01..09685358145 100644 --- a/src/renderer/src/components/settings/appearance-search.ts +++ b/src/renderer/src/components/settings/appearance-search.ts @@ -223,13 +223,13 @@ const getAppearanceSectionEntries = createLocalizedCatalog((): SettingsSearchEnt ]) type AppearancePaneSearchOptions = { - showWarpImport?: boolean + showDesktopThemeImports?: boolean showSystemTray?: boolean showMenuBarIcon?: boolean } -function buildAppearancePaneSearchEntries( - options: AppearancePaneSearchOptions +export function getAppearancePaneSearchEntries( + options: AppearancePaneSearchOptions = {} ): SettingsSearchEntry[] { return [ ...getAppearanceSectionEntries(), @@ -247,13 +247,3 @@ function buildAppearancePaneSearchEntries( ...getMenuBarIconEntries(options) ] } - -export function getAppearancePaneSearchEntries( - options: AppearancePaneSearchOptions = {} -): SettingsSearchEntry[] { - return buildAppearancePaneSearchEntries({ - showWarpImport: options.showWarpImport ?? true, - showSystemTray: options.showSystemTray, - showMenuBarIcon: options.showMenuBarIcon - }) -} diff --git a/src/renderer/src/components/settings/terminal-search.test.ts b/src/renderer/src/components/settings/terminal-search.test.ts index b9d1ac76969..f86bcfa3f2c 100644 --- a/src/renderer/src/components/settings/terminal-search.test.ts +++ b/src/renderer/src/components/settings/terminal-search.test.ts @@ -156,14 +156,17 @@ describe('getTerminalPaneSearchEntries', () => { expect(matchesSettingsSearch(query, getAppearancePaneSearchEntries())).toBe(true) }) - it('omits the Warp import appearance entry when desktop-only controls are hidden', () => { - const desktopEntries = getAppearancePaneSearchEntries({ showWarpImport: true }) - const webEntries = getAppearancePaneSearchEntries({ showWarpImport: false }) + it.each(['ghostty', 'warp', 'yaml'])( + 'omits desktop-only %s search results on web clients', + (query) => { + const desktopEntries = getAppearancePaneSearchEntries() + const webEntries = getAppearancePaneSearchEntries({ showDesktopThemeImports: false }) - expect(desktopEntries.some((entry) => entry.title === 'Import from Warp')).toBe(true) - expect(webEntries.some((entry) => entry.title === 'Import from Warp')).toBe(false) - expect(webEntries.some((entry) => entry.title === 'Import from Ghostty')).toBe(true) - }) + expect(matchesSettingsSearch(query, desktopEntries)).toBe(true) + expect(matchesSettingsSearch(query, webEntries)).toBe(false) + expect(matchesSettingsSearch('font size', webEntries)).toBe(true) + } + ) it('includes the system tray appearance entry only when desktop tray controls are shown', () => { const desktopEntries = getAppearancePaneSearchEntries({ showSystemTray: true }) diff --git a/src/renderer/src/components/settings/terminal-search.ts b/src/renderer/src/components/settings/terminal-search.ts index 2a460bd64a1..39a66d65e51 100644 --- a/src/renderer/src/components/settings/terminal-search.ts +++ b/src/renderer/src/components/settings/terminal-search.ts @@ -63,10 +63,10 @@ export { } from './terminal-window-setup-search' type TerminalAppearanceSearchOptions = { - showWarpImport?: boolean + showDesktopThemeImports?: boolean } -const getTerminalAppearanceSearchEntriesWithoutWarp = createLocalizedCatalog( +const getTerminalAppearanceSearchEntriesWithoutImports = createLocalizedCatalog( (): SettingsSearchEntry[] => [ ...getTerminalTypographySearchEntries(), ...getTerminalCursorSearchEntries(), @@ -74,16 +74,15 @@ const getTerminalAppearanceSearchEntriesWithoutWarp = createLocalizedCatalog( ...getTerminalThemeTargetSearchEntries(), ...getTerminalDarkThemeSearchEntries(), ...getTerminalLightThemeSearchEntries(), - ...getTerminalWindowSearchEntries(), - ...getTerminalGhosttyImportSearchEntries() + ...getTerminalWindowSearchEntries() ] ) -// Why: compose rather than filter — entry titles are localized, so matching on -// an English title would leak the Warp entry back in under non-English locales. -const getTerminalAppearanceSearchEntriesWithWarp = createLocalizedCatalog( +// Compose catalogs because translated titles cannot reliably identify desktop-only entries. +const getTerminalAppearanceSearchEntriesWithImports = createLocalizedCatalog( (): SettingsSearchEntry[] => [ - ...getTerminalAppearanceSearchEntriesWithoutWarp(), + ...getTerminalAppearanceSearchEntriesWithoutImports(), + ...getTerminalGhosttyImportSearchEntries(), ...getTerminalWarpImportSearchEntries(), ...getTerminalYamlImportSearchEntries() ] @@ -92,9 +91,9 @@ const getTerminalAppearanceSearchEntriesWithWarp = createLocalizedCatalog( export function getTerminalAppearanceSearchEntries( options: TerminalAppearanceSearchOptions = {} ): SettingsSearchEntry[] { - return (options.showWarpImport ?? true) - ? getTerminalAppearanceSearchEntriesWithWarp() - : getTerminalAppearanceSearchEntriesWithoutWarp() + return (options.showDesktopThemeImports ?? true) + ? getTerminalAppearanceSearchEntriesWithImports() + : getTerminalAppearanceSearchEntriesWithoutImports() } export function getTerminalPaneSearchEntries(platform: { diff --git a/src/renderer/src/components/settings/use-runtime-environment-catalog.ts b/src/renderer/src/components/settings/use-runtime-environment-catalog.ts index a4acfb2b121..5470bf5b6e4 100644 --- a/src/renderer/src/components/settings/use-runtime-environment-catalog.ts +++ b/src/renderer/src/components/settings/use-runtime-environment-catalog.ts @@ -51,10 +51,7 @@ export function useRuntimeEnvironmentCatalog(): RuntimeEnvironmentCatalog { // linger in the sidebar registry. useAppStore.getState().setRuntimeEnvironments(nextEnvironments) if (verified) { - useAppStore.getState().setRuntimeEnvironmentStatus(verified.environmentId, { - status: verified.runtimeStatus, - checkedAt: Date.now() - }) + await useAppStore.getState().readRuntimeHostStatusSnapshots() } if (mountedRef.current) { setEnvironments(visibleEnvironments) @@ -93,10 +90,7 @@ export function useRuntimeEnvironmentCatalog(): RuntimeEnvironmentCatalog { const runtimeStatus = unwrapRuntimeRpcResult(response) // Why: feed the live status into the store so sidebar host pickers // reflect manual refreshes, not just the settings pane. - useAppStore.getState().setRuntimeEnvironmentStatus(environment.id, { - status: runtimeStatus, - checkedAt: Date.now() - }) + await useAppStore.getState().readRuntimeHostStatusSnapshots() if (!mountedRef.current) { return } @@ -114,11 +108,7 @@ export function useRuntimeEnvironmentCatalog(): RuntimeEnvironmentCatalog { // Why: record the failed probe (null status) so the sidebar can // distinguish unreachable from never-checked. const remoteControl = extractRuntimeTransportDiagnostics(error) - useAppStore.getState().setRuntimeEnvironmentStatus(environment.id, { - status: null, - ...(remoteControl ? { remoteControl } : {}), - checkedAt: Date.now() - }) + await useAppStore.getState().readRuntimeHostStatusSnapshots() if (!mountedRef.current) { return } diff --git a/src/renderer/src/components/settings/use-runtime-environment-connection-actions.ts b/src/renderer/src/components/settings/use-runtime-environment-connection-actions.ts index 062fde45ff4..2174c3633c6 100644 --- a/src/renderer/src/components/settings/use-runtime-environment-connection-actions.ts +++ b/src/renderer/src/components/settings/use-runtime-environment-connection-actions.ts @@ -40,14 +40,7 @@ export function useRuntimeEnvironmentConnectionActions({ await window.api.runtimeEnvironments.disconnect({ selector: environment.id }) // Why: disconnect is non-destructive; keep the saved server but show the // user that this live client is no longer attached to it. - useAppStore.getState().setRuntimeEnvironmentStatus( - environment.id, - { - status: null, - checkedAt: Date.now() - }, - { suppressDisconnectToast: true } - ) + await useAppStore.getState().readRuntimeHostStatusSnapshots() if (mountedRef.current) { setDetailsByEnvironmentId((current) => ({ ...current, @@ -96,10 +89,7 @@ export function useRuntimeEnvironmentConnectionActions({ const compatibility = evaluateHostDetails(runtimeStatus) // Why: row Connect is reachability only. The Advanced selector is the // explicit default-host control and should be the only active-server path. - useAppStore.getState().setRuntimeEnvironmentStatus(environment.id, { - status: runtimeStatus, - checkedAt: Date.now() - }) + await useAppStore.getState().readRuntimeHostStatusSnapshots() if (mountedRef.current) { setDetailsByEnvironmentId((current) => ({ ...current, @@ -143,11 +133,7 @@ export function useRuntimeEnvironmentConnectionActions({ } catch (error) { const message = error instanceof Error ? error.message : 'Failed to connect server.' const remoteControl = extractRuntimeTransportDiagnostics(error) - useAppStore.getState().setRuntimeEnvironmentStatus(environment.id, { - status: null, - ...(remoteControl ? { remoteControl } : {}), - checkedAt: Date.now() - }) + await useAppStore.getState().readRuntimeHostStatusSnapshots() if (mountedRef.current) { setDetailsByEnvironmentId((current) => ({ ...current, diff --git a/src/renderer/src/components/sidebar/AddRemoteHostDialog.tsx b/src/renderer/src/components/sidebar/AddRemoteHostDialog.tsx index 03658792d94..1c6ba1ba75a 100644 --- a/src/renderer/src/components/sidebar/AddRemoteHostDialog.tsx +++ b/src/renderer/src/components/sidebar/AddRemoteHostDialog.tsx @@ -68,7 +68,7 @@ export function AddRemoteHostDialog({ const setSshTargetsMetadata = useAppStore((s) => s.setSshTargetsMetadata) const recordSshRepoReadoptions = useAppStore((s) => s.recordSshRepoReadoptions) const setRuntimeEnvironments = useAppStore((s) => s.setRuntimeEnvironments) - const setRuntimeEnvironmentStatus = useAppStore((s) => s.setRuntimeEnvironmentStatus) + const readRuntimeHostStatusSnapshots = useAppStore((s) => s.readRuntimeHostStatusSnapshots) const recordFeatureInteraction = useAppStore((s) => s.recordFeatureInteraction) const busy = isSaving || isBulkImporting || resolvingConfigAlias !== null @@ -283,10 +283,7 @@ export function AddRemoteHostDialog({ } const environments = await window.api.runtimeEnvironments.list() setRuntimeEnvironments(environments) - setRuntimeEnvironmentStatus(result.environment.id, { - status: result.runtimeStatus, - checkedAt: Date.now() - }) + await readRuntimeHostStatusSnapshots() toast.success( translate('auto.components.sidebar.AddRemoteHostDialog.serverSaved', 'Remote server added.') ) diff --git a/src/renderer/src/components/sidebar/HostSectionHeaderMenu.tsx b/src/renderer/src/components/sidebar/HostSectionHeaderMenu.tsx index 3aead74fd81..31d2fab5b91 100644 --- a/src/renderer/src/components/sidebar/HostSectionHeaderMenu.tsx +++ b/src/renderer/src/components/sidebar/HostSectionHeaderMenu.tsx @@ -141,13 +141,10 @@ export function HostSectionHeaderMenu({ row }: { row: HostHeaderRow }): React.JS selector: parsed.environmentId, timeoutMs: 10_000 }) - const runtimeStatus = unwrapRuntimeRpcResult(response) + unwrapRuntimeRpcResult(response) // Why: feed the probe result into the shared store so the host header and // other host pickers reflect this check without a separate fetch. - useAppStore.getState().setRuntimeEnvironmentStatus(parsed.environmentId, { - status: runtimeStatus, - checkedAt: Date.now() - }) + await useAppStore.getState().readRuntimeHostStatusSnapshots() toast.success( translate( 'auto.components.sidebar.HostSectionHeaderMenu.7f1a2b3c4d', @@ -160,10 +157,7 @@ export function HostSectionHeaderMenu({ row }: { row: HostHeaderRow }): React.JS } catch (err) { // Why: record the failed probe so the host registry can drop a previously // healthy verdict instead of showing stale "compatible" state. - useAppStore.getState().setRuntimeEnvironmentStatus(parsed.environmentId, { - status: null, - checkedAt: Date.now() - }) + await useAppStore.getState().readRuntimeHostStatusSnapshots() toast.error( err instanceof Error ? err.message diff --git a/src/renderer/src/components/sidebar/NoticeHostGlyph.test.tsx b/src/renderer/src/components/sidebar/NoticeHostGlyph.test.tsx index 46bf7cd371f..efd47b976ec 100644 --- a/src/renderer/src/components/sidebar/NoticeHostGlyph.test.tsx +++ b/src/renderer/src/components/sidebar/NoticeHostGlyph.test.tsx @@ -83,7 +83,8 @@ describe('NoticeHostGlyph', () => { ) }) - it('marks a paired runtime with no live status as disconnected', async () => { + it('marks a paired runtime a probe found unreachable as disconnected', async () => { + runtimeStatusByEnvironmentId.set('openclaw-env', { status: null }) const container = await render('runtime:openclaw-env') expect(container.querySelector('[data-testid="tooltip"]')?.textContent).toBe( @@ -91,6 +92,17 @@ describe('NoticeHostGlyph', () => { ) }) + it('does not call a host disconnected before its first probe answers', async () => { + // No entry means "not asked yet", not "asked and unreachable" — collapsing the two + // painted every remote row destructive between launch and the first probe. + const container = await render('runtime:openclaw-env') + + expect(container.querySelector('[data-testid="tooltip"]')?.textContent).toBe( + 'Project on openclaw' + ) + expect(container.querySelector('svg')?.getAttribute('class')).not.toContain('text-destructive') + }) + it('gives the local host the monitor glyph the run-target rows use', async () => { const container = await render('local', 'Local Mac') diff --git a/src/renderer/src/components/sidebar/NoticeHostGlyph.tsx b/src/renderer/src/components/sidebar/NoticeHostGlyph.tsx index db1616203dd..7c070450e7d 100644 --- a/src/renderer/src/components/sidebar/NoticeHostGlyph.tsx +++ b/src/renderer/src/components/sidebar/NoticeHostGlyph.tsx @@ -5,6 +5,10 @@ import { HostRowIcon } from '../host-row-icon' import { useAppStore } from '@/store' import { parseExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' import { translate } from '@/i18n/i18n' +import { + isDisconnectedRuntimeHostState, + runtimeHostConnectionStateForEntry +} from '@/runtime/runtime-host-connection-state' type NoticeHostGlyphProps = { hostId: ExecutionHostId @@ -26,11 +30,15 @@ export default function NoticeHostGlyph({ keyboardFocusable }: NoticeHostGlyphProps): React.JSX.Element | null { const host = parseExecutionHostId(hostId) + // Why the shared derivation, not raw truthiness: an absent entry means "not probed yet", + // which is not the same verdict as a probe that came back unreachable. const isDisconnected = useAppStore((s) => { if (host?.kind !== 'runtime') { return false } - return !s.runtimeStatusByEnvironmentId.get(host.environmentId)?.status + return isDisconnectedRuntimeHostState( + runtimeHostConnectionStateForEntry(s.runtimeStatusByEnvironmentId.get(host.environmentId)) + ) }) if (!host) { diff --git a/src/renderer/src/components/sidebar/WorktreeCard.ssh-reconnect-prompt.test.tsx b/src/renderer/src/components/sidebar/WorktreeCard.ssh-reconnect-prompt.test.tsx index 1fe2f4b9530..55ef3263ad4 100644 --- a/src/renderer/src/components/sidebar/WorktreeCard.ssh-reconnect-prompt.test.tsx +++ b/src/renderer/src/components/sidebar/WorktreeCard.ssh-reconnect-prompt.test.tsx @@ -218,18 +218,35 @@ describe('WorktreeCard SSH reconnect prompt', () => { expect(markup).not.toContain('Retry SSH connection') }) - it('marks a runtime-host worktree disconnected when its environment has no status', () => { + it('marks a runtime-host worktree disconnected once a probe finds it unreachable', () => { + runtimeEnvironments = [{ id: 'env-1', name: 'Remote Mac' }] + runtimeStatusByEnvironmentId.set('env-1', { status: null }) + const runtimeRepo: Repo = { + ...makeRepo(), + connectionId: undefined, + executionHostId: 'runtime:env-1' + } + const markup = renderToStaticMarkup( + + ) + expect(markup).toContain('Remote Mac disconnected') + }) + + // Why: "not probed yet" is not "probed and unreachable" — collapsing them painted every + // remote card destructive and dimmed between launch and the first probe answering. + it('leaves a runtime-host worktree undimmed before its first probe answers', () => { runtimeEnvironments = [{ id: 'env-1', name: 'Remote Mac' }] const runtimeRepo: Repo = { ...makeRepo(), connectionId: undefined, executionHostId: 'runtime:env-1' } - // No status entry for env-1 → host is disconnected. const markup = renderToStaticMarkup( ) - expect(markup).toContain('Remote Mac disconnected') + expect(markup).not.toContain('Remote Mac disconnected') + expect(markup).toContain('Project on Remote Mac') + expect(markup).not.toContain('opacity-60') }) it('distinguishes connected worktrees on different Orca servers', () => { diff --git a/src/renderer/src/components/sidebar/delete-worktree-toast.test.ts b/src/renderer/src/components/sidebar/delete-worktree-toast.test.ts index dffedf06337..c63b92cc174 100644 --- a/src/renderer/src/components/sidebar/delete-worktree-toast.test.ts +++ b/src/renderer/src/components/sidebar/delete-worktree-toast.test.ts @@ -50,6 +50,39 @@ describe('getDeleteWorktreeToastCopy', () => { }) }) + // Why: the structured sweep now CLOSES an attached session on the ordinary delete, so reaching + // this toast means the close was attempted and did not settle — not that Orca declined to try. + it('offers force delete when an agent session could not be confirmed closed', () => { + expect( + toastCopyForRemovalError( + 'feature/foo', + 'Refusing to remove worktree with running agent sessions: repo-1::/w — could not confirm these closed: 1 agent session (claude). Retry with force delete (--force) to remove it anyway.' + ) + ).toEqual({ + title: 'Failed to delete workspace feature/foo', + description: + 'Orca could not confirm every agent session in this workspace has closed, so it stopped before deleting any files. Use Force Delete to remove it anyway.', + isDestructive: false + }) + }) + + // Why: the same split the PTY pair above draws. Force Delete proceeds either way, and telling a + // user "could not confirm" about a conversation Orca watched stay attached asks them to waive a + // doubt that does not exist — the work in that conversation goes with the delete. + it('names the running agent sessions when the close left them attached', () => { + expect( + toastCopyForRemovalError( + 'feature/foo', + 'Refusing to remove worktree with running agent sessions: repo-1::/w — still live: 2 agent sessions (claude, codex). Retry with force delete (--force) to remove it anyway.' + ) + ).toEqual({ + title: 'Failed to delete workspace feature/foo', + description: + 'This workspace still has running agent sessions that Orca could not close, so it stopped before deleting any files. Force Delete will discard any work they hold.', + isDestructive: false + }) + }) + // Why: a sweep that never answered wedges removal the same way, and the waiver clears // both — so it must reach the same force affordance instead of a dead end. it('offers force delete when the teardown sweep itself timed out', () => { diff --git a/src/renderer/src/components/sidebar/delete-worktree-toast.ts b/src/renderer/src/components/sidebar/delete-worktree-toast.ts index 946e99eadee..dc32abfc40f 100644 --- a/src/renderer/src/components/sidebar/delete-worktree-toast.ts +++ b/src/renderer/src/components/sidebar/delete-worktree-toast.ts @@ -2,6 +2,7 @@ import { translate } from '@/i18n/i18n' import { isLockedWorktreeRemovalError, isProvenLivePtyRemovalError, + isProvenLiveStructuredSessionRemovalError, type WorktreeForceDeleteReason } from '../../../../shared/worktree/removal' export type DeleteWorktreeToastCopy = { @@ -81,13 +82,19 @@ export function getDeleteWorktreeToastCopy( 'Failed to delete workspace {{value0}}', { value0: worktreeName } ), - // Why this is not the "could not confirm" wording: Orca watched these sessions stay - // attached, so there is no doubt to waive — Force Delete ends a conversation that is - // running right now, and any work it holds goes with it. - description: translate( - 'auto.components.sidebar.delete.worktree.toast.runningAgentSession', - 'This workspace still has running agent sessions, so Orca stopped before deleting any files. Force Delete will close them and discard any work they hold.' - ), + // Why two branches, like the PTY pair above: an ordinary delete already tried to close + // these sessions, and only the observation AFTER that attempt separates one Orca watched + // stay attached from one it simply could not reach. Telling the first user "could not + // confirm" asks them to waive a doubt that does not exist, and a conversation dies with it. + description: isProvenLiveStructuredSessionRemovalError(error) + ? translate( + 'auto.components.sidebar.delete.worktree.toast.runningAgentSessionLive', + 'This workspace still has running agent sessions that Orca could not close, so it stopped before deleting any files. Force Delete will discard any work they hold.' + ) + : translate( + 'auto.components.sidebar.delete.worktree.toast.runningAgentSession', + 'Orca could not confirm every agent session in this workspace has closed, so it stopped before deleting any files. Use Force Delete to remove it anyway.' + ), isDestructive: false } } diff --git a/src/renderer/src/components/sidebar/folder-workspace-composer-submit.test.ts b/src/renderer/src/components/sidebar/folder-workspace-composer-submit.test.ts index a96564b6652..ef27dfcc03b 100644 --- a/src/renderer/src/components/sidebar/folder-workspace-composer-submit.test.ts +++ b/src/renderer/src/components/sidebar/folder-workspace-composer-submit.test.ts @@ -116,6 +116,7 @@ describe('submitFolderWorkspaceCreate', () => { }) expect(onOpenChange).toHaveBeenCalledWith(false) expect(mocks.activateAndRevealFolderWorkspace).toHaveBeenCalledWith('folder-workspace-1', { + agent: null, runtimeEnvironmentId: null }) expect(consoleError).toHaveBeenCalledWith( @@ -532,6 +533,7 @@ describe('submitFolderWorkspaceCreate', () => { linkedTask: linkedWorkItem }) expect(mocks.activateAndRevealFolderWorkspace).toHaveBeenCalledWith('folder-workspace-1', { + agent: null, runtimeEnvironmentId: null }) expect(mocks.ensureAgentStartupInTerminal).not.toHaveBeenCalled() @@ -659,6 +661,7 @@ describe('submitFolderWorkspaceCreate', () => { }) expect(onOpenChange).toHaveBeenCalledWith(false) expect(mocks.activateAndRevealFolderWorkspace).toHaveBeenCalledWith('folder-workspace-1', { + agent: null, runtimeEnvironmentId: null }) }) diff --git a/src/renderer/src/components/sidebar/folder-workspace-composer-submit.ts b/src/renderer/src/components/sidebar/folder-workspace-composer-submit.ts index 34eab00e730..77ff1c193b8 100644 --- a/src/renderer/src/components/sidebar/folder-workspace-composer-submit.ts +++ b/src/renderer/src/components/sidebar/folder-workspace-composer-submit.ts @@ -207,6 +207,7 @@ export async function submitFolderWorkspaceCreate({ onOpenChange(false) try { let activation = activateAndRevealFolderWorkspace(workspace.id, { + agent: quickAgent, ...(!structuredLaunch && startup ? { startup } : {}), ...(structuredLaunch ? { providesInitialSurface: true } : {}), runtimeEnvironmentId @@ -229,6 +230,7 @@ export async function submitFolderWorkspaceCreate({ connectionId: workspace.connectionId ?? projectGroup.connectionId }) const fallbackActivation = activateAndRevealFolderWorkspace(workspace.id, { + agent: quickAgent, ...(startup ? { startup } : {}), runtimeEnvironmentId }) diff --git a/src/renderer/src/components/sidebar/sidebar-host-options.test.ts b/src/renderer/src/components/sidebar/sidebar-host-options.test.ts index 454268c24c4..6fe8d0d5901 100644 --- a/src/renderer/src/components/sidebar/sidebar-host-options.test.ts +++ b/src/renderer/src/components/sidebar/sidebar-host-options.test.ts @@ -77,11 +77,10 @@ describe('sidebar host options', () => { }) expect(hosts.map((host) => host.id)).toEqual(['local', 'runtime:runtime-1']) - // Without live status the focused runtime has no proof of reachability, so it - // reads 'disconnected' rather than defaulting to 'available'/"Connected". + // A first probe still in progress is not evidence of disconnection. expect(hosts.find((host) => host.id === 'runtime:runtime-1')).toMatchObject({ detail: 'Orca server', - health: 'disconnected' + health: 'connecting' }) }) diff --git a/src/renderer/src/components/sidebar/sleep-worktree-flow.test.ts b/src/renderer/src/components/sidebar/sleep-worktree-flow.test.ts index b63b37f2926..c38f0d4e36d 100644 --- a/src/renderer/src/components/sidebar/sleep-worktree-flow.test.ts +++ b/src/renderer/src/components/sidebar/sleep-worktree-flow.test.ts @@ -1,9 +1,20 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' const mocks = vi.hoisted(() => { - const state = { - activeWorktreeId: null as string | null, - setActiveWorktree: vi.fn(), + const state: { + activeWorktreeId: string | null + setActiveWorktree: ReturnType + shutdownWorktreeBrowsers: ReturnType + shutdownWorktreeTerminals: ReturnType + suppressPtyExit: ReturnType + consumeSuppressedPtyExit: ReturnType + tabsByWorktree: Record + ptyIdsByTabId: Record + } = { + activeWorktreeId: null, + setActiveWorktree: vi.fn((worktreeId: string | null) => { + state.activeWorktreeId = worktreeId + }), shutdownWorktreeBrowsers: vi.fn().mockResolvedValue(undefined), shutdownWorktreeTerminals: vi.fn().mockResolvedValue(undefined), suppressPtyExit: vi.fn(), @@ -33,7 +44,8 @@ vi.mock('@/store', () => ({ vi.mock('sonner', () => ({ toast: { error: mocks.toastError } })) vi.mock('@/lib/worktree-sleep-intent', () => ({ clearWorktreeSleepIntent: mocks.clearWorktreeSleepIntent, - markWorktreeSleepIntent: mocks.markWorktreeSleepIntent + markWorktreeSleepIntent: mocks.markWorktreeSleepIntent, + withWorktreeSleepTeardown: (_worktreeId: string, teardown: () => Promise) => teardown() })) import { runSleepWorktree, runSleepWorktrees } from './sleep-worktree-flow' @@ -95,19 +107,17 @@ describe('runSleepWorktree', () => { expect(activeClear).toBeLessThan(browsersCall) }) - it('marks active sleep intent before clearing the active slept worktree', async () => { + it('marks sleep intent before clearing the active slept worktree and keeps it after teardown', async () => { mocks.state.activeWorktreeId = 'wt-1' await runSleepWorktree('wt-1') expect(mocks.markWorktreeSleepIntent).toHaveBeenCalledWith('wt-1') - expect(mocks.clearWorktreeSleepIntent).toHaveBeenCalledWith('wt-1') const markCall = mocks.markWorktreeSleepIntent.mock.invocationCallOrder[0] const activeClear = mocks.state.setActiveWorktree.mock.invocationCallOrder[0] - const terminalShutdown = mocks.state.shutdownWorktreeTerminals.mock.invocationCallOrder[0] - const clearCall = mocks.clearWorktreeSleepIntent.mock.invocationCallOrder[0] expect(markCall).toBeLessThan(activeClear) - expect(terminalShutdown).toBeLessThan(clearCall) + // Why: the marker outlives a successful sleep so mounted panes stay cold until an explicit wake. + expect(mocks.clearWorktreeSleepIntent).not.toHaveBeenCalled() }) it('preserves active row position through section-scoped sidebar row ids', async () => { @@ -181,14 +191,56 @@ describe('runSleepWorktree', () => { expect(pinnedGetBoundingClientRect).not.toHaveBeenCalled() }) - it('leaves activeWorktreeId alone when sleeping a background worktree', async () => { + it('leaves activeWorktreeId alone and marks a background worktree slept', async () => { mocks.state.activeWorktreeId = 'wt-other' await runSleepWorktree('wt-1') expect(mocks.state.setActiveWorktree).not.toHaveBeenCalled() expect(mocks.state.suppressPtyExit).not.toHaveBeenCalled() - expect(mocks.markWorktreeSleepIntent).not.toHaveBeenCalled() + expect(mocks.markWorktreeSleepIntent).toHaveBeenCalledWith('wt-1') + expect(mocks.clearWorktreeSleepIntent).not.toHaveBeenCalled() + }) + + it('leaves a worktree the user activated mid-batch awake', async () => { + let releaseFirst: () => void = () => {} + mocks.state.shutdownWorktreeBrowsers.mockImplementationOnce( + () => + new Promise((resolve) => { + releaseFirst = resolve + }) + ) + + const run = runSleepWorktrees(['wt-1', 'wt-2']) + await Promise.resolve() + // Why: the user clicked wt-2 while wt-1 was tearing down; sleeping it anyway + // must not leave the active workspace marked with no clear pending. + mocks.state.activeWorktreeId = 'wt-2' + releaseFirst() + await run + + expect(mocks.clearWorktreeSleepIntent).toHaveBeenLastCalledWith('wt-2') + }) + + it('marks each worktree only when its own teardown starts', async () => { + let releaseFirst: () => void = () => {} + mocks.state.shutdownWorktreeBrowsers.mockImplementationOnce( + () => + new Promise((resolve) => { + releaseFirst = resolve + }) + ) + + const run = runSleepWorktrees(['wt-1', 'wt-2']) + await Promise.resolve() + + // Why: wt-2 is still awake while wt-1 tears down; marking it early would + // hold its panes cold and swallow its activity. + expect(mocks.markWorktreeSleepIntent).toHaveBeenCalledWith('wt-1') + expect(mocks.markWorktreeSleepIntent).not.toHaveBeenCalledWith('wt-2') + releaseFirst() + await run + expect(mocks.markWorktreeSleepIntent).toHaveBeenCalledWith('wt-2') }) it('surfaces a toast and skips terminals when browsers throws', async () => { diff --git a/src/renderer/src/components/sidebar/sleep-worktree-flow.ts b/src/renderer/src/components/sidebar/sleep-worktree-flow.ts index cf474b28e54..1e414a81800 100644 --- a/src/renderer/src/components/sidebar/sleep-worktree-flow.ts +++ b/src/renderer/src/components/sidebar/sleep-worktree-flow.ts @@ -1,6 +1,10 @@ import { toast } from 'sonner' import { useAppStore } from '@/store' -import { clearWorktreeSleepIntent, markWorktreeSleepIntent } from '@/lib/worktree-sleep-intent' +import { + clearWorktreeSleepIntent, + markWorktreeSleepIntent, + withWorktreeSleepTeardown +} from '@/lib/worktree-sleep-intent' import { VIRTUALIZED_SCROLL_ANCHOR_RECORD_EVENT } from '@/hooks/useVirtualizedScrollAnchor' import { translate } from '@/i18n/i18n' @@ -141,15 +145,15 @@ export async function runSleepWorktrees(worktreeIds: readonly string[]): Promise shutdownWorktreeBrowsers, shutdownWorktreeTerminals } = useAppStore.getState() - let activeSleepIntentWorktreeId: string | null = null - if (activeWorktreeId && worktreeIds.includes(activeWorktreeId)) { - const restoreSidebarPosition = preserveSidebarWorktreePosition(activeWorktreeId) + const sleptActiveWorktreeId = + activeWorktreeId && worktreeIds.includes(activeWorktreeId) ? activeWorktreeId : null + if (sleptActiveWorktreeId) { + const restoreSidebarPosition = preserveSidebarWorktreePosition(sleptActiveWorktreeId) // Why: clearing the active workspace can unmount TerminalPanes before - // shutdownWorktreeTerminals writes PTY suppressions. Use a non-rendering - // intent marker so those exits do not stamp activity, without inserting an - // extra Zustand update that can disturb the sidebar's scroll restoration. - markWorktreeSleepIntent(activeWorktreeId) - activeSleepIntentWorktreeId = activeWorktreeId + // shutdownWorktreeTerminals writes PTY suppressions; mark first so those + // exits do not stamp activity. Kept off the store so it cannot disturb the + // sidebar's scroll restoration. + markWorktreeSleepIntent(sleptActiveWorktreeId) setActiveWorktree(null) restoreSidebarPosition() } @@ -157,13 +161,17 @@ export async function runSleepWorktrees(worktreeIds: readonly string[]): Promise const failedWorktreeIds = new Set() try { for (const worktreeId of worktreeIds) { + // Why: the marker outlives teardown so the panes left mounted stay cold + // until an explicit wake (#10205); mark per workspace so an earlier + // slow teardown never leaves a later, still-awake one marked. + markWorktreeSleepIntent(worktreeId) try { // Why: sleep mirrors removeWorktree's shutdown sequence — browsers first // so destroyPersistentWebview unregisters the Chromium guests before any // other teardown runs, terminals second so the PTY kill uses the same // ordering on both paths. Without the browser thunk here, sleep leaks // browserPagesByWorkspace entries and live webviews for the slept worktree. - await shutdownWorktreeBrowsers(worktreeId) + await withWorktreeSleepTeardown(worktreeId, () => shutdownWorktreeBrowsers(worktreeId)) } catch (err) { console.error('[sleep-worktree] browser shutdown failed', { worktreeId, error: err }) failedWorktreeIds.add(worktreeId) @@ -178,9 +186,15 @@ export async function runSleepWorktrees(worktreeIds: readonly string[]): Promise // history dir (local) or relay session id (SSH); it also captures // serializer buffers into buffersByLeafId for SSH wake to reseed // scrollback. See DESIGN_DOC_TERMINAL_HISTORY_FIX_V2.md §3.3.c. - await shutdownWorktreeTerminals(worktreeId, { keepIdentifiers: true }) - if (typeof window !== 'undefined' && window.api?.ephemeralVm?.suspendWorkspace) { - await window.api.ephemeralVm.suspendWorkspace({ workspaceId: worktreeId }) + await withWorktreeSleepTeardown(worktreeId, async () => { + await shutdownWorktreeTerminals(worktreeId, { keepIdentifiers: true }) + if (typeof window !== 'undefined' && window.api?.ephemeralVm?.suspendWorkspace) { + await window.api.ephemeralVm.suspendWorkspace({ workspaceId: worktreeId }) + } + }) + // Why: a workspace the user activated during the batch is awake by their choice. + if (useAppStore.getState().activeWorktreeId === worktreeId) { + clearWorktreeSleepIntent(worktreeId) } } catch (err) { console.error('[sleep-worktree] terminal or host suspension failed', { @@ -192,12 +206,12 @@ export async function runSleepWorktrees(worktreeIds: readonly string[]): Promise } } } finally { - if (activeSleepIntentWorktreeId) { - clearWorktreeSleepIntent(activeSleepIntentWorktreeId) - if (failedWorktreeIds.has(activeSleepIntentWorktreeId)) { - // Why: any failed sleep step must leave the workspace visible and retryable. - setActiveWorktree(activeSleepIntentWorktreeId) - } + // Why: a failed sleep leaves the workspace awake and retryable. + for (const worktreeId of failedWorktreeIds) { + clearWorktreeSleepIntent(worktreeId) + } + if (sleptActiveWorktreeId && failedWorktreeIds.has(sleptActiveWorktreeId)) { + setActiveWorktree(sleptActiveWorktreeId) } } if (errors.length > 0) { diff --git a/src/renderer/src/components/sidebar/use-worktree-card-foundation.ts b/src/renderer/src/components/sidebar/use-worktree-card-foundation.ts index fc339bbe33f..d8ec20bb45a 100644 --- a/src/renderer/src/components/sidebar/use-worktree-card-foundation.ts +++ b/src/renderer/src/components/sidebar/use-worktree-card-foundation.ts @@ -10,6 +10,10 @@ import { getHostDisplayLabelOverrides } from '../../../../shared/host-setting-ov import { getWorkspacePortsByWorktreeId } from '@/lib/workspace-port-groups' import { getExplicitRuntimeEnvironmentIdForWorktree } from '@/lib/worktree-runtime-owner' import { hydrateRuntimeEnvironmentSshState } from '@/runtime/runtime-environment-ssh-state' +import { + isDisconnectedRuntimeHostState, + runtimeHostConnectionStateForEntry +} from '@/runtime/runtime-host-connection-state' import { useAppStore } from '@/store' import { selectRuntimeAwareSshStatus, @@ -177,12 +181,17 @@ export function useWorktreeCardFoundation({ const runtimeHostLabel = runtimeHostId ? (getHostDisplayLabelOverrides(settings).get(runtimeHostId) ?? runtimeEnvironmentName) : null - // Why: runtime ("Orca server") hosts get the same disconnected dimming as SSH when their environment has no live status. + // Why the shared derivation, not raw truthiness: an absent entry means "not probed yet", + // which is not the same verdict as a probe that came back unreachable. const isRuntimeDisconnected = useAppStore((s) => { if (!runtimeOwnerEnvironmentId) { return false } - return !s.runtimeStatusByEnvironmentId.get(runtimeOwnerEnvironmentId)?.status + return isDisconnectedRuntimeHostState( + runtimeHostConnectionStateForEntry( + s.runtimeStatusByEnvironmentId.get(runtimeOwnerEnvironmentId) + ) + ) }) const [titleRenaming, setTitleRenaming] = useState(false) const [showRenameErrorDialog, setShowRenameErrorDialog] = useState(false) diff --git a/src/renderer/src/components/sidebar/useWorktreeAgentRows.test.ts b/src/renderer/src/components/sidebar/useWorktreeAgentRows.test.ts index bd410ddc2a2..34393219518 100644 --- a/src/renderer/src/components/sidebar/useWorktreeAgentRows.test.ts +++ b/src/renderer/src/components/sidebar/useWorktreeAgentRows.test.ts @@ -91,17 +91,19 @@ function makeSplitPaneLayout(firstLeafId: string, secondLeafId: string): Termina describe('buildWorktreeAgentRows', () => { it('includes retained rows even when their original tab is no longer current', () => { + const retained = makeRetained(ORPHAN_PANE_KEY, 'wt-1', 1000) const rows = buildWorktreeAgentRows({ tabs: [makeTab('tab-1')], entries: [], // Why: useWorktreeAgentRows filters retained snapshots by worktreeId, not // current tab membership. This is the sidebar behavior that sleep cleanup // must counter by dropping worktree-scoped retained rows. - retained: [makeRetained(ORPHAN_PANE_KEY, 'wt-1', 1000)], + retained: [retained], now: 2000 }) expect(rows.map((row) => row.paneKey)).toEqual([ORPHAN_PANE_KEY]) + expect(rows[0].tab).toBe(retained.tab) expect(rows[0].state).toBe('done') }) diff --git a/src/renderer/src/components/sidebar/worktree-agent-rows.ts b/src/renderer/src/components/sidebar/worktree-agent-rows.ts index 21e69b89e8c..009c562447f 100644 --- a/src/renderer/src/components/sidebar/worktree-agent-rows.ts +++ b/src/renderer/src/components/sidebar/worktree-agent-rows.ts @@ -78,7 +78,7 @@ function isRetainedLegacyAliasOfSeenStablePane(args: { function markSeenPaneKeyForCurrentTab(args: { paneKey: string | undefined - currentTabIds: Set + currentTabsById: ReadonlyMap terminalLayoutsByTabId?: Record seenPaneKeys: Set }): void { @@ -87,14 +87,14 @@ function markSeenPaneKeyForCurrentTab(args: { } const parsed = parsePaneKey(args.paneKey) if (parsed) { - if (args.currentTabIds.has(parsed.tabId)) { + if (args.currentTabsById.has(parsed.tabId)) { args.seenPaneKeys.add(args.paneKey) } return } const legacy = parseLegacyNumericPaneKey(args.paneKey) - if (!legacy || !args.currentTabIds.has(legacy.tabId)) { + if (!legacy || !args.currentTabsById.has(legacy.tabId)) { return } args.seenPaneKeys.add(args.paneKey) @@ -112,7 +112,7 @@ function markCompletedWorkerParentPaneKeysSeen(args: { retained: RetainedAgentEntry[] runtimeAgentOrchestrationByPaneKey?: Record terminalLayoutsByTabId?: Record - currentTabIds: Set + currentTabsById: ReadonlyMap seenPaneKeys: Set }): void { const markEntry = (entry: AgentStatusEntry): void => { @@ -124,7 +124,7 @@ function markCompletedWorkerParentPaneKeysSeen(args: { // visible parent pane still has a stale spinner title. markSeenPaneKeyForCurrentTab({ paneKey: rowEntry.orchestration?.parentPaneKey, - currentTabIds: args.currentTabIds, + currentTabsById: args.currentTabsById, terminalLayoutsByTabId: args.terminalLayoutsByTabId, seenPaneKeys: args.seenPaneKeys }) @@ -150,7 +150,7 @@ export function buildWorktreeAgentRows(args: { }): DashboardAgentRow[] { const rows: DashboardAgentRow[] = [] const seenPaneKeys = new Set() - const currentTabIds = new Set(args.tabs.map((tab) => tab.id)) + const currentTabsById = new Map(args.tabs.map((tab) => [tab.id, tab] as const)) const entriesByTabId = new Map() for (const entry of args.entries) { @@ -199,7 +199,7 @@ export function buildWorktreeAgentRows(args: { retained: args.retained, runtimeAgentOrchestrationByPaneKey: args.runtimeAgentOrchestrationByPaneKey, terminalLayoutsByTabId: args.terminalLayoutsByTabId, - currentTabIds, + currentTabsById, seenPaneKeys }) @@ -256,11 +256,12 @@ export function buildWorktreeAgentRows(args: { ra.entry, args.runtimeAgentOrchestrationByPaneKey ) + const tab = currentTabsById.get(ra.tab.id) ?? ra.tab rows.push({ paneKey: rowEntry.paneKey, entry: rowEntry, - tab: ra.tab, - agentType: resolveRowAgentType(rowEntry, ra.tab), + tab, + agentType: resolveRowAgentType(rowEntry, tab), rowSource: 'retained', state: 'done', startedAt: ra.startedAt diff --git a/src/renderer/src/components/status-bar/SshStatusSegment.tsx b/src/renderer/src/components/status-bar/SshStatusSegment.tsx index be74c0fd7f2..cfaeeeb6bdc 100644 --- a/src/renderer/src/components/status-bar/SshStatusSegment.tsx +++ b/src/renderer/src/components/status-bar/SshStatusSegment.tsx @@ -33,7 +33,7 @@ import { } from './remote-host-connection-status' import { isConnectedRuntimeHostState, - runtimeHostConnectionState, + runtimeHostConnectionStateForEntry, runtimeStatusForOverall } from '@/runtime/runtime-host-connection-state' import { refreshRuntimeProjectWorktreesAndLineage } from '@/hooks/runtime-project-refresh-scheduler' @@ -74,7 +74,7 @@ export function SshStatusSegment({ const settings = useAppStore((s) => s.settings) const runtimeEnvironments = useAppStore((s) => s.runtimeEnvironments) const runtimeStatusByEnvironmentId = useAppStore((s) => s.runtimeStatusByEnvironmentId) - const setRuntimeEnvironmentStatus = useAppStore((s) => s.setRuntimeEnvironmentStatus) + const readRuntimeHostStatusSnapshots = useAppStore((s) => s.readRuntimeHostStatusSnapshots) const hydrateRuntimeEnvironmentStatuses = useAppStore((s) => s.hydrateRuntimeEnvironmentStatuses) const remoteWorkspaceSyncStatusByTargetId = useAppStore( (s) => s.remoteWorkspaceSyncStatusByTargetId @@ -105,7 +105,7 @@ export function SshStatusSegment({ return { id: environment.id, label: override || environment.name || environment.id, - hasStatusEntry: Boolean(statusEntry), + snapshot: statusEntry?.snapshot, status: statusEntry?.status ?? null, active: settings?.activeRuntimeEnvironmentId === environment.id, remoteControl: statusEntry?.remoteControl ?? statusEntry?.status?.remoteControl ?? null @@ -113,7 +113,7 @@ export function SshStatusSegment({ }) const runtimeHostRows = runtimeHosts.map((host) => ({ ...host, - state: runtimeHostConnectionState(host) + state: runtimeHostConnectionStateForEntry(runtimeStatusByEnvironmentId.get(host.id)) })) // Available remote servers are online even when they are not the active runtime. // Keep host health separate from the advanced active-server selection. @@ -152,11 +152,7 @@ export function SshStatusSegment({ async (environmentId: string): Promise => { try { await window.api.runtimeEnvironments.disconnect({ selector: environmentId }) - setRuntimeEnvironmentStatus( - environmentId, - { status: null, checkedAt: Date.now() }, - { suppressDisconnectToast: true } - ) + await readRuntimeHostStatusSnapshots() recordFeatureInteraction('ssh') } catch (err) { toast.error( @@ -169,7 +165,7 @@ export function SshStatusSegment({ ) } }, - [recordFeatureInteraction, setRuntimeEnvironmentStatus] + [recordFeatureInteraction, readRuntimeHostStatusSnapshots] ) if (targets.length === 0 && runtimeHosts.length === 0) { diff --git a/src/renderer/src/components/tab-bar/EditorFileTabContextMenu.tsx b/src/renderer/src/components/tab-bar/EditorFileTabContextMenu.tsx index 1813265573f..a6df437feac 100644 --- a/src/renderer/src/components/tab-bar/EditorFileTabContextMenu.tsx +++ b/src/renderer/src/components/tab-bar/EditorFileTabContextMenu.tsx @@ -32,11 +32,22 @@ const isMac = navigator.userAgent.includes('Mac') const isLinux = navigator.userAgent.includes('Linux') /** Platform-appropriate label: macOS → Finder, Windows → File Explorer, Linux → Files */ -const revealLabel = isMac - ? 'Reveal in Finder' - : isLinux - ? 'Open Containing Folder' - : 'Reveal in File Explorer' +function getRevealLabel(): string { + return isMac + ? translate( + 'auto.components.tab.bar.EditorFileTabContextMenu.revealInFinder', + 'Reveal in Finder' + ) + : isLinux + ? translate( + 'auto.components.tab.bar.EditorFileTabContextMenu.openContainingFolder', + 'Open Containing Folder' + ) + : translate( + 'auto.components.tab.bar.EditorFileTabContextMenu.revealInFileExplorer', + 'Reveal in File Explorer' + ) +} type EditorFileTabContextMenuProps = { open: boolean @@ -251,7 +262,7 @@ export function EditorFileTabContextMenu({ }} > - {revealLabel} + {getRevealLabel()} diff --git a/src/renderer/src/components/tab-bar/tab-bar-static-create-menu.tsx b/src/renderer/src/components/tab-bar/tab-bar-static-create-menu.tsx index 9a7a19a9186..45c39c2da55 100644 --- a/src/renderer/src/components/tab-bar/tab-bar-static-create-menu.tsx +++ b/src/renderer/src/components/tab-bar/tab-bar-static-create-menu.tsx @@ -13,7 +13,7 @@ import { import type { TabBarProps } from './tab-bar-props' import { resolveWindowsShellLaunchTarget } from './windows-shell-launch' -export function renderTabBarStaticCreateMenu({ +export function TabBarStaticCreateMenu({ terminalOnly, mobileEmulatorEnabled, managedBrowserCreationEnabled, diff --git a/src/renderer/src/components/tab-bar/tab-bar-surface.tsx b/src/renderer/src/components/tab-bar/tab-bar-surface.tsx index dcf22611227..0e9540870e3 100644 --- a/src/renderer/src/components/tab-bar/tab-bar-surface.tsx +++ b/src/renderer/src/components/tab-bar/tab-bar-surface.tsx @@ -22,7 +22,7 @@ import type { TabBarCreateMenuController } from './use-tab-bar-create-menu-contr import type { TabBarItemProjection } from './use-tab-bar-item-projection' import type { TabBarItem } from './tab-bar-item-model' import { renderTabBarItems } from './tab-bar-item-surface' -import { renderTabBarStaticCreateMenu } from './tab-bar-static-create-menu' +import { TabBarStaticCreateMenu } from './tab-bar-static-create-menu' import ClientHostedBrowserTabRows from './ClientHostedBrowserTabRows' import type { ClientHostedBrowserRow } from '../../../../shared/client-hosted-browser-rows' @@ -99,24 +99,6 @@ export function renderTabBarSurface({ activeClientHostedBrowserRowId, togglePinned }) - const standardCreateMenuItems = renderTabBarStaticCreateMenu({ - props, - terminalOnly, - mobileEmulatorEnabled, - managedBrowserCreationEnabled, - mobileEmulatorCreationEnabled, - workspaceHasSimulatorTab, - showMobileEmulatorIntroCallout, - windowsShellEntries, - defaultWindowsPowerShellImplementation, - pwshAvailable: windowsTerminalCapabilities.pwshAvailable, - newTerminalShortcut, - newBrowserShortcut, - newSimulatorShortcut, - newFileShortcut, - openMarkdownShortcut, - queueNewActiveTerminalFocusAfterNewTabMenuClose - }) return (
: null} ) : null} - {showStaticCreateMenuItems ? standardCreateMenuItems : null} + {showStaticCreateMenuItems ? ( + + ) : null} {showStaticCreateMenuItems && showAgentLaunchItems ? ( <> diff --git a/src/renderer/src/components/terminal-cold-activation.ts b/src/renderer/src/components/terminal-cold-activation.ts index d57cb82d766..8b6e96467ee 100644 --- a/src/renderer/src/components/terminal-cold-activation.ts +++ b/src/renderer/src/components/terminal-cold-activation.ts @@ -16,6 +16,7 @@ import type { TerminalParkingFoundation } from './use-terminal-parking-foundatio export function applyTerminalColdActivation(controller: TerminalParkingFoundation) { const { + activationDeferralPlanRevisionRef, activationDeferredMountTabIdsByWorktreeRef, activeGroupIdByWorktree, activeTabId, @@ -96,7 +97,7 @@ export function applyTerminalColdActivation(controller: TerminalParkingFoundatio if (lastActivationWorktreeIdRef.current !== renderedActiveWorktreeId) { lastActivationWorktreeIdRef.current = renderedActiveWorktreeId const tabById = new Map(worktreeTabs.map((tab) => [tab.id, tab])) - planColdActivationTabDeferral({ + const installedDeferralPlan = planColdActivationTabDeferral({ restrictions: backgroundMountTabIdsByWorktreeRef.current, deferredMountTabIdsByWorktree: activationDeferredMountTabIdsByWorktreeRef.current, worktreeId: renderedActiveWorktreeId, @@ -118,6 +119,11 @@ export function applyTerminalColdActivation(controller: TerminalParkingFoundatio }, immediateTabIds }) + // Why: the install mutates only refs, so without a returned revision the + // admission drain's effect deps never change and the plan strands. + if (installedDeferralPlan) { + activationDeferralPlanRevisionRef.current += 1 + } } else if (!coldActivationDeferralEnabled || !activationHostSupportsDeferral) { backgroundMountTabIdsByWorktreeRef.current.delete(renderedActiveWorktreeId) activationDeferredMountTabIdsByWorktreeRef.current.delete(renderedActiveWorktreeId) @@ -165,7 +171,10 @@ export function applyTerminalColdActivation(controller: TerminalParkingFoundatio groupsByWorktree, activeGroupIdByWorktree ) - return { anyMountedWorktreeHasLayout } + return { + anyMountedWorktreeHasLayout, + activationDeferralPlanRevision: activationDeferralPlanRevisionRef.current + } } export type TerminalColdActivationController = TerminalParkingFoundation & diff --git a/src/renderer/src/components/terminal-pane/CloseTerminalDialog.test.tsx b/src/renderer/src/components/terminal-pane/CloseTerminalDialog.test.tsx index d2b8efd3efa..0531720fe47 100644 --- a/src/renderer/src/components/terminal-pane/CloseTerminalDialog.test.tsx +++ b/src/renderer/src/components/terminal-pane/CloseTerminalDialog.test.tsx @@ -4,6 +4,11 @@ import { act } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, describe, expect, it, vi } from 'vitest' import CloseTerminalDialog from './CloseTerminalDialog' +import { translate } from '@/i18n/i18n' + +vi.mock('@/i18n/i18n', () => ({ + translate: vi.fn((_key: string, fallback: string) => fallback) +})) const mountedRoots: Root[] = [] @@ -49,6 +54,22 @@ describe('CloseTerminalDialog', () => { document.body.innerHTML = '' }) + it('does no dialog-copy work while closed, then builds the opened confirmation', async () => { + const container = document.createElement('div') + document.body.appendChild(container) + const root = createRoot(container) + mountedRoots.push(root) + const props = { onCancel: vi.fn(), onConfirm: vi.fn() } + vi.mocked(translate).mockClear() + + await act(async () => root.render()) + expect(translate).not.toHaveBeenCalled() + + await act(async () => root.render()) + expect(document.body.textContent).toContain('Stop running command?') + expect(translate).toHaveBeenCalled() + }) + it('renders running command copy and confirms without skipping by default', async () => { const onConfirm = vi.fn() diff --git a/src/renderer/src/components/terminal-pane/CloseTerminalDialog.tsx b/src/renderer/src/components/terminal-pane/CloseTerminalDialog.tsx index c4da5244457..9edbca8b22e 100644 --- a/src/renderer/src/components/terminal-pane/CloseTerminalDialog.tsx +++ b/src/renderer/src/components/terminal-pane/CloseTerminalDialog.tsx @@ -70,71 +70,104 @@ export default function CloseTerminalDialog({ }} > - - - {isAgent - ? translate( - 'auto.components.terminal.pane.CloseTerminalDialog.stop_agent_title', - 'Stop this agent?' - ) - : translate( - 'auto.components.terminal.pane.CloseTerminalDialog.stop_command_title', - 'Stop running command?' - )} - - - {isAgent - ? translate( - 'auto.components.terminal.pane.CloseTerminalDialog.stop_agent_description', - "Closing this terminal will stop the agent's current work." - ) - : translate( - 'auto.components.terminal.pane.CloseTerminalDialog.stop_command_description', - 'Closing this terminal will stop the command running inside it.' - )} - - - {trimmedTabLabel ? ( -

- {trimmedTabLabel} -

- ) : null} -
- setDontAskAgain(checked === true)} - /> - -
- - - - +
) } + +// Keep translation and element construction behind the dialog portal's mount boundary. +function CloseTerminalDialogBody({ + isAgent, + trimmedTabLabel, + checkboxId, + dontAskAgain, + setDontAskAgain, + onCancel, + onConfirm +}: { + isAgent: boolean + trimmedTabLabel: string | undefined + checkboxId: string + dontAskAgain: boolean + setDontAskAgain: (value: boolean) => void + onCancel: () => void + onConfirm: (dontAskAgain: boolean) => void +}): React.JSX.Element { + return ( + <> + + + {isAgent + ? translate( + 'auto.components.terminal.pane.CloseTerminalDialog.stop_agent_title', + 'Stop this agent?' + ) + : translate( + 'auto.components.terminal.pane.CloseTerminalDialog.stop_command_title', + 'Stop running command?' + )} + + + {isAgent + ? translate( + 'auto.components.terminal.pane.CloseTerminalDialog.stop_agent_description', + "Closing this terminal will stop the agent's current work." + ) + : translate( + 'auto.components.terminal.pane.CloseTerminalDialog.stop_command_description', + 'Closing this terminal will stop the command running inside it.' + )} + + + {trimmedTabLabel ? ( +

+ {trimmedTabLabel} +

+ ) : null} +
+ setDontAskAgain(checked === true)} + /> + +
+ + + + + + ) +} diff --git a/src/renderer/src/components/terminal-pane/TerminalContextMenu.test.tsx b/src/renderer/src/components/terminal-pane/TerminalContextMenu.test.tsx index 58a39f28a50..bd25abcce74 100644 --- a/src/renderer/src/components/terminal-pane/TerminalContextMenu.test.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalContextMenu.test.tsx @@ -2,6 +2,7 @@ import React from 'react' import { renderToStaticMarkup } from 'react-dom/server' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import TerminalContextMenu from './TerminalContextMenu' +import { translate } from '@/i18n/i18n' import type { KeybindingOverrides } from '../../../../shared/keybindings' type ItemProps = { onSelect?: () => void; children?: React.ReactNode } @@ -13,9 +14,12 @@ vi.mock('@/components/ui/dropdown-menu', async () => { const React_ = await import('react') const passthrough = ({ children }: { children?: React.ReactNode }) => React_.createElement(React_.Fragment, null, children) + const OpenContext = React_.createContext(false) return { - DropdownMenu: passthrough, - DropdownMenuContent: passthrough, + DropdownMenu: ({ open, children }: { open: boolean; children?: React.ReactNode }) => + React_.createElement(OpenContext.Provider, { value: open }, children), + DropdownMenuContent: ({ children }: { children?: React.ReactNode }) => + React_.useContext(OpenContext) ? passthrough({ children }) : null, DropdownMenuLabel: passthrough, DropdownMenuSeparator: () => null, DropdownMenuShortcut: ({ children }: { children?: React.ReactNode }) => { @@ -36,7 +40,7 @@ vi.mock('@/components/ui/dropdown-menu', async () => { } } }) -vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string) => fallback })) +vi.mock('@/i18n/i18n', () => ({ translate: vi.fn((_key: string, fallback: string) => fallback) })) vi.mock('@/lib/agent-catalog', () => ({ AgentIcon: () => null })) vi.mock('./terminal-context-menu-dismiss', () => ({ shouldIgnoreTerminalMenuPointerDownOutside: () => false @@ -104,6 +108,7 @@ function renderMenu(overrides: Record = {}): string { describe('TerminalContextMenu', () => { beforeEach(() => { + vi.mocked(translate).mockClear() items.list = [] shortcuts.list = [] vi.stubGlobal('navigator', { userAgent: 'Linux' }) @@ -113,6 +118,16 @@ describe('TerminalContextMenu', () => { vi.unstubAllGlobals() }) + it('does no menu-copy work while closed, then builds the opened menu', () => { + renderMenu({ open: false }) + expect(translate).not.toHaveBeenCalled() + expect(items.list).toHaveLength(0) + + renderMenu() + expect(translate).toHaveBeenCalled() + expect(items.list.length).toBeGreaterThan(0) + }) + it('renders a "Copy Context" item that triggers onCopyAgentSessionContext (issue #5020)', () => { const onCopyAgentSessionContext = vi.fn() const onForkAgentSession = vi.fn() @@ -167,6 +182,7 @@ describe('TerminalContextMenu', () => { item?.onSelect?.() expect(onCopyAgentSessionId).toHaveBeenCalledTimes(1) + vi.mocked(translate).mockClear() items.list = [] renderMenu({ canCopyAgentSessionId: false }) expect( diff --git a/src/renderer/src/components/terminal-pane/TerminalContextMenu.tsx b/src/renderer/src/components/terminal-pane/TerminalContextMenu.tsx index 2cc76cd7164..5236d61d1a6 100644 --- a/src/renderer/src/components/terminal-pane/TerminalContextMenu.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalContextMenu.tsx @@ -78,11 +78,59 @@ type TerminalContextMenuProps = { onCopyAgentSessionId: () => void } -export default function TerminalContextMenu({ - open, +export default function TerminalContextMenu(props: TerminalContextMenuProps): React.JSX.Element { + const { open, onOpenChange, menuPoint, menuOpenedAtRef } = props + return ( + { + if (!nextOpen && Date.now() - menuOpenedAtRef.current < 100) { + return + } + onOpenChange(nextOpen) + }} + modal={false} + > + +
-
+
- {simulatorRepoName && ( - - - - - - - )} + @@ -187,16 +182,15 @@ export function WorktreeJumpPaletteBrowserRow({ } />
-
+
- {browserRepoName && ( - - - - - - - )} + { const title = row?.querySelector('[data-slot="palette-open-tab-title"]') const worktree = row?.querySelector('[data-slot="palette-open-tab-worktree"]') expect(title?.textContent).toBe(longTitle) - expect(title?.classList.contains('flex-auto')).toBe(true) + expect(title?.classList.contains('min-w-0')).toBe(true) + expect(title?.classList.contains('shrink-0')).toBe(false) expect(worktree?.textContent).toBe('user-support') + const locationChip = worktree?.closest('[data-slot="palette-location-chip"]') + expect(locationChip).not.toBeNull() + expect(locationChip?.parentElement?.classList.contains('max-w-[40%]')).toBe(true) + expect(locationChip?.parentElement?.classList.contains('min-w-0')).toBe(true) expect(worktree?.compareDocumentPosition(title ?? document.createElement('span'))).toBe( Node.DOCUMENT_POSITION_PRECEDING ) }) - it('tags the worktree rail label as a branch when the visible name is the branch', async () => { + it('shows the branch in the location chip when the workspace display name is empty', async () => { await renderPalette({ worktreesByRepo: { 'repo-1': [makeWorktree('wt-tabs', '', { displayName: '' })] diff --git a/src/renderer/src/components/worktree-jump-palette-primitives.test.tsx b/src/renderer/src/components/worktree-jump-palette-primitives.test.tsx index a54a48329be..8834c240086 100644 --- a/src/renderer/src/components/worktree-jump-palette-primitives.test.tsx +++ b/src/renderer/src/components/worktree-jump-palette-primitives.test.tsx @@ -3,7 +3,7 @@ import { cleanup, render, type RenderResult, screen } from '@testing-library/react' import { afterEach, expect, it } from 'vitest' import { TooltipProvider } from '@/components/ui/tooltip' -import { PaletteOpenTabPrimaryLine } from './worktree-jump-palette-primitives' +import { PaletteLocationChip, PaletteOpenTabPrimaryLine } from './worktree-jump-palette-primitives' afterEach(() => cleanup()) @@ -18,8 +18,6 @@ function renderPrimaryLine( secondaryText="src/app.ts" secondaryRanges={[]} secondaryMatches={secondaryMatches} - worktreeName="Workspace" - worktreeRanges={[]} /> ) @@ -45,3 +43,114 @@ it('renders no badge when every secondary match is already shown', () => { expect(screen.queryByText(/^\+\d+$/)).toBeNull() }) + +it('elides a deep path from the head so the matched tail stays visible', () => { + const path = '/Users/me/projects/orca/new-create-button-design/proposals/create-button.html' + const start = path.indexOf('create-butt') + const { container } = render( + + + + ) + + const secondary = container.querySelector('[data-slot="palette-open-tab-secondary"]') + expect(secondary?.textContent).toBe(path) + const [head, tail] = Array.from(secondary?.children ?? []) + expect(head?.textContent).toBe('/Users/me/projects/orca') + expect(tail?.textContent).toBe('/new-create-button-design/proposals/create-button.html') + expect(tail?.querySelector('.font-semibold')?.textContent).toBe('create-butt') +}) + +it('keeps slash-separated agent snippets intact', () => { + const snippet = + 'Ran pnpm test src/renderer/src/components/worktree-jump-palette-primitives.test.tsx' + const start = snippet.indexOf('worktree-jump') + const { container } = render( + + + + ) + + const secondary = container.querySelector('[data-slot="palette-open-tab-secondary"]') + expect(secondary?.textContent).toBe(snippet) + expect(secondary?.children).toHaveLength(1) + expect(secondary?.querySelector('.font-semibold')?.textContent).toBe('worktree-jump') +}) + +it('folds the worktree into the repo chip and drops it when it repeats the repo name', () => { + const { container, rerender } = render( + + + + ) + expect(container.querySelector('[data-slot="palette-location-chip"]')?.textContent).toBe( + 'orca·new-create-button-design' + ) + const chip = container.querySelector('[data-slot="palette-location-chip"]') + const repo = container.querySelector('[data-slot="palette-location-repo"]') + const worktree = container.querySelector('[data-slot="palette-open-tab-worktree"]') + expect(chip?.className).toContain('overflow-hidden') + expect(chip?.className).toContain('min-w-0') + expect(repo?.className).toContain('max-w-[55%]') + expect(repo?.className).toContain('min-w-[3ch]') + expect(worktree?.className).toContain('min-w-[3ch]') + expect(worktree?.getAttribute('data-state')).toBeNull() + expect(worktree?.getAttribute('tabindex')).toBeNull() + + rerender( + + + + ) + expect(container.querySelector('[data-slot="palette-location-chip"]')?.textContent).toBe('orca') + expect( + container.querySelector('[data-slot="palette-location-repo"] .font-semibold')?.textContent + ).toBe('orca') +}) + +it('keeps a short title at its natural width so the session age stays beside it', () => { + const { container } = render( + + + + ) + + const title = container.querySelector('[data-slot="palette-open-tab-title"]') + expect(title?.className).toContain('min-w-0') + expect(title?.className).not.toContain('shrink-0') +}) + +it('caps the title only when it shares the line with secondary text', () => { + const { container } = renderPrimaryLine([]) + + const title = container.querySelector('[data-slot="palette-open-tab-title"]') + expect(title?.className).toContain('max-w-[62%]') + expect(title?.className).toContain('shrink-0') +}) diff --git a/src/renderer/src/components/worktree-jump-palette-primitives.tsx b/src/renderer/src/components/worktree-jump-palette-primitives.tsx index 4162a56cb6e..aadad46748d 100644 --- a/src/renderer/src/components/worktree-jump-palette-primitives.tsx +++ b/src/renderer/src/components/worktree-jump-palette-primitives.tsx @@ -1,11 +1,12 @@ -import React, { useLayoutEffect, useRef, useState } from 'react' +import React from 'react' import { ShortcutKeyCombo } from '@/components/ShortcutKeyCombo' import { translate } from '@/i18n/i18n' import type { PaletteHostBadge } from '@/components/cmd-j/palette-host-badge' import type { MatchRange, PaletteSearchResult } from '@/lib/worktree-palette-search' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import type { Worktree } from '../../../shared/worktree/types' -import { resolveWorktreeBranchLabel } from '@/lib/worktree-default-display-name' +import { splitPathHeadForElision } from '@/lib/path-head-elision' +import { RepoBadgeMark } from '@/components/repo/RepoBadgeLabel' +import { cn } from '@/lib/utils' const NO_SECONDARY_MATCHES: readonly { text: string; ranges: readonly MatchRange[] }[] = [] @@ -67,14 +68,51 @@ export function HighlightedText({ return <>{parts} } +function PaletteOpenTabSecondaryText({ + text, + ranges, + elidePathHead +}: { + text: string + ranges: readonly MatchRange[] + elidePathHead: boolean +}): React.JSX.Element { + const split = elidePathHead ? splitPathHeadForElision(text, ranges) : null + const content = split ? ( + + {split.head} + + + + + ) : ( + + + + ) + return ( + + {content} + + {text} + + + ) +} + export function PaletteOpenTabPrimaryLine({ title, titleRanges, secondaryText, secondaryRanges, secondaryMatches = NO_SECONDARY_MATCHES, - worktreeName, - worktreeRanges, + elideSecondaryPathHead = false, sessionAge, leadingBadges }: { @@ -83,13 +121,11 @@ export function PaletteOpenTabPrimaryLine({ secondaryText: string secondaryRanges: readonly MatchRange[] secondaryMatches?: readonly { text: string; ranges: readonly MatchRange[] }[] - worktreeName: string - worktreeRanges: readonly MatchRange[] + elideSecondaryPathHead?: boolean sessionAge?: string leadingBadges?: React.ReactNode }): React.JSX.Element { const showSecondary = secondaryText.trim().length > 0 - const showWorktree = worktreeName.trim().length > 0 const additionalSecondaryMatches = secondaryMatches.filter( (match) => match.text && match.text !== secondaryText ) @@ -98,7 +134,10 @@ export function PaletteOpenTabPrimaryLine({
@@ -116,12 +155,11 @@ export function PaletteOpenTabPrimaryLine({ ) : null} {leadingBadges} {showSecondary ? ( - <> - · - - - - + ) : null} {additionalSecondaryMatches.length ? ( <> @@ -154,85 +192,76 @@ export function PaletteOpenTabPrimaryLine({ ) : null} - {showWorktree ? ( - <> - · - - - - - ) : null}
) } -function resolveOpenTabWorktreeRailTooltip({ - isBranch, - truncated, - name +export function PaletteLocationChip({ + repoName, + repoRanges, + repoColor, + worktreeName, + worktreeRanges, + className }: { - isBranch: boolean - truncated: boolean - name: string -}): string { - if (truncated) { - return name - } - return isBranch - ? translate('auto.components.WorktreeJumpPalette.paletteOpenTabBranch', 'Branch name') - : translate('auto.components.WorktreeJumpPalette.paletteOpenTabWorkspace', 'Workspace name') -} - -export function PaletteOpenTabWorktreeRailLabel({ - name, - matchRanges, - worktree, - className, - slot = 'palette-open-tab-worktree' -}: { - name: string - matchRanges: readonly MatchRange[] - worktree?: Pick | null + repoName: string + repoRanges: readonly MatchRange[] + repoColor?: string + worktreeName: string + worktreeRanges: readonly MatchRange[] className?: string - slot?: string }): React.JSX.Element | null { - const [truncated, setTruncated] = useState(false) - const labelRef = useRef(null) - useLayoutEffect(() => { - const node = labelRef.current - if (!node) { - setTruncated(false) - return - } - const updateTruncated = (): void => { - const next = node.scrollWidth > node.clientWidth - setTruncated((current) => (current === next ? current : next)) - } - updateTruncated() - if (typeof ResizeObserver === 'undefined') { - return - } - const observer = new ResizeObserver(updateTruncated) - observer.observe(node) - return () => observer.disconnect() - }, [name]) - if (name.trim().length === 0) { + const showRepo = repoName.trim().length > 0 + const repeatedName = showRepo && worktreeName === repoName + const showWorktree = worktreeName.trim().length > 0 && !repeatedName + if (!showRepo && !showWorktree) { return null } - const isBranch = worktree != null && name === resolveWorktreeBranchLabel(worktree) - const tooltip = resolveOpenTabWorktreeRailTooltip({ isBranch, truncated, name }) + const repoMatchRanges = repeatedName + ? [...repoRanges, ...worktreeRanges].sort((left, right) => left.start - right.start) + : repoRanges + const label = [showRepo ? repoName : '', showWorktree ? worktreeName : ''] + .filter(Boolean) + .join(' · ') + const chip = ( + + {showRepo ? ( + <> + + + + + + ) : null} + {showRepo && showWorktree ? ( + + · + + ) : null} + {showWorktree ? ( + + + + ) : null} + + ) return ( - - - - - - - {tooltip} + {chip} + + {label} ) diff --git a/src/renderer/src/components/worktree-jump-palette-workspace-tab-row.tsx b/src/renderer/src/components/worktree-jump-palette-workspace-tab-row.tsx index 787cbff449c..0763300eca7 100644 --- a/src/renderer/src/components/worktree-jump-palette-workspace-tab-row.tsx +++ b/src/renderer/src/components/worktree-jump-palette-workspace-tab-row.tsx @@ -3,20 +3,20 @@ import { FileText, SquareTerminal } from 'lucide-react' import { AgentIcon } from '@/lib/agent-catalog' import { CommandItem } from '@/components/ui/command' import { PaletteRecentTabStatusDot } from '@/components/cmd-j/palette-live-status' -import { RepoBadgeMark } from '@/components/repo/RepoBadgeLabel' import { getPaletteHostBadge } from '@/components/cmd-j/palette-host-badge' import { cn } from '@/lib/utils' import { translate } from '@/i18n/i18n' import type { WorkspaceTabPaletteItem } from './worktree-jump-palette-model' import type { WorktreeJumpPaletteController } from './use-worktree-jump-palette-controller' import { - HighlightedText, PaletteHostBadgeChip, + PaletteLocationChip, PaletteOpenTabPrimaryLine, PaletteRowShortcutBadge } from './worktree-jump-palette-primitives' import { formatPaletteSessionAge } from '@/components/cmd-j/palette-session-age' import { resolvePaletteRepoForWorktree } from '@/lib/palette-repo-resolution' +import { isEditorTabContentType } from '@/store/slices/editor/tabs/editor-tab-content-type' export function WorktreeJumpPaletteWorkspaceTabRow({ entry, @@ -76,8 +76,7 @@ export function WorktreeJumpPaletteWorkspaceTabRow({ secondaryText={result.secondaryText} secondaryRanges={result.secondaryRanges} secondaryMatches={result.secondaryMatches} - worktreeName={result.worktreeName} - worktreeRanges={result.worktreeRanges} + elideSecondaryPathHead={isEditorTabContentType(result.contentType)} sessionAge={sessionAge} leadingBadges={ <> @@ -103,16 +102,15 @@ export function WorktreeJumpPaletteWorkspaceTabRow({ ) : null}
-
+
- {workspaceTabRepoName && ( - - - - - - - )} + Promise, + onPresent: () => void +): { request: () => void; dispose: () => void } { + let disposed = false + let pending = false + return { + request() { + if (disposed || pending) { + return + } + pending = true + void readAway() + .then((away) => { + // Unknown presence must not clear unread attention. + if (!disposed && away === false) { + onPresent() + } + }) + .catch(() => {}) + .finally(() => { + pending = false + }) + }, + dispose() { + disposed = true + } + } +} + +export function subscribeAutoAckPresenceSignals( + onRescan: () => void, + onInput: () => void +): () => void { + const input = (event: Event): void => { + if (event.isTrusted) { + onInput() + } + } + document.addEventListener('visibilitychange', onRescan) + window.addEventListener('focus', onRescan) + const events = ['pointerdown', 'keydown', 'pointermove'] as const + for (const event of events) { + window.addEventListener(event, input) + } + return () => { + document.removeEventListener('visibilitychange', onRescan) + window.removeEventListener('focus', onRescan) + for (const event of events) { + window.removeEventListener(event, input) + } + } +} diff --git a/src/renderer/src/hooks/agent-auto-ack-targets.ts b/src/renderer/src/hooks/agent-auto-ack-targets.ts new file mode 100644 index 00000000000..bd832dd7482 --- /dev/null +++ b/src/renderer/src/hooks/agent-auto-ack-targets.ts @@ -0,0 +1,37 @@ +import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' + +export type AutoAckTabTarget = { tabId: string; worktreeId: string | null } + +/** + * Tabs whose visible pane counts as "seen" right now, each paired with the worktree that owns it. + * + * Why the floating workspace is gated on panel visibility rather than `activeView`: the panel is an + * overlay that sits above every view and stays mounted while closed, and its active tab never + * becomes the global `activeTabId` — so neither the view nor the tab id can stand in for "on screen". + */ +export function resolveAutoAckTabTargets( + state: { + activeView: string + activeTabId: string | null + activeWorktreeId: string | null + activeTabIdByWorktree: Record + }, + options: { floatingPanelVisible: boolean } +): AutoAckTabTarget[] { + const targets: AutoAckTabTarget[] = [] + if (options.floatingPanelVisible) { + const floatingTabId = state.activeTabIdByWorktree[FLOATING_TERMINAL_WORKTREE_ID] ?? null + // The floating pane is on top when two worktrees claim the same tab ID. + if (floatingTabId) { + targets.push({ tabId: floatingTabId, worktreeId: FLOATING_TERMINAL_WORKTREE_ID }) + } + } + if ( + state.activeView === 'terminal' && + state.activeTabId && + !targets.some((target) => target.tabId === state.activeTabId) + ) { + targets.push({ tabId: state.activeTabId, worktreeId: state.activeWorktreeId }) + } + return targets +} diff --git a/src/renderer/src/hooks/agent-hook-completion-fresh-working.test.ts b/src/renderer/src/hooks/agent-hook-completion-fresh-working.test.ts index 006a848fdab..fef0a2c95fc 100644 --- a/src/renderer/src/hooks/agent-hook-completion-fresh-working.test.ts +++ b/src/renderer/src/hooks/agent-hook-completion-fresh-working.test.ts @@ -12,7 +12,7 @@ type MockStoreState = { settings: { experimentalTerminalAttention: boolean notifications: { enabled: boolean; agentTaskComplete: boolean } - } + } | null ptyIdsByTabId: Record suppressedPtyExitIds: Record tabsByWorktree: Record @@ -71,12 +71,14 @@ describe('agent hook completion fresh-working gate', () => { afterEach(() => vi.useRealTimers()) - it('stays gated through a stamped working completion after re-enable', async () => { + it('waits for fresh working after settings hydration before dispatching completion', async () => { const { observeAgentHookCompletionForNotification, syncAgentHookCompletionNotificationSettings } = await import('./agent-hook-completion-notifications') + const hydratedSettings = mockStoreState.settings + mockStoreState.settings = null syncAgentHookCompletionNotificationSettings() observeAgentHookCompletionForNotification({ paneKey: PANE_KEY, @@ -84,7 +86,7 @@ describe('agent hook completion fresh-working gate', () => { payload: { ...working(), stateStartedAt: 1_000 } }) - mockStoreState.settings.notifications.agentTaskComplete = true + mockStoreState.settings = hydratedSettings syncAgentHookCompletionNotificationSettings() observeAgentHookCompletionForNotification({ paneKey: PANE_KEY, diff --git a/src/renderer/src/hooks/agent-hook-completion-notifications.test.ts b/src/renderer/src/hooks/agent-hook-completion-notifications.test.ts index 71233c7f697..2b39a07a4fb 100644 --- a/src/renderer/src/hooks/agent-hook-completion-notifications.test.ts +++ b/src/renderer/src/hooks/agent-hook-completion-notifications.test.ts @@ -170,7 +170,7 @@ describe('agent hook completion notifications', () => { afterEach(() => vi.useRealTimers()) - it('requires fresh working after notifications start disabled and later re-enable', async () => { + it('keeps completion tracking active across desktop notification changes', async () => { mockStoreState.settings.notifications.agentTaskComplete = false const { observeAgentHookCompletionForNotification, @@ -187,7 +187,7 @@ describe('agent hook completion notifications', () => { payload: hookStatus('done') }) - expect(dispatchTerminalNotification).not.toHaveBeenCalled() + expect(dispatchTerminalNotification).toHaveBeenCalledTimes(1) observeAgentHookCompletionForNotification({ paneKey, @@ -201,6 +201,7 @@ describe('agent hook completion notifications', () => { }) vi.advanceTimersByTime(HOOK_DONE_QUIET_MS) + expect(dispatchTerminalNotification).toHaveBeenCalledTimes(2) expect(dispatchTerminalNotification).toHaveBeenCalledWith( 'wt-1', expect.objectContaining({ @@ -216,7 +217,7 @@ describe('agent hook completion notifications', () => { ) }, 15_000) - it('accepts hook lifecycle while every completion alert consumer is disabled', async () => { + it('offers hook completion to mobile while desktop notifications and attention are disabled', async () => { mockStoreState.settings.notifications.agentTaskComplete = false mockStoreState.settings.experimentalTerminalAttention = false const { @@ -240,13 +241,13 @@ describe('agent hook completion notifications', () => { paneKey, expect.objectContaining({ state: 'done', agentType: 'codex' }) ) - expect(dispatchTerminalNotification).not.toHaveBeenCalled() + expect(dispatchTerminalNotification).toHaveBeenCalledTimes(1) mockStoreState.settings.notifications.agentTaskComplete = true syncAgentHookCompletionNotificationSettings() vi.advanceTimersByTime(HOOK_DONE_QUIET_MS) - expect(dispatchTerminalNotification).not.toHaveBeenCalled() + expect(dispatchTerminalNotification).toHaveBeenCalledTimes(1) }) it('tracks hook completion for terminal attention when OS completion notifications are disabled', async () => { @@ -266,8 +267,7 @@ describe('agent hook completion notifications', () => { 'wt-1', expect.objectContaining({ source: 'agent-task-complete', - paneKey, - suppressOsNotification: true + paneKey }) ) }, 15_000) diff --git a/src/renderer/src/hooks/agent-hook-completion-notifications.ts b/src/renderer/src/hooks/agent-hook-completion-notifications.ts index 7d226331eed..dbf8ca45f6d 100644 --- a/src/renderer/src/hooks/agent-hook-completion-notifications.ts +++ b/src/renderer/src/hooks/agent-hook-completion-notifications.ts @@ -99,17 +99,8 @@ function pruneClosedPaneCoordinators(): void { } } -function isAgentTaskCompleteNotificationEnabled(): boolean { - const notifications = useAppStore.getState().settings?.notifications - return notifications?.enabled !== false && notifications?.agentTaskComplete !== false -} - -function isTerminalAttentionEnabled(): boolean { - return useAppStore.getState().settings?.experimentalTerminalAttention === true -} - function isAgentTaskCompleteTrackingEnabled(): boolean { - return isAgentTaskCompleteNotificationEnabled() || isTerminalAttentionEnabled() + return isAgentHookCompletionTrackingEnabled(useAppStore.getState()) } function syncAgentTaskCompleteTrackingEnabled(enabled: boolean): void { @@ -260,7 +251,6 @@ function createCoordinator(paneKey: string, worktreeId: string): AgentCompletion source: 'agent-task-complete', terminalTitle: title, paneKey, - suppressOsNotification: !isAgentTaskCompleteNotificationEnabled(), ...(meta?.agentStatus ? { agentStatusSnapshot: meta.agentStatus } : {}) }) }, @@ -274,7 +264,6 @@ function createCoordinator(paneKey: string, worktreeId: string): AgentCompletion source: 'agent-task-complete', terminalTitle: title, paneKey, - suppressOsNotification: !isAgentTaskCompleteNotificationEnabled(), agentStatusSnapshot: meta.agentStatus }) }, diff --git a/src/renderer/src/hooks/agent-hook-completion-store-sync.test.ts b/src/renderer/src/hooks/agent-hook-completion-store-sync.test.ts index de1f22eca11..972059d56c1 100644 --- a/src/renderer/src/hooks/agent-hook-completion-store-sync.test.ts +++ b/src/renderer/src/hooks/agent-hook-completion-store-sync.test.ts @@ -130,7 +130,13 @@ describe('agent hook completion store sync', () => { notifications: { enabled: false, agentTaskComplete: false } } }) - expect(shouldSyncAgentHookCompletionForStoreUpdate(trackingDisabled, previous)).toBe(true) + expect(shouldSyncAgentHookCompletionForStoreUpdate(trackingDisabled, previous)).toBe(false) + expect( + shouldSyncAgentHookCompletionForStoreUpdate( + createState({ ...previous, settings: null }), + previous + ) + ).toBe(true) }) it('treats tab order and duplicate-id worktree precedence as liveness inputs', () => { diff --git a/src/renderer/src/hooks/agent-hook-completion-store-sync.ts b/src/renderer/src/hooks/agent-hook-completion-store-sync.ts index 12c7d9102d6..a884625b11a 100644 --- a/src/renderer/src/hooks/agent-hook-completion-store-sync.ts +++ b/src/renderer/src/hooks/agent-hook-completion-store-sync.ts @@ -1,3 +1,6 @@ +import { isAgentTaskCompleteTrackingEnabledFromState as isAgentHookCompletionTrackingEnabled } from '@/components/terminal-pane/agent-task-complete-policy' +export { isAgentHookCompletionTrackingEnabled } + type CompletionNotificationSettings = { readonly enabled?: boolean readonly agentTaskComplete?: boolean @@ -24,15 +27,6 @@ export type AgentHookCompletionStoreSnapshot = { type TabVisit = () => void -export function isAgentHookCompletionTrackingEnabled( - state: AgentHookCompletionStoreSnapshot -): boolean { - const notifications = state.settings?.notifications - const notificationEnabled = - notifications?.enabled !== false && notifications?.agentTaskComplete !== false - return notificationEnabled || state.settings?.experimentalTerminalAttention === true -} - function terminalTabLivenessMatches( current: AgentHookCompletionStoreSnapshot['tabsByWorktree'], previous: AgentHookCompletionStoreSnapshot['tabsByWorktree'], diff --git a/src/renderer/src/hooks/composer-state/full-creation-execution.ts b/src/renderer/src/hooks/composer-state/full-creation-execution.ts index 28961e355c6..1ad5a92abab 100644 --- a/src/renderer/src/hooks/composer-state/full-creation-execution.ts +++ b/src/renderer/src/hooks/composer-state/full-creation-execution.ts @@ -219,6 +219,7 @@ export function useFullCreationExecution(input: FullCreationExecutionInput) { const initialActivation = activateAndRevealWorktree(worktree.id, { sidebarRevealBehavior: 'auto', + agent: tuiAgent, setup: result.setup, defaultTabs: result.defaultTabs, issueCommand, @@ -229,6 +230,7 @@ export function useFullCreationExecution(input: FullCreationExecutionInput) { const settlement = await settleFullCreationStructuredLaunch({ plan: launchPlan, + agent: tuiAgent, worktreeId: worktree.id, startup, pendingFirstAgentMessageRename, diff --git a/src/renderer/src/hooks/composer-state/full-creation-structured-launch.test.ts b/src/renderer/src/hooks/composer-state/full-creation-structured-launch.test.ts index 4a7b569bf79..d3808357ee8 100644 --- a/src/renderer/src/hooks/composer-state/full-creation-structured-launch.test.ts +++ b/src/renderer/src/hooks/composer-state/full-creation-structured-launch.test.ts @@ -36,6 +36,7 @@ const plan = (overrides: Partial = {}) => const baseArgs = { plan: plan(), + agent: 'codex' as const, worktreeId: 'worktree-1', startup: { command: 'codex' } as never, pendingFirstAgentMessageRename: true, @@ -94,6 +95,7 @@ describe('settleFullCreationStructuredLaunch', () => { }) expect(mocks.activateAndRevealWorktree).toHaveBeenCalledWith('worktree-1', { sidebarRevealBehavior: 'auto', + agent: 'codex', createNewTerminalForStartup: true, startup: baseArgs.startup }) diff --git a/src/renderer/src/hooks/composer-state/full-creation-structured-launch.ts b/src/renderer/src/hooks/composer-state/full-creation-structured-launch.ts index c7e19026ba7..4293e97505a 100644 --- a/src/renderer/src/hooks/composer-state/full-creation-structured-launch.ts +++ b/src/renderer/src/hooks/composer-state/full-creation-structured-launch.ts @@ -3,12 +3,14 @@ import type { WorktreeStartupPayload } from '@/lib/worktree-startup-payload' import { activateAndRevealWorktree } from '@/lib/worktree-activation' import type { StructuredAgentLaunchSettlement } from '@/lib/structured-agent-launch-settlement' import { activateStructuredAgentSessionById } from '@/lib/structured-agent-session-tab-activation' +import type { TuiAgent } from '../../../../shared/tui-agent' /** Full-create dialog: the structured launch plus what this flow did before structured chat * existed. Returns null when the plan's route is not structured. */ export async function settleFullCreationStructuredLaunch(args: { /** Planned before the worktree existed; `worktreeId` names the one that was created. */ plan: AgentSessionLaunchPlan + agent: TuiAgent worktreeId: string startup: WorktreeStartupPayload | undefined pendingFirstAgentMessageRename: boolean @@ -27,6 +29,7 @@ export async function settleFullCreationStructuredLaunch(args: { } const activation = activateAndRevealWorktree(args.worktreeId, { sidebarRevealBehavior: 'auto', + agent: args.agent, createNewTerminalForStartup: true, ...(args.startup ? { startup: args.startup } : {}) }) diff --git a/src/renderer/src/hooks/ipc-events-agent-status-store-test-fixtures.ts b/src/renderer/src/hooks/ipc-events-agent-status-store-test-fixtures.ts index 609b3fb562c..96bca500d21 100644 --- a/src/renderer/src/hooks/ipc-events-agent-status-store-test-fixtures.ts +++ b/src/renderer/src/hooks/ipc-events-agent-status-store-test-fixtures.ts @@ -167,6 +167,10 @@ export function buildStoreState(overrides: StoreLike): StoreLike { updateTabTitles: vi.fn(), runtimePaneTitlesByTabId: {}, terminalLayoutsByTabId: {}, + ptyIdsByTabId: {}, + suppressedPtyExitIds: {}, + markWorktreeUnread: vi.fn(), + markAgentCompletionPaneUnread: vi.fn(), agentStatusByPaneKey: {}, setAgentStatuses: vi.fn(() => []), recordAgentProviderSession: vi.fn(), diff --git a/src/renderer/src/hooks/ipc-events-agent-status-window-test-fixtures.ts b/src/renderer/src/hooks/ipc-events-agent-status-window-test-fixtures.ts index 5b50e3d0520..e1b5f548996 100644 --- a/src/renderer/src/hooks/ipc-events-agent-status-window-test-fixtures.ts +++ b/src/renderer/src/hooks/ipc-events-agent-status-window-test-fixtures.ts @@ -127,6 +127,7 @@ export function buildWindowApi(args: { onDetectedPortsChanged: () => () => {}, ...args.ssh }, + notifications: { dispatch: vi.fn(async () => ({ delivered: false })) }, agentStatus: { onSet: args.onSet, onClear: args.onClear ?? vi.fn(() => () => {}), diff --git a/src/renderer/src/hooks/ipc-events-test-harness.ts b/src/renderer/src/hooks/ipc-events-test-harness.ts index ae9efcc798e..b3d1ef71b98 100644 --- a/src/renderer/src/hooks/ipc-events-test-harness.ts +++ b/src/renderer/src/hooks/ipc-events-test-harness.ts @@ -140,6 +140,9 @@ export async function loadIpcEventsHarness( dispatchEvent: vi.fn(), api: new Proxy( { + runtimeEnvironments: createApiNamespaceStub({ + getStatusSnapshots: () => Promise.resolve([]) + }), ui: createApiNamespaceStub({ getZoomLevel: () => 0, consumePendingOpenSettings: () => Promise.resolve(false), diff --git a/src/renderer/src/hooks/ipc-events/app-lifetime-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/app-lifetime-ipc-bridge.ts index fa683b7188f..c5964d77fec 100644 --- a/src/renderer/src/hooks/ipc-events/app-lifetime-ipc-bridge.ts +++ b/src/renderer/src/hooks/ipc-events/app-lifetime-ipc-bridge.ts @@ -1,3 +1,4 @@ +import type { RuntimeHostStatusSnapshot } from '../../../../shared/runtime-host-status' import { getTabIdsAwaitingHostHydrationRemount } from '@/lib/parked-terminal-host-hydration' import { emitAutomationsChangedWindowEvent } from '@/lib/automations-changed-window-event' import { createBackgroundSleepingAgentWakeDispatcher } from '@/lib/wake-sleeping-agents-in-background' @@ -63,13 +64,23 @@ export function installAppLifetimeIpcEvents( ) const worktreeRuntime = createWorktreeEventRuntime(unsubs, isRuntimeEnvironmentActive) - const onSharedControlDiagnostics = window.api.runtimeEnvironments?.onSharedControlDiagnostics - if (onSharedControlDiagnostics) { - unsubs.push( - onSharedControlDiagnostics((event) => { - useAppStore.getState().publishRuntimeEnvironmentDiagnostics(event) + const statusApi = window.api.runtimeEnvironments + if (statusApi?.onStatusChanged) { + const apply = (snapshot: RuntimeHostStatusSnapshot): void => { + useAppStore.getState().applyRuntimeHostStatusSnapshot(snapshot) + } + let stopped = false + unsubs.push(statusApi.onStatusChanged(apply), () => { + stopped = true + }) + void statusApi + .getStatusSnapshots() + .then((snapshots) => { + if (!stopped) { + snapshots.forEach(apply) + } }) - ) + .catch((error) => console.error('Failed to read runtime status snapshots:', error)) } const unsubscribeRuntimeEnvironmentStore = registerRuntimeClientIpcBridge(unsubs, worktreeRuntime) registerProjectCatalogIpcBridge( diff --git a/src/renderer/src/hooks/ipc-events/runtime-client-ipc-bridge.ts b/src/renderer/src/hooks/ipc-events/runtime-client-ipc-bridge.ts index dc85e375124..a5db87bbce1 100644 --- a/src/renderer/src/hooks/ipc-events/runtime-client-ipc-bridge.ts +++ b/src/renderer/src/hooks/ipc-events/runtime-client-ipc-bridge.ts @@ -29,20 +29,6 @@ import { } from './runtime-environment-subscription-selection' import type { WorktreeEventRuntime } from './worktree-event-runtime' -/** Backoff for re-asking status.get after a probe that failed on its own socket. */ -const RUNTIME_STATUS_PROBE_RETRY_DELAYS_MS = [2_000, 10_000] - -/** - * Why a request carries its reason: `reconnected` must re-ask even when the cache reads - * reachable (a restart changes the runtimeId under an unchanged-looking status), while - * `recordedUnreachable` is satisfied by any answer that clears the offline verdict. - */ -type RuntimeStatusProbeTrigger = 'reconnected' | 'recordedUnreachable' - -function isRuntimeStatusRecordedUnreachable(environmentId: string): boolean { - return useAppStore.getState().runtimeStatusByEnvironmentId?.get(environmentId)?.status === null -} - export function registerRuntimeClientIpcBridge( unsubs: (() => void)[], worktreeRuntime: WorktreeEventRuntime @@ -148,107 +134,6 @@ export function registerRuntimeClientIpcBridge( }) } - const inFlightRuntimeStatusProbes = new Set() - const trailingRuntimeStatusProbes = new Map() - const runtimeStatusProbeRetryTimers = new Map>() - let runtimeStatusProbesStopped = false - // Why not the desired-subscription set alone: a host that is not the active environment - // drops out of it the moment anything records its status unreachable, so gating the - // retry on it cancels the retry exactly where recovery matters. Only removal - // (or a still-unhydrated catalog behind an active id) decides whether to keep asking, - // and the tombstone covers the window where settings still names a deleted host active. - const shouldProbeRuntimeStatus = (environmentId: string): boolean => { - const state = useAppStore.getState() - if (state.removedRuntimeEnvironmentIds?.has(environmentId)) { - return false - } - return ( - (state.runtimeEnvironments ?? []).some((environment) => environment.id === environmentId) || - getRuntimeClientEventEnvironmentIds(state).includes(environmentId) - ) - } - // Why: concurrent probes resolve in arbitrary order, so a slow one can publish its - // stale answer over a newer one and leave the sidebar naming a superseded runtime. - const probeRuntimeStatus = ( - environmentId: string, - attempt = 0, - trigger: RuntimeStatusProbeTrigger = 'reconnected' - ): void => { - if (runtimeStatusProbesStopped || !shouldProbeRuntimeStatus(environmentId)) { - return - } - if (inFlightRuntimeStatusProbes.has(environmentId)) { - // Serialize, don't drop: the in-flight answer predates this request, so a reconnect - // that lands mid-probe would otherwise go unasked — and a probe that succeeds - // schedules no retry to pick it up later. A reconnect outranks a queued - // recorded-unreachable request, which the in-flight answer may already settle. - if (trigger === 'reconnected' || !trailingRuntimeStatusProbes.has(environmentId)) { - trailingRuntimeStatusProbes.set(environmentId, trigger) - } - return - } - const pendingRetry = runtimeStatusProbeRetryTimers.get(environmentId) - if (pendingRetry !== undefined) { - clearTimeout(pendingRetry) - runtimeStatusProbeRetryTimers.delete(environmentId) - } - inFlightRuntimeStatusProbes.add(environmentId) - void useAppStore - .getState() - // publishUnreachable: false — the transport that just proved this host alive is not the - // socket status.get dials, so a failed probe here is unverifiable and must publish nothing. - .refreshRuntimeEnvironmentStatus(environmentId, undefined, { publishUnreachable: false }) - .catch(() => false) - .then((reachable) => { - inFlightRuntimeStatusProbes.delete(environmentId) - const trailingTrigger = trailingRuntimeStatusProbes.get(environmentId) - if (trailingTrigger !== undefined) { - trailingRuntimeStatusProbes.delete(environmentId) - // A newer reconnect asked while this one was dialing: restart the attempt chain. - // A resubscribe only asked because the cache read unreachable, so skip the extra - // socket + E2EE handshake when this answer already cleared that. - if ( - trailingTrigger === 'reconnected' || - isRuntimeStatusRecordedUnreachable(environmentId) - ) { - probeRuntimeStatus(environmentId, 0, trailingTrigger) - return - } - } - // Why: status.get dials its own short-lived socket, so it can fail while the - // control transport that just proved the host is up stays healthy. That failure - // is unverifiable and publishes nothing, so no store transition, resubscribe or - // further trigger follows — without this bounded retry one unlucky probe leaves - // a host already recorded offline stranded until the next transport gap. - const retryDelayMs = RUNTIME_STATUS_PROBE_RETRY_DELAYS_MS[attempt] - if ( - reachable || - retryDelayMs === undefined || - runtimeStatusProbesStopped || - !shouldProbeRuntimeStatus(environmentId) - ) { - return - } - runtimeStatusProbeRetryTimers.set( - environmentId, - setTimeout(() => { - runtimeStatusProbeRetryTimers.delete(environmentId) - probeRuntimeStatus(environmentId, attempt + 1) - }, retryDelayMs) - ) - }) - } - unsubs.push(() => { - // The flag, not just the timers: a probe still in flight at teardown would - // otherwise schedule a fresh retry chain after the bridge is gone. - runtimeStatusProbesStopped = true - trailingRuntimeStatusProbes.clear() - for (const retryTimer of runtimeStatusProbeRetryTimers.values()) { - clearTimeout(retryTimer) - } - runtimeStatusProbeRetryTimers.clear() - }) - const runtimeClientEventsSync = createRuntimeClientEventsSync({ getDesiredEnvironmentIds: () => getRuntimeClientEventEnvironmentIds(useAppStore.getState()), getSubscriptionKey: (environmentId) => buildRuntimeClientEventEnvironmentKey([environmentId]), @@ -271,7 +156,13 @@ export function registerRuntimeClientIpcBridge( () => { invalidateRuntimeClientEventReplay({ getSshStateReference: () => useAppStore.getState().sshStateByEnvironment, - refreshRuntimeStatus: () => probeRuntimeStatus(environmentId), + refreshRuntimeStatus: () => { + const state = useAppStore.getState() + const snapshot = state.runtimeStatusByEnvironmentId.get(environmentId)?.snapshot + if (!snapshot || snapshot.transport === 'unknown') { + void state.refreshRuntimeEnvironmentStatus(environmentId) + } + }, requestProjectRefresh: () => runtimeProjectRefreshScheduler.request(environmentId), markEnvironmentSshStateStale: () => useAppStore.getState().markEnvironmentSshStateStale(environmentId), @@ -281,19 +172,6 @@ export function registerRuntimeClientIpcBridge( }) } ) - // Why: only a reconnect of an already-ready transport replays with the tag above. - // A connection whose first ready lands after the host recovered (app started, or - // the env was added, while it was down) never replays, so the recorded-unreachable - // verdict this subscribe just disproved has to be re-asked here. Kept off the - // returned promise so subscription registration/teardown ordering is unchanged. - void subscription.then( - () => { - if (isRuntimeStatusRecordedUnreachable(environmentId)) { - probeRuntimeStatus(environmentId, 0, 'recordedUnreachable') - } - }, - () => {} - ) return subscription }, onEvent: handleRuntimeClientEvent diff --git a/src/renderer/src/hooks/ipc-events/runtime-reconnect-host-status.test.ts b/src/renderer/src/hooks/ipc-events/runtime-reconnect-host-status.test.ts index 0d605a3fab1..67050a77c19 100644 --- a/src/renderer/src/hooks/ipc-events/runtime-reconnect-host-status.test.ts +++ b/src/renderer/src/hooks/ipc-events/runtime-reconnect-host-status.test.ts @@ -67,16 +67,12 @@ describe('remote Orca server reconnect', () => { }[] = [] let liveRuntimeId = 'remote-runtime' let failingStatusProbes = 0 - let blockNextStatusProbe = false - let releaseBlockedStatusProbe: (() => void) | null = null beforeEach(() => { subscriptionResponders = [] unsubs = [] liveRuntimeId = 'remote-runtime' failingStatusProbes = 0 - blockNextStatusProbe = false - releaseBlockedStatusProbe = null // Module-level sonner double: without this a toast from an earlier test leaks into // the assertions below. vi.mocked(toast.warning).mockClear() @@ -88,12 +84,6 @@ describe('remote Orca server reconnect', () => { // Captured before the block so a probe that is still dialing answers with the // runtime it was dispatched against, not with whatever restarted meanwhile. const dispatchedRuntimeId = liveRuntimeId - if (blockNextStatusProbe) { - blockNextStatusProbe = false - await new Promise((resolve) => { - releaseBlockedStatusProbe = resolve - }) - } if (failingStatusProbes > 0) { failingStatusProbes -= 1 // status.get dials its own socket; it can fail while the control transport is up. @@ -170,261 +160,42 @@ describe('remote Orca server reconnect', () => { } as unknown as WorktreeEventRuntime) } - it('re-probes a replayed subscription while the cached status still looks reachable', async () => { + it('keeps legacy event recovery as a single request, with retries owned outside the renderer', async () => { + vi.useFakeTimers() startBridge() await settle() - expect(sidebarHostHealth()).toBe('available') - - // The gap was short enough that nothing probed during it, so the cached status still - // names the pre-restart runtime and the replay tag is the only evidence it is stale. - liveRuntimeId = 'remote-runtime-restarted' + failingStatusProbes = 1 replaySubscription() await settle() - - expect( - useAppStore.getState().runtimeStatusByEnvironmentId.get(ENVIRONMENT_ID)?.status?.runtimeId - ).toBe('remote-runtime-restarted') - expect(sidebarHostHealth()).toBe('available') - }) - - it('returns the sidebar host to online when the first subscription lands untagged', async () => { - // A connection that was never ready does not replay: nothing tags its first - // response, so a client that booted while the host was down has only the - // successful subscribe as evidence that the recorded verdict is stale. - useAppStore.setState({ - runtimeStatusByEnvironmentId: new Map([ - [ENVIRONMENT_ID, { status: null, checkedAt: Date.now() }] - ]) as never - }) - expect(sidebarHostHealth()).toBe('disconnected') - - startBridge() - await settle() - - expect(sidebarHostHealth()).toBe('available') - expect(subscriptionResponders.length).toBeGreaterThan(0) - }) - - it('re-asks after a probe that failed while the transport stayed up', async () => { - vi.useFakeTimers() - // Already recorded unreachable, so the failing probe's `null` is an unchanged - // re-publication: it writes nothing and leaves no store transition for the - // resubscribe path to key off. Only a retry can still recover this host. - useAppStore.setState({ - runtimeStatusByEnvironmentId: new Map([ - [ENVIRONMENT_ID, { status: null, checkedAt: Date.now() }] - ]) as never - }) - failingStatusProbes = 1 - - startBridge() - await settle() - expect(sidebarHostHealth()).toBe('disconnected') - - await vi.advanceTimersByTimeAsync(2_000) - await settle() - - expect(sidebarHostHealth()).toBe('available') - }) - - it('stops re-asking a host that keeps refusing, instead of polling it forever', async () => { - vi.useFakeTimers() - useAppStore.setState({ - runtimeStatusByEnvironmentId: new Map([ - [ENVIRONMENT_ID, { status: null, checkedAt: Date.now() }] - ]) as never - }) - failingStatusProbes = Number.POSITIVE_INFINITY - - startBridge() - await settle() + expect(window.api.runtimeEnvironments.getStatus).toHaveBeenCalledTimes(1) await vi.advanceTimersByTimeAsync(120_000) - await settle() - - // One probe on the successful subscribe plus the two bounded retries. - expect(window.api.runtimeEnvironments.getStatus).toHaveBeenCalledTimes(3) + expect(window.api.runtimeEnvironments.getStatus).toHaveBeenCalledTimes(1) }) - it('stops probing once the bridge is torn down mid-probe', async () => { - vi.useFakeTimers() + it('does not add a status request when a connection-owned subscription replays', async () => { + useAppStore.getState().applyRuntimeHostStatusSnapshot({ + environmentId: ENVIRONMENT_ID, + pairingRevision: 1, + sequence: 100, + checkedAt: 1, + transport: 'ready', + verification: 'verified', + status: liveRuntimeStatus() + }) + startBridge() + await settle() + replaySubscription() + await settle() + expect(window.api.runtimeEnvironments.getStatus).not.toHaveBeenCalled() + expect(sidebarHostHealth()).toBe('available') + }) + + it('does not start UI recovery machinery when an initial subscription attaches', async () => { useAppStore.setState({ - runtimeStatusByEnvironmentId: new Map([ - [ENVIRONMENT_ID, { status: null, checkedAt: Date.now() }] - ]) as never - }) - failingStatusProbes = Number.POSITIVE_INFINITY - blockNextStatusProbe = true - - startBridge() - await settle() - expect(window.api.runtimeEnvironments.getStatus).toHaveBeenCalledTimes(1) - - // Teardown clears scheduled retries, but this probe has not answered yet. - stopBridge?.() - stopBridge = null - for (const unsub of unsubs.splice(0)) { - unsub() - } - releaseBlockedStatusProbe?.() - await settle() - await vi.advanceTimersByTimeAsync(120_000) - await settle() - - expect(window.api.runtimeEnvironments.getStatus).toHaveBeenCalledTimes(1) - }) - - it('re-asks for a saved host that is not the active environment', async () => { - vi.useFakeTimers() - // A non-active host is only in the desired-subscription set while its status is non-null, - // so gating the retry on that set would strand it offline with its subscription already - // torn down the moment anything else (an explicit disconnect, the toast's own retry) - // records the same outage. - useAppStore.setState({ - settings: { activeRuntimeEnvironmentId: 'env-laptop' } as never + runtimeStatusByEnvironmentId: new Map([[ENVIRONMENT_ID, { status: null, checkedAt: 1 }]]) }) startBridge() await settle() - expect(sidebarHostHealth()).toBe('available') - - failingStatusProbes = 1 - replaySubscription() - await settle() - useAppStore.getState().setRuntimeEnvironmentStatus(ENVIRONMENT_ID, { - status: null, - checkedAt: Date.now() - }) - expect(sidebarHostHealth()).toBe('disconnected') - - await vi.advanceTimersByTimeAsync(2_000) - await settle() - - expect(sidebarHostHealth()).toBe('available') - }) - - it('re-asks after a reconnect that lands while an earlier probe is still dialing', async () => { - blockNextStatusProbe = true - startBridge() - await settle() - replaySubscription() - await settle() - expect(window.api.runtimeEnvironments.getStatus).toHaveBeenCalledTimes(1) - - // The host restarts while that probe is still on its own socket: the transport drops, - // reconnects and replays again. Serializing is right, dropping the request is not — - // the in-flight answer predates the restart this replay is reporting. - liveRuntimeId = 'remote-runtime-restarted' - replaySubscription() - await settle() - expect(window.api.runtimeEnvironments.getStatus).toHaveBeenCalledTimes(1) - - releaseBlockedStatusProbe?.() - await settle() - - expect( - useAppStore.getState().runtimeStatusByEnvironmentId.get(ENVIRONMENT_ID)?.status?.runtimeId - ).toBe('remote-runtime-restarted') - }) - - it('does not resurrect a host removed while a retry was pending', async () => { - vi.useFakeTimers() - useAppStore.setState({ - runtimeStatusByEnvironmentId: new Map([ - [ENVIRONMENT_ID, { status: null, checkedAt: Date.now() }] - ]) as never - }) - failingStatusProbes = Number.POSITIVE_INFINITY - - startBridge() - await settle() - expect(window.api.runtimeEnvironments.getStatus).toHaveBeenCalledTimes(1) - - // The user deletes the remote server before the first retry fires. Settings can still - // name it as active until the next settings read, so removal is what has to stop this. - useAppStore.getState().setRuntimeEnvironments([]) - await settle() - expect(useAppStore.getState().runtimeStatusByEnvironmentId.has(ENVIRONMENT_ID)).toBe(false) - - await vi.advanceTimersByTimeAsync(120_000) - await settle() - - expect(window.api.runtimeEnvironments.getStatus).toHaveBeenCalledTimes(1) - // buildExecutionHostRegistry enumerates the status map, so a re-published entry for a - // deleted id puts that host back in the sidebar under its raw id. - expect(useAppStore.getState().runtimeStatusByEnvironmentId.has(ENVIRONMENT_ID)).toBe(false) - }) - - it('keeps a live cached status when the replay-triggered probe fails on its own socket', async () => { - startBridge() - await settle() - expect(sidebarHostHealth()).toBe('available') - // Asserted over every write, not just the end state: a demotion that a later probe - // undoes still flashed the sidebar offline and still fired the toast. - let recordedUnreachable = false - unsubs.push( - useAppStore.subscribe((state) => { - recordedUnreachable ||= - state.runtimeStatusByEnvironmentId.get(ENVIRONMENT_ID)?.status === null - }) - ) - - // status.get dials its own short-lived socket, so its failure is unverifiable — and the - // transport that just replayed is proof the host is up. Recording it as offline would - // manufacture the stuck-offline sidebar this re-probe exists to cure. - failingStatusProbes = 1 - replaySubscription() - await settle() - - expect(recordedUnreachable).toBe(false) - expect(sidebarHostHealth()).toBe('available') - expect(toast.warning).not.toHaveBeenCalled() - }) - - it('returns a stuck-offline host to online when the replayed probe answers', async () => { - // The reported bug: the sidebar stayed offline after the connection recovered. The first - // probe failing keeps the recorded verdict unreachable, so only the replay recovers it - // (its retry chain is still parked behind a 2s timer this test never advances). - useAppStore.setState({ - runtimeStatusByEnvironmentId: new Map([ - [ENVIRONMENT_ID, { status: null, checkedAt: Date.now() }] - ]) as never - }) - failingStatusProbes = 1 - startBridge() - await settle() - expect(sidebarHostHealth()).toBe('disconnected') - - replaySubscription() - await settle() - - expect(sidebarHostHealth()).toBe('available') - }) - - it('does not dial a second status socket when the in-flight probe already answered', async () => { - startBridge() - await settle() - expect(window.api.runtimeEnvironments.getStatus).toHaveBeenCalledTimes(0) - - // A reconnect re-probes unconditionally, and that probe is still on its own socket. - blockNextStatusProbe = true - replaySubscription() - await settle() - expect(window.api.runtimeEnvironments.getStatus).toHaveBeenCalledTimes(1) - - // Meanwhile the outage's own failed probe is recorded, which resubscribes; that - // resubscribe resolves against a cache that still reads unreachable. - useAppStore.getState().setRuntimeEnvironmentStatus(ENVIRONMENT_ID, { - status: null, - checkedAt: Date.now() - }) - await settle() - expect(window.api.runtimeEnvironments.getStatus).toHaveBeenCalledTimes(1) - - releaseBlockedStatusProbe?.() - await settle() - - // The resubscribe only wanted an answer for a host the cache called unreachable, and - // the probe it waited on gave one: a second status.get is a whole extra socket dial. - expect(window.api.runtimeEnvironments.getStatus).toHaveBeenCalledTimes(1) - expect(sidebarHostHealth()).toBe('available') + expect(window.api.runtimeEnvironments.getStatus).not.toHaveBeenCalled() }) }) diff --git a/src/renderer/src/hooks/remote-workspace-session-merge-local-survival.test.ts b/src/renderer/src/hooks/remote-workspace-session-merge-local-survival.test.ts index 361493b34ef..b3ed31bb963 100644 --- a/src/renderer/src/hooks/remote-workspace-session-merge-local-survival.test.ts +++ b/src/renderer/src/hooks/remote-workspace-session-merge-local-survival.test.ts @@ -379,4 +379,39 @@ describe('local rows the snapshot carries no answer for', () => { expect(merged.defaultTerminalTabsAppliedByWorktreeId?.[WORKTREE]).toBe(true) }) + + // The recovery ledger is client-local: the host has never heard of it and its + // snapshot never carries one. Letting a reconnect erase it hands the tab a + // fresh remount allowance on every republication — which is the remount storm + // (b5cfc6ca) the ledger exists to end, restored on a timer. + describe('client-local recovery ledger', () => { + const ledger = { + attemptedAt: [1000], + generation: 1, + outcome: 'failed' as const, + startedAt: 1000, + reason: 'reattach-unverifiable' as const, + tabGeneration: 1 + } + + it('survives a reconnect the host snapshot knows nothing about', () => { + const local = terminalTab('agent', { generation: 1, recovery: ledger }) + const current = sessionState({ tabsByWorktree: { [WORKTREE]: [local] } }) + const remote = sessionState({ tabsByWorktree: { [WORKTREE]: [terminalTab('agent')] } }) + + const merged = merge(current, remote, { [WORKTREE]: [local] }) + + expect(merged.tabsByWorktree[WORKTREE][0].recovery).toEqual(ledger) + }) + + it('leaves a tab that never recovered without one', () => { + const local = terminalTab('agent') + const current = sessionState({ tabsByWorktree: { [WORKTREE]: [local] } }) + const remote = sessionState({ tabsByWorktree: { [WORKTREE]: [terminalTab('agent')] } }) + + const merged = merge(current, remote, { [WORKTREE]: [local] }) + + expect(merged.tabsByWorktree[WORKTREE][0].recovery).toBeUndefined() + }) + }) }) diff --git a/src/renderer/src/hooks/remote-workspace-session-merge.ts b/src/renderer/src/hooks/remote-workspace-session-merge.ts index fa247d8bbbd..f8c2c9dabf2 100644 --- a/src/renderer/src/hooks/remote-workspace-session-merge.ts +++ b/src/renderer/src/hooks/remote-workspace-session-merge.ts @@ -14,7 +14,11 @@ function preserveNewerLocalTerminalFields(remote: TerminalTab, local: TerminalTa const preserved = { ...remote, generation: local.generation, - ptyId: local.ptyId + ptyId: local.ptyId, + // Why: the recovery ledger is client-local and travels with generation — + // a remote snapshot that dropped it would hand the tab a fresh remount + // allowance on every republication, which is the storm again (b5cfc6ca). + ...(local.recovery ? { recovery: local.recovery } : {}) } return local.pendingActivationSpawn ? { ...preserved, pendingActivationSpawn: local.pendingActivationSpawn } diff --git a/src/renderer/src/hooks/settings-navigation-interface-sections.ts b/src/renderer/src/hooks/settings-navigation-interface-sections.ts index 0208dd1f526..35d51532315 100644 --- a/src/renderer/src/hooks/settings-navigation-interface-sections.ts +++ b/src/renderer/src/hooks/settings-navigation-interface-sections.ts @@ -26,7 +26,7 @@ export function buildInterfaceSettingsSections({ ), icon: Palette, searchEntries: getAppearancePaneSearchEntries({ - showWarpImport: showDesktopOnlySettings, + showDesktopThemeImports: showDesktopOnlySettings, showSystemTray: showDesktopOnlySettings && isWindows, showMenuBarIcon: showDesktopOnlySettings && isMac }), diff --git a/src/renderer/src/hooks/useAutoAckViewedAgent.away.test.ts b/src/renderer/src/hooks/useAutoAckViewedAgent.away.test.ts new file mode 100644 index 00000000000..3f76d71c377 --- /dev/null +++ b/src/renderer/src/hooks/useAutoAckViewedAgent.away.test.ts @@ -0,0 +1,208 @@ +// @vitest-environment happy-dom +import { act, cleanup, renderHook, waitFor } from '@testing-library/react' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { useAutoAckViewedAgent } from './useAutoAckViewedAgent' +import { useAppStore } from '../store' +import { makeTab } from '../store/slices/store-test-helpers' +import { makePaneKey } from '../../../shared/stable-pane-id' +import { createNotificationsApi } from '../web/preload-api/web-notifications-api' + +const leaf = '11111111-1111-4111-8111-111111111111' +const pane = makePaneKey('away-tab', leaf) +const readAway = vi.fn<() => Promise>() +const dismiss = vi.fn() +const previousApi = window.api +beforeEach(() => { + readAway.mockReset().mockResolvedValue(true) + dismiss.mockReset() + vi.stubGlobal('__ORCA_WEB_CLIENT__', false) + Object.assign(window, { api: { notifications: { getDesktopAwayState: readAway, dismiss } } }) + vi.spyOn(document, 'hasFocus').mockReturnValue(true) + useAppStore.setState({ + activeView: 'terminal', + activeTabId: 'away-tab', + activeWorktreeId: 'away-workspace', + activeTabIdByWorktree: {}, + tabsByWorktree: { + 'away-workspace': [makeTab({ id: 'away-tab', worktreeId: 'away-workspace' })] + }, + terminalLayoutsByTabId: { + 'away-tab': { root: null, activeLeafId: leaf, expandedLeafId: null } + }, + agentStatusByPaneKey: {}, + retainedAgentsByPaneKey: {}, + acknowledgedAgentsByPaneKey: {}, + unreadAgentCompletionPanes: {}, + unreadTerminalTabs: {}, + manuallyUnreadTurnsByPaneKey: {} + }) + useAppStore + .getState() + .setAgentStatus(pane, { state: 'done', prompt: 'away test', agentType: 'codex' }) + useAppStore.getState().markAgentCompletionPaneUnread(pane) +}) +afterEach(() => { + cleanup() + Object.assign(window, { api: previousApi }) + vi.restoreAllMocks() + vi.unstubAllGlobals() +}) + +it('leaves the focused pane unread while desktop is away, then acknowledges on user return', async () => { + renderHook(() => useAutoAckViewedAgent(false)) + await act(async () => { + await Promise.resolve() + }) + expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBe(true) + expect(dismiss).not.toHaveBeenCalled() + readAway.mockResolvedValue(false) + const input = new Event('pointerdown') + Object.defineProperty(input, 'isTrusted', { value: true }) + act(() => window.dispatchEvent(input)) + await waitFor(() => + expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBeUndefined() + ) + expect(dismiss).toHaveBeenCalledTimes(1) +}) + +it('does not acknowledge when the presence query fails or the hook unmounts', async () => { + let resolve!: (away: boolean) => void + readAway.mockImplementation( + () => + new Promise((r) => { + resolve = r + }) + ) + const hook = renderHook(() => useAutoAckViewedAgent(false)) + hook.unmount() + await act(async () => { + resolve(false) + }) + expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBe(true) + readAway.mockRejectedValue(new Error('unavailable')) + renderHook(() => useAutoAckViewedAgent(false)) + await act(async () => { + await Promise.resolve() + }) + expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBe(true) + expect(dismiss).not.toHaveBeenCalled() +}) + +it('acknowledges focused web completions despite unsupported native presence', async () => { + vi.stubGlobal('__ORCA_WEB_CLIENT__', true) + readAway.mockImplementation(createNotificationsApi().getDesktopAwayState) + renderHook(() => useAutoAckViewedAgent(false)) + await act(async () => {}) + expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBeUndefined() + expect(dismiss).toHaveBeenCalledTimes(1) + expect(readAway).not.toHaveBeenCalled() +}) + +it('keeps native unknown presence conservative', async () => { + readAway.mockResolvedValue(undefined) + renderHook(() => useAutoAckViewedAgent(false)) + await act(async () => {}) + act(() => window.dispatchEvent(new Event('focus'))) + await act(async () => {}) + expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBe(true) + expect(dismiss).not.toHaveBeenCalled() +}) + +it.each(['focus', 'visibilitychange'])('rescans pending web attention on %s', async (signal) => { + vi.stubGlobal('__ORCA_WEB_CLIENT__', true) + readAway.mockImplementation(createNotificationsApi().getDesktopAwayState) + const focus = vi.mocked(document.hasFocus).mockReturnValue(false) + const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden') + renderHook(() => useAutoAckViewedAgent(false)) + await act(async () => {}) + expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBe(true) + expect(dismiss).not.toHaveBeenCalled() + focus.mockReturnValue(true) + visibility.mockReturnValue('visible') + act(() => (signal === 'focus' ? window : document).dispatchEvent(new Event(signal))) + expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBeUndefined() + expect(dismiss).toHaveBeenCalledTimes(1) +}) + +it('ignores unrelated writes while away but queries for a new completion', async () => { + renderHook(() => useAutoAckViewedAgent(false)) + await act(async () => {}) + expect(readAway).toHaveBeenCalledTimes(1) + for (let i = 0; i < 20; i++) { + await act(async () => { + useAppStore.setState({ settings: useAppStore.getState().settings }) + }) + } + expect(readAway).toHaveBeenCalledTimes(1) + await act(async () => { + useAppStore.setState({ unreadAgentCompletionPanes: { [pane]: true } }) + }) + expect(readAway).toHaveBeenCalledTimes(2) + expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBe(true) + readAway.mockResolvedValue(false) + await act(async () => window.dispatchEvent(new Event('focus'))) + expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBeUndefined() + expect(dismiss).toHaveBeenCalledTimes(1) +}) + +it('does not query presence for a visible pane without attention', async () => { + useAppStore.setState({ agentStatusByPaneKey: {}, unreadAgentCompletionPanes: {} }) + renderHook(() => useAutoAckViewedAgent(false)) + await act(async () => window.dispatchEvent(new Event('focus'))) + expect(readAway).not.toHaveBeenCalled() +}) + +it('rechecks focus after a pending presence query resolves', async () => { + let resolve!: (away: boolean) => void + readAway.mockImplementation( + () => + new Promise((r) => { + resolve = r + }) + ) + renderHook(() => useAutoAckViewedAgent(false)) + vi.mocked(document.hasFocus).mockReturnValue(false) + await act(async () => resolve(false)) + expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBe(true) + expect(dismiss).not.toHaveBeenCalled() + vi.mocked(document.hasFocus).mockReturnValue(true) + readAway.mockResolvedValue(false) + await act(async () => window.dispatchEvent(new Event('focus'))) + expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBeUndefined() +}) + +it('rechecks the selected pane after a coalesced presence query resolves', async () => { + let resolve!: (away: boolean) => void + readAway.mockImplementation( + () => + new Promise((r) => { + resolve = r + }) + ) + renderHook(() => useAutoAckViewedAgent(false)) + act(() => useAppStore.setState({ activeTabId: 'other-tab' })) + expect(readAway).toHaveBeenCalledTimes(1) + await act(async () => resolve(false)) + expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBe(true) + expect(dismiss).not.toHaveBeenCalled() + readAway.mockResolvedValue(false) + await act(async () => useAppStore.setState({ activeTabId: 'away-tab' })) + expect(useAppStore.getState().unreadAgentCompletionPanes[pane]).toBeUndefined() +}) + +it.each([false, true])('preserves manual unread across return signals (web=%s)', async (web) => { + vi.stubGlobal('__ORCA_WEB_CLIENT__', web) + readAway.mockResolvedValue(false) + renderHook(() => useAutoAckViewedAgent(false)) + await act(async () => {}) + act(() => useAppStore.getState().unacknowledgeAgents([pane])) + const turn = useAppStore.getState().agentStatusByPaneKey[pane]!.stateStartedAt + dismiss.mockClear() + await act(async () => window.dispatchEvent(new Event('focus'))) + const input = new Event('pointerdown') + Object.defineProperty(input, 'isTrusted', { value: true }) + act(() => window.dispatchEvent(input)) + expect(useAppStore.getState().acknowledgedAgentsByPaneKey[pane]).toBeUndefined() + expect(useAppStore.getState().manuallyUnreadTurnsByPaneKey[pane]).toBe(turn) + expect(dismiss).not.toHaveBeenCalled() +}) diff --git a/src/renderer/src/hooks/useAutoAckViewedAgent.clock-skew.test.ts b/src/renderer/src/hooks/useAutoAckViewedAgent.clock-skew.test.ts index 2c69593563e..2664536c756 100644 --- a/src/renderer/src/hooks/useAutoAckViewedAgent.clock-skew.test.ts +++ b/src/renderer/src/hooks/useAutoAckViewedAgent.clock-skew.test.ts @@ -2,6 +2,7 @@ import { cleanup, renderHook } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type * as AgentAutoAckPresence from './agent-auto-ack-presence' import { useAutoAckViewedAgent } from './useAutoAckViewedAgent' import { useAppStore } from '../store' import { makeTab } from '../store/slices/store-test-helpers' @@ -13,6 +14,15 @@ import type { AgentStatusEntry } from '../../../shared/agent-status-types' // acknowledgeAgents returned the same object within one millisecond — a scan costing >=1ms with a // turn stamped ahead of the local clock (SSH/remote host) re-acked forever (React #185). +// These suites isolate synchronous acknowledgement and layout behavior. +vi.mock('./agent-auto-ack-presence', async (importOriginal) => ({ + ...(await importOriginal()), + createAutoAckPresenceCheck: (_read: unknown, onPresent: () => void) => ({ + request: onPresent, + dispose() {} + }) +})) + const TAB_ID = 'tab-main' const LEAF_ID = '11111111-1111-4111-8111-111111111111' const PANE_KEY = makePaneKey(TAB_ID, LEAF_ID) diff --git a/src/renderer/src/hooks/useAutoAckViewedAgent.floating-panel.test.ts b/src/renderer/src/hooks/useAutoAckViewedAgent.floating-panel.test.ts index fc31eaa9506..ce19e70b5c4 100644 --- a/src/renderer/src/hooks/useAutoAckViewedAgent.floating-panel.test.ts +++ b/src/renderer/src/hooks/useAutoAckViewedAgent.floating-panel.test.ts @@ -2,6 +2,7 @@ import { cleanup, renderHook } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type * as AgentAutoAckPresence from './agent-auto-ack-presence' import { useAutoAckViewedAgent } from './useAutoAckViewedAgent' import { useAppStore } from '../store' import { selectFloatingWorkspaceHasUnread } from '../store/selectors' @@ -9,6 +10,15 @@ import { makeTab } from '../store/slices/store-test-helpers' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' import { makePaneKey } from '../../../shared/stable-pane-id' +// These suites isolate synchronous acknowledgement and layout behavior. +vi.mock('./agent-auto-ack-presence', async (importOriginal) => ({ + ...(await importOriginal()), + createAutoAckPresenceCheck: (_read: unknown, onPresent: () => void) => ({ + request: onPresent, + dispose() {} + }) +})) + const FLOATING_TAB_ID = 'tab-floating' const MAIN_TAB_ID = 'tab-main' const LEAF_ID = '11111111-1111-4111-8111-111111111111' @@ -100,3 +110,22 @@ describe('useAutoAckViewedAgent — floating workspace panel visibility', () => expect(selectFloatingWorkspaceHasUnread(state)).toBe(false) }) }) + +it('does not acknowledge the regular workspace for a colliding floating tab', () => { + vi.spyOn(document, 'hasFocus').mockReturnValue(true) + seedFloatingCompletion() + useAppStore.setState({ + activeView: 'terminal', + activeTabId: FLOATING_TAB_ID, + activeWorktreeId: 'regular', + unreadAgentCompletionPanes: { [FLOATING_PANE_KEY]: true } + }) + const cleared = vi.spyOn(useAppStore.getState(), 'clearWorktreeUnread') + try { + renderHook(() => useAutoAckViewedAgent(true)) + expect(cleared).not.toHaveBeenCalledWith('regular') + } finally { + cleanup() + vi.restoreAllMocks() + } +}) diff --git a/src/renderer/src/hooks/useAutoAckViewedAgent.test.ts b/src/renderer/src/hooks/useAutoAckViewedAgent.test.ts index 370205299d6..80769c0334b 100644 --- a/src/renderer/src/hooks/useAutoAckViewedAgent.test.ts +++ b/src/renderer/src/hooks/useAutoAckViewedAgent.test.ts @@ -398,8 +398,8 @@ describe('resolveAutoAckTabTargets', () => { it('scans the floating tab alongside the main tab while the panel is visible', () => { expect(resolveAutoAckTabTargets(baseState, { floatingPanelVisible: true })).toEqual([ - { tabId: 'tab-1', worktreeId: 'wt-1' }, - { tabId: FLOATING_TAB_ID, worktreeId: FLOATING_TERMINAL_WORKTREE_ID } + { tabId: FLOATING_TAB_ID, worktreeId: FLOATING_TERMINAL_WORKTREE_ID }, + { tabId: 'tab-1', worktreeId: 'wt-1' } ]) }) @@ -427,13 +427,13 @@ describe('resolveAutoAckTabTargets', () => { ).toEqual([]) }) - it('keeps the real worktree when one tab id is claimed by both worktrees', () => { + it('prefers the visible floating worktree when both worktrees claim one tab id', () => { expect( resolveAutoAckTabTargets( { ...baseState, activeTabId: FLOATING_TAB_ID }, { floatingPanelVisible: true } ) - ).toEqual([{ tabId: FLOATING_TAB_ID, worktreeId: 'wt-1' }]) + ).toEqual([{ tabId: FLOATING_TAB_ID, worktreeId: FLOATING_TERMINAL_WORKTREE_ID }]) }) }) diff --git a/src/renderer/src/hooks/useAutoAckViewedAgent.ts b/src/renderer/src/hooks/useAutoAckViewedAgent.ts index 40a3591e2b0..7da0993cdaf 100644 --- a/src/renderer/src/hooks/useAutoAckViewedAgent.ts +++ b/src/renderer/src/hooks/useAutoAckViewedAgent.ts @@ -1,5 +1,12 @@ +import { resolveAutoAckTabTargets } from './agent-auto-ack-targets' +export { resolveAutoAckTabTargets, type AutoAckTabTarget } from './agent-auto-ack-targets' import { useEffect, useRef } from 'react' +import { + createAutoAckPresenceCheck, + subscribeAutoAckPresenceSignals +} from './agent-auto-ack-presence' import { useAppStore } from '@/store' +import { isWebClientLocation } from '@/lib/web-client-location' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' import type { AgentStatusEntry } from '../../../shared/agent-status-types' import type { RetainedAgentEntry } from '@/store/slices/agent-status' @@ -189,39 +196,6 @@ export function acknowledgeViewedAgentAttention( } } -export type AutoAckTabTarget = { tabId: string; worktreeId: string | null } - -/** - * Tabs whose visible pane counts as "seen" right now, each paired with the worktree that owns it. - * - * Why the floating workspace is gated on panel visibility rather than `activeView`: the panel is an - * overlay that sits above every view and stays mounted while closed, and its active tab never - * becomes the global `activeTabId` — so neither the view nor the tab id can stand in for "on screen". - */ -export function resolveAutoAckTabTargets( - state: { - activeView: string - activeTabId: string | null - activeWorktreeId: string | null - activeTabIdByWorktree: Record - }, - options: { floatingPanelVisible: boolean } -): AutoAckTabTarget[] { - const targets: AutoAckTabTarget[] = [] - if (state.activeView === 'terminal' && state.activeTabId) { - targets.push({ tabId: state.activeTabId, worktreeId: state.activeWorktreeId }) - } - if (options.floatingPanelVisible) { - const floatingTabId = state.activeTabIdByWorktree[FLOATING_TERMINAL_WORKTREE_ID] ?? null - // Why first-wins on a tab-id collision: tab ids can be claimed by two worktrees - // (see active-tab-owner-worktree), and acking under the wrong one strands its unread dot. - if (floatingTabId && !targets.some((target) => target.tabId === floatingTabId)) { - targets.push({ tabId: floatingTabId, worktreeId: FLOATING_TERMINAL_WORKTREE_ID }) - } - } - return targets -} - // Auto-ack an agent row as "seen" when the user is already on its tab, so the dashboard/Dock don't stay bold for an event they watched happen. // Scans live + retained maps: Codex's title-revert (pty-connection.ts:onAgentExited) migrates `done` rows to retained mid-race — see docs/codex-agent-row-bold-stuck.md. export function useAutoAckViewedAgent(floatingPanelVisible: boolean): void { @@ -243,7 +217,11 @@ export function useAutoAckViewedAgent(floatingPanelVisible: boolean): void { let lastUnreadAgentCompletionPanes: unknown = undefined // `force` re-scans after a signal the store never sees: panel open/closed is React-local state. - const maybeAck = (options?: { force?: boolean }): void => { + const presence = createAutoAckPresenceCheck( + async () => window.api?.notifications?.getDesktopAwayState?.(), + () => maybeAck({ force: true, presenceConfirmed: true }) + ) + const maybeAck = (options?: { force?: boolean; presenceConfirmed?: boolean }): void => { const s = useAppStore.getState() const floatingWorkspaceActiveTabId = s.activeTabIdByWorktree[FLOATING_TERMINAL_WORKTREE_ID] ?? null @@ -261,6 +239,16 @@ export function useAutoAckViewedAgent(floatingPanelVisible: boolean): void { return } + // Presence signals force a rescan; unrelated writes must not retry an away result. + lastActiveView = s.activeView + lastActiveTabId = s.activeTabId + lastFloatingWorkspaceActiveTabId = floatingWorkspaceActiveTabId + lastAgentStatus = s.agentStatusByPaneKey + lastRetained = s.retainedAgentsByPaneKey + lastAcknowledged = s.acknowledgedAgentsByPaneKey + lastLayouts = s.terminalLayoutsByTabId + lastUnreadAgentCompletionPanes = s.unreadAgentCompletionPanes + // Why: tab-active only proxies "seen"; gate on window visible+focused so away-time transitions don't silently clear the bold signal. if (typeof document !== 'undefined') { if (document.visibilityState !== 'visible') { @@ -279,15 +267,20 @@ export function useAutoAckViewedAgent(floatingPanelVisible: boolean): void { if (targets.length === 0) { return } - // Why: advance refs only after gates pass, else the diff is consumed and a gated-out transition never re-acks when focus returns. - lastActiveView = s.activeView - lastActiveTabId = s.activeTabId - lastFloatingWorkspaceActiveTabId = floatingWorkspaceActiveTabId - lastAgentStatus = s.agentStatusByPaneKey - lastRetained = s.retainedAgentsByPaneKey - lastAcknowledged = s.acknowledgedAgentsByPaneKey - lastLayouts = s.terminalLayoutsByTabId - lastUnreadAgentCompletionPanes = s.unreadAgentCompletionPanes + // Browsers have no native idle capability; their visible/focused gates still apply. + if (!options?.presenceConfirmed && !isWebClientLocation()) { + const hasAttention = targets.some(({ tabId }) => { + const leafId = resolveActiveLeafId(s, tabId) + return ( + computeAutoAckTargets(s, tabId, leafId).length > 0 || + computeViewedAgentCompletionPaneKey(s, tabId, leafId) !== null + ) + }) + if (hasAttention) { + presence.request() + return + } + } const activePaneKeys = new Set() for (const target of targets) { @@ -341,16 +334,15 @@ export function useAutoAckViewedAgent(floatingPanelVisible: boolean): void { maybeAck() // Subscribe to all store changes; the ref-equality guard above skips unrelated updates. const unsubscribe = useAppStore.subscribe(() => maybeAck()) - // Why: focus/visibility don't flow through zustand, so re-run the scan on these DOM events when focus returns. - const onVisibility = (): void => maybeAck() - const onFocus = (): void => maybeAck() - document.addEventListener('visibilitychange', onVisibility) - window.addEventListener('focus', onFocus) + const stopPresenceSignals = subscribeAutoAckPresenceSignals( + () => maybeAck({ force: true }), + () => maybeAck({ force: true, presenceConfirmed: true }) + ) return () => { + presence.dispose() rescanRef.current = null unsubscribe() - document.removeEventListener('visibilitychange', onVisibility) - window.removeEventListener('focus', onFocus) + stopPresenceSignals() } }, []) diff --git a/src/renderer/src/hooks/useIpcEvents-lifecycle.test.ts b/src/renderer/src/hooks/useIpcEvents-lifecycle.test.ts index 5991c40c4de..2e13d9382e4 100644 --- a/src/renderer/src/hooks/useIpcEvents-lifecycle.test.ts +++ b/src/renderer/src/hooks/useIpcEvents-lifecycle.test.ts @@ -30,7 +30,7 @@ const EXPECTED_DIRECT_CALLBACK_METHODS = [ 'runtime.onNativeChatLaunchDraftResolved', 'runtime.onTerminalDriverChanged', 'runtime.onTerminalFitOverrideChanged', - 'runtimeEnvironments.onSharedControlDiagnostics', + 'runtimeEnvironments.onStatusChanged', 'settings.onChanged', 'ssh.onCredentialRequest', 'ssh.onCredentialResolved', @@ -106,7 +106,7 @@ const EXPECTED_DIRECT_CALLBACK_METHODS = [ const EXPECTED_CALLBACK_REGISTRATION_SEQUENCE = [ 'ui.onMobileMarkdownRequest', 'automations.onChanged', - 'runtimeEnvironments.onSharedControlDiagnostics', + 'runtimeEnvironments.onStatusChanged', 'repos.onChanged', 'worktrees.onChanged', 'worktrees.onHeadIdentitiesChanged', @@ -382,7 +382,7 @@ describe('useIpcEvents App-lifetime lifecycle', () => { ).toEqual([ 'ui.onMobileMarkdownRequest', 'automations.onChanged', - 'runtimeEnvironments.onSharedControlDiagnostics', + 'runtimeEnvironments.onStatusChanged', 'runtimeEnvironments.subscribe', ...EXPECTED_CALLBACK_REGISTRATION_SEQUENCE.slice(3) ]) diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index a091ef9e5af..c7b87a80cb0 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -2397,8 +2397,6 @@ "recentChatsTerminalsHeader": "Recent Chats & Terminals", "27f10cca63": "Search chats, terminals, worktrees, settings, and actions...", "2770f02910": "Search chats, terminals, worktrees, settings, and actions", - "paletteOpenTabBranch": "Branch name", - "paletteOpenTabWorkspace": "Workspace name", "lastActiveTime": "Last active {{value0}} ago" }, "github": { @@ -3389,7 +3387,10 @@ "1d04b1630b": "Split Down", "6b3efb106e": "Split Up", "fdd29eb669": "Pin Tab", - "8e9d603a09": "Unpin Tab" + "8e9d603a09": "Unpin Tab", + "revealInFinder": "Reveal in Finder", + "openContainingFolder": "Open Containing Folder", + "revealInFileExplorer": "Reveal in File Explorer" }, "QuickLaunchButton": { "348a04c1ad": "Agent settings…", @@ -5805,7 +5806,8 @@ "lockedReason": "This workspace is locked by Git. Git reported: {{value0}}. Run git worktree unlock from its repository, then retry deletion.", "unstoppedPty": "Orca could not confirm every terminal in this workspace has exited, so it stopped before deleting any files. Use Force Delete to remove it anyway.", "unstoppedPtyLive": "This workspace still has running terminals, so Orca stopped before deleting any files. Force Delete will kill them and discard any uncommitted work they hold.", - "runningAgentSession": "This workspace still has running agent sessions, so Orca stopped before deleting any files. Force Delete will close them and discard any work they hold." + "runningAgentSession": "Orca could not confirm every agent session in this workspace has closed, so it stopped before deleting any files. Use Force Delete to remove it anyway.", + "runningAgentSessionLive": "This workspace still has running agent sessions that Orca could not close, so it stopped before deleting any files. Force Delete will discard any work they hold." } } }, @@ -11997,7 +11999,10 @@ "3161c4e425": "folder", "e887fa4b2e": "Open in Terminal", "1d8e182c32": "View File", - "clipboardStagingUnavailable": "Could not copy the file because Orca's temporary storage is unavailable" + "clipboardStagingUnavailable": "Could not copy the file because Orca's temporary storage is unavailable", + "revealInFinder": "Reveal in Finder", + "openContainingFolder": "Open Containing Folder", + "revealInFileExplorer": "Reveal in File Explorer" }, "FileExplorerToolbar": { "d238264654": "Show Git Ignored Files", @@ -14697,7 +14702,10 @@ "f0fd4174b5": "Open file tab to use rich markdown editing", "a10d9b8337": "Open file", "2076ecfc9c": "Previous change", - "631dab0df3": "Next change" + "631dab0df3": "Next change", + "revealInFinder": "Reveal in Finder", + "openContainingFolder": "Open Containing Folder", + "revealInFileExplorer": "Reveal in File Explorer" }, "EditorPanelMarkdownActionsMenu": { "3e0ce48c24": "Export as PDF", @@ -16904,6 +16912,21 @@ "HostedReviewUnlinkMenuItem": { "label": "Unlink {{value0}} from workspace", "description": "Orca will hide {{value0}} {{value1}} details for this workspace. The {{value0}} and branch on {{value2}} won’t be changed." + }, + "UnexpectedSignoutCard": { + "9f2c1a4b7d": "You've been signed out", + "3e8f5c2a91": "Dismiss", + "7b4d9e1f2a": "Sign in again as {{value0}} to restore Artifact sharing, Orca Relay, and skill sharing.", + "5a1c8d3e6f": "Sign in again to restore Artifact sharing, Orca Relay, and skill sharing.", + "1f6b2c9d4e": "What you get back", + "8d2e4f7a1b": "Artifact sharing", + "2c9a5b6e8d": "Publish HTML and Markdown files and manage every shared link from Orca.", + "6e3f1a9c5b": "Orca Relay", + "4b7d2e8f1a": "Connect Orca Mobile to this desktop across cellular or any Wi-Fi.", + "9a4c6b2d7e": "Skill sharing", + "3d8e5f1b9c": "Share skills behind an unlisted link and install them on any machine you use.", + "7e1a9c4d2f": "Signing in…", + "c5b3e8a17d": "Sign in to Orca" } }, "i18n": { @@ -17834,5 +17857,13 @@ "title": "Orca keeps failing to load", "stalledMessage": "The app window stopped responding while reloading after a crash.", "crashLoopMessage": "The app window crashed repeatedly and stopped reloading automatically." + }, + "notifications": { + "agentStatus": { + "needsInput": "needs input", + "working": "working", + "stopped": "stopped", + "finished": "finished" + } } } diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 56695c14755..cc2f2140612 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -14922,5 +14922,13 @@ "action": "Probar Agentes", "hiddenToast": "La pestaña Agentes está oculta. Vuelve a activarla en Configuración → Experimental." } + }, + "notifications": { + "agentStatus": { + "needsInput": "necesita información", + "working": "trabajando", + "stopped": "detenido", + "finished": "finalizado" + } } } diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index fe8eaf19756..db35a124c7d 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -2201,8 +2201,6 @@ "recentChatsTerminalsHeader": "Chats et terminaux récents", "27f10cca63": "Rechercher chats, terminaux, worktrees, paramètres et actions...", "2770f02910": "Rechercher chats, terminaux, worktrees, paramètres et actions", - "paletteOpenTabBranch": "Nom de branche", - "paletteOpenTabWorkspace": "Nom de l'espace de travail", "lastActiveTime": "Dernière activité il y a {{value0}}" }, "github": { @@ -16591,5 +16589,13 @@ }, "quickOpen": { "moreMatchesAvailable": "D'autres correspondances sont peut-être disponibles. Affinez votre recherche pour réduire les résultats." + }, + "notifications": { + "agentStatus": { + "needsInput": "attend une réponse", + "working": "en cours", + "stopped": "arrêté", + "finished": "terminé" + } } } diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 2224e322951..f5a8c53a8c5 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -14957,5 +14957,13 @@ "action": "Agent を試す", "hiddenToast": "Agent タブを非表示にしました。設定 → 実験的機能で再度有効にできます。" } + }, + "notifications": { + "agentStatus": { + "needsInput": "入力待ち", + "working": "処理中", + "stopped": "停止", + "finished": "完了" + } } } diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index 25359a26785..9267742bb1c 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -15096,5 +15096,13 @@ "action": "에이전트 사용해 보기", "hiddenToast": "에이전트 탭이 숨겨졌습니다. 설정 → 실험 기능에서 다시 활성화하세요." } + }, + "notifications": { + "agentStatus": { + "needsInput": "입력 필요", + "working": "작업 중", + "stopped": "중지됨", + "finished": "완료됨" + } } } diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index f00d3ea0d90..85bfdc384db 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -15061,5 +15061,13 @@ "action": "试用智能体", "hiddenToast": "智能体标签页已隐藏。可在设置 → 实验性功能中重新启用。" } + }, + "notifications": { + "agentStatus": { + "needsInput": "需要输入", + "working": "处理中", + "stopped": "已停止", + "finished": "已完成" + } } } diff --git a/src/renderer/src/lib/http-link-routing.test.ts b/src/renderer/src/lib/http-link-routing.test.ts index efd9ff7e4b5..3626ccf5b36 100644 --- a/src/renderer/src/lib/http-link-routing.test.ts +++ b/src/renderer/src/lib/http-link-routing.test.ts @@ -139,6 +139,41 @@ describe('openHttpLink', () => { expect(createBrowserTabMock).not.toHaveBeenCalled() }) + it('keeps explicitly local links local while a remote runtime is active', () => { + storeState.settings = { openLinksInApp: true, activeRuntimeEnvironmentId: 'remote-1' } + + openHttpLink('https://example.com/', { + worktreeId: 'wt-1', + allowRemoteInApp: true, + sourceOwner: { kind: 'local' } + }) + + expect(createBrowserTabMock).toHaveBeenCalledWith('wt-1', 'https://example.com/', { + activate: true + }) + expect(openRuntimeBrowserTabMock).not.toHaveBeenCalled() + }) + + it('routes opted-in links without a source owner through the active runtime', () => { + storeState.settings = { + openLinksInApp: true, + activeRuntimeEnvironmentId: ' remote-1 ' + } + + openHttpLink('https://github.com/acme/widgets/pull/123', { + worktreeId: 'wt-1', + allowRemoteInApp: true + }) + + expect(openRuntimeBrowserTabMock).toHaveBeenCalledExactlyOnceWith({ + workspaceId: 'wt-1', + url: 'https://github.com/acme/widgets/pull/123', + intent: { kind: 'url' } + }) + expect(createBrowserTabMock).not.toHaveBeenCalled() + expect(openUrlMock).not.toHaveBeenCalled() + }) + it('routes to the system browser when a remote runtime environment is active', () => { storeState.settings = { openLinksInApp: true, activeRuntimeEnvironmentId: 'env-1' } diff --git a/src/renderer/src/lib/http-link-routing.ts b/src/renderer/src/lib/http-link-routing.ts index aa89fb7071f..628a205f00f 100644 --- a/src/renderer/src/lib/http-link-routing.ts +++ b/src/renderer/src/lib/http-link-routing.ts @@ -127,7 +127,10 @@ export function openHttpLink(url: string, opts: OpenHttpLinkOptions = {}): void } const state = storeAccessor?.() const remoteRuntimeActive = Boolean(state?.settings?.activeRuntimeEnvironmentId?.trim()) - const sourceIsLocal = sourceOwner ? sourceOwner.kind === 'local' : !remoteRuntimeActive + const effectiveSourceOwner = sourceOwner + const sourceIsLocal = effectiveSourceOwner + ? effectiveSourceOwner.kind === 'local' + : !remoteRuntimeActive const openLinksInApp = state?.settings?.openLinksInApp === true const modifier = resolveModifierRouting( Boolean(modifierHeld), @@ -144,16 +147,20 @@ export function openHttpLink(url: string, opts: OpenHttpLinkOptions = {}): void wantsOrca && allowRemoteInApp && worktreeId && - (sourceOwner?.kind === 'runtime' || sourceOwner?.kind === 'ssh') + (effectiveSourceOwner?.kind === 'runtime' || + effectiveSourceOwner?.kind === 'ssh' || + (!effectiveSourceOwner && remoteRuntimeActive)) ) { if (workspaceHttpLinkBrowserOpener) { void workspaceHttpLinkBrowserOpener({ workspaceId: worktreeId, url, intent: { kind: 'url' }, - ...(sourceOwner.kind === 'runtime' - ? { expectedRuntimeEnvironmentId: sourceOwner.runtimeEnvironmentId } - : { expectedSshConnectionId: sourceOwner.connectionId }) + ...(effectiveSourceOwner?.kind === 'runtime' + ? { expectedRuntimeEnvironmentId: effectiveSourceOwner.runtimeEnvironmentId } + : effectiveSourceOwner?.kind === 'ssh' + ? { expectedSshConnectionId: effectiveSourceOwner.connectionId } + : {}) }).catch((error) => { toast.error( error instanceof Error diff --git a/src/renderer/src/lib/monaco-languages/monarch-embed-entry-budget.ts b/src/renderer/src/lib/monaco-languages/monarch-embed-entry-budget.ts new file mode 100644 index 00000000000..8f455818373 --- /dev/null +++ b/src/renderer/src/lib/monaco-languages/monarch-embed-entry-budget.ts @@ -0,0 +1,46 @@ +// Monarch tokenizes an embedded language by mutual recursion: `_myTokenize` +// calls `_nestedTokenize` for every embed entered *mid-line*, which calls +// `_myTokenize` back for the rest of the line. Both calls are in tail position +// and V8 has no TCO, so JS stack use grows with the number of mid-line embed +// entries — one `` +// (under Monaco's own 20_000 line cap) reached ~1743 frames and threw +// `RangeError: Maximum call stack size exceeded`. Monaco's `safeTokenize` catches +// that per line, so the visible failure is a line that silently loses all +// highlighting; the frame count is what this suite bounds. + +// 6600 is the largest `{a}` count under Monaco's line cap (19_800 chars); the +// filter below drops it for the longer chunk shapes, so the densest embed +// shape is the one that gets driven at maximum length. +const RAMP = [50, 200, 500, 1000, 2500, 6600] + +function interpolationLine(count: number): string { + return `

${Array.from({ length: count }, (_, index) => `{a${index}}`).join('')}

` +} + +function repeatedLine(count: number, chunk: string): string { + return `

${chunk.repeat(count)}` +} + +const PATHOLOGICAL_LINES: [string, (count: number) => string][] = [ + ['interpolations', interpolationLine], + // Densest embed entries per character: two embeds (typescript, then html + // again) per three characters. + ['back-to-back interpolations', (count) => '{a}'.repeat(count)], + ['html comments', (count) => repeatedLine(count, '')], + ['script tags', (count) => repeatedLine(count, '')], + ['style tags', (count) => repeatedLine(count, '')] +] + +describe.each([ + ['svelte', svelteMonarchLanguage], + ['astro', astroMonarchLanguage] +])('%s embed-entry recursion', (languageId, language) => { + it.each(PATHOLOGICAL_LINES)( + 'stays within the embed budget for a line of %s', + (_name, buildLine) => { + // Monaco refuses to tokenize at all past its line cap, so the ramp stops + // where a real editor would. + const ramp = RAMP.filter((count) => buildLine(count).length < MAX_TOKENIZATION_LINE_LENGTH) + expect(ramp.length).toBeGreaterThanOrEqual(3) + + const depths = ramp.map((count) => + measureNestedDepth(createMonarchTokenizer(languageId, language), [buildLine(count)]) + ) + + for (const measurement of depths) { + expect(measurement.error).toBeUndefined() + expect(measurement.maxNestedDepth).toBeLessThanOrEqual(EMBED_ENTRY_REST_OF_LINE_BUDGET) + } + // Depth must stop tracking the occurrence count, not merely grow slower. + expect(Math.max(...depths.map((measurement) => measurement.maxNestedDepth))).toBeLessThan( + ramp.at(-1) as number + ) + } + ) + + it('tokenizes interpolations without dropping the embed', () => { + // Regression: monarch honours `nextEmbedded` on a zero-width match only + // when the token is `@rematch`; with any other token it hits the + // no-progress `continue` and silently drops the pending embed. Both + // grammars then reached a `nextEmbedded: '@pop'` rule with no embed + // active and threw "cannot pop embedded language if not inside one" on + // the *first* interpolation — the error seen in the field. + const measurement = measureNestedDepth(createMonarchTokenizer(languageId, language), [ + '

a {first} b {second} c

' + ]) + + expect(measurement.error).toBeUndefined() + // Depth > 0 proves the embeds were really entered, not silently skipped. + expect(measurement.maxNestedDepth).toBeGreaterThan(0) + }) + + it.each([ + ['script', 'ts', 'typescript'], + ['style', 'scss', 'scss'] + ])('re-embeds a %s body after an over-budget opening line', (tag, lang, embeddedLanguageId) => { + // The opening tag plus code on the same line pushes the tag close past the + // budget, so the body starts unembedded. Every following short line must + // recover the embed (and the `lang=` language) instead of leaving the whole + // block unhighlighted until the closing tag. + const embeds = endEmbeddedLanguages( + tokenizeLines(createMonarchTokenizer(languageId, language), [ + `<${tag} lang="${lang}">a = "${'x'.repeat(EMBED_ENTRY_REST_OF_LINE_BUDGET)}"`, + ' b', + ' c', + `` + ]) + ) + + expect(embeds).toEqual([null, embeddedLanguageId, embeddedLanguageId, null]) + }) + + it('keeps tokenizing after an over-budget line and re-embeds on the next one', () => { + const overBudget = `
{value}
` + const measurement = measureNestedDepth(createMonarchTokenizer(languageId, language), [ + overBudget, + '

{value}

' + ]) + + expect(measurement.error).toBeUndefined() + expect(measurement.maxNestedDepth).toBeGreaterThan(0) + }) +}) + +describe('unguarded embedded tokenizer', () => { + // Control: the same markup/expression shape with no budget on embed entry. + // The frame count then tracks the interpolation count one-for-one; ~1700 + // frames is already a RangeError in this runtime, so the ramp stops short of + // the overflow to stay deterministic. + const perInterpolationEmbedLanguage: Monaco.languages.IMonarchLanguage = { + defaultToken: '', + tokenizer: { + root: [[/ { + const depths = [50, 200, 500].map( + (count) => + measureNestedDepth(createMonarchTokenizer('control', perInterpolationEmbedLanguage), [ + `${interpolationLine(count)} ` + ]).maxNestedDepth + ) + + expect(depths).toEqual([51, 201, 501]) + }) +}) + +describe('vue embed-entry recursion', () => { + const templateLine = (count: number): string => + `` + + it('stays within the embed budget for a line of interpolations', () => { + const ramp = [50, 200, 1000, 2500, 3900].filter( + (count) => templateLine(count).length < MAX_TOKENIZATION_LINE_LENGTH + ) + expect(ramp.length).toBeGreaterThanOrEqual(3) + + const depths = ramp.map((count) => + measureNestedDepth(createMonarchTokenizer('vue', vueMonarchLanguage), [templateLine(count)]) + ) + + for (const measurement of depths) { + expect(measurement.error).toBeUndefined() + expect(measurement.maxNestedDepth).toBeLessThanOrEqual(EMBED_ENTRY_REST_OF_LINE_BUDGET) + } + expect(Math.max(...depths.map((measurement) => measurement.maxNestedDepth))).toBeLessThan( + ramp.at(-1) as number + ) + }) + + it.each([ + ['script', 'ts', 'typescript'], + ['style', 'scss', 'scss'] + ])('re-embeds a %s body after an over-budget opening line', (tag, lang, embeddedLanguageId) => { + const embeds = endEmbeddedLanguages( + tokenizeLines(createMonarchTokenizer('vue', vueMonarchLanguage), [ + `<${tag} lang="${lang}">a = "${'x'.repeat(EMBED_ENTRY_REST_OF_LINE_BUDGET)}"`, + ' b', + `` + ]) + ) + + expect(embeds).toEqual([null, embeddedLanguageId, null]) + }) + + it('tokenizes a template interpolation without dropping the embed', () => { + const measurement = measureNestedDepth(createMonarchTokenizer('vue', vueMonarchLanguage), [ + '' + ]) + + expect(measurement.error).toBeUndefined() + expect(measurement.maxNestedDepth).toBeGreaterThan(0) + }) +}) diff --git a/src/renderer/src/lib/monaco-languages/monarch-tokenizer-test-harness.ts b/src/renderer/src/lib/monaco-languages/monarch-tokenizer-test-harness.ts new file mode 100644 index 00000000000..08f8c14cd5a --- /dev/null +++ b/src/renderer/src/lib/monaco-languages/monarch-tokenizer-test-harness.ts @@ -0,0 +1,159 @@ +import type * as Monaco from 'monaco-editor' +import { compile } from 'monaco-editor/esm/vs/editor/standalone/common/monarch/monarchCompile.js' +import { MonarchTokenizer } from 'monaco-editor/esm/vs/editor/standalone/common/monarch/monarchLexer.js' +import { MAX_TOKENIZATION_LINE_LENGTH } from './monarch-embed-entry-budget' + +// Drives the real `MonarchTokenizer` shipped with monaco-editor rather than +// walking a grammar's rule table. A table walk cannot see the failures that +// actually reach the renderer — a grammar that throws on every `{expr}`, or +// that silently drops an embed, still has a well-formed rule table. + +/** One Monaco token. `language` is the (embedded) language the region belongs to. */ +export type MonarchToken = { offset: number; type: string; language: string } + +type MonarchEndState = { embeddedLanguageData?: { languageId: string } | null } + +export type MonarchTokenizerInstance = { + getInitialState: () => unknown + tokenize: ( + line: string, + hasEOL: boolean, + state: unknown + ) => { tokens: MonarchToken[]; endState: MonarchEndState } + _nestedTokenize: (...args: unknown[]) => unknown +} + +export function createMonarchTokenizer( + languageId: string, + language: Monaco.languages.IMonarchLanguage, + maxTokenizationLineLength = MAX_TOKENIZATION_LINE_LENGTH +): MonarchTokenizerInstance { + // Nested languages stay unregistered, so `nestedLanguageTokenize` emits one + // empty-typed token tagged with the embedded language id instead of running + // that language's tokenizer. That is what makes `token.language` a direct + // readout of which embed covers which region. + const languageService = { + languageIdCodec: { encodeLanguageId: () => 1, decodeLanguageId: () => '' }, + getLanguageIdByLanguageName: () => null, + getLanguageIdByMimeType: () => null, + isRegisteredLanguageId: () => false, + requestBasicLanguageFeatures: () => {} + } + const themeService = { getColorTheme: () => ({ tokenTheme: {} }) } + const configurationService = { + getValue: () => maxTokenizationLineLength, + onDidChangeConfiguration: () => ({ dispose: () => {} }) + } + + return new MonarchTokenizer( + languageService, + themeService, + languageId, + compile(languageId, language), + configurationService + ) as MonarchTokenizerInstance +} + +export type TokenizedLine = { + text: string + tokens: MonarchToken[] + /** Embedded language still active at end of line; `null` means that region renders unhighlighted. */ + endEmbeddedLanguageId: string | null +} + +/** Tokenizes `lines` as one document, threading tokenizer state line to line. */ +export function tokenizeLines( + tokenizer: MonarchTokenizerInstance, + lines: string[] +): TokenizedLine[] { + let state: unknown = tokenizer.getInitialState() + return lines.map((text) => { + const { tokens, endState } = tokenizer.tokenize(text, true, state) + state = endState + return { + text, + tokens, + endEmbeddedLanguageId: endState.embeddedLanguageData?.languageId ?? null + } + }) +} + +export function tokenizeMonarchDocument( + languageId: string, + language: Monaco.languages.IMonarchLanguage, + source: string +): TokenizedLine[] { + return tokenizeLines(createMonarchTokenizer(languageId, language), source.split('\n')) +} + +/** The embedded language each line *ends* in — `null` for no embed. */ +export function endEmbeddedLanguages(lines: TokenizedLine[]): (string | null)[] { + return lines.map((line) => line.endEmbeddedLanguageId) +} + +/** The distinct languages a line's tokens were attributed to, in order. */ +export function tokenLanguages(line: TokenizedLine): string[] { + return line.tokens + .map((token) => token.language) + .filter((language, index, all) => language !== all[index - 1]) +} + +/** + * Per line, which languages actually cover it. This is the readout that catches + * a silently dropped embed: the region falls back to the host grammar's own id + * instead of `html` / `typescript` / `scss`, and renders unhighlighted. + */ +export function tokenLanguagesPerLine(lines: TokenizedLine[]): string[][] { + return lines.map(tokenLanguages) +} + +/** Token type covering `index`, without the grammar's `tokenPostfix`. */ +export function tokenTypeAt(line: TokenizedLine, index: number): string { + const covering = line.tokens.findLast((token) => token.offset <= index) + return covering?.type.split('.').slice(0, -1).join('.') ?? '' +} + +/** One `text | offset:type@language … | embed=…` row per line, for snapshots. */ +export function formatTokenizedLines(lines: TokenizedLine[]): string[] { + return lines.map((line) => { + const tokens = line.tokens + .map((token) => `${token.offset}:${token.type || '-'}@${token.language}`) + .join(' ') + return `${line.text} | ${tokens} | embed=${line.endEmbeddedLanguageId ?? 'none'}` + }) +} + +export type TokenizeMeasurement = { maxNestedDepth: number; error: Error | undefined } + +/** + * Tokenizes `lines`, recording peak `_nestedTokenize` recursion — the real JS + * stack cost, since Monarch enters an embed by mutual recursion with no TCO. + * Embeds cannot nest, so this counts sequential embed enter/exit transitions on + * one line, each holding a frame until the line ends. Errors are captured rather + * than thrown so a caller can assert on frame count and failure together. + */ +export function measureNestedDepth( + tokenizer: MonarchTokenizerInstance, + lines: string[] +): TokenizeMeasurement { + const nestedTokenize = tokenizer._nestedTokenize.bind(tokenizer) + let depth = 0 + let maxNestedDepth = 0 + tokenizer._nestedTokenize = (...args: unknown[]) => { + depth += 1 + maxNestedDepth = Math.max(maxNestedDepth, depth) + try { + return nestedTokenize(...args) + } finally { + depth -= 1 + } + } + + let error: Error | undefined + try { + tokenizeLines(tokenizer, lines) + } catch (thrown) { + error = thrown as Error + } + return { maxNestedDepth, error } +} diff --git a/src/renderer/src/lib/monaco-languages/monarch-upstream-mdx-recursion.test.ts b/src/renderer/src/lib/monaco-languages/monarch-upstream-mdx-recursion.test.ts new file mode 100644 index 00000000000..b87a025bf1e --- /dev/null +++ b/src/renderer/src/lib/monaco-languages/monarch-upstream-mdx-recursion.test.ts @@ -0,0 +1,58 @@ +// @vitest-environment happy-dom +// Why happy-dom: monaco's `basic-languages` entry points import the full +// browser editor before they export the grammar. +import { language as mdxLanguage } from 'monaco-editor/esm/vs/basic-languages/mdx/mdx.js' +import { describe, expect, it } from 'vitest' +import { + EMBED_ENTRY_REST_OF_LINE_BUDGET, + MAX_TOKENIZATION_LINE_LENGTH +} from './monarch-embed-entry-budget' +import { createMonarchTokenizer, measureNestedDepth } from './monarch-tokenizer-test-harness' +import { svelteMonarchLanguage } from './register-svelte' + +// Why pin a third-party grammar: monaco's OWN shipped mdx grammar enters a `js` +// embed on every `{` and pops on `}` with no budget, so it reproduces the +// unbounded embed-entry recursion exactly. That makes it the proof this shape is +// monaco's, not something Orca's svelte/astro/vue grammars invented — and it is +// the tripwire for a monaco upgrade that changes the recursion shape. Do not +// delete as "not our code". + +/** One `js` embed enter/exit transition per repeat, in 3 characters. */ +const interpolations = (count: number): string => '{a}'.repeat(count) + +/** Longest run of them monaco will still tokenize at all. */ +const UNTOKENIZABLE_ABOVE = Math.floor(MAX_TOKENIZATION_LINE_LENGTH / 3) - 1 + +describe('upstream monaco mdx grammar', () => { + it('spends one stack frame per interpolation, unbounded', () => { + const frames = [50, 200, 500].map( + (count) => + measureNestedDepth(createMonarchTokenizer('mdx', mdxLanguage), [interpolations(count)]) + .maxNestedDepth + ) + + expect(frames).toEqual([50, 200, 500]) + }) + + it('exhausts the JS stack on a line monaco is still willing to tokenize', () => { + const line = interpolations(UNTOKENIZABLE_ABOVE) + expect(line.length).toBeLessThan(MAX_TOKENIZATION_LINE_LENGTH) + + const measurement = measureNestedDepth(createMonarchTokenizer('mdx', mdxLanguage), [line]) + + // The frame ceiling is runtime-dependent (~1145 measured here), so assert the + // failure rather than the number. + expect(measurement.error).toBeInstanceOf(RangeError) + expect(measurement.maxNestedDepth).toBeLessThan(UNTOKENIZABLE_ABOVE) + }) + + it('is what the embed-entry budget holds: the same shape stays bounded', () => { + const measurement = measureNestedDepth( + createMonarchTokenizer('svelte', svelteMonarchLanguage), + [interpolations(UNTOKENIZABLE_ABOVE)] + ) + + expect(measurement.error).toBeUndefined() + expect(measurement.maxNestedDepth).toBeLessThanOrEqual(EMBED_ENTRY_REST_OF_LINE_BUDGET) + }) +}) diff --git a/src/renderer/src/lib/monaco-languages/register-astro.test.ts b/src/renderer/src/lib/monaco-languages/register-astro.test.ts index 8d1458bdf52..694c4379ee8 100644 --- a/src/renderer/src/lib/monaco-languages/register-astro.test.ts +++ b/src/renderer/src/lib/monaco-languages/register-astro.test.ts @@ -1,112 +1,32 @@ import { describe, expect, it, vi } from 'vitest' +import { + endEmbeddedLanguages, + formatTokenizedLines, + tokenizeMonarchDocument, + tokenLanguages, + tokenLanguagesPerLine +} from './monarch-tokenizer-test-harness' import { astroLanguageConfiguration, astroMonarchLanguage, registerAstroLanguage } from './register-astro' -type MonarchAction = { - next?: string - nextEmbedded?: string - switchTo?: string -} -type MonarchRule = [RegExp, string | MonarchAction, string?] | { include: string } - -function normalizeState(nextState: string): string { - return nextState.startsWith('@') ? nextState.slice(1) : nextState +// Driven through the real `MonarchTokenizer`: a rule-table walk cannot tell a +// working grammar from one that throws on every `{expr}`, which is how broken +// Astro highlighting shipped green. +function tokenizeAstro(source: string) { + return tokenizeMonarchDocument('astro', astroMonarchLanguage, source) } -function isRuleEntry(rule: MonarchRule): rule is [RegExp, string | MonarchAction, string?] { - return Array.isArray(rule) -} - -function getRuleAction(rule: [RegExp, string | MonarchAction, string?]): MonarchAction | undefined { - const [, action, nextStateShortcut] = rule - return typeof action === 'object' - ? action - : nextStateShortcut - ? { next: nextStateShortcut } - : undefined -} - -function findRuleAction( - state: string, - source: string, - { embedPopOnly = false }: { embedPopOnly?: boolean } = {} -): MonarchAction | undefined { - const tokenizer = astroMonarchLanguage.tokenizer as Record - const stateRules = tokenizer[state] ?? tokenizer[state.split('.')[0]] - const candidateRules = embedPopOnly - ? stateRules.filter((rule) => { - if (!isRuleEntry(rule)) { - return false - } - return getRuleAction(rule)?.nextEmbedded === '@pop' - }) - : stateRules - const matchedRule = candidateRules.find((rule) => { - if (!isRuleEntry(rule)) { - return false - } - const [regexp] = rule - regexp.lastIndex = 0 - const match = regexp.exec(source) - return match !== null && match.index === 0 - }) - - return matchedRule && isRuleEntry(matchedRule) ? getRuleAction(matchedRule) : undefined -} - -function collectFixtureRuleActions(source: string): string[] { - const ruleActions: string[] = [] - const tokenizer = astroMonarchLanguage.tokenizer as Record - const lines = source.split('\n') - const checks: { line: number; state: string; pattern: string }[] = [ - { line: 1, state: 'root', pattern: '---' }, - { line: 4, state: 'frontmatter', pattern: '---' }, - // After the frontmatter closes we are back in `markupReenter`; the next - // non-structural character switches into `markup` with html active. - { line: 6, state: 'markupReenter', pattern: '' }, - { line: 6, state: 'markup', pattern: '{' }, - { line: 6, state: 'astroExpression', pattern: '}' }, - { line: 8, state: 'markup', pattern: '' }, - { line: 10, state: 'scriptBody.javascript', pattern: '' }, - { line: 12, state: 'markup', pattern: '' }, - { line: 14, state: 'styleBody.css', pattern: '' } - ] - - checks.forEach((check) => { - const line = lines.at(check.line - 1) ?? '' - const stateRules = tokenizer[check.state] ?? tokenizer[check.state.split('.')[0]] - const matchedRule = stateRules.find((rule) => { - if (!isRuleEntry(rule)) { - return false - } - const [regexp] = rule - regexp.lastIndex = 0 - const match = regexp.exec(line) - return match !== null && match[0] === check.pattern - }) - if (!matchedRule || !isRuleEntry(matchedRule)) { - return - } - - const actionObject = getRuleAction(matchedRule) - - const nextState = actionObject?.next ? normalizeState(actionObject.next) : '-' - const nextEmbedded = actionObject?.nextEmbedded ?? '-' - const switchTo = actionObject?.switchTo ? normalizeState(actionObject.switchTo) : '-' - ruleActions.push( - `${check.line}:${check.state}:${check.pattern || ''} -> next=${nextState}, embedded=${nextEmbedded}, switch=${switchTo}` - ) - }) - - return ruleActions +/** Which languages actually cover each line — a dropped embed shows up as `astro`. */ +function languagesPerLine(source: string): string[][] { + return tokenLanguagesPerLine(tokenizeAstro(source)) } describe('registerAstroLanguage registration', () => { + // Structural by necessity: covers the registration call itself (ids, + // extensions, idempotence), which tokenizing cannot observe. it('registers the astro language, Monarch tokenizer, and configuration once', () => { const languages: { id: string }[] = [{ id: 'typescript' }] const register = vi.fn((entry: { id: string }) => { @@ -140,8 +60,8 @@ describe('registerAstroLanguage registration', () => { }) }) -describe('astro tokenizer transitions', () => { - it('captures Astro tokenizer transitions for a representative component fixture', () => { +describe('astro tokenization', () => { + it('tokenizes a representative component', () => { const fixture = `--- import Layout from '../layouts/Layout.astro' const title = 'Home' @@ -157,111 +77,120 @@ const title = 'Home' h1 { color: rebeccapurple; } ` - const ruleActions = collectFixtureRuleActions(fixture) - - expect(ruleActions).toMatchInlineSnapshot(` + expect(formatTokenizedLines(tokenizeAstro(fixture))).toMatchInlineSnapshot(` [ - "1:root:--- -> next=-, embedded=typescript, switch=frontmatter", - "4:frontmatter:--- -> next=-, embedded=@pop, switch=markupReenter", - "6:markupReenter: -> next=-, embedded=html, switch=markup", - "6:markup:{ -> next=-, embedded=@pop, switch=astroExpressionEnter", - "6:astroExpression:} -> next=-, embedded=@pop, switch=markupReenter", - "8:markup: -> next=-, embedded=@pop, switch=markupReenter", - "12:markup: -> next=-, embedded=@pop, switch=markupReenter", + "--- | 0:keyword.astro@astro | embed=typescript", + "import Layout from '../layouts/Layout.astro' | 0:-@typescript | embed=typescript", + "const title = 'Home' | 0:-@typescript | embed=typescript", + "--- | 0:keyword.astro@astro | embed=none", + " | | embed=html", + "

{title}

| 0:-@html 4:delimiter.curly.astro@astro 5:-@typescript 10:delimiter.curly.astro@astro 11:-@html | embed=html", + " | 0:-@html | embed=html", + " | 0:tag.astro@astro | embed=none", + " | | embed=html", + " | 0:tag.astro@astro | embed=none", ] `) }) -}) -describe('astro tokenizer regressions', () => { - // Regression: a file that opens with a markup expression like `{title}` has - // no html embed active yet. If `root` itself ever emitted `nextEmbedded: - // '@pop'` Monaco would throw "cannot pop embedded language if not inside - // one" before any push had occurred. Enforce the invariant directly. - it('never pops an embedded language from the root state', () => { - const tokenizer = astroMonarchLanguage.tokenizer as Record - const popRules = tokenizer.root.filter((rule) => { - if (!isRuleEntry(rule)) { - return false - } - return getRuleAction(rule)?.nextEmbedded === '@pop' - }) - expect(popRules).toHaveLength(0) + it('embeds the frontmatter fence as typescript', () => { + expect( + endEmbeddedLanguages(tokenizeAstro("---\nconst title = 'Home'\n---\n

hi

")) + ).toEqual(['typescript', 'typescript', null, 'html']) }) - // Regression (verified live in the Electron app): when entry from root went - // straight to `@markup` with `nextEmbedded: 'html'`, while the embed-pop - // path also went via `@markupReenter`, Monarch's nested tokenizer reported - // "cannot pop embedded language if not inside one" on `{expr}` in markup. - // Routing every push of the html embed through `markupReenter` keeps the - // embed-stack invariant identical for every entry into `markup`. - it('routes all entries into markup through markupReenter', () => { - expect(findRuleAction('root', '

Hello

')).toMatchObject({ - switchTo: '@markupReenter' - }) - expect(findRuleAction('root', '{title}')).toMatchObject({ - switchTo: '@markupReenter' - }) - expect(findRuleAction('markupReenter', '

Hello

')).toMatchObject({ - switchTo: '@markup', - nextEmbedded: 'html' - }) + // Pins monaco-editor#1127: the pop rule's `^` survives Monaco's regex + // rebuild, so an indented or trailing `---` must not close the fence early. + it('keeps the frontmatter fence open past a --- that is not at column 0', () => { + expect(endEmbeddedLanguages(tokenizeAstro('---\n// ---\n ---\n---\n

hi

'))).toEqual([ + 'typescript', + 'typescript', + 'typescript', + null, + 'html' + ]) }) - // Regression: while the html embed is active, only parent rules whose action - // pops the embed are consulted before delegating to html. The `markup` - // state must wire `nextEmbedded: '@pop'` on the structural rules so a - // trailing ``)).toEqual([ + ['html'], + ['astro'], + [embeddedLanguageId], + ['astro'] + ]) + }) + + it.each([ + ['`)).toEqual([ + ['html'], + ['astro'], + [embeddedLanguageId], + ['astro'] + ]) + }) +}) + +describe('astro root state invariant', () => { + // Structural on purpose: behaviour can only reach the root rules some fixture + // happens to exercise, and a root rule that pops an embed throws on the very + // first character of a file. Guard every root rule, exercised or not. + it('has no root rule that pops an embedded language', () => { + const rootRules = (astroMonarchLanguage.tokenizer as Record).root + const popRules = rootRules.filter( + (rule) => + Array.isArray(rule) && (rule[1] as { nextEmbedded?: string })?.nextEmbedded === '@pop' + ) + + expect(popRules).toEqual([]) }) }) diff --git a/src/renderer/src/lib/monaco-languages/register-astro.ts b/src/renderer/src/lib/monaco-languages/register-astro.ts index 800f303be74..e27a32ed4ca 100644 --- a/src/renderer/src/lib/monaco-languages/register-astro.ts +++ b/src/renderer/src/lib/monaco-languages/register-astro.ts @@ -1,4 +1,8 @@ import type * as Monaco from 'monaco-editor' +import { + restOfLineWithinEmbedBudget, + tagCloseWithinEmbedBudget +} from './monarch-embed-entry-budget' type MonacoModule = typeof Monaco @@ -33,6 +37,13 @@ export const astroMonarchLanguage: Monaco.languages.IMonarchLanguage = { // Inside the frontmatter fence the typescript embed is active; only a // closing `---` on its own line pops it. Astro requires the closing // fence at column 0. + // + // The `^` here means "start of the region the embed covers", not start of + // line (monaco-editor#1127): `_findLeavingNestedLanguageOffset` slices the + // compiled `^(?:` prefix off the pop rule and tests `matchOnlyAtLineStart` + // against the substring `_myTokenize` handed it. Correct only because this + // embed always opens at end-of-line, so that substring is a whole line — + // do not reuse a `^`-anchored pop rule for an embed entered mid-line. frontmatter: [ [/^---\s*$/, { token: 'keyword', switchTo: '@markupReenter', nextEmbedded: '@pop' }] ], @@ -50,7 +61,32 @@ export const astroMonarchLanguage: Monaco.languages.IMonarchLanguage = { [//, { token: 'comment', switchTo: '@markupReenter' }], [/[^-]+/, 'comment'], @@ -64,14 +100,27 @@ export const astroMonarchLanguage: Monaco.languages.IMonarchLanguage = { astroExpressionEnter: [ // Empty `{}`: entry popped html, but typescript was never entered. [/\}/, { token: 'delimiter.curly', switchTo: '@markupReenter' }], - [/(?=.)/, { token: '', switchTo: '@astroExpression', nextEmbedded: 'typescript' }] + [ + restOfLineWithinEmbedBudget, + { token: '@rematch', switchTo: '@astroExpression', nextEmbedded: 'typescript' } + ], + [/(?=.)/, { token: '@rematch', switchTo: '@astroExpressionPlain' }] ], astroExpression: [ [/\}/, { token: 'delimiter.curly', switchTo: '@markupReenter', nextEmbedded: '@pop' }] ], + // Same expression, no typescript embed: reached only past the budget. + astroExpressionPlain: [ + [/\}/, { token: 'delimiter.curly', switchTo: '@markupReenter' }], + [/[^}]+/, ''] + ], scriptOpen: [ [/\/>/, { token: 'tag', switchTo: '@markupReenter' }], - [/>/, { token: 'tag', switchTo: '@scriptBody.$S2', nextEmbedded: '$S2' }], + [ + tagCloseWithinEmbedBudget, + { token: 'tag', switchTo: '@scriptBody.$S2', nextEmbedded: '$S2' } + ], + [/>/, { token: 'tag', switchTo: '@scriptBodyPlain.$S2' }], [/lang(?=\s*=)/, { token: 'attribute.name', switchTo: '@scriptLangBeforeEquals.$S2' }], { include: '@tagAttributes' } ], @@ -101,9 +150,24 @@ export const astroMonarchLanguage: Monaco.languages.IMonarchLanguage = { scriptBody: [ [/<\/script\s*>/, { token: 'tag', switchTo: '@markupReenter', nextEmbedded: '@pop' }] ], + // Over-budget mirror of the body: re-enters `$S2` as soon as the rest of + // the line fits, so a long opening line does not grey out the whole block. + scriptBodyPlain: [ + [/<\/script\s*>/, { token: 'tag', switchTo: '@markupReenter' }], + [ + restOfLineWithinEmbedBudget, + { token: '@rematch', switchTo: '@scriptBody.$S2', nextEmbedded: '$S2' } + ], + [/[^<]+/, ''], + [/./, ''] + ], styleOpen: [ [/\/>/, { token: 'tag', switchTo: '@markupReenter' }], - [/>/, { token: 'tag', switchTo: '@styleBody.$S2', nextEmbedded: '$S2' }], + [ + tagCloseWithinEmbedBudget, + { token: 'tag', switchTo: '@styleBody.$S2', nextEmbedded: '$S2' } + ], + [/>/, { token: 'tag', switchTo: '@styleBodyPlain.$S2' }], [/lang(?=\s*=)/, { token: 'attribute.name', switchTo: '@styleLangBeforeEquals.$S2' }], { include: '@tagAttributes' } ], @@ -133,6 +197,15 @@ export const astroMonarchLanguage: Monaco.languages.IMonarchLanguage = { styleBody: [ [/<\/style\s*>/, { token: 'tag', switchTo: '@markupReenter', nextEmbedded: '@pop' }] ], + styleBodyPlain: [ + [/<\/style\s*>/, { token: 'tag', switchTo: '@markupReenter' }], + [ + restOfLineWithinEmbedBudget, + { token: '@rematch', switchTo: '@styleBody.$S2', nextEmbedded: '$S2' } + ], + [/[^<]+/, ''], + [/./, ''] + ], tagAttributes: [ [/[^\s/>=]+/, 'attribute.name'], [/=/, 'delimiter'], diff --git a/src/renderer/src/lib/monaco-languages/register-jsonl.test.ts b/src/renderer/src/lib/monaco-languages/register-jsonl.test.ts index 8e195a46926..8dd79ac28e3 100644 --- a/src/renderer/src/lib/monaco-languages/register-jsonl.test.ts +++ b/src/renderer/src/lib/monaco-languages/register-jsonl.test.ts @@ -1,4 +1,9 @@ import { describe, expect, it, vi } from 'vitest' +import { + formatTokenizedLines, + tokenizeMonarchDocument, + tokenTypeAt +} from './monarch-tokenizer-test-harness' import { JSONL_LANGUAGE_ID, jsonlLanguageConfiguration, @@ -6,6 +11,10 @@ import { registerJsonlLanguage } from './register-jsonl' +function tokenizeJsonl(source: string) { + return tokenizeMonarchDocument(JSONL_LANGUAGE_ID, jsonlMonarchLanguage, source) +} + function createMonacoMock(existingLanguageIds: string[] = []) { return { languages: { @@ -52,3 +61,65 @@ describe('registerJsonlLanguage', () => { expect(monaco.languages.setMonarchTokensProvider).not.toHaveBeenCalled() }) }) + +describe('jsonl tokenization', () => { + it('tokenizes a representative pair of records', () => { + const fixture = `{"a": 1, "b": "x", "c": true, "d": null} +{"e": [1, -2.5e3], "f": "a\\"b"}` + + expect(formatTokenizedLines(tokenizeJsonl(fixture))).toMatchInlineSnapshot(` + [ + "{"a": 1, "b": "x", "c": true, "d": null} | 0:delimiter.curly.jsonl@jsonl 1:type.identifier.jsonl@jsonl 4:delimiter.jsonl@jsonl 5:white.jsonl@jsonl 6:number.jsonl@jsonl 7:delimiter.jsonl@jsonl 8:white.jsonl@jsonl 9:type.identifier.jsonl@jsonl 12:delimiter.jsonl@jsonl 13:white.jsonl@jsonl 14:string.jsonl@jsonl 17:delimiter.jsonl@jsonl 18:white.jsonl@jsonl 19:type.identifier.jsonl@jsonl 22:delimiter.jsonl@jsonl 23:white.jsonl@jsonl 24:keyword.jsonl@jsonl 28:delimiter.jsonl@jsonl 29:white.jsonl@jsonl 30:type.identifier.jsonl@jsonl 33:delimiter.jsonl@jsonl 34:white.jsonl@jsonl 35:keyword.jsonl@jsonl 39:delimiter.curly.jsonl@jsonl | embed=none", + "{"e": [1, -2.5e3], "f": "a\\"b"} | 0:delimiter.curly.jsonl@jsonl 1:type.identifier.jsonl@jsonl 4:delimiter.jsonl@jsonl 5:white.jsonl@jsonl 6:delimiter.square.jsonl@jsonl 7:number.jsonl@jsonl 8:delimiter.jsonl@jsonl 9:white.jsonl@jsonl 10:number.jsonl@jsonl 16:delimiter.square.jsonl@jsonl 17:delimiter.jsonl@jsonl 18:white.jsonl@jsonl 19:type.identifier.jsonl@jsonl 22:delimiter.jsonl@jsonl 23:white.jsonl@jsonl 24:string.jsonl@jsonl 26:string.escape.jsonl@jsonl 28:string.jsonl@jsonl 30:delimiter.curly.jsonl@jsonl | embed=none", + ] + `) + }) + + it('colours a property key differently from a string value', () => { + // The `(?=\s*:)` lookahead is the only thing separating the two; a regression + // there makes every key look like a value. + const [line] = tokenizeJsonl('{"key": "value"}') + + expect(tokenTypeAt(line, 1)).toBe('type.identifier') + expect(tokenTypeAt(line, 8)).toBe('string') + }) + + // Regression, found by this suite once it started running the real tokenizer: + // `@string` used to survive the line break, so one truncated record rendered + // every record after it as a single string. + it.each([ + ['mid-string', '{"a": "truncated here'], + ['mid-escape', '{"a": "truncated\\'], + ['on a trailing backslash', '{"a": "x\\'] + ])('does not let a record truncated %s poison the next one', (_name, truncated) => { + const [, second] = tokenizeJsonl(`${truncated}\n{"b": 1}`) + + expect(tokenTypeAt(second, 1)).toBe('type.identifier') + expect(tokenTypeAt(second, 6)).toBe('number') + }) + + it('marks the unterminated remainder of a truncated record', () => { + const [first] = tokenizeJsonl('{"a": "truncated here') + + expect(tokenTypeAt(first, 6)).toBe('string.invalid') + }) + + it.each([ + ['escaped quote', '{"m": "he said \\"hi\\""}', 15], + ['escaped backslash', '{"m": "C:\\\\Users"}', 10], + ['unicode escape', '{"m": "\\u00e9"}', 7], + ['newline escape', '{"m": "a\\nb"}', 8] + ])('still highlights an %s inside a well-formed record', (_name, record, escapeOffset) => { + // The fix must not cost escape fidelity on the common case: a candidate that + // collapsed the string into one regex lost every one of these. + const [line] = tokenizeJsonl(record) + + expect(tokenTypeAt(line, escapeOffset)).toBe('string.escape') + }) + + it('flags an invalid escape inside a well-formed record', () => { + const [line] = tokenizeJsonl('{"m": "a\\qb"}') + + expect(tokenTypeAt(line, 8)).toBe('string.escape.invalid') + }) +}) diff --git a/src/renderer/src/lib/monaco-languages/register-jsonl.ts b/src/renderer/src/lib/monaco-languages/register-jsonl.ts index fbe0bb4dbac..cb12660ba9b 100644 --- a/src/renderer/src/lib/monaco-languages/register-jsonl.ts +++ b/src/renderer/src/lib/monaco-languages/register-jsonl.ts @@ -34,7 +34,14 @@ export const jsonlMonarchLanguage: Monaco.languages.IMonarchLanguage = { { include: '@whitespace' }, // Property key vs string value are both quoted; color keys distinctly. [/"(?:[^"\\]|\\.)*"(?=\s*:)/, 'type.identifier'], - [/"/, 'string', '@string'], + // Why the lookahead: each JSONL line is an independent value, but Monarch + // state survives the line break. Pushing `@string` unconditionally meant + // one truncated record (a normal way for a log to end) left every later + // record inside the string state, rendering the rest of the file as one + // string. Only enter the escape-aware state once a closing quote is known + // to be on this line; an unterminated remainder is consumed below instead. + [/"(?=(?:[^"\\]|\\.)*")/, 'string', '@string'], + [/"(?:[^"\\]|\\.)*\\?$/, 'string.invalid'], [/[{}[\]]/, '@brackets'], [/-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/, 'number'], [/\b(?:true|false)\b/, 'keyword'], diff --git a/src/renderer/src/lib/monaco-languages/register-svelte.test.ts b/src/renderer/src/lib/monaco-languages/register-svelte.test.ts index 430c321f65c..866ecf21ad3 100644 --- a/src/renderer/src/lib/monaco-languages/register-svelte.test.ts +++ b/src/renderer/src/lib/monaco-languages/register-svelte.test.ts @@ -1,124 +1,33 @@ import { describe, expect, it, vi } from 'vitest' +import { + endEmbeddedLanguages, + formatTokenizedLines, + tokenizeMonarchDocument, + tokenLanguages, + tokenLanguagesPerLine, + tokenTypeAt +} from './monarch-tokenizer-test-harness' import { registerSvelteLanguage, svelteLanguageConfiguration, svelteMonarchLanguage } from './register-svelte' -type MonarchAction = { - next?: string - nextEmbedded?: string - switchTo?: string -} -type MonarchRule = [RegExp, string | MonarchAction, string?] | { include: string } - -function normalizeState(nextState: string): string { - return nextState.startsWith('@') ? nextState.slice(1) : nextState +// These tests drive the real `MonarchTokenizer`. Walking the rule table instead +// let a grammar that threw on 100% of Svelte inputs — including `

a {b}

` — +// ship with a green suite, because a broken grammar still has a valid table. +function tokenizeSvelte(source: string) { + return tokenizeMonarchDocument('svelte', svelteMonarchLanguage, source) } -function isRuleEntry(rule: MonarchRule): rule is [RegExp, string | MonarchAction, string?] { - return Array.isArray(rule) -} - -function getRuleAction(rule: [RegExp, string | MonarchAction, string?]): MonarchAction | undefined { - const [, action, nextStateShortcut] = rule - return typeof action === 'object' - ? action - : nextStateShortcut - ? { next: nextStateShortcut } - : undefined -} - -function findRuleAction( - state: string, - source: string, - { embedPopOnly = false }: { embedPopOnly?: boolean } = {} -): MonarchAction | undefined { - const tokenizer = svelteMonarchLanguage.tokenizer as Record - const stateRules = tokenizer[state] ?? tokenizer[state.split('.')[0]] - // When the html embed is active inside `markup`, Monaco's - // `_findLeavingNestedLanguageOffset` only consults rules whose action has - // `nextEmbedded: '@pop'` — the zero-width `@rematch` catch-all is - // skipped. Mirror that when callers want to verify the "structural rule - // pops the embed" path. - const candidateRules = embedPopOnly - ? stateRules.filter((rule) => { - if (!isRuleEntry(rule)) { - return false - } - return getRuleAction(rule)?.nextEmbedded === '@pop' - }) - : stateRules - const matchedRule = candidateRules.find((rule) => { - if (!isRuleEntry(rule)) { - return false - } - const [regexp] = rule - regexp.lastIndex = 0 - const match = regexp.exec(source) - return match !== null && match.index === 0 - }) - - return matchedRule && isRuleEntry(matchedRule) ? getRuleAction(matchedRule) : undefined -} - -function collectFixtureRuleActions(source: string): string[] { - const ruleActions: string[] = [] - const tokenizer = svelteMonarchLanguage.tokenizer as Record - const lines = source.split('\n') - const checks: { line: number; state: string; pattern: string }[] = [ - { line: 1, state: 'root', pattern: '' }, - { line: 4, state: 'scriptBody.typescript', pattern: '' }, - // After pops back to root and the next non-structural character - // switches root -> markup with the html embed active. - { line: 6, state: 'root', pattern: '' }, - { line: 7, state: 'markup', pattern: '{#if' }, - { line: 7, state: 'svelteBlockExpression', pattern: '}' }, - { line: 8, state: 'markup', pattern: '{' }, - { line: 8, state: 'svelteExpression', pattern: '}' }, - { line: 9, state: 'markup', pattern: '{:else' }, - { line: 9, state: 'svelteBlockExpressionEnter', pattern: '}' }, - { line: 11, state: 'markup', pattern: '{/if}' }, - { line: 13, state: 'markup', pattern: '{' }, - { line: 13, state: 'svelteExpression', pattern: '}' }, - { line: 14, state: 'markup', pattern: '{@html' }, - { line: 14, state: 'svelteExpression', pattern: '}' }, - { line: 16, state: 'markup', pattern: '' }, - { line: 18, state: 'styleBody.css', pattern: '' } - ] - - checks.forEach((check) => { - const line = lines.at(check.line - 1) ?? '' - const stateRules = tokenizer[check.state] ?? tokenizer[check.state.split('.')[0]] - const matchedRule = stateRules.find((rule) => { - if (!isRuleEntry(rule)) { - return false - } - const [regexp] = rule - regexp.lastIndex = 0 - const match = regexp.exec(line) - return match !== null && match[0] === check.pattern - }) - if (!matchedRule || !isRuleEntry(matchedRule)) { - return - } - - const actionObject = getRuleAction(matchedRule) - - const nextState = actionObject?.next ? normalizeState(actionObject.next) : '-' - const nextEmbedded = actionObject?.nextEmbedded ?? '-' - const switchTo = actionObject?.switchTo ? normalizeState(actionObject.switchTo) : '-' - ruleActions.push( - `${check.line}:${check.state}:${check.pattern || ''} -> next=${nextState}, embedded=${nextEmbedded}, switch=${switchTo}` - ) - }) - - return ruleActions +/** Which languages actually cover each line — a dropped embed shows up as `svelte`. */ +function languagesPerLine(source: string): string[][] { + return tokenLanguagesPerLine(tokenizeSvelte(source)) } describe('registerSvelteLanguage registration', () => { + // Structural by necessity: this covers the registration call itself + // (ids, extensions, idempotence), which no amount of tokenizing can observe. it('registers the svelte language, Monarch tokenizer, and configuration once', () => { const languages: { id: string }[] = [{ id: 'typescript' }] const register = vi.fn((entry: { id: string }) => { @@ -152,8 +61,8 @@ describe('registerSvelteLanguage registration', () => { }) }) -describe('svelte tokenizer transitions', () => { - it('captures Svelte tokenizer transitions for a representative SFC fixture', () => { +describe('svelte tokenization', () => { + it('tokenizes a representative SFC', () => { const fixture = ` -> next=-, embedded=@pop, switch=markupReenter", - "6:root: -> next=-, embedded=html, switch=markup", - "7:markup:{#if -> next=-, embedded=@pop, switch=svelteBlockExpressionEnter", - "7:svelteBlockExpression:} -> next=-, embedded=@pop, switch=markupReenter", - "8:markup:{ -> next=-, embedded=@pop, switch=svelteExpressionEnter", - "8:svelteExpression:} -> next=-, embedded=@pop, switch=markupReenter", - "9:markup:{:else -> next=-, embedded=@pop, switch=svelteBlockExpressionEnter", - "9:svelteBlockExpressionEnter:} -> next=-, embedded=-, switch=markupReenter", - "11:markup:{/if} -> next=-, embedded=-, switch=-", - "13:markup:{ -> next=-, embedded=@pop, switch=svelteExpressionEnter", - "13:svelteExpression:} -> next=-, embedded=@pop, switch=markupReenter", - "14:markup:{@html -> next=-, embedded=@pop, switch=svelteExpressionEnter", - "14:svelteExpression:} -> next=-, embedded=@pop, switch=markupReenter", - "16:markup: -> next=-, embedded=@pop, switch=markupReenter", + " | 0:tag.svelte@svelte | embed=none", + " | | embed=html", + "

Counter

| 0:-@html | embed=html", + "{#if count > 0} | 0:keyword.control.svelte@svelte 4:-@typescript 14:keyword.control.svelte@svelte | embed=none", + "

{count} clicked

| 0:-@html 5:delimiter.curly.svelte@svelte 6:-@typescript 11:delimiter.curly.svelte@svelte 12:-@html | embed=html", + "{:else} | 0:keyword.control.svelte@svelte | embed=none", + "

not yet

| 0:-@html | embed=html", + "{/if} | 0:-@html | embed=html", + " | 0:-@html | embed=html", + " | 0:-@html 17:delimiter.curly.svelte@svelte 18:-@typescript 27:delimiter.curly.svelte@svelte 28:-@html 29:delimiter.curly.svelte@svelte 30:-@typescript 35:delimiter.curly.svelte@svelte 36:-@html | embed=html", + "{@html 'raw'} | 0:keyword.control.svelte@svelte 6:-@typescript 21:delimiter.curly.svelte@svelte | embed=none", + " | | embed=html", + " | 0:tag.svelte@svelte | embed=none", ] `) }) -}) -describe('svelte tokenizer regressions', () => { - // Regression: when a Svelte file starts with `{#if}`, `{name}`, or `{@html}`, - // no html embed is active yet. Earlier drafts unconditionally emitted - // `nextEmbedded: '@pop'` from root, which Monaco rejects with - // "cannot pop embedded language if not inside one". The fix splits the - // entry-only `root` state from the html-embedded `markup` state. - it('does not pop a non-existent embed when a file starts with a Svelte block', () => { - const action = findRuleAction('root', '{#if foo}') - expect(action).toMatchObject({ switchTo: '@svelteBlockExpressionEnter' }) - expect(action?.nextEmbedded).toBeUndefined() + // Regression (the field failure): the first interpolation of a file threw + // "cannot pop embedded language if not inside one" — every Svelte file with a + // `{}` in it, which is essentially all of them. + it('highlights every interpolation of a markup line', () => { + const [line] = tokenizeSvelte('

a {first} b {second} c

') + + expect(tokenLanguages(line)).toEqual([ + 'html', + 'svelte', + 'typescript', + 'svelte', + 'html', + 'svelte', + 'typescript', + 'svelte', + 'html' + ]) }) - it('starts the html embed and switches to markup when markup begins', () => { - expect(findRuleAction('root', '

Counter

')).toMatchObject({ - switchTo: '@markup', - nextEmbedded: 'html' - }) + it('opens a file on a Svelte block without popping a missing embed', () => { + // No html embed exists yet at file start, so the block's entry rule must not + // pop one — Monarch throws outright if it does. + const [line] = tokenizeSvelte('{#if count > 0}') + + expect(tokenTypeAt(line, 0)).toBe('keyword.control') + expect(tokenLanguages(line)).toEqual(['svelte', 'typescript', 'svelte']) }) - // Regression: while the html embed is active, only parent rules whose action - // pops the embed are consulted before delegating to html. The first draft - // omitted `nextEmbedded: '@pop'` from ``)).toEqual([ + ['html'], + ['svelte'], + [embeddedLanguageId], + ['svelte'] + ]) + }) + + it.each([ + ['`)).toEqual([ + ['html'], + ['svelte'], + [embeddedLanguageId], + ['svelte'] + ]) + }) +}) + +describe('svelte root state invariant', () => { + // Structural on purpose: behaviour can only reach the root rules some fixture + // happens to exercise, and a root rule that pops an embed throws on the very + // first character of a file. Guard every root rule, exercised or not. + it('has no root rule that pops an embedded language', () => { + const rootRules = (svelteMonarchLanguage.tokenizer as Record).root + const popRules = rootRules.filter( + (rule) => + Array.isArray(rule) && (rule[1] as { nextEmbedded?: string })?.nextEmbedded === '@pop' + ) + + expect(popRules).toEqual([]) }) }) diff --git a/src/renderer/src/lib/monaco-languages/register-svelte.ts b/src/renderer/src/lib/monaco-languages/register-svelte.ts index 8fd197ea112..7e4b0cc0292 100644 --- a/src/renderer/src/lib/monaco-languages/register-svelte.ts +++ b/src/renderer/src/lib/monaco-languages/register-svelte.ts @@ -1,4 +1,8 @@ import type * as Monaco from 'monaco-editor' +import { + restOfLineWithinEmbedBudget, + tagCloseWithinEmbedBudget +} from './monarch-embed-entry-budget' type MonacoModule = typeof Monaco @@ -38,7 +42,18 @@ export const svelteMonarchLanguage: Monaco.languages.IMonarchLanguage = { { token: 'keyword.control', switchTo: '@svelteExpressionEnter' } ], [/\{(?=[^#:/@])/, { token: 'delimiter.curly', switchTo: '@svelteExpressionEnter' }], - [/(?=.)/, { token: '', switchTo: '@markup', nextEmbedded: 'html' }] + // `@rematch` is required: on a zero-width match Monarch's progress check + // `continue`s and silently drops a pending `nextEmbedded` for any other + // token, leaving `markup` without the html embed its pop rules assume. + [ + restOfLineWithinEmbedBudget, + { token: '@rematch', switchTo: '@markup', nextEmbedded: 'html' } + ], + // Past the budget: same structure, no embed, so the rest of the line + // cannot deepen the recursion. + [/<\/?[A-Za-z][^>]*>/, 'tag'], + [/[^<{]+/, ''], + [/./, ''] ], // html-embedded markup state. INVARIANT: whenever we are in `markup`, the // html embed is active. Every state that pops back to markup routes @@ -88,7 +103,14 @@ export const svelteMonarchLanguage: Monaco.languages.IMonarchLanguage = { // switches to `markup`. `@rematch` short-circuits Monarch's progress // check — a zero-width match that stays in the same state and stack // depth otherwise throws "no progress in tokenizer". - markupReenter: [[/(?=.)/, { token: '@rematch', switchTo: '@markup', nextEmbedded: 'html' }]], + markupReenter: [ + [ + restOfLineWithinEmbedBudget, + { token: '@rematch', switchTo: '@markup', nextEmbedded: 'html' } + ], + // Over budget: `root` carries the same structural rules without embeds. + [/(?=.)/, { token: '@rematch', switchTo: '@root' }] + ], comment: [ [/-->/, { token: 'comment', switchTo: '@markupReenter' }], [/[^-]+/, 'comment'], @@ -105,23 +127,44 @@ export const svelteMonarchLanguage: Monaco.languages.IMonarchLanguage = { // Empty expression `{}`: entry popped the html embed, but we never // entered the typescript embed, so only the state needs to unwind. [/\}/, { token: 'delimiter.curly', switchTo: '@markupReenter' }], - [/(?=.)/, { token: '', switchTo: '@svelteExpression', nextEmbedded: 'typescript' }] + [ + restOfLineWithinEmbedBudget, + { token: '@rematch', switchTo: '@svelteExpression', nextEmbedded: 'typescript' } + ], + [/(?=.)/, { token: '@rematch', switchTo: '@svelteExpressionPlain' }] ], svelteExpression: [ [/\}/, { token: 'delimiter.curly', switchTo: '@markupReenter', nextEmbedded: '@pop' }] ], + // Same expression, no typescript embed: reached only past the budget. + svelteExpressionPlain: [ + [/\}/, { token: 'delimiter.curly', switchTo: '@markupReenter' }], + [/[^}]+/, ''] + ], svelteBlockExpressionEnter: [ [/\}/, { token: 'keyword.control', switchTo: '@markupReenter' }], - [/(?=.)/, { token: '', switchTo: '@svelteBlockExpression', nextEmbedded: 'typescript' }] + [ + restOfLineWithinEmbedBudget, + { token: '@rematch', switchTo: '@svelteBlockExpression', nextEmbedded: 'typescript' } + ], + [/(?=.)/, { token: '@rematch', switchTo: '@svelteBlockExpressionPlain' }] ], svelteBlockExpression: [ [/\}/, { token: 'keyword.control', switchTo: '@markupReenter', nextEmbedded: '@pop' }] ], + svelteBlockExpressionPlain: [ + [/\}/, { token: 'keyword.control', switchTo: '@markupReenter' }], + [/[^}]+/, ''] + ], scriptOpen: [ // Self-closing `' }, - { line: 9, state: 'root', pattern: '' }, - { line: 11, state: 'styleBody.css', pattern: '' } - ] - - checks.forEach((check) => { - const line = lines.at(check.line - 1) ?? '' - const stateRules = tokenizer[check.state] ?? tokenizer[check.state.split('.')[0]] - const matchedRule = stateRules.find((rule) => { - if (!isRuleEntry(rule)) { - return false - } - const [regexp] = rule - regexp.lastIndex = 0 - const match = regexp.exec(line) - return match !== null && match[0] === check.pattern - }) - if (!matchedRule || !isRuleEntry(matchedRule)) { - return - } - - const actionObject = getRuleAction(matchedRule) - - ruleActions.push({ - line: check.line, - state: check.state, - matched: check.pattern, - nextState: actionObject?.next ? normalizeState(actionObject.next) : undefined, - nextEmbedded: actionObject?.nextEmbedded, - switchTo: actionObject?.switchTo ? normalizeState(actionObject.switchTo) : undefined - }) - }) - - return ruleActions -} - -describe('registerVueLanguage', () => { +describe('registerVueLanguage registration', () => { + // Structural by necessity: covers the registration call itself (ids, + // extensions, idempotence), which tokenizing cannot observe. it('registers the vue language, Monarch tokenizer, and configuration once', () => { const languages: { id: string }[] = [{ id: 'typescript' }] const register = vi.fn((entry: { id: string }) => { @@ -136,8 +54,10 @@ describe('registerVueLanguage', () => { expect(setLanguageConfiguration).toHaveBeenCalledTimes(1) expect(setLanguageConfiguration).toHaveBeenCalledWith('vue', vueLanguageConfiguration) }) +}) - it('captures Vue tokenizer transitions for a representative SFC fixture', () => { +describe('vue tokenization', () => { + it('tokenizes a representative SFC', () => { const fixture = ` @@ -150,121 +70,110 @@ const message = 'hello' p { color: rebeccapurple; } ` - const ruleActions = collectFixtureRuleActions(fixture) - - expect(ruleActions).toMatchInlineSnapshot(` + expect(formatTokenizedLines(tokenizeVue(fixture))).toMatchInlineSnapshot(` [ - { - "line": 1, - "matched": "", - "nextEmbedded": "html", - "nextState": undefined, - "state": "templateOpen", - "switchTo": "templateBody", - }, - { - "line": 2, - "matched": "{{", - "nextEmbedded": "@pop", - "nextState": "templateExpressionEnter", - "state": "templateBody", - "switchTo": undefined, - }, - { - "line": 2, - "matched": "}}", - "nextEmbedded": "@pop", - "nextState": "pop", - "state": "templateExpression", - "switchTo": undefined, - }, - { - "line": 3, - "matched": "", - "nextEmbedded": "@pop", - "nextState": "pop", - "state": "templateBody", - "switchTo": undefined, - }, - { - "line": 5, - "matched": "", - "nextEmbedded": "$S2", - "nextState": undefined, - "state": "scriptOpen.typescript", - "switchTo": "scriptBody.$S2", - }, - { - "line": 7, - "matched": "", - "nextEmbedded": "@pop", - "nextState": "pop", - "state": "scriptBody.typescript", - "switchTo": undefined, - }, - { - "line": 9, - "matched": "", - "nextEmbedded": "$S2", - "nextState": undefined, - "state": "styleOpen.css", - "switchTo": "styleBody.$S2", - }, - { - "line": 11, - "matched": "", - "nextEmbedded": "@pop", - "nextState": "pop", - "state": "styleBody.css", - "switchTo": undefined, - }, + " | 0:tag.vue@vue | embed=none", + " | | embed=none", + " | 0:tag.vue@vue | embed=none", + " | | embed=none", + " | 0:tag.vue@vue | embed=none", ] `) }) - it('tracks embedded languages from Vue block attributes', () => { - expect(findRuleAction('templateExpressionEnter', 'message }}')).toMatchObject({ - nextEmbedded: 'typescript', - switchTo: '@templateExpression' - }) - expect(findRuleAction('scriptLangValue.typescript', '"js"')).toMatchObject({ - switchTo: '@scriptOpen.javascript' - }) - expect(findRuleAction('scriptLangValue.javascript', '"ts"')).toMatchObject({ - switchTo: '@scriptOpen.typescript' - }) - expect(findRuleAction('scriptLangValue.typescript', 'js')).toMatchObject({ - switchTo: '@scriptOpen.javascript' - }) - expect(findRuleAction('styleLangValue.css', '"scss"')).toMatchObject({ - switchTo: '@styleOpen.scss' - }) - expect(findRuleAction('styleLangValue.css', 'less')).toMatchObject({ - switchTo: '@styleOpen.less' - }) + // Regression: every `{{ }}` threw "cannot pop embedded language if not inside + // one" once the template body lost its html embed. + it('highlights every interpolation in a template line', () => { + const [, line] = tokenizeVue('') + + expect(tokenLanguages(line)).toEqual([ + 'html', + 'vue', + 'typescript', + 'vue', + 'html', + 'vue', + 'typescript', + 'vue', + 'html' + ]) + }) + + it('embeds the template body as html', () => { + expect(endEmbeddedLanguages(tokenizeVue(''))).toEqual([ + 'html', + 'html', + null + ]) + }) + + it('keeps the template embedded across a comment before it', () => { + expect(languagesPerLine('\n')).toEqual([ + ['vue'], + ['vue'], + ['html'], + ['vue'] + ]) + }) + + it('does not enter typescript for an empty interpolation', () => { + // `{{}}` pops html on entry but never pushes typescript; the close must + // unwind only the state, or it pops an embed that is not there. + const [, line] = tokenizeVue('') + + expect(tokenLanguages(line)).toEqual(['html', 'vue', 'html']) + }) +}) + +describe('vue embedded language attributes', () => { + it.each([ + ['`)).toEqual([ + ['vue'], + [embeddedLanguageId], + ['vue'] + ]) + }) + + it.each([ + ['`)).toEqual([ + ['vue'], + [embeddedLanguageId], + ['vue'] + ]) + }) +}) + +describe('vue root state invariant', () => { + // Structural on purpose: behaviour can only reach the root rules some fixture + // happens to exercise, and a root rule that pops an embed throws on the very + // first character of a file. Guard every root rule, exercised or not. + it('has no root rule that pops an embedded language', () => { + const rootRules = (vueMonarchLanguage.tokenizer as Record).root + const popRules = rootRules.filter( + (rule) => + Array.isArray(rule) && (rule[1] as { nextEmbedded?: string })?.nextEmbedded === '@pop' + ) + + expect(popRules).toEqual([]) }) }) diff --git a/src/renderer/src/lib/monaco-languages/register-vue.ts b/src/renderer/src/lib/monaco-languages/register-vue.ts index b3531f8f16c..a12f1557f7e 100644 --- a/src/renderer/src/lib/monaco-languages/register-vue.ts +++ b/src/renderer/src/lib/monaco-languages/register-vue.ts @@ -1,4 +1,8 @@ import type * as Monaco from 'monaco-editor' +import { + restOfLineWithinEmbedBudget, + tagCloseWithinEmbedBudget +} from './monarch-embed-entry-budget' type MonacoModule = typeof Monaco @@ -28,31 +32,72 @@ export const vueMonarchLanguage: Monaco.languages.IMonarchLanguage = { ], templateOpen: [ [/\/>/, 'tag', '@pop'], - [/>/, { token: 'tag', switchTo: '@templateBody', nextEmbedded: 'html' }], + [ + tagCloseWithinEmbedBudget, + { token: 'tag', switchTo: '@templateBody', nextEmbedded: 'html' } + ], + [/>/, { token: 'tag', switchTo: '@templateBodyPlain' }], { include: '@tagAttributes' } ], + // INVARIANT: the html embed is active whenever this state is. Leaving an + // interpolation routes back through `templateBodyReenter`, never straight + // here, or the next `{{` would pop an embed that is no longer on the stack. + // Transitions are flat (`switchTo`) so the monarch stack stays at the depth + // `` still pops back to `root`. templateBody: [ [ /\{\{/, - { token: 'delimiter.curly', next: '@templateExpressionEnter', nextEmbedded: '@pop' } + { token: 'delimiter.curly', switchTo: '@templateExpressionEnter', nextEmbedded: '@pop' } ], - [/<\/template\s*>/, { token: 'tag', next: '@pop', nextEmbedded: '@pop' }], - // After a `{{ ... }}` interpolation returns here, the html embed - // has been popped alongside the typescript expression embed. Re-enter - // html so the remaining template markup is tokenized by Monaco's html - // tokenizer instead of falling back to the empty default token. - [/(?=.)/, { token: '', nextEmbedded: 'html' }] + [/<\/template\s*>/, { token: 'tag', next: '@pop', nextEmbedded: '@pop' }] + ], + // Re-entry shim. `@rematch` is required: on a zero-width match Monarch's + // progress check rejects any other token and drops the pending embed with + // it, leaving `templateBody` without the html embed its pop rules assume. + templateBodyReenter: [ + [ + restOfLineWithinEmbedBudget, + { token: '@rematch', switchTo: '@templateBody', nextEmbedded: 'html' } + ], + [/(?=.)/, { token: '@rematch', switchTo: '@templateBodyPlain' }] + ], + // Same body with no embeds, so the rest of an over-budget line cannot + // deepen the recursion. Its rules must not touch the embed stack. + templateBodyPlain: [ + [/\{\{/, { token: 'delimiter.curly', switchTo: '@templateExpressionEnter' }], + [/<\/template\s*>/, { token: 'tag', next: '@pop' }], + [ + restOfLineWithinEmbedBudget, + { token: '@rematch', switchTo: '@templateBody', nextEmbedded: 'html' } + ], + [/<\/?[A-Za-z][^>]*>/, 'tag'], + [/[^<{]+/, ''], + [/./, ''] ], templateExpressionEnter: [ - [/\}\}/, { token: 'delimiter.curly', next: '@pop' }], - [/(?=.)/, { token: '', switchTo: '@templateExpression', nextEmbedded: 'typescript' }] + [/\}\}/, { token: 'delimiter.curly', switchTo: '@templateBodyReenter' }], + [ + restOfLineWithinEmbedBudget, + { token: '@rematch', switchTo: '@templateExpression', nextEmbedded: 'typescript' } + ], + [/(?=.)/, { token: '@rematch', switchTo: '@templateExpressionPlain' }] ], templateExpression: [ - [/\}\}/, { token: 'delimiter.curly', next: '@pop', nextEmbedded: '@pop' }] + [/\}\}/, { token: 'delimiter.curly', switchTo: '@templateBodyReenter', nextEmbedded: '@pop' }] + ], + // Same expression, no typescript embed: reached only past the budget. + templateExpressionPlain: [ + [/\}\}/, { token: 'delimiter.curly', switchTo: '@templateBodyReenter' }], + [/[^}]+/, ''], + [/./, ''] ], scriptOpen: [ [/\/>/, 'tag', '@pop'], - [/>/, { token: 'tag', switchTo: '@scriptBody.$S2', nextEmbedded: '$S2' }], + [ + tagCloseWithinEmbedBudget, + { token: 'tag', switchTo: '@scriptBody.$S2', nextEmbedded: '$S2' } + ], + [/>/, { token: 'tag', switchTo: '@scriptBodyPlain.$S2' }], [/lang(?=\s*=)/, { token: 'attribute.name', switchTo: '@scriptLangBeforeEquals.$S2' }], { include: '@tagAttributes' } ], @@ -80,9 +125,24 @@ export const vueMonarchLanguage: Monaco.languages.IMonarchLanguage = { [/\s+/, 'white'] ], scriptBody: [[/<\/script\s*>/, { token: 'tag', next: '@pop', nextEmbedded: '@pop' }]], + // Over-budget mirror of the body: re-enters `$S2` as soon as the rest of + // the line fits, so a long opening line does not grey out the whole block. + scriptBodyPlain: [ + [/<\/script\s*>/, { token: 'tag', next: '@pop' }], + [ + restOfLineWithinEmbedBudget, + { token: '@rematch', switchTo: '@scriptBody.$S2', nextEmbedded: '$S2' } + ], + [/[^<]+/, ''], + [/./, ''] + ], styleOpen: [ [/\/>/, 'tag', '@pop'], - [/>/, { token: 'tag', switchTo: '@styleBody.$S2', nextEmbedded: '$S2' }], + [ + tagCloseWithinEmbedBudget, + { token: 'tag', switchTo: '@styleBody.$S2', nextEmbedded: '$S2' } + ], + [/>/, { token: 'tag', switchTo: '@styleBodyPlain.$S2' }], [/lang(?=\s*=)/, { token: 'attribute.name', switchTo: '@styleLangBeforeEquals.$S2' }], { include: '@tagAttributes' } ], @@ -110,6 +170,15 @@ export const vueMonarchLanguage: Monaco.languages.IMonarchLanguage = { [/\s+/, 'white'] ], styleBody: [[/<\/style\s*>/, { token: 'tag', next: '@pop', nextEmbedded: '@pop' }]], + styleBodyPlain: [ + [/<\/style\s*>/, { token: 'tag', next: '@pop' }], + [ + restOfLineWithinEmbedBudget, + { token: '@rematch', switchTo: '@styleBody.$S2', nextEmbedded: '$S2' } + ], + [/[^<]+/, ''], + [/./, ''] + ], tagAttributes: [ [/[^\s/>=]+/, 'attribute.name'], [/=/, 'delimiter'], diff --git a/src/renderer/src/lib/path-head-elision.test.ts b/src/renderer/src/lib/path-head-elision.test.ts new file mode 100644 index 00000000000..3fd110dd27e --- /dev/null +++ b/src/renderer/src/lib/path-head-elision.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it } from 'vitest' +import { splitPathHeadForElision } from './path-head-elision' + +describe('splitPathHeadForElision', () => { + it('keeps the last two segments as the tail', () => { + expect(splitPathHeadForElision('/Users/me/projects/orca/proposals/create-button.html')).toEqual( + { + head: '/Users/me/projects/orca', + tail: '/proposals/create-button.html', + tailRanges: [] + } + ) + }) + + it('supports Windows paths without changing their separators', () => { + const path = 'C:\\Users\\me\\projects\\orca\\src\\renderer\\app.ts' + const start = path.indexOf('src') + + expect(splitPathHeadForElision(path, [{ start, end: start + 3 }])).toEqual({ + head: 'C:\\Users\\me\\projects\\orca', + tail: '\\src\\renderer\\app.ts', + tailRanges: [{ start: 1, end: 4 }] + }) + }) + + it('keeps backslashes inside POSIX segment names', () => { + expect(splitPathHeadForElision('/tmp/project/src/name\\with\\slashes.ts')).toEqual({ + head: '/tmp/project', + tail: '/src/name\\with\\slashes.ts', + tailRanges: [] + }) + }) + + it('leaves short or shallow paths whole', () => { + expect(splitPathHeadForElision('src/app.ts')).toBeNull() + expect(splitPathHeadForElision('a/b/c')).toBeNull() + expect(splitPathHeadForElision('/tmp/orca-create-button/create-button.html')).toEqual({ + head: '/tmp', + tail: '/orca-create-button/create-button.html', + tailRanges: [] + }) + }) + + it('extends the tail back to the first matched segment and re-bases ranges', () => { + const path = '/Users/me/projects/orca/new-create-button-design/proposals/create-button.html' + const start = path.indexOf('create-butt') + const split = splitPathHeadForElision(path, [{ start, end: start + 'create-butt'.length }]) + expect(split).toEqual({ + head: '/Users/me/projects/orca', + tail: '/new-create-button-design/proposals/create-button.html', + tailRanges: [{ start: 5, end: 16 }] + }) + }) + + it('pulls a segment the match starts in fully into the tail', () => { + const path = '/Users/me/projects/orca/deep/nested/file.ts' + const split = splitPathHeadForElision(path, [{ start: 20, end: 30 }]) + expect(split?.head).toBe('/Users/me/projects') + expect(split?.tail).toBe('/orca/deep/nested/file.ts') + expect(split?.tailRanges).toEqual([{ start: 2, end: 12 }]) + }) + + it('returns null when the match sits in the first segment', () => { + const path = '/Users-long-prefix/me/projects/orca/deep/file.ts' + expect(splitPathHeadForElision(path, [{ start: 1, end: 6 }])).toBeNull() + }) +}) diff --git a/src/renderer/src/lib/path-head-elision.ts b/src/renderer/src/lib/path-head-elision.ts new file mode 100644 index 00000000000..e21bac240d6 --- /dev/null +++ b/src/renderer/src/lib/path-head-elision.ts @@ -0,0 +1,52 @@ +import type { MatchRange } from './palette-match/normalized-text' +import { isWindowsAbsolutePathLike } from '../../../shared/cross-platform-path' + +export type PathHeadElisionSplit = { + head: string + tail: string + tailRanges: readonly MatchRange[] +} + +const MIN_ELISION_LENGTH = 28 +const MIN_SEGMENTS = 4 +const TAIL_SEGMENTS = 2 + +export function splitPathHeadForElision( + path: string, + ranges: readonly MatchRange[] = [] +): PathHeadElisionSplit | null { + if (path.length <= MIN_ELISION_LENGTH) { + return null + } + const windowsPath = isWindowsAbsolutePathLike(path) + const separators: number[] = [] + for (let index = 0; index < path.length; index += 1) { + if (path[index] === '/' || (windowsPath && path[index] === '\\')) { + separators.push(index) + } + } + if (separators.length < MIN_SEGMENTS - 1) { + return null + } + let tailStart = separators[separators.length - TAIL_SEGMENTS]! + const firstMatchStart = ranges.reduce( + (earliest, range) => (range.start < range.end ? Math.min(earliest, range.start) : earliest), + Number.POSITIVE_INFINITY + ) + if (firstMatchStart < tailStart) { + const segmentSeparator = separators.findLast((separator) => separator < firstMatchStart) + tailStart = segmentSeparator ?? 0 + } + const head = path.slice(0, tailStart) + if (!(windowsPath ? /[^/\\]/ : /[^/]/).test(head)) { + return null + } + return { + head, + tail: path.slice(tailStart), + tailRanges: ranges.map((range) => ({ + start: range.start - tailStart, + end: range.end - tailStart + })) + } +} diff --git a/src/renderer/src/lib/session-write-subscriber.test.ts b/src/renderer/src/lib/session-write-subscriber.test.ts index 80111781534..9753d8303b7 100644 --- a/src/renderer/src/lib/session-write-subscriber.test.ts +++ b/src/renderer/src/lib/session-write-subscriber.test.ts @@ -389,6 +389,43 @@ describe('createSessionWriteSubscriber', () => { cleanup() }) + it('ignores recovery-ledger-only changes', () => { + // Why: the ledger is stripped from the persisted session, so churning it + // must not rebuild and rewrite the durable payload on every remount. + const persist = vi.fn<(payload: WorkspaceSessionWrite) => void>() + const cleanup = createSessionWriteSubscriber({ store: useAppStore, persist }) + + useAppStore.setState({ + workspaceSessionReady: true, + hydrationSucceeded: true, + ...makeTerminalSessionState('bash') + }) + vi.advanceTimersByTime(200) + persist.mockClear() + + useAppStore.setState({ + tabsByWorktree: { + 'wt-1': [ + { + ...useAppStore.getState().tabsByWorktree['wt-1'][0], + recovery: { + attemptedAt: [1], + generation: 1, + outcome: 'pending', + startedAt: 1, + reason: 'reattach-unverifiable', + tabGeneration: 0 + } + } + ] + } + }) + vi.advanceTimersByTime(200) + + expect(persist).not.toHaveBeenCalled() + cleanup() + }) + it('ignores decorative unified terminal label churn', () => { const persist = vi.fn<(payload: WorkspaceSessionWrite) => void>() const cleanup = createSessionWriteSubscriber({ store: useAppStore, persist }) diff --git a/src/renderer/src/lib/session-write-subscriber.ts b/src/renderer/src/lib/session-write-subscriber.ts index d54675e15ab..685a8e56e3f 100644 --- a/src/renderer/src/lib/session-write-subscriber.ts +++ b/src/renderer/src/lib/session-write-subscriber.ts @@ -14,7 +14,10 @@ type UnifiedTab = UnifiedTabsByWorktree[string][number] const TERMINAL_TAB_LIVE_TITLE_KEYS = new Set(['title']) // Why: this handoff flag is stripped from workspace sessions, so toggling it // alone should not rebuild and rewrite the durable session payload. -const TERMINAL_TAB_TRANSIENT_SESSION_KEYS = new Set(['pendingActivationSpawn']) +const TERMINAL_TAB_TRANSIENT_SESSION_KEYS = new Set([ + 'pendingActivationSpawn', + 'recovery' +]) function terminalTabChangedForSession(prev: TerminalTab, next: TerminalTab): boolean { if (prev === next) { diff --git a/src/renderer/src/lib/web-runtime-worktree-terminal-after-wake.ts b/src/renderer/src/lib/web-runtime-worktree-terminal-after-wake.ts index bf1664dc57c..bb3cf9f26a8 100644 --- a/src/renderer/src/lib/web-runtime-worktree-terminal-after-wake.ts +++ b/src/renderer/src/lib/web-runtime-worktree-terminal-after-wake.ts @@ -11,50 +11,114 @@ import { endWebRuntimeWakeTerminalRespawn } from '@/runtime/web-runtime-wake-terminal-respawn' import { getRuntimeEnvironmentIdForWorktree } from '@/lib/worktree-runtime-owner' +import { + draftViewModeProps, + resolveStartupLaunchDraftText, + type WorktreeStartupPayload +} from '@/lib/worktree-startup-payload' +import type { TuiAgent } from '../../../shared/tui-agent' +import { initialAgentTabViewModeProps } from '@/lib/native-chat-initial-view-mode' +import { isNativeChatTranscriptLocalReadable } from '@/lib/native-chat-transcript-readability' +import { getConnectionId } from '@/lib/connection-context' +import { toast } from 'sonner' -export function ensureWebRuntimeWorktreeTerminalAfterWake(worktreeId: string): void { - const state = useAppStore.getState() - const worktree = state.getKnownWorktreeById(worktreeId) - if (!worktree) { - return +export function ensureWebRuntimeWorktreeTerminalAfterWake( + worktreeId: string, + opts?: { + runtimeEnvironmentId?: string | null + startup?: WorktreeStartupPayload + agent?: TuiAgent | null + activate?: boolean } - const runtimeEnvironmentId = getRuntimeEnvironmentIdForWorktree(state, worktree.id) +): void { + const state = useAppStore.getState() + const runtimeEnvironmentId = + opts && 'runtimeEnvironmentId' in opts + ? (opts.runtimeEnvironmentId ?? null) + : getRuntimeEnvironmentIdForWorktree(state, worktreeId) if (!runtimeEnvironmentId || !isWebRuntimeSessionActive(runtimeEnvironmentId)) { return } const tabs = state.tabsByWorktree[worktreeId] ?? [] - const hasLivePty = tabs.some((tab) => tabHasLivePty(state.ptyIdsByTabId, tab.id)) - if (hasLivePty) { + const launchAgent = opts?.startup?.launchAgent ?? opts?.agent ?? undefined + if ( + launchAgent && + tabs.some( + (tab) => + tab.launchAgent === launchAgent && + (isWebTerminalSurfaceTabId(tab.id) || tabHasLivePty(state.ptyIdsByTabId, tab.id)) + ) + ) { return } - const hasMirroredHostTabs = tabs.some((tab) => isWebTerminalSurfaceTabId(tab.id)) - if (hasMirroredHostTabs) { - // Why: the host session still owns these tabs — wait for the mirror to repopulate PTY handles instead of duplicating a terminal. - return - } + if (!launchAgent) { + const hasLivePty = tabs.some((tab) => tabHasLivePty(state.ptyIdsByTabId, tab.id)) + if (hasLivePty) { + return + } - if (getLastKnownHostTerminalTabCount(runtimeEnvironmentId, worktreeId) > 0) { - return - } + const hasMirroredHostTabs = tabs.some((tab) => isWebTerminalSurfaceTabId(tab.id)) + if (hasMirroredHostTabs) { + // Why: the host session still owns these tabs — wait for the mirror to repopulate PTY handles instead of duplicating a terminal. + return + } - const { renderableTabCount } = state.reconcileWorktreeTabModel(worktreeId) - if (tabs.length > 0 && renderableTabCount === 0) { - return + if (getLastKnownHostTerminalTabCount(runtimeEnvironmentId, worktreeId) > 0) { + return + } + + const { renderableTabCount } = state.reconcileWorktreeTabModel(worktreeId) + if (tabs.length > 0 && renderableTabCount === 0) { + return + } } if (!beginWebRuntimeWakeTerminalRespawn(worktreeId)) { return } - // Why: sleep keeps tab rows but terminal.stop clears host PTYs, so a woke workspace can have tab chrome but no surface. + const startup = opts?.startup + const viewModeProps = launchAgent + ? initialAgentTabViewModeProps(state.settings, { + agent: launchAgent, + ...draftViewModeProps(resolveStartupLaunchDraftText(startup)), + nativeChatTranscriptIsLocalReadable: isNativeChatTranscriptLocalReadable( + getConnectionId(worktreeId) + ) + }) + : {} + // Why: sleep keeps tab rows but terminal.stop clears host PTYs, while a failed create receipt leaves a selected agent with no host surface. void createWebRuntimeSessionTerminal({ worktreeId, environmentId: runtimeEnvironmentId, - activate: true, + ...viewModeProps, + ...(startup + ? { + command: startup.command, + ...(startup.env ? { env: startup.env } : {}), + ...(startup.launchConfig ? { launchConfig: startup.launchConfig } : {}), + ...(startup.launchToken ? { launchToken: startup.launchToken } : {}), + ...(launchAgent ? { launchAgent, preparedAgentCommand: true } : {}), + ...(startup.startupCommandDelivery + ? { startupCommandDelivery: startup.startupCommandDelivery } + : {}) + } + : launchAgent + ? { agent: launchAgent } + : {}), + activate: opts?.activate !== false, selectWorktree: false - }).finally(() => { - endWebRuntimeWakeTerminalRespawn(worktreeId) }) + .then((outcome) => { + if (outcome.status === 'failed') { + toast.error(outcome.message, { + id: `web-runtime-worktree-terminal:${runtimeEnvironmentId}:${worktreeId}` + }) + } + }) + .finally(() => { + endWebRuntimeWakeTerminalRespawn(worktreeId) + }) } diff --git a/src/renderer/src/lib/workspace-session-patch.test.ts b/src/renderer/src/lib/workspace-session-patch.test.ts index 2f604fb67bb..d2084d6fd03 100644 --- a/src/renderer/src/lib/workspace-session-patch.test.ts +++ b/src/renderer/src/lib/workspace-session-patch.test.ts @@ -182,7 +182,15 @@ describe('buildWorkspaceSessionPatch', () => { title: 'shell', ptyId: 'pty-1', worktreeId: localWorktreeId, - pendingActivationSpawn: true + pendingActivationSpawn: true, + recovery: { + attemptedAt: [1], + generation: 1, + outcome: 'pending', + startedAt: 1, + reason: 'reattach-unverifiable', + tabGeneration: 1 + } } as never ] }, @@ -217,6 +225,9 @@ describe('buildWorkspaceSessionPatch', () => { ].sort() ) expect('pendingActivationSpawn' in patch.tabsByWorktree![localWorktreeId][0]).toBe(false) + // Why: the recovery ledger describes a mounted pane's in-flight heal; a + // persisted one would refuse the first legitimate recovery after restart. + expect('recovery' in patch.tabsByWorktree![localWorktreeId][0]).toBe(false) expect(patch.terminalLayoutsByTabId?.['tab-local'].buffersByLeafId).toBeUndefined() expect(patch.terminalLayoutsByTabId?.['tab-local'].scrollbackRefsByLeafId).toBeUndefined() }) diff --git a/src/renderer/src/lib/workspace-session.ts b/src/renderer/src/lib/workspace-session.ts index 330a150b636..affa2b36ca4 100644 --- a/src/renderer/src/lib/workspace-session.ts +++ b/src/renderer/src/lib/workspace-session.ts @@ -204,12 +204,14 @@ export function buildSanitizedTabsByWorktree( tabsByWorktree: WorkspaceSessionSnapshot['tabsByWorktree'] ): WorkspaceSessionState['tabsByWorktree'] { // Why: strip transient pendingActivationSpawn — session:set persists without Zod re-parse, so a stale flag would drop the first PTY spawn on restart. + // Same for the recovery ledger: it describes a mounted pane's in-flight heal, so a persisted one would refuse the first recovery after restart. return Object.fromEntries( Object.entries(tabsByWorktree).map(([worktreeId, tabs]) => [ worktreeId, tabs.map((tab) => { - const { pendingActivationSpawn: _unused, ...rest } = tab + const { pendingActivationSpawn: _unused, recovery: _recovery, ...rest } = tab void _unused + void _recovery return rest }) ]) diff --git a/src/renderer/src/lib/worktree-activation-emptied-workspace-reseed.test.ts b/src/renderer/src/lib/worktree-activation-emptied-workspace-reseed.test.ts index f9ebf55b0d2..ea4f3119bbc 100644 --- a/src/renderer/src/lib/worktree-activation-emptied-workspace-reseed.test.ts +++ b/src/renderer/src/lib/worktree-activation-emptied-workspace-reseed.test.ts @@ -32,6 +32,23 @@ function seedClosedLastTerminal(worktreeId: string): void { } describe('activating a workspace whose last terminal was closed', () => { + it.each([ + ['Blank Terminal', null, 1], + ['an agent', 'codex' as const, 0] + ])('seeds a default shell for %s selection only', (_label, agent, expectedTabCount) => { + const worktree = makeWorktree() + seedEmptyActivatableWorktree(worktree) + + const result = activateAndRevealWorktree(worktree.id, { + agent, + notifyHostRuntime: false + }) + + expect(result).not.toBe(false) + expect(result === false ? null : result.primaryTabId === null).toBe(expectedTabCount === 0) + expect(useAppStore.getState().tabsByWorktree[worktree.id] ?? []).toHaveLength(expectedTabCount) + }) + it.each([true, false])( 'forwards providesInitialSurface=%s through the async activation gate', async (providesInitialSurface) => { @@ -234,6 +251,22 @@ function seedEmptiedFolderWorkspaceOnTwoHosts(): void { } describe('activating a folder workspace whose last terminal was closed', () => { + it.each([ + ['Blank Terminal', null, 1], + ['an agent', 'codex' as const, 0] + ])('seeds a default shell for %s selection only', (_label, agent, expectedTabCount) => { + seedEmptiedFolderWorkspaceOnTwoHosts() + + const result = activateAndRevealFolderWorkspace(FOLDER_ID, { + agent, + executionHostId: 'local' + }) + + expect(result).not.toBe(false) + expect(useAppStore.getState().activeWorktreeId).toBe(FOLDER_KEY) + expect(useAppStore.getState().tabsByWorktree[FOLDER_KEY]).toHaveLength(expectedTabCount) + }) + it.each([true, false])( 'forwards providesInitialSurface=%s through the async activation gate', async (providesInitialSurface) => { diff --git a/src/renderer/src/lib/worktree-activation-empty-remote.test.ts b/src/renderer/src/lib/worktree-activation-empty-remote.test.ts index 9326be93960..c16a8d6a448 100644 --- a/src/renderer/src/lib/worktree-activation-empty-remote.test.ts +++ b/src/renderer/src/lib/worktree-activation-empty-remote.test.ts @@ -6,6 +6,9 @@ import { resetWebRuntimeWakeTerminalRespawnForTests } from '@/runtime/web-runtim import { resetWebSessionTabsSnapshotFreshnessForTests } from '@/runtime/web-session-tabs-sync' import { useAppStore } from '@/store' import { ensureWebRuntimeWorktreeTerminalAfterWake } from './web-runtime-worktree-terminal-after-wake' +import { toast } from 'sonner' + +vi.mock('sonner', () => ({ toast: { error: vi.fn() } })) const initialAppStoreState = useAppStore.getState() const WORKTREE_PATH = path.join('workspace', 'feature') @@ -13,6 +16,7 @@ const REPO_PATH = path.join('workspace', 'repo') const ORCA_WORKSPACES_PATH = path.join('workspace', '.orca-workspaces') afterEach(() => { + vi.clearAllMocks() delete (globalThis as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__ vi.unstubAllGlobals() resetWebSessionTabsSnapshotFreshnessForTests() @@ -115,5 +119,55 @@ describe('empty remote worktree activation', () => { }) }) ) + expect(toast.error).not.toHaveBeenCalled() + }) + + it('surfaces a failed host terminal request without retrying ambiguously', async () => { + const worktree = makeWorktree() + const callRuntimeEnvironment = vi.fn().mockResolvedValueOnce({ + ok: false, + error: { code: 'terminal_create_failed', message: 'Host refused the terminal' } + }) + ;(globalThis as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__ = true + vi.stubGlobal('window', { + api: { + runtimeEnvironments: { + call: callRuntimeEnvironment, + subscribe: vi.fn() + } + } + }) + + useAppStore.setState({ + repos: [ + { + id: 'repo-1', + path: REPO_PATH, + displayName: 'repo', + badgeColor: '#000000', + addedAt: 0 + } + ], + worktreesByRepo: { 'repo-1': [worktree] }, + tabsByWorktree: {}, + ptyIdsByTabId: {}, + settings: { + ...getDefaultSettings(ORCA_WORKSPACES_PATH), + activeRuntimeEnvironmentId: 'web-runtime-1' + }, + reconcileWorktreeTabModel: vi.fn(() => ({ + renderableTabCount: 0, + activeRenderableTabId: null + })) + }) + + ensureWebRuntimeWorktreeTerminalAfterWake(worktree.id) + + await vi.waitFor(() => + expect(toast.error).toHaveBeenCalledWith('Host refused the terminal', { + id: `web-runtime-worktree-terminal:web-runtime-1:${worktree.id}` + }) + ) + expect(callRuntimeEnvironment).toHaveBeenCalledTimes(1) }) }) diff --git a/src/renderer/src/lib/worktree-activation-surface-caller-wiring.test.ts b/src/renderer/src/lib/worktree-activation-surface-caller-wiring.test.ts index ff2d5c802c1..4e7e02336ca 100644 --- a/src/renderer/src/lib/worktree-activation-surface-caller-wiring.test.ts +++ b/src/renderer/src/lib/worktree-activation-surface-caller-wiring.test.ts @@ -23,7 +23,10 @@ const SURFACE_PROVIDING_CALLERS = [ ] // The activation seam itself: declares the option and forwards it into the tombstone gate. -const SEAM_FILES = ['src/renderer/src/lib/worktree-activation.ts'] +const SEAM_FILES = [ + 'src/renderer/src/lib/worktree-activation-surface-selection.ts', + 'src/renderer/src/lib/worktree-activation.ts' +] function listSourceFiles(dir: string): string[] { return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { diff --git a/src/renderer/src/lib/worktree-activation-surface-selection.ts b/src/renderer/src/lib/worktree-activation-surface-selection.ts new file mode 100644 index 00000000000..ef4b5c1386a --- /dev/null +++ b/src/renderer/src/lib/worktree-activation-surface-selection.ts @@ -0,0 +1,39 @@ +import type { TuiAgent } from '../../../shared/tui-agent' +import type { + WorktreeDefaultTabsLaunch, + WorktreeSetupLaunch +} from '../../../shared/worktree/launch-types' +import type { ExecutionHostId } from '../../../shared/execution-host' +import type { PendingSidebarWorktreeReveal } from '@/store/slices/ui' +import type { WorktreeStartupPayload } from '@/lib/worktree-startup-payload' +import type { IssueCommandLaunch } from '@/lib/worktree-setup-issue-command-queue' + +export type WorktreeActivationSurfaceSelection = { + /** The create picker's selection; null means Blank Terminal. */ + agent?: TuiAgent | null + /** A navigation caller is about to open its own editor, diff, or other non-terminal surface. */ + providesInitialSurface?: boolean +} + +export type WorktreeActivationOptions = WorktreeActivationSurfaceSelection & { + startup?: WorktreeStartupPayload + initialCwd?: string + setup?: WorktreeSetupLaunch + defaultTabs?: WorktreeDefaultTabsLaunch + issueCommand?: IssueCommandLaunch + sidebarRevealBehavior?: PendingSidebarWorktreeReveal['behavior'] + notifyHostRuntime?: boolean + revealInSidebar?: boolean + executionHostId?: ExecutionHostId + backendStartupTerminalSpawned?: boolean + /** Install a preserved fallback startup beside setup/default terminals already seeded. */ + createNewTerminalForStartup?: boolean + /** Keep sidebar filters intact when navigating to a hidden target. */ + clearSidebarFilters?: boolean +} + +export function activationProvidesInitialSurface( + selection?: WorktreeActivationSurfaceSelection +): boolean { + return selection?.providesInitialSurface === true || selection?.agent != null +} diff --git a/src/renderer/src/lib/worktree-activation-web-runtime.test.ts b/src/renderer/src/lib/worktree-activation-web-runtime.test.ts index 98a7679ae6d..2daee618eba 100644 --- a/src/renderer/src/lib/worktree-activation-web-runtime.test.ts +++ b/src/renderer/src/lib/worktree-activation-web-runtime.test.ts @@ -1,4 +1,5 @@ -import { describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { activateAndRevealFolderWorkspace, activateAndRevealWorktree } from './worktree-activation' import { ensureWorktreeHasInitialTerminal } from './worktree-initial-terminal-seeding' import type { AppStoreState } from './worktree-activation-test-harness' import { @@ -6,9 +7,228 @@ import { registerWorktreeActivationReset } from './worktree-activation-test-harness' import { useAppStore } from '@/store' +import { + makeCreatedAgentWorktree, + seedEmptyActivatableWorktree +} from './worktree-activation-created-agent-test-state' +import { + resetWebRuntimeWakeTerminalRespawnForTests, + shouldSkipWebRuntimeWakeTerminalRespawn +} from '@/runtime/web-runtime-wake-terminal-respawn' registerWorktreeActivationReset() +afterEach(() => { + vi.unstubAllGlobals() + resetWebRuntimeWakeTerminalRespawnForTests() +}) + +describe('activateAndRevealWorktree', () => { + it('asks the paired host for the prepared agent terminal when backend startup did not spawn', async () => { + const worktree = { + ...makeCreatedAgentWorktree(), + hostId: 'local' as const, + runtimeOwnerEnvironmentId: 'web-runtime-1' + } + const callRuntimeEnvironment = vi.fn( + async (request: { method: string; params?: Record }) => + request.method === 'session.tabs.createTerminal' + ? { + ok: true, + result: { + tab: { id: 'host-agent-tab', leafId: 'host-agent-leaf' }, + publicationEpoch: 'epoch-1', + snapshotVersion: 1 + } + } + : { ok: false, error: { code: 'test', message: 'stop after recording the request' } } + ) + ;(globalThis as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__ = true + vi.stubGlobal('window', { + api: { runtimeEnvironments: { call: callRuntimeEnvironment } } + }) + seedEmptyActivatableWorktree(worktree) + const settings = useAppStore.getState().settings + useAppStore.setState({ + settings: settings + ? { ...settings, activeRuntimeEnvironmentId: 'web-runtime-1' } + : ({ activeRuntimeEnvironmentId: 'web-runtime-1' } as unknown as typeof settings) + }) + useAppStore.setState({ + tabsByWorktree: { + [worktree.id]: [ + { + id: 'stale-local-agent-tab', + ptyId: 'stale-local-agent-pty', + worktreeId: worktree.id, + title: 'Codex', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1, + launchAgent: 'codex' + } + ] + } + }) + + activateAndRevealWorktree(worktree.id, { + agent: 'codex', + startup: { + command: "codex 'fix the ownership race'", + env: { ORCA_AGENT_PROFILE: 'review' }, + launchAgent: 'codex', + launchToken: 'launch-1' + } + }) + await vi.waitFor(() => + expect(callRuntimeEnvironment).toHaveBeenCalledWith( + expect.objectContaining({ method: 'worktree.activate' }) + ) + ) + + const createRequests = callRuntimeEnvironment.mock.calls.filter( + ([request]) => request.method === 'session.tabs.createTerminal' + ) + expect(createRequests).toHaveLength(1) + expect(createRequests[0]?.[0]).toEqual( + expect.objectContaining({ + params: expect.objectContaining({ + command: "codex 'fix the ownership race'", + env: { ORCA_AGENT_PROFILE: 'review' }, + launchAgent: 'codex', + launchToken: 'launch-1' + }) + }) + ) + await vi.waitFor(() => expect(shouldSkipWebRuntimeWakeTerminalRespawn(worktree.id)).toBe(false)) + }) + + it('does not request another host terminal when backend startup already spawned', async () => { + const worktree = { + ...makeCreatedAgentWorktree(), + hostId: 'local' as const, + runtimeOwnerEnvironmentId: 'web-runtime-1' + } + const callRuntimeEnvironment = vi.fn().mockResolvedValue({ + ok: false, + error: { code: 'test', message: 'stop after recording the request' } + }) + ;(globalThis as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__ = true + vi.stubGlobal('window', { + api: { runtimeEnvironments: { call: callRuntimeEnvironment } } + }) + seedEmptyActivatableWorktree(worktree) + useAppStore.setState((state) => ({ + settings: state.settings + ? { ...state.settings, activeRuntimeEnvironmentId: 'web-runtime-1' } + : ({ activeRuntimeEnvironmentId: 'web-runtime-1' } as unknown as typeof state.settings) + })) + + activateAndRevealWorktree(worktree.id, { + agent: 'codex', + backendStartupTerminalSpawned: true + }) + await vi.waitFor(() => + expect(callRuntimeEnvironment).toHaveBeenCalledWith( + expect.objectContaining({ method: 'worktree.activate' }) + ) + ) + + expect( + callRuntimeEnvironment.mock.calls.filter( + ([request]) => request.method === 'session.tabs.createTerminal' + ) + ).toHaveLength(0) + }) +}) + +describe('activateAndRevealFolderWorkspace', () => { + it.each([ + [ + 'the selected agent', + { + agent: 'codex' as const, + startup: { command: 'codex', launchAgent: 'codex' as const, launchToken: 'launch-1' } + }, + { command: 'codex', launchAgent: 'codex', launchToken: 'launch-1' } + ], + ['Blank Terminal', { agent: null }, { command: undefined }] + ])('asks the runtime owner for exactly one %s surface', async (_label, activation, expected) => { + const callRuntimeEnvironment = vi.fn( + async (request: { method: string; params?: Record }) => + request.method === 'session.tabs.createTerminal' + ? { + ok: true, + result: { + tab: { id: 'host-tab', leafId: 'host-leaf' }, + publicationEpoch: 'epoch-1', + snapshotVersion: 1 + } + } + : { ok: false, error: { code: 'test', message: 'stop after recording the request' } } + ) + ;(globalThis as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__ = true + vi.stubGlobal('window', { + api: { runtimeEnvironments: { call: callRuntimeEnvironment } } + }) + const settings = useAppStore.getState().settings + useAppStore.setState({ + activeView: 'terminal', + folderWorkspaces: [ + { + id: 'folder-1', + projectGroupId: 'group-1', + name: 'runtime folder', + folderPath: '/workspace/runtime-folder', + linkedTask: null, + comment: '', + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + executionHostId: 'runtime:web-runtime-1' + } + ], + getFreshFolderWorkspacePathStatus: vi.fn(() => ({ exists: true })), + tabsByWorktree: {}, + settings: settings + ? { ...settings, activeRuntimeEnvironmentId: 'web-runtime-1' } + : ({ activeRuntimeEnvironmentId: 'web-runtime-1' } as unknown as typeof settings), + markWorktreeVisited: vi.fn(), + recordWorktreeVisit: vi.fn(), + revealWorktreeInSidebar: vi.fn() + } as unknown as Partial) + + activateAndRevealFolderWorkspace('folder-1', { + ...activation, + runtimeEnvironmentId: 'web-runtime-1' + }) + + await vi.waitFor(() => + expect( + callRuntimeEnvironment.mock.calls.filter( + ([request]) => request.method === 'session.tabs.createTerminal' + ) + ).toHaveLength(1) + ) + const createRequest = callRuntimeEnvironment.mock.calls.find( + ([request]) => request.method === 'session.tabs.createTerminal' + )?.[0] + expect(createRequest).toEqual( + expect.objectContaining({ + params: expect.objectContaining(expected) + }) + ) + if (activation.agent === null) { + expect(createRequest?.params).not.toHaveProperty('launchAgent') + } + await vi.waitFor(() => + expect(shouldSkipWebRuntimeWakeTerminalRespawn('folder:folder-1')).toBe(false) + ) + }) +}) + describe('ensureWorktreeHasInitialTerminal', () => { it('does not create a local fallback tab in the paired web runtime client', () => { ;(globalThis as { __ORCA_WEB_CLIENT__?: boolean }).__ORCA_WEB_CLIENT__ = true diff --git a/src/renderer/src/lib/worktree-activation.ts b/src/renderer/src/lib/worktree-activation.ts index d2304c28b9d..a77a16682c8 100644 --- a/src/renderer/src/lib/worktree-activation.ts +++ b/src/renderer/src/lib/worktree-activation.ts @@ -1,8 +1,4 @@ import type { FolderWorkspace } from '../../../shared/folder-workspace-types' -import type { - WorktreeDefaultTabsLaunch, - WorktreeSetupLaunch -} from '../../../shared/worktree/launch-types' import { translate } from '@/i18n/i18n' import { useAppStore } from '@/store' import type { PendingSidebarWorktreeReveal } from '@/store/slices/ui' @@ -29,13 +25,17 @@ import { isDetachedHeadWorkspace } from '@/components/sidebar/visible-worktrees' import type { ExecutionHostId } from '../../../shared/execution-host' import { findFolderWorkspaceOwner } from './folder-workspace-runtime-owner' import type { WorktreeStartupPayload } from '@/lib/worktree-startup-payload' -import type { IssueCommandLaunch } from '@/lib/worktree-setup-issue-command-queue' import { ensureWorktreeHasInitialTerminal, reseedGatedEmptyWorkspace } from '@/lib/worktree-initial-terminal-seeding' import { ensureWebRuntimeWorktreeTerminalAfterWake } from '@/lib/web-runtime-worktree-terminal-after-wake' import { applyWorktreeNavViewEntry } from '@/lib/worktree-nav-view-history-replay' +import { + activationProvidesInitialSurface, + type WorktreeActivationOptions, + type WorktreeActivationSurfaceSelection +} from './worktree-activation-surface-selection' /** * Shared activation sequence used by the worktree palette and add-repo/worktree dialogs. @@ -80,14 +80,12 @@ function canInspectAgentActivationInventory(): boolean { export function activateAndRevealFolderWorkspace( folderWorkspaceId: string, - opts?: { + opts?: WorktreeActivationSurfaceSelection & { sidebarRevealBehavior?: PendingSidebarWorktreeReveal['behavior'] revealInSidebar?: boolean startup?: WorktreeStartupPayload runtimeEnvironmentId?: string | null executionHostId?: ExecutionHostId - /** See activateAndRevealWorktree — same contract for folder workspaces. */ - providesInitialSurface?: boolean } ): ActivateAndRevealResult | false { const state = useAppStore.getState() @@ -133,6 +131,7 @@ export function activateAndRevealFolderWorkspace( state.setActiveFolderWorkspace(folderWorkspaceId, opts?.executionHostId) const workspaceKey = folderWorkspaceKey(folderWorkspaceId) + const providesInitialSurface = activationProvidesInitialSurface(opts) state.markWorktreeVisited(workspaceKey) if (!state.isNavigatingHistory) { state.recordWorktreeVisit(workspaceKey) @@ -151,17 +150,13 @@ export function activateAndRevealFolderWorkspace( if (shouldGateAgentActivation) { void gateWorktreeAgentActivation(workspaceKey).then((outcome) => { if (outcome === 'empty') { - reseedGatedEmptyWorkspace(workspaceKey, opts?.providesInitialSurface) + reseedGatedEmptyWorkspace(workspaceKey, providesInitialSurface) } }) } const primaryTabId = shouldGateAgentActivation ? null - : ensureFolderWorkspaceInitialTerminal( - folderWorkspace, - opts?.startup, - opts?.providesInitialSurface - ) + : ensureFolderWorkspaceInitialTerminal(folderWorkspace, opts?.startup, providesInitialSurface) if (opts?.revealInSidebar !== false) { state.revealWorktreeInSidebar( @@ -170,33 +165,20 @@ export function activateAndRevealFolderWorkspace( ) } + if (opts?.providesInitialSurface !== true) { + ensureWebRuntimeWorktreeTerminalAfterWake(workspaceKey, { + runtimeEnvironmentId, + startup: opts?.startup, + agent: opts?.agent + }) + } + return { primaryTabId } } export function activateAndRevealWorktree( worktreeId: string, - opts?: { - startup?: WorktreeStartupPayload - initialCwd?: string - setup?: WorktreeSetupLaunch - defaultTabs?: WorktreeDefaultTabsLaunch - issueCommand?: IssueCommandLaunch - sidebarRevealBehavior?: PendingSidebarWorktreeReveal['behavior'] - notifyHostRuntime?: boolean - revealInSidebar?: boolean - executionHostId?: ExecutionHostId - backendStartupTerminalSpawned?: boolean - /** Install a preserved fallback startup beside setup/default terminals already seeded. */ - createNewTerminalForStartup?: boolean - /** Set by callers that navigate here only to open their own non-terminal surface - * (an editor file, a diff). Activation then leaves a closed-last-terminal workspace - * empty instead of adding a shell the user never asked for. Caveat: on a - * runtime-owned workspace with a live web session the host owns terminal creation, - * so ensureWebRuntimeWorktreeTerminalAfterWake may still seed one (matches main). */ - providesInitialSurface?: boolean - /** Keep sidebar filters intact when navigating to a hidden target. */ - clearSidebarFilters?: boolean - } + opts?: WorktreeActivationOptions ): ActivateAndRevealResult | false { const state = useAppStore.getState() const wt = state.getKnownWorktreeById(worktreeId, opts?.executionHostId) @@ -206,6 +188,7 @@ export function activateAndRevealWorktree( const hasActivationWork = Boolean( opts?.startup || opts?.setup || opts?.defaultTabs || opts?.issueCommand ) + const providesInitialSurface = activationProvidesInitialSurface(opts) // Why: a plain reselect should still reveal the sidebar row but must not restamp focus recency or wake persistence. const isPlainAlreadyActiveTerminal = !hasActivationWork && @@ -266,7 +249,7 @@ export function activateAndRevealWorktree( if (shouldGateAgentActivation) { void gateWorktreeAgentActivation(worktreeId).then((outcome) => { if (outcome === 'empty') { - reseedGatedEmptyWorkspace(worktreeId, opts?.providesInitialSurface) + reseedGatedEmptyWorkspace(worktreeId, providesInitialSurface) } }) } @@ -274,7 +257,7 @@ export function activateAndRevealWorktree( // 4. Ensure a focusable surface exists for externally-created worktrees const primaryTabId = shouldGateAgentActivation ? null - : opts?.providesInitialSurface === true && !hasActivationWork + : providesInitialSurface && !hasActivationWork ? null : ensureWorktreeHasInitialTerminal( useAppStore.getState(), @@ -286,8 +269,8 @@ export function activateAndRevealWorktree( { ...(opts?.backendStartupTerminalSpawned ? { backendStartupTerminalSpawned: true } : {}), ...(opts?.createNewTerminalForStartup ? { createNewTerminalForStartup: true } : {}), - ...(opts?.providesInitialSurface === true ? { callerProvidesSurface: true } : {}), - reseedEmptiedWorkspace: opts?.providesInitialSurface !== true + ...(providesInitialSurface ? { callerProvidesSurface: true } : {}), + reseedEmptiedWorkspace: !providesInitialSurface } ) if (primaryTabId && opts?.initialCwd) { @@ -325,8 +308,15 @@ export function activateAndRevealWorktree( } } - if (opts?.notifyHostRuntime !== false && !opts?.backendStartupTerminalSpawned) { - ensureWebRuntimeWorktreeTerminalAfterWake(worktreeId) + if ( + opts?.notifyHostRuntime !== false && + !opts?.backendStartupTerminalSpawned && + opts?.providesInitialSurface !== true + ) { + ensureWebRuntimeWorktreeTerminalAfterWake(worktreeId, { + startup: opts?.startup, + agent: opts?.agent + }) } return { primaryTabId } @@ -340,9 +330,8 @@ export function activateAndRevealWorktree( */ export function activateAndRevealWorkspace( workspaceId: string, - opts?: { + opts?: WorktreeActivationSurfaceSelection & { executionHostId?: ExecutionHostId - providesInitialSurface?: boolean revealInSidebar?: boolean /** Worktree-only: folder workspaces are never filter-hidden. */ clearSidebarFilters?: boolean diff --git a/src/renderer/src/lib/worktree-creation-agent-seeding.test.ts b/src/renderer/src/lib/worktree-creation-agent-seeding.test.ts new file mode 100644 index 00000000000..601ad837843 --- /dev/null +++ b/src/renderer/src/lib/worktree-creation-agent-seeding.test.ts @@ -0,0 +1,87 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { WorktreeCreationRequest } from './pending-worktree-creation' + +const mocks = vi.hoisted(() => ({ + activateAndRevealWorktree: vi.fn(), + completeWorktreeCreation: vi.fn(), + ensureWorktreeHasInitialTerminal: vi.fn(), + ensureWebRuntimeWorktreeTerminalAfterWake: vi.fn() +})) + +const store = { + activePendingCreationId: null as string | null, + activeView: 'tasks' as 'tasks' | 'terminal', + createWorktree: vi.fn(), + pendingWorktreeCreations: {} as Record, + repos: [] +} + +vi.mock('@/store', () => ({ useAppStore: { getState: () => store } })) +vi.mock('@/lib/worktree-activation', () => ({ + activateAndRevealWorktree: mocks.activateAndRevealWorktree +})) +vi.mock('@/lib/worktree-initial-terminal-seeding', () => ({ + ensureWorktreeHasInitialTerminal: mocks.ensureWorktreeHasInitialTerminal +})) +vi.mock('@/lib/worktree-creation-completion', () => ({ + completeWorktreeCreation: mocks.completeWorktreeCreation +})) +vi.mock('@/lib/web-runtime-worktree-terminal-after-wake', () => ({ + ensureWebRuntimeWorktreeTerminalAfterWake: mocks.ensureWebRuntimeWorktreeTerminalAfterWake +})) + +import { executeWorktreeCreation } from './worktree-creation-flow-execute' + +const request: WorktreeCreationRequest = { + repoId: 'repo-1', + name: 'feature', + setupDecision: 'inherit', + agent: 'codex', + agentLaunchRoute: 'terminal-tui', + pendingFirstAgentMessageRename: false, + note: '', + startupPlan: null, + quickPrompt: '', + quickTelemetry: null +} + +describe('executeWorktreeCreation agent seeding', () => { + beforeEach(() => { + vi.clearAllMocks() + store.activePendingCreationId = null + store.activeView = 'tasks' + store.pendingWorktreeCreations = { 'creation-1': { creationId: 'creation-1' } } + store.createWorktree.mockResolvedValue({ + worktree: { id: 'worktree-1', repoId: request.repoId } + }) + }) + + it('routes a background agent selection through host-aware surface creation', async () => { + await executeWorktreeCreation('creation-1', request) + + expect(mocks.activateAndRevealWorktree).not.toHaveBeenCalled() + expect(mocks.ensureWorktreeHasInitialTerminal).not.toHaveBeenCalled() + expect(mocks.ensureWebRuntimeWorktreeTerminalAfterWake).toHaveBeenCalledOnce() + expect(mocks.ensureWebRuntimeWorktreeTerminalAfterWake).toHaveBeenCalledWith('worktree-1', { + startup: undefined, + agent: 'codex', + activate: false + }) + expect(mocks.completeWorktreeCreation).toHaveBeenCalledWith( + expect.objectContaining({ primaryTabId: null }) + ) + }) + + it('passes the agent selection through an active reveal', async () => { + store.activePendingCreationId = 'creation-1' + store.activeView = 'terminal' + mocks.activateAndRevealWorktree.mockReturnValue({ primaryTabId: null }) + + await executeWorktreeCreation('creation-1', request) + + expect(mocks.activateAndRevealWorktree).toHaveBeenCalledWith( + 'worktree-1', + expect.objectContaining({ agent: 'codex' }) + ) + }) +}) diff --git a/src/renderer/src/lib/worktree-creation-flow-execute.ts b/src/renderer/src/lib/worktree-creation-flow-execute.ts index 273b3ece1a8..d4409d10549 100644 --- a/src/renderer/src/lib/worktree-creation-flow-execute.ts +++ b/src/renderer/src/lib/worktree-creation-flow-execute.ts @@ -19,9 +19,13 @@ import type { WorktreeCreationRequest } from '@/lib/pending-worktree-creation' import { createBrowserUuid } from '@/lib/browser-uuid' import { resolveBackendDraftStartup } from '@/lib/worktree-draft-startup-view-mode' import { buildWorktreeCreationStartupOpt } from '@/lib/worktree-creation-flow-startup' -import { launchStructuredWorktreeSession } from '@/lib/worktree-creation-structured-session' +import { + launchStructuredWorktreeSession, + type WorktreeCreationStructuredSessionResult +} from '@/lib/worktree-creation-structured-session' import { completeWorktreeCreation } from '@/lib/worktree-creation-completion' import { markStructuredWorktreeLaunchUnconfirmed } from '@/lib/worktree-creation-structured-recovery' +import { ensureWebRuntimeWorktreeTerminalAfterWake } from '@/lib/web-runtime-worktree-terminal-after-wake' // Why: activePendingCreationId can outlive the terminal route when the user // switches app views; only the terminal route renders the creation panel. @@ -163,27 +167,41 @@ export async function executeWorktreeCreation( (completionState.activeView === 'terminal' && completionState.activePendingCreationId === null)) + // Why: the worktree exists past this point and nothing awaits this caller, so + // each follow-up step is best-effort — an escaped throw would strand the + // creation surface over the finished workspace instead of reaching completion. let activation: ActivateAndRevealResult | false = false - let primaryTabId: string | null + let primaryTabId: string | null = null if (shouldActivateOnCompletion && !structuredLaunch) { - activation = activateAndRevealWorktree(worktree.id, { - sidebarRevealBehavior: 'auto', - ...(result.setup ? { setup: result.setup } : {}), - ...(result.defaultTabs ? { defaultTabs: result.defaultTabs } : {}), - ...(startupOpt ? { startup: startupOpt } : {}), - ...(preparedRequest.issueCommand ? { issueCommand: preparedRequest.issueCommand } : {}), - ...(backendSpawned ? { backendStartupTerminalSpawned: true } : {}) - }) - primaryTabId = activation === false ? null : activation.primaryTabId - } else { - // Keep chat creation on its pending surface until the session is ready. - const hasExplicitTerminalWork = Boolean( - startupOpt || result.setup || preparedRequest.issueCommand || result.defaultTabs - ) - primaryTabId = - structuredLaunch && !hasExplicitTerminalWork - ? null - : ensureWorktreeHasInitialTerminal( + try { + activation = activateAndRevealWorktree(worktree.id, { + sidebarRevealBehavior: 'auto', + ...(preparedRequest.agent !== null ? { agent: preparedRequest.agent } : {}), + ...(result.setup ? { setup: result.setup } : {}), + ...(result.defaultTabs ? { defaultTabs: result.defaultTabs } : {}), + ...(startupOpt ? { startup: startupOpt } : {}), + ...(preparedRequest.issueCommand ? { issueCommand: preparedRequest.issueCommand } : {}), + ...(backendSpawned ? { backendStartupTerminalSpawned: true } : {}) + }) + primaryTabId = activation === false ? null : activation.primaryTabId + } catch (error) { + console.error('worktree create: activate-and-reveal failed', worktree.id, error) + // Activation can publish the worktree before a later step throws. Do not + // infer a primary tab from default-tab ordering; only a fresh seed may + // return one here. + const stateAfterActivationFailure = useAppStore.getState() + const existingTabs = stateAfterActivationFailure.tabsByWorktree[worktree.id] ?? [] + const launchAgent = startupOpt?.launchAgent ?? preparedRequest.agent + const verifiedLaunchTabId = + result.startupTerminal?.tabId ?? + (launchAgent ? existingTabs.find((tab) => tab.launchAgent === launchAgent)?.id : undefined) + if (verifiedLaunchTabId) { + // Startup terminal ids and stamped agent tabs are the only safe primary + // ids when activation returned no result. + primaryTabId = verifiedLaunchTabId + } else if (existingTabs.length === 0) { + try { + primaryTabId = ensureWorktreeHasInitialTerminal( useAppStore.getState(), worktree.id, startupOpt, @@ -191,11 +209,68 @@ export async function executeWorktreeCreation( preparedRequest.issueCommand, result.defaultTabs, { - activateCreatedTabs: false, - ...(structuredLaunch ? { callerProvidesSurface: true } : {}), + ...(preparedRequest.agent !== null ? { callerProvidesSurface: true } : {}), ...(backendSpawned ? { backendStartupTerminalSpawned: true } : {}) } ) + } catch (recoveryError) { + console.error( + 'worktree create: activation recovery seeding failed', + worktree.id, + recoveryError + ) + } + } + if (!backendSpawned) { + try { + ensureWebRuntimeWorktreeTerminalAfterWake(worktree.id, { + startup: startupOpt, + agent: preparedRequest.agent + }) + } catch (recoveryError) { + console.error( + 'worktree create: activation recovery after-wake seeding failed', + worktree.id, + recoveryError + ) + } + } + } + } else { + // Keep chat creation on its pending surface until the session is ready. + const hasExplicitTerminalWork = Boolean( + startupOpt || result.setup || preparedRequest.issueCommand || result.defaultTabs + ) + if (preparedRequest.agent === null || hasExplicitTerminalWork) { + try { + primaryTabId = ensureWorktreeHasInitialTerminal( + useAppStore.getState(), + worktree.id, + startupOpt, + result.setup, + preparedRequest.issueCommand, + result.defaultTabs, + { + activateCreatedTabs: false, + ...(preparedRequest.agent !== null ? { callerProvidesSurface: true } : {}), + ...(backendSpawned ? { backendStartupTerminalSpawned: true } : {}) + } + ) + } catch (error) { + console.error('worktree create: initial terminal seeding failed', worktree.id, error) + } + } + if (!structuredLaunch && !backendSpawned) { + try { + ensureWebRuntimeWorktreeTerminalAfterWake(worktree.id, { + startup: startupOpt, + agent: preparedRequest.agent, + activate: false + }) + } catch (error) { + console.error('worktree create: after-wake terminal seeding failed', worktree.id, error) + } + } } let structuredLaunchAccepted = structuredLaunch @@ -204,25 +279,34 @@ export async function executeWorktreeCreation( agentLaunchRoute === 'structured-native-chat' && isAgentSessionHandleProvider(preparedRequest.agent) ) { - const structuredSession = await launchStructuredWorktreeSession({ - creationId, - request: preparedRequest, - agentLaunchRoute, - worktreeId: worktree.id, - shouldActivateOnCompletion, - fallbackStartupOpt, - activation, - primaryTabId - }) - structuredLaunchAccepted = structuredSession.accepted - activation = structuredSession.activation - primaryTabId = structuredSession.primaryTabId - if (structuredSession.cancelled) { - return + let structuredSession: WorktreeCreationStructuredSessionResult | null = null + try { + structuredSession = await launchStructuredWorktreeSession({ + creationId, + request: preparedRequest, + agentLaunchRoute, + worktreeId: worktree.id, + shouldActivateOnCompletion, + fallbackStartupOpt, + activation, + primaryTabId + }) + } catch (error) { + // Why: plan.launch is guarded inside, but its sync prologue is not; treat + // an escaped throw like a failed launch (accepted) and still complete. + console.error('worktree create: structured session launch failed', worktree.id, error) } - if (structuredSession.visibilityUnknown) { - markStructuredWorktreeLaunchUnconfirmed(creationId, worktree.id) - return + if (structuredSession) { + structuredLaunchAccepted = structuredSession.accepted + activation = structuredSession.activation + primaryTabId = structuredSession.primaryTabId + if (structuredSession.cancelled) { + return + } + if (structuredSession.visibilityUnknown) { + markStructuredWorktreeLaunchUnconfirmed(creationId, worktree.id) + return + } } } diff --git a/src/renderer/src/lib/worktree-creation-flow-stranded-surface.test.ts b/src/renderer/src/lib/worktree-creation-flow-stranded-surface.test.ts new file mode 100644 index 00000000000..143645e9008 --- /dev/null +++ b/src/renderer/src/lib/worktree-creation-flow-stranded-surface.test.ts @@ -0,0 +1,377 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { + PendingWorktreeCreation, + WorktreeCreationRequest +} from '@/lib/pending-worktree-creation' +import { shouldShowWorktreeCreationSurface } from '@/lib/worktree-creation-surface' + +// Guards executeWorktreeCreation's post-create tail: callers fire and forget, +// so a throw after createWorktree succeeds must be contained per-step and the +// creation must still reach completeWorktreeCreation, which tears the creation +// surface down. Also covers the caller-side .catch() backstop: a rejection that +// still escapes (e.g. pre-create preparation) becomes a visible error state +// plus toast instead of a panel silently stuck at "creating". + +type TestActiveView = 'terminal' | 'tasks' + +const store = { + settings: { + activeRuntimeEnvironmentId: null as string | null, + experimentalNativeChat: undefined as boolean | undefined, + openAgentTabsInChatByDefault: undefined as boolean | undefined + }, + activeView: 'terminal' as TestActiveView, + activePendingCreationId: 'creation-1' as string | null, + repos: [] as { id: string; connectionId: string | null }[], + pendingWorktreeCreations: {} as Record, + beginPendingWorktreeCreation: vi.fn((entry: PendingWorktreeCreation) => { + store.pendingWorktreeCreations[entry.creationId] = entry + store.activePendingCreationId = entry.creationId + }), + updatePendingWorktreeCreation: vi.fn( + (creationId: string, patch: Partial) => { + const entry = store.pendingWorktreeCreations[creationId] + if (entry) { + store.pendingWorktreeCreations[creationId] = { ...entry, ...patch } + } + } + ), + // Mirrors pending-worktree-creation.ts: drop the entry and the active pointer. + removePendingWorktreeCreation: vi.fn((creationId: string) => { + delete store.pendingWorktreeCreations[creationId] + if (store.activePendingCreationId === creationId) { + store.activePendingCreationId = null + } + }), + setActivePendingWorktreeCreation: vi.fn((creationId: string | null) => { + store.activePendingCreationId = creationId + }), + setActiveView: vi.fn((view: TestActiveView) => { + store.activeView = view + }), + setSidebarOpen: vi.fn(), + updateWorktreeMeta: vi.fn(), + createWorktree: vi.fn(), + tabsByWorktree: {} as Record, + unifiedTabsByWorktree: {} +} + +vi.mock('@/store', () => ({ + useAppStore: { + getState: () => store + } +})) + +vi.mock('sonner', () => ({ + toast: { error: vi.fn() } +})) + +vi.mock('@/lib/worktree-activation', () => ({ + activateAndRevealWorktree: vi.fn() +})) + +vi.mock('@/lib/worktree-initial-terminal-seeding', () => ({ + ensureWorktreeHasInitialTerminal: vi.fn() +})) + +vi.mock('@/lib/web-runtime-worktree-terminal-after-wake', () => ({ + ensureWebRuntimeWorktreeTerminalAfterWake: vi.fn() +})) + +vi.mock('@/lib/workspace-activation-terminal-focus', () => ({ + queueWorkspaceActivationTerminalFocus: vi.fn() +})) + +vi.mock('@/lib/new-workspace', () => ({ + ensureAgentStartupInTerminal: vi.fn() +})) + +vi.mock('@/lib/worktree-creation-agent-seeds', () => ({ + seedAgentTabStateAfterWorktreeCreate: vi.fn() +})) + +vi.mock('@/lib/ephemeral-vm-workspace-target', () => ({ + prepareEphemeralVmWorkspaceTarget: vi.fn() +})) + +vi.mock('@/lib/ephemeral-vm-worktree-creation', () => ({ + prepareRequestForCreate: vi.fn( + async (_creationId: string, request: WorktreeCreationRequest) => request + ), + attachEphemeralVmRuntimeToWorkspace: vi.fn(async () => undefined), + cleanupEphemeralVmRuntimeForFailedCreate: vi.fn(async () => undefined) +})) + +vi.mock('@/lib/worktree-creation-structured-recovery', () => ({ + markStructuredWorktreeLaunchUnconfirmed: vi.fn(), + retryStructuredWorktreeLaunch: vi.fn() +})) + +import { toast } from 'sonner' +import { activateAndRevealWorktree } from '@/lib/worktree-activation' +import { ensureWorktreeHasInitialTerminal } from '@/lib/worktree-initial-terminal-seeding' +import { ensureWebRuntimeWorktreeTerminalAfterWake } from '@/lib/web-runtime-worktree-terminal-after-wake' +import { ensureAgentStartupInTerminal } from '@/lib/new-workspace' +import { prepareRequestForCreate } from '@/lib/ephemeral-vm-worktree-creation' +import { executeWorktreeCreation } from './worktree-creation-flow-execute' +import { runBackgroundWorktreeCreation } from './worktree-creation-flow' + +function makeRequest(overrides: Partial = {}): WorktreeCreationRequest { + return { + repoId: 'repo-1', + name: 'feature', + setupDecision: 'inherit', + agent: null, + pendingFirstAgentMessageRename: false, + note: '', + startupPlan: null, + quickPrompt: '', + quickTelemetry: null, + ...overrides + } as WorktreeCreationRequest +} + +function seedPendingCreation(request: WorktreeCreationRequest): void { + store.pendingWorktreeCreations = { + 'creation-1': { + creationId: 'creation-1', + phase: 'fetching', + status: 'creating', + startedAt: 1, + indeterminate: false, + loaderVisible: true, + request + } + } + store.activePendingCreationId = 'creation-1' +} + +function surfaceInput(activeView: TestActiveView): { + activeView: TestActiveView + activePendingCreationId: string | null + hasActivePendingCreation: boolean +} { + return { + activeView, + activePendingCreationId: store.activePendingCreationId, + hasActivePendingCreation: + store.activePendingCreationId !== null && + store.pendingWorktreeCreations[store.activePendingCreationId] !== undefined + } +} + +beforeEach(() => { + // resetAllMocks: implementations from prior tests (the injected throws) must not leak. + vi.resetAllMocks() + vi.spyOn(console, 'error').mockImplementation(() => undefined) + store.activeView = 'terminal' + store.repos = [{ id: 'repo-1', connectionId: null }] + store.tabsByWorktree = {} + store.pendingWorktreeCreations = {} + store.activePendingCreationId = null + store.createWorktree.mockResolvedValue({ + worktree: { id: 'wt-1', repoId: 'repo-1' } + }) +}) + +describe('a throw after createWorktree succeeds no longer strands the creation surface', () => { + it('activating branch: a throw in activateAndRevealWorktree recovers a terminal and completes', async () => { + const request = makeRequest() + seedPendingCreation(request) + vi.mocked(ensureWorktreeHasInitialTerminal).mockReturnValue('recovered-tab') + vi.mocked(activateAndRevealWorktree).mockImplementation(() => { + throw new Error('activation exploded') + }) + + await executeWorktreeCreation('creation-1', request) + + expect(console.error).toHaveBeenCalledWith( + 'worktree create: activate-and-reveal failed', + 'wt-1', + expect.any(Error) + ) + expect(ensureWorktreeHasInitialTerminal).toHaveBeenCalledWith( + store, + 'wt-1', + undefined, + undefined, + undefined, + undefined, + {} + ) + // Contained: completion still tears the surface down. + expect(store.removePendingWorktreeCreation).toHaveBeenCalledWith('creation-1', { + cleanupVm: false + }) + expect(store.pendingWorktreeCreations['creation-1']).toBeUndefined() + expect(store.activePendingCreationId).toBeNull() + expect(shouldShowWorktreeCreationSurface(surfaceInput('terminal'))).toBe(false) + }) + + it('activating branch: leaves existing default tabs untouched after a partial failure', async () => { + const request = makeRequest({ issueCommand: { command: 'echo setup' } }) + seedPendingCreation(request) + store.tabsByWorktree = { 'wt-1': [{ id: 'existing-tab' }] } + vi.mocked(activateAndRevealWorktree).mockImplementation(() => { + throw new Error('reveal exploded after tab creation') + }) + + await executeWorktreeCreation('creation-1', request) + + expect(ensureWorktreeHasInitialTerminal).not.toHaveBeenCalled() + expect(store.removePendingWorktreeCreation).toHaveBeenCalledWith('creation-1', { + cleanupVm: false + }) + }) + + it('activating branch: routes draft and follow-up delivery to the stamped agent tab', async () => { + const request = makeRequest({ + agent: 'codex', + startupPlan: { + agent: 'codex', + launchCommand: 'codex', + expectedProcess: 'codex', + draftPrompt: 'draft context', + followupPrompt: 'follow-up context', + launchConfig: { agentArgs: '', agentEnv: {} } + } + }) + seedPendingCreation(request) + store.tabsByWorktree = { + 'wt-1': [{ id: 'default-tab' }, { id: 'agent-tab', launchAgent: 'codex' }] + } + vi.mocked(activateAndRevealWorktree).mockImplementation(() => { + throw new Error('reveal exploded after default tabs were created') + }) + + await executeWorktreeCreation('creation-1', request) + + expect(ensureWorktreeHasInitialTerminal).not.toHaveBeenCalled() + expect(ensureAgentStartupInTerminal).toHaveBeenCalledWith( + expect.objectContaining({ primaryTabId: 'agent-tab' }) + ) + }) + + it('background branch: a throw in after-wake seeding is contained after tabs are seeded', async () => { + // User left the terminal view mid-create, so the non-activating branch runs. + store.activeView = 'tasks' + const request = makeRequest() + seedPendingCreation(request) + vi.mocked(ensureWorktreeHasInitialTerminal).mockReturnValue('tab-1') + vi.mocked(ensureWebRuntimeWorktreeTerminalAfterWake).mockImplementation(() => { + throw new Error('after-wake exploded') + }) + + await executeWorktreeCreation('creation-1', request) + + // Tabs were seeded for the new worktree... + expect(ensureWorktreeHasInitialTerminal).toHaveBeenCalledWith( + store, + 'wt-1', + undefined, + undefined, + undefined, + undefined, + expect.objectContaining({ activateCreatedTabs: false }) + ) + expect(console.error).toHaveBeenCalledWith( + 'worktree create: after-wake terminal seeding failed', + 'wt-1', + expect.any(Error) + ) + // ...and the creation still completed instead of stranding the entry. + expect(store.removePendingWorktreeCreation).toHaveBeenCalledWith('creation-1', { + cleanupVm: false + }) + expect(store.pendingWorktreeCreations['creation-1']).toBeUndefined() + expect(store.activePendingCreationId).toBeNull() + expect(shouldShowWorktreeCreationSurface(surfaceInput('terminal'))).toBe(false) + }) + + it('concurrent create: a throw completing a backgrounded creation still tears its entry down', async () => { + // A second submitted create repointed activePendingCreationId, so this + // creation's completion takes the non-activating branch on the terminal view. + store.activeView = 'terminal' + const request = makeRequest() + seedPendingCreation(request) + store.activePendingCreationId = 'creation-2' + store.createWorktree.mockResolvedValue({ + worktree: { id: 'wt-1', repoId: 'repo-1' }, + setup: { runnerScriptPath: '/tmp/setup.sh' } + }) + vi.mocked(ensureWorktreeHasInitialTerminal).mockReturnValue('tab-1') + vi.mocked(ensureWebRuntimeWorktreeTerminalAfterWake).mockImplementation(() => { + throw new Error('after-wake exploded') + }) + + await executeWorktreeCreation('creation-1', request) + + // Blank terminal + Setup tab are seeded by this one synchronous call. + expect(activateAndRevealWorktree).not.toHaveBeenCalled() + expect(ensureWorktreeHasInitialTerminal).toHaveBeenCalledWith( + store, + 'wt-1', + undefined, + { runnerScriptPath: '/tmp/setup.sh' }, + undefined, + undefined, + expect.objectContaining({ activateCreatedTabs: false }) + ) + // The entry is gone; the pointer stays on the other in-flight creation. + expect(store.pendingWorktreeCreations['creation-1']).toBeUndefined() + expect(store.activePendingCreationId).toBe('creation-2') + expect(shouldShowWorktreeCreationSurface(surfaceInput('terminal'))).toBe(false) + }) + + it('control: with no throw the same flow completes and tears the surface down', async () => { + store.activeView = 'tasks' + const request = makeRequest() + seedPendingCreation(request) + vi.mocked(ensureWorktreeHasInitialTerminal).mockReturnValue('tab-1') + + await executeWorktreeCreation('creation-1', request) + + expect(store.removePendingWorktreeCreation).toHaveBeenCalledWith('creation-1', { + cleanupVm: false + }) + expect(store.pendingWorktreeCreations['creation-1']).toBeUndefined() + expect(store.activePendingCreationId).toBeNull() + expect(shouldShowWorktreeCreationSurface(surfaceInput('terminal'))).toBe(false) + }) + + it('backstop: a rejection that escapes the execute promise becomes a visible inline error', async () => { + // Pre-create preparation runs before the in-function try/catch. + vi.mocked(prepareRequestForCreate).mockRejectedValue(new Error('prepare exploded')) + + const creationId = runBackgroundWorktreeCreation(makeRequest()) + + await vi.waitFor(() => { + expect(store.pendingWorktreeCreations[creationId]).toMatchObject({ + status: 'error', + error: 'prepare exploded' + }) + }) + expect(toast.error).not.toHaveBeenCalled() + expect(store.removePendingWorktreeCreation).not.toHaveBeenCalled() + expect(console.error).toHaveBeenCalledWith( + 'worktree create: unhandled failure', + creationId, + expect.any(Error) + ) + }) + + it('backstop: a rejection after leaving the panel is announced with a toast', async () => { + store.activeView = 'tasks' + vi.mocked(prepareRequestForCreate).mockRejectedValue(new Error('prepare exploded')) + + const creationId = runBackgroundWorktreeCreation(makeRequest()) + // The pending surface is revealed synchronously; move away before the + // rejected preparation reaches the fire-and-forget backstop. + store.activeView = 'tasks' + + await vi.waitFor(() => { + expect(toast.error).toHaveBeenCalledWith('prepare exploded') + }) + expect(store.pendingWorktreeCreations[creationId]).toMatchObject({ status: 'error' }) + }) +}) diff --git a/src/renderer/src/lib/worktree-creation-flow.test.ts b/src/renderer/src/lib/worktree-creation-flow.test.ts index 84ac3a61b32..a599a265513 100644 --- a/src/renderer/src/lib/worktree-creation-flow.test.ts +++ b/src/renderer/src/lib/worktree-creation-flow.test.ts @@ -606,7 +606,7 @@ describe('staged background worktree creation', () => { delete store.pendingWorktreeCreations['creation-1'] store.activePendingCreationId = null resolveTrust() - await vi.waitFor(() => expect(ensureWorktreeHasInitialTerminal).toHaveBeenCalledTimes(1)) + await vi.waitFor(() => expect(store.removePendingWorktreeCreation).toHaveBeenCalled()) expect(activateAndRevealWorktree).not.toHaveBeenCalled() }) diff --git a/src/renderer/src/lib/worktree-creation-flow.ts b/src/renderer/src/lib/worktree-creation-flow.ts index dfde4e7fe58..7a46e708417 100644 --- a/src/renderer/src/lib/worktree-creation-flow.ts +++ b/src/renderer/src/lib/worktree-creation-flow.ts @@ -1,3 +1,4 @@ +import { toast } from 'sonner' import { useAppStore } from '@/store' import { findPendingLinkedWorkItemCreationId, @@ -11,11 +12,34 @@ import { getWorktreeCreationIndeterminate } from '@/lib/worktree-creation-flow-startup' import { retryStructuredWorktreeLaunch } from '@/lib/worktree-creation-structured-recovery' +import { + formatWorkspaceCreateError, + getWorkspaceCreateErrorToastMessage +} from '@/lib/workspace-create-error-format' type ContinueBackgroundWorktreeCreationOptions = { revealCreationSurface?: boolean } +// Why: nothing awaits these creations, so an escaped rejection would otherwise +// strand the pending entry — and the creation surface — with no error shown. +function startWorktreeCreation(creationId: string, request: WorktreeCreationRequest): void { + executeWorktreeCreation(creationId, request).catch((error: unknown) => { + console.error('worktree create: unhandled failure', creationId, error) + const store = useAppStore.getState() + if (!store.pendingWorktreeCreations[creationId]) { + return + } + const message = getWorkspaceCreateErrorToastMessage(formatWorkspaceCreateError(error)) + store.updatePendingWorktreeCreation(creationId, { status: 'error', error: message }) + // Why: the panel renders this error inline while its surface is visible; + // only announce it separately after the user has navigated away. + if (!(store.activeView === 'terminal' && store.activePendingCreationId === creationId)) { + toast.error(message) + } + }) +} + function revealPendingCreation( creationId: string, request: WorktreeCreationRequest, @@ -62,7 +86,7 @@ export function runBackgroundWorktreeCreation(request: WorktreeCreationRequest): // client over plain HTTP). createBrowserUuid falls back to getRandomValues. const creationId = createBrowserUuid() revealPendingCreation(creationId, request, getInitialWorktreeCreationPhase(request)) - void executeWorktreeCreation(creationId, request) + startWorktreeCreation(creationId, request) return creationId } @@ -101,7 +125,7 @@ export function continueBackgroundWorktreeCreation( store.setActiveView('terminal') store.setSidebarOpen(true) } - void executeWorktreeCreation(creationId, request) + startWorktreeCreation(creationId, request) return true } @@ -133,5 +157,5 @@ export function retryBackgroundWorktreeCreation(creationId: string): void { ) return } - void executeWorktreeCreation(creationId, entry.request) + startWorktreeCreation(creationId, entry.request) } diff --git a/src/renderer/src/lib/worktree-creation-structured-session.test.ts b/src/renderer/src/lib/worktree-creation-structured-session.test.ts index b8e1d609ea8..f072c17d417 100644 --- a/src/renderer/src/lib/worktree-creation-structured-session.test.ts +++ b/src/renderer/src/lib/worktree-creation-structured-session.test.ts @@ -13,6 +13,7 @@ const mocks = vi.hoisted(() => ({ activateStructuredAgentSessionById: vi.fn(), activateAndRevealWorktree: vi.fn(), ensureWorktreeHasInitialTerminal: vi.fn(), + ensureWebRuntimeWorktreeTerminalAfterWake: vi.fn(), preflightAgentTrust: vi.fn(), updateWorktreeMeta: vi.fn() })) @@ -54,6 +55,10 @@ vi.mock('@/lib/worktree-initial-terminal-seeding', () => ({ ensureWorktreeHasInitialTerminal: mocks.ensureWorktreeHasInitialTerminal })) +vi.mock('@/lib/web-runtime-worktree-terminal-after-wake', () => ({ + ensureWebRuntimeWorktreeTerminalAfterWake: mocks.ensureWebRuntimeWorktreeTerminalAfterWake +})) + vi.mock('@/lib/worktree-activation', () => ({ activateAndRevealWorktree: mocks.activateAndRevealWorktree })) @@ -351,6 +356,11 @@ describe('launchStructuredWorktreeSession', () => { undefined, { activateCreatedTabs: false, createNewTerminalForStartup: true } ) + expect(mocks.ensureWebRuntimeWorktreeTerminalAfterWake).toHaveBeenCalledWith('worktree-1', { + startup: undefined, + agent: 'codex', + activate: false + }) }) it('stops the fallback mid-way when the creation is dismissed and retires nothing', async () => { diff --git a/src/renderer/src/lib/worktree-creation-structured-session.ts b/src/renderer/src/lib/worktree-creation-structured-session.ts index ee7fd594502..df86f56efed 100644 --- a/src/renderer/src/lib/worktree-creation-structured-session.ts +++ b/src/renderer/src/lib/worktree-creation-structured-session.ts @@ -12,6 +12,7 @@ import type { WorktreeStartupPayload } from '@/lib/worktree-startup-payload' import { closeStructuredAgentSession } from '@/runtime/structured-agent-session-close' import { callRuntimeRpc } from '@/runtime/runtime-rpc-client' import { toRuntimeWorktreeSelector } from '@/runtime/runtime-worktree-selector' +import { ensureWebRuntimeWorktreeTerminalAfterWake } from '@/lib/web-runtime-worktree-terminal-after-wake' export type WorktreeCreationStructuredSessionResult = { accepted: boolean @@ -92,17 +93,21 @@ async function openLegacyWorktreeSurface( }) return { activation, primaryTabId: activation === false ? null : activation.primaryTabId } } - return { - primaryTabId: ensureWorktreeHasInitialTerminal( - useAppStore.getState(), - args.worktreeId, - args.fallbackStartupOpt, - undefined, - undefined, - undefined, - { activateCreatedTabs: false, createNewTerminalForStartup: true } - ) - } + const primaryTabId = ensureWorktreeHasInitialTerminal( + useAppStore.getState(), + args.worktreeId, + args.fallbackStartupOpt, + undefined, + undefined, + undefined, + { activateCreatedTabs: false, createNewTerminalForStartup: true } + ) + ensureWebRuntimeWorktreeTerminalAfterWake(args.worktreeId, { + startup: args.fallbackStartupOpt, + agent: args.request.agent, + activate: false + }) + return { primaryTabId } } export async function launchStructuredWorktreeSession( diff --git a/src/renderer/src/lib/worktree-sleep-intent.ts b/src/renderer/src/lib/worktree-sleep-intent.ts index 7beac240803..6512abec692 100644 --- a/src/renderer/src/lib/worktree-sleep-intent.ts +++ b/src/renderer/src/lib/worktree-sleep-intent.ts @@ -1,13 +1,69 @@ +// Why: a slept workspace keeps its panes mounted with only dead PTYs behind them. +// Any pane connect that runs while the marker is set waits here, and the clear +// that marks the workspace awake resumes every waiting connect. const sleepingWorktreeIds = new Set() +const tearingDownWorktreeIds = new Set() +const wakeListenersByWorktreeId = new Map void>>() export function markWorktreeSleepIntent(worktreeId: string): void { sleepingWorktreeIds.add(worktreeId) } -export function clearWorktreeSleepIntent(worktreeId: string): void { +/** + * Why: a spawn that resolves while the sleep teardown is still awaiting its host + * would bind a PTY and clear the marker, waking every waiting pane mid-sleep. + * Binds during the teardown window are not wakes. + */ +export async function withWorktreeSleepTeardown( + worktreeId: string, + teardown: () => Promise +): Promise { + tearingDownWorktreeIds.add(worktreeId) + try { + return await teardown() + } finally { + tearingDownWorktreeIds.delete(worktreeId) + } +} + +export function clearWorktreeSleepIntent(worktreeId: string | null): void { + if (!worktreeId || tearingDownWorktreeIds.has(worktreeId)) { + return + } + if (!sleepingWorktreeIds.delete(worktreeId)) { + return + } + const listeners = wakeListenersByWorktreeId.get(worktreeId) + wakeListenersByWorktreeId.delete(worktreeId) + for (const listener of listeners ?? []) { + try { + listener() + } catch (error) { + // Why: one pane's connect failure must not strand its siblings or throw out of a store action. + console.error('[sleep-intent] wake listener failed', { worktreeId, error }) + } + } +} + +// Why: a purged worktree must not wake its panes; they are being unmounted. +export function forgetWorktreeSleepIntent(worktreeId: string): void { sleepingWorktreeIds.delete(worktreeId) + tearingDownWorktreeIds.delete(worktreeId) + wakeListenersByWorktreeId.delete(worktreeId) } export function hasWorktreeSleepIntent(worktreeId: string | null): boolean { return worktreeId !== null && sleepingWorktreeIds.has(worktreeId) } + +export function onWorktreeSleepIntentCleared(worktreeId: string, listener: () => void): () => void { + const listeners = wakeListenersByWorktreeId.get(worktreeId) ?? new Set<() => void>() + listeners.add(listener) + wakeListenersByWorktreeId.set(worktreeId, listeners) + return () => { + listeners.delete(listener) + if (listeners.size === 0 && wakeListenersByWorktreeId.get(worktreeId) === listeners) { + wakeListenersByWorktreeId.delete(worktreeId) + } + } +} diff --git a/src/renderer/src/runtime/runtime-host-connection-state.test.ts b/src/renderer/src/runtime/runtime-host-connection-state.test.ts index 8db0c0eb010..30ee06a5e98 100644 --- a/src/renderer/src/runtime/runtime-host-connection-state.test.ts +++ b/src/renderer/src/runtime/runtime-host-connection-state.test.ts @@ -2,7 +2,9 @@ import { describe, expect, it } from 'vitest' import type { RuntimeStatus } from '../../../shared/runtime-types' import { isConnectedRuntimeHostState, + isDisconnectedRuntimeHostState, runtimeHostConnectionState, + runtimeHostConnectionStateForEntry, runtimeStatusForOverall } from './runtime-host-connection-state' @@ -177,3 +179,72 @@ describe('runtime host connection state', () => { ).toBe('disconnected') }) }) + +describe('runtime host connection state for a recorded status entry', () => { + it('separates a host that was never probed from one a probe found unreachable', () => { + // The sidebar read raw truthiness, which collapsed these two into the same red glyph. + expect(runtimeHostConnectionStateForEntry(undefined)).toBe('checking') + expect(runtimeHostConnectionStateForEntry({ status: null })).toBe('disconnected') + }) + + it('reads the remote-control diagnostics recorded beside a failed probe', () => { + expect( + runtimeHostConnectionStateForEntry({ + status: null, + remoteControl: remoteControl('reconnecting') + }) + ).toBe('reconnecting') + }) + + it('agrees with the status bar that a closed control channel is disconnected', () => { + expect( + runtimeHostConnectionStateForEntry({ + status: makeStatus({ remoteControl: remoteControl('closed') }) + }) + ).toBe('disconnected') + }) + + it('names only the disconnected verdict as disconnected', () => { + expect(isDisconnectedRuntimeHostState('disconnected')).toBe(true) + for (const state of [ + 'connected', + 'checking', + 'reconnecting', + 'runtime-unavailable', + 'workspace-window-closed' + ] as const) { + expect(isDisconnectedRuntimeHostState(state)).toBe(false) + } + }) +}) + +function remoteControl( + state: NonNullable['state'] +): NonNullable { + return { + state, + pendingRequestCount: 0, + subscriptionCount: 0, + reconnectAttempt: 1, + lastConnectedAt: null, + lastClose: null, + lastError: null + } +} + +it('does not report reconnecting after verification is terminally blocked', () => { + expect( + runtimeHostConnectionStateForEntry({ + status: null, + snapshot: { + environmentId: 'browser', + pairingRevision: 1, + sequence: 1, + checkedAt: 1, + status: null, + verification: 'blocked', + transport: 'disconnected' + } + }) + ).toBe('disconnected') +}) diff --git a/src/renderer/src/runtime/runtime-host-connection-state.ts b/src/renderer/src/runtime/runtime-host-connection-state.ts index 6094c995804..c10477415a1 100644 --- a/src/renderer/src/runtime/runtime-host-connection-state.ts +++ b/src/renderer/src/runtime/runtime-host-connection-state.ts @@ -1,3 +1,4 @@ +import type { RuntimeHostStatusSnapshot } from '../../../shared/runtime-host-status' import type { RuntimeStatus } from '../../../shared/runtime-types' import { isRuntimeWorkspaceWindowClosed } from '../../../shared/runtime-workspace-window-availability' @@ -97,3 +98,44 @@ export function isConnectedRuntimeHostState(state: RuntimeHostConnectionState): state === 'connected' || state === 'runtime-unavailable' || state === 'workspace-window-closed' ) } + +/** + * Only this verdict earns the destructive glyph. 'checking' and 'reconnecting' are + * unverifiable, not down, per docs/reference/ssh-execution-boundary.md. + */ +export function isDisconnectedRuntimeHostState(state: RuntimeHostConnectionState): boolean { + return state === 'disconnected' +} + +/** The same derivation, read straight off a recorded status entry. */ +export function runtimeHostConnectionStateForEntry( + entry: + | { + status: RuntimeStatus | null + remoteControl?: RuntimeStatus['remoteControl'] | null + snapshot?: RuntimeHostStatusSnapshot + } + | null + | undefined +): RuntimeHostConnectionState { + if (entry?.snapshot) { + const snapshot = entry.snapshot + if (snapshot.retired || snapshot.verification === 'blocked') { + return 'disconnected' + } + if (snapshot.transport === 'disconnected') { + return 'reconnecting' + } + if (snapshot.verification === 'checking' && !entry.status) { + return 'checking' + } + if (snapshot.transport === 'ready' && snapshot.verification !== 'verified') { + return 'runtime-unavailable' + } + } + return runtimeHostConnectionState({ + hasStatusEntry: Boolean(entry), + status: entry?.status ?? null, + remoteControl: entry?.remoteControl ?? entry?.status?.remoteControl ?? null + }) +} diff --git a/src/renderer/src/runtime/web-runtime-session-types.ts b/src/renderer/src/runtime/web-runtime-session-types.ts index 289562674cb..8664c9192ce 100644 --- a/src/renderer/src/runtime/web-runtime-session-types.ts +++ b/src/renderer/src/runtime/web-runtime-session-types.ts @@ -28,6 +28,8 @@ export type CreateWebRuntimeSessionTerminalArgs = { launchToken?: string agent?: TuiAgent launchAgent?: TuiAgent + /** The command already encodes the complete agent startup and prompt-delivery plan. */ + preparedAgentCommand?: boolean agentSessionKind?: 'fresh' | 'resume' prompt?: string promptDelivery?: AgentPromptDelivery diff --git a/src/renderer/src/runtime/web-runtime-terminal-create-operation.ts b/src/renderer/src/runtime/web-runtime-terminal-create-operation.ts index 601888e5f9b..d14adc5d889 100644 --- a/src/renderer/src/runtime/web-runtime-terminal-create-operation.ts +++ b/src/renderer/src/runtime/web-runtime-terminal-create-operation.ts @@ -88,7 +88,9 @@ export async function createWebRuntimeSessionTerminalResult( let legacyAlreadyPlacedInGroup = false // Why: structured creation cannot yet express afterTabId; keep the exact legacy placement contract until it can. // Why: focus belongs to the paired client; a headless execution host has no renderer to focus. - const hostAuthority = args.afterTabId + // Why: rebuilding a prepared command through host authority can discard its embedded prompt and delivery flags. + const mustUseLegacyAgentCreate = args.preparedAgentCommand || args.afterTabId + const hostAuthority = mustUseLegacyAgentCreate ? undefined : args.agentSessionKind === 'resume' ? args.providerSession diff --git a/src/renderer/src/runtime/web-session-tabs-sync/active-session-subscription.ts b/src/renderer/src/runtime/web-session-tabs-sync/active-session-subscription.ts index 71475ff2e79..83789643f1f 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync/active-session-subscription.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync/active-session-subscription.ts @@ -141,13 +141,16 @@ export function installActiveSessionTabsSubscription({ const hasLiveLocalPty = localTabs.some( (tab) => (syncState.ptyIdsByTabId[tab.id] ?? []).length > 0 ) - const bootstrap = shouldBootstrapInitialWebRuntimeTerminal({ - event: recoveredEvent, - activeWorktreeId, - requestedInitialTerminal, - snapshotIsFresh: decision.apply, - localTerminalCount - }) + const skipAutomaticTerminal = shouldSkipWebRuntimeWakeTerminalRespawn(activeWorktreeId) + const bootstrap = + !skipAutomaticTerminal && + shouldBootstrapInitialWebRuntimeTerminal({ + event: recoveredEvent, + activeWorktreeId, + requestedInitialTerminal, + snapshotIsFresh: decision.apply, + localTerminalCount + }) const respawn = shouldRespawnWebRuntimeTerminalAfterWake({ event: recoveredEvent, activeWorktreeId, @@ -155,7 +158,7 @@ export function installActiveSessionTabsSubscription({ snapshotIsFresh: decision.apply, localTerminalCount, hasLiveLocalPty, - skipWakeRespawn: shouldSkipWebRuntimeWakeTerminalRespawn(activeWorktreeId) + skipWakeRespawn: skipAutomaticTerminal }) let settle: HostSessionMirrorSettle | null = decision.apply ? null diff --git a/src/renderer/src/runtime/web-session-tabs-sync/mirrored-terminal-recovery-ledger.test.ts b/src/renderer/src/runtime/web-session-tabs-sync/mirrored-terminal-recovery-ledger.test.ts new file mode 100644 index 00000000000..d1992a27030 --- /dev/null +++ b/src/renderer/src/runtime/web-session-tabs-sync/mirrored-terminal-recovery-ledger.test.ts @@ -0,0 +1,74 @@ +import { describe, expect, it } from 'vitest' +import type { RuntimeMobileSessionTabsResult } from '../../../../shared/runtime-types' +import type { TerminalTab, TerminalTabRecoveryLedger } from '../../../../shared/terminal-tab-types' +import { buildMirroredTerminalTabs } from './terminal-build' +import { toWebTerminalSurfaceTabId } from '../web-terminal-surface-id' + +/** + * The recovery ledger is client-local. The host publishes no such field, so a + * rebuild that does not carry the existing one restores this tab's remount + * allowance on EVERY snapshot — which is the remount storm (b5cfc6ca) the + * ledger exists to end, re-armed on the host's publication cadence. + * + * `generation` is deliberately not asserted here: the host carries none and the + * rebuild emits none, which is why `isSupersededLedger` compares strictly + * forward (`>`) rather than `!==`. See terminal-tab-recovery-ledger.ts. + */ +const WORKTREE = 'repo-1::worktree-1' +const ENVIRONMENT = 'env-1' +const HOST_TAB = 'host-tab-1' + +const LEDGER: TerminalTabRecoveryLedger = { + attemptedAt: [1_000], + generation: 1, + outcome: 'failed', + startedAt: 1_000, + reason: 'reattach-unverifiable', + tabGeneration: 1 +} + +function snapshot(): RuntimeMobileSessionTabsResult { + return { + worktree: WORKTREE, + publicationEpoch: 'epoch-1', + snapshotVersion: 1, + activeGroupId: 'group-1', + activeTabId: null, + activeTabType: null, + tabs: [ + { + type: 'terminal', + id: 'surface-1', + parentTabId: HOST_TAB, + leafId: 'leaf-1', + title: 'Terminal', + status: 'ready', + terminal: 'handle-1', + isActive: true + } + ] + } as RuntimeMobileSessionTabsResult +} + +function rebuild(existing?: Partial): TerminalTab { + const localTabId = toWebTerminalSurfaceTabId(HOST_TAB) + const existingById = new Map( + existing ? [[localTabId, { id: localTabId, ...existing } as TerminalTab]] : [] + ) + const [mirrored] = buildMirroredTerminalTabs(snapshot(), ENVIRONMENT, existingById, {}, 0, 1_000) + return mirrored!.tab +} + +describe('buildMirroredTerminalTabs recovery ledger', () => { + it('carries the client-local ledger across a host snapshot rebuild', () => { + expect(rebuild({ recovery: LEDGER }).recovery).toEqual(LEDGER) + }) + + it('emits none for a tab that never recovered', () => { + expect(rebuild({}).recovery).toBeUndefined() + }) + + it('emits none for a tab the client has never seen', () => { + expect(rebuild().recovery).toBeUndefined() + }) +}) diff --git a/src/renderer/src/runtime/web-session-tabs-sync/terminal-build.ts b/src/renderer/src/runtime/web-session-tabs-sync/terminal-build.ts index dfc3759009d..aacb445bbe3 100644 --- a/src/renderer/src/runtime/web-session-tabs-sync/terminal-build.ts +++ b/src/renderer/src/runtime/web-session-tabs-sync/terminal-build.ts @@ -171,6 +171,10 @@ export function buildMirroredTerminalTabs( // without this dropped the client's agent-prompt label on every snapshot. ...(existing?.generatedTitle ? { generatedTitle: existing.generatedTitle } : {}), ...(existing?.aiVaultTitle ? { aiVaultTitle: existing.aiVaultTitle } : {}), + // Why: the recovery ledger is client-local and the host carries none, so + // rebuilding without it would restore this tab's remount allowance on + // every snapshot — the counting loop recovery is meant to end (b5cfc6ca). + ...(existing?.recovery ? { recovery: existing.recovery } : {}), ...(quickCommandLabel ? { quickCommandLabel } : {}), ...(startupCwd ? { startupCwd } : {}), customTitle: existing?.customTitle ?? null, diff --git a/src/renderer/src/store/slices/runtime-status-diagnostics-generation.ts b/src/renderer/src/store/slices/runtime-status-diagnostics-generation.ts deleted file mode 100644 index 22ba23cbbb1..00000000000 --- a/src/renderer/src/store/slices/runtime-status-diagnostics-generation.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY } from '../../../../shared/protocol-version' -import type { RemoteRuntimeSharedConnectionDiagnostics } from '../../../../shared/remote-runtime-shared-control-types' -import type { RuntimeEnvironmentStatus } from './runtime-status' - -const diagnosticsGenerationByEnvironment = new Map() - -export function updateRuntimeEnvironmentStatusOverlay( - state: Map, - environmentId: string, - status: RuntimeEnvironmentStatus -): Map { - const current = state.get(environmentId) - if (!current || current.status?.runtimeId !== status.status?.runtimeId) { - return state - } - return new Map(state).set(environmentId, status) -} - -export function acceptRuntimeEnvironmentDiagnosticsGeneration( - environmentId: string, - transportGeneration: number -): boolean { - const previous = diagnosticsGenerationByEnvironment.get(environmentId) - if (previous !== undefined && transportGeneration < previous) { - return false - } - diagnosticsGenerationByEnvironment.set(environmentId, transportGeneration) - return true -} - -export function clearRuntimeEnvironmentDiagnosticsGenerationsForTests(): void { - diagnosticsGenerationByEnvironment.clear() -} - -export function mergePushedRuntimeEnvironmentDiagnostics(args: { - environmentId: string - transportGeneration: number - diagnostics: RemoteRuntimeSharedConnectionDiagnostics - current: RuntimeEnvironmentStatus | undefined - publish: (status: RuntimeEnvironmentStatus) => void -}): void { - if ( - !args.current?.status?.capabilities?.includes(REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY) || - !acceptRuntimeEnvironmentDiagnosticsGeneration(args.environmentId, args.transportGeneration) - ) { - return - } - args.publish({ - ...args.current, - status: { ...args.current.status, remoteControl: args.diagnostics } - }) -} diff --git a/src/renderer/src/store/slices/runtime-status-diagnostics-publish.ts b/src/renderer/src/store/slices/runtime-status-diagnostics-publish.ts deleted file mode 100644 index e51c8621bae..00000000000 --- a/src/renderer/src/store/slices/runtime-status-diagnostics-publish.ts +++ /dev/null @@ -1,106 +0,0 @@ -import type { RemoteRuntimeSharedConnectionDiagnostics } from '../../../../shared/remote-runtime-shared-control-types' -import type { AppState } from '../types' -import type { RuntimeEnvironmentStatus } from './runtime-status' -import * as diagnosticsGeneration from './runtime-status-diagnostics-generation' -import * as runtimeStatusRecheck from './runtime-status-recheck' - -export function updateRuntimeStatusStore( - state: AppState, - updater: (state: Map) => Map -): AppState | Pick { - const next = updater(state.runtimeStatusByEnvironmentId) - return next === state.runtimeStatusByEnvironmentId - ? state - : { runtimeStatusByEnvironmentId: next } -} - -export function publishRuntimeEnvironmentDiagnostics(args: { - environmentId: string - transportGeneration: number - diagnostics: RemoteRuntimeSharedConnectionDiagnostics - getCurrent: () => RuntimeEnvironmentStatus | undefined - updateState: (status: RuntimeEnvironmentStatus) => boolean - afterPublish?: (status: RuntimeEnvironmentStatus) => void -}): void { - diagnosticsGeneration.mergePushedRuntimeEnvironmentDiagnostics({ - environmentId: args.environmentId, - transportGeneration: args.transportGeneration, - diagnostics: args.diagnostics, - current: args.getCurrent(), - publish: (status) => { - if (args.updateState(status)) { - args.afterPublish?.(status) - } - } - }) -} - -export function applyRuntimeEnvironmentStatusOverlay(args: { - environmentId: string - status: RuntimeEnvironmentStatus - setState: ( - updater: (state: Map) => Map - ) => void -}): boolean { - let updated = false - args.setState((state) => { - const next = diagnosticsGeneration.updateRuntimeEnvironmentStatusOverlay( - state, - args.environmentId, - args.status - ) - updated = next !== state - return next - }) - return updated -} - -export function createRuntimeEnvironmentDiagnosticsPublisher(args: { - getCurrent: (environmentId: string) => RuntimeEnvironmentStatus | undefined - setState: ( - updater: (state: Map) => Map - ) => void - afterPublish: (environmentId: string, status: RuntimeEnvironmentStatus) => void -}): (event: { - environmentId: string - transportGeneration: number - diagnostics: RemoteRuntimeSharedConnectionDiagnostics -}) => void { - return (event) => - publishRuntimeEnvironmentDiagnostics({ - ...event, - getCurrent: () => args.getCurrent(event.environmentId), - updateState: (status) => - applyRuntimeEnvironmentStatusOverlay({ - environmentId: event.environmentId, - status, - setState: args.setState - }), - afterPublish: (status) => args.afterPublish(event.environmentId, status) - }) -} - -export function createRuntimeEnvironmentDiagnosticsSlicePublisher(args: { - getCurrent: (environmentId: string) => RuntimeEnvironmentStatus | undefined - setState: ( - updater: (state: Map) => Map - ) => void - getStore: () => AppState - getConnectionGeneration: (environmentId: string) => number -}): (event: { - environmentId: string - transportGeneration: number - diagnostics: RemoteRuntimeSharedConnectionDiagnostics -}) => void { - return createRuntimeEnvironmentDiagnosticsPublisher({ - getCurrent: args.getCurrent, - setState: args.setState, - afterPublish: (environmentId, status) => - runtimeStatusRecheck.reconcileRuntimeStatusForSlice( - environmentId, - status.status, - args.getStore, - () => args.getConnectionGeneration(environmentId) - ) - }) -} diff --git a/src/renderer/src/store/slices/runtime-status-diagnostics.test.ts b/src/renderer/src/store/slices/runtime-status-diagnostics.test.ts deleted file mode 100644 index 9faecdcabf1..00000000000 --- a/src/renderer/src/store/slices/runtime-status-diagnostics.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { create } from 'zustand' -import { REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY } from '../../../../shared/protocol-version' -import type { RuntimeStatus } from '../../../../shared/runtime-types' -import { createRuntimeStatusSlice, type RuntimeStatusSlice } from './runtime-status' - -function makeStatus(overrides: Partial = {}): RuntimeStatus { - return { - runtimeId: 'runtime-a', - rendererGraphEpoch: 0, - graphStatus: 'ready', - authoritativeWindowId: null, - liveTabCount: 3, - liveLeafCount: 0, - runtimeProtocolVersion: 3, - minCompatibleRuntimeClientVersion: 3, - capabilities: ['browser.screencast.v1'], - ...overrides - } as RuntimeStatus -} - -function createSliceStore() { - return create()((...a) => ({ - ...createRuntimeStatusSlice(...(a as unknown as Parameters)) - })) -} - -describe('runtime-status diagnostics', () => { - it('merges transport diagnostics into the complete status and fences stale pushes', () => { - const store = createSliceStore() - const status = makeStatus({ - capabilities: ['browser.screencast.v1', REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY] - }) - store.getState().setRuntimeEnvironmentStatus('env-a', { status, checkedAt: 1 }) - const closed = { - state: 'closed' as const, - pendingRequestCount: 0, - subscriptionCount: 1, - reconnectAttempt: 2, - lastConnectedAt: 1, - lastClose: { code: 1006, reason: 'network' }, - lastError: 'connection lost' - } - store.getState().publishRuntimeEnvironmentDiagnostics({ - environmentId: 'env-a', - transportGeneration: 3, - diagnostics: closed - }) - expect(store.getState().runtimeStatusByEnvironmentId.get('env-a')?.status).toMatchObject({ - runtimeId: 'runtime-a', - capabilities: expect.arrayContaining([ - 'browser.screencast.v1', - REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY - ]), - liveTabCount: 3, - remoteControl: closed - }) - store.getState().publishRuntimeEnvironmentDiagnostics({ - environmentId: 'env-a', - transportGeneration: 2, - diagnostics: { ...closed, state: 'ready' } - }) - expect( - store.getState().runtimeStatusByEnvironmentId.get('env-a')?.status?.remoteControl?.state - ).toBe('closed') - }) - - it('ignores diagnostics after the latest status drops shared-control support', () => { - const store = createSliceStore() - const status = makeStatus({ capabilities: [] }) - store.getState().setRuntimeEnvironmentStatus('env-a', { status, checkedAt: 1 }) - - store.getState().publishRuntimeEnvironmentDiagnostics({ - environmentId: 'env-a', - transportGeneration: 3, - diagnostics: { - state: 'reconnecting', - pendingRequestCount: 0, - subscriptionCount: 1, - reconnectAttempt: 2, - lastConnectedAt: 1, - lastClose: { code: 1006, reason: 'network' }, - lastError: 'connection lost' - } - }) - - expect(store.getState().runtimeStatusByEnvironmentId.get('env-a')?.status).toBe(status) - }) -}) diff --git a/src/renderer/src/store/slices/runtime-status-recheck.test.ts b/src/renderer/src/store/slices/runtime-status-recheck.test.ts deleted file mode 100644 index 9f09580c390..00000000000 --- a/src/renderer/src/store/slices/runtime-status-recheck.test.ts +++ /dev/null @@ -1,238 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { create } from 'zustand' -import { toast } from 'sonner' -import { REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY } from '../../../../shared/protocol-version' -import type { PublicKnownRuntimeEnvironment } from '../../../../shared/runtime-environments' -import type { RuntimeStatus } from '../../../../shared/runtime-types' -import { - clearRuntimeEnvironmentConnectionGenerationsForTests, - createRuntimeStatusSlice, - setRuntimeEnvironmentConnectionGenerationForTests, - type RuntimeStatusSlice -} from './runtime-status' -import { clearRuntimeStatusRechecksForTests } from './runtime-status-recheck' - -vi.mock('sonner', () => ({ toast: { warning: vi.fn(), dismiss: vi.fn() } })) - -beforeEach(() => { - vi.useFakeTimers() - clearRuntimeStatusRechecksForTests() - clearRuntimeEnvironmentConnectionGenerationsForTests() - vi.mocked(toast.warning).mockReset() -}) - -afterEach(() => { - clearRuntimeStatusRechecksForTests() - vi.useRealTimers() - vi.unstubAllGlobals() -}) - -describe('runtime status recheck', () => { - it('publishes an observe-only ready result through the setter', async () => { - const getStatus = vi.fn().mockResolvedValue(response(status('ready'))) - const store = createStore(getStatus) - - store.getState().setRuntimeEnvironmentStatus('env-a', { - status: status('awaiting_ready'), - checkedAt: 1 - }) - await vi.advanceTimersByTimeAsync(3_000) - - expect(getStatus).toHaveBeenCalledWith({ - selector: 'env-a', - timeoutMs: 10_000, - observeOnly: true - }) - expect( - store.getState().runtimeStatusByEnvironmentId.get('env-a')?.status?.remoteControl - ).toMatchObject({ - state: 'ready' - }) - await vi.advanceTimersByTimeAsync(120_000) - expect(getStatus).toHaveBeenCalledOnce() - }) - - it('continues indefinitely on the capped ladder, including unchanged publishes', async () => { - const getStatus = vi.fn().mockResolvedValue(response(status('reconnecting'))) - const store = createStore(getStatus) - store.getState().setRuntimeEnvironmentStatus('env-a', { - status: status('reconnecting'), - checkedAt: 1 - }) - - await vi.advanceTimersByTimeAsync(3_000 + 6_000 + 12_000 + 30_000 + 60_000 + 60_000) - - expect(getStatus).toHaveBeenCalledTimes(6) - expect(store.getState().runtimeStatusByEnvironmentId.get('env-a')?.checkedAt).toBe(1) - }) - - it('cancels on removal, capability loss, and null without probing again', async () => { - const getStatus = vi.fn() - const store = createStore(getStatus) - store.getState().setRuntimeEnvironmentStatus('env-a', { - status: status('awaiting_authenticated'), - checkedAt: 1 - }) - store.getState().setRuntimeEnvironmentStatus('env-a', { - status: { ...status('awaiting_authenticated'), capabilities: [] }, - checkedAt: 2 - }) - await vi.advanceTimersByTimeAsync(60_000) - expect(getStatus).not.toHaveBeenCalled() - - store.getState().setRuntimeEnvironmentStatus('env-a', { - status: status('awaiting_ready'), - checkedAt: 3 - }) - store.getState().setRuntimeEnvironments([]) - await vi.advanceTimersByTimeAsync(60_000) - expect(getStatus).not.toHaveBeenCalled() - }) - - it('cancels an armed probe when the connection generation changes', async () => { - const getStatus = vi.fn() - const store = createStore(getStatus) - store.getState().setRuntimeEnvironmentStatus('env-a', { - status: status('awaiting_ready'), - checkedAt: 1 - }) - - setRuntimeEnvironmentConnectionGenerationForTests('env-a', 2) - await vi.advanceTimersByTimeAsync(3_000) - - expect(getStatus).not.toHaveBeenCalled() - }) - - it('restarts the ladder for a newly published connection generation', async () => { - const getStatus = vi.fn().mockResolvedValue(response(status('ready', 'rt-next'))) - const store = createStore(getStatus) - store.getState().setRuntimeEnvironmentStatus('env-a', { - status: status('awaiting_ready'), - checkedAt: 1 - }) - store.getState().setRuntimeEnvironmentStatus('env-a', { - status: status('awaiting_ready', 'rt-next'), - checkedAt: 2 - }) - - await vi.advanceTimersByTimeAsync(3_000) - - expect(getStatus).toHaveBeenCalledOnce() - expect(store.getState().runtimeStatusByEnvironmentId.get('env-a')?.status?.runtimeId).toBe( - 'rt-next' - ) - }) - - it('discards an in-flight result after a ready publish bumps the epoch', async () => { - const pending = deferred>() - const getStatus = vi.fn().mockReturnValue(pending.promise) - const store = createStore(getStatus) - store.getState().setRuntimeEnvironmentStatus('env-a', { - status: status('awaiting_ready'), - checkedAt: 1 - }) - await vi.advanceTimersByTimeAsync(3_000) - store.getState().setRuntimeEnvironmentStatus('env-a', { - status: status('ready'), - checkedAt: 2 - }) - - pending.resolve(response(status('reconnecting'))) - await Promise.resolve() - await Promise.resolve() - - expect( - store.getState().runtimeStatusByEnvironmentId.get('env-a')?.status?.remoteControl - ).toMatchObject({ - state: 'ready' - }) - }) - - it('keeps setter side effects when a recheck discovers disconnection', async () => { - const getStatus = vi.fn().mockResolvedValue({ - id: 'status.get', - ok: false, - error: { - code: 'runtime_unavailable', - message: 'offline', - data: { remoteControl: status('reconnecting').remoteControl } - }, - _meta: { runtimeId: 'rt' } - }) - const store = createStore(getStatus) - store.getState().setRuntimeEnvironmentStatus('env-a', { - status: status('awaiting_ready'), - checkedAt: 1 - }) - - await vi.advanceTimersByTimeAsync(3_000) - - expect(store.getState().runtimeStatusByEnvironmentId.get('env-a')?.status).toBeNull() - expect(store.getState().runtimeStatusByEnvironmentId.get('env-a')?.remoteControl).toMatchObject( - { - state: 'reconnecting' - } - ) - expect(toast.warning).toHaveBeenCalledOnce() - }) -}) - -function createStore(getStatus: ReturnType) { - vi.stubGlobal('window', { - api: { runtimeEnvironments: { getStatus, list: vi.fn() } } - }) - const store = create()((...args) => ({ - ...createRuntimeStatusSlice(...(args as unknown as Parameters)) - })) - store.getState().setRuntimeEnvironments([environment()]) - return store -} - -function status( - controlState: NonNullable['state'], - runtimeId = 'rt' -): RuntimeStatus { - return { - runtimeId, - rendererGraphEpoch: 1, - graphStatus: 'ready', - authoritativeWindowId: null, - liveTabCount: 0, - liveLeafCount: 0, - capabilities: [REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY], - remoteControl: { - state: controlState, - pendingRequestCount: 0, - subscriptionCount: 0, - reconnectAttempt: 1, - lastConnectedAt: null, - lastClose: null, - lastError: null - } - } as RuntimeStatus -} - -function response(result: RuntimeStatus) { - return { id: 'status.get', ok: true as const, result, _meta: { runtimeId: result.runtimeId } } -} - -function environment(): PublicKnownRuntimeEnvironment { - return { - id: 'env-a', - name: 'Dev Box', - createdAt: 1, - updatedAt: 1, - lastUsedAt: null, - runtimeId: 'rt', - endpoints: [{ id: 'ws', kind: 'websocket', label: 'WebSocket', endpoint: 'ws://x' }], - preferredEndpointId: 'ws' - } -} - -function deferred() { - let resolve: (value: T) => void = () => {} - const promise = new Promise((done) => { - resolve = done - }) - return { promise, resolve } -} diff --git a/src/renderer/src/store/slices/runtime-status-recheck.ts b/src/renderer/src/store/slices/runtime-status-recheck.ts deleted file mode 100644 index 303e5b4318d..00000000000 --- a/src/renderer/src/store/slices/runtime-status-recheck.ts +++ /dev/null @@ -1,167 +0,0 @@ -import { REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY } from '../../../../shared/protocol-version' -import type { RuntimeStatus } from '../../../../shared/runtime-types' -import { unwrapRuntimeRpcResult } from '@/runtime/runtime-rpc-client' -import { extractRuntimeTransportDiagnostics } from '@/runtime/runtime-status-probe-diagnostics' -import type { RuntimeEnvironmentStatus } from './runtime-status' - -const RECHECK_DELAYS_MS = [3_000, 6_000, 12_000, 30_000, 60_000] - -type RecheckState = { - epoch: number - attempt: number - timer: ReturnType | null - inFlight: boolean - connectionGeneration: number - environmentExists: () => boolean - getConnectionGeneration: () => number - publish: (status: RuntimeEnvironmentStatus) => void -} - -type RuntimeStatusStore = { - runtimeEnvironments: readonly { id: string }[] - setRuntimeEnvironmentStatus: (environmentId: string, status: RuntimeEnvironmentStatus) => void -} - -const rechecks = new Map() - -export function reconcileRuntimeStatusRecheck(args: { - environmentId: string - status: RuntimeStatus | null - connectionGeneration: number - environmentExists: () => boolean - getConnectionGeneration: () => number - publish: (status: RuntimeEnvironmentStatus) => void -}): void { - if (!shouldRecheck(args.status)) { - cancelRuntimeStatusRecheck(args.environmentId) - return - } - let state = rechecks.get(args.environmentId) - if (state && state.connectionGeneration !== args.connectionGeneration) { - cancelRuntimeStatusRecheck(args.environmentId) - state = undefined - } - if (!state) { - state = { - epoch: 0, - attempt: 0, - timer: null, - inFlight: false, - connectionGeneration: args.connectionGeneration, - environmentExists: args.environmentExists, - getConnectionGeneration: args.getConnectionGeneration, - publish: args.publish - } - rechecks.set(args.environmentId, state) - } else { - state.connectionGeneration = args.connectionGeneration - state.environmentExists = args.environmentExists - state.getConnectionGeneration = args.getConnectionGeneration - state.publish = args.publish - } - armRuntimeStatusRecheck(args.environmentId, state) -} - -export function reconcileRuntimeStatusForSlice( - environmentId: string, - status: RuntimeStatus | null, - get: () => RuntimeStatusStore, - getConnectionGeneration: () => number -): void { - reconcileRuntimeStatusRecheck({ - environmentId, - status, - connectionGeneration: getConnectionGeneration(), - environmentExists: () => - get().runtimeEnvironments.some((environment) => environment.id === environmentId), - getConnectionGeneration, - publish: (nextStatus) => get().setRuntimeEnvironmentStatus(environmentId, nextStatus) - }) -} - -export function cancelRuntimeStatusRecheck(environmentId: string): void { - const state = rechecks.get(environmentId) - if (!state) { - return - } - state.epoch += 1 - if (state.timer) { - clearTimeout(state.timer) - } - rechecks.delete(environmentId) -} - -export function cancelRuntimeStatusRechecks(environmentIds: Iterable): void { - for (const environmentId of environmentIds) { - cancelRuntimeStatusRecheck(environmentId) - } -} - -export function clearRuntimeStatusRechecksForTests(): void { - cancelRuntimeStatusRechecks([...rechecks.keys()]) -} - -function shouldRecheck(status: RuntimeStatus | null): boolean { - return Boolean( - status?.capabilities?.includes(REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY) && - status.remoteControl && - status.remoteControl.state !== 'ready' - ) -} - -function armRuntimeStatusRecheck(environmentId: string, state: RecheckState): void { - if (state.timer || state.inFlight) { - return - } - const delay = RECHECK_DELAYS_MS[Math.min(state.attempt, RECHECK_DELAYS_MS.length - 1)] - const generation = state.connectionGeneration - state.attempt += 1 - state.timer = setTimeout( - () => void fireRuntimeStatusRecheck(environmentId, state, generation), - delay - ) -} - -async function fireRuntimeStatusRecheck( - environmentId: string, - state: RecheckState, - generation: number -): Promise { - state.timer = null - const epoch = state.epoch - if ( - rechecks.get(environmentId) !== state || - !state.environmentExists() || - state.getConnectionGeneration() !== generation - ) { - cancelRuntimeStatusRecheck(environmentId) - return - } - state.inFlight = true - let nextEntry: RuntimeEnvironmentStatus - try { - const response = await window.api.runtimeEnvironments.getStatus({ - selector: environmentId, - timeoutMs: 10_000, - observeOnly: true - }) - nextEntry = { status: unwrapRuntimeRpcResult(response), checkedAt: Date.now() } - } catch (error: unknown) { - const remoteControl = extractRuntimeTransportDiagnostics(error) - nextEntry = { - status: null, - ...(remoteControl ? { remoteControl } : {}), - checkedAt: Date.now() - } - } - state.inFlight = false - if ( - rechecks.get(environmentId) !== state || - state.epoch !== epoch || - !state.environmentExists() || - state.getConnectionGeneration() !== generation - ) { - return - } - state.publish(nextEntry) -} diff --git a/src/renderer/src/store/slices/runtime-status-refresh.ts b/src/renderer/src/store/slices/runtime-status-refresh.ts index 638a3fae636..fb27eec6a43 100644 --- a/src/renderer/src/store/slices/runtime-status-refresh.ts +++ b/src/renderer/src/store/slices/runtime-status-refresh.ts @@ -15,6 +15,22 @@ export async function refreshRuntimeEnvironmentStatus( selector: environmentId, timeoutMs }) + if (window.api.runtimeEnvironments.getStatusSnapshots) { + try { + const snapshots = await window.api.runtimeEnvironments.getStatusSnapshots() + const snapshot = snapshots.find((entry) => entry.environmentId === environmentId) + if (snapshot) { + publish({ + snapshot, + status: snapshot.verification === 'verified' ? snapshot.status : null, + checkedAt: snapshot.checkedAt + }) + } + } catch (error) { + console.error('Failed to read runtime host status snapshot:', error) + } + return response.ok + } const status = unwrapRuntimeRpcResult(response) if (getRuntimeEnvironmentRevision(environmentId) !== expectedEnvironmentRevision) { return false diff --git a/src/renderer/src/store/slices/runtime-status-restored-browser-host-attach.test.ts b/src/renderer/src/store/slices/runtime-status-restored-browser-host-attach.test.ts index 0ba4d645026..d4b788cd49a 100644 --- a/src/renderer/src/store/slices/runtime-status-restored-browser-host-attach.test.ts +++ b/src/renderer/src/store/slices/runtime-status-restored-browser-host-attach.test.ts @@ -73,14 +73,10 @@ describe('restored client-hosted browser host attach on reachability', () => { }) }) - // The reconnect policy suppresses the *failure* publish only. A probe that answered still owes - // both recovery follow-ups, or a restored client-hosted page never comes back after the gap. - it('runs both recovery follow-ups on a success when the caller opted out of publishing failures', async () => { + it('runs both recovery follow-ups after a successful refresh', async () => { stubApi(vi.fn().mockResolvedValue(createCompatibleRuntimeStatusResponse('runtime-a'))) - await storeWithRestoredHandles(true) - .getState() - .refreshRuntimeEnvironmentStatus('env-a', undefined, { publishUnreachable: false }) + await storeWithRestoredHandles(true).getState().refreshRuntimeEnvironmentStatus('env-a') expect(prepareBrowserClientHostPlacement).toHaveBeenCalledWith({ selector: 'env-a', @@ -89,24 +85,12 @@ describe('restored client-hosted browser host attach on reachability', () => { expect(replayClientHostedBrowserCloseIntents).toHaveBeenCalledWith('env-a', expect.anything()) }) - // Under either policy a failed probe owes *no* follow-ups: it verified nothing, so there is no - // recovered host to reattach restored pages to and no one to replay closes at. - it.each([ - { name: 'the default policy', options: undefined }, - { name: 'a caller that opted out of publishing', options: { publishUnreachable: false } } - ])( - 'starts no browser client host when the environment is unreachable: $name', - async (scenario) => { - stubApi(vi.fn().mockRejectedValue(new Error('unreachable'))) - - await storeWithRestoredHandles(true) - .getState() - .refreshRuntimeEnvironmentStatus('env-a', undefined, scenario.options) - - expect(prepareBrowserClientHostPlacement).not.toHaveBeenCalled() - expect(replayClientHostedBrowserCloseIntents).not.toHaveBeenCalled() - } - ) + it('runs no recovery follow-ups when the environment is unreachable', async () => { + stubApi(vi.fn().mockRejectedValue(new Error('unreachable'))) + await storeWithRestoredHandles(true).getState().refreshRuntimeEnvironmentStatus('env-a') + expect(prepareBrowserClientHostPlacement).not.toHaveBeenCalled() + expect(replayClientHostedBrowserCloseIntents).not.toHaveBeenCalled() + }) it('starts no browser client host for restored pages the server hosts', async () => { stubApi(vi.fn().mockResolvedValue(createCompatibleRuntimeStatusResponse('runtime-a'))) diff --git a/src/renderer/src/store/slices/runtime-status-snapshot.test.ts b/src/renderer/src/store/slices/runtime-status-snapshot.test.ts new file mode 100644 index 00000000000..fa437065b28 --- /dev/null +++ b/src/renderer/src/store/slices/runtime-status-snapshot.test.ts @@ -0,0 +1,111 @@ +import { beforeEach, expect, it, vi } from 'vitest' +import { create } from 'zustand' +import { toast } from 'sonner' +import { + createRuntimeStatusSlice, + clearRuntimeEnvironmentConnectionGenerationsForTests, + type RuntimeStatusSlice +} from './runtime-status' +import type { RuntimeHostStatusSnapshot } from '../../../../shared/runtime-host-status' +import type { RuntimeStatus } from '../../../../shared/runtime-types' +import type { PublicKnownRuntimeEnvironment } from '../../../../shared/runtime-environments' +import { runtimeHostConnectionStateForEntry } from '@/runtime/runtime-host-connection-state' + +vi.mock('sonner', () => ({ toast: { warning: vi.fn(), dismiss: vi.fn() } })) +vi.mock('@/runtime/restored-client-hosted-browser-host-attach', () => ({ + ensureBrowserClientHostsForRestoredPages: vi.fn(), + ensureBrowserClientHostForRestartedRuntime: vi.fn() +})) +vi.mock('@/runtime/client-hosted-browser-close-intent-replay', () => ({ + replayClientHostedBrowserCloseIntents: vi.fn() +})) + +beforeEach(() => { + clearRuntimeEnvironmentConnectionGenerationsForTests() + vi.clearAllMocks() +}) +const environment = { + id: 'env-a', + name: 'Host', + createdAt: 1, + pairingRevision: 1, + endpoints: [], + preferredEndpointId: '' +} as unknown as PublicKnownRuntimeEnvironment +function store() { + const value = create()((...args) => + createRuntimeStatusSlice(...(args as unknown as Parameters)) + ) + value.getState().setRuntimeEnvironments([environment]) + return value +} +function snapshot( + sequence: number, + patch: Partial = {} +): RuntimeHostStatusSnapshot { + return { + environmentId: 'env-a', + pairingRevision: 1, + sequence, + checkedAt: sequence, + transport: 'ready', + verification: 'verified', + status: { runtimeId: 'rt-1' } as RuntimeStatus, + ...patch + } +} + +it('hydrates both viewers and rejects an older read after a newer publication', () => { + for (const viewer of [store(), store()]) { + viewer.getState().applyRuntimeHostStatusSnapshot(snapshot(2)) + viewer + .getState() + .applyRuntimeHostStatusSnapshot(snapshot(1, { status: null, verification: 'unavailable' })) + expect(viewer.getState().runtimeStatusByEnvironmentId.get('env-a')?.status?.runtimeId).toBe( + 'rt-1' + ) + } +}) + +it('represents failed verification honestly without manufacturing a session restart or toast', () => { + const viewer = store() + viewer.getState().applyRuntimeHostStatusSnapshot(snapshot(1)) + const generation = viewer + .getState() + .runtimeStatusByEnvironmentId.get('env-a')?.connectionGeneration + viewer.getState().applyRuntimeHostStatusSnapshot(snapshot(2, { verification: 'unavailable' })) + expect( + runtimeHostConnectionStateForEntry(viewer.getState().runtimeStatusByEnvironmentId.get('env-a')) + ).toBe('runtime-unavailable') + viewer.getState().applyRuntimeHostStatusSnapshot(snapshot(3)) + expect(viewer.getState().runtimeStatusByEnvironmentId.get('env-a')?.connectionGeneration).toBe( + generation + ) + expect(toast.warning).not.toHaveBeenCalled() + viewer + .getState() + .applyRuntimeHostStatusSnapshot(snapshot(4, { status: { runtimeId: 'rt-2' } as RuntimeStatus })) + expect( + viewer.getState().runtimeStatusByEnvironmentId.get('env-a')?.connectionGeneration + ).toBeGreaterThan(generation ?? 0) +}) + +it('retains disconnect ordering and rejects publications for removed or replaced pairings', () => { + const viewer = store() + viewer.getState().applyRuntimeHostStatusSnapshot(snapshot(1)) + viewer + .getState() + .applyRuntimeHostStatusSnapshot( + snapshot(3, { retired: true, verification: 'blocked', transport: 'disconnected' }) + ) + viewer.getState().applyRuntimeHostStatusSnapshot(snapshot(2)) + expect( + runtimeHostConnectionStateForEntry(viewer.getState().runtimeStatusByEnvironmentId.get('env-a')) + ).toBe('disconnected') + viewer.getState().setRuntimeEnvironments([{ ...environment, pairingRevision: 2 }]) + viewer.getState().applyRuntimeHostStatusSnapshot(snapshot(4)) + expect(viewer.getState().runtimeStatusByEnvironmentId.has('env-a')).toBe(false) + viewer.getState().setRuntimeEnvironments([]) + viewer.getState().applyRuntimeHostStatusSnapshot(snapshot(5, { pairingRevision: 2 })) + expect(viewer.getState().runtimeStatusByEnvironmentId.has('env-a')).toBe(false) +}) diff --git a/src/renderer/src/store/slices/runtime-status-snapshot.ts b/src/renderer/src/store/slices/runtime-status-snapshot.ts new file mode 100644 index 00000000000..b3543471d29 --- /dev/null +++ b/src/renderer/src/store/slices/runtime-status-snapshot.ts @@ -0,0 +1,43 @@ +import type { RuntimeHostStatusSnapshot } from '../../../../shared/runtime-host-status' +import type { AppState } from '../types' +import type { RuntimeEnvironmentStatus } from './runtime-status-types' +import { ensureBrowserClientHostsForRestoredPages } from '@/runtime/restored-client-hosted-browser-host-attach' +import { replayClientHostedBrowserCloseIntents } from '@/runtime/client-hosted-browser-close-intent-replay' + +export function applyRuntimeHostStatusSnapshot( + snapshot: RuntimeHostStatusSnapshot, + state: AppState, + publishEvidence: (entry: RuntimeEnvironmentStatus) => void +): void { + const environment = state.runtimeEnvironments.find((entry) => entry.id === snapshot.environmentId) + if ( + !environment || + (environment.pairingRevision ?? environment.createdAt) !== snapshot.pairingRevision + ) { + return + } + const previous = state.runtimeStatusByEnvironmentId.get(snapshot.environmentId) + if (previous?.snapshot && previous.snapshot.sequence >= snapshot.sequence) { + return + } + const entry: RuntimeEnvironmentStatus = { + snapshot, + checkedAt: snapshot.checkedAt, + connectionGeneration: previous?.connectionGeneration, + status: snapshot.verification === 'verified' && !snapshot.retired ? snapshot.status : null, + remoteControl: snapshot.remoteControl + } + if (entry.status) { + if (snapshot.remoteControl) { + entry.status = { ...entry.status, remoteControl: snapshot.remoteControl } + } + state.setRuntimeEnvironmentStatus(snapshot.environmentId, entry) + if (previous?.status == null) { + void ensureBrowserClientHostsForRestoredPages(state) + void replayClientHostedBrowserCloseIntents(snapshot.environmentId, state) + } + } else { + // Lost contact or a failed method observes no runtime session ending. + publishEvidence(entry) + } +} diff --git a/src/renderer/src/store/slices/runtime-status-types.ts b/src/renderer/src/store/slices/runtime-status-types.ts index c34feaf07bf..78e47123cf5 100644 --- a/src/renderer/src/store/slices/runtime-status-types.ts +++ b/src/renderer/src/store/slices/runtime-status-types.ts @@ -1,8 +1,9 @@ +import type { RuntimeHostStatusSnapshot } from '../../../../shared/runtime-host-status' import type { PublicKnownRuntimeEnvironment } from '../../../../shared/runtime-environments' import type { RuntimeStatus } from '../../../../shared/runtime-types' -import type { RemoteRuntimeSharedConnectionDiagnostics } from '../../../../shared/remote-runtime-shared-control-types' export type RuntimeEnvironmentStatus = { + snapshot?: RuntimeHostStatusSnapshot status: RuntimeStatus | null remoteControl?: RuntimeStatus['remoteControl'] | null appVersion?: string | null @@ -10,11 +11,9 @@ export type RuntimeEnvironmentStatus = { connectionGeneration?: number } -export type RuntimeStatusRefreshOptions = { - publishUnreachable?: boolean -} - export type RuntimeStatusSlice = { + readRuntimeHostStatusSnapshots: () => Promise + applyRuntimeHostStatusSnapshot: (snapshot: RuntimeHostStatusSnapshot) => void runtimeEnvironments: readonly PublicKnownRuntimeEnvironment[] runtimeEnvironmentCatalogHydrated: boolean runtimeEnvironmentCatalogSettled: boolean @@ -26,17 +25,8 @@ export type RuntimeStatusSlice = { status: RuntimeEnvironmentStatus, options?: { suppressDisconnectToast?: boolean } ) => void - publishRuntimeEnvironmentDiagnostics: (args: { - environmentId: string - transportGeneration: number - diagnostics: RemoteRuntimeSharedConnectionDiagnostics - }) => void clearRuntimeEnvironmentStatus: (environmentId: string) => void retainRuntimeEnvironmentStatuses: (environmentIds: Iterable) => void - refreshRuntimeEnvironmentStatus: ( - environmentId: string, - timeoutMs?: number, - options?: RuntimeStatusRefreshOptions - ) => Promise + refreshRuntimeEnvironmentStatus: (environmentId: string, timeoutMs?: number) => Promise hydrateRuntimeEnvironmentStatuses: () => Promise } diff --git a/src/renderer/src/store/slices/runtime-status.test.ts b/src/renderer/src/store/slices/runtime-status.test.ts index 8e3260957bf..fdc843c748a 100644 --- a/src/renderer/src/store/slices/runtime-status.test.ts +++ b/src/renderer/src/store/slices/runtime-status.test.ts @@ -710,33 +710,37 @@ describe('runtime-status slice', () => { clearRuntimeCompatibilityCacheForTests() }) - // Both directions of the failure-publication policy, from one failing probe. A user-initiated - // check publishes the outage it just observed; a caller holding live transport evidence must - // not, because status.get dials its own socket and its failure is unverifiable, not exited. - it.each([ - { name: 'a user-initiated check', options: undefined, publishes: true }, - { name: 'publishUnreachable defaulted', options: {}, publishes: true }, - { - name: 'a caller that opted out of publishing', - options: { publishUnreachable: false }, - publishes: false - } - ])('records null and returns false when a runtime refresh fails: $name', async (scenario) => { + it('records null and returns false when a runtime refresh fails', async () => { const getStatus = vi.fn().mockRejectedValue(new Error('closed')) stubRuntimeEnvironmentApi({ getStatus }) const store = createSliceStore() const cached = makeStatus() store.getState().setRuntimeEnvironmentStatus('env-a', { status: cached, checkedAt: 1 }) - const reachable = await store - .getState() - .refreshRuntimeEnvironmentStatus('env-a', undefined, scenario.options) + const reachable = await store.getState().refreshRuntimeEnvironmentStatus('env-a') - // The dial-answered contract the bridge's bounded retry chain reads is policy-independent. expect(reachable).toBe(false) - expect(store.getState().runtimeStatusByEnvironmentId.get('env-a')?.status).toBe( - scenario.publishes ? null : cached - ) + expect(store.getState().runtimeStatusByEnvironmentId.get('env-a')?.status).toBe(null) + }) + + it('preserves successful reachability when reading its snapshot fails', async () => { + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + vi.stubGlobal('window', { + api: { + runtimeEnvironments: { + getStatus: vi.fn().mockResolvedValue(createCompatibleRuntimeStatusResponse('runtime-a')), + getStatusSnapshots: vi.fn().mockRejectedValue(new Error('IPC read failed')) + } + } + }) + try { + const store = createSliceStore() + expect(await store.getState().refreshRuntimeEnvironmentStatus('env-a')).toBe(true) + expect(store.getState().runtimeStatusByEnvironmentId.has('env-a')).toBe(false) + expect(log).toHaveBeenCalled() + } finally { + log.mockRestore() + } }) it('hydrates saved environments through the single-environment refresh path', async () => { diff --git a/src/renderer/src/store/slices/runtime-status.ts b/src/renderer/src/store/slices/runtime-status.ts index 10985f389d8..c11fba3308a 100644 --- a/src/renderer/src/store/slices/runtime-status.ts +++ b/src/renderer/src/store/slices/runtime-status.ts @@ -1,11 +1,7 @@ import type { StateCreator } from 'zustand' import type { AppState } from '../types' import type { RuntimeStatusSlice } from './runtime-status-types' -export type { - RuntimeEnvironmentStatus, - RuntimeStatusRefreshOptions, - RuntimeStatusSlice -} from './runtime-status-types' +export type { RuntimeEnvironmentStatus, RuntimeStatusSlice } from './runtime-status-types' import { runtimeEnvironmentStatusesEqual } from './runtime-environment-status-equality' import { clearRecentRuntimeCompatibilityFailure, @@ -20,21 +16,16 @@ import { import { reconcileCatalogRows } from './repo-identity-reconcile' import { createRuntimeStatusHydration } from './runtime-status-hydration' import { refreshRuntimeEnvironmentStatus } from './runtime-status-refresh' -import * as runtimeStatusDiagnostics from './runtime-status-diagnostics-generation' import * as runtimeStatusConnectionGeneration from './runtime-status-connection-generation' import { replayClientHostedBrowserCloseIntents } from '@/runtime/client-hosted-browser-close-intent-replay' import { ensureBrowserClientHostForRestartedRuntime, ensureBrowserClientHostsForRestoredPages } from '@/runtime/restored-client-hosted-browser-host-attach' -import * as runtimeStatusRecheck from './runtime-status-recheck' -import * as runtimeStatusDiagnosticsPublish from './runtime-status-diagnostics-publish' +import { applyRuntimeHostStatusSnapshot } from './runtime-status-snapshot' export const clearRuntimeEnvironmentConnectionGenerationsForTests = (): void => { - runtimeStatusRecheck.cancelRuntimeStatusRechecks( - runtimeStatusConnectionGeneration.clearRuntimeEnvironmentConnectionGenerations() - ) - runtimeStatusDiagnostics.clearRuntimeEnvironmentDiagnosticsGenerationsForTests() + runtimeStatusConnectionGeneration.clearRuntimeEnvironmentConnectionGenerations() } export { @@ -52,6 +43,15 @@ export const createRuntimeStatusSlice: StateCreator { + try { + const snapshots = await window.api.runtimeEnvironments.getStatusSnapshots() + snapshots.forEach((snapshot) => get().applyRuntimeHostStatusSnapshot(snapshot)) + } catch (error) { + console.error('Failed to read runtime host status:', error) + } + }, + setRuntimeEnvironments: (environments) => { const previousRevisionById = new Map( get().runtimeEnvironments.map((environment) => [ @@ -76,7 +76,6 @@ export const createRuntimeStatusSlice: StateCreator environment.id) .filter((id) => !nextIds.has(id)) - runtimeStatusRecheck.cancelRuntimeStatusRechecks([...removedIds, ...replacedEnvironmentIds]) set((s) => { const keep = new Set(environments.map((environment) => environment.id)) const nextStatuses = new Map(s.runtimeStatusByEnvironmentId) @@ -155,15 +154,29 @@ export const createRuntimeStatusSlice: StateCreator + applyRuntimeHostStatusSnapshot(snapshot, get(), (entry) => { + set((s) => ({ + runtimeStatusByEnvironmentId: new Map(s.runtimeStatusByEnvironmentId).set( + snapshot.environmentId, + entry + ) + })) + }), + setRuntimeEnvironmentStatus: (environmentId, status, options) => { const previous = get().runtimeStatusByEnvironmentId.get(environmentId) + if (previous?.snapshot && !status.snapshot) { + return + } + const previousVerifiedStatus = previous?.snapshot?.status ?? previous?.status const pairedDeviceId = status.status?.pairedDeviceId?.trim() // A new runtime id under a known previous one is a restart, not a first connect: the guests are // still ours to host, but only a fresh attach hands them back to the replacement runtime. const runtimeRestarted = Boolean( status.status !== null && - previous?.status != null && - previous.status.runtimeId !== status.status.runtimeId + previousVerifiedStatus != null && + previousVerifiedStatus.runtimeId !== status.status.runtimeId ) // Why: a non-null status proves the runtime just answered, so drop any stale // "offline" compat failure before this online transition fires the @@ -177,7 +190,8 @@ export const createRuntimeStatusSlice: StateCreator - get().runtimeEnvironments.some((environment) => environment.id === environmentId), - getConnectionGeneration: () => - runtimeStatusConnectionGeneration.getRuntimeEnvironmentConnectionGeneration(environmentId), - publish: (entry) => get().setRuntimeEnvironmentStatus(environmentId, entry) - }) if (runtimeRestarted) { void ensureBrowserClientHostForRestartedRuntime(get(), environmentId) } @@ -250,18 +253,7 @@ export const createRuntimeStatusSlice: StateCreator get().runtimeStatusByEnvironmentId.get(environmentId), - setState: (updater) => - set((s) => runtimeStatusDiagnosticsPublish.updateRuntimeStatusStore(s, updater)), - getStore: get, - getConnectionGeneration: - runtimeStatusConnectionGeneration.getRuntimeEnvironmentConnectionGeneration - }), - clearRuntimeEnvironmentStatus: (environmentId) => { - runtimeStatusRecheck.cancelRuntimeStatusRecheck(environmentId) dismissRuntimeDisconnectedToast(environmentId) set((s) => { runtimeStatusConnectionGeneration.advanceRuntimeEnvironmentConnectionGeneration(environmentId) @@ -278,7 +270,6 @@ export const createRuntimeStatusSlice: StateCreator + refreshRuntimeEnvironmentStatus: (environmentId, timeoutMs = 10_000) => refreshRuntimeEnvironmentStatus(environmentId, timeoutMs, (entry) => { - if (entry.status === null && options?.publishUnreachable === false) { - // Unverifiable, not exited: leave the cached verdict for the caller's retry to settle. + if (entry.snapshot) { + get().applyRuntimeHostStatusSnapshot(entry.snapshot) return } // Why: setRuntimeEnvironmentStatus drops any stale compat failure on a non-null diff --git a/src/renderer/src/store/slices/tab-view-mode.test.ts b/src/renderer/src/store/slices/tab-view-mode.test.ts index aa892756b23..56b99c13ba4 100644 --- a/src/renderer/src/store/slices/tab-view-mode.test.ts +++ b/src/renderer/src/store/slices/tab-view-mode.test.ts @@ -81,4 +81,41 @@ describe('tab view mode', () => { store.getState().toggleTabViewMode('missing-tab') expect(store.getState().unifiedTabsByWorktree[WT]).toBe(before) }) + + // Why: terminal-pane recovery asks the terminal row who owns the surface. + // Host sync already writes viewMode there; only these local toggles skipped + // it, which is why the guard had to OR two indices to get a safe answer. + describe('mirrors onto the terminal row', () => { + function terminalRow(tabId: string) { + return store.getState().tabsByWorktree[WT]?.find((tab) => tab.id === tabId) + } + + beforeEach(() => { + const tabId = store.getState().createTab(WT).id + store.setState({ + unifiedTabsByWorktree: { + [WT]: [ + ...store.getState().unifiedTabsByWorktree[WT].filter((tab) => tab.id !== tabId), + makeUnifiedTab({ id: tabId, entityId: tabId, worktreeId: WT, groupId: 'g-left' }) + ] + } + } as Partial) + rowTabId = tabId + }) + + let rowTabId = '' + + it('toggleTabViewMode patches the row in the same write', () => { + store.getState().toggleTabViewMode(rowTabId) + expect(terminalRow(rowTabId)?.viewMode).toBe('chat') + + store.getState().toggleTabViewMode(rowTabId) + expect(terminalRow(rowTabId)?.viewMode).toBe('terminal') + }) + + it('setTabViewMode patches the row in the same write', () => { + store.getState().setTabViewMode(rowTabId, 'chat') + expect(terminalRow(rowTabId)?.viewMode).toBe('chat') + }) + }) }) diff --git a/src/renderer/src/store/slices/tabs/tabs-host-mirroring.ts b/src/renderer/src/store/slices/tabs/tabs-host-mirroring.ts index e87a34f81c2..66f09743e37 100644 --- a/src/renderer/src/store/slices/tabs/tabs-host-mirroring.ts +++ b/src/renderer/src/store/slices/tabs/tabs-host-mirroring.ts @@ -2,23 +2,27 @@ import type { AppState } from '../../types' import type { TerminalTab } from '../../../../../shared/terminal-tab-types' import { findTabAndWorktree } from '../tab-group-state' import { getRuntimeEnvironmentIdForWorktree } from '@/lib/worktree-runtime-owner' +import { locateTerminalTab } from '../../terminals/terminal-tab-location' -export function patchTerminalTabPinned( +/** + * Mirror a host-tracked unified-tab field onto its terminal row, in whichever + * bucket actually holds the row. Reconcile derives these fields from the + * TerminalTab, so a local toggle that only patched the unified tab would be + * recomputed away by the next host snapshot — and recovery's chat-ownership + * guard reads the row, so a lagging row lets a hidden chat surface remount. + */ +export function patchTerminalTabRow( tabsByWorktree: Record, - worktreeId: string, tabId: string, - isPinned: boolean + patch: Partial> ): Partial> { - const tabs = tabsByWorktree[worktreeId] - if (!tabs?.some((tab) => tab.id === tabId)) { + const location = locateTerminalTab(tabsByWorktree, tabId) + if (!location) { return {} } - return { - tabsByWorktree: { - ...tabsByWorktree, - [worktreeId]: tabs.map((tab) => (tab.id === tabId ? { ...tab, isPinned } : tab)) - } - } + const nextTabs = tabsByWorktree[location.worktreeId].slice() + nextTabs[location.index] = { ...location.tab, ...patch } + return { tabsByWorktree: { ...tabsByWorktree, [location.worktreeId]: nextTabs } } } // Why: pin is host-authoritative for remote-server tabs, so mirror it (like setTabColor) or it's lost on reconnect/other clients. diff --git a/src/renderer/src/store/slices/tabs/tabs-label-actions.ts b/src/renderer/src/store/slices/tabs/tabs-label-actions.ts index 8acb925bfae..42b8e3d7163 100644 --- a/src/renderer/src/store/slices/tabs/tabs-label-actions.ts +++ b/src/renderer/src/store/slices/tabs/tabs-label-actions.ts @@ -6,7 +6,7 @@ import { applyTabOrderSortValues, partitionPinnedTabOrder } from './tabs-tab-ord import { mirrorTabPinnedToHost, mirrorTabViewModeToHost, - patchTerminalTabPinned + patchTerminalTabRow } from './tabs-host-mirroring' export function createTabsLabelActions( @@ -62,7 +62,13 @@ export function createTabsLabelActions( }, setTabViewMode: (tabId, mode) => { - set((state) => patchTab(state.unifiedTabsByWorktree, tabId, { viewMode: mode }) ?? {}) + set((state) => ({ + ...patchTab(state.unifiedTabsByWorktree, tabId, { viewMode: mode }), + // Why the row too: viewMode is declared on both types and host-sync + // already writes it to the row. Only these local toggles skipped it, so + // readers had to OR the two indices to find out who owns the surface. + ...patchTerminalTabRow(state.tabsByWorktree, tabId, { viewMode: mode }) + })) mirrorTabViewModeToHost(get(), tabId, mode) }, @@ -86,7 +92,10 @@ export function createTabsLabelActions( (terminal) => terminal.id === found.tab.entityId )?.launchAgent ?? null toggled = { from: fromMode, to: nextMode, agent } - return patchTab(state.unifiedTabsByWorktree, tabId, { viewMode: nextMode }) ?? {} + return { + ...patchTab(state.unifiedTabsByWorktree, tabId, { viewMode: nextMode }), + ...patchTerminalTabRow(state.tabsByWorktree, tabId, { viewMode: nextMode }) + } }) // Why: emit after the state write so the event reflects the committed mode. const committed = toggled as { @@ -141,7 +150,7 @@ export function createTabsLabelActions( [worktreeId]: applyTabOrderSortValues(tabs, tabOrder) }, // Why: reconcile derives pin from the TerminalTab, so mirror it there too or a host snapshot recomputes isPinned:false and un-pins during the echo window. - ...patchTerminalTabPinned(state.tabsByWorktree, worktreeId, tabId, true), + ...patchTerminalTabRow(state.tabsByWorktree, tabId, { isPinned: true }), groupsByWorktree: { ...state.groupsByWorktree, [worktreeId]: updateGroup(groups, { ...group, tabOrder }) @@ -178,7 +187,7 @@ export function createTabsLabelActions( ...state.unifiedTabsByWorktree, [worktreeId]: applyTabOrderSortValues(tabs, tabOrder) }, - ...patchTerminalTabPinned(state.tabsByWorktree, worktreeId, tabId, false), + ...patchTerminalTabRow(state.tabsByWorktree, tabId, { isPinned: false }), groupsByWorktree: { ...state.groupsByWorktree, [worktreeId]: updateGroup(groups, { ...group, tabOrder }) diff --git a/src/renderer/src/store/slices/terminal-tab-recovery-remount.test.ts b/src/renderer/src/store/slices/terminal-tab-recovery-remount.test.ts index f4b28129251..b1db16ae413 100644 --- a/src/renderer/src/store/slices/terminal-tab-recovery-remount.test.ts +++ b/src/renderer/src/store/slices/terminal-tab-recovery-remount.test.ts @@ -1,5 +1,8 @@ import { describe, expect, it } from 'vitest' import { createTestStore, makeWorktree, seedStore } from './store-test-helpers' +import { isTerminalTabPresent } from './terminal-tab-retirement' +import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' +import { folderWorkspaceKey } from '../../../../shared/workspace-scope' const WORKTREE_ID = 'repo1::/path/wt1' @@ -20,7 +23,7 @@ describe('remountTerminalTabForRecovery', () => { const remounted = store.getState().remountTerminalTabForRecovery(tabId) - expect(remounted).toBe(true) + expect(remounted.remounted).toBe(true) const after = store.getState().tabsByWorktree[WORKTREE_ID].find((tab) => tab.id === tabId) expect(after?.generation ?? 0).toBe((before?.generation ?? 0) + 1) // Recovery is not user interaction — the remount's PTY updates must not @@ -35,7 +38,7 @@ describe('remountTerminalTabForRecovery', () => { store.getState().queueTabStartupCommand(tabId, startup) const before = store.getState().pendingStartupByTabId[tabId] - expect(store.getState().remountTerminalTabForRecovery(tabId)).toBe(true) + expect(store.getState().remountTerminalTabForRecovery(tabId).remounted).toBe(true) const after = store.getState().pendingStartupByTabId[tabId] expect(after).toEqual(before) @@ -58,6 +61,119 @@ describe('remountTerminalTabForRecovery', () => { const store = createTestStore() seedWorktreeWithTab(store) - expect(store.getState().remountTerminalTabForRecovery('missing-tab')).toBe(false) + expect(store.getState().remountTerminalTabForRecovery('missing-tab')).toEqual({ + remounted: false, + declinedBy: 'tab-missing' + }) + }) +}) + +// Crash b5cfc6ca: recovery released its per-tab remount budget from getTab, which +// reads unifiedTabsByWorktree. That index can drop a tab this one still holds, and +// the release then erased the budget each remount had just consumed. +describe('isTerminalTabPresent as the recovery existence check', () => { + it('answers true for a tab remountTerminalTabForRecovery can still remount', () => { + const store = createTestStore() + const tabId = seedWorktreeWithTab(store) + + expect(isTerminalTabPresent(store.getState(), tabId)).toBe(true) + expect(store.getState().remountTerminalTabForRecovery(tabId).remounted).toBe(true) + }) + + it('stays true when the tab is missing from the unified tab index', () => { + const store = createTestStore() + const tabId = seedWorktreeWithTab(store) + store.setState({ unifiedTabsByWorktree: {} }) + + expect(store.getState().getTab(tabId)).toBeNull() + expect(isTerminalTabPresent(store.getState(), tabId)).toBe(true) + }) + + it('answers false once the tab leaves the remount index', () => { + const store = createTestStore() + const tabId = seedWorktreeWithTab(store) + store.setState({ tabsByWorktree: { [WORKTREE_ID]: [] } }) + + expect(isTerminalTabPresent(store.getState(), tabId)).toBe(false) + expect(store.getState().remountTerminalTabForRecovery(tabId).remounted).toBe(false) + }) + + // The budget release still has to fire for a real close, or a closed tab's + // timestamps and pending retry outlive it. + it('answers false after a genuine closeTab', () => { + const store = createTestStore() + const tabId = seedWorktreeWithTab(store) + + store.getState().closeTab(tabId) + + expect(isTerminalTabPresent(store.getState(), tabId)).toBe(false) + }) +}) + +// Not every workspace is a repository checkout. The ledger is keyed to the tab +// ROW and resolved through locateTerminalTab, which scans every bucket in +// tabsByWorktree — so a folder workspace and the floating-terminal bucket must +// behave identically without a single branch for them. The predecessor kept the +// budget in a module map keyed by tabId, and its row patcher made the caller +// name the bucket, which is where a non-worktree key could go wrong. +describe.each([ + ['a repository worktree', WORKTREE_ID], + ['a folder workspace', folderWorkspaceKey('fw-1')], + ['the floating terminal bucket', FLOATING_TERMINAL_WORKTREE_ID] +])('the recovery ledger on %s', (_label, bucketId) => { + function seedBucket(store: ReturnType): string { + seedStore(store, { + worktreesByRepo: { + repo1: [makeWorktree({ id: WORKTREE_ID, repoId: 'repo1', path: '/path/wt1' })] + } + }) + return store.getState().createTab(bucketId).id + } + + const AUTOMATIC = { reason: 'write-stalled', trigger: 'automatic', now: 0 } as const + + it('admits, observes and then refuses the same reason until a new trigger', () => { + const store = createTestStore() + const tabId = seedBucket(store) + const row = (): { recovery?: unknown } | undefined => + store.getState().tabsByWorktree[bucketId]?.find((tab) => tab.id === tabId) + + const first = store.getState().remountTerminalTabForRecovery(tabId, AUTOMATIC) + expect(first.remounted).toBe(true) + // The ledger landed on the row in this bucket, not in a worktree-keyed map. + expect(row()?.recovery).toMatchObject({ outcome: 'pending', reason: 'write-stalled' }) + + // Unsettled blocks the next automatic ask, even past the cooldown. + expect( + store.getState().remountTerminalTabForRecovery(tabId, { ...AUTOMATIC, now: 16_000 }) + ).toEqual({ remounted: false, declinedBy: 'unsettled', retryInMs: 15_000 }) + + if (!first.remounted) { + throw new Error('unreachable: the first remount was admitted') + } + store.getState().settleTerminalTabRecovery(tabId, first.generation, 'failed') + expect(row()?.recovery).toMatchObject({ outcome: 'failed' }) + expect( + store.getState().remountTerminalTabForRecovery(tabId, { ...AUTOMATIC, now: 600_000 }) + ).toEqual({ remounted: false, declinedBy: 'settled-failure' }) + + // The user asking again is the new trigger the refusal waits for. + expect( + store + .getState() + .remountTerminalTabForRecovery(tabId, { ...AUTOMATIC, trigger: 'user', now: 600_000 }) + .remounted + ).toBe(true) + }) + + it('drops the ledger with the row when the tab closes', () => { + const store = createTestStore() + const tabId = seedBucket(store) + store.getState().remountTerminalTabForRecovery(tabId, AUTOMATIC) + + store.getState().closeTab(tabId) + + expect(isTerminalTabPresent(store.getState(), tabId)).toBe(false) + expect(store.getState().tabsByWorktree[bucketId]?.some((tab) => tab.id === tabId)).toBeFalsy() }) }) diff --git a/src/renderer/src/store/slices/terminal-tab-retirement.ts b/src/renderer/src/store/slices/terminal-tab-retirement.ts index b57ac4946fc..80e67824699 100644 --- a/src/renderer/src/store/slices/terminal-tab-retirement.ts +++ b/src/renderer/src/store/slices/terminal-tab-retirement.ts @@ -9,6 +9,7 @@ import { resolveTerminalHostOwnership } from '@/lib/terminal-worktree-route' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' import { isEphemeralSetupTerminalWorktreeId } from '../../../../shared/ephemeral-setup-terminal-worktree-id' import { parseWorkspaceKey } from '../../../../shared/workspace-scope' +import { locateTerminalTab } from '../terminals/terminal-tab-location' export type TerminalTabCloseReason = 'user' | 'cleanup' | 'pty-exit' @@ -131,7 +132,7 @@ export function isTerminalTabPresent( state: Pick, tabId: string ): boolean { - return Object.values(state.tabsByWorktree).some((tabs) => tabs.some((tab) => tab.id === tabId)) + return locateTerminalTab(state.tabsByWorktree, tabId) !== null } export function buildTerminalTabRetirementPlan( diff --git a/src/renderer/src/store/slices/ui-notice-dismissals.test.ts b/src/renderer/src/store/slices/ui-notice-dismissals.test.ts index f17c77c78e3..180f96e427a 100644 --- a/src/renderer/src/store/slices/ui-notice-dismissals.test.ts +++ b/src/renderer/src/store/slices/ui-notice-dismissals.test.ts @@ -280,3 +280,81 @@ describe('createUISlice clearOsc52ClipboardDefaultOnNotice', () => { expect(setUI).toHaveBeenCalledWith({ osc52ClipboardDefaultOnNoticePending: false }) }) }) + +describe('unexpected sign-out dismissal persistence', () => { + it('persists a dismissal once even when effects repeat', () => { + const setUI = vi.fn(() => Promise.resolve()) + vi.stubGlobal('window', { api: { ui: { set: setUI } } }) + const store = createUIStore() + + store.getState().dismissUnexpectedSignoutCard('1.2.3') + store.getState().dismissUnexpectedSignoutCard('1.2.3') + + expect(store.getState().dismissedUnexpectedSignoutVersion).toBe('1.2.3') + expect(setUI).toHaveBeenCalledExactlyOnceWith({ dismissedUnexpectedSignoutVersion: '1.2.3' }) + }) + + it.each([undefined, null, '1.2.2'])( + 'does not re-arm a local dismissal from stale hydration (%s)', + (dismissedUnexpectedSignoutVersion) => { + vi.stubGlobal('window', { api: { ui: { set: vi.fn(() => Promise.resolve()) } } }) + const store = createUIStore() + store.getState().dismissUnexpectedSignoutCard('1.2.3') + + store.getState().hydratePersistedUI(makePersistedUI({ dismissedUnexpectedSignoutVersion })) + + expect(store.getState().unexpectedSignoutDismissedVersions).toContain('1.2.3') + } + ) + + it('defaults legacy profiles and restores dismissal on reopen', () => { + const store = createUIStore() + expect(store.getState().dismissedUnexpectedSignoutVersion).toBeNull() + store + .getState() + .hydratePersistedUI( + makePersistedUI({ dismissedUnexpectedSignoutVersion: undefined }), + 'startup' + ) + expect(store.getState().dismissedUnexpectedSignoutVersion).toBeNull() + const reopened = createUIStore() + reopened + .getState() + .hydratePersistedUI( + makePersistedUI({ dismissedUnexpectedSignoutVersion: '1.2.3' }), + 'startup' + ) + expect(reopened.getState().dismissedUnexpectedSignoutVersion).toBe('1.2.3') + }) + + it('accepts another window dismissal after hydrating an older version', () => { + const store = createUIStore() + store + .getState() + .hydratePersistedUI( + makePersistedUI({ dismissedUnexpectedSignoutVersion: '1.2.2' }), + 'startup' + ) + store + .getState() + .hydratePersistedUI(makePersistedUI({ dismissedUnexpectedSignoutVersion: '1.2.3' })) + expect(store.getState().dismissedUnexpectedSignoutVersion).toBe('1.2.3') + }) +}) + +describe('unexpected sign-out hydrated dismissal history', () => { + it.each([undefined, null, '1.2.2', '1.2.4'])( + 'retains an observed dismissal after a different version sync (%s)', + (dismissedUnexpectedSignoutVersion) => { + const store = createUIStore() + store + .getState() + .hydratePersistedUI( + makePersistedUI({ dismissedUnexpectedSignoutVersion: '1.2.3' }), + 'startup' + ) + store.getState().hydratePersistedUI(makePersistedUI({ dismissedUnexpectedSignoutVersion })) + expect(store.getState().unexpectedSignoutDismissedVersions).toContain('1.2.3') + } + ) +}) diff --git a/src/renderer/src/store/slices/ui/ui-slice-contract-preferences.ts b/src/renderer/src/store/slices/ui/ui-slice-contract-preferences.ts index dff5f50c7e3..d913f998d2c 100644 --- a/src/renderer/src/store/slices/ui/ui-slice-contract-preferences.ts +++ b/src/renderer/src/store/slices/ui/ui-slice-contract-preferences.ts @@ -175,6 +175,10 @@ export type UISlicePersistence = { dismissedUpdateVersion: string | null dismissUpdate: (versionOverride?: string) => void clearDismissedUpdateVersion: () => void + /** App version that dismissed the unexpected-sign-out card; null = never dismissed. */ + dismissedUnexpectedSignoutVersion: string | null + unexpectedSignoutDismissedVersions: string[] + dismissUnexpectedSignoutCard: (version: string) => void /** Dev-only channel override; null follows the running build's own channel. */ releaseChannelOverride: ReleaseChannel | null setReleaseChannelOverride: (channel: ReleaseChannel | null) => void diff --git a/src/renderer/src/store/slices/ui/ui-slice-hydration-actions.ts b/src/renderer/src/store/slices/ui/ui-slice-hydration-actions.ts index a5daf8a500d..6ca8d702bd3 100644 --- a/src/renderer/src/store/slices/ui/ui-slice-hydration-actions.ts +++ b/src/renderer/src/store/slices/ui/ui-slice-hydration-actions.ts @@ -52,6 +52,7 @@ import { } from '../persisted-ui-write-baseline' import { hydrateTrustedOrcaHooks, + hydrateUnexpectedSignoutDismissal, normalizeHydratedVisibleWorkspaceHostIds, preserveStringArrayIdentity, sanitizeHydratedActiveView, @@ -226,6 +227,7 @@ export function createUiHydrationActions(set: UISliceSet, _get: UISliceGet): Par return DEFAULT_PET_ID })(), dismissedUpdateVersion: ui.dismissedUpdateVersion ?? null, + ...hydrateUnexpectedSignoutDismissal(s, ui.dismissedUnexpectedSignoutVersion), // Why: a persisted value from a build that knew a different channel set // would otherwise survive as-is; activeChannel only falls back on null, // so an unknown string reaches listBuilds and the segmented control. diff --git a/src/renderer/src/store/slices/ui/ui-slice-hydration-sanitizers.ts b/src/renderer/src/store/slices/ui/ui-slice-hydration-sanitizers.ts index bfed25a75cc..9737a575f06 100644 --- a/src/renderer/src/store/slices/ui/ui-slice-hydration-sanitizers.ts +++ b/src/renderer/src/store/slices/ui/ui-slice-hydration-sanitizers.ts @@ -238,3 +238,16 @@ export function migrateStatusBarItems(items: readonly string[] | undefined): Sta } return out as StatusBarItem[] } + +export function hydrateUnexpectedSignoutDismissal( + state: Pick, + version: string | null | undefined +): Pick { + const observed = state.unexpectedSignoutDismissedVersions + return { + dismissedUnexpectedSignoutVersion: version ?? null, + // A later sync must never undo any dismissal observed in this session. + unexpectedSignoutDismissedVersions: + typeof version === 'string' && !observed.includes(version) ? [...observed, version] : observed + } +} diff --git a/src/renderer/src/store/slices/ui/ui-slice-update-actions.ts b/src/renderer/src/store/slices/ui/ui-slice-update-actions.ts index e4beadf4c6c..942ff9610a5 100644 --- a/src/renderer/src/store/slices/ui/ui-slice-update-actions.ts +++ b/src/renderer/src/store/slices/ui/ui-slice-update-actions.ts @@ -43,6 +43,18 @@ export function createUiUpdateActions(set: UISliceSet, get: UISliceGet): Partial updateChangelog: null, updateUserInitiatedCycle: false, dismissedUpdateVersion: null, + dismissedUnexpectedSignoutVersion: null, + unexpectedSignoutDismissedVersions: [], + dismissUnexpectedSignoutCard: (version) => { + if (get().unexpectedSignoutDismissedVersions.includes(version)) { + return + } + set({ + dismissedUnexpectedSignoutVersion: version, + unexpectedSignoutDismissedVersions: [...get().unexpectedSignoutDismissedVersions, version] + }) + void window.api.ui.set({ dismissedUnexpectedSignoutVersion: version }).catch(console.error) + }, clearDismissedUpdateVersion: () => { set({ dismissedUpdateVersion: null }) }, diff --git a/src/renderer/src/store/slices/worktree-helpers.ts b/src/renderer/src/store/slices/worktree-helpers.ts index 3fa3219fa32..d6d9e9de74f 100644 --- a/src/renderer/src/store/slices/worktree-helpers.ts +++ b/src/renderer/src/store/slices/worktree-helpers.ts @@ -25,6 +25,11 @@ import type { import type { WorktreeRemovalTarget } from '../../../../shared/worktree/removal' import type { TerminalGitHubPRLink } from '../../../../shared/terminal-github-pr-link-detector' import type { ExecutionHostId } from '../../../../shared/execution-host' +import type { TerminalPaneRecoveryOutcome } from '../../../../shared/terminal-tab-types' +import type { + TerminalRecoveryRemountRequest, + TerminalRecoveryRemountResult +} from '../terminals/terminal-tab-recovery-ledger' import type { RemoveWorktreeOptions } from './worktree-removal-options' import type { HostQualifiedDetectedWorktreeResult, @@ -310,9 +315,24 @@ export type WorktreeSlice = { * TerminalPane unmounts, detaches (preserving a live PTY), and remounts with * a fresh xterm that reattaches and replays. Used by terminal-pane-recovery * when a pane's write pipeline is certified dead or its input is - * undeliverable while the PTY is alive. Returns false when the tab is gone. + * undeliverable while the PTY is alive. + * + * The generation bump and the tab's recovery ledger are written together, so + * the budget cannot outlive — or be released independently of — the row it + * belongs to. Omitting the request marks an external lifecycle remount: it + * skips admission and writes no ledger. */ - remountTerminalTabForRecovery: (tabId: string) => boolean + remountTerminalTabForRecovery: ( + tabId: string, + request?: TerminalRecoveryRemountRequest + ) => TerminalRecoveryRemountResult + /** Record what a mounted pane observed for its recovery attempt. Ignored + * unless `generation` is the row's current, still-pending ledger epoch. */ + settleTerminalTabRecovery: ( + tabId: string, + generation: number, + outcome: Exclude + ) => void setActiveFolderWorkspace: (folderWorkspaceId: string, executionHostId?: ExecutionHostId) => void setRenamingWorktreeId: (request: string | WorktreeRenameRequest | null) => void allWorktrees: () => Worktree[] diff --git a/src/renderer/src/store/slices/worktree-sleep-intent-lifecycle.test.ts b/src/renderer/src/store/slices/worktree-sleep-intent-lifecycle.test.ts new file mode 100644 index 00000000000..8b3c73e2ff1 --- /dev/null +++ b/src/renderer/src/store/slices/worktree-sleep-intent-lifecycle.test.ts @@ -0,0 +1,167 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import * as intent from '@/lib/worktree-sleep-intent' +import { buildWorktreePurgeState } from './worktrees/teardown/worktree-purge-state' +import { createTestStore, makeWorktree, seedStore } from './store-test-helpers' +import { createStoreCascadesMockApi } from './store-cascades-test-harness' + +const { clearWorktreeSleepIntent, hasWorktreeSleepIntent, markWorktreeSleepIntent } = intent +const WORKTREE_ID = 'repo1::/path/wt1' +const FOLDER_KEY = 'folder:folder-1' + +createStoreCascadesMockApi() + +function seedWorktree(store: ReturnType): void { + seedStore(store, { + worktreesByRepo: { + repo1: [makeWorktree({ id: WORKTREE_ID, repoId: 'repo1', path: '/path/wt1' })] + }, + refreshGitHubForWorktree: vi.fn(), + refreshGitHubForWorktreeIfStale: vi.fn() + }) +} + +// Why this suite exists: the sleep marker outlives teardown so mounted panes stay cold +// (#10205). Every route that makes a workspace awake again must release it, or the +// workspace is stuck cold and its PTY exits stop counting as activity. +describe('worktree sleep intent lifecycle', () => { + beforeEach(() => { + clearWorktreeSleepIntent(WORKTREE_ID) + clearWorktreeSleepIntent(FOLDER_KEY) + }) + + it('is released by activating the worktree', () => { + const store = createTestStore() + seedWorktree(store) + markWorktreeSleepIntent(WORKTREE_ID) + + store.getState().setActiveWorktree(WORKTREE_ID) + + expect(hasWorktreeSleepIntent(WORKTREE_ID)).toBe(false) + }) + + it('survives the sleep flow clearing the active selection', () => { + const store = createTestStore() + seedWorktree(store) + markWorktreeSleepIntent(WORKTREE_ID) + + store.getState().setActiveWorktree(null) + + expect(hasWorktreeSleepIntent(WORKTREE_ID)).toBe(true) + }) + + it('is released by activating a folder workspace', () => { + const store = createTestStore() + store.setState({ + folderWorkspaces: [ + { + id: 'folder-1', + projectGroupId: 'group-1', + name: 'Folder', + folderPath: '/folder', + executionHostId: 'local', + linkedTask: null, + comment: '', + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0, + createdAt: 1, + updatedAt: 1 + } + ] + }) + markWorktreeSleepIntent(FOLDER_KEY) + + store.getState().setActiveFolderWorkspace('folder-1') + + expect(hasWorktreeSleepIntent(FOLDER_KEY)).toBe(false) + }) + + it('is released when any PTY binds to a tab in the worktree', () => { + const store = createTestStore() + seedWorktree(store) + const tab = store.getState().createTab(WORKTREE_ID, undefined, undefined, { activate: false }) + markWorktreeSleepIntent(WORKTREE_ID) + + store.getState().updateTabPtyId(tab.id, 'pty-cli-created') + + expect(hasWorktreeSleepIntent(WORKTREE_ID)).toBe(false) + }) + + it('is released when a tab is created with a live PTY', () => { + const store = createTestStore() + seedWorktree(store) + markWorktreeSleepIntent(WORKTREE_ID) + + store.getState().createTab(WORKTREE_ID, undefined, undefined, { + activate: false, + initialPtyId: 'pty-cli-created' + }) + + expect(hasWorktreeSleepIntent(WORKTREE_ID)).toBe(false) + }) + + it('notifies wake listeners once and only on a real clear', () => { + const { onWorktreeSleepIntentCleared } = intent + const woke = vi.fn() + markWorktreeSleepIntent(WORKTREE_ID) + const unsubscribe = onWorktreeSleepIntentCleared(WORKTREE_ID, woke) + + clearWorktreeSleepIntent('repo1::/path/other') + expect(woke).not.toHaveBeenCalled() + clearWorktreeSleepIntent(WORKTREE_ID) + clearWorktreeSleepIntent(WORKTREE_ID) + expect(woke).toHaveBeenCalledTimes(1) + + markWorktreeSleepIntent(WORKTREE_ID) + clearWorktreeSleepIntent(WORKTREE_ID) + expect(woke).toHaveBeenCalledTimes(1) + unsubscribe() + }) + + it('ignores a PTY bind that lands while the sleep teardown is in flight', async () => { + const store = createTestStore() + seedWorktree(store) + const tab = store.getState().createTab(WORKTREE_ID, undefined, undefined, { activate: false }) + markWorktreeSleepIntent(WORKTREE_ID) + const woke = vi.fn() + intent.onWorktreeSleepIntentCleared(WORKTREE_ID, woke) + + await intent.withWorktreeSleepTeardown(WORKTREE_ID, async () => { + store.getState().updateTabPtyId(tab.id, 'pty-late-spawn') + }) + + expect(hasWorktreeSleepIntent(WORKTREE_ID)).toBe(true) + expect(woke).not.toHaveBeenCalled() + store.getState().updateTabPtyId(tab.id, 'pty-after-teardown') + expect(hasWorktreeSleepIntent(WORKTREE_ID)).toBe(false) + }) + + it('keeps notifying siblings when one wake listener throws', () => { + const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + const woke = vi.fn() + markWorktreeSleepIntent(WORKTREE_ID) + intent.onWorktreeSleepIntentCleared(WORKTREE_ID, () => { + throw new Error('boom') + }) + intent.onWorktreeSleepIntentCleared(WORKTREE_ID, woke) + + expect(() => clearWorktreeSleepIntent(WORKTREE_ID)).not.toThrow() + expect(woke).toHaveBeenCalledTimes(1) + errorSpy.mockRestore() + }) + + it('is forgotten without waking panes when the worktree is purged', () => { + const store = createTestStore() + seedWorktree(store) + markWorktreeSleepIntent(WORKTREE_ID) + const woke = vi.fn() + intent.onWorktreeSleepIntentCleared(WORKTREE_ID, woke) + + store.setState(buildWorktreePurgeState(store.getState(), [WORKTREE_ID])) + + expect(hasWorktreeSleepIntent(WORKTREE_ID)).toBe(false) + expect(woke).not.toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/store/slices/worktrees.ts b/src/renderer/src/store/slices/worktrees.ts index 606a5a26857..330d27e7bb2 100644 --- a/src/renderer/src/store/slices/worktrees.ts +++ b/src/renderer/src/store/slices/worktrees.ts @@ -52,6 +52,7 @@ import { createGetKnownWorktreeById, createPurgeWorktreeTerminalState, createRemountTerminalTabForRecovery, + createSettleTerminalTabRecovery, createSetRenamingWorktreeId } from './worktrees/session/worktree-slice-lookups' import { createPurgeStaleRuntimeHostState } from './worktrees/teardown/purge-stale-runtime-host-state' @@ -108,6 +109,7 @@ export const createWorktreeSlice: StateCreator seedActiveWorktreeLastVisitedIfMissing: createSeedActiveWorktreeLastVisitedIfMissing(set, get), setRenamingWorktreeId: createSetRenamingWorktreeId(set, get), remountTerminalTabForRecovery: createRemountTerminalTabForRecovery(set, get), + settleTerminalTabRecovery: createSettleTerminalTabRecovery(set, get), setActiveWorktree: createSetActiveWorktree(set, get), setActiveFolderWorkspace: createSetActiveFolderWorkspace(set, get), allWorktrees: createAllWorktrees(set, get), diff --git a/src/renderer/src/store/slices/worktrees/session/set-active-folder-workspace.ts b/src/renderer/src/store/slices/worktrees/session/set-active-folder-workspace.ts index d2b5af79114..b89da1ace44 100644 --- a/src/renderer/src/store/slices/worktrees/session/set-active-folder-workspace.ts +++ b/src/renderer/src/store/slices/worktrees/session/set-active-folder-workspace.ts @@ -9,6 +9,7 @@ import { } from '../listing/detected-worktree-meta' import { shouldDeferActivationTerminalPrep } from './activation-terminal-prep' import { deriveActiveSurfaceForWorktree } from '../../tabs/tabs-surface' +import { clearWorktreeSleepIntent } from '@/lib/worktree-sleep-intent' export function createSetActiveFolderWorkspace( set: WorktreeSliceSet, @@ -62,6 +63,8 @@ export function createSetActiveFolderWorkspace( : s.folderWorkspaces } }) + // Why: cleared after the set() so a waiting pane connects against the activated state. + clearWorktreeSleepIntent(workspaceKey) if (workspace.isUnread) { void get().updateFolderWorkspace( folderWorkspaceId, diff --git a/src/renderer/src/store/slices/worktrees/session/set-active-worktree.ts b/src/renderer/src/store/slices/worktrees/session/set-active-worktree.ts index b4ec0b0f99a..31c7e8bbb37 100644 --- a/src/renderer/src/store/slices/worktrees/session/set-active-worktree.ts +++ b/src/renderer/src/store/slices/worktrees/session/set-active-worktree.ts @@ -24,6 +24,7 @@ import { } from '../listing/detected-worktree-meta' import { persistPassiveWorktreeMetaForOwner } from '../listing/worktree-owner-settings' import { resolveActivatedWorktreeSurface } from './active-worktree-surface' +import { clearWorktreeSleepIntent } from '@/lib/worktree-sleep-intent' import { pendingActivationTerminalPrepCancels, shouldDeferActivationTerminalPrep @@ -206,6 +207,11 @@ export function createSetActiveWorktree( } }) + // Why: any activation is an explicit wake (null is the sleep flow clearing selection). + // Cleared after the set() above so a pane still waiting on the marker connects once, + // in the remounted generation, instead of connecting and then being remounted. + clearWorktreeSleepIntent(worktreeId) + if (worktreeId && shouldPrepareTerminalTabs) { const prepareTerminalTabs = (): void => { pendingActivationTerminalPrepCancels.delete(worktreeId) diff --git a/src/renderer/src/store/slices/worktrees/session/worktree-slice-lookups.ts b/src/renderer/src/store/slices/worktrees/session/worktree-slice-lookups.ts index c6fd3143b17..78e0e397bca 100644 --- a/src/renderer/src/store/slices/worktrees/session/worktree-slice-lookups.ts +++ b/src/renderer/src/store/slices/worktrees/session/worktree-slice-lookups.ts @@ -4,6 +4,16 @@ import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../../../shared/constant import { getTerminalActivationSpawnSuppression } from '../../terminal-activation-spawn-suppression' import { findKnownWorktreeById } from '../listing/detected-worktree-meta' import { buildWorktreePurgeState } from '../teardown/worktree-purge-state' +import { locateTerminalTab } from '../../../terminals/terminal-tab-location' +import { + admitTerminalRecoveryRemount, + nextTerminalRecoveryLedger, + settledTerminalRecoveryLedger +} from '../../../terminals/terminal-tab-recovery-ledger' +import type { + TerminalRecoveryRemountRequest, + TerminalRecoveryRemountResult +} from '../../../terminals/terminal-tab-recovery-ledger' export function createSetRenamingWorktreeId( set: WorktreeSliceSet, @@ -20,47 +30,97 @@ export function createRemountTerminalTabForRecovery( set: WorktreeSliceSet, _get: WorktreeSliceGet ): WorktreeSlice['remountTerminalTabForRecovery'] { - return (tabId) => { - let remounted = false + return (tabId, request) => { + const remountRequest: TerminalRecoveryRemountRequest = request ?? { + // The lifetime bridge's host-hydration remount is an external trigger: it + // is not a heal attempt, so it neither consumes nor consults the ledger. + reason: 'reattach-unverifiable', + trigger: 'external', + now: Date.now() + } + let result: TerminalRecoveryRemountResult = { + remounted: false, + declinedBy: 'tab-missing' + } set((s) => { - for (const [worktreeId, tabs] of Object.entries(s.tabsByWorktree)) { - const index = tabs.findIndex((tab) => tab.id === tabId) - if (index === -1) { - continue - } - const tab = tabs[index] - const nextTabs = tabs.slice() - const pendingStartup = s.pendingStartupByTabId[tabId] - nextTabs[index] = { - ...tab, - // Why: bump generation to remount a pane whose renderer died while its PTY stayed alive, so it reattaches, not spawns. - generation: (tab.generation ?? 0) + 1, - // Why: recovery isn't a user interaction — suppress its PTY updates from reshuffling Recent, like activation remounts. - pendingActivationSpawn: getTerminalActivationSpawnSuppression( - s.terminalLayoutsByTabId[tab.id] - ) - } - remounted = true - return { - tabsByWorktree: { - ...s.tabsByWorktree, - [worktreeId]: nextTabs - }, - ...(pendingStartup - ? { - // Why: a remounted pane must own a distinct one-shot startup record so a stale - // pane cannot consume the successor's command during teardown. - pendingStartupByTabId: { - ...s.pendingStartupByTabId, - [tabId]: { ...pendingStartup } - } - } - : {}) + const location = locateTerminalTab(s.tabsByWorktree, tabId) + // Why re-admit inside the write: the caller's read happened before an + // async liveness probe, and a concurrent detector may have consumed the + // budget across it. Locating the row and spending its budget is one step. + const admission = admitTerminalRecoveryRemount(location?.tab, remountRequest) + if (!location || !admission.admitted) { + if (admission.admitted) { + result = { remounted: false, declinedBy: 'tab-missing' } + } else { + const { admitted: _admitted, ...decline } = admission + result = { remounted: false, ...decline } } + return {} + } + const { worktreeId, index, tab } = location + const nextTabs = s.tabsByWorktree[worktreeId].slice() + const pendingStartup = s.pendingStartupByTabId[tabId] + // Why: bump generation to remount a pane whose renderer died while its PTY stayed alive, so it reattaches, not spawns. + const nextTabGeneration = (tab.generation ?? 0) + 1 + // An external remount is not a heal attempt, so it writes no ledger. The + // generation bump alone supersedes any ledger already on the row, which + // is exactly right: an external remount IS a new trigger. + const recovery = + remountRequest.trigger === 'external' + ? tab.recovery + : nextTerminalRecoveryLedger(tab, remountRequest, nextTabGeneration) + nextTabs[index] = { + ...tab, + generation: nextTabGeneration, + // Why: recovery isn't a user interaction — suppress its PTY updates from reshuffling Recent, like activation remounts. + pendingActivationSpawn: getTerminalActivationSpawnSuppression( + s.terminalLayoutsByTabId[tab.id] + ), + // The remount and the budget it spends are one write, so no disposal, + // release path or index drift can undo half of it (crash b5cfc6ca). + ...(recovery ? { recovery } : {}) + } + result = { remounted: true, generation: recovery?.generation ?? 0 } + return { + tabsByWorktree: { + ...s.tabsByWorktree, + [worktreeId]: nextTabs + }, + ...(pendingStartup + ? { + // Why: a remounted pane must own a distinct one-shot startup record so a stale + // pane cannot consume the successor's command during teardown. + pendingStartupByTabId: { + ...s.pendingStartupByTabId, + [tabId]: { ...pendingStartup } + } + } + : {}) } - return {} }) - return remounted + return result + } +} + +export function createSettleTerminalTabRecovery( + set: WorktreeSliceSet, + _get: WorktreeSliceGet +): WorktreeSlice['settleTerminalTabRecovery'] { + return (tabId, generation, outcome) => { + set((s) => { + const location = locateTerminalTab(s.tabsByWorktree, tabId) + if (!location) { + return {} + } + const { worktreeId, index, tab } = location + const recovery = settledTerminalRecoveryLedger(tab, generation, outcome) + if (!recovery) { + return {} + } + const nextTabs = s.tabsByWorktree[worktreeId].slice() + nextTabs[index] = { ...tab, recovery } + return { tabsByWorktree: { ...s.tabsByWorktree, [worktreeId]: nextTabs } } + }) } } diff --git a/src/renderer/src/store/slices/worktrees/teardown/remove-worktree.ts b/src/renderer/src/store/slices/worktrees/teardown/remove-worktree.ts index 075172ddce1..a6a9c87d838 100644 --- a/src/renderer/src/store/slices/worktrees/teardown/remove-worktree.ts +++ b/src/renderer/src/store/slices/worktrees/teardown/remove-worktree.ts @@ -6,6 +6,7 @@ import { parseExecutionHostId } from '../../../../../../shared/execution-host' import { ensureHooksConfirmed } from '@/lib/ensure-hooks-confirmed' import { getActiveRuntimeTarget } from '../../../../runtime/runtime-rpc-client' import { forgetHugeRepoWarningDismissalsForWorktrees } from '@/lib/source-control-huge-repo-warning-dismissals' +import { forgetWorktreeSleepIntent } from '@/lib/worktree-sleep-intent' import { showPreservedBranchToast } from '@/components/sidebar/preserved-branch-toast' import { resolveWorktreeOperationRouteResult, @@ -222,6 +223,7 @@ export function createRemoveWorktree( // Why: invalidate stale probes once deletion is authoritative, so an old toast can't mutate a same-path replacement. forgetHugeRepoWarningDismissalsForWorktrees([worktreeId]) + forgetWorktreeSleepIntent(worktreeId) // Why: forget-local is legal while the host is unreachable, so record the removal here too — otherwise an // in-flight metadata read that snapshotted this row re-appends it, and disconnected polls never drop it. if (hostId && parseExecutionHostId(hostId)?.kind === 'ssh') { diff --git a/src/renderer/src/store/slices/worktrees/teardown/worktree-purge-state.ts b/src/renderer/src/store/slices/worktrees/teardown/worktree-purge-state.ts index 78a57da7955..e2f6e5945fe 100644 --- a/src/renderer/src/store/slices/worktrees/teardown/worktree-purge-state.ts +++ b/src/renderer/src/store/slices/worktrees/teardown/worktree-purge-state.ts @@ -8,6 +8,7 @@ import { createWorktreePurgeOmitters } from './worktree-purge-omitters' import { removeDeleteStatesForWorktreeIds } from './worktree-delete-state' import { removeWorktreeVisitEntriesForTargets } from '@/lib/worktree-visit-recency' import { forgetAmbiguousOwnerWarnings } from '../listing/worktree-owner-settings' +import { forgetWorktreeSleepIntent } from '@/lib/worktree-sleep-intent' export function buildWorktreePurgeState( s: AppState, @@ -18,6 +19,10 @@ export function buildWorktreePurgeState( ) const worktreeIdSet = new Set(normalizedTargets.map((target) => target.id)) pruneHostedReviewLinkMutationGenerations(worktreeIdSet) + // Why: ids are repo::path, so a worktree recreated at the same path must not inherit a stale sleep. + for (const id of worktreeIdSet) { + forgetWorktreeSleepIntent(id) + } // Why: every authoritative and explicit purge converges here, so a deleted path can't inherit stale UI state. forgetHugeRepoWarningDismissalsForWorktrees(worktreeIdSet) forgetAmbiguousOwnerWarnings(worktreeIdSet) diff --git a/src/renderer/src/store/terminals/terminal-pty-bindings.ts b/src/renderer/src/store/terminals/terminal-pty-bindings.ts index 2e0397aff45..499ea63e8de 100644 --- a/src/renderer/src/store/terminals/terminal-pty-bindings.ts +++ b/src/renderer/src/store/terminals/terminal-pty-bindings.ts @@ -9,6 +9,7 @@ import { isRemoteRuntimePtyId } from './terminal-pty-identities' import { omitUnverifiedPtyLossTabIds } from './terminal-unverified-pty-loss' +import { clearWorktreeSleepIntent } from '@/lib/worktree-sleep-intent' import { omitDisownedPtyIds } from './terminal-disowned-pty-sources' export function createTerminalPtyBindingActions( @@ -275,6 +276,8 @@ export function createTerminalPtyBindingActions( ...(shouldBumpSortEpoch ? { sortEpoch: s.sortEpoch + 1 } : {}) } }) + // Why: a bound PTY means the workspace is awake by any route (CLI, automation, client wake), not only activation. + clearWorktreeSleepIntent(worktreeId) // Why: activation spawns come from clicking a worktree, not work in it — skip the lastActivityAt stamp and sortEpoch bump; other spawn reasons still bump. if (worktreeId && !wasActivationSpawn && !isRemoteRuntimeMirror) { get().bumpWorktreeActivity(worktreeId) diff --git a/src/renderer/src/store/terminals/terminal-tab-creation.ts b/src/renderer/src/store/terminals/terminal-tab-creation.ts index 11f9d1d2a59..83310850475 100644 --- a/src/renderer/src/store/terminals/terminal-tab-creation.ts +++ b/src/renderer/src/store/terminals/terminal-tab-creation.ts @@ -1,3 +1,4 @@ +import { clearWorktreeSleepIntent } from '@/lib/worktree-sleep-intent' import type { TerminalTab } from '../../../../shared/terminal-tab-types' import { isValidHostTerminalTabId } from '../../../../shared/terminal-tab-id' import { emptyLayoutSnapshot, singlePaneLayoutSnapshot } from '../slices/terminal-helpers' @@ -271,6 +272,10 @@ export function createTerminalTabCreationActions( } } }) + if (options?.initialPtyId) { + // Why: a tab born with a live PTY (CLI/runtime create) wakes the workspace like any other bind. + clearWorktreeSleepIntent(worktreeId) + } const shouldRecordInteraction = options?.recordInteraction ?? (!options?.pendingActivationSpawn && !options?.initialPtyId) if (shouldRecordInteraction) { diff --git a/src/renderer/src/store/terminals/terminal-tab-location.ts b/src/renderer/src/store/terminals/terminal-tab-location.ts new file mode 100644 index 00000000000..893d52f3ef0 --- /dev/null +++ b/src/renderer/src/store/terminals/terminal-tab-location.ts @@ -0,0 +1,20 @@ +import type { TerminalTab } from '../../../../shared/terminal-tab-types' + +/** + * The one scan over `tabsByWorktree`. Recovery's remount, its budget release + * and its native-chat guard must all resolve a tab through this: answering + * from a different index (getTab's `unifiedTabsByWorktree`) made every remount + * erase the budget it had just consumed, and the cap never held (crash b5cfc6ca). + */ +export function locateTerminalTab( + tabsByWorktree: Readonly>, + tabId: string +): { worktreeId: string; index: number; tab: TerminalTab } | null { + for (const [worktreeId, tabs] of Object.entries(tabsByWorktree)) { + const index = tabs.findIndex((candidate) => candidate.id === tabId) + if (index !== -1) { + return { worktreeId, index, tab: tabs[index] } + } + } + return null +} diff --git a/src/renderer/src/store/terminals/terminal-tab-recovery-ledger.ts b/src/renderer/src/store/terminals/terminal-tab-recovery-ledger.ts new file mode 100644 index 00000000000..b06b6de5d30 --- /dev/null +++ b/src/renderer/src/store/terminals/terminal-tab-recovery-ledger.ts @@ -0,0 +1,218 @@ +import { DIRECT_SSH_PANE_RETRY_SETTLEMENT_TIMEOUT_MS } from '@/components/terminal-pane/pty-connection/pty-connect-limits' +import type { + TerminalPaneRecoveryOutcome, + TerminalPaneRecoveryReason, + TerminalTab, + TerminalTabRecoveryLedger +} from '../../../../shared/terminal-tab-types' + +// Why this module exists: recovery's budget used to live in module-level Maps +// keyed by tabId. Anything keyed outside the row needs a release path, and the +// release fired on every remount-driven pane disposal — so each remount erased +// the budget it had just consumed and the cap never held (crash b5cfc6ca). +// The ledger now lives on the row, so "the budget released itself" has no +// expression: reading the budget IS reading the tab. +// +// The control is not the count. A remount that mounts a pane which fails the +// same way is not evidence that anything changed, so recovery gates on an +// OBSERVED outcome, borrowing the direct-SSH pane retry vocabulary +// (DirectSshPaneRetryResult): an attempt that has not settled blocks the next +// one, and a settled failure refuses the same reason until a new trigger. + +// Backstop only — a breadcrumb-emitting ceiling for a loop the outcome gate +// somehow failed to catch. The outcome gate is what stops a storm. +export const MAX_RECOVERIES_PER_WINDOW = 3 +export const RECOVERY_WINDOW_MS = 5 * 60_000 +// Why a cooldown exists: one incident can trip several detectors (stall watch, +// replay guard, input path) within seconds; the first remount fixes all of +// them, the rest must coalesce instead of re-remounting mid-reattach. +export const RECOVERY_COOLDOWN_MS = 15_000 +// Why reuse the direct-SSH settlement timeout: the same 31s bound already +// decides when a pane's attach attempt has stopped being in flight. A 'pending' +// ledger older than that describes a pane that never reported, not one still +// working, so it must stop blocking rather than wedge recovery forever. +export const RECOVERY_SETTLEMENT_TIMEOUT_MS = DIRECT_SSH_PANE_RETRY_SETTLEMENT_TIMEOUT_MS + +/** Why a request exists at all. Only 'automatic' is subject to the + * settled-failure refusal: a user pressing Retry, or an external lifecycle + * remount, IS the new trigger the refusal is waiting for. */ +export type TerminalRecoveryTrigger = 'automatic' | 'user' | 'external' + +export type TerminalRecoveryRemountRequest = { + reason: TerminalPaneRecoveryReason + trigger: TerminalRecoveryTrigger + /** The recovery epoch the requesting pane captured, when it has one. */ + generation?: number + now: number +} + +export type TerminalRecoveryDecline = + | { declinedBy: 'tab-missing' } + | { declinedBy: 'stale-generation' } + | { declinedBy: 'settled-failure' } + | { declinedBy: 'window-cap'; retryInMs: number } + | { declinedBy: 'unsettled'; retryInMs: number } + | { declinedBy: 'cooldown'; retryInMs: number } + +export type TerminalRecoveryAdmission = + | { admitted: true } + | ({ admitted: false } & TerminalRecoveryDecline) + +export type TerminalRecoveryRemountResult = + /** `generation` is the ledger epoch the remounted pane will capture. */ + { remounted: true; generation: number } | ({ remounted: false } & TerminalRecoveryDecline) + +const ADMITTED: TerminalRecoveryAdmission = { admitted: true } + +function recentAttempts(ledger: TerminalTabRecoveryLedger, now: number): number[] { + return ledger.attemptedAt.filter((at) => now - at < RECOVERY_WINDOW_MS) +} + +/** True once the ledger describes an attempt nothing can still settle: the row + * moved to a generation this ledger never saw (authority change, SSH pane + * retry, activation respawn, external remount). Derived, so no writer can + * forget to mark it — and none can mark it wrongly either. */ +function isSupersededLedger(tab: TerminalTab, ledger: TerminalTabRecoveryLedger): boolean { + // Strictly forward: generation only ever increments, so a row that reads + // LOWER is a host-snapshot rebuild that dropped the field, not a new trigger. + // Treating that as one would hand the tab a fresh allowance per snapshot. + return (tab.generation ?? 0) > ledger.tabGeneration +} + +export function readTerminalRecoveryOutcome( + tab: TerminalTab, + now: number +): TerminalPaneRecoveryOutcome | null { + const ledger = tab.recovery + if (!ledger) { + return null + } + if (isSupersededLedger(tab, ledger)) { + return 'superseded' + } + if (ledger.outcome === 'pending' && now - ledger.startedAt >= RECOVERY_SETTLEMENT_TIMEOUT_MS) { + return 'timed-out' + } + return ledger.outcome +} + +/** Narrowed to the one field it reads, so the connect path can pass the row it + * already resolved rather than looking the full TerminalTab up a second time. */ +export function captureTabRecoveryGeneration( + tab: Pick | null | undefined +): number { + return tab?.recovery?.generation ?? 0 +} + +/** + * The single admission decision. Runs read-only to fail a request fast, and + * again inside the store write so a probe's await cannot open a window for two + * panes to both consume the budget. + */ +export function admitTerminalRecoveryRemount( + tab: TerminalTab | null | undefined, + request: TerminalRecoveryRemountRequest +): TerminalRecoveryAdmission { + if (!tab) { + return { admitted: false, declinedBy: 'tab-missing' } + } + const ledger = tab.recovery + if ( + request.generation !== undefined && + request.generation !== captureTabRecoveryGeneration(tab) + ) { + return { admitted: false, declinedBy: 'stale-generation' } + } + if (request.trigger === 'external' || !ledger) { + return ADMITTED + } + const recent = recentAttempts(ledger, request.now) + if (recent.length >= MAX_RECOVERIES_PER_WINDOW) { + // Unconditional: the backstop must survive supersession, or anything that + // bumps tab.generation each cycle would lift the ceiling along with it. + return { + admitted: false, + declinedBy: 'window-cap', + retryInMs: recent[0] + RECOVERY_WINDOW_MS - request.now + } + } + if (request.trigger === 'user') { + // The user asking again IS the new evidence. Only the window cap — the + // backstop against a loop neither side can see — survives it. + return ADMITTED + } + const outcome = readTerminalRecoveryOutcome(tab, request.now) + if (outcome !== 'superseded') { + if (ledger.outcome === 'pending') { + if (outcome === 'pending') { + // Re-requesting under an unsettled attempt is the storm: the remounted + // pane fails the same way and asks again with a freshly captured epoch, + // so an epoch check can never refuse it. Nothing has been observed yet. + return { + admitted: false, + declinedBy: 'unsettled', + retryInMs: ledger.startedAt + RECOVERY_SETTLEMENT_TIMEOUT_MS - request.now + } + } + // Aged past the settlement bound with nobody reporting. Deliberately NOT + // read as an observed failure: a pane kind with no settle path would + // otherwise wedge its tab's recovery forever. The cooldown and the window + // cap bound it instead. + } else if ( + (ledger.outcome === 'failed' || ledger.outcome === 'timed-out') && + ledger.reason === request.reason + ) { + // A pane OBSERVED this reason fail after the last remount. Repeating it + // re-requests exactly the action that just failed with no evidence + // anything changed — wait for a real trigger (generation move, or user). + return { admitted: false, declinedBy: 'settled-failure' } + } + } + const last = recent.at(-1) + if (last !== undefined && request.now - last < RECOVERY_COOLDOWN_MS) { + return { + admitted: false, + declinedBy: 'cooldown', + retryInMs: last + RECOVERY_COOLDOWN_MS - request.now + } + } + return ADMITTED +} + +/** The ledger a remount writes, in the same object as the generation bump. */ +export function nextTerminalRecoveryLedger( + tab: TerminalTab, + request: TerminalRecoveryRemountRequest, + nextTabGeneration: number +): TerminalTabRecoveryLedger { + const previous = tab.recovery + // Carried across supersession on purpose — see the window-cap note above. + const carriedAttempts = previous ? recentAttempts(previous, request.now) : [] + return { + attemptedAt: [...carriedAttempts, request.now], + generation: captureTabRecoveryGeneration(tab) + 1, + outcome: 'pending', + startedAt: request.now, + reason: request.reason, + tabGeneration: nextTabGeneration + } +} + +/** Record what the mounted pane observed. Returns null when this settlement is + * not the current attempt's, so the caller can leave the store untouched. */ +export function settledTerminalRecoveryLedger( + tab: TerminalTab, + generation: number, + outcome: Exclude +): TerminalTabRecoveryLedger | null { + const ledger = tab.recovery + if ( + !ledger || + ledger.generation !== generation || + ledger.outcome !== 'pending' || + isSupersededLedger(tab, ledger) + ) { + return null + } + return { ...ledger, outcome } +} diff --git a/src/renderer/src/web/preload-api/web-notifications-api.ts b/src/renderer/src/web/preload-api/web-notifications-api.ts index 813d694ba82..bf3d525f743 100644 --- a/src/renderer/src/web/preload-api/web-notifications-api.ts +++ b/src/renderer/src/web/preload-api/web-notifications-api.ts @@ -3,6 +3,7 @@ import { getBrowserPlatform } from './web-storage' export function createNotificationsApi(): NonNullable['notifications']> { return { + getDesktopAwayState: async () => undefined, dispatch: () => Promise.resolve({ delivered: false, reason: 'not-supported' }), dismiss: () => Promise.resolve({ dismissed: 0 }), openSystemSettings: () => Promise.resolve(), diff --git a/src/renderer/src/web/preload-api/web-runtime-environments-api.ts b/src/renderer/src/web/preload-api/web-runtime-environments-api.ts index e6ce2fd5a5d..8e9b0ecc245 100644 --- a/src/renderer/src/web/preload-api/web-runtime-environments-api.ts +++ b/src/renderer/src/web/preload-api/web-runtime-environments-api.ts @@ -16,6 +16,9 @@ import { translateHostAccessLinkError } from '@/lib/remote-pairing-copy' import { callEnvironmentEnvelope } from './web-runtime-calls' import { closeActiveRuntimeClients, + subscribeWebRuntimeStatus, + readWebRuntimeStatusSnapshots, + observeWebRuntimeStatus, disconnectActiveRuntimeEnvironment, getClientForEnvironment, manuallyDisconnectedEnvironmentIds, @@ -29,6 +32,8 @@ export function createRuntimeEnvironmentsApi(): NonNullable< Partial['runtimeEnvironments'] > { return { + onStatusChanged: subscribeWebRuntimeStatus, + getStatusSnapshots: async () => readWebRuntimeStatusSnapshots(), list: async () => { const environment = requireActiveEnvironmentOrNull() return environment ? [redactStoredWebRuntimeEnvironment(environment)] : [] @@ -146,6 +151,12 @@ export function createRuntimeEnvironmentsApi(): NonNullable< manuallyDisconnectedEnvironmentIds.clear() closeActiveRuntimeClients() webRuntimeState.activeEnvironment = nextEnvironment + getClientForEnvironment(nextEnvironment).statusOwner?.acceptVerified({ + id: 'status.get', + ok: true, + result: runtimeStatus, + _meta: { runtimeId: runtimeStatus.runtimeId } + }) return { ok: true, environment: redactStoredWebRuntimeEnvironment(nextEnvironment), @@ -173,6 +184,7 @@ export function createRuntimeEnvironmentsApi(): NonNullable< connect: ({ selector, timeoutMs }) => { const environment = resolveEnvironment(selector) manuallyDisconnectedEnvironmentIds.delete(environment.id) + closeActiveRuntimeClients() return callEnvironmentEnvelope( environment.id, 'status.get', @@ -180,8 +192,10 @@ export function createRuntimeEnvironmentsApi(): NonNullable< timeoutMs ) }, - getStatus: ({ selector, timeoutMs }) => - callEnvironmentEnvelope(selector, 'status.get', undefined, timeoutMs), + getStatus: ({ selector, timeoutMs, observeOnly }) => + observeOnly + ? observeWebRuntimeStatus(selector, timeoutMs) + : callEnvironmentEnvelope(selector, 'status.get', undefined, timeoutMs), retryControlConnection: () => Promise.resolve(), prepareBrowserClientHostPlacement: async () => ({ kind: 'server' }), call: ({ selector, method, params, timeoutMs }) => diff --git a/src/renderer/src/web/preload-api/web-runtime-session.ts b/src/renderer/src/web/preload-api/web-runtime-session.ts index 17a19136002..15b6cb63ee7 100644 --- a/src/renderer/src/web/preload-api/web-runtime-session.ts +++ b/src/renderer/src/web/preload-api/web-runtime-session.ts @@ -1,3 +1,7 @@ +import type { + RuntimeHostStatusSnapshot, + RuntimeHostStatusResponse +} from '../../../../shared/runtime-host-status' import type { WorktreeVisibilityDefaults } from '../../../../shared/global-settings-types' import { RuntimeRpcCallQueuePool } from '../../../../shared/runtime-rpc-call-queue' import type { RuntimeRpcResponse } from '../../../../shared/runtime-rpc-envelope' @@ -30,6 +34,43 @@ export const webRuntimeState: { cachedDetectedWorktrees: null } +const statusListeners = new Set<(snapshot: RuntimeHostStatusSnapshot) => void>() +export function subscribeWebRuntimeStatus( + callback: (snapshot: RuntimeHostStatusSnapshot) => void +): () => void { + statusListeners.add(callback) + return () => { + statusListeners.delete(callback) + } +} +export function readWebRuntimeStatusSnapshots(): RuntimeHostStatusSnapshot[] { + const snapshot = webRuntimeState.activeClient?.statusOwner?.read() + return snapshot ? [snapshot] : [] +} +export async function observeWebRuntimeStatus( + selector: string, + timeoutMs?: number +): Promise { + const environment = resolveEnvironment(selector) + if (manuallyDisconnectedEnvironmentIds.has(environment.id)) { + return manuallyDisconnectedResponse(environment) + } + const existing = webRuntimeState.activeClient?.statusOwner + if (existing) { + return existing.refresh({ timeoutMs, observeOnly: true }) + } + const transient = new WebRuntimeClient(getPreferredWebPairingOffer(environment), { + reconnect: false + }) + try { + return (await transient.call('status.get', undefined, { + timeoutMs + })) as RuntimeHostStatusResponse + } finally { + transient.close() + } +} + export const manuallyDisconnectedEnvironmentIds = new Set() export const runtimeCallQueuePool = new RuntimeRpcCallQueuePool() @@ -50,7 +91,18 @@ export function getClientForEnvironment( webRuntimeState.activeClientEnvironmentId !== environment.id ) { webRuntimeState.activeClient?.close() - webRuntimeState.activeClient = new WebRuntimeClient(getPreferredWebPairingOffer(environment)) + webRuntimeState.activeClient = new WebRuntimeClient(getPreferredWebPairingOffer(environment), { + status: { + environmentId: environment.id, + pairingRevision: environment.pairingRevision ?? environment.createdAt, + publish: (snapshot) => { + for (const listener of statusListeners) { + listener(snapshot) + } + }, + verified: (response) => updateEnvironmentFromResponse(environment, response) + } + }) webRuntimeState.activeClientEnvironmentId = environment.id } return webRuntimeState.activeClient diff --git a/src/renderer/src/web/web-runtime-client-export-parity.test.ts b/src/renderer/src/web/web-runtime-client-export-parity.test.ts index 27dce452549..6ba87eaad36 100644 --- a/src/renderer/src/web/web-runtime-client-export-parity.test.ts +++ b/src/renderer/src/web/web-runtime-client-export-parity.test.ts @@ -6,8 +6,13 @@ it('keeps the paired-web client public export surface exact', () => { expectTypeOf().toEqualTypeOf() expectTypeOf().toEqualTypeOf() expectTypeOf>().toEqualTypeOf< - [pairing: WebPairingOffer] + [ + pairing: WebPairingOffer, + options?: ConstructorParameters[1] + ] + >() + expectTypeOf().toEqualTypeOf< + 'call' | 'close' | 'subscribe' | 'statusOwner' >() - expectTypeOf().toEqualTypeOf<'call' | 'close' | 'subscribe'>() expect(Object.keys(WebClient)).toEqual(['WebRuntimeClient']) }) diff --git a/src/renderer/src/web/web-runtime-client-timeout-budget.test.ts b/src/renderer/src/web/web-runtime-client-timeout-budget.test.ts index 71568adc4da..95417748271 100644 --- a/src/renderer/src/web/web-runtime-client-timeout-budget.test.ts +++ b/src/renderer/src/web/web-runtime-client-timeout-budget.test.ts @@ -70,7 +70,7 @@ describe('WebRuntimeClient timeout budget', () => { await vi.advanceTimersByTimeAsync(60_000) expect(settled).toBe(false) - expect(waitForConnected).toHaveBeenCalledWith(25) + expect(waitForConnected).toHaveBeenCalledWith(25, undefined) resolveConnection() await Promise.resolve() diff --git a/src/renderer/src/web/web-runtime-client.ts b/src/renderer/src/web/web-runtime-client.ts index 7bc756ca0c0..8a3b944f701 100644 --- a/src/renderer/src/web/web-runtime-client.ts +++ b/src/renderer/src/web/web-runtime-client.ts @@ -1,3 +1,8 @@ +import { RuntimeHostStatusOwner } from '../../../shared/runtime-host-status-owner' +import type { + RuntimeHostStatusSnapshot, + RuntimeHostStatusResponse +} from '../../../shared/runtime-host-status' import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' import { WebRuntimeConnectionTransport } from './web-runtime-connection-transport' import { subscribeWebRuntimeFileWatch } from './web-runtime-file-watch-subscription' @@ -24,11 +29,62 @@ export class WebRuntimeClient { private readonly fileWatchTeardownRetries = new Map Promise>>() private readonly childClients = new Set() - constructor(private readonly pairing: WebPairingOffer) { - this.transport = new WebRuntimeConnectionTransport(pairing, { - now: () => this.now(), - isDocumentVisible: () => this.isDocumentVisible() - }) + readonly statusOwner?: RuntimeHostStatusOwner + + constructor( + private readonly pairing: WebPairingOffer, + options: { + reconnect?: boolean + status?: { + environmentId: string + pairingRevision: number + publish: (snapshot: RuntimeHostStatusSnapshot) => void + verified: (response: RuntimeHostStatusResponse) => void + } + } = {} + ) { + this.transport = new WebRuntimeConnectionTransport( + pairing, + { + now: () => this.now(), + isDocumentVisible: () => this.isDocumentVisible() + }, + { + reconnect: options.reconnect, + onStateChanged: (state) => { + if (state === 'auth-failed') { + this.statusOwner?.authenticationRejected() + } + this.statusOwner?.connectionChanged( + state === 'connected' + ? 'ready' + : state === 'disconnected' || state === 'auth-failed' + ? 'disconnected' + : 'connecting' + ) + } + } + ) + if (options.status) { + const status = options.status + this.statusOwner = new RuntimeHostStatusOwner({ + ...status, + persistent: true, + request: (signal) => + this.transport.call('status.get', undefined, { + timeoutMs: 15_000, + signal + }) as Promise, + verified: (response) => { + status.verified(response) + return true + } + }) + this.statusOwner.connectionChanged( + this.transport.state === 'connected' ? 'ready' : 'connecting' + ) + this.statusOwner.activate() + } } call( @@ -36,7 +92,9 @@ export class WebRuntimeClient { params?: unknown, options?: { timeoutMs?: number } ): Promise> { - return this.transport.call(method, params, options) + return method === 'status.get' && this.statusOwner + ? this.statusOwner.refresh(options) + : this.transport.call(method, params, options) } async subscribe( @@ -94,6 +152,7 @@ export class WebRuntimeClient { } close(options: { notifySubscriptions?: boolean } = {}): void { + this.statusOwner?.dispose() const shouldNotifySubscriptions = options.notifySubscriptions ?? true for (const child of Array.from(this.childClients)) { child.close({ notifySubscriptions: shouldNotifySubscriptions }) diff --git a/src/renderer/src/web/web-runtime-connection-transport.ts b/src/renderer/src/web/web-runtime-connection-transport.ts index d62cf3b48ba..1ead257bbc5 100644 --- a/src/renderer/src/web/web-runtime-connection-transport.ts +++ b/src/renderer/src/web/web-runtime-connection-transport.ts @@ -43,7 +43,11 @@ export class WebRuntimeConnectionTransport { constructor( private readonly pairing: WebPairingOffer, - clock: { now: () => number; isDocumentVisible: () => boolean } + clock: { now: () => number; isDocumentVisible: () => boolean }, + private readonly lifecycle: { + onStateChanged?: (state: WebRuntimeConnectionState) => void + reconnect?: boolean + } = {} ) { this.serverPublicKey = publicKeyFromBase64(pairing.publicKeyB64) this.connectionWaiters = new WebRuntimeConnectionWaiters({ @@ -60,7 +64,7 @@ export class WebRuntimeConnectionTransport { this.requestRegistry = new WebRuntimeRequestRegistry({ deviceToken: pairing.deviceToken, nextId: () => this.nextId(), - waitForConnected: (timeoutMs) => this.connectionWaiters.wait(timeoutMs), + waitForConnected: (timeoutMs, signal) => this.connectionWaiters.wait(timeoutMs, signal), sendEncrypted: (message) => this.sendEncrypted(message) }) this.heartbeat = new WebRuntimeConnectionHeartbeat({ @@ -82,7 +86,7 @@ export class WebRuntimeConnectionTransport { async call( method: string, params?: unknown, - options?: { timeoutMs?: number } + options?: { timeoutMs?: number; signal?: AbortSignal } ): Promise> { return this.requestRegistry.call(method, params, options) } @@ -153,6 +157,7 @@ export class WebRuntimeConnectionTransport { } else if (next === 'auth-failed') { this.connectionWaiters.rejectAll(createWebRuntimeUnauthorizedError()) } + this.lifecycle.onStateChanged?.(next) } private openConnection(): void { @@ -232,7 +237,7 @@ export class WebRuntimeConnectionTransport { } private scheduleReconnect(): void { - if (this.reconnectTimer || this.intentionallyClosed) { + if (this.reconnectTimer || this.intentionallyClosed || this.lifecycle.reconnect === false) { return } const delay = withReconnectJitter( diff --git a/src/renderer/src/web/web-runtime-connection-waiters.ts b/src/renderer/src/web/web-runtime-connection-waiters.ts index c16e30cd779..a8f3d081e86 100644 --- a/src/renderer/src/web/web-runtime-connection-waiters.ts +++ b/src/renderer/src/web/web-runtime-connection-waiters.ts @@ -13,7 +13,10 @@ export class WebRuntimeConnectionWaiters { constructor(private readonly options: WebRuntimeConnectionWaiterOptions) {} - wait(timeoutMs = 30_000): Promise { + wait(timeoutMs = 30_000, signal?: AbortSignal): Promise { + if (signal?.aborted) { + return Promise.reject(signal.reason) + } if (this.options.getState() === 'connected') { return Promise.resolve() } @@ -24,11 +27,20 @@ export class WebRuntimeConnectionWaiters { return Promise.reject(new Error('Remote Orca runtime connection closed.')) } return new Promise((resolve, reject) => { - const timeout = window.setTimeout(() => { - const index = this.waiters.findIndex((waiter) => waiter.resolve === resolve) + const cleanup = (): void => { + window.clearTimeout(timeout) + signal?.removeEventListener('abort', abort) + const index = this.waiters.indexOf(waiter) if (index !== -1) { this.waiters.splice(index, 1) } + } + const abort = (): void => { + cleanup() + reject(signal?.reason) + } + const timeout = window.setTimeout(() => { + cleanup() reject( new Error( withRemoteRuntimeTailscaleHint( @@ -38,16 +50,18 @@ export class WebRuntimeConnectionWaiters { ) ) }, timeoutMs) - this.waiters.push({ + const waiter = { resolve: () => { - window.clearTimeout(timeout) + cleanup() resolve() }, - reject: (error) => { - window.clearTimeout(timeout) + reject: (error: Error) => { + cleanup() reject(error) } - }) + } + this.waiters.push(waiter) + signal?.addEventListener('abort', abort, { once: true }) }) } diff --git a/src/renderer/src/web/web-runtime-request-registry.ts b/src/renderer/src/web/web-runtime-request-registry.ts index 1347d580f00..0329e208ba3 100644 --- a/src/renderer/src/web/web-runtime-request-registry.ts +++ b/src/renderer/src/web/web-runtime-request-registry.ts @@ -6,7 +6,7 @@ const REQUEST_TIMEOUT_MS = 30_000 type WebRuntimeRequestRegistryOptions = { deviceToken: string nextId: () => string - waitForConnected: (timeoutMs?: number) => Promise + waitForConnected: (timeoutMs?: number, signal?: AbortSignal) => Promise sendEncrypted: (message: unknown) => boolean } @@ -18,17 +18,41 @@ export class WebRuntimeRequestRegistry { async call( method: string, params?: unknown, - callOptions?: { timeoutMs?: number } + callOptions?: { timeoutMs?: number; signal?: AbortSignal } ): Promise> { - await this.options.waitForConnected(callOptions?.timeoutMs) + const signal = callOptions?.signal + await this.options.waitForConnected(callOptions?.timeoutMs, signal) + signal?.throwIfAborted() return new Promise((resolve, reject) => { const id = this.options.nextId() const timeoutMs = callOptions?.timeoutMs ?? REQUEST_TIMEOUT_MS const timeout = window.setTimeout(() => { this.pending.delete(id) + cleanup() reject(new Error(`Request timed out: ${method}`)) }, timeoutMs) - this.pending.set(id, { method, resolve, reject, timeout }) + const cleanup = (): void => { + signal?.removeEventListener('abort', abort) + } + const abort = (): void => { + this.pending.delete(id) + window.clearTimeout(timeout) + cleanup() + reject(signal?.reason) + } + signal?.addEventListener('abort', abort, { once: true }) + this.pending.set(id, { + method, + resolve: (value) => { + cleanup() + resolve(value) + }, + reject: (error) => { + cleanup() + reject(error) + }, + timeout + }) if ( !this.options.sendEncrypted({ id, @@ -39,6 +63,7 @@ export class WebRuntimeRequestRegistry { ) { this.pending.delete(id) window.clearTimeout(timeout) + cleanup() reject(new Error('Remote Orca runtime is not connected.')) } }) diff --git a/src/renderer/src/web/web-runtime-status-owner.test.ts b/src/renderer/src/web/web-runtime-status-owner.test.ts new file mode 100644 index 00000000000..7abfe6f19f4 --- /dev/null +++ b/src/renderer/src/web/web-runtime-status-owner.test.ts @@ -0,0 +1,49 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import WebSocket from 'ws' +import { + createSharedControlTestServer, + closeSharedControlTestServers +} from '../../../shared/remote-runtime-shared-control-test-server' +import { WebRuntimeClient } from './web-runtime-client' + +const clients: WebRuntimeClient[] = [] +beforeEach(() => { + vi.stubGlobal('WebSocket', WebSocket) + vi.stubGlobal('window', { + setTimeout, + clearTimeout, + setInterval, + clearInterval, + atob: (value: string) => Buffer.from(value, 'base64').toString('binary'), + btoa: (value: string) => Buffer.from(value, 'binary').toString('base64') + }) +}) +afterEach(async () => { + clients.splice(0).forEach((client) => client.close()) + await closeSharedControlTestServers() + vi.unstubAllGlobals() +}) + +it('primary browser status follows the authenticated socket and closing it retires the owner', async () => { + let runtimeId = 'before' + const server = await createSharedControlTestServer({ + resultForRequest: () => ({ runtimeId, capabilities: [] }) + }) + const publish = vi.fn() + const client = new WebRuntimeClient(server.pairing, { + status: { environmentId: 'browser', pairingRevision: 1, publish, verified: vi.fn() } + }) + clients.push(client) + await expect + .poll(() => client.statusOwner?.read().verification, { timeout: 3_000 }) + .toBe('verified') + expect(client.statusOwner?.read().status?.runtimeId).toBe('before') + runtimeId = 'after' + server.closeClients() + await expect + .poll(() => client.statusOwner?.read().status?.runtimeId, { timeout: 3_000 }) + .toBe('after') + expect(client.statusOwner?.read().transport).toBe('ready') + client.close() + expect(publish.mock.lastCall?.[0]).toMatchObject({ retired: true, verification: 'blocked' }) +}) diff --git a/src/shared/agent-hook-listener/listener-event.ts b/src/shared/agent-hook-listener/listener-event.ts index 9bca14cc857..e31222d0bb6 100644 --- a/src/shared/agent-hook-listener/listener-event.ts +++ b/src/shared/agent-hook-listener/listener-event.ts @@ -44,6 +44,10 @@ export type AgentHookEventPayload = { /** Row projected from a structured session the host holds: `owned` while its provider child * runs here, `held` once the child is gone but the session is still open. Never persisted. */ structuredHost?: StructuredHostStatus + /** Runtime terminal handle the pane resolved to when main parsed this status off the PTY. + * Lets a reader rejoin the row to its terminal after the pane key moved. Never persisted: + * a handle belongs to the runtime that issued it. */ + terminalHandle?: string payload: ParsedAgentStatusPayload } diff --git a/src/shared/agent-row-conversation-name.test.ts b/src/shared/agent-row-conversation-name.test.ts index cf668627d71..f77a08e2fd4 100644 --- a/src/shared/agent-row-conversation-name.test.ts +++ b/src/shared/agent-row-conversation-name.test.ts @@ -31,6 +31,49 @@ describe('getAgentRowConversationName', () => { ) }) + it("shows the title owned by the row's provider session", () => { + const tab = makeTab({ + aiVaultTitle: { agent: 'claude', sessionId: 's1', title: 'Fix the lease probe' }, + generatedTitle: 'Fix intake flow', + title: '\u2733 Investigate replay bug' + }) + expect(getAgentRowConversationName(tab, 'claude', true, undefined, 's1')).toBe( + 'Fix the lease probe' + ) + }) + + it('lets a manual rename and a quick command still outrank the provider title', () => { + const vault = { agent: 'claude' as const, sessionId: 's1', title: 'Fix the lease probe' } + expect( + getAgentRowConversationName( + makeTab({ aiVaultTitle: vault, customTitle: 'Mine' }), + 'claude', + true, + undefined, + 's1' + ) + ).toBe('Mine') + expect( + getAgentRowConversationName( + makeTab({ aiVaultTitle: vault, quickCommandLabel: 'Run tests' }), + 'claude', + true, + undefined, + 's1' + ) + ).toBe('Run tests') + }) + + it('keeps a cwd-shaped provider title that the live-title sanitizer would discard', () => { + // `auth/login` is a real session name; as a scraped live title it would be read as a cwd. + const tab = makeTab({ + aiVaultTitle: { agent: 'claude', sessionId: 's1', title: 'auth/login' }, + title: '\u2733 Investigate replay bug' + }) + expect(getAgentRowConversationName(tab, 'claude', true, undefined, 's1')).toBe('auth/login') + expect(getAgentRowConversationName(makeTab({ title: 'auth/login' }), 'claude', true)).toBeNull() + }) + it('uses the generated title only when generated titles are enabled', () => { const tab = makeTab({ generatedTitle: 'Fix intake flow', title: '✳ Investigate replay bug' }) expect(getAgentRowConversationName(tab, 'claude', true)).toBe('Fix intake flow') diff --git a/src/shared/agent-row-conversation-name.ts b/src/shared/agent-row-conversation-name.ts index f7e2a7dc2ca..2f4ed31203b 100644 --- a/src/shared/agent-row-conversation-name.ts +++ b/src/shared/agent-row-conversation-name.ts @@ -1,7 +1,8 @@ // Resolves the stable "conversation name" an agent row can show instead of the // live last-message preview. Sources, in the same precedence the tab bar uses // (tab-title-resolution.ts): manual rename → quick-command label → OpenCode's -// semantic session title → Orca's generated title → the agent-set live title. +// semantic session title → provider session title → Orca's generated title → +// the agent-set live title. // Live titles are accepted only when they carry a real name — pure status, // identity-echo, and spinner/cwd titles yield null so callers keep the // last-message label. @@ -15,7 +16,7 @@ import type { TerminalTab } from './terminal-tab-types' export type ConversationNameTab = Pick< TerminalTab, - 'customTitle' | 'quickCommandLabel' | 'generatedTitle' | 'title' | 'defaultTitle' + 'customTitle' | 'quickCommandLabel' | 'aiVaultTitle' | 'generatedTitle' | 'title' | 'defaultTitle' > // Why: synthetic status titles ("Codex ready", "Cursor - action required") are @@ -119,7 +120,8 @@ export function getAgentRowConversationName( // this row's own pane title, or `null` when none resolves; `undefined` (a // single-pane tab) keeps the tab title. Tab-owned names above are unaffected: // the user gave those to the whole tab and they do not flip on focus. - paneLiveTitle?: string | null + paneLiveTitle?: string | null, + providerSessionId?: string ): string | null { const customTitle = tab.customTitle?.trim() if (customTitle) { @@ -134,6 +136,17 @@ export function getAgentRowConversationName( if (isMeaningfulOpenCodeTerminalTitle(liveTitle)) { return liveTitle } + // Provider titles belong to their session, not every pane in the tab. + const aiVaultTitle = tab.aiVaultTitle + const providerTitle = aiVaultTitle?.title.trim() + if ( + aiVaultTitle && + providerTitle && + aiVaultTitle.agent === agentType && + aiVaultTitle.sessionId === providerSessionId + ) { + return providerTitle + } const generatedTitle = generatedTitlesEnabled ? tab.generatedTitle?.trim() : '' if (generatedTitle) { return generatedTitle diff --git a/src/shared/agent-session-conversation-name.test.ts b/src/shared/agent-session-conversation-name.test.ts new file mode 100644 index 00000000000..aa824e5f042 --- /dev/null +++ b/src/shared/agent-session-conversation-name.test.ts @@ -0,0 +1,162 @@ +import { describe, expect, it } from 'vitest' +import { + AGENT_SESSION_CONVERSATION_NAME_MAX_LENGTH, + isAgentSessionConversationName, + normalizeAgentSessionConversationName +} from './agent-session-conversation-name' + +describe('normalizeAgentSessionConversationName', () => { + it('keeps a plain single-line name unchanged', () => { + expect(normalizeAgentSessionConversationName('Fix the flaky lease probe')).toBe( + 'Fix the flaky lease probe' + ) + }) + + it('flattens whitespace so a multi-line name cannot break the tab strip', () => { + expect(normalizeAgentSessionConversationName('Fix the\nlease\tprobe ')).toBe( + 'Fix the lease probe' + ) + }) + + it('rejects an empty or whitespace-only name rather than blanking the label', () => { + expect(normalizeAgentSessionConversationName('')).toBeNull() + expect(normalizeAgentSessionConversationName(' \n ')).toBeNull() + }) + + it('rejects anything that is not a string', () => { + expect(normalizeAgentSessionConversationName(undefined)).toBeNull() + expect(normalizeAgentSessionConversationName(null)).toBeNull() + expect(normalizeAgentSessionConversationName(42)).toBeNull() + expect(normalizeAgentSessionConversationName({ title: 'x' })).toBeNull() + }) + + it('bounds a pasted essay to the stored maximum', () => { + const normalized = normalizeAgentSessionConversationName('a'.repeat(1000)) + expect(normalized).toHaveLength(AGENT_SESSION_CONVERSATION_NAME_MAX_LENGTH) + expect(isAgentSessionConversationName(normalized)).toBe(true) + }) +}) + +describe('isAgentSessionConversationName', () => { + it('accepts only bounded canonical names', () => { + expect(isAgentSessionConversationName('Fix the probe')).toBe(true) + expect(isAgentSessionConversationName('')).toBe(false) + expect(isAgentSessionConversationName('a'.repeat(201))).toBe(false) + expect(isAgentSessionConversationName(' Fix the probe ')).toBe(false) + expect(isAgentSessionConversationName('Fix\nthe probe')).toBe(false) + expect(isAgentSessionConversationName('Fix\u202Egnp.exe probe')).toBe(false) + expect(isAgentSessionConversationName(7)).toBe(false) + }) +}) + +describe('normalizeAgentSessionConversationName hostile text', () => { + it('strips control characters and bidi overrides', () => { + // U+202E renders what follows right-to-left, so a tab could show a label + // that reads as text the name does not contain. + expect(normalizeAgentSessionConversationName('Fix\u202Egnp.exe probe')).toBe( + 'Fix gnp.exe probe' + ) + expect(normalizeAgentSessionConversationName('Fix\u0007the probe')).toBe('Fix the probe') + expect(normalizeAgentSessionConversationName('Fix\u200Bthe probe')).toBe('Fix the probe') + expect(normalizeAgentSessionConversationName('\u202E\u200B ')).toBeNull() + }) + + it('never truncates through a surrogate pair', () => { + const name = `${'a'.repeat(AGENT_SESSION_CONVERSATION_NAME_MAX_LENGTH - 1)}\u{1F600}tail` + + const normalized = normalizeAgentSessionConversationName(name) + + // A raw slice would leave the emoji's lone high surrogate, which renders as + // U+FFFD on every surface that shows the name. + expect(normalized).toBe('a'.repeat(AGENT_SESSION_CONVERSATION_NAME_MAX_LENGTH - 1)) + expect(normalized).not.toContain('\uFFFD') + }) + + it('keeps a legitimate non-ASCII name intact', () => { + expect(normalizeAgentSessionConversationName('R\u00E9sum\u00E9 du fil \u2615')).toBe( + 'R\u00E9sum\u00E9 du fil \u2615' + ) + }) +}) + +describe('normalizeAgentSessionConversationName joiners', () => { + // U+200C/U+200D carry meaning: stripping them as "format characters" splits a + // family emoji into three people and breaks Persian and Hindi orthography. + // The naming prompt asks for the user's own language, so this is normal input. + const ZWJ = '\u200D' + const ZWNJ = '\u200C' + + it.each([ + ['family emoji', `Fix \u{1F468}${ZWJ}\u{1F469}${ZWJ}\u{1F467} layout`], + ['flag emoji', `Ship \u{1F3F3}\uFE0F${ZWJ}\u{1F308} theme`], + ['profession emoji', `Add \u{1F469}${ZWJ}\u{1F4BB} avatar`], + ['Persian ZWNJ', `می${ZWNJ}خواهم تست`], + ['Hindi ZWNJ conjunct', `क्${ZWNJ}ष ठीक`] + ])('keeps the joiners in a %s name', (_label, name) => { + expect(normalizeAgentSessionConversationName(name)).toBe(name) + }) + + // Kept from the hardening: allowing the joiners must not readmit these. + it.each([ + ['bidi override', 'Fix\u202Egnp.exe probe', 'Fix gnp.exe probe'], + ['isolate pair', 'Fix\u2066the\u2069 probe', 'Fix the probe'], + ['Arabic letter mark', 'Fix\u061Cthe probe', 'Fix the probe'], + ['soft hyphen', 'Fix\u00ADthe probe', 'Fix the probe'], + ['word joiner', 'Fix\u2060the probe', 'Fix the probe'], + ['zero-width space', 'Fix\u200Bthe probe', 'Fix the probe'], + ['byte order mark', 'Fix\uFEFFthe probe', 'Fix the probe'] + ])('still strips a %s', (_label, name, expected) => { + expect(normalizeAgentSessionConversationName(name)).toBe(expected) + }) + + // Each row is a `\p{Cf}` run the hand-written enumeration this replaces let + // through, so the name normalized to a non-empty label that renders as nothing. + it.each([ + ['invisible maths operators', '\u2061\u2062\u2063\u2064'], + ['tag characters', '\u{E0020}\u{E0041}\u{E007F}'], + ['a Mongolian vowel separator', '\u180E'], + ['interlinear annotation marks', '\uFFF9\uFFFA\uFFFB'], + ['deprecated format characters', '\u206A\u206B\u206C\u206D\u206E\u206F'], + ['Arabic number signs', '\u0600\u0601\u06DD'], + ['the joiners themselves', `${ZWNJ}${ZWJ}`], + ['a bidi and zero-width mix', '\u202E\u200B\u2060'], + // A joiner survives the collapsing run, so it splits that run in two and + // each half becomes its own space; the guard has to read the spaces too. + ['joiners split by a tab', `${ZWJ}\t${ZWJ}`], + ['joiners split by a newline', `${ZWJ}\n${ZWJ}`], + ['joiners split by a byte order mark', `${ZWJ}\uFEFF${ZWJ}`], + ['joiners split by zero-width spaces', `\u200B${ZWJ}\u200B${ZWJ}`], + ['joiners split by literal spaces', ` ${ZWJ} ${ZWJ} `], + ['joiners split by a bidi override', `\u202E${ZWJ}\u202E${ZWJ}`], + ['mixed joiners split by a tab', `${ZWJ}\t${ZWNJ}`], + ['joiners wrapped in tag characters', `\u{E0020}${ZWJ}\u{E0041}${ZWJ}\u{E007F}`] + ])('rejects a name that is only %s', (_label, name) => { + expect(normalizeAgentSessionConversationName(name)).toBeNull() + }) + + it('drops a tag-character payload hidden after a real title', () => { + // Tag characters mirror ASCII, so this run decodes to readable text that no + // surface draws — it reached the user's own Codex history via thread/name/set. + const hidden = Array.from('ransom', (c) => + String.fromCodePoint(0xe0000 + c.charCodeAt(0)) + ).join('') + + const normalized = normalizeAgentSessionConversationName(`Fix login bug${hidden}`) + + expect(normalized).toBe('Fix login bug') + expect(Array.from(normalized ?? '', (c) => c.codePointAt(0) ?? 0).every((c) => c < 0x7f)).toBe( + true + ) + }) + + it('never ends a truncated name on a dangling joiner', () => { + const name = `${'A'.repeat(197)}\u{1F468}${ZWJ}\u{1F469}${ZWJ}\u{1F467}` + + const normalized = normalizeAgentSessionConversationName(name) + + // The cut lands mid-sequence; the joiner it strands attaches to nothing. + expect(normalized?.endsWith(ZWJ)).toBe(false) + expect(normalized).toBe(`${'A'.repeat(197)}\u{1F468}`) + expect(normalized).not.toContain('\uFFFD') + }) +}) diff --git a/src/shared/agent-session-conversation-name.ts b/src/shared/agent-session-conversation-name.ts new file mode 100644 index 00000000000..039721bfee2 --- /dev/null +++ b/src/shared/agent-session-conversation-name.ts @@ -0,0 +1,67 @@ +// The conversation name Orca recorded for one structured chat, normalized once +// at the single boundary that writes it. +// +// The text is free-form and provider-supplied, so it is bounded and flattened +// here rather than trusted: a name carrying a newline or a bidi override is not +// something the record should ever hold. + +import { sliceAtCodeUnitLimit } from './surrogate-safe-text-slice' + +/** Well past any provider's own cap, short enough that a pasted essay cannot enter the record. */ +export const AGENT_SESSION_CONVERSATION_NAME_MAX_LENGTH = 200 + +/** Whitespace, plus the C0/C1 controls, bidi controls and zero-width marks `\s` + * misses. A bidi override renders a label that reads as text the name does not + * contain, and a zero-width run renders as nothing at all. Subtracted from all + * of `\p{Cf}` rather than enumerated, so a format character Unicode adds later + * is covered with no list to remember; U+200C/U+200D are the one exception, + * being load-bearing in Persian, Hindi and every multi-part emoji. Accepted + * cost: the U+E0020-E007F tag sequences go too, so the England, Scotland and + * Wales flags degrade — far cheaper than an invisible payload in a label. + * Deliberately NOT reached: blank-RENDERING letters and marks such as U+2800, + * U+3164 and U+115F, which are Lo/So/Mn rather than any invisible category. A + * name made only of those is accepted and looks empty; Braille and the Hangul + * jamo fillers carry meaning in real text, so stripping them would cost more. */ +const UNRENDERABLE_RUN = /(?:[\s\p{Cc}\p{Zl}\p{Zp}]|(?![\u200C\u200D])\p{Cf})+/gu + +/** The joiners outlive the run above by design; alone — or separated only by the + * spaces that run collapsed to — they are still a blank label. */ +const BLANK_ONLY = /^[\s\u200C\u200D]+$/u + +/** A surrogate with no partner — a provider that truncated an emoji, usually. + * Under `u` this class matches ONLY unpaired ones, so astral characters keep + * both halves; left in, each renders as U+FFFD on every surface. */ +const LONE_SURROGATE = /[\uD800-\uDFFF]/gu + +/** A cut inside an emoji sequence strands the joiner that attached it. */ +const TRAILING_DANGLE = /[\s\u200C\u200D]+$/u + +export function normalizeAgentSessionConversationName(value: unknown): string | null { + if (typeof value !== 'string') { + return null + } + // Surrogates first, so the gap one leaves collapses with the run around it. + const collapsed = value.replace(LONE_SURROGATE, '').replace(UNRENDERABLE_RUN, ' ').trim() + if (!collapsed || BLANK_ONLY.test(collapsed)) { + return null + } + if (collapsed.length <= AGENT_SESSION_CONVERSATION_NAME_MAX_LENGTH) { + return collapsed + } + // Cut on a character boundary: a raw slice can strand a lone high surrogate, + // which every surface then renders as U+FFFD. + const truncated = sliceAtCodeUnitLimit( + collapsed, + AGENT_SESSION_CONVERSATION_NAME_MAX_LENGTH + ).replace(TRAILING_DANGLE, '') + return truncated || null +} + +export function isAgentSessionConversationName(value: unknown): value is string { + return ( + typeof value === 'string' && + value.length > 0 && + value.length <= AGENT_SESSION_CONVERSATION_NAME_MAX_LENGTH && + normalizeAgentSessionConversationName(value) === value + ) +} diff --git a/src/shared/agent-session-journal-schemas.test.ts b/src/shared/agent-session-journal-schemas.test.ts index c23f7915589..3a515952601 100644 --- a/src/shared/agent-session-journal-schemas.test.ts +++ b/src/shared/agent-session-journal-schemas.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest' import { + AgentJournalItemBodySchema, isAdmissibleAgentJournalItemBody, isAdmissibleAgentJournalMessageBody, isAdmissibleAgentJournalRenderItem, @@ -275,13 +276,20 @@ describe('optional tool annotations', () => { const body = { kind: 'tool-call', name: 'shell', input: null, state: 'completed' } it('admits old rows and rows with optional annotations without a new kind', () => { expect(isAdmissibleAgentJournalItemBody(body)).toBe(true) - expect(isAdmissibleAgentJournalItemBody({ ...body, exitCode: 0, durationMs: 0 })).toBe(true) + expect( + isAdmissibleAgentJournalItemBody({ ...body, callId: 'call-1', exitCode: 0, durationMs: 0 }) + ).toBe(true) expect( isAdmissibleAgentJournalItemBody({ ...body, webSearchResults: [{ title: 'Docs', url: 'https://example.com' }] }) ).toBe(true) + const padded = AgentJournalItemBodySchema.safeParse({ ...body, callId: ' call-1 ' }) + expect(padded.success).toBe(true) + if (padded.success && padded.data.kind === 'tool-call') { + expect(padded.data.callId).toBe(' call-1 ') + } }) it('admits explicit MCP identity without constraining the raw name', () => { expect( @@ -293,6 +301,9 @@ describe('optional tool annotations', () => { ).toBe(true) }) it.each([ + { callId: '' }, + { callId: ' \t' }, + { callId: 1 }, { exitCode: '127' }, { exitCode: 1.5 }, { durationMs: -1 }, @@ -300,4 +311,14 @@ describe('optional tool annotations', () => { ])('rejects malformed annotation %s', (metadata) => expect(isAdmissibleAgentJournalItemBody({ ...body, ...metadata })).toBe(false) ) + + it('rejects whitespace-only provider IDs in message blocks too', () => { + expect( + isAdmissibleAgentJournalItemBody({ + kind: 'message', + role: 'assistant', + blocks: [{ type: 'tool-call', name: 'shell', input: null, callId: '\n\t' }] + }) + ).toBe(false) + }) }) diff --git a/src/shared/agent-session-journal-schemas.ts b/src/shared/agent-session-journal-schemas.ts index 6acae63f202..eaee6bb9a63 100644 --- a/src/shared/agent-session-journal-schemas.ts +++ b/src/shared/agent-session-journal-schemas.ts @@ -49,6 +49,11 @@ const KNOWN_BLOCK_TYPES = new Set([ 'subagent-group' ]) +/** Provider IDs are opaque; reject all-whitespace values without rewriting valid IDs. */ +const ProviderCallId = z + .string() + .refine((value) => value.trim().length > 0, 'callId must contain a non-whitespace character') + /** Child-agent lifecycle stays an open string for the same reason tool states * do: a state a newer build writes must not turn the row malformed. */ const SubagentEntry = z.object({ @@ -78,6 +83,7 @@ const Block = z.union([ type: z.literal('tool-call'), name: z.string(), input: z.unknown().optional(), + callId: ProviderCallId.optional(), ...ToolMetadata }), z.object({ @@ -140,6 +146,7 @@ export const AgentJournalItemBodySchema = z.discriminatedUnion('kind', [ name: z.string(), // See the tool-call block: the key itself is lost when `input` is undefined. input: z.unknown().optional(), + callId: ProviderCallId.optional(), state: z.string().min(1), output: BoundedPayload.optional() }), diff --git a/src/shared/agent-session-journal-types.ts b/src/shared/agent-session-journal-types.ts index f1669058d63..7ba5b277e6d 100644 --- a/src/shared/agent-session-journal-types.ts +++ b/src/shared/agent-session-journal-types.ts @@ -97,6 +97,8 @@ export type AgentJournalToolCallItem = NativeChatToolMetadata & { kind: 'tool-call' name: string input: unknown + /** Provider-supplied identity within this item stream; optional for mixed-version peers. */ + callId?: string state: AgentJournalToolCallState output?: AgentJournalBoundedPayload } diff --git a/src/shared/agent-session-record.ts b/src/shared/agent-session-record.ts index 961c88e3aac..a8add5c1128 100644 --- a/src/shared/agent-session-record.ts +++ b/src/shared/agent-session-record.ts @@ -1,4 +1,5 @@ import { isAgentSessionRewindRecord, type AgentSessionRewindRecord } from './agent-session-rewind' +import { isAgentSessionConversationName } from './agent-session-conversation-name' /** * Durable agent-session record and its single-writer lease. * @@ -132,6 +133,8 @@ export type AgentSessionRecord = { options?: Record rewind?: AgentSessionRewindRecord conversationCommand?: AgentSessionConversationCommandRecord + /** The name Orca gave this conversation, so a later acquisition need not name it again. */ + conversationName?: string launchArgs?: AgentSessionLaunchArgs lease: AgentSessionLease createdAt: number @@ -345,6 +348,8 @@ export function isAgentSessionRecord(value: unknown): value is AgentSessionRecor (record.rewind === undefined || isAgentSessionRewindRecord(record.rewind)) && (record.conversationCommand === undefined || isAgentSessionConversationCommandRecord(record.conversationCommand)) && + (record.conversationName === undefined || + isAgentSessionConversationName(record.conversationName)) && (record.launchArgs === undefined || isAgentSessionLaunchArgs(record.launchArgs)) && !Object.hasOwn(record, 'launchEnv') && isAgentSessionLease(record.lease) && diff --git a/src/shared/agent-session-wire.ts b/src/shared/agent-session-wire.ts index 546f995456c..b4ef57a6b91 100644 --- a/src/shared/agent-session-wire.ts +++ b/src/shared/agent-session-wire.ts @@ -311,6 +311,10 @@ export type AgentSessionSlashCommand = { kind: 'command' | 'skill' /** Membership is authoritative, but this provider report did not classify the name. */ kindUnspecified?: true + /** Provider-authored row text; absent when the report carried names only. */ + description?: string + /** Provider-authored argument sketch, e.g. ``. */ + argumentHint?: string } /** The provider's own command surface, read per session. Additive read-only diff --git a/src/shared/agent-status-types.test.ts b/src/shared/agent-status-types.test.ts index b075f87ca86..f79f3c974f3 100644 --- a/src/shared/agent-status-types.test.ts +++ b/src/shared/agent-status-types.test.ts @@ -15,6 +15,8 @@ import { AGENT_STATUS_STATES, AGENT_TYPE_MAX_LENGTH } from './agent-status-types' +import type { AgentType, WellKnownAgentType } from './agent-status-types' +import type { TuiAgent } from './tui-agent' afterEach(() => { vi.restoreAllMocks() @@ -676,3 +678,32 @@ describe('normalizeAgentStatusPayload matches the JSON round trip', () => { } }) }) + +describe('WellKnownAgentType', () => { + // Compile-time proof the union is derived from TuiAgent rather than hand-copied: + // a literal list that misses any launchable agent id fails to typecheck here. + const widenTuiAgent = (agent: TuiAgent): WellKnownAgentType => agent + + it('covers every TuiAgent id plus the unknown sentinel', () => { + // ids the previous 22-member hand-written union had drifted past + const formerlyMissing: WellKnownAgentType[] = [ + 'qwen-code', + 'mistral-vibe', + 'claude-agent-teams' + ] + const sentinel: WellKnownAgentType = 'unknown' + + expect([...formerlyMissing, sentinel, widenTuiAgent('rovo')]).toEqual([ + 'qwen-code', + 'mistral-vibe', + 'claude-agent-teams', + 'unknown', + 'rovo' + ]) + }) + + it('keeps AgentType open to custom agent names', () => { + const custom: AgentType = 'some-in-house-agent' + expect(custom).toBe('some-in-house-agent') + }) +}) diff --git a/src/shared/agent-status-types.ts b/src/shared/agent-status-types.ts index 666cedb5748..3a062f7069d 100644 --- a/src/shared/agent-status-types.ts +++ b/src/shared/agent-status-types.ts @@ -5,6 +5,7 @@ import type { AgentProviderSessionMetadata } from './agent-session-resume' import type { OrchestrationFleetAttention } from './orchestration-fleet-attention' import type { AgentStatusRowFacets } from './agent-status-observation' +import type { TuiAgent } from './tui-agent' import { normalizeInteractivePromptField, normalizeOptionalField, @@ -26,30 +27,9 @@ export const AGENT_STATUS_STATES = ['working', 'blocked', 'waiting', 'done'] as export type AgentStatusState = (typeof AGENT_STATUS_STATES)[number] export type AgentWorkingMode = 'monitoring' // Why: agent types aren't a fixed set (custom agents exist); any non-empty string is -// accepted — these well-known names are just a convenience union for pattern-matching. -export type WellKnownAgentType = - | 'claude' - | 'openclaude' - | 'codex' - | 'gemini' - | 'antigravity' - | 'amp' - | 'opencode' - | 'mimo-code' - | 'cursor' - | 'copilot' - | 'aider' - | 'pi' - | 'omp' - | 'prime-agent' - | 'droid' - | 'command-code' - | 'grok' - | 'hermes' - | 'devin' - | 'ante' - | 'trae' - | 'unknown' +// accepted — the well-known names are the launchable TuiAgent ids plus the 'unknown' +// sentinel (no agent identified yet), a convenience union for pattern-matching. +export type WellKnownAgentType = TuiAgent | 'unknown' export type AgentType = WellKnownAgentType | (string & {}) /** A snapshot of a previous agent state, used to render activity blocks. diff --git a/src/shared/ai-vault-search-query-operators.test.ts b/src/shared/ai-vault-search-query-operators.test.ts new file mode 100644 index 00000000000..0bb5cbc463b --- /dev/null +++ b/src/shared/ai-vault-search-query-operators.test.ts @@ -0,0 +1,119 @@ +import { describe, expect, it } from 'vitest' +import { parseVaultQuery } from './ai-vault-session-filters' +import { + hasAiVaultSearchQueryOperators, + splitAiVaultSearchQuery +} from './ai-vault-search-query-operators' + +describe('what counts as an operator', () => { + it('splits repo: and path: out of the free text', () => { + const split = splitAiVaultSearchQuery('relay capacity repo:orca path:/work/app') + expect(split.text).toBe('relay capacity') + expect(split.terms).toEqual(['relay', 'capacity']) + expect(split.repoTerms).toEqual(['orca']) + expect(split.pathTerms).toEqual(['/work/app']) + expect(hasAiVaultSearchQueryOperators(split)).toBe(true) + }) + + it('keeps a value that only looks like an operator as ordinary text', () => { + const split = splitAiVaultSearchQuery('myrepo:x https://host/path:y') + expect(split.repoTerms).toEqual([]) + expect(split.pathTerms).toEqual([]) + expect(split.text).toBe('myrepo:x https://host/path:y') + }) + + it('reads a quoted operator value whole, including its spaces', () => { + expect(splitAiVaultSearchQuery('path:"/Users/ada/My Project" needle').pathTerms).toEqual([ + '/Users/ada/My Project' + ]) + }) + + it('does not let an apostrophe in prose swallow the operator between quotes', () => { + const split = splitAiVaultSearchQuery("it's a repo:orca thing's") + expect(split.repoTerms).toEqual(['orca']) + }) + + it('preserves operator case, which the panel folds and the index must not', () => { + // cwd_key keeps execution-host case, so folding here would lose a POSIX + // directory whose name differs only in case. + expect(splitAiVaultSearchQuery('path:/Work/App').pathTerms).toEqual(['/Work/App']) + expect(parseVaultQuery('path:/Work/App').pathTerms).toEqual(['/work/app']) + }) + + it('has no operators when the query is plain text', () => { + expect(hasAiVaultSearchQueryOperators(splitAiVaultSearchQuery('relay capacity'))).toBe(false) + }) +}) + +// The panel parses through this module now, so the two cannot disagree by +// construction. What is worth pinning is the handful of shapes where the +// panel's old hand-rolled tokenizer answered differently, so the change of +// behaviour is a decision on the record rather than a surprise. +describe('the shapes where the panel parser used to answer differently', () => { + it.each([ + ['repo:"" x', 'repoTerms'], + ['path:"" x', 'pathTerms'] + ] as const)('drops the empty operator value in %s instead of filtering on `""`', (query, key) => { + // The old tokenizer kept the quote characters as the value, so `repo:""` + // filtered on a label no session has and silently emptied the list. An + // operator with nothing in it is not a narrowing. + expect(splitAiVaultSearchQuery(query)[key]).toEqual([]) + expect(parseVaultQuery(query)[key]).toEqual([]) + }) + + it.each([ + ['repo:" " x', 'repoTerms'], + ['path:" " x', 'pathTerms'] + ] as const)('drops the whitespace-only operator value in %s too', (query, key) => { + // Same defect as `repo:""` wearing a different hat: an untrimmed `" "` + // survives as a term, matches no label, and empties the list. + expect(splitAiVaultSearchQuery(query)[key]).toEqual([]) + expect(parseVaultQuery(query)[key]).toEqual([]) + }) + + it('trims a quoted operator value rather than searching for the spaces', () => { + expect(splitAiVaultSearchQuery('repo:" session-search "').repoTerms).toEqual(['session-search']) + }) + + it.each(['"" empty', "'' empty", '" " empty'])( + 'reads the empty quotes in %s as an empty term', + (query) => { + // Same reason one level up: the old parser searched for the two characters + // and found nothing, where an empty term matches everything and leaves the + // rest of the query to do the work. + expect(parseVaultQuery(query).terms).toEqual(['', 'empty']) + } + ) + + it.each([ + ['"foo"bar', { terms: ['foo', 'bar'], repoTerms: [], pathTerms: [] }], + ['"a b"c', { terms: ['a b', 'c'], repoTerms: [], pathTerms: [] }], + ['repo:"a"b', { terms: ['b'], repoTerms: ['a'], pathTerms: [] }], + ['path:"a"b', { terms: ['b'], repoTerms: [], pathTerms: ['a'] }], + ['repo:"a b"c d', { terms: ['c', 'd'], repoTerms: ['a b'], pathTerms: [] }] + ])('reads %s exactly as the panel always has', (query, expected) => { + // A closing quote does not have to end a word. Requiring it turned each of + // these into one term carrying its own quote characters, which matches + // nothing; the apostrophe case below is protected by the token start, not + // by that rule. + expect(parseVaultQuery(query)).toEqual(expected) + }) +}) + +describe('agrees with the sessions panel parser on operator recognition', () => { + it.each([ + 'relay capacity', + 'repo:orca needle', + 'path:/work/app needle', + 'myrepo:x', + 'needle repo:orca path:/work/app', + 'path:"/Users/ada/My Project"', + 'https://host/path:y' + ])('reads the same operators out of %s', (query) => { + const split = splitAiVaultSearchQuery(query) + const parsed = parseVaultQuery(query) + const fold = (values: readonly string[]): string[] => values.map((v) => v.toLowerCase()).sort() + expect(fold(split.repoTerms)).toEqual(fold(parsed.repoTerms)) + expect(fold(split.pathTerms)).toEqual(fold(parsed.pathTerms)) + }) +}) diff --git a/src/shared/ai-vault-search-query-operators.ts b/src/shared/ai-vault-search-query-operators.ts new file mode 100644 index 00000000000..a75da8c769e --- /dev/null +++ b/src/shared/ai-vault-search-query-operators.ts @@ -0,0 +1,90 @@ +/** Anchored at a token start only, so `myrepo:x` and `https://h/path:x` stay literal. */ +const OPERATOR = /(repo|path):/iy + +export type AiVaultSearchQuerySplit = { + /** Query minus the operator tokens, quoting intact; what FTS sees. */ + text: string + /** The same free text as tokens with quotes stripped; what a substring matcher wants. */ + terms: readonly string[] + /** Operator values as typed apart from surrounding space: the panel folds case, the index does not. */ + repoTerms: readonly string[] + pathTerms: readonly string[] +} + +/** + * The one reading of `repo:` / `path:` in the product: the sessions panel and the + * search index must agree on what is an operator and what is ordinary text. + */ +export function splitAiVaultSearchQuery(query: string): AiVaultSearchQuerySplit { + const spans: string[] = [] + const terms: string[] = [] + const repoTerms: string[] = [] + const pathTerms: string[] = [] + let index = 0 + while (index < query.length) { + if (isBoundary(query[index])) { + index += 1 + continue + } + OPERATOR.lastIndex = index + const operator = OPERATOR.exec(query) + if (operator) { + const at = index + operator[0].length + const quoted = readQuoted(query, at) + const value = quoted?.value ?? readBare(query, at) + index = quoted ? quoted.end : at + value.length + // Trimmed for the same reason an empty value is dropped: `repo:" "` is + // not a narrowing anyone typed on purpose, and an untrimmed one matches + // no label at all, which silently empties the list. + const operand = value.trim() + if (operand) { + ;(operator[1]!.toLowerCase() === 'repo' ? repoTerms : pathTerms).push(operand) + } + continue + } + const quoted = readQuoted(query, index) + const value = quoted?.value ?? readBare(query, index) + const end = quoted ? quoted.end : index + value.length + spans.push(query.slice(index, end)) + // The span keeps the query verbatim for FTS; only the substring matcher's + // copy is trimmed, so `" "` reads as the empty term `""` already does + // rather than as a term no session's text contains. + terms.push(value.trim()) + index = end + } + return { text: spans.join(' '), terms, repoTerms, pathTerms } +} + +export function hasAiVaultSearchQueryOperators(split: AiVaultSearchQuerySplit): boolean { + return split.repoTerms.length > 0 || split.pathTerms.length > 0 +} + +function isBoundary(char: string | undefined): boolean { + return char === undefined || /\s/.test(char) +} + +/** + * A quoted span, or null when this is not one. + * + * What keeps the apostrophes in `it's a repo:orca thing's` from opening a span + * that swallows the operator is the caller: this only ever runs at a token + * start, and the quote in `it's` is not at one. The closing quote is then just + * the next one, wherever it falls, so `"a b"c` reads as the panel has always + * read it — the span, then the rest as its own token. + */ +function readQuoted(query: string, at: number): { value: string; end: number } | null { + const quote = query[at] + if (quote !== '"' && quote !== "'") { + return null + } + const close = query.indexOf(quote, at + 1) + return close === -1 ? null : { value: query.slice(at + 1, close), end: close + 1 } +} + +function readBare(query: string, at: number): string { + let end = at + while (end < query.length && !isBoundary(query[end])) { + end += 1 + } + return query.slice(at, end) +} diff --git a/src/shared/ai-vault-session-filters.ts b/src/shared/ai-vault-session-filters.ts index 7a0708151ed..39aedaf4626 100644 --- a/src/shared/ai-vault-session-filters.ts +++ b/src/shared/ai-vault-session-filters.ts @@ -8,6 +8,7 @@ import { normalizeRuntimePathSeparators } from './cross-platform-path' import { isClipboardTextByteLengthOverLimit } from './clipboard-text' +import { splitAiVaultSearchQuery } from './ai-vault-search-query-operators' import { parseWslUncPath } from './wsl-paths' import type { AiVaultAgent, @@ -179,31 +180,61 @@ export function agentLabel(agent: AiVaultAgent): string { return aiVaultAgentLabel(agent) } +/** + * One reading of `repo:` / `path:` for the whole product. + * + * Delegates to `splitAiVaultSearchQuery`, which the search index also plans + * from, so a query cannot mean one thing in this list and another in the index. + * The values come back folded because everything this file compares is folded; + * the index keeps the unfolded form, which is why the split itself does not. + */ export function parseVaultQuery(query: string): ParsedQuery { - const terms: string[] = [] - const repoTerms: string[] = [] - const pathTerms: string[] = [] - - for (const rawToken of tokenizeQuery(query)) { - const token = rawToken.toLowerCase() - if (token.startsWith('repo:')) { - const value = token.slice('repo:'.length) - if (value) { - repoTerms.push(value) - } - continue - } - if (token.startsWith('path:')) { - const value = token.slice('path:'.length) - if (value) { - pathTerms.push(value) - } - continue - } - terms.push(token) + const split = splitAiVaultSearchQuery(query) + const fold = (values: readonly string[]): string[] => values.map((value) => value.toLowerCase()) + return { + terms: fold(split.terms), + repoTerms: fold(split.repoTerms), + pathTerms: fold(split.pathTerms) } +} - return { terms, repoTerms, pathTerms } +/** What `repo:` and `path:` are compared against for one session. */ +export type AiVaultQueryOperatorTarget = { + cwd: string | null + filePath: string + /** + * What `repo:` matches. The panel passes a resolved project label when it has + * one; everything else falls back to the last two path segments. + */ + repoLabel?: string +} + +/** + * Whether one session satisfies every `repo:` and `path:` term. + * + * The single definition of what those operators mean. The search index applies + * this over its retrieved rows rather than expressing it in SQL, because SQL + * cannot: LIKE folds ASCII and nothing else, and `path:` searches the transcript + * path as well as the working directory. Both keys are conjunctive, matching + * the qualifier semantics the panel has always had. + */ +export function matchesAiVaultQueryOperators( + target: AiVaultQueryOperatorTarget, + operators: { repoTerms: readonly string[]; pathTerms: readonly string[] } +): boolean { + if (operators.repoTerms.length > 0) { + const repoLabel = (target.repoLabel ?? folderLabel(target.cwd)).toLowerCase() + if (operators.repoTerms.some((term) => !repoLabel.includes(term.toLowerCase()))) { + return false + } + } + if (operators.pathTerms.length > 0) { + const pathSearch = `${target.cwd ?? ''} ${target.filePath}`.toLowerCase() + if (operators.pathTerms.some((term) => !pathSearch.includes(term.toLowerCase()))) { + return false + } + } + return true } function matchesQuery( @@ -229,25 +260,18 @@ function matchesQuery( return false } } - if (parsed.repoTerms.length > 0) { - const sessionProject = filters.sessionProjectById?.get(session.id) - const repoLabel = ( - sessionProject?.kind === 'repo' - ? (filters.projectLabelByKey?.get(sessionProject.key) ?? sessionProject.label) - : folderLabel(session.cwd) - ).toLowerCase() - if (parsed.repoTerms.some((term) => !repoLabel.includes(term))) { - return false - } - } - if (parsed.pathTerms.length > 0) { - const pathSearch = `${session.cwd ?? ''} ${session.filePath}`.toLowerCase() - if (parsed.pathTerms.some((term) => !pathSearch.includes(term))) { - return false - } - } - - return true + const sessionProject = filters.sessionProjectById?.get(session.id) + return matchesAiVaultQueryOperators( + { + cwd: session.cwd, + filePath: session.filePath, + repoLabel: + sessionProject?.kind === 'repo' + ? (filters.projectLabelByKey?.get(sessionProject.key) ?? sessionProject.label) + : undefined + }, + parsed + ) } function sessionSortTime(session: AiVaultSession, sort: AiVaultSort): number { @@ -291,25 +315,3 @@ function createAiVaultWorkspaceMatcher(workspacePath: string): (normalizedCwd: s const matchesLinux = createNormalizedPathInsideOrEqualMatcher(workspaceWslPath.linuxPath) return (cwd) => matches(cwd) || matchesLinux(cwd) } - -function tokenizeQuery(query: string): string[] { - const tokens: string[] = [] - // Why: keep quoted operator values (repo:/path:) intact so labels and paths - // containing spaces still match — e.g. path:"/Users/ada/My Project". - const pattern = /(repo|path):"([^"]+)"|(repo|path):'([^']+)'|"([^"]+)"|'([^']+)'|(\S+)/gi - let match: RegExpExecArray | null - while ((match = pattern.exec(query)) !== null) { - const operator = match[1] ?? match[3] - const operatorValue = match[2] ?? match[4] - if (operator && operatorValue?.trim()) { - tokens.push(`${operator.toLowerCase()}:${operatorValue.trim()}`) - continue - } - - const token = match[5] ?? match[6] ?? match[7] - if (token?.trim()) { - tokens.push(token.trim()) - } - } - return tokens -} diff --git a/src/shared/cloud-service-url.test.ts b/src/shared/cloud-service-url.test.ts new file mode 100644 index 00000000000..61425fed452 --- /dev/null +++ b/src/shared/cloud-service-url.test.ts @@ -0,0 +1,13 @@ +import { expect, it } from 'vitest' +import { cleanCloudServiceOrigin } from './cloud-service-url' +it.each(['ftp://localhost', 'file://localhost', 'ws://localhost', 'http://example.com'])( + 'rejects %s even with the development loopback exception', + (url) => { + expect(cleanCloudServiceOrigin(url, true)).toBeNull() + } +) +it('allows HTTP only for explicitly enabled loopback development', () => { + expect(cleanCloudServiceOrigin('http://localhost:8080', true)).toBe('http://localhost:8080') + expect(cleanCloudServiceOrigin('http://localhost:8080', false)).toBeNull() + expect(cleanCloudServiceOrigin('https://push.onorca.dev', false)).toBe('https://push.onorca.dev') +}) diff --git a/src/shared/cloud-service-url.ts b/src/shared/cloud-service-url.ts new file mode 100644 index 00000000000..ba052d2ddc5 --- /dev/null +++ b/src/shared/cloud-service-url.ts @@ -0,0 +1,37 @@ +export function cleanCloudServiceUrl( + value: string | undefined, + allowLoopbackHttp: boolean +): string | null { + const trimmed = value?.trim() + if (!trimmed) { + return null + } + try { + const parsed = new URL(trimmed) + const loopbackHost = + parsed.hostname === '127.0.0.1' || + parsed.hostname === 'localhost' || + parsed.hostname === '[::1]' + if ( + parsed.protocol !== 'https:' && + !(parsed.protocol === 'http:' && loopbackHost && allowLoopbackHttp) + ) { + return null + } + return parsed.toString().replace(/\/$/, '') + } catch { + return null + } +} + +export function cleanCloudServiceOrigin( + value: string | undefined, + allowLoopbackHttp: boolean +): string | null { + const cleaned = cleanCloudServiceUrl(value, allowLoopbackHttp) + if (!cleaned) { + return null + } + const parsed = new URL(cleaned) + return parsed.pathname === '/' && !parsed.search && !parsed.hash ? parsed.origin : null +} diff --git a/src/shared/commit-message-agent-spec.test.ts b/src/shared/commit-message-agent-spec.test.ts index c9bfb8eb789..de5cc14529b 100644 --- a/src/shared/commit-message-agent-spec.test.ts +++ b/src/shared/commit-message-agent-spec.test.ts @@ -573,10 +573,32 @@ describe('buildArgs (OpenCode)', () => { describe('buildArgs (Antigravity)', () => { const spec = getCommitMessageAgentSpec('antigravity')! - it('runs agy with --print, --sandbox, and --model flags', () => { - const args = spec.buildArgs({ prompt: '', model: 'Gemini 3.5 Flash (Medium)' }) - expect(args).toEqual(['--print', '--sandbox', '--model', 'Gemini 3.5 Flash (Medium)']) - expect(spec.promptDelivery).toBe('stdin') + it('runs agy with the prompt attached to --print, then --sandbox and --model flags', () => { + const args = spec.buildArgs({ + prompt: 'real commit prompt', + model: 'Gemini 3.5 Flash (Medium)' + }) + expect(args).toEqual([ + '--print=real commit prompt', + '--sandbox', + '--model', + 'Gemini 3.5 Flash (Medium)' + ]) + expect(spec.promptDelivery).toBe('argv') + }) + + it('binds a leading-dash prompt to --print instead of letting it parse as an option', () => { + const args = spec.buildArgs({ prompt: '-fix: something', model: 'Gemini 3.5 Flash (Medium)' }) + expect(args[0]).toBe('--print=-fix: something') + }) + + // Why: pins argv construction only. Real agy 1.2.1 separately rejects a --print value + // that exactly matches a registered flag name (its own heuristic, independent of this + // fix) — verified `agy --print=--sandbox` still errors there. Real prompts are never + // literally a bare flag name, so this doesn't affect actual generation. + it('still glues a prompt that collides with a flag name onto --print', () => { + const args = spec.buildArgs({ prompt: '--sandbox', model: 'Gemini 3.5 Flash (Medium)' }) + expect(args[0]).toBe('--print=--sandbox') }) it('uses dynamic model discovery via agy models', () => { diff --git a/src/shared/commit-message-agent-specs-primary.ts b/src/shared/commit-message-agent-specs-primary.ts index e6ba42f775b..3e42a4c5865 100644 --- a/src/shared/commit-message-agent-specs-primary.ts +++ b/src/shared/commit-message-agent-specs-primary.ts @@ -197,7 +197,6 @@ export function buildPrimaryCommitMessageAgentSpecs({ '--print', '--no-session', '--no-tools', - '--no-extensions', '--no-skills', '--no-context-files', '--mode', diff --git a/src/shared/commit-message-agent-specs-secondary.ts b/src/shared/commit-message-agent-specs-secondary.ts index e22fce018f8..2ad7691ac36 100644 --- a/src/shared/commit-message-agent-specs-secondary.ts +++ b/src/shared/commit-message-agent-specs-secondary.ts @@ -212,8 +212,11 @@ export function buildSecondaryCommitMessageAgentSpecs({ id: 'antigravity', label: 'Antigravity', binary: 'agy', - promptDelivery: 'stdin', - buildArgs: ({ model }) => ['--print', '--sandbox', '--model', model], + // agy's --print takes the prompt as its value (#19539, #14059). Deliver on argv + // using `--print=` so a leading-dash prompt binds to the flag instead of + // being parsed as its own option, and --sandbox/--model stay separate options. + promptDelivery: 'argv', + buildArgs: ({ prompt, model }) => [`--print=${prompt}`, '--sandbox', '--model', model], modelSource: 'dynamic', modelDiscovery: { binary: 'agy', args: ['models'], parse: parseAntigravityModels }, models: [ diff --git a/src/shared/commit-message-plan.test.ts b/src/shared/commit-message-plan.test.ts index 0b728307bf7..2d58a5cf6e7 100644 --- a/src/shared/commit-message-plan.test.ts +++ b/src/shared/commit-message-plan.test.ts @@ -2,6 +2,29 @@ import { describe, expect, it } from 'vitest' import { planCommitMessageGeneration, planAgentBinary } from './commit-message-plan' describe('planCommitMessageGeneration', () => { + it('keeps extension-provided Pi models available in generated Git text plans', () => { + const result = planCommitMessageGeneration( + { agentId: 'pi', model: 'local-extension/model' }, + 'Write a commit message' + ) + expect(result.ok).toBe(true) + if (!result.ok) { + throw new Error(result.error) + } + expect(result.plan.args).not.toContain('--no-extensions') + expect(result.plan.args).toEqual( + expect.arrayContaining([ + '--no-session', + '--no-tools', + '--no-skills', + '--no-context-files', + '--model', + 'local-extension/model' + ]) + ) + expect(result.plan.stdinPayload).toBe('Write a commit message') + }) + it('plans Claude non-interactive generation with the prompt on stdin only', () => { const result = planCommitMessageGeneration( { @@ -155,6 +178,115 @@ describe('planCommitMessageGeneration', () => { }) }) + it('plans Antigravity generation with the prompt attached to --print, not stdin (#19539, #14059)', () => { + const result = planCommitMessageGeneration( + { + agentId: 'antigravity', + model: 'Gemini 3.5 Flash (Medium)' + }, + 'real commit prompt' + ) + + expect(result).toEqual({ + ok: true, + plan: { + binary: 'agy', + args: ['--print=real commit prompt', '--sandbox', '--model', 'Gemini 3.5 Flash (Medium)'], + stdinPayload: null, + label: 'Antigravity' + } + }) + }) + + it('keeps a leading-dash Antigravity prompt bound to --print instead of parsing as an option', () => { + const result = planCommitMessageGeneration( + { agentId: 'antigravity', model: 'Gemini 3.5 Flash (Medium)' }, + '-fix: something' + ) + + expect(result.ok).toBe(true) + expect(result.ok && result.plan.args.slice(0, 2)).toEqual([ + '--print=-fix: something', + '--sandbox' + ]) + }) + + // Why: pins argv construction only. Real agy 1.2.1 separately rejects a --print value + // that exactly matches a registered flag name (its own heuristic, independent of this + // fix) — verified `agy --print=--sandbox` still errors there. Real prompts are never + // literally a bare flag name, so this doesn't affect actual generation. + it('still glues an Antigravity prompt that collides with a flag name onto --print', () => { + const result = planCommitMessageGeneration( + { agentId: 'antigravity', model: 'Gemini 3.5 Flash (Medium)' }, + '--sandbox' + ) + + expect(result.ok).toBe(true) + expect(result.ok && result.plan.args.slice(0, 2)).toEqual(['--print=--sandbox', '--sandbox']) + }) + + // Why: agy has no documented stdin mode for --print (#19539's body: "--print ... is + // not a boolean flag that automatically reads from stdin; it expects the prompt + // string as its option argument"), so a large staged patch now rides on argv. This + // is the same unguarded argv delivery cursor/kimi/copilot already use (see the + // parity assertion below) — pinned here as a known property, not a regression. + it('puts a large Antigravity prompt on argv with no size guard, same as other argv-delivery agents', () => { + const bigPrompt = 'y'.repeat(70_000) + const result = planCommitMessageGeneration( + { agentId: 'antigravity', model: 'Gemini 3.5 Flash (Medium)' }, + bigPrompt + ) + + expect(result.ok).toBe(true) + expect(result.ok && result.plan.args[0]).toBe(`--print=${bigPrompt}`) + expect(result.ok && result.plan.stdinPayload).toBeNull() + + const cursorResult = planCommitMessageGeneration( + { agentId: 'cursor', model: 'auto' }, + bigPrompt + ) + expect(cursorResult.ok).toBe(true) + expect(cursorResult.ok && cursorResult.plan.args.at(-1)).toBe(bigPrompt) + expect(cursorResult.ok && cursorResult.plan.stdinPayload).toBeNull() + }) + + // Why: real #14059 reproduction config — CLI arguments field repeats --model and adds + // --add-dir/--effort/--dangerously-skip-permissions. Confirms none of it gets swallowed + // into the --print operand and the duplicate --model is deduped the same way every + // other spec's recipe args already are (DEFAULT_SINGLETON_OPTIONS, unaffected by + // argument order). + it('keeps #14059-style recipe CLI arguments intact and deduped around the print operand', () => { + const result = planCommitMessageGeneration( + { + agentId: 'antigravity', + model: 'Gemini 3.5 Flash (Medium)', + agentArgs: + '--add-dir . --model gemini-3.6-flash --effort low --dangerously-skip-permissions' + }, + 'Generate a concise git commit message for the currently staged changes.' + ) + + expect(result).toEqual({ + ok: true, + plan: { + binary: 'agy', + args: [ + '--print=Generate a concise git commit message for the currently staged changes.', + '--sandbox', + '--model', + 'gemini-3.6-flash', + '--add-dir', + '.', + '--effort', + 'low', + '--dangerously-skip-permissions' + ], + stdinPayload: null, + label: 'Antigravity' + } + }) + }) + it('plans Codex exec as non-interactive read-only generation with the prompt on stdin only', () => { const result = planCommitMessageGeneration( { diff --git a/src/shared/constants.ts b/src/shared/constants.ts index 7a06e11dba3..6840d92adc9 100644 --- a/src/shared/constants.ts +++ b/src/shared/constants.ts @@ -296,6 +296,7 @@ export function getDefaultUIState(): PersistedUIState { usagePercentageDisplay: DEFAULT_USAGE_PERCENTAGE_DISPLAY, statusBarUsageMode: DEFAULT_STATUS_BAR_USAGE_MODE, dismissedUpdateVersion: null, + dismissedUnexpectedSignoutVersion: null, lastUpdateCheckAt: null, trustedOrcaHooks: {}, setupScriptPromptDismissedRepoIds: [], diff --git a/src/shared/execution-host-registry.test.ts b/src/shared/execution-host-registry.test.ts index e509fe05bfc..e397e8ed5bf 100644 --- a/src/shared/execution-host-registry.test.ts +++ b/src/shared/execution-host-registry.test.ts @@ -320,17 +320,15 @@ describe('execution host registry', () => { ]) }) - it('includes runtime hosts from repo ownership but marks them disconnected without live status', () => { + it('keeps runtime hosts checking before their first status result', () => { const hosts = buildExecutionHostRegistry({ repos: [{ connectionId: null, executionHostId: 'runtime:env-2' }], settings: { activeRuntimeEnvironmentId: null } }) - // No live status means no evidence the Orca server is reachable, so it must - // read 'disconnected' rather than defaulting to 'available'/"Connected". expect(hosts).toMatchObject([ { id: 'local', health: 'local' }, - { id: 'runtime:env-2', kind: 'runtime', label: 'env-2', health: 'disconnected' } + { id: 'runtime:env-2', kind: 'runtime', label: 'env-2', health: 'connecting' } ]) }) @@ -373,3 +371,29 @@ describe('execution host registry', () => { ]) }) }) + +it('keeps an initial unknown-transport verification connecting', () => { + const hosts = buildExecutionHostRegistry({ + repos: [], + settings: null, + runtimeEnvironments: [{ id: 'host', name: 'Host' }], + runtimeStatusByEnvironmentId: new Map([ + [ + 'host', + { + status: null, + snapshot: { + environmentId: 'host', + pairingRevision: 1, + sequence: 1, + checkedAt: 0, + status: null, + verification: 'checking', + transport: 'unknown' + } + } + ] + ]) + }) + expect(hosts.find((host) => host.id === 'runtime:host')?.health).toBe('connecting') +}) diff --git a/src/shared/execution-host-registry.ts b/src/shared/execution-host-registry.ts index a970f9da45c..bad6b40f257 100644 --- a/src/shared/execution-host-registry.ts +++ b/src/shared/execution-host-registry.ts @@ -1,3 +1,4 @@ +import type { RuntimeHostStatusSnapshot } from './runtime-host-status' import { LOCAL_EXECUTION_HOST_ID, getLocalExecutionHostLabel, @@ -49,6 +50,7 @@ type RuntimeEnvironmentSummary = { } type RuntimeHostStatus = { + snapshot?: RuntimeHostStatusSnapshot status?: RuntimeStatus | null remoteControl?: RuntimeStatus['remoteControl'] | null appVersion?: string | null @@ -158,9 +160,24 @@ function addRuntimeHost( const hostId = toRuntimeExecutionHostId(environmentId) const runtimeStatus = statusByEnvironmentId?.get(environmentId) const status = runtimeStatus?.status - const compatibility = runtimeCompatibility(status) + const snapshot = runtimeStatus?.snapshot + const metadata = status ?? snapshot?.status + const compatibility = runtimeCompatibility(metadata) const remoteControl = runtimeStatus?.remoteControl ?? status?.remoteControl - const controlHealth = runtimeControlHealth(remoteControl) + const controlHealth = snapshot?.retired + ? 'disconnected' + : snapshot?.verification === 'blocked' + ? 'blocked' + : !runtimeStatus || + snapshot?.verification === 'checking' || + snapshot?.transport === 'disconnected' || + snapshot?.transport === 'connecting' + ? 'connecting' + : snapshot?.transport === 'ready' + ? compatibility?.kind === 'blocked' + ? 'blocked' + : 'available' + : runtimeControlHealth(remoteControl) setHost(hosts, { id: hostId, kind: 'runtime', @@ -168,12 +185,12 @@ function addRuntimeHost( detail: 'Orca server', health: controlHealth ?? runtimeHealth(status, compatibility, remoteControl), compatibility: compatibility ?? undefined, - capabilities: status?.capabilities, - appVersion: runtimeStatus?.appVersion ?? status?.appVersion ?? null, - protocolVersion: status?.runtimeProtocolVersion ?? status?.protocolVersion ?? null, + capabilities: metadata?.capabilities, + appVersion: runtimeStatus?.appVersion ?? metadata?.appVersion ?? null, + protocolVersion: metadata?.runtimeProtocolVersion ?? metadata?.protocolVersion ?? null, minCompatibleClientVersion: - status?.minCompatibleRuntimeClientVersion ?? status?.minCompatibleMobileVersion ?? null, - platform: status?.hostPlatform ?? null, + metadata?.minCompatibleRuntimeClientVersion ?? metadata?.minCompatibleMobileVersion ?? null, + platform: metadata?.hostPlatform ?? null, remoteControlState: remoteControl ?? null, ...(source ? { source } : {}) }) diff --git a/src/shared/mobile-push-contract.test.ts b/src/shared/mobile-push-contract.test.ts new file mode 100644 index 00000000000..e1993b78949 --- /dev/null +++ b/src/shared/mobile-push-contract.test.ts @@ -0,0 +1,21 @@ +import { expect, it } from 'vitest' +import { parseMobilePushRegistration } from './mobile-push-contract' +it('rejects malformed known preferences', () => { + expect( + parseMobilePushRegistration({ + registrationId: 'r', + expiresAt: Date.now() + 60000, + filter: { onlyWhenDesktopAway: 'true' } + }) + ).toBeUndefined() +}) + +it('retains valid preferences while ignoring unknown fields', () => { + expect( + parseMobilePushRegistration({ + registrationId: 'r', + expiresAt: 123, + filter: { onlyWhenDesktopAway: true, sound: false, unknown: true } + })?.filter + ).toEqual({ onlyWhenDesktopAway: true, sound: false }) +}) diff --git a/src/shared/mobile-push-contract.ts b/src/shared/mobile-push-contract.ts new file mode 100644 index 00000000000..c9dbd426ea9 --- /dev/null +++ b/src/shared/mobile-push-contract.ts @@ -0,0 +1,99 @@ +// Why: the desktop host, the push gateway, and the phone must agree on these +// exact strings. See cloud/packages/push-contract/src. + +export const MOBILE_PUSH_SOURCES = ['agent-task-complete', 'terminal-bell', 'plugin'] as const +export type MobilePushSource = (typeof MOBILE_PUSH_SOURCES)[number] + +// The only two states a phone can be told about; the host maps its richer +// agent status onto them before it ever reaches the gateway. +export const MOBILE_PUSH_AGENT_STATES = ['needs-input', 'finished'] as const +export type MobilePushAgentState = (typeof MOBILE_PUSH_AGENT_STATES)[number] + +export const MOBILE_PUSH_PLATFORMS = ['ios', 'android'] as const +export type MobilePushPlatform = (typeof MOBILE_PUSH_PLATFORMS)[number] + +export const MOBILE_PUSH_APNS_ENVIRONMENTS = ['sandbox', 'production'] as const +export type MobilePushApnsEnvironment = (typeof MOBILE_PUSH_APNS_ENVIRONMENTS)[number] + +export type MobilePushFilter = { + onlyWhenDesktopAway?: boolean + sound?: boolean +} + +/** Persisted on the paired DeviceEntry so a host restart can push without the phone re-registering. */ +export type MobilePushRegistration = { + registrationId: string + filter: MobilePushFilter + expiresAt: number +} + +export type MobilePushRegisterInput = { + deviceId: string + platform: MobilePushPlatform + token: string + apnsEnvironment?: MobilePushApnsEnvironment + filter: MobilePushFilter +} + +export type MobilePushRegisterResult = + | { registered: true; registrationId: string } + | { + registered: false + // Storage failures require registration to be retried; throttling leaves the prior route intact. + reason: + | 'gateway_unreachable' + | 'gateway_rejected' + | 'not_mobile' + | 'registration_storage_failed' + | 'throttled' + } + +function parseFilter(value: unknown): MobilePushFilter | null { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return null + } + const filter = value as Partial + if ( + (filter.onlyWhenDesktopAway !== undefined && typeof filter.onlyWhenDesktopAway !== 'boolean') || + (filter.sound !== undefined && typeof filter.sound !== 'boolean') + ) { + return null + } + return { + ...(typeof filter.onlyWhenDesktopAway === 'boolean' + ? { onlyWhenDesktopAway: filter.onlyWhenDesktopAway } + : {}), + ...(typeof filter.sound === 'boolean' ? { sound: filter.sound } : {}) + } +} + +/** + * Reads a persisted registration back. Returns undefined for invalid data, + * so a bad row degrades to "this device has no push" + * instead of failing the whole registry load. + */ +export function parseMobilePushRegistration(value: unknown): MobilePushRegistration | undefined { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return undefined + } + const registration = value as Partial + const filter = parseFilter(registration.filter) + if ( + typeof registration.registrationId !== 'string' || + registration.registrationId.length === 0 || + !filter || + typeof registration.expiresAt !== 'number' || + !Number.isFinite(registration.expiresAt) + ) { + return undefined + } + return { + registrationId: registration.registrationId, + filter, + expiresAt: registration.expiresAt + } +} + +export type MobilePushTestResult = + | { accepted: true } + | { accepted: false; reason: 'not_registered' | 'unavailable' | 'rate_limited' | 'rejected' } diff --git a/src/shared/native-chat-agent-profiles.test.ts b/src/shared/native-chat-agent-profiles.test.ts index 4d64e283c01..546a4bf9db0 100644 --- a/src/shared/native-chat-agent-profiles.test.ts +++ b/src/shared/native-chat-agent-profiles.test.ts @@ -1,5 +1,9 @@ import { describe, expect, it } from 'vitest' -import { getNativeChatAgentProfile } from './native-chat-agent-profiles' +import { + getHostClaimedNativeChatCommands, + getNativeChatAgentProfile, + getVerifiedNativeChatCommands +} from './native-chat-agent-profiles' describe('native chat agent picker profiles', () => { // The composer types the same `/` for every agent; skillPrefix is only the @@ -27,3 +31,28 @@ describe('native chat agent picker profiles', () => { expect(getNativeChatAgentProfile('custom-agent')).toBeNull() }) }) + +describe('host-claimed native chat commands', () => { + function names(agent: string): string[] { + return getHostClaimedNativeChatCommands(agent).map((command) => command.name) + } + + // Claude's harness expands a slash command out of the message body, so claiming + // its catalog only answered "/init is not available" for commands that do run. + it('claims nothing from the Claude-family catalog', () => { + expect(names('claude')).toEqual([]) + expect(names('openclaude')).toEqual([]) + }) + + it('keeps the Codex catalog claimed except the model-driven /goal', () => { + expect(names('codex')).toContain('permissions') + expect(names('codex')).toContain('vim') + expect(names('codex')).not.toContain('goal') + expect(getVerifiedNativeChatCommands('codex').map((command) => command.name)).toContain('goal') + }) + + it('claims the whole catalog for agents with no pass-through policy', () => { + expect(names('custom-agent')).toEqual(['clear', 'help']) + expect(names('grok')).toEqual([]) + }) +}) diff --git a/src/shared/native-chat-agent-profiles.ts b/src/shared/native-chat-agent-profiles.ts index 6f86313d17d..82fe88e9ac3 100644 --- a/src/shared/native-chat-agent-profiles.ts +++ b/src/shared/native-chat-agent-profiles.ts @@ -5,20 +5,31 @@ export type NativeChatAgentProfile = { skillPrefix: '$' | '/' /** OpenClaude reads Claude-owned roots, so this can differ from the agent. */ skillSourceOwner: AgentType + /** The agent's own harness expands a slash command out of the message text, so + * the chat host claims only the commands it implements itself. */ + expandsSlashCommandsFromText?: true + /** Catalog commands the model acts on when they arrive as prose, even though + * the runtime has no slash parser of its own. */ + textDrivenCommands?: readonly string[] } const NATIVE_CHAT_AGENT_PROFILES: Partial> = { codex: { skillPrefix: '$', - skillSourceOwner: 'codex' + skillSourceOwner: 'codex', + // The app-server has no slash parser, but the model owns goal tools and + // calls create_goal itself when `/goal ` reaches it as prose. + textDrivenCommands: ['goal'] }, claude: { skillPrefix: '/', - skillSourceOwner: 'claude' + skillSourceOwner: 'claude', + expandsSlashCommandsFromText: true }, openclaude: { skillPrefix: '/', - skillSourceOwner: 'claude' + skillSourceOwner: 'claude', + expandsSlashCommandsFromText: true }, grok: { skillPrefix: '/', @@ -38,3 +49,34 @@ export function getNativeChatAgentProfile( export function getVerifiedNativeChatCommands(agent: AgentType): readonly SlashCommandSuggestion[] { return agent === 'grok' ? [] : getAgentSlashCommands(agent) } + +/** The mirror of the claimed set: catalog commands this agent acts on when they + * arrive as message text. The picker offers these too, so a command the agent + * implements is discoverable and not merely typable. */ +export function getTextDrivenNativeChatCommands( + agent: AgentType | null | undefined +): readonly SlashCommandSuggestion[] { + if (!agent) { + return [] + } + const names = new Set(getNativeChatAgentProfile(agent)?.textDrivenCommands ?? []) + return names.size === 0 + ? [] + : getVerifiedNativeChatCommands(agent).filter((command) => names.has(command.name)) +} + +/** Catalog commands the chat host answers itself. Whatever is left over reaches + * the agent as ordinary text, which is only correct where the agent implements + * the command — so an agent unclaims a command only via the profile above. + * Claiming stays the default: it is what stops a hand-typed `/clear` from being + * sent to the model as literal prompt text. */ +export function getHostClaimedNativeChatCommands( + agent: AgentType +): readonly SlashCommandSuggestion[] { + const profile = getNativeChatAgentProfile(agent) + if (profile?.expandsSlashCommandsFromText) { + return [] + } + const passedThrough = new Set(profile?.textDrivenCommands ?? []) + return getVerifiedNativeChatCommands(agent).filter((command) => !passedThrough.has(command.name)) +} diff --git a/src/shared/native-chat-slash-commands.test.ts b/src/shared/native-chat-slash-commands.test.ts index 32d3d2d8876..33219d8f7db 100644 --- a/src/shared/native-chat-slash-commands.test.ts +++ b/src/shared/native-chat-slash-commands.test.ts @@ -89,4 +89,39 @@ describe('a session that reports its own command surface', () => { it('splits skills out for the picker to group on its own', () => { expect(sessionReportedSkillNames(reported)).toEqual(['ref-oss']) }) + + it('prefers the description the session reported over the curated one', () => { + expect( + sessionSlashCommandSuggestions('claude', [ + { name: 'clear', kind: 'command', description: 'Wipe the transcript' }, + { name: 'goal', kind: 'command', description: 'Set or view the goal' }, + { name: 'compact', kind: 'command' } + ]) + ).toEqual([ + { name: 'clear', description: 'Wipe the transcript' }, + { name: 'goal', description: 'Set or view the goal' }, + { name: 'compact', description: 'Summarize and compact the conversation' } + ]) + }) + + it('keeps a reported description and argument hint the curated catalog never claims', () => { + expect( + sessionSlashCommandSuggestions('codex', [ + { + name: 'opsx:apply', + kind: 'command', + description: 'Apply the plan', + argumentHint: '', + kindUnspecified: true + } + ]) + ).toEqual([ + { + name: 'opsx:apply', + description: 'Apply the plan', + argumentHint: '', + kindUnspecified: true + } + ]) + }) }) diff --git a/src/shared/native-chat-slash-commands.ts b/src/shared/native-chat-slash-commands.ts index 9337e9c78f7..6360ca05f83 100644 --- a/src/shared/native-chat-slash-commands.ts +++ b/src/shared/native-chat-slash-commands.ts @@ -12,6 +12,8 @@ export type SlashCommandSuggestion = { name: string /** Optional one-line description for the suggestion row. */ description?: string + /** Provider-authored argument sketch, e.g. ``. */ + argumentHint?: string kindUnspecified?: true } @@ -93,9 +95,10 @@ export function getAgentSlashCommands(agent: AgentType): readonly SlashCommandSu } /** The command rows for a session that reports its own `/` surface. The report - * is the authority on WHICH commands exist; the curated catalog above is kept - * only as the description source for the names both know about. Skills are - * excluded — they render in the picker's own skills group. */ + * is the authority on WHICH commands exist and, when it carries one, on how a + * command is described; the curated catalog above only covers the names whose + * report is text-free. Skills are excluded — they render in the picker's own + * skills group. */ export function sessionSlashCommandSuggestions( agent: AgentType, reported: readonly AgentSessionSlashCommand[] @@ -106,10 +109,11 @@ export function sessionSlashCommandSuggestions( return reported .filter((entry) => entry.kind === 'command') .map((entry) => { - const description = described.get(entry.name) + const description = entry.description ?? described.get(entry.name) return { name: entry.name, ...(description ? { description } : {}), + ...(entry.argumentHint ? { argumentHint: entry.argumentHint } : {}), ...(entry.kindUnspecified ? { kindUnspecified: true as const } : {}) } }) diff --git a/src/renderer/src/components/native-chat/native-chat-turn-activity.test.ts b/src/shared/native-chat-turn-activity.test.ts similarity index 72% rename from src/renderer/src/components/native-chat/native-chat-turn-activity.test.ts rename to src/shared/native-chat-turn-activity.test.ts index a819e3054a2..3cc64f4e106 100644 --- a/src/renderer/src/components/native-chat/native-chat-turn-activity.test.ts +++ b/src/shared/native-chat-turn-activity.test.ts @@ -1,8 +1,5 @@ import { describe, expect, it } from 'vitest' -import type { - AgentJournalItemBody, - AgentJournalRenderItem -} from '../../../../shared/agent-session-journal-types' +import type { AgentJournalItemBody, AgentJournalRenderItem } from './agent-session-journal-types' import { selectStructuredAgentTurnActivity } from './native-chat-turn-activity' function item(sequence: number, body: AgentJournalItemBody): AgentJournalRenderItem { @@ -34,6 +31,49 @@ describe('selectStructuredAgentTurnActivity', () => { expect(activity).toEqual({ kind: 'description', text: 'Preparing the answer' }) }) + it("never puts the model's reasoning on the indicator line", () => { + const reasoning = item(2, { + kind: 'message', + role: 'reasoning', + blocks: [{ type: 'text', text: 'Let me check whether the journal already records this' }] + }) + + // Reasoning is the turn's content; the row says the turn is thinking instead. + expect(selectStructuredAgentTurnActivity([turnStart, reasoning], 'turn-1')).toBeNull() + // An ordinary status row is still a description of what the turn is doing. + expect( + selectStructuredAgentTurnActivity( + [turnStart, reasoning, item(3, { kind: 'status', text: 'Updating the plan' })], + 'turn-1' + ) + ).toEqual({ kind: 'description', text: 'Updating the plan' }) + // Provider-authored copy is unaffected, so Codex keeps its line. + expect( + selectStructuredAgentTurnActivity([turnStart, reasoning], 'turn-1', { + turnId: 'turn-1', + text: 'Running a command' + }) + ).toEqual({ kind: 'description', text: 'Running a command' }) + }) + + it('skips reasoning behind a typed turn item too', () => { + const typedTurnStart = item(1, { kind: 'turn', turnId: 'turn-1', state: 'running' }) + + expect( + selectStructuredAgentTurnActivity( + [ + typedTurnStart, + item(2, { + kind: 'message', + role: 'reasoning', + blocks: [{ type: 'text', text: 'Weighing two approaches' }] + }) + ], + 'turn-1' + ) + ).toBeNull() + }) + it('prefers matching ephemeral provider activity over journal-derived status', () => { const activity = selectStructuredAgentTurnActivity( [turnStart, item(2, { kind: 'status', text: 'Older journal status' })], diff --git a/src/renderer/src/components/native-chat/native-chat-turn-activity.ts b/src/shared/native-chat-turn-activity.ts similarity index 86% rename from src/renderer/src/components/native-chat/native-chat-turn-activity.ts rename to src/shared/native-chat-turn-activity.ts index e42abea2bf6..fbc1756529b 100644 --- a/src/renderer/src/components/native-chat/native-chat-turn-activity.ts +++ b/src/shared/native-chat-turn-activity.ts @@ -1,11 +1,8 @@ -import { readAgentJournalTurn } from '../../../../shared/agent-session-turn-record' -import type { AgentJournalRenderItem } from '../../../../shared/agent-session-journal-types' -import type { AgentSessionTurnActivity } from '../../../../shared/agent-session-wire' -import { normalizePromptField } from '../../../../shared/agent-status-field-normalization' -import { - describeActiveToolCall, - formatActiveToolLabel -} from '../../../../shared/native-chat-tool-activity' +import { readAgentJournalTurn } from './agent-session-turn-record' +import type { AgentJournalRenderItem } from './agent-session-journal-types' +import type { AgentSessionTurnActivity } from './agent-session-wire' +import { normalizePromptField } from './agent-status-field-normalization' +import { describeActiveToolCall, formatActiveToolLabel } from './native-chat-tool-activity' export type NativeChatTurnActivity = { kind: 'description'; text: string } diff --git a/src/shared/native-chat-turn-status.test.ts b/src/shared/native-chat-turn-status.test.ts index 3fdcccb7bf3..c98d4f79a73 100644 --- a/src/shared/native-chat-turn-status.test.ts +++ b/src/shared/native-chat-turn-status.test.ts @@ -1,24 +1,16 @@ import { describe, expect, it } from 'vitest' -import type { NativeChatMessage } from './native-chat-types' import { + describeNativeChatActiveTurnLabel, describeNativeChatTurnStatus, + formatNativeChatActiveTurnLabel, formatNativeChatDuration, formatNativeChatTurnStatusLabel, nativeChatElapsedSeconds, - nativeChatTurnHasResponse, reduceNativeChatTurnTiming, selectNativeChatTurnStatuses, type NativeChatTurnTimingByTurn } from './native-chat-turn-status' -function message( - id: string, - role: NativeChatMessage['role'], - blocks: NativeChatMessage['blocks'] -): NativeChatMessage { - return { id, role, blocks, timestamp: null, source: 'transcript' } -} - describe('formatNativeChatDuration', () => { it.each([ [0, '0s'], @@ -59,6 +51,51 @@ describe('describeNativeChatTurnStatus', () => { }) }) +describe('describeNativeChatActiveTurnLabel', () => { + it('lets provider activity beat both fallbacks', () => { + expect( + describeNativeChatActiveTurnLabel({ + activityText: 'Reading src/main.ts', + thinking: true, + elapsedSeconds: 12 + }) + ).toEqual({ source: 'activity', text: 'Reading src/main.ts' }) + }) + + it('falls back to reasoning when the provider says nothing usable', () => { + expect( + describeNativeChatActiveTurnLabel({ activityText: ' ', thinking: true, elapsedSeconds: 12 }) + ).toEqual({ source: 'status', key: 'thinking', duration: null }) + expect( + describeNativeChatActiveTurnLabel({ activityText: null, thinking: true, elapsedSeconds: 12 }) + ).toEqual({ source: 'status', key: 'thinking', duration: null }) + }) + + it('falls back to the running clock when the turn is neither talking nor reasoning', () => { + expect(describeNativeChatActiveTurnLabel({ thinking: false, elapsedSeconds: 184 })).toEqual({ + source: 'status', + key: 'workingFor', + duration: '3m 4s' + }) + }) +}) + +describe('formatNativeChatActiveTurnLabel', () => { + it('renders the one live row in English for platforms without i18n', () => { + expect( + formatNativeChatActiveTurnLabel({ + activityText: 'Running pnpm test', + thinking: false, + elapsedSeconds: 4 + }) + ).toBe('Running pnpm test') + expect(formatNativeChatActiveTurnLabel({ thinking: true, elapsedSeconds: 4 })).toBe('Thinking') + expect(formatNativeChatActiveTurnLabel({ thinking: false, elapsedSeconds: 12 })).toBe( + 'Working for 12s' + ) + }) +}) + describe('formatNativeChatTurnStatusLabel', () => { it('renders each state in English for platforms without i18n', () => { expect( @@ -73,45 +110,6 @@ describe('formatNativeChatTurnStatusLabel', () => { }) }) -describe('nativeChatTurnHasResponse', () => { - const user = message('u1', 'user', [{ type: 'text', text: 'go' }]) - - it('is false while the turn has produced nothing', () => { - expect(nativeChatTurnHasResponse([user], 0)).toBe(false) - }) - - it('ignores a whitespace-only assistant block', () => { - const blank = message('a1', 'assistant', [{ type: 'text', text: ' \n ' }]) - expect(nativeChatTurnHasResponse([user, blank], 0)).toBe(false) - }) - - it('is true on the first real text, tool call, or tool result', () => { - expect( - nativeChatTurnHasResponse( - [user, message('a1', 'assistant', [{ type: 'text', text: 'hi' }])], - 0 - ) - ).toBe(true) - expect( - nativeChatTurnHasResponse( - [user, message('t1', 'tool', [{ type: 'tool-call', name: 'Read', input: {} }])], - 0 - ) - ).toBe(true) - expect( - nativeChatTurnHasResponse( - [user, message('t1', 'tool', [{ type: 'tool-result', output: 'ok' }])], - 0 - ) - ).toBe(true) - }) - - it('does not count output that preceded the latest user turn', () => { - const earlier = message('a0', 'assistant', [{ type: 'text', text: 'old' }]) - expect(nativeChatTurnHasResponse([earlier, user], 1)).toBe(false) - }) -}) - describe('reduceNativeChatTurnTiming', () => { const validTurnKeys = new Set(['u1']) @@ -290,18 +288,18 @@ describe('reduceNativeChatTurnTiming', () => { }) describe('selectNativeChatTurnStatuses', () => { - it('reports the working turn as thinking until it produces output', () => { + it('carries the reasoning verdict it is given onto the working turn', () => { const { active } = selectNativeChatTurnStatuses( { u1: { startedAt: 1_000, workedSeconds: null } }, - { activeTurnKey: 'u1', isWorking: true, hasCurrentTurnResponse: false } + { activeTurnKey: 'u1', isWorking: true, thinking: true } ) expect(active).toEqual({ startedAt: 1_000, thinking: true, workedSeconds: null }) }) - it('stops thinking once the turn has output', () => { + it('reports a working turn that is not reasoning as counting', () => { const { active } = selectNativeChatTurnStatuses( { u1: { startedAt: 1_000, workedSeconds: null } }, - { activeTurnKey: 'u1', isWorking: true, hasCurrentTurnResponse: true } + { activeTurnKey: 'u1', isWorking: true, thinking: false } ) expect(active?.thinking).toBe(false) }) @@ -309,7 +307,7 @@ describe('selectNativeChatTurnStatuses', () => { it('exposes settled turns and resolves the active one from them when idle', () => { const { active, completedByTurn } = selectNativeChatTurnStatuses( { u1: { startedAt: 1_000, workedSeconds: 12 } }, - { activeTurnKey: 'u1', isWorking: false, hasCurrentTurnResponse: true } + { activeTurnKey: 'u1', isWorking: false, thinking: false } ) expect(completedByTurn.u1).toEqual({ startedAt: 1_000, thinking: false, workedSeconds: 12 }) expect(active).toEqual(completedByTurn.u1) @@ -318,7 +316,7 @@ describe('selectNativeChatTurnStatuses', () => { it('omits an in-flight turn from the completed map', () => { const { completedByTurn } = selectNativeChatTurnStatuses( { u1: { startedAt: 1_000, workedSeconds: null } }, - { activeTurnKey: 'u1', isWorking: true, hasCurrentTurnResponse: true } + { activeTurnKey: 'u1', isWorking: true, thinking: false } ) expect(completedByTurn).toEqual({}) }) diff --git a/src/shared/native-chat-turn-status.ts b/src/shared/native-chat-turn-status.ts index aaecbc05ce5..b34b199e9d0 100644 --- a/src/shared/native-chat-turn-status.ts +++ b/src/shared/native-chat-turn-status.ts @@ -3,8 +3,6 @@ // and the mobile app (used directly — mobile ships English only) so the two // surfaces never drift. Everything here is pure; each platform owns its own clock. -import type { NativeChatMessage } from './native-chat-types' - export const NATIVE_CHAT_TURN_STATUS_COPY = { thinking: 'Thinking', workingFor: 'Working for {{value0}}', @@ -48,6 +46,52 @@ export function describeNativeChatTurnStatus({ return { key: 'workingFor', duration: formatNativeChatDuration(elapsedSeconds) } } +/** The two readings that label a live turn's one indicator row, carried together + * so a surface cannot pick up one without the other. */ +export type NativeChatLiveTurnIndicator = { + thinking: boolean + activityText: string | null +} + +export type NativeChatActiveTurnLabel = + | { source: 'activity'; text: string } + | { source: 'status'; key: 'thinking' | 'workingFor'; duration: string | null } + +/** The live turn's single indicator label. Provider activity wins because it is the + * only text that says what the turn is actually doing; reasoning is next; the + * running clock is the floor. Shared so desktop and mobile cannot disagree. */ +export function describeNativeChatActiveTurnLabel({ + activityText, + thinking, + elapsedSeconds +}: { + activityText?: string | null + thinking: boolean + elapsedSeconds: number +}): NativeChatActiveTurnLabel { + const text = activityText?.trim() + if (text) { + return { source: 'activity', text } + } + return thinking + ? { source: 'status', key: 'thinking', duration: null } + : { source: 'status', key: 'workingFor', duration: formatNativeChatDuration(elapsedSeconds) } +} + +/** The live turn's label in English. For platforms without i18n (mobile). */ +export function formatNativeChatActiveTurnLabel(input: { + activityText?: string | null + thinking: boolean + elapsedSeconds: number +}): string { + const label = describeNativeChatActiveTurnLabel(input) + if (label.source === 'activity') { + return label.text + } + const copy = NATIVE_CHAT_TURN_STATUS_COPY[label.key] + return label.duration == null ? copy : copy.replaceAll('{{value0}}', label.duration) +} + /** Resolve the turn-status label in English. For platforms without i18n (mobile). */ export function formatNativeChatTurnStatusLabel(input: { thinking: boolean @@ -59,26 +103,6 @@ export function formatNativeChatTurnStatusLabel(input: { return duration == null ? copy : copy.replaceAll('{{value0}}', duration) } -/** True once the current turn has produced anything renderable — the boundary - * between the "Thinking" label and the counting "Working for N" label. */ -export function nativeChatTurnHasResponse( - messages: readonly NativeChatMessage[], - latestUserIndex: number -): boolean { - return messages - .slice(latestUserIndex + 1) - .some( - (message) => - (message.role === 'assistant' || message.role === 'tool') && - message.blocks.some( - (block) => - block.type === 'tool-call' || - block.type === 'tool-result' || - (block.type === 'text' && block.text.trim().length > 0) - ) - ) -} - export type NativeChatTurnTiming = { startedAt: number workedSeconds: number | null @@ -183,13 +207,14 @@ export function selectNativeChatTurnStatuses( activeTurnKey, isWorking, workingStartedAt, - hasCurrentTurnResponse, + thinking, settledByTurn }: { activeTurnKey: string isWorking: boolean workingStartedAt?: number | null - hasCurrentTurnResponse: boolean + /** Whether the active turn is reasoning right now, from its journal content. */ + thinking: boolean settledByTurn?: NativeChatSettledTurns } ): { active: NativeChatTurnStatus | null; completedByTurn: Record } { @@ -216,7 +241,7 @@ export function selectNativeChatTurnStatuses( active: isWorking ? { startedAt: workingStartedAt ?? timingByTurn[activeTurnKey]?.startedAt ?? null, - thinking: !hasCurrentTurnResponse, + thinking, workedSeconds: null } : (completedByTurn[activeTurnKey] ?? null), diff --git a/src/shared/native-chat-types.ts b/src/shared/native-chat-types.ts index 3a018d75e6b..c6835301c88 100644 --- a/src/shared/native-chat-types.ts +++ b/src/shared/native-chat-types.ts @@ -55,6 +55,8 @@ export type NativeChatToolCallBlock = NativeChatToolMetadata & { type: 'tool-call' name: string input: unknown + /** Provider-supplied identity within this item stream; absent on legacy transcripts and peers. */ + callId?: string /** Provider lifecycle when the structured app-server path can supply it. */ state?: 'running' | 'completed' | 'failed' } diff --git a/src/shared/native-chat-unverifiable-turn-status.test.ts b/src/shared/native-chat-unverifiable-turn-status.test.ts index 7e93f9cecc4..592ca699183 100644 --- a/src/shared/native-chat-unverifiable-turn-status.test.ts +++ b/src/shared/native-chat-unverifiable-turn-status.test.ts @@ -57,7 +57,7 @@ describe('authoritative unknown turn duration at the shared status consumer', () const options = { activeTurnKey: user.itemId, isWorking: false, - hasCurrentTurnResponse: true, + thinking: false, settledByTurn: selectStructuredAgentSettledTurns([user, recoveredTurn]) } @@ -87,7 +87,7 @@ describe('authoritative unknown turn duration at the shared status consumer', () { activeTurnKey: 'next', isWorking: true, - hasCurrentTurnResponse: true, + thinking: false, settledByTurn: selectStructuredAgentSettledTurns([userItem('turn-1'), item]) } ) @@ -113,7 +113,7 @@ describe('authoritative unknown turn duration at the shared status consumer', () { activeTurnKey: 'turn-1', isWorking: false, - hasCurrentTurnResponse: true, + thinking: false, settledByTurn: selectStructuredAgentSettledTurns([ userItem('turn-1'), userItem('old'), diff --git a/src/shared/notification-burst-cooldown.ts b/src/shared/notification-burst-cooldown.ts new file mode 100644 index 00000000000..e7616c57746 --- /dev/null +++ b/src/shared/notification-burst-cooldown.ts @@ -0,0 +1,37 @@ +const NOTIFICATION_COOLDOWN_MS = 5000 +const MAX_RECENT_NOTIFICATION_KEYS = 50 + +function pruneRecentNotifications(recentNotifications: Map, now: number): void { + if (recentNotifications.size <= MAX_RECENT_NOTIFICATION_KEYS) { + return + } + + for (const [key, ts] of recentNotifications) { + if (now - ts >= NOTIFICATION_COOLDOWN_MS) { + recentNotifications.delete(key) + } + } + + while (recentNotifications.size > MAX_RECENT_NOTIFICATION_KEYS) { + const oldest = recentNotifications.keys().next() + if (oldest.done) { + break + } + recentNotifications.delete(oldest.value) + } +} + +export function reserveNotificationCooldown( + recentNotifications: Map, + dedupeKey: string, + now: number +): boolean { + const lastSentAt = recentNotifications.get(dedupeKey) ?? 0 + if (now - lastSentAt < NOTIFICATION_COOLDOWN_MS) { + return false + } + recentNotifications.delete(dedupeKey) + recentNotifications.set(dedupeKey, now) + pruneRecentNotifications(recentNotifications, now) + return true +} diff --git a/src/shared/orchestration-fleet-agent-status-evidence.ts b/src/shared/orchestration-fleet-agent-status-evidence.ts index f03b1d9cbfa..43ff2c40cf4 100644 --- a/src/shared/orchestration-fleet-agent-status-evidence.ts +++ b/src/shared/orchestration-fleet-agent-status-evidence.ts @@ -1,7 +1,8 @@ // ─── The one identity/clock contract the fleet path reads ──────────────────── // A hook row carries a pane key, a delivery timestamp and, from newer hosts, an -// observation timestamp. Terminal identity lives on the runtime, not on the row. -// The fleet matcher needs both, and every fact it needs used to be an OPTIONAL +// observation timestamp. A row may carry the runtime handle observed with OSC, but +// fleet authority still resolves terminal identity from the runtime. The matcher needs both, +// and every fact it needs used to be an OPTIONAL // field on `AgentStatusIpcPayload` — so an unenriched producer published a row the // matcher silently failed to identify (failure table L-1) and a missing observation // clock silently degraded to the delivery clock (W1-14 / RR-W-P1A). @@ -10,8 +11,8 @@ // deliberately exposes no `terminalHandle?`, no `evidenceObservedAt?` and no raw // payload, so a consumer cannot read an absent identity or clock by accident. // -// This type never crosses IPC or the wire. `AgentStatusIpcPayload` is unchanged and -// remains what `agentStatus:set` / `agentStatus:getSnapshot` publish. +// This type never crosses IPC or the wire. `AgentStatusIpcPayload` remains what +// `agentStatus:set` / `agentStatus:getSnapshot` publish. import type { AgentStatusIpcPayload } from './agent-status-ipc-payload' import type { AgentStatusState, AgentType } from './agent-status-types' diff --git a/src/shared/persisted-ui-state-types.ts b/src/shared/persisted-ui-state-types.ts index 943813d7255..2a3eb411a0e 100644 --- a/src/shared/persisted-ui-state-types.ts +++ b/src/shared/persisted-ui-state-types.ts @@ -125,6 +125,8 @@ export type PersistedUIState = { /** Client-side footer presentation; verbose preserves the pre-roster all-window default. */ statusBarUsageMode?: StatusBarUsageMode dismissedUpdateVersion: string | null + /** App version that last dismissed the unexpected-sign-out card; null = never. Re-arms on each new version while still signed out. */ + dismissedUnexpectedSignoutVersion?: string | null lastUpdateCheckAt: number | null /** Dev-only update channel override; absent means the build's own channel. */ releaseChannelOverride?: ReleaseChannel | null diff --git a/src/shared/protocol-version.ts b/src/shared/protocol-version.ts index 6fa3eb9ef9b..aaec08cf46f 100644 --- a/src/shared/protocol-version.ts +++ b/src/shared/protocol-version.ts @@ -212,6 +212,8 @@ export const AUTOMATION_OWNER_FENCING_UPDATE_REQUIRED_MESSAGE = 'Editing automations on this host requires a newer Orca server. Update the HUB and try again.' export const AUTOMATION_CREATE_IDEMPOTENCY_RUNTIME_CAPABILITY = 'automation.create-idempotency.v1' as const +// Hosts without this capability have no notifications.registerPush RPC. +export const NOTIFICATIONS_REMOTE_PUSH_RUNTIME_CAPABILITY = 'notifications.remote-push.v1' as const // Generic native clients include the CLI and must not claim Electron-only page // placement support. @@ -312,7 +314,8 @@ export const RUNTIME_CAPABILITIES = [ SKILL_DELETE_CAPABILITY, AUTOMATION_LIST_HOST_SCOPE_RUNTIME_CAPABILITY, AUTOMATION_OWNER_FENCING_RUNTIME_CAPABILITY, - AUTOMATION_CREATE_IDEMPOTENCY_RUNTIME_CAPABILITY + AUTOMATION_CREATE_IDEMPOTENCY_RUNTIME_CAPABILITY, + NOTIFICATIONS_REMOTE_PUSH_RUNTIME_CAPABILITY ] as const export type RuntimeCapability = (typeof RUNTIME_CAPABILITIES)[number] | (string & {}) diff --git a/src/shared/remote-runtime-shared-control-test-server.ts b/src/shared/remote-runtime-shared-control-test-server.ts index 0e4adb1a69c..701ea0e5893 100644 --- a/src/shared/remote-runtime-shared-control-test-server.ts +++ b/src/shared/remote-runtime-shared-control-test-server.ts @@ -20,6 +20,7 @@ export type SharedControlTestServer = { } type ServerOptions = { + resultForRequest?: (method: string) => unknown delaySubscriptionReady?: boolean sendKeepaliveBeforeResponse?: boolean keepaliveDelayMs?: number @@ -174,7 +175,7 @@ function handleRequest( const streaming = isStreamingMethod(request.method) const result = streaming ? { type: 'ready', subscriptionId: `${request.method}:subscription` } - : { method: request.method } + : (options.resultForRequest?.(request.method) ?? { method: request.method }) const sendResponse = (): void => { if (options.sendUnknownResponseBeforeResponse) { sendEncrypted(ws, sharedKey, { diff --git a/src/shared/remote-workspace-session-projection.test.ts b/src/shared/remote-workspace-session-projection.test.ts index fdccd75b8e9..a11026e3581 100644 --- a/src/shared/remote-workspace-session-projection.test.ts +++ b/src/shared/remote-workspace-session-projection.test.ts @@ -6,6 +6,52 @@ import { import { getDefaultWorkspaceSession } from './constants' describe('remote workspace session projection', () => { + // The transient set this boundary mirrors. `recovery` is the tab's in-flight + // heal, timestamped with THIS machine's clock, and `pendingActivationSpawn` is + // a one-shot mount handoff — neither means anything on another client's row, + // and a foreign `startedAt` would be compared against the reader's Date.now(). + it('strips client-local transient tab fields on the way out', () => { + const session = { + ...getDefaultWorkspaceSession(), + activeRepoId: 'repo-a', + activeWorktreeId: 'repo-a::/srv/app', + activeTabId: 'tab-1', + tabsByWorktree: { + 'repo-a::/srv/app': [ + { + id: 'tab-1', + ptyId: 'pty-1', + worktreeId: 'repo-a::/srv/app', + title: 'Remote', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1, + pendingActivationSpawn: true, + recovery: { + attemptedAt: [1_000], + generation: 1, + outcome: 'failed' as const, + startedAt: 1_000, + reason: 'reattach-unverifiable' as const, + tabGeneration: 1 + } + } + ] + }, + terminalLayoutsByTabId: {} + } + + const projected = exportRemoteWorkspaceSession(session, { + isTargetWorktree: (worktreeId) => worktreeId.startsWith('repo-a::') + }) + + const exported = projected.tabsByWorktreePath['/srv/app'][0] as Record + expect(exported.recovery).toBeUndefined() + expect(exported.pendingActivationSpawn).toBeUndefined() + expect(exported.id).toBe('tab-1') + }) + it('exports terminal state using remote worktree paths instead of local repo ids', () => { const session = { ...getDefaultWorkspaceSession(), diff --git a/src/shared/remote-workspace-session-projection.ts b/src/shared/remote-workspace-session-projection.ts index 7f923050d36..29b3e15cd1d 100644 --- a/src/shared/remote-workspace-session-projection.ts +++ b/src/shared/remote-workspace-session-projection.ts @@ -32,9 +32,20 @@ function worktreePathFromId(worktreeId: string): string | null { } function tabToRemote(tab: TerminalTab, worktreePath: string): RemoteWorkspaceTerminalTab { - const { worktreeId: _worktreeId, pendingActivationSpawn: _pendingActivationSpawn, ...rest } = tab + // `recovery` joins the transient set for the same reason as + // pendingActivationSpawn: it describes THIS client's in-flight heal, and its + // timestamps are this machine's clock. On another client's row they would be + // compared against a foreign `Date.now()`. Nothing hands an unsanitized + // session to this boundary today; stripping here keeps that from mattering. + const { + worktreeId: _worktreeId, + pendingActivationSpawn: _pendingActivationSpawn, + recovery: _recovery, + ...rest + } = tab void _worktreeId void _pendingActivationSpawn + void _recovery return { ...rest, worktreePath } } diff --git a/src/shared/remote-workspace-types.ts b/src/shared/remote-workspace-types.ts index 4d6eec6021e..9544b709f9c 100644 --- a/src/shared/remote-workspace-types.ts +++ b/src/shared/remote-workspace-types.ts @@ -1,6 +1,12 @@ import type { TerminalLayoutSnapshot, TerminalTab } from './terminal-tab-types' -export type RemoteWorkspaceTerminalTab = Omit & { +// Transient client-local fields are omitted, not merely unset: `recovery` is +// this client's in-flight heal, stamped with this machine's clock, so the type +// must not let a future producer put one on the wire. +export type RemoteWorkspaceTerminalTab = Omit< + TerminalTab, + 'worktreeId' | 'pendingActivationSpawn' | 'recovery' +> & { worktreePath: string } diff --git a/src/shared/rpc-contract/accounts-params.ts b/src/shared/rpc-contract/accounts-params.ts new file mode 100644 index 00000000000..0a9559e9549 --- /dev/null +++ b/src/shared/rpc-contract/accounts-params.ts @@ -0,0 +1,81 @@ +import { z } from 'zod' + +export const CodexResetTarget = z.discriminatedUnion('runtime', [ + z.object({ runtime: z.literal('host'), wslDistro: z.null() }).strict(), + // Why: reset scope must identify one exact WSL distro; null means all slots only for selection. + z.object({ runtime: z.literal('wsl'), wslDistro: z.string().trim().min(1).max(255) }).strict() +]) + +export const CodexSelectionTarget = z.discriminatedUnion('runtime', [ + z.object({ runtime: z.literal('host'), wslDistro: z.null() }).strict(), + z + .object({ + runtime: z.literal('wsl'), + // A null distro intentionally means all WSL selection slots. + wslDistro: z.string().trim().min(1).max(255).nullable() + }) + .strict() +]) + +export const SelectAccountParams = z.object({ + accountId: z + .union([z.string().min(1, 'Missing accountId'), z.null()]) + .transform((v) => (v === null ? null : v)) +}) + +export const SelectCodexAccountForTargetParams = SelectAccountParams.extend({ + target: CodexSelectionTarget +}) + +export const RemoveAccountParams = z.object({ + accountId: z.string().min(1, 'Missing accountId') +}) + +export const CodexResetExpectedScope = z + .object({ + target: CodexResetTarget, + accountId: z.string().min(1, 'Missing accountId').max(512), + accountRevision: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER), + offerRevision: z.string().startsWith('v1:', 'Invalid offerRevision').max(4_096) + }) + .strict() + +export const ConsumeCodexResetCreditParams = z + .object({ + // Why: the phone owns the logical attempt key so a lost response can be + // retried without spending a finite earned credit twice. + idempotencyKey: z.uuid('Invalid idempotencyKey'), + expectedScope: CodexResetExpectedScope + }) + .strict() + +export const AddClaudeFromConfigDirParams = z.object({ + configDir: z.string().min(1, 'Missing configDir'), + runtime: z.enum(['host', 'wsl']).optional(), + wslDistro: z.string().nullish(), + previousLegacyCredentialsSha256: z + .string() + .regex(/^[a-f0-9]{64}$/, 'Invalid legacy credential digest') + .nullable() + .optional() +}) + +export const AddCodexFromHomeParams = z.object({ + sourceHome: z.string().min(1, 'Missing sourceHome'), + runtime: z.enum(['host', 'wsl']).optional(), + wslDistro: z.string().nullish() +}) + +// Why: `orca account list` prints only emails and the active ids, so it opts out +// of the forced all-provider usage refresh below — that lane bypasses the poll +// throttle and Retry-After gate and costs one serial round-trip per account. +export const ListAccountsParams = z.object({ + refreshUsage: z.boolean().default(true) +}) + +export const AccountsUnsubscribeParams = z.object({ + subscriptionId: z + .unknown() + .transform((value) => (typeof value === 'string' && value.length > 0 ? value : '')) + .pipe(z.string().min(1, 'Missing subscriptionId')) +}) diff --git a/src/shared/rpc-contract/agent-hooks-params.ts b/src/shared/rpc-contract/agent-hooks-params.ts new file mode 100644 index 00000000000..bed616bc0a7 --- /dev/null +++ b/src/shared/rpc-contract/agent-hooks-params.ts @@ -0,0 +1,14 @@ +import { z } from 'zod' + +export const PrepareCodexForWslPaneParams = z + .object({ + codexHome: z.string().max(4_096), + orcaCodexHome: z.string().max(4_096), + wslDistro: z + .string() + .trim() + .min(1) + .max(255) + .regex(/^[^\\/\r\n]+$/) + }) + .strict() diff --git a/src/shared/rpc-contract/agent-session-params.ts b/src/shared/rpc-contract/agent-session-params.ts new file mode 100644 index 00000000000..6a2aa23635d --- /dev/null +++ b/src/shared/rpc-contract/agent-session-params.ts @@ -0,0 +1,189 @@ +import { z } from 'zod' +import { isValidTerminalTabId } from '../terminal-tab-id' +import { + RESUMABLE_TUI_AGENTS, + getAgentResumeArgv, + hasUnsafeProviderSessionIdChars +} from '../agent-session-resume' +import { parseAgentSessionOperationTimestamp } from '../agent-session-host-authority' +import type { + RuntimeCreateAgentSessionRequest, + RuntimeEnsureAgentSessionRequest +} from '../agent-session-host-authority' +import { isTuiAgent } from '../tui-agent-config' + +export const MAX_WORKTREE_SELECTOR_LENGTH = 32_768 + +export const MAX_TRANSCRIPT_PATH_BYTES = 16 * 1024 + +export const MAX_PROMPT_BYTES = 256 * 1024 + +export const MAX_AGENT_ARGS_BYTES = 16 * 1024 + +export const MAX_LAUNCH_PREFERENCE_LENGTH = 512 + +export const StrictNonEmptyString = (max: number, message: string) => + z + .string() + .min(1, message) + .max(max, message) + .refine((value) => value === value.trim(), `${message}; surrounding whitespace is invalid`) + +export const WorktreeSelector = StrictNonEmptyString( + MAX_WORKTREE_SELECTOR_LENGTH, + 'Invalid worktree selector' +) + +export const Presentation = z.enum(['background', 'focused']) + +export const Placement = z + .object({ + tabId: z + .string() + .min(1) + .max(512) + .refine(isValidTerminalTabId, 'Invalid terminal tab ID') + .optional(), + leafId: z.string().min(1).max(128).optional() + }) + .strict() + .refine((value) => value.tabId !== undefined || value.leafId !== undefined, { + message: 'Placement must include a tab or leaf ID' + }) + +export const LaunchPreferences = z + .object({ + model: StrictNonEmptyString( + MAX_LAUNCH_PREFERENCE_LENGTH, + 'Invalid model preference' + ).optional(), + effort: StrictNonEmptyString( + MAX_LAUNCH_PREFERENCE_LENGTH, + 'Invalid effort preference' + ).optional(), + mode: StrictNonEmptyString(MAX_LAUNCH_PREFERENCE_LENGTH, 'Invalid mode preference').optional() + }) + .strict() + +export const PromptDelivery = z.enum(['auto-submit', 'draft']) + +export const AgentArgs = z + .string() + .refine( + (value) => Buffer.byteLength(value, 'utf8') <= MAX_AGENT_ARGS_BYTES, + 'Agent arguments are too large' + ) + .nullable() + +export const OmpResumeFilePath = z + .string() + .min(1) + .refine((value) => value === value.trim(), 'Invalid OMP resume path') + .refine( + (value) => + !hasUnsafeProviderSessionIdChars(value) && + Buffer.byteLength(value, 'utf8') <= MAX_TRANSCRIPT_PATH_BYTES, + 'Invalid OMP resume path' + ) + +export const ProviderSession = z + .object({ + key: z.enum(['session_id', 'conversation_id']), + id: StrictNonEmptyString(512, 'Invalid provider session ID').refine( + (value) => !value.startsWith('-') && !hasUnsafeProviderSessionIdChars(value), + 'Invalid provider session ID' + ), + transcriptPath: z + .string() + .min(1) + .refine((value) => value === value.trim(), 'Invalid transcript path') + .refine( + (value) => + !hasUnsafeProviderSessionIdChars(value) && + Buffer.byteLength(value, 'utf8') <= MAX_TRANSCRIPT_PATH_BYTES, + 'Invalid transcript path' + ) + .optional() + }) + .strict() + +export const AutomaticEnsure = z + .object({ + kind: z.literal('automatic'), + sleepingCheckpointId: z + .string() + .min(32) + .max(128) + .regex(/^[A-Za-z0-9_-]+$/), + presentation: Presentation.optional() + }) + .strict() + +export const ExplicitEnsure = z + .object({ + kind: z.literal('explicit'), + worktree: WorktreeSelector, + agent: z.enum(RESUMABLE_TUI_AGENTS), + providerSession: ProviderSession, + ompResumeFilePath: OmpResumeFilePath.optional(), + agentArgs: AgentArgs.optional(), + launchPreferences: LaunchPreferences.optional(), + presentation: Presentation.optional(), + placement: Placement.optional() + }) + .strict() + .superRefine((value, context) => { + if (value.ompResumeFilePath !== undefined && value.agent !== 'omp') { + context.addIssue({ + code: z.ZodIssueCode.custom, + path: ['ompResumeFilePath'], + message: 'OMP resume path requires the OMP agent' + }) + } + if (getAgentResumeArgv(value.agent, value.providerSession, value.ompResumeFilePath) === null) { + context.addIssue({ + code: z.ZodIssueCode.custom, + path: ['providerSession'], + message: 'Provider session is not resumable for this agent' + }) + } + }) + +export const EnsureAgentSessionParams: z.ZodType = + z.discriminatedUnion('kind', [AutomaticEnsure, ExplicitEnsure]) + +export const CreateAgentSessionParams: z.ZodType = z + .object({ + clientOperationId: z + .string() + .refine( + (value) => parseAgentSessionOperationTimestamp(value) !== null, + 'Invalid agent operation ID' + ), + worktree: WorktreeSelector, + agent: z.string().refine(isTuiAgent, 'Unknown agent preset'), + prompt: z + .string() + .refine( + (value) => Buffer.byteLength(value, 'utf8') <= MAX_PROMPT_BYTES, + 'Prompt is too large' + ) + .optional(), + promptDelivery: PromptDelivery.optional(), + agentArgs: AgentArgs.optional(), + launchPreferences: LaunchPreferences.optional(), + startupCwd: z.string().min(1).max(MAX_WORKTREE_SELECTOR_LENGTH).optional(), + presentation: Presentation.optional(), + placement: Placement.optional(), + viewMode: z.enum(['terminal', 'chat']).optional() + }) + .strict() + .superRefine((value, context) => { + if (value.promptDelivery === 'draft' && !value.prompt?.trim()) { + context.addIssue({ + code: z.ZodIssueCode.custom, + path: ['prompt'], + message: 'Draft delivery requires a non-empty prompt' + }) + } + }) diff --git a/src/shared/rpc-contract/ai-vault-params.ts b/src/shared/rpc-contract/ai-vault-params.ts new file mode 100644 index 00000000000..d036af9177f --- /dev/null +++ b/src/shared/rpc-contract/ai-vault-params.ts @@ -0,0 +1,73 @@ +import { z } from 'zod' +import { parseExecutionHostId } from '../execution-host' +import { AI_VAULT_AGENTS, AI_VAULT_SCOPE_PATHS_MAX_COUNT } from '../ai-vault-types' +import { OptionalBoolean } from './rpc-param-primitives' +import { AI_VAULT_SESSION_TITLE_REQUEST_MAX_COUNT } from '../ai-vault-session-title' + +// Why: bound limit + scopePaths so a client cannot force an unbounded scan. +// Each scopePath is a host-local match prefix (validated/capped, never used for +// traversal); the count/length caps mirror the worktree-schemas bounding style. +export const AI_VAULT_SCOPE_PATH_MAX_LENGTH = 4096 + +export const AI_VAULT_LIMIT_MAX = 2000 + +export const executionHostIdSchema = z.string().transform((value, ctx): `runtime:${string}` => { + const parsed = parseExecutionHostId(value) + if (parsed?.kind === 'runtime') { + return parsed.id + } + ctx.addIssue({ + code: 'custom', + message: 'Invalid runtime execution host id' + }) + return z.NEVER +}) + +export const AiVaultListSessionsParams = z + .object({ + limit: z + .unknown() + .transform((value) => + typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined + ) + .pipe(z.union([z.number().int(), z.undefined()])) + .optional(), + unlimited: OptionalBoolean, + force: OptionalBoolean, + scopePaths: z + .array(z.string().min(1).max(AI_VAULT_SCOPE_PATH_MAX_LENGTH)) + // Why: clamp instead of reject — scope paths only ever widen discovery, and + // rejecting would hard-break older/uncapped producers (web client, pre-cap + // desktop parents) that send more than the bound. + .transform((paths) => paths.slice(0, AI_VAULT_SCOPE_PATHS_MAX_COUNT)) + .optional(), + // Why: desktop/web callers name the runtime host they are addressing; mobile + // omits it. The scan itself is host-local either way, so the id must never + // change what is scanned — it only restamps the shared cached result. + executionHostId: executionHostIdSchema.optional() + }) + .superRefine((params, ctx) => { + if (params.unlimited !== true && params.limit && params.limit > AI_VAULT_LIMIT_MAX) { + ctx.addIssue({ code: 'custom', path: ['limit'], message: 'Limit exceeds maximum' }) + } + }) + +export const AiVaultPrepareSessionResumeParams = z.object({ + agent: z.enum(AI_VAULT_AGENTS), + sessionId: z.string().min(1).max(512).optional(), + filePath: z.string().min(1).max(AI_VAULT_SCOPE_PATH_MAX_LENGTH), + codexHome: z.string().min(1).max(AI_VAULT_SCOPE_PATH_MAX_LENGTH).nullable(), + executionHostId: z.string().optional() +}) + +export const AiVaultSessionTitlesParams = z.object({ + requests: z + .array( + z.object({ + agent: z.enum(['claude', 'codex']), + sessionId: z.string().min(1).max(512), + transcriptPath: z.string().min(1).max(32_768).optional() + }) + ) + .max(AI_VAULT_SESSION_TITLE_REQUEST_MAX_COUNT) +}) diff --git a/src/shared/rpc-contract/artifacts-params.ts b/src/shared/rpc-contract/artifacts-params.ts new file mode 100644 index 00000000000..e5743485892 --- /dev/null +++ b/src/shared/rpc-contract/artifacts-params.ts @@ -0,0 +1,43 @@ +import { z } from 'zod' +import { + ARTIFACT_MAX_CONTENT_BYTES, + ARTIFACT_MAX_REQUEST_BYTES, + artifactContentByteLength, + artifactWriteRequestByteLength +} from '../artifacts' + +export const CloudOptions = { + apiUrl: z.string().max(2_048).optional(), + authToken: z.string().max(16_384).optional() +} + +export const ListOptions = z.object({ + ...CloudOptions, + cursor: z.string().min(1).max(2_048).optional() +}) + +export const SourceRequest = z.object({ + sourceKey: z.string().min(1).max(32_768), + ...CloudOptions +}) + +export const WriteRequest = z + .object({ + sourceKey: z.string().min(1).max(32_768), + content: z + .string() + .min(1) + .max(ARTIFACT_MAX_CONTENT_BYTES) + .refine((content) => artifactContentByteLength(content) <= ARTIFACT_MAX_CONTENT_BYTES, { + message: 'Artifact content exceeds the 10 MiB limit.' + }), + contentType: z.enum(['text/html', 'text/markdown']), + fileName: z.string().min(1).max(512), + title: z.string().max(512).optional(), + ...CloudOptions + }) + .refine((request) => artifactWriteRequestByteLength(request) <= ARTIFACT_MAX_REQUEST_BYTES, { + message: 'Artifact request exceeds the supported size.' + }) + +export const ArtifactsDeleteParams = z.object({ id: z.string().min(1), ...CloudOptions }) diff --git a/src/shared/rpc-contract/automation-params.ts b/src/shared/rpc-contract/automation-params.ts new file mode 100644 index 00000000000..fff5d5db615 --- /dev/null +++ b/src/shared/rpc-contract/automation-params.ts @@ -0,0 +1,198 @@ +import { z } from 'zod' +import { isTuiAgent } from '../tui-agent-config' +import { + OptionalBoolean, + OptionalPlainString, + OptionalPositiveInt, + OptionalString, + requiredNumber, + requiredString +} from './rpc-param-primitives' +import { normalizeExecutionHostId } from '../execution-host' +import { isValidAutomationSchedule } from '../automation-schedule-parsing' +import { + MAX_AUTOMATION_PRECHECK_TIMEOUT_SECONDS, + normalizeAutomationPrecheckTimeoutSeconds +} from '../automation-precheck' +import type { TaskProviderIdentity as SharedTaskProviderIdentity } from '../task-source-context' + +export const TuiAgent = requiredString('Missing provider').refine(isTuiAgent, { + message: 'Unknown provider' +}) + +export const AutomationWorkspaceMode = z.enum(['existing', 'new_per_run']).optional() + +export const SetupDecision = z.enum(['inherit', 'run', 'skip']).optional() + +export const ExecutionHostId = requiredString('Missing host id').transform((value, ctx) => { + const hostId = normalizeExecutionHostId(value) + if (!hostId) { + ctx.addIssue({ code: 'custom', message: 'Invalid host id' }) + return z.NEVER + } + return hostId +}) + +export const AutomationSchedule = requiredString('Missing trigger').refine( + isValidAutomationSchedule, + { + message: 'Invalid automation trigger' + } +) + +export const AutomationPrecheck = z + .object({ + command: requiredString('Missing precheck command'), + timeoutSeconds: OptionalPositiveInt.transform((value) => + normalizeAutomationPrecheckTimeoutSeconds(value) + ).refine((value) => value <= MAX_AUTOMATION_PRECHECK_TIMEOUT_SECONDS, { + message: 'Precheck timeout is too large' + }) + }) + .nullable() + .optional() + +export const OptionalNullablePlainString = z + .unknown() + .transform((value) => (value === null || typeof value === 'string' ? value : undefined)) + .pipe(z.union([z.string(), z.null(), z.undefined()])) + .optional() + +export const TaskProviderIdentity = z + .custom( + (value) => + value !== null && + typeof value === 'object' && + 'provider' in value && + ['github', 'gitlab', 'linear', 'jira'].includes(String(value.provider)) + ) + .optional() + .nullable() + +export const TaskSourceContext = z + .object({ + kind: z.literal('task-source'), + provider: z.enum(['github', 'gitlab', 'linear', 'jira']), + projectId: requiredString('Missing source project id'), + hostId: ExecutionHostId, + projectHostSetupId: OptionalNullablePlainString, + repoId: OptionalNullablePlainString, + providerIdentity: TaskProviderIdentity, + accountLabel: OptionalNullablePlainString + }) + .optional() + .nullable() + +export const WorkspaceRunContext = z + .object({ + kind: z.literal('workspace-run'), + projectId: requiredString('Missing run project id'), + hostId: ExecutionHostId, + projectHostSetupId: requiredString('Missing project host setup id'), + repoId: requiredString('Missing repo id'), + path: requiredString('Missing run path') + }) + .optional() + .nullable() + +export const SshTargetGeneration = requiredNumber('Missing SSH target generation').refine( + (value) => Number.isSafeInteger(value) && value >= 1, + { message: 'Invalid SSH target generation' } +) + +export const OwnedSshSelector = z.object({ + kind: z.literal('ssh'), + targetId: requiredString('Missing SSH target id'), + targetGeneration: SshTargetGeneration +}) + +/** Orphan is accepted here, unlike a destination: a record with no executable host is still deletable. */ +export const OwnerPreconditionSelector = z.discriminatedUnion('kind', [ + z.object({ kind: z.literal('self') }), + OwnedSshSelector, + z.object({ kind: z.literal('orphan') }) +]) + +export const DestinationSelector = z.discriminatedUnion('kind', [ + z.object({ kind: z.literal('self') }), + OwnedSshSelector +]) + +export const ExpectedOwner = z.object({ selector: OwnerPreconditionSelector }).optional() + +export const Destination = z.object({ selector: DestinationSelector }).optional() + +export const ListScopeSelector = z.discriminatedUnion('kind', [ + z.object({ kind: z.literal('self') }), + z.object({ + kind: z.literal('ssh'), + targetId: requiredString('Missing SSH target id'), + expectedTargetGeneration: SshTargetGeneration + }), + z.object({ kind: z.literal('orphan') }) +]) + +/** An omitted selector is the legacy request; old clients keep the authority's complete list. */ +export const AutomationList = z.object({ selector: ListScopeSelector.optional() }) + +export const AutomationId = z.object({ + id: requiredString('Missing automation id'), + expectedOwner: ExpectedOwner +}) + +export const AutomationRuns = z.object({ + automationId: OptionalString, + expectedOwner: ExpectedOwner, + limit: OptionalPositiveInt, + cursor: OptionalString +}) + +export const AutomationCreate = z.object({ + creationKey: OptionalString, + name: requiredString('Missing automation name'), + prompt: requiredString('Missing automation prompt'), + precheck: AutomationPrecheck, + agentId: TuiAgent, + runContext: WorkspaceRunContext, + sourceContext: TaskSourceContext, + repo: OptionalString, + workspace: OptionalString, + workspaceMode: AutomationWorkspaceMode, + baseBranch: OptionalPlainString, + setupDecision: SetupDecision, + reuseSession: OptionalBoolean, + timezone: OptionalString, + rrule: AutomationSchedule, + dtstart: requiredNumber('Missing trigger start time'), + enabled: OptionalBoolean, + missedRunGraceMinutes: OptionalPositiveInt, + destination: Destination +}) + +export const AutomationUpdateFields = z.object({ + name: OptionalString, + prompt: OptionalString, + precheck: AutomationPrecheck, + agentId: TuiAgent.optional(), + runContext: WorkspaceRunContext, + sourceContext: TaskSourceContext, + repo: OptionalString, + workspace: OptionalString, + workspaceMode: AutomationWorkspaceMode, + // Why: update patches distinguish omitted from null so callers can clear a saved base branch. + baseBranch: OptionalNullablePlainString, + setupDecision: SetupDecision, + reuseSession: OptionalBoolean, + timezone: OptionalString, + rrule: AutomationSchedule.optional(), + dtstart: requiredNumber('Missing trigger start time').optional(), + enabled: OptionalBoolean, + missedRunGraceMinutes: OptionalPositiveInt +}) + +export const AutomationUpdate = z.object({ + id: requiredString('Missing automation id'), + updates: AutomationUpdateFields, + expectedOwner: ExpectedOwner, + destination: Destination +}) diff --git a/src/shared/rpc-contract/browser-core-params.ts b/src/shared/rpc-contract/browser-core-params.ts new file mode 100644 index 00000000000..6cd0dccfbd3 --- /dev/null +++ b/src/shared/rpc-contract/browser-core-params.ts @@ -0,0 +1,5 @@ +import { BrowserTarget, requiredString } from './rpc-param-primitives' + +export const CertificateProceed = BrowserTarget.extend({ + challengeId: requiredString('Missing required challengeId') +}) diff --git a/src/shared/rpc-contract/browser-extras-params.ts b/src/shared/rpc-contract/browser-extras-params.ts new file mode 100644 index 00000000000..421c8976608 --- /dev/null +++ b/src/shared/rpc-contract/browser-extras-params.ts @@ -0,0 +1,14 @@ +import { z } from 'zod' +import { MouseButton, MouseXY } from './browser-params' +import { OptionalFiniteNumber } from './rpc-param-primitives' + +export const MouseModifiers = z + .unknown() + .transform((v) => (Array.isArray(v) ? v : undefined)) + .pipe(z.union([z.array(z.enum(['cmd', 'ctrl', 'alt', 'shift'])), z.undefined()])) + .optional() + +export const MouseClick = MouseXY.merge(MouseButton).extend({ + radius: OptionalFiniteNumber, + modifiers: MouseModifiers +}) diff --git a/src/shared/rpc-contract/browser-params.ts b/src/shared/rpc-contract/browser-params.ts new file mode 100644 index 00000000000..141e9ffe8fd --- /dev/null +++ b/src/shared/rpc-contract/browser-params.ts @@ -0,0 +1,355 @@ +import { z } from 'zod' +import { + BrowserTarget, + OptionalBoolean, + OptionalFiniteNumber, + OptionalPlainString, + OptionalString, + requiredString, + requiredStringAllowingEmpty +} from './rpc-param-primitives' + +export const Element = BrowserTarget.extend({ + element: requiredString('Missing required --element') +}) + +export const Goto = BrowserTarget.extend({ + url: requiredString('Missing required --url') +}) + +export const Fill = BrowserTarget.extend({ + element: requiredString('Missing required --element'), + value: requiredStringAllowingEmpty('Missing required --value') +}) + +export const Type = BrowserTarget.extend({ + input: requiredString('Missing required --input') +}) + +export const Select = BrowserTarget.extend({ + element: requiredString('Missing required --element'), + value: z.custom((v) => typeof v === 'string', { + message: 'Missing required --value' + }) +}) + +export const Scroll = BrowserTarget.extend({ + direction: z.custom<'up' | 'down'>((v) => v === 'up' || v === 'down', { + message: 'Missing required --direction (up or down)' + }), + amount: z + .unknown() + .transform((v) => (typeof v === 'number' && v > 0 ? v : undefined)) + .pipe(z.union([z.number(), z.undefined()])) + .optional() +}) + +export const Screenshot = BrowserTarget.extend({ + format: z + .unknown() + .transform((v) => (v === 'png' || v === 'jpeg' ? v : undefined)) + .pipe(z.union([z.enum(['png', 'jpeg']), z.undefined()])) + .optional() +}) + +export const Screencast = BrowserTarget.extend({ + format: z + .unknown() + .optional() + .transform((v) => (v === 'png' ? 'png' : 'jpeg')) + .pipe(z.enum(['png', 'jpeg'])), + quality: OptionalFiniteNumber, + maxWidth: OptionalFiniteNumber, + maxHeight: OptionalFiniteNumber, + viewportWidth: OptionalFiniteNumber, + viewportHeight: OptionalFiniteNumber, + deviceScaleFactor: OptionalFiniteNumber, + mobile: OptionalBoolean, + everyNthFrame: OptionalFiniteNumber, + minFrameIntervalMs: OptionalFiniteNumber +}) + +export const FullScreenshot = BrowserTarget.extend({ + format: z + .unknown() + .optional() + .transform((v) => (v === 'jpeg' ? 'jpeg' : 'png')) + .pipe(z.enum(['png', 'jpeg'])) +}) + +export const Eval = BrowserTarget.extend({ + expression: requiredString('Missing required --expression') +}) + +export const TabList = z.object({ worktree: OptionalString }) + +// Why: --index xor --page must be present. The refine guards that invariant +// so the dispatcher surfaces a single legible error instead of either shape +// leaking into the runtime. +// +// `focus` is opt-in: when true, the runtime sends `browser:pane-focus` to +// the renderer after the switch lands. The renderer surfaces the browser +// pane only if the user is already on the targeted worktree; otherwise it +// pre-stages per-worktree state silently. This avoids cross-worktree screen +// theft when multiple agents drive browsers in parallel worktrees. +export const TabSwitch = BrowserTarget.extend({ + index: z + .unknown() + .transform((v) => (typeof v === 'number' ? v : undefined)) + .pipe(z.union([z.number(), z.undefined()])) + .optional(), + focus: z.boolean().optional() +}).refine( + (val) => { + if (val.page !== undefined) { + return true + } + return val.index !== undefined && Number.isInteger(val.index) && val.index >= 0 + }, + { message: 'Missing required --index (non-negative integer) or --page' } +) + +export const TabShow = z.object({ + page: requiredString('Missing required --page'), + worktree: OptionalString +}) + +export const TabCurrent = z.object({ worktree: OptionalString }) + +export const TabClose = z.object({ + index: z + .unknown() + .transform((v) => (typeof v === 'number' ? v : undefined)) + .pipe(z.union([z.number(), z.undefined()])) + .optional(), + page: OptionalString, + worktree: OptionalString +}) + +export const TabSetProfile = BrowserTarget.extend({ + profileId: requiredString('Missing required --profile') +}) + +export const TabProfileClone = BrowserTarget.extend({ + profileId: requiredString('Missing required --profile') +}) + +export const ProfileCreate = z.object({ + label: requiredString('Missing required --label'), + // Strict enum so unknown scope values surface validation errors instead of being + // silently coerced to 'isolated' (pr-bug-scan finding from #1397). + scope: z.enum(['isolated', 'imported']), + userAgentMode: z.enum(['clean', 'native']).optional() +}) + +export const ProfileDelete = z.object({ profileId: requiredString('Missing required --profile') }) + +export const ProfileImportFromBrowser = z.object({ + profileId: requiredString('Missing required --profile'), + browserFamily: requiredString('Missing required --browser-family'), + browserProfile: OptionalString, + supportsPartitionSkippedCookies: z.literal(true).optional() +}) + +export const Drag = BrowserTarget.extend({ + from: requiredString('Missing required --from and --to element refs'), + to: requiredString('Missing required --from and --to element refs') +}) + +export const Upload = BrowserTarget.extend({ + element: requiredString('Missing required --element and --files'), + files: z.custom( + (v) => Array.isArray(v) && v.length > 0 && v.every((f) => typeof f === 'string'), + { message: 'Missing required --element and --files' } + ) +}) + +export const Wait = BrowserTarget.extend({ + selector: OptionalPlainString, + timeout: z + .unknown() + .transform((v) => (typeof v === 'number' && v > 0 ? v : undefined)) + .pipe(z.union([z.number(), z.undefined()])) + .optional(), + text: OptionalPlainString, + url: OptionalPlainString, + load: OptionalPlainString, + fn: OptionalPlainString, + state: OptionalPlainString +}) + +export const Check = BrowserTarget.extend({ + element: requiredString('Missing required --element'), + checked: z + .unknown() + .optional() + .transform((v) => (v === undefined ? true : v)) + .pipe(z.boolean()) +}) + +export const Keypress = BrowserTarget.extend({ + key: requiredString('Missing required --key') +}) + +export const SelectorPath = BrowserTarget.extend({ + selector: requiredString('Missing required --selector and --path'), + path: requiredString('Missing required --selector and --path') +}) + +export const Highlight = BrowserTarget.extend({ + selector: requiredString('Missing required --selector') +}) + +export const Exec = BrowserTarget.extend({ + command: requiredString('Missing required --command') +}) + +export const Get = BrowserTarget.extend({ + what: requiredString('Missing required --what'), + selector: OptionalString +}) + +export const Is = BrowserTarget.extend({ + what: z.custom((v) => typeof v === 'string' && v.length > 0, { + message: 'Missing required --what and --element' + }), + selector: z.custom((v) => typeof v === 'string' && v.length > 0, { + message: 'Missing required --what and --element' + }) +}) + +export const KeyboardInsert = BrowserTarget.extend({ + text: requiredString('Missing required --text') +}) + +export const LimitParam = BrowserTarget.extend({ + limit: OptionalFiniteNumber +}) + +export const Find = BrowserTarget.extend({ + locator: requiredString('Missing required --locator, --value, and --action'), + value: requiredString('Missing required --locator, --value, and --action'), + action: requiredString('Missing required --locator, --value, and --action'), + text: OptionalString +}) + +export const CookieGet = BrowserTarget.extend({ + url: OptionalPlainString +}) + +export const CookieSet = BrowserTarget.extend({ + name: z.custom((v) => typeof v === 'string' && v.length > 0, { + message: 'Missing name or value' + }), + value: z.custom((v) => typeof v === 'string', { + message: 'Missing name or value' + }), + domain: OptionalPlainString, + path: OptionalPlainString, + secure: OptionalBoolean, + httpOnly: OptionalBoolean, + sameSite: OptionalPlainString, + expires: OptionalFiniteNumber +}) + +export const CookieDelete = BrowserTarget.extend({ + name: requiredString('Missing cookie name'), + domain: OptionalPlainString, + url: OptionalPlainString +}) + +export const Viewport = BrowserTarget.extend({ + width: z.custom((v) => typeof v === 'number' && v > 0, { + message: 'Width and height must be positive numbers' + }), + height: z.custom((v) => typeof v === 'number' && v > 0, { + message: 'Width and height must be positive numbers' + }), + deviceScaleFactor: OptionalFiniteNumber, + mobile: OptionalBoolean +}) + +export const Geolocation = BrowserTarget.extend({ + latitude: z.custom((v) => typeof v === 'number', { + message: 'Missing latitude or longitude' + }), + longitude: z.custom((v) => typeof v === 'number', { + message: 'Missing latitude or longitude' + }), + accuracy: OptionalFiniteNumber +}) + +export const InterceptEnable = BrowserTarget.extend({ + patterns: z + .unknown() + .transform((v) => (Array.isArray(v) ? (v as string[]) : undefined)) + .pipe(z.union([z.array(z.string()), z.undefined()])) + .optional() +}) + +export const MouseXY = BrowserTarget.extend({ + x: z.custom((v) => typeof v === 'number', { + message: 'Missing required x and y coordinates' + }), + y: z.custom((v) => typeof v === 'number', { + message: 'Missing required x and y coordinates' + }) +}) + +export const MouseButton = BrowserTarget.extend({ + button: OptionalPlainString +}) + +export const MouseWheel = BrowserTarget.extend({ + dy: z.custom((v) => typeof v === 'number', { + message: 'Missing required --dy' + }), + dx: OptionalFiniteNumber +}) + +export const SetDevice = BrowserTarget.extend({ + name: requiredString('Missing required --name') +}) + +export const SetOffline = BrowserTarget.extend({ + state: OptionalPlainString +}) + +export const SetHeaders = BrowserTarget.extend({ + headers: requiredString('Missing required --headers (JSON string)') +}) + +export const SetCredentials = BrowserTarget.extend({ + user: z.custom((v) => typeof v === 'string' && v.length > 0, { + message: 'Missing required --user and --pass' + }), + pass: z.custom((v) => typeof v === 'string', { + message: 'Missing required --user and --pass' + }) +}) + +export const SetMedia = BrowserTarget.extend({ + colorScheme: OptionalPlainString, + reducedMotion: OptionalPlainString +}) + +export const ClipboardWrite = BrowserTarget.extend({ + text: requiredString('Missing required --text') +}) + +export const DialogAccept = BrowserTarget.extend({ + text: OptionalPlainString +}) + +export const StorageKey = BrowserTarget.extend({ + key: requiredString('Missing required --key') +}) + +export const StorageKeyValue = BrowserTarget.extend({ + key: z.custom((v) => typeof v === 'string' && v.length > 0, { + message: 'Missing required --key and --value' + }), + value: z.custom((v) => typeof v === 'string', { + message: 'Missing required --key and --value' + }) +}) diff --git a/src/shared/rpc-contract/browser-screencast-params.ts b/src/shared/rpc-contract/browser-screencast-params.ts new file mode 100644 index 00000000000..016b7e0f83b --- /dev/null +++ b/src/shared/rpc-contract/browser-screencast-params.ts @@ -0,0 +1,5 @@ +import { z } from 'zod' + +export const ScreencastUnsubscribe = z.object({ + subscriptionId: z.string().min(1, 'Missing required --subscription-id') +}) diff --git a/src/shared/rpc-contract/browser-tab-create-params.ts b/src/shared/rpc-contract/browser-tab-create-params.ts new file mode 100644 index 00000000000..1250b6ff2a3 --- /dev/null +++ b/src/shared/rpc-contract/browser-tab-create-params.ts @@ -0,0 +1,23 @@ +import { z } from 'zod' +import { RUNTIME_NAVIGATION_TARGETS } from '../runtime-navigation' +import { BrowserPageCreationPlacement } from '../browser-client-host-placement' +import { OptionalString } from './rpc-param-primitives' + +export const BrowserTabCreateParams = z.object({ + url: OptionalString, + worktree: OptionalString, + page: OptionalString, + profileId: OptionalString, + waitForRegistration: z.boolean().optional(), + activate: z.boolean().optional(), + // Why: `activate` says the caller wants the new tab selected; `navigation` says on whose screens. + // Absent, a paired caller means 'caller' — one device's create must not steer every other UI. + navigation: z.enum(RUNTIME_NAVIGATION_TARGETS).optional(), + targetGroupId: OptionalString, + placement: BrowserPageCreationPlacement.optional() +}) + +export const BrowserOpenUrlParams = z.object({ + url: z.url(), + worktree: z.string().min(1) +}) diff --git a/src/shared/rpc-contract/client-events-params.ts b/src/shared/rpc-contract/client-events-params.ts new file mode 100644 index 00000000000..134c976e7d1 --- /dev/null +++ b/src/shared/rpc-contract/client-events-params.ts @@ -0,0 +1,8 @@ +import { z } from 'zod' + +export const ClientEventsUnsubscribeParams = z.object({ + subscriptionId: z + .unknown() + .transform((value) => (typeof value === 'string' && value.length > 0 ? value : '')) + .pipe(z.string().min(1, 'Missing subscriptionId')) +}) diff --git a/src/shared/rpc-contract/client-settings-params.ts b/src/shared/rpc-contract/client-settings-params.ts new file mode 100644 index 00000000000..def24ddc703 --- /dev/null +++ b/src/shared/rpc-contract/client-settings-params.ts @@ -0,0 +1,123 @@ +import { z } from 'zod' +import { isTaskProvider } from '../task-providers' +import type { TaskProvider } from '../task-providers' +import { isTuiAgent } from '../tui-agent-config' +import { normalizeDisabledTuiAgents } from '../tui-agent-selection' +import { + normalizeTuiAgentArgsRecord, + normalizeTuiAgentEnvRecord +} from '../tui-agent-launch-defaults' +import { normalizePRBotAuthorOverrides } from '../pr-bot-author-overrides' +import { WorktreeVisibilityDefaultsUpdate } from './worktree-visibility-defaults-params' + +export const TaskProviderParam = z.custom(isTaskProvider, { + message: 'Unknown task provider' +}) + +export const PRBotAuthorOverrideUpdate = z + .object({ author: z.string(), isBot: z.boolean() }) + .strict() + +export const NativeChatSessionOptionPickBase = { + modelId: z.string().trim().min(1).max(512), + adoptModelAsLaunchDefault: z.boolean().optional() +} + +export const NativeChatSessionOptionPick = z.union([ + z + .object({ + ...NativeChatSessionOptionPickBase, + optionId: z.enum(['model', 'effort']), + value: z.string().trim().min(1).max(512) + }) + .strict(), + z + .object({ + ...NativeChatSessionOptionPickBase, + optionId: z.enum(['fastMode', 'thinking']), + value: z.boolean() + }) + .strict() +]) + +export const NativeChatSessionOptionsMutation = z.discriminatedUnion('type', [ + z + .object({ + type: z.literal('apply-picks'), + agent: z.enum(['claude', 'codex', 'gemini', 'cursor', 'grok']), + picks: z.array(NativeChatSessionOptionPick).min(1).max(8) + }) + .strict(), + z + .object({ + type: z.literal('clear-model-if-missing'), + agent: z.enum(['claude', 'codex', 'gemini', 'cursor', 'grok']), + availableModelIds: z.array(z.string().trim().min(1).max(512)).min(1).max(256) + }) + .strict() +]) + +export const GitHubProjectRef = z + .object({ + owner: z.string(), + ownerType: z.enum(['organization', 'user']), + number: z.number().int(), + host: z.string().optional() + }) + .strict() + +export const GitHubProjectSettings = z + .object({ + pinned: z.array(GitHubProjectRef), + recent: z.array( + GitHubProjectRef.extend({ + lastOpenedAt: z.string() + }).strict() + ), + lastViewByProject: z.record(z.string(), z.object({ viewId: z.string() }).strict()), + activeProject: GitHubProjectRef.nullable() + }) + .strict() + +export const SettingsUpdate = z + .object({ + worktreeVisibilityDefaults: WorktreeVisibilityDefaultsUpdate.optional(), + defaultTuiAgent: z + .unknown() + .transform((value) => + value === null || value === 'blank' || isTuiAgent(value) ? value : undefined + ) + .optional(), + disabledTuiAgents: z + .unknown() + .transform((value) => normalizeDisabledTuiAgents(value)) + .optional(), + agentDefaultArgs: z + .unknown() + .transform((value) => normalizeTuiAgentArgsRecord(value)) + .optional(), + agentDefaultEnv: z + .unknown() + .transform((value) => normalizeTuiAgentEnvRecord(value)) + .optional(), + defaultTaskSource: TaskProviderParam.optional(), + visibleTaskProviders: z.array(TaskProviderParam).optional(), + defaultTaskViewPreset: z + .enum(['issues', 'my-issues', 'prs', 'my-prs', 'review', 'all']) + .optional(), + experimentalNewWorktreeCardStyle: z.boolean().optional(), + agentStatusHooksEnabled: z.boolean().optional(), + defaultRepoSelection: z.array(z.string()).nullable().optional(), + defaultLinearTeamSelection: z.array(z.string()).nullable().optional(), + compactWorktreeCards: z.boolean().optional(), + minimaxGroupId: z.string().optional(), + minimaxUsageModels: z.string().optional(), + minimaxEndpoint: z.enum(['overseas', 'cn']).optional(), + githubProjects: GitHubProjectSettings.optional(), + prBotAuthorOverrides: z + .unknown() + .transform((value) => normalizePRBotAuthorOverrides(value)) + .optional() + }) + .strict() + .default({}) diff --git a/src/shared/rpc-contract/client-ui-params.ts b/src/shared/rpc-contract/client-ui-params.ts new file mode 100644 index 00000000000..df84a06a256 --- /dev/null +++ b/src/shared/rpc-contract/client-ui-params.ts @@ -0,0 +1,257 @@ +import { z } from 'zod' +import { isFeatureTipId } from '../feature-tips' +import { + WORKTREE_CARD_PROPERTIES, + normalizeWorktreeCardProperties +} from '../worktree/card-properties' +import { isPluginPanelTabKey } from '../plugins/plugin-manifest' +import { isFeatureInteractionId } from '../feature-interactions' +import type { FeatureInteractionId } from '../feature-interactions' +import { ACTIVITY_GROUP_BY_VALUES, THREAD_READ_FILTER_VALUES } from '../agents-view-thread-filters' +import { isReleaseChannel } from '../release-channel' +import type { ReleaseChannel } from '../release-channel' +import { ClientUiWorkspaceFilterFields } from './client-ui-workspace-filter-fields-params' +import { TaskResumeState } from './task-resume-state-params' +import { WorkspaceCleanup } from './workspace-cleanup-ui-params' +import { omitUndefinedValues, tolerateUnknownValues } from './ui-update-value-tolerance-params' + +export const NullableString = z.string().nullable() + +export const StringArray = z.array(z.string()) + +export const FeatureTipIds = z.array( + z.custom(isFeatureTipId, { message: 'Unknown feature tip id' }) +) + +export const UnknownRecord = z.record(z.string(), z.unknown()) + +export const UnknownRecordArray = z.array(UnknownRecord) + +export type StaticRightSidebarTab = (typeof STATIC_RIGHT_SIDEBAR_TABS)[number] + +// Derived from the shared union so a new card property cannot drift out of the +// client schema — it previously omitted 'cli' and rejected the whole payload. +export const WorktreeCardPropertyParam = z.enum(WORKTREE_CARD_PROPERTIES) + +export const WorktreeCardProperties = z + .array(WorktreeCardPropertyParam) + .transform((value) => normalizeWorktreeCardProperties(value)) + +export const STATIC_RIGHT_SIDEBAR_TABS = [ + 'explorer', + 'search', + 'vault', + 'workspaces', + 'pr-checks', + 'source-control', + 'checks', + 'ports' +] as const + +// Plugin panels are open-ended `plugin:./` keys, so the +// schema validates their shape rather than enumerating them. +export const RightSidebarTabParam = z.custom( + (value) => + typeof value === 'string' && + (STATIC_RIGHT_SIDEBAR_TABS.includes(value as StaticRightSidebarTab) || + isPluginPanelTabKey(value)), + { message: 'Unknown right sidebar tab' } +) + +export const AgentActivityDisplayMode = z.enum(['compact', 'full']) + +export const StatusBarItem = z.enum([ + 'claude', + 'codex', + 'gemini', + 'antigravity', + 'opencode-go', + 'kimi', + 'minimax', + 'grok', + 'ssh', + 'resource-usage', + 'ports' +]) + +export const WorkspaceStatusDefinition = z.object({ + id: z.string(), + label: z.string(), + color: z.string().optional(), + icon: z.string().optional() +}) + +export const FeatureInteractionRecord = z + .object({ + firstInteractedAt: z.number().finite().nonnegative(), + interactionCount: z.number().int().positive().optional() + }) + .strict() + +export const FeatureInteractions = z + .record(z.string(), FeatureInteractionRecord) + .superRefine((value, ctx) => { + for (const id of Object.keys(value)) { + if (!isFeatureInteractionId(id)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: `Unknown feature interaction id: ${id}`, + path: [id] + }) + } + } + }) + +export const FeatureInteractionIdParam = z.custom(isFeatureInteractionId, { + message: 'Unknown feature interaction id' +}) + +export const TopLevelViewSchema = z.enum([ + 'terminal', + 'settings', + 'tasks', + 'activity', + 'automations', + 'space', + 'skills', + 'artifacts', + 'mobile' +]) + +export const UiUpdateFields = z + .object({ + lastActiveRepoId: NullableString.optional(), + lastActiveWorktreeId: NullableString.optional(), + // Why: sync hydration ignores this persisted startup view, so paired windows stay put. + activeView: TopLevelViewSchema.optional(), + sidebarWidth: z.number().finite().optional(), + rightSidebarOpen: z.boolean().optional(), + rightSidebarTab: RightSidebarTabParam.optional(), + rightSidebarExplorerView: z.enum(['files', 'search']).optional(), + rightSidebarWidth: z.number().finite().optional(), + markdownTocPanelWidth: z.number().finite().optional(), + combinedDiffFileTreeWidth: z.number().finite().optional(), + groupBy: z.enum(['none', 'workspace-status', 'repo', 'pr-status']).optional(), + showWorkspaceLineage: z.boolean().optional(), + sortBy: z.enum(['name', 'smart', 'recent', 'repo', 'manual']).optional(), + projectOrderBy: z.enum(['manual', 'recent']).optional(), + showActiveOnly: z.boolean().optional(), + hideSleepingWorkspaces: z.boolean().optional(), + showSleepingWorkspaces: z.boolean().optional(), + showInactiveWorkspaces: z.boolean().optional(), + workspaceHostScope: z.string().optional(), + visibleWorkspaceHostIds: z.array(z.string()).nullable().optional(), + agentsVisibleHostIds: z.array(z.string()).nullable().optional(), + agentsFilterRepoIds: StringArray.optional(), + agentsShowChildAgents: z.boolean().optional(), + agentsCompactMode: z.boolean().optional(), + agentsShowSearch: z.boolean().optional(), + agentsReadFilter: z.enum(THREAD_READ_FILTER_VALUES).optional(), + agentsGroupBy: z.enum(ACTIVITY_GROUP_BY_VALUES).optional(), + workspaceHostOrder: z.array(z.string()).optional(), + automationHostFilter: z + .union([ + z.object({ kind: z.literal('all') }).strict(), + z.object({ kind: z.literal('host'), hostKey: z.string().min(1) }).strict() + ]) + .optional(), + manualRepoOrder: z + .array(z.object({ hostId: z.string(), repoId: z.string() }).strict()) + .optional(), + ...ClientUiWorkspaceFilterFields, + // Why: rides App.tsx's debounced writer, so omitting it rejected that entire + // payload (sidebar widths, filters, agent acks) for every paired client. + showDotfilesByWorktree: z.record(z.string(), z.boolean()).optional(), + collapsedGroups: StringArray.optional(), + uiZoomLevel: z.number().finite().optional(), + editorFontZoomLevel: z.number().finite().optional(), + worktreeCardProperties: WorktreeCardProperties.optional(), + _worktreeCardModeDefaulted: z.boolean().optional(), + agentActivityDisplayMode: AgentActivityDisplayMode.optional(), + workspaceStatuses: z.array(WorkspaceStatusDefinition).optional(), + workspaceBoardOpacity: z.number().finite().optional(), + workspaceBoardColumnWidth: z.number().finite().optional(), + syncTaskStatusFromWorkspaceBoard: z.boolean().optional(), + _workspaceStatusesDefaultOrderMigrated: z.boolean().optional(), + _workspaceStatusesReorderedDefaultRepaired: z.boolean().optional(), + _workspaceStatusesDefaultWorkflowMigrated: z.boolean().optional(), + _workspaceStatusesDefaultVisualsMigrated: z.boolean().optional(), + statusBarItems: z.array(StatusBarItem).optional(), + _portsStatusBarDefaultAdded: z.boolean().optional(), + _kimiStatusBarDefaultAdded: z.boolean().optional(), + _minimaxStatusBarDefaultAdded: z.boolean().optional(), + _antigravityStatusBarDefaultAdded: z.boolean().optional(), + _grokStatusBarDefaultAdded: z.boolean().optional(), + statusBarVisible: z.boolean().optional(), + usagePercentageDisplay: z.enum(['used', 'remaining']).optional(), + statusBarUsageMode: z.enum(['verbose', 'compact']).optional(), + dismissedUpdateVersion: NullableString.optional(), + dismissedUnexpectedSignoutVersion: NullableString.optional(), + lastUpdateCheckAt: z.number().finite().nullable().optional(), + pendingUpdateNudgeId: NullableString.optional(), + dismissedUpdateNudgeId: NullableString.optional(), + // Why the predicate rather than an inline z.enum: an enum here is a copy of + // RELEASE_CHANNELS, and a copy that drifts silently rejects the new + // channel's override on its way here — the picker moves, nothing installs. + releaseChannelOverride: z.custom(isReleaseChannel).nullable().optional(), + notificationPermissionRequested: z.boolean().optional(), + updateReassuranceSeen: z.boolean().optional(), + osc52ClipboardDefaultOnNoticePending: z.boolean().optional(), + acknowledgedAgentsByPaneKey: z.record(z.string(), z.number().finite()).optional(), + activityClearedAtByPaneKey: z.record(z.string(), z.number().finite()).optional(), + manuallyUnreadTurnsByPaneKey: z.record(z.string(), z.number().finite()).optional(), + browserDefaultUrl: NullableString.optional(), + browserDefaultSearchEngine: z + .enum(['google', 'duckduckgo', 'bing', 'kagi']) + .nullable() + .optional(), + browserDefaultZoomLevel: z.number().finite().optional(), + browserKagiSessionLink: NullableString.optional(), + windowBounds: z + .object({ + x: z.number().finite(), + y: z.number().finite(), + width: z.number().finite(), + height: z.number().finite() + }) + .nullable() + .optional(), + windowMaximized: z.boolean().optional(), + _sortBySmartMigrated: z.boolean().optional(), + _inlineAgentsDefaultedForExperiment: z.boolean().optional(), + _inlineAgentsDefaultedForAllUsers: z.boolean().optional(), + trustedOrcaHooks: z.record(z.string(), z.unknown()).optional(), + setupScriptPromptDismissedRepoIds: StringArray.optional(), + // Why: one-shot dismissals the renderer writes through ui.set; each was a + // whole-payload rejection for paired clients while unlisted. + setupGuideSidebarDismissed: z.boolean().optional(), + setupGuideBrowserMilestoneMigrated: z.boolean().optional(), + setupGuideBrowserMilestoneLegacyComplete: z.boolean().optional(), + browserImportHintHidden: z.boolean().optional(), + mobileEmulatorTabIntroDismissed: z.boolean().optional(), + mobileEmulatorAgentSetupDismissed: z.boolean().optional(), + projectOrderManualDefaultNoticeDismissed: z.boolean().optional(), + usagePercentageDisplayChangeNoticeDismissed: z.boolean().optional(), + usageEmptyStateDismissed: z.boolean().optional(), + petVisible: z.boolean().optional(), + petId: z.string().optional(), + customPets: UnknownRecordArray.optional(), + petSize: z.number().finite().optional(), + sidekickVisible: z.boolean().optional(), + sidekickId: z.string().optional(), + customSidekicks: UnknownRecordArray.optional(), + sidekickSize: z.number().finite().optional(), + taskResumeState: TaskResumeState.optional(), + workspaceCleanup: WorkspaceCleanup.optional(), + featureTipsSeenIds: FeatureTipIds.optional(), + featureInteractions: FeatureInteractions.optional(), + contextualToursSeenIds: StringArray.optional(), + contextualToursAutoEligible: z.boolean().optional() + }) + .strict() + +export const UiUpdate = z + .object(tolerateUnknownValues(UiUpdateFields.shape)) + .strict() + .default({}) + .transform(omitUndefinedValues) diff --git a/src/shared/rpc-contract/client-ui-workspace-filter-fields-params.ts b/src/shared/rpc-contract/client-ui-workspace-filter-fields-params.ts new file mode 100644 index 00000000000..d0239b03ec3 --- /dev/null +++ b/src/shared/rpc-contract/client-ui-workspace-filter-fields-params.ts @@ -0,0 +1,11 @@ +import { z } from 'zod' + +export const ClientUiWorkspaceFilterFields = { + hideDefaultBranchWorkspace: z.boolean().optional(), + hideAutomationGeneratedWorkspaces: z.boolean().optional(), + hideCliCreatedWorkspaces: z.boolean().optional(), + hideDetachedHeadWorkspaces: z.boolean().optional(), + hideWorkspacesFromOtherDevices: z.boolean().optional(), + alwaysShowDefaultBranchWorkspace: z.boolean().optional(), + filterRepoIds: z.array(z.string()).optional() +} diff --git a/src/shared/rpc-contract/clipboard-params.ts b/src/shared/rpc-contract/clipboard-params.ts new file mode 100644 index 00000000000..3f2b1948775 --- /dev/null +++ b/src/shared/rpc-contract/clipboard-params.ts @@ -0,0 +1,67 @@ +import { z } from 'zod' +import { + CLIPBOARD_IMAGE_MAX_BASE64_CHARS, + CLIPBOARD_IMAGE_TOO_LARGE_ERROR +} from '../clipboard-image' + +export const MAX_CLIPBOARD_IMAGE_BASE64_CHARS = CLIPBOARD_IMAGE_MAX_BASE64_CHARS + +export const CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS = 512 * 1024 + +export const BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/ + +export function isValidBase64(value: string): boolean { + return value.length % 4 !== 1 && BASE64_PATTERN.test(value) +} + +export function clipboardImageBase64Payload(maxChars: number, tooLargeMessage: string) { + return z.unknown().transform((value, ctx): string => { + if (typeof value !== 'string') { + ctx.addIssue({ code: 'custom', message: 'Missing image content' }) + return z.NEVER + } + if (value.length > maxChars) { + ctx.addIssue({ code: 'custom', message: tooLargeMessage }) + return z.NEVER + } + if (!isValidBase64(value)) { + ctx.addIssue({ code: 'custom', message: 'Clipboard image content must be base64' }) + return z.NEVER + } + return value + }) +} + +export const SaveImageAsTempFile = z.object({ + contentBase64: clipboardImageBase64Payload( + MAX_CLIPBOARD_IMAGE_BASE64_CHARS, + CLIPBOARD_IMAGE_TOO_LARGE_ERROR + ), + connectionId: z.string().min(1).nullable().optional() +}) + +export const StartImageUpload = z.object({ + expectedBase64Length: z + .number() + .int() + .nonnegative() + .max(MAX_CLIPBOARD_IMAGE_BASE64_CHARS, CLIPBOARD_IMAGE_TOO_LARGE_ERROR), + connectionId: z.string().min(1).nullable().optional() +}) + +export const AppendImageUploadChunk = z.object({ + uploadId: z.string().min(1), + offset: z.number().int().nonnegative(), + contentBase64: clipboardImageBase64Payload( + CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS, + 'Clipboard image chunk is too large' + ) +}) + +export const CommitImageUpload = z.object({ + uploadId: z.string().min(1) +}) + +export const AbortImageUpload = z.object({ + uploadId: z.string().min(1) +}) diff --git a/src/shared/rpc-contract/computer-params.ts b/src/shared/rpc-contract/computer-params.ts new file mode 100644 index 00000000000..08ffd1a6cfa --- /dev/null +++ b/src/shared/rpc-contract/computer-params.ts @@ -0,0 +1,5 @@ +import { z } from 'zod' + +export const ComputerPermissionsStatusParams = z.object({}) + +export const ComputerCapabilitiesParams = z.object({}) diff --git a/src/shared/rpc-contract/computer-schemas-params.ts b/src/shared/rpc-contract/computer-schemas-params.ts new file mode 100644 index 00000000000..d1802de3eff --- /dev/null +++ b/src/shared/rpc-contract/computer-schemas-params.ts @@ -0,0 +1,227 @@ +import { z } from 'zod' +import { + OptionalBoolean, + OptionalFiniteNumber, + OptionalString, + requiredString, + requiredStringAllowingEmpty +} from './rpc-param-primitives' +import { + computerUseClickModifiersValidationMessage, + computerUseHotkeyValidationMessage, + computerUsePressKeyValidationMessage +} from '../computer-use-key-spec' + +export const OptionalNonNegativeInt = z.number().int().nonnegative().optional() + +export const OptionalPositiveInt = z.number().int().positive().optional() + +export const ComputerTarget = z.object({ + app: requiredString('Missing app'), + session: OptionalString, + worktree: OptionalString +}) + +export const ComputerObserveTargetBase = ComputerTarget.extend({ + noScreenshot: OptionalBoolean, + restoreWindow: OptionalBoolean, + windowId: OptionalNonNegativeInt, + windowIndex: OptionalNonNegativeInt +}) + +export function validateWindowTarget( + value: { windowId?: number; windowIndex?: number }, + ctx: z.RefinementCtx +): void { + if (value.windowId !== undefined && value.windowIndex !== undefined) { + ctx.addIssue({ + code: 'custom', + message: 'Window targeting accepts either --window-id or --window-index, not both' + }) + } +} + +export function validateComputerTarget( + value: { session?: string; worktree?: string; windowId?: number; windowIndex?: number }, + ctx: z.RefinementCtx +): void { + if (value.session !== undefined && value.worktree !== undefined) { + ctx.addIssue({ + code: 'custom', + message: 'Computer-use targeting accepts either session or worktree, not both' + }) + } + validateWindowTarget(value, ctx) +} + +export const ComputerObserveTarget = ComputerObserveTargetBase.superRefine(validateComputerTarget) + +export const ListApps = z.object({}).strict() + +export const ListWindows = z + .object({ + app: requiredString('Missing app') + }) + .strict() + +export const Click = ComputerObserveTargetBase.extend({ + elementIndex: OptionalNonNegativeInt, + x: OptionalFiniteNumber, + y: OptionalFiniteNumber, + clickCount: OptionalPositiveInt, + mouseButton: z.enum(['left', 'right', 'middle']).optional(), + modifiers: z.string().optional() +}).superRefine((value, ctx) => { + validateComputerTarget(value, ctx) + const hasElement = value.elementIndex !== undefined + const hasX = value.x !== undefined + const hasY = value.y !== undefined + if (!hasElement && !(hasX && hasY)) { + ctx.addIssue({ + code: 'custom', + message: 'Click requires --element-index or both --x and --y' + }) + } + if (hasX !== hasY) { + ctx.addIssue({ + code: 'custom', + message: 'Click coordinates require both --x and --y' + }) + } + if (hasElement && (hasX || hasY)) { + ctx.addIssue({ + code: 'custom', + message: 'Click accepts either --element-index or coordinate flags, not both' + }) + } + if (value.modifiers !== undefined) { + const message = computerUseClickModifiersValidationMessage(value.modifiers) + if (message) { + ctx.addIssue({ code: 'custom', message }) + } + } +}) + +export const PerformSecondaryAction = ComputerObserveTargetBase.extend({ + elementIndex: OptionalNonNegativeInt, + action: requiredString('Missing action') +}).superRefine((value, ctx) => { + validateComputerTarget(value, ctx) + if (value.elementIndex === undefined) { + ctx.addIssue({ code: 'custom', message: 'Missing element index' }) + } +}) + +export const Scroll = ComputerObserveTargetBase.extend({ + elementIndex: OptionalNonNegativeInt, + x: OptionalFiniteNumber, + y: OptionalFiniteNumber, + direction: z.enum(['up', 'down', 'left', 'right']), + pages: z.number().positive().optional() +}).superRefine((value, ctx) => { + validateComputerTarget(value, ctx) + const hasElement = value.elementIndex !== undefined + const hasX = value.x !== undefined + const hasY = value.y !== undefined + if (!hasElement && !(hasX && hasY)) { + ctx.addIssue({ + code: 'custom', + message: 'Scroll requires --element-index or both --x and --y' + }) + } + if (hasX !== hasY) { + ctx.addIssue({ + code: 'custom', + message: 'Scroll coordinates require both --x and --y' + }) + } + if (hasElement && (hasX || hasY)) { + ctx.addIssue({ + code: 'custom', + message: 'Scroll accepts either --element-index or coordinate flags, not both' + }) + } +}) + +export const Drag = ComputerObserveTargetBase.extend({ + fromElementIndex: OptionalNonNegativeInt, + toElementIndex: OptionalNonNegativeInt, + fromX: OptionalFiniteNumber, + fromY: OptionalFiniteNumber, + toX: OptionalFiniteNumber, + toY: OptionalFiniteNumber +}).superRefine((value, ctx) => { + validateComputerTarget(value, ctx) + const hasElementPair = value.fromElementIndex !== undefined && value.toElementIndex !== undefined + const hasPartialElementPair = + value.fromElementIndex !== undefined || value.toElementIndex !== undefined + const coordinateKeys = [value.fromX, value.fromY, value.toX, value.toY] + const hasCoordinatePair = coordinateKeys.every((coordinate) => coordinate !== undefined) + const hasPartialCoordinatePair = coordinateKeys.some((coordinate) => coordinate !== undefined) + if (hasElementPair && hasCoordinatePair) { + ctx.addIssue({ + code: 'custom', + message: 'Drag accepts either element indexes or coordinate flags, not both' + }) + } + if (!hasElementPair && !hasCoordinatePair) { + ctx.addIssue({ + code: 'custom', + message: 'Drag requires --from-element-index and --to-element-index, or all coordinate flags' + }) + } + if (hasPartialElementPair && !hasElementPair) { + ctx.addIssue({ + code: 'custom', + message: 'Drag element targeting requires both --from-element-index and --to-element-index' + }) + } + if (hasPartialCoordinatePair && !hasCoordinatePair) { + ctx.addIssue({ + code: 'custom', + message: 'Drag coordinates require --from-x, --from-y, --to-x, and --to-y' + }) + } +}) + +export const TypeText = ComputerObserveTargetBase.extend({ + text: requiredString('Missing text') +}).superRefine(validateComputerTarget) + +export const PressKey = ComputerObserveTargetBase.extend({ + key: requiredString('Missing key') +}).superRefine((value, ctx) => { + validateComputerTarget(value, ctx) + const message = computerUsePressKeyValidationMessage(value.key) + if (message) { + ctx.addIssue({ code: 'custom', message }) + } +}) + +export const Hotkey = ComputerObserveTargetBase.extend({ + key: requiredString('Missing key') +}).superRefine((value, ctx) => { + validateComputerTarget(value, ctx) + const message = computerUseHotkeyValidationMessage(value.key) + if (message) { + ctx.addIssue({ code: 'custom', message }) + } +}) + +export const ComputerPermissions = z.object({ + id: z.enum(['accessibility', 'screenshots']).optional() +}) + +export const PasteText = ComputerObserveTargetBase.extend({ + text: requiredString('Missing text') +}).superRefine(validateComputerTarget) + +export const SetValue = ComputerObserveTargetBase.extend({ + elementIndex: OptionalNonNegativeInt, + value: requiredStringAllowingEmpty('Missing value') +}).superRefine((value, ctx) => { + validateComputerTarget(value, ctx) + if (value.elementIndex === undefined) { + ctx.addIssue({ code: 'custom', message: 'Missing element index' }) + } +}) diff --git a/src/shared/rpc-contract/emulator-params.ts b/src/shared/rpc-contract/emulator-params.ts new file mode 100644 index 00000000000..401e1ee05aa --- /dev/null +++ b/src/shared/rpc-contract/emulator-params.ts @@ -0,0 +1,154 @@ +import { z } from 'zod' + +// Minimal schemas for emulator commands (loose for initial testing; can be tightened like browser-schemas). +export const WorktreeParam = z.object({ worktree: z.string().optional() }).partial() + +export const TapParams = z.object({ + x: z.number().min(0).max(1), + y: z.number().min(0).max(1), + device: z.string().optional(), + emulator: z.string().optional(), + worktree: z.string().optional() +}) + +export const GesturePoint = z.object({ + edge: z.number().int().min(0).max(4).optional(), + type: z.enum(['begin', 'move', 'end']), + x: z.number().min(0).max(1), + y: z.number().min(0).max(1) +}) + +export const GestureParams = z.object({ + points: z.array(GesturePoint).min(2).max(64), + device: z.string().optional(), + emulator: z.string().optional(), + worktree: z.string().optional() +}) + +export const TypeParams = z.object({ + text: z.string(), + device: z.string().optional(), + emulator: z.string().optional(), + worktree: z.string().optional() +}) + +export const ButtonParams = z.object({ + name: z.string(), + device: z.string().optional(), + emulator: z.string().optional(), + worktree: z.string().optional() +}) + +export const RotateOrientation = z.enum([ + 'portrait', + 'portrait_upside_down', + 'landscape_left', + 'landscape_right' +]) + +export const RotateParams = z.object({ + orientation: RotateOrientation, + device: z.string().optional(), + emulator: z.string().optional(), + worktree: z.string().optional() +}) + +export const ExecParams = z.object({ + command: z.string(), + device: z.string().optional(), + emulator: z.string().optional(), + worktree: z.string().optional() +}) + +export const LaunchParams = z.object({ + package: z.string(), + activity: z.string().optional(), + device: z.string().optional(), + emulator: z.string().optional(), + worktree: z.string().optional() +}) + +export const PermissionsParams = z + .object({ + op: z.enum(['grant', 'revoke', 'reset']), + package: z.string().optional(), + permission: z.string().optional(), + device: z.string().optional(), + emulator: z.string().optional(), + worktree: z.string().optional() + }) + .superRefine((value, ctx) => { + if (value.op === 'reset') { + if (value.package) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['package'], + message: 'package is not allowed for reset' + }) + } + if (value.permission) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['permission'], + message: 'permission is not allowed for reset' + }) + } + return + } + if (!value.package) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['package'], + message: 'package is required for grant/revoke' + }) + } + if (!value.permission) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['permission'], + message: 'permission is required for grant/revoke' + }) + } + }) + +export const AxParams = z.object({ + device: z.string().optional(), + emulator: z.string().optional(), + worktree: z.string().optional() +}) + +export const LogcatParams = z.object({ + lines: z.number().int().positive().optional(), + filters: z.array(z.string()).optional(), + device: z.string().optional(), + emulator: z.string().optional(), + worktree: z.string().optional() +}) + +export const AttachParams = z.object({ + device: z.string().optional(), + worktree: z.string().optional(), + focus: z.boolean().optional() +}) + +export const KillParams = z.object({ + device: z.string().optional(), + emulator: z.string().optional(), + worktree: z.string().optional() +}) + +export const ShutdownParams = KillParams.extend({ + managedOnly: z.boolean().optional() +}) + +export const ListParams = WorktreeParam + +export const EmulatorUnregisterActiveParams = z + .object({ worktree: z.string().optional() }) + .partial() + +export const EmulatorListDevicesParams = z.object({ worktree: z.string().optional() }).partial() + +export const EmulatorAvailabilityParams = z.object({ worktree: z.string().optional() }).partial() + +export const EmulatorListSimulatorsParams = z.object({ worktree: z.string().optional() }).partial() diff --git a/src/shared/rpc-contract/files-mutation-params.ts b/src/shared/rpc-contract/files-mutation-params.ts new file mode 100644 index 00000000000..554d1f387e0 --- /dev/null +++ b/src/shared/rpc-contract/files-mutation-params.ts @@ -0,0 +1,84 @@ +import { z } from 'zod' +import { FileOpen, WorktreeSelector } from './files-target-params' + +export const RUNTIME_FILE_BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/ + +export function isValidRuntimeFileBase64(value: unknown): value is string { + return ( + typeof value === 'string' && value.length % 4 !== 1 && RUNTIME_FILE_BASE64_PATTERN.test(value) + ) +} + +export const FileMutationOpen = FileOpen.extend({ + expectedExecutionHostId: z.string().min(1).optional(), + expectedSshTargetId: z.string().min(1).optional(), + expectedSshConnectionGeneration: z.number().int().nonnegative().optional() +}) + +// Why: write content must be a real string. Coercing a missing/non-string value +// to '' silently truncated the target file to empty instead of erroring. An +// explicit '' is still accepted (writing an empty file is legitimate). +export const FileWrite = FileMutationOpen.extend({ + content: z + .unknown() + .refine((v): v is string => typeof v === 'string', { message: 'Missing file content' }) +}) + +export const FileWriteBase64 = FileMutationOpen.extend({ + contentBase64: z + .unknown() + .refine((v): v is string => typeof v === 'string', { message: 'Missing file content' }) + // Why: Buffer.from(..., 'base64') accepts malformed input by dropping + // invalid bytes, which can silently create empty or corrupt uploaded files. + .refine(isValidRuntimeFileBase64, 'File content must be base64') +}) + +export const FileWriteBase64Chunk = FileWriteBase64.extend({ + append: z.boolean().optional() +}) + +export const FileRename = WorktreeSelector.extend({ + expectedExecutionHostId: z.string().min(1).optional(), + expectedSshTargetId: z.string().min(1).optional(), + expectedSshConnectionGeneration: z.number().int().nonnegative().optional(), + oldRelativePath: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing source path')), + newRelativePath: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing destination path')) +}) + +export const FileCopy = WorktreeSelector.extend({ + expectedExecutionHostId: z.string().min(1).optional(), + expectedSshTargetId: z.string().min(1).optional(), + expectedSshConnectionGeneration: z.number().int().nonnegative().optional(), + sourceRelativePath: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing source path')), + destinationRelativePath: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing destination path')) +}) + +export const FileCommitUpload = WorktreeSelector.extend({ + expectedExecutionHostId: z.string().min(1).optional(), + expectedSshTargetId: z.string().min(1).optional(), + expectedSshConnectionGeneration: z.number().int().nonnegative().optional(), + tempRelativePath: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing temporary path')), + finalRelativePath: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing final path')) +}) + +export const FileDelete = FileMutationOpen.extend({ + recursive: z.boolean().optional() +}) diff --git a/src/shared/rpc-contract/files-params.ts b/src/shared/rpc-contract/files-params.ts new file mode 100644 index 00000000000..6ae6267caa0 --- /dev/null +++ b/src/shared/rpc-contract/files-params.ts @@ -0,0 +1,99 @@ +import { z } from 'zod' +import { QUICK_OPEN_REMOTE_QUERY_MAX_CODE_UNITS } from '../quick-open-path-search' +import { FileOpen, WorktreeSelector } from './files-target-params' + +export const FilePathSearch = WorktreeSelector.extend({ + query: z.string().max(QUICK_OPEN_REMOTE_QUERY_MAX_CODE_UNITS).default(''), + limit: z.number().int().positive().max(32).default(16), + excludePaths: z.array(z.string()).optional(), + mode: z.literal('quick-open').optional() +}) + +export const ResolveTerminalPath = WorktreeSelector.extend({ + pathText: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing path text')), + terminal: z + .unknown() + .transform((v) => (typeof v === 'string' && v.length > 0 ? v : null)) + .nullable() + .optional(), + cwd: z + .unknown() + .transform((v) => (typeof v === 'string' && v.length > 0 ? v : null)) + .nullable() + .optional(), + crossWorkspace: z + .unknown() + .transform((v) => v === true) + .optional(), + nativeChatContext: z + .object({ + tabId: z.string().min(1), + sessionId: z.string().min(1) + }) + .optional() +}) + +export const FileOpenDiff = FileOpen.extend({ + staged: z.boolean().optional() +}) + +export const DocPreviewFileRead = FileOpen.extend({ + entryRelativePath: z.string().min(1), + implicitRootRelativePath: z.string().nullable(), + authorizedRootRelativePaths: z.array(z.string()) +}) + +export const FileTreePath = WorktreeSelector.extend({ + relativePath: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string()) +}) + +export const ServerDirectoryBrowse = z.object({ + path: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string()) +}) + +export const FileReadChunk = FileOpen.extend({ + offset: z.number().int().nonnegative(), + length: z + .number() + .int() + .positive() + .max(512 * 1024) +}) + +export const FileSearch = WorktreeSelector.extend({ + query: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing search query')), + caseSensitive: z.boolean().optional(), + wholeWord: z.boolean().optional(), + useRegex: z.boolean().optional(), + includePattern: z.string().optional(), + excludePattern: z.string().optional(), + maxResults: z.number().int().positive().optional() +}) + +// Why: `maxResults` is a new optional field (wire rule 1) — an older host strips it and keeps its +// own default. It existed only on the Electron IPC hop, so "the client names its cap and a full page +// means there is more" was true for desktop and merely incidental for web and mobile, which were +// saved by `remoteFileContentBudget` defaulting the cap inside `listRuntimeFiles`. +export const FileListAll = WorktreeSelector.extend({ + excludePaths: z.array(z.string()).optional(), + maxResults: z.number().int().positive().optional() +}) + +export const FileUnwatch = z.object({ + subscriptionId: z + .unknown() + .transform((value) => (typeof value === 'string' && value.length > 0 ? value : '')) + .pipe(z.string().min(1, 'Missing subscriptionId')) +}) diff --git a/src/shared/rpc-contract/files-target-params.ts b/src/shared/rpc-contract/files-target-params.ts new file mode 100644 index 00000000000..6c546b3605e --- /dev/null +++ b/src/shared/rpc-contract/files-target-params.ts @@ -0,0 +1,15 @@ +import { z } from 'zod' + +export const WorktreeSelector = z.object({ + worktree: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing worktree selector')) +}) + +export const FileOpen = WorktreeSelector.extend({ + relativePath: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing relative path')) +}) diff --git a/src/shared/rpc-contract/files-terminal-artifact-params.ts b/src/shared/rpc-contract/files-terminal-artifact-params.ts new file mode 100644 index 00000000000..2e7e4f8015b --- /dev/null +++ b/src/shared/rpc-contract/files-terminal-artifact-params.ts @@ -0,0 +1,19 @@ +import { z } from 'zod' +import { WorktreeSelector } from './files-target-params' + +export const TerminalArtifactFile = WorktreeSelector.extend({ + grantId: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing terminal artifact grant')), + absolutePath: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing terminal artifact path')) +}) + +export const TerminalArtifactFileWrite = TerminalArtifactFile.extend({ + content: z + .unknown() + .refine((v): v is string => typeof v === 'string', { message: 'Missing file content' }) +}) diff --git a/src/shared/rpc-contract/folder-workspace-params.ts b/src/shared/rpc-contract/folder-workspace-params.ts new file mode 100644 index 00000000000..7b416b0083c --- /dev/null +++ b/src/shared/rpc-contract/folder-workspace-params.ts @@ -0,0 +1,85 @@ +import { z } from 'zod' +import { WorkspaceLinkedItemSchema } from '../workspace-linked-item-schema' +import { TaskSourceContextSchema } from '../task-source-context-schema' +import { isWorkspaceLinkedItemSourceContextMatch } from '../workspace-linked-item-source-context' +import { isTuiAgent } from '../tui-agent-config' +import { OptionalFiniteNumber, OptionalString, requiredString } from './rpc-param-primitives' +import { DiffCommentSchema } from '../diff-comment-schema' + +export const FolderWorkspaceLinkedTask = WorkspaceLinkedItemSchema.nullable() + +export function assertLinkedTaskSourceContextMatch( + value: { + linkedTask?: z.infer + linkedTaskSourceContext?: z.infer | null + }, + ctx: z.RefinementCtx +): void { + if ( + value.linkedTask && + value.linkedTaskSourceContext && + !isWorkspaceLinkedItemSourceContextMatch(value.linkedTask, value.linkedTaskSourceContext) + ) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: 'Linked task and source context identities must match' + }) + } +} + +export const FolderWorkspaceCreate = z + .object({ + projectGroupId: requiredString('Missing project group id'), + name: OptionalString, + folderPath: OptionalString.nullable().optional(), + connectionId: OptionalString.nullable().optional(), + linkedTask: FolderWorkspaceLinkedTask.optional(), + linkedTaskSourceContext: TaskSourceContextSchema.nullable().optional(), + createdWithAgent: z.string().refine(isTuiAgent).optional(), + pendingFirstAgentMessageRename: z.boolean().optional() + }) + .superRefine(assertLinkedTaskSourceContextMatch) + +export const FolderWorkspaceUpdate = z.object({ + folderWorkspaceId: requiredString('Missing folder workspace id'), + updates: z + .object({ + name: OptionalString, + folderPath: OptionalString, + linkedTask: FolderWorkspaceLinkedTask.optional(), + linkedTaskSourceContext: TaskSourceContextSchema.nullable().optional(), + comment: z.string().optional(), + isArchived: z.boolean().optional(), + isUnread: z.boolean().optional(), + isPinned: z.boolean().optional(), + sortOrder: OptionalFiniteNumber, + manualOrder: OptionalFiniteNumber, + workspaceStatus: OptionalString, + createdWithAgent: z.string().refine(isTuiAgent).optional(), + pendingFirstAgentMessageRename: z.boolean().optional(), + firstAgentMessageRenameError: z.string().nullable().optional(), + lastActivityAt: OptionalFiniteNumber, + diffComments: z.array(DiffCommentSchema).optional() + }) + .superRefine(assertLinkedTaskSourceContextMatch) +}) + +export const FolderWorkspaceSelector = z.object({ + folderWorkspaceId: requiredString('Missing folder workspace id') +}) + +export const FolderWorkspacePathStatus = z.discriminatedUnion('scope', [ + z.object({ + scope: z.literal('folder-workspace'), + folderWorkspaceId: requiredString('Missing folder workspace id') + }), + z.object({ + scope: z.literal('project-group'), + projectGroupId: requiredString('Missing project group id') + }), + z.object({ + scope: z.literal('path'), + path: requiredString('Missing folder path'), + connectionId: OptionalString.nullable().optional() + }) +]) diff --git a/src/shared/rpc-contract/git-admission-tier-params.ts b/src/shared/rpc-contract/git-admission-tier-params.ts new file mode 100644 index 00000000000..e45173782f8 --- /dev/null +++ b/src/shared/rpc-contract/git-admission-tier-params.ts @@ -0,0 +1,14 @@ +import { z } from 'zod' + +// Why: the admission tier is part of the wire contract, so the literal union +// lives with the schema; src/main re-exports it instead of redeclaring it. +export type GitAdmissionTier = 'interactive' | 'status' | 'background' + +export const OptionalGitAdmissionTier = z + .unknown() + .optional() + .transform((value): GitAdmissionTier | undefined => { + return value === 'interactive' || value === 'status' || value === 'background' + ? value + : undefined + }) diff --git a/src/shared/rpc-contract/git-params.ts b/src/shared/rpc-contract/git-params.ts new file mode 100644 index 00000000000..6e4cb35b8ef --- /dev/null +++ b/src/shared/rpc-contract/git-params.ts @@ -0,0 +1,271 @@ +import { z } from 'zod' +import { OptionalGitAdmissionTier } from './git-admission-tier-params' + +export const WorktreeSelector = z.object({ + worktree: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing worktree selector')) +}) + +export const GitStatusParams = WorktreeSelector.extend({ + admissionTier: OptionalGitAdmissionTier, + includeIgnored: z.boolean().optional(), + includeLineStats: z.boolean().optional(), + bypassEffectiveUpstreamNegativeCache: z.boolean().optional(), + reuseLineStats: z.boolean().optional(), + // Shape is re-validated host-side before it reaches a git argv. + branchLineTotalMergeBase: z.string().optional() +}) + +export const GitCheckIgnored = WorktreeSelector.extend({ + paths: z.array(z.string().min(1, 'Missing path')).max(2000) +}) + +export const GitSubmoduleStatus = WorktreeSelector.extend({ + submodulePath: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe( + z + .string() + .min(1, 'Missing submodule path') + // Why: never let a submodule path be parsed as a git flag (arg injection). + .refine((value) => !value.startsWith('-'), 'Submodule path must not start with -') + ), + // Why: submodule expansion is requested from a Source Control row; the row + // area determines whether the gitlink range is HEAD->index or index->worktree. + area: z.enum(['staged', 'unstaged', 'untracked']).optional() +}) + +export const GitFilePath = WorktreeSelector.extend({ + filePath: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing file path')) +}) + +export const GitDiff = GitFilePath.extend({ + staged: z.boolean(), + compareAgainstHead: z.boolean().optional() +}) + +export const GitBranchCompare = WorktreeSelector.extend({ + admissionTier: OptionalGitAdmissionTier, + baseRef: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe( + z + .string() + .min(1, 'Missing base ref') + .refine((value) => !value.startsWith('-'), 'Base ref must not start with -') + ) +}) + +export const FullGitObjectId = z + .string() + .regex(/^(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})$/, 'Expected a full git object id') + +export const GitCommitCompare = WorktreeSelector.extend({ + commitId: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(FullGitObjectId) +}) + +export const GitHistory = WorktreeSelector.extend({ + limit: z.number().int().min(1).max(200).optional(), + baseRef: z.string().nullable().optional() +}) + +export const GitBranchDiff = GitFilePath.extend({ + compare: z.object({ + baseRef: z.string().optional(), + baseOid: FullGitObjectId.optional(), + headOid: FullGitObjectId, + mergeBase: FullGitObjectId + }), + oldPath: z.string().optional() +}) + +export const GitCommitDiff = GitFilePath.extend({ + commitOid: FullGitObjectId, + parentOid: FullGitObjectId.nullable().optional(), + oldPath: z.string().optional() +}) + +export const GitCommit = WorktreeSelector.extend({ + message: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing commit message')) +}) + +export const CommitMessageModelCapability = z.object({ + id: z.string(), + label: z.string(), + thinkingLevels: z.array(z.object({ id: z.string(), label: z.string() })).optional(), + defaultThinkingLevel: z.string().optional() +}) + +export const CommitMessageAiSettings = z.object({ + enabled: z.boolean(), + agentId: z.string().nullable(), + selectedModelByAgent: z.record(z.string(), z.string()), + selectedModelByAgentByHost: z.record(z.string(), z.record(z.string(), z.string())).optional(), + discoveredModelsByAgent: z.record(z.string(), z.array(CommitMessageModelCapability)).optional(), + discoveredModelsByAgentByHost: z + .record(z.string(), z.record(z.string(), z.array(CommitMessageModelCapability))) + .optional(), + selectedThinkingByModel: z.record(z.string(), z.string()), + customPrompt: z.string(), + customAgentCommand: z.string() +}) + +export const SourceControlAiSettings = CommitMessageAiSettings.omit({ customPrompt: true }).extend({ + actions: z + .record( + z.string(), + z.object({ + agentId: z.string().nullable().optional(), + commandInputTemplate: z.string().optional(), + agentArgs: z.string().optional() + }) + ) + .optional(), + instructionsByOperation: z.record(z.string(), z.string()).optional(), + modelOverridesByOperation: z + .record( + z.string(), + z.object({ + selectedModelByAgent: z.record(z.string(), z.string()).optional(), + selectedModelByAgentByHost: z + .record(z.string(), z.record(z.string(), z.string())) + .optional(), + selectedThinkingByModel: z.record(z.string(), z.string()).optional() + }) + ) + .optional(), + prCreationDefaults: z + .object({ + draft: z.boolean().optional(), + useTemplate: z.boolean().optional(), + generateDetailsOnOpen: z.boolean().optional(), + openAfterCreate: z.boolean().optional() + }) + .optional(), + launchActionDefaults: z + .record( + z.string(), + z.object({ + agentId: z.string().nullable().optional(), + commandInputTemplate: z.string().optional(), + agentArgs: z.string().optional() + }) + ) + .optional() +}) + +export const ResolvedSourceControlAiGenerationParams = z.object({ + agentId: z.string(), + model: z.string(), + thinkingLevel: z.string().optional(), + customPrompt: z.string().optional(), + commandInputTemplate: z.string().optional(), + agentArgs: z.string().optional(), + customAgentCommand: z.string().optional(), + agentCommandOverride: z.string().optional() +}) + +export const GitGenerateCommitMessage = WorktreeSelector.extend({ + commitMessageAi: CommitMessageAiSettings.optional(), + sourceControlAi: SourceControlAiSettings.optional(), + sourceControlAiResolvedParams: ResolvedSourceControlAiGenerationParams.optional(), + agentCmdOverrides: z.record(z.string(), z.string()).optional(), + commitMessageDiscoveryHostKey: z.string().optional() +}) + +export const GitDiscoverCommitMessageModels = WorktreeSelector.extend({ + agentId: z.string().min(1, 'Missing agent id'), + agentCmdOverrides: z.record(z.string(), z.string()).optional() +}) + +export const GitGeneratePullRequestFields = GitGenerateCommitMessage.extend({ + base: z.string().min(1, 'Missing base branch'), + title: z.string(), + body: z.string(), + draft: z.boolean(), + provider: z + .enum(['github', 'gitlab', 'bitbucket', 'azure-devops', 'gitea', 'unsupported']) + .optional(), + useTemplate: z.boolean().optional() +}) + +export const GitBulkPaths = WorktreeSelector.extend({ + filePaths: z.array(z.string().min(1, 'Missing file path')) +}) + +export const GitPushTargetParam = z.object({ + remoteName: z.string(), + branchName: z.string(), + remoteUrl: z.string().optional(), + remoteCreated: z.boolean().optional() +}) + +export const GitPush = WorktreeSelector.extend({ + publish: z.boolean().optional(), + forceWithLease: z.boolean().optional(), + pushTarget: GitPushTargetParam.optional() +}) + +export const GitTargetedRemote = WorktreeSelector.extend({ + pushTarget: GitPushTargetParam.optional() +}) + +export const GitForkSync = WorktreeSelector.extend({ + expectedUpstream: z.object({ + owner: z.string().trim().min(1), + repo: z.string().trim().min(1) + }) +}) + +export const GitRebaseFromBase = WorktreeSelector.extend({ + baseRef: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe( + z + .string() + .min(1, 'Missing base ref') + .refine((value) => !value.startsWith('-'), 'Base ref must not start with -') + ) +}) + +export const GitCheckout = WorktreeSelector.extend({ + branch: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe( + z + .string() + .min(1, 'Missing branch') + // Why: never let a branch arg be parsed as a git flag (arg injection). + .refine((value) => !value.startsWith('-'), 'Branch must not start with -') + ) +}) + +export const GitRemoteFileUrl = WorktreeSelector.extend({ + relativePath: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing relative path')), + line: z.number().int().min(1) +}) + +export const GitRemoteCommitUrl = WorktreeSelector.extend({ + sha: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(FullGitObjectId) +}) diff --git a/src/shared/rpc-contract/github-issue-params.ts b/src/shared/rpc-contract/github-issue-params.ts new file mode 100644 index 00000000000..47effe410ff --- /dev/null +++ b/src/shared/rpc-contract/github-issue-params.ts @@ -0,0 +1,27 @@ +import { z } from 'zod' +import { RepoSelector, SlugRepo } from './github-repo-target-params' +import { requiredString } from './rpc-param-primitives' +import { IssueUpdate } from './github-issue-update-params' + +export const Issue = RepoSelector.extend({ + number: z.number().int().positive() +}) + +export const CreateIssue = RepoSelector.extend({ + title: requiredString('Missing title'), + body: z.string(), + labels: z.array(z.string()).optional(), + assignees: z.array(z.string()).optional() +}) + +export const UpdateIssue = RepoSelector.extend({ + number: z.number().int().positive(), + updates: IssueUpdate +}) + +export const IssueComment = RepoSelector.extend({ + number: z.number().int().positive(), + body: requiredString('Comment body required'), + type: z.enum(['issue', 'pr']).optional(), + prRepo: SlugRepo.nullable().optional() +}) diff --git a/src/shared/rpc-contract/github-issue-update-params.ts b/src/shared/rpc-contract/github-issue-update-params.ts new file mode 100644 index 00000000000..40eb7ab7d51 --- /dev/null +++ b/src/shared/rpc-contract/github-issue-update-params.ts @@ -0,0 +1,13 @@ +import { z } from 'zod' +import { OptionalString } from './rpc-param-primitives' + +// Why: repo-selector and slug-addressed issue updates must accept the identical field set. +export const IssueUpdate = z.object({ + state: z.enum(['open', 'closed']).optional(), + title: OptionalString, + body: OptionalString, + addLabels: z.array(z.string()).optional(), + removeLabels: z.array(z.string()).optional(), + addAssignees: z.array(z.string()).optional(), + removeAssignees: z.array(z.string()).optional() +}) diff --git a/src/shared/rpc-contract/github-project-params.ts b/src/shared/rpc-contract/github-project-params.ts new file mode 100644 index 00000000000..1a7a0d76f0c --- /dev/null +++ b/src/shared/rpc-contract/github-project-params.ts @@ -0,0 +1,128 @@ +import { z } from 'zod' +import { SlugRepo } from './github-repo-target-params' +import { OptionalString, requiredString } from './rpc-param-primitives' +import { IssueUpdate } from './github-issue-update-params' + +export const SlugAssignableUsers = SlugRepo.extend({ + seedLogins: z.array(z.string()).optional() +}) + +export const ProjectOwnerType = z.enum(['organization', 'user']) + +export const ProjectViewTable = z.object({ + owner: requiredString('Missing owner'), + // Why: Enterprise host identity must survive RPC parsing; Zod strips + // undeclared fields before the runtime can host-qualify gh requests. + host: OptionalString, + ownerType: ProjectOwnerType, + projectNumber: z.number().int().positive(), + viewId: OptionalString, + viewNumber: z.number().int().positive().optional(), + viewName: OptionalString, + queryOverride: OptionalString +}) + +export const ProjectWorkItemDetailsBySlug = SlugRepo.extend({ + number: z.number().int().positive(), + type: z.enum(['issue', 'pr']) +}) + +export const ProjectRef = z.object({ + input: requiredString('Missing project reference'), + // Why: Enterprise host identity must survive RPC parsing; Zod strips + // undeclared fields before the runtime can host-qualify gh requests. + host: OptionalString +}) + +export const ProjectViews = z.object({ + owner: requiredString('Missing owner'), + // Why: Enterprise host identity must survive RPC parsing; Zod strips + // undeclared fields before the runtime can host-qualify gh requests. + host: OptionalString, + ownerType: ProjectOwnerType, + projectNumber: z.number().int().positive() +}) + +export const ProjectItemField = z.object({ + projectId: requiredString('Missing project ID'), + // Why: Enterprise host identity must survive RPC parsing; Zod strips + // undeclared fields before the runtime can host-qualify gh requests. + host: OptionalString, + itemId: requiredString('Missing item ID'), + fieldId: requiredString('Missing field ID'), + value: z.any() +}) + +export const ClearProjectItemField = z.object({ + projectId: requiredString('Missing project ID'), + // Why: Enterprise host identity must survive RPC parsing; Zod strips + // undeclared fields before the runtime can host-qualify gh requests. + host: OptionalString, + itemId: requiredString('Missing item ID'), + fieldId: requiredString('Missing field ID') +}) + +export const SlugIssueUpdate = z.object({ + owner: requiredString('Missing owner'), + repo: requiredString('Missing repo'), + // Why: Enterprise host identity must survive RPC parsing; Zod strips + // undeclared fields before the runtime can host-qualify gh requests. + host: OptionalString, + number: z.number().int().positive(), + updates: IssueUpdate +}) + +export const SlugPullRequestUpdate = z.object({ + owner: requiredString('Missing owner'), + repo: requiredString('Missing repo'), + // Why: Enterprise host identity must survive RPC parsing; Zod strips + // undeclared fields before the runtime can host-qualify gh requests. + host: OptionalString, + number: z.number().int().positive(), + updates: z.object({ + state: z.enum(['open', 'closed']).optional(), + title: OptionalString, + body: OptionalString + }) +}) + +export const SlugIssueTypeUpdate = z.object({ + owner: requiredString('Missing owner'), + repo: requiredString('Missing repo'), + // Why: Enterprise host identity must survive RPC parsing; Zod strips + // undeclared fields before the runtime can host-qualify gh requests. + host: OptionalString, + number: z.number().int().positive(), + issueTypeId: z.string().nullable() +}) + +export const SlugIssueComment = z.object({ + owner: requiredString('Missing owner'), + repo: requiredString('Missing repo'), + // Why: Enterprise host identity must survive RPC parsing; Zod strips + // undeclared fields before the runtime can host-qualify gh requests. + host: OptionalString, + number: z.number().int().positive(), + body: requiredString('Comment body required') +}) + +export const SlugIssueCommentEdit = z.object({ + owner: requiredString('Missing owner'), + repo: requiredString('Missing repo'), + // Why: Enterprise host identity must survive RPC parsing; Zod strips + // undeclared fields before the runtime can host-qualify gh requests. + host: OptionalString, + commentId: z.number().int().positive(), + body: requiredString('Comment body required') +}) + +export const SlugIssueCommentDelete = z.object({ + owner: requiredString('Missing owner'), + repo: requiredString('Missing repo'), + // Why: Enterprise host identity must survive RPC parsing; Zod strips + // undeclared fields before the runtime can host-qualify gh requests. + host: OptionalString, + commentId: z.number().int().positive() +}) + +export const GithubProjectListAccessibleParams = z.object({ host: OptionalString }) diff --git a/src/shared/rpc-contract/github-pull-request-params.ts b/src/shared/rpc-contract/github-pull-request-params.ts new file mode 100644 index 00000000000..6762e8ea130 --- /dev/null +++ b/src/shared/rpc-contract/github-pull-request-params.ts @@ -0,0 +1,79 @@ +import { z } from 'zod' +import type { GitHubPRRefreshReason } from '../github/pull-request-refresh-types' +import { RepoSelector, SlugRepo } from './github-repo-target-params' +import { OptionalString, requiredString } from './rpc-param-primitives' + +export const OptionalPRRefreshReason = z + .unknown() + .optional() + .transform((value): GitHubPRRefreshReason | undefined => { + return value === 'visible' || + value === 'active' || + value === 'post-push' || + value === 'manual' || + value === 'swr' + ? value + : undefined + }) + +export const PrForBranch = RepoSelector.extend({ + branch: requiredString('Missing branch'), + reason: OptionalPRRefreshReason, + linkedPRNumber: z.number().int().positive().nullable().optional(), + fallbackPRNumber: z.number().int().positive().nullable().optional(), + acceptMergedFallbackPR: z.boolean().optional(), + currentHeadOid: z.string().nullable().optional() +}) + +export const PullRequest = RepoSelector.extend({ + prNumber: z.number().int().positive(), + noCache: z.boolean().optional(), + prRepo: SlugRepo.nullable().optional() +}) + +export const PRCommentReaction = RepoSelector.extend({ + reactionSubjectId: requiredString('Missing reaction subject ID'), + content: z.enum(['+1', '-1', 'laugh', 'confused', 'heart', 'hooray', 'rocket', 'eyes']), + reacted: z.boolean(), + prRepo: SlugRepo.nullable().optional() +}) + +export const PullRequestChecks = PullRequest.extend({ + headSha: OptionalString +}) + +export const PullRequestCheckDetails = RepoSelector.extend({ + checkRunId: z.number().int().positive().optional(), + workflowRunId: z.number().int().positive().optional(), + checkName: OptionalString, + url: OptionalString.nullable().optional(), + prRepo: SlugRepo.nullable().optional() +}) + +export const RerunPullRequestChecks = PullRequest.extend({ + headSha: OptionalString, + failedOnly: z.boolean().optional() +}) + +export const PullRequestFileContents = RepoSelector.extend({ + prNumber: z.number().int().positive(), + prRepo: SlugRepo.nullable().optional(), + path: requiredString('Missing file path'), + oldPath: OptionalString, + status: z.enum(['added', 'removed', 'modified', 'renamed', 'copied', 'changed', 'unchanged']), + headSha: requiredString('Missing head SHA'), + baseSha: requiredString('Missing base SHA') +}) + +export const PullRequestFileViewed = RepoSelector.extend({ + prRepo: SlugRepo.nullable().optional(), + pullRequestId: requiredString('Missing pull request ID'), + path: requiredString('Missing file path'), + viewed: z.boolean() +}) + +export const ReviewThread = RepoSelector.extend({ + prRepo: SlugRepo.nullable().optional(), + threadId: requiredString('Missing thread ID'), + resolve: z.boolean() +}) diff --git a/src/shared/rpc-contract/github-pull-request-update-params.ts b/src/shared/rpc-contract/github-pull-request-update-params.ts new file mode 100644 index 00000000000..f5fcc38ef73 --- /dev/null +++ b/src/shared/rpc-contract/github-pull-request-update-params.ts @@ -0,0 +1,76 @@ +import { z } from 'zod' +import { RepoSelector, SlugRepo } from './github-repo-target-params' +import { OptionalString, requiredString } from './rpc-param-primitives' + +export const UpdatePrTitle = RepoSelector.extend({ + prNumber: z.number().int().positive(), + title: requiredString('Missing title'), + prRepo: SlugRepo.nullable().optional() +}) + +export const UpdatePr = RepoSelector.extend({ + prNumber: z.number().int().positive(), + updates: z.object({ + title: OptionalString, + body: z.string().optional() + }), + prRepo: SlugRepo.nullable().optional() +}) + +export const MergePr = RepoSelector.extend({ + prNumber: z.number().int().positive(), + method: z.enum(['merge', 'squash', 'rebase']).optional(), + prRepo: SlugRepo.nullable().optional() +}) + +export const SetPrAutoMerge = RepoSelector.extend({ + prNumber: z.number().int().positive(), + enabled: z.boolean(), + method: z.enum(['merge', 'squash', 'rebase']).optional(), + prRepo: SlugRepo.nullable().optional() +}) + +export const UpdatePrState = RepoSelector.extend({ + prNumber: z.number().int().positive(), + prRepo: SlugRepo.nullable().optional(), + updates: z.object({ + state: z.enum(['open', 'closed']) + }) +}) + +export const MarkPrReadyForReview = RepoSelector.extend({ + prNumber: z.number().int().positive(), + prRepo: SlugRepo.nullable().optional() +}) + +export const RequestPrReviewers = RepoSelector.extend({ + prNumber: z.number().int().positive(), + prRepo: SlugRepo.nullable().optional(), + reviewers: z.array(z.string()).min(1) +}) + +export const RemovePrReviewers = RepoSelector.extend({ + prNumber: z.number().int().positive(), + prRepo: SlugRepo.nullable().optional(), + reviewers: z.array(z.string()).min(1) +}) + +export const PRReviewComment = RepoSelector.extend({ + prNumber: z.number().int().positive(), + prRepo: SlugRepo.nullable().optional(), + commitId: requiredString('Missing PR head SHA'), + path: requiredString('File path required'), + line: z.number().int().positive(), + startLine: z.number().int().positive().optional(), + body: requiredString('Comment body required') +}) + +export const PRReviewCommentReply = RepoSelector.extend({ + prNumber: z.number().int().positive(), + commentId: z.number().int().positive(), + body: requiredString('Comment body required'), + threadId: OptionalString, + path: OptionalString, + line: z.number().int().positive().optional(), + prRepo: SlugRepo.nullable().optional() +}) diff --git a/src/shared/rpc-contract/github-repo-target-params.ts b/src/shared/rpc-contract/github-repo-target-params.ts new file mode 100644 index 00000000000..199e90ad388 --- /dev/null +++ b/src/shared/rpc-contract/github-repo-target-params.ts @@ -0,0 +1,14 @@ +import { z } from 'zod' +import { OptionalString, requiredString } from './rpc-param-primitives' + +export const RepoSelector = z.object({ + repo: requiredString('Missing repo selector') +}) + +export const SlugRepo = z.object({ + owner: requiredString('Missing owner'), + repo: requiredString('Missing repo'), + // Why: Enterprise host identity must survive RPC parsing; Zod strips + // undeclared fields before the runtime can host-qualify gh requests. + host: OptionalString +}) diff --git a/src/shared/rpc-contract/github-repo-work-item-params.ts b/src/shared/rpc-contract/github-repo-work-item-params.ts new file mode 100644 index 00000000000..ecee149054f --- /dev/null +++ b/src/shared/rpc-contract/github-repo-work-item-params.ts @@ -0,0 +1,39 @@ +import { z } from 'zod' +import { RepoSelector } from './github-repo-target-params' +import { OptionalFiniteNumber, OptionalString, requiredString } from './rpc-param-primitives' + +export const WorkItemsList = RepoSelector.extend({ + limit: OptionalFiniteNumber, + query: OptionalString, + page: z.number().int().positive().optional(), + noCache: z.boolean().optional() +}) + +export const IssuesList = RepoSelector.extend({ + limit: OptionalFiniteNumber +}) + +export const WorkItem = RepoSelector.extend({ + number: z.number().int().positive(), + type: z.enum(['issue', 'pr']).optional() +}) + +export const WorkItemByOwnerRepo = RepoSelector.extend({ + owner: requiredString('Missing owner'), + ownerRepo: requiredString('Missing repo'), + // Why: Enterprise host identity must survive RPC parsing; Zod strips + // undeclared fields before the runtime can host-qualify gh requests. + host: OptionalString, + number: z.number().int().positive(), + type: z.enum(['issue', 'pr']) +}) + +export const WorkItemDetails = WorkItem + +export const WorkItemsCount = RepoSelector.extend({ + query: OptionalString +}) + +export const RateLimit = z.object({ + force: z.boolean().optional() +}) diff --git a/src/shared/rpc-contract/gitlab-params.ts b/src/shared/rpc-contract/gitlab-params.ts new file mode 100644 index 00000000000..4165f190968 --- /dev/null +++ b/src/shared/rpc-contract/gitlab-params.ts @@ -0,0 +1,149 @@ +import { z } from 'zod' +import { OptionalFiniteNumber, OptionalString, requiredString } from './rpc-param-primitives' + +export const RepoSelector = z.object({ + repo: requiredString('Missing repo selector') +}) + +export const EmptyParams = z.object({}).optional().default({}) + +export const GitLabRateLimit = z + .object({ + force: z.boolean().optional(), + host: OptionalString + }) + .optional() + .default({}) + +// nullish, not optional: renderer callers normalise a missing ref to `null` +// (`item.projectRef ?? null`), which a bare `.optional()` would reject outright. +export const GitLabProjectRef = z + .object({ + host: requiredString('Missing GitLab host'), + path: requiredString('Missing GitLab project path') + }) + .nullish() + +export const WorkItemsList = RepoSelector.extend({ + state: z.enum(['opened', 'merged', 'closed', 'all']).optional(), + page: OptionalFiniteNumber, + perPage: OptionalFiniteNumber, + query: OptionalString +}) + +export const IssuesList = RepoSelector.extend({ + state: z.unknown().optional(), + assignee: OptionalString, + limit: OptionalFiniteNumber, + page: OptionalFiniteNumber +}) + +export const CreateIssue = RepoSelector.extend({ + title: requiredString('Missing title'), + body: z.string() +}) + +export const IssueUpdate = z.object({ + state: z.enum(['opened', 'closed']).optional(), + title: z.string().optional(), + body: z.string().optional(), + addLabels: z.array(z.string()).optional(), + removeLabels: z.array(z.string()).optional(), + addAssignees: z.array(z.string()).optional(), + removeAssignees: z.array(z.string()).optional() +}) + +export const UpdateIssue = RepoSelector.extend({ + number: z.number().int().positive(), + updates: IssueUpdate, + projectRef: GitLabProjectRef +}) + +export const UpdateMrState = RepoSelector.extend({ + iid: z.number().int().positive(), + state: z.enum(['opened', 'closed']), + projectRef: GitLabProjectRef +}) + +export const UpdateMr = RepoSelector.extend({ + iid: z.number().int().positive(), + updates: z.object({ + title: z.string().optional(), + body: z.string().optional(), + addLabels: z.array(z.string()).optional(), + removeLabels: z.array(z.string()).optional(), + readyForReview: z.literal(true).optional() + }), + projectRef: GitLabProjectRef +}) + +export const UpdateMrReviewers = RepoSelector.extend({ + iid: z.number().int().positive(), + reviewerIds: z.array(z.number().int().nonnegative()), + projectRef: GitLabProjectRef +}) + +export const MergeMr = RepoSelector.extend({ + iid: z.number().int().positive(), + method: z.enum(['merge', 'squash', 'rebase']).optional(), + projectRef: GitLabProjectRef +}) + +export const AddIssueComment = RepoSelector.extend({ + number: z.number().int().positive(), + body: requiredString('Comment body is required'), + projectRef: GitLabProjectRef +}) + +export const AddMRComment = RepoSelector.extend({ + iid: z.number().int().positive(), + body: requiredString('Comment body is required'), + projectRef: GitLabProjectRef +}) + +export const AddMRInlineComment = RepoSelector.extend({ + iid: z.number().int().positive(), + input: z.object({ + body: requiredString('Comment body is required'), + path: requiredString('File path is required'), + oldPath: z.string().optional(), + line: z.number().int().positive(), + baseSha: requiredString('Base SHA is required'), + startSha: requiredString('Start SHA is required'), + headSha: requiredString('Head SHA is required') + }), + projectRef: GitLabProjectRef +}) + +export const ResolveMRDiscussion = RepoSelector.extend({ + iid: z.number().int().positive(), + discussionId: requiredString('Discussion id is required'), + resolved: z.boolean(), + projectRef: GitLabProjectRef +}) + +export const JobTrace = RepoSelector.extend({ + jobId: z.number().int().positive(), + projectRef: GitLabProjectRef, + // Why: raw CI traces routinely exceed the 1 MB transport frame cap, so callers + // that only render an excerpt ask main to bound it before it crosses the wire. + logExcerpt: z.boolean().optional() +}) + +export const RetryJob = RepoSelector.extend({ + jobId: z.number().int().positive(), + projectRef: GitLabProjectRef +}) + +export const WorkItemDetails = RepoSelector.extend({ + iid: z.number().int().positive(), + type: z.enum(['issue', 'mr']), + projectRef: GitLabProjectRef +}) + +export const WorkItemByPath = RepoSelector.extend({ + host: requiredString('Missing GitLab host'), + path: requiredString('Missing GitLab project path'), + iid: z.number().int().positive(), + type: z.enum(['issue', 'mr']) +}) diff --git a/src/shared/rpc-contract/hosted-review-params.ts b/src/shared/rpc-contract/hosted-review-params.ts new file mode 100644 index 00000000000..cb9ec7683cc --- /dev/null +++ b/src/shared/rpc-contract/hosted-review-params.ts @@ -0,0 +1,47 @@ +import { z } from 'zod' +import { requiredString } from './rpc-param-primitives' +import { OptionalGitAdmissionTier } from './git-admission-tier-params' + +export const HostedReviewForBranch = z.object({ + repo: requiredString('Missing repo selector'), + branch: requiredString('Missing branch'), + admissionTier: OptionalGitAdmissionTier, + currentHeadOid: z.string().nullable().optional(), + // Only the caller's selected worktree; the host caps how many earn the fast tier. + active: z.boolean().optional(), + linkedGitHubPR: z.number().int().positive().nullable().optional(), + fallbackGitHubPR: z.number().int().positive().nullable().optional(), + linkedGitLabMR: z.number().int().positive().nullable().optional(), + linkedBitbucketPR: z.number().int().positive().nullable().optional(), + linkedAzureDevOpsPR: z.number().int().positive().nullable().optional(), + linkedGiteaPR: z.number().int().positive().nullable().optional() +}) + +export const HostedReviewCreationEligibility = z.object({ + repo: requiredString('Missing repo selector'), + worktree: z.string().min(1, 'Missing worktree selector').optional(), + branch: requiredString('Missing branch'), + base: z.string().nullable().optional(), + hasUncommittedChanges: z.boolean().optional(), + hasUpstream: z.boolean().optional(), + ahead: z.number().int().nonnegative().optional(), + behind: z.number().int().nonnegative().optional(), + linkedGitHubPR: z.number().int().positive().nullable().optional(), + fallbackGitHubPR: z.number().int().positive().nullable().optional(), + linkedGitLabMR: z.number().int().positive().nullable().optional(), + linkedBitbucketPR: z.number().int().positive().nullable().optional(), + linkedAzureDevOpsPR: z.number().int().positive().nullable().optional(), + linkedGiteaPR: z.number().int().positive().nullable().optional() +}) + +export const HostedReviewCreate = z.object({ + repo: requiredString('Missing repo selector'), + worktree: z.string().min(1, 'Missing worktree selector').optional(), + provider: z.enum(['github', 'gitlab', 'bitbucket', 'azure-devops', 'gitea', 'unsupported']), + base: requiredString('Missing base branch'), + head: z.string().optional(), + title: requiredString('Missing title'), + body: z.string().optional(), + draft: z.boolean().optional(), + useTemplate: z.boolean().optional() +}) diff --git a/src/shared/rpc-contract/jira-params.ts b/src/shared/rpc-contract/jira-params.ts new file mode 100644 index 00000000000..b550124fd7f --- /dev/null +++ b/src/shared/rpc-contract/jira-params.ts @@ -0,0 +1,101 @@ +import { z } from 'zod' +import { + OptionalFiniteNumber, + OptionalPlainString, + OptionalString, + requiredString +} from './rpc-param-primitives' + +export const VALID_FILTERS = ['assigned', 'reported', 'all', 'done'] as const + +export const SiteSelection = z + .object({ + siteId: OptionalString + }) + .optional() + +export const Connect = z.object({ + siteUrl: requiredString('Site URL is required'), + // Self-hosted PAT auth needs no email; connect() enforces it for Cloud. + email: OptionalPlainString, + apiToken: requiredString('API token is required'), + authType: z.enum(['cloud', 'server']).optional() +}) + +export const SelectSite = z.object({ + siteId: requiredString('Site ID is required') +}) + +export const SearchIssues = z.object({ + jql: requiredString('Missing JQL'), + limit: OptionalFiniteNumber, + siteId: OptionalString +}) + +export const ListIssues = z + .object({ + filter: z.enum(VALID_FILTERS).optional(), + limit: OptionalFiniteNumber, + siteId: OptionalString + }) + .optional() + +export const IssueKey = z.object({ + key: requiredString('Issue key is required'), + siteId: OptionalString +}) + +export const CreateIssue = z.object({ + siteId: OptionalString, + projectId: requiredString('Project is required'), + issueTypeId: requiredString('Issue type is required'), + title: requiredString('Title is required'), + description: OptionalPlainString, + customFields: z.record(z.string(), z.unknown()).optional(), + userFieldKeys: z.array(z.string()).optional() +}) + +export const IssueUpdate = z.object({ + key: requiredString('Issue key is required'), + siteId: OptionalString, + updates: z.object({ + title: OptionalString, + labels: z.array(z.string()).optional(), + assigneeAccountId: z.union([z.string(), z.null()]).optional(), + priorityId: z.union([z.string(), z.null()]).optional(), + transitionId: OptionalString + }) +}) + +export const IssueComment = z.object({ + key: requiredString('Issue key is required'), + body: requiredString('Comment body is required'), + siteId: OptionalString +}) + +export const ProjectIssueTypes = z.object({ + projectIdOrKey: requiredString('Project is required'), + siteId: OptionalString +}) + +export const ProjectIssueTypeFields = z.object({ + projectIdOrKey: requiredString('Project is required'), + issueTypeId: requiredString('Issue type is required'), + siteId: OptionalString +}) + +export const AssignableUsers = z.object({ + key: requiredString('Issue key is required'), + query: OptionalPlainString, + siteId: OptionalString +}) + +export const UserSearch = z.object({ + query: OptionalPlainString, + siteId: OptionalString +}) + +export const ProjectStatusOrder = z.object({ + projectKey: requiredString('Project key is required'), + siteId: OptionalString +}) diff --git a/src/shared/rpc-contract/linear-agent-access-params.ts b/src/shared/rpc-contract/linear-agent-access-params.ts new file mode 100644 index 00000000000..ac1c627c6cd --- /dev/null +++ b/src/shared/rpc-contract/linear-agent-access-params.ts @@ -0,0 +1,146 @@ +import { z } from 'zod' +import { OptionalFiniteNumber, OptionalString, requiredString } from './rpc-param-primitives' + +export const LINEAR_DUE_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/ + +export const LinearDueDate = z.string().refine((value) => LINEAR_DUE_DATE_PATTERN.test(value), { + message: 'Linear due dates must use YYYY-MM-DD' +}) + +export const OptionalLinearDueDate = LinearDueDate.optional() + +export const OptionalLinearDueDateOrClear = z.union([LinearDueDate, z.null()]).optional() + +export const AgentSearchIssues = z.object({ + query: requiredString('Missing query'), + limit: OptionalFiniteNumber, + workspaceId: z.union([z.string(), z.literal('all')]).optional() +}) + +export const LinearWorkspaceRead = z.object({ + workspaceId: z.union([z.string(), z.literal('all')]).optional() +}) + +export const LinearTeamLookup = z.object({ + teamInput: requiredString('Missing team'), + workspaceId: OptionalString.refine((value) => value !== 'all', { + message: '--workspace all is only valid for team list' + }) +}) + +export const LinearIssueList = z.object({ + filter: z.enum(['assigned', 'created', 'all', 'completed', 'open']).optional(), + teamInput: OptionalString, + limit: OptionalFiniteNumber, + workspaceId: z.union([z.string(), z.literal('all')]).optional() +}) + +export const LinearProjectList = z.object({ + query: OptionalString, + limit: OptionalFiniteNumber, + workspaceId: z.union([z.string(), z.literal('all')]).optional() +}) + +export const LinearIncludeFlags = z.object({ + comments: z.boolean(), + children: z.boolean(), + attachments: z.boolean(), + relations: z.boolean(), + activity: z.boolean().default(false) +}) + +export const LinearCurrentContext = z + .object({ + worktreeId: OptionalString, + terminalHandle: OptionalString, + cwd: OptionalString, + remote: z.boolean().optional() + }) + .optional() + +export const LinearWriteTarget = z.object({ + input: OptionalString, + current: z.boolean().optional(), + workspaceId: OptionalString.refine((value) => value !== 'all', { + message: '--workspace all is not valid for Linear writes' + }), + context: LinearCurrentContext +}) + +export const AgentIssueContext = z.object({ + input: OptionalString, + current: z.boolean().optional(), + workspaceId: OptionalString, + include: LinearIncludeFlags, + depth: z.number().int().min(0).max(5), + context: LinearCurrentContext +}) + +export const LinearIssueSetState = LinearWriteTarget.extend({ + to: requiredString('Missing target state') +}) + +export const LinearIssueUpdateTask = LinearWriteTarget.extend({ + operation: z.enum(['assignee', 'priority', 'estimate', 'dueDate', 'labels']), + assigneeId: z.string().nullable().optional(), + assigneeMe: z.boolean().optional(), + priority: z.number().int().min(0).max(4).optional(), + estimate: z.number().int().min(0).nullable().optional(), + dueDate: OptionalLinearDueDateOrClear, + labelMode: z.enum(['add', 'remove', 'set']).optional(), + labels: z.array(z.string()).optional() +}) + +export const LinearIssueAddComment = LinearWriteTarget.extend({ + body: requiredString('Missing comment body'), + replyTo: OptionalString, + writeId: OptionalString +}) + +export const LinearIssueRelationWrite = LinearWriteTarget.extend({ + relatedInput: requiredString('Missing related issue'), + relationship: z.enum(['blocks', 'blockedBy', 'relatedTo', 'duplicateOf']), + operation: z.enum(['add', 'remove']) +}) + +export const LinearIssueAttachLink = LinearWriteTarget.extend({ + url: requiredString('Missing attachment URL'), + title: OptionalString, + writeId: OptionalString +}) + +export const LinearIssueCreate = z.object({ + title: requiredString('Missing issue title'), + body: OptionalString, + teamInput: OptionalString, + teamKey: OptionalString, + state: OptionalString, + assignee: OptionalString, + priority: z.number().int().min(0).max(4).optional(), + estimate: z.number().int().min(0).optional(), + dueDate: OptionalLinearDueDate, + labels: z.array(z.string()).optional(), + projectInput: OptionalString, + parentInput: OptionalString, + parentCurrent: z.boolean().optional(), + workspaceId: OptionalString.refine((value) => value !== 'all', { + message: '--workspace all is not valid for Linear writes' + }), + writeId: OptionalString, + context: LinearCurrentContext +}) + +export const LinearSaveIssue = LinearWriteTarget.extend({ + team: OptionalString, + title: OptionalString, + description: z.string().optional(), + state: OptionalString, + assignee: z.string().nullable().optional(), + priority: z.number().int().min(0).max(4).optional(), + estimate: z.number().min(0).nullable().optional(), + dueDate: OptionalLinearDueDateOrClear, + labels: z.array(z.string()).optional(), + project: z.string().nullable().optional(), + parentId: z.string().nullable().optional(), + writeId: OptionalString +}) diff --git a/src/shared/rpc-contract/linear-issue-attribute-filter-params.ts b/src/shared/rpc-contract/linear-issue-attribute-filter-params.ts new file mode 100644 index 00000000000..8d793f42ba1 --- /dev/null +++ b/src/shared/rpc-contract/linear-issue-attribute-filter-params.ts @@ -0,0 +1,35 @@ +import { z } from 'zod' +import { + LINEAR_ISSUE_ATTRIBUTE_FILTER_ID_MAX_LENGTH, + LINEAR_ISSUE_ATTRIBUTE_FILTER_MAX_LABEL_IDS, + LINEAR_ISSUE_ATTRIBUTE_FILTER_MAX_PRIORITIES, + LINEAR_ISSUE_ATTRIBUTE_FILTER_MAX_STATE_IDS +} from '../linear/issue-attribute-filter' + +// Why: keep ListIssues param validation co-located with shared limits without +// pushing linear.ts past the max-lines ratchet. +export const LinearAttributeFilterId = z + .string() + .trim() + .min(1) + .max(LINEAR_ISSUE_ATTRIBUTE_FILTER_ID_MAX_LENGTH) + +export const LinearIssueAttributeFilterSchema = z + .object({ + stateIds: z.array(LinearAttributeFilterId).max(LINEAR_ISSUE_ATTRIBUTE_FILTER_MAX_STATE_IDS), + priorities: z + .array(z.number().int().min(0).max(4)) + .max(LINEAR_ISSUE_ATTRIBUTE_FILTER_MAX_PRIORITIES), + assignee: z.union([ + z.object({ kind: z.literal('unassigned') }).strict(), + z + .object({ + kind: z.literal('user'), + id: LinearAttributeFilterId + }) + .strict(), + z.null() + ]), + labelIds: z.array(LinearAttributeFilterId).max(LINEAR_ISSUE_ATTRIBUTE_FILTER_MAX_LABEL_IDS) + }) + .strict() diff --git a/src/shared/rpc-contract/linear-issue-list-params.ts b/src/shared/rpc-contract/linear-issue-list-params.ts new file mode 100644 index 00000000000..ec4813f4186 --- /dev/null +++ b/src/shared/rpc-contract/linear-issue-list-params.ts @@ -0,0 +1,38 @@ +import { z } from 'zod' +import { OptionalFiniteNumber, OptionalString } from './rpc-param-primitives' +import { LinearIssueAttributeFilterSchema } from './linear-issue-attribute-filter-params' + +export const LegacyListIssues = z + .object({ + filter: z.enum(['assigned', 'created', 'all', 'completed']).optional(), + limit: OptionalFiniteNumber, + workspaceId: OptionalString, + attributeFilter: LinearIssueAttributeFilterSchema.optional() + }) + .strict() + .optional() + +export const McpListIssues = z + .object({ + team: OptionalString, + cycle: OptionalString, + label: OptionalString, + limit: z.number().int().min(1).max(250).optional(), + query: OptionalString, + state: OptionalString, + cursor: OptionalString, + orderBy: z.enum(['createdAt', 'updatedAt']).optional(), + project: OptionalString, + release: OptionalString, + assignee: OptionalString, + delegate: OptionalString, + parentId: OptionalString, + priority: z.number().int().min(0).max(4).optional(), + createdAt: OptionalString, + updatedAt: OptionalString, + includeArchived: z.boolean().optional(), + workspaceId: OptionalString + }) + .strict() + +export const ListIssues = z.union([McpListIssues, LegacyListIssues]) diff --git a/src/shared/rpc-contract/linear-params.ts b/src/shared/rpc-contract/linear-params.ts new file mode 100644 index 00000000000..313227c6029 --- /dev/null +++ b/src/shared/rpc-contract/linear-params.ts @@ -0,0 +1,124 @@ +import { z } from 'zod' +import { OptionalFiniteNumber, OptionalString, requiredString } from './rpc-param-primitives' + +export const VALID_CUSTOM_VIEW_MODELS = ['issue', 'project'] as const + +export const LinearPriority = z.number().int().min(0).max(4).optional() + +export const LinearLabelIds = z.array(requiredString('Invalid label ID')).optional() + +export const Connect = z.object({ + apiKey: requiredString('Invalid API key') +}) + +export const WorkspaceSelection = z + .object({ + workspaceId: OptionalString + }) + .optional() + +export const ConcreteWorkspaceId = requiredString( + 'Concrete Linear workspace ID is required' +).refine((value) => value !== 'all', 'Concrete Linear workspace ID is required') + +export const SelectWorkspace = z.object({ + workspaceId: requiredString('Workspace ID is required') +}) + +export const SearchIssues = z.object({ + query: requiredString('Missing query'), + limit: OptionalFiniteNumber, + workspaceId: OptionalString +}) + +export const CreateIssue = z.object({ + teamId: requiredString('Team ID is required'), + title: requiredString('Title is required'), + description: OptionalString, + workspaceId: OptionalString, + parentIssueId: OptionalString, + projectId: z.union([z.string(), z.null()]).optional(), + stateId: OptionalString, + priority: LinearPriority, + assigneeId: z.union([z.string(), z.null()]).optional(), + labelIds: LinearLabelIds +}) + +export const IssueId = z.object({ + id: requiredString('Issue ID is required'), + workspaceId: OptionalString +}) + +export const IssueComment = z.object({ + issueId: requiredString('Issue ID is required'), + body: requiredString('Comment body is required'), + workspaceId: OptionalString +}) + +export const ListProjects = z + .object({ + query: OptionalString, + limit: OptionalFiniteNumber, + workspaceId: OptionalString, + force: z.boolean().optional() + }) + .optional() + +export const ProjectId = z.object({ + id: requiredString('Project ID is required'), + workspaceId: ConcreteWorkspaceId, + force: z.boolean().optional() +}) + +export const ProjectIssues = z.object({ + projectId: requiredString('Project ID is required'), + limit: OptionalFiniteNumber, + workspaceId: ConcreteWorkspaceId, + force: z.boolean().optional() +}) + +export const ListCustomViews = z.object({ + model: z.enum(VALID_CUSTOM_VIEW_MODELS), + limit: OptionalFiniteNumber, + workspaceId: OptionalString, + force: z.boolean().optional() +}) + +export const CustomViewId = z.object({ + viewId: requiredString('Custom view ID is required'), + model: z.enum(VALID_CUSTOM_VIEW_MODELS), + workspaceId: ConcreteWorkspaceId, + force: z.boolean().optional() +}) + +export const CustomViewContents = z.object({ + viewId: requiredString('Custom view ID is required'), + limit: OptionalFiniteNumber, + workspaceId: ConcreteWorkspaceId, + force: z.boolean().optional() +}) + +export const TeamId = z.object({ + teamId: requiredString('Team ID is required'), + workspaceId: OptionalString +}) + +export const IssueUpdate = z.object({ + id: requiredString('Issue ID is required'), + workspaceId: OptionalString, + updates: z.object({ + stateId: OptionalString, + title: OptionalString, + description: z.string().optional(), + assigneeId: z.union([z.string(), z.null()]).optional(), + estimate: z.union([z.number().int().min(0), z.null()]).optional(), + priority: z.number().int().min(0).max(4).optional(), + labelIds: z.array(z.string()).optional(), + projectId: z.union([z.string(), z.null()]).optional() + }) +}) + +export const LinearIssueCommentsParams = z.object({ + issueId: requiredString('Issue ID is required'), + workspaceId: OptionalString +}) diff --git a/src/shared/rpc-contract/linear-project-create-params.ts b/src/shared/rpc-contract/linear-project-create-params.ts new file mode 100644 index 00000000000..2eec8beb1fa --- /dev/null +++ b/src/shared/rpc-contract/linear-project-create-params.ts @@ -0,0 +1,20 @@ +import { z } from 'zod' +import { OptionalString, requiredString } from './rpc-param-primitives' + +export const LinearPriority = z.number().int().min(0).max(4).optional() + +export const LinearLabelIds = z.array(requiredString('Invalid label ID')).optional() + +export const CreateProject = z.object({ + name: requiredString('Project name is required'), + description: OptionalString, + content: OptionalString, + workspaceId: OptionalString, + teamIds: z.array(requiredString('Invalid team ID')).min(1, 'At least one team is required'), + leadId: z.union([z.string(), z.null()]).optional(), + memberIds: z.array(requiredString('Invalid member ID')).optional(), + labelIds: LinearLabelIds, + priority: LinearPriority, + startDate: OptionalString, + targetDate: OptionalString +}) diff --git a/src/shared/rpc-contract/native-chat-params.ts b/src/shared/rpc-contract/native-chat-params.ts new file mode 100644 index 00000000000..5a88049e10f --- /dev/null +++ b/src/shared/rpc-contract/native-chat-params.ts @@ -0,0 +1,50 @@ +import { z } from 'zod' +import type { AgentType } from '../native-chat-types' + +// Why: native chat renders an agent's own transcript (Claude/Codex JSONL). The +// desktop reaches the readers via Electron IPC; mobile/web clients reach the +// same pure readers through these runtime RPC methods so the native chat view +// works over the paired connection, not just in the desktop renderer. + +export const NativeChatSession = z.object({ + agent: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing agent')) + .transform((v) => v as AgentType), + sessionId: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing session id')), + // How many of the most-recent messages to return. Clients start small for a + // fast first paint and raise it to page older history in as the user scrolls. + // Clamp (don't reject) a limit past the max window so a client paging beyond it + // gets the capped tail and pagination stops cleanly — a hard `.max` rejection + // would fail the read and stall "load earlier" at the boundary. + limit: z + .number() + .int() + .positive() + .transform((value) => Math.min(value, MOBILE_NATIVE_CHAT_MAX_WINDOW)) + .optional(), + // Optional client-supplied cleanup token. When present, the subscribe handler + // keys the fs-watcher cleanup under it so registration and unsubscribe derive + // from the SAME token (back-compat: falls back to `agent:sessionId` when absent, + // which is exactly what existing mobile clients rely on). + subscriptionId: z.string().min(1).optional(), + // Authoritative transcript path from the agent hook (providerSession), used to + // locate the file directly when the session id no longer names it (recent + // Claude Code). Optional for back-compat with older clients. + transcriptPath: z.string().min(1).optional(), + // A pending snapshot is not authoritative transcript history. Only clients + // that advertise this semantic may receive one; legacy clients treat it as a + // settled empty read and can overwrite retention / unblock launch drafts. + capabilities: z.object({ transcriptPending: z.literal(1).optional() }).optional(), + beforeOffset: z.number().int().nonnegative().optional() +}) + +export const NativeChatUnsubscribe = z.object({ + subscriptionId: z.string().min(1).optional() +}) + +export const MOBILE_NATIVE_CHAT_MAX_WINDOW = 2000 diff --git a/src/shared/rpc-contract/notifications-params.ts b/src/shared/rpc-contract/notifications-params.ts new file mode 100644 index 00000000000..6ae2cd45f5e --- /dev/null +++ b/src/shared/rpc-contract/notifications-params.ts @@ -0,0 +1,61 @@ +import { z } from 'zod' +import { MOBILE_PUSH_APNS_ENVIRONMENTS, MOBILE_PUSH_PLATFORMS } from '../mobile-push-contract' + +export const NotificationUnsubscribeParams = z.object({ + subscriptionId: z + .unknown() + .transform((value) => (typeof value === 'string' && value.length > 0 ? value : '')) + .pipe(z.string().min(1, 'Missing subscriptionId')) +}) + +// Why: notifications.getMissedSince is the catch-up RPC for mobile reconnect +// (#8129). The client passes the highest seq it has already delivered; the +// runtime returns only notifications dispatched after that seq. Because the +// desktop assigns a monotonic seq to every dispatched notification, the cut is +// exact and idempotent — re-requesting with the same watermark can never +// return an already-delivered event, so reconnects never duplicate local +// pushes (the adversarial-review gate for #8129). +// `epoch` names the counter lifetime lastSeenSeq came from (#8591). The desktop's +// seq restarts at 0 on every launch while the client's watermark is persisted, so +// without it a post-restart watermark silently cuts away everything. Optional: a +// client that predates the field keeps the seq-only cut. +export const NotificationGetMissedSinceParams = z.object({ + lastSeenSeq: z.number().int().min(0, 'lastSeenSeq must be a non-negative integer'), + epoch: z.string().optional(), + includeDesktopSuppressed: z.boolean().optional(), + deliveredPushes: z + .array( + z.object({ + notificationId: z.string().min(1).max(2048), + notificationEpoch: z.string().min(1).max(128), + notificationSeq: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER) + }) + ) + .max(256) + .optional() +}) + +export const NotificationPushFilterParams = z.object({ + onlyWhenDesktopAway: z.boolean().optional(), + sound: z.boolean().optional() +}) + +export const NotificationRegisterPushParams = z + .object({ + platform: z.enum(MOBILE_PUSH_PLATFORMS), + token: z.string().min(1).max(4096), + apnsEnvironment: z.enum(MOBILE_PUSH_APNS_ENVIRONMENTS).optional(), + filter: NotificationPushFilterParams + }) + // Why strict: the device identity is added by the handler, so a caller-supplied + // `deviceId` must be an error, not a key silently dropped. + .strict() + // Why: an APNs token is only routable against the environment it was minted in, + // so a missing environment must fail loudly rather than default to production. + .refine((params) => params.platform !== 'ios' || params.apnsEnvironment !== undefined, { + message: 'apnsEnvironment is required for ios' + }) + +export const NotificationsSubscribeParams = z + .object({ includeDesktopSuppressed: z.boolean().optional() }) + .optional() diff --git a/src/shared/rpc-contract/orchestration-federation-control-params.ts b/src/shared/rpc-contract/orchestration-federation-control-params.ts new file mode 100644 index 00000000000..9bb5ada502f --- /dev/null +++ b/src/shared/rpc-contract/orchestration-federation-control-params.ts @@ -0,0 +1,22 @@ +import { z } from 'zod' +import { OptionalFiniteNumber, requiredString } from './rpc-param-primitives' +import { ORCHESTRATION_WORKER_READ_SOURCES } from '../orchestration-worker-output' + +export const FederationDispatchParams = z.object({ + dispatchId: requiredString('Missing Dispatch ID') +}) + +export const FederationReadParams = FederationDispatchParams.extend({ + cursor: OptionalFiniteNumber, + limit: OptionalFiniteNumber +}) + +export const FederationOutputReadParams = FederationDispatchParams.extend({ + cursor: z.union([z.number().int().nonnegative(), z.string().min(1).max(2_048)]).optional(), + limit: OptionalFiniteNumber, + source: z.enum(ORCHESTRATION_WORKER_READ_SOURCES).optional() +}) + +export const FederationFleetSnapshotParams = z.object({ + dispatchIds: z.array(requiredString('Missing Dispatch ID')).min(1).max(100) +}) diff --git a/src/shared/rpc-contract/orchestration-federation-relay-params.ts b/src/shared/rpc-contract/orchestration-federation-relay-params.ts new file mode 100644 index 00000000000..ef1608e8611 --- /dev/null +++ b/src/shared/rpc-contract/orchestration-federation-relay-params.ts @@ -0,0 +1,47 @@ +import { z } from 'zod' +import { OptionalFiniteNumber, requiredString } from './rpc-param-primitives' + +export const FederationPullParams = z.object({ + dispatchId: requiredString('Missing Dispatch ID'), + afterSequence: OptionalFiniteNumber, + replayUnacknowledged: z.boolean().optional(), + limit: OptionalFiniteNumber +}) + +export const FederationAckParams = z.object({ + dispatchId: requiredString('Missing Dispatch ID'), + throughSequence: z.number().int().nonnegative(), + settlements: z + .array( + z.object({ + sequence: z.number().int().positive(), + lifecycle: z.discriminatedUnion('action', [ + z.object({ + action: z.enum(['completed', 'failed']), + authority: z.literal('run_home') + }), + z.object({ + action: z.literal('rejected'), + code: z.string(), + reason: z.string(), + authority: z.literal('run_home') + }) + ]) + }) + ) + .optional() +}) + +export const FederationImportParams = z.object({ + dispatchId: requiredString('Missing Dispatch ID'), + items: z.array( + z.object({ + dispatch_id: requiredString('Missing item Dispatch ID'), + direction: z.literal('to_worker'), + sequence: z.number().int().positive(), + message_id: requiredString('Missing relay message ID'), + kind: requiredString('Missing relay kind'), + payload: requiredString('Missing relay payload') + }) + ) +}) diff --git a/src/shared/rpc-contract/orchestration-federation-start-params.ts b/src/shared/rpc-contract/orchestration-federation-start-params.ts new file mode 100644 index 00000000000..24cf82223f6 --- /dev/null +++ b/src/shared/rpc-contract/orchestration-federation-start-params.ts @@ -0,0 +1,29 @@ +import { z } from 'zod' +import { OptionalFiniteNumber, OptionalString, requiredString } from './rpc-param-primitives' +import { OptionalWorkerLaunchPreference } from './orchestration-worker-start-params' + +export const FederationAttachStartParams = z.object({ + /** Omitted by v1.4.198 coordinators; the worker host then mints a stub home Run. */ + runId: OptionalString, + dispatchId: requiredString('Missing Dispatch ID'), + taskId: requiredString('Missing Task ID'), + taskSpec: requiredString('Missing Task spec'), + /** Depth stamped by the Run home; omitted by older clients and defaults to 1. */ + depth: z.number().int().min(1).optional(), + protocolVersion: z.union([z.literal(1), z.literal(2), z.literal(3)]), + worktree: requiredString('Missing remote worktree selector'), + name: OptionalString, + repo: OptionalString, + baseBranch: OptionalString, + displayName: OptionalString, + displayNameKind: z.enum(['generated', 'user']).optional(), + comment: OptionalString, + setup: z.enum(['run', 'skip', 'inherit']).optional(), + setupSource: z.enum(['explicit_request', 'orchestration_default']).optional(), + terminal: OptionalString, + agent: OptionalString, + model: OptionalWorkerLaunchPreference, + effort: OptionalWorkerLaunchPreference, + timeoutMs: OptionalFiniteNumber, + devMode: z.boolean().optional() +}) diff --git a/src/shared/rpc-contract/orchestration-gates-params.ts b/src/shared/rpc-contract/orchestration-gates-params.ts new file mode 100644 index 00000000000..c7ea607b345 --- /dev/null +++ b/src/shared/rpc-contract/orchestration-gates-params.ts @@ -0,0 +1,34 @@ +import { z } from 'zod' +import { OptionalFiniteNumber, OptionalString, requiredString } from './rpc-param-primitives' + +export const RunParams = z.object({ + spec: requiredString('Missing --spec'), + from: OptionalString, + pollIntervalMs: OptionalFiniteNumber, + maxConcurrent: OptionalFiniteNumber, + worktree: OptionalString +}) + +export const RunStopParams = z.object({}) + +export const GateCreateParams = z.object({ + task: requiredString('Missing --task'), + question: requiredString('Missing --question'), + options: OptionalString, + from: OptionalString, + run: OptionalString +}) + +export const GateResolveParams = z.object({ + id: requiredString('Missing --id'), + resolution: requiredString('Missing --resolution'), + from: OptionalString, + run: OptionalString +}) + +export const GateListParams = z.object({ + task: OptionalString, + status: z.enum(['pending', 'resolved', 'timeout']).optional(), + from: OptionalString, + run: OptionalString +}) diff --git a/src/shared/rpc-contract/orchestration-params.ts b/src/shared/rpc-contract/orchestration-params.ts new file mode 100644 index 00000000000..e58dca2143c --- /dev/null +++ b/src/shared/rpc-contract/orchestration-params.ts @@ -0,0 +1,153 @@ +import { z } from 'zod' +import { + OptionalBoolean, + OptionalFiniteNumber, + OptionalString, + requiredString +} from './rpc-param-primitives' + +export type DispatchMutationMessageType = + | 'worker_done' + | 'heartbeat' + | 'escalation' + | 'decision_gate' + +export function isDispatchMutationMessageType( + type: string | undefined +): type is DispatchMutationMessageType { + return ( + type === 'worker_done' || + type === 'heartbeat' || + type === 'escalation' || + type === 'decision_gate' + ) +} + +export function getLifecycleGroupRecipientError(type: DispatchMutationMessageType): string { + return `${type} messages belong to one exact Dispatch and cannot target a group address.` +} + +export const CheckParams = z + .object({ + terminal: OptionalString, + terminalPaneKey: OptionalString, + unread: OptionalBoolean, + peek: OptionalBoolean, + // Why: `all` surfaces every message and skips mark-read; legacy encoding was the `{unread: false}` trick (design doc §3.2/§3.3). + all: OptionalBoolean, + types: OptionalString, + format: OptionalBoolean, + // Why: one-release RPC compatibility only; the public CLI uses --format because no terminal input is injected. + inject: OptionalBoolean, + ack: OptionalString, + compatibilityAck: OptionalString, + compatibilityQuestionAck: OptionalString, + compatibilityCliCommand: z.enum(['orca', 'orca-ide', 'orca-dev']).optional(), + run: OptionalString, + wait: OptionalBoolean, + timeoutMs: OptionalFiniteNumber + }) + .superRefine((params, ctx) => { + // Why: CLI encodes --peek as {peek:true, unread:false} for pre-peek runtimes, so that pair is one mode, not a conflict. + const modes = [ + params.unread === true, + params.peek === true, + params.all === true || (params.unread === false && params.peek !== true) + ].filter(Boolean) + if (modes.length > 1) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: 'Choose at most one message read mode: --unread, --peek, or --all.' + }) + } + }) + +export const ReplyParams = z.object({ + id: requiredString('Missing --id'), + body: requiredString('Missing --body'), + from: OptionalString, + run: OptionalString +}) + +export const InboxParams = z.object({ + limit: OptionalFiniteNumber, + // Why: filters the inbox to a handle so inbox and check --all give agreeing results (design doc §3.3). + terminal: OptionalString +}) + +export const TaskCreateParams = z.object({ + spec: requiredString('Missing --spec'), + taskTitle: OptionalString, + displayName: OptionalString, + deps: OptionalString, + parent: OptionalString, + callerTerminalHandle: OptionalString, + run: OptionalString +}) + +export const TaskListParams = z.object({ + status: z.enum(['pending', 'ready', 'dispatched', 'completed', 'failed', 'blocked']).optional(), + ready: OptionalBoolean, + // Why: server-side truncation keeps --brief cheap over SSH/relay instead of shipping full specs the CLI throws away. + brief: OptionalBoolean, + run: OptionalString, + callerTerminalHandle: OptionalString +}) + +export const DispatchParams = z.object({ + task: requiredString('Missing --task'), + // Why: --to is optional so --dry-run can preview without a target; the handler enforces presence before any side-effecting work. + to: OptionalString, + from: OptionalString, + inject: OptionalBoolean, + dryRun: OptionalBoolean, + returnPreamble: OptionalBoolean, + devMode: OptionalBoolean, + run: OptionalString +}) + +export const DispatchShowParams = z.object({ + task: OptionalString, + preamble: OptionalBoolean, + from: OptionalString, + devMode: OptionalBoolean +}) + +export const AskParams = z + .object({ + to: OptionalString, + question: OptionalString, + resume: OptionalString, + options: OptionalString, + timeoutMs: OptionalFiniteNumber, + from: OptionalString, + run: OptionalString, + compatibilityCliCommand: z.enum(['orca', 'orca-ide', 'orca-dev']).optional(), + compatibilityWindowsCommand: z.enum(['orca', 'orca-ide']).optional() + }) + .superRefine((params, ctx) => { + if ((params.question ? 1 : 0) + (params.resume ? 1 : 0) !== 1) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: 'Choose exactly one of --question or --resume.' + }) + } + }) + +export const ResetParams = z + .object({ + all: OptionalBoolean, + tasks: OptionalBoolean, + messages: OptionalBoolean + }) + .superRefine((params, ctx) => { + const selectedScopeCount = [params.all, params.tasks, params.messages].filter( + (scope) => scope === true + ).length + if (selectedScopeCount !== 1) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: 'Choose exactly one reset scope: --all, --tasks, or --messages.' + }) + } + }) diff --git a/src/shared/rpc-contract/orchestration-runs-mutation-request-show-params.ts b/src/shared/rpc-contract/orchestration-runs-mutation-request-show-params.ts new file mode 100644 index 00000000000..496c1ea3827 --- /dev/null +++ b/src/shared/rpc-contract/orchestration-runs-mutation-request-show-params.ts @@ -0,0 +1,4 @@ +import { z } from 'zod' +import { requiredString } from './rpc-param-primitives' + +export const RequestShowParams = z.object({ request: requiredString('Missing --request') }) diff --git a/src/shared/rpc-contract/orchestration-runs-params.ts b/src/shared/rpc-contract/orchestration-runs-params.ts new file mode 100644 index 00000000000..30aad1e9eae --- /dev/null +++ b/src/shared/rpc-contract/orchestration-runs-params.ts @@ -0,0 +1,23 @@ +import { z } from 'zod' +import { OptionalBoolean, OptionalString, requiredString } from './rpc-param-primitives' +import { ORCHESTRATION_RUN_PAGE_LIMIT } from '../orchestration-run-pagination' + +export const RunCreateParams = z.object({ + objective: requiredString('Missing --objective'), + from: requiredString('Missing coordinator terminal') +}) + +export const RunUseParams = z.object({ + id: requiredString('Missing --id'), + from: requiredString('Missing coordinator terminal'), + takeoverLegacy: OptionalBoolean +}) + +export const RunCurrentParams = z.object({ from: requiredString('Missing coordinator terminal') }) + +export const RunListParams = z.object({ + limit: z.number().int().min(1).max(ORCHESTRATION_RUN_PAGE_LIMIT).optional(), + cursor: z.string().min(1).optional() +}) + +export const RunShowParams = z.object({ id: requiredString('Missing --id'), from: OptionalString }) diff --git a/src/shared/rpc-contract/orchestration-worker-control-params.ts b/src/shared/rpc-contract/orchestration-worker-control-params.ts new file mode 100644 index 00000000000..9aa097522f1 --- /dev/null +++ b/src/shared/rpc-contract/orchestration-worker-control-params.ts @@ -0,0 +1,11 @@ +import { z } from 'zod' +import { OptionalFiniteNumber, requiredString } from './rpc-param-primitives' +import { ORCHESTRATION_WORKER_READ_SOURCES } from '../orchestration-worker-output' + +export const WorkerDispatchParams = z.object({ dispatch: requiredString('Missing --dispatch') }) + +export const WorkerReadParams = WorkerDispatchParams.extend({ + cursor: z.union([z.number().int().nonnegative(), z.string().min(1).max(2_048)]).optional(), + limit: OptionalFiniteNumber, + source: z.enum(ORCHESTRATION_WORKER_READ_SOURCES).optional() +}) diff --git a/src/shared/rpc-contract/orchestration-worker-release-params.ts b/src/shared/rpc-contract/orchestration-worker-release-params.ts new file mode 100644 index 00000000000..345a99e87b1 --- /dev/null +++ b/src/shared/rpc-contract/orchestration-worker-release-params.ts @@ -0,0 +1,12 @@ +import { z } from 'zod' + +export const OrchestrationWorkerTerminalUserInputParams = z + .object({ + paneKey: z.string().min(1).optional(), + sessionId: z.string().min(1).optional(), + terminal: z.string().min(1).optional() + }) + .refine( + (value) => Boolean(value.paneKey ?? value.sessionId ?? value.terminal), + 'Missing paneKey, sessionId or terminal' + ) diff --git a/src/shared/rpc-contract/orchestration-worker-release-schemas-params.ts b/src/shared/rpc-contract/orchestration-worker-release-schemas-params.ts new file mode 100644 index 00000000000..b2d75c46adc --- /dev/null +++ b/src/shared/rpc-contract/orchestration-worker-release-schemas-params.ts @@ -0,0 +1,25 @@ +import { z } from 'zod' +import { requiredString } from './rpc-param-primitives' +import { ORCHESTRATION_FLEET_PAGE_MAX } from '../orchestration-fleet-projection' + +export const WorkerDispatchParams = z.object({ dispatch: requiredString('Missing --dispatch') }) + +export const WorkerRetainParams = WorkerDispatchParams.strict() + +export const WORKER_TERMINAL_LIST_STATES = [ + 'active', + 'reclaimable', + 'retained', + 'release_pending', + 'release_unknown', + 'released' +] as const + +export const WorkerListParams = z.object({ + run: z.string().min(1).optional(), + terminalState: z.enum(WORKER_TERMINAL_LIST_STATES).optional(), + cursor: z.string().min(1).max(2_048).optional(), + limit: z.number().int().min(1).max(ORCHESTRATION_FLEET_PAGE_MAX).optional(), + includeRemote: z.boolean().optional(), + paginate: z.boolean().optional() +}) diff --git a/src/shared/rpc-contract/orchestration-worker-start-params.ts b/src/shared/rpc-contract/orchestration-worker-start-params.ts new file mode 100644 index 00000000000..dc6432aa47a --- /dev/null +++ b/src/shared/rpc-contract/orchestration-worker-start-params.ts @@ -0,0 +1,61 @@ +import { z } from 'zod' +import { OptionalFiniteNumber, OptionalString, requiredString } from './rpc-param-primitives' + +export const OptionalWorkerLaunchPreference = z + .string() + .min(1) + .max(512) + .refine((value) => value === value.trim(), 'Surrounding whitespace is invalid') + .optional() + +export const WorkerStartParams = z + .object({ + task: OptionalString, + spec: OptionalString, + taskTitle: OptionalString, + deps: OptionalString, + parent: OptionalString, + on: OptionalString, + run: OptionalString, + from: requiredString('Missing --from'), + worktree: OptionalString, + name: OptionalString, + repo: OptionalString, + baseBranch: OptionalString, + displayName: OptionalString, + comment: OptionalString, + setup: z.enum(['run', 'skip', 'inherit']).optional(), + terminal: OptionalString, + agent: OptionalString, + model: OptionalWorkerLaunchPreference, + effort: OptionalWorkerLaunchPreference, + retryOf: OptionalString, + timeoutMs: OptionalFiniteNumber, + devMode: z.boolean().optional() + }) + .superRefine((params, ctx) => { + if (!params.task && !params.spec) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['task'], + message: 'Missing --task or --spec' + }) + } + if (params.task && params.spec) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['spec'], + message: '--task and --spec are mutually exclusive' + }) + } + // Why: --spec creates a new Task, so a retry link to a prior Dispatch could never resolve and + // the refusal named a Task id the caller never supplied. + if (params.retryOf && params.spec) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['retryOf'], + message: + '--retry-of needs --task naming the failed Task; --spec creates a new one' + }) + } + }) diff --git a/src/shared/rpc-contract/orchestration-worker-stop-params.ts b/src/shared/rpc-contract/orchestration-worker-stop-params.ts new file mode 100644 index 00000000000..cb465c8808b --- /dev/null +++ b/src/shared/rpc-contract/orchestration-worker-stop-params.ts @@ -0,0 +1,4 @@ +import { z } from 'zod' +import { requiredString } from './rpc-param-primitives' + +export const WorkerDispatchParams = z.object({ dispatch: requiredString('Missing --dispatch') }) diff --git a/src/shared/rpc-contract/plugins-params.ts b/src/shared/rpc-contract/plugins-params.ts new file mode 100644 index 00000000000..8819f328d86 --- /dev/null +++ b/src/shared/rpc-contract/plugins-params.ts @@ -0,0 +1,20 @@ +import { z } from 'zod' +import { isQualifiedPluginKey } from '../plugins/plugin-manifest' + +export const PluginSetEnabledParams = z.object({ + pluginKey: z.string().refine(isQualifiedPluginKey, 'invalid qualified plugin key'), + enabled: z.boolean() +}) + +export const PluginReadPanelEntryParams = z.object({ + pluginKey: z.string().min(1), + panelId: z.string().min(1) +}) + +export const PluginInvokeCommandParams = z.object({ + pluginKey: z.string().min(1), + commandId: z.string().min(1), + args: z.unknown().optional() +}) + +export const PluginsPanelActionParams = z.unknown() diff --git a/src/shared/rpc-contract/preflight-params.ts b/src/shared/rpc-contract/preflight-params.ts new file mode 100644 index 00000000000..3dc6a8d1ef2 --- /dev/null +++ b/src/shared/rpc-contract/preflight-params.ts @@ -0,0 +1,13 @@ +import { z } from 'zod' + +export const PreflightCheck = z.object({ + force: z.boolean().optional() +}) + +export const PreflightDetectRemoteAgents = z.object({ + connectionId: z.string().min(1) +}) + +export const PreflightDetectRemoteWindowsTerminalCapabilities = z.object({ + connectionId: z.string().min(1) +}) diff --git a/src/shared/rpc-contract/project-runtime-params.ts b/src/shared/rpc-contract/project-runtime-params.ts new file mode 100644 index 00000000000..38d9ebff0ba --- /dev/null +++ b/src/shared/rpc-contract/project-runtime-params.ts @@ -0,0 +1,95 @@ +import { z } from 'zod' +import { OptionalString, requiredString } from './rpc-param-primitives' +import { + LOCAL_EXECUTION_HOST_ID, + normalizeExecutionHostId, + parseExecutionHostId +} from '../execution-host' + +export const ProjectProviderIdentity = z.object({ + provider: z.literal('github'), + owner: requiredString('Missing project owner'), + repo: requiredString('Missing project repository'), + host: OptionalString +}) + +// Why: `runtime:` ids are minted by the calling client's own pairing store +// (addEnvironmentFromPairingCode -> randomUUID), so they name a machine only relative to that +// client. A client sending one to this runtime is addressing *us*, and runtimes do not proxy +// these calls onward, so the host it names is this machine. Persisting the caller's id verbatim +// makes one machine look like a different host to every other client, hides its rows from them, +// and defeats the (projectId, hostId) duplicate check. Store our own spelling instead: `local`. +// Rows written before this normalization keep their client-minted stamp; readers still project +// `local` back to `runtime:`, so the client-visible model is unchanged. +export const RequestedHostId = requiredString('Missing host ID').transform((value, ctx) => { + const hostId = normalizeExecutionHostId(value) + if (!hostId) { + ctx.addIssue({ code: 'custom', message: 'Invalid host ID' }) + return z.NEVER + } + return parseExecutionHostId(hostId)?.kind === 'runtime' ? LOCAL_EXECUTION_HOST_ID : hostId +}) + +export const ProjectHostSetupExistingFolder = z.object({ + projectId: requiredString('Missing project ID'), + projectProviderIdentity: ProjectProviderIdentity.optional(), + hostId: RequestedHostId, + path: requiredString('Missing project path'), + kind: z.enum(['git', 'folder']).optional(), + displayName: OptionalString, + setupMethod: z.enum(['imported-existing-folder', 'cloned']).optional() +}) + +export const ProjectHostSetupClone = z.object({ + projectId: requiredString('Missing project ID'), + projectProviderIdentity: ProjectProviderIdentity.optional(), + hostId: RequestedHostId, + url: requiredString('Missing clone URL'), + destination: requiredString('Missing clone destination'), + displayName: OptionalString +}) + +export const LocalWindowsRuntimePreference = z.discriminatedUnion('kind', [ + z.object({ kind: z.literal('inherit-global') }), + z.object({ kind: z.literal('windows-host') }), + z.object({ kind: z.literal('wsl'), distro: requiredString('Missing WSL distro') }) +]) + +export const ProjectUpdate = z.object({ + projectId: requiredString('Missing project ID'), + updates: z.object({ + localWindowsRuntimePreference: LocalWindowsRuntimePreference.optional() + }) +}) + +export const ProjectHostSetupCreate = z.object({ + projectId: requiredString('Missing project ID'), + hostId: RequestedHostId, + setupId: OptionalString, + path: OptionalString, + kind: z.enum(['git', 'folder']).optional(), + displayName: OptionalString, + worktreeBasePath: OptionalString, + gitUsername: OptionalString, + setupState: z.enum(['ready', 'not-set-up', 'setting-up', 'error', 'unsupported']).optional(), + setupMethod: z.enum(['imported-existing-folder', 'cloned', 'provisioned']).optional() +}) + +export const ProjectHostSetupUpdate = z.object({ + setupId: requiredString('Missing setup ID'), + updates: z.object({ + displayName: OptionalString, + path: OptionalString, + worktreeBasePath: OptionalString, + setupState: z.enum(['ready', 'not-set-up', 'setting-up', 'error', 'unsupported']).optional(), + setupMethod: z + .enum(['legacy-repo', 'imported-existing-folder', 'cloned', 'provisioned']) + .optional(), + gitUsername: OptionalString, + kind: z.enum(['git', 'folder']).optional() + }) +}) + +export const ProjectHostSetupDelete = z.object({ + setupId: requiredString('Missing setup ID') +}) diff --git a/src/shared/rpc-contract/repo-params.ts b/src/shared/rpc-contract/repo-params.ts new file mode 100644 index 00000000000..e5d29174a03 --- /dev/null +++ b/src/shared/rpc-contract/repo-params.ts @@ -0,0 +1,100 @@ +import { z } from 'zod' +import { OptionalFiniteNumber, OptionalString, requiredString } from './rpc-param-primitives' +import { createRepoUpdateSchema } from './repo-update-params' +import { RepoSelector } from './github-repo-target-params' + +export const RepoPath = z.object({ + path: requiredString('Missing repo path'), + kind: z.enum(['git', 'folder']).optional(), + displayName: OptionalString +}) + +export const RepoCreate = z.object({ + parentPath: requiredString('Missing parent path'), + name: requiredString('Missing repo name'), + kind: z.enum(['git', 'folder']).optional() +}) + +export const RepoClone = z.object({ + url: requiredString('Missing clone URL'), + destination: requiredString('Missing clone destination') +}) + +export const RepoSetBaseRef = z.object({ + repo: requiredString('Missing repo selector'), + ref: requiredString('Missing base ref') +}) + +export const RepoUpdate = createRepoUpdateSchema(RepoSelector.shape) + +export const RepoSearchRefs = z.object({ + repo: requiredString('Missing repo selector'), + query: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : undefined)) + .pipe(z.string({ message: 'Missing query' })), + limit: OptionalFiniteNumber +}) + +export const RepoReorder = z.object({ + orderedIds: z.array(z.string()) +}) + +export const ProjectGroupCreate = z.object({ + name: requiredString('Missing group name'), + parentPath: OptionalString, + connectionId: OptionalString.nullable().optional(), + parentGroupId: OptionalString.nullable().optional(), + createdFrom: z.enum(['manual', 'folder-scan', 'migration']).optional() +}) + +export const ProjectGroupUpdate = z.object({ + groupId: requiredString('Missing group id'), + updates: z.object({ + name: OptionalString, + isCollapsed: z.boolean().optional(), + tabOrder: OptionalFiniteNumber, + color: OptionalString.nullable().optional() + }) +}) + +export const ProjectGroupSelector = z.object({ + groupId: requiredString('Missing group id') +}) + +export const ProjectGroupMoveProject = z.object({ + repo: requiredString('Missing repo selector'), + groupId: OptionalString.nullable(), + order: OptionalFiniteNumber +}) + +export const ProjectGroupScanNested = z.object({ + path: requiredString('Missing folder path') +}) + +export const ProjectGroupImportNested = z.discriminatedUnion('mode', [ + z.object({ + parentPath: requiredString('Missing parent path'), + groupName: z.string().optional().default(''), + projectPaths: z.array(z.string()), + mode: z.literal('group') + }), + z.object({ + parentPath: requiredString('Missing parent path'), + // Why: blank group names fall back to the scanned folder basename; separate + // imports do not create a group but share the same renderer payload shape. + groupName: z.string().optional().default(''), + projectPaths: z.array(z.string()), + mode: z.literal('separate') + }) +]) + +export const RepoIssueCommandWrite = RepoSelector.extend({ + content: z.string() +}) + +export const RepoSparsePresetSave = RepoSelector.extend({ + id: OptionalString, + name: requiredString('Missing preset name'), + directories: z.array(z.string()) +}) diff --git a/src/shared/rpc-contract/repo-update-params.ts b/src/shared/rpc-contract/repo-update-params.ts new file mode 100644 index 00000000000..179bb1994dc --- /dev/null +++ b/src/shared/rpc-contract/repo-update-params.ts @@ -0,0 +1,77 @@ +import { z } from 'zod' +import { normalizeRepoSourceControlAiOverrides } from '../source-control-ai' +import { normalizeRepoBadgeColor } from '../repo-badge-color' +import { sanitizeRepoIcon } from '../repo-icon' +import { + normalizeCustomWorktreeVisibilitySources, + normalizeWorktreeVisibilitySourcePreferences +} from '../worktree/visibility-sources' +import { OptionalFiniteNumber, OptionalString } from './rpc-param-primitives' + +export const RepoSourceControlAiOverrides = z + .unknown() + .optional() + .transform((value) => + value === undefined + ? undefined + : value === null + ? null + : normalizeRepoSourceControlAiOverrides(value) + ) + +export const RepoBadgeColor = z + .unknown() + .optional() + .transform((value) => + value === undefined ? undefined : (normalizeRepoBadgeColor(value) ?? undefined) + ) + +export const RepoUpstream = z + .object({ + owner: z.string().min(1), + repo: z.string().min(1) + }) + .nullable() + .optional() + +// The return type is inferred on purpose: an explicit z.ZodObject<...z.ZodRawShape> +// annotation widened `updates` to an open record, which erased all 24 named fields +// from RpcParams<'repo.update'> for every typed caller. +export function createRepoUpdateSchema(selectorShape: T) { + return z.object({ + ...selectorShape, + updates: z.object({ + displayName: OptionalString, + badgeColor: RepoBadgeColor, + repoIcon: z + .unknown() + .transform((value) => sanitizeRepoIcon(value)) + .optional(), + upstream: RepoUpstream, + hookSettings: z.unknown().optional(), + worktreeBaseRef: OptionalString, + worktreeBasePath: OptionalString, + kind: z.enum(['git', 'folder']).optional(), + symlinkPaths: z.array(z.string()).optional(), + issueSourcePreference: z.enum(['auto', 'upstream', 'origin']).optional(), + forkSyncMode: z.enum(['ask', 'safe-auto', 'off']).optional(), + externalWorktreeVisibility: z.enum(['hide', 'show']).nullable().optional(), + externalWorktreeVisibilityPromptDismissedAt: z.number().finite().optional(), + externalWorktreeInboxBaselinePaths: z.array(z.string()).optional(), + importedExternalWorktreePaths: z.array(z.string()).optional(), + agentWorktreeVisibility: z.enum(['hide', 'show']).nullable().optional(), + customWorktreeVisibilitySources: z + .unknown() + .transform((value) => normalizeCustomWorktreeVisibilitySources(value)) + .optional(), + worktreeVisibilitySourcePreferences: z + .unknown() + .transform((value) => normalizeWorktreeVisibilitySourcePreferences(value)) + .optional(), + externalWorktreeDiscoverySuppressedAt: z.number().finite().nullable().optional(), + projectGroupId: OptionalString.nullable().optional(), + projectGroupOrder: OptionalFiniteNumber, + sourceControlAi: RepoSourceControlAiOverrides + }) + }) +} diff --git a/src/shared/rpc-contract/rpc-param-primitives.ts b/src/shared/rpc-contract/rpc-param-primitives.ts new file mode 100644 index 00000000000..a22efbd2765 --- /dev/null +++ b/src/shared/rpc-contract/rpc-param-primitives.ts @@ -0,0 +1,84 @@ +import { z } from 'zod' + +// Why: the original handlers treated non-numeric/NaN limit values as "no +// limit" rather than as errors. Preserve that forgiving behavior so CLI +// callers passing stringified numbers or Infinity still reach the runtime. +// The outer optional() is required for omitted keys in Zod v4; an optional +// schema hidden behind pipe() still makes z.object require the property. +export const OptionalFiniteNumber = z + .unknown() + .transform((value) => (typeof value === 'number' && Number.isFinite(value) ? value : undefined)) + .pipe(z.union([z.number(), z.undefined()])) + .optional() + +export const OptionalPositiveInt = z + .unknown() + .transform((value) => + typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined + ) + .pipe(z.union([z.number(), z.undefined()])) + .optional() + +export const OptionalString = z + .unknown() + .transform((value) => (typeof value === 'string' && value.length > 0 ? value : undefined)) + .pipe(z.union([z.string(), z.undefined()])) + .optional() + +export const OptionalPlainString = z + .unknown() + .transform((value) => (typeof value === 'string' ? value : undefined)) + .pipe(z.union([z.string(), z.undefined()])) + .optional() + +export const OptionalBoolean = z + .unknown() + .transform((value) => (typeof value === 'boolean' ? value : undefined)) + .pipe(z.union([z.boolean(), z.undefined()])) + .optional() + +// Why: runtime handlers accept `linkedIssue: number | null | undefined` with +// distinct meanings — undefined means "no update", null means "clear", number +// means "set". The ambient JSON decode produces all three shapes as-is. +export const TriStateLinkedIssue = z + .unknown() + .transform((value) => { + if (value === null) { + return null + } + if (typeof value === 'number' && Number.isFinite(value)) { + return value + } + return undefined + }) + .pipe(z.union([z.number(), z.null(), z.undefined()])) + .optional() + +// Why: the legacy extractBrowserTarget treated worktree as a plain-string +// passthrough (empty string preserved) but `page` as non-empty-string. The +// browser bridge uses worktree-as-empty-string to mean "any worktree", so +// keep that asymmetry intact to avoid widening scope unexpectedly. +export const BrowserTarget = z.object({ + worktree: OptionalPlainString, + page: OptionalString +}) + +export function requiredString(message: string) { + return z + .unknown() + .transform((value) => (typeof value === 'string' ? value : '')) + .pipe(z.string().min(1, message)) +} + +export function requiredStringAllowingEmpty(message: string) { + return z.unknown().refine((value): value is string => typeof value === 'string', { message }) +} + +export function requiredNumber(message: string) { + return z + .unknown() + .transform((value) => + typeof value === 'number' && Number.isFinite(value) ? value : Number.NaN + ) + .pipe(z.number().refine((v) => Number.isFinite(v), { message })) +} diff --git a/src/shared/rpc-contract/rpc-params-catalog.generated.ts b/src/shared/rpc-contract/rpc-params-catalog.generated.ts new file mode 100644 index 00000000000..57ed4a5b5a5 --- /dev/null +++ b/src/shared/rpc-contract/rpc-params-catalog.generated.ts @@ -0,0 +1,1169 @@ +// GENERATED by config/scripts/generate-rpc-params-catalog.mjs. Do not edit; +// run `pnpm run generate:rpc-params-catalog`. +import type { z } from 'zod' +import { AgentSkillShareRequestSchema } from '../agent-skill-sharing-contract' +import { + BrowserClientFileChannelAbortParams, + BrowserClientFileChannelReadParams, + BrowserClientFileChannelWriteParams +} from '../browser-client-file-channel-protocol' +import { + BrowserClientHostAttachParams, + BrowserClientHostCommandResultParams, + BrowserNetworkTunnelAttachParams +} from '../browser-client-host-protocol' +import { BrowserClientPageMetadataParams } from '../browser-client-page-metadata-protocol' +import { + PairingGetEndpointsParamsSchema, + PairingProvisionRelayParamsSchema +} from '../mobile-relay-credential-contract' +import { pluginConsentRequestSchema } from '../plugins/plugin-consent-request' +import { + AccountsUnsubscribeParams, + AddClaudeFromConfigDirParams, + AddCodexFromHomeParams, + ConsumeCodexResetCreditParams, + ListAccountsParams, + RemoveAccountParams, + SelectAccountParams, + SelectCodexAccountForTargetParams +} from './accounts-params' +import { PrepareCodexForWslPaneParams } from './agent-hooks-params' +import { CreateAgentSessionParams, EnsureAgentSessionParams } from './agent-session-params' +import { + AiVaultListSessionsParams, + AiVaultPrepareSessionResumeParams, + AiVaultSessionTitlesParams +} from './ai-vault-params' +import { ArtifactsDeleteParams, ListOptions, SourceRequest, WriteRequest } from './artifacts-params' +import { + AutomationCreate, + AutomationId, + AutomationList, + AutomationRuns, + AutomationUpdate +} from './automation-params' +import { CertificateProceed } from './browser-core-params' +import { MouseClick } from './browser-extras-params' +import { + Check, + ClipboardWrite, + CookieDelete, + CookieGet, + CookieSet, + DialogAccept, + Drag, + Element, + Eval, + Exec, + Fill, + Find, + FullScreenshot, + Geolocation, + Get, + Goto, + Highlight, + InterceptEnable, + Is, + KeyboardInsert, + Keypress, + LimitParam, + MouseButton, + MouseWheel, + MouseXY, + ProfileCreate, + ProfileDelete, + ProfileImportFromBrowser, + Screencast, + Screenshot, + Scroll, + Select, + SelectorPath, + SetCredentials, + SetDevice, + SetHeaders, + SetMedia, + SetOffline, + StorageKey, + StorageKeyValue, + TabClose, + TabCurrent, + TabList, + TabProfileClone, + TabSetProfile, + TabShow, + TabSwitch, + Type, + Upload, + Viewport, + Wait +} from './browser-params' +import { ScreencastUnsubscribe } from './browser-screencast-params' +import { BrowserOpenUrlParams, BrowserTabCreateParams } from './browser-tab-create-params' +import { ClientEventsUnsubscribeParams } from './client-events-params' +import { + NativeChatSessionOptionsMutation, + PRBotAuthorOverrideUpdate, + SettingsUpdate +} from './client-settings-params' +import { FeatureInteractionIdParam, UiUpdate } from './client-ui-params' +import { + AbortImageUpload, + AppendImageUploadChunk, + CommitImageUpload, + SaveImageAsTempFile, + StartImageUpload +} from './clipboard-params' +import { ComputerCapabilitiesParams, ComputerPermissionsStatusParams } from './computer-params' +import { + Click, + ComputerObserveTarget, + ComputerPermissions, + Drag as DragOfComputerSchemasParams, + Hotkey, + ListApps, + ListWindows, + PasteText, + PerformSecondaryAction, + PressKey, + Scroll as ScrollOfComputerSchemasParams, + SetValue, + TypeText +} from './computer-schemas-params' +import { + AttachParams as AttachParamsOfEmulatorParams, + AxParams, + ButtonParams, + EmulatorAvailabilityParams, + EmulatorListDevicesParams, + EmulatorListSimulatorsParams, + EmulatorUnregisterActiveParams, + ExecParams, + GestureParams, + KillParams, + LaunchParams, + ListParams, + LogcatParams, + PermissionsParams, + RotateParams, + ShutdownParams, + TapParams, + TypeParams +} from './emulator-params' +import { + FileCommitUpload, + FileCopy, + FileDelete, + FileMutationOpen, + FileRename, + FileWrite, + FileWriteBase64, + FileWriteBase64Chunk +} from './files-mutation-params' +import { + DocPreviewFileRead, + FileListAll, + FileOpenDiff, + FilePathSearch, + FileReadChunk, + FileSearch, + FileTreePath, + FileUnwatch, + ResolveTerminalPath, + ServerDirectoryBrowse +} from './files-params' +import { FileOpen, WorktreeSelector } from './files-target-params' +import { TerminalArtifactFile, TerminalArtifactFileWrite } from './files-terminal-artifact-params' +import { + FolderWorkspaceCreate, + FolderWorkspacePathStatus, + FolderWorkspaceSelector, + FolderWorkspaceUpdate +} from './folder-workspace-params' +import { + GitBranchCompare, + GitBranchDiff, + GitBulkPaths, + GitCheckIgnored, + GitCheckout, + GitCommit, + GitCommitCompare, + GitCommitDiff, + GitDiff, + GitDiscoverCommitMessageModels, + GitFilePath, + GitForkSync, + GitGenerateCommitMessage, + GitGeneratePullRequestFields, + GitHistory, + GitPush, + GitRebaseFromBase, + GitRemoteCommitUrl, + GitRemoteFileUrl, + GitStatusParams, + GitSubmoduleStatus, + GitTargetedRemote, + WorktreeSelector as WorktreeSelectorOfGitParams +} from './git-params' +import { CreateIssue, Issue, IssueComment, UpdateIssue } from './github-issue-params' +import { + ClearProjectItemField, + GithubProjectListAccessibleParams, + ProjectItemField, + ProjectRef, + ProjectViewTable, + ProjectViews, + ProjectWorkItemDetailsBySlug, + SlugAssignableUsers, + SlugIssueComment, + SlugIssueCommentDelete, + SlugIssueCommentEdit, + SlugIssueTypeUpdate, + SlugIssueUpdate, + SlugPullRequestUpdate +} from './github-project-params' +import { + PRCommentReaction, + PrForBranch, + PullRequest, + PullRequestCheckDetails, + PullRequestChecks, + PullRequestFileContents, + PullRequestFileViewed, + RerunPullRequestChecks, + ReviewThread +} from './github-pull-request-params' +import { + MarkPrReadyForReview, + MergePr, + PRReviewComment, + PRReviewCommentReply, + RemovePrReviewers, + RequestPrReviewers, + SetPrAutoMerge, + UpdatePr, + UpdatePrState, + UpdatePrTitle +} from './github-pull-request-update-params' +import { RepoSelector, SlugRepo } from './github-repo-target-params' +import { + IssuesList, + RateLimit, + WorkItem, + WorkItemByOwnerRepo, + WorkItemsCount, + WorkItemsList +} from './github-repo-work-item-params' +import { + AddIssueComment, + AddMRComment, + AddMRInlineComment, + CreateIssue as CreateIssueOfGitlabParams, + EmptyParams, + GitLabRateLimit, + IssuesList as IssuesListOfGitlabParams, + JobTrace, + MergeMr, + RepoSelector as RepoSelectorOfGitlabParams, + ResolveMRDiscussion, + RetryJob, + UpdateIssue as UpdateIssueOfGitlabParams, + UpdateMr, + UpdateMrReviewers, + UpdateMrState, + WorkItemByPath, + WorkItemDetails, + WorkItemsList as WorkItemsListOfGitlabParams +} from './gitlab-params' +import { + HostedReviewCreate, + HostedReviewCreationEligibility, + HostedReviewForBranch +} from './hosted-review-params' +import { + AssignableUsers, + Connect, + CreateIssue as CreateIssueOfJiraParams, + IssueComment as IssueCommentOfJiraParams, + IssueKey, + IssueUpdate, + ListIssues, + ProjectIssueTypeFields, + ProjectIssueTypes, + ProjectStatusOrder, + SearchIssues, + SelectSite, + SiteSelection, + UserSearch +} from './jira-params' +import { + AgentIssueContext, + AgentSearchIssues, + LinearCurrentContext, + LinearIssueAddComment, + LinearIssueAttachLink, + LinearIssueCreate, + LinearIssueList, + LinearIssueRelationWrite, + LinearIssueSetState, + LinearIssueUpdateTask, + LinearProjectList, + LinearSaveIssue, + LinearTeamLookup, + LinearWorkspaceRead +} from './linear-agent-access-params' +import { + ListIssues as ListIssuesOfLinearIssueListParams, + McpListIssues +} from './linear-issue-list-params' +import { + Connect as ConnectOfLinearParams, + CreateIssue as CreateIssueOfLinearParams, + CustomViewContents, + CustomViewId, + IssueComment as IssueCommentOfLinearParams, + IssueId, + IssueUpdate as IssueUpdateOfLinearParams, + LinearIssueCommentsParams, + ListCustomViews, + ListProjects, + ProjectId, + ProjectIssues, + SearchIssues as SearchIssuesOfLinearParams, + SelectWorkspace, + TeamId, + WorkspaceSelection +} from './linear-params' +import { CreateProject } from './linear-project-create-params' +import { NativeChatSession, NativeChatUnsubscribe } from './native-chat-params' +import { + NotificationGetMissedSinceParams, + NotificationRegisterPushParams, + NotificationUnsubscribeParams, + NotificationsSubscribeParams +} from './notifications-params' +import { + FederationDispatchParams, + FederationFleetSnapshotParams, + FederationOutputReadParams, + FederationReadParams +} from './orchestration-federation-control-params' +import { + FederationAckParams, + FederationImportParams, + FederationPullParams +} from './orchestration-federation-relay-params' +import { FederationAttachStartParams } from './orchestration-federation-start-params' +import { + GateCreateParams, + GateListParams, + GateResolveParams, + RunParams, + RunStopParams +} from './orchestration-gates-params' +import { + AskParams, + CheckParams, + DispatchParams, + DispatchShowParams, + InboxParams, + ReplyParams, + ResetParams, + TaskCreateParams, + TaskListParams +} from './orchestration-params' +import { RequestShowParams } from './orchestration-runs-mutation-request-show-params' +import { + RunCreateParams, + RunCurrentParams, + RunListParams, + RunShowParams, + RunUseParams +} from './orchestration-runs-params' +import { WorkerDispatchParams, WorkerReadParams } from './orchestration-worker-control-params' +import { OrchestrationWorkerTerminalUserInputParams } from './orchestration-worker-release-params' +import { + WorkerDispatchParams as WorkerDispatchParamsOfOrchestrationWorkerReleaseSchemasParams, + WorkerListParams, + WorkerRetainParams +} from './orchestration-worker-release-schemas-params' +import { WorkerStartParams } from './orchestration-worker-start-params' +import { WorkerDispatchParams as WorkerDispatchParamsOfOrchestrationWorkerStopParams } from './orchestration-worker-stop-params' +import { + PluginInvokeCommandParams, + PluginReadPanelEntryParams, + PluginSetEnabledParams, + PluginsPanelActionParams +} from './plugins-params' +import { + PreflightCheck, + PreflightDetectRemoteAgents, + PreflightDetectRemoteWindowsTerminalCapabilities +} from './preflight-params' +import { + ProjectHostSetupClone, + ProjectHostSetupCreate, + ProjectHostSetupDelete, + ProjectHostSetupExistingFolder, + ProjectHostSetupUpdate, + ProjectUpdate +} from './project-runtime-params' +import { + ProjectGroupCreate, + ProjectGroupImportNested, + ProjectGroupMoveProject, + ProjectGroupScanNested, + ProjectGroupSelector, + ProjectGroupUpdate, + RepoClone, + RepoCreate, + RepoIssueCommandWrite, + RepoPath, + RepoReorder, + RepoSearchRefs, + RepoSetBaseRef, + RepoSparsePresetSave, + RepoUpdate +} from './repo-params' +import { BrowserTarget } from './rpc-param-primitives' +import { ClientCapabilitiesUpdate } from './runtime-client-capabilities-params' +import { SessionTabsUnsubscribeAllParams } from './session-tabs-params' +import { + ActivateTab, + CloseLifecycleTab, + CloseTab, + CreateTerminalTab, + MoveTab, + SaveMarkdownTab, + SessionTabsUnsubscribe, + SetTabProps, + UpdatePaneLayout, + WorktreeTabSelector +} from './session-tabs-schemas-params' +import { + SkillsCancelInstallParams, + SkillsDiscoverParams, + SkillsGetInstallProgressParams +} from './skills-params' +import { + DictationChunk, + DictationHandle, + DictationSetup, + DictationStart, + SpeechModelAction +} from './speech-params' +import { SshTarget } from './ssh-params' +import { + AttachParams, + CancelParams, + ConversationCommandParams, + CreateParams, + CreateSupportParams, + HandoffParams, + HandoffStatusParams, + HistoryParams, + HoldParams, + OptionsParams, + RespondParams, + RewindParams, + SendParams, + SetOptionParams, + SubscribeParams, + UnsubscribeParams +} from './structured-agent-session-params' +import { TerminalAdoptOrphans } from './terminal-orphan-params' +import { TerminalQuickCommandsUpdate } from './terminal-quick-command-params' +import { + TerminalMultiplex, + TerminalResizeForClient, + TerminalSubscribe +} from './terminal-stream-params' +import { + AgentTeamsPrepareLaunch, + AgentTeamsTmuxCompat, + TerminalCloseAll, + TerminalCreateParams, + TerminalFocus, + TerminalHandle, + TerminalInspectProcess, + TerminalListParams, + TerminalRead, + TerminalRecoverPane, + TerminalRename, + TerminalResolveActive, + TerminalResolvePane, + TerminalSend, + TerminalSplit, + TerminalStopExact, + TerminalWait +} from './terminal-unary-params' +import { TerminalGetAutoRestoreFitParams } from './terminal-viewport-methods-params' +import { + TerminalSetAutoRestoreFit, + TerminalSetDisplayMode, + TerminalUnsubscribe, + TerminalUpdateViewport +} from './terminal-viewport-schemas-params' +import { UpdaterCheckParams } from './updater-params' +import { WorkspacePortKillParams, WorkspacePortScanParams } from './workspace-ports-params' +import { WorktreeCreate, WorktreePrefetchCreateBase } from './worktree-create-params' +import { + WorktreeActivate, + WorktreeDetectedListParams, + WorktreeForceDeleteBranch, + WorktreeListParams, + WorktreePsParams, + WorktreeRemove, + WorktreeResolveMrBase, + WorktreeResolvePrBase, + WorktreeSelector as WorktreeSelectorOfWorktreeParams, + WorktreeSet, + WorktreeSortOrder, + WorktreeTeardownMissingTerminalsParams +} from './worktree-params' +import { SkillBundleInstallRequestSchema } from '../skill-bundle-install-contract' +import { SkillDeleteRequestSchema } from '../skill-delete-contract' +import { + SkillInstallPreviewRequestSchema, + SkillInstallRequestSchema, + SkillRemoveRequestSchema +} from '../skill-install-contract' +import { + SkillUploadBeginRequestSchema, + SkillUploadChunkRequestSchema, + SkillUploadCommitRequestSchema +} from '../skill-upload-session-contract' + +// Why: the host parses params with these schemas, so a client that matches this map +// matches the dispatcher. Clients must import it for types only — parsing a params +// schema client-side runs the coercing transforms and rewrites the wire bytes. +export const RPC_PARAMS_BY_METHOD = { + 'accounts.addClaudeFromConfigDir': AddClaudeFromConfigDirParams, + 'accounts.addCodexFromHome': AddCodexFromHomeParams, + 'accounts.consumeCodexResetCredit': ConsumeCodexResetCreditParams, + 'accounts.list': ListAccountsParams, + 'accounts.removeClaude': RemoveAccountParams, + 'accounts.removeCodex': RemoveAccountParams, + 'accounts.selectClaude': SelectAccountParams, + 'accounts.selectCodex': SelectAccountParams, + 'accounts.selectCodexForTarget': SelectCodexAccountForTargetParams, + 'accounts.subscribe': null, + 'accounts.unsubscribe': AccountsUnsubscribeParams, + 'agentHooks.prepareCodexForWslPane': PrepareCodexForWslPaneParams, + 'agentSession.cancel': CancelParams, + 'agentSession.close': OptionsParams, + 'agentSession.commands': OptionsParams, + 'agentSession.conversationCommand': ConversationCommandParams, + 'agentSession.create': CreateParams, + 'agentSession.createSupport': CreateSupportParams, + 'agentSession.ensure': AttachParams, + 'agentSession.handoffStatus': HandoffStatusParams, + 'agentSession.history': HistoryParams, + 'agentSession.hold': HoldParams, + 'agentSession.options': OptionsParams, + 'agentSession.release': HoldParams, + 'agentSession.requestHandoff': HandoffParams, + 'agentSession.respondToApproval': RespondParams, + 'agentSession.respondToQuestion': RespondParams, + 'agentSession.reveal': OptionsParams, + 'agentSession.rewind': RewindParams, + 'agentSession.send': SendParams, + 'agentSession.setOption': SetOptionParams, + 'agentSession.subscribe': SubscribeParams, + 'agentSession.subscribeStatus': null, + 'agentSession.unsubscribe': UnsubscribeParams, + 'agentTeams.prepareLaunch': AgentTeamsPrepareLaunch, + 'agentTeams.tmuxCompat': AgentTeamsTmuxCompat, + 'aiVault.listSessions': AiVaultListSessionsParams, + 'aiVault.prepareSessionResume': AiVaultPrepareSessionResumeParams, + 'aiVault.resolveSessionTitles': AiVaultSessionTitlesParams, + 'artifacts.delete': ArtifactsDeleteParams, + 'artifacts.getPublishedLink': SourceRequest, + 'artifacts.list': ListOptions, + 'artifacts.publish': WriteRequest, + 'artifacts.share': WriteRequest, + 'artifacts.unshare': SourceRequest, + 'artifacts.update': WriteRequest, + 'automation.create': AutomationCreate, + 'automation.delete': AutomationId, + 'automation.list': AutomationList, + 'automation.runNow': AutomationId, + 'automation.runs': AutomationRuns, + 'automation.show': AutomationId, + 'automation.update': AutomationUpdate, + 'browser.back': BrowserTarget, + 'browser.capture.start': BrowserTarget, + 'browser.capture.stop': BrowserTarget, + 'browser.certificate.proceed': CertificateProceed, + 'browser.check': Check, + 'browser.clear': Element, + 'browser.click': Element, + 'browser.clientHost.attach': BrowserClientHostAttachParams, + 'browser.clientHost.commandResult': BrowserClientHostCommandResultParams, + 'browser.clientHost.fileChannel.abort': BrowserClientFileChannelAbortParams, + 'browser.clientHost.fileChannel.read': BrowserClientFileChannelReadParams, + 'browser.clientHost.fileChannel.write': BrowserClientFileChannelWriteParams, + 'browser.clientHost.pageMetadata': BrowserClientPageMetadataParams, + 'browser.clipboardRead': BrowserTarget, + 'browser.clipboardWrite': ClipboardWrite, + 'browser.console': LimitParam, + 'browser.cookie.delete': CookieDelete, + 'browser.cookie.get': CookieGet, + 'browser.cookie.set': CookieSet, + 'browser.dblclick': Element, + 'browser.dialogAccept': DialogAccept, + 'browser.dialogDismiss': BrowserTarget, + 'browser.download': SelectorPath, + 'browser.drag': Drag, + 'browser.eval': Eval, + 'browser.exec': Exec, + 'browser.fill': Fill, + 'browser.find': Find, + 'browser.focus': Element, + 'browser.forward': BrowserTarget, + 'browser.fullScreenshot': FullScreenshot, + 'browser.geolocation': Geolocation, + 'browser.get': Get, + 'browser.goto': Goto, + 'browser.highlight': Highlight, + 'browser.hover': Element, + 'browser.intercept.disable': BrowserTarget, + 'browser.intercept.enable': InterceptEnable, + 'browser.intercept.list': BrowserTarget, + 'browser.is': Is, + 'browser.keyboardInsertText': KeyboardInsert, + 'browser.keypress': Keypress, + 'browser.mouseClick': MouseClick, + 'browser.mouseDown': MouseButton, + 'browser.mouseMove': MouseXY, + 'browser.mouseUp': MouseButton, + 'browser.mouseWheel': MouseWheel, + 'browser.network': LimitParam, + 'browser.openUrl': BrowserOpenUrlParams, + 'browser.pdf': BrowserTarget, + 'browser.profileClearDefaultCookies': null, + 'browser.profileCreate': ProfileCreate, + 'browser.profileDelete': ProfileDelete, + 'browser.profileDetectBrowsers': null, + 'browser.profileImportFromBrowser': ProfileImportFromBrowser, + 'browser.profileList': null, + 'browser.reload': BrowserTarget, + 'browser.screencast': Screencast, + 'browser.screencast.unsubscribe': ScreencastUnsubscribe, + 'browser.screenshot': Screenshot, + 'browser.scroll': Scroll, + 'browser.scrollIntoView': Element, + 'browser.select': Select, + 'browser.selectAll': Element, + 'browser.setCredentials': SetCredentials, + 'browser.setDevice': SetDevice, + 'browser.setHeaders': SetHeaders, + 'browser.setMedia': SetMedia, + 'browser.setOffline': SetOffline, + 'browser.snapshot': BrowserTarget, + 'browser.storage.local.clear': BrowserTarget, + 'browser.storage.local.get': StorageKey, + 'browser.storage.local.set': StorageKeyValue, + 'browser.storage.session.clear': BrowserTarget, + 'browser.storage.session.get': StorageKey, + 'browser.storage.session.set': StorageKeyValue, + 'browser.tabClose': TabClose, + 'browser.tabCreate': BrowserTabCreateParams, + 'browser.tabCurrent': TabCurrent, + 'browser.tabList': TabList, + 'browser.tabProfileClone': TabProfileClone, + 'browser.tabProfileShow': TabShow, + 'browser.tabSetProfile': TabSetProfile, + 'browser.tabShow': TabShow, + 'browser.tabSwitch': TabSwitch, + 'browser.type': Type, + 'browser.upload': Upload, + 'browser.viewport': Viewport, + 'browser.wait': Wait, + 'clipboard.abortImageUpload': AbortImageUpload, + 'clipboard.appendImageUploadChunk': AppendImageUploadChunk, + 'clipboard.commitImageUpload': CommitImageUpload, + 'clipboard.saveImageAsTempFile': SaveImageAsTempFile, + 'clipboard.startImageUpload': StartImageUpload, + 'computer.capabilities': ComputerCapabilitiesParams, + 'computer.click': Click, + 'computer.drag': DragOfComputerSchemasParams, + 'computer.getAppState': ComputerObserveTarget, + 'computer.hotkey': Hotkey, + 'computer.listApps': ListApps, + 'computer.listWindows': ListWindows, + 'computer.pasteText': PasteText, + 'computer.performSecondaryAction': PerformSecondaryAction, + 'computer.permissions': ComputerPermissions, + 'computer.permissionsStatus': ComputerPermissionsStatusParams, + 'computer.pressKey': PressKey, + 'computer.scroll': ScrollOfComputerSchemasParams, + 'computer.setValue': SetValue, + 'computer.typeText': TypeText, + 'diagnostics.memory': null, + 'emulator.attach': AttachParamsOfEmulatorParams, + 'emulator.availability': EmulatorAvailabilityParams, + 'emulator.ax': AxParams, + 'emulator.button': ButtonParams, + 'emulator.exec': ExecParams, + 'emulator.gesture': GestureParams, + 'emulator.kill': KillParams, + 'emulator.launch': LaunchParams, + 'emulator.list': ListParams, + 'emulator.listDevices': EmulatorListDevicesParams, + 'emulator.listSimulators': EmulatorListSimulatorsParams, + 'emulator.logcat': LogcatParams, + 'emulator.permissions': PermissionsParams, + 'emulator.rotate': RotateParams, + 'emulator.shutdown': ShutdownParams, + 'emulator.tap': TapParams, + 'emulator.type': TypeParams, + 'emulator.unregisterActive': EmulatorUnregisterActiveParams, + 'files.browseServerDir': ServerDirectoryBrowse, + 'files.commitUpload': FileCommitUpload, + 'files.copy': FileCopy, + 'files.createDir': FileMutationOpen, + 'files.createDirNoClobber': FileMutationOpen, + 'files.createFile': FileMutationOpen, + 'files.delete': FileDelete, + 'files.list': WorktreeSelector, + 'files.listAll': FileListAll, + 'files.listMarkdownDocuments': WorktreeSelector, + 'files.open': FileOpen, + 'files.openDiff': FileOpenDiff, + 'files.read': FileOpen, + 'files.readChunk': FileReadChunk, + 'files.readDir': FileTreePath, + 'files.readDocPreview': DocPreviewFileRead, + 'files.readPreview': FileOpen, + 'files.readTerminalArtifact': TerminalArtifactFile, + 'files.readTerminalArtifactPreview': TerminalArtifactFile, + 'files.rename': FileRename, + 'files.resolveTerminalPath': ResolveTerminalPath, + 'files.search': FileSearch, + 'files.searchPaths': FilePathSearch, + 'files.stat': FileTreePath, + 'files.unwatch': FileUnwatch, + 'files.watch': WorktreeSelector, + 'files.write': FileWrite, + 'files.writeBase64': FileWriteBase64, + 'files.writeBase64Chunk': FileWriteBase64Chunk, + 'files.writeTerminalArtifact': TerminalArtifactFileWrite, + 'folderWorkspace.create': FolderWorkspaceCreate, + 'folderWorkspace.delete': FolderWorkspaceSelector, + 'folderWorkspace.getPathStatus': FolderWorkspacePathStatus, + 'folderWorkspace.list': null, + 'folderWorkspace.update': FolderWorkspaceUpdate, + 'git.abortMerge': WorktreeSelectorOfGitParams, + 'git.abortRebase': WorktreeSelectorOfGitParams, + 'git.branchCompare': GitBranchCompare, + 'git.branchDiff': GitBranchDiff, + 'git.bulkDiscard': GitBulkPaths, + 'git.bulkStage': GitBulkPaths, + 'git.bulkUnstage': GitBulkPaths, + 'git.cancelGenerateCommitMessage': WorktreeSelectorOfGitParams, + 'git.cancelGeneratePullRequestFields': WorktreeSelectorOfGitParams, + 'git.checkIgnored': GitCheckIgnored, + 'git.checkout': GitCheckout, + 'git.commit': GitCommit, + 'git.commitCompare': GitCommitCompare, + 'git.commitDiff': GitCommitDiff, + 'git.conflictOperation': WorktreeSelectorOfGitParams, + 'git.diff': GitDiff, + 'git.discard': GitFilePath, + 'git.discoverCommitMessageModels': GitDiscoverCommitMessageModels, + 'git.fastForward': GitTargetedRemote, + 'git.fetch': GitTargetedRemote, + 'git.forkSync': GitForkSync, + 'git.generateCommitMessage': GitGenerateCommitMessage, + 'git.generatePullRequestFields': GitGeneratePullRequestFields, + 'git.history': GitHistory, + 'git.localBranches': WorktreeSelectorOfGitParams, + 'git.pull': GitTargetedRemote, + 'git.push': GitPush, + 'git.rebaseFromBase': GitRebaseFromBase, + 'git.remoteCommitUrl': GitRemoteCommitUrl, + 'git.remoteFileUrl': GitRemoteFileUrl, + 'git.stage': GitFilePath, + 'git.status': GitStatusParams, + 'git.submoduleStatus': GitSubmoduleStatus, + 'git.unstage': GitFilePath, + 'git.upstreamStatus': GitTargetedRemote, + 'github.addIssueComment': IssueComment, + 'github.addPRReviewComment': PRReviewComment, + 'github.addPRReviewCommentReply': PRReviewCommentReply, + 'github.countWorkItems': WorkItemsCount, + 'github.createIssue': CreateIssue, + 'github.issue': Issue, + 'github.listAssignableUsers': RepoSelector, + 'github.listIssues': IssuesList, + 'github.listLabels': RepoSelector, + 'github.listWorkItems': WorkItemsList, + 'github.markPRReadyForReview': MarkPrReadyForReview, + 'github.mergePR': MergePr, + 'github.prCheckDetails': PullRequestCheckDetails, + 'github.prChecks': PullRequestChecks, + 'github.prComments': PullRequest, + 'github.prFileContents': PullRequestFileContents, + 'github.prForBranch': PrForBranch, + 'github.project.addIssueCommentBySlug': SlugIssueComment, + 'github.project.clearItemField': ClearProjectItemField, + 'github.project.deleteIssueCommentBySlug': SlugIssueCommentDelete, + 'github.project.listAccessible': GithubProjectListAccessibleParams, + 'github.project.listAssignableUsersBySlug': SlugAssignableUsers, + 'github.project.listIssueTypesBySlug': SlugRepo, + 'github.project.listLabelsBySlug': SlugRepo, + 'github.project.listViews': ProjectViews, + 'github.project.resolveRef': ProjectRef, + 'github.project.updateIssueBySlug': SlugIssueUpdate, + 'github.project.updateIssueCommentBySlug': SlugIssueCommentEdit, + 'github.project.updateIssueTypeBySlug': SlugIssueTypeUpdate, + 'github.project.updateItemField': ProjectItemField, + 'github.project.updatePullRequestBySlug': SlugPullRequestUpdate, + 'github.project.viewTable': ProjectViewTable, + 'github.project.workItemDetailsBySlug': ProjectWorkItemDetailsBySlug, + 'github.rateLimit': RateLimit, + 'github.removePRReviewers': RemovePrReviewers, + 'github.repoSlug': RepoSelector, + 'github.repoUpstream': RepoSelector, + 'github.requestPRReviewers': RequestPrReviewers, + 'github.rerunPRChecks': RerunPullRequestChecks, + 'github.resolveReviewThread': ReviewThread, + 'github.setPRAutoMerge': SetPrAutoMerge, + 'github.setPRCommentReaction': PRCommentReaction, + 'github.setPRFileViewed': PullRequestFileViewed, + 'github.updateIssue': UpdateIssue, + 'github.updatePR': UpdatePr, + 'github.updatePRState': UpdatePrState, + 'github.updatePRTitle': UpdatePrTitle, + 'github.workItem': WorkItem, + 'github.workItemByOwnerRepo': WorkItemByOwnerRepo, + 'github.workItemDetails': WorkItem, + 'gitlab.addIssueComment': AddIssueComment, + 'gitlab.addMRComment': AddMRComment, + 'gitlab.addMRInlineComment': AddMRInlineComment, + 'gitlab.createIssue': CreateIssueOfGitlabParams, + 'gitlab.diagnoseAuth': EmptyParams, + 'gitlab.jobTrace': JobTrace, + 'gitlab.listIssues': IssuesListOfGitlabParams, + 'gitlab.listLabels': RepoSelectorOfGitlabParams, + 'gitlab.listMRs': WorkItemsListOfGitlabParams, + 'gitlab.listWorkItems': WorkItemsListOfGitlabParams, + 'gitlab.mergeMR': MergeMr, + 'gitlab.rateLimit': GitLabRateLimit, + 'gitlab.resolveMRDiscussion': ResolveMRDiscussion, + 'gitlab.retryJob': RetryJob, + 'gitlab.todos': RepoSelectorOfGitlabParams, + 'gitlab.updateIssue': UpdateIssueOfGitlabParams, + 'gitlab.updateMR': UpdateMr, + 'gitlab.updateMRReviewers': UpdateMrReviewers, + 'gitlab.updateMRState': UpdateMrState, + 'gitlab.workItemByPath': WorkItemByPath, + 'gitlab.workItemDetails': WorkItemDetails, + 'host.gitBash.isAvailable': null, + 'host.platform': null, + 'host.pwsh.isAvailable': null, + 'host.wsl.isAvailable': null, + 'host.wsl.listDistros': null, + 'hostedReview.create': HostedReviewCreate, + 'hostedReview.createStacked': HostedReviewCreate, + 'hostedReview.forBranch': HostedReviewForBranch, + 'hostedReview.getCreationEligibility': HostedReviewCreationEligibility, + 'jira.addIssueComment': IssueCommentOfJiraParams, + 'jira.connect': Connect, + 'jira.createIssue': CreateIssueOfJiraParams, + 'jira.disconnect': SiteSelection, + 'jira.getIssue': IssueKey, + 'jira.getIssueStream': IssueKey, + 'jira.getProjectStatusOrder': ProjectStatusOrder, + 'jira.issueComments': IssueKey, + 'jira.issueCommentsStream': IssueKey, + 'jira.listAssignableUsers': AssignableUsers, + 'jira.listCreateFields': ProjectIssueTypeFields, + 'jira.listIssueTypes': ProjectIssueTypes, + 'jira.listIssues': ListIssues, + 'jira.listPriorities': SiteSelection, + 'jira.listProjects': SiteSelection, + 'jira.listTransitions': IssueKey, + 'jira.lookupIssueSummary': IssueKey, + 'jira.readStatus': null, + 'jira.searchIssues': SearchIssues, + 'jira.searchUsers': UserSearch, + 'jira.selectSite': SelectSite, + 'jira.status': null, + 'jira.testConnection': SiteSelection, + 'jira.updateIssue': IssueUpdate, + 'linear.addIssueComment': IssueCommentOfLinearParams, + 'linear.agentIssueList': LinearIssueList, + 'linear.agentProjectList': LinearProjectList, + 'linear.agentSearchIssues': AgentSearchIssues, + 'linear.agentTeamLabels': LinearTeamLookup, + 'linear.agentTeamList': LinearWorkspaceRead, + 'linear.agentTeamMembers': LinearTeamLookup, + 'linear.agentTeamStates': LinearTeamLookup, + 'linear.connect': ConnectOfLinearParams, + 'linear.createIssue': CreateIssueOfLinearParams, + 'linear.createProject': CreateProject, + 'linear.disconnect': WorkspaceSelection, + 'linear.getCustomView': CustomViewId, + 'linear.getIssue': IssueId, + 'linear.getProject': ProjectId, + 'linear.issueAddComment': LinearIssueAddComment, + 'linear.issueAttachLink': LinearIssueAttachLink, + 'linear.issueComments': LinearIssueCommentsParams, + 'linear.issueContext': AgentIssueContext, + 'linear.issueCreate': LinearIssueCreate, + 'linear.issueRelationWrite': LinearIssueRelationWrite, + 'linear.issueSetState': LinearIssueSetState, + 'linear.issueUpdateTask': LinearIssueUpdateTask, + 'linear.listCustomViewIssues': CustomViewContents, + 'linear.listCustomViewProjects': CustomViewContents, + 'linear.listCustomViews': ListCustomViews, + 'linear.listIssues': ListIssuesOfLinearIssueListParams, + 'linear.listProjectIssues': ProjectIssues, + 'linear.listProjects': ListProjects, + 'linear.listTeams': WorkspaceSelection, + 'linear.mcpListIssues': McpListIssues, + 'linear.resolveCurrentIssue': LinearCurrentContext, + 'linear.saveIssue': LinearSaveIssue, + 'linear.searchIssues': SearchIssuesOfLinearParams, + 'linear.selectWorkspace': SelectWorkspace, + 'linear.status': null, + 'linear.teamLabels': TeamId, + 'linear.teamMembers': TeamId, + 'linear.teamStates': TeamId, + 'linear.testConnection': WorkspaceSelection, + 'linear.updateIssue': IssueUpdateOfLinearParams, + 'markdown.readTab': ActivateTab, + 'markdown.saveTab': SaveMarkdownTab, + 'nativeChat.readSession': NativeChatSession, + 'nativeChat.subscribe': NativeChatSession, + 'nativeChat.unsubscribe': NativeChatUnsubscribe, + 'network.browserTunnel': BrowserNetworkTunnelAttachParams, + 'notifications.getMissedSince': NotificationGetMissedSinceParams, + 'notifications.registerPush': NotificationRegisterPushParams, + 'notifications.subscribe': NotificationsSubscribeParams, + 'notifications.testPush': null, + 'notifications.unregisterPush': null, + 'notifications.unsubscribe': NotificationUnsubscribeParams, + 'orchestration.ask': AskParams, + 'orchestration.check': CheckParams, + 'orchestration.dispatch': DispatchParams, + 'orchestration.dispatchShow': DispatchShowParams, + 'orchestration.federationAck': FederationAckParams, + 'orchestration.federationAttachStart': FederationAttachStartParams, + 'orchestration.federationFleetSnapshot': FederationFleetSnapshotParams, + 'orchestration.federationImport': FederationImportParams, + 'orchestration.federationPull': FederationPullParams, + 'orchestration.federationRead': FederationReadParams, + 'orchestration.federationReadOutput': FederationOutputReadParams, + 'orchestration.federationRelease': FederationDispatchParams, + 'orchestration.federationShow': FederationDispatchParams, + 'orchestration.federationStop': FederationDispatchParams, + 'orchestration.gateCreate': GateCreateParams, + 'orchestration.gateList': GateListParams, + 'orchestration.gateResolve': GateResolveParams, + 'orchestration.inbox': InboxParams, + 'orchestration.reply': ReplyParams, + 'orchestration.requestShow': RequestShowParams, + 'orchestration.reset': ResetParams, + 'orchestration.run': RunParams, + 'orchestration.runCreate': RunCreateParams, + 'orchestration.runCurrent': RunCurrentParams, + 'orchestration.runList': RunListParams, + 'orchestration.runShow': RunShowParams, + 'orchestration.runStop': RunStopParams, + 'orchestration.runUse': RunUseParams, + 'orchestration.taskCreate': TaskCreateParams, + 'orchestration.taskList': TaskListParams, + 'orchestration.workerAbandon': WorkerDispatchParams, + 'orchestration.workerList': WorkerListParams, + 'orchestration.workerRead': WorkerReadParams, + 'orchestration.workerRelease': WorkerDispatchParamsOfOrchestrationWorkerReleaseSchemasParams, + 'orchestration.workerRetain': WorkerRetainParams, + 'orchestration.workerShow': WorkerDispatchParams, + 'orchestration.workerStart': WorkerStartParams, + 'orchestration.workerStop': WorkerDispatchParamsOfOrchestrationWorkerStopParams, + 'orchestration.workerTerminalUserInput': OrchestrationWorkerTerminalUserInputParams, + 'pairing.getEndpoints': PairingGetEndpointsParamsSchema, + 'pairing.provisionRelay': PairingProvisionRelayParamsSchema, + 'plugins.consent': pluginConsentRequestSchema, + 'plugins.invokeCommand': PluginInvokeCommandParams, + 'plugins.list': null, + 'plugins.panelAction': PluginsPanelActionParams, + 'plugins.readPanelEntry': PluginReadPanelEntryParams, + 'plugins.setEnabled': PluginSetEnabledParams, + 'preflight.check': PreflightCheck, + 'preflight.detectAgents': null, + 'preflight.detectRemoteAgents': PreflightDetectRemoteAgents, + 'preflight.detectRemoteWindowsTerminalCapabilities': + PreflightDetectRemoteWindowsTerminalCapabilities, + 'preflight.refreshAgents': null, + 'project.list': null, + 'project.update': ProjectUpdate, + 'projectGroup.create': ProjectGroupCreate, + 'projectGroup.delete': ProjectGroupSelector, + 'projectGroup.importNested': ProjectGroupImportNested, + 'projectGroup.list': null, + 'projectGroup.moveProject': ProjectGroupMoveProject, + 'projectGroup.scanNested': ProjectGroupScanNested, + 'projectGroup.update': ProjectGroupUpdate, + 'projectHostSetup.clone': ProjectHostSetupClone, + 'projectHostSetup.create': ProjectHostSetupCreate, + 'projectHostSetup.delete': ProjectHostSetupDelete, + 'projectHostSetup.list': null, + 'projectHostSetup.setupExistingFolder': ProjectHostSetupExistingFolder, + 'projectHostSetup.update': ProjectHostSetupUpdate, + 'repo.add': RepoPath, + 'repo.baseRefDefault': RepoSelector, + 'repo.clone': RepoClone, + 'repo.create': RepoCreate, + 'repo.gitAvailable': null, + 'repo.hooks': RepoSelector, + 'repo.hooksCheck': RepoSelector, + 'repo.issueCommandRead': RepoSelector, + 'repo.issueCommandWrite': RepoIssueCommandWrite, + 'repo.list': null, + 'repo.reorder': RepoReorder, + 'repo.rm': RepoSelector, + 'repo.saveSparsePreset': RepoSparsePresetSave, + 'repo.searchRefs': RepoSearchRefs, + 'repo.setBaseRef': RepoSetBaseRef, + 'repo.setupScriptImports': RepoSelector, + 'repo.show': RepoSelector, + 'repo.sparsePresets': RepoSelector, + 'repo.update': RepoUpdate, + 'runtime.clientCapabilities.update': ClientCapabilitiesUpdate, + 'runtime.clientEvents.subscribe': null, + 'runtime.clientEvents.unsubscribe': ClientEventsUnsubscribeParams, + 'session.tabs.activate': ActivateTab, + 'session.tabs.close': CloseTab, + 'session.tabs.closeLifecycle': CloseLifecycleTab, + 'session.tabs.createTerminal': CreateTerminalTab, + 'session.tabs.list': WorktreeTabSelector, + 'session.tabs.listAll': null, + 'session.tabs.move': MoveTab, + 'session.tabs.setTabProps': SetTabProps, + 'session.tabs.subscribe': WorktreeTabSelector, + 'session.tabs.subscribeAll': null, + 'session.tabs.unsubscribe': SessionTabsUnsubscribe, + 'session.tabs.unsubscribeAll': SessionTabsUnsubscribeAllParams, + 'session.tabs.updatePaneLayout': UpdatePaneLayout, + 'settings.get': null, + 'settings.getTerminalQuickCommands': null, + 'settings.mutateNativeChatSessionOptions': NativeChatSessionOptionsMutation, + 'settings.update': SettingsUpdate, + 'settings.updatePRBotAuthorOverride': PRBotAuthorOverrideUpdate, + 'settings.updateTerminalQuickCommands': TerminalQuickCommandsUpdate, + 'skills.beginUpload': SkillUploadBeginRequestSchema, + 'skills.cancelInstall': SkillsCancelInstallParams, + 'skills.cancelUpload': SkillUploadCommitRequestSchema, + 'skills.commitUpload': SkillUploadCommitRequestSchema, + 'skills.delete': SkillDeleteRequestSchema, + 'skills.discover': SkillsDiscoverParams, + 'skills.getInstallProgress': SkillsGetInstallProgressParams, + 'skills.install': SkillInstallRequestSchema, + 'skills.installBundle': SkillBundleInstallRequestSchema, + 'skills.listManagedInstalls': null, + 'skills.previewDelete': SkillDeleteRequestSchema, + 'skills.previewInstall': SkillInstallPreviewRequestSchema, + 'skills.removeInstall': SkillRemoveRequestSchema, + 'skills.share': AgentSkillShareRequestSchema, + 'skills.uploadChunk': SkillUploadChunkRequestSchema, + 'speech.dictation.cancel': DictationHandle, + 'speech.dictation.chunk': DictationChunk, + 'speech.dictation.finish': DictationHandle, + 'speech.dictation.setup': DictationSetup, + 'speech.dictation.start': DictationStart, + 'speech.models.delete': SpeechModelAction, + 'speech.models.download': SpeechModelAction, + 'speech.models.list': null, + 'ssh.connect': SshTarget, + 'ssh.getState': SshTarget, + 'ssh.listRemovedTargetLabels': null, + 'ssh.listTargetSummaries': null, + 'ssh.listTargets': null, + 'stats.summary': null, + 'status.get': null, + 'terminal.adoptOrphans': TerminalAdoptOrphans, + 'terminal.agentStatus': TerminalHandle, + 'terminal.clearBuffer': TerminalHandle, + 'terminal.close': TerminalHandle, + 'terminal.closeAll': TerminalCloseAll, + 'terminal.closeTab': TerminalHandle, + 'terminal.create': TerminalCreateParams, + 'terminal.createAgentSession': CreateAgentSessionParams, + 'terminal.ensureAgentSession': EnsureAgentSessionParams, + 'terminal.focus': TerminalFocus, + 'terminal.getAutoRestoreFit': TerminalGetAutoRestoreFitParams, + 'terminal.getDisplayMode': TerminalHandle, + 'terminal.inspectProcess': TerminalInspectProcess, + 'terminal.isRunningAgent': TerminalHandle, + 'terminal.list': TerminalListParams, + 'terminal.multiplex': TerminalMultiplex, + 'terminal.read': TerminalRead, + 'terminal.recoverPane': TerminalRecoverPane, + 'terminal.rename': TerminalRename, + 'terminal.resizeForClient': TerminalResizeForClient, + 'terminal.resolveActive': TerminalResolveActive, + 'terminal.resolveIdentity': TerminalHandle, + 'terminal.resolvePane': TerminalResolvePane, + 'terminal.restoreFit': TerminalHandle, + 'terminal.send': TerminalSend, + 'terminal.setAutoRestoreFit': TerminalSetAutoRestoreFit, + 'terminal.setDisplayMode': TerminalSetDisplayMode, + 'terminal.show': TerminalHandle, + 'terminal.sleep': TerminalCloseAll, + 'terminal.split': TerminalSplit, + 'terminal.stop': TerminalCloseAll, + 'terminal.stopExact': TerminalStopExact, + 'terminal.subscribe': TerminalSubscribe, + 'terminal.unsubscribe': TerminalUnsubscribe, + 'terminal.updateViewport': TerminalUpdateViewport, + 'terminal.wait': TerminalWait, + 'ui.get': null, + 'ui.recordFeatureInteraction': FeatureInteractionIdParam, + 'ui.set': UiUpdate, + 'updater.check': UpdaterCheckParams, + 'updater.download': null, + 'updater.getStatus': null, + 'updater.install': null, + 'workspacePorts.kill': WorkspacePortKillParams, + 'workspacePorts.scan': WorkspacePortScanParams, + 'worktree.activate': WorktreeActivate, + 'worktree.create': WorktreeCreate, + 'worktree.detectedList': WorktreeDetectedListParams, + 'worktree.forceDeleteBranch': WorktreeForceDeleteBranch, + 'worktree.lineageList': null, + 'worktree.list': WorktreeListParams, + 'worktree.listRetiredNames': WorktreeDetectedListParams, + 'worktree.persistSortOrder': WorktreeSortOrder, + 'worktree.prefetchCreateBase': WorktreePrefetchCreateBase, + 'worktree.ps': WorktreePsParams, + 'worktree.resolveMrBase': WorktreeResolveMrBase, + 'worktree.resolvePrBase': WorktreeResolvePrBase, + 'worktree.rm': WorktreeRemove, + 'worktree.set': WorktreeSet, + 'worktree.show': WorktreeSelectorOfWorktreeParams, + 'worktree.sleep': WorktreeSelectorOfWorktreeParams, + 'worktree.teardownMissingTerminals': WorktreeTeardownMissingTerminalsParams +} as const + +// Why: these methods bind a schema the shared contract cannot hold because its value +// graph reaches into src/main. Listing them keeps the gap visible instead of absent. +export const RPC_METHODS_WITHOUT_SHARED_PARAMS: readonly string[] = [ + 'emulator.install', + 'orchestration.send', + 'orchestration.taskUpdate' +] + +export type RpcMethodName = keyof typeof RPC_PARAMS_BY_METHOD + +// Why: z.output is the post-parse shape the handler receives, which is not what a +// client may send — a .default() field reads as required. z.input is not the answer +// either: requiredString is z.unknown().transform(...), so its input admits any value. +// Senders use RpcSendParams from ./rpc-send-params, which is derived from this map. +export type RpcParams = + (typeof RPC_PARAMS_BY_METHOD)[Method] extends z.ZodType + ? z.output<(typeof RPC_PARAMS_BY_METHOD)[Method]> + : void diff --git a/src/shared/rpc-contract/rpc-send-params.ts b/src/shared/rpc-contract/rpc-send-params.ts new file mode 100644 index 00000000000..fcb6d66a359 --- /dev/null +++ b/src/shared/rpc-contract/rpc-send-params.ts @@ -0,0 +1,69 @@ +import type { z } from 'zod' +import type { RPC_PARAMS_BY_METHOD, RpcMethodName } from './rpc-params-catalog.generated' + +// Why this exists: neither of zod's two inferred types describes an outgoing request. +// z.output is what the handler receives *after* parsing, so a `.default(x)` field reads as +// required and a sender that legitimately omits it fails to typecheck. z.input is worse here +// — the params builders parse with z.unknown() so a hostile client cannot crash the +// dispatcher, which collapses every requiredString/OptionalString field to `unknown`. +// +// So take each channel where it is honest: key optionality from zod's own `optin` marker +// (the z.input rule, which is the one that understands .default and .optional), and value +// types from z.output (the post-coercion contract the builders declare in their pipe target). +// Derived from the generated catalog, so it cannot drift from the dispatcher. +// +// Type-level only. Never import the schema *values* into a client: requiredString is +// z.unknown().transform(...), so a client-side parse coerces a non-string to '' instead of +// rejecting it, silently changing the bytes on the wire. + +type Prettify = { [K in keyof T]: T[K] } & {} + +/** zod's own input-side key-optionality rule, copied from $InferObjectInput. */ +type SendOptionalSchema = { _zod: { optin: 'optional' | 'defaulted' } } + +type SendShape = Prettify< + { + -readonly [K in keyof Shape as Shape[K] extends SendOptionalSchema ? never : K]: RpcSendInput< + Shape[K] + > + } & { + -readonly [K in keyof Shape as Shape[K] extends SendOptionalSchema ? K : never]?: RpcSendInput< + Shape[K] + > + } +> + +/** + * The value a sender may put on the wire for one schema. Wrappers not listed here (record, + * tuple, lazy, intersection) fall through to z.output, which is what shipped before. + */ +export type RpcSendInput = + Schema extends z.ZodOptional + ? RpcSendInput | undefined + : Schema extends z.ZodDefault + ? RpcSendInput | undefined + : Schema extends z.ZodPrefault + ? RpcSendInput | undefined + : Schema extends z.ZodNullable + ? RpcSendInput | null + : Schema extends z.ZodArray + ? RpcSendInput[] + : // ZodObject is the only schema carrying a `shape`, and matching on it keeps + // .strict()/.extend()/.superRefine() results in this branch. + Schema extends { shape: infer Shape } + ? keyof Shape extends never + ? // Mirrors $InferObjectOutput: a no-field object admits no properties. + Record + : SendShape + : // ZodDiscriminatedUnion extends ZodUnion, so both land here. + Schema extends z.ZodUnion + ? RpcSendInput + : Schema extends z.ZodType + ? z.output + : never + +/** The params a client may send for `Method`; `void` for the methods that take none. */ +export type RpcSendParams = + (typeof RPC_PARAMS_BY_METHOD)[Method] extends z.ZodType + ? RpcSendInput<(typeof RPC_PARAMS_BY_METHOD)[Method]> + : void diff --git a/src/shared/rpc-contract/runtime-client-capabilities-params.ts b/src/shared/rpc-contract/runtime-client-capabilities-params.ts new file mode 100644 index 00000000000..77f7914585b --- /dev/null +++ b/src/shared/rpc-contract/runtime-client-capabilities-params.ts @@ -0,0 +1,7 @@ +import { z } from 'zod' + +export const ClientCapabilitiesUpdate = z + .object({ + clientCapabilities: z.array(z.string().min(1).max(128)).max(64) + }) + .strict() diff --git a/src/shared/rpc-contract/session-tabs-params.ts b/src/shared/rpc-contract/session-tabs-params.ts new file mode 100644 index 00000000000..dfcdf60cca2 --- /dev/null +++ b/src/shared/rpc-contract/session-tabs-params.ts @@ -0,0 +1,7 @@ +import { z } from 'zod' + +export const SessionTabsUnsubscribeAllParams = z + .object({ + subscriptionId: z.string().min(1).optional() + }) + .nullish() diff --git a/src/shared/rpc-contract/session-tabs-schemas-params.ts b/src/shared/rpc-contract/session-tabs-schemas-params.ts new file mode 100644 index 00000000000..d04f5443477 --- /dev/null +++ b/src/shared/rpc-contract/session-tabs-schemas-params.ts @@ -0,0 +1,230 @@ +import { z } from 'zod' +import { RUNTIME_NAVIGATION_TARGETS } from '../runtime-navigation' +import { TAB_ACTIVATION_INTENTS } from '../tab-activation-intent' +import { OptionalBoolean } from './rpc-param-primitives' +import { sleepingAgentLaunchConfigSchema } from '../workspace-session-sleeping-agents' +import type { TuiAgent } from '../tui-agent' +import { isTuiAgent } from '../tui-agent-config' +import { MAX_QUICK_COMMAND_AGENT_PROMPT_LENGTH } from '../terminal-quick-commands' + +export const WorktreeTabSelector = z.object({ + worktree: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing worktree selector')) +}) + +export const SessionTabsUnsubscribe = WorktreeTabSelector.extend({ + subscriptionId: z.string().min(1).optional() +}) + +export const ActivateTab = WorktreeTabSelector.extend({ + tabId: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing tab id')), + leafId: z.string().max(128).optional(), + notifyClients: OptionalBoolean, + navigation: z.enum(RUNTIME_NAVIGATION_TARGETS).optional(), + // Why: absent means user intent, so clients that predate this field keep the + // tab-open wake gesture. Only 'automatic' may be refused for a slept pane. + intent: z.enum(TAB_ACTIVATION_INTENTS).optional() +}) + +export const CloseTab = ActivateTab.extend({ + // Why: optional preserves authenticated legacy user closes; lifecycle intent + // uses the additive evidence-bearing method instead. + reason: z.literal('user').optional() +}) + +export const CloseLifecycleTab = ActivateTab.extend({ + reason: z.enum(['pty-exit', 'cleanup']), + publicationEpoch: z.string().min(1).max(128), + terminal: z.string().min(1).max(256) +}) + +export type TerminalPaneLayoutNodeInput = + | { type: 'leaf'; leafId: string } + | { + type: 'split' + direction: 'horizontal' | 'vertical' + first: TerminalPaneLayoutNodeInput + second: TerminalPaneLayoutNodeInput + ratio?: number + } + +// Why: this schema parses UNTRUSTED remote-client input. A recursive zod parse +// of a deeply-nested tree would overflow the main-process stack, so validate +// iteratively with hard depth + node-count caps before building the typed value. +export const MAX_PANE_LAYOUT_DEPTH = 64 + +export const MAX_PANE_LAYOUT_NODES = 1024 + +export function parseTerminalPaneLayoutNode(value: unknown): TerminalPaneLayoutNodeInput | null { + // Iterative validate-then-build: first walk the raw tree with an explicit + // stack (no recursion) enforcing caps, then build bottom-up. + let nodeCount = 0 + const stack: { raw: unknown; depth: number }[] = [{ raw: value, depth: 0 }] + while (stack.length > 0) { + const { raw, depth } = stack.pop()! + if (depth > MAX_PANE_LAYOUT_DEPTH || ++nodeCount > MAX_PANE_LAYOUT_NODES) { + return null + } + if (typeof raw !== 'object' || raw === null) { + return null + } + const node = raw as Record + if (node.type === 'leaf') { + if (typeof node.leafId !== 'string' || node.leafId.length < 1 || node.leafId.length > 128) { + return null + } + continue + } + if (node.type === 'split') { + if (node.direction !== 'horizontal' && node.direction !== 'vertical') { + return null + } + if ( + node.ratio !== undefined && + (typeof node.ratio !== 'number' || + !Number.isFinite(node.ratio) || + node.ratio < 0 || + node.ratio > 1) + ) { + return null + } + stack.push({ raw: node.first, depth: depth + 1 }, { raw: node.second, depth: depth + 1 }) + continue + } + return null + } + return value as TerminalPaneLayoutNodeInput +} + +export const TerminalPaneLayoutNodeSchema = z + .unknown() + .transform((value) => parseTerminalPaneLayoutNode(value)) + .pipe( + z.custom((value) => value !== null, { + message: 'Invalid or too-deep pane layout tree' + }) + ) + +export const UpdatePaneLayout = WorktreeTabSelector.extend({ + tabId: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing tab id')), + root: z.union([z.null(), TerminalPaneLayoutNodeSchema]), + expandedLeafId: z.string().max(128).nullable().optional(), + titlesByLeafId: z.record(z.string(), z.string()).optional() +}) + +export const SetTabProps = WorktreeTabSelector.extend({ + tabId: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing tab id')), + // undefined = leave unchanged; null = clear color / unset. + color: z.string().max(64).nullable().optional(), + isPinned: z.boolean().optional(), + // undefined = leave unchanged; no "clear" semantic (absence means default 'terminal'). + viewMode: z.enum(['terminal', 'chat']).optional() +}) + +export const CreateTerminalTab = WorktreeTabSelector.extend({ + afterTabId: z.string().optional(), + targetGroupId: z.string().optional(), + command: z.string().optional(), + cwd: z.string().min(1).optional(), + env: z.record(z.string(), z.string()).optional(), + envToDelete: z.array(z.string().min(1).max(256)).max(32).optional(), + startupCommandDelivery: z.enum(['fast', 'shell-ready']).optional(), + launchConfig: sleepingAgentLaunchConfigSchema, + launchToken: z.string().min(1).max(128).optional(), + agent: z + .custom(isTuiAgent, { + message: 'Unknown agent preset' + }) + .optional(), + // Why: agent prompts must be quoted and injected for the host shell (native, + // WSL, or SSH) instead of pasted from the mobile client before the TUI is ready. + agentPrompt: z + .string() + .max(MAX_QUICK_COMMAND_AGENT_PROMPT_LENGTH) + .refine((value) => value.trim().length > 0, { message: 'Agent prompt cannot be empty' }) + .optional(), + // Why: `agent` is the legacy preset field; `launchAgent` is the launch-plan + // identity used when preserving resume config across runtime boundaries. + launchAgent: z + .custom(isTuiAgent, { + message: 'Unknown launch agent' + }) + .optional(), + viewMode: z.enum(['terminal', 'chat']).optional(), + activate: z.boolean().optional(), + select: z.boolean().optional(), + navigation: z.enum(RUNTIME_NAVIGATION_TARGETS).optional(), + // Why: idempotency key so a retried create (double-tap, reconnect replay) + // returns the in-flight operation instead of spawning a duplicate terminal. + clientMutationId: z.string().min(1).max(128).optional() +}).superRefine((value, context) => { + if (value.agentPrompt !== undefined && value.agent === undefined) { + context.addIssue({ + code: 'custom', + path: ['agentPrompt'], + message: 'Agent prompt requires an agent preset' + }) + } + if (value.agentPrompt !== undefined && value.command !== undefined) { + context.addIssue({ + code: 'custom', + path: ['agentPrompt'], + message: 'Agent prompt cannot be combined with a startup command' + }) + } +}) + +export const MoveTabBase = { + worktree: WorktreeTabSelector.shape.worktree, + tabId: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing tab id')), + targetGroupId: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing target group id')) +} as const + +export const MoveTab = z.discriminatedUnion('kind', [ + z + .object({ + ...MoveTabBase, + kind: z.literal('reorder'), + tabOrder: z.array(z.string().min(1)).min(1, 'Missing tab order') + }) + .strict(), + z + .object({ + ...MoveTabBase, + kind: z.literal('move-to-group'), + index: z.number().int().nonnegative().optional() + }) + .strict(), + z + .object({ + ...MoveTabBase, + kind: z.literal('split'), + splitDirection: z.enum(['left', 'right', 'up', 'down']) + }) + .strict() +]) + +export const SaveMarkdownTab = ActivateTab.extend({ + baseVersion: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing base version')), + content: z.string() +}) diff --git a/src/shared/rpc-contract/skills-params.ts b/src/shared/rpc-contract/skills-params.ts new file mode 100644 index 00000000000..53d7b769523 --- /dev/null +++ b/src/shared/rpc-contract/skills-params.ts @@ -0,0 +1,12 @@ +import { z } from 'zod' +import { SkillDiscoveryTargetSchema } from '../skills' + +export const SkillsGetInstallProgressParams = z + .object({ operationId: z.string().min(1).max(128) }) + .strict() + +export const SkillsCancelInstallParams = z + .object({ operationId: z.string().min(1).max(128) }) + .strict() + +export const SkillsDiscoverParams = SkillDiscoveryTargetSchema.default({}) diff --git a/src/shared/rpc-contract/speech-params.ts b/src/shared/rpc-contract/speech-params.ts new file mode 100644 index 00000000000..8cd0ea00a49 --- /dev/null +++ b/src/shared/rpc-contract/speech-params.ts @@ -0,0 +1,54 @@ +import { z } from 'zod' +import { OptionalString, requiredString } from './rpc-param-primitives' + +export const AUDIO_BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/ + +export const DICTATION_SAMPLE_RATE = 16_000 + +export const PCM_BYTES_PER_SAMPLE = 2 + +export const MAX_DICTATION_AUDIO_SECONDS = 5 + +export const MAX_DICTATION_AUDIO_CHUNK_BYTES = + DICTATION_SAMPLE_RATE * PCM_BYTES_PER_SAMPLE * MAX_DICTATION_AUDIO_SECONDS + +export const MAX_DICTATION_AUDIO_CHUNK_BASE64_LENGTH = + Math.ceil(MAX_DICTATION_AUDIO_CHUNK_BYTES / 3) * 4 + +export function isValidAudioBase64(value: string): boolean { + return value.length % 4 !== 1 && AUDIO_BASE64_PATTERN.test(value) +} + +export const DictationStart = z.object({ + dictationId: requiredString('Missing dictation ID'), + modelId: OptionalString +}) + +export const DictationChunk = z.object({ + dictationId: requiredString('Missing dictation ID'), + audioBase64: requiredString('Missing audio chunk') + // Why: feedMobileDictation decodes into Buffer + Float32Array; reject + // oversized chunks before allocation. This mirrors the mobile pending-audio budget. + .refine( + (value) => value.length <= MAX_DICTATION_AUDIO_CHUNK_BASE64_LENGTH, + 'Audio chunk is too large' + ) + // Why: Buffer.from(..., 'base64') silently drops malformed bytes; reject + // bad mobile audio chunks instead of feeding empty/corrupt PCM. + .refine(isValidAudioBase64, 'Audio chunk must be base64'), + sampleRate: z.number().finite().positive() +}) + +export const DictationHandle = z.object({ + dictationId: requiredString('Missing dictation ID') +}) + +export const SpeechModelAction = z.object({ + modelId: requiredString('Missing model ID') +}) + +export const DictationSetup = z.object({ + enabled: z.boolean().optional(), + modelId: OptionalString, + dictationMode: z.enum(['toggle', 'hold']).optional() +}) diff --git a/src/shared/rpc-contract/ssh-params.ts b/src/shared/rpc-contract/ssh-params.ts new file mode 100644 index 00000000000..77f336c991b --- /dev/null +++ b/src/shared/rpc-contract/ssh-params.ts @@ -0,0 +1,5 @@ +import { z } from 'zod' + +export const SshTarget = z.object({ + targetId: z.string().min(1) +}) diff --git a/src/shared/rpc-contract/structured-agent-session-params.ts b/src/shared/rpc-contract/structured-agent-session-params.ts new file mode 100644 index 00000000000..7d2c73afb66 --- /dev/null +++ b/src/shared/rpc-contract/structured-agent-session-params.ts @@ -0,0 +1,246 @@ +import { z } from 'zod' +import { isAgentSessionId } from '../agent-session-record' +import { normalizeExecutionHostId } from '../execution-host' +import { + AGENT_SESSION_HISTORY_DIRECTIONS, + AGENT_SESSION_HISTORY_MAX_LIMIT +} from '../agent-session-wire' + +export const MAX_ID_LENGTH = 512 + +// Four Claude questions with all four generated choices occupy 610 chars when fully percent-encoded. +export const MAX_RESPONSE_OPTION_ID_LENGTH = 1024 + +export const MAX_PROMPT_BYTES = 256 * 1024 + +export const MAX_BLOCKS = 64 + +export const MAX_OPTION_LABEL = 512 + +export const SessionId = z + .string() + .max(MAX_ID_LENGTH) + .refine(isAgentSessionId, 'Invalid agent session id') + +export const Identifier = (message: string, maxLength = MAX_ID_LENGTH) => + z + .string() + .min(1, message) + .max(maxLength, message) + .refine((value) => value === value.trim(), message) + +export const JournalCursor = z + .object({ + epoch: Identifier('Invalid journal epoch'), + sequence: z.number().int().nonnegative() + }) + .strict() + +export const MutationEnvelope = z + .object({ + sessionId: SessionId, + clientOperationId: Identifier('Invalid client operation id'), + /** Null is the "must not exist yet" case; every other call fences. */ + expectedRuntimeFence: z.number().int().positive().nullable(), + payloadFingerprint: z + .string() + .regex(/^[0-9a-f]{64}$/, 'Payload fingerprint must be a sha256 hex digest') + }) + .strict() + +export const ProviderHandle = z.discriminatedUnion('kind', [ + z.object({ kind: z.literal('codex'), threadId: Identifier('Invalid thread id') }).strict(), + z + .object({ + kind: z.literal('claude'), + sessionId: Identifier('Invalid provider session id'), + leafUuid: Identifier('Invalid leaf uuid').nullable() + }) + .strict() +]) + +export const ExecutionHostId = z + .string() + .max(MAX_ID_LENGTH) + .transform((value) => normalizeExecutionHostId(value)) + .refine((value): value is NonNullable => value !== null, { + message: 'Invalid execution host id' + }) + +export const ExecutionLocation = z + .object({ + executionHostId: ExecutionHostId, + wslDistro: Identifier('Invalid WSL distro').nullable(), + workspaceId: Identifier('Invalid workspace id'), + workspaceKind: z.enum(['git-worktree', 'folder']) + }) + .strict() + +export const AccountHome = z + .object({ + variable: z.enum(['CLAUDE_CONFIG_DIR', 'CODEX_HOME']), + path: z.string().min(1).max(4096) + }) + .strict() + +export const AttachParams = z + .object({ + envelope: MutationEnvelope, + location: ExecutionLocation, + provider: z.enum(['codex', 'claude']), + agent: Identifier('Invalid agent'), + accountHome: AccountHome, + runtimeKind: z.enum(['native', 'tui']), + providerHandle: ProviderHandle + }) + .strict() + +/** An identity, and nothing the host would otherwise read off disk. A transcript path or account + * home here would let a client choose which file this host imports and which credential directory + * the provider child launches against; both are derived host-side from this id instead. */ +export const ResumeSource = z + .object({ + providerSessionId: Identifier('Invalid provider session id') + }) + .strict() + +export const CreateIntentParams = z + .object({ + envelope: MutationEnvelope, + worktree: Identifier('Invalid worktree selector'), + agent: z.enum(['claude', 'codex']), + resumeFrom: ResumeSource.optional() + }) + .strict() + +export const CreateParams = z.union([AttachParams, CreateIntentParams]) + +export const CreateSupportParams = z + .object({ + worktree: Identifier('Invalid worktree selector'), + agent: z.enum(['claude', 'codex']) + }) + .strict() + +/** Clients may only author user turns. Accepting an assistant or tool role here + * would let one client write words into the agent's mouth in another's + * timeline, and the provider — not the client — owns those. */ +export const SendBlock = z.discriminatedUnion('type', [ + z.object({ type: z.literal('text'), text: z.string() }).strict(), + z + .object({ + type: z.literal('image-ref'), + path: z.string().min(1).max(4096).optional(), + url: z.string().min(1).max(4096).optional(), + alt: z.string().max(MAX_OPTION_LABEL).optional() + }) + .strict() + .refine( + (value) => Boolean(value.path) !== Boolean(value.url), + 'Provide exactly one of path/url' + ) +]) + +export const SendParams = z + .object({ + envelope: MutationEnvelope, + retryUnknown: z.literal(true).optional(), + body: z + .object({ + kind: z.literal('message'), + role: z.literal('user'), + blocks: z.array(SendBlock).min(1).max(MAX_BLOCKS) + }) + .strict() + .refine( + (value) => Buffer.byteLength(JSON.stringify(value.blocks), 'utf8') <= MAX_PROMPT_BYTES, + 'Message is too large' + ) + }) + .strict() + +export const CancelParams = z + .object({ + envelope: MutationEnvelope, + turnId: Identifier('Invalid turn id'), + scope: z.literal('background-tasks').optional(), + taskId: Identifier('Invalid task id').optional() + }) + .strict() + .refine((value) => value.taskId === undefined || value.scope === 'background-tasks', { + message: 'A task id requires background-task scope' + }) + +export const RespondParams = z + .object({ + envelope: MutationEnvelope, + itemId: Identifier('Invalid item id'), + /** Compare-and-set: the revision the client had on screen. */ + expectedRevision: z.number().int().positive(), + optionId: Identifier('Invalid option id', MAX_RESPONSE_OPTION_ID_LENGTH) + }) + .strict() + +export const SetOptionParams = z + .object({ + envelope: MutationEnvelope, + key: Identifier('Invalid option key'), + value: z.string().max(MAX_OPTION_LABEL) + }) + .strict() + +export const HandoffParams = z + .object({ + envelope: MutationEnvelope, + direction: z.enum(['to-tui', 'to-native']), + mode: z.enum(['now', 'after-turn', 'stop-turn']), + action: z.enum(['start', 'cancel-queued', 'retry', 'recover']).optional() + }) + .strict() + +export const OptionsParams = z.object({ sessionId: SessionId }).strict() + +export const ConversationCommandParams = z + .object({ + envelope: MutationEnvelope, + command: z.enum(['clear', 'compact']) + }) + .strict() + +/** One surface's claim on one session. The id names the surface, not the client: two chat views + * looking at the same session are two holders, and either leaving must not release + * the other's. */ +export const HoldParams = z + .object({ sessionId: SessionId, holderId: Identifier('Invalid holder id') }) + .strict() + +export const HistoryParams = z + .object({ + sessionId: SessionId, + direction: z.enum(AGENT_SESSION_HISTORY_DIRECTIONS), + cursor: JournalCursor.optional(), + limit: z.number().int().positive().max(AGENT_SESSION_HISTORY_MAX_LIMIT).optional() + }) + .strict() + +export const SubscribeParams = z + .object({ sessionId: SessionId, cursor: JournalCursor.optional() }) + .strict() + +export const UnsubscribeParams = z + .object({ + sessionId: SessionId, + subscriptionId: Identifier('Invalid subscription id').optional() + }) + .strict() + +/** Read-only owner classification retained for restart safety; mutation handoff is separate. */ +export const HandoffStatusParams = z.object({ sessionId: SessionId }).strict() + +export const RewindParams = z + .object({ + envelope: MutationEnvelope, + itemId: Identifier('Invalid item id', 4096), + expectedEpoch: Identifier('Invalid journal epoch') + }) + .strict() diff --git a/src/shared/rpc-contract/task-resume-state-params.ts b/src/shared/rpc-contract/task-resume-state-params.ts new file mode 100644 index 00000000000..56ab022eb92 --- /dev/null +++ b/src/shared/rpc-contract/task-resume-state-params.ts @@ -0,0 +1,32 @@ +import { z } from 'zod' + +/** + * Tasks page-position state persisted through `ui.set`; mirrors `TaskResumeState`. + * + * This object is `.strict()` and sits behind `ui.set`'s field-level `.catch`, so a key + * a host predates makes that host drop the ENTIRE resume state — github and jira with + * it — and report success. Only add a field here when clients must agree on it across + * versions; per-device view preferences belong in client-local storage instead. + */ +export const TaskResumeState = z + .object({ + githubMode: z.enum(['items', 'project']).optional(), + githubItemsPreset: z.string().nullable().optional(), + githubItemsQuery: z.string().optional(), + githubProjectHiddenFieldIdsByView: z.record(z.string(), z.array(z.string())).optional(), + linearMode: z.enum(['issues', 'projects', 'views', 'in-orca']).optional(), + linearPreset: z.enum(['assigned', 'created', 'all', 'completed']).optional(), + linearQuery: z.string().optional(), + linearContext: z + .object({ + kind: z.enum(['project', 'view']), + id: z.string(), + workspaceId: z.string(), + model: z.enum(['issue', 'project']).optional() + }) + .strict() + .optional(), + jiraPreset: z.enum(['assigned', 'reported', 'all', 'done']).optional(), + jiraQuery: z.string().optional() + }) + .strict() diff --git a/src/shared/rpc-contract/terminal-orphan-params.ts b/src/shared/rpc-contract/terminal-orphan-params.ts new file mode 100644 index 00000000000..2a14c2b72c3 --- /dev/null +++ b/src/shared/rpc-contract/terminal-orphan-params.ts @@ -0,0 +1,105 @@ +import { z } from 'zod' +import type { TabGroupLayoutNode } from '../tab-types' +import { OptionalString, requiredString } from './rpc-param-primitives' +import { TerminalPaneLayoutNodeSchema } from './session-tabs-schemas-params' +import { isPtyIncarnationId } from '../pty-incarnation' +import type { PtyIncarnationId } from '../pty-incarnation' + +export function parseOrphanGroupLayout(value: unknown): TabGroupLayoutNode | null { + const stack: { value: unknown; depth: number }[] = [{ value, depth: 0 }] + let count = 0 + while (stack.length > 0) { + const current = stack.pop()! + if ( + current.depth > 64 || + ++count > 1_024 || + !current.value || + typeof current.value !== 'object' + ) { + return null + } + const node = current.value as Record + if (node.type === 'leaf') { + if ( + typeof node.groupId !== 'string' || + node.groupId.length < 1 || + node.groupId.length > 256 + ) { + return null + } + continue + } + if ( + node.type !== 'split' || + (node.direction !== 'horizontal' && node.direction !== 'vertical') || + (node.ratio !== undefined && + (typeof node.ratio !== 'number' || + !Number.isFinite(node.ratio) || + node.ratio < 0 || + node.ratio > 1)) + ) { + return null + } + stack.push( + { value: node.first, depth: current.depth + 1 }, + { value: node.second, depth: current.depth + 1 } + ) + } + return value as TabGroupLayoutNode +} + +export const TerminalOrphanGroupLayout = z + .unknown() + .transform(parseOrphanGroupLayout) + .pipe(z.custom((value) => value !== null, 'Invalid orphan group layout')) + +export const TerminalOrphanTopology = z.object({ + tabs: z + .array( + z.object({ + tabId: requiredString('Missing topology tab id').pipe(z.string().max(256)), + root: TerminalPaneLayoutNodeSchema, + activeLeafId: requiredString('Missing active leaf id').pipe(z.string().max(128)), + expandedLeafId: z.string().max(128).nullable() + }) + ) + .min(1) + .max(64), + groups: z + .array( + z.object({ + id: z.string().min(1).max(256), + activeTabId: z.string().min(1).max(256), + tabOrder: z.array(z.string().min(1).max(256)).min(1).max(64), + recentTabIds: z.array(z.string().min(1).max(256)).max(64).optional() + }) + ) + .min(1) + .max(64), + groupLayout: TerminalOrphanGroupLayout.optional() +}) + +export const TerminalOrphanIncarnationId = z.custom( + isPtyIncarnationId, + 'Invalid PTY incarnation' +) + +export const TerminalAdoptOrphans = z.object({ + worktree: requiredString('Missing worktree selector').pipe(z.string().max(32_768)), + expectedTopologyRevision: z.number().int().nonnegative(), + claims: z + .array( + z.object({ + terminal: requiredString('Missing terminal handle').pipe(z.string().max(256)), + ptyId: requiredString('Missing PTY id').pipe(z.string().max(8_192)), + incarnationId: TerminalOrphanIncarnationId, + tabId: requiredString('Missing tab id').pipe(z.string().max(256)), + leafId: requiredString('Missing leaf id').pipe(z.string().max(128)) + }) + ) + .min(1) + .max(64), + activeTabId: OptionalString.pipe(z.string().max(256).optional()), + activeGroupId: OptionalString.pipe(z.string().max(256).optional()), + topology: TerminalOrphanTopology.optional() +}) diff --git a/src/shared/rpc-contract/terminal-quick-command-params.ts b/src/shared/rpc-contract/terminal-quick-command-params.ts new file mode 100644 index 00000000000..2a38bf28d8f --- /dev/null +++ b/src/shared/rpc-contract/terminal-quick-command-params.ts @@ -0,0 +1,73 @@ +import { z } from 'zod' +import { + MAX_QUICK_COMMAND_AGENT_PROMPT_LENGTH, + MAX_QUICK_COMMAND_ID_LENGTH, + MAX_QUICK_COMMAND_LABEL_LENGTH, + MAX_QUICK_COMMAND_REPO_ID_LENGTH, + MAX_QUICK_COMMAND_TERMINAL_TEXT_LENGTH, + normalizeTerminalQuickCommands, + supportsTerminalAgentQuickCommand +} from '../terminal-quick-commands' +import type { TerminalQuickCommand } from '../terminal-quick-command-types' + +export const TerminalQuickCommandScopeUpdate = z.discriminatedUnion('type', [ + z.object({ type: z.literal('global') }).strict(), + z + .object({ + type: z.literal('repo'), + repoId: z.string().max(MAX_QUICK_COMMAND_REPO_ID_LENGTH) + }) + .strict() +]) + +export const TerminalQuickCommandUpdateItem = z.union([ + z + .object({ + id: z.string().max(MAX_QUICK_COMMAND_ID_LENGTH), + label: z.string().max(MAX_QUICK_COMMAND_LABEL_LENGTH), + action: z.literal('terminal-command').optional(), + command: z.string().max(MAX_QUICK_COMMAND_TERMINAL_TEXT_LENGTH), + appendEnter: z.boolean(), + scope: TerminalQuickCommandScopeUpdate.optional() + }) + .strict(), + z + .object({ + id: z.string().max(MAX_QUICK_COMMAND_ID_LENGTH), + label: z.string().max(MAX_QUICK_COMMAND_LABEL_LENGTH), + action: z.literal('agent-prompt'), + agent: z.custom(supportsTerminalAgentQuickCommand, { + message: 'Agent does not support prompt commands' + }), + prompt: z.string().max(MAX_QUICK_COMMAND_AGENT_PROMPT_LENGTH), + scope: TerminalQuickCommandScopeUpdate.optional() + }) + .strict() +]) + +export const TerminalQuickCommandsUpdate = z + .object({ + // Why: a single host-side mutation preserves unrelated desktop/mobile edits + // and avoids retransmitting the full ~240 KB list for every small change. + mutation: z.union([ + z + .object({ + type: z.literal('upsert'), + command: TerminalQuickCommandUpdateItem.transform( + (value) => normalizeTerminalQuickCommands([value])[0] + ).pipe( + z.custom((value) => value !== undefined, { + message: 'Quick command cannot be normalized' + }) + ) + }) + .strict(), + z + .object({ + type: z.literal('delete'), + id: z.string().min(1).max(MAX_QUICK_COMMAND_ID_LENGTH) + }) + .strict() + ]) + }) + .strict() diff --git a/src/shared/rpc-contract/terminal-stream-params.ts b/src/shared/rpc-contract/terminal-stream-params.ts new file mode 100644 index 00000000000..88506f63b47 --- /dev/null +++ b/src/shared/rpc-contract/terminal-stream-params.ts @@ -0,0 +1,40 @@ +import { z } from 'zod' +import { requiredString } from './rpc-param-primitives' +import { TerminalViewport } from './terminal-unary-params' + +export const TerminalHandle = z.object({ terminal: requiredString('Missing terminal handle') }) + +export const TerminalResizeForClient = z.discriminatedUnion('mode', [ + z.object({ + terminal: requiredString('Missing terminal handle'), + mode: z.literal('mobile-fit'), + cols: z.number().finite().positive(), + rows: z.number().finite().positive(), + clientId: requiredString('Missing client ID') + }), + z.object({ + terminal: requiredString('Missing terminal handle'), + mode: z.literal('restore'), + clientId: requiredString('Missing client ID') + }) +]) + +export const TerminalSubscribe = TerminalHandle.extend({ + client: z + .object({ + id: requiredString('Missing client ID'), + type: z.enum(['mobile', 'desktop']).default('desktop') + }) + .optional(), + viewport: TerminalViewport.optional(), + capabilities: z + .object({ + terminalBinaryStream: z.literal(1).optional(), + desktopViewportClaims: z.literal(1).optional(), + mobileInputLeaseOnly: z.literal(1).optional(), + writeUnavailable: z.literal(1).optional() + }) + .optional() +}) + +export const TerminalMultiplex = z.object({}) diff --git a/src/shared/rpc-contract/terminal-unary-params.ts b/src/shared/rpc-contract/terminal-unary-params.ts new file mode 100644 index 00000000000..e86bdf1fdc1 --- /dev/null +++ b/src/shared/rpc-contract/terminal-unary-params.ts @@ -0,0 +1,222 @@ +import { z } from 'zod' +import { OptionalFiniteNumber, OptionalString, requiredString } from './rpc-param-primitives' +import { isTuiAgent } from '../tui-agent-config' +import { TERMINAL_PANE_SPLIT_SOURCES } from '../feature-education-telemetry' + +export const TerminalHandle = z.object({ + terminal: requiredString('Missing terminal handle'), + // Additive fence understood by newer hosts; legacy hosts safely ignore it. + expectedIncarnationId: requiredString('Missing PTY incarnation').optional() +}) + +export const TerminalFocus = TerminalHandle.extend({ + navigation: z.enum(['caller', 'host']).optional() +}) + +/** + * `terminal.inspectProcess` carries one member the sibling handle methods must not: whether the + * caller's answer decides something once, which is what licenses the host to pay for a process-table + * read. Extended rather than added to `TerminalHandle` so `clearBuffer`/`agentStatus`/`isRunningAgent` + * keep refusing an option they have no use for. + */ +export const TerminalInspectProcess = TerminalHandle.extend({ + // Additive request member understood by newer hosts; legacy hosts safely ignore it. + scanChildProcesses: z.boolean().optional() +}) + +export const TerminalListParams = z.object({ + worktree: OptionalString, + limit: OptionalFiniteNumber, + handles: z + .array(requiredString('Missing terminal handle').pipe(z.string().max(256))) + .max(64) + .optional(), + requireFreshPtyLiveness: z.boolean().optional(), + // Why: layouts are ~31% of a large listing and only the human CLI formatter + // reads them. Absent means "include" so pre-flag clients keep rendering them. + includeVisualLayouts: z.boolean().optional() +}) + +export const TerminalResolveActive = z.object({ + worktree: OptionalString, + /** Refuse instead of guessing when several leaves could be the caller's own terminal. */ + requireUnambiguous: z.boolean().optional() +}) + +export const TerminalResolvePane = z.object({ + paneKey: requiredString('Missing pane key'), + worktreeId: OptionalString +}) + +export const TerminalRecoverPane = z.object({ + paneKey: requiredString('Missing pane key'), + worktreeId: requiredString('Missing worktree ID'), + expectedTerminal: requiredString('Missing expected terminal handle').optional() +}) + +export const TerminalRead = TerminalHandle.extend({ + cursor: z + .unknown() + .transform((value) => { + if (value === undefined) { + return undefined + } + if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) { + return Number.NaN + } + return value + }) + .pipe( + z + .number() + .optional() + .refine((v) => v === undefined || Number.isFinite(v), { + message: 'Cursor must be a non-negative integer' + }) + ) + .optional(), + limit: OptionalFiniteNumber, + // Why: optional so an older host that does not understand it simply drops the key and answers + // with its usual stream read; the response's `source` is what tells the caller which it got. + screen: z.literal(true).optional() +}).refine((params) => !(params.screen === true && params.cursor !== undefined), { + // Why: a cursor pages through accumulated output; a screen is the current frame with nothing + // behind it. Honoring both would answer with rendered lines carrying the stream's pagination + // metadata — two frames of reference in one payload, which is the confusion `source` exists to + // remove. The CLI already refuses the pair, but the RPC is reachable without it. + message: 'Cursor cannot be combined with a screen read' +}) + +// Why: preserve the legacy contract — `title: string | null` only, `undefined` rejected, so the CLI's "reset" signal stays distinct. +export const TerminalRename = TerminalHandle.extend({ + title: z.custom((value) => value === null || typeof value === 'string', { + message: 'Missing --title (pass empty string or null to reset)' + }) +}) + +export const TerminalSend = TerminalHandle.extend({ + text: OptionalString, + enter: z.unknown().optional(), + interrupt: z.unknown().optional(), + // Why: older hosts strip this optional intent and retain their direct-send behavior. + agentPrompt: z.literal(true).optional(), + // Why: waiting observes the same prompt receipt; it never authorizes a second write. + waitSubmitMs: z.number().int().min(0).max(3_600_000).optional(), + resolvedLaunchDraft: z + .object({ + text: z.string(), + createdAt: z.number().finite() + }) + .optional(), + requireAgentStatus: z.enum(['sendable']).optional(), + // Why: terminal-generated replies are valid input but must not transfer the shared terminal floor. + inputKind: z.enum(['query-reply']).optional(), + // Why: identifies the caller for the driver state machine; when absent (older clients) the server falls back to the most recent mobile actor (docs/mobile-presence-lock.md). + client: z + .object({ + id: requiredString('Missing client ID'), + type: z.enum(['mobile', 'desktop']).default('desktop').optional() + }) + .optional(), + viewport: z + .object({ + cols: z.number().int().min(1).max(1000), + rows: z.number().int().min(1).max(500) + }) + .optional(), + claimViewport: z.literal(true).optional() +}) + +export const TerminalViewport = z.object({ + cols: z.number().int().min(1).max(1000), + rows: z.number().int().min(1).max(500) +}) + +export const TerminalWait = TerminalHandle.extend({ + for: z.custom<'exit' | 'tui-idle'>((value) => value === 'exit' || value === 'tui-idle', { + message: 'Invalid --for value. Supported: exit, tui-idle' + }), + timeoutMs: OptionalFiniteNumber +}) + +export const TerminalCreateParams = z.object({ + worktree: OptionalString, + clientMutationId: z.string().min(1).max(128).optional(), + reconcileExisting: z.boolean().optional(), + command: OptionalString, + startupCommandDelivery: z.enum(['fast', 'shell-ready']).optional(), + env: z.record(z.string(), z.string()).optional(), + envToDelete: z.array(z.string().min(1).max(256)).max(32).optional(), + launchConfig: z + .object({ + agentCommand: z.string().optional(), + agentArgs: z.string(), + agentEnv: z.record(z.string(), z.string()), + ompResumeFilePath: z + .string() + .min(1) + .max(32 * 1024) + .optional() + }) + .optional(), + resumeProviderSession: z + .object({ + key: z.enum(['session_id', 'conversation_id']), + id: z.string().min(1).max(512), + transcriptPath: z.string().min(1).max(32_768).optional() + }) + .optional(), + launchToken: OptionalString, + launchAgent: z.string().refine(isTuiAgent).optional(), + terminalColorQueryReplies: z + .object({ + foreground: z.string().max(128).optional(), + background: z.string().max(128).optional() + }) + .optional(), + title: OptionalString, + focus: z.unknown().optional(), + rendererBacked: z.unknown().optional(), + activate: z.unknown().optional(), + presentation: z.enum(['background', 'focused']).optional(), + tabId: OptionalString, + leafId: OptionalString +}) + +export const TerminalSplit = TerminalHandle.extend({ + direction: z + .unknown() + .transform((v) => (v === 'vertical' || v === 'horizontal' ? v : undefined)) + .pipe(z.union([z.enum(['vertical', 'horizontal']), z.undefined()])) + .optional(), + command: OptionalString, + env: z.record(z.string(), z.string()).optional(), + telemetrySource: z.enum(TERMINAL_PANE_SPLIT_SOURCES).optional() +}) + +export const TerminalStop = z.object({ + worktree: requiredString('Missing worktree selector') +}) + +export const TerminalCloseAll = TerminalStop + +export const TerminalSleep = TerminalStop + +export const TerminalStopExact = TerminalStop.extend({ + expectedPtyIds: z.array(requiredString('Missing PTY ID')).min(1), + keepHistory: z.boolean().optional(), + targetOnly: z.boolean().optional() +}) + +export const AgentTeamsTmuxCompat = z.object({ + teamId: requiredString('Missing agent team ID'), + token: requiredString('Missing agent team token'), + envPane: requiredString('Missing tmux pane identity'), + cwd: OptionalString, + argv: z.array(z.string()) +}) + +export const AgentTeamsPrepareLaunch = z.object({ + paneKey: requiredString('Missing pane key'), + env: z.record(z.string(), z.string()).optional() +}) diff --git a/src/shared/rpc-contract/terminal-viewport-methods-params.ts b/src/shared/rpc-contract/terminal-viewport-methods-params.ts new file mode 100644 index 00000000000..f0aba484f63 --- /dev/null +++ b/src/shared/rpc-contract/terminal-viewport-methods-params.ts @@ -0,0 +1,3 @@ +import { z } from 'zod' + +export const TerminalGetAutoRestoreFitParams = z.object({}) diff --git a/src/shared/rpc-contract/terminal-viewport-schemas-params.ts b/src/shared/rpc-contract/terminal-viewport-schemas-params.ts new file mode 100644 index 00000000000..aac38a1858e --- /dev/null +++ b/src/shared/rpc-contract/terminal-viewport-schemas-params.ts @@ -0,0 +1,51 @@ +import { z } from 'zod' +import { requiredString } from './rpc-param-primitives' + +export const TerminalHandle = z.object({ terminal: requiredString('Missing terminal handle') }) + +export const TerminalSetDisplayMode = TerminalHandle.extend({ + // Why: 'auto' = mobile drives dims while subscribed (desktop restores on last-leave); 'desktop' = no resize, mobile scales to fit. + mode: z.enum(['auto', 'desktop']), + // Why: identifies the caller for the driver state machine; optional for older mobile clients. + client: z + .object({ + id: requiredString('Missing client ID'), + type: z.enum(['mobile', 'desktop']).default('desktop').optional() + }) + .optional(), + // Why: carries the measured viewport so an 'auto' toggle on a viewport-less record can phone-fit instead of no-op'ing. + viewport: z + .object({ + cols: z.number().int().positive(), + rows: z.number().int().positive() + }) + .optional() +}) + +export const TerminalUnsubscribe = z.object({ + subscriptionId: requiredString('Missing subscription ID'), + // Why: lets the server rebuild the composite `${terminal}:${clientId}` cleanup key when older clients pass a bare subscriptionId (docs/mobile-presence-lock.md). + client: z + .object({ + id: requiredString('Missing client ID') + }) + .optional() +}) + +// Why: in-place update avoids an unsubscribe→resubscribe that flashed the lock banner and stranded the PTY at phone dims (docs/mobile-presence-lock.md). +export const TerminalUpdateViewport = TerminalHandle.extend({ + client: z.object({ + id: requiredString('Missing client ID'), + type: z.enum(['mobile', 'desktop']).default('mobile').optional() + }), + viewport: z.object({ + cols: z.number().int().min(20).max(240), + rows: z.number().int().min(8).max(120) + }), + claim: z.boolean().optional() +}) + +// Why: phone-fit auto-restore preference (docs/mobile-fit-hold.md); `null` = Indefinite, finite ms clamped to [5_000, 60min] server-side. +export const TerminalSetAutoRestoreFit = z.object({ + ms: z.number().nullable() +}) diff --git a/src/shared/rpc-contract/ui-update-value-tolerance-params.ts b/src/shared/rpc-contract/ui-update-value-tolerance-params.ts new file mode 100644 index 00000000000..1b8ca0c2cd4 --- /dev/null +++ b/src/shared/rpc-contract/ui-update-value-tolerance-params.ts @@ -0,0 +1,25 @@ +import type { z } from 'zod' + +/** + * `UiUpdate` rides App.tsx's debounced writer, so one drifted enum member used + * to fail the WHOLE batch and silently drop sidebar widths, filters and agent + * acks alongside it. Degrade instead: a value the schema cannot express is + * dropped from the payload and the rest of the batch still lands. Unknown KEYS + * stay a hard rejection — the parity assertions exist to catch those. + */ +export function tolerateUnknownValues(shape: TShape): TShape { + return Object.fromEntries( + Object.entries(shape).map(([key, schema]) => [ + key, + (schema as z.ZodType).catch(() => undefined) + ]) + ) as unknown as TShape +} + +/** Drops the `undefined` entries `tolerateUnknownValues` leaves behind, so a + * rejected value reads as absent rather than as an explicit clear. */ +export function omitUndefinedValues>(value: TValue): TValue { + return Object.fromEntries( + Object.entries(value).filter(([, entry]) => entry !== undefined) + ) as TValue +} diff --git a/src/shared/rpc-contract/updater-params.ts b/src/shared/rpc-contract/updater-params.ts new file mode 100644 index 00000000000..8020f126712 --- /dev/null +++ b/src/shared/rpc-contract/updater-params.ts @@ -0,0 +1,6 @@ +import { z } from 'zod' + +export const UpdaterCheckParams = z.object({ + includePrerelease: z.boolean().optional(), + includePerfPrerelease: z.boolean().optional() +}) diff --git a/src/shared/rpc-contract/workspace-cleanup-ui-params.ts b/src/shared/rpc-contract/workspace-cleanup-ui-params.ts new file mode 100644 index 00000000000..ebe35ff4826 --- /dev/null +++ b/src/shared/rpc-contract/workspace-cleanup-ui-params.ts @@ -0,0 +1,28 @@ +import { z } from 'zod' +import { normalizeWorkspaceCleanupBrowseState } from '../workspace-cleanup-browse-state' +import type { WorkspaceCleanupBrowseState } from '../workspace-cleanup-browse-state' + +export const WorkspaceCleanupDismissal = z.object({ + worktreeId: z.string(), + dismissedAt: z.number().finite(), + fingerprint: z.string(), + classifierVersion: z.number().finite(), + executionHostId: z.string().min(1).optional() +}) + +/** + * Deliberately unvalidated shape, then normalized: the filter groups must NOT be + * strict or enumerated here. A newer client sends filters this build has never + * heard of, and a per-field zod shape would reject the whole `ui.set` payload + * instead of persisting the parts the host does understand. The shared + * normalizer never throws and degrades field by field, so an older host narrows + * the state rather than refusing it. + */ +export const WorkspaceCleanupBrowse = z + .custom() + .transform((value) => normalizeWorkspaceCleanupBrowseState(value)) + +export const WorkspaceCleanup = z.object({ + dismissals: z.record(z.string(), WorkspaceCleanupDismissal), + browse: WorkspaceCleanupBrowse.optional() +}) diff --git a/src/shared/rpc-contract/workspace-ports-params.ts b/src/shared/rpc-contract/workspace-ports-params.ts new file mode 100644 index 00000000000..300f0e84fb1 --- /dev/null +++ b/src/shared/rpc-contract/workspace-ports-params.ts @@ -0,0 +1,12 @@ +import { z } from 'zod' +import { OptionalString, requiredNumber } from './rpc-param-primitives' + +export const WorkspacePortScanParams = z.object({ + repoId: OptionalString +}) + +export const WorkspacePortKillParams = z.object({ + repoId: OptionalString, + pid: requiredNumber('Missing process id'), + port: requiredNumber('Missing port') +}) diff --git a/src/shared/rpc-contract/worktree-create-params.ts b/src/shared/rpc-contract/worktree-create-params.ts new file mode 100644 index 00000000000..7c0b1f55fad --- /dev/null +++ b/src/shared/rpc-contract/worktree-create-params.ts @@ -0,0 +1,154 @@ +import { z } from 'zod' +import { WorkspaceLinkedItemSchema } from '../workspace-linked-item-schema' +import { TaskSourceContextSchema } from '../task-source-context-schema' +import { workspaceSourceSchema } from '../telemetry-events' +import { RUNTIME_NAVIGATION_TARGETS } from '../runtime-navigation' +import { sleepingAgentLaunchConfigSchema } from '../workspace-session-sleeping-agents' +import { isTuiAgent } from '../tui-agent-config' +import { + OptionalBoolean, + OptionalFiniteNumber, + OptionalString, + TriStateLinkedIssue +} from './rpc-param-primitives' +import { + AutomationWorkspaceProvenanceRequest, + CliWorkspaceProvenanceRequest, + OptionalTuiAgent, + assertLinkedWorkItemSourceContextMatch +} from './worktree-params' + +export const WorktreeCreate = z + .object({ + repo: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing repo selector')), + name: OptionalString, + /** Set by clients that fell back to a generated creature name. Absent means user-typed, so the + * host neither skips a retired candidate nor retires the name it lands on. */ + nameWasGenerated: z.boolean().optional(), + baseBranch: OptionalString, + compareBaseRef: OptionalString, + branchNameOverride: OptionalString, + linkedIssue: TriStateLinkedIssue, + linkedPR: TriStateLinkedIssue, + linkedLinearIssue: z.string().optional(), + linkedLinearIssueWorkspaceId: z.union([z.string(), z.null()]).optional(), + linkedLinearIssueOrganizationUrlKey: z.union([z.string(), z.null()]).optional(), + linkedGitLabMR: TriStateLinkedIssue, + linkedGitLabIssue: TriStateLinkedIssue, + linkedBitbucketPR: TriStateLinkedIssue, + linkedAzureDevOpsPR: TriStateLinkedIssue, + linkedGiteaPR: TriStateLinkedIssue, + linkedWorkItem: WorkspaceLinkedItemSchema.nullable().optional(), + linkedTaskSourceContext: TaskSourceContextSchema.nullable().optional(), + comment: OptionalString, + displayName: OptionalString, + displayNameKind: z.enum(['generated', 'user']).optional(), + telemetrySource: z + .unknown() + .transform((value) => { + const parsed = workspaceSourceSchema.safeParse(value) + return parsed.success ? parsed.data : undefined + }) + .optional(), + workspaceStatus: OptionalString, + manualOrder: OptionalFiniteNumber, + sparseCheckout: z + .object({ + directories: z.array(z.string()), + presetId: OptionalString + }) + .optional(), + pushTarget: z + .object({ + remoteName: z.string(), + branchName: z.string(), + remoteUrl: OptionalString + }) + .optional(), + runHooks: OptionalBoolean, + activate: OptionalBoolean, + // Why: activation on create is view intent, so it is addressed like worktree.activate. + // Contract: a paired desktop/web caller resolves to 'caller' and therefore receives NO + // activateWorktree event — it must reveal from this call's result, which carries setup, + // startup and defaultTabs. Pass an explicit target to opt into an all-surface reveal. + navigation: z.enum(RUNTIME_NAVIGATION_TARGETS).optional(), + parentWorkspace: OptionalString, + // Why: an app-selected parent is a manual action, not the CLI's `--parent-workspace` flag. + // Absent keeps the CLI provenance older clients rely on. + parentWorkspaceOrigin: z.literal('manual').optional(), + envParentWorkspace: OptionalString, + parentWorktree: OptionalString, + cwdParentWorktree: OptionalString, + noParent: OptionalBoolean, + callerTerminalHandle: OptionalString, + orchestrationContext: z + .object({ + parentWorktreeId: OptionalString, + orchestrationRunId: OptionalString, + taskId: OptionalString, + coordinatorHandle: OptionalString + }) + .optional(), + setupDecision: z + .unknown() + .transform((v) => + typeof v === 'string' && (v === 'run' || v === 'skip' || v === 'inherit') ? v : undefined + ) + .pipe(z.union([z.enum(['run', 'skip', 'inherit']), z.undefined()])) + .optional(), + // Why: some clients (e.g. desktop) pass a pre-built launch command so the + // first terminal pane launches the selected agent instead of an idle shell. + // Clients that can't quote for the host shell send `startupAgent` instead. + startupCommand: OptionalString, + startupEnv: z.record(z.string(), z.string()).optional(), + startupLaunchConfig: sleepingAgentLaunchConfigSchema, + startupCommandDelivery: z.enum(['fast', 'shell-ready']).optional(), + // Why: CLI clients should not hardcode agent launch quoting because SSH + // workspaces execute in a different shell than the client process. + startupAgent: OptionalTuiAgent, + startupPrompt: OptionalString, + // Why: task-driven mobile creates need desktop parity: the host chooses + // the same default/detected agent and drafts the linked issue/PR URL into it. + startupDraft: OptionalString, + createdWithAgent: z + .unknown() + .transform((value) => (isTuiAgent(value) ? value : undefined)) + .optional(), + // Why: mobile retries a create interrupted by a connection migration with the + // same key so the host dedupes instead of spawning a duplicate worktree. + clientMutationId: z.string().min(1).max(128).optional(), + automationProvenanceRequest: AutomationWorkspaceProvenanceRequest.optional(), + cliProvenanceRequest: CliWorkspaceProvenanceRequest.optional() + }) + .superRefine((params, ctx) => { + assertLinkedWorkItemSourceContextMatch(params, ctx) + if ((params.parentWorkspace || params.parentWorktree) && params.noParent === true) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: 'Choose either one parent selector or --no-parent.' + }) + } + if (params.parentWorkspace && params.parentWorktree) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: 'Choose either one parent selector or --no-parent.' + }) + } + if (params.startupPrompt !== undefined && params.startupAgent === undefined) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: 'startupPrompt requires startupAgent' + }) + } + }) + +export const WorktreePrefetchCreateBase = z.object({ + repo: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing repo selector')), + baseBranch: OptionalString +}) diff --git a/src/shared/rpc-contract/worktree-params.ts b/src/shared/rpc-contract/worktree-params.ts new file mode 100644 index 00000000000..00ed7627f9d --- /dev/null +++ b/src/shared/rpc-contract/worktree-params.ts @@ -0,0 +1,215 @@ +import { z } from 'zod' +import { normalizeExecutionHostId } from '../execution-host' +import { isTuiAgent } from '../tui-agent-config' +import type { TuiAgent } from '../tui-agent' +import { + OptionalBoolean, + OptionalFiniteNumber, + OptionalPlainString, + OptionalString, + TriStateLinkedIssue +} from './rpc-param-primitives' +import { RUNTIME_NAVIGATION_TARGETS } from '../runtime-navigation' +import { WorkspaceLinkedItemSchema } from '../workspace-linked-item-schema' +import { TaskSourceContextSchema } from '../task-source-context-schema' +import { isWorkspaceLinkedItemSourceContextMatch } from '../workspace-linked-item-source-context' + +export const OptionalExecutionHostId = z + .string() + .transform((value, ctx) => { + const hostId = normalizeExecutionHostId(value) + if (!hostId) { + ctx.addIssue({ code: 'custom', message: 'Invalid host id' }) + return z.NEVER + } + return hostId + }) + .optional() + +export const OptionalTuiAgent = z + .unknown() + .superRefine((value, ctx) => { + if (value !== undefined && !isTuiAgent(value)) { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Unknown TUI agent' }) + } + }) + .transform((value): TuiAgent | undefined => (isTuiAgent(value) ? value : undefined)) + .optional() + +export const AutomationWorkspaceProvenanceRequest = z.object({ + automationId: z.string(), + automationRunId: z.string(), + dispatchToken: z.string(), + createRequestId: z.string() +}) + +// Why no dispatch token (unlike automation provenance): this is a descriptive +// origin marker for sidebar filtering, not an authority grant. The host stamps +// createdAt itself so a client clock can't skew sort order. +export const CliWorkspaceProvenanceRequest = z.object({ + callerTerminalHandle: OptionalString +}) + +export const WorktreeListParams = z.object({ + repo: OptionalString, + limit: OptionalFiniteNumber +}) + +export const WorktreeDetectedListParams = z.object({ + repo: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing repo selector')) +}) + +export const WorktreeTeardownMissingTerminalsParams = WorktreeDetectedListParams.extend({ + worktreeIds: z.array(z.string().min(1)).max(10_000), + connectionId: z.string().nullable().optional() +}) + +export const WorktreePsParams = z.object({ + limit: OptionalFiniteNumber, + afterSnapshotId: z.string().min(1).max(128).nullable().optional(), + supportsWorktreeVisibilitySourceDefaults: z.literal(true).optional() +}) + +export const WorktreeSortOrder = z.object({ + orderedIds: z.array(z.string()) +}) + +export const WorktreeSelector = z.object({ + worktree: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing worktree selector')) +}) + +export const WorktreeActivate = WorktreeSelector.extend({ + notifyClients: OptionalBoolean, + navigation: z.enum(RUNTIME_NAVIGATION_TARGETS).optional() +}) + +/** Shared by WorktreeCreate and WorktreeSet so the two error messages cannot drift. */ +export function assertLinkedWorkItemSourceContextMatch( + params: { + linkedWorkItem?: z.infer | null + linkedTaskSourceContext?: z.infer | null + }, + ctx: z.RefinementCtx +): void { + if ( + params.linkedWorkItem && + params.linkedTaskSourceContext && + !isWorkspaceLinkedItemSourceContextMatch(params.linkedWorkItem, params.linkedTaskSourceContext) + ) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: 'Linked work item and source context identities must match' + }) + } +} + +export const WorktreeSet = WorktreeSelector.extend({ + // Why: '' is the blanking contract — "fall back to the branch/folder name". + // OptionalString coerced it to undefined, so on remote/SSH hosts clearing the + // name was dropped here and the old name came back on the next refresh. + displayName: OptionalPlainString, + // Why: empty comments are meaningful metadata updates, so use the plain + // string parser instead of OptionalString's empty-as-undefined behavior. + comment: OptionalPlainString, + linkedIssue: TriStateLinkedIssue, + linkedPR: TriStateLinkedIssue, + suppressedGitHubPR: z.number().int().positive().nullable().optional(), + linkedLinearIssue: z.union([z.string(), z.null()]).optional(), + linkedLinearIssueWorkspaceId: z.union([z.string(), z.null()]).optional(), + linkedLinearIssueOrganizationUrlKey: z.union([z.string(), z.null()]).optional(), + linkedGitLabMR: TriStateLinkedIssue, + linkedGitLabIssue: TriStateLinkedIssue, + linkedBitbucketPR: TriStateLinkedIssue, + linkedAzureDevOpsPR: TriStateLinkedIssue, + linkedGiteaPR: TriStateLinkedIssue, + linkedWorkItem: WorkspaceLinkedItemSchema.nullable().optional(), + linkedTaskSourceContext: TaskSourceContextSchema.nullable().optional(), + isArchived: OptionalBoolean, + isUnread: OptionalBoolean, + isPinned: OptionalBoolean, + sortOrder: OptionalFiniteNumber, + manualOrder: OptionalFiniteNumber, + lastActivityAt: OptionalFiniteNumber, + createdAt: OptionalFiniteNumber, + sparseDirectories: z.array(z.string()).optional(), + sparseBaseRef: OptionalString, + sparsePresetId: OptionalString, + baseRef: OptionalString, + workspaceStatus: OptionalString, + pushTarget: z + .object({ + remoteName: z.string(), + branchName: z.string(), + remoteUrl: OptionalString + }) + .nullable() + .optional(), + diffComments: z.array(z.unknown()).optional(), + mobileDiffReview: z.unknown().optional(), + parentWorktree: OptionalString, + noParent: OptionalBoolean +}).superRefine((params, ctx) => { + assertLinkedWorkItemSourceContextMatch(params, ctx) + if (params.parentWorktree && params.noParent === true) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: 'Choose either --parent-worktree or --no-parent, not both.' + }) + } +}) + +export const WorktreeRemove = WorktreeSelector.extend({ + hostId: OptionalExecutionHostId, + force: OptionalBoolean, + // Why (#11960): the CLI's --force is an unambiguous force affordance, but the + // desktop sets `force` for an ordinary confirmed delete too, so the PTY-stop + // waiver travels on its own field. + allowUnverifiedPtyStop: OptionalBoolean, + runHooks: OptionalBoolean +}) + +export const WorktreeForceDeleteBranch = WorktreeSelector.extend({ + hostId: OptionalExecutionHostId, + branchName: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing branch name')), + expectedHead: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing expected branch head')) +}) + +export const WorktreeResolvePrBase = z.object({ + repo: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing repo selector')), + prNumber: z + .unknown() + .transform((v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0)) + .pipe(z.number().int().positive('Missing PR number')), + headRefName: OptionalString, + baseRefName: OptionalString, + isCrossRepository: OptionalBoolean +}) + +export const WorktreeResolveMrBase = z.object({ + repo: z + .unknown() + .transform((v) => (typeof v === 'string' ? v : '')) + .pipe(z.string().min(1, 'Missing repo selector')), + mrIid: z + .unknown() + .transform((v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0)) + .pipe(z.number().int().positive('Missing MR number')), + sourceBranch: OptionalString, + targetBranch: OptionalString, + isCrossRepository: OptionalBoolean +}) diff --git a/src/shared/rpc-contract/worktree-visibility-defaults-params.ts b/src/shared/rpc-contract/worktree-visibility-defaults-params.ts new file mode 100644 index 00000000000..c03199d78db --- /dev/null +++ b/src/shared/rpc-contract/worktree-visibility-defaults-params.ts @@ -0,0 +1,19 @@ +import { z } from 'zod' +import { + normalizeCustomWorktreeVisibilitySources, + normalizeWorktreeVisibilitySourcePreferences +} from '../worktree/visibility-sources' + +export const WorktreeVisibilityDefaultsUpdate = z + .object({ + external: z.enum(['hide', 'show']).optional(), + customSources: z + .unknown() + .transform((value) => normalizeCustomWorktreeVisibilitySources(value)) + .optional(), + sourcePreferences: z + .unknown() + .transform((value) => normalizeWorktreeVisibilitySourcePreferences(value)) + .optional() + }) + .strict() diff --git a/src/shared/runtime-host-status-owner.test.ts b/src/shared/runtime-host-status-owner.test.ts new file mode 100644 index 00000000000..32331991988 --- /dev/null +++ b/src/shared/runtime-host-status-owner.test.ts @@ -0,0 +1,207 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { RuntimeHostStatusOwner } from './runtime-host-status-owner' +import { runtimeHostStatusFailure, type RuntimeHostStatusResponse } from './runtime-host-status' +import type { RuntimeStatus } from './runtime-types' + +const owners: RuntimeHostStatusOwner[] = [] +beforeEach(() => vi.useFakeTimers()) +afterEach(() => { + owners.splice(0).forEach((owner) => owner.dispose()) + vi.useRealTimers() +}) +function success(runtimeId = 'host-1'): RuntimeHostStatusResponse & { ok: true } { + return { + id: 'status', + ok: true, + result: { runtimeId, capabilities: [] } as unknown as RuntimeStatus, + _meta: { runtimeId } + } +} +function deferred() { + let resolve!: (response: RuntimeHostStatusResponse) => void + const promise = new Promise((done) => { + resolve = done + }) + return { promise, resolve } +} +function createOwner(persistent = false) { + const request = vi + .fn<(signal: AbortSignal) => Promise>() + .mockResolvedValue(success()) + const publish = vi.fn() + const verified = vi.fn((_response: RuntimeHostStatusResponse, _active: boolean) => persistent) + const owner = new RuntimeHostStatusOwner({ + environmentId: 'env-a', + pairingRevision: 1, + persistent, + request, + publish, + verified + }) + owners.push(owner) + return { owner, request, publish, verified } +} + +it('shares one verification between viewers with independent deadlines', async () => { + const { owner, request } = createOwner() + const pending = deferred() + request.mockReturnValue(pending.promise) + const impatient = owner.refresh({ timeoutMs: 100 }) + const patient = owner.refresh({ timeoutMs: 1_000 }) + await vi.advanceTimersByTimeAsync(100) + expect((await impatient).ok).toBe(false) + expect(request).toHaveBeenCalledOnce() + expect(request.mock.calls[0][0].aborted).toBe(false) + pending.resolve(success()) + expect((await patient).ok).toBe(true) +}) + +it('uses ready transitions, not diagnostic updates or a healthy polling timer', async () => { + const { owner, request } = createOwner(true) + await owner.refresh() + owner.connectionChanged('ready') + await vi.advanceTimersByTimeAsync(0) + owner.connectionChanged('ready') + await vi.advanceTimersByTimeAsync(300_000) + expect(request).toHaveBeenCalledTimes(2) + owner.connectionChanged('disconnected') + await vi.advanceTimersByTimeAsync(300_000) + expect(request).toHaveBeenCalledTimes(2) + owner.connectionChanged('ready') + await vi.advanceTimersByTimeAsync(0) + expect(request).toHaveBeenCalledTimes(3) +}) + +it('retries a failed status operation while retaining healthy transport and last good metadata', async () => { + const { owner, request } = createOwner(true) + owner.connectionChanged('ready') + await owner.refresh() + request.mockResolvedValueOnce(runtimeHostStatusFailure('runtime_unavailable', 'status timed out')) + await owner.refresh() + expect(owner.read()).toMatchObject({ + transport: 'ready', + verification: 'unavailable', + status: { runtimeId: 'host-1' } + }) + await vi.advanceTimersByTimeAsync(3_000) + expect(owner.read().verification).toBe('verified') + expect(request).toHaveBeenCalledTimes(3) +}) + +it('retires a lost-socket request before explicit fallback and rejects its late result', async () => { + const { owner, request } = createOwner(true) + owner.connectionChanged('ready') + const old = deferred() + request.mockReturnValueOnce(old.promise) + const waiting = owner.refresh() + owner.connectionChanged('disconnected') + expect(request.mock.calls[0][0].aborted).toBe(true) + request.mockResolvedValueOnce(success('fallback-host')) + expect((await owner.refresh()).ok).toBe(true) + expect((await waiting).ok).toBe(true) + old.resolve(success('obsolete-host')) + await vi.advanceTimersByTimeAsync(0) + expect(owner.read().status?.runtimeId).toBe('fallback-host') + owner.connectionChanged('ready') + await vi.advanceTimersByTimeAsync(0) + expect(request).toHaveBeenCalledTimes(3) +}) + +it('a reconnect transfers waiting readers to a fresh verification', async () => { + const { owner, request } = createOwner(true) + owner.connectionChanged('ready') + const old = deferred() + request.mockReturnValueOnce(old.promise) + const waiting = owner.refresh() + owner.connectionChanged('disconnected') + owner.connectionChanged('ready') + expect((await waiting).ok).toBe(true) + old.resolve(success('old')) + await vi.advanceTimersByTimeAsync(0) + expect(owner.read().status?.runtimeId).toBe('host-1') +}) + +it('disconnect settles readers and prevents late results and retry resurrection', async () => { + const { owner, request, publish } = createOwner() + const old = deferred() + request.mockReturnValue(old.promise) + const waiting = owner.refresh() + owner.dispose() + expect((await waiting).ok).toBe(false) + const sequence = owner.read().sequence + old.resolve(success()) + owner.connectionChanged('ready') + await vi.advanceTimersByTimeAsync(300_000) + expect(owner.read()).toMatchObject({ retired: true, sequence }) + expect(publish.mock.lastCall?.[0].retired).toBe(true) + expect(request).toHaveBeenCalledOnce() +}) + +it('passive reads create neither standing retries nor connection intent', async () => { + const { owner, request, verified } = createOwner() + request.mockResolvedValueOnce(runtimeHostStatusFailure('runtime_unavailable', 'offline')) + await owner.refresh({ observeOnly: true }) + await vi.advanceTimersByTimeAsync(300_000) + expect(request).toHaveBeenCalledOnce() + await owner.refresh({ observeOnly: true }) + expect(verified.mock.lastCall?.[1]).toBe(false) +}) + +it('authentication rejection blocks automatic verification until explicit reconnect', async () => { + const { owner, request } = createOwner(true) + owner.connectionChanged('ready') + request.mockResolvedValueOnce(runtimeHostStatusFailure('unauthorized', 're-pair')) + await owner.refresh() + owner.connectionChanged('disconnected') + owner.connectionChanged('ready') + await vi.advanceTimersByTimeAsync(300_000) + expect(request).toHaveBeenCalledOnce() + expect((await owner.refresh({ reconnect: true })).ok).toBe(true) +}) + +it('blocks a rejected reconnect even without an outstanding status request', async () => { + const { owner, request } = createOwner(true) + owner.connectionChanged('ready') + await owner.refresh() + owner.connectionChanged('disconnected') + owner.authenticationRejected() + expect(owner.read()).toMatchObject({ verification: 'blocked', status: { runtimeId: 'host-1' } }) + owner.connectionChanged('ready') + await vi.advanceTimersByTimeAsync(300_000) + expect(request).toHaveBeenCalledOnce() +}) + +it('cancelling one reader leaves the shared request available to other readers', async () => { + const { owner, request } = createOwner() + const pending = deferred() + request.mockReturnValue(pending.promise) + const controller = new AbortController() + const cancelled = owner.refresh({ signal: controller.signal }) + const remaining = owner.refresh() + const rejection = expect(cancelled).rejects.toThrow('cancelled') + controller.abort(new Error('cancelled')) + await rejection + expect(request.mock.calls[0][0].aborted).toBe(false) + pending.resolve(success()) + expect((await remaining).ok).toBe(true) +}) + +it.each(['unknown', 'ready'] as const)( + 'distinguishes the caller deadline with %s transport', + async (transport) => { + const { owner, request } = createOwner() + owner.connectionChanged(transport) + request.mockReturnValue(deferred().promise) + const response = owner.refresh({ timeoutMs: 100 }) + await vi.advanceTimersByTimeAsync(100) + expect(await response).toMatchObject({ + ok: false, + error: { + message: + transport === 'ready' + ? 'Status request timed out.' + : 'Timed out waiting for the remote Orca runtime.' + } + }) + } +) diff --git a/src/shared/runtime-host-status-owner.ts b/src/shared/runtime-host-status-owner.ts new file mode 100644 index 00000000000..d9c52395c89 --- /dev/null +++ b/src/shared/runtime-host-status-owner.ts @@ -0,0 +1,274 @@ +import { + isRuntimeHostStatusBlocked, + runtimeHostStatusError, + runtimeHostStatusFailure, + type RuntimeHostStatusResponse, + type RuntimeHostStatusSnapshot +} from './runtime-host-status' + +const RETRY_DELAYS_MS = [3_000, 6_000, 12_000, 30_000, 60_000] +const REQUEST_TIMEOUT_MS = 15_000 +let publicationSequence = 0 + +type Waiter = { + resolve: (response: RuntimeHostStatusResponse) => void + cleanup: () => void +} + +type StatusOwnerOptions = { + environmentId: string + pairingRevision: number + persistent?: boolean + request: (signal: AbortSignal) => Promise + verified: (response: Extract, active: boolean) => boolean + publish: (snapshot: RuntimeHostStatusSnapshot) => void +} + +/** One verification and one retry slot, shared by all readers of this connection. */ +export class RuntimeHostStatusOwner { + private active = false + private disposed = false + private persistent: boolean + private attempt = 0 + private retry: ReturnType | null = null + private request: AbortController | null = null + private readonly waiters = new Set() + private response: RuntimeHostStatusResponse = runtimeHostStatusFailure( + 'runtime_unavailable', + 'Status has not been checked.' + ) + private snapshot: RuntimeHostStatusSnapshot + + constructor(private readonly options: StatusOwnerOptions) { + this.persistent = options.persistent ?? false + this.snapshot = { + environmentId: options.environmentId, + pairingRevision: options.pairingRevision, + sequence: ++publicationSequence, + checkedAt: 0, + status: null, + verification: 'checking', + transport: 'unknown' + } + } + + read(): RuntimeHostStatusSnapshot { + return this.snapshot + } + + activate(): void { + if (this.active || this.disposed) { + return + } + this.active = true + this.startRequest() + } + + acceptVerified(response: Extract): void { + if (this.disposed) { + return + } + this.active = true + this.retireRequest() + this.clearRetry() + this.complete(response) + } + + refresh( + options: { timeoutMs?: number; observeOnly?: true; reconnect?: true; signal?: AbortSignal } = {} + ): Promise { + if (options.signal?.aborted) { + return Promise.reject(options.signal.reason) + } + if (this.disposed) { + return Promise.resolve(this.response) + } + if (!options.observeOnly) { + this.active = true + } + if (options.reconnect) { + this.attempt = 0 + this.update({ verification: 'checking' }) + } + if (this.snapshot.verification === 'blocked') { + return Promise.resolve(this.response) + } + const result = new Promise((resolve, reject) => { + const release = (): void => { + waiter.cleanup() + this.waiters.delete(waiter) + if (!this.active && this.waiters.size === 0) { + this.retireRequest() + } + } + const abort = (): void => { + release() + reject(options.signal?.reason) + } + const timer = setTimeout(() => { + release() + resolve( + runtimeHostStatusFailure( + 'runtime_unavailable', + this.snapshot.transport === 'ready' + ? 'Status request timed out.' + : 'Timed out waiting for the remote Orca runtime.' + ) + ) + }, options.timeoutMs ?? REQUEST_TIMEOUT_MS) + const waiter: Waiter = { + resolve, + cleanup: () => { + clearTimeout(timer) + options.signal?.removeEventListener('abort', abort) + } + } + this.waiters.add(waiter) + options.signal?.addEventListener('abort', abort, { once: true }) + }) + this.startRequest() + return result + } + + connectionChanged( + transport: RuntimeHostStatusSnapshot['transport'], + remoteControl?: RuntimeHostStatusSnapshot['remoteControl'] + ): void { + if (this.disposed) { + return + } + const previous = this.snapshot.transport + this.update({ transport, ...(remoteControl !== undefined ? { remoteControl } : {}) }) + if (transport === previous) { + return + } + if (previous === 'ready') { + this.retireRequest() + this.clearRetry() + if (this.snapshot.verification !== 'blocked') { + this.update({ verification: 'unavailable' }) + } + } + if (transport === 'ready' && this.snapshot.verification !== 'blocked') { + // A pre-reconnect answer cannot verify the new socket's runtime. + this.retireRequest() + if (this.active || this.waiters.size > 0) { + this.startRequest() + } + } + } + + authenticationRejected(): void { + if (this.disposed) { + return + } + this.retireRequest() + this.clearRetry() + this.complete(runtimeHostStatusFailure('unauthorized', 'Pair this client again.')) + } + + dispose(): void { + if (this.disposed) { + return + } + this.disposed = true + this.active = false + this.retireRequest() + this.clearRetry() + this.response = runtimeHostStatusFailure( + 'runtime_manually_disconnected', + 'Runtime environment was disconnected or replaced.' + ) + this.update({ retired: true, transport: 'disconnected', verification: 'blocked' }) + this.settleWaiters() + } + + private startRequest(): void { + if (this.disposed || this.request || this.snapshot.verification === 'blocked') { + return + } + this.clearRetry() + const controller = new AbortController() + this.request = controller + if (this.snapshot.verification !== 'verified') { + this.update({ verification: 'checking' }) + } + void this.verify(controller) + } + + private async verify(controller: AbortController): Promise { + let response: RuntimeHostStatusResponse + try { + response = await this.options.request(controller.signal) + } catch (error) { + response = runtimeHostStatusError(error) + if (error instanceof TypeError || error instanceof SyntaxError) { + console.error('Runtime status verification failed:', error) + response = runtimeHostStatusFailure('invalid_runtime_response', error.message) + } + } + if (this.request !== controller || this.disposed) { + return + } + this.request = null + this.complete(response) + } + + private complete(response: RuntimeHostStatusResponse): void { + this.response = response + if (response.ok) { + this.attempt = 0 + this.update({ status: response.result, checkedAt: Date.now(), verification: 'verified' }) + this.persistent = this.options.verified(response, this.active) + } else { + this.update({ + checkedAt: Date.now(), + verification: isRuntimeHostStatusBlocked(response) ? 'blocked' : 'unavailable' + }) + this.scheduleRetry() + } + this.settleWaiters() + } + + private scheduleRetry(): void { + if ( + !this.active || + this.disposed || + this.snapshot.verification === 'blocked' || + (this.persistent && this.snapshot.transport !== 'ready') + ) { + return + } + const delay = RETRY_DELAYS_MS[Math.min(this.attempt++, RETRY_DELAYS_MS.length - 1)] + this.retry = setTimeout(() => { + this.retry = null + this.startRequest() + }, delay) + } + + private settleWaiters(): void { + for (const waiter of this.waiters) { + waiter.cleanup() + waiter.resolve(this.response) + } + this.waiters.clear() + } + + private retireRequest(): void { + const request = this.request + this.request = null + request?.abort() + } + + private clearRetry(): void { + if (this.retry) { + clearTimeout(this.retry) + } + this.retry = null + } + + private update(patch: Partial): void { + this.snapshot = { ...this.snapshot, ...patch, sequence: ++publicationSequence } + this.options.publish(this.snapshot) + } +} diff --git a/src/shared/runtime-host-status.ts b/src/shared/runtime-host-status.ts new file mode 100644 index 00000000000..4dd7ff7cc22 --- /dev/null +++ b/src/shared/runtime-host-status.ts @@ -0,0 +1,44 @@ +import type { RemoteRuntimeSharedConnectionDiagnostics } from './remote-runtime-shared-control-types' +import type { RuntimeRpcFailure, RuntimeRpcResponse } from './runtime-rpc-envelope' +import type { RuntimeStatus } from './runtime-types' + +export const RUNTIME_HOST_STATUS_CHANNEL = 'runtimeEnvironments:statusChanged' + +/** Local client state; never exchanged with the paired host. */ +export type RuntimeHostStatusSnapshot = { + environmentId: string + pairingRevision: number + sequence: number + checkedAt: number + status: RuntimeStatus | null + verification: 'checking' | 'verified' | 'unavailable' | 'blocked' + transport: 'unknown' | 'connecting' | 'ready' | 'disconnected' + remoteControl?: RemoteRuntimeSharedConnectionDiagnostics | null + retired?: true +} + +export type RuntimeHostStatusResponse = RuntimeRpcResponse + +export function runtimeHostStatusFailure(code: string, message: string): RuntimeRpcFailure { + return { id: 'status.get', ok: false, error: { code, message } } +} + +export function runtimeHostStatusError(error: unknown): RuntimeRpcFailure { + const code = + error instanceof Error && 'code' in error && typeof error.code === 'string' + ? error.code + : 'runtime_unavailable' + return runtimeHostStatusFailure(code, error instanceof Error ? error.message : String(error)) +} + +export function isRuntimeHostStatusBlocked(response: RuntimeRpcFailure): boolean { + return [ + 'unauthorized', + 'forbidden', + 'invalid_argument', + 'invalid_runtime_response', + 'protocol_version_mismatch', + 'method_not_found', + 'unsupported_method' + ].includes(response.error.code) +} diff --git a/src/shared/runtime-terminal-contracts.ts b/src/shared/runtime-terminal-contracts.ts index db1c3751ba8..ad392a2b9a0 100644 --- a/src/shared/runtime-terminal-contracts.ts +++ b/src/shared/runtime-terminal-contracts.ts @@ -330,6 +330,10 @@ export type RuntimeTerminalClose = { export type RuntimeTerminalWaitCondition = 'exit' | 'tui-idle' +// Why both spellings: the codex-* members were published by every host before the agent-neutral +// rename, so they are permanent — a client still has to read them off an older host. This build +// keeps a codex-* reason only where the matched wording is plausibly Codex's own; every matcher +// that inspects no agent publishes the agent-* spelling. export type RuntimeTerminalWaitBlockedReason = | 'codex-update-prompt' | 'codex-trust-workspace' @@ -337,6 +341,11 @@ export type RuntimeTerminalWaitBlockedReason = | 'codex-model-migration-prompt' | 'codex-hooks-review-prompt' | 'codex-interactive-prompt' + | 'agent-update-prompt' + | 'agent-trust-workspace' + | 'agent-cwd-prompt' + | 'agent-hooks-review-prompt' + | 'agent-interactive-prompt' | 'agent-approval-prompt' export type RuntimeTerminalWait = { diff --git a/src/shared/structured-agent-session-composer.test.ts b/src/shared/structured-agent-session-composer.test.ts index ec3b301a8e2..b51de0396be 100644 --- a/src/shared/structured-agent-session-composer.test.ts +++ b/src/shared/structured-agent-session-composer.test.ts @@ -6,15 +6,59 @@ import { } from './structured-agent-session-composer' describe('structuredSlashCommands', () => { - // The composer menu and the dispatcher read this one list. When they disagreed, + const hostController = { + snapshot: [], + invokeAction: async () => true, + setOption: async () => true, + conversationCommands: ['clear', 'compact'] as const, + runConversationCommand: async () => ({ accepted: true, error: null }) + } + const REFUSAL = /is not available in chat sessions/ + + // The composer menu and the dispatcher read the same policy. When they disagreed, // a Claude session was offered Codex-only tokens that missed the command guard - // and reached the model as literal prompt text instead of erroring. - it.each(['codex', 'claude'] as const)('offers %s only commands it also accepts', (agent) => { - const offered = structuredSlashCommands() - expect(offered.length).toBeGreaterThan(0) - for (const command of offered) { - expect(isStructuredAgentSessionComposerCommand(`/${command.name}`, agent)).toBe(true) + // and reached the model as literal prompt text instead of erroring. A row is + // honored either way now: the host answers it, or it passes through to the agent. + it.each(['codex', 'claude'] as const)( + 'offers %s only commands the host answers or the agent runs', + async (agent) => { + const offered = structuredSlashCommands(['clear', 'compact'], agent) + expect(offered.length).toBeGreaterThan(0) + for (const command of offered) { + const outcome = await dispatchStructuredAgentSessionComposerCommand(`/${command.name}`, { + ...hostController, + agent + }) + expect(outcome.error ?? '').not.toMatch(REFUSAL) + } } + ) + + // Codex reports no catalog of its own, so this fallback is its whole `/` menu — + // without the row, a command that now works is impossible to discover. + it('offers Codex the /goal the model acts on, described from the catalog', () => { + const offered = structuredSlashCommands(['clear', 'compact'], 'codex') + expect(offered.map((command) => command.name)).toEqual([ + 'model', + 'effort', + 'clear', + 'compact', + 'goal' + ]) + expect(offered.find((command) => command.name === 'goal')?.description).toBe( + 'Set or view the goal' + ) + // Picking it must reach the model, not the host's refusal. + expect(isStructuredAgentSessionComposerCommand('/goal', 'codex')).toBe(false) + }) + + it('adds nothing for an agent whose own harness expands its commands', () => { + expect(structuredSlashCommands(['clear', 'compact'], 'claude').map((c) => c.name)).toEqual([ + 'model', + 'effort', + 'clear', + 'compact' + ]) }) it('offers only the commands a chat session can carry out', () => { @@ -98,3 +142,68 @@ describe('dispatchStructuredAgentSessionComposerCommand', () => { expect(runConversationCommand).not.toHaveBeenCalled() }) }) + +describe('agent-implemented commands pass through to the agent', () => { + const controller = { + snapshot: [], + invokeAction: async () => true, + setOption: async () => true + } + const PASSED_THROUGH = { handled: false, accepted: false, error: null } + + // Claude's harness runs a slash command it finds in the message text, so + // claiming these answered "not available" for commands that do work. + it.each(['init', 'review', 'help'] as const)( + 'sends /%s on to the Claude harness instead of refusing it', + async (name) => { + expect(isStructuredAgentSessionComposerCommand(`/${name}`, 'claude')).toBe(false) + expect( + await dispatchStructuredAgentSessionComposerCommand(`/${name}`, { + ...controller, + agent: 'claude' + }) + ).toEqual(PASSED_THROUGH) + } + ) + + it.each(['clear', 'compact', 'model', 'effort'] as const)( + 'still claims the host-owned /%s on Claude', + async (name) => { + expect(isStructuredAgentSessionComposerCommand(`/${name}`, 'claude')).toBe(true) + expect( + ( + await dispatchStructuredAgentSessionComposerCommand(`/${name}`, { + ...controller, + agent: 'claude' + }) + ).handled + ).toBe(true) + } + ) + + // Codex's app-server has no slash parser, but the model owns goal tools and + // creates a real goal from `/goal ` arriving as prose. + it('passes /goal through on Codex, arguments and all', async () => { + expect(isStructuredAgentSessionComposerCommand('/goal', 'codex')).toBe(false) + expect( + await dispatchStructuredAgentSessionComposerCommand('/goal ship the fix', { + ...controller, + agent: 'codex' + }) + ).toEqual(PASSED_THROUGH) + }) + + it('keeps refusing a Codex command the model cannot carry out', async () => { + expect(isStructuredAgentSessionComposerCommand('/permissions', 'codex')).toBe(true) + expect( + await dispatchStructuredAgentSessionComposerCommand('/permissions', { + ...controller, + agent: 'codex' + }) + ).toMatchObject({ + handled: true, + error: + '/permissions is not available in chat sessions. Use the slash menu to see available commands.' + }) + }) +}) diff --git a/src/shared/structured-agent-session-composer.ts b/src/shared/structured-agent-session-composer.ts index 70d10c34cfa..093d588effb 100644 --- a/src/shared/structured-agent-session-composer.ts +++ b/src/shared/structured-agent-session-composer.ts @@ -1,4 +1,7 @@ -import { getVerifiedNativeChatCommands } from './native-chat-agent-profiles' +import { + getHostClaimedNativeChatCommands, + getTextDrivenNativeChatCommands +} from './native-chat-agent-profiles' import type { AgentType } from './agent-status-types' import type { SessionOptionDescriptor, SessionOptionValue } from './native-chat-session-options' import type { SlashCommandSuggestion } from './native-chat-slash-commands' @@ -50,30 +53,45 @@ function commandParts(text: string): { name: string; argument: string } | null { return match ? { name: match[1]!.toLowerCase(), argument: match[2]?.trim() ?? '' } : null } -/** The commands the composer menu offers. Strictly what the dispatcher honors, - * so a menu pick is never answered with "not available". */ +/** The commands the composer menu offers when the host reports no catalog of its + * own: the host's own commands, plus the ones this agent acts on from message + * text. Both are honored — the first here, the second by the agent — so a menu + * pick is never answered with "not available". */ export function structuredSlashCommands( - commands: readonly AgentSessionConversationCommand[] = [] + commands: readonly AgentSessionConversationCommand[] = [], + agent?: AgentType | null ): readonly SlashCommandSuggestion[] { - return [ + const hostOwned = [ ...STRUCTURED_AGENT_SESSION_SLASH_COMMANDS, ...CONVERSATION_COMMANDS.filter((entry) => commands.includes(entry.name as AgentSessionConversationCommand) ) ] + // Why: a host with no catalog to report would otherwise hide the commands the + // agent itself implements, e.g. Codex's `/goal`. + return [ + ...hostOwned, + ...getTextDrivenNativeChatCommands(agent).filter( + (entry) => !hostOwned.some((offered) => offered.name === entry.name) + ) + ] } /** Wider than the offered menu on purpose: a TUI-only command still has to be * claimed here and answered, or a hand-typed `/clear` reaches the model as - * literal prompt text. */ + * literal prompt text. Commands the agent itself implements are deliberately + * absent — the profile unclaims those so they pass through as text. */ function structuredRecognizedCommands(agent: AgentType): readonly SlashCommandSuggestion[] { return [ ...STRUCTURED_AGENT_SESSION_SLASH_COMMANDS, ...CONVERSATION_COMMANDS, - ...getVerifiedNativeChatCommands(agent) + ...getHostClaimedNativeChatCommands(agent) ] } +/** Whether the chat host, rather than the agent, owns this command. Callers also + * use it to refuse attachments: a host command sends no message, so attachments + * would be silently dropped, whereas a pass-through command is a real send. */ export function isStructuredAgentSessionComposerCommand( text: string, agent: AgentType = 'codex' diff --git a/src/shared/structured-agent-session-live-turn.test.ts b/src/shared/structured-agent-session-live-turn.test.ts new file mode 100644 index 00000000000..b9ce5f2c022 --- /dev/null +++ b/src/shared/structured-agent-session-live-turn.test.ts @@ -0,0 +1,113 @@ +import { describe, expect, it } from 'vitest' +import type { AgentJournalRenderItem } from './agent-session-journal-types' +import { isStructuredAgentSessionThinking } from './structured-agent-session-live-turn' + +function item( + itemId: string, + sequence: number, + body: AgentJournalRenderItem['body'] +): AgentJournalRenderItem { + return { itemId, sequence, revision: 1, observedAt: sequence, body } +} + +describe('isStructuredAgentSessionThinking', () => { + const turnStart = item('turn-start', 1, { + kind: 'status', + text: 'Working', + turnLifecycle: { turnId: 'turn-1', state: 'running' } + }) + const reasoning = (sequence: number): AgentJournalRenderItem => + item(`reasoning-${sequence}`, sequence, { + kind: 'message', + role: 'reasoning', + blocks: [{ type: 'text', text: 'Weighing two approaches' }] + }) + + it('is true while reasoning is the newest thing the turn produced', () => { + expect(isStructuredAgentSessionThinking([turnStart, reasoning(2)])).toBe(true) + }) + + it('is false once a tool call, a message or a diff lands after the reasoning', () => { + const after = (body: AgentJournalRenderItem['body']): boolean => + isStructuredAgentSessionThinking([turnStart, reasoning(2), item('after', 3, body)]) + expect(after({ kind: 'tool-call', name: 'shell', input: null, state: 'running' })).toBe(false) + expect( + after({ kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'Here you go' }] }) + ).toBe(false) + expect( + after({ + kind: 'diff', + path: 'src/a.ts', + patch: { head: '@@', byteLength: 2, digest: 'd', truncated: false } + }) + ).toBe(false) + }) + + it('is false when a turn produced no reasoning at all', () => { + expect(isStructuredAgentSessionThinking([turnStart])).toBe(false) + expect(isStructuredAgentSessionThinking([])).toBe(false) + }) + + it('does not read an earlier turn as this one reasoning', () => { + // The scan stops at this turn's own record, so the previous turn's reasoning + // cannot leak forward into a turn that has produced nothing yet. + const newTurn = item('turn-2-start', 2, { + kind: 'status', + text: 'Working', + turnLifecycle: { turnId: 'turn-2', state: 'running' } + }) + expect(isStructuredAgentSessionThinking([reasoning(1), newTurn])).toBe(false) + }) + + it('does not read a completed turn as reasoning during the next pending dispatch', () => { + const completedTurn = item('turn-1', 1, { + kind: 'turn', + turnId: 'turn-1', + state: 'completed' + }) + expect(isStructuredAgentSessionThinking([completedTurn, reasoning(2)])).toBe(false) + }) + + it('stops at a typed turn item, the carrier this host writes', () => { + const typedTurn = (sequence: number, turnId: string): AgentJournalRenderItem => + item(`turn-${turnId}`, sequence, { kind: 'turn', turnId, state: 'running' }) + expect(isStructuredAgentSessionThinking([typedTurn(1, 'turn-1'), reasoning(2)])).toBe(true) + expect(isStructuredAgentSessionThinking([reasoning(1), typedTurn(2, 'turn-2')])).toBe(false) + }) + + it('lets an unmarked status stay transparent to the latest reasoning state', () => { + const plan = item('plan', 3, { kind: 'status', text: 'Step 1. Read the file' }) + expect(isStructuredAgentSessionThinking([turnStart, plan])).toBe(false) + expect(isStructuredAgentSessionThinking([turnStart, reasoning(2), plan])).toBe(true) + }) + + it.each([ + { + kind: 'approval' as const, + title: 'Run the command?', + detail: null, + options: [], + resolution: { + state: 'pending' as const, + selectedOptionId: null, + resolvedBy: null, + resolvedAt: null + } + }, + { + kind: 'question' as const, + question: 'Which path?', + options: [], + resolution: { + state: 'pending' as const, + selectedOptionId: null, + resolvedBy: null, + resolvedAt: null + } + } + ])('stops thinking when the turn is waiting on a $kind', (prompt) => { + expect( + isStructuredAgentSessionThinking([turnStart, reasoning(2), item('prompt', 3, prompt)]) + ).toBe(false) + }) +}) diff --git a/src/shared/structured-agent-session-live-turn.ts b/src/shared/structured-agent-session-live-turn.ts new file mode 100644 index 00000000000..319a6d7d579 --- /dev/null +++ b/src/shared/structured-agent-session-live-turn.ts @@ -0,0 +1,76 @@ +// What the newest turn in a structured journal is doing right now, read off the +// tail of the item list. Every scan here stops at the turn's own record — the +// typed `turn` item, or the legacy status row that carries one — because state +// from an earlier turn is never this turn's state. + +import type { + AgentJournalRenderItem, + AgentJournalToolCallItem +} from './agent-session-journal-types' +import { readAgentJournalTurn } from './agent-session-turn-record' + +export function activeStructuredAgentSessionTurnId( + items: readonly AgentJournalRenderItem[] +): string | null { + for (let index = items.length - 1; index >= 0; index -= 1) { + const turn = readAgentJournalTurn(items[index]?.body) + if (turn) { + return turn.state === 'running' ? turn.turnId : null + } + } + return null +} + +/** + * Whether the newest thing the active turn produced is the model's own reasoning. + * + * This is what "thinking" has to mean for the indicator to be honest: the turn is reasoning + * *right now*. The older rule — "the turn has produced no renderable output yet" — reports + * thinking while the request is merely in flight, and stops reporting it the moment a tool call + * lands, which is usually when reasoning actually starts. + */ +export function isStructuredAgentSessionThinking( + items: readonly AgentJournalRenderItem[] +): boolean { + let newestContentIsReasoning: boolean | null = null + for (let index = items.length - 1; index >= 0; index -= 1) { + const body = items[index]?.body + const turn = readAgentJournalTurn(body) + if (turn) { + return turn.state === 'running' && newestContentIsReasoning === true + } + if (newestContentIsReasoning !== null) { + continue + } + if (body?.kind === 'message') { + newestContentIsReasoning = body.role === 'reasoning' + } else if ( + body?.kind === 'tool-call' || + body?.kind === 'diff' || + body?.kind === 'approval' || + body?.kind === 'question' + ) { + newestContentIsReasoning = false + } + // Plain status copy is activity chrome, not newer transcript content. + } + return false +} + +/** The tool call the newest turn is still inside, or null when nothing is running. + * An abandoned `running` call from an earlier crashed turn can never be reported + * as live work. */ +export function activeStructuredAgentSessionToolCall( + items: readonly AgentJournalRenderItem[] +): AgentJournalToolCallItem | null { + for (let index = items.length - 1; index >= 0; index -= 1) { + const body = items[index]?.body + if (readAgentJournalTurn(body)) { + return null + } + if (body?.kind === 'tool-call' && body.state === 'running') { + return body + } + } + return null +} diff --git a/src/shared/structured-agent-session-projection.test.ts b/src/shared/structured-agent-session-projection.test.ts index 645aca4d6fe..928180e7a6c 100644 --- a/src/shared/structured-agent-session-projection.test.ts +++ b/src/shared/structured-agent-session-projection.test.ts @@ -475,6 +475,7 @@ describe('notice projection for desktop and mobile consumers', () => { it('preserves optional tool annotations for desktop and mobile projection', () => { const metadata = { + callId: 'call-1', exitCode: 127, durationMs: 400, webSearchResults: [{ title: 'Docs', url: 'https://example.com' }] diff --git a/src/shared/structured-agent-session-projection.ts b/src/shared/structured-agent-session-projection.ts index 559be217ee9..e0189ed7124 100644 --- a/src/shared/structured-agent-session-projection.ts +++ b/src/shared/structured-agent-session-projection.ts @@ -3,20 +3,26 @@ import { normalizeOptionalField, normalizePromptField } from './agent-status-field-normalization' -import type { - AgentJournalRenderItem, - AgentJournalSubmission, - AgentJournalToolCallItem -} from './agent-session-journal-types' +import type { AgentJournalRenderItem, AgentJournalSubmission } from './agent-session-journal-types' import { AGENT_STATUS_TOOL_INPUT_MAX_LENGTH, AGENT_STATUS_TOOL_NAME_MAX_LENGTH } from './agent-status-types' import { describeToolInput } from './native-chat-tool-summary' -import { readAgentJournalTurn } from './agent-session-turn-record' +import { + activeStructuredAgentSessionToolCall, + activeStructuredAgentSessionTurnId +} from './structured-agent-session-live-turn' + import type { NativeChatBlock, NativeChatMessage } from './native-chat-types' import { sha256 } from './sha256' +// Re-exported so the live-turn readers' existing consumers keep one import site. +export { + activeStructuredAgentSessionToolCall, + activeStructuredAgentSessionTurnId +} from './structured-agent-session-live-turn' + function boundedText(payload: { head: string; truncated: boolean; byteLength: number }): string { return payload.truncated ? `${payload.head}\n… (${payload.byteLength} bytes)` : payload.head } @@ -54,6 +60,7 @@ function itemBlocks(item: AgentJournalRenderItem): { name: body.name, input: body.input, state: body.state, + ...(body.callId !== undefined ? { callId: body.callId } : {}), ...(body.mcpIdentity !== undefined ? { mcpIdentity: body.mcpIdentity } : {}), ...(body.exitCode !== undefined ? { exitCode: body.exitCode } : {}), ...(body.durationMs !== undefined ? { durationMs: body.durationMs } : {}), @@ -158,18 +165,6 @@ export function projectStructuredItemToNativeChat( return message } -export function activeStructuredAgentSessionTurnId( - items: readonly AgentJournalRenderItem[] -): string | null { - for (let index = items.length - 1; index >= 0; index -= 1) { - const turn = readAgentJournalTurn(items[index]?.body) - if (turn) { - return turn.state === 'running' ? turn.turnId : null - } - } - return null -} - export function hasPersistedStructuredAgentSessionTurn( items: readonly AgentJournalRenderItem[] ): boolean { @@ -269,24 +264,6 @@ export function latestStructuredAgentSessionAssistantMessage( return '' } -/** The tool call the newest turn is still inside, or null when nothing is running. - * Scanning stops at the turn's own lifecycle row so an abandoned `running` call - * from an earlier crashed turn can never be reported as live work. */ -export function activeStructuredAgentSessionToolCall( - items: readonly AgentJournalRenderItem[] -): AgentJournalToolCallItem | null { - for (let index = items.length - 1; index >= 0; index -= 1) { - const body = items[index]?.body - if (readAgentJournalTurn(body)) { - return null - } - if (body?.kind === 'tool-call' && body.state === 'running') { - return body - } - } - return null -} - /** The activity fields a sidebar row shows beside the prompt, named as the agent-status * entry names them so the client can hand them straight to a row. */ export type StructuredAgentSessionStatusProjection = { diff --git a/src/shared/structured-agent-session-read-refusal.ts b/src/shared/structured-agent-session-read-refusal.ts new file mode 100644 index 00000000000..18487f12be3 --- /dev/null +++ b/src/shared/structured-agent-session-read-refusal.ts @@ -0,0 +1,45 @@ +/** + * The one refusal a structured-session READ can raise that is not a failure to read. + * + * `agentSession.history` and `agentSession.subscribe` both resolve the session through the host's + * `requireSession`, which raises this code when the host holds no session object by that id. That + * is never a transcript Orca could not read — it is a session this host has not attached YET (the + * surface's hold is what attaches one) or one it has just closed. Both windows end on their own: + * the first when the hold lands, the second when the chat tab retires. + * + * The genuinely latched lease — "Orca cannot prove the previous owner exited" — reaches the client + * through the ACQUISITION path instead, so narrowing on the code costs a read no real diagnosis. + * See `agent-session-lease-adjudication`. + */ + +/** Raised by a host that holds no attached session by that id. */ +export const AGENT_SESSION_UNATTACHED_REFUSAL_CODE = 'agent_session_ownership_unknown' + +/** + * How long a read may keep refusing this way before the pane is allowed to call it a failure. + * + * Both windows this code covers are sub-second in practice, so an unattached read that outlives + * this one is no longer transitional and the user is owed the error rather than a spinner that + * never resolves. + */ +export const AGENT_SESSION_UNATTACHED_READ_GRACE_MS = 5_000 + +/** + * Whether a read failure is that refusal. + * + * Takes both shapes the client sees: the thrown RPC error, whose `code` and `message` are each the + * bare refusal code, and the raw failure payload a stream delivers to its error callback. + */ +export function isUnattachedAgentSessionReadRefusal(error: unknown): boolean { + if (typeof error === 'string') { + return error === AGENT_SESSION_UNATTACHED_REFUSAL_CODE + } + if (typeof error !== 'object' || error === null) { + return false + } + const { code, message } = error as { code?: unknown; message?: unknown } + return ( + code === AGENT_SESSION_UNATTACHED_REFUSAL_CODE || + message === AGENT_SESSION_UNATTACHED_REFUSAL_CODE + ) +} diff --git a/src/shared/structured-agent-session-turn-timing.test.ts b/src/shared/structured-agent-session-turn-timing.test.ts index f1487f0ef42..769d30fab10 100644 --- a/src/shared/structured-agent-session-turn-timing.test.ts +++ b/src/shared/structured-agent-session-turn-timing.test.ts @@ -158,7 +158,7 @@ describe('host-settled turns override local observation', () => { { activeTurnKey: 'u1', isWorking: false, - hasCurrentTurnResponse: true, + thinking: false, settledByTurn: settled } ) diff --git a/src/shared/surrogate-safe-text-slice.ts b/src/shared/surrogate-safe-text-slice.ts new file mode 100644 index 00000000000..6e9e2d8d030 --- /dev/null +++ b/src/shared/surrogate-safe-text-slice.ts @@ -0,0 +1,19 @@ +// Cutting text to a length bound without splitting a character in half. +// +// JavaScript string length counts UTF-16 code units, so a raw `slice` at a +// bound can land between the two halves of an astral character — an emoji, or +// most CJK extension characters — and leave a lone surrogate that every surface +// renders as U+FFFD. + +/** Cut to `limit` UTF-16 code units without splitting a trailing surrogate pair. */ +export function sliceAtCodeUnitLimit(value: string, limit: number): string { + if (value.length <= limit) { + return value + } + const end = limit > 0 && isHighSurrogate(value.charCodeAt(limit - 1)) ? limit - 1 : limit + return value.slice(0, end) +} + +function isHighSurrogate(code: number): boolean { + return code >= 0xd800 && code <= 0xdbff +} diff --git a/src/shared/terminal-tab-types.ts b/src/shared/terminal-tab-types.ts index 1c455333ea9..d99472e2fde 100644 --- a/src/shared/terminal-tab-types.ts +++ b/src/shared/terminal-tab-types.ts @@ -1,6 +1,58 @@ import type { AiVaultSessionTitle } from './ai-vault-session-title' import type { TuiAgent } from './tui-agent' +/** Why recovery reasons live in the shared row type: the tab row carries the + * recovery ledger, and the ledger records which reason it last acted on. */ +export type TerminalPaneRecoveryReason = + | 'write-stalled' + | 'replay-wedged' + | 'input-undeliverable' + // The paired runtime that owns the PTY refused this write and said so on the + // wire. Distinct from 'input-undeliverable' because it skips the liveness + // probe: main's registry holds no entry for a `remote:` id, so `pty:hasPty` + // routes it to the local provider and answers a fabricated "dead". The + // rejection frame is the evidence instead — it came from the process that + // owns the PTY, over a connection that is by construction still up. + | 'input-rejected-by-host' + | 'reattach-unverifiable' + // A restore was requested for a certified-dead pipeline (reveal path). + | 'restore-blocked' + // A spawn resolved without a PTY id, so the pane is mounted with no transport + // binding. pty:data for the old id then lands in the pre-handler buffer, which + // ACKs it — main's delivery health stays green while the pane shows nothing. + | 'spawn-left-pane-unbound' + +/** Same vocabulary the direct-SSH pane retry ledger settles with + * (DirectSshPaneRetryResult), so a pane reports both through one call. */ +export type TerminalPaneRecoveryOutcome = + | 'pending' + | 'success' + | 'failed' + | 'timed-out' + | 'superseded' + +/** The tab's recovery ledger. Lives on the row — not in a module- or + * store-level map keyed by tabId — so a tab's existence and its recovery + * budget are the same object: nothing can release the budget while keeping + * the row, and closing the tab drops both together (crash b5cfc6ca). */ +export type TerminalTabRecoveryLedger = { + /** Remount timestamps inside the rolling window. Backstop, not the control. */ + attemptedAt: number[] + /** Recovery epoch. A mounted pane captures it and stale requests are refused. */ + generation: number + /** What the mounted pane observed for the attempt this ledger describes. */ + outcome: TerminalPaneRecoveryOutcome + /** When that attempt was requested. Bounds how long 'pending' may block. */ + startedAt: number + /** The reason this attempt acted on. A settled failure refuses the SAME + * reason again until a new trigger arrives. */ + reason: TerminalPaneRecoveryReason + /** `tab.generation` right after the remount. Any later bump — authority + * change, SSH pane retry, activation respawn — is a new trigger, so the + * mismatch alone supersedes this ledger. No writer required. */ + tabGeneration: number +} + // ─── Terminal Tab (legacy — used by persistence and TerminalContentSlice) ─ export type TerminalTab = { id: string @@ -53,6 +105,11 @@ export type TerminalTab = { * `sortEpoch` increments. Split layouts use a numeric count because one tab * can remount several panes. Never persisted — it is a transient handoff. */ pendingActivationSpawn?: boolean | number + /** Transient recovery ledger for this tab. Never persisted — it describes a + * mounted pane's in-flight heal, and a stale one would refuse the first + * legitimate recovery after restart. Stripped exactly like + * `pendingActivationSpawn` (buildSanitizedTabsByWorktree). */ + recovery?: TerminalTabRecoveryLedger } export type TerminalPaneSplitDirection = 'vertical' | 'horizontal' diff --git a/src/shared/terminal-wait-blocked-reason-legacy-alias.test.ts b/src/shared/terminal-wait-blocked-reason-legacy-alias.test.ts new file mode 100644 index 00000000000..2e3e7e4687c --- /dev/null +++ b/src/shared/terminal-wait-blocked-reason-legacy-alias.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from 'vitest' +import { + agentNeutralTerminalWaitBlockedReason, + describeTerminalWaitBlockedReason +} from './terminal-wait-blocked-reason-legacy-alias' +import type { RuntimeTerminalWaitBlockedReason } from './runtime-terminal-contracts' + +describe('agentNeutralTerminalWaitBlockedReason', () => { + it.each([ + ['codex-update-prompt', 'agent-update-prompt'], + ['codex-trust-workspace', 'agent-trust-workspace'], + ['codex-cwd-prompt', 'agent-cwd-prompt'], + ['codex-hooks-review-prompt', 'agent-hooks-review-prompt'], + ['codex-interactive-prompt', 'agent-interactive-prompt'] + ] as const)('renames %s published by an older host to %s', (legacy, neutral) => { + expect(agentNeutralTerminalWaitBlockedReason(legacy)).toBe(neutral) + }) + + // Why no alias: this build still publishes it, so aliasing it would rename a live reason rather + // than reinterpret an older host's -- and 'codex just got an upgrade' does name Codex. + it('leaves the agent-specific codex-model-migration-prompt alone', () => { + expect(agentNeutralTerminalWaitBlockedReason('codex-model-migration-prompt')).toBeNull() + }) + + it.each(['agent-approval-prompt', 'agent-trust-workspace', 'agent-hooks-review-prompt'] as const)( + 'reports no alias for the already-neutral %s', + (reason) => { + expect(agentNeutralTerminalWaitBlockedReason(reason)).toBeNull() + } + ) + + // Why: the reason is JSON off the wire with no enum to validate it, and an object-literal lookup + // would answer these from Object.prototype -- the CLI would then print a function to the user. + it.each(['constructor', 'toString', 'valueOf', '__proto__', 'hasOwnProperty'])( + 'reports no alias for the prototype key %s', + (reason) => { + expect( + agentNeutralTerminalWaitBlockedReason(reason as RuntimeTerminalWaitBlockedReason) + ).toBeNull() + } + ) +}) + +// Why one formatter: the CLI's wait/show output and the worker and federation "Agent startup +// blocked:" receipts all render this token, and only the CLI used to alias it. +describe('describeTerminalWaitBlockedReason', () => { + it('names the neutral spelling beside a legacy token', () => { + expect(describeTerminalWaitBlockedReason('codex-trust-workspace')).toBe( + 'codex-trust-workspace (agent-trust-workspace)' + ) + }) + + it.each(['agent-trust-workspace', 'codex-model-migration-prompt'] as const)( + 'renders %s unannotated', + (reason) => { + expect(describeTerminalWaitBlockedReason(reason)).toBe(reason) + } + ) +}) diff --git a/src/shared/terminal-wait-blocked-reason-legacy-alias.ts b/src/shared/terminal-wait-blocked-reason-legacy-alias.ts new file mode 100644 index 00000000000..50ce940e608 --- /dev/null +++ b/src/shared/terminal-wait-blocked-reason-legacy-alias.ts @@ -0,0 +1,34 @@ +import type { RuntimeTerminalWaitBlockedReason } from './runtime-terminal-contracts' + +// Why: hosts older than the agent-neutral spellings still publish the codex-* tokens for dialogs +// their matcher never proved were Codex's, so a paired client renders the neutral equivalent +// instead of showing a Codex label to a Gemini/Cursor/Antigravity user. +// Why a Map: the reason arrives off the wire unvalidated, and a plain object would answer +// 'constructor' or 'toString' from Object.prototype and print a function to the user. +// Why one-directional: nothing consumes an agent-* -> codex-* mapping. A new host's agent-* token +// reaching an old client is rendered by that client's shipped code, which this build cannot change. +const LEGACY_CODEX_REASON_ALIASES = new Map([ + ['codex-update-prompt', 'agent-update-prompt'], + ['codex-trust-workspace', 'agent-trust-workspace'], + ['codex-cwd-prompt', 'agent-cwd-prompt'], + ['codex-hooks-review-prompt', 'agent-hooks-review-prompt'], + ['codex-interactive-prompt', 'agent-interactive-prompt'] +]) + +/** Neutral spelling for a reason an older host published, or null when it is already neutral or agent-specific. */ +export function agentNeutralTerminalWaitBlockedReason( + reason: RuntimeTerminalWaitBlockedReason +): RuntimeTerminalWaitBlockedReason | null { + return LEGACY_CODEX_REASON_ALIASES.get(reason) ?? null +} + +/** + * A blocked reason as shown to a user: the token the host published, plus the neutral spelling when + * the host predates it. Why append and not replace: the raw token is what scripts parse. + */ +export function describeTerminalWaitBlockedReason( + reason: RuntimeTerminalWaitBlockedReason +): string { + const neutral = agentNeutralTerminalWaitBlockedReason(reason) + return neutral ? `${reason} (${neutral})` : reason +} diff --git a/src/shared/workspace-session-schema.ts b/src/shared/workspace-session-schema.ts index 48fe00a7f4d..0a24551381e 100644 --- a/src/shared/workspace-session-schema.ts +++ b/src/shared/workspace-session-schema.ts @@ -99,6 +99,12 @@ const terminalTabSchema = z.object({ customTitle: z.string().nullable(), color: z.string().nullable(), isPinned: z.boolean().optional(), + // Why: recovery asks the terminal row who owns the surface, so a row that + // loses viewMode on reload reads as "not chat-owned" and lets a hidden chat + // surface remount itself. Declared here so the row survives the parse, with + // the same `.catch('terminal')` degradation the unified tab uses below. + // Legacy rows that predate this stay undefined → 'terminal' in the renderer. + viewMode: z.enum(['terminal', 'chat']).catch('terminal').optional(), sortOrder: z.number(), createdAt: z.number(), generation: z.number().optional(), diff --git a/src/shared/workspace-session-terminal-schema.test.ts b/src/shared/workspace-session-terminal-schema.test.ts index 5878b70a1b9..18a930fa492 100644 --- a/src/shared/workspace-session-terminal-schema.test.ts +++ b/src/shared/workspace-session-terminal-schema.test.ts @@ -72,4 +72,53 @@ describe('parseWorkspaceSession terminal fields', () => { expect(result.value.tabsByWorktree.wt).toEqual([]) } }) + + // Why this matters beyond persistence hygiene: terminal-pane recovery asks + // the terminal ROW who owns the surface. While the row lost viewMode on load, + // a chat-owned tab read as "not chat-owned" after every restart and recovery + // would remount its hidden surface — the race #19745's guard exists to stop. + describe('terminal row viewMode', () => { + function parseRow(row: Record): Record | undefined { + const result = parseWorkspaceSession({ + activeRepoId: null, + activeWorktreeId: 'wt', + activeTabId: 'tab1', + tabsByWorktree: { + wt: [ + { + id: 'tab1', + ptyId: null, + worktreeId: 'wt', + title: 'Terminal 1', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 0, + ...row + } + ] + }, + terminalLayoutsByTabId: {} + }) + expect(result.ok).toBe(true) + return result.ok ? result.value.tabsByWorktree.wt[0] : undefined + } + + it('survives the load boundary so a restored row still reads chat-owned', () => { + expect(parseRow({ viewMode: 'chat' })?.viewMode).toBe('chat') + }) + + it('keeps an explicit terminal mode', () => { + expect(parseRow({ viewMode: 'terminal' })?.viewMode).toBe('terminal') + }) + + it('leaves a row persisted by an older build undefined rather than failing', () => { + expect(parseRow({})?.viewMode).toBeUndefined() + }) + + it('degrades an unknown mode from a newer build instead of dropping the tab', () => { + // .catch('terminal') — the safe default, never a whole-session parse failure. + expect(parseRow({ viewMode: 'holographic' })?.viewMode).toBe('terminal') + }) + }) }) diff --git a/src/shared/worktree/removal.ts b/src/shared/worktree/removal.ts index 59e5803eddb..237d73630df 100644 --- a/src/shared/worktree/removal.ts +++ b/src/shared/worktree/removal.ts @@ -22,11 +22,12 @@ export type WorktreeForceDeleteReason = // rather than scanning the whole message and letting a path spell out a verdict. export const UNSTOPPED_PTY_DETAIL_SEPARATOR = ' — ' -// Why: verification distinguishes a PTY it watched stay alive from one it could not reach, +// Why: verification distinguishes a process it watched stay alive from one it could not reach, // and the delete toast must not flatten the two — a user waiving "we could not confirm" is -// making a different decision than one killing a terminal Orca just saw running. The marker -// and its matcher stay together for the same reason the force hint does. -export const UNSTOPPED_PTY_LIVE_DETAIL_PREFIX = 'still live:' +// making a different decision than one killing something Orca just saw running. The marker +// and its matcher stay together for the same reason the force hint does. Shared by the PTY +// sweep and the structured-session sweep, which both re-observe after their stop. +export const STILL_LIVE_DETAIL_PREFIX = 'still live:' // Why (#11960): a sweep that never answers wedges removal exactly like a stop that could not // be proven, and the waiver clears both — but this error carries different words, so without @@ -54,7 +55,15 @@ export function isUnstoppedPtyRemovalError(error: string): boolean { export function isProvenLivePtyRemovalError(error: string): boolean { return ( isUnstoppedPtyRemovalError(error) && - error.includes(`${UNSTOPPED_PTY_DETAIL_SEPARATOR}${UNSTOPPED_PTY_LIVE_DETAIL_PREFIX}`) + error.includes(`${UNSTOPPED_PTY_DETAIL_SEPARATOR}${STILL_LIVE_DETAIL_PREFIX}`) + ) +} + +/** True only when the observation AFTER the close found the session still attached. */ +export function isProvenLiveStructuredSessionRemovalError(error: string): boolean { + return ( + isRunningAgentSessionRemovalError(error) && + error.includes(`${UNSTOPPED_PTY_DETAIL_SEPARATOR}${STILL_LIVE_DETAIL_PREFIX}`) ) } diff --git a/tests/e2e/helpers/markdown-inline-image.ts b/tests/e2e/helpers/markdown-inline-image.ts new file mode 100644 index 00000000000..50669742169 --- /dev/null +++ b/tests/e2e/helpers/markdown-inline-image.ts @@ -0,0 +1,71 @@ +import { mkdirSync, writeFileSync } from 'node:fs' +import path from 'node:path' +import type { Page } from '@stablyai/playwright-test' +import { expect } from '@stablyai/playwright-test' + +const ERROR_BOUNDARY_TEXT = 'The rich markdown editor hit an unexpected error' +const SCHEMA_ERROR_SIGNATURE = 'Invalid content for node' + +// A 22x22 PNG dot, small enough to keep inline with the surrounding text. +const INLINE_DOT_PNG_BASE64 = + 'iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAAOklEQVR42mOoMGL4TwvMQHOD//dQB48aTKbB6IBigwmBwWUwsWDUYPINHnqpgqYZZLQQoqrBQ6bOAwDparQl4qEv0wAAAABJRU5ErkJggg==' + +export const INLINE_IMAGE_FIXTURE_DIRECTORY = '.orca-e2e-markdown-inline-image' + +export const INLINE_IMAGE_PARAGRAPH_MARKDOWN = [ + '# Inline image crash repro', + '', + 'Some text ![alt](inline-dot.png) more text', + '' +].join('\n') + +export const INLINE_IMAGE_DETAILS_MARKDOWN = [ + '# Details summary inline image repro', + '', + '
', + 'Toggle ![alt](inline-dot.png) label', + '', + 'Body', + '', + '
', + '' +].join('\n') + +export function writeInlineImageAsset(rootPath: string): void { + const directory = path.join(rootPath, INLINE_IMAGE_FIXTURE_DIRECTORY) + mkdirSync(directory, { recursive: true }) + writeFileSync( + path.join(directory, 'inline-dot.png'), + Buffer.from(INLINE_DOT_PNG_BASE64, 'base64') + ) +} + +/** + * The schema RangeError is thrown inside EditorView.dispatch, outside React's + * render phase, so no error boundary observes it — it only surfaces as a page + * error. Collect both signals. + */ +export function collectRichMarkdownPageErrors(page: Page): string[] { + const pageErrors: string[] = [] + page.on('pageerror', (error) => pageErrors.push(`${error.name}: ${error.message}`)) + page.on('console', (message) => { + if (message.type() === 'error') { + pageErrors.push(message.text()) + } + }) + return pageErrors +} + +export async function expectNoRichMarkdownSchemaCrash( + page: Page, + pageErrors: string[] +): Promise { + expect( + pageErrors.filter((entry) => entry.includes(SCHEMA_ERROR_SIGNATURE)), + 'no schema RangeError may be raised' + ).toEqual([]) + await expect( + page.getByText(ERROR_BOUNDARY_TEXT), + 'rich markdown error boundary must not trip' + ).toHaveCount(0) +} diff --git a/tests/e2e/helpers/relay-execution-process.ts b/tests/e2e/helpers/relay-execution-process.ts new file mode 100644 index 00000000000..c9247bffca8 --- /dev/null +++ b/tests/e2e/helpers/relay-execution-process.ts @@ -0,0 +1,125 @@ +import { randomUUID } from 'node:crypto' +import { mkdir, mkdtemp, readFile, realpath, rm } from 'node:fs/promises' +import path from 'node:path' +import { createInterface } from 'node:readline' +import { spawnProcess } from '../../../src/shared/child-process/run-process' + +const executionProgram = ` +const fs = require('node:fs'); +const readline = require('node:readline'); +const marker = process.argv[1]; +let sequence = 0; +readline.createInterface({ input: process.stdin }).on('line', line => { + const { id, value } = JSON.parse(line); + if (value === 'mutation-1') fs.appendFileSync('mutations.log', marker + '\\n'); + process.stdout.write(JSON.stringify({ id, pid: process.pid, cwd: fs.realpathSync('.'), + marker, sequence: ++sequence, value }) + '\\n'); +}); +` + +export async function createRelayExecutionProcess() { + await mkdir(path.join(process.cwd(), '.tmp'), { recursive: true }) + const folder = await mkdtemp(path.join(process.cwd(), '.tmp', 'relay-execution-')) + const executionCwd = await realpath(folder) + const marker = randomUUID() + const pending = new Map< + number, + { + resolve: (value: string) => void + reject: (error: Error) => void + timer: ReturnType + } + >() + let sequence = 0 + let nextId = 0 + let failure: Error | null = null + const child = spawnProcess({ + program: process.execPath, + args: ['-e', executionProgram, marker], + cwd: folder, + env: { ...process.env, ORCA_BACKGROUND_LAUNCH: '1' } + }) + const fail = (error: Error) => { + failure = error + for (const item of pending.values()) { + clearTimeout(item.timer) + item.reject(error) + } + pending.clear() + } + child.on('error', fail) + child.stdin.on('error', fail) + child.stdout.on('error', fail) + child.stderr.on('error', fail) + child.stderr.resume() + const closed = new Promise((resolve) => + child.once('close', () => { + fail(new Error('execution process exited')) + resolve() + }) + ) + const lines = createInterface({ input: child.stdout }) + lines.on('line', (line) => { + try { + const output = JSON.parse(line) + const item = pending.get(output.id) + if ( + !item || + output.pid !== child.pid || + output.cwd !== executionCwd || + output.marker !== marker || + output.sequence !== sequence + 1 + ) { + throw new Error('execution ownership or output sequence changed') + } + sequence = output.sequence + clearTimeout(item.timer) + pending.delete(output.id) + item.resolve(output.value) + } catch (error) { + fail(error as Error) + } + }) + return { + pid: child.pid, + sequence: () => sequence, + execute: (value: string) => + new Promise((resolve, reject) => { + if (failure) { + reject(failure) + return + } + const id = ++nextId + const timer = setTimeout(() => fail(new Error('execution response timed out')), 5_000) + pending.set(id, { resolve, reject, timer }) + child.stdin.write(`${JSON.stringify({ id, value })}\n`) + }), + mutations: async () => { + try { + const entries = (await readFile(path.join(folder, 'mutations.log'), 'utf8')) + .trim() + .split('\n') + if (entries.some((entry) => entry !== marker)) { + throw new Error('unexpected execution artifact') + } + return entries.length + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + return 0 + } + throw error + } + }, + close: async () => { + child.stdin.end() + const timer = setTimeout(() => child.kill('SIGKILL'), 5_000) + try { + await closed + } finally { + clearTimeout(timer) + lines.close() + await rm(folder, { recursive: true, force: true }) + } + } + } +} diff --git a/tests/e2e/helpers/slept-workspace-probe.ts b/tests/e2e/helpers/slept-workspace-probe.ts new file mode 100644 index 00000000000..b2b5635b526 --- /dev/null +++ b/tests/e2e/helpers/slept-workspace-probe.ts @@ -0,0 +1,133 @@ +/** + * Shared probes for GH #10205: a deliberately slept workspace must stay cold. + * Drives the shipping sleep path (sidebar context menu) and reads both the + * renderer's live PTY model and host truth. + */ +import type { Locator, Page } from '@stablyai/playwright-test' +import { expect } from '@stablyai/playwright-test' +import { ensureTerminalVisible } from './store' +import { waitForActivePanePtyId, waitForActiveTerminalManager } from './terminal' + +export type WorkspaceSample = { + livePtyCount: number + tabCount: number + tabIds: string[] + mountedTabIds: string[] + tabPtyHints: (string | null)[] +} + +export function rowLocator(page: Page, worktreeId: string): Locator { + return page + .locator( + `[data-worktree-sidebar] [role="option"][data-worktree-id=${JSON.stringify(worktreeId)}]` + ) + .first() +} + +export async function readWorkspaceSample( + page: Page, + worktreeId: string +): Promise { + return page.evaluate((id) => { + const state = window.__store?.getState() + if (!state) { + throw new Error('window.__store is not available') + } + const tabs = state.tabsByWorktree[id] ?? [] + const tabIds = new Set(tabs.map((tab) => tab.id)) + const managers = window.__paneManagers + return { + livePtyCount: tabs.reduce( + (count, tab) => count + (state.ptyIdsByTabId[tab.id]?.length ?? 0), + 0 + ), + tabCount: tabs.length, + tabIds: tabs.map((tab) => tab.id), + mountedTabIds: managers + ? Array.from(managers.keys()).filter((tabId) => tabIds.has(tabId)) + : [], + tabPtyHints: tabs.map((tab) => tab.ptyId ?? null) + } + }, worktreeId) +} + +/** Host-side truth: a revived workspace shows a freshly created live session here. */ +export async function readHostLiveTerminalCount(page: Page, worktreeId: string): Promise { + return (await page.evaluate(async (id) => { + const result = await window.api.runtime.call({ + method: 'terminal.list', + params: { worktree: `id:${id}`, requireFreshPtyLiveness: true } + }) + if (!result.ok) { + throw new Error(result.error.message) + } + return (result.result as { totalCount: number }).totalCount + }, worktreeId)) as number +} + +/** Connect-verdict lines (REATTACH / ATTACH / FRESH SPAWN / SKIP SPAWN) for one workspace. */ +export async function readConnectDiagnostics(page: Page, worktreeId: string): Promise { + return page.evaluate((id) => { + const state = window.__store?.getState() + const target = globalThis as unknown as Record + const diag = (target.__ptyConnectDiag as string[] | undefined) ?? [] + const tabIds = new Set((state?.tabsByWorktree[id] ?? []).map((tab) => tab.id)) + // Pane ids restart at 1 per worktree, so a verdict line is attributed to the + // tab named by the most recent connect line for that same pane id. + const tabByPaneId = new Map() + const owned: string[] = [] + for (const line of diag) { + const connect = /^pane=(\d+) tab=(\S+) /.exec(line) + if (connect) { + tabByPaneId.set(connect[1], connect[2]) + if (tabIds.has(connect[2])) { + owned.push(line) + } + continue + } + const verdict = /^pane=(\d+) ->/.exec(line) + if (verdict) { + const tabId = tabByPaneId.get(verdict[1]) + if (tabId && tabIds.has(tabId)) { + owned.push(line) + } + } + } + return owned + }, worktreeId) +} + +export async function giveWorkspaceALivePty(page: Page, worktreeId: string): Promise { + await page.evaluate((id) => { + window.__store?.getState().setActiveWorktree(id) + }, worktreeId) + await ensureTerminalVisible(page) + await waitForActiveTerminalManager(page, 30_000) + return waitForActivePanePtyId(page, 30_000) +} + +/** The shipping sleep path: right-click the sidebar row, click "Sleep". */ +export async function sleepWorkspaceViaSidebar(page: Page, worktreeId: string): Promise { + const row = rowLocator(page, worktreeId) + await expect(row).toBeVisible() + await row.scrollIntoViewIfNeeded() + const scope = row.locator('[data-worktree-context-menu-scope="worktree"]').first() + const target = (await scope.count()) > 0 ? scope : row + await target.click({ button: 'right' }) + const sleepItem = page.getByRole('menuitem', { name: 'Sleep', exact: true }).first() + await expect(sleepItem).toBeVisible() + await sleepItem.click() +} + +export async function activateWorkspaceByClick(page: Page, worktreeId: string): Promise { + const row = rowLocator(page, worktreeId) + await expect(row).toBeVisible() + await row.scrollIntoViewIfNeeded() + await row.click() + await expect + .poll(() => page.evaluate(() => window.__store?.getState().activeWorktreeId ?? null), { + timeout: 10_000, + message: `sidebar click did not activate ${worktreeId}` + }) + .toBe(worktreeId) +} diff --git a/tests/e2e/linear-url-workspace-entry.spec.ts b/tests/e2e/linear-url-workspace-entry.spec.ts index 76e17e11ffe..d1cb2677257 100644 --- a/tests/e2e/linear-url-workspace-entry.spec.ts +++ b/tests/e2e/linear-url-workspace-entry.spec.ts @@ -97,6 +97,10 @@ async function releaseHeldLinearLookup(page: Page): Promise { async function pasteLinearUrl(page: Page, input: ReturnType): Promise { await page.evaluate((text) => window.api.ui.writeClipboardText(text), LINEAR_URL) + // X selection ownership is async; pasting before it lands delivers stale text. + await expect + .poll(() => page.evaluate(() => window.api.ui.readClipboardText()), { timeout: 5_000 }) + .toBe(LINEAR_URL) await input.focus() await page.keyboard.press(pasteChord()) } diff --git a/tests/e2e/native-chat-first-flush-race.spec.ts b/tests/e2e/native-chat-first-flush-race.spec.ts index 1362a882902..2e85e2dc132 100644 --- a/tests/e2e/native-chat-first-flush-race.spec.ts +++ b/tests/e2e/native-chat-first-flush-race.spec.ts @@ -141,10 +141,24 @@ test.describe('Native chat first-flush transcript race (#8401)', () => { path: path.join(screenshotDir, '01-loading-no-error.png') }) - // Why: a short real delay proves the first readSession attempt already - // hit the not-yet-flushed file (returning notFound) and the renderer's - // backoff retry — not a lucky first read — is what picks it up below. - await orcaPage.waitForTimeout(1_500) + // Why observe, not sleep: 1_500ms is exactly UNFLUSHED_SETTLE_MS, so a fixed + // wait straddles the boundary where the host reports the transcript pending + // and the renderer cancels its own retry. Read through the same IPC instead, + // proving the miss directly. A notFound is never cached, so this cannot + // perturb the hydration the assertions below measure. + await expect + .poll( + () => + orcaPage.evaluate( + ({ id, file }) => + window.api.nativeChat + .readSession('claude', id, 50, file) + .then((result) => Boolean(result && 'error' in result && result.notFound)), + { id: sessionId, file: transcriptPath } + ), + { timeout: 10_000, message: 'transcript resolved before the first flush' } + ) + .toBe(true) await expect(orcaPage.getByText(ERROR_TITLE)).toHaveCount(0) const userText = 'Explain the native chat first-flush race fix for #8401' diff --git a/tests/e2e/native-chat-history-prepend-anchor.spec.ts b/tests/e2e/native-chat-history-prepend-anchor.spec.ts new file mode 100644 index 00000000000..aea95302363 --- /dev/null +++ b/tests/e2e/native-chat-history-prepend-anchor.spec.ts @@ -0,0 +1,204 @@ +import { randomUUID } from 'node:crypto' +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import type { Page } from '@stablyai/playwright-test' +import type { GlobalSettings } from '../../src/shared/global-settings-types' +import { test, expect } from './helpers/orca-app' +import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' +import { waitForActivePaneHookDescriptor, waitForActiveTerminalManager } from './helpers/terminal' + +const TRANSCRIPT_ROWS = 650 + +async function enableNativeChatSetting(page: Page): Promise { + await page.evaluate(async () => { + const nextSettings = await window.api.settings.set({ experimentalNativeChat: true }) + window.__store?.setState({ settings: nextSettings as GlobalSettings }) + }) +} + +async function seedClaudeProviderSession( + page: Page, + args: { paneKey: string; worktreeId: string; sessionId: string; transcriptPath: string } +): Promise { + await page.evaluate(({ paneKey, worktreeId, sessionId, transcriptPath }) => { + window.__store + ?.getState() + .setAgentStatus( + paneKey, + { state: 'working', prompt: 'e2e history anchor probe', agentType: 'claude' }, + 'Claude', + undefined, + { worktreeId }, + { providerSession: { key: 'session_id', id: sessionId, transcriptPath } } + ) + }, args) +} + +async function toggleTerminalTabToChatView( + page: Page, + args: { tabId: string; worktreeId: string } +): Promise { + await page.evaluate(({ tabId, worktreeId }) => { + const store = window.__store + if (!store) { + throw new Error('Store unavailable') + } + const state = store.getState() + const unifiedTab = (state.unifiedTabsByWorktree[worktreeId] ?? []).find( + (tab) => tab.contentType === 'terminal' && tab.entityId === tabId + ) + if (!unifiedTab) { + throw new Error('Unified terminal tab not found for chat toggle') + } + state.toggleTabViewMode(unifiedTab.id) + }, args) +} + +function claudeTranscript(rowCount: number, sessionId: string): string { + const startedAt = Date.now() - rowCount * 1_000 + return `${Array.from({ length: rowCount }, (_, index) => { + const marker = `E2E transcript row ${String(index).padStart(4, '0')}` + const body = Array.from( + { length: 5 }, + (_unused, line) => `Measured paragraph ${line + 1} for row ${String(index).padStart(4, '0')}.` + ).join('\n\n') + return JSON.stringify({ + sessionId, + uuid: `${sessionId}-${index}`, + timestamp: new Date(startedAt + index * 1_000).toISOString(), + type: index % 2 === 0 ? 'user' : 'assistant', + message: { + role: index % 2 === 0 ? 'user' : 'assistant', + model: 'claude-opus-4', + content: [{ type: 'text', text: `${marker}\n\n${body}` }] + } + }) + }).join('\n')}\n` +} + +test.describe('Native chat history prepend anchoring', () => { + test('keeps the visible transcript row at the same viewport offset', async ({ orcaPage }) => { + await waitForSessionReady(orcaPage) + await waitForActiveWorktree(orcaPage) + await ensureTerminalVisible(orcaPage) + await waitForActiveTerminalManager(orcaPage, 30_000) + + const descriptor = await waitForActivePaneHookDescriptor(orcaPage) + const [tabId] = descriptor.paneKey.split(':') + const sessionId = `e2e-prepend-anchor-${randomUUID()}` + const scratchDir = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-native-chat-anchor-')) + const transcriptPath = path.join(scratchDir, `${sessionId}.jsonl`) + writeFileSync(transcriptPath, claudeTranscript(TRANSCRIPT_ROWS, sessionId)) + + try { + await enableNativeChatSetting(orcaPage) + await seedClaudeProviderSession(orcaPage, { + paneKey: descriptor.paneKey, + worktreeId: descriptor.worktreeId, + sessionId, + transcriptPath + }) + await toggleTerminalTabToChatView(orcaPage, { + tabId, + worktreeId: descriptor.worktreeId + }) + + await expect(orcaPage.locator('[data-native-chat-root="true"]')).toBeVisible({ + timeout: 15_000 + }) + const scroll = orcaPage.locator('[data-native-chat-scroll]') + const transcriptWindow = orcaPage.locator('[data-native-chat-window]') + const loadEarlier = orcaPage.getByRole('button', { name: 'Load earlier messages' }) + await expect(transcriptWindow).toBeVisible({ timeout: 30_000 }) + await expect(loadEarlier).toBeAttached({ timeout: 30_000 }) + await expect + .poll(() => transcriptWindow.locator(':scope > [data-index]').count()) + .toBeGreaterThan(3) + + const initialTotalSize = await transcriptWindow.evaluate((element) => element.offsetHeight) + const anchor = await scroll.evaluate(async (element) => { + element.scrollTop = element.scrollHeight * 0.55 + element.dispatchEvent(new Event('scroll', { bubbles: true })) + let previousGeometry = '' + let stableFrames = 0 + for (let frame = 0; frame < 120 && stableFrames < 5; frame += 1) { + await new Promise((resolve) => requestAnimationFrame(() => resolve())) + const geometry = `${element.scrollHeight}:${element.scrollTop}` + stableFrames = geometry === previousGeometry ? stableFrames + 1 : 0 + previousGeometry = geometry + } + const scrollRect = element.getBoundingClientRect() + const candidates = Array.from( + element.querySelectorAll('[data-native-chat-window] > [data-index]') + ).filter((row) => { + const rect = row.getBoundingClientRect() + return rect.top >= scrollRect.top + 40 && rect.bottom <= scrollRect.bottom - 40 + }) + const row = candidates[Math.floor(candidates.length / 2)] + const marker = row + ? Array.from(row.querySelectorAll('p')).find((paragraph) => + /^E2E transcript row \d{4}$/.test(paragraph.textContent?.trim() ?? '') + ) + : undefined + if (!row || !marker) { + return null + } + return { + index: Number(row.dataset.index), + marker: marker.textContent?.trim() ?? '', + scrollHeight: element.scrollHeight, + scrollTop: element.scrollTop, + viewportOffset: row.getBoundingClientRect().top - scrollRect.top + } + }) + expect(anchor, 'expected a fully visible measured row to anchor').not.toBeNull() + if (!anchor) { + throw new Error('Expected a fully visible measured row to anchor') + } + + // The button stays off-screen so invoking it here exercises the real pagination + // handler without Playwright first scrolling the reader to the transcript head. + await loadEarlier.evaluate((button: HTMLButtonElement) => button.click()) + await expect + .poll(() => transcriptWindow.evaluate((element) => element.offsetHeight)) + .toBeGreaterThan(initialTotalSize) + await expect(loadEarlier).toBeAttached({ timeout: 30_000 }) + + const anchoredMarker = orcaPage.getByText(anchor.marker, { exact: true }) + await expect(anchoredMarker).toBeAttached({ timeout: 15_000 }) + const after = await anchoredMarker.evaluate(async (marker) => { + const row = marker.closest('[data-index]') + const scrollRoot = marker.closest('[data-native-chat-scroll]') + if (!row || !scrollRoot) { + return null + } + let previousGeometry = '' + let stableFrames = 0 + for (let frame = 0; frame < 120 && stableFrames < 5; frame += 1) { + await new Promise((resolve) => requestAnimationFrame(() => resolve())) + const geometry = `${scrollRoot.scrollHeight}:${scrollRoot.scrollTop}` + stableFrames = geometry === previousGeometry ? stableFrames + 1 : 0 + previousGeometry = geometry + } + return { + index: Number(row.dataset.index), + scrollHeight: scrollRoot.scrollHeight, + scrollTop: scrollRoot.scrollTop, + viewportOffset: row.getBoundingClientRect().top - scrollRoot.getBoundingClientRect().top + } + }) + expect(after, 'anchored row must remain mounted after history prepends').not.toBeNull() + expect(after?.index).toBe(anchor.index + 200) + const contentGrowth = (after?.scrollHeight ?? 0) - anchor.scrollHeight + const scrollAdjustment = (after?.scrollTop ?? 0) - anchor.scrollTop + expect( + Math.abs(contentGrowth - scrollAdjustment), + `content grew ${contentGrowth}px while scrollTop adjusted ${scrollAdjustment}px` + ).toBeLessThanOrEqual(2) + expect(Math.abs((after?.viewportOffset ?? 0) - anchor.viewportOffset)).toBeLessThanOrEqual(3) + } finally { + rmSync(scratchDir, { recursive: true, force: true }) + } + }) +}) diff --git a/tests/e2e/orchestration-idle-mail-delivery.spec.ts b/tests/e2e/orchestration-idle-mail-delivery.spec.ts index cffa6415208..9d90aed1875 100644 --- a/tests/e2e/orchestration-idle-mail-delivery.spec.ts +++ b/tests/e2e/orchestration-idle-mail-delivery.spec.ts @@ -653,7 +653,12 @@ test.describe('orchestration delivery to a cold-parked agent', () => { const parkingDelayMs = 500 test.use({ - orcaAppExtraEnv: { ORCA_E2E_TERMINAL_PARKING_DELAY_MS: String(parkingDelayMs) } + orcaAppExtraEnv: { + ORCA_E2E_TERMINAL_PARKING_DELAY_MS: String(parkingDelayMs), + // The working-title round trip (PTY -> daemon -> main) must beat the Enter + // timer; 500ms is a production heuristic, not a budget CI can honour. + ORCA_E2E_ORCHESTRATION_POINTER_ENTER_DELAY_MS: '5000' + } }) test('keeps one pointer and one idempotent prompt on the same parked PTY', async ({ diff --git a/tests/e2e/paired-runtime-rejected-input-remount.unit.test.ts b/tests/e2e/paired-runtime-rejected-input-remount.unit.test.ts index fae82b45d44..3967f7934eb 100644 --- a/tests/e2e/paired-runtime-rejected-input-remount.unit.test.ts +++ b/tests/e2e/paired-runtime-rejected-input-remount.unit.test.ts @@ -27,7 +27,11 @@ type StoreState = Record let mockStoreState: StoreState let storeSubscribers: ((state: StoreState) => void)[] = [] -const remountTerminalTabForRecovery = vi.fn<(tabId: string) => boolean>(() => true) +/** The store action reports admission now, not a bare boolean. */ +const REMOUNTED = { remounted: true as const, generation: 1 } +const remountTerminalTabForRecovery = vi.fn<(tabId: string, request?: unknown) => typeof REMOUNTED>( + () => REMOUNTED +) vi.mock('@/store', () => ({ useAppStore: { @@ -278,7 +282,7 @@ describe('host-rejected paired-runtime input reaches a pane remount', () => { vi.resetModules() vi.clearAllMocks() storeSubscribers = [] - remountTerminalTabForRecovery.mockReturnValue(true) + remountTerminalTabForRecovery.mockReturnValue(REMOUNTED) mockStoreState = { activeWorktreeId: 'wt-1', activeWorkspaceExecutionHostId: `runtime:${ENVIRONMENT_ID}`, @@ -417,7 +421,12 @@ describe('host-rejected paired-runtime input reaches a pane remount', () => { // Hop 1: the host turned the refusal into the negotiated frame. await vi.waitFor(() => expect(hostOpcodes).toContain(TerminalStreamOpcode.WriteUnavailable)) // Hop 2 (the one that was missing): it survives pane recovery as a remount. - await vi.waitFor(() => expect(remountTerminalTabForRecovery).toHaveBeenCalledWith('tab-1')) + await vi.waitFor(() => + expect(remountTerminalTabForRecovery).toHaveBeenCalledWith( + 'tab-1', + expect.objectContaining({ reason: 'input-rejected-by-host', trigger: 'automatic' }) + ) + ) binding.dispose() _resetTerminalPaneRecoveryForTests() diff --git a/tests/e2e/relay-region-compatibility.unit.test.ts b/tests/e2e/relay-region-compatibility.unit.test.ts new file mode 100644 index 00000000000..65f54067fd4 --- /dev/null +++ b/tests/e2e/relay-region-compatibility.unit.test.ts @@ -0,0 +1,120 @@ +import { describe, expect, it, vi } from 'vitest' +import { + AssignmentRequestSchema as BaselineRequest, + AssignmentResponseSchema as BaselineResponse +} from '../../cloud/apps/relay/src/test-fixtures/relay-contract-baseline/director-messages' +import { + DrainSchema as BaselineDrain, + HostHelloSchema as BaselineHello +} from '../../cloud/apps/relay/src/test-fixtures/relay-contract-baseline/control-messages' +import { AssignmentRequestSchema } from '../../cloud/packages/relay-contract/src/director-messages' +import { HostHelloSchema } from '../../cloud/packages/relay-contract/src/control-messages' +import { requestRelayAssignment } from '../../src/main/runtime/relay/relay-http-client' +import { RelayAssignRateGate } from '../../src/main/runtime/relay/relay-assign-rate-gate' + +const assignment = { + v: 1, + cellUrl: 'https://asia.example.test', + assignmentEpoch: 3, + lease: 'synthetic-assignment' +} +const window = { + generation: 1, + assignmentEpoch: 3, + incumbentRegion: 'asia-east2', + expiresAt: 100_000_000, + policyVersion: 1 +} +function request(fetch: typeof globalThis.fetch) { + return requestRelayAssignment({ + directorUrl: 'https://director.example.test', + relayHostId: 'abcdefghijklmnop', + relayToken: 'synthetic-authorization', + preferredRegion: 'asia-east2', + reconnect: true, + regionCorrection: { v: 1, action: 'issue-window' }, + fetch, + assignRateGate: new RelayAssignRateGate() + }) +} + +describe('relay correction mixed-version wire contracts', () => { + it('new desktop falls back against the actual pinned old director parser', async () => { + const bodies: unknown[] = [] + const fetch = vi.fn(async (_url, init) => { + const body: unknown = JSON.parse(String(init?.body)) + bodies.push(body) + return BaselineRequest.safeParse(body).success + ? Response.json(BaselineResponse.parse(assignment)) + : new Response(null, { status: 400 }) + }) + expect(await request(fetch)).toEqual(assignment) + expect(bodies).toHaveLength(2) + expect(AssignmentRequestSchema.safeParse(bodies[0]).success).toBe(true) + expect(BaselineRequest.safeParse(bodies[0]).success).toBe(false) + expect(bodies[1]).toEqual({ + v: 1, + relayHostId: 'abcdefghijklmnop', + preferredRegion: 'asia-east2', + reconnect: true + }) + }) + + it('the old desktop assignment shape remains accepted by the new director', () => { + const request = BaselineRequest.parse({ v: 1, relayHostId: 'abcdefghijklmnop' }) + expect(AssignmentRequestSchema.parse(request)).toEqual(request) + expect(BaselineResponse.parse(assignment)).toEqual(assignment) + }) + + it('the negotiated capability requires no change to the strict old host hello', () => { + const hello = { + v: 1, + relayHostId: 'abcdefghijklmnop', + assignmentEpoch: 3, + hostPublicKeyB64: Buffer.alloc(32).toString('base64'), + appVersion: 'test' + } + expect(BaselineHello.parse(HostHelloSchema.parse(hello))).toEqual(hello) + expect(BaselineHello.safeParse({ ...hello, idleRegionalRehome: true }).success).toBe( + false + ) + }) + + it('the idle cutover uses a drain frame understood by the pinned old desktop', () => { + const drain = { recovery: 'resolve-director', graceMs: 0 } + expect(BaselineDrain.parse(drain)).toEqual(drain) + }) + + it.each([ + { v: 1, window: { ...window, policyVersion: 2 } }, + { v: 2, window }, + { v: 1, window: { ...window, expiresAt: -1 } }, + { v: 1, window: { ...window, unexpectedField: true } } + ])( + 'defers unsupported or malformed optional correction without losing placement: %j', + async (regionCorrection) => { + const result = await request(async () => Response.json({ ...assignment, regionCorrection })) + expect(result).toMatchObject(assignment) + expect(result.regionCorrection).toBeUndefined() + } + ) + + it('still accepts supported correction metadata', async () => { + const regionCorrection = { v: 1, window } + expect(await request(async () => Response.json({ ...assignment, regionCorrection }))).toEqual({ + ...assignment, + regionCorrection + }) + }) + + it.each([ + { cellUrl: 'http://untrusted.example.test' }, + { assignmentEpoch: -1 }, + { lease: '' }, + { unexpectedField: true } + ])('keeps the core assignment strict: %j', async (invalid) => { + await expect(request(async () => Response.json({ ...assignment, ...invalid }))).rejects.toThrow( + 'relay_assignment_failed_502' + ) + }) +}) diff --git a/tests/e2e/relay-region-correction.unit.test.ts b/tests/e2e/relay-region-correction.unit.test.ts new file mode 100644 index 00000000000..614e5c08c1d --- /dev/null +++ b/tests/e2e/relay-region-correction.unit.test.ts @@ -0,0 +1,519 @@ +import { createHash, randomUUID } from 'node:crypto' +import { once } from 'node:events' +import { afterEach, describe, expect, it, vi } from 'vitest' +import nacl from 'tweetnacl' +import WebSocket from 'ws' +import type { IdleRegionalRehomeRequest } from '../../cloud/packages/relay-contract/src/idle-regional-rehome' +import { + openInMemoryRelayDatabase, + readRelayDatabasePoolPressure +} from '../../cloud/apps/relay/src/database' +import { createRelayServer } from '../../cloud/apps/relay/src/relay-server' +import type { RelayConfig } from '../../cloud/apps/relay/src/config' +import type * as AdminTokenVerifier from '../../cloud/apps/relay/src/admin-token-verifier' +import { RelayOriginPool } from '../../src/main/runtime/relay/relay-origin-pool' +import { RELAY_HOST_CAPABILITY_HEADERS } from '../../src/main/runtime/relay/relay-control-protocol' +import type { MobileSocketTransport } from '../../src/main/runtime/rpc/mobile-socket-wiring' +import { createRelayExecutionProcess } from './helpers/relay-execution-process' + +vi.mock('../../cloud/apps/relay/src/relay-token-verifier', () => ({ + createRelayTokenVerifier: () => async (hostId: string) => ({ + sub: 'transport-test-user', + prof: 'profile-1', + org: 'org-1', + relayHostId: hostId, + purpose: 'host-control', + exp: 4_102_444_800 + }), + readBearer: (value: string | undefined) => value?.replace(/^Bearer /, '') ?? null +})) + +vi.mock('../../cloud/apps/relay/src/admin-token-verifier', async (importOriginal) => ({ + ...(await importOriginal()), + createRegionalRehomeTokenVerifier: () => async (token: string) => token === 'test-director-token' +})) + +const cleanups: (() => Promise)[] = [] +afterEach(async () => { + const failures: unknown[] = [] + for (const cleanup of cleanups.splice(0).toReversed()) { + try { + await cleanup() + } catch (error) { + failures.push(error) + } + } + vi.restoreAllMocks() + if (failures.length > 0) { + throw new AggregateError(failures, 'relay topology cleanup failed') + } +}) + +async function topology() { + const execution = await createRelayExecutionProcess() + cleanups.push(() => execution.close()) + let clock = Date.now() + vi.spyOn(Date, 'now').mockImplementation(() => clock) + const database = await openInMemoryRelayDatabase() + cleanups.push(() => database.close()) + const keypair = nacl.box.keyPair() + const hostId = createHash('sha256').update(keypair.publicKey).digest('base64url').slice(0, 16) + const identity = { userId: 'transport-test-user', relayHostId: hostId } + const cells = [ + { + id: 'transport-us', + url: 'https://transport-us.example.test', + region: 'us-central1' as const, + capacityRequests: 100 + }, + { + id: 'transport-asia', + url: 'https://transport-asia.example.test', + region: 'asia-east2' as const, + capacityRequests: 100 + } + ] + const incarnations = [ + '11111111-1111-4111-8111-111111111111', + '22222222-2222-4222-8222-222222222222' + ] + const endpoints = new Map() + const sockets = new Set() + const servers = cells.map((cell, index) => + createRelayServer( + { + port: 0, + publicUrl: cell.url, + cellUrl: cell.url, + role: 'cell', + cellId: cell.id, + region: cell.region, + cells, + dataDir: '', + authIssuer: 'https://auth.example.test', + authAudience: 'orca-relay', + adminJwksUrl: 'https://auth.example.test/jwks', + jwksUrl: 'https://auth.example.test/jwks', + assignmentSigningKey: new Uint8Array(32), + adminAudience: 'https://director.example.test/v1/admin/drain', + deployServiceAccount: 'deploy@example.test', + rehomeAudience: 'https://director.example.test/v1/admin/host-drain', + rehomeDirectorServiceAccount: 'director@example.test', + databasePoolMax: 1, + publicAssignmentsEnabled: true, + publicAssignmentConcurrency: 2, + publicAssignmentQueueMax: 128, + publicAssignmentWaitMs: 4_000, + publicResolveConcurrency: 1, + publicResolveWaitMs: 5_000, + publicAssignmentRetryAfterSeconds: 5, + regionCorrectionCohortPercent: 100 + } as RelayConfig, + database, + { now: () => clock, random: () => 0.5, cellIncarnation: incarnations[index] } + ) + ) + cleanups.push(async () => { + for (const socket of sockets) { + socket.terminate() + } + for (const relay of servers) { + relay.sessions.drain(0) + await new Promise((resolve) => relay.server.close(() => resolve())) + } + }) + const source = servers[0]! + const target = servers[1]! + await source.assignments.inspectRegionalRehomeControl() + clock += 86_400_000 + await source.assignments.applyRegionalRehomeControl({ + expectedGeneration: 0, + enabled: true, + notBefore: clock, + ratePerMinute: 10, + preferenceMaxAgeMs: 86_400_000, + hostCooldownMs: 604_800_000, + drainGraceMs: 60_000 + }) + await source.assignments.reconcileCells(cells) + const startedAt = clock - 1_000 + const safety = () => ({ + observedAt: clock, + sqlFailures: 0, + reconnects: 0, + controlActivityRecoveryFailures: 0, + databasePoolWaiting: 0, + databasePoolWaitersMax: 0, + databasePoolWaitMsMax: 0 + }) + const heartbeat = async () => { + for (const [index, cell] of cells.entries()) { + const relay = servers[index]! + relay.observability.flush({ + ...relay.runtimeCounts(), + ...readRelayDatabasePoolPressure(database) + }) + await source.assignments.recordCellHeartbeat({ + cellId: cell.id, + cellUrl: cell.url, + region: cell.region, + cellIncarnation: incarnations[index]!, + startedAt, + ready: true, + observedRequests: 0 + }) + await source.assignments.recordCellRegionalRehomeStatus({ + cellId: cell.id, + cellIncarnation: incarnations[index]!, + regionalRehomeProtocol: 3, + safety: { + observedAt: clock, + sqlFailures: 0, + reconnects: 0, + controlActivityRecoveryFailures: 0, + databasePoolWaiting: 0, + databasePoolWaitersMax: 0, + databasePoolWaitMsMax: 0 + } + }) + } + } + await heartbeat() + for (const [index, relay] of servers.entries()) { + relay.server.listen(0, '127.0.0.1') + await once(relay.server, 'listening') + const address = relay.server.address() + if (!address || typeof address === 'string') { + throw new Error('missing local address') + } + endpoints.set(new URL(cells[index]!.url).host, `ws://127.0.0.1:${address.port}`) + } + const connect = (url: string, headers?: Record) => { + const parsed = new URL(url) + const socket = new WebSocket(`${endpoints.get(parsed.host)}${parsed.pathname}`, { headers }) + sockets.add(socket) + return socket + } + let failCorroboration = 0 + let pauseCorroboration = false + let corroborationFailures = 0 + let rejectTargetControls = false + let targetControlFailures = 0 + const executionErrors: unknown[] = [] + let delayedReply: (() => void) | null = null + const received: string[] = [] + const pool = new RelayOriginPool({ + directorUrl: 'https://director.example.test', + relayHostId: hostId, + identity: { userId: identity.userId, profileId: 'profile-1', organizationId: 'org-1' }, + keypair: { ...keypair, publicKeyB64: Buffer.from(keypair.publicKey).toString('base64') }, + appVersion: 'transport-test', + isCurrent: () => true, + onStatus: () => {}, + now: () => clock, + mobileSocketWiring: { + attachTransport: (transport: MobileSocketTransport) => { + transport.onMessage((raw, reply) => { + const value = raw.toString() + received.push(value) + void execution + .execute(value) + .then((output) => { + if (output === 'mutation-1') { + delayedReply = () => reply('mutation-1-ack') + } else { + reply(`host:${output}`) + } + }) + .catch((error) => executionErrors.push(error)) + }) + return () => {} + } + } as never, + createControlSocket: (url, token) => { + if (rejectTargetControls && new URL(url).host === new URL(cells[1]!.url).host) { + targetControlFailures++ + throw new Error('simulated_target_unavailable') + } + const socket = connect(url, { + authorization: `Bearer ${token}`, + ...RELAY_HOST_CAPABILITY_HEADERS + }) + if (process.env.ORCA_RELAY_TRANSPORT_DIAGNOSTICS === '1') { + const cell = new URL(url).host + console.info('transport-control-created', { + cell, + stack: new Error('transport control created').stack + }) + socket.on('message', (raw) => { + const message = JSON.parse(raw.toString()) + if (['region-restored', 'host-hello-ack', 'drain'].includes(message.type)) { + console.info('transport-control-message', { + cell, + type: message.type, + assignmentEpoch: message.assignmentEpoch, + generation: message.generation + }) + } + }) + socket.on('close', (code) => console.info('transport-control-close', { cell, code })) + } + return socket + }, + createDataSocket: (url) => connect(url), + fetch: (async () => { + if (failCorroboration > 0 || pauseCorroboration) { + failCorroboration = Math.max(0, failCorroboration - 1) + corroborationFailures++ + return Response.json({ error: 'temporary_director_failure' }, { status: 503 }) + } + const assignment = await source.assignments.resolve(identity) + if (!assignment) { + return Response.json({ error: 'assignment_not_found' }, { status: 409 }) + } + return Response.json({ + v: 1, + cellUrl: assignment.cellUrl, + assignmentEpoch: assignment.assignmentEpoch, + lease: 'synthetic-assignment-lease' + }) + }) as typeof fetch + }) + cleanups.push(async () => { + pool.closeNow() + }) + const assignment = await source.assignments.assign(identity, 'us-central1') + await pool.openInitial( + { + v: 1, + cellUrl: assignment.cellUrl, + assignmentEpoch: assignment.assignmentEpoch, + lease: 'synthetic-assignment-lease' + }, + hostId + ) + const attachPhone = async (cellIndex: number, device: string) => { + const invite = await source.store.createInvite(identity, device) + const socket = connect(`${cells[cellIndex]!.url}/v1/connect/${hostId}`) + await once(socket, 'open') + const hello = once(socket, 'message') + socket.send( + JSON.stringify({ type: 'relay-auth', v: 1, mode: 'connect', credential: invite.inviteToken }) + ) + const [raw] = await hello + expect(JSON.parse(raw.toString())).toMatchObject({ type: 'relay-hello', ok: true }) + return socket + } + let candidate: (IdleRegionalRehomeRequest & { sourceCellUrl: string }) | undefined + const prepareMove = async () => { + const issued = await source.assignments.exchangeRegionCorrection( + identity, + { v: 1, action: 'issue-window' }, + assignment.assignmentEpoch + ) + await source.assignments.exchangeRegionCorrection( + identity, + { + v: 1, + action: 'report', + generation: issued.window!.generation, + assignmentEpoch: assignment.assignmentEpoch, + policyVersion: 1, + outcome: 'conclusive', + measurements: { 'us-central1': 180, 'asia-east2': 40 } + }, + assignment.assignmentEpoch + ) + candidate = (await source.assignments.selectIdleRegionalRehomeCandidates(safety()))[0] + expect(candidate).toBeDefined() + return candidate! + } + const move = async () => { + if (!candidate) { + await prepareMove() + } + const { sourceCellUrl, ...request } = candidate! + const address = endpoints.get(new URL(sourceCellUrl).host)!.replace('ws:', 'http:') + const response = await fetch(`${address}/v1/admin/host-idle-rehome`, { + method: 'POST', + headers: { authorization: 'Bearer test-director-token', 'content-type': 'application/json' }, + body: JSON.stringify({ ...request, cohortPercent: 100, directorSafety: safety() }) + }) + const body = (await response.json()) as { v: number; outcome: string } + expect(response.status, JSON.stringify(body)).toBe(200) + return { outcome: body.outcome } + } + return { + source, + target, + pool, + identity, + database, + cells, + attachPhone, + connectDevice: () => connect(`${cells[0]!.url}/v1/connect/${hostId}`), + move, + prepareMove, + heartbeat, + now: () => clock, + advance: (ms: number) => { + clock += ms + }, + received, + failNextCorroboration: () => { + failCorroboration = 1 + }, + pauseCorroboration: (paused: boolean) => { + pauseCorroboration = paused + }, + corroborationFailures: () => corroborationFailures, + targetControlFailures: () => targetControlFailures, + failTarget: () => { + rejectTargetControls = true + const session = target.sessions.get(identity) + if (session?.socket) { + session.socket.terminate() + } + }, + execution, + executionErrors, + mutations: () => execution.mutations(), + reply: () => { + if (!delayedReply) { + throw new Error('no delayed mutation') + } + delayedReply() + } + } +} + +async function echo(socket: WebSocket, value: string) { + const marker = `${value}:${randomUUID()}` + const response = once(socket, 'message') + socket.send(marker) + const [raw] = await response + expect(raw.toString()).toBe(`host:${marker}`) +} + +describe('idle region correction across real relay and desktop WebSockets', () => { + it('releases the empty source and recovers normally when the target never registers', async () => { + const context = await topology() + await context.prepareMove() + context.failTarget() + expect(await context.move()).toEqual({ outcome: 'committed' }) + await expect.poll(() => context.source.sessions.get(context.identity)).toBeNull() + await expect + .poll(async () => + context.database.query( + `SELECT activity_id FROM relay_assignment_activity_leases + WHERE user_id = ? AND relay_host_id = ? AND cell_id = ?`, + [context.identity.userId, context.identity.relayHostId, context.cells[0]!.id] + ) + ) + .toEqual([]) + await expect.poll(context.targetControlFailures).toBeGreaterThan(0) + context.advance(15 * 60_000 + 1) + await context.heartbeat() + expect(await context.source.assignments.abortExpiredEvacuations()).toBe(1) + expect(await context.source.assignments.resolve(context.identity)).toMatchObject({ + cellId: context.cells[0]!.id, + assignmentEpoch: 3 + }) + await expect + .poll(() => context.pool.activeAssignment?.cellUrl, { timeout: 15_000 }) + .toBe(context.cells[0]!.url) + await expect + .poll(() => context.source.sessions.get(context.identity)?.state, { timeout: 15_000 }) + .toBe('active') + const returning = await context.attachPhone(0, 'phone-after-target-failure') + await echo(returning, 'after-target-failure') + expect(await context.mutations()).toBe(0) + expect(context.executionErrors).toEqual([]) + }, 30_000) + + it('rejects an arrival during cutover and restores admissions after a definite failed commit', async () => { + const context = await topology() + await context.prepareMove() + const original = context.source.sessions.get(context.identity)! + let entered!: () => void + let release!: () => void + const committing = new Promise((resolve) => { + entered = resolve + }) + const gate = new Promise((resolve) => { + release = resolve + }) + vi.spyOn(context.source.assignments, 'commitIdleRegionalRehome').mockImplementationOnce( + async () => { + entered() + await gate + throw new Error('simulated_database_unavailable_before_commit') + } + ) + const move = context.move() + await committing + try { + const invite = await context.source.store.createInvite(context.identity, 'racing-phone') + const arriving = context.connectDevice() + const rejected = once(arriving, 'close') + await once(arriving, 'open') + arriving.send( + JSON.stringify({ + type: 'relay-auth', + v: 1, + mode: 'connect', + credential: invite.inviteToken + }) + ) + expect((await rejected)[0]).toBe(4409) + expect(context.source.sessions.get(context.identity)).toBe(original) + } finally { + release() + await move + } + expect(await move).toEqual({ outcome: 'deferred' }) + expect(context.source.sessions.get(context.identity)).toBe(original) + const returning = await context.attachPhone(0, 'retrying-phone') + await echo(returning, 'after-definite-abort') + expect(await context.mutations()).toBe(0) + expect(context.executionErrors).toEqual([]) + }, 30_000) + + it('defers for either connected device, then moves after both disconnect without replaying work', async () => { + const context = await topology() + const phone = await context.attachPhone(0, 'phone') + const tablet = await context.attachPhone(0, 'tablet') + const sourceSession = context.source.sessions.get(context.identity)! + await echo(phone, 'before-cutover') + phone.send('mutation-1') + await expect.poll(context.mutations).toBe(1) + expect(await context.move()).toEqual({ outcome: 'busy' }) + expect(context.source.sessions.get(context.identity)).toBe(sourceSession) + expect((await context.source.assignments.resolve(context.identity))?.cellId).toBe( + context.cells[0]!.id + ) + const acknowledged = once(phone, 'message') + context.reply() + expect((await acknowledged)[0].toString()).toBe('mutation-1-ack') + const phoneClosed = once(phone, 'close') + phone.close() + await phoneClosed + await expect.poll(() => sourceSession.activeSplices.size).toBe(1) + expect(await context.move()).toEqual({ outcome: 'busy' }) + await echo(tablet, 'quiet-tablet-still-connected') + const tabletClosed = once(tablet, 'close') + tablet.close() + await tabletClosed + await expect.poll(() => sourceSession.activeSplices.size).toBe(0) + expect(await context.move()).toEqual({ outcome: 'committed' }) + await expect + .poll(() => context.pool.activeAssignment?.cellUrl, { timeout: 15_000 }) + .toBe(context.cells[1]!.url) + await expect.poll(() => context.source.sessions.get(context.identity)).toBeNull() + const returning = await context.attachPhone(1, 'returning-phone') + await echo(returning, 'after-idle-cutover') + expect(await context.mutations()).toBe(1) + expect(context.executionErrors).toEqual([]) + expect(context.execution.sequence()).toBe(4) + }, 30_000) +}) diff --git a/tests/e2e/rich-markdown-inline-image.spec.ts b/tests/e2e/rich-markdown-inline-image.spec.ts new file mode 100644 index 00000000000..03de223ad13 --- /dev/null +++ b/tests/e2e/rich-markdown-inline-image.spec.ts @@ -0,0 +1,135 @@ +import { test, expect } from './helpers/orca-app' +import { + cleanupMarkdownFixture, + createMarkdownFixture, + getActiveWorktreeContext, + openMarkdownFixture, + waitForRichMarkdownEditor +} from './helpers/markdown-editor-fixture' +import { + collectRichMarkdownPageErrors, + expectNoRichMarkdownSchemaCrash, + INLINE_IMAGE_DETAILS_MARKDOWN, + INLINE_IMAGE_FIXTURE_DIRECTORY, + INLINE_IMAGE_PARAGRAPH_MARKDOWN, + writeInlineImageAsset +} from './helpers/markdown-inline-image' +import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' + +// A markdown image nested in a paragraph or a toggle summary used to parse into a +// schema-invalid document that only threw on the first edit reassembling it. +test.describe('Rich markdown inline image regression', () => { + test.beforeEach(async ({ orcaPage }) => { + await waitForSessionReady(orcaPage) + await waitForActiveWorktree(orcaPage) + }) + + test('an inline image inside a paragraph survives a keystroke', async ({ + orcaPage + }, testInfo) => { + const context = await getActiveWorktreeContext(orcaPage) + const pageErrors = collectRichMarkdownPageErrors(orcaPage) + let filePath: string | null = null + + try { + writeInlineImageAsset(context.rootPath) + filePath = await createMarkdownFixture( + context, + INLINE_IMAGE_FIXTURE_DIRECTORY, + 'paragraph-inline-image', + testInfo.workerIndex, + INLINE_IMAGE_PARAGRAPH_MARKDOWN + ) + await openMarkdownFixture(orcaPage, context, filePath) + const editor = await waitForRichMarkdownEditor(orcaPage) + + const paragraph = editor.locator('p').filter({ hasText: 'more text' }).first() + await expect(paragraph).toBeVisible({ timeout: 15_000 }) + await expect(editor.locator('img')).toHaveCount(1, { timeout: 15_000 }) + + // Typing at the paragraph start reassembles the whole paragraph, which is + // the frame the reported RangeError bottomed out in. + await paragraph.click({ position: { x: 12, y: 8 } }) + await orcaPage.keyboard.press('Home') + await orcaPage.keyboard.type('X') + + await expect(editor.locator('p').filter({ hasText: 'XSome text' })).toHaveCount(1) + await expect(editor.locator('img')).toHaveCount(1) + await expectNoRichMarkdownSchemaCrash(orcaPage, pageErrors) + } finally { + await cleanupMarkdownFixture(filePath) + } + }) + + test('an inline image inside a toggle summary survives a keystroke', async ({ + orcaPage + }, testInfo) => { + const context = await getActiveWorktreeContext(orcaPage) + const pageErrors = collectRichMarkdownPageErrors(orcaPage) + let filePath: string | null = null + + try { + writeInlineImageAsset(context.rootPath) + filePath = await createMarkdownFixture( + context, + INLINE_IMAGE_FIXTURE_DIRECTORY, + 'details-inline-image', + testInfo.workerIndex, + INLINE_IMAGE_DETAILS_MARKDOWN + ) + await openMarkdownFixture(orcaPage, context, filePath) + const editor = await waitForRichMarkdownEditor(orcaPage) + + const summary = editor.locator('summary').first() + await expect(summary).toBeVisible({ timeout: 15_000 }) + await expect(editor.locator('summary img')).toHaveCount(1, { timeout: 15_000 }) + + await summary.click() + await orcaPage.keyboard.press('End') + await orcaPage.keyboard.type('X') + + await expect(editor.locator('summary').filter({ hasText: 'labelX' })).toHaveCount(1) + await expect(editor.locator('summary img')).toHaveCount(1) + await expectNoRichMarkdownSchemaCrash(orcaPage, pageErrors) + } finally { + await cleanupMarkdownFixture(filePath) + } + }) + + test('a formatting command over an inline image keeps the image', async ({ + orcaPage + }, testInfo) => { + const context = await getActiveWorktreeContext(orcaPage) + const pageErrors = collectRichMarkdownPageErrors(orcaPage) + let filePath: string | null = null + + try { + writeInlineImageAsset(context.rootPath) + filePath = await createMarkdownFixture( + context, + INLINE_IMAGE_FIXTURE_DIRECTORY, + 'paragraph-inline-image-bold', + testInfo.workerIndex, + INLINE_IMAGE_PARAGRAPH_MARKDOWN + ) + await openMarkdownFixture(orcaPage, context, filePath) + const editor = await waitForRichMarkdownEditor(orcaPage) + + const paragraph = editor.locator('p').filter({ hasText: 'more text' }).first() + await expect(paragraph).toBeVisible({ timeout: 15_000 }) + await expect(editor.locator('img')).toHaveCount(1, { timeout: 15_000 }) + + // toggleBold runs tr.addMark across the selection, which reassembles every + // paragraph it spans — and silently dropped the image before the fix. + await paragraph.click({ position: { x: 12, y: 8 } }) + await orcaPage.keyboard.press('ControlOrMeta+a') + await orcaPage.getByRole('button', { name: 'Bold', exact: true }).first().click() + + await expect(editor.locator('strong').first()).toBeVisible() + await expect(editor.locator('img')).toHaveCount(1) + await expectNoRichMarkdownSchemaCrash(orcaPage, pageErrors) + } finally { + await cleanupMarkdownFixture(filePath) + } + }) +}) diff --git a/tests/e2e/runtime-host-status-recovery.spec.ts b/tests/e2e/runtime-host-status-recovery.spec.ts new file mode 100644 index 00000000000..09707606da1 --- /dev/null +++ b/tests/e2e/runtime-host-status-recovery.spec.ts @@ -0,0 +1,221 @@ +import { createConnection, createServer, type Socket, type AddressInfo } from 'node:net' +import type { Page } from '@stablyai/playwright-test' +import { decodePairingOffer, encodePairingOffer } from '../../src/shared/pairing' +import { expect, test } from './helpers/orca-app' +import { + createRuntimeDesktopPairingOffer, + launchPairedElectronClient, + launchPairedWebClient, + type RuntimeDesktopPairingOffer +} from './helpers/paired-electron-client' +import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' + +async function interruptibleHost(offer: RuntimeDesktopPairingOffer) { + const pairing = decodePairingOffer(offer.pairingUrl) + const endpoint = new URL(pairing.endpoint) + const sockets = new Set() + let online = true + const server = createServer((client) => { + if (!online) { + client.destroy() + return + } + const host = createConnection({ host: endpoint.hostname, port: Number(endpoint.port) }) + for (const socket of [client, host]) { + sockets.add(socket) + socket.on('error', () => { + client.destroy() + host.destroy() + }) + socket.on('close', () => { + sockets.delete(socket) + client.destroy() + host.destroy() + }) + } + client.pipe(host).pipe(client) + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + const address = server.address() as AddressInfo + const pairingUrl = encodePairingOffer({ ...pairing, endpoint: `ws://127.0.0.1:${address.port}` }) + let webClientUrl: string | undefined + if (offer.webClientUrl) { + const url = new URL(offer.webClientUrl) + url.search = '' + url.hash = new URLSearchParams({ pairing: pairingUrl }).toString() + webClientUrl = url.href + } + return { + offer: { pairingUrl, webClientUrl }, + setOnline(value: boolean) { + online = value + if (!online) { + sockets.forEach((socket) => socket.destroy()) + } + }, + async close() { + sockets.forEach((socket) => socket.destroy()) + await new Promise((resolve) => server.close(() => resolve())) + } + } +} + +async function statusEvidence(page: Page, environmentId?: string) { + return page.evaluate((id) => { + const entries = window.__store?.getState().runtimeStatusByEnvironmentId + const entry = id ? entries?.get(id) : entries?.values().next().value + return entry?.snapshot + ? { + verification: entry.snapshot.verification, + transport: entry.snapshot.transport, + runtimeId: entry.status?.runtimeId, + sequence: entry.snapshot.sequence + } + : null + }, environmentId) +} + +async function expectWorkspaceHostAppearance( + page: Page, + disconnected: boolean, + hostLabel?: string +) { + const cards = page.locator('[data-worktree-card-surface="true"]') + const card = ( + hostLabel ? cards.filter({ has: page.getByText(hostLabel, { exact: true }) }) : cards + ).first() + await expect(card).toBeVisible() + await expect(card).toHaveCSS('opacity', disconnected ? '0.6' : '1') + const icon = card.locator(disconnected ? 'svg.lucide-server-off' : 'svg.lucide-server').first() + await expect(icon).toBeVisible() + await expect( + card.locator(disconnected ? 'svg.lucide-server' : 'svg.lucide-server-off') + ).toHaveCount(0) + await expect(icon).toHaveClass(disconnected ? /text-destructive/ : /text-muted-foreground/) + await icon.hover() + await expect( + page.getByRole('tooltip', { name: disconnected ? /disconnected/i : /Project on/ }) + ).toBeVisible() + await page.mouse.move(900, 600) +} + +for (const topology of ['desktop', 'headless'] as const) { + test(`connection-owned status recovers with a ${topology} host and independent viewers`, async ({ + electronApp, + orcaPage: page, + testRepoPath + }, testInfo) => { + test.setTimeout(180_000) + let headless: Awaited> | null = null + let proxy: Awaited> | undefined + let client: Awaited> | undefined + let browser: Awaited> | undefined + try { + headless = + topology === 'headless' + ? await launchHeadlessPairedRuntimeHost({ pinnedServePort: true }) + : null + const offer = headless?.offer ?? (await createRuntimeDesktopPairingOffer(page)) + await (headless + ? headless.client.call('repo.add', { path: testRepoPath }) + : page.evaluate(async (path) => { + await window.api.repos.add({ path }) + await window.__store?.getState().fetchRepos() + }, testRepoPath)) + proxy = await interruptibleHost(offer) + client = await launchPairedElectronClient(offer, testInfo, 'Direct host') + proxy.setOnline(false) + const offlineId = await client.page.evaluate(async (pairingCode) => { + const { environment } = await window.api.runtimeEnvironments.addFromPairingCode({ + name: 'Recovering host', + pairingCode + }) + const store = window.__store!.getState() + store.setRuntimeEnvironments(await window.api.runtimeEnvironments.list()) + await store.refreshRuntimeEnvironmentStatus(environment.id, 1_000) + return environment.id + }, proxy.offer.pairingUrl) + await expect + .poll(() => statusEvidence(client!.page, offlineId)) + .toMatchObject({ verification: 'unavailable' }) + expect(await statusEvidence(client!.page, client.environmentId)).toMatchObject({ + verification: 'verified' + }) + proxy.setOnline(true) + await expect + .poll(() => statusEvidence(client!.page, offlineId), { timeout: 30_000 }) + .toMatchObject({ verification: 'verified', transport: 'ready' }) + const initial = await statusEvidence(client!.page, offlineId) + await expectWorkspaceHostAppearance(client.page, false, 'Recovering host') + await expect(client.page.getByText('Recovering host', { exact: true }).first()).toBeVisible() + await client.page.screenshot({ path: testInfo.outputPath(`${topology}-recovered.png`) }) + browser = await launchPairedWebClient(electronApp, proxy.offer) + await expect + .poll(() => statusEvidence(browser!.page), { timeout: 30_000 }) + .toMatchObject({ verification: 'verified', transport: 'ready' }) + await expectWorkspaceHostAppearance(browser.page, false) + proxy.setOnline(false) + await expect + .poll(() => statusEvidence(client!.page, offlineId)) + .toMatchObject({ transport: 'disconnected' }) + await expect + .poll(() => statusEvidence(browser!.page), { timeout: 30_000 }) + .toMatchObject({ transport: 'disconnected' }) + expect(await statusEvidence(client!.page, client.environmentId)).toMatchObject({ + verification: 'verified', + transport: 'ready' + }) + await expectWorkspaceHostAppearance(client.page, false, 'Recovering host') + await expectWorkspaceHostAppearance(client.page, false, 'Direct host') + await expectWorkspaceHostAppearance(browser.page, false) + await client.page.screenshot({ + path: testInfo.outputPath(`${topology}-sidebar-reconnecting.png`) + }) + await browser.page.screenshot({ + path: testInfo.outputPath(`${topology}-browser-reconnecting.png`) + }) + proxy.setOnline(true) + await expect + .poll(() => statusEvidence(client!.page, offlineId), { timeout: 30_000 }) + .toMatchObject({ verification: 'verified', transport: 'ready' }) + await expect + .poll(() => statusEvidence(browser!.page), { timeout: 30_000 }) + .toMatchObject({ verification: 'verified', transport: 'ready' }) + expect((await statusEvidence(client!.page, offlineId))!.sequence).toBeGreaterThan( + initial!.sequence + ) + await expectWorkspaceHostAppearance(client.page, false, 'Recovering host') + await expectWorkspaceHostAppearance(browser.page, false) + await browser.page.screenshot({ + path: testInfo.outputPath(`${topology}-browser-recovered.png`) + }) + await client.page.evaluate(async (selector) => { + await window.api.runtimeEnvironments.disconnect({ selector }) + }, offlineId) + await expect + .poll(() => statusEvidence(client!.page, offlineId)) + .toMatchObject({ verification: 'blocked', transport: 'disconnected' }) + await expectWorkspaceHostAppearance(client.page, true, 'Recovering host') + await expectWorkspaceHostAppearance(client.page, false, 'Direct host') + await client.page.screenshot({ + path: testInfo.outputPath(`${topology}-sidebar-disconnected.png`) + }) + await client.page.evaluate(async (selector) => { + await window.api.runtimeEnvironments.connect({ selector }) + }, offlineId) + await expect + .poll(() => statusEvidence(client!.page, offlineId), { timeout: 30_000 }) + .toMatchObject({ verification: 'verified', transport: 'ready' }) + await expectWorkspaceHostAppearance(client.page, false, 'Recovering host') + await expectWorkspaceHostAppearance(browser.page, false) + await client.page.screenshot({ + path: testInfo.outputPath(`${topology}-sidebar-restored.png`) + }) + } finally { + await browser?.dispose() + await client?.dispose() + await proxy?.close() + await headless?.dispose() + } + }) +} diff --git a/tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts b/tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts index 09cfa6d6d7c..9a5528938be 100644 --- a/tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts +++ b/tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts @@ -16,6 +16,7 @@ import { resetWebSessionTabsSnapshotFreshnessForTests, type WebSessionTabsSyncState } from '../../src/renderer/src/runtime/web-session-tabs-sync' +import { makeAgentStatusStoreWiring } from '../../src/main/runtime/agent-status-store-wiring.test-fixture' vi.mock('../../src/renderer/src/store', () => ({ useAppStore: { @@ -689,7 +690,9 @@ describe('real PTY decorative session-tabs fanout', () => { }) it('renews retained hook status without resetting its state start', () => { - const runtime = new OrcaRuntimeService() + const statusWiring = makeAgentStatusStoreWiring() + const runtime = new OrcaRuntimeService(null, undefined, statusWiring.deps) + const uninstallStatusRepublish = statusWiring.attach(runtime) const ptyId = seedWorktree(runtime, 0) const internals = runtime as unknown as RuntimeInternals const seededTab = internals.mobileSessionTabsByWorktree.get('workspace-0')?.tabs[0] @@ -769,5 +772,7 @@ describe('real PTY decorative session-tabs fanout', () => { true ) unsubscribe() + uninstallStatusRepublish() + statusWiring.statusStore.stop() }) }) diff --git a/tests/e2e/session-tabs-rich-status-boundaries.unit.test.ts b/tests/e2e/session-tabs-rich-status-boundaries.unit.test.ts index 2c60fe19082..d15a6513cee 100644 --- a/tests/e2e/session-tabs-rich-status-boundaries.unit.test.ts +++ b/tests/e2e/session-tabs-rich-status-boundaries.unit.test.ts @@ -1,5 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { OrcaRuntimeService } from '../../src/main/runtime/orca-runtime' +import { makeAgentStatusStoreWiring } from '../../src/main/runtime/agent-status-store-wiring.test-fixture' import type { RuntimeMobileSessionTabsResult, RuntimeMobileSessionTabsSnapshot @@ -27,7 +28,9 @@ type Harness = { } function createHarness(): Harness { - const runtime = new OrcaRuntimeService() + const statusWiring = makeAgentStatusStoreWiring() + const runtime = new OrcaRuntimeService(null, undefined, statusWiring.deps) + const uninstallStatusRepublish = statusWiring.attach(runtime) runtime.registerPty(PTY_ID, WORKTREE_ID) const tab: TerminalTab = { type: 'terminal', @@ -58,7 +61,17 @@ function createHarness(): Harness { const unsubscribe = runtime.onMobileSessionTabsChanged((snapshot) => { publications.push(structuredClone(snapshot)) }) - return { internals, publications, runtime, tab, unsubscribe } + return { + internals, + publications, + runtime, + tab, + unsubscribe: () => { + unsubscribe() + uninstallStatusRepublish() + statusWiring.statusStore.stop() + } + } } function setRichStatus( diff --git a/tests/e2e/slept-workspace-remount-wake.spec.ts b/tests/e2e/slept-workspace-remount-wake.spec.ts new file mode 100644 index 00000000000..54109a6b532 --- /dev/null +++ b/tests/e2e/slept-workspace-remount-wake.spec.ts @@ -0,0 +1,87 @@ +/** + * GH #10205: a manual sleep keeps the tab's session id as a wake hint, so a later + * remount of its still-mounted pane reattaches that dead id and the daemon spawns + * a fresh shell. Production parking timings are deliberate: a shrunk park delay + * unmounts the slept panes and hides the behavior. + */ +import type { Page } from '@stablyai/playwright-test' +import { expect, test } from './helpers/orca-app' +import { getAllWorktreeIds, waitForSessionReady } from './helpers/store' +import { + activateWorkspaceByClick, + giveWorkspaceALivePty, + readConnectDiagnostics, + readHostLiveTerminalCount, + readWorkspaceSample, + sleepWorkspaceViaSidebar +} from './helpers/slept-workspace-probe' + +const OBSERVATION_MS = 8_000 +const SAMPLE_INTERVAL_MS = 200 + +async function assertStaysCold(page: Page, worktreeId: string): Promise { + let peakLivePty = 0 + let peakTabs = 0 + const deadline = Date.now() + OBSERVATION_MS + while (Date.now() < deadline) { + const sample = await readWorkspaceSample(page, worktreeId) + peakLivePty = Math.max(peakLivePty, sample.livePtyCount) + peakTabs = Math.max(peakTabs, sample.tabCount) + await page.waitForTimeout(SAMPLE_INTERVAL_MS) + } + const hostLive = await readHostLiveTerminalCount(page, worktreeId) + const diag = await readConnectDiagnostics(page, worktreeId) + console.error(`[#10205] ${JSON.stringify({ peakLivePty, peakTabs, hostLive, diag })}`) + expect(peakLivePty, 'slept workspace grew a live PTY').toBe(0) + expect(peakTabs, 'slept workspace grew a tab').toBe(1) + expect(hostLive, 'host created a session for the slept workspace').toBe(0) + // Why: proves the gate held rather than the pane having quietly unmounted. + expect(diag.at(-1), 'remounted pane did not wait for the wake').toContain('WAIT FOR WAKE') +} + +test('remounting a slept hidden pane does not respawn its PTY', async ({ orcaPage }) => { + await waitForSessionReady(orcaPage) + const [slept, other] = await getAllWorktreeIds(orcaPage) + expect(other, 'seeded repo must expose two worktrees').toBeTruthy() + await giveWorkspaceALivePty(orcaPage, slept) + await giveWorkspaceALivePty(orcaPage, other) + await activateWorkspaceByClick(orcaPage, slept) + expect((await readWorkspaceSample(orcaPage, slept)).livePtyCount).toBeGreaterThan(0) + + await sleepWorkspaceViaSidebar(orcaPage, slept) + await expect + .poll(async () => (await readWorkspaceSample(orcaPage, slept)).livePtyCount, { + timeout: 20_000, + message: 'sleep did not release the workspace PTYs' + }) + .toBe(0) + await activateWorkspaceByClick(orcaPage, other) + + const sample = await readWorkspaceSample(orcaPage, slept) + const sleptTabId = sample.tabIds[0] + expect(sleptTabId, 'slept workspace must retain a tab').toBeTruthy() + // Presence preconditions: the pane is still mounted and still carries its wake hint, + // otherwise a remount has nothing to reattach and the oracle passes vacuously. + expect(sample.mountedTabIds, 'slept pane was parked before the remount').toContain(sleptTabId) + expect(sample.tabPtyHints[0], 'sleep must keep the session id as a wake hint').toBeTruthy() + + const remounted = await orcaPage.evaluate( + (tabId) => window.__store?.getState().remountTerminalTabForRecovery(tabId).remounted ?? false, + sleptTabId + ) + expect(remounted, 'remountTerminalTabForRecovery did not find the slept tab').toBe(true) + await assertStaysCold(orcaPage, slept) + + // Non-vacuity: a deliberate click must still wake it, and exactly once — the + // waiting pane and its remounted successor must not both reattach. + await activateWorkspaceByClick(orcaPage, slept) + await expect + .poll(async () => (await readWorkspaceSample(orcaPage, slept)).livePtyCount, { + timeout: 40_000, + message: 'the slept workspace never wakes even on deliberate activation' + }) + .toBeGreaterThan(0) + await orcaPage.waitForTimeout(3_000) + expect((await readWorkspaceSample(orcaPage, slept)).livePtyCount).toBe(1) + expect(await readHostLiveTerminalCount(orcaPage, slept)).toBe(1) +}) diff --git a/tests/e2e/tasks-page.spec.ts b/tests/e2e/tasks-page.spec.ts index b8f57a1996f..962f86de0c5 100644 --- a/tests/e2e/tasks-page.spec.ts +++ b/tests/e2e/tasks-page.spec.ts @@ -13,6 +13,9 @@ import { GITHUB_TASK_SEARCH_IDLE_MS } from '../../src/renderer/src/components/us // on a loaded runner, so one slow keystroke committed a prefix and failed the assertion. const TASK_SEARCH_TYPING_DELAY_MS = Math.round(GITHUB_TASK_SEARCH_IDLE_MS / 6) const TASK_SEARCH_SETTLE_MS = GITHUB_TASK_SEARCH_IDLE_MS + 50 +// Why derived: the probe must outlast the idle window plus a React commit and two +// store round trips; a flat 2s left ~1.2s of slack on a single-worker runner. +const TASK_SEARCH_PROBE_TIMEOUT_MS = GITHUB_TASK_SEARCH_IDLE_MS * 6 type RenderedTaskSource = { source: string @@ -411,7 +414,9 @@ test.describe('Tasks page', () => { await input.fill('') await expect - .poll(async () => readTaskSearchRequestProbe(orcaPage), { timeout: 2_000 }) + .poll(async () => readTaskSearchRequestProbe(orcaPage), { + timeout: TASK_SEARCH_PROBE_TIMEOUT_MS + }) .toEqual({ countQueries: ['is:issue is:open'], fetchQueries: ['is:issue is:open'] }) await resetTaskSearchRequestProbe(orcaPage) @@ -422,7 +427,9 @@ test.describe('Tasks page', () => { // The contract is that no prefix of the typed query is ever queried, not that the // probe is empty at one instant: exactly one request per surface, for the final value. await expect - .poll(async () => readTaskSearchRequestProbe(orcaPage), { timeout: 2_000 }) + .poll(async () => readTaskSearchRequestProbe(orcaPage), { + timeout: TASK_SEARCH_PROBE_TIMEOUT_MS + }) .toEqual({ countQueries: ['is:issue rate'], fetchQueries: ['is:issue rate'] }) await resetTaskSearchRequestProbe(orcaPage) @@ -430,7 +437,9 @@ test.describe('Tasks page', () => { await input.press('Enter') await expect - .poll(async () => readTaskSearchRequestProbe(orcaPage), { timeout: 2_000 }) + .poll(async () => readTaskSearchRequestProbe(orcaPage), { + timeout: TASK_SEARCH_PROBE_TIMEOUT_MS + }) .toEqual({ countQueries: ['is:issue ratex'], fetchQueries: ['is:issue ratex'] }) await orcaPage.waitForTimeout(TASK_SEARCH_SETTLE_MS) expect(await readTaskSearchRequestProbe(orcaPage)).toEqual({ diff --git a/tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts b/tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts index c734301d33f..fd4915d0ce3 100644 --- a/tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts +++ b/tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts @@ -160,14 +160,16 @@ process.stdout.write(${JSON.stringify(`${marker}\n`)}) observe() }, blocked.tabId) - const remounted = await orcaPage.evaluate((tabId) => { + // No request argument: an external lifecycle remount, which skips the + // recovery ledger entirely and so reports generation 0. + const remountResult = await orcaPage.evaluate((tabId) => { const state = window.__store?.getState() if (!state) { throw new Error('Renderer store unavailable') } return state.remountTerminalTabForRecovery(tabId) }, blocked.tabId) - expect(remounted).toBe(true) + expect(remountResult).toMatchObject({ remounted: true }) // Keep the original pre-spawn attempt gated until React has committed the // successor pane. Releasing earlier lets a loaded CI renderer finish the diff --git a/tests/e2e/worktree-switch-first-paint.spec.ts b/tests/e2e/worktree-switch-first-paint.spec.ts new file mode 100644 index 00000000000..307e179faf6 --- /dev/null +++ b/tests/e2e/worktree-switch-first-paint.spec.ts @@ -0,0 +1,486 @@ +import { execFileSync } from 'node:child_process' +import { mkdtempSync, realpathSync, rmSync } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import type { Page, TestInfo } from '@stablyai/playwright-test' +import { expect, test } from './helpers/orca-app' +import { loadWorktreesUntilPathsPresent } from './helpers/worktree-registration' +import { + ensureTerminalVisible, + getAllWorktreeIds, + switchToWorktree, + waitForActiveWorktree, + waitForSessionReady +} from './helpers/store' +import { + execInTerminal, + waitForActivePanePtyId, + waitForActiveTerminalManager, + waitForTerminalOutput +} from './helpers/terminal' + +/** + * Worktree-switch first-paint budget. + * + * Why this exists: worktree-switch-responsiveness.spec.ts proves the click task + * stays short, and the reveal-convergence spec proves the buffer eventually + * matches. Neither covers the symptom users report — the revealed terminal is + * BLANK for a beat after the switch. This measures the phase that owns that + * beat: switch click -> revealed pane has painted its restored content. + * + * The scenario is the one that dominates at many-worktree scale: a switch to a + * worktree whose tabs are in the persisted session but have never been mounted + * in this renderer. Hot-retain only keeps 4 worktrees warm, so with hundreds of + * worktrees essentially every switch is this one. Reloading the renderer between + * rounds reproduces it exactly, at production parking timings. + */ + +// Why 3: the field profile that motivated this budget has 449 worktrees whose +// median tab count is 2-3, so a 3-tab worktree is the switch users actually pay for. +const TABS_PER_WORKTREE = Number(process.env.ORCA_SWITCH_TABS ?? '3') +const SCROLLBACK_LINES = 1_500 +// Budget: a switch has to look instant. Anything over this reads as a stall. +const FIRST_PAINT_BUDGET_MS = Number(process.env.ORCA_SWITCH_BUDGET_MS ?? '250') +// Why repeat: a single cold reveal on a loaded dev machine swings by tens of ms, +// which is the same order as the effect under test. +const SWITCH_SAMPLE_COUNT = Number(process.env.ORCA_SWITCH_ROUNDS ?? '5') + +type SwitchSample = { + activationMs: number | null + paneMountedMs: number | null + contentRestoredMs: number | null + maxFrameGapMs: number + longTaskTotalMs: number + worstLongTaskMs: number + mountedAtActivation: number + settledPaneManagers: number + settledPanes: number + settledWebglContexts: number +} + +type SwitchPaintProbe = { + t0: number + activationMs: number | null + paneMountedMs: number | null + contentRestoredMs: number | null + frames: number[] + longTasks: number[] + mountedAtActivation: number + stop: () => void +} + +declare global { + var __switchPaintProbe: SwitchPaintProbe | undefined +} + +async function ensureTabs(page: Page, worktreeId: string, marker: string): Promise { + await switchToWorktree(page, worktreeId) + await ensureTerminalVisible(page) + const tabIds: string[] = [] + for (let index = 0; index < TABS_PER_WORKTREE; index += 1) { + const tabId = await page.evaluate( + ({ id, wanted }) => { + const state = window.__store!.getState() + const existing = state.tabsByWorktree[id] ?? [] + const reuse = existing[wanted] + const tab = reuse ?? state.createTab(id, undefined, undefined, { activate: true }) + state.setActiveTab(tab.id) + state.setActiveTabType('terminal') + return tab.id + }, + { id: worktreeId, wanted: index } + ) + await waitForActiveTerminalManager(page, 30_000) + const ptyId = await waitForActivePanePtyId(page, 30_000) + const label = `${marker}_T${index}` + await execInTerminal( + page, + ptyId, + `for i in $(seq 1 ${SCROLLBACK_LINES}); do echo "${label}_$i ${'y'.repeat(48)}"; done; echo ${label}_READY` + ) + await waitForTerminalOutput(page, `${label}_READY`, 60_000) + tabIds.push(tabId) + } + return tabIds +} + +async function waitForUnmountedTabs(page: Page, tabIds: readonly string[]): Promise { + return expect + .poll( + () => + page.evaluate((ids) => ids.every((id) => window.__paneManagers?.has(id) !== true), tabIds), + { timeout: 20_000, message: 'switch target still had mounted panes' } + ) + .toBe(true) + .then( + () => true, + () => false + ) +} + +/** Tabs with a mounted pane, once the post-reveal warm-up has settled. */ +async function waitForMountedTabs(page: Page, tabIds: readonly string[]): Promise { + const read = () => + page.evaluate( + (ids) => ids.filter((id) => window.__paneManagers?.has(id) === true).sort(), + [...tabIds] + ) + await expect + .poll(async () => (await read()).length, { + timeout: 20_000, + message: 'activation-deferred tabs never mounted after the reveal' + }) + .toBe(tabIds.length) + .catch(() => undefined) + return read() +} + +async function measureSwitch( + page: Page, + targetWorktreeId: string, + targetTabIds: readonly string[] +): Promise { + await page.evaluate( + ({ worktreeId, tabIds }) => { + const probe = { + t0: performance.now(), + activationMs: null as number | null, + paneMountedMs: null as number | null, + contentRestoredMs: null as number | null, + frames: [] as number[], + longTasks: [] as number[], + mountedAtActivation: 0, + stop: () => {} + } + globalThis.__switchPaintProbe = probe + let observer: PerformanceObserver | null = null + try { + observer = new PerformanceObserver((list) => { + for (const entry of list.getEntries()) { + probe.longTasks.push(entry.duration) + } + }) + observer.observe({ entryTypes: ['longtask'] }) + } catch { + /* longtask unsupported */ + } + let running = true + const visibleTabId = () => { + const state = window.__store!.getState() + return state.activeWorktreeId === worktreeId && state.activeTabType === 'terminal' + ? state.activeTabId + : (state.activeTabIdByWorktree?.[worktreeId] ?? null) + } + const tick = () => { + if (!running) { + return + } + const now = performance.now() - probe.t0 + probe.frames.push(now) + const state = window.__store!.getState() + if (probe.activationMs === null && state.activeWorktreeId === worktreeId) { + probe.activationMs = now + // Why here and not at paint: this is the switch's own frame, before any + // idle admission can run, so it measures what the SWITCH mounted. + probe.mountedAtActivation = tabIds.filter( + (id) => window.__paneManagers?.has(id) === true + ).length + } + const tabId = visibleTabId() + const manager = tabId ? window.__paneManagers?.get(tabId) : null + const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null + if (probe.paneMountedMs === null && pane?.container?.isConnected) { + probe.paneMountedMs = now + } + if (probe.contentRestoredMs === null && pane) { + // Restored = the revealed viewport carries real text rather than an + // empty grid. Read on a frame callback, so this is the frame the + // content became renderable — one frame ahead of the pixels, and not + // a pixel assertion. Both arms are measured identically. + const buffer = pane.terminal.buffer.active + let filledRows = 0 + for (let row = 0; row < pane.terminal.rows; row += 1) { + const line = buffer.getLine(buffer.viewportY + row) + if (line && line.translateToString(true).trim().length > 0) { + filledRows += 1 + } + } + if (filledRows >= Math.min(5, pane.terminal.rows)) { + probe.contentRestoredMs = now + } + } + requestAnimationFrame(tick) + } + requestAnimationFrame(tick) + probe.stop = () => { + running = false + try { + observer?.disconnect() + } catch { + /* ignore */ + } + } + window.__store!.getState().setActiveWorktree(worktreeId) + }, + { worktreeId: targetWorktreeId, tabIds: [...targetTabIds] } + ) + + // Why poll rather than sample a fixed window: the measurement is "how long did + // the restore take", so the harness must outlast the slowest runner rather than + // give up at a deadline and report the reveal as never restoring. + await expect + .poll(() => page.evaluate(() => globalThis.__switchPaintProbe?.contentRestoredMs ?? null), { + timeout: 30_000, + message: 'revealed terminal never restored its content' + }) + .not.toBeNull() + // Let the idle admission drain so the settled-resource readings are steady. + await page.waitForTimeout(2_000) + + return page.evaluate(() => { + const probe = globalThis.__switchPaintProbe! + probe.stop() + let maxGap = 0 + let previous = 0 + for (const frame of probe.frames) { + maxGap = Math.max(maxGap, frame - previous) + previous = frame + } + let settledPanes = 0 + let settledWebglContexts = 0 + const managers = window.__paneManagers + for (const manager of managers?.values() ?? []) { + settledPanes += (manager.getPanes?.() ?? []).length + // Why diagnostics and not `pane.webglAddon`: getPanes() hands back a public + // projection that has no webglAddon field, so reading it is always falsy. + const diagnostics = + ( + manager as { getRenderingDiagnostics?: () => { hasWebgl?: boolean }[] } + ).getRenderingDiagnostics?.() ?? [] + settledWebglContexts += diagnostics.filter((entry) => entry.hasWebgl === true).length + } + return { + settledPaneManagers: managers?.size ?? 0, + settledPanes, + settledWebglContexts, + activationMs: probe.activationMs, + paneMountedMs: probe.paneMountedMs, + contentRestoredMs: probe.contentRestoredMs, + maxFrameGapMs: +maxGap.toFixed(1), + longTaskTotalMs: +probe.longTasks.reduce((total, value) => total + value, 0).toFixed(1), + worstLongTaskMs: +probe.longTasks + .reduce((worst, value) => Math.max(worst, value), 0) + .toFixed(1), + mountedAtActivation: probe.mountedAtActivation + } + }) +} + +function report(label: string, sample: SwitchSample): string { + return [ + `${label}:`, + ` activation ${sample.activationMs?.toFixed(1) ?? 'n/a'}ms`, + ` pane mounted ${sample.paneMountedMs?.toFixed(1) ?? 'n/a'}ms`, + ` content restored ${sample.contentRestoredMs?.toFixed(1) ?? 'never'}ms`, + ` max frame gap ${sample.maxFrameGapMs}ms`, + ` long tasks total=${sample.longTaskTotalMs}ms worst=${sample.worstLongTaskMs}ms`, + ` panes at switch ${sample.mountedAtActivation}/${TABS_PER_WORKTREE}`, + ` settled resources managers=${sample.settledPaneManagers} panes=${sample.settledPanes} webgl=${sample.settledWebglContexts}` + ].join('\n') +} + +async function publish(testInfo: TestInfo, name: string, body: string): Promise { + console.log(body) + await testInfo.attach(name, { body, contentType: 'text/plain' }) +} + +// Why 8 extra: hot-retain keeps the 4 most recently hidden worktrees mounted and +// exempts the last-active one, so a target only cold-parks once enough other +// worktrees have been visited after it. That is the steady state at field scale. +const FILLER_WORKTREE_COUNT = Number(process.env.ORCA_SWITCH_FILLER_WORKTREES ?? '8') + +async function addFillerWorktrees( + page: Page, + testRepoPath: string +): Promise<{ ids: string[]; cleanup: () => void }> { + const parent = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'orca-switch-paint-'))) + const paths = Array.from({ length: FILLER_WORKTREE_COUNT }, (_, index) => + path.join(parent, `filler-${index}`) + ) + const removeAll = (): void => { + for (const worktreePath of paths) { + try { + execFileSync('git', ['worktree', 'remove', '--force', worktreePath], { + cwd: testRepoPath, + stdio: 'ignore' + }) + } catch { + /* best effort */ + } + } + rmSync(parent, { recursive: true, force: true }) + } + // Why clean up before rethrowing: testRepoPath is worker-scoped and reused by + // later specs, so a half-built fixture would leak worktrees into them. + try { + for (const worktreePath of paths) { + execFileSync('git', ['worktree', 'add', '--detach', worktreePath, 'HEAD'], { + cwd: testRepoPath, + stdio: 'ignore' + }) + } + } catch (error) { + removeAll() + throw error + } + try { + return await registerFillerWorktrees(page, testRepoPath, paths, removeAll) + } catch (error) { + removeAll() + throw error + } +} + +async function registerFillerWorktrees( + page: Page, + testRepoPath: string, + paths: readonly string[], + cleanup: () => void +): Promise<{ ids: string[]; cleanup: () => void }> { + const repoId = await page.evaluate( + (repoPath) => + window.__store!.getState().repos.find((repo) => repo.path === repoPath)?.id ?? null, + testRepoPath + ) + if (!repoId) { + throw new Error(`seeded repo not registered: ${testRepoPath}`) + } + await loadWorktreesUntilPathsPresent(page, repoId, [...paths]) + const ids = await page.evaluate( + ({ id, wanted }) => + (window.__store!.getState().worktreesByRepo[id] ?? []) + .filter((worktree) => wanted.includes(worktree.path)) + .map((worktree) => worktree.id), + { id: repoId, wanted: paths } + ) + return { ids, cleanup } +} + +function median(values: readonly number[]): number { + const sorted = [...values].sort((a, b) => a - b) + const middle = Math.floor(sorted.length / 2) + return sorted.length % 2 === 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle] +} + +// Linux needs a mapped window for animation frames after reload; run on an isolated display. +test.describe('Worktree switch first paint @headful', () => { + test.skip( + process.env.ORCA_BACKGROUND_LAUNCH === '1', + 'First-paint measurement requires a mapped window' + ) + test('repaints an unmounted worktree within the switch budget', async ({ + orcaPage, + testRepoPath + }, testInfo) => { + test.setTimeout(900_000) + await waitForSessionReady(orcaPage) + await waitForActiveWorktree(orcaPage) + await ensureTerminalVisible(orcaPage) + + const worktreeIds = await getAllWorktreeIds(orcaPage) + expect(worktreeIds.length).toBeGreaterThanOrEqual(2) + const [primaryId, targetId] = worktreeIds + const filler = await addFillerWorktrees(orcaPage, testRepoPath) + + const samples: SwitchSample[] = [] + const lines: string[] = [] + try { + const targetTabIds = await ensureTabs(orcaPage, targetId, 'WTB') + + // Give the filler worktrees persisted tabs without mounting them, so the + // store carries a field-scale tab population (the profile that motivated + // this budget has 846 tabs across 449 worktrees). + await orcaPage.evaluate( + ({ ids, perWorktree }) => { + const state = window.__store!.getState() + for (const id of ids) { + const existing = state.tabsByWorktree[id] ?? [] + for (let index = existing.length; index < perWorktree; index += 1) { + state.createTab(id) + } + } + }, + { ids: filler.ids, perWorktree: 2 } + ) + + for (let round = 0; round < SWITCH_SAMPLE_COUNT; round += 1) { + // Leave the primary active and let the session persist before reloading: + // startup restores the persisted active worktree, so this is what makes + // the target come back with tabs in the session and no pane ever mounted + // — the state every switch lands in once the worktree count exceeds the + // hot-retain working set. + await switchToWorktree(orcaPage, primaryId) + await ensureTerminalVisible(orcaPage) + await orcaPage.waitForTimeout(2_500) + await orcaPage.reload() + await waitForSessionReady(orcaPage) + await waitForActiveWorktree(orcaPage) + await ensureTerminalVisible(orcaPage) + await orcaPage.waitForTimeout(2_500) + const unmounted = await waitForUnmountedTabs(orcaPage, targetTabIds) + expect(unmounted, 'target worktree was already mounted before the switch').toBe(true) + + const sample = await measureSwitch(orcaPage, targetId, targetTabIds) + samples.push(sample) + lines.push(report(`round ${round + 1} (target unmounted=${unmounted})`, sample)) + + // The half of the contract that keeps the speed-up free: the hidden tabs + // the switch skipped still end up mounted, so the next tab switch is as + // warm as it was before the reveal stopped mounting them up front. + const warmedTabIds = await waitForMountedTabs(orcaPage, targetTabIds) + expect(warmedTabIds, 'deferred tabs never joined the warm working set').toEqual( + [...targetTabIds].sort() + ) + } + } finally { + filler.cleanup() + } + + const restored = samples + .map((sample) => sample.contentRestoredMs) + .filter((value): value is number => value !== null) + expect(restored.length, 'revealed terminal never restored its content').toBe(samples.length) + const summary = [ + `first activation -> ${TABS_PER_WORKTREE}-tab worktree, ${samples.length} rounds`, + ` content restored: median=${median(restored).toFixed(1)}ms samples=${restored + .map((value) => value.toFixed(0)) + .join(', ')}ms`, + ` activation: median=${median( + samples.map((sample) => sample.activationMs ?? 0) + ).toFixed(1)}ms`, + ` panes at switch: ${samples.map((sample) => sample.mountedAtActivation).join(', ')}`, + ` settled panes: ${samples.map((sample) => sample.settledPanes).join(', ')}`, + ` settled webgl: ${samples.map((sample) => sample.settledWebglContexts).join(', ')}`, + '', + ...lines + ].join('\n') + await publish(testInfo, 'first-activation-switch.txt', summary) + + for (const sample of samples) { + expect( + sample.mountedAtActivation, + 'the switch mounted more than the pane the user is looking at' + ).toBe(1) + } + // Why CI is exempt from the budget and not from the invariants: shared + // runners cannot hold a latency threshold, but "the switch mounted one pane" + // and "the warm set came back" are exact and are the real regression guards. + if (process.env.CI) { + console.log( + `[switch-budget] CI run, latency budget not enforced (median ${median(restored).toFixed(1)}ms)` + ) + return + } + expect(median(restored)).toBeLessThanOrEqual(FIRST_PAINT_BUDGET_MS) + }) +}) diff --git a/tests/tools/benchmarks/terminal-cold-park-resource-bench.mjs b/tests/tools/benchmarks/terminal-cold-park-resource-bench.mjs index 63b7222a93d..ffac29bddea 100644 --- a/tests/tools/benchmarks/terminal-cold-park-resource-bench.mjs +++ b/tests/tools/benchmarks/terminal-cold-park-resource-bench.mjs @@ -27,19 +27,19 @@ import { pickFreePort, stopDevApp, waitForStoreReady -} from '../../config/scripts/windows-apphang-repro/electron-dev-session.mjs' +} from '../../../config/scripts/windows-apphang-repro/electron-dev-session.mjs' import { createCompletedOnboardingProfile, safeRemoveLocalDirectory -} from '../../config/scripts/windows-apphang-repro/wsl-workspace-fixture.mjs' +} from '../../../config/scripts/windows-apphang-repro/wsl-workspace-fixture.mjs' import { pollUntil, rendererActionTimeoutMs, runWithTimeout, setupTimeoutMs -} from '../../config/scripts/windows-apphang-repro/repro-timing.mjs' +} from '../../../config/scripts/windows-apphang-repro/repro-timing.mjs' -const rootDir = path.resolve(fileURLToPath(new URL('../..', import.meta.url))) +const rootDir = path.resolve(fileURLToPath(new URL('../../..', import.meta.url))) const PARK_DELAY_MS = 1_500 const SETTLE_AFTER_PARK_MS = 4_000 // Short root so the daemon Unix socket fits under the macOS 104-char limit; diff --git a/tests/tools/benchmarks/terminal-cold-park-reveal-bench.mjs b/tests/tools/benchmarks/terminal-cold-park-reveal-bench.mjs index a01cbf2cc3a..70bf1f66944 100644 --- a/tests/tools/benchmarks/terminal-cold-park-reveal-bench.mjs +++ b/tests/tools/benchmarks/terminal-cold-park-reveal-bench.mjs @@ -33,19 +33,19 @@ import { pickFreePort, stopDevApp, waitForStoreReady -} from '../../config/scripts/windows-apphang-repro/electron-dev-session.mjs' +} from '../../../config/scripts/windows-apphang-repro/electron-dev-session.mjs' import { createCompletedOnboardingProfile, safeRemoveLocalDirectory -} from '../../config/scripts/windows-apphang-repro/wsl-workspace-fixture.mjs' +} from '../../../config/scripts/windows-apphang-repro/wsl-workspace-fixture.mjs' import { pollUntil, rendererActionTimeoutMs, runWithTimeout, setupTimeoutMs -} from '../../config/scripts/windows-apphang-repro/repro-timing.mjs' +} from '../../../config/scripts/windows-apphang-repro/repro-timing.mjs' -const rootDir = path.resolve(fileURLToPath(new URL('../..', import.meta.url))) +const rootDir = path.resolve(fileURLToPath(new URL('../../..', import.meta.url))) const scenarioTimeoutMs = 300_000 // Short enough that a tab parks within a few seconds of being hidden, long diff --git a/tests/tools/benchmarks/terminal-perf-bench.mjs b/tests/tools/benchmarks/terminal-perf-bench.mjs index a73ffae6bc9..551f33d0433 100644 --- a/tests/tools/benchmarks/terminal-perf-bench.mjs +++ b/tests/tools/benchmarks/terminal-perf-bench.mjs @@ -19,16 +19,16 @@ import { pickFreePort, stopDevApp, waitForStoreReady -} from '../../config/scripts/windows-apphang-repro/electron-dev-session.mjs' +} from '../../../config/scripts/windows-apphang-repro/electron-dev-session.mjs' import { pollUntil, rendererActionTimeoutMs, runWithTimeout, setupTimeoutMs -} from '../../config/scripts/windows-apphang-repro/repro-timing.mjs' -import { safeRemoveLocalDirectory } from '../../config/scripts/windows-apphang-repro/wsl-workspace-fixture.mjs' +} from '../../../config/scripts/windows-apphang-repro/repro-timing.mjs' +import { safeRemoveLocalDirectory } from '../../../config/scripts/windows-apphang-repro/wsl-workspace-fixture.mjs' -const rootDir = path.resolve(fileURLToPath(new URL('../..', import.meta.url))) +const rootDir = path.resolve(fileURLToPath(new URL('../../..', import.meta.url))) const scenarioTimeoutMs = 300_000 const defaultIterations = 8 const defaultSwitches = 24 diff --git a/tests/tools/pi-owner-runtime-smoke.mjs b/tests/tools/pi-owner-runtime-smoke.mjs new file mode 100644 index 00000000000..204627340ac --- /dev/null +++ b/tests/tools/pi-owner-runtime-smoke.mjs @@ -0,0 +1,128 @@ +// Run: node tests/tools/pi-owner-runtime-smoke.mjs /path/to/pi-coding-agent +import assert from 'node:assert/strict' +import { once } from 'node:events' +import { mkdtemp, writeFile, rm } from 'node:fs/promises' +import { createServer } from 'node:http' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' +import { pathToFileURL } from 'node:url' +import { build } from 'esbuild' + +const piRoot = resolve(process.argv[2] || '') +assert.ok(process.argv[2], 'Pass an installed pi-coding-agent package directory') +const scratch = await mkdtemp(join(tmpdir(), 'orca-pi-owner-')) +const received = [] +const server = createServer(async (request, response) => { + let body = '' + for await (const chunk of request) { + body += chunk + } + received.push(JSON.parse(body)) + response.end('{}') +}) +try { + const bundle = join(scratch, 'orca.cjs') + await build({ + stdin: { + contents: [ + "export { getPiAgentStatusExtensionSource } from './src/main/pi/agent-status-extension-source';", + "export { runProcess } from './src/shared/child-process/run-process';" + ].join('\n'), + resolveDir: process.cwd() + }, + bundle: true, + platform: 'node', + format: 'cjs', + outfile: bundle, + packages: 'external' + }) + const { getPiAgentStatusExtensionSource, runProcess } = createRequire(import.meta.url)(bundle) + server.listen(0, '127.0.0.1') + await once(server, 'listening') + const dead = await runProcess({ + program: process.execPath, + args: ['-e', 'console.log(process.pid)'] + }) + assert.equal(dead.code, 0) + const deadPid = Number(dead.stdout.trim()) + assert.throws(() => process.kill(deadPid, 0), { code: 'ESRCH' }) + const worker = join(scratch, 'worker.mjs') + const moduleUrl = (file) => JSON.stringify(pathToFileURL(join(piRoot, file)).href) + await writeFile( + worker, + ` + import assert from 'node:assert/strict' + import { loadExtensions } from ${moduleUrl('dist/core/extensions/loader.js')} + import { ExtensionRunner } from ${moduleUrl('dist/core/extensions/runner.js')} + import { SessionManager } from ${moduleUrl('dist/core/session-manager.js')} + const loaded = await loadExtensions([process.argv[2]], process.cwd()) + assert.deepEqual(loaded.errors, []) + const runner = new ExtensionRunner(loaded.extensions, loaded.runtime, process.cwd(), SessionManager.inMemory(process.cwd()), undefined) + const errors = [] + runner.onError(error => errors.push(error)) + await runner.emit({ type: 'agent_start' }) + await new Promise(resolve => setTimeout(resolve, 250)) + assert.deepEqual(errors, []) + console.log(JSON.stringify({pid: process.pid, owner: process.env[process.argv[3]], handlers: loaded.extensions[0].handlers.size})) + ` + ) + const results = [] + for (const kind of ['pi', 'omp', 'prime-agent']) { + const ownerKey = + kind === 'prime-agent' ? 'ORCA_PRIME_AGENT_STATUS_OWNED' : 'ORCA_PI_STATUS_OWNED' + for (const scenario of ['baseline-dead', 'fixed-dead', 'fixed-live']) { + let source = getPiAgentStatusExtensionSource(kind) + if (scenario === 'baseline-dead') { + const guard = 'if (ownerPid && ownerPid !== selfPid && isStatusOwnerAlive(ownerPid)) return' + assert.ok( + source.includes(guard), + 'Baseline mutation must replace the actual ownership guard' + ) + source = source.replace(guard, 'if (ownerPid && ownerPid !== selfPid) return') + } + const extension = join(scratch, `${kind}-${scenario}.ts`) + await writeFile(extension, source) + const before = received.length + const owner = scenario === 'fixed-live' ? process.pid : deadPid + const child = await runProcess({ + program: process.execPath, + args: [worker, extension, ownerKey], + cwd: scratch, + env: { + ...process.env, + ORCA_BACKGROUND_LAUNCH: '1', + ORCA_PANE_KEY: 'owner-proof', + ORCA_AGENT_HOOK_PORT: String(server.address().port), + ORCA_AGENT_HOOK_TOKEN: 'isolated-proof-token', + ORCA_AGENT_HOOK_ENV: 'proof', + ORCA_AGENT_HOOK_ENDPOINT: '', + ORCA_PI_STATUS_OWNED: '', + ORCA_PRIME_AGENT_STATUS_OWNED: '', + PRIME_AGENT_INTERNAL_DAEMON_WORKER: kind === 'prime-agent' ? '1' : '', + [ownerKey]: String(owner) + }, + timeoutMs: 15000 + }) + assert.equal(child.code, 0, child.stderr) + const observation = JSON.parse(child.stdout.trim().split('\n').at(-1)) + const shouldReport = scenario === 'fixed-dead' + assert.equal( + received.length - before, + shouldReport ? 1 : 0, + `${kind}/${scenario}: HTTP delivery` + ) + assert.equal(observation.owner, String(shouldReport ? observation.pid : owner)) + assert.equal(observation.handlers > 0, shouldReport) + if (shouldReport) { + assert.equal(received.at(-1).payload.hook_event_name, 'agent_start') + } + results.push({ kind, scenario, posts: received.length - before, ...observation }) + } + } + console.log(JSON.stringify({ platform: process.platform, results }, null, 2)) +} finally { + server.closeAllConnections() + server.close() + await rm(scratch, { recursive: true, force: true }) +} diff --git a/tests/tools/pi-provider-runtime-smoke.mjs b/tests/tools/pi-provider-runtime-smoke.mjs new file mode 100644 index 00000000000..bda4f6a0f89 --- /dev/null +++ b/tests/tools/pi-provider-runtime-smoke.mjs @@ -0,0 +1,130 @@ +import assert from 'node:assert/strict' +import { once } from 'node:events' +import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises' +import { createServer } from 'node:http' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' +import { build } from 'esbuild' +const piCli = process.argv[2] && resolve(process.argv[2]) +assert.ok(piCli, 'Pass the installed Pi CLI entrypoint') +const scratch = await mkdtemp(join(tmpdir(), 'orca-pi-provider-')) +const requests = [] +const server = createServer(async (req, res) => { + let body = '' + for await (const part of req) { + body += part + } + requests.push(JSON.parse(body)) + res.writeHead(200, { 'content-type': 'text/event-stream' }) + for (const chunk of [ + { + id: 'proof', + object: 'chat.completion.chunk', + choices: [ + { + index: 0, + delta: { role: 'assistant', content: 'fixture-generated-commit' }, + finish_reason: null + } + ] + }, + { + id: 'proof', + object: 'chat.completion.chunk', + choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], + usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } + } + ]) { + res.write(`data: ${JSON.stringify(chunk)}\n\n`) + } + res.end('data: [DONE]\n\n') +}) +try { + const bundle = join(scratch, 'orca.cjs') + await build({ + stdin: { + contents: + "export {planCommitMessageGeneration} from './src/shared/commit-message-plan'; export {runProcess} from './src/shared/child-process/run-process';", + resolveDir: process.cwd() + }, + bundle: true, + platform: 'node', + format: 'cjs', + outfile: bundle, + packages: 'external' + }) + const { planCommitMessageGeneration, runProcess } = createRequire(import.meta.url)(bundle) + server.listen(0, '127.0.0.1') + await once(server, 'listening') + const dir = join(scratch, 'agent') + await mkdir(join(dir, 'extensions'), { recursive: true }) + await writeFile( + join(dir, 'extensions', 'provider.ts'), + `export default function(pi){pi.registerProvider('orca-proof',{name:'Proof',baseUrl:'http://127.0.0.1:${server.address().port}/v1',apiKey:'fixture-only',api:'openai-completions',models:[{id:'local',name:'Proof',reasoning:false,input:['text'],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:8192,maxTokens:256}]})}` + ) + await writeFile( + join(dir, 'settings.json'), + JSON.stringify({ defaultProvider: 'orca-proof', defaultModel: 'local' }) + ) + const planned = planCommitMessageGeneration( + { agentId: 'pi', model: 'orca-proof/local' }, + 'Generate one short commit message.' + ) + assert.equal(planned.ok, true) + const fixedArgs = planned.plan.args + assert.ok(!fixedArgs.includes('--no-extensions')) + const variants = [ + ['baseline', [...fixedArgs, '--no-extensions']], + ['extensions-enabled', fixedArgs] + ] + const results = [] + for (const [variant, args] of variants) { + const n = requests.length + const result = await runProcess({ + program: process.execPath, + args: [piCli, ...args], + cwd: scratch, + env: { + PATH: process.env.PATH, + SystemRoot: process.env.SystemRoot, + WINDIR: process.env.WINDIR, + HOME: scratch, + USERPROFILE: scratch, + ORCA_BACKGROUND_LAUNCH: '1', + PI_CODING_AGENT_DIR: dir + }, + input: planned.plan.stdinPayload, + timeoutMs: 20000 + }) + results.push({ + variant, + args, + code: result.code, + stdout: result.stdout, + stderr: result.stderr, + requests: requests.length - n + }) + } + assert.equal(results[0].requests, 0) + assert.notEqual(results[0].code, 0) + assert.equal(results[1].code, 0, results[1].stderr) + assert.match(results[1].stdout, /fixture-generated-commit/) + assert.equal(results[1].requests, 1) + console.log( + JSON.stringify( + { + scope: + 'Actual Pi CLI and production command planner; isolated extension provider with local OpenAI-compatible fixture.', + platform: process.platform, + results + }, + null, + 2 + ) + ) +} finally { + server.closeAllConnections() + server.close() + await rm(scratch, { recursive: true, force: true }) +} diff --git a/tests/tools/relay-bench/find-cell.mjs b/tests/tools/relay-bench/find-cell.mjs new file mode 100644 index 00000000000..cc48be054c9 --- /dev/null +++ b/tests/tools/relay-bench/find-cell.mjs @@ -0,0 +1,32 @@ +import { createRequire } from 'node:module' +const WebSocket = createRequire(import.meta.url)('ws') +const hostId = process.argv[2] +const bogus = 'A'.repeat(43) +const probe = (cell) => + new Promise((resolve) => { + const ws = new WebSocket(`wss://${cell}.relay.onorca.dev/v1/connect/${hostId}`, { + perMessageDeflate: false + }) + const t0 = performance.now() + const done = (r) => { + try { + ws.terminate() + } catch {} + resolve({ cell, ms: Math.round(performance.now() - t0), ...r }) + } + ws.on('open', () => + ws.send(JSON.stringify({ type: 'relay-auth', v: 1, mode: 'connect', credential: bogus })) + ) + ws.on('message', (m) => done({ hello: JSON.parse(m.toString()).code })) + ws.on('error', (e) => done({ error: e.code ?? e.message })) + ws.on('close', (c) => done({ close: c })) + setTimeout(() => done({ error: 'timeout' }), 8000) + }) +const cells = Array.from({ length: 30 }, (_, i) => `c${i + 1}`) +const results = await Promise.all(cells.map(probe)) +for (const r of results) { + if (r.hello !== 4409 || process.argv[3]) { + console.log(JSON.stringify(r)) + } +} +console.log('probed', results.length, 'wrong-cell:', results.filter((r) => r.hello === 4409).length)